react-semaphor 0.1.60 → 0.1.62
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/axis-mapping-8ZVwlkl6.js +315 -0
- package/dist/chunks/axis-mapping-Cwa3KrDR.js +16 -0
- package/dist/chunks/bar-chart-settings-B_WyC-7g.js +52 -0
- package/dist/chunks/bar-chart-settings-CvorW7RD.js +1 -0
- package/dist/chunks/bubble-chart-settings-BPtESqYK.js +1 -0
- package/dist/chunks/bubble-chart-settings-CxFAlErV.js +50 -0
- package/dist/chunks/common-chart-settings-CvRrQf-H.js +1 -0
- package/dist/chunks/common-chart-settings-D3ww0Xtx.js +147 -0
- package/dist/chunks/custom-visual-settings-DXWyN2Dr.js +11 -0
- package/dist/chunks/custom-visual-settings-m5o8R5tL.js +243 -0
- package/dist/chunks/dashboard-plus-B8-ocT_Z.js +41 -0
- package/dist/chunks/dashboard-plus-DSUKhvcv.js +2941 -0
- package/dist/chunks/display-labels-BYsRReye.js +1 -0
- package/dist/chunks/display-labels-C_jsL0Jo.js +74 -0
- package/dist/chunks/editor-C7xQi9Ab.js +105 -0
- package/dist/chunks/editor-DqvyBUrl.js +8321 -0
- package/dist/chunks/filter-on-click-columns-6dRYhvgz.js +1 -0
- package/dist/chunks/filter-on-click-columns-BJUGTE6W.js +120 -0
- package/dist/chunks/frame-filters-D9sDN4Vm.js +1 -0
- package/dist/chunks/frame-filters-DFgqSoV2.js +75 -0
- package/dist/chunks/{index-BzapoQUW.js → index--MUeDITx.js} +28320 -25737
- package/dist/chunks/index-Bvtpj-_R.js +1080 -0
- package/dist/chunks/kpi-settings-BONvmfNr.js +1 -0
- package/dist/chunks/kpi-settings-CI-9fp4Z.js +286 -0
- package/dist/chunks/map-chart-settings-CSxZdu_g.js +1 -0
- package/dist/chunks/map-chart-settings-DQIN7Pn8.js +334 -0
- package/dist/chunks/pie-chart-settings-CN3JCLdP.js +86 -0
- package/dist/chunks/pie-chart-settings-CsErfZOL.js +1 -0
- package/dist/chunks/reusable-select-CQbD03nT.js +40 -0
- package/dist/chunks/reusable-select-CVRzPWkg.js +1 -0
- package/dist/chunks/stacked-chart-settings-BfqHFFqA.js +1 -0
- package/dist/chunks/stacked-chart-settings-poYotO6Q.js +90 -0
- package/dist/chunks/table-visual-settings-B46pdUra.js +46 -0
- package/dist/chunks/table-visual-settings-ZKWuNokZ.js +1 -0
- package/dist/chunks/tag-BrxBSbSe.js +20 -0
- package/dist/chunks/tag-D9G2kz2B.js +6 -0
- package/dist/chunks/use-assign-filter-5gplfsO1.js +83 -0
- package/dist/chunks/use-assign-filter-DzmBSsyO.js +1 -0
- package/dist/chunks/use-local-storage-state-CBh2HHB9.js +16 -0
- package/dist/chunks/use-local-storage-state-CL0JsTZM.js +1745 -0
- package/dist/chunks/use-plugin-query-DA6Yrp7P.js +12 -0
- package/dist/chunks/use-plugin-query-JdHNPYZS.js +1 -0
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +103 -103
- package/dist/style.css +1 -1
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunks/dashboard-plus-BEe61COU.js +0 -17362
- package/dist/chunks/dashboard-plus-Bi6F5Cid.js +0 -225
- package/dist/chunks/index-DvVwuOlu.js +0 -1045
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),s=require("./index-Bvtpj-_R.js"),T=require("react"),ee=require("./use-local-storage-state-CBh2HHB9.js"),ds=require("./use-plugin-query-JdHNPYZS.js"),us=require("react-dom"),Le=require("./axis-mapping-Cwa3KrDR.js"),ms=require("./display-labels-BYsRReye.js");function xs(t){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const a in t)if(a!=="default"){const r=Object.getOwnPropertyDescriptor(t,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:()=>t[a]})}}return n.default=t,Object.freeze(n)}const hs=xs(T);/**
|
|
2
|
+
* @license lucide-react v0.453.0 - ISC
|
|
3
|
+
*
|
|
4
|
+
* This source code is licensed under the ISC license.
|
|
5
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
+
*/const ps=s.createLucideIcon("BookOpenText",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M16 12h2",key:"7q9ll5"}],["path",{d:"M16 8h2",key:"msurwy"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}],["path",{d:"M6 12h2",key:"32wvfc"}],["path",{d:"M6 8h2",key:"30oboj"}]]);/**
|
|
7
|
+
* @license lucide-react v0.453.0 - ISC
|
|
8
|
+
*
|
|
9
|
+
* This source code is licensed under the ISC license.
|
|
10
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
+
*/const fs=s.createLucideIcon("ChevronsUpDown",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);/**
|
|
12
|
+
* @license lucide-react v0.453.0 - ISC
|
|
13
|
+
*
|
|
14
|
+
* This source code is licensed under the ISC license.
|
|
15
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
16
|
+
*/const Ye=s.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"}]]);/**
|
|
17
|
+
* @license lucide-react v0.453.0 - ISC
|
|
18
|
+
*
|
|
19
|
+
* This source code is licensed under the ISC license.
|
|
20
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
21
|
+
*/const gs=s.createLucideIcon("Columns3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
|
|
22
|
+
* @license lucide-react v0.453.0 - ISC
|
|
23
|
+
*
|
|
24
|
+
* This source code is licensed under the ISC license.
|
|
25
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
26
|
+
*/const js=s.createLucideIcon("DatabaseZap",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 15 21.84",key:"14ibmq"}],["path",{d:"M21 5V8",key:"1marbg"}],["path",{d:"M21 12L18 17H22L19 22",key:"zafso"}],["path",{d:"M3 12A9 3 0 0 0 14.59 14.87",key:"1y4wr8"}]]);/**
|
|
27
|
+
* @license lucide-react v0.453.0 - ISC
|
|
28
|
+
*
|
|
29
|
+
* This source code is licensed under the ISC license.
|
|
30
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
31
|
+
*/const vs=s.createLucideIcon("EyeClosed",[["path",{d:"m15 18-.722-3.25",key:"1j64jw"}],["path",{d:"M2 8a10.645 10.645 0 0 0 20 0",key:"1e7gxb"}],["path",{d:"m20 15-1.726-2.05",key:"1cnuld"}],["path",{d:"m4 15 1.726-2.05",key:"1dsqqd"}],["path",{d:"m9 18 .722-3.25",key:"ypw2yx"}]]);/**
|
|
32
|
+
* @license lucide-react v0.453.0 - ISC
|
|
33
|
+
*
|
|
34
|
+
* This source code is licensed under the ISC license.
|
|
35
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
36
|
+
*/const bs=s.createLucideIcon("FileJson2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1",key:"fq0c9t"}],["path",{d:"M8 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1",key:"4gibmv"}]]);/**
|
|
37
|
+
* @license lucide-react v0.453.0 - ISC
|
|
38
|
+
*
|
|
39
|
+
* This source code is licensed under the ISC license.
|
|
40
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
41
|
+
*/const ys=s.createLucideIcon("GitCompareArrows",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M12 6h5a2 2 0 0 1 2 2v7",key:"1yj91y"}],["path",{d:"m15 9-3-3 3-3",key:"1lwv8l"}],["circle",{cx:"19",cy:"18",r:"3",key:"1qljk2"}],["path",{d:"M12 18H7a2 2 0 0 1-2-2V9",key:"16sdep"}],["path",{d:"m9 15 3 3-3 3",key:"1m3kbl"}]]);/**
|
|
42
|
+
* @license lucide-react v0.453.0 - ISC
|
|
43
|
+
*
|
|
44
|
+
* This source code is licensed under the ISC license.
|
|
45
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
46
|
+
*/const Ns=s.createLucideIcon("Hammer",[["path",{d:"m15 12-8.373 8.373a1 1 0 1 1-3-3L12 9",key:"eefl8a"}],["path",{d:"m18 15 4-4",key:"16gjal"}],["path",{d:"m21.5 11.5-1.914-1.914A2 2 0 0 1 19 8.172V7l-2.26-2.26a6 6 0 0 0-4.202-1.756L9 2.96l.92.82A6.18 6.18 0 0 1 12 8.4V10l2 2h1.172a2 2 0 0 1 1.414.586L18.5 14.5",key:"b7pghm"}]]);/**
|
|
47
|
+
* @license lucide-react v0.453.0 - ISC
|
|
48
|
+
*
|
|
49
|
+
* This source code is licensed under the ISC license.
|
|
50
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
51
|
+
*/const Ve=s.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"}]]);/**
|
|
52
|
+
* @license lucide-react v0.453.0 - ISC
|
|
53
|
+
*
|
|
54
|
+
* This source code is licensed under the ISC license.
|
|
55
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
56
|
+
*/const qe=s.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"}]]);/**
|
|
57
|
+
* @license lucide-react v0.453.0 - ISC
|
|
58
|
+
*
|
|
59
|
+
* This source code is licensed under the ISC license.
|
|
60
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
61
|
+
*/const Cs=s.createLucideIcon("Rows3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}],["path",{d:"M21 15H3",key:"9uk58r"}]]);/**
|
|
62
|
+
* @license lucide-react v0.453.0 - ISC
|
|
63
|
+
*
|
|
64
|
+
* This source code is licensed under the ISC license.
|
|
65
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
66
|
+
*/const Te=s.createLucideIcon("Shapes",[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]]);/**
|
|
67
|
+
* @license lucide-react v0.453.0 - ISC
|
|
68
|
+
*
|
|
69
|
+
* This source code is licensed under the ISC license.
|
|
70
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
71
|
+
*/const Ss=s.createLucideIcon("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
|
|
72
|
+
* @license lucide-react v0.453.0 - ISC
|
|
73
|
+
*
|
|
74
|
+
* This source code is licensed under the ISC license.
|
|
75
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
76
|
+
*/const ws=s.createLucideIcon("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);/**
|
|
77
|
+
* @license lucide-react v0.453.0 - ISC
|
|
78
|
+
*
|
|
79
|
+
* This source code is licensed under the ISC license.
|
|
80
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
81
|
+
*/const ks=s.createLucideIcon("Wand",[["path",{d:"M15 4V2",key:"z1p9b7"}],["path",{d:"M15 16v-2",key:"px0unx"}],["path",{d:"M8 9h2",key:"1g203m"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M17.8 11.8 19 13",key:"yihg8r"}],["path",{d:"M15 9h.01",key:"x1ddxp"}],["path",{d:"M17.8 6.2 19 5",key:"fd4us0"}],["path",{d:"m3 21 9-9",key:"1jfql5"}],["path",{d:"M12.2 6.2 11 5",key:"i3da3b"}]]);function Ts({initialJoinPlan:t,availableDataSources:n}){const[a,r]=T.useState(t),[m,c]=T.useState(new Set),d=()=>{const v=a.joins.length>0?Math.max(...a.joins.map(o=>o.sequence))+1:1,l={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:v,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...a,joins:[...a.joins,l]}),c(new Set([...m,l.id]))},i=v=>{r({...a,joins:a.joins.filter(l=>l.id!==v)}),c(new Set([...m].filter(l=>l!==v)))},u=(v,l)=>{var E,D,M,P,I;const o=a.joins.find(R=>R.id===v);if(!o)return;const p={...o,...l};if((E=p.source)!=null&&E.name&&((D=p.target)!=null&&D.name)&&p.source.name===p.target.name){s.ue.error("Self-joins are not yet supported",{description:`Joining ${p.source.name} to itself is not currently supported. Please select a different target table.`});return}const S=a.joins.filter(R=>{var G;return R.id!==v&&R.target.name===((G=p.target)==null?void 0:G.name)});if((M=p.target)!=null&&M.name&&S.length>0){s.ue.error("Duplicate join targets are not supported",{description:`The table ${p.target.name} is already used as a target in another join. Each table can only be joined once.`});return}const x=a.joins.map(R=>R.id===v?p:R);if((P=p.source)!=null&&P.name&&((I=p.target)!=null&&I.name)&&p.joinKeyGroups[0].keys.length===0){const R=n.find(q=>{var O;return q.name===((O=p.source)==null?void 0:O.name)}),G=n.find(q=>{var O;return q.name===((O=p.target)==null?void 0:O.name)}),V={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(R==null?void 0:R.name)||"",entityName:(R==null?void 0:R.name)||"",entityType:(R==null?void 0:R.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(G==null?void 0:G.name)||"",entityName:(G==null?void 0:G.name)||"",entityType:(G==null?void 0:G.type)||"table"},operator:"="},_=[...p.joinKeyGroups];_[0]={..._[0],keys:[V]},p.joinKeyGroups=_,x[x.findIndex(q=>q.id===v)]=p}r({...a,joins:x})};return{joinPlan:a,expandedJoins:m,setJoinPlan:r,addJoin:d,removeJoin:i,updateJoin:u,moveJoinUp:v=>{const l=a.joins.findIndex(o=>o.id===v);if(l>0){const o=[...a.joins],p={...o[l]},S={...o[l-1]};o[l]=S,o[l-1]=p,o.forEach((E,D)=>{E.sequence=D+1});const x={...a,joins:o};r(x)}},moveJoinDown:v=>{const l=a.joins.findIndex(o=>o.id===v);if(l<a.joins.length-1){const o=[...a.joins],p={...o[l]},S={...o[l+1]};o[l]=S,o[l+1]=p,o.forEach((E,D)=>{E.sequence=D+1});const x={...a,joins:o};r(x)}},toggleJoinExpansion:v=>{const l=new Set(m);l.has(v)?l.delete(v):l.add(v),c(l)},getAvailableSourceEntities:v=>{if(a.joins.length===0)return n;const l=a.joins.findIndex(p=>p.id===v);if(l===0)return n.filter(p=>p.name===a.baseEntity.name);const o=new Set;return a.baseEntity.name&&o.add(a.baseEntity.name),a.joins.slice(0,l).forEach(p=>{o.add(p.source.name),o.add(p.target.name)}),n.filter(p=>o.has(p.name))},getAvailableTargetEntities:v=>n.filter(l=>l.name!==v),addJoinKeyGroup:v=>{const l=a.joins.find(p=>p.id===v);if(!l)return;const o=[...l.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];u(v,{joinKeyGroups:o})},updateGroupOperator:(v,l,o)=>{const p=a.joins.find(x=>x.id===v);if(!p)return;const S=[...p.joinKeyGroups];S[l]={...S[l],operator:o},u(v,{joinKeyGroups:S})},removeJoinKeyGroup:(v,l)=>{const o=a.joins.find(S=>S.id===v);if(!o)return;const p=[...o.joinKeyGroups];p.splice(l,1),u(v,{joinKeyGroups:p})},addJoinKey:(v,l)=>{const o=a.joins.find(D=>D.id===v);if(!o)return;const p=n.find(D=>D.name===o.source.name),S=n.find(D=>D.name===o.target.name),x=[...o.joinKeyGroups],E={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(p==null?void 0:p.name)||"",entityName:(p==null?void 0:p.name)||"",entityType:(p==null?void 0:p.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",qualifiedFieldName:"",entityId:(S==null?void 0:S.name)||"",entityName:(S==null?void 0:S.name)||"",entityType:(S==null?void 0:S.type)||"table"},operator:"="};x[l]={...x[l],keys:[...x[l].keys,E]},u(v,{joinKeyGroups:x})},updateJoinKey:(v,l,o,p,S)=>{const x=a.joins.find(I=>I.id===v);if(!x)return;const E=n.find(I=>I.name===x.source.name),D=n.find(I=>I.name===x.target.name),M=[...x.joinKeyGroups],P=M[l].keys[o];p==="sourceColumnName"&&E?M[l].keys[o]={...P,source:{...P.source,name:S}}:p==="targetColumnName"&&D?M[l].keys[o]={...P,target:{...P.target,name:S}}:p==="operator"&&(M[l].keys[o]={...P,operator:S}),u(v,{joinKeyGroups:M})},removeJoinKey:(v,l,o)=>{const p=a.joins.find(x=>x.id===v);if(!p)return;const S=[...p.joinKeyGroups];S[l].keys.splice(o,1),u(v,{joinKeyGroups:S})},generateSQLPreview:()=>{const v=[...a.joins].sort((p,S)=>p.sequence-S.sequence),l=a.baseEntity;if(!l.name)return"SELECT * FROM table -- Please select a base entity";let o=`SELECT *
|
|
82
|
+
FROM ${l.name}`;return v.forEach(p=>{const S=n.find(D=>D.name===p.target.name);if(!S)return;const x=p.joinKeyGroups.filter(D=>D.keys&&D.keys.length>0).map(D=>{const M=D.keys.filter(P=>{var I,R,G,V;return((I=P.source)==null?void 0:I.name)&&((R=P.target)==null?void 0:R.name)&&((G=P.source)==null?void 0:G.entityName)&&((V=P.target)==null?void 0:V.entityName)}).map(P=>`${P.source.entityName}.${P.source.name} ${P.operator} ${P.target.entityName}.${P.target.name}`);return M.length>1?`(${M.join(` ${D.operator} `)})`:M[0]}).filter(Boolean),E=x.length>1?x.join(" OR "):x[0]||"condition_here";o+=`
|
|
83
|
+
${p.joinType} JOIN ${S.name}
|
|
84
|
+
ON ${E}`}),o},isValidConfiguration:()=>!(!a.baseEntity.name||a.joins.some(p=>!p.source.name||!p.target.name)||a.joins.some(p=>p.joinKeyGroups.some(S=>S.keys.length===0))||a.joins.some(p=>p.joinKeyGroups.some(S=>S.keys.some(x=>!x.source.name||!x.target.name||!x.operator))))}}function Es({joinPlan:t,availableDataSources:n,onSave:a,onRemove:r,onCancel:m}){const{setCardConfig:c}=s.useEditorActions();s.useEditorStore(x=>x.card.config);const{columnGroups:d}=s.useColumns(),{joinPlan:i,expandedJoins:u,setJoinPlan:h,addJoin:g,removeJoin:j,updateJoin:f,moveJoinUp:w,moveJoinDown:N,toggleJoinExpansion:b,getAvailableSourceEntities:y,getAvailableTargetEntities:F,addJoinKeyGroup:k,updateGroupOperator:z,removeJoinKeyGroup:B,addJoinKey:C,updateJoinKey:v,removeJoinKey:l,generateSQLPreview:o,isValidConfiguration:p}=Ts({initialJoinPlan:t,availableDataSources:n}),S=x=>{const E=d.find(D=>D.entityName===x);return(E==null?void 0:E.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(s.Select,{value:i.baseEntity.name,onValueChange:x=>{const E=n.find(D=>D.name===x);h({...i,baseEntity:{connectionId:(E==null?void 0:E.connectionId)||"",connectionType:(E==null?void 0:E.connectionType)||"none",type:(E==null?void 0:E.type)||"table",name:x,database:E==null?void 0:E.database,schema:E==null?void 0:E.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(s.SelectContent,{children:n.map(x=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:x.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:x.type}),x.name,e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},x.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:o()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(s.Label,{children:["Joins Configuration (",i.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:g,children:[e.jsx(s.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),i.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:i.joins.map(x=>{const E=n.find(P=>P.name===x.source.name),D=n.find(P=>P.name===x.target.name),M=u.has(x.id);return e.jsxs(s.Card,{className:"border",children:[e.jsx(s.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(s.Badge,{children:x.sequence}),e.jsxs(s.CardTitle,{className:"text-sm",children:["Join ",x.sequence,E&&D&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",E.name," → ",D.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>w(x.id),disabled:x.sequence===1,children:e.jsx(s.ArrowUp,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>N(x.id),disabled:x.sequence===i.joins.length,children:e.jsx(s.ArrowDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>b(x.id),children:M?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>j(x.id),children:e.jsx(s.X,{className:"h-4 w-4"})})]})]})}),M&&e.jsxs(s.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(s.Label,{children:"Source"}),e.jsxs(s.Select,{value:x.source.name,onValueChange:P=>{const I=n.find(R=>R.name===P);f(x.id,{source:{connectionId:(I==null?void 0:I.connectionId)||"",connectionType:(I==null?void 0:I.connectionType)||"none",type:(I==null?void 0:I.type)||"table",name:P,database:I==null?void 0:I.database,schema:I==null?void 0:I.schema}})},children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select source..."})}),e.jsx(s.SelectContent,{children:y(x.id).map(P=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:P.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:P.type}),P.name]})},P.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Join Type"}),e.jsxs(s.Select,{value:x.joinType,onValueChange:P=>f(x.id,{joinType:P}),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{children:"Target"}),e.jsxs(s.Select,{value:x.target.name,onValueChange:P=>{const I=n.find(R=>R.name===P);f(x.id,{target:{connectionId:(I==null?void 0:I.connectionId)||"",connectionType:(I==null?void 0:I.connectionType)||"none",type:(I==null?void 0:I.type)||"table",name:P,database:I==null?void 0:I.database,schema:I==null?void 0:I.schema}})},disabled:!x.source.name,children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Select target..."})}),e.jsx(s.SelectContent,{children:x.source.name?F(x.source.name).map(P=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:P.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:P.type}),P.name,P.name===x.source.name&&e.jsx(s.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},P.name)):[]})]})]})]}),x.source.name&&x.target.name&&E&&D&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{children:"Join Conditions"}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>k(x.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),x.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:x.joinKeyGroups.map((P,I)=>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(s.Label,{children:["Group ",I+1]}),I>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(s.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(s.Select,{value:P.operator,onValueChange:R=>z(x.id,I,R),children:[e.jsx(s.SelectTrigger,{className:"w-[100px]",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>B(x.id,I),children:e.jsx(s.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[P.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:P.keys.map((R,G)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[G>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:P.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:R.source.name,onValueChange:V=>v(x.id,I,G,"sourceColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Source column"})}),e.jsx(s.SelectContent,{children:S(x.source.name).map(V=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:V.name}),e.jsx(s.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(s.Select,{value:R.operator,onValueChange:V=>v(x.id,I,G,"operator",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(s.Select,{value:R.target.name,onValueChange:V=>v(x.id,I,G,"targetColumnName",V),children:[e.jsx(s.SelectTrigger,{children:e.jsx(s.SelectValue,{placeholder:"Target column"})}),e.jsx(s.SelectContent,{children:S(x.target.name).map(V=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:V.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:V.name}),e.jsx(s.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx(s.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>l(x.id,I,G),children:e.jsx(s.X,{className:"size-3.5"})})]},R.id||G))}),e.jsxs(s.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>C(x.id,I),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},P.id))})]})]})]},x.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>{r(),m()},children:"Remove All"}),e.jsx(s.Button,{variant:"outline",onClick:m,children:"Cancel"}),e.jsx(s.Button,{onClick:()=>a(i),disabled:!p(),children:"Save"})]})]})}function Pe({children:t,open:n,onOpenChange:a,joinPlan:r,availableDataSources:m,onRemove:c,onSave:d,onCancel:i}){return e.jsxs(s.Dialog,{open:n,onOpenChange:a,children:[e.jsxs(s.DialogContent,{className:"max-w-4xl",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Join Configuration"}),e.jsx(s.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(Es,{joinPlan:r,availableDataSources:m,onSave:d,onCancel:i,onRemove:c})]}),t]})}function Ds({joins:t,baseEntityId:n,availableDataSources:a,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[t.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 m=[...t].sort((d,i)=>d.sequence-i.sequence),c=a.find(d=>d.name===n);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(s.Badge,{variant:"secondary",className:"text-xs",children:c==null?void 0:c.type}),e.jsx("span",{className:"text-xs font-medium",children:c==null?void 0:c.name}),e.jsx(s.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),m.map(d=>{const i=a.find(u=>u.name===d.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(s.Badge,{variant:"outline",className:"text-xs",children:d.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(s.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})]})]},d.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",t.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...t].sort((m,c)=>m.sequence-c.sequence).map((m,c)=>{const d=a.find(u=>u.name===m.source.name),i=a.find(u=>u.name===m.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(s.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:c+1}),e.jsx(s.Badge,{variant:"outline",className:"shrink-0 text-xs",children:m.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[d==null?void 0:d.name," → ",i==null?void 0:i.name]}),e.jsxs(s.Badge,{variant:"outline",className:"ml-auto text-xs",children:[m.joinKeyGroups.reduce((u,h)=>u+h.keys.length,0)," ","condition",m.joinKeyGroups.reduce((u,h)=>u+h.keys.length,0)>1?"s":""]})]},m.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 Is(){var j,f;const t=s.useEditorStore(w=>w.card),{autoJoinMetadata:n}=s.useDashboardCardQuery(t),a=s.useEditorStore(w=>w.actions.updateCardConfig),r=((j=t==null?void 0:t.config)==null?void 0:j.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[m,c]=T.useState(!1),d=((f=t==null?void 0:t.dataSource)==null?void 0:f.selectedEntities)||[],i=w=>{a(t.id,{...t==null?void 0:t.config,joinPlan:w}),c(!1)},u=()=>{a(t.id,{...t==null?void 0:t.config,joinPlan:void 0})},h=()=>{c(!1)},g=()=>{const w=[...r.joins].sort((y,F)=>y.sequence-F.sequence),N=r.baseEntity;if(!N.name)return"SELECT * FROM table -- Please select a base entity";let b=`SELECT *
|
|
85
|
+
FROM ${N.name}`;return w.forEach(y=>{const F=d.find(B=>B.name===y.target.name);if(!F)return;const k=y.joinKeyGroups.filter(B=>B.keys&&B.keys.length>0).map(B=>{const C=B.keys.filter(v=>{var l,o,p,S;return((l=v.source)==null?void 0:l.name)&&((o=v.target)==null?void 0:o.name)&&((p=v.source)==null?void 0:p.entityName)&&((S=v.target)==null?void 0:S.entityName)}).map(v=>`${v.source.entityName}.${v.source.name} ${v.operator} ${v.target.entityName}.${v.target.name}`);return C.length>1?`(${C.join(` ${B.operator} `)})`:C[0]}).filter(Boolean),z=k.length>1?k.join(" OR "):k[0]||"condition_here";b+=`
|
|
86
|
+
${y.joinType} JOIN ${F.name}
|
|
87
|
+
ON ${z}`}),b};return d.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(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>c(!0),children:[e.jsx(s.Link,{className:s.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(s.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(Ds,{joins:r.joins,baseEntityId:r.baseEntity.name,availableDataSources:d,generateSQLPreview:g})})]})}),(n==null?void 0:n.autoResolved)&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"secondary",className:"h-6 gap-1 bg-blue-50 text-blue-700 dark:bg-blue-950 dark:text-blue-300",children:[e.jsx(s.Sparkles,{className:"h-3 w-3"}),"Auto"]})}),e.jsx(s.TooltipContent,{side:"right",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium",children:"Auto-resolved using relationships:"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:n.relationshipsUsed.map((w,N)=>e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:w},N))})]})})]})}),e.jsx(Pe,{open:m,onOpenChange:c,joinPlan:r,availableDataSources:d,onSave:i,onCancel:h,onRemove:u,children:e.jsx("div",{})})]}),r.joins.length===0&&e.jsx(Pe,{open:m,onOpenChange:c,joinPlan:r,availableDataSources:d,onSave:i,onCancel:h,onRemove:u,children:e.jsxs(s.Button,{onClick:()=>c(!0),variant:"outline",size:"sm",className:"w-full",children:[e.jsx(s.Link,{className:"mr-3 size-4"}),"Configure Joins"]})})]})})})}function As({open:t,onOpenChange:n}){const[a,r]=T.useState([]),{updateDataSource:m}=s.useEditorActions(),c=s.useDashboardStore(b=>b.dashboard.aiContext),d=(c==null?void 0:c.selectedEntities)||[];T.useEffect(()=>{t&&r([])},[t]);const i=b=>{r(y=>y.some(k=>k.name===b.name&&k.type===b.type)?y.filter(k=>!(k.name===b.name&&k.type===b.type)):[...y,b])},u=()=>{r([...d])},h=()=>{r([])},g=()=>{if(a.length===0)return;const b=a[0],y=b.connectionId||"",F=b.connectionType||"",z=a.some(C=>C.type==="dataset")?"semanticDomain":"database";m({connectionId:y,connectionType:F,mode:z,selectedEntities:a}),n(!1)},j=b=>{switch(b.type){case"table":return e.jsx(s.Table,{className:"h-4 w-4"});case"view":return e.jsx(ws,{className:"h-4 w-4"});case"model":return e.jsx(js,{className:"h-4 w-4"});case"dataset":return e.jsx(s.Database,{className:"h-4 w-4"});case"file":case"url":case"upload":return e.jsx(s.FileText,{className:"h-4 w-4"});default:return e.jsx(s.Database,{className:"h-4 w-4"})}},f=b=>"label"in b&&b.label?b.label:b.name,w=b=>{if("description"in b&&b.description)return b.description;const y=[];return b.database&&y.push(b.database),b.schema&&y.push(b.schema),b.name&&y.push(b.name),y.join(".")},N=b=>a.some(y=>y.name===b.name&&y.type===b.type);return d.length===0?e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-md",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"No Data Available"}),e.jsx(s.DialogDescription,{children:"No entities are currently available in the AI context. Please add some data sources to the dashboard first."})]}),e.jsx(s.DialogFooter,{children:e.jsx(s.Button,{onClick:()=>n(!1),children:"Close"})})]})}):e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"flex max-w-2xl flex-col",children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Select Data to Analyze"}),e.jsx(s.DialogDescription,{children:"Choose entities from the dashboard's context"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"outline",size:"sm",onClick:u,disabled:a.length===d.length,children:"Select All"}),e.jsx(s.Button,{variant:"outline",size:"sm",onClick:h,disabled:a.length===0,children:"Clear All"})]}),e.jsxs(s.Badge,{variant:"secondary",children:[a.length," of ",d.length," selected"]})]}),e.jsx(s.Separator,{}),e.jsx(s.ScrollArea,{className:"h-64",children:e.jsx("div",{className:"space-y-2",children:d.map((b,y)=>e.jsxs("div",{className:s.cn("flex items-center gap-3 rounded-lg border p-3 transition-colors hover:bg-muted/50",N(b)&&"border-primary bg-primary/5"),children:[e.jsx(s.Checkbox,{checked:N(b),onCheckedChange:()=>i(b)}),e.jsx("div",{className:"flex items-center gap-2 text-muted-foreground",children:j(b)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-medium",children:f(b)}),e.jsx("div",{className:"truncate text-sm text-muted-foreground",children:w(b)})]}),e.jsx(s.Badge,{variant:"outline",className:"text-xs",children:b.type})]},`${b.type}-${b.name}-${y}`))})})]}),e.jsx(s.DialogFooter,{children:e.jsx("div",{className:"flex w-full justify-between",children:e.jsxs("div",{className:"flex grow justify-end gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs(s.Button,{onClick:g,disabled:a.length===0,children:["Select"," ",a.length>0?`(${a.length})`:""]})]})})})]})})}function Ps({entity:t,title:n,maxDetails:a=10}){const m=s.getEntityDetails(t).slice(0,a),c=m.find(i=>i.label==="Description"),d=m.filter(i=>i.label==="Description"?!1:!["Connection","Database","Schema"].includes(i.label));return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:n||s.getDisplayName(t)}),c&&e.jsxs("div",{className:"border-t border-border pt-2",children:[e.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:c.value})]}),d.length>0&&e.jsx("div",{className:"space-y-0.5",children:d.map((i,u)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[i.label,":"]}),e.jsx("span",{className:"font-mono",children:i.value})]},u))})]})})}function Ls({entities:t}){return e.jsx(s.TooltipContent,{side:"top",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:t.map((n,a)=>{const r=s.getEntityDetails(n),m=r.find(d=>d.label==="Description"),c=r.filter(d=>d.label==="Description"?!1:!["Connection","Database","Schema"].includes(d.label)).slice(0,3);return e.jsxs("div",{className:"border-b border-border pb-1 last:border-b-0",children:[e.jsx("div",{className:"text-xs font-medium",children:s.getDisplayName(n)}),m&&e.jsxs("div",{className:"mb-1 mt-1",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Description:"}),e.jsx("div",{className:"text-xs leading-relaxed",children:m.value})]}),c.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:c.map((d,i)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[d.label,":"]}),e.jsx("span",{className:"font-mono",children:d.value})]},i))})]},`remaining-${n.type}-${n.name}-${a}`)})})]})})}function Xe({isVisible:t}){const n=s.useEditorStore(f=>f.isDevMode);ee.useSyncLegacyEditorState();const[a,r]=T.useState(!1),[m,c]=T.useState(!1),[d,i]=T.useState(!0),u=s.useEditorStore(f=>f.card.dataSource);s.useCurrentUserInfo();const{updateDataSource:h}=s.useEditorActions(),g={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},j={...g,...u,selectedEntities:(u==null?void 0:u.selectedEntities)||[]};return e.jsxs("div",{className:s.cn("flex flex-col overflow-hidden bg-background transition-all duration-300 ease-in-out",{"w-[325px]":t,"w-0":!t}),children:[e.jsxs("div",{children:[e.jsx("div",{className:"p-4 px-6 pb-2",children:e.jsxs(s.Button,{className:"w-full bg-muted/50",variant:"outline",onClick:()=>r(!0),children:[e.jsx(s.Database,{className:"mr-2 h-3.5 w-3.5"}),"Choose Dataset"]})}),e.jsxs("div",{className:"relative px-6",children:[e.jsx("div",{className:"absolute inset-0 flex items-center px-6",children:e.jsx("div",{className:"w-full border-t border-border"})}),e.jsx("div",{className:"relative flex justify-center",children:e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:()=>i(!d),className:"size-6 bg-background p-1 py-1 hover:bg-accent",children:d?e.jsx(s.ChevronUp,{className:"h-3.5 w-3.5"}):e.jsx(s.ChevronDown,{className:"h-3.5 w-3.5"})})})]}),e.jsxs("div",{className:`overflow-hidden px-6 ${d?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[j.selectedEntities.length>0&&e.jsx(s.TooltipProvider,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[j.selectedEntities.slice(0,3).map((f,w)=>e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.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:[s.getDisplayName(f),e.jsx("button",{onClick:N=>{N.stopPropagation();const b=j.selectedEntities.filter(y=>!(y.name===f.name&&y.type===f.type));h({...g,...u,selectedEntities:b})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 hover:bg-red-100",children:e.jsx(s.X,{className:"h-2.5 w-2.5 group-hover:text-red-500"})})]})}),e.jsx(Ps,{entity:f})]},`${f.type}-${f.name}-${w}`)),j.selectedEntities.length>3&&e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Badge,{variant:"outline",className:"text-xs",children:["+",j.selectedEntities.length-3," more"]})}),e.jsx(Ls,{entities:j.selectedEntities.slice(3)})]})]})}),!n&&e.jsx(Is,{})]})]}),e.jsx(ee.FieldsSection,{}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(u==null?void 0:u.selectedEntities)||[],dialogMode:"dataSource",open:a,onOpenChange:r,dataSource:j}),e.jsx(As,{open:m,onOpenChange:c})]})}function Ze({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){const m=s.useEditorStore(b=>b.isDevMode),{setIsDevMode:c,setCardSql:d,setRunSql:i}=s.useEditorActions(),[u,h]=T.useState(!1),g=s.useEditorStore(b=>b.card),j=s.useEditorStore(b=>b.frame),f=s.useDashboardStore(b=>b.selectedSheetId),w=s.useDashboardStore(b=>{var y;return(y=b.dashboard)==null?void 0:y.id});function N(b){c(!0),d(b||t),setTimeout(()=>{i(!0)},100)}return e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col pt-4",children:[!m&&t&&!n&&e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsxs(s.Button,{onClick:()=>N(),variant:"secondary",size:"sm",children:[e.jsx(s.FileCode2,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),e.jsxs(s.Button,{onClick:()=>h(!u),variant:"outline",size:"sm",children:[e.jsx(s.Info,{className:"mr-2 h-4 w-4"}),"Card Details"]})]}),u&&e.jsx("div",{className:"mb-3 rounded-lg border border-border bg-muted/30 p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Card Information"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>h(!1),children:e.jsx(Ye,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Card ID"}),e.jsx("code",{className:"text-xs font-mono",children:g.id||"N/A"})]}),e.jsx(s.CopyButton,{text:g.id||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Frame ID"}),e.jsx("code",{className:"text-xs font-mono",children:j.id||"N/A"})]}),e.jsx(s.CopyButton,{text:j.id||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Sheet ID"}),e.jsx("code",{className:"text-xs font-mono",children:f||"N/A"})]}),e.jsx(s.CopyButton,{text:f||"",className:"h-6 w-6"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Dashboard ID"}),e.jsx("code",{className:"text-xs font-mono",children:w||"N/A"})]}),e.jsx(s.CopyButton,{text:w||"",className:"h-6 w-6"})]})]})]})}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-auto text-xs leading-relaxed text-foreground/80",children:[n&&e.jsx(s.QueryErrorDisplay,{error:n,errorSql:a,showFeedbackButton:!1,onOpenInEditor:()=>N(a)}),!n&&t&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute right-2 top-2 z-10",children:e.jsx(s.CopyButton,{text:t,className:"h-6 w-6"})}),e.jsx(s.CodeHighlighter,{code:t,language:"sql"})]})})]}),n&&r&&e.jsx("div",{className:"mt-3",children:e.jsxs(s.Button,{onClick:r,size:"sm",variant:"outline",children:[e.jsx(Ns,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})})]})}function Bs({sql:t,error:n,errorSql:a,onDebugWithAssistant:r}){return e.jsxs(s.HoverCard,{openDelay:n?0:500,children:[e.jsx(s.HoverCardTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"link",className:"h-5 p-0",children:n?e.jsx(Ye,{className:"h-4 w-4 text-red-500"}):e.jsx(s.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(s.HoverCardContent,{align:"start",className:"flex w-[700px]",children:e.jsx(Ze,{errorSql:a,sql:t,error:n,onDebugWithAssistant:r})})]})}function Fs(t){return s.GenIcon({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:[]}]})(t)}function Ms(){const t=s.useQueryClient(),{isConsoleMode:n}=s.useDashboardPreferences(),[a,r]=T.useState(!1),[m,c]=T.useState(!1);s.useEditorStore(O=>O.frame);const d=s.useEditorStore(O=>O.card);s.useEditorStore(O=>O.isShowingVisual),s.useEditorStore(O=>O.selectedConnectionId),s.useEditorStore(O=>O.tempQueryData),s.useEditorStore(O=>O.selectedDatabaseName),s.useEditorStore(O=>O.selectedDatamodelId),s.useEditorStore(O=>O.selectedSchemaName);const i=s.useEditorStore(O=>O.showAIDialog);s.useEditorStore(O=>O.selectedTableName);const u=s.useEditorStore(O=>{var U;return(U=O==null?void 0:O.card)==null?void 0:U.sql}),h=s.useEditorStore(O=>{var U;return(U=O==null?void 0:O.card)==null?void 0:U.python}),{cardFilterValues:g}=s.useCardFilterValues((d==null?void 0:d.id)??""),{setCardCustomCfg:j,setQueryResultColumns:f,setCardSql:w,setTempQueryData:N,setPythonStdOut:b,setCardPreferences:y,setCardType:F,setCardPython:k,runAssistant:z,setShowAIDialog:B}=s.useEditorActions();s.useEditorStore(O=>O.onSave),s.useEditorStore(O=>O.onClose),s.useEditorStore(O=>O.actions.setSqlGen);const C=s.useEditorStore(O=>O.runSql),v=s.useEditorStore(O=>O.actions.setRunSql),l=s.useEditorStore(O=>O.actions.setIsSqlRunning),{data:o,isLoading:p,isFetching:S,isSuccess:x,isError:E,error:D,errorSql:M,queryKey:P,refetch:I,errorMessage:R}=s.useDashboardCardQuery(d);T.useEffect(()=>{if(o&&(o.rowLimitExceeded&&s.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),b((o==null?void 0:o.output)||""),o.records.length>0)){const{dimensionKeys:O}=s.getKeys(o.records);f(O)}},[o,f,b]),T.useEffect(()=>{(p||S)&&l(!0),(E||x)&&l(!1),E&&(f([]),b(""))},[p,S,o,b,E,x,l,f,D]),T.useEffect(()=>{C&&(t.getQueryData(P)||I(),v(!1))},[C,I,v,P,t]);async function G(){const O=`Can you help me debug this query?
|
|
88
|
+
|
|
89
|
+
Error:
|
|
90
|
+
|
|
91
|
+
${R}
|
|
92
|
+
|
|
93
|
+
Error SQL:
|
|
94
|
+
|
|
95
|
+
${M}
|
|
96
|
+
|
|
97
|
+
Query:
|
|
98
|
+
|
|
99
|
+
${u}
|
|
100
|
+
|
|
101
|
+
${h?`Python:
|
|
102
|
+
${h}`:""}
|
|
103
|
+
`;z(O)}function V(){return e.jsxs(e.Fragment,{children:[m&&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(s.JsonEditorReadonly,{jsonString:JSON.stringify(g,null,2)})})}),g&&g.length>0&&e.jsx(s.Button,{variant:"ghost",onClick:()=>c(!m),className:"absolute bottom-0 right-6 size-7 p-1",children:m?e.jsx(s.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(s.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function _(){return e.jsxs(s.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(s.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(s.SqlEditor,{})}),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(s.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(s.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(s.PythonEditor,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function q(){return e.jsx("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(s.Button,{title:"Shift + Enter",disabled:p||S,onClick:()=>{I()},className:"h-8 shrink-0",size:"sm",children:[p||S?e.jsx(s.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(s.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(Bs,{errorSql:M,sql:o==null?void 0:o.sql,error:R,onDebugWithAssistant:G}),e.jsx(ee.EditorClearButton,{}),e.jsxs(s.Toggle,{pressed:a,onPressedChange:O=>r(O),className:"h-8",size:"sm",variant:"outline",children:[e.jsx(Fs,{className:"mr-2 size-4 text-foreground/70"}),"Python"]}),!i&&e.jsxs("button",{disabled:i,onClick:()=>{B(!0)},className:"flex h-9 w-full cursor-text items-center justify-start px-3 text-left text-sm text-muted-foreground",children:[e.jsx(s.Sparkles,{className:"mr-2 size-4 text-foreground/70"}),"Type your question..."]})]})})}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:[_(),V()]}),q()]})}function Ie(t){const[n,a]=T.useState(null);return n}function es(){const{data:t,isLoading:n,isError:a}=ds.usePluginQuery(),r=s.useQueries({queries:((t==null?void 0:t.plugins)||[]).map(i=>({queryKey:["manifest",i.value],queryFn:()=>s.loadManifest(i.value),enabled:!!i.value,staleTime:5*60*1e3,gcTime:10*60*1e3,retry:2,retryDelay:u=>Math.min(1e3*2**u,3e4)}))}),m=[];let c=n,d=a;return r.forEach((i,u)=>{var h;if(i.isLoading&&(c=!0),i.isError&&(d=!0),i.data&&((h=t==null?void 0:t.plugins)!=null&&h[u])){const g=t.plugins[u],j=i.data.visuals.map(f=>({name:f.name,pluginName:g.label,componentType:f.componentType,pluginType:g.type,icon:f.icon,chartType:f.chartType,url:g.value}));m.push(...j)}}),{data:m,isLoading:c,isError:d}}function Os({onChartTypeChange:t}){const{setCardCustomCfg:n,setCardPreferences:a,setCardType:r,setCustomCardPreferences:m}=s.useEditorActions(),{data:c,isLoading:d,isError:i}=es(),u=T.useCallback((h,g)=>{n(null),a({}),r(h),g&&m({type:"component",visualType:"single",url:g.url,componentName:g.name,icon:g.icon}),t==null||t()},[n,a,r,m,t]);return d?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-muted-foreground",children:"Loading custom visuals..."})]}):i?e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"py-4 text-center text-sm text-destructive",children:"Failed to load custom visuals"})]}):!c||c.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(s.Separator,{className:"my-3"}),e.jsx("div",{className:"mb-2",children:e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Custom Charts"})}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:c.map((h,g)=>e.jsx(zs,{text:h.name,onClick:()=>u("custom",h),icon:h.icon},`${h.url}-${h.name}-${g}`))})]})}const zs=({text:t,icon:n,onClick:a})=>{const r=Ie();return e.jsxs("button",{onClick:a,className:"flex flex-col items-center gap-2 rounded-lg border border-border bg-background p-3 transition-all hover:border-primary/50 hover:bg-muted/50 hover:shadow-sm",children:[r?e.jsx(r,{className:"h-6 w-6"}):e.jsx(Te,{className:"h-6 w-6 text-muted-foreground"}),e.jsx("span",{title:t,className:"line-clamp-2 text-center text-xs font-medium text-foreground",children:t})]})};function Rs({onChartTypeChange:t,iconClassName:n,searchQuery:a=""}){const{setCardType:r,setCardPreferences:m,setIsDevMode:c}=s.useEditorStore(f=>f.actions),{setCardCustomCfg:d,setCustomCardPreferences:i,setQueryConfig:u}=s.useEditorActions();function h(f,w){d(null),m({}),r(f),["custom","text","map"].includes(f)&&(c(!0),u(void 0)),t==null||t()}const j=[{type:"table",name:"Table",icon:s.Table2},{type:"bar",name:"Bar Chart",icon:s.ChartColumnIncreasing},{type:"line",name:"Line Chart",icon:s.ChartLine},{type:"stackedBar",name:"Stacked Bar",icon:s.ChartColumnStacked},{type:"stackedLine",name:"Stacked Line",icon:s.MdStackedLineChart},{type:"scatter",name:"Scatter",icon:s.ChartScatter},{type:"bubble",name:"Bubble",icon:s.TbChartBubble},{type:"pie",name:"Pie Chart",icon:s.ChartPie},{type:"doughnut",name:"Doughnut",icon:s.Donut},{type:"funnel",name:"Funnel",icon:s.TbChartFunnel},{type:"radar",name:"Radar",icon:s.Radar},{type:"polarArea",name:"Polar Area",icon:s.PiChartPolar},{type:"tornado",name:"Tornado",icon:s.Tornado},{type:"range",name:"Range",icon:s.ChartNoAxesGantt},{type:"kpi",name:"KPI",icon:s.TiSortNumerically},{type:"text",name:"Text",icon:s.BookType},{type:"map",name:"Map",icon:s.Map},{type:"custom",name:"Custom",icon:Te}].filter(f=>f.name.toLowerCase().includes(a.toLowerCase()));return e.jsx("div",{className:"grid grid-cols-3 gap-2",children:j.map(f=>{const w=f.icon;return e.jsxs("button",{onClick:()=>h(f.type),className:"flex flex-col items-center gap-2 rounded-lg border border-border bg-background p-3 transition-all hover:border-primary/50 hover:bg-muted/50 hover:shadow-sm",children:[e.jsx(w,{className:s.cn("h-6 w-6",n),strokeWidth:f.icon===s.MdStackedLineChart?0:void 0}),e.jsx("span",{className:"text-xs font-medium text-foreground",children:f.name})]},f.type)})})}function $s({chartType:t,className:n,customIcon:a,componentName:r}){const m=Ie();switch(t){case"bar":return e.jsx(s.ChartColumnIncreasing,{className:n});case"line":return e.jsx(s.ChartLine,{className:n});case"pie":return e.jsx(s.ChartPie,{className:n});case"radar":return e.jsx(s.Radar,{className:n});case"scatter":return e.jsx(s.ChartScatter,{className:n});case"bubble":return e.jsx(s.TbChartBubble,{className:n});case"doughnut":return e.jsx(s.Donut,{className:n});case"stackedBar":return e.jsx(s.ChartColumnStacked,{className:n});case"stackedLine":return e.jsx(s.MdStackedLineChart,{className:n});case"polarArea":return e.jsx(s.PiChartPolar,{className:n});case"funnel":return e.jsx(s.TbChartFunnel,{className:n});case"tornado":case"pyramid":return e.jsx(s.Tornado,{className:n});case"range":return e.jsx(s.ChartNoAxesGantt,{className:n});case"kpi":return e.jsx(s.TiSortNumerically,{className:n});case"text":return e.jsx(s.Type,{className:n});case"map":return e.jsx(s.Map,{className:n});case"custom":return a&&m?e.jsx(m,{className:n}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(Te,{className:n});default:return e.jsx(s.Table2,{className:n})}}function ss({variant:t="ghost"}){var i,u;const[n,a]=T.useState(!1),[r,m]=T.useState(""),c=s.useEditorStore(h=>h.card),d=c.type;return e.jsxs(s.Popover,{open:n,onOpenChange:h=>{a(h),h||m("")},children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx(s.Button,{size:"sm",variant:t||"ghost",children:e.jsx($s,{className:"size-4",chartType:d,customIcon:(i=c.customCardPreferences)==null?void 0:i.icon,componentName:(u=c.customCardPreferences)==null?void 0:u.componentName})})}),e.jsxs(s.PopoverContent,{onOpenAutoFocus:h=>h.preventDefault(),className:"z-[70] w-[360px] p-3",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-sm border border-border bg-background px-3 py-2",children:[e.jsx(s.Search,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search charts...",value:r,onChange:h=>m(h.target.value),className:"h-auto border-0 p-0 text-sm focus-visible:ring-0 focus-visible:ring-offset-0"})]}),e.jsxs("div",{className:"max-h-[400px] overflow-y-auto",children:[e.jsx(Rs,{onChartTypeChange:()=>a(!1),searchQuery:r}),e.jsx(Os,{onChartTypeChange:()=>a(!1)})]})]})]})}function Vs({error:t,className:n="",textClassName:a="",copyButtonClassName:r=""}){const[m,c]=T.useState(!1),d=T.useRef(null),i=T.useRef(!1);function u(){t&&!i.current&&navigator.clipboard.writeText(t)}function h(f){(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),u())}function g(){const f=window.getSelection();if(f&&f.toString().trim()!==""){const w=f.toString();navigator.clipboard.writeText(w),c(!0),i.current=!0,setTimeout(()=>{c(!1),i.current=!1},1e3)}else i.current=!1}function j(){c(!1),i.current=!1}return e.jsxs("div",{className:`relative rounded-md border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/20 ${n}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(s.CopyButton,{text:t,className:`h-6 w-6 p-0 text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 ${r}`})}),e.jsx("div",{ref:d,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${a}`,onClick:u,onKeyDown:h,onMouseUp:g,onMouseDown:j,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:t}),m&&e.jsx("div",{className:"absolute bottom-1 right-1 rounded bg-green-100 px-2 py-1 text-xs text-green-600 dark:bg-green-900/30 dark:text-green-400",children:"Copied!"}),e.jsx("div",{className:"clear-both"})]})}function qs(){const t=s.useEditorStore(c=>{var d,i;return(i=(d=c.card.preferences)==null?void 0:d.chartOptions)==null?void 0:i.indexAxis}),n=s.useEditorStore(c=>c.card.type),{setChartOrientation:a}=s.useEditorStore(c=>c.actions);function r(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="x"||t===void 0?"y":"x")},tooltip:"Chart Orientation",children:t==="x"||t===void 0?e.jsx(qe,{className:"size-4"}):e.jsx(Ve,{className:"size-4"})})}function m(){return e.jsx(s.IconButton,{onClick:()=>{a(t==="y"||t===void 0?"x":"y")},tooltip:"Chart Orientation",children:t==="y"||t===void 0?e.jsx(qe,{className:"size-4"}):e.jsx(Ve,{className:"size-4"})})}return e.jsx(e.Fragment,{children:n==="funnel"?m():r()})}function Gs({className:t}){var f,w,N,b,y,F,k,z;const n=s.useEditorStore(B=>B.card),{setCardPreferences:a,updateCardInFrame:r,setCard:m}=s.useEditorActions(),[c,d]=T.useState(!1),i=((w=(f=n.preferences)==null?void 0:f.displayOptions)==null?void 0:w.showFilterInfo)??!0,u=((b=(N=n.preferences)==null?void 0:N.displayOptions)==null?void 0:b.showCardToolbar)??!0,h=((F=(y=n.preferences)==null?void 0:y.displayOptions)==null?void 0:F.showChrome)??!0,g=((z=(k=n.preferences)==null?void 0:k.displayOptions)==null?void 0:z.allowScroll)??!0,j=(B,C)=>{var o;const v={...n.preferences,displayOptions:{...(o=n.preferences)==null?void 0:o.displayOptions,[B]:C}};a(v);const l={...n,preferences:v};m(l),r(l)};return e.jsx("div",{className:s.cn("flex items-center",t),children:e.jsxs(s.DropdownMenu,{modal:!1,open:c,onOpenChange:d,children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.IconButton,{className:"h-8 w-8 p-0",tooltip:"Display Options",children:e.jsx(s.SlidersHorizontal,{className:"h-4 w-4"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",className:"w-64",children:[e.jsx(s.DropdownMenuLabel,{children:"Display Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"mb-2 text-xs text-muted-foreground",children:"Changes apply to dashboard view only"})}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:i,onCheckedChange:B=>{j("showFilterInfo",B)},onSelect:B=>B.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Filter Info"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Badge"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:B=>{j("showCardToolbar",B)},onSelect:B=>B.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Toolbar"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Hover actions"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:h,onCheckedChange:B=>{j("showChrome",B)},onSelect:B=>B.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Card Chrome"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Frame & padding"})]}),e.jsxs(s.DropdownMenuCheckboxItem,{checked:g,onCheckedChange:B=>{j("allowScroll",B)},onSelect:B=>B.preventDefault(),className:"pr-2",children:[e.jsx("span",{className:"flex-1",children:"Allow Scroll"}),e.jsx("span",{className:"ml-4 text-xs text-muted-foreground",children:"Card content scroll"})]})]})]})})}function ts(){const t=s.useEditorStore(c=>c.card),n=s.useEditorStore(c=>{var d,i;return(i=(d=c.card)==null?void 0:d.preferences)==null?void 0:i.chartOptions}),a=s.getChartGridStyle(n),{setChartGrid:r}=s.useEditorActions();function m(){const c=["xy","none","x","y"],i=(c.indexOf(a)+1)%c.length;r(c[i])}return e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center gap-2",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(t.type)&&e.jsx(e.Fragment,{children:e.jsx(qs,{})}),!["kpi","text","custom","table"].includes(t.type)&&e.jsx(e.Fragment,{}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(t.type)&&e.jsxs(s.IconButton,{tooltip:"Grid Style",onClick:m,children:[(a==="xy"||!a)&&e.jsx(s.Grid3x3,{className:"size-4"}),a==="x"&&e.jsx(gs,{className:"size-4"}),a==="y"&&e.jsx(Cs,{className:"size-4"}),a==="none"&&e.jsx(Ss,{className:"size-4"})]}),e.jsx(Gs,{})]})}function Js(){const t=s.useEditorStore(N=>N.frame),n=s.useEditorStore(N=>N.card),{setFrame:a,setActiveTabCardId:r,setCard:m,updateCardInFrame:c}=s.useEditorActions(),d=(N,b)=>{N.dataTransfer.setData("tabIndex",b.toString())},i=N=>{N.preventDefault()},u=(N,b)=>{const y=N.dataTransfer.getData("tabIndex");if(y===b.toString())return;const F=Array.from(t.cards),[k]=F.splice(parseInt(y),1);F.splice(b,0,k),a({...t,cards:F})};function h(N){const b=t.cards.filter(k=>k.id!==N),y=b[0],F={...t,cards:b,activeCardId:y.id};a(F),r(y.id),m(y)}function g(N,b){const y={...t,cards:[...t.cards,b],activeCardId:N.id};a(y),r(b.id)}function j(){const N={...n,id:s.v4(),title:`${n.title} Copy`,tabTitle:`${n.tabTitle||n.title} Copy`};g(n,N)}function f(N){const b={dataSource:N.dataSource,connectionId:N.connectionId,lastSelectedDatabase:N.lastSelectedDatabase,lastSelectedSchema:N.lastSelectedSchema,lastSelectedTable:N.lastSelectedTable,lastSelectedDatamodelId:N.lastSelectedDatamodelId,id:s.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};g(N,b)}function w(N,b){return N.cards.length===1&&(b.displayTab===!0||b.displayTab===void 0)||N.activeCardId!==b.id&&(b.displayTab===!0||b.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const y=b.displayTab===void 0?!1:!b.displayTab;m({...b,displayTab:y}),c({...b,displayTab:y})},children:b.displayTab===!0||b.displayTab===void 0?e.jsx(s.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(vs,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(s.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[t.cards.map((N,b)=>e.jsxs(s.TabsTrigger,{draggable:!0,onDragStart:y=>d(y,b),onDragOver:i,onDrop:y=>u(y,b),className:"",value:N.id,children:[w(t,N),e.jsx(s.Editable,{enabled:t.activeCardId===N.id,text:N.tabTitle||N.title,onSave:y=>{m({...n,tabTitle:y}),c({...n,tabTitle:y})},children:N.tabTitle||N.title},N.id),t.activeCardId===N.id&&e.jsx(s.CopyPlus,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:y=>{y.stopPropagation(),j()}}),t.activeCardId===N.id&&t.cards.length>1&&e.jsx(s.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>h(N.id)})]},N.id)),e.jsx(s.IconButton,{tooltip:"Add Card",className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",onClick:()=>f(n),children:e.jsx(s.Plus,{className:"h-4 w-4"})})]})})}function ns(){const t=s.useEditorStore(y=>y.frame),n=s.useEditorStore(y=>y.card),a=s.useEditorStore(y=>y.isSqlRunning),r=s.useEditorStore(y=>y.isDevMode),{setFrame:m,setActiveTabCardId:c,setCard:d,setIsDevMode:i,setRunSql:u}=s.useEditorActions(),{data:h,isLoading:g,isFetching:j,isError:f}=s.useDashboardCardQuery(n);function w(y){const F=t.cards.find(k=>k.id===y);if(F!=null&&F.sql){r||i(!0),c(y);return}if(F!=null&&F.queryConfig){r&&i(!1),N(y),c(y);return}r||N(y),c(y)}function N(y){const F={...t,cards:t.cards.map(z=>z.id===n.id?n:z),activeCardId:y};m(F);const k=F.cards.find(z=>z.id===y);k.sql&&u(!0),d(k)}function b(){return n.type==="kpi"?g||j?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border border-border",children:e.jsx(s.KPICard,{card:n,data:h==null?void 0:h.records,isPending:g||j,isError:f})})}):n.type==="text"?g||j?e.jsx("div",{className:"z-50 flex h-full items-center justify-center",children:e.jsx(s.LoadingDots,{size:"md",color:"muted","aria-label":"Loading data"})}):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(s.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(s.TextCard,{isLoading:a,card:n,data:h==null?void 0:h.records})})})}):e.jsx(s.ErrorBoundary,{FallbackComponent:s.FallbackVisual,children:e.jsx(s.EditorCard,{className:"grow border-none shadow-none"})})}return e.jsxs(s.Tabs,{onValueChange:w,value:t.activeCardId,className:"flex grow flex-col",children:[t.cards.map(y=>e.jsx(s.TabsContent,{className:"mt-0 grow",value:y.id,children:b()},y.id)),e.jsx(Js,{})]})}function Ge({children:t}){var v,l;s.useEditorStore(o=>o.frame);const n=s.useEditorStore(o=>o.card),a=s.useEditorStore(o=>o.isDevMode),r=s.useEditorStore(o=>o.isShowingVisual),m=s.useDashboardStore(o=>o.isVisualEditing),c=s.useEditorStore(o=>o.pythonStdOut);s.useEditorStore(o=>o.actions.setRunSql);const{setFrame:d,setCard:i,setActiveTabCardId:u,runAssistant:h,setIsDevMode:g,setCardPreferences:j}=s.useEditorActions(),{data:f,isLoading:w,isFetching:N,errorMessage:b,refetch:y}=s.useDashboardCardQuery(n),[F,k]=T.useState(!1);T.useEffect(()=>{N||k(!1)},[N]);function z(){const o=JSON.stringify(f==null?void 0:f.records,null,2),p=new Blob([o],{type:"application/json"}),S=URL.createObjectURL(p),x=document.createElement("a");x.href=S,x.download=`${n.title}.json`,x.click()}function B(){const p=[Object.keys(f==null?void 0:f.records.reduce((D,M)=>({...D,...M}),{})).join(","),...((f==null?void 0:f.records)||[]).map(D=>Object.values(D).join(","))].join(`
|
|
104
|
+
`),S=new Blob([p],{type:"text/csv"}),x=URL.createObjectURL(S),E=document.createElement("a");E.href=x,E.download=`${n.title}.csv`,E.click()}function C(){const o=`Can you get the documentation for ${n.type} chart?`;h(o)}return n?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[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(ss,{}),m&&e.jsx(s.IconButton,{tooltip:"Visual Docs",onClick:C,children:e.jsx(ps,{className:"size-4"})}),!["table","custom"].includes(n.type)&&m&&e.jsx(s.CustomizeVisualDialog,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:B,children:e.jsx(s.PiFileCsv,{className:"size-4"})}),e.jsx(s.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:z,children:e.jsx(bs,{strokeWidth:1.5,className:"size-4"})}),e.jsx(s.CopyButton,{text:JSON.stringify(f==null?void 0:f.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:[t,e.jsx(s.IconButton,{tooltip:"Refresh",disabled:w||N,onClick:()=>{k(!0),y()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":F})})}),e.jsx(ts,{})]}),n.type==="table"&&n.sql&&a&&e.jsxs("div",{className:"mr-2 flex items-center gap-3",children:[e.jsx(s.Checkbox,{id:"pagination",checked:((l=(v=n.preferences)==null?void 0:v.tablePrefs)==null?void 0:l.enableDevModePagination)??!1,onCheckedChange:o=>{var p;j({...n.preferences,tablePrefs:{...(p=n.preferences)==null?void 0:p.tablePrefs,enableDevModePagination:o}}),y()}}),e.jsx(s.Label,{htmlFor:"pagination",children:"Paginate Results"})]}),a&&e.jsx(Qs,{})]}),r?e.jsx(ns,{}):e.jsxs(s.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[c&&e.jsxs(e.Fragment,{children:[e.jsx(s.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:c&&e.jsx(Ks,{})}),e.jsx(s.ResizableHandle,{})]}),e.jsxs(s.ResizablePanel,{id:"2",order:2,minSize:10,className:s.cn("relative flex h-full min-h-0 w-full flex-1 basis-0",{"px-6":c}),children:[(f==null?void 0:f.records)&&(f==null?void 0:f.records.length)>0&&e.jsx(s.TableVisual,{card:n,data:(f==null?void 0:f.records)||[]}),b&&e.jsx(Vs,{error:b})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function Ks(){const t=s.useEditorStore(a=>a.pythonStdOut);if(!t)return null;const n=t.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(s.ScrollArea,{className:"overflow-y-auto pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:n}}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]})]})}function Qs(){const t=s.useEditorStore(a=>a.isShowingVisual),n=s.useEditorStore(a=>a.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(s.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(s.SmallSwitch,{checked:t,onCheckedChange:()=>n(!t),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function Us(){const t=T.useRef(null),n=T.useRef(null),a=s.useEditorStore(m=>m.isShowingVisual),r=s.useEditorStore(m=>m.showAIDialog);return T.useEffect(()=>{var m,c,d,i;r?((m=t.current)==null||m.resize(0),(c=n.current)==null||c.resize(0)):((d=t.current)==null||d.resize(25),(i=n.current)==null||i.resize(25))},[r]),e.jsxs(s.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:[e.jsx(s.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx(Ms,{})}),e.jsx(s.ResizableHandle,{withHandle:!0}),e.jsx(s.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:a&&!r?e.jsxs(s.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(s.ResizablePanel,{ref:t,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(s.VisualAside,{})})}),!r&&e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(Ge,{})})]}):e.jsx(Ge,{})})]})}function Hs(t){var se;s.useAIInteractionStore(A=>A.currentAIContext);const[n,a]=T.useState(""),[r,m]=T.useState(null),{authToken:c,tokenProps:d}=s.useSemaphorContext(),i=s.useEditorStore(A=>{var J;return(J=A==null?void 0:A.card)==null?void 0:J.sql}),u=s.useEditorStore(A=>A.isDevMode),h=s.useEditorStore(A=>{var J;return(J=A==null?void 0:A.card)==null?void 0:J.python}),{setCardPython:g,setCardSql:j,setRunSql:f,switchCardType:w,setQueryConfig:N}=s.useEditorActions(),b=s.useEditorStore(A=>A.currentAssitantScope)||[],y=s.useEditorStore(A=>A.userInputForAI),F=s.useEditorStore(A=>A.triggerAIRun),k=s.useEditorStore(A=>A.card),z=s.useEditorStore(A=>A.selectedDatabaseName),B=s.useEditorStore(A=>A.selectedTableName),C=s.useEditorStore(A=>A.selectedConnectionId),v=s.useEditorStore(A=>A.selectedSchemaName),l=s.useDashboardStore(A=>A.dashboard.aiScopeTables),{errorMessage:o,refetch:p,data:S}=s.useDashboardCardQuery(k),{setTriggerAIRun:x,setCurrentAssitantScope:E,setCardConfig:D}=s.useEditorActions(),{selectedDatamodelName:M,connectionType:P,selectedDatamodelId:I}=s.useEditorAside(),R=(se=s.useDashboardQuery().data)==null?void 0:se.assistantProfileId,{messages:G,setMessages:V,regenerate:_,error:q,sendMessage:O,status:U,addToolResult:ne,stop:ie,clearError:le}=s.useChat({transport:new s.DefaultChatTransport({api:`${d.apiServiceUrl}/v1/assistant`,headers:()=>({Authorization:`Bearer ${c==null?void 0:c.accessToken}`}),body:()=>{const A=s.useAIInteractionStore.getState();return{random:Math.random(),assistantId:"editor-assistant",assistantProfileId:R,isDevMode:u,aiContext:A.currentAIContext,reasoningEffort:A.reasoningEffort,showReasoning:A.showReasoning}},credentials:"omit",prepareSendMessagesRequest:({messages:A,body:J})=>({body:{...J,messages:s.cleanupIncompleteMessages(A)}})}),onError:A=>{var J;if(A.name==="AbortError"||(J=A.message)!=null&&J.includes("aborted")){console.log("[Editor Assistant] Stream aborted (expected)");return}console.error("[Editor Assistant] Stream error:",A)},onToolCall:K,onFinish({isAbort:A,isDisconnect:J,isError:te}){a(""),console.log(A?"[Editor Assistant] Stream aborted by user":J?"[Editor Assistant] Stream disconnected (network error)":te?"[Editor Assistant] Stream error occurred":"[Editor Assistant] Stream completed successfully")}});T.useEffect(()=>{F&&y&&(O({role:"user",parts:[{type:"text",text:y}]}),x(!1))},[F,y,O,x]);async function K({toolCall:A}){var J,te,ce,pe,re,fe,be,ye,Ne,de,Ce,Se,we,ke,ge,je;if(["createChartFromSql","createForecast"].includes(A.toolName)){const $=((J=A.input)==null?void 0:J.sql)??((te=A.args)==null?void 0:te.sql),H=((ce=A.input)==null?void 0:ce.python)??((pe=A.args)==null?void 0:pe.python),W=((re=A.input)==null?void 0:re.chartType)??((fe=A.args)==null?void 0:fe.chartType);w(W),j($),g(H),f(!0),ne({tool:A.toolName,toolCallId:A.toolCallId,output:{status:"success",message:"Let the user know that chart is created"}})}else if(A.toolName==="getUserSql"){if(!i){ne({tool:A.toolName,toolCallId:A.toolCallId,output:{status:"error",message:"No SQL found"}});return}ne({tool:A.toolName,toolCallId:A.toolCallId,output:{status:"success",sql:i,python:h||""}})}else if(A.toolName==="generateQueryConfig"){a("Generating query config...");const $=((be=A.input)==null?void 0:be.chartType)??((ye=A.args)==null?void 0:ye.chartType),H=((Ne=A.input)==null?void 0:Ne.queryConfig)??((de=A.args)==null?void 0:de.queryConfig);((Ce=A.input)==null?void 0:Ce.cardConfig)??((Se=A.args)==null||Se.cardConfig),w($),D(H),j(void 0),g(void 0);const W=await p();if((we=W==null?void 0:W.data)!=null&&we.error){ne({tool:A.toolName,toolCallId:A.toolCallId,output:{status:"error",queryConfig:H,message:(ke=W==null?void 0:W.data)==null?void 0:ke.error.message}});return}if((ge=W==null?void 0:W.data)!=null&&ge.records){ne({tool:A.toolName,toolCallId:A.toolCallId,output:{status:"success",queryConfig:H,message:"The data has been visualized"}});return}ne({tool:A.toolName,toolCallId:A.toolCallId,output:{status:"success",queryConfig:H,message:"The data has been visualized",records:(je=W==null?void 0:W.data)==null?void 0:je.records}})}else a("Analyzing...")}function Q(A){const J=s.removeFromScopeArray(b,A);Z(J)}function Z(A){const J=s.sanitizeAIScope(A);E(J),V(te=>[...te,{id:crypto.randomUUID(),role:"system",parts:[{type:"text",text:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(J)}`}]}])}function oe(){const A={databaseName:z||"",schemaName:v||"",tableName:B||"",datamodelId:I||"",datamodelName:s.resolveDatamodelName(M),connectionId:C||"",connectionType:P||""},J=s.dedup([...b,A]);Z(J)}function me(){const A={databaseName:z||"",schemaName:v||"",tableName:B||"",datamodelName:s.resolveDatamodelName(M),connectionId:C||"",connectionType:P||"",datamodelId:I||""};if(!s.isInAiScopeArray([...l||[],...b],A)||b.length===0){const te=s.dedup([...l||[],...b,A]).filter(ce=>ce.connectionId===A.connectionId);Z(te)}}const xe=!["ready","error"].includes(U),he=s.getErrorMessage(q);return{messages:G,setMessages:V,sendMessage:O,regenerate:_,isLoading:xe,handleSetAIScope:me,handleAddCurrentTableToScope:oe,removeFromCurrentSelections:Q,currentAssitantScope:b,setCurrentAssitantScope:E,stop:ie,status:U,toolStatus:n,llmUsage:r,onFinish:t,errorMessage:he,clearError:le}}const _s=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Je({isFullscreen:t,onFullscreenChange:n,fullscreenContainer:a}){const r=T.useRef(null),[m,c]=T.useState(!1),[d,i]=T.useState(s.isDevEnv),[u,h]=T.useState(!1),[g,j]=T.useState(!1),[f,w]=T.useState(!1),N=t??f,b=s.useCurrentAIContext(),{setCurrentAIContext:y}=s.useAIActions(),{clearQueue:F}=s.useQueueActions(),{clearFileAttachments:k}=s.useFileActions(),z=s.useFileAttachments("editor"),B=s.useDashboardStore($=>$.dashboard.aiContext),C=s.useEditorStore($=>$.card.dataSource),v=s.useEditorStore($=>$.actions.setCardSql),l=s.useEditorStore($=>$.actions.setRunSql),o=s.useEditorStore($=>$.showAIDialog),p=s.useDashboardStore($=>$.handleOpenAssistantProfile),{setShowAIDialog:S,setCardPython:x}=s.useEditorActions(),{setDataSource:E}=s.useEditorActions(),{assistantProfile:D}=s.useAssistantProfile(),{messages:M,setMessages:P,sendMessage:I,isLoading:R,stop:G,status:V,llmUsage:_,errorMessage:q,clearError:O}=Hs(),[U,ne]=T.useState(""),ie=$=>{ne($.target.value)},le=$=>{$.preventDefault();const H=U.trim();if(!H&&z.length===0)return;const W=[];H&&W.push({type:"text",text:H}),z.forEach(ve=>{ve.data&&W.push({type:"file",mediaType:ve.type,filename:ve.name,url:`data:${ve.type};base64,${ve.data}`})}),I({role:"user",parts:W}),ne(""),k("editor"),J({force:!0})},{visibleMessages:K,hasMoreMessages:Q,totalMessageCount:Z,loadMoreMessages:oe,resetMessageWindow:me}=s.useMessageWindow(M,{maxVisibleMessages:15,initialLoadCount:10,loadMoreCount:5}),{scrollRef:xe,isAtBottom:he,hasNewMessages:se,newMessageCount:A,scrollToBottom:J,handleScroll:te,resetNewMessageCount:ce}=s.useAutoScroll(K,{threshold:50,behavior:"smooth",isStreaming:R});T.useEffect(()=>{var $;o&&(($=r.current)==null||$.focus(),y({selectedEntities:(C==null?void 0:C.selectedEntities)||[]}))},[o,C,y]),s.useAutoSubmitQueue({assistantType:"editor",status:V,isLoading:R,sendMessage:I});const{hasActiveTools:pe}=s.useActiveToolStatus(M),re=T.useCallback($=>{n==null||n($),t===void 0&&w($)},[t,n]);T.useEffect(()=>{if(!N)return;function $(H){H.key==="Escape"&&re(!1)}return window.addEventListener("keydown",$),()=>{window.removeEventListener("keydown",$)}},[N,re]);const fe=T.useCallback($=>{I({role:"user",parts:[{type:"text",text:$}]}),J({force:!0})},[I,J]),be=T.useCallback(async()=>{const $=JSON.stringify(M??[],null,2);try{if(typeof navigator>"u"||!navigator.clipboard)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText($),s.ue.success("Conversation copied")}catch(H){console.error("Failed to copy conversation",H),s.ue.error("Unable to copy conversation")}},[M]),ye=T.useCallback(()=>{re(!N)},[N,re]);function Ne($,H){H==="sql"?(v($),l(!0)):H==="python"&&(x($),l(!0))}function de(){b.selectedEntities.length===0&&y({selectedEntities:(B==null?void 0:B.selectedEntities)||[]})}function Ce($){de();const H={role:"user",parts:[{type:"text",text:$.title+" "+$.subtitle}]};I(H)}function Se($){de(),I({role:"user",parts:[{type:"text",text:$}]})}function we(){return e.jsxs(s.DropdownMenu,{children:[e.jsx(s.DropdownMenuTrigger,{asChild:!0,children:e.jsx(s.Button,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",variant:"ghost",children:e.jsx(s.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(s.DropdownMenuContent,{align:"end",children:[e.jsx(s.DropdownMenuLabel,{children:"Options"}),e.jsx(s.DropdownMenuSeparator,{}),e.jsx(s.DropdownMenuCheckboxItem,{checked:m,onCheckedChange:c,children:"Token Usage"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:d,onCheckedChange:i,children:"Tool Invocations"}),e.jsx(s.DropdownMenuCheckboxItem,{checked:u,onCheckedChange:h,children:"System Message"})]})]})}function ke(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const ge=(U==null?void 0:U.length)===0&&(M==null?void 0:M.filter($=>$.role==="user").length)===0,je=e.jsxs("div",{"data-role":"editor-assistant",className:s.cn("flex h-full w-full flex-col justify-between px-6 py-4",N&&"rounded-2xl border border-border/60 bg-background px-8 pb-6 pt-6 shadow-xl"),children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[ke(),p&&e.jsx(s.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:p,children:(D==null?void 0:D.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center",children:[we(),d&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-2 h-7 px-2 text-muted-foreground hover:text-foreground",onClick:be,children:"Copy Conversation"}),e.jsx(s.IconButton,{tooltip:N?"Exit Fullscreen":"Expand",className:"h-7 p-2 text-muted-foreground hover:text-foreground",onClick:ye,children:N?e.jsx(s.Minimize2,{className:"size-4"}):e.jsx(s.Maximize2,{className:"size-4"})}),e.jsx(s.IconButton,{className:"h-7 p-2 text-muted-foreground hover:text-foreground",tooltip:"New Chat",onClick:()=>{P([]),F("editor"),O(),me()},children:e.jsx(s.SquarePen,{className:"size-4"})}),e.jsx(s.Button,{variant:"ghost",className:"h-7 p-2 text-muted-foreground hover:text-foreground",size:"sm",onClick:()=>{S(!1)},children:e.jsx(s.X,{className:"size-4"})})]})]}),e.jsx(s.CustomScrollArea,{ref:xe,className:"mt-2 flex w-full grow basis-0",onScroll:te,children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[Q&&e.jsx("div",{className:"flex justify-center py-2",children:e.jsxs(s.Button,{variant:"outline",size:"sm",onClick:oe,className:"text-xs",children:["Load ",Math.min(5,Z-K.length)," ","more messages (",Z-K.length," ","hidden)"]})}),e.jsx(s.PrintMessages,{messages:K,showTools:d,handleRun:Ne,showSystemMessage:u,onQuickReply:fe,disableQuickReplies:R}),!pe&&e.jsx(s.AssistantStatus,{status:V,errorMessage:q})]})}),!he&&e.jsx("div",{className:"absolute bottom-24 right-8 z-10",children:e.jsxs(s.Button,{onClick:()=>{J({force:!0}),ce()},size:"sm",variant:"secondary",className:"rounded-full shadow-lg","aria-label":"Scroll to bottom",children:[e.jsx(s.ChevronDown,{className:"h-4 w-4"}),se&&A>0&&e.jsx("span",{className:"ml-1.5 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-xs text-primary-foreground",children:A>9?"9+":A})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[ge&&!D&&e.jsx(s.Placeholders,{onClick:Ce,placeholders:_s}),e.jsx("div",{children:ge&&D&&e.jsx(s.SeedQuestions,{seedQuestions:D.seedQuestions||[],handleSeedQuestionClick:Se})})]}),e.jsx(s.PendingMessagesDisplay,{assistantType:"editor",className:"mb-3"}),e.jsx(s.ChatInputWithContext,{ref:r,setInput:ne,stop:G,input:U,handleInputChange:ie,handleSubmit:$=>{de(),le($),J({force:!0})},isLoading:R,status:V,assistantType:"editor",onFocus:()=>{}})]}),_&&m&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",_.inputTokens," prompt tokens, ",_.outputTokens," ","completion tokens, ",_.totalTokens," total tokens"]})}),e.jsx(s.DataSourceDialog,{incomingSelectedEntities:(C==null?void 0:C.selectedEntities)||[],open:g,onOpenChange:j,dataSource:C||s.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]});return N&&a?us.createPortal(e.jsx("div",{className:"pointer-events-auto absolute inset-0 z-50 flex bg-background px-6 pb-6 pt-[calc(var(--app-header-height,15px)+1rem)]",children:e.jsx("div",{className:"flex h-full w-full",children:je})}),a):je}const Ws="chart-selector-standard-first";function Ys(){const[t,n]=ee.useLocalStorageState(Ws,!0);return{standardFirst:t,updatePreference:n}}const Ke=({pluginVisual:t,index:n,onSelect:a})=>{const r=Ie(t.icon||""),m=t.name.charAt(0).toUpperCase(),c=s.getAutoDetectedChartIcon(t.name);return e.jsx(s.CommandItem,{value:`${t.name} custom visual plugin component`,onSelect:a,className:"group flex items-center gap-2",children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[r?e.jsx(r,{className:"h-4 w-4"}):c||e.jsx("div",{className:"flex h-4 w-4 items-center justify-center rounded bg-muted text-xs font-medium",children:m}),e.jsx("span",{children:t.name})]}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{tabIndex:0,className:"opacity-0 outline-none transition-opacity group-hover:opacity-100",children:e.jsx(s.Info,{className:"ml-1 h-3.5 w-3.5 text-muted-foreground"})})}),e.jsx(s.TooltipContent,{side:"right",children:t.pluginName})]})]})},`${t.url}-${t.name}-${n}`)},Qe=["default","standardPlugin","customPlugin"];function Xs({selectedChart:t,onChartChange:n}){var B;const[a,r]=T.useState(!1),{data:m}=es();Ys();const d=((B=s.useEditorStore(C=>C.card).customCardPreferences)==null?void 0:B.url)||"";ee.useRemoteChartStore(d);const{setCardType:i,setCardPreferences:u,setIsDevMode:h}=s.useEditorStore(C=>C.actions),{setCardCustomCfg:g,setCustomCardPreferences:j,setQueryConfig:f}=s.useEditorActions(),[w,N]=ee.useLocalStorageState("chart-section-active",null),b=T.useMemo(()=>w?[w,...Qe.filter(C=>C!==w)]:Qe,[w]);function y(C){g(null),u({}),i(C),["custom","map"].includes(C)&&(h(!0),f(void 0)),n(C),r(!1)}function F(C){g(null),u({}),i("custom"),j({type:"component",visualType:"single",url:C.url,componentName:C.name,icon:C.icon,pluginChartType:C.chartType}),f(void 0),n("custom"),r(!1)}const k=()=>{var v;if(t==="custom"){const l=s.useEditorStore.getState().card;return((v=l==null?void 0:l.customCardPreferences)==null?void 0:v.componentName)||"Custom Visual"}const C=s.chartTypes.find(l=>l.id===t);return(C==null?void 0:C.label)||"Select chart type"},z=()=>{var v,l;if(t==="custom"){const o=s.useEditorStore.getState().card,p=(v=o==null?void 0:o.customCardPreferences)==null?void 0:v.icon,S=(l=o==null?void 0:o.customCardPreferences)==null?void 0:l.componentName;if(p&&S)return e.jsx(Zs,{icon:p,componentName:S});if(S){const x=s.getAutoDetectedChartIcon(S);if(x)return x}return e.jsx(Te,{className:"h-4 w-4"})}const C=s.chartTypes.find(o=>o.id===t);if(C){const o=C.icon;return e.jsx(o,{className:"h-4 w-4"})}return e.jsx(Te,{className:"h-4 w-4"})};return e.jsx("div",{className:"",children:e.jsxs(s.Popover,{open:a,onOpenChange:r,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":a,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[z(),e.jsx("span",{children:k()})]}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"w-[300px] p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(s.CommandList,{className:"mb-2 max-h-[300px]",children:[e.jsx(s.CommandEmpty,{children:"No chart type found."}),b.map(C=>{if(C==="default")return e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"flex items-center gap-2",children:"Default Visuals"})}),e.jsx(s.TooltipContent,{side:"right",children:"These are the standard visuals available in Semaphor"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:w==="default",onCheckedChange:v=>N(v?"default":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:s.chartTypes.map(v=>{const l=v.icon;return e.jsx(s.CommandItem,{value:`${v.label} ${v.id} chart graph visualization`,onSelect:()=>y(v.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(l,{className:"h-4 w-4"}),e.jsx("span",{children:v.label})]})},v.id)})},"default");if(C==="standardPlugin"){const v=m.filter(l=>l.pluginType==="standard");return v.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsx("p",{children:"Standard Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:w==="standardPlugin",onCheckedChange:l=>N(l?"standardPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:v.filter(l=>l.componentType==="chart").map((l,o)=>e.jsx(Ke,{pluginVisual:l,index:o,onSelect:()=>F(l)},`${l.url}-${l.name}-${o}`))},"standardPlugin"):null}if(C==="customPlugin"){const v=m.filter(l=>l.pluginType==="custom");return v.length?e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"group flex w-full items-center justify-between",children:[e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("span",{className:"flex items-center gap-2",children:["Custom Visuals",e.jsx(s.Info,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),e.jsx(s.TooltipContent,{side:"right",children:"External visuals that are specific to your project"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:"Show on top"}),e.jsx(s.Switch,{checked:w==="customPlugin",onCheckedChange:l=>N(l?"customPlugin":null),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:v.map((l,o)=>e.jsx(Ke,{pluginVisual:l,index:o,onSelect:()=>F(l)},`${l.url}-${l.name}-${o}`))},"customPlugin"):null}return null})]})]})})]})})}const Zs=({icon:t,componentName:n})=>{const a=Ie(),r=s.getAutoDetectedChartIcon(n);return a?e.jsx(a,{className:"h-4 w-4"}):r||e.jsx(Te,{className:"h-4 w-4"})},et=[{id:"table",icon:s.Table2,label:"Table"},{id:"bar",icon:s.ChartColumnIncreasing,label:"Bar Chart"},{id:"line",icon:s.ChartLine,label:"Line Chart"},{id:"stackedBar",icon:s.ChartColumnStacked,label:"Stacked Bar",requiresPivot:!0},{id:"pie",icon:s.ChartPie,label:"Pie Chart"},{id:"doughnut",icon:s.Donut,label:"Donut Chart"},{id:"kpi",icon:s.TiSortNumerically,label:"KPI"}];function st({selectedChart:t,onChartChange:n}){var m;const a=s.useEditorStore(c=>c.card),r=((m=a==null?void 0:a.config)==null?void 0:m.pivotByColumns)&&a.config.pivotByColumns.length>0;return e.jsx("div",{className:"flex items-center justify-center gap-1",children:et.map(c=>{if(c.requiresPivot&&!r)return null;const d=c.icon,i=t===c.id;return e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"ghost",size:"sm",onClick:()=>n(c.id),className:s.cn("h-8 w-8 p-0",i&&"bg-accent text-accent-foreground"),children:[e.jsx(d,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:c.label})]})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:c.label})})]},c.id)})})}const Be=({dataType:t})=>s.getFieldIconComponent(t);function tt({aliasTemplate:t,onAliasTemplateChange:n}){var u;const[a,r]=T.useState(t),[m,c]=T.useState(!1),d=(u=s.useEditorStore(h=>{var g;return(g=h.card.config)==null?void 0:g.pivotByColumns}))==null?void 0:u[0],i=d?`e.g. Min Sales in {{${d.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.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(s.Input$1,{placeholder:i,value:m?a:t,onChange:h=>{r(h.target.value),c(!0)},onFocus:()=>c(!0),onPointerDown:h=>h.stopPropagation(),className:"h-8 text-xs",onKeyDown:h=>{h.key==="Enter"&&m&&a!==t?(n(a),c(!1)):h.key==="Escape"&&(r(t),c(!1))},"aria-label":"Edit alias template"}),m&&a!==t&&e.jsxs(e.Fragment,{children:[e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{n(a),c(!1)},children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(t),c(!1)},children:e.jsx(s.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function nt({valueAliases:t,onValueAliasesChange:n}){const[a,r]=T.useState(null),[m,c]=T.useState(""),[d,i]=T.useState(""),u=()=>{n({...t,"":""})},h=j=>{const f={...t};delete f[j],n(f)},g=j=>{const f={...t};delete f[j],f[m]=d,n(f),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(t).map(([j,f],w)=>e.jsx("div",{className:"flex items-center gap-2",children:a===j?e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:m,onChange:N=>c(N.target.value),className:"h-8 w-24 text-xs",onPointerDown:N=>N.stopPropagation(),onKeyDown:N=>{N.key==="Enter"?g(j):N.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:d,onChange:N=>i(N.target.value),className:"h-8 w-24 text-xs",onPointerDown:N=>N.stopPropagation(),onKeyDown:N=>{N.key==="Enter"?g(j):N.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>g(j),children:e.jsx(s.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(s.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(s.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(s.Input$1,{placeholder:"Value key",value:j,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(j),c(j),i(f)},"aria-label":"Edit value alias key"}),e.jsx(s.Input$1,{placeholder:"Alias label",value:f,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(j),c(j),i(f)},"aria-label":"Edit value alias label"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>h(j),"aria-label":"Remove value alias",children:e.jsx(s.X,{className:"h-3 w-3"})})]})},j+w)),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:u,children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function at({column:t}){const n=s.useEditorStore(u=>u.card.type),a=s.useEditorStore(u=>{var h,g;return(g=(h=u.card)==null?void 0:h.config)==null?void 0:g.metricColumns}),r=(a==null?void 0:a.map(u=>u.label))||[],m=r==null?void 0:r.find(u=>u===t.label||u===t.name),c=m?r.indexOf(m):-1;function d(){return e.jsx("div",{className:"pr-1",children:m&&e.jsx(Le.MetricFragment,{idx:c,col:m,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function i(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(ms.DisplayLabels,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(n)&&d(),["pie","doughnut"].includes(n)&&i()]})}function rt({field:t,searchQuery:n="",limit:a=500}){const{authToken:r,tokenProps:m}=s.useSemaphorContext(),c=s.useEditorStore(h=>h.card),d=c==null?void 0:c.dataSource,i=["attribute-values",t.entityName,t.name,n,a],u=s.useQuery({queryKey:i,queryFn:async()=>{if(!(d!=null&&d.connectionId))return console.warn("No connection ID available for attribute values query"),[];try{const h={groupByColumns:[{...t,role:"groupby"}],metricColumns:[],filters:n?{id:"search-filter",logicalOperator:"AND",negate:!1,conditions:[{id:"search-condition",field:t,operator:"contains",value:n}],groups:[]}:void 0,rowLimit:a},g={connection_id:d.connectionId,cardConfig:h,cardDataSource:d,cache_config:s.getCacheConfig({card:c})};console.log("requestBody",g);const j=await s.postRequestRegular(`${m.apiServiceUrl}/v1/query`,(r==null?void 0:r.accessToken)||"",g);if(j!=null&&j.error)return console.error("Error fetching attribute values:",j.error),[];const f=t.name;return((j==null?void 0:j.records)||[]).map(N=>{const b=N[f]||N[t.alias||f]||N[t.label];return{id:b||"",value:b||"",label:String(b||"(empty)")}})}catch(h){return console.error("Error fetching attribute values:",h),[]}},enabled:!!t&&!!(d!=null&&d.connectionId),staleTime:5*60*1e3,gcTime:10*60*1e3});return{values:u.data||[],isLoading:u.isLoading,isFetching:u.isFetching,isError:u.isError,error:u.error,refetch:u.refetch}}function ot({open:t,onOpenChange:n,availableFields:a,existingFilters:r,editingCondition:m,onSave:c}){var z,B;const d=!!m,[i,u]=T.useState(d?"values":"fields"),[h,g]=T.useState(""),[j,f]=T.useState({id:(m==null?void 0:m.id)||s.v4(),field:(m==null?void 0:m.field)||null,selectedValues:m?Array.isArray(m.value)?m.value:[m.value]:[]}),w=a.filter(C=>{var l;return d?!1:!((l=r==null?void 0:r.conditions)==null?void 0:l.some(o=>o.field.id===C.id))&&C.label.toLowerCase().includes(h.toLowerCase())}),N=C=>{f({...j,field:C}),u("values")},b=()=>{if(j.field&&j.selectedValues.length>0){const C={id:j.id,field:j.field,operator:"in",value:j.selectedValues};let v;if(d){const l=((r==null?void 0:r.conditions)||[]).map(o=>o.id===m.id?C:o);v={...r,conditions:l}}else{const l=(r==null?void 0:r.conditions)||[];v={id:(r==null?void 0:r.id)||s.v4(),logicalOperator:"AND",negate:!1,conditions:[...l,C],groups:[]}}c(v),n(!1)}},y=()=>{if(!d||!m)return;const C=((r==null?void 0:r.conditions)||[]).filter(v=>v.id!==m.id);if(C.length>0){const v={...r,conditions:C};c(v)}else c(void 0);n(!1)},F=C=>{f({...j,selectedValues:C})},k=()=>{d&&m?(f({id:m.id,field:m.field,selectedValues:Array.isArray(m.value)?m.value:[m.value]}),u("values")):(f({id:s.v4(),field:null,selectedValues:[]}),u("fields")),g("")};return T.useEffect(()=>{t&&k()},[t,d,m]),e.jsx(s.Dialog,{open:t,onOpenChange:n,children:e.jsxs(s.DialogContent,{className:"max-w-2xl",children:[e.jsx(s.DialogHeader,{children:e.jsx(s.DialogTitle,{children:d?`Edit Filter: ${(z=j.field)==null?void 0:z.label}`:i==="fields"?"Select Field to Filter":`Select Values for ${(B=j.field)==null?void 0:B.label}`})}),e.jsxs("div",{className:"space-y-4",children:[!d&&(r==null?void 0:r.conditions)&&r.conditions.length>0&&i==="fields"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Current Filters:"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:r.conditions.map(C=>e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted rounded-md text-xs",children:[e.jsxs("span",{className:"font-medium",children:[C.field.label,":"]}),e.jsx("span",{className:"text-muted-foreground",children:Array.isArray(C.value)?`${C.value.length} values`:String(C.value)})]},C.id))})]}),i==="fields"&&!d?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search fields...",value:h,onChange:C=>g(C.target.value),className:"pl-10"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-[400px] overflow-y-auto",children:w.map(C=>e.jsxs(s.Button,{variant:"outline",className:"justify-start h-auto py-2 px-3",onClick:()=>N(C),children:[e.jsx(Be,{dataType:s.getDataType(C.dataType)}),e.jsxs("div",{className:"ml-2 text-left",children:[e.jsx("div",{className:"text-sm font-medium",children:C.label}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[C.entityName,".",C.name]})]})]},C.id))}),w.length===0&&h&&e.jsxs("div",{className:"text-center py-4 text-sm text-muted-foreground",children:['No fields found matching "',h,'"']}),w.length===0&&!h&&a.length>0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"All available fields are already filtered"})]}):e.jsx(it,{field:j.field,selectedValues:j.selectedValues,onValuesChange:F,onBack:d?void 0:()=>u("fields")}),e.jsxs("div",{className:"flex justify-between pt-4 border-t",children:[e.jsx("div",{children:d?e.jsx(s.Button,{variant:"destructive",onClick:y,children:"Delete Filter"}):e.jsx(s.Button,{variant:"outline",onClick:k,children:"Reset"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(s.Button,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(s.Button,{onClick:b,disabled:!j.field||j.selectedValues.length===0,children:"Apply"})]})]})]})]})})}function it({field:t,selectedValues:n,onValuesChange:a,onBack:r}){const[m,c]=T.useState(""),{values:d,isLoading:i,isFetching:u}=rt({field:t,searchQuery:m,limit:500}),h=m?d.filter(f=>String(f.value).toLowerCase().includes(m.toLowerCase())):d,g=f=>{const w=n.includes(f);a(w?n.filter(N=>N!==f):[...n,f])},j=()=>{n.length===h.length&&h.length>0?a([]):a(h.map(f=>f.value))};return e.jsxs("div",{className:"space-y-4",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:r,children:"← Back"}),e.jsxs(s.Label,{className:"text-sm font-medium",children:["Select values for ",t.label]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(s.Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(s.Input$1,{placeholder:"Search values...",value:m,onChange:f=>c(f.target.value),className:"pl-10"})]}),i||u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(s.LoaderCircle,{className:"h-6 w-6 animate-spin"})}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 pb-2 border-b",children:[e.jsx(s.Checkbox,{checked:n.length===h.length&&h.length>0,onCheckedChange:j}),e.jsxs(s.Label,{className:"text-sm",children:["Select All (",h.length,")"]})]}),e.jsx("div",{className:"max-h-[300px] overflow-y-auto space-y-1",children:h.map(f=>e.jsxs("div",{className:"flex items-center gap-2 p-2 hover:bg-muted/50 rounded cursor-pointer",onClick:()=>g(f.value),children:[e.jsx(s.Checkbox,{checked:n.includes(f.value),onCheckedChange:()=>g(f.value)}),e.jsx(Le.OverflowSpan,{className:"text-sm",children:f.label})]},f.id))})]})]})}function lt({field:t,zone:n,index:a,sortDirection:r,onSortDirectionChange:m,hasPivotColumns:c=!1,cardType:d}){var Me,Oe,ze,Re;const{attributes:i,listeners:u,setNodeRef:h,transform:g,transition:j,isDragging:f}=s.useSortable({id:t.id}),w=s.useEditorStore(L=>L.card),{updateLabel:N,handleAggregationChange:b,handleDateFormatChange:y,handleGranularityChange:F,handleAliasTemplateChange:k,handleValueAliasesChange:z,removeField:B,handleKpiComparisonTypeChange:C,handleKpiShowTrendlineChange:v,handleKpiTrendlineWindowChange:l,handleKpiTrendlineGranularityChange:o,handleKpiTargetValueChange:p}=ee.useFieldManagement(w),[S,x]=T.useState(!1),[E,D]=T.useState(!1),[M,P]=T.useState(null),[I,R]=T.useState(t.dateFormat||"YYYY-MM-DD"),[G,V]=T.useState(t.customFormat||""),[_,q]=T.useState(!!t.customFormat),[O,U]=T.useState(t.granularity||"day"),[ne,ie]=T.useState(t.aliasTemplate||""),[le,K]=T.useState(t.valueAliases||{}),[Q,Z]=T.useState((Me=t.parameters)==null?void 0:Me.filters),oe=L=>{L==="custom"?q(!0):(q(!1),R(L),n==="groupBy"&&y(a,L,""))},me=L=>{V(L),n==="groupBy"&&y(a,"custom",L)},xe=L=>{var ae;U(L);const X=(ae=s.getDateFormatOptionsForGranularity(L)[0])==null?void 0:ae.value;X&&!_&&(R(X),n==="groupBy"&&y(a,X,"")),n==="groupBy"&&F(a,L)},he=L=>{ie(L),n==="metrics"&&k(a,L)},se=L=>{K(L),n==="metrics"&&z(a,L)},A=L=>{N(n,a,L)},J=L=>{var Y;if(Z(L),n==="metrics"){const X={...t,parameters:{...t.parameters,filters:L}},ae=[...((Y=w.config)==null?void 0:Y.metricColumns)||[]];ae[a]=X,s.useEditorStore.getState().actions.updateCardConfig(w.id,{metricColumns:ae})}D(!1)},te=()=>{B(n,a)},ce={transform:s.CSS.Transform.toString(g),transition:j},pe=s.getDataType(t.dataType),re=pe==="date",fe=d==="kpi",be=s.getDateFormatOptionsForGranularity(O),ye=n!=="pivotBy",Ne=re&&n==="groupBy"&&(!fe||((Oe=w.config)==null?void 0:Oe.comparisonType)==="start_vs_end"),de=!fe&&re&&n==="groupBy",Ce=d&&s.COMPARISON_SUPPORTED_CHART_TYPES.includes(d)&&re&&n==="groupBy",Se=d==="kpi"&&re&&n==="groupBy",we=d&&d!=="pivotTable"&&n==="metrics"&&((ze=w.config)==null?void 0:ze.comparisonType)==="target",ke=n==="metrics",ge=()=>e.jsx("div",{title:`${t.entityName}.${t.name}`,onPointerDown:L=>{L.stopPropagation()},className:"max-w-[270px] cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${t.entityName}.${t.name}`}),je=()=>ye?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Label"}),e.jsx(s.InlineEditField,{value:t.label??"",onSave:A,placeholder:"Display label...",type:"text"})]}):null,$=()=>Ne?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(s.Select,{value:O,onValueChange:xe,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsx(s.SelectContent,{children:["day","week","month","quarter","year"].map(L=>e.jsx(s.SelectItem,{className:"text-xs",value:L,children:s.toTitleCase(L)},L))})]})]}):null,H=()=>de?e.jsxs(e.Fragment,{children:[$(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(s.Select,{value:_?"custom":I,onValueChange:oe,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select date format..."})}),e.jsx(s.SelectContent,{children:be.map(L=>e.jsx(s.SelectItem,{className:"text-xs",value:L.value,children:L.label},L.value))})]}),_&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(s.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:G,onChange:L=>{L.stopPropagation(),me(L.target.value)},onClick:L=>L.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"})]})]})]}):null,W=()=>{var X,ae,ue,Ee,$e;const L=Ce,Y=Se;return!L&&!Y?null:e.jsxs(e.Fragment,{children:[L&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(s.Select,{value:((X=w.config)==null?void 0:X.comparisonType)||"none",onValueChange:C,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(s.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(s.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(s.SelectItem,{value:"start_vs_end",children:"Start vs End"})]})]})]}),Y&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(s.SmallSwitch,{checked:((ae=w.config)==null?void 0:ae.showTrendline)||!1,onCheckedChange:v})]})}),((ue=w.config)==null?void 0:ue.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(s.Input$1,{type:"number",min:"1",max:"365",value:((Ee=w.config)==null?void 0:Ee.trendlineWindow)||30,onChange:ls=>{const cs=parseInt(ls.target.value)||30;l(cs)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(s.Select,{value:(($e=w.config)==null?void 0:$e.trendlineGranularity)||"day",onValueChange:o,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"day",children:"Day"}),e.jsx(s.SelectItem,{value:"week",children:"Week"}),e.jsx(s.SelectItem,{value:"month",children:"Month"})]})]})]})]})]})]})},ve=()=>{var L,Y;return we?e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(s.InlineEditField,{value:((L=w.config)==null?void 0:L.targetValue)!==void 0&&((Y=w.config)==null?void 0:Y.targetValue)!==null?String(w.config.targetValue):"",onSave:X=>{!isNaN(Number(X))&&X!==null?p(Number(X)):p(0)},placeholder:"Enter target value...",type:"text"})]}):null},rs=()=>ke?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(s.Select,{value:t.aggregate,onValueChange:L=>{b(a,L)},children:[e.jsx(s.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(s.SelectValue,{placeholder:"Select function..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"COUNT",children:"Count"}),e.jsx(s.SelectItem,{className:"text-xs",value:"DISTINCT",children:"Count Distinct"}),s.getDataType(t.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(s.SelectItem,{className:"text-xs",value:"SUM",children:"Sum"}),e.jsx(s.SelectItem,{className:"text-xs",value:"AVG",children:"Average"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MIN",children:"Min"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MAX",children:"Max"}),e.jsx(s.SelectItem,{className:"text-xs",value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(s.Label,{className:"text-xs font-medium text-muted-foreground",children:"Attribute Filters"}),(Q==null?void 0:Q.conditions)&&Q.conditions.length>0&&e.jsx("div",{className:"mb-2 space-y-1",children:Q.conditions.map(L=>e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 rounded bg-muted/50 p-2 text-xs transition-colors hover:bg-muted/70",onClick:()=>{P(L),D(!0)},children:[e.jsxs("span",{className:"font-medium",children:[L.field.label,":"]}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:"cursor-help text-muted-foreground",children:Array.isArray(L.value)?L.value.length===1?String(L.value[0]):L.value.length<=2?L.value.join(", "):`${L.value.slice(0,2).join(", ")} +${L.value.length-2}`:String(L.value)})}),Array.isArray(L.value)&&L.value.length>1&&e.jsx(s.TooltipContent,{side:"top",className:"max-w-[300px]",children:e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"mb-1 font-medium",children:["Selected values (",L.value.length,"):"]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto",children:L.value.map((Y,X)=>e.jsx("div",{children:String(Y)},X))})]})})]})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"ml-auto h-4 w-4 p-0",onClick:Y=>{var ae;Y.stopPropagation();const X=Q.conditions.filter(ue=>ue.id!==L.id);if(X.length>0){const ue={...Q,conditions:X};J(ue)}else if(Z(void 0),n==="metrics"){const ue={...t,parameters:{...t.parameters,filters:void 0}},Ee=[...((ae=w.config)==null?void 0:ae.metricColumns)||[]];Ee[a]=ue,s.useEditorStore.getState().actions.updateCardConfig(w.id,{metricColumns:Ee})}},children:e.jsx(s.X,{className:"h-3 w-3"})})]},L.id))}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-8 w-full justify-start text-xs",onClick:()=>{P(null),D(!0)},children:[e.jsx(s.Filter,{className:"mr-2 h-3 w-3"}),"Add attribute filter"]})]}),e.jsx(at,{column:t}),c&&e.jsxs(e.Fragment,{children:[e.jsx(tt,{aliasTemplate:ne,onAliasTemplateChange:he}),e.jsx(nt,{valueAliases:le,onValueAliasesChange:se})]})]}):null,{columns:os=[]}=s.useColumns(),is=(Q==null?void 0:Q.conditions)&&Q.conditions.length>0;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{ref:h,style:ce,...i,...u,className:`group mx-auto flex w-full flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${f?"z-50 scale-95 opacity-50":"border-slate-200"} ${n==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsx(Be,{dataType:pe}),e.jsx(Le.OverflowSpan,{className:s.cn("w-[140px] flex-1 text-sm",is&&"w-[120px]"),children:s.getMetricDisplayLabel(t)}),n==="metrics"&&((Re=Q==null?void 0:Q.conditions)==null?void 0:Re.length)&&!S&&e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-xs",children:[e.jsx(s.Filter,{className:"h-3 w-3"}),e.jsx("span",{children:Q.conditions.length})]})}),e.jsx(s.TooltipContent,{side:"top",children:e.jsx("div",{className:"text-xs",children:Q.conditions.map(L=>e.jsxs("div",{children:[L.field.label,":"," ",Array.isArray(L.value)?`${L.value.length} values`:String(L.value)]},L.id))})})]})}),n!=="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:L=>{L.stopPropagation(),x(!S)},children:e.jsx(s.ChevronDown,{className:`h-3 w-3 transition-transform ${S?"rotate-180":""}`})}),n==="sortBy"&&e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:L=>{L.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const Y=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",Y),m(Y)},children:r==="asc"?e.jsx(s.ArrowUp,{className:"h-3 w-3"}):e.jsx(s.ArrowDown,{className:"h-3 w-3"})}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:L=>{L.stopPropagation(),te()},children:e.jsx(s.X,{className:"h-2.5 w-2.5"})})]}),S&&e.jsxs("div",{className:"space-y-3",children:[ge(),je(),d==="kpi"&&$(),H(),W(),ve(),rs()]})]}),E&&e.jsx(ot,{open:E,onOpenChange:L=>{D(L),L||P(null)},availableFields:os,existingFilters:Q,editingCondition:M,onSave:L=>{var Y;if(L)J(L);else if(Z(void 0),n==="metrics"){const X={...t,parameters:{...t.parameters,filters:void 0}},ae=[...((Y=w.config)==null?void 0:Y.metricColumns)||[]];ae[a]=X,s.useEditorStore.getState().actions.updateCardConfig(w.id,{metricColumns:ae})}P(null)}})]})}function ct({concept:t}){const n=()=>{switch(t){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-blue-100 text-xs font-medium dark:bg-blue-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-blue-200/50 text-xs font-medium dark:bg-blue-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-blue-200/30 text-xs font-medium dark:bg-blue-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-blue-200/20 text-xs font-medium dark:bg-blue-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(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(s.TooltipContent,{side:"right",align:"start",className:"p-3",children:n()})]})})}function De({zone:t,fields:n,label:a,placeholder:r,shouldShow:m,hasPivotColumns:c=!1,activeField:d=null}){const{isOver:i,setNodeRef:u}=s.useDroppable({id:t}),{updateSortByColumn:h}=s.useEditorActions(),g=s.useEditorStore(y=>y.card),j=s.useEditorStore(y=>y.card.type),f=n.length>0,w=T.useMemo(()=>!d||!i?!0:ee.validateFieldForChartType(d,t,j).isValid,[d,i,t,j]),N=(y,F)=>{var z;!((z=g.config)!=null&&z.sortByColumns)||g.config.sortByColumns.findIndex(B=>B.id===y)===-1||h(g.id,y,{direction:F})};if(t==="sortBy"&&m===!1)return null;const b=t!=="sortBy"&&j!=="kpi";return e.jsxs("div",{className:"mb-4 w-full",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(s.Label,{className:s.cn("block text-sm font-medium",{}),children:a}),b&&e.jsx(ct,{concept:t})]}),e.jsx("div",{ref:u,className:s.cn("rounded-lg border-2 border-dotted p-0.5 transition-all",{"border-green-500 bg-green-50 dark:bg-green-950":i&&w,"border-red-500 bg-red-50 dark:bg-red-950":i&&!w,"border-muted-foreground/30 bg-muted/40":!i&&f,"min-h-[60px] border-muted-foreground/20 bg-background":!i&&!f}),children:n.length===0?e.jsx("div",{className:"flex min-h-[60px] items-center justify-center text-sm text-muted-foreground/60",children:r}):e.jsx(s.SortableContext,{items:n.map(y=>y.id),strategy:s.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-1",children:n.map((y,F)=>{const z=y.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(lt,{field:y,zone:t,index:F,sortDirection:z,onSortDirectionChange:B=>N(y.id,B),hasPivotColumns:c,cardType:j})})},y.id)})})})})]})}const Ue=[{value:"green",color:"#16a34a",label:"Green"},{value:"red",color:"#dc2626",label:"Red"},{value:"neutral",color:"#6b7280",label:"Neutral"}],dt=["#16a34a","#dc2626","#6b7280","#2563eb","#ca8a04","#7c3aed","#0891b2","#e11d48","#ea580c"];function Ae({value:t,onChange:n,label:a}){const[r,m]=T.useState(!1),[c,d]=T.useState(!1),i=()=>{const u=Ue.find(h=>h.value===t);return u?u.color:t.startsWith("#")?t:Ue[2].color};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(s.Popover,{open:r,onOpenChange:m,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsx("button",{className:"size-5 rounded border-2 border-input shadow-sm transition-all hover:scale-110 hover:border-gray-400",style:{backgroundColor:i()},"aria-label":`Change color for ${a}`})}),e.jsx(s.PopoverContent,{align:"start",className:"w-auto p-2",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"grid grid-cols-3 items-center justify-items-center gap-1",children:dt.map(u=>e.jsx("button",{className:s.cn("h-5 w-5 rounded border-2 transition-all",i()===u?"border-gray-900":"border-transparent"),style:{backgroundColor:u},onClick:()=>{n(u),m(!1)},children:e.jsx("span",{className:"sr-only",children:u})},u))}),e.jsx("button",{className:"w-full rounded border border-input px-2 py-1 text-xs hover:bg-muted",onClick:()=>{d(!0),m(!1)},children:"Custom color..."})]})})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:a})]}),c&&e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{className:"absolute inset-0 bg-black/50",onClick:()=>d(!1)}),e.jsx("div",{className:"relative rounded-lg bg-white shadow-lg",children:e.jsx(s.CustomColorPicker,{color:i(),onColorChange:u=>{n(u),d(!1)},onClose:()=>d(!1)})})]})]})}const He={difference:{label:"Difference",description:"Shows the exact difference between two values.",formula:"Primary - Secondary",example:"Sales increased by $5,000 compared to last year."},change:{label:"Change",description:"Shows the percentage increase or decrease between two values.",formula:"(Primary - Secondary) / Secondary × 100%",example:"Year-over-year sales change of 25%."},change_difference:{label:"Change (difference)",description:"Shows both the percentage change and the exact difference between two values.",formula:`% Change: (Primary - Secondary) / Secondary × 100%
|
|
105
|
+
Difference: Primary - Secondary`,example:"Sales grew by 25% ($5,000) compared to last year."},ratio:{label:"Ratio",description:"Shows how much of one value is covered by another — useful for quotas and benchmarks.",formula:"Primary / Secondary × 100%",example:"You've achieved 80% of your sales quota."}};function ut(){var f,w,N,b,y,F,k,z,B,C,v;const t=s.useEditorStore(l=>l.card),{setCardPreferences:n}=s.useEditorActions(),a=((f=t.config)==null?void 0:f.metricColumns)||[],r=((w=t.config)==null?void 0:w.groupByColumns)||[],m=a.length===2&&r.length===0,c=a.length>=1&&r.length>0;if(!(t.type==="kpi"&&(m||c)))return null;const i=((b=(N=t.preferences)==null?void 0:N.kpiVisualOptions)==null?void 0:b.metricComparison)||{},u=l=>{var p;const o={...t.preferences,kpiVisualOptions:{...(p=t.preferences)==null?void 0:p.kpiVisualOptions,metricComparison:{...i,...l}}};n(o)},h=c||i.enabled,g=((y=t.config)==null?void 0:y.comparisonType)||"none",j=g==="previous_period"||g==="same_period_last_year"||g==="start_vs_end";return e.jsxs(s.AccordionItem,{value:"comparison",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ys,{className:"h-4 w-4"}),e.jsx("span",{children:"Comparison"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:[m&&a.length===2&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{htmlFor:"enable-comparison",className:"text-xs",children:"Enable Metric Comparison"}),e.jsx(s.SmallSwitch,{id:"enable-comparison",checked:i.enabled||!1,onCheckedChange:l=>u({enabled:l,...l&&!i.calculationType?{calculationType:"difference"}:{}})})]}),h&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(s.Label,{htmlFor:"calculation-type",className:"text-xs font-medium uppercase text-muted-foreground",children:"Calculated as"}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Info,{className:"h-3 w-3 cursor-help text-muted-foreground"})}),e.jsx(s.TooltipContent,{side:"right",className:"max-w-xs",children:(()=>{const l=i.calculationType||"difference",o=He[l];return e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsx("div",{className:"text-sm font-semibold",children:o==null?void 0:o.label}),e.jsx("p",{children:o==null?void 0:o.description}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Formula:"})," ",e.jsx("code",{className:"rounded bg-muted px-1 py-0.5 text-[10px]",children:o==null?void 0:o.formula})]}),e.jsxs("div",{className:"border-t pt-1.5 italic",children:[e.jsx("span",{className:"font-medium",children:"Example:"})," ",o==null?void 0:o.example]})]})})()})]})]}),e.jsxs(s.Select,{value:i.calculationType||"difference",onValueChange:l=>u({calculationType:l}),children:[e.jsx(s.SelectTrigger,{id:"calculation-type",className:"h-7 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:Object.entries(He).map(([l,o])=>e.jsx(s.SelectItem,{value:l,className:"text-xs",children:o.label},l))})]})]}),e.jsx(s.NumberFormatConfig,{formatOptions:i.formatOptions||{},onFormatOptionsChange:l=>u({formatOptions:l}),showTitle:!0,title:"COMPARISON FORMAT"}),(j||m)&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Indicator"}),m&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(s.Label,{className:"text-xs text-muted-foreground",children:"Position"}),e.jsxs(s.Select,{value:i.position||"right",onValueChange:l=>u({position:l}),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20 text-xs",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"right",className:"text-xs",children:"Right"}),e.jsx(s.SelectItem,{value:"left",className:"text-xs",children:"Left"}),e.jsx(s.SelectItem,{value:"top",className:"text-xs",children:"Top"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-arrow",checked:i.showArrow!==!1,onCheckedChange:l=>u({showArrow:l})}),e.jsx(s.Label,{htmlFor:"show-arrow",className:"cursor-pointer text-xs text-muted-foreground",children:"Arrow"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"show-color",checked:i.showColor!==!1,onCheckedChange:l=>u({showColor:l})}),e.jsx(s.Label,{htmlFor:"show-color",className:"cursor-pointer text-xs text-muted-foreground",children:"Color"})]}),i.showColor!==!1&&e.jsxs("div",{className:"space-y-2 border-l-2 border-muted pl-3",children:[e.jsx(Ae,{value:((F=i.colorConfig)==null?void 0:F.increase)||"green",onChange:l=>u({colorConfig:{...i.colorConfig,increase:l}}),label:"Primary > Secondary"}),e.jsx(Ae,{value:((k=i.colorConfig)==null?void 0:k.decrease)||"red",onChange:l=>u({colorConfig:{...i.colorConfig,decrease:l}}),label:"Primary < Secondary"}),e.jsx(Ae,{value:((z=i.colorConfig)==null?void 0:z.noChange)||"neutral",onChange:l=>u({colorConfig:{...i.colorConfig,noChange:l}}),label:"Primary = Secondary"})]})]}),e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(s.Label,{className:"text-xs font-medium uppercase text-muted-foreground",children:"Label"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Checkbox,{id:"conditional-label",checked:i.conditionalLabel||!1,onCheckedChange:l=>u({conditionalLabel:l})}),e.jsx(s.Label,{htmlFor:"conditional-label",className:"cursor-pointer text-xs text-muted-foreground",children:"Conditional"})]}),i.conditionalLabel?e.jsxs("div",{className:"space-y-3 border-l-2 border-muted pl-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-increase",className:"text-xs text-muted-foreground",children:["Primary ",">"," Secondary"]}),e.jsx(s.Input,{id:"label-increase",type:"text",value:((B=i.conditionalLabels)==null?void 0:B.increase)??"Increase",onChange:l=>u({conditionalLabels:{...i.conditionalLabels,increase:l.target.value}}),placeholder:"Increase",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(s.Label,{htmlFor:"label-decrease",className:"text-xs text-muted-foreground",children:["Primary ","<"," Secondary"]}),e.jsx(s.Input,{id:"label-decrease",type:"text",value:((C=i.conditionalLabels)==null?void 0:C.decrease)??"Decrease",onChange:l=>u({conditionalLabels:{...i.conditionalLabels,decrease:l.target.value}}),placeholder:"Decrease",className:"h-7 text-xs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-no-change",className:"text-xs text-muted-foreground",children:"Primary = Secondary"}),e.jsx(s.Input,{id:"label-no-change",type:"text",value:((v=i.conditionalLabels)==null?void 0:v.noChange)??"No change",onChange:l=>u({conditionalLabels:{...i.conditionalLabels,noChange:l.target.value}}),placeholder:"No change",className:"h-7 text-xs"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(s.Label,{htmlFor:"label-name",className:"text-xs text-muted-foreground",children:"Previous Label"}),e.jsx(s.Input,{id:"label-name",type:"text",value:i.labelName??"",onChange:l=>u({labelName:l.target.value}),placeholder:"e.g. Previous, Last Period",className:"h-7 text-xs"})]})]})]})]})]})}function mt(){var m,c;const t=s.useEditorStore(d=>d.card),{setCardPreferences:n}=s.useEditorActions();if(t.type!=="kpi")return null;const a=((c=(m=t.preferences)==null?void 0:m.kpiVisualOptions)==null?void 0:c.formatOptions)||{},r=d=>{var u;const i={...t.preferences,kpiVisualOptions:{...(u=t.preferences)==null?void 0:u.kpiVisualOptions,formatOptions:d}};n(i)};return e.jsxs(s.AccordionItem,{value:"kpi-format",className:"border-none",children:[e.jsx(s.AccordionTrigger,{className:"flex items-center gap-2 py-2 text-sm hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Hash,{className:"h-4 w-4"}),e.jsx("span",{children:"Number Format"})]})}),e.jsx(s.AccordionContent,{className:"space-y-4 pb-4 pt-2",children:e.jsx(s.NumberFormatConfig,{formatOptions:a,onFormatOptionsChange:r,showTitle:!1})})]})}function xt({groupByFields:t,pivotByFields:n,metricsFields:a,sortByFields:r,activeField:m}){const c=s.useEditorStore(y=>{var F;return((F=y.card.customCardPreferences)==null?void 0:F.url)&&y.card.type==="custom"}),d=s.useEditorStore(y=>y.card),i=d==null?void 0:d.type,u=t.length>0||a.length>0,h=i!=="kpi"||a.length<=2,g=i!=="kpi",j=i!=="kpi"&&u,f=["pie","doughnut","polar","funnel","aggregateTable"].includes(i),w=g&&!f,N=()=>i==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},b=()=>i==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs(s.Accordion,{type:"single",collapsible:!0,defaultValue:"fields",className:"w-full",children:[e.jsxs(s.AccordionItem,{value:"fields",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.List,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"FIELDS"})]})}),e.jsxs(s.AccordionContent,{className:"space-y-4 pt-2",children:[h&&e.jsx(De,{zone:"groupBy",fields:t,label:N().label,placeholder:N().placeholder,activeField:m}),w&&e.jsx(De,{zone:"pivotBy",fields:n,label:"Columns",placeholder:"Drop fields to pivot data",activeField:m}),e.jsx(De,{zone:"metrics",fields:a,label:b().label,placeholder:b().placeholder,hasPivotColumns:n.length>0,activeField:m}),j&&e.jsx(De,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics",activeField:m})]})]}),!c&&e.jsxs(s.AccordionItem,{value:"configuration",className:"border-b-0",children:[e.jsx(s.AccordionTrigger,{className:"flex w-full items-center gap-2 py-2 text-sm font-medium hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Settings2,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:"CONFIGURATION"})]})}),e.jsx(s.AccordionContent,{className:"rounded-md border border-border bg-muted/50 px-3 py-0",children:e.jsxs(s.Accordion,{type:"single",collapsible:!0,className:"w-full",children:[e.jsx(mt,{}),e.jsx(ut,{}),e.jsx(s.ColorConfigSection,{}),e.jsx(s.AxisConfigSection,{}),e.jsx(s.LegendConfigSection,{}),e.jsx(s.DataLabelsConfigSection,{})]})})]})]})}function ht({onEditJoins:t}){const n=s.useEditorStore(i=>i.card),{autoJoinMetadata:a}=s.useDashboardCardQuery(n);if(!(a!=null&&a.autoResolved))return null;const{resolvedJoinPlan:r}=a,m=(r==null?void 0:r.joins)||[];if(m.length===0)return null;const c=i=>!i||i.length===0?"No conditions":i.map(u=>{var f,w,N,b;const h=`${(f=u.source)==null?void 0:f.entityName}.${(w=u.source)==null?void 0:w.name}`,g=`${(N=u.target)==null?void 0:N.entityName}.${(b=u.target)==null?void 0:b.name}`,j=u.operator||"=";return`${h} ${j} ${g}`}).join(" AND "),d=i=>!i.joinKeyGroups||i.joinKeyGroups.length===0?"No conditions defined":i.joinKeyGroups.length===1?c(i.joinKeyGroups[0].keys):i.joinKeyGroups.map((u,h)=>({id:h,operator:u.operator,condition:c(u.keys)}));return e.jsx(s.Card,{className:"border-blue-500/30 bg-blue-50/30 dark:bg-blue-950/20",children:e.jsxs("div",{className:"flex items-center justify-between p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ks,{className:"size-4 text-blue-600 dark:text-blue-400"}),e.jsx("h3",{className:"text-sm font-medium text-blue-900 dark:text-blue-100",children:"Auto-Resolved Joins"}),e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Badge,{variant:"secondary",className:"cursor-help bg-blue-100 text-xs text-blue-700 dark:bg-blue-900 dark:text-blue-300",children:m.length})}),e.jsx(s.TooltipContent,{side:"bottom",align:"start",className:"max-w-md p-3",children:e.jsx("div",{className:"space-y-2",children:m.map((i,u)=>{const h=d(i),g=Array.isArray(h);return e.jsxs("div",{className:"rounded-md border border-border bg-background p-2",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium text-foreground",children:i.source.name}),e.jsx(s.ArrowRight,{className:"size-3 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-foreground",children:i.target.name})]}),e.jsx(s.Badge,{variant:"outline",className:"border-green-500/40 bg-green-50/30 text-xs text-green-700 dark:bg-green-950/30 dark:text-green-300",children:i.joinType})]}),e.jsx("div",{className:"mt-1 space-y-1",children:g?h.map(j=>e.jsxs("div",{className:"rounded bg-muted/30 px-2 py-1",children:[e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:j.condition}),j.operator&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",j.operator,")"]})]},j.id)):e.jsx("div",{className:"rounded bg-muted/30 px-2 py-1",children:e.jsx("code",{className:"block break-all text-xs text-muted-foreground",children:h})})})]},i.id||u)})})})]})})]}),t&&e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:t,className:"h-7 gap-1 p-2 text-xs text-blue-700 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-100",children:e.jsx(s.SquarePen,{className:"size-3.5"})})]})})}const _e={getItem(t){if(typeof window>"u")return null;try{return localStorage.getItem(t)}catch(n){return console.warn(`Failed to read from localStorage (${t}):`,n),null}},setItem(t,n){if(!(typeof window>"u"))try{localStorage.setItem(t,n)}catch(a){console.warn(`Failed to write to localStorage (${t}):`,a)}}};function pt({selectedChart:t,onChartChange:n,groupByFields:a,pivotByFields:r,metricsFields:m,sortByFields:c,activeField:d}){var l,o;const[i,u]=T.useState(()=>_e.getItem("chart-selector-expanded")==="true"),[h,g]=T.useState(!1),j=s.useEditorStore(p=>p.card),f=s.useEditorStore(p=>p.actions.updateCardConfig),w=a.length>0||r.length>0||m.length>0,{data:N,autoJoinMetadata:b}=s.useDashboardCardQuery(j),y=((l=j==null?void 0:j.config)==null?void 0:l.joinPlan)||(b!=null&&b.autoResolved?b.resolvedJoinPlan:{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]}),F=((o=j==null?void 0:j.dataSource)==null?void 0:o.selectedEntities)||[],k=p=>{f(j.id,{...j==null?void 0:j.config,joinPlan:p}),g(!1)},z=()=>{f(j.id,{...j==null?void 0:j.config,joinPlan:void 0}),g(!1)},B=()=>{g(!1)},C=()=>{g(!0)};T.useEffect(()=>{_e.setItem("chart-selector-expanded",String(i))},[i]);const v=()=>{u(p=>!p)};return e.jsxs("div",{"data-content":"Chart Configuration Panel",className:"flex w-[350px] flex-col border-x border-border",children:[e.jsxs("div",{className:s.cn("px-6 pt-4",{"space-y-4":i}),children:[e.jsx("div",{className:s.cn("overflow-hidden transition-all duration-300 ease-in-out",i?"max-h-[200px] opacity-100":"max-h-0 opacity-0"),children:i&&e.jsx(Xs,{selectedChart:t,onChartChange:n})}),e.jsxs("div",{"data-content":"Chart Quick Selector",className:"flex items-center justify-center gap-1",children:[e.jsx(st,{selectedChart:t,onChartChange:n}),e.jsxs(s.Tooltip,{children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx(s.Button,{variant:"ghost",size:"sm",onClick:v,className:"h-8 w-8 p-0","aria-label":i?"Hide all charts":"Show all charts",children:i?e.jsx(s.ChevronUp,{className:"h-4 w-4"}):e.jsx(s.ChevronDown,{className:"h-4 w-4"})})}),e.jsx(s.TooltipContent,{side:"bottom",children:e.jsx("p",{children:i?"Hide dropdown":"Show all charts"})})]})]})]}),e.jsx("div",{className:s.cn("flex justify-end gap-2 px-6 py-6"),children:e.jsx("div",{className:s.cn("invisible flex gap-2",{visible:w||N}),children:e.jsx(ee.EditorClearButton,{})})}),e.jsxs(s.ScrollArea,{className:"w-full flex-1 basis-0 px-6 pb-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx(ht,{onEditJoins:C}),e.jsx(xt,{groupByFields:a,pivotByFields:r,metricsFields:m,sortByFields:c,activeField:d})]}),e.jsx(s.ScrollBar,{orientation:"horizontal"})]}),e.jsx(Pe,{open:h,onOpenChange:g,joinPlan:y,availableDataSources:F,onSave:k,onCancel:B,onRemove:z,children:e.jsx("div",{})})]})}function ft({initialFilters:t,availableFields:n}={}){const[a,r]=T.useState(t||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});s.useEditorStore(C=>C.card.dataSource);const{columns:m,isLoading:c}=s.useColumns(),i=n||m||[],u={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},h=C=>{const v=l=>{if(l.id===C){const o=i[0]||u,p=s.getDataType(o.dataType)==="date";return{...l,conditions:[...l.conditions,{id:`condition-${Date.now()}`,field:o,operator:p?"between":"=",value:p?[]:""}]}}return{...l,groups:l.groups.map(v)}};r(v(a))},g=C=>{const v=l=>{if(l.id===C){const o=i[0]||u,p=s.getDataType(o.dataType)==="date";return{...l,groups:[...l.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:o,operator:p?"between":"=",value:p?[]:""}],groups:[]}]}}return{...l,groups:l.groups.map(v)}};r(v(a))},j=(C,v)=>{const l=o=>o.id===C?{...o,conditions:o.conditions.filter(p=>p.id!==v)}:{...o,groups:o.groups.map(l)};r(l(a))},f=(C,v)=>{const l=o=>o.id===C?{...o,groups:o.groups.filter(p=>p.id!==v)}:{...o,groups:o.groups.map(l)};r(l(a))},w=(C,v,l,o)=>{if(l==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const p=S=>S.id===C?{...S,conditions:S.conditions.map(x=>x.id===v?{...x,[l]:o}:x)}:{...S,groups:S.groups.map(p)};r(p(a))},N=(C,v,l)=>{const o=p=>p.id===C?{...p,conditions:p.conditions.map(S=>S.id===v?{...S,...l}:S)}:{...p,groups:p.groups.map(o)};r(o(a))},b=(C,v)=>{const l=o=>o.id===C?{...o,logicalOperator:v}:{...o,groups:o.groups.map(l)};r(l(a))},y=(C,v)=>{const l=o=>o.id===C?{...o,negate:v}:{...o,groups:o.groups.map(l)};r(l(a))},F=(C,v,l)=>{const o=p=>p.id===C?{...p,conditions:s.arrayMove(p.conditions,v,l)}:{...p,groups:p.groups.map(o)};r(o(a))},k=(C,v,l)=>{const o=p=>p.id===C?{...p,groups:s.arrayMove(p.groups,v,l)}:{...p,groups:p.groups.map(o)};r(o(a))},z=C=>{if(!C||C.conditions.length===0&&C.groups.length===0)return"-- No filters defined";const v=o=>{let p="";typeof o.field=="object"?p=o.field.entityName?`${o.field.entityName}.${o.field.name}`:o.field.name:p=String(o.field);const S=o.operator;let x=o.value;if(o.field.dataType==="string"&&!["in","not in"].includes(o.operator))typeof x=="string"?x=`'${x}'`:Array.isArray(x)&&(x=`'${x.join(", ")}'`);else if(o.field.dataType==="date"||o.field.dataType==="datetime"||o.field.dataType==="timestamp")if(o.operator==="between"&&Array.isArray(x)&&x.length===2){const E=x[0]?`'${x[0]}'`:"NULL",D=x[1]?`'${x[1]}'`:"NULL";return`${p} BETWEEN ${E} AND ${D}`}else if((o.operator==="in"||o.operator==="not in")&&Array.isArray(x)){const E=x.map(D=>D?`'${D}'`:"NULL").join(", ");return`${p} ${S} (${E})`}else typeof x=="string"||x instanceof Date?x=`'${x}'`:Array.isArray(x)&&x.length>0&&(x=`'${x[0]}'`);else if(["in","not in"].includes(o.operator)){let E=[];Array.isArray(x)?E=x.map(D=>typeof D=="string"?`'${D}'`:String(D)):typeof x=="string"?E=x.split(",").map(D=>{const M=D.trim();return o.field.dataType==="string"?`'${M}'`:M}):typeof x=="number"&&(E=[String(x)]),x=`(${E.join(", ")})`}switch(S){case"contains":return typeof x=="string"?`${p} LIKE '%${x.replace(/'/g,"")}'`:`${p} LIKE '%${String(x)}'`;case"startsWith":return typeof x=="string"?`${p} LIKE '${x.replace(/'/g,"")}%'`:`${p} LIKE '${String(x)}%'`;case"endsWith":return typeof x=="string"?`${p} LIKE '%${x.replace(/'/g,"")}'`:`${p} LIKE '%${String(x)}'`;case"isNull":return`${p} IS NULL`;case"isNotNull":return`${p} IS NOT NULL`;default:return`${p} ${S} ${x}`}},l=o=>{const p=o.conditions.map(v),S=o.groups.map(M=>l(M)),x=[...p,...S].filter(Boolean);if(x.length===0)return"";const E=x.join(` ${o.logicalOperator} `),D=x.length>1?`(${E})`:E;return o.negate?`NOT ${D}`:D};return l(C)},B=a.conditions.length>0||a.groups.length>0;return{currentFilters:a,setCurrentFilters:r,availableFields:i,isLoading:c,addCondition:h,addGroup:g,removeCondition:j,removeGroup:f,updateCondition:w,updateConditionFields:N,updateGroupOperator:b,updateGroupNegate:y,reorderConditions:F,reorderGroups:k,generateSQLPreview:z,hasAnyFilters:B}}function gt({children:t,className:n,delayDuration:a}){return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:a,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:s.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",n),children:t})}),e.jsx(s.PortalTooltipContent,{children:t})]})})}const jt=t=>{switch(t){case"table":return e.jsx(s.Table,{className:"h-3 w-3"});case"view":return e.jsx(s.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(s.ChartColumn,{className:"h-3 w-3"});case"file":return e.jsx(s.File,{className:"h-3 w-3"});default:return e.jsx(s.Table,{className:"h-3 w-3"})}},vt=t=>{if(t.qualifiedEntityName){const n=t.qualifiedEntityName.split(".");return n.length>1?n[0]:"default"}return"default"};function bt({value:t,onValueChange:n,availableFields:a,placeholder:r="Select field",className:m="w-64"}){const[c,d]=T.useState(!1),i=T.useMemo(()=>{const u={};return a.forEach(h=>{const g=vt(h);u[g]||(u[g]={}),u[g][h.entityId]||(u[g][h.entityId]=[]),u[g][h.entityId].push(h)}),u},[a]);return e.jsxs(s.Popover,{modal:!0,open:c,onOpenChange:d,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":c,className:s.cn("justify-between",!t&&"text-muted-foreground",m),children:[t?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(gt,{children:[t.entityName,".",t.name]})}):r,e.jsx(fs,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(s.CommandEmpty,{children:"No fields found."}),e.jsx(s.CommandList,{className:"max-h-80",children:Object.entries(i).map(([u,h])=>e.jsx(s.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(s.Database,{className:"h-3 w-3"}),u]}),children:Object.entries(h).map(([g,j])=>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:[jt(j[0].entityType),e.jsx("span",{children:j[0].entityName})]}),j.map((f,w)=>e.jsxs(s.CommandItem,{value:f.id,onSelect:()=>{n(f),d(!1)},className:"overflow-x-auto",children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",(t==null?void 0:t.id)===f.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"",children:f.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:f.description&&e.jsx("span",{children:f.description})})]})]},f.id+w))]},`${u}-${g}`))},u))})]})})]})}function Fe(t){var b;const n=s.useEditorStore(y=>y.card),{authToken:a,tokenProps:r}=s.useSemaphorContext(),m=s.useEditorStore(y=>y.card.config),c=m==null?void 0:m.joinPlan,d={...t,alias:t.name,label:"value",role:"groupby"},i={...t,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},u={...d,role:"sortby",direction:"asc"},h={joinPlan:c,groupByColumns:[d],metricColumns:[i],sortByColumns:[u]},g=((b=n.dataSource)==null?void 0:b.connectionId)||n.connectionId,{data:j,isPending:f,error:w}=s.useQuery({queryKey:["filterValues",t.entityId,t.name,t.qualifiedEntityName],queryFn:async()=>{try{return await s.postRequestRegular(`${r.apiServiceUrl}/v1/query`,(a==null?void 0:a.accessToken)||"",{connection_id:g,cardConfig:h,cardDataSource:n.dataSource})}catch(y){console.log(t),console.error("error",y)}},enabled:!!g,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((j==null?void 0:j.records)||[]).map(y=>({label:y.value||"BLANK",value:y.value||"BLANK",count:(y==null?void 0:y.count)||0})),isPending:f,error:w}}function yt({field:t,selected:n,onChange:a,placeholder:r="Select items...",className:m}){const[c,d]=hs.useState(!1),{filterValues:i}=Fe(t),u=g=>{a(n.filter(j=>j!==g))},h=g=>{n.includes(g)?a(n.filter(j=>j!==g)):a([...n,g])};return e.jsx("div",{className:s.cn("w-full",m),children:e.jsxs(s.Popover,{open:c,onOpenChange:d,modal:!0,children:[e.jsx(s.PopoverTrigger,{asChild:!0,children:e.jsxs(s.Button,{variant:"outline",role:"combobox","aria-expanded":c,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:n.length>0?n.map(g=>{const j=i.find(f=>f.value===g);return e.jsxs(s.Badge,{variant:"secondary",className:"text-xs",children:[j==null?void 0:j.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:f=>{f.key==="Enter"&&u(g)},onMouseDown:f=>{f.preventDefault(),f.stopPropagation()},onClick:f=>{f.stopPropagation(),u(g)},children:e.jsx(s.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},g)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(s.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(s.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(s.Command,{children:[e.jsx(s.CommandInput,{placeholder:"Search..."}),e.jsxs(s.CommandList,{children:[e.jsx(s.CommandEmpty,{children:"No results found."}),e.jsx(s.CommandGroup,{children:i.map((g,j)=>e.jsxs(s.CommandItem,{onSelect:()=>h(g.value),children:[e.jsx(s.Check,{className:s.cn("mr-2 h-4 w-4",n.includes(g.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:g.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:g.count})]})]},g.value+j))})]})]})})]})})}function Nt({field:t,value:n,onChange:a,placeholder:r="Select value...",className:m}){const{filterValues:c,isPending:d,error:i}=Fe(t);return d?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):i?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(s.Select,{value:n,onValueChange:a,children:[e.jsx(s.SelectTrigger,{className:m||"flex-1",children:e.jsx(s.SelectValue,{placeholder:r,children:n})}),e.jsx(s.SelectContent,{children:c.map((u,h)=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:u.value,children:u.label},u.value+h))})]})}function Ct({value:t,operator:n,onChange:a,className:r}){var u;const{tokenProps:m}=s.useSemaphorContext(),c=(u=m==null?void 0:m.params)==null?void 0:u.timeZone,d=T.useMemo(()=>{if(t){if(n==="between"||n==="not between"){if(Array.isArray(t)&&t.length===2){const h=t[0]?new Date(t[0]):void 0,g=t[1]?new Date(t[1]):void 0;if(h&&g)return{from:h,to:g}}}else if(n==="="||n==="!="){if(!Array.isArray(t)&&t){const h=new Date(t);if(!isNaN(h.getTime()))return{from:h,to:h}}}else if(n===">"||n===">="){if(!Array.isArray(t)&&t){const h=new Date(t);if(!isNaN(h.getTime()))return{from:h,to:void 0}}}else if(n==="<"||n==="<="){if(!Array.isArray(t)&&t){const h=new Date(t);if(!isNaN(h.getTime()))return{from:void 0,to:h}}}else if((n==="in"||n==="not in")&&Array.isArray(t)&&t.length>0){const h=new Date(t[0]),g=t.length>1?new Date(t[t.length-1]):h;if(!isNaN(h.getTime()))return{from:h,to:g}}}},[t,n]),i=h=>{if(!h){a(void 0);return}if(h.from&&h.to)a([h.from.toISOString(),h.to.toISOString()]);else if(h.from){const g=new Date(h.from);g.setHours(23,59,59,999),a([h.from.toISOString(),g.toISOString()])}else if(h.to){const g=new Date(h.to);g.setHours(0,0,0,0),a([g.toISOString(),h.to.toISOString()])}};return e.jsx(s.DateRangePicker,{value:d,onChange:i,timezone:c,showRelativeTab:!0,className:r,placeholder:"Select date..."})}const St=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],wt=["=","!=","contains","startsWith","endsWith","in","not in","isNull","isNotNull"],kt=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],Tt=["=","!=","isNull","isNotNull"],Et=["between","isNull","isNotNull"],Dt={"=":"Equals","!=":"Not Equals",">":"Greater Than",">=":"Greater Than or Equal","<":"Less Than","<=":"Less Than or Equal",contains:"Contains",startsWith:"Starts With",endsWith:"Ends With",in:"In","not in":"Not In",between:"Between",isNull:"Is Null",isNotNull:"Is Not Null","not between":"Not Between"};function We(t){return Dt[t]||s.titleCase(t)}function It(t){switch(t){case"string":return wt;case"number":return kt;case"boolean":return Tt;case"date":return Et;default:return St}}function as({condition:t,index:n,groupId:a,groupLogicalOperator:r,onUpdateCondition:m,onRemoveCondition:c,onUpdateGroupOperator:d,availableFields:i,updateConditionFields:u}){const{attributes:h,listeners:g,setNodeRef:j,transform:f,transition:w,isDragging:N}=s.useSortable({id:t.id}),{isPending:b,error:y}=Fe(t.field),F={transform:s.CSS.Transform.toString(f),transition:w};return e.jsxs("div",{ref:j,style:F,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${N?"z-50 opacity-50":""}`,children:[e.jsx("div",{...h,...g,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),n>0&&e.jsxs(s.Select,{value:r,onValueChange:k=>d(a,k),children:[e.jsx(s.SelectTrigger,{className:"w-24",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"AND",children:"AND"}),e.jsx(s.SelectItem,{value:"OR",children:"OR"})]})]}),n===0&&e.jsx("div",{className:"w-24"}),e.jsx(bt,{value:t.field,onValueChange:k=>{const z=k,B=s.getDataType(z.dataType)==="date";u(a,t.id,{field:z,value:"",operator:B?"between":"="})},availableFields:i,placeholder:"Select field",className:"w-64"}),e.jsxs(s.Select,{value:t.operator,onValueChange:k=>{k==="in"||k==="not in"?u(a,t.id,{operator:k,value:[]}):k==="isNull"||k==="isNotNull"?u(a,t.id,{operator:k,value:null}):u(a,t.id,{operator:k,value:""})},children:[e.jsx(s.SelectTrigger,{className:"w-32",children:e.jsx(s.SelectValue,{children:t.operator?We(t.operator):""})}),e.jsx(s.SelectContent,{children:It(s.getDataType(t.field.dataType)).map(k=>e.jsx(s.SelectItem,{className:"hover:bg-muted",value:k,children:We(k)},k))})]}),t.operator==="isNull"||t.operator==="isNotNull"?e.jsx("div",{className:"flex-1"}):s.getDataType(t.field.dataType)==="string"?t.operator==="in"||t.operator==="not in"?b?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(s.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):y?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(yt,{field:t.field,selected:Array.isArray(t.value)&&t.value.every(k=>typeof k=="string")?t.value:[],onChange:k=>u(a,t.id,{value:k}),placeholder:`Select values for ${t.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(t.operator)?e.jsx(s.Input$1,{value:typeof t.value=="string"?t.value:"",onChange:k=>u(a,t.id,{value:k.target.value}),className:"flex-1",placeholder:t.operator.charAt(0).toUpperCase()+t.operator.slice(1)+"..."}):e.jsx(Nt,{field:t.field,value:typeof t.value=="string"?t.value:"",onChange:k=>u(a,t.id,{value:k}),placeholder:"Select value...",className:"flex-1"}):s.getDataType(t.field.dataType)==="boolean"?e.jsxs(s.Select,{value:typeof t.value=="boolean"?String(t.value):"",onValueChange:k=>u(a,t.id,{value:k==="true"}),children:[e.jsx(s.SelectTrigger,{className:"flex-1",children:e.jsx(s.SelectValue,{placeholder:"Select value..."})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{value:"true",children:"True"}),e.jsx(s.SelectItem,{value:"false",children:"False"})]})]}):s.getDataType(t.field.dataType)==="date"?e.jsx(Ct,{value:t.value,operator:t.operator,onChange:k=>u(a,t.id,{value:k}),className:"flex-1"}):e.jsx(s.Input$1,{value:typeof t.value=="string"||typeof t.value=="number"?t.value:"",onChange:k=>m(a,t.id,"value",k.target.value),className:"flex-1",placeholder:t.operator==="in"||t.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>c(a,t.id),children:e.jsx(s.X,{className:"h-3 w-3"})})]})}function At({group:t,depth:n,parentGroupId:a,onUpdateGroupOperator:r,onUpdateGroupNegate:m,onRemoveGroup:c,onUpdateCondition:d,onUpdateField:i,onRemoveCondition:u,onReorderConditions:h,onReorderGroups:g,onAddCondition:j,onAddGroup:f,availableFields:w,renderFilterGroup:N,updateConditionFields:b}){const{attributes:y,listeners:F,setNodeRef:k,transform:z,transition:B,isDragging:C}=s.useSortable({id:t.id}),v={transform:s.CSS.Transform.toString(z),transition:B},l=p=>{const{active:S,over:x}=p;if(x&&S.id!==x.id){const E=t.conditions.findIndex(M=>M.id===S.id),D=t.conditions.findIndex(M=>M.id===x.id);E!==-1&&D!==-1&&h(t.id,E,D)}},o=p=>{const{active:S,over:x}=p;if(x&&S.id!==x.id&&a){const E=t.groups.findIndex(M=>M.id===S.id),D=t.groups.findIndex(M=>M.id===x.id);E!==-1&&D!==-1&&g(a,E,D)}};return e.jsxs("div",{ref:k,style:v,className:`rounded-lg ${n>0?"mt-2 border border-border":""} ${C?"z-50 opacity-50":""}`,children:[n>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",{...y,...F,className:"cursor-grab active:cursor-grabbing",children:e.jsx(s.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(s.Button,{variant:t.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>m(t.id,!t.negate),children:"NOT"}),e.jsxs(s.Select,{value:t.logicalOperator,onValueChange:p=>r(t.id,p),children:[e.jsx(s.SelectTrigger,{className:"h-7 w-20",children:e.jsx(s.SelectValue,{})}),e.jsxs(s.SelectContent,{children:[e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(s.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(s.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>a&&c(a,t.id),children:e.jsx(s.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${n>0?"":"px-0"}`,children:[e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:l,children:e.jsx(s.SortableContext,{items:t.conditions.map(p=>p.id),strategy:s.verticalListSortingStrategy,children:t.conditions.map((p,S)=>e.jsx(as,{condition:p,index:S,groupId:t.id,groupLogicalOperator:t.logicalOperator,onUpdateCondition:d,onUpdateField:i,onRemoveCondition:u,onUpdateGroupOperator:r,availableFields:w,updateConditionFields:b},p.id))})}),e.jsx(s.DndContext,{sensors:s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),collisionDetection:s.closestCenter,onDragEnd:o,children:e.jsx(s.SortableContext,{items:t.groups.map(p=>p.id),strategy:s.verticalListSortingStrategy,children:t.groups.map(p=>N(p,n+1,t.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>j(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>f(t.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Pt({filters:t,availableFields:n,onSave:a,onClearAll:r,onCancel:m}){const{currentFilters:c,availableFields:d,isLoading:i,addCondition:u,addGroup:h,removeCondition:g,removeGroup:j,updateCondition:f,updateConditionFields:w,updateGroupOperator:N,updateGroupNegate:b,reorderConditions:y,reorderGroups:F,generateSQLPreview:k,hasAnyFilters:z,setCurrentFilters:B}=ft({initialFilters:t,availableFields:n}),C=s.useSensors(s.useSensor(s.PointerSensor),s.useSensor(s.KeyboardSensor,{coordinateGetter:s.sortableKeyboardCoordinates})),[v,l]=T.useState(!1),o=(x,E,D)=>{const M=P=>P.id===x?{...P,conditions:P.conditions.map(I=>I.id===E?{...I,field:D,dataType:D.dataType}:I)}:{...P,groups:P.groups.map(M)};B(M(c))},p=(x,E=0,D)=>E===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(s.DndContext,{sensors:C,collisionDetection:s.closestCenter,onDragEnd:M=>{const{active:P,over:I}=M;if(I&&P.id!==I.id){const R=x.conditions.findIndex(V=>V.id===P.id),G=x.conditions.findIndex(V=>V.id===I.id);R!==-1&&G!==-1&&y(x.id,R,G)}},children:e.jsx(s.SortableContext,{items:x.conditions.map(M=>M.id),strategy:s.verticalListSortingStrategy,children:x.conditions.map((M,P)=>e.jsx(as,{condition:M,index:P,groupId:x.id,groupLogicalOperator:x.logicalOperator,onUpdateCondition:f,onUpdateField:o,onRemoveCondition:g,onUpdateGroupOperator:N,availableFields:d,updateConditionFields:w},M.id))})}),e.jsx(s.DndContext,{sensors:C,collisionDetection:s.closestCenter,onDragEnd:M=>{const{active:P,over:I}=M;if(I&&P.id!==I.id){const R=x.groups.findIndex(V=>V.id===P.id),G=x.groups.findIndex(V=>V.id===I.id);R!==-1&&G!==-1&&F(x.id,R,G)}},children:e.jsx(s.SortableContext,{items:x.groups.map(M=>M.id),strategy:s.verticalListSortingStrategy,children:x.groups.map(M=>p(M,E+1,x.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(s.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>u(x.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),v&&e.jsxs(s.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>h(x.id),children:[e.jsx(s.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},x.id):e.jsx(At,{group:x,depth:E,parentGroupId:D,onUpdateGroupOperator:N,onUpdateGroupNegate:b,onRemoveGroup:j,onUpdateCondition:f,onUpdateField:o,onRemoveCondition:g,onReorderConditions:y,onReorderGroups:F,onAddCondition:u,onAddGroup:h,availableFields:d,renderFilterGroup:p,updateConditionFields:w},x.id),S=s.getFilterCount(t);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(s.Card,{children:e.jsx(s.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[i?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..."})]}):p(c),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(s.SmallSwitch,{id:"advanced-mode",checked:v,onCheckedChange:x=>l(x)}),e.jsx(s.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)"})]})}),z&&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:k(c)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(s.Button,{size:"sm",variant:"outline",onClick:m,children:"Cancel"}),S>0&&e.jsx(s.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(s.Button,{size:"sm",onClick:()=>a(z?c:null),children:"Apply Filters"})]})]})}function Lt({cardId:t,filters:n,onFiltersChange:a,onClearFilters:r,availableFields:m,isOpen:c,onOpenChange:d}){const i=h=>{a(t,h),d(!1)},u=()=>{r(t),d(!1)};return e.jsxs(s.Dialog,{modal:!1,open:c,onOpenChange:d,children:[c&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(s.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:h=>{h.preventDefault()},children:[e.jsxs(s.DialogHeader,{children:[e.jsx(s.DialogTitle,{children:"Card Filters"}),e.jsx(s.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Pt,{filters:n,availableFields:m,onSave:i,onCancel:()=>d(!1),onClearAll:u})]})]})}function Bt({activeCardId:t,sourceFields:n,getFieldsForContainer:a,setFieldsForContainer:r}){var y,F;const[m,c]=T.useState(null),d=s.useEditorStore(k=>k.card),i=s.useEditorStore(k=>k.actions.updateCardConfig),u=(y=d==null?void 0:d.config)==null?void 0:y.joinPlan,h=(F=d==null?void 0:d.dataSource)==null?void 0:F.semanticDomainId,{data:g}=ee.useJoinabilityMap(h),j=[...n,...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")],f=T.useCallback(k=>k.startsWith("card-")?null:k.startsWith("source-")||n.find(z=>z.id===k)?"source":a("groupBy").find(z=>z.id===k)?"groupBy":a("metrics").find(z=>z.id===k)?"metrics":a("pivotBy").find(z=>z.id===k)?"pivotBy":a("sortBy").find(z=>z.id===k)?"sortBy":null,[n,a]),w=T.useCallback(k=>{c(k.active.id)},[]),N=T.useCallback(k=>{var p;const{active:z,over:B}=k;if(!B||!t){c(null);return}const C=z.id,v=B.id,l=f(C),o=f(v)||v;if(o==="sortBy"){if(l==="source"){const S=n.find(E=>E.id===C);if(!S){c(null);return}if(!(a("groupBy").some(E=>E.name===S.name&&E.qualifiedEntityName===S.qualifiedEntityName)||a("metrics").some(E=>E.name===S.name&&E.qualifiedEntityName===S.qualifiedEntityName))){c(null);return}}else if(l==="pivotBy"){c(null);return}else if(l!=="groupBy"&&l!=="metrics"&&l!=="sortBy"){c(null);return}}if(l==="source"&&o==="sortBy"){const S=[...n].find(M=>M.id===C);if(!S){c(null);return}const x=a("sortBy");if(s.fieldAlreadyExists(S,x)){c(null);return}const E=ee.validateFieldForChartType(S,"sortBy",d.type);if(!E.isValid){s.ue.error("Invalid Field Type",{description:E.reason,position:"top-center",duration:3e3}),c(null);return}const D=s.getNewField(S,"sortBy",x);c(null),r("sortBy",[...x,D]);return}if(l==="source"&&o!=="source"&&o!=="sortBy"){const S=[...n].find(I=>I.id===C);if(!S){c(null);return}const x=[...a("groupBy"),...a("pivotBy"),...a("metrics"),...a("sortBy")];if(x.length>0){const I=x[0].qualifiedEntityName;if(!I){c(null);return}if(I!==S.qualifiedEntityName&&S.qualifiedEntityName)if(h&&(g!=null&&g.joinabilityMap)){if(s.calculateFieldState(S,{joinabilityMap:g.joinabilityMap,selectedFields:x,baseEntityName:(p=u==null?void 0:u.baseEntity)==null?void 0:p.name}).state==="unreachable"){s.showJoinRequiredNotification(),c(null);return}}else{if(!u){s.showJoinRequiredNotification(),c(null);return}if(!s.areEntitiesJoined(I,S.qualifiedEntityName,u)){s.showJoinRequiredNotification(),c(null);return}}}const E=a(o);if(s.fieldAlreadyExists(S,E)){c(null);return}const D=ee.validateFieldForChartType(S,o,d.type);if(!D.isValid){s.ue.error("Invalid Field Type",{description:D.reason,position:"top-center",duration:3e3}),c(null);return}const M=s.getNewField(S,o,E),P=[...E,M];c(null),r(o,P),o==="metrics"&&t&&ee.cleanupKpiMetricComparisonMode(d.type,d.config,i,t,P);return}if(l&&o&&l!=="source"&&o!=="source"&&l!==o){const S=a(l),x=a(o),E=S.find(R=>R.id===C);if(!E){c(null);return}const D=ee.validateFieldForChartType(E,o,d.type);if(!D.isValid){s.ue.error("Invalid Field Type",{description:D.reason,position:"top-center",duration:3e3}),c(null);return}const M=s.getNewField(E,o,x);if(c(null),o==="sortBy"){s.fieldAlreadyExists(E,x)||r(o,[...x,M]);return}const P=S.filter(R=>R.id!==C),I=[...x,M];r(l,P),r(o,I),o==="metrics"&&t&&ee.cleanupKpiMetricComparisonMode(d.type,d.config,i,t,I);return}if(l&&o&&l===o&&l!=="source"){const S=a(l),x=S.findIndex(D=>D.id===C),E=S.findIndex(D=>D.id===v);if(x!==E){const D=s.arrayMove(S,x,E);r(l,D)}}c(null)},[t,n,a,r,f,u,h,g,d.type,i,d.config]),b=m?j.find(k=>k.id===m):null;return{activeId:m,activeField:b,handleDragStart:w,handleDragEnd:N}}function Ft({activeView:t,onViewChange:n}){const a=s.useEditorStore(d=>d.card),{config:r}=T.useContext(s.SemaphorContext).tokenProps,m=(r==null?void 0:r.showInfoTab)!==!1,{errorMessage:c}=s.useDashboardCardQuery(a);return e.jsx(s.Tabs,{value:t,onValueChange:d=>n(d),children:e.jsxs(s.TabsList,{className:"h-9 w-fit gap-1 bg-background p-0",children:[e.jsx(s.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(s.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),a.type!=="kpi"&&m&&e.jsx(s.TabsTrigger,{value:"info",className:s.cn("rounded-md transition data-[state=active]:bg-muted",c&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:c?"Error":"Info"})]})})}const Mt=[{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 Ot(){var u,h;const t=s.useEditorStore(g=>g.card),{updateRowLimit:n}=s.useEditorActions(),[a,r]=T.useState(!1),[m,c]=T.useState(""),d=g=>{if(g==="custom"){r(!0);return}r(!1),n(t.id,parseInt(g))},i=g=>{const j=g.target.value;c(j),j&&!isNaN(parseInt(j))&&n(t.id,parseInt(j))};return e.jsx("div",{className:"flex items-center gap-2",children:a?e.jsx(s.Input,{type:"number",value:m,onChange:i,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(s.Select,{value:((h=(u=t.config)==null?void 0:u.rowLimit)==null?void 0:h.toString())||"100",onValueChange:d,children:[e.jsx(s.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(s.SelectValue,{placeholder:"Select limit"})}),e.jsx(s.SelectContent,{children:Mt.map(g=>e.jsx(s.SelectItem,{value:g.value,children:g.label},g.value))})]})})}function zt({isOpen:t,onClose:n}){const a=ee.useClickOutside(n,{enabled:t}),r=s.useEditorStore(g=>{var j;return((j=g.card.customCardPreferences)==null?void 0:j.url)||""}),m=s.useEditorStore(g=>g.card),c=s.useEditorStore(g=>{var j;return((j=g.card.customCardPreferences)==null?void 0:j.pluginChartType)||""}),d=s.useEditorStore(g=>{var j;return((j=g.card.customCardPreferences)==null?void 0:j.settings)||{}}),{data:i}=s.useDashboardCardQuery(m),{getCard:u}=s.useCustomVisual(r),h=T.useMemo(()=>!r||r.trim()===""?null:u("Chart Settings"),[u,r]);return e.jsx("div",{ref:a,className:s.cn("absolute right-0 top-0 z-40 h-full w-[350px] border-l bg-background shadow-lg transition-transform duration-300",t?"translate-x-0":"translate-x-full"),style:{willChange:"transform"},tabIndex:t?0:-1,"aria-hidden":!t,children:e.jsxs("div",{className:"flex h-full flex-col p-4 px-5 pr-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Chart Settings"}),e.jsx(s.IconButton,{"aria-label":"Hide Chart Settings",tooltip:"Hide",onClick:n,className:"h-7 p-2 text-muted-foreground hover:text-foreground",children:e.jsx(s.X,{className:"size-3.5"})})]}),e.jsx("div",{className:"h-full min-h-0 flex-1",children:h&&e.jsx(T.Suspense,{fallback:e.jsx("div",{children:"Loading chart settings..."}),children:e.jsx(h,{chartData:(i==null?void 0:i.records)||[],chartType:c,settings:d})})})]})})}function Rt({activeView:t,onViewChange:n,showDebug:a,onDebugToggle:r,onFiltersClick:m,activeCard:c,columns:d,columnsLoading:i,columnsError:u}){var ne,ie,le;const h=s.useEditorStore(K=>K.card),g=s.useDashboardStore(K=>K.filterValues),{updateCardConfig:j,setCard:f,updateCardInFrame:w,setShowAIDialog:N}=s.useEditorActions(),b=s.useEditorStore(K=>K.showAIDialog),y=s.useDashboardStore(K=>K.isVisualEditing),[F,k]=T.useState(!1),[z,B]=T.useState(!1),[C,v]=T.useState(null),{config:l}=T.useContext(s.SemaphorContext).tokenProps,o=(l==null?void 0:l.showInfoTab)!==!1,p=s.useEditorStore(K=>{var Q;return((Q=K.card.customCardPreferences)==null?void 0:Q.url)&&K.card.type==="custom"}),{data:S,errorMessage:x,isLoading:E,isFetching:D,errorSql:M,pagination:P,refetch:I,comparisonMetadata:R}=s.useDashboardCardQuery(c),[G,V]=T.useState(!1);T.useEffect(()=>{D||V(!1)},[D]);const _=(K,Q)=>{const Z={...c,paginationConfig:{page:K+1,pageSize:Q}};f(Z),w(Z)};function q(){return e.jsxs("div",{className:"relative border-b border-border bg-background p-4",children:[e.jsx("button",{onClick:r,className:"absolute right-4 top-4 rounded-md p-1 hover:bg-muted","aria-label":"Close Debug Panel",children:e.jsx(s.X,{className:"h-4 w-4"})}),e.jsxs("div",{className:"space-y-4 pr-8",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(h.config||{},null,2)})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Dashboard Filters"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(g||{},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(c.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:i?"Loading...":u?"Error loading columns":JSON.stringify(d.slice(0,5),null,2)})]})]})]})}const O=K=>{if(!h.config)return;if(!K.length){j(h.id,{...h.config,sortByColumns:[]});return}const Q=h.config,Z=K.map(({id:oe,desc:me})=>{var A,J;const xe=(A=Q.metricColumns)==null?void 0:A.find(te=>te.label===oe),he=(J=Q.groupByColumns)==null?void 0:J.find(te=>te.label===oe),se=xe||he;return se?{id:s.getFieldId("sortBy",se),name:se.name,dataType:se.dataType,label:se.label,qualifiedEntityName:se.qualifiedEntityName,entityId:se.entityId,entityName:se.entityName,entityType:se.entityType,role:"sortby",direction:me?"desc":"asc"}:null}).filter(oe=>oe!==null);j(h.id,{...Q,sortByColumns:Z})},U=T.useMemo(()=>{var K,Q;return(Q=(K=h.config)==null?void 0:K.sortByColumns)==null?void 0:Q.map(Z=>({id:Z.label,desc:Z.direction==="desc"}))},[(ne=h.config)==null?void 0:ne.sortByColumns]);return e.jsxs("div",{className:s.cn("relative flex w-0 grow flex-col",{"border-l":b&&y}),children:[a&&q(),e.jsxs("div",{className:"group/visualization relative flex h-full max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t==="chart"&&b&&e.jsx(ss,{variant:"outline"}),e.jsx(Ft,{activeView:t,onViewChange:n}),e.jsx(s.FilterInfo,{cardId:c.id,cardFilters:(ie=c.config)==null?void 0:ie.filters,cardFilterCount:s.getFilterCount(((le=c.config)==null?void 0:le.filters)||null),onFiltersClick:m}),R&&e.jsx(s.ComparisonMetadataBadge,{metadata:R,variant:"compact"}),e.jsx("div",{className:"ml-2",children:e.jsx(Ot,{})}),b&&e.jsx(ee.EditorClearButton,{})]}),e.jsxs("div",{className:s.cn("flex grow items-center justify-end gap-2"),children:[e.jsx(s.IconButton,{tooltip:"Refresh",disabled:E||D,onClick:()=>{V(!0),I()},children:e.jsx(s.RefreshCcw,{className:s.cn("h-4 w-4",{"animate-spin":G})})}),t==="chart"&&e.jsx(ts,{}),!b&&e.jsx(s.IconButton,{onClick:()=>N(!b),tooltip:"AI",className:"h-8","aria-label":"AI",children:e.jsx(s.Sparkles,{className:"size-4"})}),r&&s.isDevEnv]})]}),!F&&p&&e.jsx(s.IconButton,{"aria-label":"Open Chart Settings",tooltip:"Open Chart Settings",onClick:()=>k(!0),className:"absolute right-5 top-1/2 z-40 size-10 -translate-y-1/2 rounded-full border border-border bg-background shadow-lg hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:e.jsx(s.Settings2,{className:"size-4"})}),e.jsxs("div",{className:"mt-3 flex min-h-0 grow flex-col",children:[t==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:e.jsx(ns,{})}),t==="table"&&(S==null?void 0:S.records)&&e.jsx("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:e.jsx(s.TableVisual,{card:c,data:(S==null?void 0:S.records)||[],paginationMetadata:P,onPaginationChange:_,isLoading:E||D,onSortChange:O,sortState:U})}),t==="info"&&o&&e.jsx("div",{className:"flex min-h-0 flex-1 flex-col pb-6",children:e.jsx("div",{className:"flex min-h-0 flex-1 flex-col rounded-md bg-background px-6",children:x?e.jsx(s.QueryErrorDisplay,{error:x,errorSql:M,onSendFeedback:()=>{const K=s.prepareFeedbackData(s.FeedbackCategory.QUERY_GENERATION,{cardConfig:h.config,dataSource:c.dataSource,dashboardFilters:g,errorMessage:x,errorSql:M,generatedSql:S==null?void 0:S.sql});v(K),B(!0)},onOpenInEditor:()=>{N(!0),setTimeout(()=>{const K=s.useEditorStore.getState().actions;K.setIsDevMode(!0),K.setCardSql(M||""),setTimeout(()=>{K.setRunSql(!0)},100)},100)}}):e.jsx(Ze,{sql:S==null?void 0:S.sql,error:x,errorSql:M})})})]}),e.jsx(zt,{isOpen:F,onClose:()=>k(!1)}),C&&e.jsx(s.FeedbackDialog,{open:z,onOpenChange:B,feedbackData:C})]})]})}function $t({activeField:t}){const[n,a]=T.useState(!0);return T.useEffect(()=>{t&&a(!0)},[t]),t?e.jsxs("div",{className:`flex max-w-[300px] items-center gap-2 rounded-lg border border-blue-500 bg-background p-2 shadow-lg transition-all duration-200 ${n?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(s.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(Be,{dataType:t.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:t.label||t.name})]}):null}const Vt=()=>{const t=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||t.apply(console,r)};const n=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},a=r=>{var m;if((m=r.reason)!=null&&m.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",n,!0),window.addEventListener("unhandledrejection",a,!0),()=>{console.error=t,window.removeEventListener("error",n,!0),window.removeEventListener("unhandledrejection",a,!0)}};function qt(){var V,_;const[t,n]=T.useState("chart"),[a,r]=T.useState(!1),[m,c]=T.useState(!1),[d,i]=T.useState(!0),u=s.useEditorStore(q=>q.showAIDialog),h=s.useDashboardStore(q=>q.isVisualEditing),{setCardType:g}=s.useEditorActions(),j=s.useEditorStore(q=>q.card.type);T.useEffect(()=>Vt(),[]);const f=q=>{g(q)},w=s.useEditorStore(q=>q.frame),N=s.useEditorStore(q=>q.card);s.useEditorStore(q=>q.activeTabCardId),s.useEditorStore(q=>q.actions.getAvailableFields);const{addCard:b,removeCard:y,updateCard:F,setActiveCard:k,updateFilters:z}=s.useEditorActions(),{columns:B=[],isLoading:C,error:v}=s.useColumns(),l=s.useSensors(s.useSensor(s.PointerSensor,{activationConstraint:{distance:8}})),o=N,{getFieldsForContainer:p,setFieldsForContainer:S}=ee.useFieldManagement(o),{activeField:x,handleDragStart:E,handleDragEnd:D}=Bt({activeCardId:w.activeCardId,sourceFields:B,getFieldsForContainer:p,setFieldsForContainer:S}),M=(q,O)=>{O&&z(q,O)},P=q=>{var O;F(q,{config:{...(O=w.cards.find(U=>U.id===q))==null?void 0:O.config,filters:void 0}})},I=B,R=q=>{if(!q)return 0;let O=q.conditions.length;return q.groups.forEach(U=>{O+=R(U)}),O},G=R(((V=o==null?void 0:o.config)==null?void 0:V.filters)||null);return e.jsxs(s.DndContext,{sensors:l,collisionDetection:s.closestCenter,onDragStart:E,onDragEnd:D,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(Xe,{isVisible:d,onToggleVisibility:()=>i(!d)}),e.jsxs("div",{className:"flex flex-1 transition-all duration-300 ease-in-out",children:[!u&&e.jsx(pt,{selectedChart:j,onChartChange:f,groupByFields:p("groupBy"),pivotByFields:p("pivotBy"),metricsFields:p("metrics"),sortByFields:p("sortBy"),activeField:x}),e.jsx(Rt,{selectedChart:j,activeView:t,onViewChange:n,showDebug:a,onDebugToggle:()=>r(!a),onFiltersClick:()=>c(!0),filterCount:G,activeCard:o,dataSourceState:N.dataSource||s.EMPTY_DATA_SOURCE,columns:B,columnsLoading:C,columnsError:v,getFieldsForContainer:p,cards:w.cards,activeCardId:w.activeCardId,addCard:b,setActiveCard:k})]}),!d&&h&&e.jsx("div",{className:"fixed left-6 top-[105px] z-50",children:e.jsx(s.Button,{size:"sm",variant:"outline",className:"h-10 w-10 rounded-full border-border bg-background p-0 shadow-lg hover:bg-muted",onClick:()=>i(!0),title:"Show Data Source Panel",children:e.jsx(s.Database,{className:"h-4 w-4"})})})]}),o&&e.jsx(Lt,{cardId:o.id,filters:((_=o.config)==null?void 0:_.filters)||null,onFiltersChange:M,onClearFilters:P,availableFields:I,isOpen:m,onOpenChange:c}),e.jsx(s.DragOverlay,{dropAnimation:null,children:e.jsx($t,{activeField:x||null})})]})}function Gt({authToken:t,onSave:n,onClose:a}){const r=T.useRef(null),m=s.useEditorStore(v=>v.showAIDialog),c=s.useEditorStore(v=>v.isDevMode),d=s.useAssistantLayoutStore(v=>v.setFullscreen),i=s.useAssistantLayoutStore(v=>v.setPanelOpen),u=s.useAssistantLayoutStore(v=>v.setContainer),h=s.useAssistantPanel("editor"),g=s.useFullscreenAssistant(),j=s.useAssistantContainer("editor"),f=g==="editor",w=T.useCallback(v=>{u("editor",v)},[u]),{setAuthToken:N}=s.useDashboardActions(),{setShowAIDialog:b,setOnSave:y,setOnClose:F}=s.useEditorActions(),{setActiveAssistantType:k}=s.useAIActions();T.useEffect(()=>{n&&y(n),a&&F(a)},[n,y,a,F]),T.useEffect(()=>{t&&t.accessToken&&N(t)},[t,N]),T.useEffect(()=>{var v,l;m?((v=r.current)==null||v.resize(40),i("editor",!0),k("editor")):((l=r.current)==null||l.resize(0),i("editor",!1),g==="editor"&&d(null),k(null))},[m,i,k,d,g]);function z(v){v<1?(b(!1),i("editor",!1),g==="editor"&&d(null),k(null)):(m||(b(!0),k("editor")),h.isOpen||i("editor",!0))}function B(){return e.jsxs(e.Fragment,{children:[e.jsx(Xe,{isVisible:!0,onToggleVisibility:()=>{}}),e.jsxs("div",{className:"relative flex grow border-l",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"editor-main",className:s.cn("grow transition-opacity",f&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Us,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:z,defaultSize:h.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Je,{isFullscreen:f,onFullscreenChange:v=>d(v?"editor":null),fullscreenContainer:j})})})]}),e.jsx("div",{ref:w,className:s.cn("absolute inset-0",!f&&"pointer-events-none")})]})]})}function C(){return e.jsxs("div",{className:"relative flex h-full grow",children:[e.jsxs(s.ResizablePanelGroup,{"data-content":"explorer",className:s.cn("flex grow transition-opacity",f&&"pointer-events-none opacity-0"),direction:"horizontal",children:[e.jsx(s.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(qt,{})}),e.jsx(s.ResizableHandle,{}),e.jsx(s.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:z,defaultSize:h.isOpen?40:0,className:"flex",children:e.jsx("div",{className:"grow overflow-y-auto",children:e.jsx(Je,{isFullscreen:f,onFullscreenChange:v=>d(v?"editor":null),fullscreenContainer:j})})})]}),e.jsx("div",{ref:w,className:s.cn("absolute inset-0",!f&&"pointer-events-none")})]})}return e.jsx(s.ErrorBoundary,{FallbackComponent:s.Fallback,children:c?e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:B()}):C()})}exports.default=Gt;
|