react-semaphor 0.0.527 → 0.0.528
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{dashboard-plus-D4i7WErk.js → dashboard-plus-BuUA2b05.js} +55 -60
- package/dist/chunks/{dashboard-plus-DV5VATMC.js → dashboard-plus-BxRMgI4Z.js} +3924 -3824
- package/dist/chunks/{index-DdUA7rY3.js → index-3MZdC5cQ.js} +141 -146
- package/dist/chunks/{index-CxuQLwIa.js → index-DmA6sOL5.js} +16846 -17439
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +2 -2
- package/dist/style.css +1 -1
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +1 -1
- package/package.json +1 -1
|
@@ -1,29 +1,29 @@
|
|
|
1
|
-
"use strict";const e=require("react/jsx-runtime"),t=require("./index-
|
|
1
|
+
"use strict";const e=require("react/jsx-runtime"),t=require("./index-3MZdC5cQ.js"),L=require("react");require("react-dom");function Ss(s){const a=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const n in s)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(s,n);Object.defineProperty(a,n,r.get?r:{enumerable:!0,get:()=>s[n]})}}return a.default=s,Object.freeze(a)}const he=Ss(L);/**
|
|
2
2
|
* @license lucide-react v0.453.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
5
5
|
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
-
*/const
|
|
6
|
+
*/const ws=t.createLucideIcon("AlignCenter",[["path",{d:"M17 12H7",key:"16if0g"}],["path",{d:"M19 18H5",key:"18s9l3"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/**
|
|
7
7
|
* @license lucide-react v0.453.0 - ISC
|
|
8
8
|
*
|
|
9
9
|
* This source code is licensed under the ISC license.
|
|
10
10
|
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
-
*/const
|
|
11
|
+
*/const ks=t.createLucideIcon("AlignLeft",[["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 18H3",key:"1amg6g"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/**
|
|
12
12
|
* @license lucide-react v0.453.0 - ISC
|
|
13
13
|
*
|
|
14
14
|
* This source code is licensed under the ISC license.
|
|
15
15
|
* See the LICENSE file in the root directory of this source tree.
|
|
16
|
-
*/const
|
|
16
|
+
*/const Es=t.createLucideIcon("AlignRight",[["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M21 18H7",key:"1ygte8"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/**
|
|
17
17
|
* @license lucide-react v0.453.0 - ISC
|
|
18
18
|
*
|
|
19
19
|
* This source code is licensed under the ISC license.
|
|
20
20
|
* See the LICENSE file in the root directory of this source tree.
|
|
21
|
-
*/const
|
|
21
|
+
*/const Ds=t.createLucideIcon("ArrowDown10",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M17 10V4h-2",key:"zcsr5x"}],["path",{d:"M15 10h4",key:"id2lce"}],["rect",{x:"15",y:"14",width:"4",height:"6",ry:"2",key:"33xykx"}]]);/**
|
|
22
22
|
* @license lucide-react v0.453.0 - ISC
|
|
23
23
|
*
|
|
24
24
|
* This source code is licensed under the ISC license.
|
|
25
25
|
* See the LICENSE file in the root directory of this source tree.
|
|
26
|
-
*/const
|
|
26
|
+
*/const Ts=t.createLucideIcon("ArrowDownZA",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M15 4h5l-5 6h5",key:"8asdl1"}],["path",{d:"M15 20v-3.5a2.5 2.5 0 0 1 5 0V20",key:"r6l5cz"}],["path",{d:"M20 18h-5",key:"18j1r2"}]]);/**
|
|
27
27
|
* @license lucide-react v0.453.0 - ISC
|
|
28
28
|
*
|
|
29
29
|
* This source code is licensed under the ISC license.
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
*
|
|
34
34
|
* This source code is licensed under the ISC license.
|
|
35
35
|
* See the LICENSE file in the root directory of this source tree.
|
|
36
|
-
*/const
|
|
36
|
+
*/const As=t.createLucideIcon("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/**
|
|
37
37
|
* @license lucide-react v0.453.0 - ISC
|
|
38
38
|
*
|
|
39
39
|
* This source code is licensed under the ISC license.
|
|
@@ -43,42 +43,42 @@
|
|
|
43
43
|
*
|
|
44
44
|
* This source code is licensed under the ISC license.
|
|
45
45
|
* See the LICENSE file in the root directory of this source tree.
|
|
46
|
-
*/const
|
|
46
|
+
*/const Ls=t.createLucideIcon("ArrowUp01",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["rect",{x:"15",y:"4",width:"4",height:"6",ry:"2",key:"1bwicg"}],["path",{d:"M17 20v-6h-2",key:"1qp1so"}],["path",{d:"M15 20h4",key:"1j968p"}]]);/**
|
|
47
47
|
* @license lucide-react v0.453.0 - ISC
|
|
48
48
|
*
|
|
49
49
|
* This source code is licensed under the ISC license.
|
|
50
50
|
* See the LICENSE file in the root directory of this source tree.
|
|
51
|
-
*/const
|
|
51
|
+
*/const Os=t.createLucideIcon("ArrowUpAZ",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]]);/**
|
|
52
52
|
* @license lucide-react v0.453.0 - ISC
|
|
53
53
|
*
|
|
54
54
|
* This source code is licensed under the ISC license.
|
|
55
55
|
* See the LICENSE file in the root directory of this source tree.
|
|
56
|
-
*/const
|
|
56
|
+
*/const Bs=t.createLucideIcon("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]);/**
|
|
57
57
|
* @license lucide-react v0.453.0 - ISC
|
|
58
58
|
*
|
|
59
59
|
* This source code is licensed under the ISC license.
|
|
60
60
|
* See the LICENSE file in the root directory of this source tree.
|
|
61
|
-
*/const
|
|
61
|
+
*/const Fs=t.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"}]]);/**
|
|
62
62
|
* @license lucide-react v0.453.0 - ISC
|
|
63
63
|
*
|
|
64
64
|
* This source code is licensed under the ISC license.
|
|
65
65
|
* See the LICENSE file in the root directory of this source tree.
|
|
66
|
-
*/const
|
|
66
|
+
*/const Ot=t.createLucideIcon("BookType",[["path",{d:"M10 13h4",key:"ytezjc"}],["path",{d:"M12 6v7",key:"1f6ttz"}],["path",{d:"M16 8V6H8v2",key:"x8j6u4"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}]]);/**
|
|
67
67
|
* @license lucide-react v0.453.0 - ISC
|
|
68
68
|
*
|
|
69
69
|
* This source code is licensed under the ISC license.
|
|
70
70
|
* See the LICENSE file in the root directory of this source tree.
|
|
71
|
-
*/const
|
|
71
|
+
*/const zs=t.createLucideIcon("Box",[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]]);/**
|
|
72
72
|
* @license lucide-react v0.453.0 - ISC
|
|
73
73
|
*
|
|
74
74
|
* This source code is licensed under the ISC license.
|
|
75
75
|
* See the LICENSE file in the root directory of this source tree.
|
|
76
|
-
*/const
|
|
76
|
+
*/const Ps=t.createLucideIcon("Braces",[["path",{d:"M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1",key:"ezmyqa"}],["path",{d:"M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1",key:"e1hn23"}]]);/**
|
|
77
77
|
* @license lucide-react v0.453.0 - ISC
|
|
78
78
|
*
|
|
79
79
|
* This source code is licensed under the ISC license.
|
|
80
80
|
* See the LICENSE file in the root directory of this source tree.
|
|
81
|
-
*/const
|
|
81
|
+
*/const Rs=t.createLucideIcon("Calculator",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["line",{x1:"8",x2:"16",y1:"6",y2:"6",key:"x4nwl0"}],["line",{x1:"16",x2:"16",y1:"14",y2:"18",key:"wjye3r"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]);/**
|
|
82
82
|
* @license lucide-react v0.453.0 - ISC
|
|
83
83
|
*
|
|
84
84
|
* This source code is licensed under the ISC license.
|
|
@@ -118,37 +118,37 @@
|
|
|
118
118
|
*
|
|
119
119
|
* This source code is licensed under the ISC license.
|
|
120
120
|
* See the LICENSE file in the root directory of this source tree.
|
|
121
|
-
*/const
|
|
121
|
+
*/const qs=t.createLucideIcon("CircleArrowRight",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"m12 16 4-4-4-4",key:"1i9zcv"}]]);/**
|
|
122
122
|
* @license lucide-react v0.453.0 - ISC
|
|
123
123
|
*
|
|
124
124
|
* This source code is licensed under the ISC license.
|
|
125
125
|
* See the LICENSE file in the root directory of this source tree.
|
|
126
|
-
*/const
|
|
126
|
+
*/const Bt=t.createLucideIcon("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/**
|
|
127
127
|
* @license lucide-react v0.453.0 - ISC
|
|
128
128
|
*
|
|
129
129
|
* This source code is licensed under the ISC license.
|
|
130
130
|
* See the LICENSE file in the root directory of this source tree.
|
|
131
|
-
*/const
|
|
131
|
+
*/const _s=t.createLucideIcon("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);/**
|
|
132
132
|
* @license lucide-react v0.453.0 - ISC
|
|
133
133
|
*
|
|
134
134
|
* This source code is licensed under the ISC license.
|
|
135
135
|
* See the LICENSE file in the root directory of this source tree.
|
|
136
|
-
*/const
|
|
136
|
+
*/const Gs=t.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"}]]);/**
|
|
137
137
|
* @license lucide-react v0.453.0 - ISC
|
|
138
138
|
*
|
|
139
139
|
* This source code is licensed under the ISC license.
|
|
140
140
|
* See the LICENSE file in the root directory of this source tree.
|
|
141
|
-
*/const
|
|
141
|
+
*/const $s=t.createLucideIcon("Component",[["path",{d:"M15.536 11.293a1 1 0 0 0 0 1.414l2.376 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1uwlt4"}],["path",{d:"M2.297 11.293a1 1 0 0 0 0 1.414l2.377 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414L6.088 8.916a1 1 0 0 0-1.414 0z",key:"10291m"}],["path",{d:"M8.916 17.912a1 1 0 0 0 0 1.415l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.415l-2.377-2.376a1 1 0 0 0-1.414 0z",key:"1tqoq1"}],["path",{d:"M8.916 4.674a1 1 0 0 0 0 1.414l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1x6lto"}]]);/**
|
|
142
142
|
* @license lucide-react v0.453.0 - ISC
|
|
143
143
|
*
|
|
144
144
|
* This source code is licensed under the ISC license.
|
|
145
145
|
* See the LICENSE file in the root directory of this source tree.
|
|
146
|
-
*/const
|
|
146
|
+
*/const Js=t.createLucideIcon("CopyPlus",[["line",{x1:"15",x2:"15",y1:"12",y2:"18",key:"1p7wdc"}],["line",{x1:"12",x2:"18",y1:"15",y2:"15",key:"1nscbv"}],["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/**
|
|
147
147
|
* @license lucide-react v0.453.0 - ISC
|
|
148
148
|
*
|
|
149
149
|
* This source code is licensed under the ISC license.
|
|
150
150
|
* See the LICENSE file in the root directory of this source tree.
|
|
151
|
-
*/const
|
|
151
|
+
*/const Hs=t.createLucideIcon("DollarSign",[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]]);/**
|
|
152
152
|
* @license lucide-react v0.453.0 - ISC
|
|
153
153
|
*
|
|
154
154
|
* This source code is licensed under the ISC license.
|
|
@@ -158,47 +158,47 @@
|
|
|
158
158
|
*
|
|
159
159
|
* This source code is licensed under the ISC license.
|
|
160
160
|
* See the LICENSE file in the root directory of this source tree.
|
|
161
|
-
*/const
|
|
161
|
+
*/const Ft=t.createLucideIcon("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]);/**
|
|
162
162
|
* @license lucide-react v0.453.0 - ISC
|
|
163
163
|
*
|
|
164
164
|
* This source code is licensed under the ISC license.
|
|
165
165
|
* See the LICENSE file in the root directory of this source tree.
|
|
166
|
-
*/const
|
|
166
|
+
*/const Us=t.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"}]]);/**
|
|
167
167
|
* @license lucide-react v0.453.0 - ISC
|
|
168
168
|
*
|
|
169
169
|
* This source code is licensed under the ISC license.
|
|
170
170
|
* See the LICENSE file in the root directory of this source tree.
|
|
171
|
-
*/const
|
|
171
|
+
*/const Ys=t.createLucideIcon("FileCode2",[["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:"m5 12-3 3 3 3",key:"oke12k"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]]);/**
|
|
172
172
|
* @license lucide-react v0.453.0 - ISC
|
|
173
173
|
*
|
|
174
174
|
* This source code is licensed under the ISC license.
|
|
175
175
|
* See the LICENSE file in the root directory of this source tree.
|
|
176
|
-
*/const
|
|
176
|
+
*/const Ks=t.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"}]]);/**
|
|
177
177
|
* @license lucide-react v0.453.0 - ISC
|
|
178
178
|
*
|
|
179
179
|
* This source code is licensed under the ISC license.
|
|
180
180
|
* See the LICENSE file in the root directory of this source tree.
|
|
181
|
-
*/const
|
|
181
|
+
*/const Qs=t.createLucideIcon("File",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}]]);/**
|
|
182
182
|
* @license lucide-react v0.453.0 - ISC
|
|
183
183
|
*
|
|
184
184
|
* This source code is licensed under the ISC license.
|
|
185
185
|
* See the LICENSE file in the root directory of this source tree.
|
|
186
|
-
*/const
|
|
186
|
+
*/const Ws=t.createLucideIcon("Fingerprint",[["path",{d:"M12 10a2 2 0 0 0-2 2c0 1.02-.1 2.51-.26 4",key:"1nerag"}],["path",{d:"M14 13.12c0 2.38 0 6.38-1 8.88",key:"o46ks0"}],["path",{d:"M17.29 21.02c.12-.6.43-2.3.5-3.02",key:"ptglia"}],["path",{d:"M2 12a10 10 0 0 1 18-6",key:"ydlgp0"}],["path",{d:"M2 16h.01",key:"1gqxmh"}],["path",{d:"M21.8 16c.2-2 .131-5.354 0-6",key:"drycrb"}],["path",{d:"M5 19.5C5.5 18 6 15 6 12a6 6 0 0 1 .34-2",key:"1tidbn"}],["path",{d:"M8.65 22c.21-.66.45-1.32.57-2",key:"13wd9y"}],["path",{d:"M9 6.8a6 6 0 0 1 9 5.2v2",key:"1fr1j5"}]]);/**
|
|
187
187
|
* @license lucide-react v0.453.0 - ISC
|
|
188
188
|
*
|
|
189
189
|
* This source code is licensed under the ISC license.
|
|
190
190
|
* See the LICENSE file in the root directory of this source tree.
|
|
191
|
-
*/const
|
|
191
|
+
*/const Xs=t.createLucideIcon("Glasses",[["circle",{cx:"6",cy:"15",r:"4",key:"vux9w4"}],["circle",{cx:"18",cy:"15",r:"4",key:"18o8ve"}],["path",{d:"M14 15a2 2 0 0 0-2-2 2 2 0 0 0-2 2",key:"1ag4bs"}],["path",{d:"M2.5 13 5 7c.7-1.3 1.4-2 3-2",key:"1hm1gs"}],["path",{d:"M21.5 13 19 7c-.7-1.3-1.5-2-3-2",key:"1r31ai"}]]);/**
|
|
192
192
|
* @license lucide-react v0.453.0 - ISC
|
|
193
193
|
*
|
|
194
194
|
* This source code is licensed under the ISC license.
|
|
195
195
|
* See the LICENSE file in the root directory of this source tree.
|
|
196
|
-
*/const
|
|
196
|
+
*/const Zs=t.createLucideIcon("Grid3x3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
|
|
197
197
|
* @license lucide-react v0.453.0 - ISC
|
|
198
198
|
*
|
|
199
199
|
* This source code is licensed under the ISC license.
|
|
200
200
|
* See the LICENSE file in the root directory of this source tree.
|
|
201
|
-
*/const
|
|
201
|
+
*/const en=t.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"}]]);/**
|
|
202
202
|
* @license lucide-react v0.453.0 - ISC
|
|
203
203
|
*
|
|
204
204
|
* This source code is licensed under the ISC license.
|
|
@@ -208,37 +208,37 @@
|
|
|
208
208
|
*
|
|
209
209
|
* This source code is licensed under the ISC license.
|
|
210
210
|
* See the LICENSE file in the root directory of this source tree.
|
|
211
|
-
*/const
|
|
211
|
+
*/const tn=t.createLucideIcon("LayoutList",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}],["path",{d:"M14 4h7",key:"3xa0d5"}],["path",{d:"M14 9h7",key:"1icrd9"}],["path",{d:"M14 15h7",key:"1mj8o2"}],["path",{d:"M14 20h7",key:"11slyb"}]]);/**
|
|
212
212
|
* @license lucide-react v0.453.0 - ISC
|
|
213
213
|
*
|
|
214
214
|
* This source code is licensed under the ISC license.
|
|
215
215
|
* See the LICENSE file in the root directory of this source tree.
|
|
216
|
-
*/const
|
|
216
|
+
*/const sn=t.createLucideIcon("ListEnd",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M10 18H3",key:"13769t"}],["path",{d:"M21 6v10a2 2 0 0 1-2 2h-5",key:"ilrcs8"}],["path",{d:"m16 16-2 2 2 2",key:"kkc6pm"}]]);/**
|
|
217
217
|
* @license lucide-react v0.453.0 - ISC
|
|
218
218
|
*
|
|
219
219
|
* This source code is licensed under the ISC license.
|
|
220
220
|
* See the LICENSE file in the root directory of this source tree.
|
|
221
|
-
*/const
|
|
221
|
+
*/const nn=t.createLucideIcon("ListStart",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M10 6H3",key:"lf8lx7"}],["path",{d:"M21 18V8a2 2 0 0 0-2-2h-5",key:"1hghli"}],["path",{d:"m16 8-2-2 2-2",key:"160uvd"}]]);/**
|
|
222
222
|
* @license lucide-react v0.453.0 - ISC
|
|
223
223
|
*
|
|
224
224
|
* This source code is licensed under the ISC license.
|
|
225
225
|
* See the LICENSE file in the root directory of this source tree.
|
|
226
|
-
*/const
|
|
226
|
+
*/const an=t.createLucideIcon("ListX",[["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"m19 10-4 4",key:"1tz659"}],["path",{d:"m15 10 4 4",key:"1n7nei"}]]);/**
|
|
227
227
|
* @license lucide-react v0.453.0 - ISC
|
|
228
228
|
*
|
|
229
229
|
* This source code is licensed under the ISC license.
|
|
230
230
|
* See the LICENSE file in the root directory of this source tree.
|
|
231
|
-
*/const
|
|
231
|
+
*/const rn=t.createLucideIcon("Logs",[["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M3 12h1",key:"lp3yf2"}],["path",{d:"M3 18h1",key:"1eiwyy"}],["path",{d:"M3 6h1",key:"rgxa97"}],["path",{d:"M8 12h1",key:"1con00"}],["path",{d:"M8 18h1",key:"13wk12"}],["path",{d:"M8 6h1",key:"tn6mkg"}]]);/**
|
|
232
232
|
* @license lucide-react v0.453.0 - ISC
|
|
233
233
|
*
|
|
234
234
|
* This source code is licensed under the ISC license.
|
|
235
235
|
* See the LICENSE file in the root directory of this source tree.
|
|
236
|
-
*/const
|
|
236
|
+
*/const on=t.createLucideIcon("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/**
|
|
237
237
|
* @license lucide-react v0.453.0 - ISC
|
|
238
238
|
*
|
|
239
239
|
* This source code is licensed under the ISC license.
|
|
240
240
|
* See the LICENSE file in the root directory of this source tree.
|
|
241
|
-
*/const
|
|
241
|
+
*/const ln=t.createLucideIcon("MapPin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);/**
|
|
242
242
|
* @license lucide-react v0.453.0 - ISC
|
|
243
243
|
*
|
|
244
244
|
* This source code is licensed under the ISC license.
|
|
@@ -248,12 +248,12 @@
|
|
|
248
248
|
*
|
|
249
249
|
* This source code is licensed under the ISC license.
|
|
250
250
|
* See the LICENSE file in the root directory of this source tree.
|
|
251
|
-
*/const
|
|
251
|
+
*/const cn=t.createLucideIcon("MessageCircleMore",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M8 12h.01",key:"czm47f"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M16 12h.01",key:"1l6xoz"}]]);/**
|
|
252
252
|
* @license lucide-react v0.453.0 - ISC
|
|
253
253
|
*
|
|
254
254
|
* This source code is licensed under the ISC license.
|
|
255
255
|
* See the LICENSE file in the root directory of this source tree.
|
|
256
|
-
*/const
|
|
256
|
+
*/const dn=t.createLucideIcon("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/**
|
|
257
257
|
* @license lucide-react v0.453.0 - ISC
|
|
258
258
|
*
|
|
259
259
|
* This source code is licensed under the ISC license.
|
|
@@ -268,12 +268,12 @@
|
|
|
268
268
|
*
|
|
269
269
|
* This source code is licensed under the ISC license.
|
|
270
270
|
* See the LICENSE file in the root directory of this source tree.
|
|
271
|
-
*/const
|
|
271
|
+
*/const un=t.createLucideIcon("Network",[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]]);/**
|
|
272
272
|
* @license lucide-react v0.453.0 - ISC
|
|
273
273
|
*
|
|
274
274
|
* This source code is licensed under the ISC license.
|
|
275
275
|
* See the LICENSE file in the root directory of this source tree.
|
|
276
|
-
*/const
|
|
276
|
+
*/const mn=t.createLucideIcon("Plug",[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M9 8V2",key:"14iosj"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z",key:"osxo6l"}]]);/**
|
|
277
277
|
* @license lucide-react v0.453.0 - ISC
|
|
278
278
|
*
|
|
279
279
|
* This source code is licensed under the ISC license.
|
|
@@ -283,12 +283,7 @@
|
|
|
283
283
|
*
|
|
284
284
|
* This source code is licensed under the ISC license.
|
|
285
285
|
* See the LICENSE file in the root directory of this source tree.
|
|
286
|
-
*/const
|
|
287
|
-
* @license lucide-react v0.453.0 - ISC
|
|
288
|
-
*
|
|
289
|
-
* This source code is licensed under the ISC license.
|
|
290
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
291
|
-
*/const Ft=t.createLucideIcon("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/**
|
|
286
|
+
*/const zt=t.createLucideIcon("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/**
|
|
292
287
|
* @license lucide-react v0.453.0 - ISC
|
|
293
288
|
*
|
|
294
289
|
* This source code is licensed under the ISC license.
|
|
@@ -313,7 +308,7 @@
|
|
|
313
308
|
*
|
|
314
309
|
* This source code is licensed under the ISC license.
|
|
315
310
|
* See the LICENSE file in the root directory of this source tree.
|
|
316
|
-
*/const
|
|
311
|
+
*/const Pt=t.createLucideIcon("Sigma",[["path",{d:"M18 7V5a1 1 0 0 0-1-1H6.5a.5.5 0 0 0-.4.8l4.5 6a2 2 0 0 1 0 2.4l-4.5 6a.5.5 0 0 0 .4.8H17a1 1 0 0 0 1-1v-2",key:"wuwx1p"}]]);/**
|
|
317
312
|
* @license lucide-react v0.453.0 - ISC
|
|
318
313
|
*
|
|
319
314
|
* This source code is licensed under the ISC license.
|
|
@@ -333,7 +328,7 @@
|
|
|
333
328
|
*
|
|
334
329
|
* This source code is licensed under the ISC license.
|
|
335
330
|
* See the LICENSE file in the root directory of this source tree.
|
|
336
|
-
*/const
|
|
331
|
+
*/const Rt=t.createLucideIcon("Tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]]);/**
|
|
337
332
|
* @license lucide-react v0.453.0 - ISC
|
|
338
333
|
*
|
|
339
334
|
* This source code is licensed under the ISC license.
|
|
@@ -353,11 +348,11 @@
|
|
|
353
348
|
*
|
|
354
349
|
* This source code is licensed under the ISC license.
|
|
355
350
|
* See the LICENSE file in the root directory of this source tree.
|
|
356
|
-
*/const Rt=t.createLucideIcon("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);function it(s){var a;return{...s,sheets:(a=s==null?void 0:s.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(o=>{var i;return{...o,cards:(i=o.cards)==null?void 0:i.map(c=>qt(c))}})}})}}function qt(s){return{...s,customCfg:yn(s.customCfg),data:[]}}function yn(s){var a,n;return s?{...s,data:{...s==null?void 0:s.data,labels:[],datasets:(n=(a=s==null?void 0:s.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function bn(s,a,n,r){if(!r)return null;const o=JSON.stringify(a);return await t.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:s,template:o,filterValues:n,operation:"create"})}async function Ye(s,a){if(!a)return null;const{id:n,template:r,filterValues:o,isDefault:i,shared:c}=s;return await t.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:o,isDefault:i,shared:c,operation:"update"})}async function vn(s,a){return a?await t.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:s}):null}function Nn(){const[s,a]=L.useState(""),[n,r]=L.useState(!1),o=t.useDashboardStore(f=>f.lenses),{setLenses:i,setSelectedLensId:c}=t.useDashboardActions(),[d,l]=L.useState(!1),[x,h]=L.useState(!1),u=t.useDashboardStore(f=>f.dashboard),j=t.useDashboardStore(f=>f.filterValues),{authToken:y}=t.useSemaphorContext();async function N(){l(!0);const f=it(u),E=await bn(s,f,j,y==null?void 0:y.accessToken);E&&(i([...o||[],E]),c(E.id),h(!1)),l(!1)}return e.jsxs(t.Dialog,{open:x,onOpenChange:h,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(t.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Create Lens"}),e.jsx(t.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(t.Label,{className:"text-right",children:"Name"}),e.jsx(t.Input,{value:s,onChange:f=>{a(f.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),n&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(t.DialogFooter,{children:e.jsx(t.Button,{size:"sm",variant:"outline",type:"submit",onClick:N,disabled:d,children:d?"Creating...":"Add"})})]})]})}function Cn(){const[s,a]=L.useState(!1),n=t.useDashboardStore(h=>h.lenses),r=t.useDashboardStore(h=>h.selectedLensId),{setLenses:o,setSelectedLensId:i}=t.useDashboardActions(),{authToken:c}=t.useSemaphorContext();async function d(h){i(h)}async function l(h){if(await vn(h,c==null?void 0:c.accessToken)){const j=n==null?void 0:n.filter(y=>y.id!==h);o(j||[]),i("original")}}async function x(h){const u=n==null?void 0:n.map(N=>N.id===h.id?{...N,isDefault:!h.isDefault}:{...N,isDefault:!1});o(u||[]);const j={...h,isDefault:!h.isDefault};await Ye(j,c==null?void 0:c.accessToken);const y=n==null?void 0:n.find(N=>N.isDefault);if(y&&y.id!==h.id){const N={...y,isDefault:!1};await Ye(N,c==null?void 0:c.accessToken)}}return e.jsxs(t.DropdownMenu,{open:s,onOpenChange:a,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(Ws,{className:"h-4 w-4"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(t.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuRadioGroup,{value:r,onValueChange:d,children:[e.jsx(t.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(h=>e.jsxs(t.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:h.id,children:[e.jsx("p",{children:h.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(t.House,{onClick:u=>{u.preventDefault(),x(h)},className:t.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!h.isDefault,"text-green-500":h.isDefault}),strokeWidth:1.5}),e.jsx(t.Cross2Icon,{onClick:u=>{u.preventDefault(),l(h.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},h.id))]})]})]})}function _t(){var i;const s=t.useDashboardStore.getState().authToken,a=t.useDashboardStore.getState().theme,n=t.useDashboardStore.getState().filterValues,r=(i=t.useDashboardStore.getState().dashboard)==null?void 0:i.title,o=t.useDashboardStore.getState().selectedSheetId;return{authToken:s,theme:a||"light",filterValues:n,dashboardTitle:r||"",selectedSheetId:o||""}}async function Gt(){const s=t.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:o,selectedSheetId:i}=_t();if(s)return;const c=new URLSearchParams;c.set("token",(a==null?void 0:a.accessToken)||""),c.set("theme",n),c.set("filterValues",JSON.stringify(r)),c.set("selectedSheetId",i||"");const d=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(c.toString())}`;t.useDashboardStore.setState({isDownloadingPdf:!0});const h=(await(await fetch(d,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,u=document.createElement("a");u.href=h;const j=`${o}-${new Date().toISOString()}.pdf`;u.download=j,u.click(),t.useDashboardStore.setState({isDownloadingPdf:!1})}function Sn({iconClassName:s}){const{authToken:a}=t.useSemaphorContext();t.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.title}),t.useDashboardStore(o=>o.theme),t.useDashboardStore(o=>o.filterValues);const n=t.useDashboardStore(o=>o.isDownloadingPdf);async function r(){await Gt()}return e.jsx(t.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:n?e.jsx(t.LoaderCircle,{className:t.cn("size-3.5 animate-spin",s)}):e.jsx(t.Download,{className:t.cn("size-4",s)})})}function ae({defaultValue:s,label:a,options:n,value:r,onValueChange:o,className:i,icon:c,showPlaceholderLabel:d=!0}){return e.jsxs(t.Select,{defaultValue:s,value:r,onValueChange:o,children:[e.jsx(t.SelectTrigger,{className:t.cn("w-full focus:ring-0 focus:ring-offset-0",i),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),d&&e.jsx(t.SelectValue,{placeholder:a})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:a}),n.map(l=>e.jsx(t.SelectItem,{value:l.value,children:l.label},l.value))]})})]})}const wt=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function $t({triggerButtonClassName:s}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:o,error:i,isDeleting:c}=wn(),[d,l]=L.useState(""),[x,h]=L.useState(wt[0].value),[u,j]=L.useState("06:00"),[y,N]=L.useState("");return e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Schedule Dashboard",className:t.cn("h-7 p-2",s),children:e.jsx(t.Clock,{className:"size-4"})})}),e.jsx(t.PopoverContent,{align:"end",className:"w-80",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribe to receive dashboard via email"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"email",children:"Email"}),e.jsx(t.Input,{id:"email",value:d,onChange:f=>l(f.target.value),className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"subject",children:"Subject"}),e.jsx(t.Input,{id:"subject",placeholder:"Monthly Sales Report",value:y,onChange:f=>{N(f.target.value.replace(/[^a-zA-Z0-9\s-_]/g,""))},className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"frequency",children:"Frequency"}),e.jsx(ae,{className:"col-span-2 h-8",label:"Select Frequency",options:wt,value:x,onValueChange:f=>h(f)})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"time",children:"Time"}),e.jsx(t.Input,{id:"time",type:"time",value:u,onChange:f=>j(f.target.value),className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsx("div",{className:"mt-2 flex justify-end",children:e.jsxs(t.Button,{onClick:async()=>{await n({email:d,frequency:x,time:u,subject:y}),j("00:00"),l(""),N("")},className:"h-8 p-2",disabled:o==="loading"||!d,children:[o==="loading"&&e.jsx(t.LoaderCircle,{className:"mr-2 size-4 animate-spin"}),o==="success"&&e.jsx(t.Check,{className:"mr-2 size-4"}),o==="error"&&e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{children:e.jsx(Ot,{className:"mr-2 size-4 text-destructive"})}),e.jsx(t.TooltipContent,{children:e.jsx("p",{children:i})})]}),"Schedule"]})}),a&&a.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.Separator,{className:"my-2"}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Subscriptions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active email subscriptions"})]}),t.isDevEnv]})}),e.jsx("div",{className:"grid gap-2",children:a==null?void 0:a.map(f=>e.jsxs("div",{className:"group grid grid-cols-5 gap-3",children:[e.jsx("div",{className:"col-span-3 text-sm",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"boder-border rounded-md border bg-muted px-2 py-1",children:[t.titleCase(f.frequency)," "]}),e.jsx(t.Label,{children:f.time})]})}),e.jsxs("div",{className:"col-span-2 flex items-center justify-end gap-4",children:[e.jsx(kt,{tooltip:`Next Run: ${new Date(f.nextRun).toLocaleString()} ${f.timezone}`,children:e.jsx(Rs,{className:"size-3.5"})}),e.jsx(kt,{tooltip:`${f.endUserEmail}`,children:e.jsx(rn,{className:"size-3.5"})}),c===f.id?e.jsx(t.LoaderCircle,{className:"size-3.5 animate-spin"}):e.jsx(t.Trash2,{onClick:()=>r(f.id),className:"size-3.5 cursor-pointer"})]})]},f.id))})]})]})]})})]})})}const kt=({children:s,tooltip:a})=>e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:s}),e.jsx(t.TooltipContent,{children:a})]})});function wn(){const[s,a]=L.useState("idle"),[n,r]=L.useState(""),[o,i]=L.useState(null),c=t.useDashboardStore(O=>O.authToken),d=t.useDashboardStore(O=>O.dashboard.id),l=t.useDashboardStore(O=>O.dashboard.title),{endUserId:x}=t.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),h="https://semaphor.cloud/api/v1/subscriptions/get",u={dashboardId:d,endUserId:x},{data:j,isLoading:y,isError:N,isFetching:f,refetch:E}=t.useQuery({queryKey:["subscriptions",d,x],queryFn:()=>t.getRequest(h,(c==null?void 0:c.accessToken)||"",u),enabled:!!(c!=null&&c.accessToken)&&!!d&&!!x});async function p({email:O,subject:I,frequency:k,time:v}){const{authToken:C,...S}=_t(),D=Intl.DateTimeFormat().resolvedOptions().timeZone,w={email:O,frequency:k,time:v,timezone:D,endUserId:x,endUserEmail:O,subject:I||l||"Scheduled Dashboard",dashboardId:d,dashboardParams:S};a("loading");const m="https://semaphor.cloud/api/v1/subscriptions/create";try{const B=await t.postRequestRegular(m,(C==null?void 0:C.accessToken)||"",{...w});a("success"),r(""),E(),setTimeout(()=>{a("idle")},2e3)}catch(B){console.error(B),a("error"),r(B.message)}}async function g(O){const I="https://semaphor.cloud/api/v1/subscriptions/delete";i(O);try{await t.postRequestRegular(I,(c==null?void 0:c.accessToken)||"",{id:O}),E(),setTimeout(()=>{i(null)},2e3)}catch(k){console.error(k),i(null),a("error"),r(k.message)}}return{data:j,isLoading:y,isFetching:f,isError:N,isDeleting:o,refetch:E,handleScheduleSubscription:p,handleDeleteSubscription:g,status:s,error:n}}function kn(){const{authToken:s}=t.useSemaphorContext();t.useDashboardStore(m=>m.theme);const a=t.useDashboardStore(m=>m.lenses),n=t.useDashboardStore(m=>m.selectedLensId),r=a==null?void 0:a.find(m=>m.id===n),o=t.useDashboardStore(m=>m.dashboard);t.useDashboardStore(m=>m.selectedSheetId);const i=t.useDashboardStore(m=>m.isDashboardEditing),c=t.useEditorStore(m=>m.card),d=t.useEditorStore(m=>m.selectedConnectionId),[l,x]=L.useState(!1),h=t.useDashboardStore(m=>m.filterValues),u=t.useDashboardStore(m=>m.isVisualEditing),j=t.useDashboardStore(m=>m.showFilters);t.useDashboardStore(m=>m.showDashboardJSON);const y=t.useDashboardStore(m=>m.onSaveFunction),N=t.useDashboardStore(m=>m.actions.setShowFilters),{addFrame:f,setSelectedFrameId:E}=t.useDashboardStore(m=>m.actions),{getSelectedSheet:p,setIsDashboardEditing:g,setShowDashboardJSON:O}=t.useDashboardStore(m=>m.actions),I=p(),{tenantId:k,endUserId:v}=L.useMemo(()=>t.getTenantAndEndUserId(s==null?void 0:s.accessToken),[s==null?void 0:s.accessToken]),C=L.useMemo(()=>k||v,[k,v]),S=()=>{if(!i||!I)return;const m={dataSource:c.dataSource,mode:"explorer",connectionId:d,id:t.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},B={id:t.v4(),cards:[m],activeCardId:m.id};f(I.id,B),E(B.id)},D=()=>{g(!0)};async function w(){if(x(!0),!n||!r)return;const m=it(o),B=JSON.stringify(m),M={...r,template:B,filterValues:h};await Ye(M,s==null?void 0:s.accessToken),t.ue.success("Lens saved"),y==null||y(m),x(!1)}return u?null:e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-1 pl-3 pr-2",role:"dashboard-controls",children:[!u&&e.jsx("div",{className:"flex items-center gap-3",children:e.jsx(t.Label,{children:r==null?void 0:r.name})}),e.jsxs("div",{className:"flex gap-2",children:[!1,!u&&e.jsx(Sn,{}),!u&&e.jsx($t,{}),i&&!u&&C&&e.jsx(Nn,{}),!u&&C&&e.jsx(Cn,{}),i&&!u&&e.jsxs(t.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!i,onClick:S,children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!i&&e.jsx(t.Button,{variant:"ghost",className:"h-7 p-2",onClick:D,size:"sm",children:e.jsx(t.Pencil,{className:"h-4 w-4"})}),i&&!u&&e.jsx(t.IconButton,{className:"h-7 p-2",onClick:()=>{g(!1),O(!1)},children:e.jsx(t.Cross2Icon,{className:"h-4 w-4"})}),i&&!u&&C&&e.jsx(t.Button,{className:"h-7 p-2",variant:"ghost",disabled:l,onClick:w,size:"sm",children:e.jsx(xn,{className:"h-4 w-4"})}),!j&&!u&&i&&e.jsx(t.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>N(!0),size:"sm",children:e.jsx(t.Filter,{className:"h-4 w-4"})}),!u&&i&&!1,!u&&!1]})]})}function En({name:s,items:a,value:n,onChange:r,isLoading:o,isError:i,refetch:c,className:d,icon:l,showNone:x=!1}){const h=he.useRef(null),[u,j]=he.useState(!1),[y,N]=he.useState("100%"),f=x?[...a||[],{id:"none",name:"None"}]:a;he.useLayoutEffect(()=>{h.current&&N(h.current.offsetWidth)},[]);function E(){var g;return o?"Loading...":i?"Error":n?(g=a==null?void 0:a.find(O=>O.id===n))==null?void 0:g.name:`Select ${s}`}function p(g,O){r(O),j(!1)}return e.jsxs(t.Popover,{open:u,onOpenChange:j,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{ref:h,variant:"outline",role:"combobox","aria-expanded":u,className:t.cn("flex h-9 w-full justify-between",d),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[l&&e.jsx("div",{className:"mr-2",children:l}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:E()})]}),e.jsx(t.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-full p-0",style:{minWidth:y},children:e.jsxs(t.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(t.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(t.IconButton,{className:"h-7",onClick:c,children:e.jsx(Ft,{className:t.cn("size-3.5 opacity-50",o&&"animate-spin")})})]}),e.jsxs(t.CommandList,{children:[e.jsxs(t.CommandEmpty,{children:["No ",s==null?void 0:s.toLowerCase()," found."]}),e.jsx(t.CommandGroup,{children:f==null?void 0:f.map(g=>e.jsx(t.CommandItem,{className:"overflow-x-auto",value:g.name,onSelect:O=>p(O,g.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Check,{className:t.cn("size-4",n===g.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:g.name,children:g.name})]})},g.id))})]})]})})]})}function be({title:s,items:a,value:n,isLoading:r,isError:o,refetch:i,onChange:c,showNone:d=!1,className:l,disabled:x=!1,type:h="combobox"}){const u=r?"Loading...":o?"Error":n;function j(){if(s==="Connection")return e.jsx(un,{className:"size-4"});if(s==="Database")return e.jsx(t.Database,{className:"size-4"});if(s==="Schema")return e.jsx(dn,{className:"size-4"});if(s==="Table")return e.jsx(ze,{className:"size-4"});if(s==="Model")return e.jsx(Fs,{className:"size-4"})}function y(){return e.jsxs(t.Select,{disabled:x,value:u,onValueChange:c,children:[e.jsx(t.SelectTrigger,{className:t.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",l),children:e.jsx(t.SelectValue,{placeholder:r?"Loading...":o?"Error":`Select ${s}`})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[r?e.jsx(t.SelectLabel,{children:"Loading..."}):e.jsxs(t.SelectLabel,{className:"flex items-center justify-between gap-2",children:[s,e.jsx(Ft,{className:t.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:i})]}),e.jsxs(e.Fragment,{children:[d&&e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),a&&a.map((f,E)=>e.jsx(t.SelectItem,{value:f.id,children:f.name},E))]}),(r||o)&&e.jsx(t.SelectItem,{value:u,children:u})]})})]})}function N(){return e.jsx(En,{icon:j(),items:a,value:u,onChange:c||(()=>{}),isLoading:r,isError:o,refetch:i,name:s,showNone:d})}return e.jsx(t.TooltipProvider$1,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:h==="select"?y():N()})})}function Dn({column:s}){const[a,n]=L.useState(!1),r=t.useEditorStore(f=>f.selectedTableName),o=t.useEditorStore(f=>f.selectedSchemaName),i=t.useEditorStore(f=>f.selectedDatabaseName),c=t.useEditorStore(f=>f.selectedDatamodelId),d=t.useEditorStore(f=>f.sqlGen),{modelItems:l,connectionType:x}=t.useEditorAside(),h=t.useEditorStore(f=>f.actions.setSqlGen),u=t.useEditorStore(f=>f.actions.setCardSql),j=t.useEditorStore(f=>f.actions.setRunSql);function y(f,E){var I;const p=t.createSqlGenConfig(f,d,E),g=(I=l==null?void 0:l.find(k=>k.id===c))==null?void 0:I.name;h(p);const O=t.getSql(p,t.fmt(o||""),t.fmt(r),g||"",x,i||"");O&&(u(O),j(!0)),n(!1)}function N(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>y(s,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>y(s,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>y(s,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>y(s,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>y(s,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(t.HoverCard,{openDelay:0,open:a,onOpenChange:n,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx(t.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(t.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:N()})]})}function lt({column:s}){return e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger$1,{className:"shrink-0",asChild:!0,children:t.isTextDataType(s.data_type)?e.jsx(t.TextIcon,{className:"size-3 text-muted-foreground"}):t.isNumberDataType(s.data_type)?e.jsx(nt,{className:"size-3 text-muted-foreground"}):t.isDateDataType(s.data_type)?e.jsx(t.Calendar,{className:"size-3 text-muted-foreground"}):t.isBooleanDataType(s.data_type)?e.jsx(Vt,{className:"size-3 text-muted-foreground"}):s.data_type.startsWith("json")?e.jsx(zs,{className:"size-3 text-muted-foreground"}):e.jsx(t.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(t.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:s.data_type})})]})}function Re({column:s,className:a}){return e.jsxs("div",{className:t.cn("flex min-h-8 grow items-center space-x-2 px-2 text-sm",a),children:[e.jsx(lt,{column:s}),e.jsx("span",{children:s.column_name})]})}function In({id:s,children:a,type:n="column"}){const{attributes:r,listeners:o,setNodeRef:i,transform:c}=t.useDraggable({id:s,data:{type:n}}),d=c?{translate:t.CSS.Translate.toString(c),transform:t.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:i,style:d,...o,...r,children:a})}function Tn({onClick:s,column:a}){const n=t.useDndStore(h=>h.activeId),r=t.useEditorStore(h=>{var u;return(u=h.card.queryConfig)==null?void 0:u.groupByColumns}),o=t.useEditorStore(h=>{var u;return(u=h.card.queryConfig)==null?void 0:u.metricColumns}),i=t.useEditorStore(h=>{var u;return(u=h.card.queryConfig)==null?void 0:u.filterColumns});function c(h){return d(h)||l(h)||x(h)}function d(h){return r==null?void 0:r.some(u=>u.name===h.column_name)}function l(h){return o==null?void 0:o.some(u=>u.name===h.column_name)}function x(h){return i==null?void 0:i.some(u=>u.name===h.column_name)}return e.jsxs("div",{onClick:()=>s(a),className:t.cn("relative grow overflow-x-hidden overflow-y-hidden rounded-md active:border active:border-dashed active:border-muted-foreground",{"bg-muted-foreground/10":c(a)}),children:[n===a.column_name&&e.jsx(t.DragOverlay,{children:e.jsx(Re,{column:a,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),n===a.column_name&&e.jsx("div",{className:"absolute inset-0",children:n===a.column_name&&e.jsx(Re,{column:a})}),e.jsx(In,{id:a.column_name,type:"column",children:e.jsx(Re,{column:a})})]})}const qe={id:"__placeholder__",role:"groupby",type:"string"},_e={id:"__placeholder__",role:"groupby",type:"string"},Ge={id:"__placeholder__",role:"metric",type:"number"},$e={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},Jt={id:"__placeholder__"},xe="droppable-group-by",pe="droppable-metrics",fe="droppable-pivot-by",Me="sortable-group-by",Ke="sortable-metrics",Ae="sortable-pivot-by",Qe="droppable-filters",We="sortable-filters",ct="sortable-order-by";function Mn(){const s=t.useDndStore(T=>T.insertIndex),a=t.useEditorStore(T=>{var b;return((b=T.card.queryConfig)==null?void 0:b.groupByColumns)||[]}),n=t.useEditorStore(T=>{var b;return((b=T.card.queryConfig)==null?void 0:b.metricColumns)||[]}),r=t.useEditorStore(T=>{var b;return((b=T.card.queryConfig)==null?void 0:b.filterColumns)||[]}),o=t.useEditorStore(T=>{var b;return((b=T.card.queryConfig)==null?void 0:b.orderBy)||[]}),i=t.useEditorStore(T=>{var b;return((b=T.card.queryConfig)==null?void 0:b.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:d,setPreviewGroupByColumns:l,setPreviewMetricColumns:x,setPreviewFilterColumns:h,setPreviewPivotColumns:u}=t.useDndActions(),{setGroupByColumns:j,setMetricColumns:y,setFilterColumns:N,setOrderByColumns:f,setPivotByColumns:E}=t.useEditorActions(),{columns:p}=t.useDataColumns(),{formattedTableName:g}=t.useEditorAside(),O=t.useSensors(t.useSensor(t.MouseSensor,{activationConstraint:{distance:1}})),I=T=>{var F;const{active:b,over:A}=T;if(((F=b.data.current)==null?void 0:F.type)==="column"&&A){const P=A.id,R=p.find(q=>q.column_name===b.id);if(!R)return;const z=t.isNumberDataType(R.data_type),Y=t.isTextDataType(R.data_type),V=t.isDateDataType(R.data_type);if(Y||V){if(a.some(H=>H.id===P)){const H=a.findIndex(G=>G.id===P);c(H);const K=a.filter(G=>G.id!==qe.id);K.splice(H,0,qe),l(K)}else if(A.id===xe){c(a.length);const H=[...a,qe];l(H),x(n),h(r)}}if(Y||V){if(i.some(H=>H.id===P)){const H=i.findIndex(G=>G.id===P);c(H);const K=i.filter(G=>G.id!==_e.id);K.splice(H,0,_e),u(K)}else if(A.id===fe){c(i.length);const H=[...i,_e];u(H),l(a),x(n),h(r)}}if(z||Y){if(n.some(H=>H.id===P)){console.log("isOverMetricSortable",P);const H=n.findIndex(G=>G.id===P);c(H);const K=n.filter(G=>G.id!==Ge.id);K.splice(H,0,Ge),x(K)}else if(A.id===pe){c(n.length);const H=[...n,Ge];x(H),h(r),l(a),u(i)}}if(v(R)){if(r.some(H=>H.id===P)){const H=r.findIndex(G=>G.id===P);c(H);const K=r.filter(G=>G.id!==$e.id);K.splice(H,0,$e),h(K)}else if(A.id===Qe){c(r.length);const H=[...r,$e];h(H),x(n),l(a),u(i)}}}else l(a),x(n),h(r),u(i)};function k(T){d(T.active.id),c(null),l(a),x(n),h(r),u(i)}function v(T){return!r.some(b=>b.name===T.column_name)}function C(T,b="SUM"){const{column_name:A,data_type:F}=T,P=[...n],R=s!==null?s:n.length,z={...T,id:ie(A),name:A,label:ke(A,b),type:F,role:"metric",aggregate:b};P.splice(R,0,z),y(P)}function S(T){const b=t.isTextDataType(T.data_type);t.isDateDataType(T.data_type);const A=[...i],F=s!==null?s:i.length;let P;b?P={...T,id:ie(T.column_name),name:T.column_name,type:T.data_type,role:"groupby"}:P={...T,id:ie(T.column_name),name:T.column_name,type:T.data_type,role:"groupby",label:ve(T.column_name,"month"),granularity:"month"},A.splice(F,0,P),E(A)}function D(T){const b=t.isTextDataType(T.data_type);t.isDateDataType(T.data_type);const A=[...a],F=s!==null?s:a.length;let P;b?P={...T,id:ie(T.column_name),name:T.column_name,type:T.data_type,role:"groupby"}:P={...T,id:ie(T.column_name),name:T.column_name,type:T.data_type,role:"groupby",label:ve(T.column_name,"month"),granularity:"month"},A.splice(F,0,P),j(A)}function w(T){const b=[...r],A=s!==null?s:r.length,F={...T,id:ie(T.column_name),name:T.column_name,type:T.data_type,sql:t.getDefaultFilterSql(T.data_type,g,t.fmt(T.column_name)),role:"filter"};b.splice(A,0,F),N(b)}function m(T){var P,R,z,Y,V,q,H,K;const{active:b,over:A}=T,F=b.data.current;if((F==null?void 0:F.type)==="column"&&A){const G=p.find(se=>se.column_name===b.id);if(!G)return;const $=t.isNumberDataType(G.data_type),J=t.isTextDataType(G.data_type),X=t.isDateDataType(G.data_type);(J||X)&&(A.id===xe||((P=A.data.current)==null?void 0:P.type)===Me)&&D(G),(J||X)&&(A.id===fe||((R=A.data.current)==null?void 0:R.type)===Ae)?S(G):($||J)&&(A.id===pe||((z=A.data.current)==null?void 0:z.type)===Ke)?($&&C(G),J&&C(G,"COUNT")):v(G)&&(A.id===Qe||((Y=A.data.current)==null?void 0:Y.type)===We)&&w(G)}if(A&&((V=A.data.current)==null?void 0:V.type)===Me&&a.some(G=>G.id===b.id)){const G=a.findIndex(J=>J.id===b.id),$=a.findIndex(J=>J.id===A.id);if(G!==-1&&$!==-1&&G!==$){const J=[...a],[X]=J.splice(G,1);J.splice($,0,X),j(J)}}if(A&&((q=A.data.current)==null?void 0:q.type)===Ae&&i.some(G=>G.id===b.id)){const G=i.findIndex(J=>J.id===b.id),$=i.findIndex(J=>J.id===A.id);if(G!==-1&&$!==-1&&G!==$){const J=[...i],[X]=J.splice(G,1);J.splice($,0,X),E(J)}}if(A&&((H=A.data.current)==null?void 0:H.type)===Ke&&n.some(G=>G.id===b.id)){const G=n.findIndex(J=>J.id===b.id),$=n.findIndex(J=>J.id===A.id);if(G!==-1&&$!==-1&&G!==$){const J=[...n],[X]=J.splice(G,1);J.splice($,0,X),y(J)}}if(A&&((K=A.data.current)==null?void 0:K.type)===We&&r.some(G=>G.id===b.id)){const G=r.findIndex(J=>J.id===b.id),$=r.findIndex(J=>J.id===A.id);if(G!==-1&&$!==-1&&G!==$){const J=[...r],[X]=J.splice(G,1);J.splice($,0,X),N(J)}}B(T),d(null),c(null),l(a),x(n),h(r),u(i)}function B(T){const{active:b,over:A}=T,F=b.data.current;if((F==null?void 0:F.type)===ct&&A){const P=o.findIndex(z=>Ce(z.columnId)===b.id),R=o.findIndex(z=>Ce(z.columnId)===A.id);if(P!==-1&&R!==-1&&P!==R){const z=[...o],[Y]=z.splice(P,1);z.splice(R,0,Y),f(z)}}}function M(){d(null),c(null),l(a),x(n),h(r)}return{handleDragOver:I,handleDragEnd:m,handleDragStart:k,handleDragCancel:M,sensors:O}}function ie(s){return`${s}-${t.v4()}`}function ke(s,a){const n=t.toTitleCase(s.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Ce(s){return`${ct}-${s}`}function ve(s,a){const n=t.toTitleCase(s.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function An({schemaName:s,tableName:a,columns:n,status:r}){const o=t.useEditorStore(b=>b.sqlGen),i=t.useEditorStore(b=>b.isDevMode),c=t.useEditorStore(b=>b.selectedConnectionId),d=t.useEditorStore(b=>{var A,F;return(F=(A=b.card)==null?void 0:A.queryConfig)==null?void 0:F.metricColumns});t.useEditorStore(b=>{var A,F;return(F=(A=b.card)==null?void 0:A.queryConfig)==null?void 0:F.groupByColumns});const l=t.useEditorStore(b=>b.selectedDatabaseName),x=t.useEditorStore(b=>b.selectedSchemaName),h=t.useEditorStore(b=>b.selectedTableName),u=t.useEditorStore(b=>b.selectedDatamodelId),j=t.useDashboardStore(b=>b.dashboard.aiScopeTables),{addToAIScope:y,removeFromAIScope:N}=t.useDashboardActions(),{addColumnToMetricColumns:f,addColumnToGroupBy:E,setCardSql:p,setRunSql:g,setSqlGen:O,setIsShowingVisual:I}=t.useEditorActions(),{connectionType:k,modelItems:v,selectedDatamodelName:C}=t.useEditorAside();function S(b){var A;if(i){const F=t.createSqlGenConfig(b,o);O(F);const P=(A=v==null?void 0:v.find(z=>z.id===u))==null?void 0:A.name,R=t.getSql(F,t.fmt(s),t.fmt(a),P||"",k,l||"");R&&(p(R),g(!0))}if(!i){if(t.isTextDataType(b.data_type))if(d&&d.length>0){const F={...b,role:"groupby",id:ie(b.column_name),name:b.column_name,type:b.data_type};E(F)}else{const F={...b,role:"metric",id:ie(b.column_name),name:b.column_name,label:ke(b.column_name,"COUNT"),type:b.data_type,aggregate:"COUNT"};f(F)}if(t.isDateDataType(b.data_type)){const F={...b,role:"groupby",id:ie(b.column_name),name:b.column_name,type:b.data_type,label:ve(b.column_name,"month"),granularity:"month"};E(F)}if(t.isNumberDataType(b.data_type)){const F={...b,role:"metric",id:ie(b.column_name),name:b.column_name,label:ke(b.column_name,"SUM"),type:b.data_type,aggregate:"SUM"};f(F)}}}function D(b){b===!0&&(h||C)&&c?(y({connectionId:c,connectionType:k==="S3"||k==="API"?"DuckDb":k||"",databaseName:l||"",schemaName:x||"",tableName:h||"",datamodelName:t.resolveDatamodelName(C),datamodelId:u||""}),t.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(N({connectionId:c||"",connectionType:k||"",tableName:h||"",datamodelName:t.resolveDatamodelName(C),datamodelId:u||"",databaseName:l||"",schemaName:x||""}),t.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function w(){const b=t.getFormattedTableNameForQuery({schemaName:s,tableName:a,modelName:C,connectionType:k,databaseName:l||""});I(!1);const A=k==="MSSQL"?`SELECT top 10 * FROM ${b}`:`SELECT * FROM ${b} LIMIT 10`;p(A),g(!0)}function m(){const b=t.getFormattedTableNameForQuery({schemaName:s,tableName:a,modelName:C,connectionType:k,databaseName:l||""});p(`SELECT COUNT(*) as count FROM ${b}`),g(!0)}function B(){return(j==null?void 0:j.find(b=>b.connectionId===c&&(b.tableName===h||b.datamodelName===C)))!==void 0}function M(b){return i?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>S(b),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(lt,{column:b}),e.jsx("span",{children:b.column_name})]}),e.jsx("div",{onClick:A=>A.stopPropagation(),className:"flex items-center justify-end",children:t.isNumberDataType(b.data_type)&&e.jsx(Dn,{column:b})})]}):e.jsx(Tn,{onClick:S,column:b})}function T(){return e.jsxs(e.Fragment,{children:[e.jsxs(t.Toggle,{title:`${B()?"Remove from":"Add to"} Assistant Scope`,pressed:B(),onPressedChange:D,variant:"outline",className:t.cn("h-9 px-2",{}),children:[e.jsx(t.Plus,{className:t.cn("mr-1 size-4",{"text-green-400":B(),"text-muted-foreground":!B()})}),"AI"]}),e.jsxs(t.Button,{disabled:r!=="Success",onClick:w,size:"sm",variant:"secondary",className:"flex",children:[r!=="Success"?e.jsx(t.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(an,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(t.Button,{disabled:r!=="Success",onClick:m,size:"sm",variant:"secondary",className:"w-full",children:[r!=="Success"?e.jsx(t.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(zt,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-6",children:Array.from({length:3}).map((b,A)=>e.jsx(t.Skeleton,{className:"h-7 w-full"},A))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[i&&e.jsx("div",{className:"mx-2 flex items-center justify-center gap-2",children:T()}),e.jsxs(t.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-2 py-0",children:[e.jsx("div",{className:"flex flex-col gap-1",children:n==null?void 0:n.map(b=>e.jsx("div",{className:t.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:M(b)},b.column_name))}),e.jsx(t.ScrollBar,{orientation:"vertical"}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function Ht({ColumnsComponent:s,type:a}){var me;const n=t.useEditorStore(W=>W.card),r=t.useEditorStore(W=>W.selectedConnectionId),o=t.useDashboardStore(W=>W.showFilters),i=t.useEditorStore(W=>W.selectedDatamodelId),c=t.useEditorStore(W=>W.selectedDatabaseName),d=t.useEditorStore(W=>W.selectedSchemaName),l=t.useEditorStore(W=>W.selectedTableName),x=t.useEditorStore(W=>W.isDevMode),{setSelectedTableName:h,setIsDevMode:u,setCardSql:j}=t.useEditorActions(),{connectionItems:y,modelItems:N,schemaItems:f,databaseItems:E,tableItems:p,columns:g,isConnectionsLoading:O,isModelsLoading:I,isConnectionsError:k,isModelsError:v,isDatabasesLoadingOrFetching:C,isDatabaseError:S,isSchemaLoadingOrFetching:D,isSchemaError:w,isColumnsError:m,isColumnsLoadingOrFetching:B,isTableLoadingOrFetching:M,isTableError:T,connectionType:b,isNonDbConnection:A,refetchDatabases:F,refetchModels:P,refetchSchemas:R,refetchTables:z,refetchColumns:Y,refetchConnections:V,handleConnectionChange:q,handleDatabaseChange:H,handleSchemaChange:K,handleDatamodelChange:G,handleTableChange:$,tableName:J,schemaName:X}=t.useEditorAside(),{data:se,refetch:re}=t.useDashboardCardQuery(n);function le(){return s?s(X,J,g):e.jsx(An,{schemaName:X,tableName:J,columns:g,status:B?"Loading...":m?"Error":"Success"})}function ne(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function te(W){W===!0?se&&(j(se.userSql),setTimeout(()=>{re()},100)):j(""),u(W)}function ce(){if(!r||b==="S3"||b==="API")return null;if(!i||i==="none")return e.jsx(be,{refetch:F,showNone:!0,onChange:H,isError:S,isLoading:C,items:E,value:c||"",title:"Database",type:"combobox"})}function _(){if(r&&!A&&(!c||c==="none")&&(!i||i==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(t.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(t.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(t.Separator,{})})]})}function Q(){if(!r||b==="S3"||b==="API")return null;if(!c||c==="none")return e.jsx(be,{refetch:P,showNone:!0,onChange:G,isError:v,isLoading:I,items:N,value:i||"",title:"Model",type:"combobox"})}function oe(){return!r||b==="S3"||b==="API"||!c||c==="none"?null:e.jsx(be,{refetch:R,onChange:K,isError:w,isLoading:D,items:f,value:d||"",title:"Schema",type:"combobox"})}function de(){function W(){let Z=!1;return b==="API"?(Z=!1,Z):((b==="S3"||r&&c&&c!=="none"&&d)&&(Z=!0),Z)}return W()?e.jsx(be,{refetch:z,onChange:$,isError:T,items:p,isLoading:M,value:l||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:t.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!o}),children:[e.jsxs("section",{className:"space-y-3 px-6 py-4",children:[e.jsx(be,{refetch:V,items:y,title:"Connection",value:r||"",onChange:q,isLoading:O,isError:k,type:"combobox",connectionTooltip:((me=y==null?void 0:y.find(W=>W.id===r))==null?void 0:me.type)||""}),ce(),_(),Q(),oe(),de()]}),le(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:a==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:x,onCheckedChange:te,id:"dev-mode"}),e.jsx(t.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(t.Button,{onClick:ne,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(ln,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function Ut({error:s,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[o,i]=L.useState(!1),c=L.useRef(null),d=L.useRef(!1);function l(){s&&!d.current&&navigator.clipboard.writeText(s)}function x(j){(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),l())}function h(){const j=window.getSelection();if(j&&j.toString().trim()!==""){const y=j.toString();navigator.clipboard.writeText(y),i(!0),d.current=!0,setTimeout(()=>{i(!1),d.current=!1},1e3)}else d.current=!1}function u(){i(!1),d.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 ${a}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(t.CopyButton,{text:s,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:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${n}`,onClick:l,onKeyDown:x,onMouseUp:h,onMouseDown:u,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:s}),o&&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 Yt({sql:s,error:a,onDebugWithAssistant:n}){const r=t.useEditorStore(l=>l.isDevMode),{setIsDevMode:o,setCardSql:i,setRunSql:c}=t.useEditorActions();function d(){o(!r),i(s),setTimeout(()=>{c(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-2",children:[e.jsxs(t.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(Ut,{error:a}),s&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"rounded-md",children:e.jsx(t.CodeHighlighter,{code:s,language:"sql"})})})]}),!r&&s&&e.jsxs(t.Button,{onClick:d,variant:"secondary",size:"sm",children:[e.jsx(Us,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&n&&e.jsxs(t.Button,{onClick:n,size:"sm",variant:"secondary",children:[e.jsx(Zs,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function Kt({sql:s,error:a,onDebugWithAssistant:n}){return e.jsxs(t.HoverCard,{openDelay:a?0:500,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(Ot,{className:"h-4 w-4 text-red-500"}):e.jsx(t.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(t.HoverCardContent,{align:"start",className:"flex w-[600px]",children:e.jsx(Yt,{sql:s,error:a,onDebugWithAssistant:n})})]})}var Qt={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Et=L.createContext&&L.createContext(Qt),Ln=["attr","size","title"];function On(s,a){if(s==null)return{};var n=Bn(s,a),r,o;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(o=0;o<i.length;o++)r=i[o],!(a.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Bn(s,a){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(a.indexOf(r)>=0)continue;n[r]=s[r]}return n}function Le(){return Le=Object.assign?Object.assign.bind():function(s){for(var a=1;a<arguments.length;a++){var n=arguments[a];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(s[r]=n[r])}return s},Le.apply(this,arguments)}function Dt(s,a){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);a&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(s,o).enumerable})),n.push.apply(n,r)}return n}function Oe(s){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?Dt(Object(n),!0).forEach(function(r){Fn(s,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(n)):Dt(Object(n)).forEach(function(r){Object.defineProperty(s,r,Object.getOwnPropertyDescriptor(n,r))})}return s}function Fn(s,a,n){return a=zn(a),a in s?Object.defineProperty(s,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):s[a]=n,s}function zn(s){var a=Pn(s,"string");return typeof a=="symbol"?a:a+""}function Pn(s,a){if(typeof s!="object"||!s)return s;var n=s[Symbol.toPrimitive];if(n!==void 0){var r=n.call(s,a);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(s)}function Wt(s){return s&&s.map((a,n)=>L.createElement(a.tag,Oe({key:n},a.attr),Wt(a.child)))}function ge(s){return a=>L.createElement(Vn,Le({attr:Oe({},s.attr)},a),Wt(s.child))}function Vn(s){var a=n=>{var{attr:r,size:o,title:i}=s,c=On(s,Ln),d=o||n.size||"1em",l;return n.className&&(l=n.className),s.className&&(l=(l?l+" ":"")+s.className),L.createElement("svg",Le({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,c,{className:l,style:Oe(Oe({color:s.color||n.color},n.style),s.style),height:d,width:d,xmlns:"http://www.w3.org/2000/svg"}),i&&L.createElement("title",null,i),s.children)};return Et!==void 0?L.createElement(Et.Consumer,null,n=>a(n)):a(Qt)}function Rn(s){return ge({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(s)}function Xt(s){const{theme:a}=t.useTheme(),n=t.useDashboardStore(f=>f.theme),r=t.useEditorStore(f=>f.frame),o=t.useEditorStore(f=>f.card),i=t.useEditorStore(f=>f.activeTabCardId),c=t.Le(),{refetch:d}=t.useDashboardCardQuery(o),{updateCardTab:l,setRunSql:x}=t.useEditorActions(),h=L.useRef(),u=L.useRef({}),j=r.cards.find(f=>f.id===i),y=L.useCallback(()=>{let f="";return s==="python"&&(f=(j==null?void 0:j.python)||t.PYTHON_DEFAULT_CODE),s==="sql"&&(f=(j==null?void 0:j.sql)||""),f},[s,j]);L.useEffect(()=>{if(i&&o.id&&o.id!==i){if(h.current&&c){const f=h.current.getModel();f&&(u.current[o.id]=f);let E=u.current[i];if(!E){const p=y();E=c.editor.createModel(p,s),u.current[i]=E}h.current.setModel(E)}l(i,o),x(!0)}},[i,o,l,c,x,s,y]),L.useEffect(()=>{if(!c)return;const f=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",E=n==="system"?f:n;c.editor.defineTheme("default",{base:E==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":E==="light"?"#ffffff":t.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),L.useEffect(()=>{const f=h.current;f&&c&&o&&f.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return d(),!1})},[c,d,o]);function N(f,E){if(h.current=f,!u.current[o.id]){const p=f.getModel(),g=y();u.current[o.id]=p||(E==null?void 0:E.editor.createModel(g,s))||f.getModel()}f.setModel(u.current[o.id])}return{handleEditorDidMount:N}}function qn(){const s=t.useEditorStore(c=>c.card.sql),a=t.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=t.useEditorActions(),{handleEditorDidMount:o}=Xt("sql");function i(c){n(c),t.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!s&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(t.Ft,{theme:"default",className:"pt-3",onChange:i,value:s||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:o})]})}function _n(){const s=t.useEditorStore(o=>o.card.python),{setCardPython:a}=t.useEditorActions(),{handleEditorDidMount:n}=Xt("python");function r(o){a(o)}return e.jsx(t.Ft,{className:"pt-3",theme:"default",onChange:r,value:s||t.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function Gn({jsonString:s}){return e.jsx(t.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:s,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function $n(){const s=t.useQueryClient(),[a,n]=L.useState(!1),[r,o]=L.useState(!1);t.useEditorStore(z=>z.frame);const i=t.useEditorStore(z=>z.card);t.useEditorStore(z=>z.isShowingVisual),t.useEditorStore(z=>z.selectedConnectionId),t.useEditorStore(z=>z.tempQueryData),t.useEditorStore(z=>z.selectedDatabaseName),t.useEditorStore(z=>z.selectedDatamodelId),t.useEditorStore(z=>z.selectedSchemaName);const c=t.useEditorStore(z=>z.showAIDialog);t.useEditorStore(z=>z.selectedTableName);const d=t.useEditorStore(z=>{var Y;return(Y=z==null?void 0:z.card)==null?void 0:Y.sql}),l=t.useEditorStore(z=>{var Y;return(Y=z==null?void 0:z.card)==null?void 0:Y.python}),{sheetFilterValues:x}=t.useSheetFilterValues(),{setCardCustomCfg:h,setQueryResultColumns:u,setCardSql:j,setTempQueryData:y,setPythonStdOut:N,setCardPreferences:f,setCardType:E,setCardPython:p,runAssistant:g,setShowAIDialog:O}=t.useEditorActions();t.useEditorStore(z=>z.onSave),t.useEditorStore(z=>z.onClose),t.useEditorStore(z=>z.actions.setSqlGen);const I=t.useEditorStore(z=>z.runSql),k=t.useEditorStore(z=>z.actions.setRunSql),v=t.useEditorStore(z=>z.actions.setIsSqlRunning),{data:C,isLoading:S,isFetching:D,isSuccess:w,isError:m,error:B,queryKey:M,refetch:T,errorMessage:b}=t.useDashboardCardQuery(i);L.useEffect(()=>{if(C&&(C.rowLimitExceeded&&t.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),N((C==null?void 0:C.output)||""),C.records.length>0)){const{dimensionKeys:z}=t.getKeys(C.records);u(z)}},[C,u,N]),L.useEffect(()=>{(S||D)&&v(!0),(m||w)&&v(!1),m&&(u([]),N(""))},[S,D,C,N,m,w,v,u,B]),L.useEffect(()=>{I&&(s.getQueryData(M)||T(),k(!1))},[I,T,k,M,s]);async function A(){const z=`Can you help me debug this query in the current table scope?
|
|
351
|
+
*/const qt=t.createLucideIcon("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);function it(s){var a;return{...s,sheets:(a=s==null?void 0:s.sheets)==null?void 0:a.map(n=>{var r;return{...n,frames:(r=n.frames)==null?void 0:r.map(o=>{var i;return{...o,cards:(i=o.cards)==null?void 0:i.map(c=>_t(c))}})}})}}function _t(s){return{...s,customCfg:yn(s.customCfg),data:[]}}function yn(s){var a,n;return s?{...s,data:{...s==null?void 0:s.data,labels:[],datasets:(n=(a=s==null?void 0:s.data)==null?void 0:a.datasets)==null?void 0:n.map(r=>({...r,data:[]}))}}:null}async function bn(s,a,n,r){if(!r)return null;const o=JSON.stringify(a);return await t.postRequest("https://semaphor.cloud/api/v1/lens",r,{name:s,template:o,filterValues:n,operation:"create"})}async function Ye(s,a){if(!a)return null;const{id:n,template:r,filterValues:o,isDefault:i,shared:c}=s;return await t.postRequest("https://semaphor.cloud/api/v1/lens",a,{lensId:n,template:r,filterValues:o,isDefault:i,shared:c,operation:"update"})}async function vn(s,a){return a?await t.postRequest("https://semaphor.cloud/api/v1/lens",a,{operation:"delete",lensId:s}):null}function Nn(){const[s,a]=L.useState(""),[n,r]=L.useState(!1),o=t.useDashboardStore(p=>p.lenses),{setLenses:i,setSelectedLensId:c}=t.useDashboardActions(),[d,l]=L.useState(!1),[x,h]=L.useState(!1),u=t.useDashboardStore(p=>p.dashboard),j=t.useDashboardStore(p=>p.filterValues),{authToken:y}=t.useSemaphorContext();async function S(){l(!0);const p=it(u),D=await bn(s,p,j,y==null?void 0:y.accessToken);D&&(i([...o||[],D]),c(D.id),h(!1)),l(!1)}return e.jsxs(t.Dialog,{open:x,onOpenChange:h,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Lens"]})}),e.jsxs(t.DialogContent,{className:"sm:max-w-[425px]",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Create Lens"}),e.jsx(t.DialogDescription,{children:"Lenses are private by default and are only visible to you."})]}),e.jsx("div",{className:"grid gap-4 py-4",children:e.jsxs("div",{className:"grid grid-cols-8 items-center gap-4",children:[e.jsx(t.Label,{className:"text-right",children:"Name"}),e.jsx(t.Input,{value:s,onChange:p=>{a(p.target.value)},id:"name",className:"col-span-7 focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0"})]})}),n&&e.jsx("p",{className:"text-sm",children:"The lens name already exists. Use a differnet name."}),e.jsx(t.DialogFooter,{children:e.jsx(t.Button,{size:"sm",variant:"outline",type:"submit",onClick:S,disabled:d,children:d?"Creating...":"Add"})})]})]})}function Cn(){const[s,a]=L.useState(!1),n=t.useDashboardStore(h=>h.lenses),r=t.useDashboardStore(h=>h.selectedLensId),{setLenses:o,setSelectedLensId:i}=t.useDashboardActions(),{authToken:c}=t.useSemaphorContext();async function d(h){i(h)}async function l(h){if(await vn(h,c==null?void 0:c.accessToken)){const j=n==null?void 0:n.filter(y=>y.id!==h);o(j||[]),i("original")}}async function x(h){const u=n==null?void 0:n.map(S=>S.id===h.id?{...S,isDefault:!h.isDefault}:{...S,isDefault:!1});o(u||[]);const j={...h,isDefault:!h.isDefault};await Ye(j,c==null?void 0:c.accessToken);const y=n==null?void 0:n.find(S=>S.isDefault);if(y&&y.id!==h.id){const S={...y,isDefault:!1};await Ye(S,c==null?void 0:c.accessToken)}}return e.jsxs(t.DropdownMenu,{open:s,onOpenChange:a,children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Lenses",className:"h-7 p-2",children:e.jsx(Xs,{className:"h-4 w-4"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",className:"w-60",children:[e.jsx(t.DropdownMenuLabel,{className:"px-3",children:"Lenses"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsxs(t.DropdownMenuRadioGroup,{value:r,onValueChange:d,children:[e.jsx(t.DropdownMenuRadioItem,{value:"original",children:"Original"}),n==null?void 0:n.map(h=>e.jsxs(t.DropdownMenuRadioItem,{className:"group flex justify-between gap-2",value:h.id,children:[e.jsx("p",{children:h.name}),e.jsxs("span",{className:"flex items-center gap-3",children:[e.jsx(t.House,{onClick:u=>{u.preventDefault(),x(h)},className:t.cn("size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",{invisible:!h.isDefault,"text-green-500":h.isDefault}),strokeWidth:1.5}),e.jsx(t.Cross2Icon,{onClick:u=>{u.preventDefault(),l(h.id)},className:"invisible size-3.5 text-muted-foreground hover:cursor-pointer hover:text-foreground group-hover:visible",strokeWidth:1.5})]})]},h.id))]})]})]})}function Gt(){var i;const s=t.useDashboardStore.getState().authToken,a=t.useDashboardStore.getState().theme,n=t.useDashboardStore.getState().filterValues,r=(i=t.useDashboardStore.getState().dashboard)==null?void 0:i.title,o=t.useDashboardStore.getState().selectedSheetId;return{authToken:s,theme:a||"light",filterValues:n,dashboardTitle:r||"",selectedSheetId:o||""}}async function $t(){const s=t.useDashboardStore.getState().isDownloadingPdf,{authToken:a,theme:n,filterValues:r,dashboardTitle:o,selectedSheetId:i}=Gt();if(s)return;const c=new URLSearchParams;c.set("token",(a==null?void 0:a.accessToken)||""),c.set("theme",n),c.set("filterValues",JSON.stringify(r)),c.set("selectedSheetId",i||"");const d=`https://semaphor.cloud/api/v1/generate-pdf?params=${encodeURIComponent(c.toString())}`;t.useDashboardStore.setState({isDownloadingPdf:!0});const h=(await(await fetch(d,{method:"GET",headers:{Authorization:`Bearer ${a==null?void 0:a.accessToken}`}})).json()).url,u=document.createElement("a");u.href=h;const j=`${o}-${new Date().toISOString()}.pdf`;u.download=j,u.click(),t.useDashboardStore.setState({isDownloadingPdf:!1})}function Sn({iconClassName:s}){const{authToken:a}=t.useSemaphorContext();t.useDashboardStore(o=>{var i;return(i=o.dashboard)==null?void 0:i.title}),t.useDashboardStore(o=>o.theme),t.useDashboardStore(o=>o.filterValues);const n=t.useDashboardStore(o=>o.isDownloadingPdf);async function r(){await $t()}return e.jsx(t.IconButton,{tooltip:"Download PDF",className:"h-7 p-2",onClick:r,children:n?e.jsx(t.LoaderCircle,{className:t.cn("size-3.5 animate-spin",s)}):e.jsx(t.Download,{className:t.cn("size-4",s)})})}function ae({defaultValue:s,label:a,options:n,value:r,onValueChange:o,className:i,icon:c,showPlaceholderLabel:d=!0}){return e.jsxs(t.Select,{defaultValue:s,value:r,onValueChange:o,children:[e.jsx(t.SelectTrigger,{className:t.cn("w-full focus:ring-0 focus:ring-offset-0",i),children:e.jsxs("div",{className:"flex items-center gap-2",children:[c&&e.jsx("span",{children:c}),d&&e.jsx(t.SelectValue,{placeholder:a})]})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:a}),n.map(l=>e.jsx(t.SelectItem,{value:l.value,children:l.label},l.value))]})})]})}const wt=[{value:"daily",label:"Daily"},{value:"weekly",label:"Weekly"},{value:"biweekly",label:"Bi-Weekly"},{value:"monthly",label:"Monthly"}];function Jt({triggerButtonClassName:s}){const{data:a,handleScheduleSubscription:n,handleDeleteSubscription:r,status:o,error:i,isDeleting:c}=wn(),[d,l]=L.useState(""),[x,h]=L.useState(wt[0].value),[u,j]=L.useState("06:00"),[y,S]=L.useState("");return e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Schedule Dashboard",className:t.cn("h-7 p-2",s),children:e.jsx(t.Clock,{className:"size-4"})})}),e.jsx(t.PopoverContent,{align:"end",className:"w-80",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Schedule Subscription"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribe to receive dashboard via email"})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"email",children:"Email"}),e.jsx(t.Input,{id:"email",value:d,onChange:p=>l(p.target.value),className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"subject",children:"Subject"}),e.jsx(t.Input,{id:"subject",placeholder:"Monthly Sales Report",value:y,onChange:p=>{S(p.target.value.replace(/[^a-zA-Z0-9\s-_]/g,""))},className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"frequency",children:"Frequency"}),e.jsx(ae,{className:"col-span-2 h-8",label:"Select Frequency",options:wt,value:x,onValueChange:p=>h(p)})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"time",children:"Time"}),e.jsx(t.Input,{id:"time",type:"time",value:u,onChange:p=>j(p.target.value),className:`col-span-2 h-8 ${t.removeRing}`})]}),e.jsx("div",{className:"mt-2 flex justify-end",children:e.jsxs(t.Button,{onClick:async()=>{await n({email:d,frequency:x,time:u,subject:y}),j("00:00"),l(""),S("")},className:"h-8 p-2",disabled:o==="loading"||!d,children:[o==="loading"&&e.jsx(t.LoaderCircle,{className:"mr-2 size-4 animate-spin"}),o==="success"&&e.jsx(t.Check,{className:"mr-2 size-4"}),o==="error"&&e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{children:e.jsx(Bt,{className:"mr-2 size-4 text-destructive"})}),e.jsx(t.TooltipContent,{children:e.jsx("p",{children:i})})]}),"Schedule"]})}),a&&a.length>0&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.Separator,{className:"my-2"}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Subscriptions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Active email subscriptions"})]}),t.isDevEnv]})}),e.jsx("div",{className:"grid gap-2",children:a==null?void 0:a.map(p=>e.jsxs("div",{className:"group grid grid-cols-5 gap-3",children:[e.jsx("div",{className:"col-span-3 text-sm",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"boder-border rounded-md border bg-muted px-2 py-1",children:[t.titleCase(p.frequency)," "]}),e.jsx(t.Label,{children:p.time})]})}),e.jsxs("div",{className:"col-span-2 flex items-center justify-end gap-4",children:[e.jsx(kt,{tooltip:`Next Run: ${new Date(p.nextRun).toLocaleString()} ${p.timezone}`,children:e.jsx(qs,{className:"size-3.5"})}),e.jsx(kt,{tooltip:`${p.endUserEmail}`,children:e.jsx(on,{className:"size-3.5"})}),c===p.id?e.jsx(t.LoaderCircle,{className:"size-3.5 animate-spin"}):e.jsx(t.Trash2,{onClick:()=>r(p.id),className:"size-3.5 cursor-pointer"})]})]},p.id))})]})]})]})})]})})}const kt=({children:s,tooltip:a})=>e.jsx(t.TooltipProvider,{delayDuration:0,children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:s}),e.jsx(t.TooltipContent,{children:a})]})});function wn(){const[s,a]=L.useState("idle"),[n,r]=L.useState(""),[o,i]=L.useState(null),c=t.useDashboardStore(v=>v.authToken),d=t.useDashboardStore(v=>v.dashboard.id),l=t.useDashboardStore(v=>v.dashboard.title),{endUserId:x}=t.getTenantAndEndUserId((c==null?void 0:c.accessToken)||""),h="https://semaphor.cloud/api/v1/subscriptions/get",u={dashboardId:d,endUserId:x},{data:j,isLoading:y,isError:S,isFetching:p,refetch:D}=t.useQuery({queryKey:["subscriptions",d,x],queryFn:()=>t.getRequest(h,(c==null?void 0:c.accessToken)||"",u),enabled:!!(c!=null&&c.accessToken)&&!!d&&!!x});async function f({email:v,subject:O,frequency:E,time:b}){const{authToken:C,...w}=Gt(),T=Intl.DateTimeFormat().resolvedOptions().timeZone,k={email:v,frequency:E,time:b,timezone:T,endUserId:x,endUserEmail:v,subject:O||l||"Scheduled Dashboard",dashboardId:d,dashboardParams:w};a("loading");const m="https://semaphor.cloud/api/v1/subscriptions/create";try{const B=await t.postRequestRegular(m,(C==null?void 0:C.accessToken)||"",{...k});a("success"),r(""),D(),setTimeout(()=>{a("idle")},2e3)}catch(B){console.error(B),a("error"),r(B.message)}}async function g(v){const O="https://semaphor.cloud/api/v1/subscriptions/delete";i(v);try{await t.postRequestRegular(O,(c==null?void 0:c.accessToken)||"",{id:v}),D(),setTimeout(()=>{i(null)},2e3)}catch(E){console.error(E),i(null),a("error"),r(E.message)}}return{data:j,isLoading:y,isFetching:p,isError:S,isDeleting:o,refetch:D,handleScheduleSubscription:f,handleDeleteSubscription:g,status:s,error:n}}function kn(){const{authToken:s}=t.useSemaphorContext();t.useDashboardStore(m=>m.theme);const a=t.useDashboardStore(m=>m.lenses),n=t.useDashboardStore(m=>m.selectedLensId),r=a==null?void 0:a.find(m=>m.id===n),o=t.useDashboardStore(m=>m.dashboard);t.useDashboardStore(m=>m.selectedSheetId);const i=t.useDashboardStore(m=>m.isDashboardEditing),c=t.useEditorStore(m=>m.card),d=t.useEditorStore(m=>m.selectedConnectionId),[l,x]=L.useState(!1),h=t.useDashboardStore(m=>m.filterValues),u=t.useDashboardStore(m=>m.isVisualEditing),j=t.useDashboardStore(m=>m.showFilters);t.useDashboardStore(m=>m.showDashboardJSON);const y=t.useDashboardStore(m=>m.onSaveFunction),S=t.useDashboardStore(m=>m.actions.setShowFilters),{addFrame:p,setSelectedFrameId:D}=t.useDashboardStore(m=>m.actions),{getSelectedSheet:f,setIsDashboardEditing:g,setShowDashboardJSON:v}=t.useDashboardStore(m=>m.actions),O=f(),{tenantId:E,endUserId:b}=L.useMemo(()=>t.getTenantAndEndUserId(s==null?void 0:s.accessToken),[s==null?void 0:s.accessToken]),C=L.useMemo(()=>E||b,[E,b]),w=()=>{if(!i||!O)return;const m={dataSource:c.dataSource,mode:"explorer",connectionId:d,id:t.v4(),title:"Title",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[]},B={id:t.v4(),cards:[m],activeCardId:m.id};p(O.id,B),D(B.id)},T=()=>{g(!0)};async function k(){if(x(!0),!n||!r)return;const m=it(o),B=JSON.stringify(m),A={...r,template:B,filterValues:h};await Ye(A,s==null?void 0:s.accessToken),t.ue.success("Lens saved"),y==null||y(m),x(!1)}return u?null:e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b py-1 pl-3 pr-2",role:"dashboard-controls",children:[!u&&e.jsx("div",{className:"flex items-center gap-3",children:e.jsx(t.Label,{children:r==null?void 0:r.name})}),e.jsxs("div",{className:"flex gap-2",children:[!1,!u&&e.jsx(Sn,{}),!u&&e.jsx(Jt,{}),i&&!u&&C&&e.jsx(Nn,{}),!u&&C&&e.jsx(Cn,{}),i&&!u&&e.jsxs(t.Button,{variant:"secondary",className:"h-7 p-2",size:"sm",disabled:!i,onClick:w,children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),"Frame"]}),!i&&e.jsx(t.Button,{variant:"ghost",className:"h-7 p-2",onClick:T,size:"sm",children:e.jsx(t.Pencil,{className:"h-4 w-4"})}),i&&!u&&e.jsx(t.IconButton,{className:"h-7 p-2",onClick:()=>{g(!1),v(!1)},children:e.jsx(t.Cross2Icon,{className:"h-4 w-4"})}),i&&!u&&C&&e.jsx(t.Button,{className:"h-7 p-2",variant:"ghost",disabled:l,onClick:k,size:"sm",children:e.jsx(xn,{className:"h-4 w-4"})}),!j&&!u&&i&&e.jsx(t.Button,{className:"h-7 p-2",variant:"ghost",onClick:()=>S(!0),size:"sm",children:e.jsx(t.Filter,{className:"h-4 w-4"})}),!u&&i&&!1,!u&&!1]})]})}function En({name:s,items:a,value:n,onChange:r,isLoading:o,isError:i,refetch:c,className:d,icon:l,showNone:x=!1}){const h=he.useRef(null),[u,j]=he.useState(!1),[y,S]=he.useState("100%"),p=x?[...a||[],{id:"none",name:"None"}]:a;he.useLayoutEffect(()=>{h.current&&S(h.current.offsetWidth)},[]);function D(){var g;return o?"Loading...":i?"Error":n?(g=a==null?void 0:a.find(v=>v.id===n))==null?void 0:g.name:`Select ${s}`}function f(g,v){r(v),j(!1)}return e.jsxs(t.Popover,{open:u,onOpenChange:j,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{ref:h,variant:"outline",role:"combobox","aria-expanded":u,className:t.cn("flex h-9 w-full justify-between",d),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[l&&e.jsx("div",{className:"mr-2",children:l}),e.jsx("span",{className:"max-w-[150px] overflow-hidden truncate text-ellipsis whitespace-nowrap",children:D()})]}),e.jsx(t.ChevronDown,{className:"size-4 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-full p-0",style:{minWidth:y},children:e.jsxs(t.Command,{children:[e.jsxs("div",{className:"flex h-9 items-center justify-between border-b pr-1",children:[e.jsx(t.CommandInput,{className:"h-9",placeholder:"Search..."}),e.jsx(t.IconButton,{className:"h-7",onClick:c,children:e.jsx(zt,{className:t.cn("size-3.5 opacity-50",o&&"animate-spin")})})]}),e.jsxs(t.CommandList,{children:[e.jsxs(t.CommandEmpty,{children:["No ",s==null?void 0:s.toLowerCase()," found."]}),e.jsx(t.CommandGroup,{children:p==null?void 0:p.map(g=>e.jsx(t.CommandItem,{className:"overflow-x-auto",value:g.name,onSelect:v=>f(v,g.id),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Check,{className:t.cn("size-4",n===g.id?"opacity-100":"opacity-0")}),e.jsx("div",{title:g.name,children:g.name})]})},g.id))})]})]})})]})}function be({title:s,items:a,value:n,isLoading:r,isError:o,refetch:i,onChange:c,showNone:d=!1,className:l,disabled:x=!1,type:h="combobox"}){const u=r?"Loading...":o?"Error":n;function j(){if(s==="Connection")return e.jsx(mn,{className:"size-4"});if(s==="Database")return e.jsx(t.Database,{className:"size-4"});if(s==="Schema")return e.jsx(un,{className:"size-4"});if(s==="Table")return e.jsx(ze,{className:"size-4"});if(s==="Model")return e.jsx(zs,{className:"size-4"})}function y(){return e.jsxs(t.Select,{disabled:x,value:u,onValueChange:c,children:[e.jsx(t.SelectTrigger,{className:t.cn("h-9 w-full border-muted focus:ring-1 focus:ring-offset-0",l),children:e.jsx(t.SelectValue,{placeholder:r?"Loading...":o?"Error":`Select ${s}`})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[r?e.jsx(t.SelectLabel,{children:"Loading..."}):e.jsxs(t.SelectLabel,{className:"flex items-center justify-between gap-2",children:[s,e.jsx(zt,{className:t.cn("mr-1 size-3 cursor-pointer text-muted-foreground hover:text-foreground",r&&"animate-spin"),onClick:i})]}),e.jsxs(e.Fragment,{children:[d&&e.jsx(t.SelectItem,{value:"none",children:"None"},"none"),a&&a.map((p,D)=>e.jsx(t.SelectItem,{value:p.id,children:p.name},D))]}),(r||o)&&e.jsx(t.SelectItem,{value:u,children:u})]})})]})}function S(){return e.jsx(En,{icon:j(),items:a,value:u,onChange:c||(()=>{}),isLoading:r,isError:o,refetch:i,name:s,showNone:d})}return e.jsx(t.TooltipProvider$1,{delayDuration:0,children:e.jsx("div",{className:"flex items-center gap-2",children:h==="select"?y():S()})})}function Dn({column:s}){const[a,n]=L.useState(!1),r=t.useEditorStore(p=>p.selectedTableName),o=t.useEditorStore(p=>p.selectedSchemaName),i=t.useEditorStore(p=>p.selectedDatabaseName),c=t.useEditorStore(p=>p.selectedDatamodelId),d=t.useEditorStore(p=>p.sqlGen),{modelItems:l,connectionType:x}=t.useEditorAside(),h=t.useEditorStore(p=>p.actions.setSqlGen),u=t.useEditorStore(p=>p.actions.setCardSql),j=t.useEditorStore(p=>p.actions.setRunSql);function y(p,D){var O;const f=t.createSqlGenConfig(p,d,D),g=(O=l==null?void 0:l.find(E=>E.id===c))==null?void 0:O.name;h(f);const v=t.getSql(f,t.fmt(o||""),t.fmt(r),g||"",x,i||"");v&&(u(v),j(!0)),n(!1)}function S(){return e.jsxs("ul",{className:"text-xs",children:[e.jsx("li",{onClick:()=>y(s,"COUNT"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Count"}),e.jsx("li",{onClick:()=>y(s,"AVG"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Avg"}),e.jsx("li",{onClick:()=>y(s,"SUM"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Sum"}),e.jsx("li",{onClick:()=>y(s,"MAX"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Max"}),e.jsx("li",{onClick:()=>y(s,"MIN"),className:"cursor-pointer p-1 px-3 transition-colors hover:bg-muted",children:"Min"})]})}return e.jsxs(t.HoverCard,{openDelay:0,open:a,onOpenChange:n,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx(t.EllipsisVertical,{className:"invisible size-3.5 cursor-pointer text-foreground/40 group-hover:visible"})}),e.jsx(t.HoverCardContent,{align:"center",className:"w-20 rounded-md p-0 shadow-none",children:S()})]})}function lt({column:s}){return e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger$1,{className:"shrink-0",asChild:!0,children:t.isTextDataType(s.data_type)?e.jsx(t.TextIcon,{className:"size-3 text-muted-foreground"}):t.isNumberDataType(s.data_type)?e.jsx(nt,{className:"size-3 text-muted-foreground"}):t.isDateDataType(s.data_type)?e.jsx(t.Calendar,{className:"size-3 text-muted-foreground"}):t.isBooleanDataType(s.data_type)?e.jsx(Vt,{className:"size-3 text-muted-foreground"}):s.data_type.startsWith("json")?e.jsx(Ps,{className:"size-3 text-muted-foreground"}):e.jsx(t.QuestionMarkIcon,{className:"size-3 text-muted-foreground"})}),e.jsx(t.TooltipContent,{children:e.jsx("p",{className:"text-xs",children:s.data_type})})]})}function Ve({column:s,className:a}){return e.jsxs("div",{className:t.cn("flex min-h-8 grow items-center space-x-2 px-2 text-sm",a),children:[e.jsx(lt,{column:s}),e.jsx("span",{children:s.column_name})]})}function Tn({id:s,children:a,type:n="column"}){const{attributes:r,listeners:o,setNodeRef:i,transform:c}=t.useDraggable({id:s,data:{type:n}}),d=c?{translate:t.CSS.Translate.toString(c),transform:t.CSS.Transform.toString(c)}:void 0;return e.jsx("div",{ref:i,style:d,...o,...r,children:a})}function In({onClick:s,column:a}){const n=t.useDndStore(h=>h.activeId),r=t.useEditorStore(h=>{var u;return(u=h.card.queryConfig)==null?void 0:u.groupByColumns}),o=t.useEditorStore(h=>{var u;return(u=h.card.queryConfig)==null?void 0:u.metricColumns}),i=t.useEditorStore(h=>{var u;return(u=h.card.queryConfig)==null?void 0:u.filterColumns});function c(h){return d(h)||l(h)||x(h)}function d(h){return r==null?void 0:r.some(u=>u.name===h.column_name)}function l(h){return o==null?void 0:o.some(u=>u.name===h.column_name)}function x(h){return i==null?void 0:i.some(u=>u.name===h.column_name)}return e.jsxs("div",{onClick:()=>s(a),className:t.cn("relative grow overflow-x-hidden overflow-y-hidden rounded-md active:border active:border-dashed active:border-muted-foreground",{"bg-muted-foreground/10":c(a)}),children:[n===a.column_name&&e.jsx(t.DragOverlay,{children:e.jsx(Ve,{column:a,className:"rounded-md border-2 border-dashed border-muted-foreground bg-muted shadow-md"})}),n===a.column_name&&e.jsx("div",{className:"absolute inset-0",children:n===a.column_name&&e.jsx(Ve,{column:a})}),e.jsx(Tn,{id:a.column_name,type:"column",children:e.jsx(Ve,{column:a})})]})}const qe={id:"__placeholder__",role:"groupby",type:"string"},_e={id:"__placeholder__",role:"groupby",type:"string"},Ge={id:"__placeholder__",role:"metric",type:"number"},$e={name:"Filter",id:"__placeholder__",role:"filter",type:"string"},Ht={id:"__placeholder__"},xe="droppable-group-by",pe="droppable-metrics",fe="droppable-pivot-by",Ae="sortable-group-by",Ke="sortable-metrics",Me="sortable-pivot-by",Qe="droppable-filters",We="sortable-filters",ct="sortable-order-by";function An(){const s=t.useDndStore(I=>I.insertIndex),a=t.useEditorStore(I=>{var N;return((N=I.card.queryConfig)==null?void 0:N.groupByColumns)||[]}),n=t.useEditorStore(I=>{var N;return((N=I.card.queryConfig)==null?void 0:N.metricColumns)||[]}),r=t.useEditorStore(I=>{var N;return((N=I.card.queryConfig)==null?void 0:N.filterColumns)||[]}),o=t.useEditorStore(I=>{var N;return((N=I.card.queryConfig)==null?void 0:N.orderBy)||[]}),i=t.useEditorStore(I=>{var N;return((N=I.card.queryConfig)==null?void 0:N.pivotColumns)||[]}),{setInsertIndex:c,setActiveId:d,setPreviewGroupByColumns:l,setPreviewMetricColumns:x,setPreviewFilterColumns:h,setPreviewPivotColumns:u}=t.useDndActions(),{setGroupByColumns:j,setMetricColumns:y,setFilterColumns:S,setOrderByColumns:p,setPivotByColumns:D}=t.useEditorActions(),{columns:f}=t.useDataColumns(),{formattedTableName:g}=t.useEditorAside(),v=t.useSensors(t.useSensor(t.MouseSensor,{activationConstraint:{distance:1}})),O=I=>{var F;const{active:N,over:M}=I;if(((F=N.data.current)==null?void 0:F.type)==="column"&&M){const P=M.id,V=f.find(q=>q.column_name===N.id);if(!V)return;const z=t.isNumberDataType(V.data_type),Y=t.isTextDataType(V.data_type),R=t.isDateDataType(V.data_type);if(Y||R){if(a.some(H=>H.id===P)){const H=a.findIndex(G=>G.id===P);c(H);const K=a.filter(G=>G.id!==qe.id);K.splice(H,0,qe),l(K)}else if(M.id===xe){c(a.length);const H=[...a,qe];l(H),x(n),h(r)}}if(Y||R){if(i.some(H=>H.id===P)){const H=i.findIndex(G=>G.id===P);c(H);const K=i.filter(G=>G.id!==_e.id);K.splice(H,0,_e),u(K)}else if(M.id===fe){c(i.length);const H=[...i,_e];u(H),l(a),x(n),h(r)}}if(z||Y){if(n.some(H=>H.id===P)){console.log("isOverMetricSortable",P);const H=n.findIndex(G=>G.id===P);c(H);const K=n.filter(G=>G.id!==Ge.id);K.splice(H,0,Ge),x(K)}else if(M.id===pe){c(n.length);const H=[...n,Ge];x(H),h(r),l(a),u(i)}}if(b(V)){if(r.some(H=>H.id===P)){const H=r.findIndex(G=>G.id===P);c(H);const K=r.filter(G=>G.id!==$e.id);K.splice(H,0,$e),h(K)}else if(M.id===Qe){c(r.length);const H=[...r,$e];h(H),x(n),l(a),u(i)}}}else l(a),x(n),h(r),u(i)};function E(I){d(I.active.id),c(null),l(a),x(n),h(r),u(i)}function b(I){return!r.some(N=>N.name===I.column_name)}function C(I,N="SUM"){const{column_name:M,data_type:F}=I,P=[...n],V=s!==null?s:n.length,z={...I,id:ie(M),name:M,label:ke(M,N),type:F,role:"metric",aggregate:N};P.splice(V,0,z),y(P)}function w(I){const N=t.isTextDataType(I.data_type);t.isDateDataType(I.data_type);const M=[...i],F=s!==null?s:i.length;let P;N?P={...I,id:ie(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:P={...I,id:ie(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Ne(I.column_name,"month"),granularity:"month"},M.splice(F,0,P),D(M)}function T(I){const N=t.isTextDataType(I.data_type);t.isDateDataType(I.data_type);const M=[...a],F=s!==null?s:a.length;let P;N?P={...I,id:ie(I.column_name),name:I.column_name,type:I.data_type,role:"groupby"}:P={...I,id:ie(I.column_name),name:I.column_name,type:I.data_type,role:"groupby",label:Ne(I.column_name,"month"),granularity:"month"},M.splice(F,0,P),j(M)}function k(I){const N=[...r],M=s!==null?s:r.length,F={...I,id:ie(I.column_name),name:I.column_name,type:I.data_type,sql:t.getDefaultFilterSql(I.data_type,g,t.fmt(I.column_name)),role:"filter"};N.splice(M,0,F),S(N)}function m(I){var P,V,z,Y,R,q,H,K;const{active:N,over:M}=I,F=N.data.current;if((F==null?void 0:F.type)==="column"&&M){const G=f.find(se=>se.column_name===N.id);if(!G)return;const $=t.isNumberDataType(G.data_type),J=t.isTextDataType(G.data_type),X=t.isDateDataType(G.data_type);(J||X)&&(M.id===xe||((P=M.data.current)==null?void 0:P.type)===Ae)&&T(G),(J||X)&&(M.id===fe||((V=M.data.current)==null?void 0:V.type)===Me)?w(G):($||J)&&(M.id===pe||((z=M.data.current)==null?void 0:z.type)===Ke)?($&&C(G),J&&C(G,"COUNT")):b(G)&&(M.id===Qe||((Y=M.data.current)==null?void 0:Y.type)===We)&&k(G)}if(M&&((R=M.data.current)==null?void 0:R.type)===Ae&&a.some(G=>G.id===N.id)){const G=a.findIndex(J=>J.id===N.id),$=a.findIndex(J=>J.id===M.id);if(G!==-1&&$!==-1&&G!==$){const J=[...a],[X]=J.splice(G,1);J.splice($,0,X),j(J)}}if(M&&((q=M.data.current)==null?void 0:q.type)===Me&&i.some(G=>G.id===N.id)){const G=i.findIndex(J=>J.id===N.id),$=i.findIndex(J=>J.id===M.id);if(G!==-1&&$!==-1&&G!==$){const J=[...i],[X]=J.splice(G,1);J.splice($,0,X),D(J)}}if(M&&((H=M.data.current)==null?void 0:H.type)===Ke&&n.some(G=>G.id===N.id)){const G=n.findIndex(J=>J.id===N.id),$=n.findIndex(J=>J.id===M.id);if(G!==-1&&$!==-1&&G!==$){const J=[...n],[X]=J.splice(G,1);J.splice($,0,X),y(J)}}if(M&&((K=M.data.current)==null?void 0:K.type)===We&&r.some(G=>G.id===N.id)){const G=r.findIndex(J=>J.id===N.id),$=r.findIndex(J=>J.id===M.id);if(G!==-1&&$!==-1&&G!==$){const J=[...r],[X]=J.splice(G,1);J.splice($,0,X),S(J)}}B(I),d(null),c(null),l(a),x(n),h(r),u(i)}function B(I){const{active:N,over:M}=I,F=N.data.current;if((F==null?void 0:F.type)===ct&&M){const P=o.findIndex(z=>Se(z.columnId)===N.id),V=o.findIndex(z=>Se(z.columnId)===M.id);if(P!==-1&&V!==-1&&P!==V){const z=[...o],[Y]=z.splice(P,1);z.splice(V,0,Y),p(z)}}}function A(){d(null),c(null),l(a),x(n),h(r)}return{handleDragOver:O,handleDragEnd:m,handleDragStart:E,handleDragCancel:A,sensors:v}}function ie(s){return`${s}-${t.v4()}`}function ke(s,a){const n=t.toTitleCase(s.replace(/_/g," "));switch(a){case"SUM":return`Sum of ${n}`;case"COUNT":return`Count of ${n}`;case"DISTINCT":return`Unique ${n}`;case"AVG":return`Average of ${n}`;case"MIN":return`Min of ${n}`;case"MAX":return`Max of ${n}`;default:return n}}function Se(s){return`${ct}-${s}`}function Ne(s,a){const n=t.toTitleCase(s.replace(/_/g," "));switch(a){case"day":return`Date of ${n}`;case"week":return`Week of ${n}`;case"month":return`Month of ${n}`;case"year":return`Year of ${n}`;default:return n}}function Mn({schemaName:s,tableName:a,columns:n,status:r}){const o=t.useEditorStore(N=>N.sqlGen),i=t.useEditorStore(N=>N.isDevMode),c=t.useEditorStore(N=>N.selectedConnectionId),d=t.useEditorStore(N=>{var M,F;return(F=(M=N.card)==null?void 0:M.queryConfig)==null?void 0:F.metricColumns});t.useEditorStore(N=>{var M,F;return(F=(M=N.card)==null?void 0:M.queryConfig)==null?void 0:F.groupByColumns});const l=t.useEditorStore(N=>N.selectedDatabaseName),x=t.useEditorStore(N=>N.selectedSchemaName),h=t.useEditorStore(N=>N.selectedTableName),u=t.useEditorStore(N=>N.selectedDatamodelId),j=t.useDashboardStore(N=>N.dashboard.aiScopeTables),{addToAIScope:y,removeFromAIScope:S}=t.useDashboardActions(),{addColumnToMetricColumns:p,addColumnToGroupBy:D,setCardSql:f,setRunSql:g,setSqlGen:v,setIsShowingVisual:O}=t.useEditorActions(),{connectionType:E,modelItems:b,selectedDatamodelName:C}=t.useEditorAside();function w(N){var M;if(i){const F=t.createSqlGenConfig(N,o);v(F);const P=(M=b==null?void 0:b.find(z=>z.id===u))==null?void 0:M.name,V=t.getSql(F,t.fmt(s),t.fmt(a),P||"",E,l||"");V&&(f(V),g(!0))}if(!i){if(t.isTextDataType(N.data_type))if(d&&d.length>0){const F={...N,role:"groupby",id:ie(N.column_name),name:N.column_name,type:N.data_type};D(F)}else{const F={...N,role:"metric",id:ie(N.column_name),name:N.column_name,label:ke(N.column_name,"COUNT"),type:N.data_type,aggregate:"COUNT"};p(F)}if(t.isDateDataType(N.data_type)){const F={...N,role:"groupby",id:ie(N.column_name),name:N.column_name,type:N.data_type,label:Ne(N.column_name,"month"),granularity:"month"};D(F)}if(t.isNumberDataType(N.data_type)){const F={...N,role:"metric",id:ie(N.column_name),name:N.column_name,label:ke(N.column_name,"SUM"),type:N.data_type,aggregate:"SUM"};p(F)}}}function T(N){N===!0&&(h||C)&&c?(y({connectionId:c,connectionType:E==="S3"||E==="API"?"DuckDb":E||"",databaseName:l||"",schemaName:x||"",tableName:h||"",datamodelName:t.resolveDatamodelName(C),datamodelId:u||""}),t.ue.success("Added to Assistant Scope",{position:"top-right",duration:2500,richColors:!0})):(S({connectionId:c||"",connectionType:E||"",tableName:h||"",datamodelName:t.resolveDatamodelName(C),datamodelId:u||"",databaseName:l||"",schemaName:x||""}),t.ue("Removed from Assistant Scope",{position:"top-right",duration:2e3,richColors:!0}))}function k(){const N=t.getFormattedTableNameForQuery({schemaName:s,tableName:a,modelName:C,connectionType:E,databaseName:l||""});O(!1);const M=E==="MSSQL"?`SELECT top 10 * FROM ${N}`:`SELECT * FROM ${N} LIMIT 10`;f(M),g(!0)}function m(){const N=t.getFormattedTableNameForQuery({schemaName:s,tableName:a,modelName:C,connectionType:E,databaseName:l||""});f(`SELECT COUNT(*) as count FROM ${N}`),g(!0)}function B(){return(j==null?void 0:j.find(N=>N.connectionId===c&&(N.tableName===h||N.datamodelName===C)))!==void 0}function A(N){return i?e.jsxs("div",{className:"flex grow items-center justify-between space-x-2 rounded-md px-2 py-1",onClick:()=>w(N),children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(lt,{column:N}),e.jsx("span",{children:N.column_name})]}),e.jsx("div",{onClick:M=>M.stopPropagation(),className:"flex items-center justify-end",children:t.isNumberDataType(N.data_type)&&e.jsx(Dn,{column:N})})]}):e.jsx(In,{onClick:w,column:N})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs(t.Toggle,{title:`${B()?"Remove from":"Add to"} Assistant Scope`,pressed:B(),onPressedChange:T,variant:"outline",className:t.cn("h-9 px-2",{}),children:[e.jsx(t.Plus,{className:t.cn("mr-1 size-4",{"text-green-400":B(),"text-muted-foreground":!B()})}),"AI"]}),e.jsxs(t.Button,{disabled:r!=="Success",onClick:k,size:"sm",variant:"secondary",className:"flex",children:[r!=="Success"?e.jsx(t.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(rn,{className:"mr-2 size-4"}),"Top 10"]}),e.jsxs(t.Button,{disabled:r!=="Success",onClick:m,size:"sm",variant:"secondary",className:"w-full",children:[r!=="Success"?e.jsx(t.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin text-foreground/50"}):e.jsx(Pt,{className:"mr-2 size-4"}),"Count"]})]})}return r!=="Success"?e.jsx("div",{className:"flex grow flex-col justify-start gap-2 px-6",children:Array.from({length:3}).map((N,M)=>e.jsx(t.Skeleton,{className:"h-7 w-full"},M))}):e.jsxs("div",{className:"flex grow flex-col space-y-4 px-4",children:[i&&e.jsx("div",{className:"mx-2 flex items-center justify-center gap-2",children:I()}),e.jsxs(t.CustomScrollArea,{className:"flex-1 basis-0 overflow-y-auto px-2 py-0",children:[e.jsx("div",{className:"flex flex-col gap-1",children:n==null?void 0:n.map(N=>e.jsx("div",{className:t.cn("mr-2 cursor-pointer rounded-md text-sm transition-colors hover:bg-muted"),children:A(N)},N.column_name))}),e.jsx(t.ScrollBar,{orientation:"vertical"}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function Ut({ColumnsComponent:s,type:a}){var me;const n=t.useEditorStore(W=>W.card),r=t.useEditorStore(W=>W.selectedConnectionId),o=t.useDashboardStore(W=>W.showFilters),i=t.useEditorStore(W=>W.selectedDatamodelId),c=t.useEditorStore(W=>W.selectedDatabaseName),d=t.useEditorStore(W=>W.selectedSchemaName),l=t.useEditorStore(W=>W.selectedTableName),x=t.useEditorStore(W=>W.isDevMode),{setSelectedTableName:h,setIsDevMode:u,setCardSql:j}=t.useEditorActions(),{connectionItems:y,modelItems:S,schemaItems:p,databaseItems:D,tableItems:f,columns:g,isConnectionsLoading:v,isModelsLoading:O,isConnectionsError:E,isModelsError:b,isDatabasesLoadingOrFetching:C,isDatabaseError:w,isSchemaLoadingOrFetching:T,isSchemaError:k,isColumnsError:m,isColumnsLoadingOrFetching:B,isTableLoadingOrFetching:A,isTableError:I,connectionType:N,isNonDbConnection:M,refetchDatabases:F,refetchModels:P,refetchSchemas:V,refetchTables:z,refetchColumns:Y,refetchConnections:R,handleConnectionChange:q,handleDatabaseChange:H,handleSchemaChange:K,handleDatamodelChange:G,handleTableChange:$,tableName:J,schemaName:X}=t.useEditorAside(),{data:se,refetch:re}=t.useDashboardCardQuery(n);function le(){return s?s(X,J,g):e.jsx(Mn,{schemaName:X,tableName:J,columns:g,status:B?"Loading...":m?"Error":"Success"})}function ne(){window.location.href="mailto:support@semaphor.cloud?subject=Help&body=I need help with..."}function te(W){W===!0?se&&(j(se.userSql),setTimeout(()=>{re()},100)):j(""),u(W)}function ce(){if(!r||N==="S3"||N==="API")return null;if(!i||i==="none")return e.jsx(be,{refetch:F,showNone:!0,onChange:H,isError:w,isLoading:C,items:D,value:c||"",title:"Database",type:"combobox"})}function _(){if(r&&!M&&(!c||c==="none")&&(!i||i==="none"))return e.jsxs("div",{className:"grid grid-cols-3",children:[e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(t.Separator,{})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(t.Label,{children:"OR"})}),e.jsx("div",{className:"col-span-1 grid place-items-center",children:e.jsx(t.Separator,{})})]})}function Q(){if(!r||N==="S3"||N==="API")return null;if(!c||c==="none")return e.jsx(be,{refetch:P,showNone:!0,onChange:G,isError:b,isLoading:O,items:S,value:i||"",title:"Model",type:"combobox"})}function oe(){return!r||N==="S3"||N==="API"||!c||c==="none"?null:e.jsx(be,{refetch:V,onChange:K,isError:k,isLoading:T,items:p,value:d||"",title:"Schema",type:"combobox"})}function de(){function W(){let Z=!1;return N==="API"?(Z=!1,Z):((N==="S3"||r&&c&&c!=="none"&&d)&&(Z=!0),Z)}return W()?e.jsx(be,{refetch:z,onChange:$,isError:I,items:f,isLoading:A,value:l||"",title:"Table",type:"combobox"}):null}return e.jsxs("aside",{className:t.cn("flex h-full min-w-[310px] max-w-[310px] flex-col justify-between rounded-none",{"border-r-[1px]":!o}),children:[e.jsxs("section",{className:"space-y-3 px-6 py-4",children:[e.jsx(be,{refetch:R,items:y,title:"Connection",value:r||"",onChange:q,isLoading:v,isError:E,type:"combobox",connectionTooltip:((me=y==null?void 0:y.find(W=>W.id===r))==null?void 0:me.type)||""}),ce(),_(),Q(),oe(),de()]}),le(),e.jsx("div",{className:"flex items-center justify-between gap-2 px-6 py-4",children:a==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Switch,{className:"data-[state=checked]:bg-muted-foreground/80",checked:x,onCheckedChange:te,id:"dev-mode"}),e.jsx(t.Label,{htmlFor:"dev-mode",children:"Advanced Mode"})]}),e.jsxs(t.Button,{onClick:ne,size:"sm",variant:"secondary",className:"group flex items-center gap-2 rounded-full",children:[e.jsx(cn,{className:"size-4"}),e.jsx("span",{className:"hidden group-hover:block",children:"Help"})]})]})})]})}function Yt({error:s,className:a="",textClassName:n="",copyButtonClassName:r=""}){const[o,i]=L.useState(!1),c=L.useRef(null),d=L.useRef(!1);function l(){s&&!d.current&&navigator.clipboard.writeText(s)}function x(j){(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),l())}function h(){const j=window.getSelection();if(j&&j.toString().trim()!==""){const y=j.toString();navigator.clipboard.writeText(y),i(!0),d.current=!0,setTimeout(()=>{i(!1),d.current=!1},1e3)}else d.current=!1}function u(){i(!1),d.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 ${a}`,children:[e.jsx("div",{className:"float-right mb-2 ml-2",children:e.jsx(t.CopyButton,{text:s,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:c,className:`cursor-pointer select-text break-all font-mono text-xs text-red-700 dark:text-red-300 ${n}`,onClick:l,onKeyDown:x,onMouseUp:h,onMouseDown:u,tabIndex:0,role:"button","aria-label":"Click to copy error message or select text to copy",children:s}),o&&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 Kt({sql:s,error:a,onDebugWithAssistant:n}){const r=t.useEditorStore(l=>l.isDevMode),{setIsDevMode:o,setCardSql:i,setRunSql:c}=t.useEditorActions();function d(){o(!r),i(s),setTimeout(()=>{c(!0)},100)}return e.jsx("div",{className:"flex justify-between space-x-4",children:e.jsxs("div",{className:"flex grow flex-col space-y-2",children:[e.jsxs(t.ScrollArea,{className:"max-h-[250px] min-h-0 overflow-scroll text-xs leading-relaxed text-foreground/80",children:[a&&e.jsx(Yt,{error:a}),s&&e.jsx("div",{className:"flex flex-col space-y-1.5",children:e.jsx("div",{className:"rounded-md",children:e.jsx(t.CodeHighlighter,{code:s,language:"sql"})})})]}),!r&&s&&e.jsxs(t.Button,{onClick:d,variant:"secondary",size:"sm",children:[e.jsx(Ys,{className:"mr-2 h-4 w-4"}),"View in SQL Editor"]}),a&&n&&e.jsxs(t.Button,{onClick:n,size:"sm",variant:"secondary",children:[e.jsx(en,{className:"mr-2 h-4 w-4"}),"Debug with Assistant"]})]})})}function Qt({sql:s,error:a,onDebugWithAssistant:n}){return e.jsxs(t.HoverCard,{openDelay:a?0:500,children:[e.jsx(t.HoverCardTrigger,{asChild:!0,children:e.jsx(t.Button,{variant:"link",className:"h-5 p-0",children:a?e.jsx(Bt,{className:"h-4 w-4 text-red-500"}):e.jsx(t.Info,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(t.HoverCardContent,{align:"start",className:"flex w-[600px]",children:e.jsx(Kt,{sql:s,error:a,onDebugWithAssistant:n})})]})}var Wt={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Et=L.createContext&&L.createContext(Wt),Ln=["attr","size","title"];function On(s,a){if(s==null)return{};var n=Bn(s,a),r,o;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(o=0;o<i.length;o++)r=i[o],!(a.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Bn(s,a){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(a.indexOf(r)>=0)continue;n[r]=s[r]}return n}function Le(){return Le=Object.assign?Object.assign.bind():function(s){for(var a=1;a<arguments.length;a++){var n=arguments[a];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(s[r]=n[r])}return s},Le.apply(this,arguments)}function Dt(s,a){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);a&&(r=r.filter(function(o){return Object.getOwnPropertyDescriptor(s,o).enumerable})),n.push.apply(n,r)}return n}function Oe(s){for(var a=1;a<arguments.length;a++){var n=arguments[a]!=null?arguments[a]:{};a%2?Dt(Object(n),!0).forEach(function(r){Fn(s,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(n)):Dt(Object(n)).forEach(function(r){Object.defineProperty(s,r,Object.getOwnPropertyDescriptor(n,r))})}return s}function Fn(s,a,n){return a=zn(a),a in s?Object.defineProperty(s,a,{value:n,enumerable:!0,configurable:!0,writable:!0}):s[a]=n,s}function zn(s){var a=Pn(s,"string");return typeof a=="symbol"?a:a+""}function Pn(s,a){if(typeof s!="object"||!s)return s;var n=s[Symbol.toPrimitive];if(n!==void 0){var r=n.call(s,a);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(a==="string"?String:Number)(s)}function Xt(s){return s&&s.map((a,n)=>L.createElement(a.tag,Oe({key:n},a.attr),Xt(a.child)))}function ge(s){return a=>L.createElement(Rn,Le({attr:Oe({},s.attr)},a),Xt(s.child))}function Rn(s){var a=n=>{var{attr:r,size:o,title:i}=s,c=On(s,Ln),d=o||n.size||"1em",l;return n.className&&(l=n.className),s.className&&(l=(l?l+" ":"")+s.className),L.createElement("svg",Le({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,c,{className:l,style:Oe(Oe({color:s.color||n.color},n.style),s.style),height:d,width:d,xmlns:"http://www.w3.org/2000/svg"}),i&&L.createElement("title",null,i),s.children)};return Et!==void 0?L.createElement(Et.Consumer,null,n=>a(n)):a(Wt)}function Vn(s){return ge({attr:{viewBox:"0 0 448 512"},child:[{tag:"path",attr:{d:"M439.8 200.5c-7.7-30.9-22.3-54.2-53.4-54.2h-40.1v47.4c0 36.8-31.2 67.8-66.8 67.8H172.7c-29.2 0-53.4 25-53.4 54.3v101.8c0 29 25.2 46 53.4 54.3 33.8 9.9 66.3 11.7 106.8 0 26.9-7.8 53.4-23.5 53.4-54.3v-40.7H226.2v-13.6h160.2c31.1 0 42.6-21.7 53.4-54.2 11.2-33.5 10.7-65.7 0-108.6zM286.2 404c11.1 0 20.1 9.1 20.1 20.3 0 11.3-9 20.4-20.1 20.4-11 0-20.1-9.2-20.1-20.4.1-11.3 9.1-20.3 20.1-20.3zM167.8 248.1h106.8c29.7 0 53.4-24.5 53.4-54.3V91.9c0-29-24.4-50.7-53.4-55.6-35.8-5.9-74.7-5.6-106.8.1-45.2 8-53.4 24.7-53.4 55.6v40.7h106.9v13.6h-147c-31.1 0-58.3 18.7-66.8 54.2-9.8 40.7-10.2 66.1 0 108.6 7.6 31.6 25.7 54.2 56.8 54.2H101v-48.8c0-35.3 30.5-66.4 66.8-66.4zm-6.7-142.6c-11.1 0-20.1-9.1-20.1-20.3.1-11.3 9-20.4 20.1-20.4 11 0 20.1 9.2 20.1 20.4s-9 20.3-20.1 20.3z"},child:[]}]})(s)}function Zt(s){const{theme:a}=t.useTheme(),n=t.useDashboardStore(p=>p.theme),r=t.useEditorStore(p=>p.frame),o=t.useEditorStore(p=>p.card),i=t.useEditorStore(p=>p.activeTabCardId),c=t.Le(),{refetch:d}=t.useDashboardCardQuery(o),{updateCardTab:l,setRunSql:x}=t.useEditorActions(),h=L.useRef(),u=L.useRef({}),j=r.cards.find(p=>p.id===i),y=L.useCallback(()=>{let p="";return s==="python"&&(p=(j==null?void 0:j.python)||t.PYTHON_DEFAULT_CODE),s==="sql"&&(p=(j==null?void 0:j.sql)||""),p},[s,j]);L.useEffect(()=>{if(i&&o.id&&o.id!==i){if(h.current&&c){const p=h.current.getModel();p&&(u.current[o.id]=p);let D=u.current[i];if(!D){const f=y();D=c.editor.createModel(f,s),u.current[i]=D}h.current.setModel(D)}l(i,o),x(!0)}},[i,o,l,c,x,s,y]),L.useEffect(()=>{if(!c)return;const p=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",D=n==="system"?p:n;c.editor.defineTheme("default",{base:D==="light"?"vs":"vs-dark",inherit:!0,rules:[],colors:{"editor.background":D==="light"?"#ffffff":t.hslStringToHex("240 10% 10%")}}),c.editor.setTheme("default")},[a,n,c]),L.useEffect(()=>{const p=h.current;p&&c&&o&&p.addCommand(c.KeyMod.Shift|c.KeyCode.Enter,function(){return d(),!1})},[c,d,o]);function S(p,D){if(h.current=p,!u.current[o.id]){const f=p.getModel(),g=y();u.current[o.id]=f||(D==null?void 0:D.editor.createModel(g,s))||p.getModel()}p.setModel(u.current[o.id])}return{handleEditorDidMount:S}}function qn(){const s=t.useEditorStore(c=>c.card.sql),a=t.useEditorStore(c=>c.sqlGen),{setCardSql:n,setSqlGen:r}=t.useEditorActions(),{handleEditorDidMount:o}=Zt("sql");function i(c){n(c),t.isObjectEmpty(a)||r({})}return e.jsxs("div",{className:"relative h-full w-full",children:[!s&&e.jsx("div",{className:"pointer-events-none absolute left-[65px] top-3 z-10 font-mono text-sm text-muted-foreground",children:"Write your SQL here"}),e.jsx(t.Ft,{theme:"default",className:"pt-3",onChange:i,value:s||"",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"sql",onMount:o})]})}function _n(){const s=t.useEditorStore(o=>o.card.python),{setCardPython:a}=t.useEditorActions(),{handleEditorDidMount:n}=Zt("python");function r(o){a(o)}return e.jsx(t.Ft,{className:"pt-3",theme:"default",onChange:r,value:s||t.PYTHON_DEFAULT_CODE,options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:13,renderLineHighlight:"none"},defaultLanguage:"python",onMount:n})}function Gn({jsonString:s}){return e.jsx(t.Ft,{theme:"default",defaultLanguage:"json",className:"mt-1 min-h-[220px]",value:s,options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"off",glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})}function $n(){const s=t.useQueryClient(),[a,n]=L.useState(!1),[r,o]=L.useState(!1);t.useEditorStore(z=>z.frame);const i=t.useEditorStore(z=>z.card);t.useEditorStore(z=>z.isShowingVisual),t.useEditorStore(z=>z.selectedConnectionId),t.useEditorStore(z=>z.tempQueryData),t.useEditorStore(z=>z.selectedDatabaseName),t.useEditorStore(z=>z.selectedDatamodelId),t.useEditorStore(z=>z.selectedSchemaName);const c=t.useEditorStore(z=>z.showAIDialog);t.useEditorStore(z=>z.selectedTableName);const d=t.useEditorStore(z=>{var Y;return(Y=z==null?void 0:z.card)==null?void 0:Y.sql}),l=t.useEditorStore(z=>{var Y;return(Y=z==null?void 0:z.card)==null?void 0:Y.python}),{sheetFilterValues:x}=t.useSheetFilterValues(),{setCardCustomCfg:h,setQueryResultColumns:u,setCardSql:j,setTempQueryData:y,setPythonStdOut:S,setCardPreferences:p,setCardType:D,setCardPython:f,runAssistant:g,setShowAIDialog:v}=t.useEditorActions();t.useEditorStore(z=>z.onSave),t.useEditorStore(z=>z.onClose),t.useEditorStore(z=>z.actions.setSqlGen);const O=t.useEditorStore(z=>z.runSql),E=t.useEditorStore(z=>z.actions.setRunSql),b=t.useEditorStore(z=>z.actions.setIsSqlRunning),{data:C,isLoading:w,isFetching:T,isSuccess:k,isError:m,error:B,queryKey:A,refetch:I,errorMessage:N}=t.useDashboardCardQuery(i);L.useEffect(()=>{if(C&&(C.rowLimitExceeded&&t.ue.error("Row limit (10,000) exceeded. Refine your query.",{position:"top-center",richColors:!0}),S((C==null?void 0:C.output)||""),C.records.length>0)){const{dimensionKeys:z}=t.getKeys(C.records);u(z)}},[C,u,S]),L.useEffect(()=>{(w||T)&&b(!0),(m||k)&&b(!1),m&&(u([]),S(""))},[w,T,C,S,m,k,b,u,B]),L.useEffect(()=>{O&&(s.getQueryData(A)||I(),E(!1))},[O,I,E,A,s]);async function M(){const z=`Can you help me debug this query in the current table scope?
|
|
357
352
|
|
|
358
353
|
Error:
|
|
359
354
|
|
|
360
|
-
${
|
|
355
|
+
${N}
|
|
361
356
|
|
|
362
357
|
Query:
|
|
363
358
|
|
|
@@ -365,11 +360,11 @@
|
|
|
365
360
|
|
|
366
361
|
${l?`Python:
|
|
367
362
|
${l}`:""}
|
|
368
|
-
`;g(z)}function F(){return e.jsxs(e.Fragment,{children:[r&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx(Gn,{jsonString:JSON.stringify(x,null,2)})})}),x&&x.length>0&&e.jsx(t.Button,{variant:"ghost",onClick:()=>o(!r),className:"absolute bottom-0 right-6 size-7 p-1",children:r?e.jsx(t.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(t.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function P(){return e.jsxs(t.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(t.ResizablePanel,{id:"1",order:1,defaultSize:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(qn,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(t.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(t.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(_n,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function R(){return e.jsxs("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsxs(t.Button,{title:"Shift + Enter",disabled:S||D,onClick:()=>{T()},className:"h-8 shrink-0",size:"sm",children:[S||D?e.jsx(t.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(t.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(Kt,{sql:C==null?void 0:C.sql,error:b,onDebugWithAssistant:A}),e.jsx(t.EditorClearButton,{}),e.jsx(t.Toggle,{pressed:a,onPressedChange:z=>n(z),className:"",size:"sm",children:e.jsx(Rn,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{O(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:c?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.EditorCancelButton,{}),e.jsx(t.EditorAcceptButton,{})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[P(),F()]}),R()]})}function Jn({data:s}){var c;const[a,n]=L.useState([]),o=Object.keys(s[0]).map(d=>({accessorKey:d,header:({column:l})=>{const x=l.getIsSorted();return e.jsx("div",{className:"flex gap-2",children:e.jsxs("div",{className:"flex cursor-pointer items-center",onClick:()=>l.toggleSorting(l.getIsSorted()==="asc"),children:[d,x==="asc"?e.jsx(t.TriangleUpIcon,{className:"ml-2 h-5 w-5"}):x==="desc"?e.jsx(t.TriangleDownIcon,{className:"ml-2 h-5 w-5"}):null]})})}})),i=t.useReactTable({data:s,columns:o,getCoreRowModel:t.getCoreRowModel(),getPaginationRowModel:t.getPaginationRowModel(),onSortingChange:n,getSortedRowModel:t.getSortedRowModel(),manualPagination:!0,state:{sorting:a}});return e.jsxs(t.CustomScrollArea,{className:"grow overflow-auto font-mono text-xs text-foreground/95",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(t.TableHeader,{className:"sticky top-0 z-50 h-0 bg-muted",children:i.getHeaderGroups().map(d=>e.jsx(t.TableRow,{className:"",children:d.headers.map(l=>e.jsx(t.TableHead,{className:"h-11 font-semibold text-foreground",children:l.isPlaceholder?null:t.flexRender(l.column.columnDef.header,l.getContext())},l.id))},d.id))}),e.jsx(t.TableBody,{children:(c=i.getRowModel().rows)!=null&&c.length?i.getRowModel().rows.map(d=>e.jsx(t.TableRow,{className:"h-11 whitespace-nowrap py-2","data-state":d.getIsSelected()&&"selected",children:d.getVisibleCells().map(l=>e.jsx(t.TableCell,{className:"py-2",children:t.flexRender(l.column.columnDef.cell,l.getContext())},l.id))},d.id)):e.jsx(t.TableRow,{children:e.jsx(t.TableCell,{colSpan:o.length,className:"h-24 text-center",children:"No results."})})})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function Hn({card:s}){var g,O,I,k,v,C,S,D,w,m,B;const[a,n]=L.useState(!1),[r,o]=L.useState([]),{authToken:i}=t.useSemaphorContext(),c=t.getTokenParams(i==null?void 0:i.accessToken),d=t.useDashboardStore(M=>M.themeStyle),l={colors:((O=(g=d==null?void 0:d.chart)==null?void 0:g.dataset)==null?void 0:O.backgroundColor)||[]};(I=s.customCardPreferences)!=null&&I.inputData;const{getCard:x}=t.useCustomVisual(((k=s.customCardPreferences)==null?void 0:k.url)||""),h=((v=s.customCardPreferences)==null?void 0:v.visualType)||"single",u=t.useEditorStore(M=>M.frame),{setCustomCardPreferences:j}=t.useEditorActions(),{data:y}=t.useDashboardCardQuery(s),N=L.useCallback((M,T)=>{o(b=>({...b,[M]:T}))},[]);if(!((C=s.customCardPreferences)!=null&&C.componentName))return null;const f=x((S=s.customCardPreferences)==null?void 0:S.componentName);function E(M){n(M)}const p=Object.keys(((D=s.customCardPreferences)==null?void 0:D.dataInputCardIds)||{}).map(M=>{var A,F,P;const T=(F=(A=s.customCardPreferences)==null?void 0:A.dataInputCardIds)==null?void 0:F[M].cardId,b=(P=u==null?void 0:u.cards)==null?void 0:P.find(R=>R.id===T);return b||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(L.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[f&&h==="single"&&e.jsx(f,{params:c,theme:l,settings:(w=s.customCardPreferences)==null?void 0:w.settings,onDataChange:N,data:(y==null?void 0:y.records)||[]}),f&&h==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((m=s.customCardPreferences)==null?void 0:m.dataInputCardIds)||{}).map(M=>{var A,F,P;const T=(F=(A=s.customCardPreferences)==null?void 0:A.dataInputCardIds)==null?void 0:F[M].cardId,b=(P=u==null?void 0:u.cards)==null?void 0:P.find(R=>R.id===T);if(b)return e.jsx(t.MultiInputEmptyRenderer,{onLoadingStatus:E,onDataChange:N,dataInputIndex:M,card:b},b.id+M)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(f,{theme:l,onDataChange:N,settings:p.map(M=>{var T;return(T=M==null?void 0:M.customCardPreferences)==null?void 0:T.settings}),data:p.map(M=>M!=null&&M.id?r==null?void 0:r[M.id]:[])})})]})]},(B=s.customCardPreferences)==null?void 0:B.componentName)})}function Zt({className:s,...a}){var p;const n=t.useEditorStore(g=>g.card),r=((p=n.customCardPreferences)==null?void 0:p.showCardHeader)??!0,o=t.useEditorStore(g=>g.frame),i=t.useDashboardStore(g=>g.dashboard.filters);t.useEditorStore(g=>g.actions.setRunSql);const{updateFilter:c}=t.useDashboardActions(),d=i==null?void 0:i.find(g=>g.id===o.filterId),{data:l,isLoading:x,isFetching:h,errorMessage:u}=t.useDashboardCardQuery(n),{setCard:j}=t.useEditorActions(),{data:y}=t.useTopoJson(n),N=L.useMemo(()=>!n.id||!(l!=null&&l.records)?null:t.createChartConfig({card:n,data:l==null?void 0:l.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:y}),[n.id,l==null?void 0:l.records,n.type,n.queryConfig,n.customCfg,n.preferences,y]);function f(g){return e.jsx(Hn,{card:g})}function E(){if(l!=null&&l.records&&(l==null?void 0:l.records.length)===0&&!x&&!h)return u?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(t.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:n.mode!=="explorer"?"Error fetching data. Please check your SQL or Python code.":"Error fetching data. Please check your chart configuration"})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(t.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if(!n.id)return null;if(n.type==="custom")return f(n);if(!["table","custom"].includes(n.type)&&N)return e.jsx(e.Fragment,{children:x||h?e.jsx(e.Fragment,{}):e.jsx(t.ChartJsVisual,{cfg:N})});if(n.type==="table"&&(l!=null&&l.records)&&(l==null?void 0:l.records.length)>0)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(t.TableVisual,{card:n,data:l==null?void 0:l.records})})}return e.jsxs(t.Card,{role:"editor-visual-card",className:t.cn("relative flex h-full flex-col rounded-none",s),...a,children:[r&&e.jsxs(t.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{children:[e.jsx(t.Editable,{enabled:!0,text:n.title,onSave:g=>j({...n,title:g}),children:e.jsx("div",{className:"flex items-center gap-5",children:e.jsx(t.CardTitle,{className:"text-base",children:n.title||"Add title"})})},n.title),e.jsx(t.Editable,{enabled:!0,text:n.description||"",onSave:g=>j({...n,description:g}),children:e.jsx(t.CardDescription,{children:n.description||"Add description"})},n.description)]}),d&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Editable,{enabled:!0,className:"my-1",text:d.title||d.column,onSave:g=>c({...d,title:g}),children:e.jsx(t.Label,{children:d.title})}),e.jsx(t.FilterComponent,{filter:d})]})]}),e.jsx(t.CardContent,{className:"flex grow flex-col",children:E()})]})}const Je=({language:s,value:a,onChange:n,readonly:r})=>e.jsx(t.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:s,value:a,onChange:n}),Un=()=>e.jsxs(t.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(t.DialogTitle,{children:"Customize Card"})}),e.jsxs(t.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),Yn=({customCode:s,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:o})=>e.jsxs(t.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(t.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(t.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(t.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(t.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(t.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Je,{language:"json",value:n,onChange:r})}),e.jsx(t.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Je,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(t.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Je,{language:"javascript",value:s,onChange:o})})]}),Kn=({error:s,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:o})=>e.jsxs(t.DialogFooter,{className:"flex items-center",children:[e.jsx(t.Label,{className:"mr-2 text-red-500",children:s}),e.jsx(t.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(t.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(t.Button,{onClick:o,variant:"outline",children:"Close"})]});function Qn(){const[s,a]=L.useState(!1),[n,r]=L.useState(""),[o,i]=L.useState(""),[c,d]=L.useState(""),[l,x]=L.useState(""),h=t.useEditorStore(k=>k.card),u=t.useEditorStore(k=>k.card.customCfg),j=u?JSON.stringify(u,null,2):"",{data:y}=t.useDashboardCardQuery(h),{data:N}=t.useTopoJson(h),{setCardCustomCfg:f,setCustomVisualCode:E}=t.useEditorActions(),p=k=>{var v,C;return JSON.stringify({...k,data:{...k.data,datasets:(C=(v=k.data)==null?void 0:v.datasets)==null?void 0:C.map(S=>({...S,data:[]}))}},null,2)},g=()=>{var v,C;if(!((v=y==null?void 0:y.records)!=null&&v.length))return;const k=t.createChartConfig({card:h,data:y.records,cardType:h.type,queryConfig:h.queryConfig,preferences:h.preferences,topoJson:N});if(k){r(p(k)),d(((C=h.preferences)==null?void 0:C.customVisualCode)||"");const S=t.merge(k,u);i(p(S))}},O=()=>{try{if(c&&E(c),o){const k=JSON.parse(o),v=t.getObjectDiff(JSON.parse(n),k);f(v),x("")}}catch{x("Invalid JSON configuration")}},I=Object.keys(u||{}).length===0;return e.jsxs(t.Dialog,{open:s,onOpenChange:a,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Customize Visual",onClick:g,className:I?"":"text-green-600 hover:text-green-700",children:e.jsx(t.Settings,{className:"h-4 w-4"})})}),e.jsxs(t.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(Un,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackEditorCard,children:e.jsx(Zt,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Yn,{customCode:c,cardCustomCfgString:j,mergedConfig:o,onConfigChange:k=>i(k??""),onCodeChange:k=>d(k??"")})]}),e.jsx(Kn,{error:l,hasCardCustomConfig:!!u,onReset:()=>{i(n),f(null)},onApply:O,onClose:()=>a(!1)})]})]})}function Pe(s){const[a,n]=L.useState(null);return a}function dt(){const{authToken:s}=t.useSemaphorContext(),{data:a,isLoading:n,isFetching:r,isError:o}=t.useQuery({queryKey:["plugins",s==null?void 0:s.accessToken],queryFn:()=>t.getPlugins(s==null?void 0:s.accessToken)});return{data:a,isLoading:n,isFetching:r,isError:o}}function Wn({onChartTypeChange:s}){const[a,n]=L.useState([]),{setCardCustomCfg:r,setCardPreferences:o,setCardType:i,setCustomCardPreferences:c}=t.useEditorActions(),{data:d}=dt();function l(x,h){r(null),o({}),i(x),h&&c({type:"component",visualType:"single",url:h.url,componentName:h.name,icon:h.icon}),s==null||s()}return L.useEffect(()=>{(async()=>{var h;if(d){const j=(await Promise.all((h=d==null?void 0:d.plugins)==null?void 0:h.map(async y=>(await t.loadManifest(y.value)).visuals.map(E=>({name:E.name,icon:E.icon,url:y.value}))))).flat();n(j)}})()},[d]),a.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(t.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:a.map((x,h)=>e.jsx(Xn,{text:x.name,onClick:()=>l("custom",x),icon:x.icon},x.url+x.name+h))})]})}const Xn=({text:s,icon:a,onClick:n})=>{const r=Pe(),o=s.charAt(0).toUpperCase();return e.jsx(t.IconButton,{onClick:n,tooltip:s,children:r?e.jsx(r,{className:"h-4 w-4"}):o})};function ut(s){return ge({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm87.63,96H191.48A64.1,64.1,0,0,0,136,64.52V40.37A88.13,88.13,0,0,1,215.63,120ZM120,120H80.68A48.09,48.09,0,0,1,120,80.68Zm0,16v39.32A48.09,48.09,0,0,1,80.68,136Zm16,0h39.32A48.09,48.09,0,0,1,136,175.32Zm0-16V80.68A48.09,48.09,0,0,1,175.32,120ZM120,40.37V64.52A64.1,64.1,0,0,0,64.52,120H40.37A88.13,88.13,0,0,1,120,40.37ZM40.37,136H64.52A64.1,64.1,0,0,0,120,191.48v24.15A88.13,88.13,0,0,1,40.37,136ZM136,215.63V191.48A64.1,64.1,0,0,0,191.48,136h24.15A88.13,88.13,0,0,1,136,215.63Z"},child:[]}]})(s)}function Zn(s){return ge({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M48,180c0,11,7.18,20,16,20a14.24,14.24,0,0,0,10.22-4.66A8,8,0,0,1,85.78,206.4,30.06,30.06,0,0,1,64,216c-17.65,0-32-16.15-32-36s14.35-36,32-36a30.06,30.06,0,0,1,21.78,9.6,8,8,0,0,1-11.56,11.06A14.24,14.24,0,0,0,64,160C55.18,160,48,169,48,180Zm79.6-8.69c-4-1.16-8.14-2.35-10.45-3.84-1.25-.81-1.23-1-1.12-1.9a4.57,4.57,0,0,1,2-3.67c4.6-3.12,15.34-1.73,19.82-.56A8,8,0,0,0,142,145.86c-2.12-.55-21-5.22-32.84,2.76a20.58,20.58,0,0,0-9,14.95c-2,15.88,13.65,20.41,23,23.11,12.06,3.49,13.12,4.92,12.78,7.59-.31,2.41-1.26,3.34-2.14,3.93-4.6,3.06-15.17,1.56-19.55.36A8,8,0,0,0,109.94,214a61.34,61.34,0,0,0,15.19,2c5.82,0,12.3-1,17.49-4.46a20.82,20.82,0,0,0,9.19-15.23C154,179,137.49,174.17,127.6,171.31Zm83.09-26.84a8,8,0,0,0-10.23,4.84L188,184.21l-12.47-34.9a8,8,0,0,0-15.07,5.38l20,56a8,8,0,0,0,15.07,0l20-56A8,8,0,0,0,210.69,144.47ZM216,88v24a8,8,0,0,1-16,0V96H152a8,8,0,0,1-8-8V40H56v72a8,8,0,0,1-16,0V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88Zm-27.31-8L160,51.31V80Z"},child:[]}]})(s)}function mt(s){return ge({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M6 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"},child:[]},{tag:"path",attr:{d:"M16 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"},child:[]},{tag:"path",attr:{d:"M14.5 7.5m-4.5 0a4.5 4.5 0 1 0 9 0a4.5 4.5 0 1 0 -9 0"},child:[]}]})(s)}function ht(s){return ge({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4.387 3h15.226a1 1 0 0 1 .948 1.316l-5.105 15.316a2 2 0 0 1 -1.898 1.368h-3.116a2 2 0 0 1 -1.898 -1.368l-5.104 -15.316a1 1 0 0 1 .947 -1.316"},child:[]},{tag:"path",attr:{d:"M5 9h14"},child:[]},{tag:"path",attr:{d:"M7 15h10"},child:[]}]})(s)}function xt(s){return ge({attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"m2 19.99 7.5-7.51 4 4 7.09-7.97L22 9.92l-8.5 9.56-4-4-6 6.01-1.5-1.5zm1.5-4.5 6-6.01 4 4L22 3.92l-1.41-1.41-7.09 7.97-4-4L2 13.99l1.5 1.5z"},child:[]}]})(s)}function pt(s){return ge({attr:{version:"1.2",baseProfile:"tiny",viewBox:"0 0 24 24"},child:[{tag:"path",attr:{d:"M4 18c-.552 0-1-.448-1-1v-6.382l-.553.276c-.495.248-1.095.046-1.342-.447-.247-.494-.046-1.094.448-1.342l2-1c.31-.155.678-.139.973.044.294.183.474.504.474.851v8c0 .552-.448 1-1 1zM13 18h-5c-.404 0-.769-.244-.924-.617-.155-.374-.069-.804.217-1.09l4-4c.254-.254.394-.591.394-.95 0-.358-.14-.695-.394-.949-.508-.508-1.39-.508-1.9.001-.253.252-.393.589-.393.948 0 .552-.448 1-1 1s-1-.448-1-1c0-.894.348-1.733.98-2.364 1.265-1.263 3.464-1.263 4.727.001.632.631.979 1.471.979 2.363 0 .893-.348 1.733-.979 2.364l-2.293 2.293h2.586c.552 0 1 .448 1 1s-.448 1-1 1zM20.955 12.377c.338-.457.545-1.016.545-1.627 0-1.517-1.234-2.75-2.75-2.75-1.031 0-1.966.569-2.44 1.484-.254.49-.063 1.094.428 1.348.49.254 1.094.062 1.348-.428.128-.249.383-.404.664-.404.414 0 .75.336.75.75s-.336.75-.75.75c-.552 0-1 .448-1 1s.448 1 1 1c.689 0 1.25.561 1.25 1.25s-.561 1.25-1.25 1.25-1.25-.561-1.25-1.25c0-.552-.448-1-1-1s-1 .448-1 1c0 1.792 1.458 3.25 3.25 3.25s3.25-1.458 3.25-3.25c0-.939-.406-1.779-1.045-2.373z"},child:[]}]})(s)}function es({onChartTypeChange:s,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:o}=t.useEditorStore(h=>h.actions),{setCardCustomCfg:i,setCustomCardPreferences:c,setQueryConfig:d}=t.useEditorActions();function l(h,u){i(null),r({}),n(h),["custom","text","map"].includes(h)&&(o(!0),d(void 0)),s==null||s()}const x=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(t.IconButton,{openDelay:x,tooltip:"Table",onClick:()=>l("table"),className:"h-10 p-4",children:e.jsx(ze,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Bar Chart",onClick:()=>l("bar"),className:"h-10 p-4",children:e.jsx(Be,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Line Chart",onClick:()=>l("line"),className:"h-10 p-4",children:e.jsx(Fe,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Stacked Bar Chart",onClick:()=>l("stackedBar"),className:"h-10 p-4",children:e.jsx(Xe,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Stacked Line Chart",onClick:()=>l("stackedLine"),className:"h-10 p-4",children:e.jsx(xt,{className:t.cn("size-5",a),strokeWidth:0})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Scatter Chart",onClick:()=>l("scatter"),className:"h-10 p-4",children:e.jsx(tt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Bubble Chart",onClick:()=>l("bubble"),className:"h-10 p-4",children:e.jsx(mt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Pie Chart",onClick:()=>l("pie"),className:"h-10 p-4",children:e.jsx(et,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Doughnut Chart",onClick:()=>l("doughnut"),className:"h-10 p-4",children:e.jsx(st,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Funnel Chart",onClick:()=>l("funnel"),className:"h-10 p-4",children:e.jsx(ht,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Radar Chart",onClick:()=>l("radar"),className:"h-10 p-4",children:e.jsx(rt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Polar Area Chart",onClick:()=>l("polarArea"),className:"h-10 p-4",children:e.jsx(ut,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Tornado Chart",onClick:()=>l("tornado"),className:"h-10 p-4",children:e.jsx(ot,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{tooltip:"Range Chart",onClick:()=>l("range"),className:"h-10 p-4",children:e.jsx(Ze,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"KPI",onClick:()=>l("kpi"),className:"h-10 p-4",children:e.jsx(pt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Text",onClick:()=>l("text"),className:"h-10 p-4",children:e.jsx(Lt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{tooltip:"Map",onClick:()=>l("map"),className:"h-10 p-4",children:e.jsx(at,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Custom",onClick:()=>l("custom"),className:"h-10 p-4",children:e.jsx(we,{className:t.cn("size-5",a)})})]})}function ea({chartType:s,className:a,customIcon:n,componentName:r}){const o=Pe();switch(s){case"bar":return e.jsx(Be,{className:a});case"line":return e.jsx(Fe,{className:a});case"pie":return e.jsx(et,{className:a});case"radar":return e.jsx(rt,{className:a});case"scatter":return e.jsx(tt,{className:a});case"bubble":return e.jsx(mt,{className:a});case"doughnut":return e.jsx(st,{className:a});case"stackedBar":return e.jsx(Xe,{className:a});case"stackedLine":return e.jsx(xt,{className:a});case"polarArea":return e.jsx(ut,{className:a});case"funnel":return e.jsx(ht,{className:a});case"tornado":case"pyramid":return e.jsx(ot,{className:a});case"range":return e.jsx(Ze,{className:a});case"kpi":return e.jsx(pt,{className:a});case"text":return e.jsx(Rt,{className:a});case"map":return e.jsx(at,{className:a});case"custom":return n&&o?e.jsx(o,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(we,{className:a});default:return e.jsx(ze,{className:a})}}function ts({variant:s="ghost"}){var i,c;const[a,n]=L.useState(!1),r=t.useEditorStore(d=>d.card),o=r.type;return t.useDashboardStore(d=>d.isVisualEditing),e.jsxs(t.Popover,{open:a,onOpenChange:n,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{size:"sm",variant:s||"ghost",children:e.jsx(ea,{className:"size-4",chartType:o,customIcon:(i=r.customCardPreferences)==null?void 0:i.icon,componentName:(c=r.customCardPreferences)==null?void 0:c.componentName})})}),e.jsxs(t.PopoverContentCustom,{onOpenAutoFocus:d=>d.preventDefault(),className:"w-72 p-1",children:[e.jsx(es,{onChartTypeChange:()=>n(!1)}),e.jsx(Wn,{onChartTypeChange:()=>n(!1)})]})]})}const Ee="focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0";function It(s,a){var r,o,i;const n=t.getNumberAxis(s,{});return["pie","doughnut","polarArea","funnel"].includes(a)?"category":((i=(o=(r=s==null?void 0:s.chartOptions)==null?void 0:r.scales)==null?void 0:o[n])==null?void 0:i.type)||"linear"}function ta(){var A,F,P,R,z,Y;const[s,a]=L.useState(!1),n=t.useEditorStore(V=>{var q;return(q=V.card)==null?void 0:q.preferences}),r=t.useEditorStore(V=>{var q;return(q=V.card)==null?void 0:q.type}),o=t.getNumberAxis(n,{}),[i,c]=L.useState(It(n,r)),[d,l]=L.useState(((P=(F=(A=n==null?void 0:n.chartOptions)==null?void 0:A.scales)==null?void 0:F[o])==null?void 0:P.min)||""),[x,h]=L.useState(((Y=(z=(R=n==null?void 0:n.chartOptions)==null?void 0:R.scales)==null?void 0:z[o])==null?void 0:Y.max)||""),[u,j]=L.useState(d||x?"custom":"auto"),[y,N]=L.useState(""),[f,E]=L.useState(0),[p,g]=L.useState(""),[O,I]=L.useState(""),[k,v]=L.useState(""),C=t.useEditorStore(V=>V.actions.setCardPreferences),{updateCardInFrame:S}=t.useEditorActions(),D=t.useEditorStore(V=>V.card),w=["pie","doughnut","polarArea","funnel"].includes(r);L.useEffect(()=>{var V,q,H,K,G,$,J,X,se,re,le,ne,te,ce;c(It(n,r)),l(((H=(q=(V=n==null?void 0:n.chartOptions)==null?void 0:V.scales)==null?void 0:q[o])==null?void 0:H.min)===0?0:""),h((($=(G=(K=n==null?void 0:n.chartOptions)==null?void 0:K.scales)==null?void 0:G[o])==null?void 0:$.max)||""),N(((re=(se=(X=(J=n==null?void 0:n.chartOptions)==null?void 0:J.scales)==null?void 0:X[o])==null?void 0:se.ticks)==null?void 0:re.stepSize)||""),E(((le=n==null?void 0:n.numberAxisFormat)==null?void 0:le.decimalPlaces)||0),g(((ne=n==null?void 0:n.numberAxisFormat)==null?void 0:ne.suffix)||""),I(((te=n==null?void 0:n.numberAxisFormat)==null?void 0:te.currency)||""),v(((ce=n==null?void 0:n.numberAxisFormat)==null?void 0:ce.locale)||"")},[s,n,o,r]);function m(V,q){return q===""||/^[0-9\b]+$/.test(q)?Number(q):Number(V)}function B(){const V=[...new Set(t.LOCALE_CURRENCY_PAIRS.map(q=>q.currency))];return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-6 items-center gap-2",children:[e.jsx(t.Label,{className:"col-span-2 hover:cursor-pointer hover:underline",htmlFor:"currency",children:e.jsx("a",{target:"_blank",href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat",children:"Currency"})}),e.jsxs(t.Select,{value:O||"none",onValueChange:q=>I(q==="none"?"":q),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Currency"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),V.map(q=>e.jsx(t.SelectItem,{value:q,children:q},q))]})})]}),e.jsxs(t.Select,{value:k,onValueChange:q=>v(q),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Locale"}),t.LOCALE_CURRENCY_PAIRS.map(q=>e.jsx(t.SelectItem,{value:q.locale,children:q.locale},q.locale))]})})]})]}),e.jsxs("div",{className:"grid grid-cols-9 items-center gap-2",children:[e.jsx(t.Label,{className:"col-span-3",htmlFor:"format",children:"Decimals"}),e.jsx(t.Input,{value:f,onChange:q=>E(Number(q.target.value)),id:"format",className:`col-span-6 h-8 w-full tracking-wide ${Ee}`})]})]})}function M(){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 space-y-2",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the scale for number axis"})}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"scale",children:"Type"}),e.jsxs(t.Select,{disabled:w,value:i,onValueChange:V=>c(V),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{id:"type",children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Option"}),e.jsx(t.SelectItem,{value:"linear",children:"Linear"}),e.jsx(t.SelectItem,{value:"logarithmic",children:"Logarithmic"}),e.jsx(t.SelectItem,{value:"category",children:"Category"})]})})]})]}),i=="linear"&&e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2 py-1",children:[e.jsx(t.Label,{htmlFor:"scale-option",children:"Setup"}),e.jsxs(t.RadioGroup,{disabled:w,id:"scale-option",value:u,onValueChange:V=>j(V),className:"col-span-2 flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"auto",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Auto"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"custom",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Custom"})]})]})]}),u==="custom"&&i=="linear"&&T()]})}function T(){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"range",children:"Range"}),e.jsx(t.Input,{id:"min",value:d,onChange:V=>l(q=>m(q,V.target.value)),className:`col-span-1 h-8 w-full ${Ee}`}),e.jsx(t.Input,{value:x,onChange:V=>h(q=>m(q,V.target.value)),id:"max",className:`col-span-1 h-8 w-full ${Ee}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"step-size",children:"Step Size"}),e.jsx(t.Input,{value:y,onChange:V=>N(q=>m(q,V.target.value)),id:"step-size",className:`col-span-1 h-8 w-full ${Ee}`})]})]})}function b(){var K;let V={};u==="custom"&&(V={min:d,max:x,ticks:{stepSize:y}});const q={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,scales:{...(K=n==null?void 0:n.chartOptions)==null?void 0:K.scales,[o]:{type:i,...i==="linear"?V:{}}}},numberAxisFormat:{decimalPlaces:f,suffix:p,currency:O,locale:k}};console.log(q),C(q);const H={...D,preferences:q};S(H)}return e.jsxs(t.Popover,{onOpenChange:V=>a(V),children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Format Number",children:e.jsx(Js,{className:"size-4"})})}),e.jsx(t.PopoverContentCustom,{align:"end",className:"max-w-65",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Format Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the format for number axis"})]}),e.jsxs("div",{className:"grid gap-2",children:[B(),M(),e.jsx(t.SelectSeparator,{}),e.jsx("div",{className:"grid grid-cols-3",children:e.jsx(t.Button,{onClick:b,variant:"secondary",className:"col-span-1 col-start-3 h-8 w-full",children:"Apply"})})]})]})})]})}function sa(){const s=t.useEditorStore(d=>{var l,x,h,u;return(u=(h=(x=(l=d.card.preferences)==null?void 0:l.chartOptions)==null?void 0:x.plugins)==null?void 0:h.legend)==null?void 0:u.position}),a=t.useEditorStore(d=>{var l,x,h,u;return(u=(h=(x=(l=d.card.preferences)==null?void 0:l.chartOptions)==null?void 0:x.plugins)==null?void 0:h.legend)==null?void 0:u.align}),n=t.useEditorStore(d=>{var l,x,h,u;return(u=(h=(x=(l=d.card.preferences)==null?void 0:l.chartOptions)==null?void 0:x.plugins)==null?void 0:h.legend)==null?void 0:u.display}),{setLegendOptions:r}=t.useEditorActions(),o=d=>{r({display:d,position:s,align:a})},i=d=>{r({display:n,position:d,align:a})},c=d=>{r({display:n,position:s,align:d})};return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Legend Settings",children:e.jsx(en,{className:"size-4"})})}),e.jsx(t.PopoverContentCustom,{align:"end",className:"w-72",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Legend Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the legend options for the chart."})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"displayLegend",children:"Display"}),e.jsx("div",{className:"col-span-2 flex h-8 items-center",children:e.jsx(t.SmallSwitch,{checked:n,onCheckedChange:o,id:"displayLegend"})})]}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"position",children:"Position"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(t.IconButton,{tooltip:"Top",onClick:()=>i("top"),children:e.jsx(t.ArrowUp,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Left",onClick:()=>i("left"),children:e.jsx(Ts,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Bottom",onClick:()=>i("bottom"),children:e.jsx(t.ArrowDown,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Right",onClick:()=>i("right"),children:e.jsx(Ms,{className:"size-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"align",children:"Align"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(t.IconButton,{tooltip:"Start",onClick:()=>c("start"),children:e.jsx(ws,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Center",onClick:()=>c("center"),children:e.jsx(Ss,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"End",onClick:()=>c("end"),children:e.jsx(ks,{className:"size-4"})})]})]})]})]})]})})]})}function na(){const s=t.useEditorStore(i=>{var c,d;return(d=(c=i.card.preferences)==null?void 0:c.chartOptions)==null?void 0:d.indexAxis}),a=t.useEditorStore(i=>i.card.type),{setChartOrientation:n}=t.useEditorStore(i=>i.actions);function r(){return e.jsx(t.IconButton,{onClick:()=>{n(s==="x"||s===void 0?"y":"x")},tooltip:"Chart Orientation",children:s==="x"||s===void 0?e.jsx(St,{className:"size-4"}):e.jsx(Ct,{className:"size-4"})})}function o(){return e.jsx(t.IconButton,{onClick:()=>{n(s==="y"||s===void 0?"x":"y")},tooltip:"Chart Orientation",children:s==="y"||s===void 0?e.jsx(St,{className:"size-4"}):e.jsx(Ct,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?o():r()})}function ss(){const s=t.useEditorStore(c=>c.card),a=t.useEditorStore(c=>c.isShowingVisual),n=t.useEditorStore(c=>{var d,l;return(l=(d=c.card)==null?void 0:d.preferences)==null?void 0:l.chartOptions}),r=t.getChartGridStyle(n),{setChartGrid:o}=t.useEditorActions();function i(){const c=["xy","none","x","y"],l=(c.indexOf(r)+1)%c.length;o(c[l])}return a?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(s.type)&&e.jsx(e.Fragment,{children:e.jsx(na,{})}),!["kpi","text","custom","table"].includes(s.type)&&e.jsxs(e.Fragment,{children:[e.jsx(ta,{}),e.jsx(sa,{})]}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(s.type)&&e.jsxs(t.IconButton,{tooltip:"Grid Style",onClick:i,children:[(r==="xy"||!r)&&e.jsx(Xs,{className:"size-4"}),r==="x"&&e.jsx(_s,{className:"size-4"}),r==="y"&&e.jsx(hn,{className:"size-4"}),r==="none"&&e.jsx(gn,{className:"size-4"})]})]}):null}function aa(){const s=t.useEditorStore(N=>N.frame),a=t.useEditorStore(N=>N.card),{setFrame:n,setActiveTabCardId:r,setCard:o,updateCardInFrame:i}=t.useEditorActions(),c=(N,f)=>{N.dataTransfer.setData("tabIndex",f.toString())},d=N=>{N.preventDefault()},l=(N,f)=>{const E=N.dataTransfer.getData("tabIndex");if(E===f.toString())return;const p=Array.from(s.cards),[g]=p.splice(parseInt(E),1);p.splice(f,0,g),n({...s,cards:p})};function x(N){const f=s.cards.filter(g=>g.id!==N),E=f[0],p={...s,cards:f,activeCardId:E.id};n(p),r(E.id),o(E)}function h(N,f){const E={...s,cards:[...s.cards,f],activeCardId:N.id};n(E),r(f.id)}function u(){const N={...a,id:t.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`,mode:a.mode||"explorer"};h(a,N)}function j(N){const f={dataSource:N.dataSource,connectionId:N.connectionId,lastSelectedDatabase:N.lastSelectedDatabase,lastSelectedSchema:N.lastSelectedSchema,lastSelectedTable:N.lastSelectedTable,lastSelectedDatamodelId:N.lastSelectedDatamodelId,id:t.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};h(N,f)}function y(N,f){return N.cards.length===1&&(f.displayTab===!0||f.displayTab===void 0)||N.activeCardId!==f.id&&(f.displayTab===!0||f.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const E=f.displayTab===void 0?!1:!f.displayTab;o({...f,displayTab:E}),i({...f,displayTab:E})},children:f.displayTab===!0||f.displayTab===void 0?e.jsx(t.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(Hs,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(t.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[s.cards.map((N,f)=>e.jsxs(t.TabsTrigger,{draggable:!0,onDragStart:E=>c(E,f),onDragOver:d,onDrop:E=>l(E,f),className:"",value:N.id,children:[y(s,N),e.jsx(t.Editable,{enabled:s.activeCardId===N.id,text:N.tabTitle||N.title,onSave:E=>{o({...a,tabTitle:E}),i({...a,tabTitle:E})},children:N.tabTitle||N.title},N.id),s.activeCardId===N.id&&s.cards.length>1&&e.jsx(t.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>x(N.id)})]},N.id)),e.jsx(t.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>j(a),children:e.jsx(t.Plus,{className:"h-4 w-4"})}),e.jsx(t.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:u,children:e.jsx($s,{className:"h-4 w-4"})})]})})}function ns(){const s=t.useEditorStore(f=>f.frame),a=t.useEditorStore(f=>f.card),n=t.useEditorStore(f=>f.isSqlRunning),r=t.useEditorStore(f=>f.isDevMode),{setFrame:o,setActiveTabCardId:i,setCard:c,setIsDevMode:d,setRunSql:l}=t.useEditorActions(),{data:x,isLoading:h,isFetching:u}=t.useDashboardCardQuery(a);function j(f){const E=s.cards.find(p=>p.id===f);if(E!=null&&E.sql){r||d(!0),i(f);return}if(E!=null&&E.queryConfig){r&&d(!1),y(f),i(f);return}r||y(f),i(f)}function y(f){const E={...s,cards:s.cards.map(g=>g.id===a.id?{...a,mode:a.mode||g.mode}:g),activeCardId:f};o(E);const p=E.cards.find(g=>g.id===f);p.sql&&l(!0),c(p)}function N(){return a.type==="kpi"?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(t.KPICard,{card:a,data:x==null?void 0:x.records,isPending:h})})}):a.type==="text"?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(t.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(t.TextCard,{isLoading:n,card:a,data:x==null?void 0:x.records})})})}):e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackEditorCard,children:e.jsx(Zt,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:j,value:s.activeCardId,className:"flex grow flex-col",children:[s.cards.map(f=>e.jsx(t.TabsContent,{className:"mt-0 grow",value:f.id,children:N()},f.id)),e.jsx(aa,{})]})}function De({children:s}){t.useEditorStore(g=>g.frame);const a=t.useEditorStore(g=>g.card),n=t.useEditorStore(g=>g.isDevMode),r=t.useEditorStore(g=>g.isShowingVisual),o=t.useDashboardStore(g=>g.isVisualEditing),i=t.useEditorStore(g=>g.pythonStdOut);t.useEditorStore(g=>g.actions.setRunSql);const{setFrame:c,setCard:d,setActiveTabCardId:l,runAssistant:x,setIsDevMode:h}=t.useEditorActions(),{data:u,isLoading:j,isFetching:y,errorMessage:N}=t.useDashboardCardQuery(a);function f(){const g=JSON.stringify(u==null?void 0:u.records,null,2),O=new Blob([g],{type:"application/json"}),I=URL.createObjectURL(O),k=document.createElement("a");k.href=I,k.download=`${a.title}.json`,k.click()}function E(){const O=[Object.keys(u==null?void 0:u.records.reduce((C,S)=>({...C,...S}),{})).join(","),...((u==null?void 0:u.records)||[]).map(C=>Object.values(C).join(","))].join(`
|
|
369
|
-
`),I=new Blob([O],{type:"text/csv"}),k=URL.createObjectURL(I),v=document.createElement("a");v.href=k,v.download=`${a.title}.csv`,v.click()}function p(){const g=`Can you get the documentation for ${a.type} chart?`;x(g)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[(j||y)&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 top-0 z-50 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(t.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(ts,{}),o&&e.jsx(t.IconButton,{tooltip:"Visual Docs",onClick:p,children:e.jsx(Bs,{className:"size-4"})}),!["table","custom"].includes(a.type)&&o&&e.jsx(Qn,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(t.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:E,children:e.jsx(Zn,{className:"size-4"})}),e.jsx(t.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:f,children:e.jsx(Ys,{strokeWidth:1.5,className:"size-4"})}),e.jsx(t.CopyButton,{text:JSON.stringify(u==null?void 0:u.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[s,e.jsx(ss,{})]}),n&&e.jsx(oa,{})]}),r?e.jsx(ns,{}):e.jsxs(t.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[i&&e.jsxs(e.Fragment,{children:[e.jsx(t.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:i&&e.jsx(ra,{})}),e.jsx(t.ResizableHandle,{})]}),e.jsxs(t.ResizablePanel,{id:"2",order:2,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:[(u==null?void 0:u.records)&&(u==null?void 0:u.records.length)>0&&e.jsx(Jn,{data:(u==null?void 0:u.records)||[]}),N&&e.jsx(Ut,{error:N})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function ra(){const s=t.useEditorStore(n=>n.pythonStdOut);if(!s)return null;const a=s.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col border-r",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center border-b bg-muted px-3 font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(t.ScrollArea,{className:"overflow-y-auto px-2 pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function oa(){const s=t.useEditorStore(n=>n.isShowingVisual),a=t.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(t.SmallSwitch,{checked:s,onCheckedChange:()=>a(!s),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function ia(){var f,E;const s=t.useEditorStore(p=>p.card.customCardPreferences),{data:a}=dt(),n=(a==null?void 0:a.plugins)||[],r=t.useEditorStore(p=>p.card),o=t.useEditorStore(p=>p.frame),i=(s==null?void 0:s.visualType)||"single",{setCustomCardPreferences:c}=t.useEditorActions(),{components:d,manifest:l}=t.useCustomVisual((s==null?void 0:s.url)||""),x=(f=l==null?void 0:l.visuals)==null?void 0:f.find(p=>p.name===(s==null?void 0:s.componentName));function h(p,g){if(!s)return;const I={...(s==null?void 0:s.dataInputCardIds)||{},[p]:{cardId:g,hookRef:null}};c({...s,dataInputCardIds:I})}function u(p){var O,I;const g=(O=o==null?void 0:o.cards)==null?void 0:O.filter(k=>{var v;return((v=k==null?void 0:k.customCardPreferences)==null?void 0:v.visualType)!=="multiple"}).map(k=>({value:k.id,label:k.tabTitle||k.title}));return e.jsx("div",{className:"space-y-2",children:(I=p==null?void 0:p.dataInputs)==null?void 0:I.map((k,v)=>{var C,S;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:k}),e.jsx(ae,{className:"col-span-6 h-8 w-full justify-between",label:"",options:g||[],value:((S=(C=s==null?void 0:s.dataInputCardIds)==null?void 0:C[v])==null?void 0:S.cardId)||"",onValueChange:D=>h(v,D)})]},v+Math.random())})})}function j(p,g,O=[],I=""){var k,v;return s?p==="input"?e.jsx(t.Input,{className:`h-8 w-full ${t.removeRing}`,value:((k=s==null?void 0:s.settings)==null?void 0:k[g])||I,onChange:C=>{c({...s,settings:{...s==null?void 0:s.settings,[g]:C.target.value}})}},g):p==="select"?e.jsx(ae,{className:"h-8 w-full",label:"",options:O,value:((v=s==null?void 0:s.settings)==null?void 0:v[g])||I,onValueChange:C=>{c({...s,settings:{...s==null?void 0:s.settings,[g]:C}})}}):null:null}function y(p){const g=Object.entries((p==null?void 0:p.settings)||{});return e.jsx("div",{className:"space-y-3",children:g.map(([O,I])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:I.title}),j(I.ui,O,I.options,I.defaultValue)]},O))})}function N(p){s&&c({...s,visualType:p,componentName:""})}return e.jsxs(t.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(t.AccordionItem,{value:"plugin-settings",children:[e.jsx(t.AccordionTrigger,{children:"Plugin"}),e.jsx(t.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(ae,{icon:e.jsx(Os,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(s==null?void 0:s.url)||"",onValueChange:p=>c({...s||{url:"",componentName:""},url:p})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&e.jsx(t.Tabs,{value:i,onValueChange:N,children:e.jsxs(t.TabsList,{className:"h-9 w-full",children:[e.jsx(t.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(t.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&s&&e.jsx(e.Fragment,{children:d&&e.jsx(ae,{icon:e.jsx(Gs,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(d==null?void 0:d.filter(p=>p.type===i).map(p=>({value:p.name,label:p.name})))||[],value:s.componentName,onValueChange:p=>{console.log("changing value",p),c({...s,componentName:p})}})})]})})]}),((E=r==null?void 0:r.customCardPreferences)==null?void 0:E.componentName)&&e.jsxs(t.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{children:[x&&x.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:u(x)})]}),x&&x.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:y(x)})})]})]})]})}function je(){const[s,a]=L.useState([]),n=t.useEditorStore(x=>x.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:o}=t.useEditorStore(x=>x.actions),i=t.useEditorStore(x=>x.queryResultColumns);t.useEditorStore(x=>{var h;return(h=x.card.preferences)==null?void 0:h.filterOnClickColumnIndex}),L.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function c(x,h){var u,j;h?n!=null&&n.onClickFilter&&((u=n==null?void 0:n.onClickFilter)==null?void 0:u.length)>0?o({...n,onClickFilter:[...n.onClickFilter,{columnIndex:x,expression:""}]}):o({...n,onClickFilter:[{columnIndex:x,expression:""}]}):(o({...n,onClickFilter:(j=n==null?void 0:n.onClickFilter)==null?void 0:j.filter(y=>y.columnIndex!==x)}),a(y=>{const N=[...y];return N[x]=!1,N}))}function d(x,h){var j;const u=(j=n==null?void 0:n.onClickFilter)==null?void 0:j.map(y=>y.columnIndex===x?{...y,expression:h.target.value}:y);o({...n,onClickFilter:u})}function l(x){var h,u,j,y;if(s!=null&&s[x]||(u=(h=n==null?void 0:n.onClickFilter)==null?void 0:h.find(N=>N.columnIndex===x))!=null&&u.expression)return e.jsx(t.Input,{value:(y=(j=n==null?void 0:n.onClickFilter)==null?void 0:j.find(N=>N.columnIndex===x))==null?void 0:y.expression,onChange:N=>d(x,N),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsxs("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:[e.jsx(t.Label,{children:"On Click"}),i==null?void 0:i.map((x,h)=>{var u,j;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(t.Checkbox,{checked:!!((u=n==null?void 0:n.onClickFilter)!=null&&u.find(y=>y.columnIndex===h)),onCheckedChange:y=>c(h,y)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:x}),e.jsx("div",{className:"flex items-center gap-2",children:((j=n==null?void 0:n.onClickFilter)==null?void 0:j.find(y=>y.columnIndex===h))&&e.jsx(t.Pencil,{onClick:()=>{a(y=>{const N=[...y];return N[h]=!y[h],N})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),l(h)]})},x)})]})}function la({idx:s}){var d;const a=t.useEditorStore(l=>{var x;return(x=l.card)==null?void 0:x.preferences}),n=t.useEditorStore(l=>{var x;return(x=l.card.preferences)==null?void 0:x.datasetOptions}),r=t.useEditorStore(l=>l.actions.setCardPreferences),o=(d=a==null?void 0:a.chartOptions)==null?void 0:d.indexAxis,i=n==null?void 0:n.find(l=>l.idx===s);function c(l,x){(l==="end"||l==="start")&&t.getContrastColor(t.getCanvasBackgroundColor());const h={display:l!=="none",align:l,anchor:l,clamp:!0};if(!i)r({...a,datasetOptions:[...n||[],{idx:x,datalabels:h}]});else{const u={...i};u.datalabels=h;const j=n==null?void 0:n.map(y=>y.idx===x?u:y);r({...a,datasetOptions:j})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(Pt,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(t.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>c("none",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(tn,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(nn,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(sn,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})})]})})]})}function ca(){const s=t.useEditorStore(i=>i.card),{data:a}=t.useDashboardCardQuery(s),{keys:n}=t.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(i=>!t.METADATA_KEYS.includes(i));let o=r;if(["stackedBar","stackedLine"].includes(s.type)){const i=t.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:c}=t.getKeys(i);o=c.slice(1)}return{transformedMetricKeys:o,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function ft({children:s,className:a,delayDuration:n}){return e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{delayDuration:n,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:t.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}function as(){const s=t.useEditorStore(l=>l.card),a=t.useEditorStore(l=>{var x,h,u;return(u=(h=(x=l==null?void 0:l.card)==null?void 0:x.preferences)==null?void 0:h.chartOptions)==null?void 0:u.indexAxis}),{data:n}=t.useDashboardCardQuery(s),r=a==="y"?"Metric":"Dimension",o=a==="y"?"Dimension":"Metric",{dimensionKeys:i,transformedMetricKeys:c,keys:d}=ca();return d.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:i.map(l=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:l,children:rs(l)},l))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:o}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((l,x)=>e.jsx(os,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:l,idx:x},l))})]})]})}function rs(s,a=30){return s.length>a?s.slice(0,a)+"...":s}function os({col:s,idx:a,className:n,iconClassName:r,children:o}){const i=t.useEditorStore(h=>{var u;return(u=h.card)==null?void 0:u.preferences}),c=t.useEditorStore(h=>{var u,j;return(j=(u=h.card)==null?void 0:u.preferences)==null?void 0:j.datasetOptions}),d=c==null?void 0:c.find(h=>h.idx===a),{setCardPreferences:l}=t.useEditorStore(h=>h.actions);function x(h){if(!d)l({...i,datasetOptions:[...c||[],{idx:a,type:h==="area"?"line":h,fill:h==="area"?"origin":""}]});else{const u={...d};u.type=h==="area"?"line":h,u.fill=h==="area"?"origin":"";const j=c==null?void 0:c.map(y=>y.idx===a?u:y);l({...i,datasetOptions:j})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[o||e.jsx(ft,{className:"max-w-[100px]",title:s,children:rs(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Be,{onClick:()=>x("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Fe,{onClick:()=>x("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Vs,{onClick:()=>x("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(la,{idx:a})]})]})}function is(){const s=t.useEditorStore(y=>y.selectedConnectionId),a=t.useEditorStore(y=>y.selectedDatamodelId),n=t.useEditorStore(y=>y.selectedDatabaseName),r=t.useEditorStore(y=>y.selectedSchemaName),o=t.useEditorStore(y=>y.selectedTableName),i=t.useDashboardStore(y=>y.dashboard.filters)||[],c=t.useDashboardStore(y=>y.actions.addFilter),d=t.useDashboardStore(y=>y.actions.removeFilter),{removeFilterValues:l}=t.useDashboardActions(),{modelItems:x,tableName:h,connectionType:u}=t.useEditorAside();function j(y,N="dashboard"){var C;const f=t.fmt(y.column_name),E=t.fmt(n||""),p=t.fmt(r||""),g=t.fmt(h);let O=t.getQualifiedTableName({schemaName:p,tableName:g,connectionType:u,databaseName:E}),I=`${O}.${f}`;const k=(C=x==null?void 0:x.find(S=>S.id===a))==null?void 0:C.name;a&&a!=="none"&&(I=`${t.DATAMODEL_NAMESPCACE}.${k}.${f}`,O=`${t.DATAMODEL_NAMESPCACE}.${k}`);const v=i==null?void 0:i.find(S=>S.column===I&&S.table===g&&(S.database===E||S.database===n));if(v)l(v.id),d(v.id);else{const S=t.v4();return h==="api"&&s?(c({location:N,id:S,column:I,title:y.column_name,dataType:y.data_type,table:"api",database:"",connectionId:s,operation:"in",sql:t.getDefaultFilterSql(y.data_type,O,f)}),S):(c({id:S,location:N,column:I,title:y.column_name,dataType:y.data_type,table:o||"",database:n||"",connectionId:s||"",operation:"in",sql:t.getDefaultFilterSql(y.data_type,O,f)}),S)}}return{assignFilter:j}}function Ne(){const s=t.useDashboardStore(d=>d.dashboard.filters),a=t.useEditorStore(d=>d.frame),{setFrame:n}=t.useEditorActions(),{columns:r}=t.useEditorAside(),{assignFilter:o}=is();function i(d){const l=o(d,"frame");n({...a,filterId:l})}const c=s==null?void 0:s.find(d=>d.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Card Filter"}),e.jsx(da,{onSelect:i,columns:r}),c&&e.jsx(t.FilterHeader,{filter:c})]})}function da({columns:s,onSelect:a}){var c;const[n,r]=he.useState(!1),[o,i]=he.useState("");return e.jsxs(t.Popover,{open:n,onOpenChange:r,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[o?(c=s.find(d=>d.column_name===o))==null?void 0:c.column_name:"Select Column...",e.jsx(t.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No framework found."}),e.jsx(t.CommandGroup,{children:s==null?void 0:s.map(d=>e.jsxs(t.CommandItem,{value:d.column_name,onSelect:l=>{const x=l===o?"":l;i(x),r(!1),x&&a(d)},children:[d.column_name,e.jsx(t.CheckIcon,{className:t.cn("ml-auto h-4 w-4",o===d.column_name?"opacity-100":"opacity-0")})]},d.column_name))})]})]})})]})}function ua({cardType:s}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} Chart`}),e.jsxs(t.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsx(t.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(as,{})})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(je,{}),e.jsx(Ne,{})]})]})]})})}function Ve(){const s=t.useEditorStore(d=>d.card.type),a=t.useEditorStore(d=>d.isDevMode),n=t.useEditorStore(d=>d.card.preferences),{setCardPreferences:r}=t.useEditorStore(d=>d.actions);function o(d){var h;const l={datalabels:{display:d!=="none",align:d,anchor:d,clamp:!0}},x={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(h=n==null?void 0:n.chartOptions)==null?void 0:h.plugins,...l}}};r(x)}function i(){var d,l,x;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.Select,{value:((x=(l=(d=n==null?void 0:n.chartOptions)==null?void 0:d.plugins)==null?void 0:l.datalabels)==null?void 0:x.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Data Labels"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"start",children:"Start"}),e.jsx(t.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var d,l,x;return e.jsx("div",{children:e.jsxs(t.Select,{value:((x=(l=(d=n==null?void 0:n.chartOptions)==null?void 0:d.plugins)==null?void 0:l.datalabels)==null?void 0:x.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(t.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?i():c()})}function ma({cardType:s}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:i=>i.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} Chart`}),e.jsx(t.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(s)})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsx(t.AccordionContent,{className:"px-2",children:e.jsx(Ve,{})})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(je,{}),e.jsx(Ne,{})]})]})]})})}const ha={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},xa={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function pa(){const s=t.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(t.Accordion,{className:" ",type:"single",collapsible:!0,children:fa(s)}),!["kpi"].includes(s)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ve,{}),e.jsx(je,{}),e.jsx(Ne,{})]})]})}function fa(s){if(["line","bar"].includes(s))return e.jsxs(e.Fragment,{children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(t.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(ha,null,2)})]})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(t.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(xa,null,2)})]})]})]});if(s==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:s})," chart query?"]})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(s==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:s})," chart query?"]})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(s))return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:s==="polarArea"?"Polar":s.charAt(0).toUpperCase()+s.slice(1)})," ","chart query"]})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function ga(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(t.Accordion,{type:"single",collapsible:!0,children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(t.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(t.FormatNumberSetting,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function He({children:s,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,className:t.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(t.Label,{children:a}),e.jsx(t.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:s})]})}const ja=[{label:"Mercator",value:"mercator"},{label:"Azimuthal Equidistant",value:"azimuthalEquidistant"},{label:"Gnomonic",value:"gnomonic"},{label:"Orthographic",value:"orthographic"},{label:"Stereographic",value:"stereographic"},{label:"Equal Earth",value:"equalEarth"},{label:"Albers",value:"albers"},{label:"Albers USA",value:"albersUsa"},{label:"Conic Conformal",value:"conicConformal"},{label:"Conic Equal Area",value:"conicEqualArea"},{label:"Conic Equidistant",value:"conicEquidistant"},{label:"Equirectangular",value:"equirectangular"},{label:"Transverse Mercator",value:"transverseMercator"},{label:"Natural Earth 1",value:"naturalEarth1"}],ya=["blues","brBG","buGn","buPu","cividis","cool","cubehelixDefault","gnBu","greens","greys","inferno","magma","orRd","oranges","pRGn","piYG","plasma","puBu","puBuGn","puOr","puRd","purples","rainbow","rdBu","rdGy","rdPu","rdYlBu","rdYlGn","reds","sinebow","spectral","turbo","viridis","warm","ylGn","ylGnBu","ylOrBr","ylOrRd"],ba=ya.map(s=>({label:s,value:s}));function va(){var l,x,h,u,j,y,N,f,E,p,g,O,I,k,v,C,S,D;const s=t.useEditorStore(w=>w.card),a=(x=(l=s==null?void 0:s.preferences)==null?void 0:l.mapVisualOptions)==null?void 0:x.topoJsonUrl,[n,r]=L.useState(((u=(h=s==null?void 0:s.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:u.customTopoJsonUrl)||""),{setCardPreferences:o}=t.useEditorActions(),{data:i}=t.useTopoJson(s),c=Object.keys((i==null?void 0:i.objects)||{}).map(w=>({label:w,value:w}))||[],d=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(He,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(He,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(ae,{className:"h-9",options:d,onValueChange:w=>{console.log("value",w),o({...s.preferences,mapVisualOptions:{topoJsonUrl:w}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(t.Input,{onChange:w=>{r(w.target.value)},onBlur:()=>{var w;console.log("onBlur",n),o({...s.preferences,mapVisualOptions:{...(w=s.preferences)==null?void 0:w.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${t.removeRing}`,placeholder:"Custom URL"}),i&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Map Object"}),e.jsx(ae,{className:"h-9",options:c,value:((y=(j=s.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:y.objectKey)||"",label:"Map Object",onValueChange:w=>{var m;o({...s.preferences,mapVisualOptions:{...(m=s.preferences)==null?void 0:m.mapVisualOptions,objectKey:w}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(ae,{className:"h-9",options:ja,value:((f=(N=s.preferences)==null?void 0:N.mapVisualOptions)==null?void 0:f.projection)||"",label:"Projection",onValueChange:w=>{var m;o({...s.preferences,mapVisualOptions:{...(m=s.preferences)==null?void 0:m.mapVisualOptions,projection:w}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(ae,{className:"h-9",options:ba,value:((p=(E=s.preferences)==null?void 0:E.mapVisualOptions)==null?void 0:p.colorScale)||"",label:"Select Color Scale",onValueChange:w=>{var m;o({...s.preferences,mapVisualOptions:{...(m=s.preferences)==null?void 0:m.mapVisualOptions,colorScale:w}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(He,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:.1,value:((O=(g=s.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:O.projectionScale)||1,onChange:w=>{var m;o({...s.preferences,mapVisualOptions:{...(m=s.preferences)==null?void 0:m.mapVisualOptions,projectionScale:Number(w.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((v=(k=(I=s.preferences)==null?void 0:I.mapVisualOptions)==null?void 0:k.projectionOffset)==null?void 0:v[0])||0,onChange:w=>{var m,B,M,T;o({...s.preferences,mapVisualOptions:{...(m=s.preferences)==null?void 0:m.mapVisualOptions,projectionOffset:[Number(w.target.value),((T=(M=(B=s.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:M.projectionOffset)==null?void 0:T[1])||0]}})}}),e.jsx(t.Label,{children:"Y"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((D=(S=(C=s.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:S.projectionOffset)==null?void 0:D[1])||0,onChange:w=>{var m,B,M,T;o({...s.preferences,mapVisualOptions:{...(m=s.preferences)==null?void 0:m.mapVisualOptions,projectionOffset:[((T=(M=(B=s.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:M.projectionOffset)==null?void 0:T[0])||0,Number(w.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(je,{})]})}function Na(){var r;const s=t.useEditorStore(o=>o.card.preferences),{setCardPreferences:a}=t.useEditorStore(o=>o.actions);function n(o){a({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:o==="dynamic"}})}return e.jsxs(t.RadioGroup,{value:(r=s==null?void 0:s.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Ie({cardType:s,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return s==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} ${n}`}),e.jsx(t.AccordionContent,{children:a||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[s!=="text"&&e.jsx(Ve,{}),s==="text"&&e.jsx(Na,{})]})]}),!["range","text"].includes(s)&&e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(je,{}),e.jsx(Ne,{})]})]})]})})}function Ca(){const s=t.useEditorStore(r=>{var o,i;return(i=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:i.sortChart}),{setSortChart:a}=t.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Sort"}),e.jsx(ae,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:s||"none",onValueChange:r=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(t.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(as,{})]})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(je,{}),e.jsx(Ne,{})]})]})]})})}function Sa({cardType:s="table"}){console.log("cardType",s);const a=t.useEditorStore(o=>{var i;return(i=o.card)==null?void 0:i.preferences}),n=t.useEditorStore(o=>o.actions.setCardPreferences),r=o=>{n({...a,allowDownload:o})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(t.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(je,{}),e.jsx(Ne,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}const wa=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT dimension, cohort, metric FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),ka=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),Ea=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function Da(){const s=t.useEditorStore(n=>n.card.type);function a(n){switch(n){case"stackedBar":case"stackedLine":return e.jsx(Ca,{});case"tornado":case"pyramid":return e.jsx(Ie,{docContent:wa,cardType:n});case"kpi":return e.jsx(ga,{});case"line":case"bar":return e.jsx(ua,{cardType:n});case"range":return e.jsx(Ie,{docContent:ka,cardType:n});case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return e.jsx(Ie,{cardType:n});case"bubble":case"scatter":return e.jsx(ma,{cardType:n});case"table":return e.jsx(Sa,{cardType:n});case"text":return e.jsx(Ie,{docContent:Ea,cardType:n,suffix:"Visual"});case"map":return e.jsx(va,{});case"custom":return e.jsx(ia,{});default:return e.jsx(pa,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[a(s),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function ls({label:s,column:a,functions:n,onFunctionChange:r}){let o=n[0];"aggregate"in a?o=n.find(c=>c.value===a.aggregate)||n[0]:"granularity"in a&&(o=n.find(c=>c.value===a.granularity)||n[0]);function i(c){r(c)}return e.jsx(ae,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:o.logo,options:n,value:o.value,onValueChange:c=>i(c),label:s,showPlaceholderLabel:!1})}const Ia=[{label:"Sum",value:"SUM",logo:e.jsx(zt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(nt,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(Qs,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(Is,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(t.ArrowDown,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(t.ArrowUp,{className:"size-3.5"})}];function Ta({column:s}){const{updateMetricColumnOld:a}=t.useEditorActions();let n=Ia;t.isTextDataType(s.type)&&(n=n.filter(o=>["COUNT","DISTINCT"].includes(o.value))),t.isNumberDataType(s.type)&&(n=n.filter(o=>!["DISTINCT"].includes(o.value)));function r(o){const i={...s,aggregate:o,label:ke(s.name,o)};a(s.id,i)}return e.jsx(ls,{column:s,functions:n,onFunctionChange:o=>r(o),label:"Aggregation"})}const Ma=[{label:"Day (D)",value:"day",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function Aa({column:s}){const{updateGroupByColumnOld:a}=t.useEditorActions();function n(r){const o={...s,granularity:r,label:ve(s.name,r)};a(s.id,o)}return e.jsx(ls,{column:s,functions:Ma,onFunctionChange:r=>n(r),label:"Granularity"})}function La({col:s,onChange:a,droppableId:n}){const{columns:r}=t.useDataColumns(),o=L.useMemo(()=>{let d=[];(n===xe||n===pe||n===fe)&&(d=r);const l=d==null?void 0:d.filter(x=>x.column_name!==s.name);return l==null?void 0:l.map(x=>({id:x.column_name,value:x.column_name}))},[r,n,s.name]),i=[{id:s.name,value:s.name}];function c(d){const l=r==null?void 0:r.find(x=>{var h;return x.column_name===((h=d[0])==null?void 0:h.id)});l&&a(l)}return o!=null&&o.length?e.jsx(t.ComboBox2,{multiple:!1,options:o,selectedOptions:i,onChange:c,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:s.name})}function cs({column:s}){const a=t.useEditorStore(l=>l.card.type),n=t.useEditorStore(l=>{var x,h;return(h=(x=l.card)==null?void 0:x.config)==null?void 0:h.metricColumns}),r=(n==null?void 0:n.map(l=>l.label))||[],o=r==null?void 0:r.find(l=>l===s.label||l===s.name),i=o?r.indexOf(o):-1;function c(){return e.jsx("div",{className:"pr-1",children:o&&e.jsx(os,{idx:i,col:o,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function d(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Ve,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&c(),["pie","doughnut"].includes(a)&&d()]})}function Oa({column:s,type:a,onRemoveColumn:n,droppableId:r}){const[o,i]=L.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:d,updatePivotByColumnOld:l}=t.useEditorActions(),{attributes:x,listeners:h,setNodeRef:u,transform:j,transition:y,isDragging:N}=t.useSortable({id:s.id,data:{type:a}}),f=j?{opacity:N?.5:void 0,transform:t.CSS.Translate.toString(j),transition:y}:void 0,E=t.isTextDataType(s.type);function p(v){const C=t.isNumberDataType(v.data_type),S=t.isTextDataType(v.data_type),D=t.isDateDataType(v.data_type),w=C?"number":S?"string":D?"date":"string";if(r===xe){if(S){const m={id:s.id,name:v.column_name,type:w,role:"groupby"};c(s.id,m)}if(D){const m={id:s.id,name:v.column_name,type:w,role:"groupby",label:ve(v.column_name,"month"),granularity:"month"};c(s.id,m)}}if(r===fe){if(S){const m={id:s.id,name:v.column_name,type:w,role:"groupby"};l(s.id,m)}if(D){const m={id:s.id,name:v.column_name,type:w,label:ve(v.column_name,"month"),granularity:"month",role:"groupby"};l(s.id,m)}}if(r===pe){const m={id:s.id,name:v.column_name,type:w,role:"metric",label:ke(v.column_name,"SUM"),aggregate:C?"SUM":"COUNT"};d(s.id,m)}}function g(){if(r===pe)return e.jsx("div",{"data-setting-container":"",className:"mt-1.5 max-h-32 overflow-y-auto rounded-md border border-border p-3 text-sm",children:e.jsx(cs,{column:s})})}function O(){const v=t.isDateDataType(s.type);if(r===pe)return e.jsx(Ta,{column:s});if((r===xe||r===fe)&&v)return e.jsx(Aa,{column:s})}function I(){return e.jsx("div",{className:t.cn("grow",{"pl-3":(r===xe||r===fe)&&E}),children:e.jsx(La,{col:s,onChange:p,droppableId:r})})}function k(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>i(!o),children:o?e.jsx(pn,{className:t.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(Bt,{className:t.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...h,...x,ref:u,style:f,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[k(),O(),I()]}),o&&g()]}),e.jsx("div",{className:t.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:o}),children:e.jsx("button",{onClick:()=>n(s.id),children:e.jsx(t.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function Ue({id:s,label:a,columns:n,previewColumns:r,sortableType:o,onRemoveColumn:i}){var f,E;const{setNodeRef:c,isOver:d,over:l}=t.useDroppable({id:s}),x=t.useDndStore(p=>p.activeId),h=t.useEditorStore(p=>{var g;return(g=p.card)==null?void 0:g.type}),u=d||((E=(f=l==null?void 0:l.data)==null?void 0:f.current)==null?void 0:E.type)===o,j=x?r:n,y=o===Me?"Rows":o===Ae?"Pivot Columns":"Columns";function N(){if(!j||j.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(t.SortableContext,{items:n==null?void 0:n.map(p=>p.id),children:e.jsxs("div",{className:t.cn("group space-y-2 rounded-md p-4",u&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(t.Label,{className:"text-sm",children:a}),h!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:y})]}),N(),e.jsx("div",{className:"space-y-2",children:j==null?void 0:j.map(p=>p.id===Jt.id?e.jsx(Ba,{},p.id):e.jsx(Oa,{droppableId:s,type:o,column:p,onRemoveColumn:i},p.id))})]})})}function Ba(){return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm",children:e.jsx("span",{className:"text-muted-foreground/70",children:"Drop here"})})}function ds({children:s,id:a,type:n}){const{attributes:r,listeners:o,setNodeRef:i,transform:c,transition:d,isDragging:l}=t.useSortable({id:a,data:{type:n}}),x=c?{opacity:l?.5:void 0,transform:t.CSS.Translate.toString(c),transition:d}:void 0;return e.jsx("div",{...o,...r,ref:i,style:x,children:s})}function Fa(){const s=t.useEditorStore(p=>{var g;return(g=p.card.queryConfig)==null?void 0:g.orderBy})||[],a=t.useEditorStore(p=>{var g;return(g=p.card.queryConfig)==null?void 0:g.groupByColumns})||[],n=t.useEditorStore(p=>{var g;return(g=p.card.queryConfig)==null?void 0:g.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:o,updateOrderByColumn:i}=t.useEditorActions(),c=[...a,...n];if(c.length===0)return e.jsx(e.Fragment,{});const d=e.jsx(Ls,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),l=e.jsx(Ds,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),x=e.jsx(As,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=e.jsx(Es,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=c==null?void 0:c.filter(p=>!s.some(g=>g.columnId===p.id)).map(p=>({id:p.id,value:p.label||p.name}));function j(p,g){const O=y(p);return O?O.role==="metric"?g==="asc"?x:h:g==="asc"?d:l:null}function y(p){return c.find(g=>g.id===p)}function N(p){const g=s.find(O=>O.columnId===p);if(g){const O={...g,direction:g.direction==="asc"?"desc":"asc"};i(O)}}const f=p=>{r({columnId:p.id,direction:"asc"})};function E(p){const g=s.find(O=>O.columnId===p);g&&o(g)}return e.jsx(t.SortableContext,{items:s.map(p=>Ce(p.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(t.Label,{className:"text-sm",children:"Sort By"}),u.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(t.ComboBox2,{multiple:!1,options:u,selectedOptions:[],onChange:p=>f(p[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),s.map(p=>{var g,O;return e.jsx(ds,{id:Ce(p.columnId),type:ct,children:e.jsx("div",{className:"group flex h-8 items-center gap-2 rounded-sm p-0",children:e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2 rounded-sm bg-muted px-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Bt,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(ft,{className:"w-[175px] text-sm",children:((g=y(p.columnId))==null?void 0:g.label)||((O=y(p.columnId))==null?void 0:O.name)})]}),e.jsx("button",{title:p.direction==="asc"?"Ascending":"Descending",onClick:()=>N(p.columnId),className:"rounded-sm p-0",children:j(p.columnId,p.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>E(p.columnId),className:"rounded-sm p-0",children:e.jsx(t.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},p.columnId)},Ce(p.columnId))})]})})}function za(){const s=t.useEditorStore(E=>{var p;return((p=E.card.queryConfig)==null?void 0:p.groupByColumns)||[]}),a=t.useEditorStore(E=>E.card.type),n=t.useDndStore(E=>E.previewGroupByColumns),r=t.useEditorStore(E=>{var p;return((p=E.card.queryConfig)==null?void 0:p.metricColumns)||[]}),o=t.useDndStore(E=>E.previewMetricColumns),i=t.useEditorStore(E=>{var p;return((p=E.card.queryConfig)==null?void 0:p.pivotColumns)||[]}),c=t.useDndStore(E=>E.previewPivotColumns),{removeColumnFromGroupBy:d,removeColumnFromMetricColumns:l,removeColumnFromPivotBy:x}=t.useEditorActions();function h(E){d(E)}function u(E){l(E)}function j(E){x(E)}let y="Group By",N="Metrics",f="Stack By";return a==="table"&&(y="Rows",N="Metrics",f="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(es,{iconClassName:"size-[19px]"}),e.jsxs(t.CustomScrollArea,{className:"flex min-h-0 grow basis-0 flex-col gap-4 overflow-y-auto",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e.jsx(Ue,{onRemoveColumn:h,sortableType:Me,id:xe,label:y,columns:s,previewColumns:n}),e.jsx(Ue,{onRemoveColumn:j,sortableType:Ae,id:fe,label:f,columns:i,previewColumns:c}),e.jsx(Ue,{onRemoveColumn:u,sortableType:Ke,id:pe,label:N,columns:r,previewColumns:o}),e.jsx(Fa,{})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function gt({children:s,column:a,id:n,sortableType:r,className:o}){const[i,c]=L.useState(!1),{removeEditorFilter:d,clearEditorFilter:l}=t.useEditorActions(),x=t.useEditorStore(u=>{var j,y;return(y=(j=u.card.queryConfig)==null?void 0:j.filters)==null?void 0:y.some(N=>N.filterColumnName===a.name)});function h(u){d(u)}return e.jsx(ds,{id:n,type:r,children:e.jsxs("div",{className:t.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":i}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-sm",children:a.name}),x&&e.jsx("button",{onClick:()=>l(a),children:e.jsx(t.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>h(a),children:e.jsx(t.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:t.cn("group flex items-center rounded-t-md text-sm",!i&&"rounded-b-md",i&&"border border-border"),children:[e.jsx("div",{children:e.jsx(t.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:t.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",o),children:s})]})]})})}function Pa({column:s,sortableType:a}){const n=t.useDashboardStore(O=>O.themeStyle),r=t.useEditorStore(O=>{var I,k;return(k=(I=O.card)==null?void 0:I.queryConfig)==null?void 0:k.filters}),o=t.useEditorStore(O=>{var I,k;return(k=(I=O.card.queryConfig)==null?void 0:I.filterColumns)==null?void 0:k.find(v=>v.name===s.name)}),{selectedConnectionId:i,selectedDatabaseName:c,selectedTableName:d}=t.useEditorAside(),l=L.useMemo(()=>{var O;return(O=r==null?void 0:r.find(I=>I.filterColumnName===s.name))==null?void 0:O.filterValue},[r,s.name]),x=L.useMemo(()=>Array.isArray(l)?l.map(O=>({id:O,value:O})):[],[l]),{updateEditorFilterValue:h}=t.useEditorActions(),u={column:s.name,sql:s.sql,id:s.name,connectionId:i,dataType:s.type},{data:j,isLoading:y,isFetching:N,isError:f}=t.useFilterQuery(u),E=L.useMemo(()=>{var I;return u.column?(I=j==null?void 0:j.records)==null?void 0:I.map(k=>{let v=u.column.split(".").slice(-1)[0].replace(/"/g,"");return k[v]===void 0&&(v=v.toLowerCase()),{id:k[v],value:k[v]}}):[]},[j,u.column]);function p(O){const I=O.map(k=>k.id);h(s.name,I)}function g(){return y||N?e.jsx(t.Skeleton,{style:{borderRadius:n==null?void 0:n.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):f?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(t.ComboBox2,{renderFilterModeButton:()=>e.jsx(Va,{columnName:s.name}),showNegativeIndicator:(o==null?void 0:o.mode)==="exclude",options:E,onChange:p,selectedOptions:x,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(gt,{className:"w-60",id:s.id,sortableType:a,column:s,children:g()})}function Va({columnName:s}){const{setEditorFilterMode:a}=t.useEditorActions(),n=t.useEditorStore(o=>{var i,c;return(c=(i=o.card.queryConfig)==null?void 0:i.filterColumns)==null?void 0:c.find(d=>d.name===s)});function r(){(n==null?void 0:n.mode)==="exclude"?a(s,"include"):a(s,"exclude")}return e.jsx(t.Button,{onClick:r,variant:"secondary",size:"sm",className:t.cn("h-5 text-xs hover:underline",{}),children:t.titleCase((n==null?void 0:n.mode)==="exclude"?"exclude":"include")})}function Ra({column:s,sortableType:a}){const[n,r]=L.useState(!1),{selectedConnectionId:o,selectedDatabaseName:i,selectedTableName:c}=t.useEditorAside(),d={column:s.name,sql:s.sql,id:s.name,connectionId:o,title:"",dataType:s.type},{isLoading:l,isFetching:x,isError:h,data:u}=t.useFilterQuery(d),j=u==null?void 0:u.records,{dateRange:y,setDateRange:N,initialDateRange:f}=t.useDateRangeFromRecords(j),{updateEditorFilterValue:E}=t.useEditorActions();function p(I){var v,C;const k={gte:(v=I==null?void 0:I.from)==null?void 0:v.toISOString(),lte:(C=I==null?void 0:I.to)==null?void 0:C.toISOString()};E(s.name,k)}function g(){E(s.name,null,!0),N(f)}function O(){return l||x?e.jsx("div",{children:e.jsx(t.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):h?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):j?e.jsx(t.DateRangePopover,{title:d.title,open:n,inputClassName:"h-8",setOpen:r,dateRange:y,setDateRange:N,onApply:p,onClear:g}):e.jsx(t.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(gt,{className:"w-72",id:s.id,sortableType:a,column:s,children:O()})}function qa({id:s,label:a,columns:n,previewColumns:r,sortableType:o}){var N,f;const{setNodeRef:i,isOver:c,over:d}=t.useDroppable({id:s}),l=t.useDndStore(E=>E.activeId),x={},h=c||((f=(N=d==null?void 0:d.data)==null?void 0:N.current)==null?void 0:f.type)===o;function u(){if(!y||y.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function j(E){const p=t.isDateDataType(E.type);return E.id===Jt.id?e.jsx(gt,{id:E.id,sortableType:o,column:E,children:e.jsx(_a,{})},E.id):p?e.jsx(Ra,{droppableId:s,sortableType:o,column:E},E.id):e.jsx(Pa,{droppableId:s,sortableType:o,column:E},E.id)}const y=l?r:n;return e.jsx(t.SortableContext,{items:n==null?void 0:n.map(E=>E.id),children:e.jsxs("div",{className:t.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",h&&"border border-muted-foreground/20"),ref:i,style:x,children:[e.jsx(t.Label,{className:"text-sm",children:a}),u(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:y==null?void 0:y.map(E=>j(E))})]})})}function _a(){return e.jsx("div",{className:"flex h-8 w-60 items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm text-muted-foreground",children:"Drop here"})}function Ga(){const s=t.useEditorStore(o=>{var i;return((i=o.card.queryConfig)==null?void 0:i.filterColumns)||[]}),a=t.useDndStore(o=>o.previewFilterColumns),{removeColumnFromFilterColumns:n}=t.useEditorActions();function r(o){n(o)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(qa,{onRemoveColumn:r,sortableType:We,id:Qe,label:"Filters",columns:s,previewColumns:a})})}function $a(){const s=t.useEditorStore(i=>i.card),a=t.useEditorStore(i=>i.showAIDialog),{setShowAIDialog:n}=t.useEditorActions(),{data:r,errorMessage:o}=t.useDashboardCardQuery(s);return e.jsxs("section",{className:"flex justify-between gap-2 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.EditorClearButton,{}),!a&&e.jsxs(t.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(cn,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(Kt,{sql:r==null?void 0:r.sql,error:o})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-green-300 px-3 py-1 text-xs font-medium text-black",children:"Preview"}),e.jsx(t.EditorCancelButton,{}),e.jsx(t.EditorAcceptButton,{variant:"default"})]})]})}function Ja(){const s=L.useRef(null),a=L.useRef(null),n=t.useEditorStore(d=>d.isShowingVisual),r=t.useEditorStore(d=>d.showAIDialog),o=t.useEditorStore(d=>d.isDevMode);L.useEffect(()=>{var d,l,x,h;r?((d=s.current)==null||d.resize(0),(l=a.current)==null||l.resize(0)):((x=s.current)==null||x.resize(25),(h=a.current)==null||h.resize(25))},[r]);function i(){return e.jsxs(e.Fragment,{children:[e.jsx(t.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx($n,{})}),e.jsx(t.ResizableHandle,{withHandle:!0}),e.jsx(t.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!r?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(t.ResizablePanel,{ref:s,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Da,{})})}),!r&&e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(De,{})})]}):e.jsx(De,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:n?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(t.ResizablePanel,{ref:a,defaultSize:25,maxSize:30,children:e.jsx(za,{})})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(t.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(t.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx($a,{}),e.jsx(Ga,{})]}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(De,{})})]})})]}):e.jsx(De,{})})})}return e.jsx(t.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:o?i():c()})}function Ha(s){const a=t.useAIInteractionStore(_=>_.currentAIContext),[n,r]=L.useState(""),[o,i]=L.useState(null),{authToken:c}=t.useSemaphorContext(),d=t.useEditorStore(_=>{var Q;return(Q=_==null?void 0:_.card)==null?void 0:Q.sql}),l=t.useEditorStore(_=>_.isDevMode),x=t.useEditorStore(_=>{var Q;return(Q=_==null?void 0:_.card)==null?void 0:Q.python}),{setCardPython:h,setCardSql:u,setRunSql:j,switchCardType:y,setQueryConfig:N}=t.useEditorActions(),f=t.useEditorStore(_=>_.currentAssitantScope)||[],E=t.useEditorStore(_=>_.userInputForAI),p=t.useEditorStore(_=>_.triggerAIRun),g=t.useEditorStore(_=>_.card),O=t.useEditorStore(_=>_.selectedDatabaseName),I=t.useEditorStore(_=>_.selectedTableName),k=t.useEditorStore(_=>_.selectedConnectionId),v=t.useEditorStore(_=>_.selectedSchemaName),C=t.useDashboardStore(_=>_.dashboard.aiScopeTables),{errorMessage:S,refetch:D,data:w}=t.useDashboardCardQuery(g),{setTriggerAIRun:m,setCurrentAssitantScope:B,setCardConfig:M}=t.useEditorActions(),{selectedDatamodelName:T,connectionType:b,selectedDatamodelId:A}=t.useEditorAside(),{messages:F,setMessages:P,reload:R,error:z,append:Y,input:V,setInput:q,status:H,handleInputChange:K,handleSubmit:G,stop:$}=t.useChat({api:"https://semaphor.cloud/api/v1/assistant",headers:{Authorization:`Bearer ${c==null?void 0:c.accessToken}`},body:{random:Math.random(),assistantId:"editor-assistant",isDevMode:l,aiContext:a},maxSteps:10,onError:_=>{console.log("on error",_)},onToolCall:J,onFinish(_,Q){X(Q.usage),r(""),Q.finishReason==="stop"&&r("")}});L.useEffect(()=>{p&&E&&(Y({role:"user",content:E}),m(!1))},[p,E,Y,m]);async function J({toolCall:_}){var Q,oe,de,me;if(["createChartFromSql","createForecast"].includes(_.toolName)){const W=_.args.sql,Z=_.args.python,ee=_.args.chartType;return y(ee),u(W),h(Z),j(!0),{status:"success",message:"Let the user know that chart is created"}}else if(_.toolName==="getTableColumns")r("Getting table columns...");else{if(_.toolName==="getUserSql")return d?{status:"success",sql:d,python:x||""}:{status:"error",message:"No SQL found"};if(_.toolName==="getCurrentTableScope")return r("Getting table scope..."),ne(),{status:"success",tables:f};if(_.toolName==="generateQueryConfig"){r("Generating query config...");const W=_.args.chartType,Z=_.args.queryConfig;_.args.cardConfig,y(W),M(Z),u(void 0),h(void 0);const ee=await D();return(Q=ee==null?void 0:ee.data)!=null&&Q.error?{status:"error",queryConfig:Z,message:(oe=ee==null?void 0:ee.data)==null?void 0:oe.error.message}:(de=ee==null?void 0:ee.data)!=null&&de.records?{status:"success",queryConfig:Z,message:"The data has been visualized"}:{status:"success",queryConfig:Z,message:"The data has been visualized",records:(me=ee==null?void 0:ee.data)==null?void 0:me.records}}else r("Analyzing...")}}function X(_){i(Q=>Q?{promptTokens:Q.promptTokens+_.promptTokens,completionTokens:Q.completionTokens+_.completionTokens,totalTokens:Q.totalTokens+_.totalTokens}:_)}function se(_){const Q=t.removeFromScopeArray(f,_);re(Q)}function re(_){const Q=t.sanitizeAIScope(_);B(Q),P(oe=>[...oe,{id:crypto.randomUUID(),role:"system",content:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(Q)}`}])}function le(){const _={databaseName:O||"",schemaName:v||"",tableName:I||"",datamodelId:A||"",datamodelName:t.resolveDatamodelName(T),connectionId:k||"",connectionType:b||""},Q=t.dedup([...f,_]);re(Q)}function ne(){const _={databaseName:O||"",schemaName:v||"",tableName:I||"",datamodelName:t.resolveDatamodelName(T),connectionId:k||"",connectionType:b||"",datamodelId:A||""};if(!t.isInAiScopeArray([...C||[],...f],_)||f.length===0){const oe=t.dedup([...C||[],...f,_]).filter(de=>de.connectionId===_.connectionId);re(oe)}}const te=!["ready","error"].includes(H),ce=t.getErrorMessage(z);return{messages:F,setMessages:P,reload:R,append:Y,input:V,setInput:q,isLoading:te,handleSetAIScope:ne,handleAddCurrentTableToScope:le,removeFromCurrentSelections:se,currentAssitantScope:f,setCurrentAssitantScope:B,handleInputChange:K,handleSubmit:G,stop:$,chatStatus:H,toolStatus:n,llmUsage:o,onFinish:s,errorMessage:ce}}const Ua=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function Tt(){const s=L.useRef(null),a=L.useRef(null),[n,r]=L.useState(!1),[o,i]=L.useState(t.isDevEnv),[c,d]=L.useState(!1),[l,x]=L.useState(!1),h=t.useCurrentAIContext(),{setCurrentAIContext:u}=t.useAIActions(),j=t.useDashboardStore($=>$.dashboard.aiContext),y=t.useEditorStore($=>$.card.dataSource),N=t.useEditorStore($=>$.actions.setCardSql),f=t.useEditorStore($=>$.actions.setRunSql),E=t.useEditorStore($=>$.showAIDialog),p=t.useDashboardStore($=>$.handleOpenAssistantProfile),{setShowAIDialog:g,setCardPython:O}=t.useEditorActions(),{setDataSource:I}=t.useEditorActions(),{assistantProfile:k}=t.useAssistantProfile(),{messages:v,setMessages:C,reload:S,append:D,input:w,setInput:m,isLoading:B,handleInputChange:M,handleSubmit:T,stop:b,chatStatus:A,llmUsage:F,errorMessage:P}=Ha();t.useAssistantScroll({scrollContainerRef:s,inputRef:a,messages:v}),L.useEffect(()=>{var $;E&&(($=a.current)==null||$.focus(),u({selectedEntities:(y==null?void 0:y.selectedEntities)||[]}))},[E,y,u]);function R($,J){J==="sql"?(N($),f(!0)):J==="python"&&(O($),f(!0))}function z(){var $;($=j==null?void 0:j.selectedEntities)==null||$[0],x(!0)}function Y(){h.selectedEntities.length===0&&u({selectedEntities:(j==null?void 0:j.selectedEntities)||[]})}function V($){Y();const J={role:"user",content:$.title+" "+$.subtitle};D(J)}function q($){Y(),D({role:"user",content:$})}function H(){return e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.Button,{className:"h-7 p-2",size:"sm",variant:"ghost",children:e.jsx(t.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",children:[e.jsx(t.DropdownMenuLabel,{children:"Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsx(t.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:r,children:"Token Usage"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:i,children:"Tool Invocations"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:d,children:"System Message"})]})]})}function K(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const G=(w==null?void 0:w.length)===0&&(v==null?void 0:v.filter($=>$.role==="user").length)===0;return e.jsxs("div",{"data-role":"editor-assistant",className:"flex h-full w-full flex-col justify-between px-6 py-4",children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[K(),p&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:p,children:(k==null?void 0:k.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center gap-2",children:[H(),e.jsx(t.IconButton,{tooltip:"Add Context",className:"h-7 p-2",onClick:z,children:e.jsx(t.Settings,{className:"size-4"})}),e.jsx(t.IconButton,{className:"h-7 p-2",tooltip:"New Chat",onClick:()=>{C([]),S()},children:e.jsx(t.SquarePen,{className:"size-4"})}),e.jsx(t.Button,{variant:"ghost",className:"h-8",size:"sm",onClick:()=>{g(!1)},children:e.jsx(t.PanelRight,{className:"size-4"})})]})]}),e.jsx(t.CustomScrollArea,{ref:s,className:"mt-2 flex w-full grow basis-0",children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[e.jsx(t.PrintMessages,{messages:v,showTools:o,handleRun:R,showSystemMessage:c}),e.jsx(t.ChatStatus,{messages:v,chatStatus:A,errorMessage:P})]})}),e.jsxs("div",{className:"mb-3",children:[G&&!k&&e.jsx(t.Placeholders,{onClick:V,placeholders:Ua}),e.jsx("div",{children:G&&k&&e.jsx(t.SeedQuestions,{seedQuestions:k.seedQuestions||[],handleSeedQuestionClick:q})})]}),e.jsx(t.ChatInputWithContext,{ref:a,setInput:m,stop:b,input:w,handleInputChange:M,handleSubmit:$=>{Y(),T($)},isLoading:B,onFocus:()=>{}}),F&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",F.promptTokens," prompt tokens,"," ",F.completionTokens," completion tokens,"," ",F.totalTokens," total tokens"]})}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:(y==null?void 0:y.selectedEntities)||[],open:l,onOpenChange:x,dataSource:y||t.EMPTY_DATA_SOURCE,fallbackDataSource:t.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function Ya({field:s}){const{attributes:a,listeners:n,setNodeRef:r,transform:o,transition:i,isDragging:c}=t.useSortable({id:s.id}),[d,l]=L.useState(!1),x={transform:t.CSS.Transform.toString(o),transition:i},h=t.getDataType(s.dataType),j=(y=>{const N=(y||"").toLowerCase();switch(t.getDataType(N)){case"number":return nt;case"date":return t.Calendar;case"boolean":return Vt;case"json":return qs;case"geo":return on;default:return Rt}})(s.dataType);return e.jsxs("div",{ref:r,style:x,...a,...n,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:border-blue-200 hover:bg-blue-50 dark:hover:border-blue-800 dark:hover:bg-blue-950"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1 p-2",children:[e.jsx("div",{className:"flex-shrink-0 hover:cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"invisible size-3.5 text-gray-400 group-hover/container:visible"})}),e.jsx(j,{className:t.cn("size-3.5 flex-shrink-0 text-gray-500",h==="string"?"text-blue-500":"",h==="number"?"text-green-500":"",h==="date"?"text-purple-500":"",h==="boolean"?"text-orange-500":"")}),e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm text-foreground/90 hover:text-foreground dark:text-muted-foreground ${d?"whitespace-normal break-words":"truncate"}`,children:s.name})})}),e.jsx(t.TooltipContent,{side:"bottom",align:"start",className:"max-w-fit",children:e.jsxs("div",{className:"overflow-x-auto",children:[e.jsx("p",{className:t.cn("font-medium",{"text-blue-500":h==="string","text-green-500":h==="number","text-purple-500":h==="date","text-orange-500":h==="boolean"}),children:s.label||s.name}),s.description&&e.jsx("div",{className:"mt-1 text-sm text-muted-foreground",children:s.description}),e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(mn,{className:"size-3.5"}),e.jsx("p",{className:"",children:s.qualifiedEntityName?`${s.qualifiedEntityName}.${s.name}`:s.name})]}),e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(j,{className:t.cn("size-3 flex-shrink-0 text-gray-500",h==="string"?"text-blue-500":"",h==="number"?"text-green-500":"",h==="date"?"text-purple-500":"",h==="boolean"?"text-orange-500":"")}),e.jsx("p",{className:t.cn("text-xs font-normal text-gray-500"),children:s.dataType})]})]})})]})}),e.jsx("button",{onClick:y=>{y.stopPropagation(),l(!d)},className:"invisible flex-shrink-0 text-gray-400 hover:text-gray-600 group-hover/container:visible",children:d?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"})})]}),d&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(t.Card,{className:"",children:e.jsxs(t.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:s.label||s.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:s.name})]}),e.jsx(t.Badge,{variant:"outline",className:"mt-2 text-xs",children:s.dataType})]})})})]})}function Ka({entityGroup:s,fields:a,isOpen:n,onToggle:r}){return e.jsxs(t.Collapsible,{open:n,onOpenChange:r,children:[e.jsxs(t.CollapsibleTrigger,{className:"flex w-full items-center gap-2 rounded-md px-3 py-2 hover:bg-muted",children:[e.jsx("span",{className:"flex-1 text-left text-sm font-medium",children:s.label||s.entityName}),e.jsxs("span",{className:"text-xs text-gray-500",children:["(",a.length,")"]}),n?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"})]}),e.jsx(t.CollapsibleContent,{className:"mt-1 space-y-1",children:e.jsx(t.SortableContext,{items:a.map(o=>o.id),strategy:t.verticalListSortingStrategy,children:a.map(o=>e.jsx(Ya,{field:o},o.id))})})]})}function Qa(){const[s,a]=L.useState(""),[n,r]=L.useState(new Set),[o,i]=L.useState("all");Wa();const c=t.useEditorStore(I=>I.card.dataSource),{columns:d=[],columnGroups:l=[],isLoading:x,error:h}=t.useColumns(),u=d.filter(I=>I.name.toLowerCase().includes(s.toLowerCase())||I.dataType.toLowerCase().includes(s.toLowerCase())||I.qualifiedEntityName&&I.qualifiedEntityName.toLowerCase().includes(s.toLowerCase())),j=I=>I.dataType==="number"||I.dataType==="integer"||I.dataType==="float"||I.dataType==="decimal"||I.dataType==="currency"?"metrics":"dimensions",N=(o==="all"?u:u.filter(I=>j(I)===o)).reduce((I,k)=>{const v=k.qualifiedEntityName||"Other Fields";return I[v]||(I[v]={label:t.toLabel(k.entityName),fields:[]}),I[v].fields.push(k),I},{});L.useEffect(()=>{const I=Object.keys(N);r(new Set(I))},[Object.keys(N).join(",")]);const f=I=>{const k=new Set(n);k.has(I)?k.delete(I):k.add(I),r(k)},E=u.filter(I=>j(I)==="dimensions").length,p=u.filter(I=>j(I)==="metrics").length,g=u.filter(I=>j(I)==="calculated").length,O=u.length>0;return x?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(t.LoaderCircle,{className:"h-8 w-8 animate-spin text-gray-400"}),e.jsx("span",{className:"mt-2 text-sm text-gray-500",children:"Loading fields..."})]}):h?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(t.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:h.message||"Failed to load column data"})]}):!c||!c.selectedEntities||c.selectedEntities.length===0?e.jsx(t.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(t.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[d.length>0&&e.jsx("div",{className:"mb-4",children:e.jsx(t.Input$1,{type:"text",placeholder:"Search fields...",value:s,onChange:I=>a(I.target.value)})}),O&&e.jsx(t.Tabs,{defaultValue:"all",value:o,onValueChange:I=>i(I),className:"mb-4",children:e.jsxs(t.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(t.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:u.length})]}),e.jsxs(t.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(t.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:E})]}),e.jsxs(t.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(t.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:p})]}),e.jsxs(t.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(Ps,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:g})]})]})})]}),e.jsxs(t.CustomScrollArea,{className:"py-2",children:[e.jsxs("div",{className:"space-y-2",children:[Object.entries(N).map(([I,k])=>{const v=l.find(C=>C.entityName===I)||{entityName:I,label:k.label};return e.jsx(Ka,{entityGroup:v,fields:k.fields,isOpen:n.has(I),onToggle:()=>f(I)},I)}),Object.keys(N).length===0&&d.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(N).length===0&&d.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"}),e.jsx(t.ScrollBar,{orientation:"vertical"})]})]})}function Wa(){const[s,a]=L.useState(!1);return t.useDndMonitor({onDragStart(){a(!0)},onDragEnd(){a(!1)},onDragCancel(){a(!1)}}),s}function Xa(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(Qa,{})," "]})}function Za({initialJoinPlan:s,availableDataSources:a}){const[n,r]=L.useState(s),[o,i]=L.useState(new Set),c=()=>{const v=n.joins.length>0?Math.max(...n.joins.map(S=>S.sequence))+1:1,C={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({...n,joins:[...n.joins,C]}),i(new Set([...o,C.id]))},d=v=>{r({...n,joins:n.joins.filter(C=>C.id!==v)}),i(new Set([...o].filter(C=>C!==v)))},l=(v,C)=>{var m,B;const S=n.joins.find(M=>M.id===v);if(!S)return;const D={...S,...C},w=n.joins.map(M=>M.id===v?D:M);if((m=D.source)!=null&&m.name&&((B=D.target)!=null&&B.name)&&D.joinKeyGroups[0].keys.length===0){const M=a.find(F=>{var P;return F.name===((P=D.source)==null?void 0:P.name)}),T=a.find(F=>{var P;return F.name===((P=D.target)==null?void 0:P.name)}),b={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(M==null?void 0:M.name)||"",entityName:(M==null?void 0:M.name)||"",entityType:(M==null?void 0:M.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(T==null?void 0:T.name)||"",entityName:(T==null?void 0:T.name)||"",entityType:(T==null?void 0:T.type)||"table"},operator:"="},A=[...D.joinKeyGroups];A[0]={...A[0],keys:[b]},D.joinKeyGroups=A,w[w.findIndex(F=>F.id===v)]=D}r({...n,joins:w})};return{joinPlan:n,expandedJoins:o,setJoinPlan:r,addJoin:c,removeJoin:d,updateJoin:l,moveJoinUp:v=>{const C=n.joins.findIndex(S=>S.id===v);if(C>0){const S=[...n.joins],D={...S[C]},w={...S[C-1]};S[C]=w,S[C-1]=D,S.forEach((B,M)=>{B.sequence=M+1});const m={...n,joins:S};r(m)}},moveJoinDown:v=>{const C=n.joins.findIndex(S=>S.id===v);if(C<n.joins.length-1){const S=[...n.joins],D={...S[C]},w={...S[C+1]};S[C]=w,S[C+1]=D,S.forEach((B,M)=>{B.sequence=M+1});const m={...n,joins:S};r(m)}},toggleJoinExpansion:v=>{const C=new Set(o);C.has(v)?C.delete(v):C.add(v),i(C)},getAvailableSourceEntities:v=>{if(n.joins.length===0)return a;const C=n.joins.findIndex(D=>D.id===v);if(C===0)return a;const S=new Set;return n.baseEntity.name&&S.add(n.baseEntity.name),n.joins.slice(0,C).forEach(D=>{S.add(D.source.name),S.add(D.target.name)}),a.filter(D=>S.has(D.name))},getAvailableTargetEntities:v=>a.filter(C=>C.name!==v),addJoinKeyGroup:v=>{const C=n.joins.find(D=>D.id===v);if(!C)return;const S=[...C.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];l(v,{joinKeyGroups:S})},updateGroupOperator:(v,C,S)=>{const D=n.joins.find(m=>m.id===v);if(!D)return;const w=[...D.joinKeyGroups];w[C]={...w[C],operator:S},l(v,{joinKeyGroups:w})},removeJoinKeyGroup:(v,C)=>{const S=n.joins.find(w=>w.id===v);if(!S)return;const D=[...S.joinKeyGroups];D.splice(C,1),l(v,{joinKeyGroups:D})},addJoinKey:(v,C)=>{const S=n.joins.find(M=>M.id===v);if(!S)return;const D=a.find(M=>M.name===S.source.name),w=a.find(M=>M.name===S.target.name),m=[...S.joinKeyGroups],B={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(D==null?void 0:D.name)||"",entityName:(D==null?void 0:D.name)||"",entityType:(D==null?void 0:D.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(w==null?void 0:w.name)||"",entityName:(w==null?void 0:w.name)||"",entityType:(w==null?void 0:w.type)||"table"},operator:"="};m[C]={...m[C],keys:[...m[C].keys,B]},l(v,{joinKeyGroups:m})},updateJoinKey:(v,C,S,D,w)=>{const m=n.joins.find(A=>A.id===v);if(!m)return;const B=a.find(A=>A.name===m.source.name),M=a.find(A=>A.name===m.target.name),T=[...m.joinKeyGroups],b=T[C].keys[S];D==="sourceColumnName"&&B?T[C].keys[S]={...b,source:{...b.source,name:w}}:D==="targetColumnName"&&M?T[C].keys[S]={...b,target:{...b.target,name:w}}:D==="operator"&&(T[C].keys[S]={...b,operator:w}),l(v,{joinKeyGroups:T})},removeJoinKey:(v,C,S)=>{const D=n.joins.find(m=>m.id===v);if(!D)return;const w=[...D.joinKeyGroups];w[C].keys.splice(S,1),l(v,{joinKeyGroups:w})},generateSQLPreview:()=>{const v=[...n.joins].sort((D,w)=>D.sequence-w.sequence),C=n.baseEntity;if(!C.name)return"SELECT * FROM table -- Please select a base entity";let S=`SELECT *
|
|
370
|
-
FROM ${C.name}`;return
|
|
371
|
-
${
|
|
372
|
-
ON ${B}`}),S},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(D=>!D.source.name||!D.target.name)||n.joins.some(D=>D.joinKeyGroups.some(w=>w.keys.length===0))||n.joins.some(D=>D.joinKeyGroups.some(w=>w.keys.some(m=>!m.source.name||!m.target.name||!m.operator))))}}function er({joinPlan:s,availableDataSources:a,onSave:n,onRemove:r,onCancel:o}){const{setCardConfig:i}=t.useEditorActions();t.useEditorStore(m=>m.card.config);const{columnGroups:c}=t.useColumns(),{joinPlan:d,expandedJoins:l,setJoinPlan:x,addJoin:h,removeJoin:u,updateJoin:j,moveJoinUp:y,moveJoinDown:N,toggleJoinExpansion:f,getAvailableSourceEntities:E,getAvailableTargetEntities:p,addJoinKeyGroup:g,updateGroupOperator:O,removeJoinKeyGroup:I,addJoinKey:k,updateJoinKey:v,removeJoinKey:C,generateSQLPreview:S,isValidConfiguration:D}=Za({initialJoinPlan:s,availableDataSources:a}),w=m=>{const B=c.find(M=>M.entityName===m);return(B==null?void 0:B.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(t.Select,{value:d.baseEntity.name,onValueChange:m=>{const B=a.find(M=>M.name===m);x({...d,baseEntity:{connectionId:(B==null?void 0:B.connectionId)||"",connectionType:(B==null?void 0:B.connectionType)||"none",type:(B==null?void 0:B.type)||"table",name:m,database:B==null?void 0:B.database,schema:B==null?void 0:B.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(t.SelectContent,{children:a.map(m=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:m.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:m.type}),m.name,e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},m.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:S()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(t.Label,{children:["Joins Configuration (",d.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:h,children:[e.jsx(t.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),d.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:d.joins.map(m=>{const B=a.find(b=>b.name===m.source.name),M=a.find(b=>b.name===m.target.name),T=l.has(m.id);return e.jsxs(t.Card,{className:"border",children:[e.jsx(t.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{children:m.sequence}),e.jsxs(t.CardTitle,{className:"text-sm",children:["Join ",m.sequence,B&&M&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",B.name," → ",M.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>y(m.id),disabled:m.sequence===1,children:e.jsx(t.ArrowUp,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>N(m.id),disabled:m.sequence===d.joins.length,children:e.jsx(t.ArrowDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>f(m.id),children:T?e.jsx(t.ChevronUp,{className:"h-4 w-4"}):e.jsx(t.ChevronDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>u(m.id),children:e.jsx(t.X,{className:"h-4 w-4"})})]})]})}),T&&e.jsxs(t.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Source"}),e.jsxs(t.Select,{value:m.source.name,onValueChange:b=>{const A=a.find(F=>F.name===b);j(m.id,{source:{connectionId:(A==null?void 0:A.connectionId)||"",connectionType:(A==null?void 0:A.connectionType)||"none",type:(A==null?void 0:A.type)||"table",name:b,database:A==null?void 0:A.database,schema:A==null?void 0:A.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select source..."})}),e.jsx(t.SelectContent,{children:E(m.id).map(b=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:b.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:b.type}),b.name]})},b.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Join Type"}),e.jsxs(t.Select,{value:m.joinType,onValueChange:b=>j(m.id,{joinType:b}),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Target"}),e.jsxs(t.Select,{value:m.target.name,onValueChange:b=>{const A=a.find(F=>F.name===b);j(m.id,{target:{connectionId:(A==null?void 0:A.connectionId)||"",connectionType:(A==null?void 0:A.connectionType)||"none",type:(A==null?void 0:A.type)||"table",name:b,database:A==null?void 0:A.database,schema:A==null?void 0:A.schema}})},disabled:!m.source.name,children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select target..."})}),e.jsx(t.SelectContent,{children:m.source.name?p(m.source.name).map(b=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:b.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:b.type}),b.name,b.name===m.source.name&&e.jsx(t.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},b.name)):[]})]})]})]}),m.source.name&&m.target.name&&B&&M&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{children:"Join Conditions"}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>g(m.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),m.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:m.joinKeyGroups.map((b,A)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Label,{children:["Group ",A+1]}),A>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(t.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Select,{value:b.operator,onValueChange:F=>O(m.id,A,F),children:[e.jsx(t.SelectTrigger,{className:"w-[100px]",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>I(m.id,A),children:e.jsx(t.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[b.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:b.keys.map((F,P)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[P>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:b.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:F.source.name,onValueChange:R=>v(m.id,A,P,"sourceColumnName",R),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Source column"})}),e.jsx(t.SelectContent,{children:w(m.source.name).map(R=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:R.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:R.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:R.dataType})]})},R.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(t.Select,{value:F.operator,onValueChange:R=>v(m.id,A,P,"operator",R),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:F.target.name,onValueChange:R=>v(m.id,A,P,"targetColumnName",R),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Target column"})}),e.jsx(t.SelectContent,{children:w(m.target.name).map(R=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:R.name,children:e.jsxs("div",{className:"flex w-full items-center justify-between hover:bg-muted",children:[e.jsx("span",{children:R.name}),e.jsx(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:R.dataType})]})},R.name))})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>C(m.id,A,P),children:e.jsx(t.X,{className:"size-3.5"})})]},F.id||P))}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>k(m.id,A),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},b.id))})]})]})]},m.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>{r(),o()},children:"Remove All"}),e.jsx(t.Button,{variant:"outline",onClick:o,children:"Cancel"}),e.jsx(t.Button,{onClick:()=>n(d),disabled:!D(),children:"Save"})]})]})}function Mt({children:s,open:a,onOpenChange:n,joinPlan:r,availableDataSources:o,onRemove:i,onSave:c,onCancel:d}){return e.jsxs(t.Dialog,{open:a,onOpenChange:n,children:[e.jsxs(t.DialogContent,{className:"max-w-4xl",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Join Configuration"}),e.jsx(t.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(er,{joinPlan:r,availableDataSources:o,onSave:c,onCancel:d,onRemove:i})]}),s]})}function tr({joins:s,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[s.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const o=[...s].sort((c,d)=>c.sequence-d.sequence),i=n.find(c=>c.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name}),e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),o.map(c=>{const d=n.find(l=>l.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:d==null?void 0:d.type}),e.jsx("span",{className:"text-xs font-medium",children:d==null?void 0:d.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",s.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...s].sort((o,i)=>o.sequence-i.sequence).map((o,i)=>{const c=n.find(l=>l.name===o.source.name),d=n.find(l=>l.name===o.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(t.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:i+1}),e.jsx(t.Badge,{variant:"outline",className:"shrink-0 text-xs",children:o.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",d==null?void 0:d.name]}),e.jsxs(t.Badge,{variant:"outline",className:"ml-auto text-xs",children:[o.joinKeyGroups.reduce((l,x)=>l+x.keys.length,0)," ","condition",o.joinKeyGroups.reduce((l,x)=>l+x.keys.length,0)>1?"s":""]})]},o.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function sr(){var h,u;const s=t.useEditorStore(j=>j.card),a=t.useEditorStore(j=>j.actions.updateCardConfig),n=((h=s==null?void 0:s.config)==null?void 0:h.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,o]=L.useState(!1),i=((u=s==null?void 0:s.dataSource)==null?void 0:u.selectedEntities)||[],c=j=>{a(s.id,{...s==null?void 0:s.config,joinPlan:j}),o(!1)},d=()=>{a(s.id,{...s==null?void 0:s.config,joinPlan:void 0})},l=()=>{o(!1)},x=()=>{const j=[...n.joins].sort((f,E)=>f.sequence-E.sequence),y=n.baseEntity;if(!y.name)return"SELECT * FROM table -- Please select a base entity";let N=`SELECT *
|
|
373
|
-
FROM ${y.name}`;return j.forEach(
|
|
374
|
-
${
|
|
375
|
-
ON ${g}`}),N};return i.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:[n.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>o(!0),children:[e.jsx(t.Link,{className:t.cn("mr-1 h-3 w-3",{"text-blue-500":n.joins.length>0,"text-gray-500":n.joins.length===0})}),"Join",n.joins.length>1?"s":""," (",n.joins.length,")"]})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(tr,{joins:n.joins,baseEntityId:n.baseEntity.name,availableDataSources:i,generateSQLPreview:x})})]})}),e.jsx(Mt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:i,onSave:c,onCancel:l,onRemove:d,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(Mt,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:i,onSave:c,onCancel:l,onRemove:d,children:e.jsxs(t.Button,{onClick:()=>o(!0),variant:"outline",className:"h-6 text-xs font-semibold",children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Configure Join"]})})]})})})}function nr(){const[s,a]=L.useState(!1),[n,r]=L.useState(!0),o=t.useEditorStore(l=>l.card.dataSource),{updateDataSource:i}=t.useEditorActions(),c={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},d={...c,...o,selectedEntities:(o==null?void 0:o.selectedEntities)||[]};return e.jsxs("div",{className:"flex w-[325px] flex-col border-r bg-background",children:[e.jsxs("div",{children:[e.jsx("div",{className:t.cn("p-4 px-6",{"pb-0":!n}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",onClick:()=>r(!n),children:[n?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"}),e.jsx(t.Database,{className:"h-5 w-5 text-brand"}),e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"})]}),e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>a(!0),children:[e.jsx(t.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${n?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[d.selectedEntities.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1",children:[d.selectedEntities.slice(0,3).map((l,x)=>e.jsxs(t.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[t.getDisplayName(l),e.jsx("button",{onClick:h=>{h.stopPropagation();const u=d.selectedEntities.filter(j=>!(j.name===l.name&&j.type===l.type));i({...c,...o,selectedEntities:u})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 hover:bg-red-100",children:e.jsx(t.X,{className:"h-2.5 w-2.5 group-hover:text-red-500"})})]},`${l.type}-${l.name}-${x}`)),d.selectedEntities.length>3&&e.jsxs(t.Badge,{variant:"outline",className:"text-xs",children:["+",d.selectedEntities.length-3," more"]})]}),e.jsx(sr,{})]})]}),e.jsx(Xa,{}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:(o==null?void 0:o.selectedEntities)||[],dialogMode:"dataSource",open:s,onOpenChange:a,dataSource:d,fallbackDataSource:c})]})}const ar=({customVisual:s,index:a,onSelect:n})=>{const r=Pe(s.icon||""),o=s.name.charAt(0).toUpperCase(),c=(()=>{const d=s.name.toLowerCase();for(const l of Se)if(l.id==="doughnut"){if(d.includes("doughnut")||d.includes("donut")){const x=l.icon;return e.jsx(x,{className:"h-4 w-4"})}}else if(d.includes(l.id.toLowerCase())){const x=l.icon;return e.jsx(x,{className:"h-4 w-4"})}return null})();return e.jsx(t.CommandItem,{value:`${s.name} custom visual plugin component`,onSelect:n,className:"flex items-center gap-2",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:o}),e.jsx("span",{children:s.name})]})},`${s.url}-${s.name}-${a}`)},Se=[{id:"table",icon:ze,label:"Table"},{id:"bar",icon:Be,label:"Bar Chart"},{id:"line",icon:Fe,label:"Line Chart"},{id:"stackedBar",icon:Xe,label:"Stacked Bar Chart"},{id:"stackedLine",icon:xt,label:"Stacked Line Chart"},{id:"scatter",icon:tt,label:"Scatter Chart"},{id:"bubble",icon:mt,label:"Bubble Chart"},{id:"pie",icon:et,label:"Pie Chart"},{id:"doughnut",icon:st,label:"Doughnut Chart"},{id:"funnel",icon:ht,label:"Funnel Chart"},{id:"radar",icon:rt,label:"Radar Chart"},{id:"polarArea",icon:ut,label:"Polar Area Chart"},{id:"tornado",icon:ot,label:"Tornado Chart"},{id:"range",icon:Ze,label:"Range Chart"},{id:"kpi",icon:pt,label:"KPI"},{id:"text",icon:Lt,label:"Text"},{id:"map",icon:at,label:"Map"}];function rr({selectedChart:s,onChartChange:a}){const[n,r]=L.useState([]),[o,i]=L.useState(!1),{data:c}=dt(),{setCardType:d,setCardPreferences:l,setIsDevMode:x}=t.useEditorStore(p=>p.actions),{setCardCustomCfg:h,setCustomCardPreferences:u,setQueryConfig:j}=t.useEditorActions();L.useEffect(()=>{(async()=>{var g;if(c){const I=(await Promise.all((g=c==null?void 0:c.plugins)==null?void 0:g.map(async k=>(await t.loadManifest(k.value)).visuals.map(S=>({name:S.name,icon:S.icon,url:k.value}))))).flat();r(I)}})()},[c]);function y(p){h(null),l({}),d(p),["custom","text","map"].includes(p)&&(x(!0),j(void 0)),a(p),i(!1)}function N(p){h(null),l({}),d("custom"),u({type:"component",visualType:"single",url:p.url,componentName:p.name,icon:p.icon}),j(void 0),a("custom"),i(!1)}const f=()=>{var g;if(s==="custom"){const O=t.useEditorStore.getState().card;return((g=O==null?void 0:O.customCardPreferences)==null?void 0:g.componentName)||"Custom Visual"}const p=Se.find(O=>O.id===s);return(p==null?void 0:p.label)||"Select chart type"},E=()=>{var g,O;if(s==="custom"){const I=t.useEditorStore.getState().card,k=(g=I==null?void 0:I.customCardPreferences)==null?void 0:g.icon,v=(O=I==null?void 0:I.customCardPreferences)==null?void 0:O.componentName;return k&&v?e.jsx(or,{icon:k,componentName:v}):e.jsx(we,{className:"h-4 w-4"})}const p=Se.find(I=>I.id===s);if(p){const I=p.icon;return e.jsx(I,{className:"h-4 w-4"})}return e.jsx(we,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(t.Popover,{open:o,onOpenChange:i,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[E(),e.jsx("span",{children:f()})]}),e.jsx(t.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-[335px] p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(t.CommandList,{className:"max-h-[300px]",children:[e.jsx(t.CommandEmpty,{children:"No chart type found."}),e.jsx(t.CommandGroup,{heading:"Standard Visuals",className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:Se.map(p=>{const g=p.icon;return e.jsx(t.CommandItem,{value:`${p.label} ${p.id} chart graph visualization`,onSelect:()=>y(p.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(g,{className:"h-4 w-4"}),e.jsx("span",{children:p.label})]})},p.id)})}),n.length>0&&e.jsx(t.CommandGroup,{heading:"Custom Visuals",className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:n.map((p,g)=>e.jsx(ar,{customVisual:p,index:g,onSelect:()=>N(p)},`${p.url}-${p.name}-${g}`))})]})]})})]})})}const or=({icon:s,componentName:a})=>{const n=Pe(),o=(()=>{const i=a.toLowerCase();for(const c of Se)if(c.id==="doughnut"){if(i.includes("doughnut")||i.includes("donut")){const d=c.icon;return e.jsx(d,{className:"h-4 w-4"})}}else if(i.includes(c.id.toLowerCase())){const d=c.icon;return e.jsx(d,{className:"h-4 w-4"})}return null})();return n?e.jsx(n,{className:"h-4 w-4"}):o||e.jsx(we,{className:"h-4 w-4"})},us=({dataType:s})=>{const a=t.getDataType(s);return a==="string"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-blue-500 text-xs text-white",children:"T"}):a==="number"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-green-500 text-xs text-white",children:"#"}):a==="date"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-purple-500 text-xs text-white",children:"D"}):a==="boolean"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-orange-500 text-xs text-white",children:"B"}):e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-gray-500 text-xs text-white",children:"?"})};function ir({aliasTemplate:s,onAliasTemplateChange:a}){var l;const[n,r]=L.useState(s),[o,i]=L.useState(!1),c=(l=t.useEditorStore(x=>{var h;return(h=x.card.config)==null?void 0:h.pivotByColumns}))==null?void 0:l[0],d=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input$1,{placeholder:d,value:o?n:s,onChange:x=>{r(x.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:x=>x.stopPropagation(),className:"h-8 text-xs",onKeyDown:x=>{x.key==="Enter"&&o&&n!==s?(a(n),i(!1)):x.key==="Escape"&&(r(s),i(!1))},"aria-label":"Edit alias template"}),o&&n!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),i(!1)},children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(s),i(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function lr({valueAliases:s,onValueAliasesChange:a}){const[n,r]=L.useState(null),[o,i]=L.useState(""),[c,d]=L.useState(""),l=()=>{a({...s,"":""})},x=u=>{const j={...s};delete j[u],a(j)},h=u=>{const j={...s};delete j[u],j[o]=c,a(j),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(s).map(([u,j],y)=>e.jsx("div",{className:"flex items-center gap-2",children:n===u?e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:o,onChange:N=>i(N.target.value),className:"h-8 w-24 text-xs",onPointerDown:N=>N.stopPropagation(),onKeyDown:N=>{N.key==="Enter"?h(u):N.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:c,onChange:N=>d(N.target.value),className:"h-8 w-24 text-xs",onPointerDown:N=>N.stopPropagation(),onKeyDown:N=>{N.key==="Enter"?h(u):N.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>h(u),children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:u,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(u),i(u),d(j)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:j,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(u),i(u),d(j)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>x(u),"aria-label":"Remove value alias",children:e.jsx(t.X,{className:"h-3 w-3"})})]})},u+y)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:l,children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function ms(s,a){return`${t.toLabel(a)} of ${t.toLabel(s)}`}const hs=s=>{const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:o,updateSortByColumn:i,removeGroupByColumn:c,removeMetricColumn:d,removePivotByColumn:l,removeSortByColumn:x}=t.useEditorActions(),h=t.useEditorStore(w=>w.card.type),u=s==null?void 0:s.id,j=L.useCallback(w=>{if(!(s!=null&&s.config))return[];switch(w){case"groupBy":return(s.config.groupByColumns||[]).map(m=>({id:m.id,name:m.name,dataType:m.dataType,label:m.label!==void 0?m.label:m.name,qualifiedEntityName:m.qualifiedEntityName,entityId:m.entityId,entityName:m.entityName,entityType:m.entityType,dateFormat:m.dateFormat,customFormat:m.customFormat,granularity:m.granularity}));case"metrics":return s.config.metricColumns||[];case"pivotBy":return(s.config.pivotByColumns||[]).map(m=>({id:m.id,name:m.name,dataType:m.dataType,label:m.label!==void 0?m.label:m.name,qualifiedEntityName:m.qualifiedEntityName,entityId:m.entityId,entityName:m.entityName,entityType:m.entityType}));case"sortBy":return(s.config.sortByColumns||[]).map(m=>({id:m.id,name:m.name,dataType:m.dataType,label:m.label!==void 0?m.label:m.name,qualifiedEntityName:m.qualifiedEntityName,entityId:m.entityId,entityName:m.entityName,entityType:m.entityType,direction:m.direction}));case"source":return[];default:return[]}},[s]),y=L.useCallback((w,m)=>{if(u)switch(w){case"groupBy":{a(u,{groupByColumns:m});break}case"metrics":{a(u,{metricColumns:m});break}case"pivotBy":{a(u,{pivotByColumns:m});break}case"sortBy":{a(u,{sortByColumns:m});break}}},[u,a]),N=L.useCallback((w,m,B)=>{if(!u)return;const T=j(w)[m];if(T)switch(w){case"groupBy":n(u,T.id,{label:B});break;case"metrics":r(u,T.id,{label:B});break;case"pivotBy":o(u,T.id,{label:B});break;case"sortBy":i(u,T.id,{label:B});break}},[u,j,n,r,o,i]),f=L.useCallback((w,m)=>{if(!u)return;const M=j("metrics")[w];M&&r(u,M.id,{aggregate:m,label:ms(M.name,m)})},[u,j,r]),E=L.useCallback((w,m,B)=>{if(!u)return;const T=j("groupBy")[w];if(!T)return;const b={dateFormat:m};m==="custom"&&B?b.customFormat=B:b.customFormat=void 0,n(u,T.id,b)},[u,j,n]),p=L.useCallback((w,m)=>{if(!u)return;const M=j("groupBy")[w];M&&n(u,M.id,{granularity:m})},[u,j,n]),g=L.useCallback((w,m)=>{if(!u)return;const M=j("metrics")[w];M&&r(u,M.id,{aliasTemplate:m})},[u,j,r]),O=L.useCallback((w,m)=>{if(console.log("handleValueAliasesChange",w,m),!u)return;console.log("handleValueAliasesChange",w,m);const M=j("metrics")[w];M&&(console.log("handleValueAliasesChange",m),r(u,M.id,{valueAliases:m}))},[u,j,r]),I=L.useCallback(w=>{u&&a(u,{comparisonType:w})},[u,a]),k=L.useCallback(w=>{u&&a(u,{showTrendline:w})},[u,a]),v=L.useCallback(w=>{u&&a(u,{trendlineWindow:w})},[u,a]),C=L.useCallback(w=>{u&&a(u,{trendlineGranularity:w})},[u,a]),S=L.useCallback(w=>{u&&a(u,{targetValue:w})},[u,a]),D=L.useCallback((w,m)=>{if(!u)return;const M=j(w)[m];if(M){if(w!=="sortBy"){const T=j("sortBy"),b=T.filter(A=>!(A.name===M.name&&A.qualifiedEntityName===M.qualifiedEntityName));b.length!==T.length&&a(u,{sortByColumns:b})}switch(w){case"groupBy":c(u,M.id);break;case"metrics":d(u,M.id);break;case"pivotBy":l(u,M.id);break;case"sortBy":x(u,M.id);break}}},[u,j,c,d,l,x,a]);return{getFieldsForContainer:j,setFieldsForContainer:y,updateLabel:N,handleAggregationChange:f,handleDateFormatChange:E,handleGranularityChange:p,handleAliasTemplateChange:g,handleValueAliasesChange:O,removeField:D,handleKpiComparisonTypeChange:I,handleKpiShowTrendlineChange:k,handleKpiTrendlineWindowChange:v,handleKpiTrendlineGranularityChange:C,handleKpiTargetValueChange:S,cardType:h}};function At({value:s,onSave:a,placeholder:n="",type:r="text",className:o=""}){const[i,c]=L.useState(s??""),[d,l]=L.useState(!1);L.useEffect(()=>{c(s??"")},[s]);const x=()=>{a(i),l(!1)},h=()=>{c(s??""),l(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${o}`,children:[e.jsx(t.Input$1,{placeholder:n,type:r,value:d?i:s??"",onChange:u=>{c(u.target.value),l(!0)},onFocus:()=>l(!0),onClick:u=>u.stopPropagation(),className:"h-8 text-xs",onPointerDown:u=>u.stopPropagation(),onKeyDown:u=>{u.stopPropagation(),u.key==="Enter"&&d&&i!==s?x():u.key==="Escape"&&h()},"aria-label":n||"Edit field"}),d&&i!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:x,children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:h,children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function cr({field:s,zone:a,index:n,sortDirection:r,onSortDirectionChange:o,hasPivotColumns:i=!1,cardType:c}){var bt;const{attributes:d,listeners:l,setNodeRef:x,transform:h,transition:u,isDragging:j}=t.useSortable({id:s.id}),y=t.useEditorStore(U=>U.card),{updateLabel:N,handleAggregationChange:f,handleDateFormatChange:E,handleGranularityChange:p,handleAliasTemplateChange:g,handleValueAliasesChange:O,removeField:I,handleKpiComparisonTypeChange:k,handleKpiShowTrendlineChange:v,handleKpiTrendlineWindowChange:C,handleKpiTrendlineGranularityChange:S,handleKpiTargetValueChange:D}=hs(y),[w,m]=L.useState(!1),[B,M]=L.useState(s.dateFormat||"YYYY-MM-DD"),[T,b]=L.useState(s.customFormat||""),[A,F]=L.useState(!!s.customFormat),[P,R]=L.useState(s.granularity||"day"),[z,Y]=L.useState(s.aliasTemplate||""),[V,q]=L.useState(s.valueAliases||{}),H=U=>{U==="custom"?F(!0):(F(!1),M(U),a==="groupBy"&&E(n,U,""))},K=U=>{b(U),a==="groupBy"&&E(n,"custom",U)},G=U=>{R(U),a==="groupBy"&&p(n,U)},$=U=>{Y(U),a==="metrics"&&g(n,U)},J=U=>{q(U),a==="metrics"&&O(n,U)},X=U=>{N(a,n,U)},se=()=>{I(a,n)},re={transform:t.CSS.Transform.toString(h),transition:u},le=t.getDataType(s.dataType),ne=le==="date",te=c==="kpi",ce=[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}],_=!te&&a!=="pivotBy",Q=te&&ne&&a==="groupBy",oe=!te&&ne&&a==="groupBy",de=te&&ne&&a==="groupBy",me=te&&a==="metrics"&&((bt=y.config)==null?void 0:bt.comparisonType)==="target",W=a==="metrics",Z=()=>e.jsx("div",{onPointerDown:U=>{U.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${s.entityName}.${s.name}`}),ee=()=>_?e.jsx(At,{value:s.label??"",onSave:X,placeholder:"Display label...",type:"text"}):null,yt=()=>Q?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(t.Select,{value:P,onValueChange:G,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"day",children:"Day"}),e.jsx(t.SelectItem,{value:"week",children:"Week"}),e.jsx(t.SelectItem,{value:"month",children:"Month"}),e.jsx(t.SelectItem,{value:"quarter",children:"Quarter"}),e.jsx(t.SelectItem,{value:"year",children:"Year"})]})]})]}):null,gs=()=>oe?e.jsxs(e.Fragment,{children:[yt(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(t.Select,{value:A?"custom":B,onValueChange:H,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select date format..."})}),e.jsx(t.SelectContent,{children:ce.map(U=>e.jsx(t.SelectItem,{value:U.value,children:U.label},U.value))})]}),A&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(t.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:T,onChange:U=>{U.stopPropagation(),K(U.target.value)},onClick:U=>U.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,js=()=>{var U,ue,ye,vt,Nt;return de?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(t.Select,{value:((U=y.config)==null?void 0:U.comparisonType)||"none",onValueChange:k,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(t.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(t.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(t.SelectItem,{value:"target",children:"Target Value"})]})]})]}),e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(t.SmallSwitch,{checked:((ue=y.config)==null?void 0:ue.showTrendline)||!1,onCheckedChange:v})]})}),((ye=y.config)==null?void 0:ye.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(t.Input$1,{type:"number",min:"1",max:"365",value:((vt=y.config)==null?void 0:vt.trendlineWindow)||30,onChange:vs=>{const Ns=parseInt(vs.target.value)||30;C(Ns)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(t.Select,{value:((Nt=y.config)==null?void 0:Nt.trendlineGranularity)||"day",onValueChange:S,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"day",children:"Day"}),e.jsx(t.SelectItem,{value:"week",children:"Week"}),e.jsx(t.SelectItem,{value:"month",children:"Month"})]})]})]})]})]}):null},ys=()=>{var U,ue;return me?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(At,{value:((U=y.config)==null?void 0:U.targetValue)!==void 0&&((ue=y.config)==null?void 0:ue.targetValue)!==null?String(y.config.targetValue):"",onSave:ye=>{!isNaN(Number(ye))&&ye!==null?D(Number(ye)):D(0)},placeholder:"Enter target value...",type:"text"})]}):null},bs=()=>W?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(t.Select,{value:s.aggregate,onValueChange:U=>{f(n,U)},children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select function..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"COUNT",children:"Count"}),e.jsx(t.SelectItem,{value:"DISTINCT",children:"Count Distinct"}),t.getDataType(s.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(t.SelectItem,{value:"SUM",children:"Sum"}),e.jsx(t.SelectItem,{value:"AVG",children:"Average"}),e.jsx(t.SelectItem,{value:"MIN",children:"Min"}),e.jsx(t.SelectItem,{value:"MAX",children:"Max"}),e.jsx(t.SelectItem,{value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsx(cs,{column:s}),i&&e.jsxs(e.Fragment,{children:[e.jsx(ir,{aliasTemplate:z,onAliasTemplateChange:$}),e.jsx(lr,{valueAliases:V,onValueAliasesChange:J})]})]}):null;return e.jsxs("div",{ref:x,style:re,...d,...l,className:`group mx-auto flex w-full max-w-[300px] flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${j?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.GripVertical,{className:"h-3 w-3"}),e.jsx(us,{dataType:le}),e.jsx(ft,{className:"max-w-[180px] flex-1 text-sm",children:s.label||s.name}),a!=="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:U=>{U.stopPropagation(),m(!w)},children:e.jsx(t.ChevronDown,{className:`h-3 w-3 transition-transform ${w?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:U=>{U.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ue=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ue),o(ue)},children:r==="asc"?e.jsx(t.ArrowUp,{className:"h-3 w-3"}):e.jsx(t.ArrowDown,{className:"h-3 w-3"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:U=>{U.stopPropagation(),se()},children:e.jsx(t.X,{className:"h-3 w-3"})})]}),w&&e.jsxs("div",{className:"space-y-3",children:[Z(),ee(),yt(),gs(),js(),ys(),bs()]})]})}function dr({concept:s}){const a=()=>{switch(s){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-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(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{delayDuration:300,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(t.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function Te({zone:s,fields:a,label:n,placeholder:r,shouldShow:o,hasPivotColumns:i=!1}){const{isOver:c,setNodeRef:d}=t.useDroppable({id:s}),{updateSortByColumn:l}=t.useEditorActions(),x=t.useEditorStore(N=>N.card),h=t.useEditorStore(N=>N.card.type),u=a.length>0,j=(N,f)=>{var p;!((p=x.config)!=null&&p.sortByColumns)||x.config.sortByColumns.findIndex(g=>g.id===N)===-1||l(x.id,N,{direction:f})};if(s==="sortBy"&&o===!1)return null;const y=s!=="sortBy"&&h!=="kpi";return e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(t.Label,{className:t.cn("block text-sm font-medium",{}),children:n}),y&&e.jsx(dr,{concept:s})]}),e.jsx("div",{ref:d,className:`min-h-[60px] rounded-lg border-2 border-dashed p-3 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":"border-muted-foreground/20 bg-muted/50"}`,children:a.length===0?e.jsxs("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),r]}):e.jsx(t.SortableContext,{items:a.map(N=>N.id),strategy:t.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((N,f)=>{const p=N.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(cr,{field:N,zone:s,index:f,sortDirection:p,onSortDirectionChange:g=>j(N.id,g),hasPivotColumns:i,cardType:h})})},N.id)})})})})]})}function ur({groupByFields:s,pivotByFields:a,metricsFields:n,sortByFields:r}){const o=t.useEditorStore(u=>u.card),i=o==null?void 0:o.type,c=s.length>0||n.length>0,d=i!=="kpi",l=i!=="kpi"&&c,x=()=>i==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},h=()=>i==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Te,{zone:"groupBy",fields:s,label:x().label,placeholder:x().placeholder}),d&&e.jsx(Te,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Te,{zone:"metrics",fields:n,label:h().label,placeholder:h().placeholder,hasPivotColumns:a.length>0}),l&&e.jsx(Te,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})}function mr({selectedChart:s,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i}){const c=t.useEditorStore(u=>u.showAIDialog),d=n.length>0||r.length>0||o.length>0,{setShowAIDialog:l}=t.useEditorActions(),x=t.useEditorStore(u=>u.card),{data:h}=t.useDashboardCardQuery(x);return e.jsxs("div",{className:"flex w-96 flex-col border-r bg-background",children:[e.jsxs("div",{className:"space-y-4 border-b px-6 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.ChartColumn,{className:"h-5 w-5 text-brand"}),e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})]}),e.jsx(rr,{selectedChart:s,onChartChange:a})]}),e.jsxs("div",{className:t.cn("flex justify-end gap-2 px-6 pt-6"),children:[e.jsx("div",{className:t.cn("invisible",{visible:d||h}),children:e.jsx(t.EditorClearButton,{})}),!c&&e.jsxs(t.Button,{onClick:()=>l(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(fn,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(t.ScrollArea,{className:"flex-1 basis-0 px-6",children:[e.jsx(ur,{groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function hr({initialFilters:s,availableFields:a}={}){const[n,r]=L.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(k=>k.card.dataSource);const{columns:o,isLoading:i}=t.useColumns(),d=a||o||[],l={id:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},x=k=>{const v=C=>{if(C.id===k){const S=d[0]||l;return{...C,conditions:[...C.conditions,{id:`condition-${Date.now()}`,field:S,operator:"=",value:""}]}}return{...C,groups:C.groups.map(v)}};r(v(n))},h=k=>{const v=C=>{if(C.id===k){const S=d[0]||l;return{...C,groups:[...C.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:S,operator:"=",value:""}],groups:[]}]}}return{...C,groups:C.groups.map(v)}};r(v(n))},u=(k,v)=>{const C=S=>S.id===k?{...S,conditions:S.conditions.filter(D=>D.id!==v)}:{...S,groups:S.groups.map(C)};r(C(n))},j=(k,v)=>{const C=S=>S.id===k?{...S,groups:S.groups.filter(D=>D.id!==v)}:{...S,groups:S.groups.map(C)};r(C(n))},y=(k,v,C,S)=>{if(C==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const D=w=>w.id===k?{...w,conditions:w.conditions.map(m=>m.id===v?{...m,[C]:S}:m)}:{...w,groups:w.groups.map(D)};r(D(n))},N=(k,v,C)=>{const S=D=>D.id===k?{...D,conditions:D.conditions.map(w=>w.id===v?{...w,...C}:w)}:{...D,groups:D.groups.map(S)};r(S(n))},f=(k,v)=>{const C=S=>S.id===k?{...S,logicalOperator:v}:{...S,groups:S.groups.map(C)};r(C(n))},E=(k,v)=>{const C=S=>S.id===k?{...S,negate:v}:{...S,groups:S.groups.map(C)};r(C(n))},p=(k,v,C)=>{const S=D=>D.id===k?{...D,conditions:t.arrayMove(D.conditions,v,C)}:{...D,groups:D.groups.map(S)};r(S(n))},g=(k,v,C)=>{const S=D=>D.id===k?{...D,groups:t.arrayMove(D.groups,v,C)}:{...D,groups:D.groups.map(S)};r(S(n))},O=k=>{if(!k||k.conditions.length===0&&k.groups.length===0)return"-- No filters defined";const v=S=>{let D="";typeof S.field=="object"?D=S.field.entityName?`${S.field.entityName}.${S.field.name}`:S.field.name:D=String(S.field);const w=S.operator;let m=S.value;if(S.field.dataType==="string"&&!["in","not in"].includes(S.operator))typeof m=="string"?m=`'${m}'`:Array.isArray(m)&&(m=`'${m.join(", ")}'`);else if(S.field.dataType==="date")(typeof m=="string"||m instanceof Date)&&(m=`DATE('${m}')`);else if(["in","not in"].includes(S.operator)){let B=[];Array.isArray(m)?B=m.map(M=>typeof M=="string"?`'${M}'`:String(M)):typeof m=="string"?B=m.split(",").map(M=>{const T=M.trim();return S.field.dataType==="string"?`'${T}'`:T}):typeof m=="number"&&(B=[String(m)]),m=`(${B.join(", ")})`}switch(w){case"contains":return typeof m=="string"?`${D} LIKE '%${m.replace(/'/g,"")}'`:`${D} LIKE '%${String(m)}'`;case"startsWith":return typeof m=="string"?`${D} LIKE '${m.replace(/'/g,"")}%'`:`${D} LIKE '${String(m)}%'`;case"endsWith":return typeof m=="string"?`${D} LIKE '%${m.replace(/'/g,"")}'`:`${D} LIKE '%${String(m)}'`;default:return`${D} ${w} ${m}`}},C=S=>{const D=S.conditions.map(v),w=S.groups.map(T=>C(T)),m=[...D,...w].filter(Boolean);if(m.length===0)return"";const B=m.join(` ${S.logicalOperator} `),M=m.length>1?`(${B})`:B;return S.negate?`NOT ${M}`:M};return C(k)},I=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:d,isLoading:i,addCondition:x,addGroup:h,removeCondition:u,removeGroup:j,updateCondition:y,updateConditionFields:N,updateGroupOperator:f,updateGroupNegate:E,reorderConditions:p,reorderGroups:g,generateSQLPreview:O,hasAnyFilters:I}}function xr({children:s,className:a,delayDuration:n}){return e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{delayDuration:n,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:t.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:s})}),e.jsx(t.PortalTooltipContent,{children:s})]})})}const pr=s=>{switch(s){case"table":return e.jsx(t.Table,{className:"h-3 w-3"});case"view":return e.jsx(t.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(t.ChartColumn,{className:"h-3 w-3"});case"file":return e.jsx(Ks,{className:"h-3 w-3"});default:return e.jsx(t.Table,{className:"h-3 w-3"})}},fr=s=>{if(s.qualifiedEntityName){const a=s.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function gr({value:s,onValueChange:a,availableFields:n,placeholder:r="Select field",className:o="w-64"}){const[i,c]=L.useState(!1),d=L.useMemo(()=>{const l={};return n.forEach(x=>{const h=fr(x);l[h]||(l[h]={}),l[h][x.entityId]||(l[h][x.entityId]=[]),l[h][x.entityId].push(x)}),l},[n]);return e.jsxs(t.Popover,{modal:!0,open:i,onOpenChange:c,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:t.cn("justify-between",!s&&"text-muted-foreground",o),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(xr,{children:[s.entityName,".",s.name]})}):r,e.jsx(t.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(t.CommandEmpty,{children:"No fields found."}),e.jsx(t.CommandList,{className:"max-h-80",children:Object.entries(d).map(([l,x])=>e.jsx(t.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Database,{className:"h-3 w-3"}),l]}),children:Object.entries(x).map(([h,u])=>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:[pr(u[0].entityType),e.jsx("span",{children:u[0].entityName})]}),u.map((j,y)=>e.jsxs(t.CommandItem,{value:j.id,onSelect:()=>{a(j),c(!1)},className:"overflow-x-auto",children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",(s==null?void 0:s.id)===j.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:j.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:j.description&&e.jsx("span",{children:j.description})})]})]},j.id+y))]},`${l}-${h}`))},l))})]})})]})}function jt(s){var N;const a=t.useEditorStore(f=>f.card),{authToken:n}=t.useSemaphorContext(),r=t.useEditorStore(f=>f.card.config),o=r==null?void 0:r.joinPlan,i={...s,alias:s.name,label:"value",role:"groupby"},c={...s,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},d={...i,role:"sortby",direction:"asc"},l={joinPlan:o,groupByColumns:[i],metricColumns:[c],sortByColumns:[d]},x=((N=a.dataSource)==null?void 0:N.connectionId)||a.connectionId,{data:h,isPending:u,error:j}=t.useQuery({queryKey:["filterValues",s.entityId,s.name,s.qualifiedEntityName],queryFn:async()=>{try{return await t.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:x,cardConfig:l,cardDataSource:a.dataSource})}catch(f){console.log(s),console.error("error",f)}},enabled:!!x,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(f=>({label:f[s.name]||"BLANK",value:f[s.name]||"BLANK",count:(f==null?void 0:f.count)||0})),isPending:u,error:j}}function jr({field:s,selected:a,onChange:n,placeholder:r="Select items...",className:o}){const[i,c]=he.useState(!1),{filterValues:d}=jt(s),l=h=>{n(a.filter(u=>u!==h))},x=h=>{a.includes(h)?n(a.filter(u=>u!==h)):n([...a,h])};return e.jsx("div",{className:t.cn("w-full",o),children:e.jsxs(t.Popover,{open:i,onOpenChange:c,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(h=>{const u=d.find(j=>j.value===h);return e.jsxs(t.Badge,{variant:"secondary",className:"text-xs",children:[u==null?void 0:u.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:j=>{j.key==="Enter"&&l(h)},onMouseDown:j=>{j.preventDefault(),j.stopPropagation()},onClick:j=>{j.stopPropagation(),l(h)},children:e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},h)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(t.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No results found."}),e.jsx(t.CommandGroup,{children:d.map((h,u)=>e.jsxs(t.CommandItem,{onSelect:()=>x(h.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",a.includes(h.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:h.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:h.count})]})]},h.value+u))})]})]})})]})})}const xs=s=>{if(!s)return 0;let a=s.conditions.length;return s.groups.forEach(n=>{a+=xs(n)}),a};function yr({field:s,value:a,onChange:n,placeholder:r="Select value...",className:o}){const{filterValues:i,isPending:c,error:d}=jt(s);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):d?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(t.Select,{value:a,onValueChange:n,children:[e.jsx(t.SelectTrigger,{className:o||"flex-1",children:e.jsx(t.SelectValue,{placeholder:r,children:a})}),e.jsx(t.SelectContent,{children:i.map((l,x)=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:l.value,children:l.label},l.value+x))})]})}const br=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],vr=["=","!=","contains","startsWith","endsWith","in","not in"],Nr=["=","!=",">",">=","<","<=","in","not in"],Cr=["=","!="],Sr=["=","!=",">",">=","<","<=","in","not in"];function wr(s){switch(s){case"string":return vr;case"number":return Nr;case"boolean":return Cr;case"date":return Sr;default:return br}}function ps({condition:s,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:o,onRemoveCondition:i,onUpdateGroupOperator:c,availableFields:d,updateConditionFields:l}){const{attributes:x,listeners:h,setNodeRef:u,transform:j,transition:y,isDragging:N}=t.useSortable({id:s.id}),{isPending:f,error:E}=jt(s.field),p={transform:t.CSS.Transform.toString(j),transition:y};return e.jsxs("div",{ref:u,style:p,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${N?"z-50 opacity-50":""}`,children:[e.jsx("div",{...x,...h,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(t.Select,{value:r,onValueChange:g=>c(n,g),children:[e.jsx(t.SelectTrigger,{className:"w-24",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(gr,{value:s.field,onValueChange:g=>{l(n,s.id,{field:g,value:""})},availableFields:d,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:g=>{g==="in"||g==="not in"?l(n,s.id,{operator:g,value:[]}):l(n,s.id,{operator:g,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-28",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:wr(t.getDataType(s.field.dataType)).map(g=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:g,children:g},g))})]}),t.getDataType(s.field.dataType)==="string"?s.operator==="in"||s.operator==="not in"?f?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):E?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(jr,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(g=>typeof g=="string")?s.value:[],onChange:g=>l(n,s.id,{value:g}),placeholder:`Select values for ${s.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(s.operator)?e.jsx(t.Input$1,{value:typeof s.value=="string"?s.value:"",onChange:g=>l(n,s.id,{value:g.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(yr,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:g=>l(n,s.id,{value:g}),placeholder:"Select value...",className:"flex-1"}):t.getDataType(s.field.dataType)==="boolean"?e.jsxs(t.Select,{value:typeof s.value=="boolean"?String(s.value):"",onValueChange:g=>l(n,s.id,{value:g==="true"}),children:[e.jsx(t.SelectTrigger,{className:"flex-1",children:e.jsx(t.SelectValue,{placeholder:"Select value..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"true",children:"True"}),e.jsx(t.SelectItem,{value:"false",children:"False"})]})]}):e.jsx(t.Input$1,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:g=>o(n,s.id,"value",g.target.value),className:"flex-1",placeholder:s.operator==="in"||s.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>i(n,s.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]})}function kr({group:s,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:i,onUpdateCondition:c,onUpdateField:d,onRemoveCondition:l,onReorderConditions:x,onReorderGroups:h,onAddCondition:u,onAddGroup:j,availableFields:y,renderFilterGroup:N,updateConditionFields:f}){const{attributes:E,listeners:p,setNodeRef:g,transform:O,transition:I,isDragging:k}=t.useSortable({id:s.id}),v={transform:t.CSS.Transform.toString(O),transition:I},C=D=>{const{active:w,over:m}=D;if(m&&w.id!==m.id){const B=s.conditions.findIndex(T=>T.id===w.id),M=s.conditions.findIndex(T=>T.id===m.id);B!==-1&&M!==-1&&x(s.id,B,M)}},S=D=>{const{active:w,over:m}=D;if(m&&w.id!==m.id&&n){const B=s.groups.findIndex(T=>T.id===w.id),M=s.groups.findIndex(T=>T.id===m.id);B!==-1&&M!==-1&&h(n,B,M)}};return e.jsxs("div",{ref:g,style:v,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${k?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...E,...p,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(t.Button,{variant:s.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>o(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:D=>r(s.id,D),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&i(n,s.id),children:e.jsx(t.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:C,children:e.jsx(t.SortableContext,{items:s.conditions.map(D=>D.id),strategy:t.verticalListSortingStrategy,children:s.conditions.map((D,w)=>e.jsx(ps,{condition:D,index:w,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:c,onUpdateField:d,onRemoveCondition:l,onUpdateGroupOperator:r,availableFields:y,updateConditionFields:f},D.id))})}),e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:S,children:e.jsx(t.SortableContext,{items:s.groups.map(D=>D.id),strategy:t.verticalListSortingStrategy,children:s.groups.map(D=>N(D,a+1,s.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>u(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>j(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Er({filters:s,availableFields:a,onSave:n,onClearAll:r,onCancel:o}){const{currentFilters:i,availableFields:c,isLoading:d,addCondition:l,addGroup:x,removeCondition:h,removeGroup:u,updateCondition:j,updateConditionFields:y,updateGroupOperator:N,updateGroupNegate:f,reorderConditions:E,reorderGroups:p,generateSQLPreview:g,hasAnyFilters:O,setCurrentFilters:I}=hr({initialFilters:s,availableFields:a}),k=t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),[v,C]=L.useState(!1),S=(m,B,M)=>{const T=b=>b.id===m?{...b,conditions:b.conditions.map(A=>A.id===B?{...A,field:M,dataType:M.dataType}:A)}:{...b,groups:b.groups.map(T)};I(T(i))},D=(m,B=0,M)=>B===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(t.DndContext,{sensors:k,collisionDetection:t.closestCenter,onDragEnd:T=>{const{active:b,over:A}=T;if(A&&b.id!==A.id){const F=m.conditions.findIndex(R=>R.id===b.id),P=m.conditions.findIndex(R=>R.id===A.id);F!==-1&&P!==-1&&E(m.id,F,P)}},children:e.jsx(t.SortableContext,{items:m.conditions.map(T=>T.id),strategy:t.verticalListSortingStrategy,children:m.conditions.map((T,b)=>e.jsx(ps,{condition:T,index:b,groupId:m.id,groupLogicalOperator:m.logicalOperator,onUpdateCondition:j,onUpdateField:S,onRemoveCondition:h,onUpdateGroupOperator:N,availableFields:c,updateConditionFields:y},T.id))})}),e.jsx(t.DndContext,{sensors:k,collisionDetection:t.closestCenter,onDragEnd:T=>{const{active:b,over:A}=T;if(A&&b.id!==A.id){const F=m.groups.findIndex(R=>R.id===b.id),P=m.groups.findIndex(R=>R.id===A.id);F!==-1&&P!==-1&&p(m.id,F,P)}},children:e.jsx(t.SortableContext,{items:m.groups.map(T=>T.id),strategy:t.verticalListSortingStrategy,children:m.groups.map(T=>D(T,B+1,m.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>l(m.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),v&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>x(m.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},m.id):e.jsx(kr,{group:m,depth:B,parentGroupId:M,onUpdateGroupOperator:N,onUpdateGroupNegate:f,onRemoveGroup:u,onUpdateCondition:j,onUpdateField:S,onRemoveCondition:h,onReorderConditions:E,onReorderGroups:p,onAddCondition:l,onAddGroup:x,availableFields:c,renderFilterGroup:D,updateConditionFields:y},m.id),w=xs(s);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.Card,{children:e.jsx(t.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[d?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..."})]}):D(i),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Checkbox,{id:"advanced-mode",checked:v,onCheckedChange:m=>C(!!m)}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),O&&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:g(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:o,children:"Cancel"}),w>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>n(O?i:null),children:"Apply Filters"})]})]})}function Dr({cardId:s,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:o,isOpen:i,onOpenChange:c}){const d=x=>{n(s,x),c(!1)},l=()=>{r(s),c(!1)};return e.jsxs(t.Dialog,{modal:!1,open:i,onOpenChange:c,children:[i&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(t.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:x=>{x.preventDefault()},children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Card Filters"}),e.jsx(t.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Er,{filters:a,availableFields:o,onSave:d,onCancel:()=>c(!1),onClearAll:l})]})]})}function fs(s,a){return`${s}-${a.qualifiedEntityName}-${a.name}-${Date.now()}`}function Ir({activeCardId:s,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var E;const[o,i]=L.useState(null),c=t.useEditorStore(p=>p.card),d=(E=c==null?void 0:c.config)==null?void 0:E.joinPlan,l=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],x=L.useCallback(p=>p.startsWith("card-")?null:p.startsWith("source-")||a.find(g=>g.id===p)?"source":n("groupBy").find(g=>g.id===p)?"groupBy":n("metrics").find(g=>g.id===p)?"metrics":n("pivotBy").find(g=>g.id===p)?"pivotBy":n("sortBy").find(g=>g.id===p)?"sortBy":null,[a,n]),h=L.useCallback((p,g)=>{var O;return!d||!((O=d.baseEntity)!=null&&O.name)||!d.joins?!1:p===g||p===d.baseEntity.name||g===d.baseEntity.name?!0:d.joins.some(I=>{const k=t.getQualifiedEntityName(I.source),v=t.getQualifiedEntityName(I.target);return console.log(k,v),console.log(k===p&&v===g||k===g&&v===p),k===p&&v===g||k===g&&v===p})},[d]),u=L.useCallback(()=>{t.ue.error("Join Configuration Required",{richColors:!0,description:"To combine fields from two different tables, you need to define a join between them first.",position:"top-center",duration:4e3})},[]),j=(p,g)=>{const O=fs(g,p),I=t.getDataType(p.dataType),k=I==="date",v={id:O,name:p.name,dataType:p.dataType,label:t.toLabel(p.name),qualifiedEntityName:p.qualifiedEntityName,entityId:p.entityId,entityName:p.entityName,entityType:p.entityType};if(g==="metrics"){const C=I==="number"?"SUM":"COUNT",S=ms(p.label,C);return{...v,role:"metric",label:S,aggregate:C}}return g==="groupBy"?{...v,role:"groupby",...k&&{granularity:"month"}}:g==="pivotBy"?{...v,role:"pivotby"}:g==="sortBy"?{...v,role:"sortby",label:p.label,direction:"asc"}:null},y=L.useCallback(p=>{i(p.active.id)},[]),N=L.useCallback(p=>{const{active:g,over:O}=p;if(!O||!s){i(null);return}const I=g.id,k=O.id,v=x(I),C=x(k)||k;if(v==="source"&&C==="sortBy"){i(null);return}if(v==="source"&&C!=="source"&&C!=="sortBy"){const S=[...a].find(M=>M.id===I);if(!S){i(null);return}const D=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(D.length>0){const M=D[0].qualifiedEntityName;if(!M){i(null);return}if(M!==S.qualifiedEntityName&&S.qualifiedEntityName)if(d){if(!h(M,S.qualifiedEntityName)){u(),i(null);return}}else{u(),i(null);return}}const w=n(C);if(w.some(M=>M.name===S.name&&M.qualifiedEntityName===S.qualifiedEntityName)){i(null);return}const B=j(S,C);i(null),r(C,[...w,B]);return}if(v&&C&&v!=="source"&&C!=="source"&&v!==C){const S=n(v),D=n(C),w=S.find(M=>M.id===I);if(!w){i(null);return}const m=j(w,C);if(i(null),C==="sortBy"){if(v==="pivotBy"){i(null);return}D.some(T=>T.name===w.name&&T.qualifiedEntityName===w.qualifiedEntityName)||r(C,[...D,m]);return}const B=S.filter(M=>M.id!==I);r(v,B),r(C,[...D,m]);return}if(v&&C&&v===C&&v!=="source"){const S=n(v),D=S.findIndex(m=>m.id===I),w=S.findIndex(m=>m.id===k);if(D!==w){const m=t.arrayMove(S,D,w);r(v,m)}}i(null)},[s,a,n,r,x,d,u,h]),f=o?l.find(p=>p.id===o):null;return{activeId:o,activeField:f,handleDragStart:y,handleDragEnd:N}}function Tr({activeView:s,onViewChange:a}){const n=t.useEditorStore(o=>o.card),{errorMessage:r}=t.useDashboardCardQuery(n);return e.jsx(t.Tabs,{value:s,onValueChange:o=>a(o),children:e.jsxs(t.TabsList,{className:"h-9 w-fit gap-2 bg-background p-0",children:[e.jsx(t.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(t.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),n.type!=="kpi"&&e.jsx(t.TabsTrigger,{value:"sql",className:t.cn("rounded-md transition data-[state=active]:bg-muted",r&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:r?"Error":"Query"})]})})}const Mr=[{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 Ar(){var l,x;const s=t.useEditorStore(h=>h.card),{updateRowLimit:a}=t.useEditorActions(),[n,r]=L.useState(!1),[o,i]=L.useState(""),c=h=>{if(h==="custom"){r(!0);return}r(!1),a(s.id,parseInt(h))},d=h=>{const u=h.target.value;i(u),u&&!isNaN(parseInt(u))&&a(s.id,parseInt(u))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(t.Input,{type:"number",value:o,onChange:d,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((x=(l=s.config)==null?void 0:l.rowLimit)==null?void 0:x.toString())||"100",onValueChange:c,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(t.SelectValue,{placeholder:"Select limit"})}),e.jsx(t.SelectContent,{children:Mr.map(h=>e.jsx(t.SelectItem,{value:h.value,children:h.label},h.value))})]})})}function Lr({activeView:s,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:c,onFiltersClick:d,filterCount:l,activeCard:x,columns:h,columnsLoading:u,columnsError:j}){var D;const y=t.useEditorStore(w=>w.card),N=t.useDashboardStore(w=>w.filterValues),{updateCardConfig:f}=t.useEditorActions(),E=t.useEditorStore(w=>w.showAIDialog),{data:p,errorMessage:g,isPending:O,isLoading:I,isFetching:k}=t.useDashboardCardQuery(x);function v(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(y.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(N||{},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(x.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",h.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:u?"Loading...":j?"Error loading columns":JSON.stringify(h.slice(0,5),null,2)})]})]})})}const C=w=>{if(!y.config)return;if(!w.length){f(y.id,{...y.config,sortByColumns:[]});return}const m=y.config,B=w.map(({id:M,desc:T})=>{var P,R;const b=(P=m.metricColumns)==null?void 0:P.find(z=>z.label===M),A=(R=m.groupByColumns)==null?void 0:R.find(z=>z.label===M),F=b||A;return F?{id:fs("sortBy",F),name:F.name,dataType:F.dataType,label:F.label,qualifiedEntityName:F.qualifiedEntityName,entityId:F.entityId,entityName:F.entityName,entityType:F.entityType,role:"sortby",direction:T?"desc":"asc"}:null}).filter(M=>M!==null);f(y.id,{...m,sortByColumns:B})},S=L.useMemo(()=>{var w,m;return(m=(w=y.config)==null?void 0:w.sortByColumns)==null?void 0:m.map(B=>({id:B.label,desc:B.direction==="desc"}))},[(D=y.config)==null?void 0:D.sortByColumns]);return e.jsxs("div",{className:"flex w-0 grow flex-col",children:[e.jsx(t.ExplorerHeader,{showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:c,onFiltersClick:d,filterCount:l}),n&&v(),e.jsx(t.Separator,{}),e.jsxs("div",{className:"group/visualization flex max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"z-50 flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s==="chart"&&E&&e.jsx(ts,{variant:"outline"}),e.jsx(Tr,{activeView:s,onViewChange:a}),d&&e.jsxs(t.IconButton,{tooltip:"Card Filters",className:"h-8 gap-1",onClick:d,children:[e.jsx(t.Filter,{className:"h-3.5 w-3.5"}),l>0&&e.jsx("span",{className:"ml-1 rounded-full bg-blue-100 px-1.5 py-0.5 text-xs text-blue-800",children:l})]}),e.jsx("div",{className:"ml-2",children:e.jsx(Ar,{})})]}),e.jsx("div",{className:t.cn("flex grow items-center justify-end"),children:s==="chart"&&e.jsx(ss,{})})]}),e.jsxs("div",{className:"flex grow flex-col",children:[s==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:I||k?e.jsx("div",{className:"m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(t.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx(ns,{})}),s==="table"&&(p==null?void 0:p.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(I||k)&&e.jsx("div",{className:"absolute flex h-full w-full items-center justify-between",children:e.jsx("div",{className:"z-10 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(t.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}),e.jsx(t.TableVisual,{card:x,data:p==null?void 0:p.records,onSortChange:C,sortState:S})]}),s==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md border bg-background p-4",children:[(p==null?void 0:p.sql)&&e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx(Yt,{sql:p==null?void 0:p.sql,error:g})]})})]})]})]})}function Or({activeField:s}){const[a,n]=L.useState(!0);return L.useEffect(()=>{s&&n(!0)},[s]),s?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 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(t.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(us,{dataType:s.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:s.label||s.name})]}):null}const Br=()=>{const s=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||s.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var o;if((o=r.reason)!=null&&o.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=s,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function Fr(){var z,Y;const[s,a]=L.useState("chart"),[n,r]=L.useState(!1),[o,i]=L.useState(!1),c=t.useEditorStore(V=>V.showAIDialog),{setCardType:d}=t.useEditorActions(),l=t.useEditorStore(V=>V.card.type);L.useEffect(()=>Br(),[]);const x=()=>{console.log("Accept clicked - would save/apply current configuration")},h=()=>{console.log("Clear clicked - would reset all configurations")},u=()=>{console.log("Advanced mode toggled")},j=()=>{i(!0)},y=V=>{d(V)},N=t.useEditorStore(V=>V.frame),f=t.useEditorStore(V=>V.card);t.useEditorStore(V=>V.activeTabCardId),t.useEditorStore(V=>V.actions.getAvailableFields);const{addCard:E,removeCard:p,updateCard:g,setActiveCard:O,updateFilters:I}=t.useEditorActions(),{columns:k=[],isLoading:v,error:C}=t.useColumns(),S=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),D=f,{getFieldsForContainer:w,setFieldsForContainer:m}=hs(D),{activeField:B,handleDragStart:M,handleDragEnd:T}=Ir({activeCardId:N.activeCardId,sourceFields:k,getFieldsForContainer:w,setFieldsForContainer:m}),b=(V,q)=>{q&&I(V,q)},A=V=>{var q;g(V,{config:{...(q=N.cards.find(H=>H.id===V))==null?void 0:q.config,filters:void 0}})},F=k,P=V=>{if(!V)return 0;let q=V.conditions.length;return V.groups.forEach(H=>{q+=P(H)}),q},R=P(((z=D==null?void 0:D.config)==null?void 0:z.filters)||null);return e.jsxs(t.DndContext,{sensors:S,collisionDetection:t.closestCenter,onDragStart:M,onDragEnd:T,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(nr,{}),!c&&e.jsx(mr,{selectedChart:l,onChartChange:y,groupByFields:w("groupBy"),pivotByFields:w("pivotBy"),metricsFields:w("metrics"),sortByFields:w("sortBy")}),e.jsx(Lr,{selectedChart:l,activeView:s,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:x,onClear:h,onAdvancedToggle:u,onFiltersClick:j,filterCount:R,activeCard:D,dataSourceState:f.dataSource||t.EMPTY_DATA_SOURCE,columns:k,columnsLoading:v,columnsError:C,getFieldsForContainer:w,cards:N.cards,activeCardId:N.activeCardId,addCard:E,setActiveCard:O})]}),D&&e.jsx(Dr,{cardId:D.id,filters:((Y=D.config)==null?void 0:Y.filters)||null,onFiltersChange:b,onClearFilters:A,availableFields:F,isOpen:o,onOpenChange:i}),e.jsx(t.DragOverlay,{dropAnimation:null,children:e.jsx(Or,{activeField:B||null})})]})}function zr({authToken:s,onSave:a,onClose:n}){const r=L.useRef(null),o=t.useEditorStore(g=>g.showAIDialog),i=t.useEditorStore(g=>g.isDevMode),{setAuthToken:c}=t.useDashboardActions(),{setShowAIDialog:d,setOnSave:l,setOnClose:x}=t.useEditorActions(),{handleDragOver:h,handleDragEnd:u,handleDragStart:j,handleDragCancel:y,sensors:N}=Mn();L.useEffect(()=>{a&&l(a),n&&x(n)},[a,l,n,x]),L.useEffect(()=>{s&&s.accessToken&&c(s)},[s,c]),L.useEffect(()=>{var g,O;o?((g=r.current)==null||g.resize(40),d(!0)):(d(!1),(O=r.current)==null||O.resize(0))},[o,d]);function f(g){g<1?d(!1):o||d(!0)}function E(){return e.jsxs(e.Fragment,{children:[e.jsx(Ht,{type:"main"}),e.jsxs(t.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Ja,{})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:f,defaultSize:0,children:e.jsx(Tt,{})})]})]})}function p(){return e.jsxs(t.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(Fr,{})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:f,defaultSize:0,children:e.jsx(Tt,{})})]})}return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:i?e.jsx(t.DndContext,{sensors:N,onDragStart:j,onDragEnd:u,onDragOver:h,onDragCancel:y,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:E()})}):p()})}function Pr(){t.useDashboardStore(c=>c.selectedCardId);const s=t.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=t.useDashboardStore(c=>c.actions),n=t.useDashboardStore(c=>c.isVisualEditing),r=t.useDashboardStore(c=>c.actions.updateFrame);function o(c){s&&(r(s,c),a(!1))}function i(){a(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex grow",{"max-h-0 overflow-hidden":!n}),children:e.jsx(zr,{onSave:o,onClose:i})})}function Vr(){const s=t.useEditorStore(i=>i.selectedDatabaseName),a=t.useEditorStore(i=>i.selectedTableName),n=t.useDashboardStore(i=>i.dashboard.filters)||[],{columns:r}=t.useEditorAside(),{assignFilter:o}=is();return e.jsx(t.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(i=>{const c=n==null?void 0:n.find(d=>d.column===t.fmt(i.column_name)&&d.table===a&&d.database===s);return e.jsx("div",{onClick:()=>o(i),className:t.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lt,{column:i}),e.jsx("span",{children:i.column_name})]})},i.column_name)})})}function Rr(){t.useDashboardStore(a=>a.showFilters);const s=t.useDashboardStore(a=>a.actions.setShowFilters);return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(t.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(t.Button,{onClick:()=>s(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(t.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:e.jsx(Ht,{type:"filter",ColumnsComponent:()=>e.jsx(Vr,{})})})]})}function qr(){const s=t.useDashboardStore(r=>r.dashboard.filters),a=t.useDashboardStore(r=>r.theme),n=s==null?void 0:s.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:t.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(t.FilterHeader,{filter:r}),e.jsx(t.FilterComponent,{filter:r})]},r.id))}):null}function _r(){const s=t.useDashboardStore(r=>r.showFilters),a=t.useDashboardStore(r=>r.isVisualEditing),n=t.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:t.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(qr,{}),e.jsx(t.DashboardTabs,{})]}),s&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(Rr,{})})]})}function Gr(){const s=t.useDashboardStore(o=>o.dashboard),a=t.useDashboardStore(o=>o.actions.setDashboard),n=t.useDashboardStore(o=>o.showDashboardJSON),r=t.useDashboardStore(o=>o.actions.setShowDashboardJSON);return e.jsxs("div",{className:t.cn("relative p-2",{hidden:!n}),children:[e.jsxs(t.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(t.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(t.de,{onChange:o=>{if(o)try{JSON.parse(o),a(JSON.parse(o))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(s,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function $r({showControls:s=!1,showFooter:a=!0,...n}){return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:e.jsxs(t.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(t.$e,{}),e.jsxs(t.UXProvider,{children:[e.jsx(Gr,{}),e.jsxs(t.DashboardPanel,{...n,children:[s&&e.jsx(kn,{}),e.jsx(Pr,{}),e.jsx(_r,{})]})]})]})})}exports.DashboardPlus=$r;exports.ScheduleDashboard=$t;exports.SelectComponent=be;exports.cleanCard=qt;exports.downloadPdf=Gt;exports.getDashbaordStateWithoutData=it;
|
|
363
|
+
`;g(z)}function F(){return e.jsxs(e.Fragment,{children:[r&&e.jsx("div",{className:"relative flex w-1/3 min-w-0 grow overflow-hidden text-xs",role:"editor-filter-container",children:e.jsx("div",{className:"mt-2 w-[99%]",children:e.jsx(Gn,{jsonString:JSON.stringify(x,null,2)})})}),x&&x.length>0&&e.jsx(t.Button,{variant:"ghost",onClick:()=>o(!r),className:"absolute bottom-0 right-6 size-7 p-1",children:r?e.jsx(t.X,{className:"size-3.5 text-muted-foreground"}):e.jsx(t.Filter,{className:"size-3.5 text-muted-foreground"})})]})}function P(){return e.jsxs(t.ResizablePanelGroup,{className:"flex grow pb-1",direction:"vertical",role:"editor-resizable-group",children:[e.jsxs(t.ResizablePanel,{id:"1",order:1,defaultSize:a?20:100,className:"relative flex grow",children:[e.jsx("div",{id:"sql-container",className:"relative flex w-[99%]",children:e.jsx(qn,{})}),a&&e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"sql"})]}),a&&e.jsxs(e.Fragment,{children:[e.jsx(t.ResizableHandle,{withHandle:!0,className:"border"}),e.jsxs(t.ResizablePanel,{id:"2",order:2,defaultSize:80,className:"relative flex grow",children:[e.jsx("div",{id:"python-container",className:"relative flex w-[99%] pt-0",children:e.jsx(_n,{})}),e.jsx("code",{className:"absolute right-6 top-3 text-xs text-muted-foreground/70",children:"python"})]})]})]})}function V(){return e.jsxs("div",{role:"editor-controls",className:"item-center flex flex-wrap justify-between gap-2 px-6 py-4",children:[e.jsxs("div",{className:"flex grow items-center gap-2",children:[e.jsxs(t.Button,{title:"Shift + Enter",disabled:w||T,onClick:()=>{I()},className:"h-8 shrink-0",size:"sm",children:[w||T?e.jsx(t.LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(t.Play,{className:"mr-2 h-4 w-4"}),"Run"]}),e.jsx(Qt,{sql:C==null?void 0:C.sql,error:N,onDebugWithAssistant:M}),e.jsx(t.EditorClearButton,{}),e.jsx(t.Toggle,{pressed:a,onPressedChange:z=>n(z),className:"",size:"sm",children:e.jsx(Vn,{className:"size-4 text-foreground/70"})}),e.jsx("button",{disabled:c,onClick:()=>{v(!0)},className:"h-9 w-full cursor-text px-3 text-left text-sm text-muted-foreground",children:c?"":"Type your question..."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.EditorCancelButton,{}),e.jsx(t.EditorAcceptButton,{})]})]})}return e.jsxs("section",{role:"editor-section",className:"flex grow flex-col justify-end",children:[e.jsxs("div",{className:"relative flex grow justify-between overflow-y-scroll",children:[P(),F()]}),V()]})}function Jn({data:s}){var c;const[a,n]=L.useState([]),o=Object.keys(s[0]).map(d=>({accessorKey:d,header:({column:l})=>{const x=l.getIsSorted();return e.jsx("div",{className:"flex gap-2",children:e.jsxs("div",{className:"flex cursor-pointer items-center",onClick:()=>l.toggleSorting(l.getIsSorted()==="asc"),children:[d,x==="asc"?e.jsx(t.TriangleUpIcon,{className:"ml-2 h-5 w-5"}):x==="desc"?e.jsx(t.TriangleDownIcon,{className:"ml-2 h-5 w-5"}):null]})})}})),i=t.useReactTable({data:s,columns:o,getCoreRowModel:t.getCoreRowModel(),getPaginationRowModel:t.getPaginationRowModel(),onSortingChange:n,getSortedRowModel:t.getSortedRowModel(),manualPagination:!0,state:{sorting:a}});return e.jsxs(t.CustomScrollArea,{className:"grow overflow-auto font-mono text-xs text-foreground/95",children:[e.jsxs("table",{className:"w-full",children:[e.jsx(t.TableHeader,{className:"sticky top-0 z-50 h-0 bg-muted",children:i.getHeaderGroups().map(d=>e.jsx(t.TableRow,{className:"",children:d.headers.map(l=>e.jsx(t.TableHead,{className:"h-11 font-semibold text-foreground",children:l.isPlaceholder?null:t.flexRender(l.column.columnDef.header,l.getContext())},l.id))},d.id))}),e.jsx(t.TableBody,{children:(c=i.getRowModel().rows)!=null&&c.length?i.getRowModel().rows.map(d=>e.jsx(t.TableRow,{className:"h-11 whitespace-nowrap py-2","data-state":d.getIsSelected()&&"selected",children:d.getVisibleCells().map(l=>e.jsx(t.TableCell,{className:"py-2",children:t.flexRender(l.column.columnDef.cell,l.getContext())},l.id))},d.id)):e.jsx(t.TableRow,{children:e.jsx(t.TableCell,{colSpan:o.length,className:"h-24 text-center",children:"No results."})})})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function Hn({card:s}){var g,v,O,E,b,C,w,T,k,m,B;const[a,n]=L.useState(!1),[r,o]=L.useState([]),{authToken:i}=t.useSemaphorContext(),c=t.getTokenParams(i==null?void 0:i.accessToken),d=t.useDashboardStore(A=>A.themeStyle),l={colors:((v=(g=d==null?void 0:d.chart)==null?void 0:g.dataset)==null?void 0:v.backgroundColor)||[]};(O=s.customCardPreferences)!=null&&O.inputData;const{getCard:x}=t.useCustomVisual(((E=s.customCardPreferences)==null?void 0:E.url)||""),h=((b=s.customCardPreferences)==null?void 0:b.visualType)||"single",u=t.useEditorStore(A=>A.frame),{setCustomCardPreferences:j}=t.useEditorActions(),{data:y}=t.useDashboardCardQuery(s),S=L.useCallback((A,I)=>{o(N=>({...N,[A]:I}))},[]);if(!((C=s.customCardPreferences)!=null&&C.componentName))return null;const p=x((w=s.customCardPreferences)==null?void 0:w.componentName);function D(A){n(A)}const f=Object.keys(((T=s.customCardPreferences)==null?void 0:T.dataInputCardIds)||{}).map(A=>{var M,F,P;const I=(F=(M=s.customCardPreferences)==null?void 0:M.dataInputCardIds)==null?void 0:F[A].cardId,N=(P=u==null?void 0:u.cards)==null?void 0:P.find(V=>V.id===I);return N||null});return e.jsx("div",{className:"semaphor-custom mb-3 flex grow basis-0 flex-col space-y-2 overflow-y-auto",children:e.jsxs(L.Suspense,{fallback:e.jsx(e.Fragment,{}),children:[p&&h==="single"&&e.jsx(p,{params:c,theme:l,settings:(k=s.customCardPreferences)==null?void 0:k.settings,onDataChange:S,data:(y==null?void 0:y.records)||[]}),p&&h==="multiple"&&e.jsxs(e.Fragment,{children:[Object.keys(((m=s.customCardPreferences)==null?void 0:m.dataInputCardIds)||{}).map(A=>{var M,F,P;const I=(F=(M=s.customCardPreferences)==null?void 0:M.dataInputCardIds)==null?void 0:F[A].cardId,N=(P=u==null?void 0:u.cards)==null?void 0:P.find(V=>V.id===I);if(N)return e.jsx(t.MultiInputEmptyRenderer,{onLoadingStatus:D,onDataChange:S,dataInputIndex:A,card:N},N.id+A)}),e.jsx("div",{className:"flex flex-col gap-2",children:e.jsx(p,{theme:l,onDataChange:S,settings:f.map(A=>{var I;return(I=A==null?void 0:A.customCardPreferences)==null?void 0:I.settings}),data:f.map(A=>A!=null&&A.id?r==null?void 0:r[A.id]:[])})})]})]},(B=s.customCardPreferences)==null?void 0:B.componentName)})}function es({className:s,...a}){var f;const n=t.useEditorStore(g=>g.card),r=((f=n.customCardPreferences)==null?void 0:f.showCardHeader)??!0,o=t.useEditorStore(g=>g.frame),i=t.useDashboardStore(g=>g.dashboard.filters);t.useEditorStore(g=>g.actions.setRunSql);const{updateFilter:c}=t.useDashboardActions(),d=i==null?void 0:i.find(g=>g.id===o.filterId),{data:l,isLoading:x,isFetching:h,errorMessage:u}=t.useDashboardCardQuery(n),{setCard:j}=t.useEditorActions(),{data:y}=t.useTopoJson(n),S=L.useMemo(()=>!n.id||!(l!=null&&l.records)?null:t.createChartConfig({card:n,data:l==null?void 0:l.records,cardType:n.type,queryConfig:n.queryConfig,customCfg:n.customCfg,preferences:n.preferences,topoJson:y}),[n.id,l==null?void 0:l.records,n.type,n.queryConfig,n.customCfg,n.preferences,y]);function p(g){return e.jsx(Hn,{card:g})}function D(){if(l!=null&&l.records&&(l==null?void 0:l.records.length)===0&&!x&&!h)return u?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(t.SearchX,{className:"size-8 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:n.mode!=="explorer"?"Error fetching data. Please check your SQL or Python code.":"Error fetching data. Please check your chart configuration"})]}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2",children:[e.jsx(t.TreePalm,{className:"size-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No results to display"})]});if(!n.id)return null;if(n.type==="custom")return p(n);if(!["table","custom"].includes(n.type)&&S)return e.jsx(e.Fragment,{children:x||h?e.jsx(e.Fragment,{}):e.jsx(t.ChartJsVisual,{cfg:S})});if(n.type==="table"&&(l!=null&&l.records)&&(l==null?void 0:l.records.length)>0)return e.jsx("div",{className:"relative mb-2 flex h-full min-h-0 w-full flex-1 grow basis-0",children:e.jsx(t.TableVisual,{card:n,data:l==null?void 0:l.records})})}return e.jsxs(t.Card,{role:"editor-visual-card",className:t.cn("relative flex h-full flex-col rounded-none",s),...a,children:[r&&e.jsxs(t.CardHeader,{className:"flex flex-row items-start justify-between py-4",children:[e.jsxs("div",{children:[e.jsx(t.Editable,{enabled:!0,text:n.title,onSave:g=>j({...n,title:g}),children:e.jsx("div",{className:"flex items-center gap-5",children:e.jsx(t.CardTitle,{className:"text-base",children:n.title||"Add title"})})},n.title),e.jsx(t.Editable,{enabled:!0,text:n.description||"",onSave:g=>j({...n,description:g}),children:e.jsx(t.CardDescription,{children:n.description||"Add description"})},n.description)]}),d&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Editable,{enabled:!0,className:"my-1",text:d.title||d.column,onSave:g=>c({...d,title:g}),children:e.jsx(t.Label,{children:d.title})}),e.jsx(t.FilterComponent,{filter:d})]})]}),e.jsx(t.CardContent,{className:"flex grow flex-col",children:D()})]})}const Je=({language:s,value:a,onChange:n,readonly:r})=>e.jsx(t.Ft,{className:"h-full w-full overflow-hidden text-xs",theme:"default",options:{minimap:{enabled:!1},wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,lineHeight:16,renderLineHighlight:"none",readOnly:r},defaultLanguage:s,value:a,onChange:n}),Un=()=>e.jsxs(t.DialogHeader,{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(t.DialogTitle,{children:"Customize Card"})}),e.jsxs(t.DialogDescription,{children:["See the configuration options and documentation",e.jsx("a",{target:"_blank",className:"ml-1 text-blue-500 underline",href:"https://www.chartjs.org/docs/latest/samples/bar/vertical.html",children:"here."})]})]}),Yn=({customCode:s,cardCustomCfgString:a,mergedConfig:n,onConfigChange:r,onCodeChange:o})=>e.jsxs(t.Tabs,{defaultValue:"final-config",className:"flex w-1/2 flex-col",children:[e.jsxs(t.TabsList,{className:"justify-start rounded-sm rounded-b-none border border-b-0",children:[e.jsx(t.TabsTrigger,{value:"final-config",children:"Config"}),e.jsx(t.TabsTrigger,{value:"custom-config",children:"Changes"}),e.jsx(t.TabsTrigger,{value:"custom-code",children:"Custom Code"})]}),e.jsx(t.TabsContent,{value:"final-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Je,{language:"json",value:n,onChange:r})}),e.jsx(t.TabsContent,{value:"custom-config",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Je,{readonly:!0,language:"json",value:a,onChange:()=>{}})}),e.jsx(t.TabsContent,{value:"custom-code",className:"mt-0 grow rounded-b border border-t-0",children:e.jsx(Je,{language:"javascript",value:s,onChange:o})})]}),Kn=({error:s,hasCardCustomConfig:a,onReset:n,onApply:r,onClose:o})=>e.jsxs(t.DialogFooter,{className:"flex items-center",children:[e.jsx(t.Label,{className:"mr-2 text-red-500",children:s}),e.jsx(t.Button,{disabled:!a,onClick:n,variant:"outline",children:"Reset"}),e.jsx(t.Button,{onClick:r,variant:"outline",children:"Apply"}),e.jsx(t.Button,{onClick:o,variant:"outline",children:"Close"})]});function Qn(){const[s,a]=L.useState(!1),[n,r]=L.useState(""),[o,i]=L.useState(""),[c,d]=L.useState(""),[l,x]=L.useState(""),h=t.useEditorStore(E=>E.card),u=t.useEditorStore(E=>E.card.customCfg),j=u?JSON.stringify(u,null,2):"",{data:y}=t.useDashboardCardQuery(h),{data:S}=t.useTopoJson(h),{setCardCustomCfg:p,setCustomVisualCode:D}=t.useEditorActions(),f=E=>{var b,C;return JSON.stringify({...E,data:{...E.data,datasets:(C=(b=E.data)==null?void 0:b.datasets)==null?void 0:C.map(w=>({...w,data:[]}))}},null,2)},g=()=>{var b,C;if(!((b=y==null?void 0:y.records)!=null&&b.length))return;const E=t.createChartConfig({card:h,data:y.records,cardType:h.type,queryConfig:h.queryConfig,preferences:h.preferences,topoJson:S});if(E){r(f(E)),d(((C=h.preferences)==null?void 0:C.customVisualCode)||"");const w=t.merge(E,u);i(f(w))}},v=()=>{try{if(c&&D(c),o){const E=JSON.parse(o),b=t.getObjectDiff(JSON.parse(n),E);p(b),x("")}}catch{x("Invalid JSON configuration")}},O=Object.keys(u||{}).length===0;return e.jsxs(t.Dialog,{open:s,onOpenChange:a,children:[e.jsx(t.DialogTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Customize Visual",onClick:g,className:O?"":"text-green-600 hover:text-green-700",children:e.jsx(t.Settings,{className:"h-4 w-4"})})}),e.jsxs(t.DialogContent,{className:"flex h-[600px] grow flex-col overflow-auto sm:min-w-[900px] lg:min-w-[1200px]",children:[e.jsx(Un,{}),e.jsxs("div",{className:"flex grow gap-2",children:[e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackEditorCard,children:e.jsx(es,{className:"w-1/2 rounded shadow-none"})}),e.jsx(Yn,{customCode:c,cardCustomCfgString:j,mergedConfig:o,onConfigChange:E=>i(E??""),onCodeChange:E=>d(E??"")})]}),e.jsx(Kn,{error:l,hasCardCustomConfig:!!u,onReset:()=>{i(n),p(null)},onApply:v,onClose:()=>a(!1)})]})]})}function Pe(s){const[a,n]=L.useState(null);return a}function dt(){const{authToken:s}=t.useSemaphorContext(),{data:a,isLoading:n,isFetching:r,isError:o}=t.useQuery({queryKey:["plugins",s==null?void 0:s.accessToken],queryFn:()=>t.getPlugins(s==null?void 0:s.accessToken)});return{data:a,isLoading:n,isFetching:r,isError:o}}function Wn({onChartTypeChange:s}){const[a,n]=L.useState([]),{setCardCustomCfg:r,setCardPreferences:o,setCardType:i,setCustomCardPreferences:c}=t.useEditorActions(),{data:d}=dt();function l(x,h){r(null),o({}),i(x),h&&c({type:"component",visualType:"single",url:h.url,componentName:h.name,icon:h.icon}),s==null||s()}return L.useEffect(()=>{(async()=>{var h;if(d){const j=(await Promise.all((h=d==null?void 0:d.plugins)==null?void 0:h.map(async y=>(await t.loadManifest(y.value)).visuals.map(D=>({name:D.name,icon:D.icon,url:y.value}))))).flat();n(j)}})()},[d]),a.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(t.Separator,{className:"my-2"}),e.jsx("div",{className:"grid grid-cols-4 place-items-center",children:a.map((x,h)=>e.jsx(Xn,{text:x.name,onClick:()=>l("custom",x),icon:x.icon},x.url+x.name+h))})]})}const Xn=({text:s,icon:a,onClick:n})=>{const r=Pe(),o=s.charAt(0).toUpperCase();return e.jsx(t.IconButton,{onClick:n,tooltip:s,children:r?e.jsx(r,{className:"h-4 w-4"}):o})};function ut(s){return ge({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm87.63,96H191.48A64.1,64.1,0,0,0,136,64.52V40.37A88.13,88.13,0,0,1,215.63,120ZM120,120H80.68A48.09,48.09,0,0,1,120,80.68Zm0,16v39.32A48.09,48.09,0,0,1,80.68,136Zm16,0h39.32A48.09,48.09,0,0,1,136,175.32Zm0-16V80.68A48.09,48.09,0,0,1,175.32,120ZM120,40.37V64.52A64.1,64.1,0,0,0,64.52,120H40.37A88.13,88.13,0,0,1,120,40.37ZM40.37,136H64.52A64.1,64.1,0,0,0,120,191.48v24.15A88.13,88.13,0,0,1,40.37,136ZM136,215.63V191.48A64.1,64.1,0,0,0,191.48,136h24.15A88.13,88.13,0,0,1,136,215.63Z"},child:[]}]})(s)}function Zn(s){return ge({attr:{viewBox:"0 0 256 256",fill:"currentColor"},child:[{tag:"path",attr:{d:"M48,180c0,11,7.18,20,16,20a14.24,14.24,0,0,0,10.22-4.66A8,8,0,0,1,85.78,206.4,30.06,30.06,0,0,1,64,216c-17.65,0-32-16.15-32-36s14.35-36,32-36a30.06,30.06,0,0,1,21.78,9.6,8,8,0,0,1-11.56,11.06A14.24,14.24,0,0,0,64,160C55.18,160,48,169,48,180Zm79.6-8.69c-4-1.16-8.14-2.35-10.45-3.84-1.25-.81-1.23-1-1.12-1.9a4.57,4.57,0,0,1,2-3.67c4.6-3.12,15.34-1.73,19.82-.56A8,8,0,0,0,142,145.86c-2.12-.55-21-5.22-32.84,2.76a20.58,20.58,0,0,0-9,14.95c-2,15.88,13.65,20.41,23,23.11,12.06,3.49,13.12,4.92,12.78,7.59-.31,2.41-1.26,3.34-2.14,3.93-4.6,3.06-15.17,1.56-19.55.36A8,8,0,0,0,109.94,214a61.34,61.34,0,0,0,15.19,2c5.82,0,12.3-1,17.49-4.46a20.82,20.82,0,0,0,9.19-15.23C154,179,137.49,174.17,127.6,171.31Zm83.09-26.84a8,8,0,0,0-10.23,4.84L188,184.21l-12.47-34.9a8,8,0,0,0-15.07,5.38l20,56a8,8,0,0,0,15.07,0l20-56A8,8,0,0,0,210.69,144.47ZM216,88v24a8,8,0,0,1-16,0V96H152a8,8,0,0,1-8-8V40H56v72a8,8,0,0,1-16,0V40A16,16,0,0,1,56,24h96a8,8,0,0,1,5.66,2.34l56,56A8,8,0,0,1,216,88Zm-27.31-8L160,51.31V80Z"},child:[]}]})(s)}function mt(s){return ge({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M6 16m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"},child:[]},{tag:"path",attr:{d:"M16 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"},child:[]},{tag:"path",attr:{d:"M14.5 7.5m-4.5 0a4.5 4.5 0 1 0 9 0a4.5 4.5 0 1 0 -9 0"},child:[]}]})(s)}function ht(s){return ge({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4.387 3h15.226a1 1 0 0 1 .948 1.316l-5.105 15.316a2 2 0 0 1 -1.898 1.368h-3.116a2 2 0 0 1 -1.898 -1.368l-5.104 -15.316a1 1 0 0 1 .947 -1.316"},child:[]},{tag:"path",attr:{d:"M5 9h14"},child:[]},{tag:"path",attr:{d:"M7 15h10"},child:[]}]})(s)}function xt(s){return ge({attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"m2 19.99 7.5-7.51 4 4 7.09-7.97L22 9.92l-8.5 9.56-4-4-6 6.01-1.5-1.5zm1.5-4.5 6-6.01 4 4L22 3.92l-1.41-1.41-7.09 7.97-4-4L2 13.99l1.5 1.5z"},child:[]}]})(s)}function pt(s){return ge({attr:{version:"1.2",baseProfile:"tiny",viewBox:"0 0 24 24"},child:[{tag:"path",attr:{d:"M4 18c-.552 0-1-.448-1-1v-6.382l-.553.276c-.495.248-1.095.046-1.342-.447-.247-.494-.046-1.094.448-1.342l2-1c.31-.155.678-.139.973.044.294.183.474.504.474.851v8c0 .552-.448 1-1 1zM13 18h-5c-.404 0-.769-.244-.924-.617-.155-.374-.069-.804.217-1.09l4-4c.254-.254.394-.591.394-.95 0-.358-.14-.695-.394-.949-.508-.508-1.39-.508-1.9.001-.253.252-.393.589-.393.948 0 .552-.448 1-1 1s-1-.448-1-1c0-.894.348-1.733.98-2.364 1.265-1.263 3.464-1.263 4.727.001.632.631.979 1.471.979 2.363 0 .893-.348 1.733-.979 2.364l-2.293 2.293h2.586c.552 0 1 .448 1 1s-.448 1-1 1zM20.955 12.377c.338-.457.545-1.016.545-1.627 0-1.517-1.234-2.75-2.75-2.75-1.031 0-1.966.569-2.44 1.484-.254.49-.063 1.094.428 1.348.49.254 1.094.062 1.348-.428.128-.249.383-.404.664-.404.414 0 .75.336.75.75s-.336.75-.75.75c-.552 0-1 .448-1 1s.448 1 1 1c.689 0 1.25.561 1.25 1.25s-.561 1.25-1.25 1.25-1.25-.561-1.25-1.25c0-.552-.448-1-1-1s-1 .448-1 1c0 1.792 1.458 3.25 3.25 3.25s3.25-1.458 3.25-3.25c0-.939-.406-1.779-1.045-2.373z"},child:[]}]})(s)}function ts({onChartTypeChange:s,iconClassName:a}){const{setCardType:n,setCardPreferences:r,setIsDevMode:o}=t.useEditorStore(h=>h.actions),{setCardCustomCfg:i,setCustomCardPreferences:c,setQueryConfig:d}=t.useEditorActions();function l(h,u){i(null),r({}),n(h),["custom","text","map"].includes(h)&&(o(!0),d(void 0)),s==null||s()}const x=1e3;return e.jsxs("div",{className:"grid grid-cols-5 place-items-center",children:[e.jsx(t.IconButton,{openDelay:x,tooltip:"Table",onClick:()=>l("table"),className:"h-10 p-4",children:e.jsx(ze,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Bar Chart",onClick:()=>l("bar"),className:"h-10 p-4",children:e.jsx(Be,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Line Chart",onClick:()=>l("line"),className:"h-10 p-4",children:e.jsx(Fe,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Stacked Bar Chart",onClick:()=>l("stackedBar"),className:"h-10 p-4",children:e.jsx(Xe,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Stacked Line Chart",onClick:()=>l("stackedLine"),className:"h-10 p-4",children:e.jsx(xt,{className:t.cn("size-5",a),strokeWidth:0})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Scatter Chart",onClick:()=>l("scatter"),className:"h-10 p-4",children:e.jsx(tt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Bubble Chart",onClick:()=>l("bubble"),className:"h-10 p-4",children:e.jsx(mt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Pie Chart",onClick:()=>l("pie"),className:"h-10 p-4",children:e.jsx(et,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Doughnut Chart",onClick:()=>l("doughnut"),className:"h-10 p-4",children:e.jsx(st,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Funnel Chart",onClick:()=>l("funnel"),className:"h-10 p-4",children:e.jsx(ht,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Radar Chart",onClick:()=>l("radar"),className:"h-10 p-4",children:e.jsx(rt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Polar Area Chart",onClick:()=>l("polarArea"),className:"h-10 p-4",children:e.jsx(ut,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Tornado Chart",onClick:()=>l("tornado"),className:"h-10 p-4",children:e.jsx(ot,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{tooltip:"Range Chart",onClick:()=>l("range"),className:"h-10 p-4",children:e.jsx(Ze,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"KPI",onClick:()=>l("kpi"),className:"h-10 p-4",children:e.jsx(pt,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Text",onClick:()=>l("text"),className:"h-10 p-4",children:e.jsx(Ot,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{tooltip:"Map",onClick:()=>l("map"),className:"h-10 p-4",children:e.jsx(at,{className:t.cn("size-5",a)})}),e.jsx(t.IconButton,{openDelay:x,tooltip:"Custom",onClick:()=>l("custom"),className:"h-10 p-4",children:e.jsx(we,{className:t.cn("size-5",a)})})]})}function ea({chartType:s,className:a,customIcon:n,componentName:r}){const o=Pe();switch(s){case"bar":return e.jsx(Be,{className:a});case"line":return e.jsx(Fe,{className:a});case"pie":return e.jsx(et,{className:a});case"radar":return e.jsx(rt,{className:a});case"scatter":return e.jsx(tt,{className:a});case"bubble":return e.jsx(mt,{className:a});case"doughnut":return e.jsx(st,{className:a});case"stackedBar":return e.jsx(Xe,{className:a});case"stackedLine":return e.jsx(xt,{className:a});case"polarArea":return e.jsx(ut,{className:a});case"funnel":return e.jsx(ht,{className:a});case"tornado":case"pyramid":return e.jsx(ot,{className:a});case"range":return e.jsx(Ze,{className:a});case"kpi":return e.jsx(pt,{className:a});case"text":return e.jsx(qt,{className:a});case"map":return e.jsx(at,{className:a});case"custom":return n&&o?e.jsx(o,{className:a}):r?r==null?void 0:r.charAt(0).toUpperCase():e.jsx(we,{className:a});default:return e.jsx(ze,{className:a})}}function ss({variant:s="ghost"}){var i,c;const[a,n]=L.useState(!1),r=t.useEditorStore(d=>d.card),o=r.type;return t.useDashboardStore(d=>d.isVisualEditing),e.jsxs(t.Popover,{open:a,onOpenChange:n,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.Button,{size:"sm",variant:s||"ghost",children:e.jsx(ea,{className:"size-4",chartType:o,customIcon:(i=r.customCardPreferences)==null?void 0:i.icon,componentName:(c=r.customCardPreferences)==null?void 0:c.componentName})})}),e.jsxs(t.PopoverContentCustom,{onOpenAutoFocus:d=>d.preventDefault(),className:"w-72 p-1",children:[e.jsx(ts,{onChartTypeChange:()=>n(!1)}),e.jsx(Wn,{onChartTypeChange:()=>n(!1)})]})]})}const Ee="focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0";function Tt(s,a){var r,o,i;const n=t.getNumberAxis(s,{});return["pie","doughnut","polarArea","funnel"].includes(a)?"category":((i=(o=(r=s==null?void 0:s.chartOptions)==null?void 0:r.scales)==null?void 0:o[n])==null?void 0:i.type)||"linear"}function ta(){var M,F,P,V,z,Y;const[s,a]=L.useState(!1),n=t.useEditorStore(R=>{var q;return(q=R.card)==null?void 0:q.preferences}),r=t.useEditorStore(R=>{var q;return(q=R.card)==null?void 0:q.type}),o=t.getNumberAxis(n,{}),[i,c]=L.useState(Tt(n,r)),[d,l]=L.useState(((P=(F=(M=n==null?void 0:n.chartOptions)==null?void 0:M.scales)==null?void 0:F[o])==null?void 0:P.min)||""),[x,h]=L.useState(((Y=(z=(V=n==null?void 0:n.chartOptions)==null?void 0:V.scales)==null?void 0:z[o])==null?void 0:Y.max)||""),[u,j]=L.useState(d||x?"custom":"auto"),[y,S]=L.useState(""),[p,D]=L.useState(0),[f,g]=L.useState(""),[v,O]=L.useState(""),[E,b]=L.useState(""),C=t.useEditorStore(R=>R.actions.setCardPreferences),{updateCardInFrame:w}=t.useEditorActions(),T=t.useEditorStore(R=>R.card),k=["pie","doughnut","polarArea","funnel"].includes(r);L.useEffect(()=>{var R,q,H,K,G,$,J,X,se,re,le,ne,te,ce;c(Tt(n,r)),l(((H=(q=(R=n==null?void 0:n.chartOptions)==null?void 0:R.scales)==null?void 0:q[o])==null?void 0:H.min)===0?0:""),h((($=(G=(K=n==null?void 0:n.chartOptions)==null?void 0:K.scales)==null?void 0:G[o])==null?void 0:$.max)||""),S(((re=(se=(X=(J=n==null?void 0:n.chartOptions)==null?void 0:J.scales)==null?void 0:X[o])==null?void 0:se.ticks)==null?void 0:re.stepSize)||""),D(((le=n==null?void 0:n.numberAxisFormat)==null?void 0:le.decimalPlaces)||0),g(((ne=n==null?void 0:n.numberAxisFormat)==null?void 0:ne.suffix)||""),O(((te=n==null?void 0:n.numberAxisFormat)==null?void 0:te.currency)||""),b(((ce=n==null?void 0:n.numberAxisFormat)==null?void 0:ce.locale)||"")},[s,n,o,r]);function m(R,q){return q===""||/^[0-9\b]+$/.test(q)?Number(q):Number(R)}function B(){const R=[...new Set(t.LOCALE_CURRENCY_PAIRS.map(q=>q.currency))];return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-6 items-center gap-2",children:[e.jsx(t.Label,{className:"col-span-2 hover:cursor-pointer hover:underline",htmlFor:"currency",children:e.jsx("a",{target:"_blank",href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat",children:"Currency"})}),e.jsxs(t.Select,{value:v||"none",onValueChange:q=>O(q==="none"?"":q),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Currency"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),R.map(q=>e.jsx(t.SelectItem,{value:q,children:q},q))]})})]}),e.jsxs(t.Select,{value:E,onValueChange:q=>b(q),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Locale"}),t.LOCALE_CURRENCY_PAIRS.map(q=>e.jsx(t.SelectItem,{value:q.locale,children:q.locale},q.locale))]})})]})]}),e.jsxs("div",{className:"grid grid-cols-9 items-center gap-2",children:[e.jsx(t.Label,{className:"col-span-3",htmlFor:"format",children:"Decimals"}),e.jsx(t.Input,{value:p,onChange:q=>D(Number(q.target.value)),id:"format",className:`col-span-6 h-8 w-full tracking-wide ${Ee}`})]})]})}function A(){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 space-y-2",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the scale for number axis"})}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"scale",children:"Type"}),e.jsxs(t.Select,{disabled:k,value:i,onValueChange:R=>c(R),children:[e.jsx(t.SelectTrigger,{className:"col-span-2 h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{id:"type",children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Option"}),e.jsx(t.SelectItem,{value:"linear",children:"Linear"}),e.jsx(t.SelectItem,{value:"logarithmic",children:"Logarithmic"}),e.jsx(t.SelectItem,{value:"category",children:"Category"})]})})]})]}),i=="linear"&&e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2 py-1",children:[e.jsx(t.Label,{htmlFor:"scale-option",children:"Setup"}),e.jsxs(t.RadioGroup,{disabled:k,id:"scale-option",value:u,onValueChange:R=>j(R),className:"col-span-2 flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"auto",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Auto"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"custom",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Custom"})]})]})]}),u==="custom"&&i=="linear"&&I()]})}function I(){return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"range",children:"Range"}),e.jsx(t.Input,{id:"min",value:d,onChange:R=>l(q=>m(q,R.target.value)),className:`col-span-1 h-8 w-full ${Ee}`}),e.jsx(t.Input,{value:x,onChange:R=>h(q=>m(q,R.target.value)),id:"max",className:`col-span-1 h-8 w-full ${Ee}`})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-2",children:[e.jsx(t.Label,{htmlFor:"step-size",children:"Step Size"}),e.jsx(t.Input,{value:y,onChange:R=>S(q=>m(q,R.target.value)),id:"step-size",className:`col-span-1 h-8 w-full ${Ee}`})]})]})}function N(){var K;let R={};u==="custom"&&(R={min:d,max:x,ticks:{stepSize:y}});const q={...n||{},chartOptions:{...n==null?void 0:n.chartOptions,scales:{...(K=n==null?void 0:n.chartOptions)==null?void 0:K.scales,[o]:{type:i,...i==="linear"?R:{}}}},numberAxisFormat:{decimalPlaces:p,suffix:f,currency:v,locale:E}};console.log(q),C(q);const H={...T,preferences:q};w(H)}return e.jsxs(t.Popover,{onOpenChange:R=>a(R),children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Format Number",children:e.jsx(Hs,{className:"size-4"})})}),e.jsx(t.PopoverContentCustom,{align:"end",className:"max-w-65",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Format Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the format for number axis"})]}),e.jsxs("div",{className:"grid gap-2",children:[B(),A(),e.jsx(t.SelectSeparator,{}),e.jsx("div",{className:"grid grid-cols-3",children:e.jsx(t.Button,{onClick:N,variant:"secondary",className:"col-span-1 col-start-3 h-8 w-full",children:"Apply"})})]})]})})]})}function sa(){const s=t.useEditorStore(d=>{var l,x,h,u;return(u=(h=(x=(l=d.card.preferences)==null?void 0:l.chartOptions)==null?void 0:x.plugins)==null?void 0:h.legend)==null?void 0:u.position}),a=t.useEditorStore(d=>{var l,x,h,u;return(u=(h=(x=(l=d.card.preferences)==null?void 0:l.chartOptions)==null?void 0:x.plugins)==null?void 0:h.legend)==null?void 0:u.align}),n=t.useEditorStore(d=>{var l,x,h,u;return(u=(h=(x=(l=d.card.preferences)==null?void 0:l.chartOptions)==null?void 0:x.plugins)==null?void 0:h.legend)==null?void 0:u.display}),{setLegendOptions:r}=t.useEditorActions(),o=d=>{r({display:d,position:s,align:a})},i=d=>{r({display:n,position:d,align:a})},c=d=>{r({display:n,position:s,align:d})};return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsx(t.IconButton,{tooltip:"Legend Settings",children:e.jsx(tn,{className:"size-4"})})}),e.jsx(t.PopoverContentCustom,{align:"end",className:"w-72",children:e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium leading-none",children:"Legend Options"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set the legend options for the chart."})]}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"displayLegend",children:"Display"}),e.jsx("div",{className:"col-span-2 flex h-8 items-center",children:e.jsx(t.SmallSwitch,{checked:n,onCheckedChange:o,id:"displayLegend"})})]}),n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"position",children:"Position"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(t.IconButton,{tooltip:"Top",onClick:()=>i("top"),children:e.jsx(t.ArrowUp,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Left",onClick:()=>i("left"),children:e.jsx(As,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Bottom",onClick:()=>i("bottom"),children:e.jsx(t.ArrowDown,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Right",onClick:()=>i("right"),children:e.jsx(Ms,{className:"size-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-3 items-center gap-4",children:[e.jsx(t.Label,{htmlFor:"align",children:"Align"}),e.jsxs("div",{className:"col-span-2 flex h-8 items-center",children:[e.jsx(t.IconButton,{tooltip:"Start",onClick:()=>c("start"),children:e.jsx(ks,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"Center",onClick:()=>c("center"),children:e.jsx(ws,{className:"size-4"})}),e.jsx(t.IconButton,{tooltip:"End",onClick:()=>c("end"),children:e.jsx(Es,{className:"size-4"})})]})]})]})]})]})})]})}function na(){const s=t.useEditorStore(i=>{var c,d;return(d=(c=i.card.preferences)==null?void 0:c.chartOptions)==null?void 0:d.indexAxis}),a=t.useEditorStore(i=>i.card.type),{setChartOrientation:n}=t.useEditorStore(i=>i.actions);function r(){return e.jsx(t.IconButton,{onClick:()=>{n(s==="x"||s===void 0?"y":"x")},tooltip:"Chart Orientation",children:s==="x"||s===void 0?e.jsx(St,{className:"size-4"}):e.jsx(Ct,{className:"size-4"})})}function o(){return e.jsx(t.IconButton,{onClick:()=>{n(s==="y"||s===void 0?"x":"y")},tooltip:"Chart Orientation",children:s==="y"||s===void 0?e.jsx(St,{className:"size-4"}):e.jsx(Ct,{className:"size-4"})})}return e.jsx(e.Fragment,{children:a==="funnel"?o():r()})}function ns(){const s=t.useEditorStore(c=>c.card),a=t.useEditorStore(c=>c.isShowingVisual),n=t.useEditorStore(c=>{var d,l;return(l=(d=c.card)==null?void 0:d.preferences)==null?void 0:l.chartOptions}),r=t.getChartGridStyle(n),{setChartGrid:o}=t.useEditorActions();function i(){const c=["xy","none","x","y"],l=(c.indexOf(r)+1)%c.length;o(c[l])}return a?e.jsxs("div",{"data-info":"visual-settings",className:"flex items-center",children:[["line","bar","range","stackedBar","stackedLine","horizontalBar","funnel"].includes(s.type)&&e.jsx(e.Fragment,{children:e.jsx(na,{})}),!["kpi","text","custom","table"].includes(s.type)&&e.jsxs(e.Fragment,{children:[e.jsx(ta,{}),e.jsx(sa,{})]}),!["pie","doughnut","funnel","radar","polarArea","table","custom","kpi","text","map"].includes(s.type)&&e.jsxs(t.IconButton,{tooltip:"Grid Style",onClick:i,children:[(r==="xy"||!r)&&e.jsx(Zs,{className:"size-4"}),r==="x"&&e.jsx(Gs,{className:"size-4"}),r==="y"&&e.jsx(hn,{className:"size-4"}),r==="none"&&e.jsx(gn,{className:"size-4"})]})]}):null}function aa(){const s=t.useEditorStore(S=>S.frame),a=t.useEditorStore(S=>S.card),{setFrame:n,setActiveTabCardId:r,setCard:o,updateCardInFrame:i}=t.useEditorActions(),c=(S,p)=>{S.dataTransfer.setData("tabIndex",p.toString())},d=S=>{S.preventDefault()},l=(S,p)=>{const D=S.dataTransfer.getData("tabIndex");if(D===p.toString())return;const f=Array.from(s.cards),[g]=f.splice(parseInt(D),1);f.splice(p,0,g),n({...s,cards:f})};function x(S){const p=s.cards.filter(g=>g.id!==S),D=p[0],f={...s,cards:p,activeCardId:D.id};n(f),r(D.id),o(D)}function h(S,p){const D={...s,cards:[...s.cards,p],activeCardId:S.id};n(D),r(p.id)}function u(){const S={...a,id:t.v4(),title:`${a.title} Copy`,tabTitle:`${a.tabTitle||a.title} Copy`,mode:a.mode||"explorer"};h(a,S)}function j(S){const p={dataSource:S.dataSource,connectionId:S.connectionId,lastSelectedDatabase:S.lastSelectedDatabase,lastSelectedSchema:S.lastSelectedSchema,lastSelectedTable:S.lastSelectedTable,lastSelectedDatamodelId:S.lastSelectedDatamodelId,id:t.v4(),title:"Title",description:"",preferences:{onClickFilter:[{columnIndex:0,expression:""}]},type:"bar",sql:"",data:[],mode:"explorer"};h(S,p)}function y(S,p){return S.cards.length===1&&(p.displayTab===!0||p.displayTab===void 0)||S.activeCardId!==p.id&&(p.displayTab===!0||p.displayTab===void 0)?null:e.jsx("div",{onClick:()=>{const D=p.displayTab===void 0?!1:!p.displayTab;o({...p,displayTab:D}),i({...p,displayTab:D})},children:p.displayTab===!0||p.displayTab===void 0?e.jsx(t.Eye,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"}):e.jsx(Us,{className:"mr-2 size-3.5 text-muted-foreground hover:text-foreground"})})}return e.jsx(t.TabsList,{className:"group mx-4 justify-between overflow-x-auto",children:e.jsxs("div",{className:"flex items-center",children:[s.cards.map((S,p)=>e.jsxs(t.TabsTrigger,{draggable:!0,onDragStart:D=>c(D,p),onDragOver:d,onDrop:D=>l(D,p),className:"",value:S.id,children:[y(s,S),e.jsx(t.Editable,{enabled:s.activeCardId===S.id,text:S.tabTitle||S.title,onSave:D=>{o({...a,tabTitle:D}),i({...a,tabTitle:D})},children:S.tabTitle||S.title},S.id),s.activeCardId===S.id&&s.cards.length>1&&e.jsx(t.X,{className:"ml-2 size-3.5 text-muted-foreground hover:text-foreground",onClick:()=>x(S.id)})]},S.id)),e.jsx(t.Button,{className:"ml-1 h-8 px-2 hover:bg-muted-foreground/50",variant:"outline",onClick:()=>j(a),children:e.jsx(t.Plus,{className:"h-4 w-4"})}),e.jsx(t.Button,{className:"invisible ml-1 h-8 px-2 hover:bg-muted-foreground/50 group-hover:visible",variant:"outline",onClick:u,children:e.jsx(Js,{className:"h-4 w-4"})})]})})}function as(){const s=t.useEditorStore(p=>p.frame),a=t.useEditorStore(p=>p.card),n=t.useEditorStore(p=>p.isSqlRunning),r=t.useEditorStore(p=>p.isDevMode),{setFrame:o,setActiveTabCardId:i,setCard:c,setIsDevMode:d,setRunSql:l}=t.useEditorActions(),{data:x,isLoading:h,isFetching:u}=t.useDashboardCardQuery(a);function j(p){const D=s.cards.find(f=>f.id===p);if(D!=null&&D.sql){r||d(!0),i(p);return}if(D!=null&&D.queryConfig){r&&d(!1),y(p),i(p);return}r||y(p),i(p)}function y(p){const D={...s,cards:s.cards.map(g=>g.id===a.id?{...a,mode:a.mode||g.mode}:g),activeCardId:p};o(D);const f=D.cards.find(g=>g.id===p);f.sql&&l(!0),c(f)}function S(){return a.type==="kpi"?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(t.KPICard,{card:a,data:x==null?void 0:x.records,isPending:h})})}):a.type==="text"?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"w-1/2 rounded-md border",children:e.jsx(t.ScrollArea,{className:"mx-3 my-6 h-[300px] overflow-y-auto break-words px-3",children:e.jsx(t.TextCard,{isLoading:n,card:a,data:x==null?void 0:x.records})})})}):e.jsx(t.ErrorBoundary,{FallbackComponent:t.FallbackEditorCard,children:e.jsx(es,{className:"grow border-none shadow-none"})})}return e.jsxs(t.Tabs,{onValueChange:j,value:s.activeCardId,className:"flex grow flex-col",children:[s.cards.map(p=>e.jsx(t.TabsContent,{className:"mt-0 grow",value:p.id,children:S()},p.id)),e.jsx(aa,{})]})}function De({children:s}){t.useEditorStore(g=>g.frame);const a=t.useEditorStore(g=>g.card),n=t.useEditorStore(g=>g.isDevMode),r=t.useEditorStore(g=>g.isShowingVisual),o=t.useDashboardStore(g=>g.isVisualEditing),i=t.useEditorStore(g=>g.pythonStdOut);t.useEditorStore(g=>g.actions.setRunSql);const{setFrame:c,setCard:d,setActiveTabCardId:l,runAssistant:x,setIsDevMode:h}=t.useEditorActions(),{data:u,isLoading:j,isFetching:y,errorMessage:S}=t.useDashboardCardQuery(a);function p(){const g=JSON.stringify(u==null?void 0:u.records,null,2),v=new Blob([g],{type:"application/json"}),O=URL.createObjectURL(v),E=document.createElement("a");E.href=O,E.download=`${a.title}.json`,E.click()}function D(){const v=[Object.keys(u==null?void 0:u.records.reduce((C,w)=>({...C,...w}),{})).join(","),...((u==null?void 0:u.records)||[]).map(C=>Object.values(C).join(","))].join(`
|
|
364
|
+
`),O=new Blob([v],{type:"text/csv"}),E=URL.createObjectURL(O),b=document.createElement("a");b.href=E,b.download=`${a.title}.csv`,b.click()}function f(){const g=`Can you get the documentation for ${a.type} chart?`;x(g)}return a?e.jsxs("div",{className:"relative isolate flex h-full flex-col py-2 pb-3",children:[(j||y)&&e.jsx("div",{className:"absolute bottom-0 left-0 right-0 top-0 z-50 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(t.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),e.jsxs("div",{className:"z-10 mb-0 flex min-h-10 items-center justify-end gap-2 px-6",children:[r&&e.jsxs("div",{className:"flex grow items-center",children:[e.jsx(ss,{}),o&&e.jsx(t.IconButton,{tooltip:"Visual Docs",onClick:f,children:e.jsx(Fs,{className:"size-4"})}),!["table","custom"].includes(a.type)&&o&&e.jsx(Qn,{})]}),!r&&e.jsxs("div",{className:"flex grow items-center gap-1",children:[e.jsx(t.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:D,children:e.jsx(Zn,{className:"size-4"})}),e.jsx(t.Button,{className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70",variant:"ghost",size:"icon",onClick:p,children:e.jsx(Ks,{strokeWidth:1.5,className:"size-4"})}),e.jsx(t.CopyButton,{text:JSON.stringify(u==null?void 0:u.records,null,2),className:"h-7 w-fit px-1 font-mono text-xs text-muted-foreground/70"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[s,e.jsx(ns,{})]}),n&&e.jsx(oa,{})]}),r?e.jsx(as,{}):e.jsxs(t.ResizablePanelGroup,{className:"px-6",direction:"horizontal",children:[i&&e.jsxs(e.Fragment,{children:[e.jsx(t.ResizablePanel,{id:"1",order:1,defaultSize:30,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:i&&e.jsx(ra,{})}),e.jsx(t.ResizableHandle,{})]}),e.jsxs(t.ResizablePanel,{id:"2",order:2,minSize:10,className:"relative flex h-full min-h-0 w-full flex-1 basis-0",children:[(u==null?void 0:u.records)&&(u==null?void 0:u.records.length)>0&&e.jsx(Jn,{data:(u==null?void 0:u.records)||[]}),S&&e.jsx(Yt,{error:S})]})]})]}):e.jsx(e.Fragment,{children:"No Active Card"})}function ra(){const s=t.useEditorStore(n=>n.pythonStdOut);if(!s)return null;const a=s.replace(/\n/g,"<br>");return e.jsxs("div",{className:"relative flex w-full flex-col border-r",children:[e.jsx("div",{className:"sticky top-0 flex max-h-11 min-h-11 grow items-center border-b bg-muted px-3 font-mono text-xs font-semibold text-foreground/70",children:"Python Output"}),e.jsxs(t.ScrollArea,{className:"overflow-y-auto px-2 pt-1 font-mono text-xs text-foreground/90",children:[e.jsx("div",{dangerouslySetInnerHTML:{__html:a}}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function oa(){const s=t.useEditorStore(n=>n.isShowingVisual),a=t.useEditorStore(n=>n.actions.setIsShowingVisual);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Label,{htmlFor:"visualize",children:"Chart"}),e.jsx(t.SmallSwitch,{checked:s,onCheckedChange:()=>a(!s),id:"visualize",className:"data-[state=checked]:bg-foreground/50"})]})}function ia(){var p,D;const s=t.useEditorStore(f=>f.card.customCardPreferences),{data:a}=dt(),n=(a==null?void 0:a.plugins)||[],r=t.useEditorStore(f=>f.card),o=t.useEditorStore(f=>f.frame),i=(s==null?void 0:s.visualType)||"single",{setCustomCardPreferences:c}=t.useEditorActions(),{components:d,manifest:l}=t.useCustomVisual((s==null?void 0:s.url)||""),x=(p=l==null?void 0:l.visuals)==null?void 0:p.find(f=>f.name===(s==null?void 0:s.componentName));function h(f,g){if(!s)return;const O={...(s==null?void 0:s.dataInputCardIds)||{},[f]:{cardId:g,hookRef:null}};c({...s,dataInputCardIds:O})}function u(f){var v,O;const g=(v=o==null?void 0:o.cards)==null?void 0:v.filter(E=>{var b;return((b=E==null?void 0:E.customCardPreferences)==null?void 0:b.visualType)!=="multiple"}).map(E=>({value:E.id,label:E.tabTitle||E.title}));return e.jsx("div",{className:"space-y-2",children:(O=f==null?void 0:f.dataInputs)==null?void 0:O.map((E,b)=>{var C,w;return e.jsxs("div",{className:"grid grid-cols-10 gap-2",children:[e.jsx("div",{className:"col-span-4 flex items-center",children:E}),e.jsx(ae,{className:"col-span-6 h-8 w-full justify-between",label:"",options:g||[],value:((w=(C=s==null?void 0:s.dataInputCardIds)==null?void 0:C[b])==null?void 0:w.cardId)||"",onValueChange:T=>h(b,T)})]},b+Math.random())})})}function j(f,g,v=[],O=""){var E,b;return s?f==="input"?e.jsx(t.Input,{className:`h-8 w-full ${t.removeRing}`,value:((E=s==null?void 0:s.settings)==null?void 0:E[g])||O,onChange:C=>{c({...s,settings:{...s==null?void 0:s.settings,[g]:C.target.value}})}},g):f==="select"?e.jsx(ae,{className:"h-8 w-full",label:"",options:v,value:((b=s==null?void 0:s.settings)==null?void 0:b[g])||O,onValueChange:C=>{c({...s,settings:{...s==null?void 0:s.settings,[g]:C}})}}):null:null}function y(f){const g=Object.entries((f==null?void 0:f.settings)||{});return e.jsx("div",{className:"space-y-3",children:g.map(([v,O])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:O.title}),j(O.ui,v,O.options,O.defaultValue)]},v))})}function S(f){s&&c({...s,visualType:f,componentName:""})}return e.jsxs(t.Accordion,{type:"multiple",defaultValue:["component-settings"],className:"px-6 py-2",children:[e.jsxs(t.AccordionItem,{value:"plugin-settings",children:[e.jsx(t.AccordionTrigger,{children:"Plugin"}),e.jsx(t.AccordionContent,{children:e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(ae,{icon:e.jsx(Bs,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Plugin",options:n,value:(s==null?void 0:s.url)||"",onValueChange:f=>c({...s||{url:"",componentName:""},url:f})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&e.jsx(t.Tabs,{value:i,onValueChange:S,children:e.jsxs(t.TabsList,{className:"h-9 w-full",children:[e.jsx(t.TabsTrigger,{className:"h-7 w-full",value:"single",children:"Single Visual"}),e.jsx(t.TabsTrigger,{className:"h-7 w-full",value:"multiple",children:"Multi-Visual"})]})})]})}),((s==null?void 0:s.type)==="component"||(s==null?void 0:s.type)===void 0)&&s&&e.jsx(e.Fragment,{children:d&&e.jsx(ae,{icon:e.jsx($s,{className:"h-3.5 w-3.5"}),className:"h-9 w-full",label:"Select Component",options:(d==null?void 0:d.filter(f=>f.type===i).map(f=>({value:f.name,label:f.name})))||[],value:s.componentName,onValueChange:f=>{console.log("changing value",f),c({...s,componentName:f})}})})]})})]}),((D=r==null?void 0:r.customCardPreferences)==null?void 0:D.componentName)&&e.jsxs(t.AccordionItem,{className:"border-none",value:"component-settings",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{children:[x&&x.dataInputs&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Input Mapping"}),e.jsx("div",{className:"px-2",children:u(x)})]}),x&&x.settings&&e.jsx("div",{className:"space-y-3",children:e.jsx("div",{className:"px-2",children:y(x)})})]})]})]})}function je(){const[s,a]=L.useState([]),n=t.useEditorStore(x=>x.card.preferences),{setFilterOnClickColumnIndex:r,setCardPreferences:o}=t.useEditorStore(x=>x.actions),i=t.useEditorStore(x=>x.queryResultColumns);t.useEditorStore(x=>{var h;return(h=x.card.preferences)==null?void 0:h.filterOnClickColumnIndex}),L.useEffect(()=>{i&&a(new Array(i.length).fill(!1))},[i]);function c(x,h){var u,j;h?n!=null&&n.onClickFilter&&((u=n==null?void 0:n.onClickFilter)==null?void 0:u.length)>0?o({...n,onClickFilter:[...n.onClickFilter,{columnIndex:x,expression:""}]}):o({...n,onClickFilter:[{columnIndex:x,expression:""}]}):(o({...n,onClickFilter:(j=n==null?void 0:n.onClickFilter)==null?void 0:j.filter(y=>y.columnIndex!==x)}),a(y=>{const S=[...y];return S[x]=!1,S}))}function d(x,h){var j;const u=(j=n==null?void 0:n.onClickFilter)==null?void 0:j.map(y=>y.columnIndex===x?{...y,expression:h.target.value}:y);o({...n,onClickFilter:u})}function l(x){var h,u,j,y;if(s!=null&&s[x]||(u=(h=n==null?void 0:n.onClickFilter)==null?void 0:h.find(S=>S.columnIndex===x))!=null&&u.expression)return e.jsx(t.Input,{value:(y=(j=n==null?void 0:n.onClickFilter)==null?void 0:j.find(S=>S.columnIndex===x))==null?void 0:y.expression,onChange:S=>d(x,S),type:"text",className:"h-9 w-full font-mono text-xs focus-visible:ring-0 focus-visible:ring-ring focus-visible:ring-offset-0",placeholder:"Expression"})}return e.jsxs("div",{className:"max-h-[150px] space-y-2 overflow-y-auto",children:[e.jsx(t.Label,{children:"On Click"}),i==null?void 0:i.map((x,h)=>{var u,j;return e.jsx("div",{className:"group flex items-center justify-between space-y-2",children:e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex items-center space-x-2 py-2",children:[e.jsx(t.Checkbox,{checked:!!((u=n==null?void 0:n.onClickFilter)!=null&&u.find(y=>y.columnIndex===h)),onCheckedChange:y=>c(h,y)}),e.jsx("label",{className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:x}),e.jsx("div",{className:"flex items-center gap-2",children:((j=n==null?void 0:n.onClickFilter)==null?void 0:j.find(y=>y.columnIndex===h))&&e.jsx(t.Pencil,{onClick:()=>{a(y=>{const S=[...y];return S[h]=!y[h],S})},className:"invisible size-3 cursor-pointer text-gray-400 group-hover:visible"})})]}),l(h)]})},x)})]})}function la({idx:s}){var d;const a=t.useEditorStore(l=>{var x;return(x=l.card)==null?void 0:x.preferences}),n=t.useEditorStore(l=>{var x;return(x=l.card.preferences)==null?void 0:x.datasetOptions}),r=t.useEditorStore(l=>l.actions.setCardPreferences),o=(d=a==null?void 0:a.chartOptions)==null?void 0:d.indexAxis,i=n==null?void 0:n.find(l=>l.idx===s);function c(l,x){(l==="end"||l==="start")&&t.getContrastColor(t.getCanvasBackgroundColor());const h={display:l!=="none",align:l,anchor:l,clamp:!0};if(!i)r({...a,datasetOptions:[...n||[],{idx:x,datalabels:h}]});else{const u={...i};u.datalabels=h;const j=n==null?void 0:n.map(y=>y.idx===x?u:y);r({...a,datasetOptions:j})}}return e.jsxs(t.Popover,{children:[e.jsx(t.PopoverTrigger,{children:e.jsx(Rt,{className:"size-4 rotate-[135deg] cursor-pointer text-muted-foreground hover:text-foreground"})}),e.jsx(t.PopoverContent,{className:"w-fit px-2 py-1",children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>c("none",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(t.X,{className:"size-3.5"})}),e.jsx("button",{onClick:()=>c("start",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(sn,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("center",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(an,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})}),e.jsx("button",{onClick:()=>c("end",s),className:"h-7 p-1 text-xs font-normal",children:e.jsx(nn,{className:t.cn("h-4 w-4",{"rotate-90":o==="y"})})})]})})]})}function ca(){const s=t.useEditorStore(i=>i.card),{data:a}=t.useDashboardCardQuery(s),{keys:n}=t.getKeys((a==null?void 0:a.records)||[]),r=n.slice(1).filter(i=>!t.METADATA_KEYS.includes(i));let o=r;if(["stackedBar","stackedLine"].includes(s.type)){const i=t.pivotData({dataArray:(a==null?void 0:a.records)||[],groupKey:n[0],pivotKey:n[1],valueKey:n[2]}),{keys:c}=t.getKeys(i);o=c.slice(1)}return{transformedMetricKeys:o,dimensionKeys:n.slice(0,1),keys:n,defaultMetricKeys:r}}function ft({children:s,className:a,delayDuration:n}){return e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{delayDuration:n,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("span",{className:t.cn("overflow-hidden text-ellipsis whitespace-nowrap",a),children:s})}),e.jsx(t.TooltipContent,{children:s})]})})}function rs(){const s=t.useEditorStore(l=>l.card),a=t.useEditorStore(l=>{var x,h,u;return(u=(h=(x=l==null?void 0:l.card)==null?void 0:x.preferences)==null?void 0:h.chartOptions)==null?void 0:u.indexAxis}),{data:n}=t.useDashboardCardQuery(s),r=a==="y"?"Metric":"Dimension",o=a==="y"?"Dimension":"Metric",{dimensionKeys:i,transformedMetricKeys:c,keys:d}=ca();return d.length===0?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:r}),e.jsx("div",{className:"max-h-[125px] space-y-1 overflow-y-auto",children:i.map(l=>e.jsx("p",{className:"flex h-8 items-center rounded-md bg-muted/70 px-3 hover:bg-muted",title:l,children:os(l)},l))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:o}),e.jsx("div",{className:"my-1 max-h-[125px] space-y-1 overflow-y-auto",children:c.map((l,x)=>e.jsx(is,{className:"flex h-8 items-center bg-muted/70 px-3 hover:bg-muted",iconClassName:"invisible group-hover:visible",col:l,idx:x},l))})]})]})}function os(s,a=30){return s.length>a?s.slice(0,a)+"...":s}function is({col:s,idx:a,className:n,iconClassName:r,children:o}){const i=t.useEditorStore(h=>{var u;return(u=h.card)==null?void 0:u.preferences}),c=t.useEditorStore(h=>{var u,j;return(j=(u=h.card)==null?void 0:u.preferences)==null?void 0:j.datasetOptions}),d=c==null?void 0:c.find(h=>h.idx===a),{setCardPreferences:l}=t.useEditorStore(h=>h.actions);function x(h){if(!d)l({...i,datasetOptions:[...c||[],{idx:a,type:h==="area"?"line":h,fill:h==="area"?"origin":""}]});else{const u={...d};u.type=h==="area"?"line":h,u.fill=h==="area"?"origin":"";const j=c==null?void 0:c.map(y=>y.idx===a?u:y);l({...i,datasetOptions:j})}}return e.jsxs("div",{className:t.cn("group flex items-center justify-between gap-2 rounded-md",n),children:[o||e.jsx(ft,{className:"max-w-[100px]",title:s,children:os(s)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Be,{onClick:()=>x("bar"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Fe,{onClick:()=>x("line"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(Vs,{onClick:()=>x("area"),className:t.cn("size-4 cursor-pointer text-muted-foreground hover:text-foreground",r)}),e.jsx(la,{idx:a})]})]})}function ls(){const s=t.useEditorStore(y=>y.selectedConnectionId),a=t.useEditorStore(y=>y.selectedDatamodelId),n=t.useEditorStore(y=>y.selectedDatabaseName),r=t.useEditorStore(y=>y.selectedSchemaName),o=t.useEditorStore(y=>y.selectedTableName),i=t.useDashboardStore(y=>y.dashboard.filters)||[],c=t.useDashboardStore(y=>y.actions.addFilter),d=t.useDashboardStore(y=>y.actions.removeFilter),{removeFilterValues:l}=t.useDashboardActions(),{modelItems:x,tableName:h,connectionType:u}=t.useEditorAside();function j(y,S="dashboard"){var C;const p=t.fmt(y.column_name),D=t.fmt(n||""),f=t.fmt(r||""),g=t.fmt(h);let v=t.getQualifiedTableName({schemaName:f,tableName:g,connectionType:u,databaseName:D}),O=`${v}.${p}`;const E=(C=x==null?void 0:x.find(w=>w.id===a))==null?void 0:C.name;a&&a!=="none"&&(O=`${t.DATAMODEL_NAMESPCACE}.${E}.${p}`,v=`${t.DATAMODEL_NAMESPCACE}.${E}`);const b=i==null?void 0:i.find(w=>w.column===O&&w.table===g&&(w.database===D||w.database===n));if(b)l(b.id),d(b.id);else{const w=t.v4();return h==="api"&&s?(c({location:S,id:w,column:O,title:y.column_name,dataType:y.data_type,table:"api",database:"",connectionId:s,operation:"in",sql:t.getDefaultFilterSql(y.data_type,v,p)}),w):(c({id:w,location:S,column:O,title:y.column_name,dataType:y.data_type,table:o||"",database:n||"",connectionId:s||"",operation:"in",sql:t.getDefaultFilterSql(y.data_type,v,p)}),w)}}return{assignFilter:j}}function Ce(){const s=t.useDashboardStore(d=>d.dashboard.filters),a=t.useEditorStore(d=>d.frame),{setFrame:n}=t.useEditorActions(),{columns:r}=t.useEditorAside(),{assignFilter:o}=ls();function i(d){const l=o(d,"frame");n({...a,filterId:l})}const c=s==null?void 0:s.find(d=>d.id===a.filterId);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(t.Label,{children:"Card Filter"}),e.jsx(da,{onSelect:i,columns:r}),c&&e.jsx(t.FilterHeader,{filter:c})]})}function da({columns:s,onSelect:a}){var c;const[n,r]=he.useState(!1),[o,i]=he.useState("");return e.jsxs(t.Popover,{open:n,onOpenChange:r,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{size:"sm",variant:"outline",role:"combobox","aria-expanded":n,className:"w-full justify-between font-normal",children:[o?(c=s.find(d=>d.column_name===o))==null?void 0:c.column_name:"Select Column...",e.jsx(t.CaretSortIcon,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-[200px] p-0",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search column",className:"h-9"}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No framework found."}),e.jsx(t.CommandGroup,{children:s==null?void 0:s.map(d=>e.jsxs(t.CommandItem,{value:d.column_name,onSelect:l=>{const x=l===o?"":l;i(x),r(!1),x&&a(d)},children:[d.column_name,e.jsx(t.CheckIcon,{className:t.cn("ml-auto h-4 w-4",o===d.column_name?"opacity-100":"opacity-0")})]},d.column_name))})]})]})})]})}function ua({cardType:s}){return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} Chart`}),e.jsxs(t.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, y-axis-1, y-axis-2,... FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"y-axis1 - number"}),e.jsx("li",{children:"y-axis2 - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:a=>a.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bar-line-area",children:"example"})," in the docs."]})]})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsx(t.AccordionContent,{className:"space-y-4 px-2",children:e.jsx(rs,{})})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(je,{}),e.jsx(Ce,{})]})]})]})})}function Re(){const s=t.useEditorStore(d=>d.card.type),a=t.useEditorStore(d=>d.isDevMode),n=t.useEditorStore(d=>d.card.preferences),{setCardPreferences:r}=t.useEditorStore(d=>d.actions);function o(d){var h;const l={datalabels:{display:d!=="none",align:d,anchor:d,clamp:!0}},x={...n,chartOptions:{...n==null?void 0:n.chartOptions,plugins:{...(h=n==null?void 0:n.chartOptions)==null?void 0:h.plugins,...l}}};r(x)}function i(){var d,l,x;return e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"font-medium",children:"Data Labels"}),e.jsxs(t.Select,{value:((x=(l=(d=n==null?void 0:n.chartOptions)==null?void 0:d.plugins)==null?void 0:l.datalabels)==null?void 0:x.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full focus:ring-1 focus:ring-offset-0",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectLabel,{children:"Data Labels"}),e.jsx(t.SelectItem,{value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"start",children:"Start"}),e.jsx(t.SelectItem,{value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{value:"end",children:"End"})]})})]})]})}function c(){var d,l,x;return e.jsx("div",{children:e.jsxs(t.Select,{value:((x=(l=(d=n==null?void 0:n.chartOptions)==null?void 0:d.plugins)==null?void 0:l.datalabels)==null?void 0:x.anchor)||"none",onValueChange:o,defaultValue:"none",children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select position"})}),e.jsx(t.SelectContent,{children:e.jsxs(t.SelectGroup,{children:[e.jsx(t.SelectItem,{className:"text-xs",value:"none",children:"None"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"start",children:"Start"}),e.jsx(t.SelectItem,{className:"text-xs",value:"center",children:"Center"}),!["pyramid","funnel"].includes(s)&&e.jsx(t.SelectItem,{className:"text-xs",value:"end",children:"End"})]})})]})})}return e.jsx(e.Fragment,{children:a?i():c()})}function ma({cardType:s}){function a(n){return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:n==="bubble"?"SELECT label, [group], x-axis, y-axis, radius FROM table":"SELECT label, [group], x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"group (optional) - category"}),e.jsx("li",{children:"x-axis - number"}),e.jsx("li",{children:"y-axis - number"}),n==="bubble"&&e.jsx("li",{children:"radius - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:i=>i.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/bubble",children:"example"})," in the docs."]})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} Chart`}),e.jsx(t.AccordionContent,{className:"space-y-4 font-mono text-xs",children:a(s)})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsx(t.AccordionContent,{className:"px-2",children:e.jsx(Re,{})})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(je,{}),e.jsx(Ce,{})]})]})]})})}const ha={datasets:[{type:"line",label:"Sum_sales",data:[]},{type:"bar",label:"Sum_profit",data:[]}]},xa={datasets:[{fill:"origin",type:"line",label:"Sum_sales",data:[]}]};function pa(){const s=t.useEditorStore(a=>a.card.type);return e.jsxs("div",{className:"space-y-6 p-6",children:[e.jsx(t.Accordion,{className:" ",type:"single",collapsible:!0,children:fa(s)}),!["kpi"].includes(s)&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Re,{}),e.jsx(je,{}),e.jsx(Ce,{})]})]})}function fa(s){if(["line","bar"].includes(s))return e.jsxs(e.Fragment,{children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsx("p",{children:"Chart Query"})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT x-axis, y-axis-1, y-axis-2, y-axis-3,... FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"X-axis - Category (ex. city)"}),e.jsx("li",{children:"Y-axis - Number (ex. population)"})]})]})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:"Mixed Chart"}),e.jsxs(t.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and change the `type` property in the dataset."]}),e.jsx("pre",{children:JSON.stringify(ha,null,2)})]})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:"Area Chart"}),e.jsxs(t.AccordionContent,{className:"space-y-2 text-xs",children:[e.jsxs("p",{children:["Click ",e.jsx("b",{children:"Customize"})," and add `fill` property to the dataset. See",e.jsx("a",{className:"mx-1 text-blue-500 hover:underline",href:"https://www.chartjs.org/docs/latest/samples/area/line-boundaries.html",target:"_blank",children:"docs"}),"for more options."]}),e.jsx("pre",{children:JSON.stringify(xa,null,2)})]})]})]});if(s==="bubble")return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:s})," chart query?"]})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis, radius FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Bubble Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"}),e.jsx("li",{children:"Radius - Number (ex. population)"})]})]})]})});if(s==="scatter")return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:["How to create a ",e.jsx("span",{children:s})," chart query?"]})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, x-axis, y-axis FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Group (opt) - Category (ex. state)"}),e.jsx("li",{children:"X-axis - Number (ex. avg. age)"}),e.jsx("li",{children:"Y-axis - Number (ex. avg. weight)"})]})]})]})});if(["pie","doughnut","polarArea","funnel"].includes(s))return e.jsx(e.Fragment,{children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"font-normal",children:e.jsxs("p",{children:[e.jsx("span",{children:s==="polarArea"?"Polar":s.charAt(0).toUpperCase()+s.slice(1)})," ","chart query"]})}),e.jsxs(t.AccordionContent,{className:" ",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs font-semibold",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs font-normal [&>li]:mt-2",children:[e.jsx("li",{children:"Label - Category (ex. city)"}),e.jsx("li",{children:"Measure - Number (ex. population)"})]})]})]})})}function ga(){return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(t.Accordion,{type:"single",collapsible:!0,children:e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{className:"",children:"KPI Query"}),e.jsxs(t.AccordionContent,{className:"font-mono",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 font-mono text-xs",children:"SELECT current, previous FROM table"}),e.jsxs("ul",{className:"my-6 ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"current - number"}),e.jsx("li",{children:"previous - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/kpi",children:"example"})," in the docs."]})]})]})}),e.jsx("section",{className:"",children:e.jsx(t.FormatNumberSetting,{})}),e.jsx("div",{}),e.jsx("div",{})]})}function He({children:s,summary:a,open:n,className:r}){return e.jsxs("details",{open:n,className:t.cn("space-y-4 [&_summary>svg]:open:-rotate-180",r),children:[e.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-4",children:[e.jsx(t.Label,{children:a}),e.jsx(t.ChevronUp,{className:"h-4 w-4"})]}),e.jsx("div",{className:"transition-all ease-in-out",children:s})]})}const ja=[{label:"Mercator",value:"mercator"},{label:"Azimuthal Equidistant",value:"azimuthalEquidistant"},{label:"Gnomonic",value:"gnomonic"},{label:"Orthographic",value:"orthographic"},{label:"Stereographic",value:"stereographic"},{label:"Equal Earth",value:"equalEarth"},{label:"Albers",value:"albers"},{label:"Albers USA",value:"albersUsa"},{label:"Conic Conformal",value:"conicConformal"},{label:"Conic Equal Area",value:"conicEqualArea"},{label:"Conic Equidistant",value:"conicEquidistant"},{label:"Equirectangular",value:"equirectangular"},{label:"Transverse Mercator",value:"transverseMercator"},{label:"Natural Earth 1",value:"naturalEarth1"}],ya=["blues","brBG","buGn","buPu","cividis","cool","cubehelixDefault","gnBu","greens","greys","inferno","magma","orRd","oranges","pRGn","piYG","plasma","puBu","puBuGn","puOr","puRd","purples","rainbow","rdBu","rdGy","rdPu","rdYlBu","rdYlGn","reds","sinebow","spectral","turbo","viridis","warm","ylGn","ylGnBu","ylOrBr","ylOrRd"],ba=ya.map(s=>({label:s,value:s}));function va(){var l,x,h,u,j,y,S,p,D,f,g,v,O,E,b,C,w,T;const s=t.useEditorStore(k=>k.card),a=(x=(l=s==null?void 0:s.preferences)==null?void 0:l.mapVisualOptions)==null?void 0:x.topoJsonUrl,[n,r]=L.useState(((u=(h=s==null?void 0:s.preferences)==null?void 0:h.mapVisualOptions)==null?void 0:u.customTopoJsonUrl)||""),{setCardPreferences:o}=t.useEditorActions(),{data:i}=t.useTopoJson(s),c=Object.keys((i==null?void 0:i.objects)||{}).map(k=>({label:k,value:k}))||[],d=[{label:"US States 10m",value:"https://unpkg.com/us-atlas/states-10m.json"},{label:"Countries 50m",value:"https://unpkg.com/world-atlas/countries-50m.json"},{label:"Custom",value:"custom"}];return e.jsxs("div",{className:"p-6",children:[e.jsx(He,{summary:"Map Chart",children:e.jsx("p",{className:"rounded-md bg-muted p-2 font-mono text-xs",children:"SELECT country, value FROM table"})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(He,{open:!0,summary:"Settings",children:e.jsxs("div",{className:"space-y-3 px-2",children:[e.jsx(ae,{className:"h-9",options:d,onValueChange:k=>{console.log("value",k),o({...s.preferences,mapVisualOptions:{topoJsonUrl:k}})},value:a||"",label:"Select Map"}),a==="custom"&&e.jsx(t.Input,{onChange:k=>{r(k.target.value)},onBlur:()=>{var k;console.log("onBlur",n),o({...s.preferences,mapVisualOptions:{...(k=s.preferences)==null?void 0:k.mapVisualOptions,customTopoJsonUrl:n}})},value:n,className:`h-9 w-full ${t.removeRing}`,placeholder:"Custom URL"}),i&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Map Object"}),e.jsx(ae,{className:"h-9",options:c,value:((y=(j=s.preferences)==null?void 0:j.mapVisualOptions)==null?void 0:y.objectKey)||"",label:"Map Object",onValueChange:k=>{var m;o({...s.preferences,mapVisualOptions:{...(m=s.preferences)==null?void 0:m.mapVisualOptions,objectKey:k}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Projection"}),e.jsx(ae,{className:"h-9",options:ja,value:((p=(S=s.preferences)==null?void 0:S.mapVisualOptions)==null?void 0:p.projection)||"",label:"Projection",onValueChange:k=>{var m;o({...s.preferences,mapVisualOptions:{...(m=s.preferences)==null?void 0:m.mapVisualOptions,projection:k}})}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{children:"Colors"}),e.jsx(ae,{className:"h-9",options:ba,value:((f=(D=s.preferences)==null?void 0:D.mapVisualOptions)==null?void 0:f.colorScale)||"",label:"Select Color Scale",onValueChange:k=>{var m;o({...s.preferences,mapVisualOptions:{...(m=s.preferences)==null?void 0:m.mapVisualOptions,colorScale:k}})}})]})]})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(He,{className:"",summary:"Scale Options",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:.1,value:((v=(g=s.preferences)==null?void 0:g.mapVisualOptions)==null?void 0:v.projectionScale)||1,onChange:k=>{var m;o({...s.preferences,mapVisualOptions:{...(m=s.preferences)==null?void 0:m.mapVisualOptions,projectionScale:Number(k.target.value)}})}}),e.jsx(t.Label,{children:"X"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((b=(E=(O=s.preferences)==null?void 0:O.mapVisualOptions)==null?void 0:E.projectionOffset)==null?void 0:b[0])||0,onChange:k=>{var m,B,A,I;o({...s.preferences,mapVisualOptions:{...(m=s.preferences)==null?void 0:m.mapVisualOptions,projectionOffset:[Number(k.target.value),((I=(A=(B=s.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:I[1])||0]}})}}),e.jsx(t.Label,{children:"Y"}),e.jsx(t.Input,{className:`h-9 w-full ${t.removeRing}`,type:"number",step:10,value:((T=(w=(C=s.preferences)==null?void 0:C.mapVisualOptions)==null?void 0:w.projectionOffset)==null?void 0:T[1])||0,onChange:k=>{var m,B,A,I;o({...s.preferences,mapVisualOptions:{...(m=s.preferences)==null?void 0:m.mapVisualOptions,projectionOffset:[((I=(A=(B=s.preferences)==null?void 0:B.mapVisualOptions)==null?void 0:A.projectionOffset)==null?void 0:I[0])||0,Number(k.target.value)]}})}})]})}),e.jsx(t.Separator,{className:"my-4"}),e.jsx(je,{})]})}function Na(){var r;const s=t.useEditorStore(o=>o.card.preferences),{setCardPreferences:a}=t.useEditorStore(o=>o.actions);function n(o){a({...s,textVisualOptions:{...s==null?void 0:s.textVisualOptions,isDynamicText:o==="dynamic"}})}return e.jsxs(t.RadioGroup,{value:(r=s==null?void 0:s.textVisualOptions)!=null&&r.isDynamicText?"dynamic":"static",onValueChange:n,className:"flex gap-3",defaultValue:"x",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"static",id:"r1"}),e.jsx("label",{className:"text-sm",htmlFor:"r1",children:"Static"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.RadioGroupItem,{value:"dynamic",id:"r2"}),e.jsx("label",{className:"text-sm",htmlFor:"r2",children:"Dynamic"})]})]})}function Te({cardType:s,docContent:a,suffix:n="Chart"}){let r="pie-donut-polar";return s==="funnel"&&(r="funnel"),e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:`${t.titleCase(s)} ${n}`}),e.jsx(t.AccordionContent,{children:a||e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT label, measure FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"label - category"}),e.jsx("li",{children:"measure - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:o=>o.stopPropagation(),className:"text-blue-700",href:`https://docs.semaphor.cloud/docs/charts/${r}`,children:"example"})," in the docs."]})]})})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[s!=="text"&&e.jsx(Re,{}),s==="text"&&e.jsx(Na,{})]})]}),!["range","text"].includes(s)&&e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(je,{}),e.jsx(Ce,{})]})]})]})})}function Ca(){const s=t.useEditorStore(r=>{var o,i;return(i=(o=r==null?void 0:r.card)==null?void 0:o.preferences)==null?void 0:i.sortChart}),{setSortChart:a}=t.useEditorActions();function n(){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Sort"}),e.jsx(ae,{className:"h-8",label:"Sort Chart",options:[{label:"None",value:"none"},{label:"ASC",value:"asc"},{label:"DESC",value:"desc"}],value:s||"none",onValueChange:r=>{a(r)}})]})}return e.jsx("div",{className:"space-y-6 px-6 py-2",children:e.jsxs(t.Accordion,{defaultValue:["item-2"],type:"multiple",children:[e.jsxs(t.AccordionItem,{value:"item-1",children:[e.jsx(t.AccordionTrigger,{children:"Stacked Chart"}),e.jsxs(t.AccordionContent,{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT x-axis, stack-by, y-axis FROM table"}),e.jsxs("ul",{className:"ml-6 list-disc text-xs [&>li]:mt-2",children:[e.jsx("li",{children:"x-axis - category"}),e.jsx("li",{children:"stack by - category"}),e.jsx("li",{children:"y-axis - number"})]}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:r=>r.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/stacked",children:"example"})," in the docs."]})]})]}),e.jsxs(t.AccordionItem,{value:"item-2",children:[e.jsx(t.AccordionTrigger,{children:"Settings"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[n(),e.jsx(rs,{})]})]}),e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(je,{}),e.jsx(Ce,{})]})]})]})})}function Sa({cardType:s="table"}){console.log("cardType",s);const a=t.useEditorStore(o=>{var i;return(i=o.card)==null?void 0:i.preferences}),n=t.useEditorStore(o=>o.actions.setCardPreferences),r=o=>{n({...a,allowDownload:o})};return e.jsxs("div",{className:"space-y-6 px-6 py-2",children:[e.jsx(t.Accordion,{defaultValue:["item-3"],type:"multiple",children:e.jsxs(t.AccordionItem,{value:"item-3",children:[e.jsx(t.AccordionTrigger,{children:"Filters"}),e.jsxs(t.AccordionContent,{className:"space-y-4 px-2",children:[e.jsx(je,{}),e.jsx(Ce,{})]})]})}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Checkbox,{onCheckedChange:r,id:"allow-download"}),e.jsx("label",{htmlFor:"allow-download",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Allow Download"})]})]})}const wa=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT dimension, cohort, metric FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/tornado",children:"example"})," in the docs."]})]}),ka=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT y-axis, label, range-from, range-to, range-value FROM table"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/range",children:"example"})," in the docs."]})]}),Ea=e.jsxs("div",{className:"space-y-4 font-mono text-xs",children:[e.jsx("div",{className:"rounded bg-muted px-2 py-1 text-xs",children:"SELECT text FROM table limit 1"}),e.jsxs("div",{children:["See ",e.jsx("a",{target:"_blank",onClick:s=>s.stopPropagation(),className:"text-blue-700",href:"https://docs.semaphor.cloud/docs/charts/text",children:"example"})," in the docs."]})]});function Da(){const s=t.useEditorStore(n=>n.card.type);function a(n){switch(n){case"stackedBar":case"stackedLine":return e.jsx(Ca,{});case"tornado":case"pyramid":return e.jsx(Te,{docContent:wa,cardType:n});case"kpi":return e.jsx(ga,{});case"line":case"bar":return e.jsx(ua,{cardType:n});case"range":return e.jsx(Te,{docContent:ka,cardType:n});case"pie":case"doughnut":case"polarArea":case"radar":case"funnel":return e.jsx(Te,{cardType:n});case"bubble":case"scatter":return e.jsx(ma,{cardType:n});case"table":return e.jsx(Sa,{cardType:n});case"text":return e.jsx(Te,{docContent:Ea,cardType:n,suffix:"Visual"});case"map":return e.jsx(va,{});case"custom":return e.jsx(ia,{});default:return e.jsx(pa,{})}}return e.jsxs(t.ScrollArea,{className:"h-full w-full text-sm",children:[a(s),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})}function cs({label:s,column:a,functions:n,onFunctionChange:r}){let o=n[0];"aggregate"in a?o=n.find(c=>c.value===a.aggregate)||n[0]:"granularity"in a&&(o=n.find(c=>c.value===a.granularity)||n[0]);function i(c){r(c)}return e.jsx(ae,{className:"flex h-8 w-8 justify-center overflow-clip rounded-none border-none bg-muted px-0 [&>svg]:hidden",icon:o.logo,options:n,value:o.value,onValueChange:c=>i(c),label:s,showPlaceholderLabel:!1})}const Ta=[{label:"Sum",value:"SUM",logo:e.jsx(Pt,{className:"size-3.5"})},{label:"Count",value:"COUNT",logo:e.jsx(nt,{className:"size-3.5"})},{label:"Unique",value:"DISTINCT",logo:e.jsx(Ws,{className:"size-3.5"})},{label:"Average",value:"AVG",logo:e.jsx(Is,{className:"size-3.5"})},{label:"Min",value:"MIN",logo:e.jsx(t.ArrowDown,{className:"size-3.5"})},{label:"Max",value:"MAX",logo:e.jsx(t.ArrowUp,{className:"size-3.5"})}];function Ia({column:s}){const{updateMetricColumnOld:a}=t.useEditorActions();let n=Ta;t.isTextDataType(s.type)&&(n=n.filter(o=>["COUNT","DISTINCT"].includes(o.value))),t.isNumberDataType(s.type)&&(n=n.filter(o=>!["DISTINCT"].includes(o.value)));function r(o){const i={...s,aggregate:o,label:ke(s.name,o)};a(s.id,i)}return e.jsx(cs,{column:s,functions:n,onFunctionChange:o=>r(o),label:"Aggregation"})}const Aa=[{label:"Day (D)",value:"day",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"D"})},{label:"Week (W)",value:"week",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"W"})},{label:"Month (M)",value:"month",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"M"})},{label:"Year (Y)",value:"year",logo:e.jsx(t.Label,{className:"cursor-pointer text-xs",children:"Y"})}];function Ma({column:s}){const{updateGroupByColumnOld:a}=t.useEditorActions();function n(r){const o={...s,granularity:r,label:Ne(s.name,r)};a(s.id,o)}return e.jsx(cs,{column:s,functions:Aa,onFunctionChange:r=>n(r),label:"Granularity"})}function La({col:s,onChange:a,droppableId:n}){const{columns:r}=t.useDataColumns(),o=L.useMemo(()=>{let d=[];(n===xe||n===pe||n===fe)&&(d=r);const l=d==null?void 0:d.filter(x=>x.column_name!==s.name);return l==null?void 0:l.map(x=>({id:x.column_name,value:x.column_name}))},[r,n,s.name]),i=[{id:s.name,value:s.name}];function c(d){const l=r==null?void 0:r.find(x=>{var h;return x.column_name===((h=d[0])==null?void 0:h.id)});l&&a(l)}return o!=null&&o.length?e.jsx(t.ComboBox2,{multiple:!1,options:o,selectedOptions:i,onChange:c,selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"border-none bg-muted pl-0 pr-8"}):e.jsx("input",{disabled:!0,type:"text",className:"overflow-hidden truncate text-ellipsis whitespace-nowrap bg-muted text-sm",value:s.name})}function ds({column:s}){const a=t.useEditorStore(l=>l.card.type),n=t.useEditorStore(l=>{var x,h;return(h=(x=l.card)==null?void 0:x.config)==null?void 0:h.metricColumns}),r=(n==null?void 0:n.map(l=>l.label))||[],o=r==null?void 0:r.find(l=>l===s.label||l===s.name),i=o?r.indexOf(o):-1;function c(){return e.jsx("div",{className:"pr-1",children:o&&e.jsx(is,{idx:i,col:o,children:e.jsx("div",{className:"w-[130px] text-xs text-muted-foreground",children:"Display Series As"})})})}function d(){return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Data Labels"}),e.jsx(Re,{})]})}return e.jsxs("div",{className:"space-y-1",children:[["stackedBar","stackedLine","bar","line"].includes(a)&&c(),["pie","doughnut"].includes(a)&&d()]})}function Oa({column:s,type:a,onRemoveColumn:n,droppableId:r}){const[o,i]=L.useState(!1),{updateGroupByColumnOld:c,updateMetricColumnOld:d,updatePivotByColumnOld:l}=t.useEditorActions(),{attributes:x,listeners:h,setNodeRef:u,transform:j,transition:y,isDragging:S}=t.useSortable({id:s.id,data:{type:a}}),p=j?{opacity:S?.5:void 0,transform:t.CSS.Translate.toString(j),transition:y}:void 0,D=t.isTextDataType(s.type);function f(b){const C=t.isNumberDataType(b.data_type),w=t.isTextDataType(b.data_type),T=t.isDateDataType(b.data_type),k=C?"number":w?"string":T?"date":"string";if(r===xe){if(w){const m={id:s.id,name:b.column_name,type:k,role:"groupby"};c(s.id,m)}if(T){const m={id:s.id,name:b.column_name,type:k,role:"groupby",label:Ne(b.column_name,"month"),granularity:"month"};c(s.id,m)}}if(r===fe){if(w){const m={id:s.id,name:b.column_name,type:k,role:"groupby"};l(s.id,m)}if(T){const m={id:s.id,name:b.column_name,type:k,label:Ne(b.column_name,"month"),granularity:"month",role:"groupby"};l(s.id,m)}}if(r===pe){const m={id:s.id,name:b.column_name,type:k,role:"metric",label:ke(b.column_name,"SUM"),aggregate:C?"SUM":"COUNT"};d(s.id,m)}}function g(){if(r===pe)return e.jsx("div",{"data-setting-container":"",className:"mt-1.5 max-h-32 overflow-y-auto rounded-md border border-border p-3 text-sm",children:e.jsx(ds,{column:s})})}function v(){const b=t.isDateDataType(s.type);if(r===pe)return e.jsx(Ia,{column:s});if((r===xe||r===fe)&&b)return e.jsx(Ma,{column:s})}function O(){return e.jsx("div",{className:t.cn("grow",{"pl-3":(r===xe||r===fe)&&D}),children:e.jsx(La,{col:s,onChange:f,droppableId:r})})}function E(){return e.jsx("div",{"data-setting-actions":"",className:"flex h-full items-center gap-2",children:e.jsx("button",{className:"h-full pl-2",onClick:()=>i(!o),children:o?e.jsx(pn,{className:t.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")}):e.jsx(Ft,{className:t.cn("size-3 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground")})})})}return e.jsx("div",{...h,...x,ref:u,style:p,children:e.jsxs("div",{className:"group flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"grow",children:[e.jsxs("div",{className:"flex h-8 grow items-center justify-between rounded-md bg-muted",children:[E(),v(),O()]}),o&&g()]}),e.jsx("div",{className:t.cn("opacity-0 transition-opacity duration-200 group-hover:opacity-100",{hidden:o}),children:e.jsx("button",{onClick:()=>n(s.id),children:e.jsx(t.X,{className:"size-3 cursor-pointer text-muted-foreground"})})})]})})}function Ue({id:s,label:a,columns:n,previewColumns:r,sortableType:o,onRemoveColumn:i}){var p,D;const{setNodeRef:c,isOver:d,over:l}=t.useDroppable({id:s}),x=t.useDndStore(f=>f.activeId),h=t.useEditorStore(f=>{var g;return(g=f.card)==null?void 0:g.type}),u=d||((D=(p=l==null?void 0:l.data)==null?void 0:p.current)==null?void 0:D.type)===o,j=x?r:n,y=o===Ae?"Rows":o===Me?"Pivot Columns":"Columns";function S(){if(!j||j.length===0)return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}return e.jsx(t.SortableContext,{items:n==null?void 0:n.map(f=>f.id),children:e.jsxs("div",{className:t.cn("group space-y-2 rounded-md p-4",u&&"border border-muted-foreground/20"),ref:c,children:[e.jsxs("div",{className:"flex items-center justify-between pr-5",children:[e.jsx(t.Label,{className:"text-sm",children:a}),h!=="table"&&e.jsx("span",{className:"text-xs text-muted-foreground/50",children:y})]}),S(),e.jsx("div",{className:"space-y-2",children:j==null?void 0:j.map(f=>f.id===Ht.id?e.jsx(Ba,{},f.id):e.jsx(Oa,{droppableId:s,type:o,column:f,onRemoveColumn:i},f.id))})]})})}function Ba(){return e.jsx("div",{className:"mr-5 flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm",children:e.jsx("span",{className:"text-muted-foreground/70",children:"Drop here"})})}function us({children:s,id:a,type:n}){const{attributes:r,listeners:o,setNodeRef:i,transform:c,transition:d,isDragging:l}=t.useSortable({id:a,data:{type:n}}),x=c?{opacity:l?.5:void 0,transform:t.CSS.Translate.toString(c),transition:d}:void 0;return e.jsx("div",{...o,...r,ref:i,style:x,children:s})}function Fa(){const s=t.useEditorStore(f=>{var g;return(g=f.card.queryConfig)==null?void 0:g.orderBy})||[],a=t.useEditorStore(f=>{var g;return(g=f.card.queryConfig)==null?void 0:g.groupByColumns})||[],n=t.useEditorStore(f=>{var g;return(g=f.card.queryConfig)==null?void 0:g.metricColumns})||[],{addOrderByColumn:r,removeOrderByColumn:o,updateOrderByColumn:i}=t.useEditorActions(),c=[...a,...n];if(c.length===0)return e.jsx(e.Fragment,{});const d=e.jsx(Os,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),l=e.jsx(Ts,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),x=e.jsx(Ls,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),h=e.jsx(Ds,{className:"size-3.5 text-muted-foreground hover:text-foreground"}),u=c==null?void 0:c.filter(f=>!s.some(g=>g.columnId===f.id)).map(f=>({id:f.id,value:f.label||f.name}));function j(f,g){const v=y(f);return v?v.role==="metric"?g==="asc"?x:h:g==="asc"?d:l:null}function y(f){return c.find(g=>g.id===f)}function S(f){const g=s.find(v=>v.columnId===f);if(g){const v={...g,direction:g.direction==="asc"?"desc":"asc"};i(v)}}const p=f=>{r({columnId:f.id,direction:"asc"})};function D(f){const g=s.find(v=>v.columnId===f);g&&o(g)}return e.jsx(t.SortableContext,{items:s.map(f=>Se(f.columnId)),children:e.jsxs("div",{className:"space-y-2 rounded-md p-4 text-sm",children:[e.jsx(t.Label,{className:"text-sm",children:"Sort By"}),u.length>0&&e.jsx("div",{className:"mr-5",children:e.jsx(t.ComboBox2,{multiple:!1,options:u,selectedOptions:[],onChange:f=>p(f[0]),selectAllChecked:!1,onSelectAllCheckedChange:()=>{},inputClassName:"h-8 bg-muted border-none"})}),s.map(f=>{var g,v;return e.jsx(us,{id:Se(f.columnId),type:ct,children:e.jsx("div",{className:"group flex h-8 items-center gap-2 rounded-sm p-0",children:e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex h-full grow items-center justify-between gap-2 rounded-sm bg-muted px-2",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ft,{className:"size-3 cursor-move text-muted-foreground hover:text-foreground"}),e.jsx(ft,{className:"w-[175px] text-sm",children:((g=y(f.columnId))==null?void 0:g.label)||((v=y(f.columnId))==null?void 0:v.name)})]}),e.jsx("button",{title:f.direction==="asc"?"Ascending":"Descending",onClick:()=>S(f.columnId),className:"rounded-sm p-0",children:j(f.columnId,f.direction)})]}),e.jsx("div",{children:e.jsx("button",{onClick:()=>D(f.columnId),className:"rounded-sm p-0",children:e.jsx(t.X,{className:"size-3 text-muted-foreground opacity-0 transition-opacity duration-200 hover:text-foreground group-hover:opacity-100"})})})]})},f.columnId)},Se(f.columnId))})]})})}function za(){const s=t.useEditorStore(D=>{var f;return((f=D.card.queryConfig)==null?void 0:f.groupByColumns)||[]}),a=t.useEditorStore(D=>D.card.type),n=t.useDndStore(D=>D.previewGroupByColumns),r=t.useEditorStore(D=>{var f;return((f=D.card.queryConfig)==null?void 0:f.metricColumns)||[]}),o=t.useDndStore(D=>D.previewMetricColumns),i=t.useEditorStore(D=>{var f;return((f=D.card.queryConfig)==null?void 0:f.pivotColumns)||[]}),c=t.useDndStore(D=>D.previewPivotColumns),{removeColumnFromGroupBy:d,removeColumnFromMetricColumns:l,removeColumnFromPivotBy:x}=t.useEditorActions();function h(D){d(D)}function u(D){l(D)}function j(D){x(D)}let y="Group By",S="Metrics",p="Stack By";return a==="table"&&(y="Rows",S="Metrics",p="Columns"),e.jsxs("div",{className:"flex h-full w-full flex-col gap-3 py-4",children:[e.jsx(ts,{iconClassName:"size-[19px]"}),e.jsxs(t.CustomScrollArea,{className:"flex min-h-0 grow basis-0 flex-col gap-4 overflow-y-auto",children:[e.jsxs("div",{className:"flex flex-col gap-4 p-4",children:[e.jsx(Ue,{onRemoveColumn:h,sortableType:Ae,id:xe,label:y,columns:s,previewColumns:n}),e.jsx(Ue,{onRemoveColumn:j,sortableType:Me,id:fe,label:p,columns:i,previewColumns:c}),e.jsx(Ue,{onRemoveColumn:u,sortableType:Ke,id:pe,label:S,columns:r,previewColumns:o}),e.jsx(Fa,{})]}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function gt({children:s,column:a,id:n,sortableType:r,className:o}){const[i,c]=L.useState(!1),{removeEditorFilter:d,clearEditorFilter:l}=t.useEditorActions(),x=t.useEditorStore(u=>{var j,y;return(y=(j=u.card.queryConfig)==null?void 0:j.filters)==null?void 0:y.some(S=>S.filterColumnName===a.name)});function h(u){d(u)}return e.jsx(us,{id:n,type:r,children:e.jsxs("div",{className:t.cn("group space-y-1 rounded-md bg-muted px-3 py-2",{"border-border":i}),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Label,{className:"text-sm",children:a.name}),x&&e.jsx("button",{onClick:()=>l(a),children:e.jsx(t.FilterX,{className:"size-3 cursor-pointer items-center justify-center text-muted-foreground hover:text-foreground"})})]}),e.jsx("div",{"data-setting-actions":"",className:"invisible flex h-full items-center gap-2 group-hover:visible",children:e.jsx("button",{onClick:()=>h(a),children:e.jsx(t.X,{className:"size-3.5 cursor-pointer items-center justify-center rounded-r-sm text-muted-foreground"})})})]}),e.jsxs("div",{className:t.cn("group flex items-center rounded-t-md text-sm",!i&&"rounded-b-md",i&&"border border-border"),children:[e.jsx("div",{children:e.jsx(t.GripVertical,{className:"mr-2 size-3.5 cursor-move items-center justify-center p-0 text-muted-foreground/60 hover:text-foreground"})}),e.jsx("div",{className:t.cn("grow cursor-pointer overflow-hidden truncate text-ellipsis whitespace-nowrap",o),children:s})]})]})})}function Pa({column:s,sortableType:a}){const n=t.useDashboardStore(v=>v.themeStyle),r=t.useEditorStore(v=>{var O,E;return(E=(O=v.card)==null?void 0:O.queryConfig)==null?void 0:E.filters}),o=t.useEditorStore(v=>{var O,E;return(E=(O=v.card.queryConfig)==null?void 0:O.filterColumns)==null?void 0:E.find(b=>b.name===s.name)}),{selectedConnectionId:i,selectedDatabaseName:c,selectedTableName:d}=t.useEditorAside(),l=L.useMemo(()=>{var v;return(v=r==null?void 0:r.find(O=>O.filterColumnName===s.name))==null?void 0:v.filterValue},[r,s.name]),x=L.useMemo(()=>Array.isArray(l)?l.map(v=>({id:v,value:v})):[],[l]),{updateEditorFilterValue:h}=t.useEditorActions(),u={column:s.name,sql:s.sql,id:s.name,connectionId:i,dataType:s.type},{data:j,isLoading:y,isFetching:S,isError:p}=t.useFilterQuery(u),D=L.useMemo(()=>{var O;return u.column?(O=j==null?void 0:j.records)==null?void 0:O.map(E=>{let b=u.column.split(".").slice(-1)[0].replace(/"/g,"");return E[b]===void 0&&(b=b.toLowerCase()),{id:E[b],value:E[b]}}):[]},[j,u.column]);function f(v){const O=v.map(E=>E.id);h(s.name,O)}function g(){return y||S?e.jsx(t.Skeleton,{style:{borderRadius:n==null?void 0:n.controlInputRadius},className:"h-8 min-w-60 bg-foreground/10"}):p?e.jsx("div",{className:"flex h-8 min-w-60 items-center bg-muted px-2 text-sm",children:"Error"}):e.jsx(t.ComboBox2,{renderFilterModeButton:()=>e.jsx(Ra,{columnName:s.name}),showNegativeIndicator:(o==null?void 0:o.mode)==="exclude",options:D,onChange:f,selectedOptions:x,selectAllChecked:!1,onSelectAllCheckedChange:()=>{}})}return e.jsx(gt,{className:"w-60",id:s.id,sortableType:a,column:s,children:g()})}function Ra({columnName:s}){const{setEditorFilterMode:a}=t.useEditorActions(),n=t.useEditorStore(o=>{var i,c;return(c=(i=o.card.queryConfig)==null?void 0:i.filterColumns)==null?void 0:c.find(d=>d.name===s)});function r(){(n==null?void 0:n.mode)==="exclude"?a(s,"include"):a(s,"exclude")}return e.jsx(t.Button,{onClick:r,variant:"secondary",size:"sm",className:t.cn("h-5 text-xs hover:underline",{}),children:t.titleCase((n==null?void 0:n.mode)==="exclude"?"exclude":"include")})}function Va({column:s,sortableType:a}){const[n,r]=L.useState(!1),{selectedConnectionId:o,selectedDatabaseName:i,selectedTableName:c}=t.useEditorAside(),d={column:s.name,sql:s.sql,id:s.name,connectionId:o,title:"",dataType:s.type},{isLoading:l,isFetching:x,isError:h,data:u}=t.useFilterQuery(d),j=u==null?void 0:u.records,{dateRange:y,setDateRange:S,initialDateRange:p}=t.useDateRangeFromRecords(j),{updateEditorFilterValue:D}=t.useEditorActions();function f(O){var b,C;const E={gte:(b=O==null?void 0:O.from)==null?void 0:b.toISOString(),lte:(C=O==null?void 0:O.to)==null?void 0:C.toISOString()};D(s.name,E)}function g(){D(s.name,null,!0),S(p)}function v(){return l||x?e.jsx("div",{children:e.jsx(t.Skeleton,{className:"h-8 w-72 bg-foreground/10"})}):h?e.jsx("div",{className:"h-8 w-72 bg-muted px-2",children:"Error"}):j?e.jsx(t.DateRangePopover,{title:d.title,open:n,inputClassName:"h-8",setOpen:r,dateRange:y,setDateRange:S,onApply:f,onClear:g}):e.jsx(t.Label,{className:"flex h-8 w-72 items-center bg-muted px-2",children:"No Data"})}return e.jsx(gt,{className:"w-72",id:s.id,sortableType:a,column:s,children:v()})}function qa({id:s,label:a,columns:n,previewColumns:r,sortableType:o}){var S,p;const{setNodeRef:i,isOver:c,over:d}=t.useDroppable({id:s}),l=t.useDndStore(D=>D.activeId),x={},h=c||((p=(S=d==null?void 0:d.data)==null?void 0:S.current)==null?void 0:p.type)===o;function u(){if(!y||y.length===0)return e.jsx("div",{className:"flex h-8 grow items-center space-x-2 rounded-md border border-dashed border-muted-foreground/80 bg-background px-2 py-1 text-sm text-muted-foreground",children:e.jsx("span",{className:"invisible text-muted-foreground/70 group-hover:visible",children:"Drag here"})})}function j(D){const f=t.isDateDataType(D.type);return D.id===Ht.id?e.jsx(gt,{id:D.id,sortableType:o,column:D,children:e.jsx(_a,{})},D.id):f?e.jsx(Va,{droppableId:s,sortableType:o,column:D},D.id):e.jsx(Pa,{droppableId:s,sortableType:o,column:D},D.id)}const y=l?r:n;return e.jsx(t.SortableContext,{items:n==null?void 0:n.map(D=>D.id),children:e.jsxs("div",{className:t.cn("group space-y-2 rounded-md border-muted-foreground/50 p-4",h&&"border border-muted-foreground/20"),ref:i,style:x,children:[e.jsx(t.Label,{className:"text-sm",children:a}),u(),e.jsx("div",{className:"flex flex-wrap items-center gap-4",children:y==null?void 0:y.map(D=>j(D))})]})})}function _a(){return e.jsx("div",{className:"flex h-8 w-60 items-center space-x-2 rounded-md border border-dashed border-muted-foreground bg-background px-2 py-1 text-sm text-muted-foreground",children:"Drop here"})}function Ga(){const s=t.useEditorStore(o=>{var i;return((i=o.card.queryConfig)==null?void 0:i.filterColumns)||[]}),a=t.useDndStore(o=>o.previewFilterColumns),{removeColumnFromFilterColumns:n}=t.useEditorActions();function r(o){n(o)}return e.jsx("section",{className:"size-full px-4 pb-4",children:e.jsx(qa,{onRemoveColumn:r,sortableType:We,id:Qe,label:"Filters",columns:s,previewColumns:a})})}function $a(){const s=t.useEditorStore(i=>i.card),a=t.useEditorStore(i=>i.showAIDialog),{setShowAIDialog:n}=t.useEditorActions(),{data:r,errorMessage:o}=t.useDashboardCardQuery(s);return e.jsxs("section",{className:"flex justify-between gap-2 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(t.EditorClearButton,{}),!a&&e.jsxs(t.Button,{onClick:()=>n(!0),variant:"secondary",size:"sm",children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Assistant"]}),e.jsx(Qt,{sql:r==null?void 0:r.sql,error:o})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-green-300 px-3 py-1 text-xs font-medium text-black",children:"Preview"}),e.jsx(t.EditorCancelButton,{}),e.jsx(t.EditorAcceptButton,{variant:"default"})]})]})}function Ja(){const s=L.useRef(null),a=L.useRef(null),n=t.useEditorStore(d=>d.isShowingVisual),r=t.useEditorStore(d=>d.showAIDialog),o=t.useEditorStore(d=>d.isDevMode);L.useEffect(()=>{var d,l,x,h;r?((d=s.current)==null||d.resize(0),(l=a.current)==null||l.resize(0)):((x=s.current)==null||x.resize(25),(h=a.current)==null||h.resize(25))},[r]);function i(){return e.jsxs(e.Fragment,{children:[e.jsx(t.ResizablePanel,{role:"query-section",className:"flex",minSize:20,defaultSize:40,children:e.jsx($n,{})}),e.jsx(t.ResizableHandle,{withHandle:!0}),e.jsx(t.ResizablePanel,{className:"pb-1",role:"visual-section",minSize:0,defaultSize:60,children:n&&!r?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(t.ResizablePanel,{ref:s,className:"flex",defaultSize:25,maxSize:30,children:e.jsx(Da,{})})}),!r&&e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:40,defaultSize:75,maxSize:100,children:e.jsx(De,{})})]}):e.jsx(De,{})})]})}function c(){return e.jsx(e.Fragment,{children:e.jsx("div",{className:"grow","data-biz-mode-container":"",children:n?e.jsxs(t.ResizablePanelGroup,{direction:"horizontal",children:[e.jsx(e.Fragment,{children:e.jsx(t.ResizablePanel,{ref:a,defaultSize:25,maxSize:30,children:e.jsx(za,{})})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{defaultSize:75,maxSize:100,children:e.jsxs(t.ResizablePanelGroup,{direction:"vertical",children:[e.jsxs(t.ResizablePanel,{className:"flex min-h-fit flex-col",minSize:10,defaultSize:20,children:[e.jsx($a,{}),e.jsx(Ga,{})]}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{minSize:60,defaultSize:80,children:e.jsx(De,{})})]})})]}):e.jsx(De,{})})})}return e.jsx(t.ResizablePanelGroup,{direction:"vertical",className:"min-h-[250px] min-w-full max-w-lg",children:o?i():c()})}function Ha(s){const a=t.useAIInteractionStore(_=>_.currentAIContext),[n,r]=L.useState(""),[o,i]=L.useState(null),{authToken:c}=t.useSemaphorContext(),d=t.useEditorStore(_=>{var Q;return(Q=_==null?void 0:_.card)==null?void 0:Q.sql}),l=t.useEditorStore(_=>_.isDevMode),x=t.useEditorStore(_=>{var Q;return(Q=_==null?void 0:_.card)==null?void 0:Q.python}),{setCardPython:h,setCardSql:u,setRunSql:j,switchCardType:y,setQueryConfig:S}=t.useEditorActions(),p=t.useEditorStore(_=>_.currentAssitantScope)||[],D=t.useEditorStore(_=>_.userInputForAI),f=t.useEditorStore(_=>_.triggerAIRun),g=t.useEditorStore(_=>_.card),v=t.useEditorStore(_=>_.selectedDatabaseName),O=t.useEditorStore(_=>_.selectedTableName),E=t.useEditorStore(_=>_.selectedConnectionId),b=t.useEditorStore(_=>_.selectedSchemaName),C=t.useDashboardStore(_=>_.dashboard.aiScopeTables),{errorMessage:w,refetch:T,data:k}=t.useDashboardCardQuery(g),{setTriggerAIRun:m,setCurrentAssitantScope:B,setCardConfig:A}=t.useEditorActions(),{selectedDatamodelName:I,connectionType:N,selectedDatamodelId:M}=t.useEditorAside(),{messages:F,setMessages:P,reload:V,error:z,append:Y,input:R,setInput:q,status:H,handleInputChange:K,handleSubmit:G,stop:$}=t.useChat({api:"https://semaphor.cloud/api/v1/assistant",headers:{Authorization:`Bearer ${c==null?void 0:c.accessToken}`},body:{random:Math.random(),assistantId:"editor-assistant",isDevMode:l,aiContext:a},maxSteps:10,onError:_=>{console.log("on error",_)},onToolCall:J,onFinish(_,Q){X(Q.usage),r(""),Q.finishReason==="stop"&&r("")}});L.useEffect(()=>{f&&D&&(Y({role:"user",content:D}),m(!1))},[f,D,Y,m]);async function J({toolCall:_}){var Q,oe,de,me;if(["createChartFromSql","createForecast"].includes(_.toolName)){const W=_.args.sql,Z=_.args.python,ee=_.args.chartType;return y(ee),u(W),h(Z),j(!0),{status:"success",message:"Let the user know that chart is created"}}else if(_.toolName==="getTableColumns")r("Getting table columns...");else{if(_.toolName==="getUserSql")return d?{status:"success",sql:d,python:x||""}:{status:"error",message:"No SQL found"};if(_.toolName==="getCurrentTableScope")return r("Getting table scope..."),ne(),{status:"success",tables:p};if(_.toolName==="generateQueryConfig"){r("Generating query config...");const W=_.args.chartType,Z=_.args.queryConfig;_.args.cardConfig,y(W),A(Z),u(void 0),h(void 0);const ee=await T();return(Q=ee==null?void 0:ee.data)!=null&&Q.error?{status:"error",queryConfig:Z,message:(oe=ee==null?void 0:ee.data)==null?void 0:oe.error.message}:(de=ee==null?void 0:ee.data)!=null&&de.records?{status:"success",queryConfig:Z,message:"The data has been visualized"}:{status:"success",queryConfig:Z,message:"The data has been visualized",records:(me=ee==null?void 0:ee.data)==null?void 0:me.records}}else r("Analyzing...")}}function X(_){i(Q=>Q?{promptTokens:Q.promptTokens+_.promptTokens,completionTokens:Q.completionTokens+_.completionTokens,totalTokens:Q.totalTokens+_.totalTokens}:_)}function se(_){const Q=t.removeFromScopeArray(p,_);re(Q)}function re(_){const Q=t.sanitizeAIScope(_);B(Q),P(oe=>[...oe,{id:crypto.randomUUID(),role:"system",content:`Current scope of tables. Always use the table reference format when generating SQL | ${JSON.stringify(Q)}`}])}function le(){const _={databaseName:v||"",schemaName:b||"",tableName:O||"",datamodelId:M||"",datamodelName:t.resolveDatamodelName(I),connectionId:E||"",connectionType:N||""},Q=t.dedup([...p,_]);re(Q)}function ne(){const _={databaseName:v||"",schemaName:b||"",tableName:O||"",datamodelName:t.resolveDatamodelName(I),connectionId:E||"",connectionType:N||"",datamodelId:M||""};if(!t.isInAiScopeArray([...C||[],...p],_)||p.length===0){const oe=t.dedup([...C||[],...p,_]).filter(de=>de.connectionId===_.connectionId);re(oe)}}const te=!["ready","error"].includes(H),ce=t.getErrorMessage(z);return{messages:F,setMessages:P,reload:V,append:Y,input:R,setInput:q,isLoading:te,handleSetAIScope:ne,handleAddCurrentTableToScope:le,removeFromCurrentSelections:se,currentAssitantScope:p,setCurrentAssitantScope:B,handleInputChange:K,handleSubmit:G,stop:$,chatStatus:H,toolStatus:n,llmUsage:o,onFinish:s,errorMessage:ce}}const Ua=[{title:"Help me write a query for",subtitle:"orders by month"},{title:"Create a bar chart for",subtitle:"sales by category"}];function It(){const s=L.useRef(null),a=L.useRef(null),[n,r]=L.useState(!1),[o,i]=L.useState(t.isDevEnv),[c,d]=L.useState(!1),[l,x]=L.useState(!1),h=t.useCurrentAIContext(),{setCurrentAIContext:u}=t.useAIActions(),j=t.useDashboardStore($=>$.dashboard.aiContext),y=t.useEditorStore($=>$.card.dataSource),S=t.useEditorStore($=>$.actions.setCardSql),p=t.useEditorStore($=>$.actions.setRunSql),D=t.useEditorStore($=>$.showAIDialog),f=t.useDashboardStore($=>$.handleOpenAssistantProfile),{setShowAIDialog:g,setCardPython:v}=t.useEditorActions(),{setDataSource:O}=t.useEditorActions(),{assistantProfile:E}=t.useAssistantProfile(),{messages:b,setMessages:C,reload:w,append:T,input:k,setInput:m,isLoading:B,handleInputChange:A,handleSubmit:I,stop:N,chatStatus:M,llmUsage:F,errorMessage:P}=Ha();t.useAssistantScroll({scrollContainerRef:s,inputRef:a,messages:b}),L.useEffect(()=>{var $;D&&(($=a.current)==null||$.focus(),u({selectedEntities:(y==null?void 0:y.selectedEntities)||[]}))},[D,y,u]);function V($,J){J==="sql"?(S($),p(!0)):J==="python"&&(v($),p(!0))}function z(){var $;($=j==null?void 0:j.selectedEntities)==null||$[0],x(!0)}function Y(){h.selectedEntities.length===0&&u({selectedEntities:(j==null?void 0:j.selectedEntities)||[]})}function R($){Y();const J={role:"user",content:$.title+" "+$.subtitle};T(J)}function q($){Y(),T({role:"user",content:$})}function H(){return e.jsxs(t.DropdownMenu,{children:[e.jsx(t.DropdownMenuTrigger,{asChild:!0,children:e.jsx(t.Button,{className:"h-7 p-2",size:"sm",variant:"ghost",children:e.jsx(t.EllipsisVertical,{className:"size-3.5"})})}),e.jsxs(t.DropdownMenuContent,{align:"end",children:[e.jsx(t.DropdownMenuLabel,{children:"Options"}),e.jsx(t.DropdownMenuSeparator,{}),e.jsx(t.DropdownMenuCheckboxItem,{checked:n,onCheckedChange:r,children:"Token Usage"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:o,onCheckedChange:i,children:"Tool Invocations"}),e.jsx(t.DropdownMenuCheckboxItem,{checked:c,onCheckedChange:d,children:"System Message"})]})]})}function K(){return e.jsx("div",{"data-role":"header",children:e.jsx("div",{className:"text-lg font-semibold",children:"Assistant"})})}const G=(k==null?void 0:k.length)===0&&(b==null?void 0:b.filter($=>$.role==="user").length)===0;return e.jsxs("div",{"data-role":"editor-assistant",className:"flex h-full w-full flex-col justify-between px-6 py-4",children:[e.jsxs("div",{"data-role":"header-section",className:"flex items-start justify-between gap-2",children:[K(),f&&e.jsx(t.Button,{variant:"outline",size:"sm",className:"h-7 p-2",onClick:f,children:(E==null?void 0:E.name)||"Default Profile"}),e.jsxs("div",{"data-role":"header-actions",className:"flex items-center gap-2",children:[H(),e.jsx(t.IconButton,{tooltip:"Add Context",className:"h-7 p-2",onClick:z,children:e.jsx(t.Settings,{className:"size-4"})}),e.jsx(t.IconButton,{className:"h-7 p-2",tooltip:"New Chat",onClick:()=>{C([]),w()},children:e.jsx(t.SquarePen,{className:"size-4"})}),e.jsx(t.Button,{variant:"ghost",className:"h-8",size:"sm",onClick:()=>{g(!1)},children:e.jsx(t.PanelRight,{className:"size-4"})})]})]}),e.jsx(t.CustomScrollArea,{ref:s,className:"mt-2 flex w-full grow basis-0",children:e.jsxs("div",{className:"space-y-4 py-2 pr-3","data-role":"messages",children:[e.jsx(t.PrintMessages,{messages:b,showTools:o,handleRun:V,showSystemMessage:c}),e.jsx(t.ChatStatus,{messages:b,chatStatus:M,errorMessage:P})]})}),e.jsxs("div",{className:"mb-3",children:[G&&!E&&e.jsx(t.Placeholders,{onClick:R,placeholders:Ua}),e.jsx("div",{children:G&&E&&e.jsx(t.SeedQuestions,{seedQuestions:E.seedQuestions||[],handleSeedQuestionClick:q})})]}),e.jsx(t.ChatInputWithContext,{ref:a,setInput:m,stop:N,input:k,handleInputChange:A,handleSubmit:$=>{Y(),I($)},isLoading:B,onFocus:()=>{}}),F&&n&&e.jsx("div",{className:"flex h-8 items-center justify-between",children:e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Usage: ",F.promptTokens," prompt tokens,"," ",F.completionTokens," completion tokens,"," ",F.totalTokens," total tokens"]})}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:(y==null?void 0:y.selectedEntities)||[],open:l,onOpenChange:x,dataSource:y||t.EMPTY_DATA_SOURCE,fallbackDataSource:t.EMPTY_DATA_SOURCE,dialogMode:"aiContext"})]})}function Ya({field:s}){const{attributes:a,listeners:n,setNodeRef:r,transform:o,transition:i,isDragging:c}=t.useSortable({id:s.id}),[d,l]=L.useState(!1),x={transform:t.CSS.Transform.toString(o),transition:i},h=t.getDataType(s.dataType),j=(y=>{const S=(y||"").toLowerCase();switch(t.getDataType(S)){case"number":return nt;case"date":return t.Calendar;case"boolean":return Vt;case"json":return _s;case"geo":return ln;default:return qt}})(s.dataType);return e.jsxs("div",{ref:r,style:x,...a,...n,className:`group/container overflow-hidden rounded-lg transition-all ${c?"scale-95 opacity-50":"border border-transparent hover:border-blue-200 hover:bg-blue-50 dark:hover:border-blue-800 dark:hover:bg-blue-950"}`,children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1 p-2",children:[e.jsx("div",{className:"flex-shrink-0 hover:cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"invisible size-3.5 text-gray-400 group-hover/container:visible"})}),e.jsx(j,{className:t.cn("size-3.5 flex-shrink-0 text-gray-500",h==="string"?"text-blue-500":"",h==="number"?"text-green-500":"",h==="date"?"text-purple-500":"",h==="boolean"?"text-orange-500":"")}),e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:e.jsx("span",{className:`block text-sm text-foreground/90 hover:text-foreground dark:text-muted-foreground ${d?"whitespace-normal break-words":"truncate"}`,children:s.name})})}),e.jsx(t.TooltipContent,{side:"bottom",align:"start",className:"ml-5 max-w-xs",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm font-medium",children:s.label||s.name}),s.description&&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:s.description})]}),e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"mr-2 text-muted-foreground",children:"Name:"}),e.jsx("span",{className:"font-mono",children:s.name})]}),e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"mr-2 text-muted-foreground",children:"Type:"}),e.jsx("span",{className:"font-mono",children:s.dataType})]}),s.qualifiedEntityName&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[s.entityType?s.entityType.charAt(0).toUpperCase()+s.entityType.slice(1):"Entity",":"]}),e.jsx("span",{className:"font-mono",children:s.qualifiedEntityName})]})]})]})})]})}),e.jsx("button",{onClick:y=>{y.stopPropagation(),l(!d)},className:"invisible flex-shrink-0 text-gray-400 hover:text-gray-600 group-hover/container:visible",children:d?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"})})]}),d&&e.jsx("div",{className:"text-muted-foreground-700 px-2 pb-3 text-sm",children:e.jsx(t.Card,{className:"",children:e.jsxs(t.CardContent,{className:"space-y-2 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:s.label||s.name})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"break-all",children:s.name})]}),e.jsx(t.Badge,{variant:"outline",className:"mt-2 text-xs",children:s.dataType})]})})})]})}function Ka(){const[s,a]=L.useState(""),[n,r]=L.useState("all"),o=t.useEditorStore(v=>v.card.dataSource),{columns:i=[],columnGroups:c=[],isLoading:d,error:l}=t.useColumns(),x=i.filter(v=>v.name.toLowerCase().includes(s.toLowerCase())||v.dataType.toLowerCase().includes(s.toLowerCase())||v.qualifiedEntityName&&v.qualifiedEntityName.toLowerCase().includes(s.toLowerCase())),h=v=>v.dataType==="number"||v.dataType==="integer"||v.dataType==="float"||v.dataType==="decimal"||v.dataType==="currency"?"metrics":"dimensions",j=(n==="all"?x:x.filter(v=>h(v)===n)).reduce((v,O)=>{const E=O.qualifiedEntityName||"Other Fields";return v[E]||(v[E]={label:t.toLabel(O.entityName),fields:[]}),v[E].fields.push(O),v},{}),S=Object.keys(j),p=x.filter(v=>h(v)==="dimensions").length,D=x.filter(v=>h(v)==="metrics").length,f=x.filter(v=>h(v)==="calculated").length,g=x.length>0;return d?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(t.LoaderCircle,{className:"h-8 w-8 animate-spin text-gray-400"}),e.jsx("span",{className:"mt-2 text-sm text-gray-500",children:"Loading fields..."})]}):l?e.jsxs("div",{className:"flex h-[calc(100vh-200px)] w-[290px] flex-col items-center justify-center",children:[e.jsx(t.Database,{className:"mb-4 h-12 w-12 text-red-300"}),e.jsx("p",{className:"mb-2 text-sm text-red-500",children:"Error loading fields"}),e.jsx("p",{className:"px-4 text-center text-xs text-red-400",children:l.message||"Failed to load column data"})]}):!o||!o.selectedEntities||o.selectedEntities.length===0?e.jsx(t.ScrollArea,{className:"h-[calc(100vh-200px)] w-[290px]",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(t.Database,{className:"mb-4 h-12 w-12 text-gray-300"}),e.jsx("p",{className:"mb-2 text-sm text-gray-500",children:"No data source selected"}),e.jsx("p",{className:"px-4 text-xs text-gray-400",children:"Select a table, view, or dataset from the data source panel to see available fields"})]})}):e.jsxs("div",{className:"mt-2 flex h-[calc(100vh-200px)] w-full grow flex-col gap-2 px-6 pb-6",children:[e.jsxs("div",{className:"mt-1 flex-shrink-0 space-y-2",children:[i.length>0&&e.jsx("div",{className:"mb-4",children:e.jsx(t.Input$1,{type:"text",placeholder:"Search fields...",value:s,onChange:v=>a(v.target.value)})}),g&&e.jsx(t.Tabs,{defaultValue:"all",value:n,onValueChange:v=>r(v),className:"mb-4",children:e.jsxs(t.TabsList,{className:"grid h-9 w-full grid-cols-4",children:[e.jsxs(t.TabsTrigger,{value:"all",className:"text-xs",children:["All",e.jsx("span",{className:"ml-2 text-xs font-semibold",children:x.length})]}),e.jsxs(t.TabsTrigger,{value:"dimensions",className:"text-xs",children:[e.jsx(t.Layers,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:p})]}),e.jsxs(t.TabsTrigger,{value:"metrics",className:"text-xs",children:[e.jsx(t.ChartColumn,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:D})]}),e.jsxs(t.TabsTrigger,{value:"calculated",className:"text-xs",children:[e.jsx(Rs,{className:"size-4 shrink-0"}),e.jsx("span",{className:"ml-2 text-xs font-semibold",children:f})]})]})})]}),e.jsxs(t.CustomScrollArea,{className:"py-2",children:[e.jsx(t.Accordion,{type:"multiple",defaultValue:S,className:"space-y-2",children:Object.entries(j).map(([v,O])=>{const E=c.find(b=>b.entityName===v)||{entityName:v,label:O.label};return e.jsxs(t.AccordionItem,{value:v,className:"border-none",children:[e.jsx(t.AccordionTrigger,{className:"group rounded-md px-3 py-2 hover:bg-muted hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:E.label||E.entityName}),e.jsx(t.Badge,{variant:"secondary",className:"rounded-full text-xs text-muted-foreground group-hover:bg-background",children:O.fields.length})]})}),e.jsx(t.AccordionContent,{className:"pb-2",children:e.jsx("div",{className:"space-y-1",children:O.fields.map(b=>e.jsx(Ya,{field:b},b.id))})})]},v)})}),Object.keys(j).length===0&&i.length===0&&e.jsxs("div",{className:"py-8 text-center text-sm text-gray-500",children:[e.jsx("p",{children:"No fields found for selected data source"}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:"Try selecting different data sources"})]}),Object.keys(j).length===0&&i.length>0&&e.jsx("div",{className:"py-4 text-center text-sm text-gray-500",children:"No fields found for this category"}),e.jsx(t.ScrollBar,{orientation:"horizontal"}),e.jsx(t.ScrollBar,{orientation:"vertical"})]})]})}function Qa(){return e.jsxs("div",{className:" h-full flex flex-col items-center",children:[" ",e.jsx(Ka,{})," "]})}function Wa({initialJoinPlan:s,availableDataSources:a}){const[n,r]=L.useState(s),[o,i]=L.useState(new Set),c=()=>{const b=n.joins.length>0?Math.max(...n.joins.map(w=>w.sequence))+1:1,C={id:`join-${Date.now()}`,source:{type:"table",name:"",database:"",schema:""},target:{type:"table",name:"",database:"",schema:""},joinType:"INNER",sequence:b,joinKeyGroups:[{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}]};r({...n,joins:[...n.joins,C]}),i(new Set([...o,C.id]))},d=b=>{r({...n,joins:n.joins.filter(C=>C.id!==b)}),i(new Set([...o].filter(C=>C!==b)))},l=(b,C)=>{var m,B;const w=n.joins.find(A=>A.id===b);if(!w)return;const T={...w,...C},k=n.joins.map(A=>A.id===b?T:A);if((m=T.source)!=null&&m.name&&((B=T.target)!=null&&B.name)&&T.joinKeyGroups[0].keys.length===0){const A=a.find(F=>{var P;return F.name===((P=T.source)==null?void 0:P.name)}),I=a.find(F=>{var P;return F.name===((P=T.target)==null?void 0:P.name)}),N={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(A==null?void 0:A.name)||"",entityName:(A==null?void 0:A.name)||"",entityType:(A==null?void 0:A.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(I==null?void 0:I.name)||"",entityName:(I==null?void 0:I.name)||"",entityType:(I==null?void 0:I.type)||"table"},operator:"="},M=[...T.joinKeyGroups];M[0]={...M[0],keys:[N]},T.joinKeyGroups=M,k[k.findIndex(F=>F.id===b)]=T}r({...n,joins:k})};return{joinPlan:n,expandedJoins:o,setJoinPlan:r,addJoin:c,removeJoin:d,updateJoin:l,moveJoinUp:b=>{const C=n.joins.findIndex(w=>w.id===b);if(C>0){const w=[...n.joins],T={...w[C]},k={...w[C-1]};w[C]=k,w[C-1]=T,w.forEach((B,A)=>{B.sequence=A+1});const m={...n,joins:w};r(m)}},moveJoinDown:b=>{const C=n.joins.findIndex(w=>w.id===b);if(C<n.joins.length-1){const w=[...n.joins],T={...w[C]},k={...w[C+1]};w[C]=k,w[C+1]=T,w.forEach((B,A)=>{B.sequence=A+1});const m={...n,joins:w};r(m)}},toggleJoinExpansion:b=>{const C=new Set(o);C.has(b)?C.delete(b):C.add(b),i(C)},getAvailableSourceEntities:b=>{if(n.joins.length===0)return a;const C=n.joins.findIndex(T=>T.id===b);if(C===0)return a;const w=new Set;return n.baseEntity.name&&w.add(n.baseEntity.name),n.joins.slice(0,C).forEach(T=>{w.add(T.source.name),w.add(T.target.name)}),a.filter(T=>w.has(T.name))},getAvailableTargetEntities:b=>a.filter(C=>C.name!==b),addJoinKeyGroup:b=>{const C=n.joins.find(T=>T.id===b);if(!C)return;const w=[...C.joinKeyGroups,{id:"group-"+Date.now()+"-"+Math.random().toString(36).substr(2,9),operator:"AND",keys:[]}];l(b,{joinKeyGroups:w})},updateGroupOperator:(b,C,w)=>{const T=n.joins.find(m=>m.id===b);if(!T)return;const k=[...T.joinKeyGroups];k[C]={...k[C],operator:w},l(b,{joinKeyGroups:k})},removeJoinKeyGroup:(b,C)=>{const w=n.joins.find(k=>k.id===b);if(!w)return;const T=[...w.joinKeyGroups];T.splice(C,1),l(b,{joinKeyGroups:T})},addJoinKey:(b,C)=>{const w=n.joins.find(A=>A.id===b);if(!w)return;const T=a.find(A=>A.name===w.source.name),k=a.find(A=>A.name===w.target.name),m=[...w.joinKeyGroups],B={id:`key-${Date.now()}`,source:{id:`source-${Date.now()}`,name:"",dataType:"",label:"",entityId:(T==null?void 0:T.name)||"",entityName:(T==null?void 0:T.name)||"",entityType:(T==null?void 0:T.type)||"table"},target:{id:`target-${Date.now()}`,name:"",dataType:"",label:"",entityId:(k==null?void 0:k.name)||"",entityName:(k==null?void 0:k.name)||"",entityType:(k==null?void 0:k.type)||"table"},operator:"="};m[C]={...m[C],keys:[...m[C].keys,B]},l(b,{joinKeyGroups:m})},updateJoinKey:(b,C,w,T,k)=>{const m=n.joins.find(M=>M.id===b);if(!m)return;const B=a.find(M=>M.name===m.source.name),A=a.find(M=>M.name===m.target.name),I=[...m.joinKeyGroups],N=I[C].keys[w];T==="sourceColumnName"&&B?I[C].keys[w]={...N,source:{...N.source,name:k}}:T==="targetColumnName"&&A?I[C].keys[w]={...N,target:{...N.target,name:k}}:T==="operator"&&(I[C].keys[w]={...N,operator:k}),l(b,{joinKeyGroups:I})},removeJoinKey:(b,C,w)=>{const T=n.joins.find(m=>m.id===b);if(!T)return;const k=[...T.joinKeyGroups];k[C].keys.splice(w,1),l(b,{joinKeyGroups:k})},generateSQLPreview:()=>{const b=[...n.joins].sort((T,k)=>T.sequence-k.sequence),C=n.baseEntity;if(!C.name)return"SELECT * FROM table -- Please select a base entity";let w=`SELECT *
|
|
365
|
+
FROM ${C.name}`;return b.forEach(T=>{const k=a.find(A=>A.name===T.target.name);if(!k)return;const m=T.joinKeyGroups.filter(A=>A.keys&&A.keys.length>0).map(A=>{const I=A.keys.filter(N=>{var M,F,P,V;return((M=N.source)==null?void 0:M.name)&&((F=N.target)==null?void 0:F.name)&&((P=N.source)==null?void 0:P.entityName)&&((V=N.target)==null?void 0:V.entityName)}).map(N=>`${N.source.entityName}.${N.source.name} ${N.operator} ${N.target.entityName}.${N.target.name}`);return I.length>1?`(${I.join(` ${A.operator} `)})`:I[0]}).filter(Boolean),B=m.length>1?m.join(" OR "):m[0]||"condition_here";w+=`
|
|
366
|
+
${T.joinType} JOIN ${k.name}
|
|
367
|
+
ON ${B}`}),w},isValidConfiguration:()=>!(!n.baseEntity.name||n.joins.some(T=>!T.source.name||!T.target.name)||n.joins.some(T=>T.joinKeyGroups.some(k=>k.keys.length===0))||n.joins.some(T=>T.joinKeyGroups.some(k=>k.keys.some(m=>!m.source.name||!m.target.name||!m.operator))))}}function Xa({joinPlan:s,availableDataSources:a,onSave:n,onRemove:r,onCancel:o}){const{setCardConfig:i}=t.useEditorActions();t.useEditorStore(m=>m.card.config);const{columnGroups:c}=t.useColumns(),{joinPlan:d,expandedJoins:l,setJoinPlan:x,addJoin:h,removeJoin:u,updateJoin:j,moveJoinUp:y,moveJoinDown:S,toggleJoinExpansion:p,getAvailableSourceEntities:D,getAvailableTargetEntities:f,addJoinKeyGroup:g,updateGroupOperator:v,removeJoinKeyGroup:O,addJoinKey:E,updateJoinKey:b,removeJoinKey:C,generateSQLPreview:w,isValidConfiguration:T}=Wa({initialJoinPlan:s,availableDataSources:a}),k=m=>{const B=c.find(A=>A.entityName===m);return(B==null?void 0:B.columns)||[]};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Base Entity (FROM clause)"}),e.jsxs(t.Select,{value:d.baseEntity.name,onValueChange:m=>{const B=a.find(A=>A.name===m);x({...d,baseEntity:{connectionId:(B==null?void 0:B.connectionId)||"",connectionType:(B==null?void 0:B.connectionType)||"none",type:(B==null?void 0:B.type)||"table",name:m,database:B==null?void 0:B.database,schema:B==null?void 0:B.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select base entity..."})}),e.jsx(t.SelectContent,{children:a.map(m=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:m.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:m.type}),m.name,e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]})},m.name))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This entity will be used as the base table in the FROM clause of the SQL query."})]}),e.jsxs("div",{className:"rounded-md border p-3",children:[e.jsx("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Join SQL Preview"}),e.jsx("code",{className:"block whitespace-pre-wrap break-all text-xs",children:w()})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(t.Label,{children:["Joins Configuration (",d.joins.length,")"]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(t.Button,{variant:"outline",size:"sm",onClick:h,children:[e.jsx(t.Plus,{className:"mr-1 h-4 w-4"}),"Add Join"]})})]}),d.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:d.joins.map(m=>{const B=a.find(N=>N.name===m.source.name),A=a.find(N=>N.name===m.target.name),I=l.has(m.id);return e.jsxs(t.Card,{className:"border",children:[e.jsx(t.CardHeader,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{children:m.sequence}),e.jsxs(t.CardTitle,{className:"text-sm",children:["Join ",m.sequence,B&&A&&e.jsxs("span",{className:"ml-2 font-normal text-gray-600",children:["(",B.name," → ",A.name,")"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>y(m.id),disabled:m.sequence===1,children:e.jsx(t.ArrowUp,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>S(m.id),disabled:m.sequence===d.joins.length,children:e.jsx(t.ArrowDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>p(m.id),children:I?e.jsx(t.ChevronUp,{className:"h-4 w-4"}):e.jsx(t.ChevronDown,{className:"h-4 w-4"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",onClick:()=>u(m.id),children:e.jsx(t.X,{className:"h-4 w-4"})})]})]})}),I&&e.jsxs(t.CardContent,{className:"space-y-4 pb-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Source"}),e.jsxs(t.Select,{value:m.source.name,onValueChange:N=>{const M=a.find(F=>F.name===N);j(m.id,{source:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:N,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select source..."})}),e.jsx(t.SelectContent,{children:D(m.id).map(N=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:N.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:N.type}),N.name]})},N.name))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Join Type"}),e.jsxs(t.Select,{value:m.joinType,onValueChange:N=>j(m.id,{joinType:N}),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"INNER",children:"INNER JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"LEFT",children:"LEFT JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"RIGHT",children:"RIGHT JOIN"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"FULL",children:"FULL JOIN"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(t.Label,{children:"Target"}),e.jsxs(t.Select,{value:m.target.name,onValueChange:N=>{const M=a.find(F=>F.name===N);j(m.id,{target:{connectionId:(M==null?void 0:M.connectionId)||"",connectionType:(M==null?void 0:M.connectionType)||"none",type:(M==null?void 0:M.type)||"table",name:N,database:M==null?void 0:M.database,schema:M==null?void 0:M.schema}})},disabled:!m.source.name,children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Select target..."})}),e.jsx(t.SelectContent,{children:m.source.name?f(m.source.name).map(N=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:N.name,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:N.type}),N.name,N.name===m.source.name&&e.jsx(t.Badge,{variant:"outline",className:"text-xs text-yellow-600",children:"(Self-join)"})]})},N.name)):[]})]})]})]}),m.source.name&&m.target.name&&B&&A&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{children:"Join Conditions"}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",onClick:()=>g(m.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition Group"]})]}),m.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:m.joinKeyGroups.map((N,M)=>e.jsxs("div",{className:"space-y-3 rounded-md border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Label,{children:["Group ",M+1]}),M>0&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-gray-100 px-2 py-1",children:[e.jsx(t.Label,{className:"text-xs font-normal",children:"Join with:"}),e.jsx("span",{className:"text-sm font-medium",children:"OR"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(t.Select,{value:N.operator,onValueChange:F=>v(m.id,M,F),children:[e.jsx(t.SelectTrigger,{className:"w-[100px]",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",onClick:()=>O(m.id,M),children:e.jsx(t.Trash2,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[N.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:N.keys.map((F,P)=>e.jsxs("div",{className:"flex flex-col items-start gap-2 rounded-md border p-2 sm:flex-row sm:items-center",children:[P>0&&e.jsx("div",{className:"self-center rounded-md bg-gray-100 px-2 py-1 text-xs font-medium",children:N.operator}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:F.source.name,onValueChange:V=>b(m.id,M,P,"sourceColumnName",V),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Source column"})}),e.jsx(t.SelectContent,{children:k(m.source.name).map(V=>e.jsx(t.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(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:w-20",children:e.jsxs(t.Select,{value:F.operator,onValueChange:V=>b(m.id,M,P,"operator",V),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"=",children:"="}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"<",children:"<"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:">",children:">"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"<=",children:"<="}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:">=",children:">="})]})]})}),e.jsx("div",{className:"mb-2 w-full sm:mb-0 sm:flex-1",children:e.jsxs(t.Select,{value:F.target.name,onValueChange:V=>b(m.id,M,P,"targetColumnName",V),children:[e.jsx(t.SelectTrigger,{children:e.jsx(t.SelectValue,{placeholder:"Target column"})}),e.jsx(t.SelectContent,{children:k(m.target.name).map(V=>e.jsx(t.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(t.Badge,{variant:"outline",className:"ml-2 text-xs",children:V.dataType})]})},V.name))})]})}),e.jsx(t.Button,{type:"button",variant:"ghost",size:"sm",className:"self-center",onClick:()=>C(m.id,M,P),children:e.jsx(t.X,{className:"size-3.5"})})]},F.id||P))}),e.jsxs(t.Button,{type:"button",variant:"outline",size:"sm",className:"mt-2",onClick:()=>E(m.id,M),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Condition"]})]})]},N.id))})]})]})]},m.id)})})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t pt-4",children:[e.jsx(t.Button,{variant:"outline",onClick:()=>{r(),o()},children:"Remove All"}),e.jsx(t.Button,{variant:"outline",onClick:o,children:"Cancel"}),e.jsx(t.Button,{onClick:()=>n(d),disabled:!T(),children:"Save"})]})]})}function At({children:s,open:a,onOpenChange:n,joinPlan:r,availableDataSources:o,onRemove:i,onSave:c,onCancel:d}){return e.jsxs(t.Dialog,{open:a,onOpenChange:n,children:[e.jsxs(t.DialogContent,{className:"max-w-4xl",children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Join Configuration"}),e.jsx(t.DialogDescription,{children:"Configure the join between the two entities to combine the fields."})]}),e.jsx(Xa,{joinPlan:r,availableDataSources:o,onSave:c,onCancel:d,onRemove:i})]}),s]})}function Za({joins:s,baseEntityId:a,availableDataSources:n,generateSQLPreview:r}){return e.jsxs("div",{className:"divide-y divide-border",children:[s.length>0&&e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left font-semibold",children:"Join Chain"}),e.jsx("div",{className:"flex flex-wrap items-center gap-2",children:(()=>{const o=[...s].sort((c,d)=>c.sequence-d.sequence),i=n.find(c=>c.name===a);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:i==null?void 0:i.type}),e.jsx("span",{className:"text-xs font-medium",children:i==null?void 0:i.name}),e.jsx(t.Badge,{variant:"outline",className:"text-xs text-green-600",children:"BASE"})]}),o.map(c=>{const d=n.find(l=>l.name===c.target.name);return e.jsxs("div",{className:"flex items-center",children:[e.jsxs("div",{className:"mx-1 flex items-center gap-1",children:[e.jsx(t.Badge,{variant:"outline",className:"text-xs",children:c.joinType}),e.jsx("span",{className:"text-muted-foreground",children:"→"})]}),e.jsxs("div",{className:"flex items-center gap-1 rounded-md border bg-muted px-2 py-1",children:[e.jsx(t.Badge,{variant:"secondary",className:"text-xs",children:d==null?void 0:d.type}),e.jsx("span",{className:"text-xs font-medium",children:d==null?void 0:d.name})]})]},c.id)})]})})()})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("h3",{className:"mb-3 text-left text-sm font-medium",children:["Configured Joins (",s.length,")"]}),e.jsx("div",{className:"space-y-2",children:[...s].sort((o,i)=>o.sequence-i.sequence).map((o,i)=>{const c=n.find(l=>l.name===o.source.name),d=n.find(l=>l.name===o.target.name);return e.jsxs("div",{className:"flex items-center gap-2 rounded-md bg-muted p-2 text-left",children:[e.jsx(t.Badge,{variant:"secondary",className:"shrink-0 text-xs",children:i+1}),e.jsx(t.Badge,{variant:"outline",className:"shrink-0 text-xs",children:o.joinType}),e.jsxs("span",{className:"text-xs font-medium",children:[c==null?void 0:c.name," → ",d==null?void 0:d.name]}),e.jsxs(t.Badge,{variant:"outline",className:"ml-auto text-xs",children:[o.joinKeyGroups.reduce((l,x)=>l+x.keys.length,0)," ","condition",o.joinKeyGroups.reduce((l,x)=>l+x.keys.length,0)>1?"s":""]})]},o.id)})})]}),e.jsxs("div",{className:"p-4",children:[e.jsx("h3",{className:"mb-3 text-left text-sm font-medium",children:"SQL Query"}),e.jsx("div",{className:"overflow-x-auto rounded-md border bg-muted p-3",children:e.jsx("pre",{className:"whitespace-pre-wrap break-all text-left font-mono text-xs text-muted-foreground",children:r()})})]})]})}function er(){var h,u;const s=t.useEditorStore(j=>j.card),a=t.useEditorStore(j=>j.actions.updateCardConfig),n=((h=s==null?void 0:s.config)==null?void 0:h.joinPlan)||{baseEntity:{type:"table",name:"",database:"",schema:"",connectionId:"",connectionType:"none",dialect:"none"},joins:[]},[r,o]=L.useState(!1),i=((u=s==null?void 0:s.dataSource)==null?void 0:u.selectedEntities)||[],c=j=>{a(s.id,{...s==null?void 0:s.config,joinPlan:j}),o(!1)},d=()=>{a(s.id,{...s==null?void 0:s.config,joinPlan:void 0})},l=()=>{o(!1)},x=()=>{const j=[...n.joins].sort((p,D)=>p.sequence-D.sequence),y=n.baseEntity;if(!y.name)return"SELECT * FROM table -- Please select a base entity";let S=`SELECT *
|
|
368
|
+
FROM ${y.name}`;return j.forEach(p=>{const D=i.find(v=>v.name===p.target.name);if(!D)return;const f=p.joinKeyGroups.filter(v=>v.keys&&v.keys.length>0).map(v=>{const O=v.keys.filter(E=>{var b,C,w,T;return((b=E.source)==null?void 0:b.name)&&((C=E.target)==null?void 0:C.name)&&((w=E.source)==null?void 0:w.entityName)&&((T=E.target)==null?void 0:T.entityName)}).map(E=>`${E.source.entityName}.${E.source.name} ${E.operator} ${E.target.entityName}.${E.target.name}`);return O.length>1?`(${O.join(` ${v.operator} `)})`:O[0]}).filter(Boolean),g=f.length>1?f.join(" OR "):f[0]||"condition_here";S+=`
|
|
369
|
+
${p.joinType} JOIN ${D.name}
|
|
370
|
+
ON ${g}`}),S};return i.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:[n.joins.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-6 text-xs font-semibold",onClick:()=>o(!0),children:[e.jsx(t.Link,{className:t.cn("mr-1 h-3 w-3",{"text-blue-500":n.joins.length>0,"text-gray-500":n.joins.length===0})}),"Join",n.joins.length>1?"s":""," (",n.joins.length,")"]})}),e.jsx(t.TooltipContent,{side:"right",className:"max-w-md overflow-hidden p-0",children:e.jsx(Za,{joins:n.joins,baseEntityId:n.baseEntity.name,availableDataSources:i,generateSQLPreview:x})})]})}),e.jsx(At,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:i,onSave:c,onCancel:l,onRemove:d,children:e.jsx("div",{})})]}),n.joins.length===0&&e.jsx(At,{open:r,onOpenChange:o,joinPlan:n,availableDataSources:i,onSave:c,onCancel:l,onRemove:d,children:e.jsxs(t.Button,{onClick:()=>o(!0),variant:"outline",className:"h-6 text-xs font-semibold",children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Configure Join"]})})]})})})}function tr({entity:s,title:a,maxDetails:n=10}){const o=t.getEntityDetails(s).slice(0,n),i=o.find(d=>d.label==="Description"),c=o.filter(d=>d.label==="Description"?!1:!["Connection","Database","Schema"].includes(d.label));return e.jsx(t.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:a||t.getDisplayName(s)}),i&&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:i.value})]}),c.length>0&&e.jsx("div",{className:"space-y-0.5",children:c.map((d,l)=>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})]},l))})]})})}function sr({entities:s}){return e.jsx(t.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:[s.length," more entities"]}),e.jsx("div",{className:"space-y-1",children:s.map((a,n)=>{const r=t.getEntityDetails(a),o=r.find(c=>c.label==="Description"),i=r.filter(c=>c.label==="Description"?!1:!["Connection","Database","Schema"].includes(c.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:t.getDisplayName(a)}),o&&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:o.value})]}),i.length>0&&e.jsx("div",{className:"mt-1 space-y-0.5",children:i.map((c,d)=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"mr-2 text-muted-foreground",children:[c.label,":"]}),e.jsx("span",{className:"font-mono",children:c.value})]},d))})]},`remaining-${a.type}-${a.name}-${n}`)})})]})})}function nr(){const[s,a]=L.useState(!1),[n,r]=L.useState(!0),o=t.useEditorStore(l=>l.card.dataSource),{updateDataSource:i}=t.useEditorActions(),c={connectionId:"",connectionType:"",mode:"database",selectedEntities:[]},d={...c,...o,selectedEntities:(o==null?void 0:o.selectedEntities)||[]};return e.jsxs("div",{className:"flex w-[325px] flex-col border-r bg-background",children:[e.jsxs("div",{children:[e.jsx("div",{className:t.cn("p-4 px-6",{"pb-0":!n}),children:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex cursor-pointer items-center gap-2",onClick:()=>r(!n),children:[n?e.jsx(t.ChevronDown,{className:"h-4 w-4"}):e.jsx(t.ChevronRight,{className:"h-4 w-4"}),e.jsx(t.Database,{className:"h-5 w-5 text-brand"}),e.jsx("h2",{className:"text-brand-100 font-semibold",children:"Data Source"})]}),e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7",onClick:()=>a(!0),children:[e.jsx(t.Plus,{className:"mr-1 h-3.5 w-3.5"}),"Add"]})]})}),e.jsxs("div",{className:`overflow-hidden px-6 ${n?"max-h-96 space-y-4":"max-h-0 py-0 opacity-0"}`,children:[d.selectedEntities.length>0&&e.jsx(t.TooltipProvider$1,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[d.selectedEntities.slice(0,3).map((l,x)=>e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs(t.Badge,{variant:"secondary",className:"group relative cursor-pointer pr-6 text-xs transition-colors hover:border-red-200 hover:bg-red-50 dark:hover:border-red-800 dark:hover:bg-red-950",children:[t.getDisplayName(l),e.jsx("button",{onClick:h=>{h.stopPropagation();const u=d.selectedEntities.filter(j=>!(j.name===l.name&&j.type===l.type));i({...c,...o,selectedEntities:u})},className:"absolute right-1 top-1/2 -translate-y-1/2 rounded-full p-0.5 hover:bg-red-100",children:e.jsx(t.X,{className:"h-2.5 w-2.5 group-hover:text-red-500"})})]})}),e.jsx(tr,{entity:l})]},`${l.type}-${l.name}-${x}`)),d.selectedEntities.length>3&&e.jsxs(t.Tooltip,{children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsxs(t.Badge,{variant:"outline",className:"text-xs",children:["+",d.selectedEntities.length-3," more"]})}),e.jsx(sr,{entities:d.selectedEntities.slice(3)})]})]})}),e.jsx(er,{})]})]}),e.jsx(Qa,{}),e.jsx(t.DataSourceDialog,{incomingSelectedEntities:(o==null?void 0:o.selectedEntities)||[],dialogMode:"dataSource",open:s,onOpenChange:a,dataSource:d,fallbackDataSource:c})]})}const ar="chart-selector-standard-first";function rr(){const[s,a]=t.useLocalStorageState(ar,!0);return{standardFirst:s,updatePreference:a}}const Mt=({customVisual:s,index:a,onSelect:n})=>{const r=Pe(s.icon||""),o=s.name.charAt(0).toUpperCase(),c=(()=>{const d=s.name.toLowerCase();for(const l of ve)if(l.id==="doughnut"){if(d.includes("doughnut")||d.includes("donut")){const x=l.icon;return e.jsx(x,{className:"h-4 w-4"})}}else if(d.includes(l.id.toLowerCase())){const x=l.icon;return e.jsx(x,{className:"h-4 w-4"})}return null})();return e.jsx(t.CommandItem,{value:`${s.name} custom visual plugin component`,onSelect:n,className:"flex items-center gap-2",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:o}),e.jsx("span",{children:s.name})]})},`${s.url}-${s.name}-${a}`)},ve=[{id:"table",icon:ze,label:"Table"},{id:"bar",icon:Be,label:"Bar Chart"},{id:"line",icon:Fe,label:"Line Chart"},{id:"stackedBar",icon:Xe,label:"Stacked Bar Chart"},{id:"stackedLine",icon:xt,label:"Stacked Line Chart"},{id:"scatter",icon:tt,label:"Scatter Chart"},{id:"bubble",icon:mt,label:"Bubble Chart"},{id:"pie",icon:et,label:"Pie Chart"},{id:"doughnut",icon:st,label:"Doughnut Chart"},{id:"funnel",icon:ht,label:"Funnel Chart"},{id:"radar",icon:rt,label:"Radar Chart"},{id:"polarArea",icon:ut,label:"Polar Area Chart"},{id:"tornado",icon:ot,label:"Tornado Chart"},{id:"range",icon:Ze,label:"Range Chart"},{id:"kpi",icon:pt,label:"KPI"},{id:"text",icon:Ot,label:"Text"},{id:"map",icon:at,label:"Map"}];function or({selectedChart:s,onChartChange:a}){const[n,r]=L.useState([]),[o,i]=L.useState(!1),{data:c}=dt(),{standardFirst:d,updatePreference:l}=rr(),{setCardType:x,setCardPreferences:h,setIsDevMode:u}=t.useEditorStore(v=>v.actions),{setCardCustomCfg:j,setCustomCardPreferences:y,setQueryConfig:S}=t.useEditorActions();L.useEffect(()=>{(async()=>{var O;if(c){const b=(await Promise.all((O=c==null?void 0:c.plugins)==null?void 0:O.map(async C=>(await t.loadManifest(C.value)).visuals.map(k=>({name:k.name,icon:k.icon,url:C.value}))))).flat();r(b)}})()},[c]);function p(v){j(null),h({}),x(v),["custom","text","map"].includes(v)&&(u(!0),S(void 0)),a(v),i(!1)}function D(v){j(null),h({}),x("custom"),y({type:"component",visualType:"single",url:v.url,componentName:v.name,icon:v.icon}),S(void 0),a("custom"),i(!1)}const f=()=>{var O;if(s==="custom"){const E=t.useEditorStore.getState().card;return((O=E==null?void 0:E.customCardPreferences)==null?void 0:O.componentName)||"Custom Visual"}const v=ve.find(E=>E.id===s);return(v==null?void 0:v.label)||"Select chart type"},g=()=>{var O,E;if(s==="custom"){const b=t.useEditorStore.getState().card,C=(O=b==null?void 0:b.customCardPreferences)==null?void 0:O.icon,w=(E=b==null?void 0:b.customCardPreferences)==null?void 0:E.componentName;return C&&w?e.jsx(ir,{icon:C,componentName:w}):e.jsx(we,{className:"h-4 w-4"})}const v=ve.find(b=>b.id===s);if(v){const b=v.icon;return e.jsx(b,{className:"h-4 w-4"})}return e.jsx(we,{className:"h-4 w-4"})};return e.jsx("div",{className:"mb-6",children:e.jsxs(t.Popover,{open:o,onOpenChange:i,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":o,className:"w-full justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[g(),e.jsx("span",{children:f()})]}),e.jsx(t.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"w-[335px] p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search chart types..."}),e.jsxs(t.CommandList,{className:"max-h-[300px]",children:[e.jsx(t.CommandEmpty,{children:"No chart type found."}),d?e.jsxs(e.Fragment,{children:[e.jsx(t.CommandGroup,{heading:"Standard Visuals",className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:ve.map(v=>{const O=v.icon;return e.jsx(t.CommandItem,{value:`${v.label} ${v.id} chart graph visualization`,onSelect:()=>p(v.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{className:"h-4 w-4"}),e.jsx("span",{children:v.label})]})},v.id)})}),n.length>0&&e.jsx(t.CommandGroup,{heading:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:"Custom Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium",children:"Show at the top"}),e.jsx(t.Switch,{checked:!d,onCheckedChange:v=>l(!v),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:n.map((v,O)=>e.jsx(Mt,{customVisual:v,index:O,onSelect:()=>D(v)},`${v.url}-${v.name}-${O}`))})]}):e.jsxs(e.Fragment,{children:[n.length>0&&e.jsx(t.CommandGroup,{heading:e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("span",{children:"Custom Visuals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium",children:"Show at the top"}),e.jsx(t.Switch,{checked:!d,onCheckedChange:v=>l(!v),className:"scale-75"})]})]}),className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:n.map((v,O)=>e.jsx(Mt,{customVisual:v,index:O,onSelect:()=>D(v)},`${v.url}-${v.name}-${O}`))}),e.jsx(t.CommandGroup,{heading:"Standard Visuals",className:"[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",children:ve.map(v=>{const O=v.icon;return e.jsx(t.CommandItem,{value:`${v.label} ${v.id} chart graph visualization`,onSelect:()=>p(v.id),className:"flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(O,{className:"h-4 w-4"}),e.jsx("span",{children:v.label})]})},v.id)})})]})]})]})})]})})}const ir=({icon:s,componentName:a})=>{const n=Pe(),o=(()=>{const i=a.toLowerCase();for(const c of ve)if(c.id==="doughnut"){if(i.includes("doughnut")||i.includes("donut")){const d=c.icon;return e.jsx(d,{className:"h-4 w-4"})}}else if(i.includes(c.id.toLowerCase())){const d=c.icon;return e.jsx(d,{className:"h-4 w-4"})}return null})();return n?e.jsx(n,{className:"h-4 w-4"}):o||e.jsx(we,{className:"h-4 w-4"})},ms=({dataType:s})=>{const a=t.getDataType(s);return a==="string"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-blue-500 text-xs text-white",children:"T"}):a==="number"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-green-500 text-xs text-white",children:"#"}):a==="date"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-purple-500 text-xs text-white",children:"D"}):a==="boolean"?e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-orange-500 text-xs text-white",children:"B"}):e.jsx("span",{className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-sm bg-gray-500 text-xs text-white",children:"?"})};function lr({aliasTemplate:s,onAliasTemplateChange:a}){var l;const[n,r]=L.useState(s),[o,i]=L.useState(!1),c=(l=t.useEditorStore(x=>{var h;return(h=x.card.config)==null?void 0:h.pivotByColumns}))==null?void 0:l[0],d=c?`e.g. Min Sales in {{${c.name}}}`:"e.g. Min Sales in {{region}}";return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-gray-600",children:"Pivot Alias Template"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Input$1,{placeholder:d,value:o?n:s,onChange:x=>{r(x.target.value),i(!0)},onFocus:()=>i(!0),onPointerDown:x=>x.stopPropagation(),className:"h-8 text-xs",onKeyDown:x=>{x.key==="Enter"&&o&&n!==s?(a(n),i(!1)):x.key==="Escape"&&(r(s),i(!1))},"aria-label":"Edit alias template"}),o&&n!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm alias template",onClick:()=>{a(n),i(!1)},children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel alias template edit",onClick:()=>{r(s),i(!1)},children:e.jsx(t.X,{className:"h-4 w-4 text-gray-400"})})]})]})]})}function cr({valueAliases:s,onValueAliasesChange:a}){const[n,r]=L.useState(null),[o,i]=L.useState(""),[c,d]=L.useState(""),l=()=>{a({...s,"":""})},x=u=>{const j={...s};delete j[u],a(j)},h=u=>{const j={...s};delete j[u],j[o]=c,a(j),r(null)};return e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Pivot Value Aliases"}),e.jsxs("div",{className:"space-y-2",children:[Object.entries(s).map(([u,j],y)=>e.jsx("div",{className:"flex items-center gap-2",children:n===u?e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:o,onChange:S=>i(S.target.value),className:"h-8 w-24 text-xs",onPointerDown:S=>S.stopPropagation(),onKeyDown:S=>{S.key==="Enter"?h(u):S.key==="Escape"&&r(null)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:c,onChange:S=>d(S.target.value),className:"h-8 w-24 text-xs",onPointerDown:S=>S.stopPropagation(),onKeyDown:S=>{S.key==="Enter"?h(u):S.key==="Escape"&&r(null)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm value alias edit",onClick:()=>h(u),children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel value alias edit",onClick:()=>r(null),children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]}):e.jsxs(e.Fragment,{children:[e.jsx(t.Input$1,{placeholder:"Value key",value:u,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(u),i(u),d(j)},"aria-label":"Edit value alias key"}),e.jsx(t.Input$1,{placeholder:"Alias label",value:j,className:"h-8 w-24 text-xs",readOnly:!0,onClick:()=>{r(u),i(u),d(j)},"aria-label":"Edit value alias label"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>x(u),"aria-label":"Remove value alias",children:e.jsx(t.X,{className:"h-3 w-3"})})]})},u+y)),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"mt-1 h-8 text-xs",onClick:l,children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"})," Add Value Alias"]})]})]})}function hs(s,a){return`${t.toLabel(a)} of ${t.toLabel(s)}`}const xs=s=>{const{updateCardConfig:a,updateGroupByColumn:n,updateMetricColumn:r,updatePivotByColumn:o,updateSortByColumn:i,removeGroupByColumn:c,removeMetricColumn:d,removePivotByColumn:l,removeSortByColumn:x}=t.useEditorActions(),h=t.useEditorStore(k=>k.card.type),u=s==null?void 0:s.id,j=L.useCallback(k=>{if(!(s!=null&&s.config))return[];switch(k){case"groupBy":return(s.config.groupByColumns||[]).map(m=>({id:m.id,name:m.name,dataType:m.dataType,label:m.label!==void 0?m.label:m.name,qualifiedEntityName:m.qualifiedEntityName,entityId:m.entityId,entityName:m.entityName,entityType:m.entityType,dateFormat:m.dateFormat,customFormat:m.customFormat,granularity:m.granularity}));case"metrics":return s.config.metricColumns||[];case"pivotBy":return(s.config.pivotByColumns||[]).map(m=>({id:m.id,name:m.name,dataType:m.dataType,label:m.label!==void 0?m.label:m.name,qualifiedEntityName:m.qualifiedEntityName,entityId:m.entityId,entityName:m.entityName,entityType:m.entityType}));case"sortBy":return(s.config.sortByColumns||[]).map(m=>({id:m.id,name:m.name,dataType:m.dataType,label:m.label!==void 0?m.label:m.name,qualifiedEntityName:m.qualifiedEntityName,entityId:m.entityId,entityName:m.entityName,entityType:m.entityType,direction:m.direction}));case"source":return[];default:return[]}},[s]),y=L.useCallback((k,m)=>{if(u)switch(k){case"groupBy":{a(u,{groupByColumns:m});break}case"metrics":{a(u,{metricColumns:m});break}case"pivotBy":{a(u,{pivotByColumns:m});break}case"sortBy":{a(u,{sortByColumns:m});break}}},[u,a]),S=L.useCallback((k,m,B)=>{if(!u)return;const I=j(k)[m];if(I)switch(k){case"groupBy":n(u,I.id,{label:B});break;case"metrics":r(u,I.id,{label:B});break;case"pivotBy":o(u,I.id,{label:B});break;case"sortBy":i(u,I.id,{label:B});break}},[u,j,n,r,o,i]),p=L.useCallback((k,m)=>{if(!u)return;const A=j("metrics")[k];A&&r(u,A.id,{aggregate:m,label:hs(A.name,m)})},[u,j,r]),D=L.useCallback((k,m,B)=>{if(!u)return;const I=j("groupBy")[k];if(!I)return;const N={dateFormat:m};m==="custom"&&B?N.customFormat=B:N.customFormat=void 0,n(u,I.id,N)},[u,j,n]),f=L.useCallback((k,m)=>{if(!u)return;const A=j("groupBy")[k];A&&n(u,A.id,{granularity:m})},[u,j,n]),g=L.useCallback((k,m)=>{if(!u)return;const A=j("metrics")[k];A&&r(u,A.id,{aliasTemplate:m})},[u,j,r]),v=L.useCallback((k,m)=>{if(console.log("handleValueAliasesChange",k,m),!u)return;console.log("handleValueAliasesChange",k,m);const A=j("metrics")[k];A&&(console.log("handleValueAliasesChange",m),r(u,A.id,{valueAliases:m}))},[u,j,r]),O=L.useCallback(k=>{u&&a(u,{comparisonType:k})},[u,a]),E=L.useCallback(k=>{u&&a(u,{showTrendline:k})},[u,a]),b=L.useCallback(k=>{u&&a(u,{trendlineWindow:k})},[u,a]),C=L.useCallback(k=>{u&&a(u,{trendlineGranularity:k})},[u,a]),w=L.useCallback(k=>{u&&a(u,{targetValue:k})},[u,a]),T=L.useCallback((k,m)=>{if(!u)return;const A=j(k)[m];if(A){if(k!=="sortBy"){const I=j("sortBy"),N=I.filter(M=>!(M.name===A.name&&M.qualifiedEntityName===A.qualifiedEntityName));N.length!==I.length&&a(u,{sortByColumns:N})}switch(k){case"groupBy":c(u,A.id);break;case"metrics":d(u,A.id);break;case"pivotBy":l(u,A.id);break;case"sortBy":x(u,A.id);break}}},[u,j,c,d,l,x,a]);return{getFieldsForContainer:j,setFieldsForContainer:y,updateLabel:S,handleAggregationChange:p,handleDateFormatChange:D,handleGranularityChange:f,handleAliasTemplateChange:g,handleValueAliasesChange:v,removeField:T,handleKpiComparisonTypeChange:O,handleKpiShowTrendlineChange:E,handleKpiTrendlineWindowChange:b,handleKpiTrendlineGranularityChange:C,handleKpiTargetValueChange:w,cardType:h}};function Lt({value:s,onSave:a,placeholder:n="",type:r="text",className:o=""}){const[i,c]=L.useState(s??""),[d,l]=L.useState(!1);L.useEffect(()=>{c(s??"")},[s]);const x=()=>{a(i),l(!1)},h=()=>{c(s??""),l(!1)};return e.jsxs("div",{className:`flex items-center gap-2 ${o}`,children:[e.jsx(t.Input$1,{placeholder:n,type:r,value:d?i:s??"",onChange:u=>{c(u.target.value),l(!0)},onFocus:()=>l(!0),onClick:u=>u.stopPropagation(),className:"h-8 text-xs",onPointerDown:u=>u.stopPropagation(),onKeyDown:u=>{u.stopPropagation(),u.key==="Enter"&&d&&i!==s?x():u.key==="Escape"&&h()},"aria-label":n||"Edit field"}),d&&i!==s&&e.jsxs(e.Fragment,{children:[e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Confirm edit",onClick:x,children:e.jsx(t.Check,{className:"h-4 w-4 text-green-600"})}),e.jsx(t.Button,{variant:"ghost",size:"icon",className:"h-6 w-6 p-0","aria-label":"Cancel edit",onClick:h,children:e.jsx(t.X,{className:"h-4 w-4 text-muted-foreground"})})]})]})}function dr({field:s,zone:a,index:n,sortDirection:r,onSortDirectionChange:o,hasPivotColumns:i=!1,cardType:c}){var bt;const{attributes:d,listeners:l,setNodeRef:x,transform:h,transition:u,isDragging:j}=t.useSortable({id:s.id}),y=t.useEditorStore(U=>U.card),{updateLabel:S,handleAggregationChange:p,handleDateFormatChange:D,handleGranularityChange:f,handleAliasTemplateChange:g,handleValueAliasesChange:v,removeField:O,handleKpiComparisonTypeChange:E,handleKpiShowTrendlineChange:b,handleKpiTrendlineWindowChange:C,handleKpiTrendlineGranularityChange:w,handleKpiTargetValueChange:T}=xs(y),[k,m]=L.useState(!1),[B,A]=L.useState(s.dateFormat||"YYYY-MM-DD"),[I,N]=L.useState(s.customFormat||""),[M,F]=L.useState(!!s.customFormat),[P,V]=L.useState(s.granularity||"day"),[z,Y]=L.useState(s.aliasTemplate||""),[R,q]=L.useState(s.valueAliases||{}),H=U=>{U==="custom"?F(!0):(F(!1),A(U),a==="groupBy"&&D(n,U,""))},K=U=>{N(U),a==="groupBy"&&D(n,"custom",U)},G=U=>{V(U),a==="groupBy"&&f(n,U)},$=U=>{Y(U),a==="metrics"&&g(n,U)},J=U=>{q(U),a==="metrics"&&v(n,U)},X=U=>{S(a,n,U)},se=()=>{O(a,n)},re={transform:t.CSS.Transform.toString(h),transition:u},le=t.getDataType(s.dataType),ne=le==="date",te=c==="kpi",ce=[{value:"MM-DD-YYYY",label:"01-15-2024 (MM-DD-YYYY)"},{value:"YYYY-MM-DD",label:"2024-01-15 (YYYY-MM-DD)"},{value:"MM/DD/YYYY",label:"01/15/2024 (MM/DD/YYYY)"},{value:"DD/MM/YYYY",label:"15/01/2024 (DD/MM/YYYY)"},{value:"MMMM DD, YYYY",label:"January 15, 2024 (MMMM DD, YYYY)"},{value:"MMM DD, YYYY",label:"Jan 15, 2024 (MMM DD, YYYY)"},{value:"DD MMM YYYY",label:"15 Jan 2024 (DD MMM YYYY)"},{value:"YYYY-MM",label:"2024-01 (YYYY-MM)"},{value:"MMMM YYYY",label:"January 2024 (MMMM YYYY)"},{value:"custom",label:"Custom Format..."}],_=!te&&a!=="pivotBy",Q=te&&ne&&a==="groupBy",oe=!te&&ne&&a==="groupBy",de=te&&ne&&a==="groupBy",me=te&&a==="metrics"&&((bt=y.config)==null?void 0:bt.comparisonType)==="target",W=a==="metrics",Z=()=>e.jsx("div",{onPointerDown:U=>{U.stopPropagation()},className:"cursor-default overflow-hidden text-ellipsis whitespace-nowrap px-0.5 text-xs text-gray-500",children:`${s.entityName}.${s.name}`}),ee=()=>_?e.jsx(Lt,{value:s.label??"",onSave:X,placeholder:"Display label...",type:"text"}):null,yt=()=>Q?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Granularity"}),e.jsxs(t.Select,{value:P,onValueChange:G,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"day",children:"Day"}),e.jsx(t.SelectItem,{value:"week",children:"Week"}),e.jsx(t.SelectItem,{value:"month",children:"Month"}),e.jsx(t.SelectItem,{value:"quarter",children:"Quarter"}),e.jsx(t.SelectItem,{value:"year",children:"Year"})]})]})]}):null,js=()=>oe?e.jsxs(e.Fragment,{children:[yt(),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Date Format"}),e.jsxs(t.Select,{value:M?"custom":B,onValueChange:H,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select date format..."})}),e.jsx(t.SelectContent,{children:ce.map(U=>e.jsx(t.SelectItem,{value:U.value,children:U.label},U.value))})]}),M&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(t.Input$1,{placeholder:"Enter custom format (e.g., YYYY-MM-DD HH:mm)",value:I,onChange:U=>{U.stopPropagation(),K(U.target.value)},onClick:U=>U.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,ys=()=>{var U,ue,ye,vt,Nt;return de?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Comparison Type"}),e.jsxs(t.Select,{value:((U=y.config)==null?void 0:U.comparisonType)||"none",onValueChange:E,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select comparison type..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"none",children:"No Comparison"}),e.jsx(t.SelectItem,{value:"previous_period",children:"Previous Period"}),e.jsx(t.SelectItem,{value:"same_period_last_year",children:"Same Period Last Year"}),e.jsx(t.SelectItem,{value:"target",children:"Target Value"})]})]})]}),e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Show Trendline"}),e.jsx(t.SmallSwitch,{checked:((ue=y.config)==null?void 0:ue.showTrendline)||!1,onCheckedChange:b})]})}),((ye=y.config)==null?void 0:ye.showTrendline)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Window"}),e.jsx(t.Input$1,{type:"number",min:"1",max:"365",value:((vt=y.config)==null?void 0:vt.trendlineWindow)||30,onChange:Ns=>{const Cs=parseInt(Ns.target.value)||30;C(Cs)},className:"h-8 text-xs",placeholder:"30"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Trendline Granularity"}),e.jsxs(t.Select,{value:((Nt=y.config)==null?void 0:Nt.trendlineGranularity)||"day",onValueChange:w,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select granularity..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"day",children:"Day"}),e.jsx(t.SelectItem,{value:"week",children:"Week"}),e.jsx(t.SelectItem,{value:"month",children:"Month"})]})]})]})]})]}):null},bs=()=>{var U,ue;return me?e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Target Value"}),e.jsx(Lt,{value:((U=y.config)==null?void 0:U.targetValue)!==void 0&&((ue=y.config)==null?void 0:ue.targetValue)!==null?String(y.config.targetValue):"",onSave:ye=>{!isNaN(Number(ye))&&ye!==null?T(Number(ye)):T(0)},placeholder:"Enter target value...",type:"text"})]}):null},vs=()=>W?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(t.Label,{className:"text-xs font-medium text-muted-foreground",children:"Aggregation"}),e.jsxs(t.Select,{value:s.aggregate,onValueChange:U=>{p(n,U)},children:[e.jsx(t.SelectTrigger,{className:"h-8 w-full text-xs",children:e.jsx(t.SelectValue,{placeholder:"Select function..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"COUNT",children:"Count"}),e.jsx(t.SelectItem,{value:"DISTINCT",children:"Count Distinct"}),t.getDataType(s.dataType)==="number"&&e.jsxs(e.Fragment,{children:[e.jsx(t.SelectItem,{value:"SUM",children:"Sum"}),e.jsx(t.SelectItem,{value:"AVG",children:"Average"}),e.jsx(t.SelectItem,{value:"MIN",children:"Min"}),e.jsx(t.SelectItem,{value:"MAX",children:"Max"}),e.jsx(t.SelectItem,{value:"MEDIAN",children:"Median"})]})]})]})]}),e.jsx(ds,{column:s}),i&&e.jsxs(e.Fragment,{children:[e.jsx(lr,{aliasTemplate:z,onAliasTemplateChange:$}),e.jsx(cr,{valueAliases:R,onValueAliasesChange:J})]})]}):null;return e.jsxs("div",{ref:x,style:re,...d,...l,className:`group mx-auto flex w-full max-w-[300px] flex-col gap-2 rounded border border-border bg-background p-2 transition-all hover:shadow-sm dark:border-gray-800 ${j?"z-50 scale-95 opacity-50":"border-slate-200"} ${a==="filters"?"cursor-default":"cursor-move"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.GripVertical,{className:"h-3 w-3"}),e.jsx(ms,{dataType:le}),e.jsx(ft,{className:"max-w-[180px] flex-1 text-sm",children:s.label||s.name}),a!=="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:U=>{U.stopPropagation(),m(!k)},children:e.jsx(t.ChevronDown,{className:`h-3 w-3 transition-transform ${k?"rotate-180":""}`})}),a==="sortBy"&&e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 group-hover:opacity-100",onClick:U=>{U.stopPropagation(),console.log("DraggableField - Current sortDirection:",r);const ue=r==="asc"?"desc":"asc";console.log("DraggableField - New direction to set:",ue),o(ue)},children:r==="asc"?e.jsx(t.ArrowUp,{className:"h-3 w-3"}):e.jsx(t.ArrowDown,{className:"h-3 w-3"})}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:U=>{U.stopPropagation(),se()},children:e.jsx(t.X,{className:"h-3 w-3"})})]}),k&&e.jsxs("div",{className:"space-y-3",children:[Z(),ee(),yt(),js(),ys(),bs(),vs()]})]})}function ur({concept:s}){const a=()=>{switch(s){case"groupBy":return e.jsxs("div",{className:"w-64 space-y-2",children:[e.jsx("h4",{className:"text-sm font-medium",children:"Rows = Group By"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Fields that define how your data is grouped into rows."}),e.jsxs("div",{className:"rounded-md border bg-white p-2 dark:border-muted dark:bg-muted",children:[e.jsxs("div",{className:"flex border-b pb-1 dark:border-border",children:[e.jsx("div",{className:"w-1/3 bg-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(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{delayDuration:300,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx(t.CircleHelp,{className:"size-4 text-muted-foreground hover:text-foreground"})}),e.jsx(t.TooltipContent,{side:"right",align:"start",className:"p-3",children:a()})]})})}function Ie({zone:s,fields:a,label:n,placeholder:r,shouldShow:o,hasPivotColumns:i=!1}){const{isOver:c,setNodeRef:d}=t.useDroppable({id:s}),{updateSortByColumn:l}=t.useEditorActions(),x=t.useEditorStore(S=>S.card),h=t.useEditorStore(S=>S.card.type),u=a.length>0,j=(S,p)=>{var f;!((f=x.config)!=null&&f.sortByColumns)||x.config.sortByColumns.findIndex(g=>g.id===S)===-1||l(x.id,S,{direction:p})};if(s==="sortBy"&&o===!1)return null;const y=s!=="sortBy"&&h!=="kpi";return e.jsxs("div",{className:"mb-4",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx(t.Label,{className:t.cn("block text-sm font-medium",{}),children:n}),y&&e.jsx(ur,{concept:s})]}),e.jsx("div",{ref:d,className:`min-h-[60px] rounded-lg border-2 border-dashed p-3 transition-all ${c?"border-blue-500 bg-blue-50 dark:bg-blue-950":"border-muted-foreground/20 bg-muted/50"}`,children:a.length===0?e.jsxs("div",{className:"flex min-h-[40px] items-center justify-center text-sm text-gray-400",children:[e.jsx(t.Plus,{className:"mr-2 h-4 w-4"}),r]}):e.jsx(t.SortableContext,{items:a.map(S=>S.id),strategy:t.verticalListSortingStrategy,children:e.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((S,p)=>{const f=S.direction;return e.jsx("div",{className:"flex w-full items-center gap-2",children:e.jsx("div",{className:"flex-1",children:e.jsx(dr,{field:S,zone:s,index:p,sortDirection:f,onSortDirectionChange:g=>j(S.id,g),hasPivotColumns:i,cardType:h})})},S.id)})})})})]})}function mr({groupByFields:s,pivotByFields:a,metricsFields:n,sortByFields:r}){const o=t.useEditorStore(u=>u.card),i=o==null?void 0:o.type,c=s.length>0||n.length>0,d=i!=="kpi",l=i!=="kpi"&&c,x=()=>i==="kpi"?{label:"Trend By",placeholder:"Drop fields to trend data"}:{label:"Rows",placeholder:"Drop fields to group data"},h=()=>i==="kpi"?{label:"Metric",placeholder:"Drop field for KPI"}:{label:"Metrics",placeholder:"Drop fields to measure"};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ie,{zone:"groupBy",fields:s,label:x().label,placeholder:x().placeholder}),d&&e.jsx(Ie,{zone:"pivotBy",fields:a,label:"Columns",placeholder:"Drop fields to pivot data"}),e.jsx(Ie,{zone:"metrics",fields:n,label:h().label,placeholder:h().placeholder,hasPivotColumns:a.length>0}),l&&e.jsx(Ie,{zone:"sortBy",fields:r,label:"Sort By",placeholder:"Drop fields from Rows or Metrics"})]})}function hr({selectedChart:s,onChartChange:a,groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i}){const c=t.useEditorStore(u=>u.showAIDialog),d=n.length>0||r.length>0||o.length>0,{setShowAIDialog:l}=t.useEditorActions(),x=t.useEditorStore(u=>u.card),{data:h}=t.useDashboardCardQuery(x);return e.jsxs("div",{className:"flex w-96 flex-col border-r bg-background",children:[e.jsxs("div",{className:"space-y-4 border-b px-6 py-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.ChartColumn,{className:"h-5 w-5 text-brand"}),e.jsx("h2",{className:"font-semibold",children:"Chart Configuration"})]}),e.jsx(or,{selectedChart:s,onChartChange:a})]}),e.jsxs("div",{className:t.cn("flex justify-end gap-2 px-6 pt-6"),children:[e.jsx("div",{className:t.cn("invisible",{visible:d||h}),children:e.jsx(t.EditorClearButton,{})}),!c&&e.jsxs(t.Button,{onClick:()=>l(!c),variant:"outline",className:"h-8",size:"sm",children:[e.jsx(fn,{className:"mr-2 size-4"}),"AI"]})]}),e.jsxs(t.ScrollArea,{className:"flex-1 basis-0 px-6",children:[e.jsx(mr,{groupByFields:n,pivotByFields:r,metricsFields:o,sortByFields:i}),e.jsx(t.ScrollBar,{orientation:"horizontal"})]})]})}function xr({initialFilters:s,availableFields:a}={}){const[n,r]=L.useState(s||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]});t.useEditorStore(E=>E.card.dataSource);const{columns:o,isLoading:i}=t.useColumns(),d=a||o||[],l={id:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},x=E=>{const b=C=>{if(C.id===E){const w=d[0]||l;return{...C,conditions:[...C.conditions,{id:`condition-${Date.now()}`,field:w,operator:"=",value:""}]}}return{...C,groups:C.groups.map(b)}};r(b(n))},h=E=>{const b=C=>{if(C.id===E){const w=d[0]||l;return{...C,groups:[...C.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:w,operator:"=",value:""}],groups:[]}]}}return{...C,groups:C.groups.map(b)}};r(b(n))},u=(E,b)=>{const C=w=>w.id===E?{...w,conditions:w.conditions.filter(T=>T.id!==b)}:{...w,groups:w.groups.map(C)};r(C(n))},j=(E,b)=>{const C=w=>w.id===E?{...w,groups:w.groups.filter(T=>T.id!==b)}:{...w,groups:w.groups.map(C)};r(C(n))},y=(E,b,C,w)=>{if(C==="field")throw new Error("Use a dedicated method to update the field property with a Field object");const T=k=>k.id===E?{...k,conditions:k.conditions.map(m=>m.id===b?{...m,[C]:w}:m)}:{...k,groups:k.groups.map(T)};r(T(n))},S=(E,b,C)=>{const w=T=>T.id===E?{...T,conditions:T.conditions.map(k=>k.id===b?{...k,...C}:k)}:{...T,groups:T.groups.map(w)};r(w(n))},p=(E,b)=>{const C=w=>w.id===E?{...w,logicalOperator:b}:{...w,groups:w.groups.map(C)};r(C(n))},D=(E,b)=>{const C=w=>w.id===E?{...w,negate:b}:{...w,groups:w.groups.map(C)};r(C(n))},f=(E,b,C)=>{const w=T=>T.id===E?{...T,conditions:t.arrayMove(T.conditions,b,C)}:{...T,groups:T.groups.map(w)};r(w(n))},g=(E,b,C)=>{const w=T=>T.id===E?{...T,groups:t.arrayMove(T.groups,b,C)}:{...T,groups:T.groups.map(w)};r(w(n))},v=E=>{if(!E||E.conditions.length===0&&E.groups.length===0)return"-- No filters defined";const b=w=>{let T="";typeof w.field=="object"?T=w.field.entityName?`${w.field.entityName}.${w.field.name}`:w.field.name:T=String(w.field);const k=w.operator;let m=w.value;if(w.field.dataType==="string"&&!["in","not in"].includes(w.operator))typeof m=="string"?m=`'${m}'`:Array.isArray(m)&&(m=`'${m.join(", ")}'`);else if(w.field.dataType==="date")(typeof m=="string"||m instanceof Date)&&(m=`DATE('${m}')`);else if(["in","not in"].includes(w.operator)){let B=[];Array.isArray(m)?B=m.map(A=>typeof A=="string"?`'${A}'`:String(A)):typeof m=="string"?B=m.split(",").map(A=>{const I=A.trim();return w.field.dataType==="string"?`'${I}'`:I}):typeof m=="number"&&(B=[String(m)]),m=`(${B.join(", ")})`}switch(k){case"contains":return typeof m=="string"?`${T} LIKE '%${m.replace(/'/g,"")}'`:`${T} LIKE '%${String(m)}'`;case"startsWith":return typeof m=="string"?`${T} LIKE '${m.replace(/'/g,"")}%'`:`${T} LIKE '${String(m)}%'`;case"endsWith":return typeof m=="string"?`${T} LIKE '%${m.replace(/'/g,"")}'`:`${T} LIKE '%${String(m)}'`;default:return`${T} ${k} ${m}`}},C=w=>{const T=w.conditions.map(b),k=w.groups.map(I=>C(I)),m=[...T,...k].filter(Boolean);if(m.length===0)return"";const B=m.join(` ${w.logicalOperator} `),A=m.length>1?`(${B})`:B;return w.negate?`NOT ${A}`:A};return C(E)},O=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:r,availableFields:d,isLoading:i,addCondition:x,addGroup:h,removeCondition:u,removeGroup:j,updateCondition:y,updateConditionFields:S,updateGroupOperator:p,updateGroupNegate:D,reorderConditions:f,reorderGroups:g,generateSQLPreview:v,hasAnyFilters:O}}function pr({children:s,className:a,delayDuration:n}){return e.jsx(t.TooltipProvider$1,{children:e.jsxs(t.Tooltip,{delayDuration:n,children:[e.jsx(t.TooltipTrigger,{asChild:!0,children:e.jsx("div",{className:t.cn("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",a),children:s})}),e.jsx(t.PortalTooltipContent,{children:s})]})})}const fr=s=>{switch(s){case"table":return e.jsx(t.Table,{className:"h-3 w-3"});case"view":return e.jsx(t.Eye,{className:"h-3 w-3"});case"dataset":return e.jsx(t.ChartColumn,{className:"h-3 w-3"});case"file":return e.jsx(Qs,{className:"h-3 w-3"});default:return e.jsx(t.Table,{className:"h-3 w-3"})}},gr=s=>{if(s.qualifiedEntityName){const a=s.qualifiedEntityName.split(".");return a.length>1?a[0]:"default"}return"default"};function jr({value:s,onValueChange:a,availableFields:n,placeholder:r="Select field",className:o="w-64"}){const[i,c]=L.useState(!1),d=L.useMemo(()=>{const l={};return n.forEach(x=>{const h=gr(x);l[h]||(l[h]={}),l[h][x.entityId]||(l[h][x.entityId]=[]),l[h][x.entityId].push(x)}),l},[n]);return e.jsxs(t.Popover,{modal:!0,open:i,onOpenChange:c,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:t.cn("justify-between",!s&&"text-muted-foreground",o),children:[s?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(pr,{children:[s.entityName,".",s.name]})}):r,e.jsx(t.ChevronsUpDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-80 p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search fields...",className:"h-9"}),e.jsx(t.CommandEmpty,{children:"No fields found."}),e.jsx(t.CommandList,{className:"max-h-80",children:Object.entries(d).map(([l,x])=>e.jsx(t.CommandGroup,{heading:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(t.Database,{className:"h-3 w-3"}),l]}),children:Object.entries(x).map(([h,u])=>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:[fr(u[0].entityType),e.jsx("span",{children:u[0].entityName})]}),u.map((j,y)=>e.jsxs(t.CommandItem,{value:j.id,onSelect:()=>{a(j),c(!1)},className:"overflow-x-auto",children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",(s==null?void 0:s.id)===j.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:j.name})}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-gray-500",children:j.description&&e.jsx("span",{children:j.description})})]})]},j.id+y))]},`${l}-${h}`))},l))})]})})]})}function jt(s){var S;const a=t.useEditorStore(p=>p.card),{authToken:n}=t.useSemaphorContext(),r=t.useEditorStore(p=>p.card.config),o=r==null?void 0:r.joinPlan,i={...s,alias:s.name,label:"value",role:"groupby"},c={...s,role:"metric",label:"count",alias:"count",aggregate:"COUNT"},d={...i,role:"sortby",direction:"asc"},l={joinPlan:o,groupByColumns:[i],metricColumns:[c],sortByColumns:[d]},x=((S=a.dataSource)==null?void 0:S.connectionId)||a.connectionId,{data:h,isPending:u,error:j}=t.useQuery({queryKey:["filterValues",s.entityId,s.name,s.qualifiedEntityName],queryFn:async()=>{try{return await t.postRequestRegular("https://semaphor.cloud/api/v1/query",(n==null?void 0:n.accessToken)||"",{connection_id:x,cardConfig:l,cardDataSource:a.dataSource})}catch(p){console.log(s),console.error("error",p)}},enabled:!!x,refetchOnMount:!0,refetchOnWindowFocus:!1});return{filterValues:((h==null?void 0:h.records)||[]).map(p=>({label:p[s.name]||"BLANK",value:p[s.name]||"BLANK",count:(p==null?void 0:p.count)||0})),isPending:u,error:j}}function yr({field:s,selected:a,onChange:n,placeholder:r="Select items...",className:o}){const[i,c]=he.useState(!1),{filterValues:d}=jt(s),l=h=>{n(a.filter(u=>u!==h))},x=h=>{a.includes(h)?n(a.filter(u=>u!==h)):n([...a,h])};return e.jsx("div",{className:t.cn("w-full",o),children:e.jsxs(t.Popover,{open:i,onOpenChange:c,modal:!0,children:[e.jsx(t.PopoverTrigger,{asChild:!0,children:e.jsxs(t.Button,{variant:"outline",role:"combobox","aria-expanded":i,className:"h-auto min-h-10 w-full justify-between p-2",children:[e.jsx("div",{className:"flex flex-1 flex-wrap gap-1",children:a.length>0?a.map(h=>{const u=d.find(j=>j.value===h);return e.jsxs(t.Badge,{variant:"secondary",className:"text-xs",children:[u==null?void 0:u.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:j=>{j.key==="Enter"&&l(h)},onMouseDown:j=>{j.preventDefault(),j.stopPropagation()},onClick:j=>{j.stopPropagation(),l(h)},children:e.jsx(t.X,{className:"h-3 w-3 text-muted-foreground hover:text-foreground"})})]},h)}):e.jsx("span",{className:"text-muted-foreground",children:r})}),e.jsx(t.ChevronDown,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(t.PopoverContent,{className:"z-50 w-fit overflow-auto p-0",align:"start",children:e.jsxs(t.Command,{children:[e.jsx(t.CommandInput,{placeholder:"Search..."}),e.jsxs(t.CommandList,{children:[e.jsx(t.CommandEmpty,{children:"No results found."}),e.jsx(t.CommandGroup,{children:d.map((h,u)=>e.jsxs(t.CommandItem,{onSelect:()=>x(h.value),children:[e.jsx(t.Check,{className:t.cn("mr-2 h-4 w-4",a.includes(h.value)?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex grow items-center justify-between gap-4",children:[e.jsx("span",{children:h.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:h.count})]})]},h.value+u))})]})]})})]})})}const ps=s=>{if(!s)return 0;let a=s.conditions.length;return s.groups.forEach(n=>{a+=ps(n)}),a};function br({field:s,value:a,onChange:n,placeholder:r="Select value...",className:o}){const{filterValues:i,isPending:c,error:d}=jt(s);return c?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):d?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsxs(t.Select,{value:a,onValueChange:n,children:[e.jsx(t.SelectTrigger,{className:o||"flex-1",children:e.jsx(t.SelectValue,{placeholder:r,children:a})}),e.jsx(t.SelectContent,{children:i.map((l,x)=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:l.value,children:l.label},l.value+x))})]})}const vr=["=","!=",">",">=","<","<=","contains","startsWith","endsWith","in","not in"],Nr=["=","!=","contains","startsWith","endsWith","in","not in"],Cr=["=","!=",">",">=","<","<=","in","not in"],Sr=["=","!="],wr=["=","!=",">",">=","<","<=","in","not in"];function kr(s){switch(s){case"string":return Nr;case"number":return Cr;case"boolean":return Sr;case"date":return wr;default:return vr}}function fs({condition:s,index:a,groupId:n,groupLogicalOperator:r,onUpdateCondition:o,onRemoveCondition:i,onUpdateGroupOperator:c,availableFields:d,updateConditionFields:l}){const{attributes:x,listeners:h,setNodeRef:u,transform:j,transition:y,isDragging:S}=t.useSortable({id:s.id}),{isPending:p,error:D}=jt(s.field),f={transform:t.CSS.Transform.toString(j),transition:y};return e.jsxs("div",{ref:u,style:f,className:`mb-2 flex items-center gap-2 rounded p-2 hover:bg-muted/50 ${S?"z-50 opacity-50":""}`,children:[e.jsx("div",{...x,...h,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 flex-shrink-0 text-gray-400"})}),a>0&&e.jsxs(t.Select,{value:r,onValueChange:g=>c(n,g),children:[e.jsx(t.SelectTrigger,{className:"w-24",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"AND",children:"AND"}),e.jsx(t.SelectItem,{value:"OR",children:"OR"})]})]}),a===0&&e.jsx("div",{className:"w-24"}),e.jsx(jr,{value:s.field,onValueChange:g=>{l(n,s.id,{field:g,value:""})},availableFields:d,placeholder:"Select field",className:"w-64"}),e.jsxs(t.Select,{value:s.operator,onValueChange:g=>{g==="in"||g==="not in"?l(n,s.id,{operator:g,value:[]}):l(n,s.id,{operator:g,value:""})},children:[e.jsx(t.SelectTrigger,{className:"w-28",children:e.jsx(t.SelectValue,{})}),e.jsx(t.SelectContent,{children:kr(t.getDataType(s.field.dataType)).map(g=>e.jsx(t.SelectItem,{className:"hover:bg-muted",value:g,children:g},g))})]}),t.getDataType(s.field.dataType)==="string"?s.operator==="in"||s.operator==="not in"?p?e.jsxs("div",{className:"flex flex-1 items-center justify-center p-2 text-xs text-gray-500",children:[e.jsx(t.LoaderCircle,{className:"mr-2 size-3.5 animate-spin"})," Loading values..."]}):D?e.jsx("div",{className:"flex-1 p-2 text-xs text-red-500",children:"Error loading values"}):e.jsx(yr,{field:s.field,selected:Array.isArray(s.value)&&s.value.every(g=>typeof g=="string")?s.value:[],onChange:g=>l(n,s.id,{value:g}),placeholder:`Select values for ${s.operator}...`,className:"flex-1"}):["contains","startsWith","endsWith"].includes(s.operator)?e.jsx(t.Input$1,{value:typeof s.value=="string"?s.value:"",onChange:g=>l(n,s.id,{value:g.target.value}),className:"flex-1",placeholder:s.operator.charAt(0).toUpperCase()+s.operator.slice(1)+"..."}):e.jsx(br,{field:s.field,value:typeof s.value=="string"?s.value:"",onChange:g=>l(n,s.id,{value:g}),placeholder:"Select value...",className:"flex-1"}):t.getDataType(s.field.dataType)==="boolean"?e.jsxs(t.Select,{value:typeof s.value=="boolean"?String(s.value):"",onValueChange:g=>l(n,s.id,{value:g==="true"}),children:[e.jsx(t.SelectTrigger,{className:"flex-1",children:e.jsx(t.SelectValue,{placeholder:"Select value..."})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{value:"true",children:"True"}),e.jsx(t.SelectItem,{value:"false",children:"False"})]})]}):e.jsx(t.Input$1,{value:typeof s.value=="string"||typeof s.value=="number"?s.value:"",onChange:g=>o(n,s.id,"value",g.target.value),className:"flex-1",placeholder:s.operator==="in"||s.operator==="not in"?"value1, value2, value3":"Value"}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 flex-shrink-0 p-0",onClick:()=>i(n,s.id),children:e.jsx(t.X,{className:"h-3 w-3"})})]})}function Er({group:s,depth:a,parentGroupId:n,onUpdateGroupOperator:r,onUpdateGroupNegate:o,onRemoveGroup:i,onUpdateCondition:c,onUpdateField:d,onRemoveCondition:l,onReorderConditions:x,onReorderGroups:h,onAddCondition:u,onAddGroup:j,availableFields:y,renderFilterGroup:S,updateConditionFields:p}){const{attributes:D,listeners:f,setNodeRef:g,transform:v,transition:O,isDragging:E}=t.useSortable({id:s.id}),b={transform:t.CSS.Transform.toString(v),transition:O},C=T=>{const{active:k,over:m}=T;if(m&&k.id!==m.id){const B=s.conditions.findIndex(I=>I.id===k.id),A=s.conditions.findIndex(I=>I.id===m.id);B!==-1&&A!==-1&&x(s.id,B,A)}},w=T=>{const{active:k,over:m}=T;if(m&&k.id!==m.id&&n){const B=s.groups.findIndex(I=>I.id===k.id),A=s.groups.findIndex(I=>I.id===m.id);B!==-1&&A!==-1&&h(n,B,A)}};return e.jsxs("div",{ref:g,style:b,className:`rounded-lg ${a>0?"mt-2 border border-border":""} ${E?"z-50 opacity-50":""}`,children:[a>0&&e.jsxs("div",{className:"flex items-center justify-between rounded-t-lg bg-muted p-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{...D,...f,className:"cursor-grab active:cursor-grabbing",children:e.jsx(t.GripVertical,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx(t.Button,{variant:s.negate?"default":"outline",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>o(s.id,!s.negate),children:"NOT"}),e.jsxs(t.Select,{value:s.logicalOperator,onValueChange:T=>r(s.id,T),children:[e.jsx(t.SelectTrigger,{className:"h-7 w-20",children:e.jsx(t.SelectValue,{})}),e.jsxs(t.SelectContent,{children:[e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"AND",children:"AND"}),e.jsx(t.SelectItem,{className:"hover:bg-muted",value:"OR",children:"OR"})]})]}),e.jsx("span",{className:"text-sm font-medium",children:"Group"})]}),e.jsx(t.Button,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>n&&i(n,s.id),children:e.jsx(t.Trash2,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:`p-3 ${a>0?"":"px-0"}`,children:[e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:C,children:e.jsx(t.SortableContext,{items:s.conditions.map(T=>T.id),strategy:t.verticalListSortingStrategy,children:s.conditions.map((T,k)=>e.jsx(fs,{condition:T,index:k,groupId:s.id,groupLogicalOperator:s.logicalOperator,onUpdateCondition:c,onUpdateField:d,onRemoveCondition:l,onUpdateGroupOperator:r,availableFields:y,updateConditionFields:p},T.id))})}),e.jsx(t.DndContext,{sensors:t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),collisionDetection:t.closestCenter,onDragEnd:w,children:e.jsx(t.SortableContext,{items:s.groups.map(T=>T.id),strategy:t.verticalListSortingStrategy,children:s.groups.map(T=>S(T,a+1,s.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>u(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>j(s.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})]})}function Dr({filters:s,availableFields:a,onSave:n,onClearAll:r,onCancel:o}){const{currentFilters:i,availableFields:c,isLoading:d,addCondition:l,addGroup:x,removeCondition:h,removeGroup:u,updateCondition:j,updateConditionFields:y,updateGroupOperator:S,updateGroupNegate:p,reorderConditions:D,reorderGroups:f,generateSQLPreview:g,hasAnyFilters:v,setCurrentFilters:O}=xr({initialFilters:s,availableFields:a}),E=t.useSensors(t.useSensor(t.PointerSensor),t.useSensor(t.KeyboardSensor,{coordinateGetter:t.sortableKeyboardCoordinates})),[b,C]=L.useState(!1),w=(m,B,A)=>{const I=N=>N.id===m?{...N,conditions:N.conditions.map(M=>M.id===B?{...M,field:A,dataType:A.dataType}:M)}:{...N,groups:N.groups.map(I)};O(I(i))},T=(m,B=0,A)=>B===0?e.jsx("div",{className:"rounded-lg",children:e.jsxs("div",{className:"p-3 px-0",children:[e.jsx(t.DndContext,{sensors:E,collisionDetection:t.closestCenter,onDragEnd:I=>{const{active:N,over:M}=I;if(M&&N.id!==M.id){const F=m.conditions.findIndex(V=>V.id===N.id),P=m.conditions.findIndex(V=>V.id===M.id);F!==-1&&P!==-1&&D(m.id,F,P)}},children:e.jsx(t.SortableContext,{items:m.conditions.map(I=>I.id),strategy:t.verticalListSortingStrategy,children:m.conditions.map((I,N)=>e.jsx(fs,{condition:I,index:N,groupId:m.id,groupLogicalOperator:m.logicalOperator,onUpdateCondition:j,onUpdateField:w,onRemoveCondition:h,onUpdateGroupOperator:S,availableFields:c,updateConditionFields:y},I.id))})}),e.jsx(t.DndContext,{sensors:E,collisionDetection:t.closestCenter,onDragEnd:I=>{const{active:N,over:M}=I;if(M&&N.id!==M.id){const F=m.groups.findIndex(V=>V.id===N.id),P=m.groups.findIndex(V=>V.id===M.id);F!==-1&&P!==-1&&f(m.id,F,P)}},children:e.jsx(t.SortableContext,{items:m.groups.map(I=>I.id),strategy:t.verticalListSortingStrategy,children:m.groups.map(I=>T(I,B+1,m.id))})}),e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsxs(t.Button,{size:"sm",className:"h-7 text-xs",variant:"outline",onClick:()=>l(m.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Condition"]}),b&&e.jsxs(t.Button,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>x(m.id),children:[e.jsx(t.Plus,{className:"mr-1 h-3 w-3"}),"Add Group"]})]})]})},m.id):e.jsx(Er,{group:m,depth:B,parentGroupId:A,onUpdateGroupOperator:S,onUpdateGroupNegate:p,onRemoveGroup:u,onUpdateCondition:j,onUpdateField:w,onRemoveCondition:h,onReorderConditions:D,onReorderGroups:f,onAddCondition:l,onAddGroup:x,availableFields:c,renderFilterGroup:T,updateConditionFields:y},m.id),k=ps(s);return e.jsxs("div",{className:"space-y-4",children:[e.jsx(t.Card,{children:e.jsx(t.CardContent,{className:"p-4",children:e.jsxs("div",{className:"space-y-4",children:[d?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..."})]}):T(i),e.jsx("div",{className:"mt-4 border-t border-border pt-4",children:e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(t.Checkbox,{id:"advanced-mode",checked:b,onCheckedChange:m=>C(!!m)}),e.jsx("label",{htmlFor:"advanced-mode",className:"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",children:"Advanced mode (enable grouping)"})]})}),v&&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:g(i)})})]})]})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(t.Button,{size:"sm",variant:"outline",onClick:o,children:"Cancel"}),k>0&&e.jsx(t.Button,{variant:"outline",size:"sm",onClick:r,children:"Clear All"}),e.jsx(t.Button,{size:"sm",onClick:()=>n(v?i:null),children:"Apply Filters"})]})]})}function Tr({cardId:s,filters:a,onFiltersChange:n,onClearFilters:r,availableFields:o,isOpen:i,onOpenChange:c}){const d=x=>{n(s,x),c(!1)},l=()=>{r(s),c(!1)};return e.jsxs(t.Dialog,{modal:!1,open:i,onOpenChange:c,children:[i&&e.jsx("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),e.jsxs(t.DialogContent,{className:"max-h-[80vh] max-w-4xl overflow-y-auto",onInteractOutside:x=>{x.preventDefault()},children:[e.jsxs(t.DialogHeader,{children:[e.jsx(t.DialogTitle,{children:"Card Filters"}),e.jsx(t.DialogDescription,{children:"Add filters to the card to limit the data that is displayed."})]}),e.jsx(Dr,{filters:a,availableFields:o,onSave:d,onCancel:()=>c(!1),onClearAll:l})]})]})}function gs(s,a){return`${s}-${a.qualifiedEntityName}-${a.name}-${Date.now()}`}function Ir({activeCardId:s,sourceFields:a,getFieldsForContainer:n,setFieldsForContainer:r}){var D;const[o,i]=L.useState(null),c=t.useEditorStore(f=>f.card),d=(D=c==null?void 0:c.config)==null?void 0:D.joinPlan,l=[...a,...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")],x=L.useCallback(f=>f.startsWith("card-")?null:f.startsWith("source-")||a.find(g=>g.id===f)?"source":n("groupBy").find(g=>g.id===f)?"groupBy":n("metrics").find(g=>g.id===f)?"metrics":n("pivotBy").find(g=>g.id===f)?"pivotBy":n("sortBy").find(g=>g.id===f)?"sortBy":null,[a,n]),h=L.useCallback((f,g)=>{var v;return!d||!((v=d.baseEntity)!=null&&v.name)||!d.joins?!1:f===g||f===d.baseEntity.name||g===d.baseEntity.name?!0:d.joins.some(O=>{const E=t.getQualifiedEntityName(O.source),b=t.getQualifiedEntityName(O.target);return console.log(E,b),console.log(E===f&&b===g||E===g&&b===f),E===f&&b===g||E===g&&b===f})},[d]),u=L.useCallback(()=>{t.ue.error("Join Configuration Required",{richColors:!0,description:"To combine fields from two different tables, you need to define a join between them first.",position:"top-center",duration:4e3})},[]),j=(f,g)=>{const v=gs(g,f),O=t.getDataType(f.dataType),E=O==="date",b={id:v,name:f.name,dataType:f.dataType,label:t.toLabel(f.name),qualifiedEntityName:f.qualifiedEntityName,entityId:f.entityId,entityName:f.entityName,entityType:f.entityType};if(g==="metrics"){const C=O==="number"?"SUM":"COUNT",w=hs(f.label,C);return{...b,role:"metric",label:w,aggregate:C}}return g==="groupBy"?{...b,role:"groupby",...E&&{granularity:"month"}}:g==="pivotBy"?{...b,role:"pivotby"}:g==="sortBy"?{...b,role:"sortby",label:f.label,direction:"asc"}:null},y=L.useCallback(f=>{i(f.active.id)},[]),S=L.useCallback(f=>{const{active:g,over:v}=f;if(!v||!s){i(null);return}const O=g.id,E=v.id,b=x(O),C=x(E)||E;if(b==="source"&&C==="sortBy"){i(null);return}if(b==="source"&&C!=="source"&&C!=="sortBy"){const w=[...a].find(A=>A.id===O);if(!w){i(null);return}const T=[...n("groupBy"),...n("pivotBy"),...n("metrics"),...n("sortBy")];if(T.length>0){const A=T[0].qualifiedEntityName;if(!A){i(null);return}if(A!==w.qualifiedEntityName&&w.qualifiedEntityName)if(d){if(!h(A,w.qualifiedEntityName)){u(),i(null);return}}else{u(),i(null);return}}const k=n(C);if(k.some(A=>A.name===w.name&&A.qualifiedEntityName===w.qualifiedEntityName)){i(null);return}const B=j(w,C);i(null),r(C,[...k,B]);return}if(b&&C&&b!=="source"&&C!=="source"&&b!==C){const w=n(b),T=n(C),k=w.find(A=>A.id===O);if(!k){i(null);return}const m=j(k,C);if(i(null),C==="sortBy"){if(b==="pivotBy"){i(null);return}T.some(I=>I.name===k.name&&I.qualifiedEntityName===k.qualifiedEntityName)||r(C,[...T,m]);return}const B=w.filter(A=>A.id!==O);r(b,B),r(C,[...T,m]);return}if(b&&C&&b===C&&b!=="source"){const w=n(b),T=w.findIndex(m=>m.id===O),k=w.findIndex(m=>m.id===E);if(T!==k){const m=t.arrayMove(w,T,k);r(b,m)}}i(null)},[s,a,n,r,x,d,u,h]),p=o?l.find(f=>f.id===o):null;return{activeId:o,activeField:p,handleDragStart:y,handleDragEnd:S}}function Ar({activeView:s,onViewChange:a}){const n=t.useEditorStore(o=>o.card),{errorMessage:r}=t.useDashboardCardQuery(n);return e.jsx(t.Tabs,{value:s,onValueChange:o=>a(o),children:e.jsxs(t.TabsList,{className:"h-9 w-fit gap-2 bg-background p-0",children:[e.jsx(t.TabsTrigger,{value:"chart",className:"rounded-md transition data-[state=active]:bg-muted",children:"Chart"}),e.jsx(t.TabsTrigger,{value:"table",className:"rounded-md transition data-[state=active]:bg-muted",children:"Results"}),n.type!=="kpi"&&e.jsx(t.TabsTrigger,{value:"sql",className:t.cn("rounded-md transition data-[state=active]:bg-muted",r&&"text-destructive data-[state=active]:bg-destructive/10 data-[state=active]:text-destructive"),children:r?"Error":"Query"})]})})}const Mr=[{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 Lr(){var l,x;const s=t.useEditorStore(h=>h.card),{updateRowLimit:a}=t.useEditorActions(),[n,r]=L.useState(!1),[o,i]=L.useState(""),c=h=>{if(h==="custom"){r(!0);return}r(!1),a(s.id,parseInt(h))},d=h=>{const u=h.target.value;i(u),u&&!isNaN(parseInt(u))&&a(s.id,parseInt(u))};return e.jsx("div",{className:"flex items-center gap-2",children:n?e.jsx(t.Input,{type:"number",value:o,onChange:d,className:"h-7 w-24",placeholder:"Enter limit",min:1}):e.jsxs(t.Select,{value:((x=(l=s.config)==null?void 0:l.rowLimit)==null?void 0:x.toString())||"100",onValueChange:c,children:[e.jsx(t.SelectTrigger,{className:"h-8 w-24 border-none px-1 [&>svg]:hidden",children:e.jsx(t.SelectValue,{placeholder:"Select limit"})}),e.jsx(t.SelectContent,{children:Mr.map(h=>e.jsx(t.SelectItem,{value:h.value,children:h.label},h.value))})]})})}function Or({activeView:s,onViewChange:a,showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:c,onFiltersClick:d,filterCount:l,activeCard:x,columns:h,columnsLoading:u,columnsError:j}){var T;const y=t.useEditorStore(k=>k.card),S=t.useDashboardStore(k=>k.filterValues),{updateCardConfig:p}=t.useEditorActions(),D=t.useEditorStore(k=>k.showAIDialog),{data:f,errorMessage:g,isPending:v,isLoading:O,isFetching:E}=t.useDashboardCardQuery(x);function b(){return e.jsx("div",{className:"border-b border-border bg-background p-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Active Card Config"}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:JSON.stringify(y.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(S||{},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(x.dataSource||{},null,2)})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"mb-2 text-sm font-medium",children:["Columns (",h.length,")"]}),e.jsx("pre",{className:"max-h-40 overflow-auto rounded border bg-background p-3 text-xs",children:u?"Loading...":j?"Error loading columns":JSON.stringify(h.slice(0,5),null,2)})]})]})})}const C=k=>{if(!y.config)return;if(!k.length){p(y.id,{...y.config,sortByColumns:[]});return}const m=y.config,B=k.map(({id:A,desc:I})=>{var P,V;const N=(P=m.metricColumns)==null?void 0:P.find(z=>z.label===A),M=(V=m.groupByColumns)==null?void 0:V.find(z=>z.label===A),F=N||M;return F?{id:gs("sortBy",F),name:F.name,dataType:F.dataType,label:F.label,qualifiedEntityName:F.qualifiedEntityName,entityId:F.entityId,entityName:F.entityName,entityType:F.entityType,role:"sortby",direction:I?"desc":"asc"}:null}).filter(A=>A!==null);p(y.id,{...m,sortByColumns:B})},w=L.useMemo(()=>{var k,m;return(m=(k=y.config)==null?void 0:k.sortByColumns)==null?void 0:m.map(B=>({id:B.label,desc:B.direction==="desc"}))},[(T=y.config)==null?void 0:T.sortByColumns]);return e.jsxs("div",{className:"flex w-0 grow flex-col",children:[e.jsx(t.ExplorerHeader,{showDebug:n,onDebugToggle:r,onAccept:o,onClear:i,onAdvancedToggle:c,onFiltersClick:d,filterCount:l}),n&&b(),e.jsx(t.Separator,{}),e.jsxs("div",{className:"group/visualization flex max-w-full grow flex-col pt-4",children:[e.jsxs("div",{className:"z-50 flex items-center gap-2 px-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s==="chart"&&D&&e.jsx(ss,{variant:"outline"}),e.jsx(Ar,{activeView:s,onViewChange:a}),d&&e.jsxs(t.IconButton,{tooltip:"Card Filters",className:"h-8 gap-1",onClick:d,children:[e.jsx(t.Filter,{className:"h-3.5 w-3.5"}),l>0&&e.jsx("span",{className:"ml-1 rounded-full bg-blue-100 px-1.5 py-0.5 text-xs text-blue-800",children:l})]}),e.jsx("div",{className:"ml-2",children:e.jsx(Lr,{})})]}),e.jsx("div",{className:t.cn("flex grow items-center justify-end"),children:s==="chart"&&e.jsx(ns,{})})]}),e.jsxs("div",{className:"flex grow flex-col",children:[s==="chart"&&e.jsx("div",{className:"flex grow flex-col pb-6",children:O||E?e.jsx("div",{className:"m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(t.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx(as,{})}),s==="table"&&(f==null?void 0:f.records)&&e.jsxs("div",{className:"relative flex h-full min-h-0 max-w-full flex-1 grow basis-0 p-6",children:[(O||E)&&e.jsx("div",{className:"absolute flex h-full w-full items-center justify-between",children:e.jsx("div",{className:"z-10 m-auto flex h-10 w-10 items-center justify-center rounded-md bg-muted",children:e.jsx(t.LoaderCircle,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}),e.jsx(t.TableVisual,{card:x,data:f==null?void 0:f.records,onSortChange:C,sortState:w})]}),s==="sql"&&e.jsx("div",{className:"p-6",children:e.jsxs("div",{className:"rounded-md border bg-background p-4",children:[(f==null?void 0:f.sql)&&e.jsx("h3",{className:"mb-3 text-sm font-medium",children:"Generated SQL Query"}),e.jsx(Kt,{sql:f==null?void 0:f.sql,error:g})]})})]})]})]})}function Br({activeField:s}){const[a,n]=L.useState(!0);return L.useEffect(()=>{s&&n(!0)},[s]),s?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 ${a?"scale-100 opacity-100":"scale-95 opacity-0"}`,children:[e.jsx(t.GripVertical,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx(ms,{dataType:s.dataType}),e.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-sm dark:text-muted-foreground",children:s.label||s.name})]}):null}const Fr=()=>{const s=console.error;console.error=(...r)=>{r.length>0&&typeof r[0]=="string"&&r[0].includes("ResizeObserver loop completed with undelivered notifications")||s.apply(console,r)};const a=r=>{if(r.message&&(r.message.includes("ResizeObserver loop completed with undelivered notifications")||r.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),r.stopPropagation(),!1},n=r=>{var o;if((o=r.reason)!=null&&o.message&&(r.reason.message.includes("ResizeObserver loop completed with undelivered notifications")||r.reason.message.includes("ResizeObserver loop limit exceeded")))return r.preventDefault(),!1};return window.addEventListener("error",a,!0),window.addEventListener("unhandledrejection",n,!0),()=>{console.error=s,window.removeEventListener("error",a,!0),window.removeEventListener("unhandledrejection",n,!0)}};function zr(){var z,Y;const[s,a]=L.useState("chart"),[n,r]=L.useState(!1),[o,i]=L.useState(!1),c=t.useEditorStore(R=>R.showAIDialog),{setCardType:d}=t.useEditorActions(),l=t.useEditorStore(R=>R.card.type);L.useEffect(()=>Fr(),[]);const x=()=>{console.log("Accept clicked - would save/apply current configuration")},h=()=>{console.log("Clear clicked - would reset all configurations")},u=()=>{console.log("Advanced mode toggled")},j=()=>{i(!0)},y=R=>{d(R)},S=t.useEditorStore(R=>R.frame),p=t.useEditorStore(R=>R.card);t.useEditorStore(R=>R.activeTabCardId),t.useEditorStore(R=>R.actions.getAvailableFields);const{addCard:D,removeCard:f,updateCard:g,setActiveCard:v,updateFilters:O}=t.useEditorActions(),{columns:E=[],isLoading:b,error:C}=t.useColumns(),w=t.useSensors(t.useSensor(t.PointerSensor,{activationConstraint:{distance:8}})),T=p,{getFieldsForContainer:k,setFieldsForContainer:m}=xs(T),{activeField:B,handleDragStart:A,handleDragEnd:I}=Ir({activeCardId:S.activeCardId,sourceFields:E,getFieldsForContainer:k,setFieldsForContainer:m}),N=(R,q)=>{q&&O(R,q)},M=R=>{var q;g(R,{config:{...(q=S.cards.find(H=>H.id===R))==null?void 0:q.config,filters:void 0}})},F=E,P=R=>{if(!R)return 0;let q=R.conditions.length;return R.groups.forEach(H=>{q+=P(H)}),q},V=P(((z=T==null?void 0:T.config)==null?void 0:z.filters)||null);return e.jsxs(t.DndContext,{sensors:w,collisionDetection:t.closestCenter,onDragStart:A,onDragEnd:I,children:[e.jsxs("div",{className:"flex h-full grow",children:[e.jsx(nr,{}),!c&&e.jsx(hr,{selectedChart:l,onChartChange:y,groupByFields:k("groupBy"),pivotByFields:k("pivotBy"),metricsFields:k("metrics"),sortByFields:k("sortBy")}),e.jsx(Or,{selectedChart:l,activeView:s,onViewChange:a,showDebug:n,onDebugToggle:()=>r(!n),onAccept:x,onClear:h,onAdvancedToggle:u,onFiltersClick:j,filterCount:V,activeCard:T,dataSourceState:p.dataSource||t.EMPTY_DATA_SOURCE,columns:E,columnsLoading:b,columnsError:C,getFieldsForContainer:k,cards:S.cards,activeCardId:S.activeCardId,addCard:D,setActiveCard:v})]}),T&&e.jsx(Tr,{cardId:T.id,filters:((Y=T.config)==null?void 0:Y.filters)||null,onFiltersChange:N,onClearFilters:M,availableFields:F,isOpen:o,onOpenChange:i}),e.jsx(t.DragOverlay,{dropAnimation:null,children:e.jsx(Br,{activeField:B||null})})]})}function Pr({authToken:s,onSave:a,onClose:n}){const r=L.useRef(null),o=t.useEditorStore(g=>g.showAIDialog),i=t.useEditorStore(g=>g.isDevMode),{setAuthToken:c}=t.useDashboardActions(),{setShowAIDialog:d,setOnSave:l,setOnClose:x}=t.useEditorActions(),{handleDragOver:h,handleDragEnd:u,handleDragStart:j,handleDragCancel:y,sensors:S}=An();L.useEffect(()=>{a&&l(a),n&&x(n)},[a,l,n,x]),L.useEffect(()=>{s&&s.accessToken&&c(s)},[s,c]),L.useEffect(()=>{var g,v;o?((g=r.current)==null||g.resize(40),d(!0)):(d(!1),(v=r.current)==null||v.resize(0))},[o,d]);function p(g){g<1?d(!1):o||d(!0)}function D(){return e.jsxs(e.Fragment,{children:[e.jsx(Ut,{type:"main"}),e.jsxs(t.ResizablePanelGroup,{"data-content":"editor-main",className:"grow",direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] rounded-none",children:e.jsx(Ja,{})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(It,{})})]})]})}function f(){return e.jsxs(t.ResizablePanelGroup,{"data-content":"explorer",className:"flex grow",direction:"horizontal",children:[e.jsx(t.ResizablePanel,{className:"min-w-[510px] grow rounded-none",children:e.jsx(zr,{})}),e.jsx(t.ResizableHandle,{}),e.jsx(t.ResizablePanel,{"data-role":"editor-assistant-panel",ref:r,onResize:p,defaultSize:0,children:e.jsx(It,{})})]})}return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:i?e.jsx(t.DndContext,{sensors:S,onDragStart:j,onDragEnd:u,onDragOver:h,onDragCancel:y,children:e.jsx("section",{className:"isolate flex h-full grow","data-content":"editor-panel",children:D()})}):f()})}function Rr(){t.useDashboardStore(c=>c.selectedCardId);const s=t.useDashboardStore(c=>c.selectedSheetId),{setIsVisualEditing:a}=t.useDashboardStore(c=>c.actions),n=t.useDashboardStore(c=>c.isVisualEditing),r=t.useDashboardStore(c=>c.actions.updateFrame);function o(c){s&&(r(s,c),a(!1))}function i(){a(!1)}return e.jsx("div",{role:"editor-container",className:t.cn("flex grow",{"max-h-0 overflow-hidden":!n}),children:e.jsx(Pr,{onSave:o,onClose:i})})}function Vr(){const s=t.useEditorStore(i=>i.selectedDatabaseName),a=t.useEditorStore(i=>i.selectedTableName),n=t.useDashboardStore(i=>i.dashboard.filters)||[],{columns:r}=t.useEditorAside(),{assignFilter:o}=ls();return e.jsx(t.ScrollArea,{className:"flex-1 basis-0 flex-col px-3",children:r==null?void 0:r.map(i=>{const c=n==null?void 0:n.find(d=>d.column===t.fmt(i.column_name)&&d.table===a&&d.database===s);return e.jsx("div",{onClick:()=>o(i),className:t.cn("group flex cursor-pointer items-center justify-between border border-dashed border-background px-3 py-[6px] text-sm transition-colors hover:bg-muted/50",{"bg-muted":c}),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(lt,{column:i}),e.jsx("span",{children:i.column_name})]})},i.column_name)})})}function qr(){t.useDashboardStore(a=>a.showFilters);const s=t.useDashboardStore(a=>a.actions.setShowFilters);return e.jsxs("section",{className:"relative flex min-w-[320px] grow flex-col border-l px-1",children:[e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-2 px-3",children:[e.jsx(t.Label,{className:"px-2 text-lg",children:"Filters"}),e.jsx(t.Button,{onClick:()=>s(!1),className:"h-7 w-7 p-0",variant:"ghost",children:e.jsx(t.Cross2Icon,{})})]}),e.jsx("div",{className:"flex grow",children:e.jsx(Ut,{type:"filter",ColumnsComponent:()=>e.jsx(Vr,{})})})]})}function _r(){const s=t.useDashboardStore(r=>r.dashboard.filters),a=t.useDashboardStore(r=>r.theme),n=s==null?void 0:s.filter(r=>r.hide);return n!=null&&n.length?e.jsx("div",{className:t.cn("mb-1 flex items-center gap-2 border-y px-0.5 pb-0.5",{"bg-[repeating-linear-gradient(45deg,_#ffffff_0_3px,_#f3f3f3_3px_6px)]":a==="light","bg-[repeating-linear-gradient(45deg,_#18171d_0_3px,_#272729_3px_6px)]":a==="dark"}),children:n==null?void 0:n.map(r=>e.jsxs("div",{className:"flex min-w-[250px] max-w-fit flex-col gap-1 p-2",children:[e.jsx(t.FilterHeader,{filter:r}),e.jsx(t.FilterComponent,{filter:r})]},r.id))}):null}function Gr(){const s=t.useDashboardStore(r=>r.showFilters),a=t.useDashboardStore(r=>r.isVisualEditing),n=t.useDashboardStore(r=>r.isDashboardEditing);return e.jsxs("div",{role:"dashboard-plus-main",className:t.cn("",{"max-h-0 overflow-hidden":a,"flex grow overflow-auto":!a}),children:[e.jsxs("section",{className:"flex grow flex-col",children:[n&&e.jsx(_r,{}),e.jsx(t.DashboardTabs,{})]}),s&&e.jsx("div",{role:"filter-aside-container",className:"flex",children:e.jsx(qr,{})})]})}function $r(){const s=t.useDashboardStore(o=>o.dashboard),a=t.useDashboardStore(o=>o.actions.setDashboard),n=t.useDashboardStore(o=>o.showDashboardJSON),r=t.useDashboardStore(o=>o.actions.setShowDashboardJSON);return e.jsxs("div",{className:t.cn("relative p-2",{hidden:!n}),children:[e.jsxs(t.Button,{variant:"secondary",size:"sm",className:"absolute right-2 top-2 z-10 h-8",onClick:()=>r(!1),children:[e.jsx(t.X,{className:"mr-2 h-4 w-4"}),"Close"]}),e.jsx(t.de,{onChange:o=>{if(o)try{JSON.parse(o),a(JSON.parse(o))}catch{}},defaultLanguage:"json",className:"h-[550px] overflow-y-auto",value:JSON.stringify(s,null,2),options:{minimap:{enabled:!1},glyphMargin:!1,wordWrap:"on",scrollbar:{verticalScrollbarSize:0,horizontalScrollbarSize:0},fontSize:12,renderLineHighlight:"none"}})]})}function Jr({showControls:s=!1,showFooter:a=!0,...n}){return e.jsx(t.ErrorBoundary,{FallbackComponent:t.Fallback,children:e.jsxs(t.SemaphorContextProvider,{dashboardProps:n,children:[e.jsx(t.$e,{}),e.jsxs(t.UXProvider,{children:[e.jsx($r,{}),e.jsxs(t.DashboardPanel,{...n,children:[s&&e.jsx(kn,{}),e.jsx(Rr,{}),e.jsx(Gr,{})]})]})]})})}exports.DashboardPlus=Jr;exports.ScheduleDashboard=Jt;exports.SelectComponent=be;exports.cleanCard=_t;exports.downloadPdf=$t;exports.getDashbaordStateWithoutData=it;
|