react-semaphor 0.1.604 → 0.1.606
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/analytics-protocol/index.js +1 -1
- package/dist/appearance/index.js +1 -1
- package/dist/appearance-runtime/index.js +1 -1
- package/dist/assistant-context/index.js +1 -1
- package/dist/assistant-protocol/index.js +1 -1
- package/dist/brand-studio/index.js +3 -8
- package/dist/briefings/index.js +1 -1
- package/dist/chunks/{add-to-dashboard-DeHEBEqG.js → add-to-dashboard-CEmZUf9o.js} +1 -1
- package/dist/chunks/{analytics-base-schemas-BREc5WGv.js → analytics-base-schemas-DMFrDqn_.js} +1 -1
- package/dist/chunks/appearance-provider-fIhJSX6y.js +613 -0
- package/dist/chunks/appearance-runtime-provider-Bx8H-moR.js +1 -0
- package/dist/chunks/{assistant-chat-CjYrwVDa.js → assistant-chat-SBKSrrEA.js} +19 -24
- package/dist/chunks/attachment-filter-line-C_zHMhGh.js +1 -0
- package/dist/chunks/{bookmark-impact-C89zBLq3.js → bookmark-impact-BW30cm5E.js} +1 -1
- package/dist/chunks/bookmark-state-DScd31KT.js +1 -0
- package/dist/chunks/brand-CL5xDiFH.js +1 -0
- package/dist/chunks/card-filter-builder-CzScSOQY.js +11 -0
- package/dist/chunks/comparison-window-caption-tguyN24S.js +1 -0
- package/dist/chunks/{context-ALdccLHw.js → context-CntvtZwC.js} +1 -1
- package/dist/chunks/dashboard-Cyhj9EOl.js +1 -0
- package/dist/chunks/dashboard-briefing-launcher-CyOFddmD.js +42 -0
- package/dist/chunks/dashboard-controls-DpADfhr0.js +42 -0
- package/dist/chunks/dashboard-json-4xMChR2q.js +1 -0
- package/dist/chunks/dashboard-temporal-snapshot-w3SMiPKj.js +1 -0
- package/dist/chunks/edit-dashboard-visual-DlvY7au4.js +73 -0
- package/dist/chunks/filter-line-WwUV5JzN.js +1 -0
- package/dist/chunks/filter-reach-preview-DAEIyrEG.js +1 -0
- package/dist/chunks/filter-value-text-DqTHe_vu.js +1 -0
- package/dist/chunks/{index-BE1DfxNs.js → index-bkP6SnYu.js} +1 -1
- package/dist/chunks/kpi-trend-rule-N1Xkwe_u.js +1 -0
- package/dist/chunks/{layout-grid-BWtlgw0T.js → layout-grid-Dtsioq4h.js} +1 -1
- package/dist/chunks/matrix-analytical-definition-5T-2euHZ.js +1 -0
- package/dist/chunks/matrix-member-presentation-vVAv-aqg.js +1 -0
- package/dist/chunks/matrix-operation-contract-CWvcEsQ0.js +1 -0
- package/dist/chunks/numeric-range-options-C8tr-Bls.js +1 -0
- package/dist/chunks/{palette-BzC-CGOc.js → palette-565cA0nh.js} +1 -1
- package/dist/chunks/pivot-result-contract-expectations-BNWhS8mv.js +1 -0
- package/dist/chunks/pivot-result-identity-B0eWVMXg.js +1 -0
- package/dist/chunks/{raw-temporal-value-DeyEhL0S.js → raw-temporal-value-BHQ-ldpW.js} +1 -1
- package/dist/chunks/report-preferences-dialog-B2ZGPS9t.js +1 -0
- package/dist/chunks/{report-runtime-context-BWzIHCKK.js → report-runtime-context-Cd1b5pku.js} +1 -1
- package/dist/chunks/resolve-dashboard-input-context-SlAAe4GF.js +8 -0
- package/dist/chunks/resolver-CjsW8Rz0.js +1 -0
- package/dist/chunks/saved-dashboard-context-Bc2SVDr-.js +1 -0
- package/dist/chunks/schema-O1Y3WTGF.js +4 -0
- package/dist/chunks/{selection-filter-compiler-CCoCD25M.js → selection-filter-compiler-kYsRugss.js} +1 -1
- package/dist/chunks/semaphor-ready-indicator-Bj-cjkz-.js +612 -0
- package/dist/chunks/set-CACXVM2A.js +1 -0
- package/dist/chunks/slider-CWze9OEM.js +4 -0
- package/dist/chunks/stored-dashboard-CcNdU-mG.js +1 -0
- package/dist/chunks/{table-export-sheet-rC5pKmXg.js → table-export-sheet-xaczzWZF.js} +1 -1
- package/dist/chunks/{token-types-Bj9iMy0w.js → token-types-1vzMWjI-.js} +1 -1
- package/dist/chunks/{validators-CqV3Yka1.js → validators-Dg2kyF4_.js} +1 -1
- package/dist/chunks/{variable-draft-DJrfUyhv.js → variable-draft-CRbSYdB6.js} +1 -1
- package/dist/dashboard/index.js +1 -1
- package/dist/dashboard-authoring/index.js +1 -1
- package/dist/format-utils/index.js +1 -1
- package/dist/index.js +1 -1
- package/dist/report-runtime-context/index.js +1 -1
- package/dist/style.css +1 -1
- package/dist/surfboard/index.js +1 -1
- package/dist/types/brand-studio/brand-studio-draft.d.ts +45 -13
- package/dist/types/brand-studio/brand-studio-editor.d.ts +13 -2
- package/dist/types/components/index.d.ts +1 -0
- package/dist/types/components/visual/data-table/hooks/use-data-table-logic.d.ts +17 -6
- package/dist/types/components/visual/data-table/types/data-table.d.ts +52 -42
- package/dist/types/index.js +1 -1
- package/dist/types/lib/appearance/aliases.d.ts +3 -0
- package/dist/types/lib/appearance/index.d.ts +1 -0
- package/dist/types/lib/appearance/table-density.d.ts +18 -0
- package/dist/types/lib/appearance/types.d.ts +39 -1
- package/dist/types/lib/dashboard-viewer/column-header-actions.d.ts +100 -0
- package/dist/types/lib/dashboard-viewer/table-view-edit.d.ts +0 -27
- package/dist/types/lib/dashboard-viewer/table-view.d.ts +26 -2
- package/dist/types/lib/dashboard-viewer/use-table-view.d.ts +2 -0
- package/dist/types/lib/hooks/use-add-new-frame.d.ts +7 -0
- package/dist/types/lib/hooks/use-dashboard-card.d.ts +4 -0
- package/dist/types/lib/interactions/get-click-context-from-chartjs.d.ts +8 -0
- package/dist/types/lib/stores/dashboard-store.d.ts +14 -2
- package/dist/types/lib/stores/explorer-actions.d.ts +0 -4
- package/dist/types/lib/types/common-types.d.ts +1 -2
- package/dist/types/lib/utils/card-config-utils.d.ts +13 -0
- package/dist/types/lib/utils/field-placement.d.ts +17 -0
- package/dist/types/shared/analytics-protocol/analytics-refusal.d.ts +21 -1
- package/dist/types/shared/analytics-protocol/field-provenance.d.ts +7 -4
- package/dist/types/shared/dashboard-authoring/card-data-source/filter-field-folders.d.ts +48 -0
- package/dist/types/shared/dashboard-authoring/card-settings/card-display-write.d.ts +2 -8
- package/dist/types/shared/dashboard-authoring/card-settings/card-kinds.d.ts +1 -1
- package/dist/types/shared/dashboard-authoring/card-settings/column-display-values.d.ts +5 -0
- package/dist/types/shared/dashboard-authoring/card-settings/column-display.d.ts +52 -0
- package/dist/types/shared/dashboard-authoring/card-settings/index.d.ts +1 -0
- package/dist/types/shared/dashboard-authoring/card-settings/inputs.d.ts +9 -0
- package/dist/types/shared/dashboard-authoring/card-settings/resolved.d.ts +4 -0
- package/dist/types/shared/dashboard-authoring/card-settings/table-viewer-switches.d.ts +15 -0
- package/dist/types/shared/dashboard-authoring/card-settings/views.d.ts +5 -0
- package/dist/types/shared/dashboard-authoring/changes/card-query-part.d.ts +6 -0
- package/dist/types/shared/dashboard-authoring/changes/dashboard-change.d.ts +132 -3
- package/dist/types/shared/dashboard-authoring/changes/diagnostics.d.ts +3 -1
- package/dist/types/shared/dashboard-authoring/conditional-formatting/schema.d.ts +10 -10
- package/dist/types/shared/dashboard-authoring/conditional-formatting/store.d.ts +10 -1
- package/dist/types/shared/dashboard-authoring/field-aggregations.d.ts +9 -2
- package/dist/types/shared/dashboard-authoring/field-folders/field-folders.d.ts +8 -7
- package/dist/types/shared/dashboard-authoring/index.d.ts +1 -0
- package/dist/types/shared/dashboard-authoring/measure-calculations/index.d.ts +1 -1
- package/dist/types/shared/dashboard-authoring/measure-calculations/window-transforms.d.ts +2 -0
- package/dist/types/shared/dashboard-authoring/operations/card-operations.d.ts +2 -0
- package/dist/types/shared/dashboard-authoring/operations/operation-types.d.ts +7 -2
- package/dist/types/shared/dashboard-authoring/outline/outline-dashboard.d.ts +6 -2
- package/dist/types/shared/dashboard-authoring/sheet-kinds.d.ts +36 -0
- package/dist/types/shared/dashboard-authoring/table-sheet-shape.d.ts +140 -0
- package/dist/types/shared/dashboard-viewer/table-column-move.d.ts +15 -0
- package/dist/types/shared/dashboard-viewer/table-settings.d.ts +8 -2
- package/dist/types/shared/format-utils/types/format-types.d.ts +1 -1
- package/dist/usage-events/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunks/appearance-context-BqBZrijL.js +0 -1
- package/dist/chunks/appearance-runtime-provider-DmbCrOOG.js +0 -1
- package/dist/chunks/bookmark-state-69YYnRql.js +0 -1
- package/dist/chunks/brand-DCaZyRt6.js +0 -1
- package/dist/chunks/card-filter-builder-CTp6RAz1.js +0 -17
- package/dist/chunks/comparison-window-caption-C312mn3s.js +0 -1
- package/dist/chunks/dashboard-BX28ld6s.js +0 -1
- package/dist/chunks/dashboard-briefing-launcher-qo7GH4EO.js +0 -37
- package/dist/chunks/dashboard-controls-DhRjB7MA.js +0 -42
- package/dist/chunks/dashboard-json-9cHzhSjC.js +0 -1
- package/dist/chunks/dates-D-KP8G-z.js +0 -1
- package/dist/chunks/edit-DEAK0UZo.js +0 -1
- package/dist/chunks/edit-dashboard-visual-Duq_QkB_.js +0 -93
- package/dist/chunks/filter-line-CwQrqORc.js +0 -1
- package/dist/chunks/filter-reach-preview-gixPFlZj.js +0 -1
- package/dist/chunks/filter-value-text-B3tXakhd.js +0 -1
- package/dist/chunks/index-B-VF1ogs.js +0 -1
- package/dist/chunks/matrix-analytical-definition-CtFqWyCK.js +0 -1
- package/dist/chunks/matrix-member-presentation-Q0MCJ-YK.js +0 -1
- package/dist/chunks/matrix-operation-contract-D1RC1bfi.js +0 -1
- package/dist/chunks/metric-comparison-DEZYXROZ.js +0 -1
- package/dist/chunks/paintbrush-BjS3SbrH.js +0 -6
- package/dist/chunks/pickers-DuBrUht0.js +0 -1
- package/dist/chunks/pivot-result-contract-expectations-DTQAgr4n.js +0 -1
- package/dist/chunks/pivot-result-identity-DTNCB--h.js +0 -1
- package/dist/chunks/report-preferences-dialog-B_gUmCzG.js +0 -1
- package/dist/chunks/resolve-dashboard-input-context-B-TtRqxu.js +0 -8
- package/dist/chunks/resolver-AN9ChBfZ.js +0 -1
- package/dist/chunks/save-DdFUZcbi.js +0 -6
- package/dist/chunks/saved-dashboard-context-BAJ5tWiq.js +0 -1
- package/dist/chunks/schema-MC0cQSAb.js +0 -4
- package/dist/chunks/semaphor-ready-indicator-DzjorP3t.js +0 -999
- package/dist/chunks/set-DuJfGkbY.js +0 -1
- package/dist/chunks/shelf-drop-preview-context-BlLJ5RsT.js +0 -6
- package/dist/chunks/stored-dashboard-Ctcpkllg.js +0 -1
- package/dist/chunks/style-sheet-parts-BRGt9O05.js +0 -178
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import{c as Qt,t as Ht,u as Ye,v as Xe,w as Yt,e as Je,f as yt,B as K,h as Ze,T as pn,k as fn,l as hn,Y as gn,Z as bn,_ as xn,X as et,j as yn,s as ce,C as Yr,L as Xt,$ as vn,F as Qe,x as Be,y as Oe,z as ze,A as $e,D as Ve,E as ve,a0 as Xr,d as Nn}from"./style-sheet-parts-BRGt9O05.js";import{jsx as t,jsxs as l,Fragment as de}from"react/jsx-runtime";import{i1 as Jr,i2 as wn,i0 as Zr,h_ as ea,i3 as kn,hu as Sr,i4 as Dr,i5 as Cn,ex as _e,i6 as Tr,ht as Bt,e as Ue,h$ as Sn,i7 as Dn,i8 as Tn,hD as Er,hA as En,hG as In,hC as Ln,i9 as An,ia as Rn,ib as dt,ic as Ir,id as Lr,ie as zt,ig as $t,ih as On,ii as zn,ij as Ar,ik as $n,il as Vn,im as ct,io as _n,ip as Rr,iq as ta,ir as ra,is as aa,it as na,iu as Fn,iv as Mn,iw as Or,ix as qn,iy as zr,iz as Gn,iA as Bn,iB as Un,iC as jn,iD as Vt,iE as $r,cj as Pn,iF as _t,a$ as Kn,iG as Wn,iH as Qn,iI as Hn,iJ as Yn}from"./resolve-dashboard-input-context-B-TtRqxu.js";import*as He from"react";import Vr,{useMemo as P,useState as U,useRef as he,useEffect as je,useCallback as j,useId as Xn,forwardRef as Jn,Fragment as Zn}from"react";import{c as H}from"./pickers-DuBrUht0.js";import{i as es,a as ts,C as vt,k as sa,r as rs,aE as oa,aF as la}from"./validators-CqV3Yka1.js";import"./matrix-operation-contract-D1RC1bfi.js";import"./analytics-base-schemas-BREc5WGv.js";import"../value-format-preferences/index.js";import{bl as as,cp as ia,cq as ns,cr as ss,cs as os,ct as da,cu as Ut,cv as ls,bK as mt,c3 as is,c4 as ds,c5 as cs,bJ as us,ca as ms,cb as ps,bS as fs,cw as hs,b1 as Nt,bU as gs,cx as bs,am as Se,u as Me,bx as xs,cy as ys,cz as vs,cA as Ns,br as ws,bs as ks,bt as Cs,cB as Ss,cC as _r,bn as Ds,bp as Ts,bq as Es,ch as Is,ci as Ls,cj as As,ck as Rs,cl as Os,cm as zs,cn as $s,co as Vs,cD as _s,o as Fs,cE as Ms,cF as qs,cG as Gs,cH as Fr,bQ as Mr,bI as ca,cI as Bs,cJ as ua,cK as ma,cL as Us,cM as js,cN as Ps,cO as Ks,cP as Ws,cQ as Qs,cR as Hs,bi as Ys,cS as qr,cT as pa,cU as Gr,cV as Xs,cW as Js,cX as Ge,cY as fa,cZ as Zs,c_ as eo,c$ as to,d0 as ro,d1 as ao,d2 as jt,d3 as qe,d4 as Pt,d5 as Kt,d6 as Wt,d7 as no,d8 as pt,d9 as ft,da as ht,db as gt,dc as ha,dd as ga,de as ba}from"./semaphor-ready-indicator-DzjorP3t.js";import{y as so}from"./stored-dashboard-Ctcpkllg.js";import{a as xa}from"./metric-comparison-DEZYXROZ.js";import{r as oo,m as lo}from"./raw-temporal-value-DeyEhL0S.js";/**
|
|
2
|
-
* @license lucide-react v0.453.0 - ISC
|
|
3
|
-
*
|
|
4
|
-
* This source code is licensed under the ISC license.
|
|
5
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
-
*/const io=Qt("CircleDashed",[["path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0",key:"5ilxe3"}],["path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0",key:"11zvb9"}],["path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7",key:"1iw5b2"}],["path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8",key:"c0bmvh"}],["path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69",key:"1ruxm7"}],["path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8",key:"qkgqxc"}],["path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69",key:"1mcia2"}],["path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7",key:"1fvljs"}]]);/**
|
|
7
|
-
* @license lucide-react v0.453.0 - ISC
|
|
8
|
-
*
|
|
9
|
-
* This source code is licensed under the ISC license.
|
|
10
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
-
*/const Vl=Qt("FilterX",[["path",{d:"M13.013 3H2l8 9.46V19l4 2v-8.54l.9-1.055",key:"1fi1da"}],["path",{d:"m22 3-5 5",key:"12jva0"}],["path",{d:"m17 3 5 5",key:"k36vhe"}]]);/**
|
|
12
|
-
* @license lucide-react v0.453.0 - ISC
|
|
13
|
-
*
|
|
14
|
-
* This source code is licensed under the ISC license.
|
|
15
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
16
|
-
*/const co=Qt("Library",[["path",{d:"m16 6 4 14",key:"ji33uf"}],["path",{d:"M12 6v14",key:"1n7gus"}],["path",{d:"M8 8v12",key:"1gg7y9"}],["path",{d:"M4 4v16",key:"6qkkli"}]]);function uo({children:e,className:r,delayDuration:a}){return/* @__PURE__ */t(Ht,{children:/* @__PURE__ */l(Ye,{delayDuration:a,children:[/* @__PURE__ */t(Xe,{asChild:!0,children:/* @__PURE__ */t("div",{className:H("w-[200px] overflow-hidden text-ellipsis whitespace-nowrap text-sm",r),children:e})}),/* @__PURE__ */t(Yt,{children:e})]})});}function mo({value:e,onValueChange:r,availableFields:a,placeholder:n="Select field",className:o}){const[d,c]=Vr.useState(!1),i=Vr.useMemo(()=>new Set(e?[e.id]:[]),[e]),u=e?Jr(e):null;return/* @__PURE__ */l(Je,{modal:!0,open:d,onOpenChange:c,children:[/* @__PURE__ */t(yt,{asChild:!0,children:/* @__PURE__ */l(K,{variant:"outline",size:"xs",role:"combobox","aria-expanded":d,title:e?`${e.entityName}.${e.name}`:void 0,className:H("min-w-0 justify-between gap-1.5 font-normal",!e&&"text-muted-foreground",o),children:[u?/* @__PURE__ */t(uo,{className:"w-auto min-w-0 flex-1 text-left text-[12px]",children:u}):/* @__PURE__ */t("span",{className:"min-w-0 flex-1 truncate text-left",children:n}),/* @__PURE__ */t(as,{className:"h-3.5 w-3.5 shrink-0 opacity-50"})]})}),/* @__PURE__ */t(Ze,{className:"flex w-80 flex-col rounded-control p-1.5",align:"start",onOpenAutoFocus:h=>{var w,v;h.preventDefault(),(v=(w=h.currentTarget)==null?void 0:w.querySelector('input[type="text"]'))==null||v.focus();},children:/* @__PURE__ */t(ia,{fields:a,selectedIds:i,onSelect:h=>{r(h),c(!1);},density:"compact",listLabel:"Fields",listClassName:"max-h-80"})})]});}function po({value:e,onChange:r,disabled:a,options:n=["dimension","metric"]}){const o=n.length>0?n:["dimension","metric"],d=["dimension","metric"].filter(u=>o.includes(u)),c=a||d.length<=1,i=d.includes(e)?e:d[0];return/* @__PURE__ */t(pn,{value:i,onValueChange:u=>r(u),className:"w-fit shrink-0",children:/* @__PURE__ */t(fn,{size:"xs",className:"border border-border bg-transparent shadow-none",children:d.map(u=>/* @__PURE__ */t(hn,{value:u,disabled:c,className:"data-[state=active]:bg-muted data-[state=active]:shadow-none",children:ns(u)},u))})});}const Jt=He.forwardRef(({className:e,sideOffset:r=8,...a},n)=>/* @__PURE__ */t(bn,{children:/* @__PURE__ */t(ss,{children:/* @__PURE__ */t(xn,{ref:n,sideOffset:r,className:H("z-[60] overflow-hidden rounded-lg border bg-popover text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...a})})}));Jt.displayName="ValidationTooltipContent";const ya=gn;function Ft(e,r){return`${e} ${r}${e===1?"":"s"}`;}function fo({result:e}){const r=e.errors.length>0,a=Ft(e.tokens.length,"token"),n=e.errors.length>0?Ft(e.errors.length,"error"):null,o=e.warnings.length>0?Ft(e.warnings.length,"warning"):null,d=e.errors.map(c=>c.suggestion?`${c.message} (${c.suggestion})`:c.message).join(`
|
|
17
|
-
`);return/* @__PURE__ */l(Ye,{delayDuration:120,children:[/* @__PURE__ */t(Xe,{asChild:!0,children:/* @__PURE__ */t("button",{type:"button","aria-label":r?"Validation failed. Hover to view details.":"Validation passed. Hover to view details.",className:H("inline-flex h-5 w-5 items-center justify-center rounded-full transition-colors",r?"bg-destructive text-destructive-foreground hover:bg-destructive/90":"bg-emerald-600 text-white hover:bg-emerald-700"),children:r?/* @__PURE__ */t(et,{className:"h-3 w-3","aria-hidden":!0}):/* @__PURE__ */t(yn,{className:"h-3 w-3","aria-hidden":!0})})}),/* @__PURE__ */l(Jt,{side:"top",align:"start",avoidCollisions:!0,collisionPadding:12,className:"w-[min(440px,calc(100vw-32px))] p-0",children:[/* @__PURE__ */l("div",{className:"space-y-2.5 p-3 text-xs",children:[/* @__PURE__ */t("div",{className:H("font-semibold",r?"text-destructive":"text-emerald-700"),children:r?"Validation failed":"Validation passed"}),/* @__PURE__ */l("div",{className:"flex flex-wrap gap-x-2 gap-y-1 text-[11px] text-muted-foreground",children:[/* @__PURE__ */t("span",{children:a}),n&&/* @__PURE__ */t("span",{children:n}),o&&/* @__PURE__ */t("span",{children:o}),e.inferredDataType&&/* @__PURE__ */l("span",{children:["type: ",e.inferredDataType]})]}),e.tokens.length>0&&/* @__PURE__ */l("div",{className:"space-y-1.5 border-t pt-2",children:[/* @__PURE__ */t("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Tokens"}),/* @__PURE__ */t("div",{className:"max-h-28 space-y-1 overflow-y-auto pr-1 select-text",children:e.tokens.map((c,i)=>/* @__PURE__ */l("div",{className:"flex items-start gap-1.5",children:[/* @__PURE__ */t("span",{className:"rounded bg-muted px-1.5 py-0.5 font-mono leading-none",children:`{${c.token}}`}),/* @__PURE__ */t(os,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground"}),c.field?/* @__PURE__ */t("span",{className:"break-all text-muted-foreground",children:c.field.qualifiedFieldName||c.field.name}):/* @__PURE__ */t("span",{className:"text-muted-foreground",children:"Unresolved"})]},`${c.token}-${i}`))})]}),e.errors.length>0&&/* @__PURE__ */l("div",{className:"space-y-1.5",children:[/* @__PURE__ */l("div",{className:"flex items-center justify-between gap-2",children:[/* @__PURE__ */t("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-destructive",children:"Errors"}),/* @__PURE__ */t(da,{text:d,ariaLabel:"Copy validation errors",className:"h-5 w-5 p-0 text-destructive/70 hover:text-destructive"})]}),/* @__PURE__ */t("div",{className:"max-h-32 space-y-1 overflow-y-auto pr-1 text-destructive select-text",children:e.errors.map((c,i)=>/* @__PURE__ */l("div",{className:"break-words",children:[c.message,c.suggestion?` (${c.suggestion})`:""]},`${c.code}-${i}`))})]}),e.warnings.length>0&&/* @__PURE__ */l("div",{className:"space-y-1.5",children:[/* @__PURE__ */t("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-amber-700",children:"Warnings"}),/* @__PURE__ */t("div",{className:"max-h-32 space-y-1 overflow-y-auto pr-1 text-amber-700 select-text",children:e.warnings.map((c,i)=>/* @__PURE__ */l("div",{className:"break-words",children:[c.message,c.suggestion?` (${c.suggestion})`:""]},`${c.code}-${i}`))})]}),e.inferredDataType&&/* @__PURE__ */l("div",{className:"border-t pt-2 text-[11px] text-muted-foreground",children:["Inferred output type:"," ",/* @__PURE__ */t("span",{className:"font-medium text-foreground",children:e.inferredDataType})]})]}),/* @__PURE__ */t(ya,{className:"fill-popover"})]})]});}function ho({onValidate:e,isValidating:r,validationResult:a,error:n,disabled:o}){return/* @__PURE__ */l("div",{className:"flex items-center gap-2",children:[/* @__PURE__ */t(K,{type:"button",variant:"outline",size:"xs",onClick:e,disabled:r||o,children:r?"Validating…":"Validate"}),a&&/* @__PURE__ */t(fo,{result:a}),!a&&n&&/* @__PURE__ */l(Ye,{delayDuration:120,children:[/* @__PURE__ */t(Xe,{asChild:!0,children:/* @__PURE__ */t("button",{type:"button","aria-label":"Validation failed. Hover to view details.",className:"inline-flex h-5 w-5 items-center justify-center rounded-full bg-destructive text-destructive-foreground hover:bg-destructive/90",children:/* @__PURE__ */t(et,{className:"h-3 w-3","aria-hidden":!0})})}),/* @__PURE__ */l(Jt,{side:"top",align:"start",avoidCollisions:!0,collisionPadding:12,className:"w-[min(420px,calc(100vw-32px))] p-3",children:[/* @__PURE__ */l("div",{className:"space-y-2 text-xs",children:[/* @__PURE__ */l("div",{className:"flex items-center justify-between gap-2",children:[/* @__PURE__ */t("span",{className:"font-semibold text-destructive",children:"Validation failed"}),/* @__PURE__ */t(da,{text:n,ariaLabel:"Copy validation error",className:"h-5 w-5 p-0 text-destructive/70 hover:text-destructive"})]}),/* @__PURE__ */t("p",{className:"max-h-40 overflow-y-auto break-words text-destructive select-text",children:n})]}),/* @__PURE__ */t(ya,{className:"fill-popover"})]})]})]});}const go={metric:["Average revenue per order","Profit margin %","Active customers last 30 days"],dimension:["Order month from created_at","Bucket revenue into 'Large' / 'Small'","Country and state combined"]};function bo({mode:e,fieldType:r,prompt:a,onPromptChange:n,generated:o,explanation:d,isGenerating:c,error:i,onGenerate:u,onTryAgain:h,onCancel:w,onUseDraft:v,disabled:D}){const x=e==="result",y=e==="loading"||c,m=go[r];return/* @__PURE__ */l("div",{"data-testid":"ai-compose-panel","data-mode":e,className:"rounded-[6px] border border-blue-200 bg-blue-50/40 dark:border-blue-900/40 dark:bg-blue-950/20",children:[/* @__PURE__ */l("div",{className:"flex items-center gap-2 border-b border-blue-200/60 px-3 py-2 dark:border-blue-900/30",children:[/* @__PURE__ */t(Ut,{className:"h-3 w-3 text-blue-600 dark:text-blue-400","aria-hidden":!0}),/* @__PURE__ */t("span",{className:"text-[11px] font-medium text-zinc-900 dark:text-zinc-100",children:x?"AI draft — ready to use":"Compose with AI"}),/* @__PURE__ */t("span",{className:"text-[10px] text-zinc-500 dark:text-zinc-400",children:x?"Review before using.":"Describe in plain English. AI knows your fields."}),/* @__PURE__ */t("button",{type:"button","aria-label":"Close AI compose",onClick:w,disabled:D,className:"ml-auto text-blue-700/70 hover:text-blue-900 disabled:opacity-50 dark:text-blue-300/70 dark:hover:text-blue-100",children:/* @__PURE__ */t(et,{className:"h-3 w-3"})})]}),/* @__PURE__ */t("div",{className:"space-y-2 p-3",children:x?/* @__PURE__ */l(de,{children:[a.trim()&&/* @__PURE__ */l("div",{className:"flex items-start gap-1.5 rounded-[4px] bg-white px-2 py-1.5 text-[11px] dark:bg-zinc-950",children:[/* @__PURE__ */t("span",{className:"shrink-0 text-zinc-400",children:"›"}),/* @__PURE__ */l("span",{className:"italic text-zinc-600 dark:text-zinc-400",children:["“",a.trim(),"”"]})]}),/* @__PURE__ */t("div",{className:"overflow-hidden rounded-[5px] border border-zinc-200 bg-white dark:border-zinc-800 dark:bg-zinc-950",children:/* @__PURE__ */t("div",{className:"max-h-[180px]",children:/* @__PURE__ */t(Yr,{value:o,language:"sql-jinja",readOnly:!0,embedded:!0,hideLineNumbers:!0,dense:!0,ariaLabel:"Generated expression"})})}),d?/* @__PURE__ */t("p",{className:"text-[11px] text-zinc-500 dark:text-zinc-400",children:d}):null]}):/* @__PURE__ */l(de,{children:[/* @__PURE__ */t(ce,{htmlFor:"ai-compose-prompt",className:"sr-only",children:"Describe what you want to calculate"}),/* @__PURE__ */t(ls,{id:"ai-compose-prompt",value:a,onChange:L=>n(L.target.value),placeholder:r==="metric"?"e.g. average revenue per order, in dollars":"e.g. bucket orders into 'Large' / 'Small' by amount",rows:2,disabled:y||D,className:"resize-none border-zinc-200 bg-white text-[13px] text-zinc-900 shadow-none placeholder:text-zinc-400 focus:border-zinc-400 focus-visible:ring-0 disabled:opacity-60 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-50"}),!y&&/* @__PURE__ */l("div",{className:"flex flex-wrap items-center gap-1",children:[/* @__PURE__ */t("span",{className:"mr-1 text-[10px] uppercase tracking-[0.08em] text-zinc-400",children:"Try"}),m.map(L=>/* @__PURE__ */t("button",{type:"button",onClick:()=>n(L),disabled:D,className:"inline-flex h-5 items-center rounded-[4px] border border-zinc-200 bg-white px-1.5 text-[11px] text-zinc-600 hover:bg-zinc-50 hover:text-zinc-900 disabled:opacity-50 dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-400 dark:hover:bg-zinc-900 dark:hover:text-zinc-100",children:L},L))]}),i&&/* @__PURE__ */t("p",{className:"whitespace-pre-wrap text-[11px] text-destructive",children:i})]})}),/* @__PURE__ */t("div",{className:"flex items-center justify-end gap-1.5 border-t border-blue-200/60 px-3 py-2 dark:border-blue-900/30",children:x?/* @__PURE__ */l(de,{children:[/* @__PURE__ */t(K,{type:"button",variant:"outline",size:"xs",onClick:h,disabled:D,children:"Try again"}),/* @__PURE__ */t(K,{type:"button",variant:"outline",size:"xs",onClick:w,disabled:D,children:"Cancel"}),/* @__PURE__ */t(K,{type:"button",size:"xs",onClick:v,disabled:D||!o.trim(),children:"Use draft"})]}):/* @__PURE__ */l(de,{children:[/* @__PURE__ */t(K,{type:"button",variant:"outline",size:"xs",onClick:w,disabled:D,children:"Cancel"}),/* @__PURE__ */t(K,{type:"button",size:"xs",onClick:u,disabled:y||D||!a.trim(),className:H("gap-1.5",y&&"pointer-events-none"),children:y?/* @__PURE__ */l(de,{children:[/* @__PURE__ */t(Xt,{className:"h-3 w-3 animate-spin","aria-hidden":!0}),"Generating…"]}):/* @__PURE__ */l(de,{children:[/* @__PURE__ */t(Ut,{className:"h-3 w-3","aria-hidden":!0}),"Generate"]})})]})})]});}function va({groups:e,searchTerm:r,onSearchTermChange:a,onFieldClick:n,selectedFieldIds:o,unavailableFieldReasons:d,disabled:c,listLabel:i="Insert field",autoFocusSearch:u,selectFirstOnEnter:h}){const w=P(()=>new Set(o||[]),[o]),{fields:v,groupByFieldId:D}=P(()=>{const x=/* @__PURE__ */new Map(),y=[];for(const m of e)for(const V of m.fields)x.set(V.id,{id:m.id,label:m.label}),y.push(V);return{fields:y,groupByFieldId:x};},[e]);return/* @__PURE__ */t("div",{className:"flex h-full min-h-0 flex-col",children:/* @__PURE__ */t(ia,{fields:v,selectedIds:w,onSelect:n,query:r,onQueryChange:a,listLabel:i,autoFocusSearch:u,selectFirstOnEnter:h,listClassName:"min-h-0 flex-1",getGroup:x=>D.get(x.id)??null,isDisabled:x=>!x.isCompatible||!!c,isCalculated:x=>x.isCalculated?x.role==="metric"?"metric":"dimension":!1,density:"compact",renderTrailing:(x,y)=>y?/* @__PURE__ */t("span",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Selected"}):d!=null&&d[x.id]?/* @__PURE__ */t("span",{title:d[x.id],className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground/70",children:"Not in this visual"}):void 0})});}function xo({groups:e,searchTerm:r,onSearchTermChange:a,onFieldSelect:n,selectedFieldIds:o,unavailableFieldReasons:d,disabled:c}){const[i,u]=U(!1);return/* @__PURE__ */l(Je,{open:i,onOpenChange:u,children:[/* @__PURE__ */t(yt,{asChild:!0,children:/* @__PURE__ */l(K,{type:"button",variant:"outline",size:"xs",disabled:c,className:"gap-1.5",children:[/* @__PURE__ */t(mt,{className:"h-3 w-3","aria-hidden":!0}),"Insert field"]})}),/* @__PURE__ */t(Ze,{align:"end",sideOffset:6,collisionPadding:8,className:"z-[51] w-[320px] max-w-[min(320px,calc(100vw-32px))] p-2",children:/* @__PURE__ */t("div",{className:"flex h-[min(360px,calc(var(--radix-popover-content-available-height)-16px))] min-h-0 flex-col",children:/* @__PURE__ */t(va,{groups:e,searchTerm:r,unavailableFieldReasons:d,onSearchTermChange:a,onFieldClick:h=>{n(h),u(!1);},selectedFieldIds:o,disabled:c})})})]});}const Na=/\{([^}]+)\}/g;function tt(e){return e.trim().toLowerCase();}function wa(e){return Array.from(e.matchAll(Na)).map(r=>r[1]).filter(Boolean);}function yo(e){const r=/* @__PURE__ */new Set(),a=[];return e.forEach(n=>{const o=tt(n);r.has(o)||(r.add(o),a.push(n));}),a;}function Zt(e){const r=/* @__PURE__ */new Map(),a=(n,o)=>{const d=tt(n),c=r.get(d)||[];c.some(i=>i.id===o.id)||r.set(d,[...c,o]);};return e.forEach(n=>{a(n.tokenLabel,n),n.name&&n.name!==n.tokenLabel&&a(n.name,n),n.baseLabel&&n.baseLabel!==n.tokenLabel&&a(n.baseLabel,n);}),r;}function Br(e){return Array.from(e.matchAll(Na)).filter(r=>!!r[1]).map(r=>({token:r[1],start:r.index??0,end:(r.index??0)+r[0].length}));}function bt(e){return /^[a-z]$/.test(e.trim());}function ka(e,r){return(r.get(tt(e))||[]).length===1;}function Ur(e,r){return e.filter(a=>!ka(a.token,r)).sort((a,n)=>{const o=bt(a.token),d=bt(n.token);if(o!==d)return o?-1:1;if(o){const c=a.token.trim().localeCompare(n.token.trim());if(c!==0)return c;}return a.start-n.start;});}function ut(e,r){const a=wa(e),n=yo(a),o=Zt(r),d=n.map(i=>{const u=o.get(tt(i))||[];return u.length===1?u[0]:null;}),c=n.filter((i,u)=>!d[u]);return{orderedTokens:n,orderedFields:d,unresolvedTokens:c};}function vo({token:e,remaining:r,anchorRef:a,groups:n,unavailableFieldReasons:o,onPick:d,onEscape:c,onDismiss:i,onCloseAutoFocus:u}){return/* @__PURE__ */l(Je,{open:e!==null,onOpenChange:h=>{h||i();},children:[/* @__PURE__ */t(vn,{virtualRef:a}),/* @__PURE__ */t(Ze,{align:"start",side:"bottom",sideOffset:6,collisionPadding:8,className:"z-[51] w-[300px] max-w-[min(300px,calc(100vw-32px))] p-2",onOpenAutoFocus:h=>h.preventDefault(),onEscapeKeyDown:h=>{h.preventDefault(),c();},onCloseAutoFocus:u,children:e!==null?/* @__PURE__ */t(No,{token:e,remaining:r,groups:n,unavailableFieldReasons:o,onPick:d},e):null})]});}function No({token:e,remaining:r,groups:a,unavailableFieldReasons:n,onPick:o}){const[d,c]=U(()=>bt(e)?"":e.trim()),i=he(null);return je(()=>{const u=requestAnimationFrame(()=>{var w;const h=(w=i.current)==null?void 0:w.querySelector("input");h==null||h.focus(),h==null||h.select();});return()=>cancelAnimationFrame(u);},[]),/* @__PURE__ */l("div",{ref:i,className:"flex h-[min(320px,calc(var(--radix-popover-content-available-height)-16px))] min-h-0 flex-col",children:[/* @__PURE__ */l("div",{className:"mb-1.5 flex items-center justify-between gap-2 px-0.5",children:[/* @__PURE__ */l("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:["Replace"," ",/* @__PURE__ */t("code",{className:"rounded-[3px] bg-muted px-1 font-mono text-[11px] text-foreground",children:`{${e}}`})]}),r>1?/* @__PURE__ */l("span",{className:"shrink-0 text-[10px] tabular-nums text-muted-foreground",children:[r," to choose"]}):null]}),/* @__PURE__ */t("div",{className:"min-h-0 flex-1",children:/* @__PURE__ */t(va,{groups:a,searchTerm:d,onSearchTermChange:c,unavailableFieldReasons:n,onFieldClick:o,listLabel:`Choose a field for {${e}}`,selectFirstOnEnter:!0})}),/* @__PURE__ */t("p",{className:"mt-1.5 border-t border-border/60 px-0.5 pt-1.5 text-[10px] text-muted-foreground",children:"Enter picks the top match · Esc to type it yourself"})]});}const wo=["Logic","Text","Dates","Numbers","Empty values"],ko=[{id:"concatenate",label:"Combine text",symbol:"ab",preview:"Combine {a} and {b}",hint:"Space-separated",category:"Text",keywords:["concatenate","concat","join","merge","text"],common:!0},{id:"conditional-category",label:"Conditional category",symbol:"?",preview:"If {a}, return a label",hint:"IF / CASE",category:"Logic",keywords:["if","case","condition","category","label"],common:!0},{id:"date-part",label:"Month number",symbol:"M",preview:"Month number from {a}",hint:"1–12",category:"Dates",keywords:["date part","extract","month","month number"],common:!0},{id:"date-difference",label:"Days between",symbol:"Δd",preview:"Calendar days from {a} to {b}",hint:"B − A",category:"Dates",keywords:["date difference","datediff","days between","elapsed"],common:!0},{id:"null-to-zero",label:"Replace null with zero",symbol:"∅",preview:"Use 0 when {a} is null",hint:"Missing → 0",category:"Empty values",keywords:["null","blank","missing","zero","coalesce"],common:!0},{id:"safe-ratio",label:"Safe ratio",symbol:"÷",preview:"{a} ÷ {b}",hint:"Null-safe division",category:"Numbers",keywords:["divide","division","ratio","nullif","zero"],common:!0},{id:"nested-conditional",label:"Nested conditional",symbol:"??",preview:"Small, medium, or large from {a}",hint:"Multi-branch CASE",category:"Logic",keywords:["nested if","multiif","case","bands","bucket"]},{id:"membership-test",label:"Membership test",symbol:"∈",preview:"Is {a} in a list?",hint:"IN list",category:"Logic",keywords:["in","contains","membership","list","boolean"]},{id:"uppercase",label:"Uppercase",symbol:"AA",preview:"Convert {a} to uppercase",hint:"UPPER",category:"Text",keywords:["upper","uppercase","capital letters","normalize"]},{id:"lowercase",label:"Lowercase",symbol:"aa",preview:"Convert {a} to lowercase",hint:"LOWER",category:"Text",keywords:["lower","lowercase","normalize"]},{id:"trim-whitespace",label:"Trim whitespace",symbol:"↔",preview:"Remove outer whitespace from {a}",hint:"Both ends",category:"Text",keywords:["trim","whitespace","spaces","clean","normalize"]},{id:"replace-text",label:"Replace text",symbol:"a→b",preview:"Replace '-' with ' ' in {a}",hint:"Find and replace",category:"Text",keywords:["replace","substitute","clean","text"]},{id:"first-characters",label:"First characters",symbol:"abc",preview:"Take the first 3 characters of {a}",hint:"First 3",category:"Text",keywords:["substring","substr","first n","left","characters"]},{id:"character-count",label:"Character count",symbol:"#a",preview:"Count characters in {a}",hint:"Text length",category:"Text",keywords:["length","len","character count","text size"]},{id:"starts-with",label:"Starts with",symbol:"^a",preview:"Does {a} start with 'Value'?",hint:"Boolean",category:"Text",keywords:["prefix","starts with","startswith","begins","boolean"]},{id:"number-to-text",label:"Number to text",symbol:"1→a",preview:"Convert {a} to text",hint:"Text cast",category:"Text",keywords:["cast","convert","string","text","tostring"]},{id:"start-of-month",label:"Start of month",symbol:"M↤",preview:"First day of the month containing {a}",hint:"Date",category:"Dates",keywords:["month start","truncate month","first day","date"]},{id:"start-of-quarter",label:"Start of quarter",symbol:"Q↤",preview:"First day of the quarter containing {a}",hint:"Date",category:"Dates",keywords:["quarter start","truncate quarter","first day","date"]},{id:"start-of-year",label:"Start of year",symbol:"Y↤",preview:"First day of the year containing {a}",hint:"Date",category:"Dates",keywords:["year start","truncate year","first day","date"]},{id:"year-number",label:"Year number",symbol:"YYYY",preview:"Year number from {a}",hint:"e.g. 2026",category:"Dates",keywords:["year","extract year","date part"]},{id:"add-days",label:"Add days",symbol:"d+",preview:"Add 7 days to {a}",hint:"+7 days",category:"Dates",keywords:["date add","add days","plus days","offset"]},{id:"round-number",label:"Round",symbol:"≈",preview:"Round {a} to 2 decimal places",hint:"2 decimals",category:"Numbers",keywords:["round","decimal","precision"]},{id:"round-down",label:"Round down",symbol:"⌊x⌋",preview:"Round {a} down to an integer",hint:"Floor",category:"Numbers",keywords:["floor","round down","integer"]},{id:"round-up",label:"Round up",symbol:"⌈x⌉",preview:"Round {a} up to an integer",hint:"Ceiling",category:"Numbers",keywords:["ceil","ceiling","round up","integer"]},{id:"absolute-value",label:"Absolute value",symbol:"|x|",preview:"Absolute value of {a}",hint:"Remove sign",category:"Numbers",keywords:["abs","absolute","magnitude","positive"]},{id:"cap-maximum",label:"Cap at maximum",symbol:"≤",preview:"Limit {a} to a maximum of 100",hint:"Maximum 100",category:"Numbers",keywords:["cap","maximum","least","limit","outlier"]},{id:"floor-minimum",label:"Floor at minimum",symbol:"≥",preview:"Keep {a} at or above 0",hint:"Minimum 0",category:"Numbers",keywords:["minimum","greatest","floor","limit","negative"]},{id:"fill-blanks",label:"Fill text blanks",symbol:"∅a",preview:"Use 'Unknown' when {a} is null",hint:"Missing → Unknown",category:"Empty values",keywords:["null","blank","missing","unknown","coalesce","text"]},{id:"null-if-zero",label:"Treat zero as blank",symbol:"0→∅",preview:"Return null when {a} is zero",hint:"Zero → null",category:"Empty values",keywords:["nullif","zero","blank","missing"]},{id:"is-blank",label:"Is blank",symbol:"∅?",preview:"Is {a} null?",hint:"Boolean",category:"Empty values",keywords:["is null","blank","missing","null","boolean"]}];function Co({fieldType:e,onInsert:r,onInsertRowTemplate:a,rowTemplates:n,rowTemplatesLoading:o,disabled:d}){const[c,i]=U(!1),[u,h]=U(""),w=e==="dimension",v=P(()=>w?ko.map(m=>({...m,common:!!m.common,select:()=>{const V=n==null?void 0:n[m.id];V&&a(V);}})):wn.map(m=>{var V;return{id:m.id,label:m.label,symbol:m.symbol,preview:((V=m.insertTemplate)==null?void 0:V.call(m))||"",hint:m.insertHint||"",category:"Aggregate",keywords:[m.id,m.label,m.description],common:!1,select:()=>{var J;const L=(J=m.insertTemplate)==null?void 0:J.call(m);L&&r(L);}};}),[w,r,a,n]),D=u.trim().toLowerCase(),x=D?v.filter(m=>[m.label,m.preview,m.hint,m.category,...m.keywords].join(" ").toLowerCase().includes(D)):v,y=w?[...(D?[]:[{label:"Common",templates:x.filter(m=>m.common)}]),...wo.map(m=>({label:m,templates:x.filter(V=>V.category===m&&(D||!V.common))}))].filter(m=>m.templates.length>0):[{label:"Aggregate",templates:x}];return/* @__PURE__ */l(is,{open:c,onOpenChange:m=>{i(m),m||h("");},children:[/* @__PURE__ */t(ds,{asChild:!0,children:/* @__PURE__ */l(K,{type:"button",variant:"outline",size:"xs",disabled:d||w&&(o||!n),className:"gap-1.5",children:["Templates",/* @__PURE__ */t(Qe,{className:"h-3 w-3","aria-hidden":!0})]})}),/* @__PURE__ */l(cs,{align:"end",className:"w-[340px] p-0",onCloseAutoFocus:m=>m.preventDefault(),children:[/* @__PURE__ */t("div",{className:"sticky top-0 z-10 border-b bg-popover p-2",onKeyDown:m=>{["Escape","ArrowDown","ArrowUp"].includes(m.key)||m.stopPropagation();},children:/* @__PURE__ */l("div",{className:"relative",children:[/* @__PURE__ */t(us,{className:"pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground","aria-hidden":!0}),/* @__PURE__ */t(Be,{autoFocus:!0,size:"xs",value:u,onChange:m=>h(m.target.value),placeholder:"Search templates","aria-label":"Search templates",className:"pl-7"})]})}),/* @__PURE__ */t("div",{className:"max-h-[360px] overflow-y-auto p-1",children:y.length===0?/* @__PURE__ */t("p",{className:"px-2 py-6 text-center text-[12px] text-muted-foreground",children:"No templates found"}):y.map((m,V)=>/* @__PURE__ */l("div",{children:[V>0?/* @__PURE__ */t(ms,{}):null,/* @__PURE__ */t(ps,{children:m.label}),m.templates.map(L=>/* @__PURE__ */l(fs,{onSelect:J=>{J.preventDefault(),L.select(),h(""),i(!1);},className:"flex items-start justify-between gap-3 py-2",children:[/* @__PURE__ */l("div",{className:"min-w-0 flex-1",children:[/* @__PURE__ */l("div",{className:"flex items-center gap-2",children:[/* @__PURE__ */t("span",{className:"font-mono text-[12px] text-muted-foreground",children:L.symbol}),/* @__PURE__ */t("span",{className:"text-[12px] font-medium",children:L.label})]}),/* @__PURE__ */t("div",{className:"mt-0.5 truncate font-mono text-[11px] text-muted-foreground",children:L.preview})]}),L.hint?/* @__PURE__ */t("span",{className:"shrink-0 text-[10px] text-muted-foreground",children:L.hint}):null]},L.id))]},m.label))})]})]});}const So="Calculated fields";function Do(e){var r;if(e.kind==="inline"){const a=(r=e.entityName)==null?void 0:r.trim();if(a)return`${a} dataset`;}return So;}function To({inlineAnalysis:e,hasInputFields:r=!0}){const a=[];return r&&(a.push({label:"Uses",value:hs(e.kind)}),a.push({label:"Stored with",value:Do(e)})),a;}function Eo(e){const r=To(e);return r.length===0?null:/* @__PURE__ */t("div",{className:"flex items-center gap-3 border-t bg-muted/40 px-5 py-2","data-testid":"calculated-field-summary-ribbon",children:/* @__PURE__ */t("div",{className:"flex flex-wrap items-center gap-1.5",children:r.map(a=>/* @__PURE__ */l("span",{className:"inline-flex items-baseline gap-1.5 rounded-[4px] border bg-background px-1.5 py-0.5 text-[11px]",children:[/* @__PURE__ */t("span",{className:"text-[9px] font-medium uppercase tracking-[0.06em] text-muted-foreground/80",children:a.label}),/* @__PURE__ */t("span",{className:"text-foreground",children:a.value})]},a.label))})});}function Io(e){var n;const r=ea(e,"AI generation failed"),a=(n=kn(e))==null?void 0:n[0];return a?a.hint?`${a.message} Hint: ${a.hint}`:a.message||r:r;}function Lo({endpoint:e,availableFields:r,fieldType:a,dialect:n}){const{authToken:o}=Nt(),[d,c]=U(!1),[i,u]=U(null),h=j(async v=>{var D;if(!e)return u("AI generation is not available"),null;if(!v.trim())return u("Describe what you want to calculate"),null;c(!0),u(null);try{const x={type:"calculated-field-expression",context:{userQuery:v,availableFields:r.map(m=>({name:m.tokenLabel,dataType:m.dataType,...(m.role==="metric"||m.role==="groupby"?{role:m.role}:{})})),fieldType:a},options:{dialect:n}},y=await Zr(e,(o==null?void 0:o.accessToken)||"",x);if(!y.success||!((D=y.result)!=null&&D.generated))throw new Error(y.error||"No expression generated");return{generated:y.result.generated,explanation:y.result.explanation};}catch(x){return u(Io(x)),null;}finally{c(!1);}},[e,r,a,n,o==null?void 0:o.accessToken]),w=j(()=>u(null),[]);return{generateExpression:h,isGenerating:d,error:i,resetError:w};}const Ao=e=>e.entityName===_e||e.qualifiedEntityName===_e||e.entityName===vt?"Calculated Fields":e.qualifiedEntityName?Tr(e.entityName||e.qualifiedEntityName):Tr(e.entityName||"Other");function Ro(e){return e.entityName===_e||e.qualifiedEntityName===_e||e.entityName===vt?_e:e.qualifiedEntityName||e.entityName||"Other";}function Oo(e){return e.role!=="metric"?!1:e.fieldScope==="domain"||e.fieldScope==="dashboard"||e.fieldScope==="card"||e.entityName===vt||e.entityName===_e||e.qualifiedEntityName===_e;}function zo(e,r){const a=new Set((r||[]).map(n=>Sr(n)));return e.filter(n=>{const o=Sr(n.id);return!(o&&a.has(o));});}function $o(e){const r=/* @__PURE__ */new Map(),a=/* @__PURE__ */new Map();return e.forEach(n=>{let d=n.entityName&&n.entityName!==vt?`${n.entityName}.${n.name}`:n.name;const c=d.toLowerCase(),i=a.get(c)||0;i>0&&(d=`${d} ${i+1}`),a.set(c,i+1),r.set(n.id,d);}),r;}function Vo(e,r,a,n){return r==="dimension"?e.map(o=>({...o,isCompatible:!Oo(o)})).filter(o=>n):r!=="metric"?e.map(o=>({...o,isCompatible:!0})):e.map(o=>({...o,isCompatible:!0}));}function _o(e,r){if(!r)return e;const a=Dr(r);return e.filter(n=>Cn(n,r)||Dr(n.tokenLabel).includes(a));}function Fo(e){const r=/* @__PURE__ */new Map();return e.forEach(a=>{var o;const n=Ro(a);r.has(n)||r.set(n,{id:n,label:Ao(a),fields:[]}),(o=r.get(n))==null||o.fields.push(a);}),Array.from(r.values());}function Mo({fields:e,mode:r,searchTerm:a,excludeFieldIds:n,selectedAggregate:o,showIncompatible:d}){const c=P(()=>zo(e,n),[e,n]),i=P(()=>$o(c),[c]),u=P(()=>c.map(y=>{const m=Jr(y),V=y.role==="metric"&&es(y)||y.role==="groupby"&&ts(y);return{...y,baseLabel:m,tokenLabel:i.get(y.id)||m,isCalculated:V,isCompatible:!0};}),[c,i]),h=P(()=>Vo(u,r,o,d),[u,r,o,d]),w=P(()=>_o(h,a),[h,a]),v=P(()=>h.filter(y=>y.isCompatible),[h]),D=P(()=>Zt(v),[v]),x=P(()=>Fo(w),[w]);return{allFields:u,filteredFields:w,groups:x,tokenCandidates:D,tokenFields:v};}const qo=e=>Ue(e.dataType||"")==="number",jr=e=>qo(e)?"SUM":"COUNT",Go=e=>{if(e.role==="metric"){const a=e;return{...a,aggregate:a.aggregate||jr(e)};}const r=jr(e);return{...e,role:"metric",aggregate:r,alias:`${(e.alias||e.name).toLowerCase()}_${r.toLowerCase()}`};},Bo=(e,r)=>{var n;const a=e.trim();if(a){if(/\bDATE_TRUNC\b/i.test(a))return"date";if(/\bTIMESTAMP\b/i.test(a))return"datetime";if(/\bDATE\b/i.test(a)&&!/\bUPDATE\b/i.test(a))return"date";if(/['"]/.test(a))return"string";if(/[+\-*/]/.test(a))return"number";if(r.length===1)return Ue(((n=r[0])==null?void 0:n.dataType)||"");}};function Uo({expression:e,availableFields:r,validationEndpoint:a,connectionId:n,dialect:o,fieldType:d,outputType:c,validationContext:i}){const{authToken:u}=Nt(),[h,w]=U(null),[v,D]=U(!1),[x,y]=U(null),m=P(()=>Zt(r),[r]),V=P(()=>wa(e).map(M=>{const te=m.get(tt(M))||[];return{token:M,field:te.length===1?te[0]:null};}),[e,m]),L=j(($,M)=>{const te=[{code:"SQL_VALIDATION_ERROR",message:$,suggestion:(M==null?void 0:M.suggestion)||(M==null?void 0:M.errorCode)}];return{isValid:!1,tokens:V,errors:te,warnings:[]};},[V]),J=j(async()=>{var g;y(null);const $=a==null?void 0:a.trim();if(!$){const C=L("Validation endpoint is not configured");return w(C),C;}if(!!!(i!=null&&i.cardConfig&&i!=null&&i.cardDataSource&&i!=null&&i.cardId&&(i!=null&&i.connectionId||n))){const C=L("Validation context is incomplete for server-side validation");return w(C),C;}const{orderedTokens:te,orderedFields:p}=ut(e,r),A=[],I=[];te.forEach((C,R)=>{const F=p[R];F&&(A.push(C),I.push(F));});const E=d==="metric"?I.map(Go):I,N=Bo(e,I),b=Bt(e,A),T={type:"calculated-field-expression",fieldType:d,expression:b,inputFields:E,outputType:c,options:{validateWithExplain:!0},context:{connectionId:(i==null?void 0:i.connectionId)||n,cardId:i==null?void 0:i.cardId,cardConfig:i==null?void 0:i.cardConfig,cardDataSource:i==null?void 0:i.cardDataSource,activeFilters:(i==null?void 0:i.activeFilters)||[],cardType:(i==null?void 0:i.cardType)||"table",dialect:o}};D(!0);try{const C=await Zr($,(u==null?void 0:u.accessToken)||"",T),R=C==null?void 0:C.status,F=C==null?void 0:C.error,W=C==null?void 0:C.errorCode,B=[],ee=[];R==="invalid"?B.push({code:"SQL_VALIDATION_ERROR",message:F||"Expression failed SQL validation",suggestion:W?`Validation code: ${W}`:void 0}):R==="unverified"?ee.push({code:"EXECUTION_UNVERIFIED",message:F||"Execution could not be fully verified in this environment.",suggestion:"Syntax checks passed. This expression may still run successfully."}):R!=="valid"&&B.push({code:"SQL_VALIDATION_ERROR",message:F||"Unexpected SQL validation response from server",suggestion:W?`Validation code: ${W}`:void 0});const ae={isValid:(R==="valid"||R==="unverified")&&B.length===0,tokens:V,errors:B,warnings:ee,inferredDataType:(C==null?void 0:C.inferredDataType)??((g=C==null?void 0:C.metadata)==null?void 0:g.inferredDataType)??N??c??void 0};return w(ae),ae;}catch(C){const R=(C==null?void 0:C.error)||(C==null?void 0:C.message)||"Expression validation failed";y(R);const F=L(R);return w(F),F;}finally{D(!1);}},[a,i,n,e,r,d,c,o,u==null?void 0:u.accessToken,L,V]),_=j(()=>{w(null),y(null);},[]);return{validationResult:h,isValidating:v,serverError:x,validateExpression:J,resetValidation:_};}function jo({endpoint:e,connectionId:r,enabled:a=!0}){var u;const{authToken:n,authorizationScope:o}=Nt(),d=a&&!!(e&&r),c=gs({queryKey:["calculated-field-template-defaults",e,r,o],enabled:d,queryFn:async({signal:h})=>{if(!e||!r)throw new Error("Calculated-field templates are not available");const w={connectionId:r};return await Sn(e,(n==null?void 0:n.accessToken)||"","POST",w,h);},staleTime:5*60*1e3}),i=a?e?r?null:"Select a data source before using a template":"Calculated-field templates are not available":null;return{templates:(u=c.data)==null?void 0:u.templates,isLoading:d&&c.isPending,error:i||(c.error?ea(c.error,"Templates could not be loaded"):null)};}const Mt=(e,r)=>e.start===r.start&&e.end===r.end&&e.token===r.token;function Po({expression:e,onExpressionChange:r,tokenCandidates:a,textareaId:n,editorRef:o,interactive:d}){const c=P(()=>Br(e),[e]),i=P(()=>Ur(c,a),[c,a]),u=P(()=>c.map(T=>({start:T.start,end:T.end,tone:ka(T.token,a)?"field":"pending"})),[c,a]),[h,w]=U(null),v=d&&h?i.find(T=>Mt(T,h))??null:null,D=v?c.findIndex(T=>Mt(T,v)):-1,x=j(()=>typeof document<"u"?document.getElementById(n):null,[n]),y=he(D);y.current=D;const m=he(null),V=he({getBoundingClientRect:()=>{var C,R;const T=y.current,g=T>=0?((C=o.current)==null?void 0:C.getChipRect(T))??null:null;return g&&(m.current=g),g??m.current??((R=x())==null?void 0:R.getBoundingClientRect())??new DOMRect();}}),L=he(null),J=j(T=>{var g;d&&(w(T),(g=x())==null||g.setSelectionRange(T.start,T.end));},[x,d]),_=j(T=>{const g=c[T],C=g&&i.find(R=>Mt(R,g));C&&J(C);},[J,i,c]),$=j(T=>{if(T.key!=="Tab"||T.shiftKey||!d||i.length===0)return;T.preventDefault();const g=T.currentTarget,C=i.findIndex(R=>R.start===g.selectionStart&&R.end===g.selectionEnd);J(i[C===-1?0:(C+1)%i.length]);},[d,J,i]),M=j(T=>{if(!v)return;const g=`{${T.tokenLabel}}`,C=e.slice(0,v.start)+g+e.slice(v.end);r(C);const R=i.indexOf(v),F=Ur(Br(C),a);if(F.length>0){const B=F[Math.min(R,F.length-1)];w(B),requestAnimationFrame(()=>{var ee;return(ee=x())==null?void 0:ee.setSelectionRange(B.start,B.end);});return;}const W=v.start+g.length;L.current={start:W,end:W},w(null);},[v,e,x,r,i,a]),te=j(()=>{L.current=v,w(null);},[v]),p=j(()=>{L.current=null,w(null);},[]),A=j(T=>{T.preventDefault();const g=L.current;if(L.current=null,!g)return;const C=x();C==null||C.focus(),C==null||C.setSelectionRange(g.start,g.end);},[x]),[I,E]=U(null);je(()=>{if(!I)return;E(null);const T=i.find(C=>C.start>=I.start&&C.end<=I.end);if(T&&d){J(T);return;}const g=x();g==null||g.focus(),g==null||g.setSelectionRange(I.end,I.end);},[x,I,d,J,i]);const N=j(()=>{L.current=null,w(null),E(null);},[]),b=i.filter(T=>bt(T.token)).length;return{chips:u,activeChipIndex:D>=0?D:null,onChipClick:_,onEditorKeyDown:$,openFirstIn:E,reset:N,summary:{placeholders:b,unresolved:i.length-b},picker:{token:(v==null?void 0:v.token)??null,remaining:i.length,anchorRef:V,onPick:M,onEscape:te,onDismiss:p,onCloseAutoFocus:A}};}function Ko(e){var r;return(e==null?void 0:e.type)==="organization"?!0:(e==null?void 0:e.type)==="tenant"&&((r=e.permissions)==null?void 0:r.canEdit)===!0;}function Wo({status:e}){return/* @__PURE__ */l("div",{className:"rounded-control border border-border bg-muted/40 px-3 py-2 text-xs text-muted-foreground","data-testid":"domain-definition-status",children:[/* @__PURE__ */t("p",{className:"font-medium text-foreground",children:"Governed domain calculation"}),/* @__PURE__ */t("p",{children:e==="effective"?"This is the current effective domain formula. Saved visuals resolve it again when they run.":e==="loading"?"The domain catalog is still loading. This saved formula is not verified as current.":e==="unavailable"?"The domain catalog is unavailable. This saved formula is not verified as current.":"This saved formula could not be matched to the current domain catalog and is not verified as current. Reselect the field to repair it."})]});}const qt=[{value:"string",label:"String"},{value:"number",label:"Number"},{value:"boolean",label:"Boolean"},{value:"date",label:"Date"},{value:"datetime",label:"Datetime"},{value:"json",label:"JSON"},{value:"geo",label:"Geo"}],Qo=[],Ho="SUM({revenue}) / NULLIF(COUNT({order_id}), 0)",Yo="DATE_TRUNC('month', {created_at})";function _l({open:e,onOpenChange:r,availableFields:a,unavailableFieldReasons:n,existingField:o,existingFieldScope:d,domainDefinitionStatus:c,onSave:i,onSaveToDashboard:u,cardId:h,initialFieldType:w="metric",allowedFieldTypes:v,source:D,inline:x=!1}){var vr,Nr,wr,kr,Cr;const{tokenProps:y}=Nt(),m=((Nr=(vr=y.config)==null?void 0:vr.projectFeatures)==null?void 0:Nr.features.aiWritingHelpers)!==!1,{selectedConnection:V,connections:L}=bs(),J=Se(f=>{var G;return(G=f.card)==null?void 0:G.config;}),_=Se(f=>{var G;return(G=f.card)==null?void 0:G.dataSource;}),$=Se(f=>{var G;return(G=f.card)==null?void 0:G.type;}),M=D?(L??[]).find(f=>f.id===D.connectionId):V,te=D?D.config:J,p=D?D.dataSource:_,A=D?D.cardType:$,I=Me(f=>f.dashboard),E=Me(f=>f.dashboardInputValues),N=Me(f=>f.adHocFilterValues),b=Me(f=>f.selectedSheetId),T=Me(f=>{var G;return((G=f.reportContext)==null?void 0:G.calendar)??null;}),g=P(()=>I?so({dashboard:I,runtimeValues:{dashboardInputValues:E},adHocFilterValues:N,sheetId:b,sheetKind:"dashboard",calendar:T}):Qo,[N,I,E,T,b]),C=d==="domain",[R,F]=U(w),[W,B]=U(""),[ee,ae]=U(""),oe=C?(o==null?void 0:o.role)==="metric"?"metric":"dimension":R,ge=C?(o==null?void 0:o.label)||(o==null?void 0:o.name)||"":W,[De,ye]=U(null),Te=C?((wr=qt.find(f=>f.value===(o==null?void 0:o.dataType)))==null?void 0:wr.value)||null:De,[rt,Ne]=U("card"),at=C?"domain":rt,[ue,me]=U({}),[Pe,Ee]=U(""),[be,s]=U(!1),[S,k]=U(""),[O,q]=U(""),[Q,z]=U(void 0),[X,re]=U(null),[Z,pe]=U(!1),[fe,Ie]=U(!1),[Aa,nt]=U(null),wt=C?null:Aa,Ke=Xn(),ar=he(null),kt=he(!1),Ct=he(null),{userContext:Ra}=xs(),st=P(()=>a.filter(f=>f.fieldScope==="domain"&&!!f.expression),[a]),nr=P(()=>st.filter(f=>f.role==="metric"),[st]),sr=P(()=>st.filter(f=>f.role==="groupby"),[st]),Oa=!Ko(Ra),or=!!wt,se=Oa||or||C,ot=!!u?"dashboard":"card",Fe=(kr=y==null?void 0:y.apiServiceUrl)==null?void 0:kr.replace(/\/$/,""),za=Fe?`${Fe}/v1/calculated-fields/validate`:"/v1/calculated-fields/validate",$a=Fe?`${Fe}/v1/calculated-fields/templates/resolve`:"/v1/calculated-fields/templates/resolve",lr=Fe?`${Fe}/v1/ai/generate`:"/v1/ai/generate",Va=P(()=>{var Y;const f=[...a];return(((Y=o==null?void 0:o.calculatedFormula)==null?void 0:Y.inputFields)||[]).forEach(ne=>{f.some(ie=>ie.id===ne.id||ie.qualifiedFieldName===ne.qualifiedFieldName||ie.name===ne.name)||f.push(ne);}),f;},[a,o]),{tokenFields:_a,tokenCandidates:Fa,groups:ir}=Mo({fields:Va,mode:oe,excludeFieldIds:o?[o.id]:void 0,selectedAggregate:void 0,showIncompatible:!0}),we=_a,St=j((f,G)=>f.replace(/\{field_(\d+)\}/g,(Y,ne)=>{var Re;const le=G[Number(ne)];return le?`{${((Re=we.find(Ot=>Ot.id===le.id))==null?void 0:Re.tokenLabel)||le.label||le.name}}`:Y;}),[we]),xe=C?St((o==null?void 0:o.expression)||"",((Cr=o==null?void 0:o.calculatedFormula)==null?void 0:Cr.inputFields)||[]):ee,Le=Po({expression:xe,onExpressionChange:ae,tokenCandidates:Fa,textareaId:Ke,editorRef:ar,interactive:!se&&!be}),{reset:dr,openFirstIn:cr}=Le,{placeholders:Dt,unresolved:Tt}=Le.summary,ur=[Dt?`${Dt} ${Dt===1?"field":"fields"} to choose`:null,Tt?`${Tt} ${Tt===1?"field":"fields"} not found`:null].filter(Boolean).join(" · "),{generateExpression:mr,isGenerating:pr,error:Ma,resetError:ke}=Lo({endpoint:lr,availableFields:we,fieldType:oe,dialect:M==null?void 0:M.dialect}),qa=pr?"loading":O?"result":"prompt",{validationResult:lt,validateExpression:fr,isValidating:hr,serverError:Ga,resetValidation:Ce}=Uo({expression:xe,availableFields:we,validationEndpoint:za,connectionId:M==null?void 0:M.id,dialect:M==null?void 0:M.dialect,fieldType:oe,outputType:Te||void 0,validationContext:{connectionId:(M==null?void 0:M.id)||(p==null?void 0:p.connectionId),cardId:h,cardConfig:te||{},cardDataSource:p||null,activeFilters:g,cardType:A}}),Ba=(M==null?void 0:M.id)||(p==null?void 0:p.connectionId),{templates:Ua,isLoading:ja,error:gr}=jo({endpoint:$a,connectionId:Ba,enabled:e&&oe==="dimension"&&!se}),Et=lt==null?void 0:lt.inferredDataType,br=Te||Et||"string",It=j(()=>{s(!1),k(""),q(""),z(void 0),ke();},[ke]),Pa=j(()=>{se||!m||(q(""),z(void 0),ke(),s(!0));},[m,se,ke]),Ka=j(async()=>{if(!S.trim())return;const f=await mr(S);f&&(q(f.generated),z(f.explanation));},[S,mr]),Wa=j(()=>{q(""),z(void 0),ke();},[ke]),Qa=j(()=>{O.trim()&&(ae(O),Ce(),It());},[O,It,Ce]),We=P(()=>{const{orderedFields:f}=ut(xe,we);return f.filter(G=>!!G);},[we,xe]),Ae=P(()=>Dn(We),[We]),Ha=P(()=>{if(!ge.trim())return!1;const f=Tn(ge);return ys({fields:oe==="metric"?nr:sr,normalizedName:f,existingFieldId:d==="domain"?o==null?void 0:o.id:void 0,targetKind:Ae.kind==="inline"?"inline":"root",targetEntityName:Ae.kind==="inline"?Ae.entityName:void 0,targetQualifiedEntityName:Ae.kind==="inline"?Ae.qualifiedEntityName:void 0});},[Ae,sr,nr,o,d,oe,ge]),Ya=P(()=>We.map(f=>f.id),[We]),Xa=f=>{se||o||f!==oe&&F(f);},it=j(()=>{B(""),ae(""),ye(null),Ne("card"),me({}),Ee(""),s(!1),k(""),q(""),z(void 0),nt(null),re(null),pe(!1),Ce(),ke(),dr(),r(!1);},[r,Ce,ke,dr]),Lt=j(f=>{var ne;const G=((ne=f.calculatedFormula)==null?void 0:ne.inputFields)||[],Y=f.role==="metric"?vs(f):f.expression||"";ae(St(Y,G));},[St]);je(()=>{if(!e||C){kt.current=!1,Ct.current=null;return;}const f=o?`${o.role}-${o.id||o.name}`:"new";if(kt.current&&Ct.current===f)return;if(kt.current=!0,Ct.current=f,me({}),Ee(""),Ce(),o){if(o.role==="metric"){const le=Ns(o);F("metric"),B(o.label||o.name),Ne(d||"card"),nt(le.reason||null),Lt(o),ye(null);return;}nt(null),F("dimension");const Y=o;B(Y.label||Y.name),Ne(d||"card"),Lt(Y);const ne=qt.some(le=>le.value===Y.dataType)?Y.dataType:"string";ye(ne);return;}const G=v&&v.length>0?v.includes(w)?w:v[0]:w;F(G),B(""),ae(""),ye(null),nt(null),Ne(ot);},[ot,e,C,o,d,w,v,Lt,Ce]);const At=j((f,{restoreCaret:G=!0}={})=>{const Y=typeof document<"u"?document.getElementById(Ke):null;if(!Y){const ie=ee.length;return ae(Re=>Re+f),{start:ie,end:ie+f.length};}const ne=Y.selectionStart||0,le=Y.selectionEnd||0;return ae(ie=>`${ie.slice(0,ne)}${f}${ie.slice(le)}`),G&&requestAnimationFrame(()=>{Y.focus();const ie=ne+f.length;Y.setSelectionRange(ie,ie);}),{start:ne,end:ne+f.length};},[ee.length,Ke]),Rt=j(f=>{cr(At(f,{restoreCaret:!1}));},[At,cr]),Ja=f=>{if(se)return;const G=f.tokenLabel||f.label||f.name;At(`{${G}}`);},Za=f=>{se||Rt(f);},en=j(f=>{se||(Rt(f.expression),ye(f.outputType),Ce());},[Rt,se,Ce]),tn=async()=>{const f={};return ge.trim()||(f.name="Name is required"),xe.trim()||(f.expression="Expression is required"),f.expression||(await fr()).isValid||(f.expression="Fix validation errors before saving"),me(f),Object.keys(f).length===0;},rn=()=>{const{orderedTokens:f,orderedFields:G}=ut(xe,we),Y=G.filter(ie=>!!ie),ne=Bt(xe,f),le=Er({kind:"dimension",name:ge,expression:ne,inputFields:Y,dataType:br,cardId:h,existingId:o==null?void 0:o.id});return o&&o.role==="groupby"?{...o,...le}:le;},an=()=>{const{orderedTokens:f,orderedFields:G}=ut(xe,we),Y=G.filter(Ot=>!!Ot),ne=Bt(xe,f),le=En(o,ne)==="row",ie=le?Y:In(Y,(o==null?void 0:o.role)==="metric"?o:void 0),Re=Er({kind:"measure",name:ge,expression:ne,inputFields:ie,cardId:h,existingId:o==null?void 0:o.id,...(le?{stage:"row"}:{}),...(!le&&Ln(o)?{asWritten:!0}:{})});return o&&o.role==="metric"?_s(o,Re):Re;},xr=async f=>{if(f==="domain"){me(Y=>({...Y,scope:"Domain scope is not available in this explorer."}));return;}const G=oe==="dimension"?rn():an();if(f==="dashboard"){if(!u){me(Y=>({...Y,scope:"Dashboard scope is not available"}));return;}await u(G),it();return;}await i(G),it();},nn=async()=>{if(se||(me({}),!(await tn())))return;const f=o?at:ot;if(oe==="metric"&&f!=="domain"&&Ha&&!o){re(f),pe(!0);return;}Ie(!0);try{await xr(f);}catch(G){me(Y=>({...Y,scope:G instanceof Error?G.message:"The calculated field could not be saved."}));}finally{Ie(!1);}},sn=oe==="metric"?Ho:Yo,on=oe==="metric"?"Metric formula":"Column expression",ln=v||["metric","dimension"],dn=x?Xo:ws,cn=x?Jo:ks,un=x?Zo:Cs,mn=x?el:Ds,yr=/* @__PURE__ */l(de,{children:[/* @__PURE__ */l(dn,{className:"space-y-0 border-b py-3 pl-5 pr-12",children:[/* @__PURE__ */t(cn,{className:"text-[13px] font-medium",children:o?"Edit calculated field":"New calculated field"}),/* @__PURE__ */t(un,{className:"sr-only",children:"Build a calculated dimension or metric using expressions."})]}),/* @__PURE__ */l("div",{className:H("flex min-h-0 flex-col gap-4 overflow-y-auto px-5 py-4",x?"flex-1":"max-h-[calc(80vh-180px)]"),children:[C&&/* @__PURE__ */t(Wo,{status:c||"unverified"}),wt&&/* @__PURE__ */l("div",{className:"rounded-control border border-border bg-muted/40 px-3 py-2 text-xs text-muted-foreground",children:[/* @__PURE__ */t("p",{className:"font-medium text-foreground",children:"Read-only legacy metric"}),/* @__PURE__ */t("p",{children:wt})]}),/* @__PURE__ */l("div",{className:"grid grid-cols-[120px_1fr] items-center gap-3",children:[/* @__PURE__ */t(ce,{htmlFor:"calculated-name",className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Name"}),/* @__PURE__ */t(Be,{id:"calculated-name",value:ge,onChange:f=>B(f.target.value),placeholder:"Field name","aria-invalid":!!ue.name,size:"xs",className:`max-w-sm ${ue.name?"border-destructive":""}`,disabled:se}),ue.name&&/* @__PURE__ */t("p",{className:"col-start-2 text-xs text-destructive",children:ue.name})]}),/* @__PURE__ */l("div",{className:"grid grid-cols-[120px_1fr] items-center gap-3",children:[/* @__PURE__ */t(ce,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Type"}),/* @__PURE__ */t(po,{value:oe,onChange:Xa,disabled:se||!!o,options:ln}),/* @__PURE__ */t("p",{className:"col-start-2 text-[11px] text-muted-foreground",children:Ss(oe)})]}),/* @__PURE__ */l("div",{className:"space-y-1.5",children:[/* @__PURE__ */l("div",{className:"flex items-center justify-between gap-3",children:[/* @__PURE__ */t("div",{className:"flex items-center gap-2 whitespace-nowrap",children:/* @__PURE__ */t(ce,{htmlFor:Ke,className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:on})}),/* @__PURE__ */l("div",{className:"flex items-center gap-1.5",children:[/* @__PURE__ */t(xo,{groups:ir,searchTerm:Pe,onSearchTermChange:Ee,onFieldSelect:Ja,selectedFieldIds:Ya,unavailableFieldReasons:n,disabled:se||be}),/* @__PURE__ */t(Co,{fieldType:oe,onInsert:Za,onInsertRowTemplate:en,rowTemplates:Ua,rowTemplatesLoading:ja,disabled:se||be}),!!lr&&m&&!se&&/* @__PURE__ */l(K,{type:"button",variant:be?"default":"outline",size:"xs",onClick:Pa,disabled:be,className:"gap-1.5",children:[/* @__PURE__ */t(Ut,{className:"h-3 w-3","aria-hidden":!0}),be?"Composing…":"Generate"]})]})]}),gr?/* @__PURE__ */t("p",{className:"text-[11px] text-destructive",role:"alert",children:gr}):null,be?/* @__PURE__ */t(bo,{mode:qa,fieldType:oe,prompt:S,onPromptChange:k,generated:O,explanation:Q,isGenerating:pr,error:Ma,onGenerate:()=>void Ka(),onTryAgain:Wa,onCancel:It,onUseDraft:Qa}):/* @__PURE__ */l(de,{children:[/* @__PURE__ */t("div",{"aria-invalid":!!ue.expression,className:`overflow-hidden rounded-control border ${ue.expression?"border-destructive":"border-input"}`,children:/* @__PURE__ */t("div",{className:"h-[112px]",children:/* @__PURE__ */t(Yr,{ref:ar,value:xe,onValueChange:ae,language:"sql-jinja",placeholder:sn,ariaLabel:oe==="metric"?"Metric formula":"Column expression",textareaId:Ke,readOnly:se,embedded:!0,hideLineNumbers:!0,wrapLines:!0,dense:!0,chips:Le.chips,activeChipIndex:Le.activeChipIndex,onChipClick:Le.onChipClick,onKeyDown:Le.onEditorKeyDown})})}),/* @__PURE__ */t(vo,{...Le.picker,groups:ir,unavailableFieldReasons:n}),!se&&ur?/* @__PURE__ */l("p",{className:"flex items-center gap-1.5 text-[11px] text-muted-foreground",children:[/* @__PURE__ */t(io,{className:"h-3 w-3","aria-hidden":!0}),ur,". Click a dashed field or press Tab."]}):null,/* @__PURE__ */t(ho,{onValidate:fr,isValidating:hr,validationResult:lt,error:Ga,disabled:se}),ue.expression&&/* @__PURE__ */t("p",{className:"text-xs text-destructive",children:ue.expression})]})]}),oe==="dimension"&&/* @__PURE__ */l("div",{className:"grid grid-cols-[120px_1fr] items-center gap-3",children:[/* @__PURE__ */t(ce,{htmlFor:"calculated-output-type",className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Output type"}),/* @__PURE__ */l(Oe,{value:br,onValueChange:f=>ye(f),disabled:se,children:[/* @__PURE__ */t(ze,{id:"calculated-output-type",size:"xs",className:"w-44",children:/* @__PURE__ */t($e,{placeholder:"Select output type"})}),/* @__PURE__ */t(Ve,{children:qt.map(f=>/* @__PURE__ */t(ve,{value:f.value,children:f.label},f.value))})]}),Et&&!Te&&/* @__PURE__ */l("p",{className:"col-start-2 text-[11px] text-muted-foreground",children:["Suggested type: ",Et]})]}),/* @__PURE__ */l("div",{className:"grid grid-cols-[120px_1fr] items-center gap-3",children:[/* @__PURE__ */t(ce,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Availability"}),/* @__PURE__ */t("span",{className:"text-[12px] text-foreground",children:_r(o?d||"card":ot)}),ue.scope&&/* @__PURE__ */t("p",{className:"col-start-2 text-xs text-destructive",children:ue.scope})]})]}),/* @__PURE__ */t(Eo,{inlineAnalysis:Ae,hasInputFields:We.length>0}),/* @__PURE__ */l(mn,{className:"gap-1.5 border-t px-5 py-2.5",children:[/* @__PURE__ */t(K,{variant:"outline",size:"xs",onClick:it,disabled:fe,children:"Cancel"}),/* @__PURE__ */t(K,{size:"xs",onClick:()=>void nn(),disabled:fe||hr||se,children:fe?/* @__PURE__ */l(de,{children:[/* @__PURE__ */t(Xt,{className:"mr-1.5 h-3 w-3 animate-spin"}),"Applying…"]}):or||C?"Read-only":"Apply"})]})]});return/* @__PURE__ */l(de,{children:[x?e?/* @__PURE__ */t("div",{className:"flex h-full min-h-0 flex-col",children:yr}):null:/* @__PURE__ */l(Ts,{modal:!1,open:e,onOpenChange:f=>{f?r(!0):it();},children:[e&&/* @__PURE__ */t("div",{className:"pointer-events-none fixed inset-0 z-40 bg-background/80 backdrop-blur-sm"}),/* @__PURE__ */t(Es,{className:"max-w-3xl max-h-[90vh] gap-0 overflow-hidden p-0",onInteractOutside:f=>{f.preventDefault();},children:yr})]}),/* @__PURE__ */t(Is,{open:Z,onOpenChange:pe,children:/* @__PURE__ */l(Ls,{children:[/* @__PURE__ */l(As,{children:[/* @__PURE__ */t(Rs,{children:"Name conflict"}),/* @__PURE__ */l(Os,{children:['A domain metric named "',ge.trim(),'" already exists. Your local version will override it for the selected availability:'," ",_r(X||"card"),". Continue?"]})]}),/* @__PURE__ */l(zs,{children:[/* @__PURE__ */t($s,{onClick:()=>{re(null);},children:"Choose different name"}),/* @__PURE__ */t(Vs,{onClick:async()=>{if(X){pe(!1),Ie(!0);try{await xr(X);}catch(f){me(G=>({...G,scope:f instanceof Error?f.message:"The calculated field could not be saved."}));}finally{Ie(!1),re(null);}}},children:"Continue"})]})]})})]});}function Xo({className:e,...r}){return/* @__PURE__ */t("div",{className:H("flex flex-col",e),...r});}function Jo(e){return/* @__PURE__ */t("h2",{...e});}function Zo(e){return/* @__PURE__ */t("p",{...e});}function el({className:e,...r}){return/* @__PURE__ */t("div",{className:H("flex shrink-0 items-center justify-end",e),...r});}function Fl({type:e,isLinked:r,className:a,showLabel:n=!1,showLocal:o=!1}){const d=Me(m=>m.selectedFrameId),c=Fs(m=>m.selectedVisual),i=Se(m=>m.frame);let u;if(e)u=e;else if(r!==void 0)u=r?"linked":"library";else if(!!!(i!=null&&i.visualId||c!=null&&c.id)&&d)u="local";else if(c&&!d)u="library";else if(i!=null&&i.visualId&&d)u="linked";else if(c!=null&&c.id&&d)u="library";else return null;if(u==="local"&&!o)return null;const h={local:"border-slate-200/70 bg-slate-50/80 text-slate-700 shadow-sm hover:bg-slate-100/80 dark:border-slate-700 dark:bg-slate-900/70 dark:text-slate-200 dark:hover:bg-slate-800/80",linked:"border-purple-200/70 bg-gradient-to-r from-purple-50/50 to-purple-100/30 text-purple-900 shadow-sm hover:from-purple-100/60 hover:to-purple-100/50 hover:shadow-md dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100 dark:hover:from-purple-950/60 dark:hover:to-purple-900/50",library:"border-blue-200/70 bg-gradient-to-r from-blue-50/50 to-blue-100/30 text-blue-900 shadow-sm hover:from-blue-100/60 hover:to-blue-100/50 hover:shadow-md dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100 dark:hover:from-blue-950/60 dark:hover:to-blue-900/50"},w={local:"Local to this dashboard: Changes made here only affect this dashboard copy.",linked:"Linked to library: Changes made here update the library visual and all linked instances.",library:"Library visual: Share and reuse this visual across multiple dashboards."},v={local:"border-slate-200 bg-slate-50 text-slate-900 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100",linked:"border-purple-200 bg-purple-50 text-purple-900 dark:border-purple-800 dark:bg-purple-950 dark:text-purple-100",library:"border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-800 dark:bg-blue-950 dark:text-blue-100"},D={local:"fill-slate-50 dark:fill-slate-900",linked:"fill-purple-50 dark:fill-purple-950",library:"fill-blue-50 dark:fill-blue-950"},x={local:/* @__PURE__ */t("span",{className:"h-2 w-2 rounded-full bg-current/70"}),linked:/* @__PURE__ */t(qs,{className:"h-3.5 w-3.5"}),library:/* @__PURE__ */t(co,{className:"h-3.5 w-3.5"})},y={local:"Local",linked:"Linked",library:"Library"};return/* @__PURE__ */t(Ht,{children:/* @__PURE__ */l(Ye,{delayDuration:300,children:[/* @__PURE__ */t(Xe,{asChild:!0,children:/* @__PURE__ */l(Ms,{variant:"outline",className:H("cursor-help select-none transition-all",h[u],a),children:[x[u],n&&/* @__PURE__ */t("span",{className:"ml-1 text-xs font-medium leading-none",children:y[u]})]})}),/* @__PURE__ */l(Yt,{side:"bottom",className:H("max-w-xs",v[u]),children:[/* @__PURE__ */t(Xr,{className:D[u]}),/* @__PURE__ */t("p",{children:w[u]})]})]})});}const tl=Jn(({side:e="bottom",children:r,className:a,tooltip:n,onClick:o,openDelay:d=300,buttonProps:c,disabled:i,...u},h)=>/* @__PURE__ */t(Ht,{children:/* @__PURE__ */l(Ye,{delayDuration:d,children:[/* @__PURE__ */t(Xe,{asChild:!0,children:/* @__PURE__ */t(K,{disabled:i,ref:h,size:"sm",variant:"ghost",onClick:o,...u,...c,className:H(`${An}`,a),children:r})}),n&&/* @__PURE__ */l(Yt,{side:e,sideOffset:10,className:H("border-foreground/20 bg-foreground text-background"),children:[n,/* @__PURE__ */t(Xr,{className:"fill-foreground"})]})]})}));tl.displayName="IconButton";function Ca(e){const{control:r,onChange:a}=e;return/* @__PURE__ */l("div",{className:"flex flex-col gap-1.5",children:[/* @__PURE__ */t(ce,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Label"}),/* @__PURE__ */t(Be,{size:"xs",value:r.label,placeholder:"Control label",onChange:n=>a(n.target.value)})]});}function rl(e){const{currentStep:r,labels:a}=e;return/* @__PURE__ */t("div",{className:"sticky top-0 z-10 -mx-1 border-b border-border/60 bg-background/95 px-1 pb-2.5 pt-1 backdrop-blur supports-[backdrop-filter]:bg-background/85",children:/* @__PURE__ */t("div",{className:"flex flex-wrap items-center gap-2 sm:gap-2.5",children:a.map((n,o)=>{const d=o+1,c=d===r,i=d<r;return/* @__PURE__ */l(Zn,{children:[/* @__PURE__ */l("div",{className:"flex items-center gap-1.5",children:[/* @__PURE__ */t("span",{className:H("flex h-5 w-5 items-center justify-center rounded-full border text-[10px] font-medium tabular-nums",c?"border-foreground bg-foreground text-background":i?"border-foreground/30 bg-foreground/10 text-foreground":"border-border/60 bg-background text-muted-foreground"),children:d}),/* @__PURE__ */t("span",{className:H("text-[12px]",c?"font-medium text-foreground":"text-muted-foreground"),children:n})]}),o<a.length-1?/* @__PURE__ */t("span",{className:"h-px w-4 bg-border/60 sm:w-6","aria-hidden":"true"}):null]},n);})})});}function xt(e){const{secondary:r,tertiary:a,primary:n}=e;return/* @__PURE__ */l("div",{className:"sticky bottom-0 z-10 -mx-1 flex justify-end gap-2 border-t bg-background/95 px-1 pb-1 pt-3 backdrop-blur supports-[backdrop-filter]:bg-background/85",children:[r,a,n]});}function al(e){const{control:r,scope:a,detail:n}=e;return/* @__PURE__ */l("div",{className:"flex items-start gap-2.5 rounded-control border border-border/60 bg-muted/30 px-3 py-2.5",children:[/* @__PURE__ */t(Qs,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-foreground"}),/* @__PURE__ */l("div",{className:"min-w-0 space-y-0.5",children:[/* @__PURE__ */t("div",{className:"text-[13px] font-medium text-foreground",children:r.label}),/* @__PURE__ */l("div",{className:"text-[12px] text-muted-foreground",children:[ta(r.type).label," ·"," ",aa(r)," ·"," ",ra(a,r.placement)]}),n?/* @__PURE__ */t("div",{className:"text-[12px] text-muted-foreground",children:n}):null]})]});}function Pr(e){const{control:r,defaultValue:a,availableFieldChoices:n,availableMetricChoices:o,previewControlDefinitions:d,previewControlValues:c,onControlChange:i,onLabelChange:u,onDefaultValueChange:h,onBack:w,onNext:v,nextDisabled:D}=e;return/* @__PURE__ */l("div",{className:"space-y-3",children:[/* @__PURE__ */t(Ca,{control:r,onChange:u}),/* @__PURE__ */t(ua,{control:r,availableFieldChoices:n,availableMetricChoices:o,previewControlDefinitions:d,previewControlValues:c,controlLifecycle:"create",onChange:i}),/* @__PURE__ */t(ma,{control:r,value:a,onChange:h,allowNoDefault:!0,allowCardDefault:!0,hint:"This is the value viewers will see first.",previewControlDefinitions:d,previewControlValues:c}),/* @__PURE__ */t(xt,{secondary:/* @__PURE__ */t(K,{type:"button",variant:"outline",size:"xs",onClick:w,children:"Back"}),primary:/* @__PURE__ */t(K,{type:"button",size:"xs",onClick:v,disabled:D,children:"Next"})})]});}const nl=/* @__PURE__ */new Set(["grain_selector","aggregation_selector","field_selector","metric_selector"]);function Kr(e){const{text:r,ariaLabel:a}=e,[n,o]=U(!1);return/* @__PURE__ */l("button",{type:"button","aria-label":a,onClick:async()=>{try{await navigator.clipboard.writeText(r),o(!0),setTimeout(()=>o(!1),1200);}catch(d){console.error("Failed to copy",d);}},className:"group flex w-full items-center justify-between gap-2 rounded-control bg-muted/40 px-2 py-1 text-left transition-colors hover:bg-muted/60 focus-visible:bg-muted/60 focus-visible:outline-none",children:[/* @__PURE__ */t("code",{className:"min-w-0 truncate font-mono text-[12px] text-foreground",children:r}),/* @__PURE__ */t("span",{className:"shrink-0 text-[11px] text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:n?"Copied":"Click to copy"})]});}function Wr(e){const{control:r,scope:a,createdReference:n,explorerContent:o,sqlDescription:d,summaryDetail:c,onBack:i,onCancel:u,onDone:h}=e,w=nl.has(r.type),v=n.match(/\[\[param\.(.+?)\]\]/),D=v?`{{ param('${v[1]}') }}`:"";return/* @__PURE__ */l("div",{className:"space-y-4",children:[/* @__PURE__ */t(al,{control:r,scope:a,detail:c}),/* @__PURE__ */l("div",{className:"space-y-2",children:[/* @__PURE__ */t("p",{className:"text-[13px] font-medium text-foreground",children:"How cards use this control"}),/* @__PURE__ */l("div",{className:"divide-y divide-border/60 overflow-hidden rounded-control border border-border/60",children:[w?/* @__PURE__ */l("div",{className:"space-y-1 px-3 py-2.5",children:[/* @__PURE__ */t("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Explorer cards"}),/* @__PURE__ */t("div",{className:"text-[12px] text-muted-foreground",children:o})]}):null,/* @__PURE__ */l("div",{className:"space-y-1.5 px-3 py-2.5",children:[/* @__PURE__ */t("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"SQL cards"}),/* @__PURE__ */t(Kr,{text:n,ariaLabel:"Copy SQL control reference"}),D?/* @__PURE__ */t(Kr,{text:D,ariaLabel:"Copy Jinja control reference"}):null,/* @__PURE__ */l("p",{className:"text-[12px] text-muted-foreground",children:[d," ",/* @__PURE__ */t("a",{href:"https://docs.semaphor.cloud/docs/concepts/template-expressions",target:"_blank",rel:"noreferrer",className:"underline underline-offset-2 hover:text-foreground",children:"Template expressions docs"}),"."]})]})]})]}),/* @__PURE__ */t(xt,{secondary:/* @__PURE__ */t(K,{type:"button",variant:"outline",size:"xs",onClick:i,children:"Back"}),tertiary:/* @__PURE__ */t(K,{type:"button",variant:"outline",size:"xs",onClick:u,children:"Cancel"}),primary:/* @__PURE__ */t(K,{type:"button",size:"xs",onClick:h,children:"Done"})})]});}function sl(e){const r=dt(e.scope,e.existingControls,e.reservedIds),a=e.type===r.type?{...r,label:Vt[e.type]}:{...na({controls:[{...r,label:Vt[e.type]}],controlId:r.id,nextType:e.type}).controls[0],label:Vt[e.type]};return{step:2,control:a,defaultValue:ct(a,void 0)};}function Ml({scope:e,controls:r,reservedControlIds:a,defaultValues:n,onChange:o,emptyMessage:d,initialCreateFlow:c=!1,usageByControlId:i,availableFieldChoices:u,availableMetricChoices:h,structuralParticipants:w,structuralParticipantIdsByControlId:v,card:D,allowedControlTypes:x,onCreateFlowActiveChange:y,onCreateFlowComplete:m}){const V=P(()=>new Set(a||[]),[a]),L=Fn(e),J=Rn(e),[_,$]=U(null),[M,te]=U(null),[p,A]=U(()=>c?{step:1,control:dt(e,r,Array.from(V))}:null),I=he({}),E=he(void 0),N=he(c),b=P(()=>{const s=Ir({scope:e,card:D});if(!x)return s;const S=new Set(x);return s.filter(k=>S.has(k.value));},[x,D,e]),T=j(s=>{const S=Ir({scope:e,card:D,includeType:x?void 0:s});if(!x)return S;const k=new Set(x);return S.filter(O=>k.has(O.value));},[x,D,e]),g=j(s=>e==="dashboard"&&(s==="field_selector"||s==="metric_selector"),[e]),C=P(()=>p?Lr(w||[],p.control.type):[],[p,w]),R=P(()=>{if(!p)return{fields:u||[],metrics:h||[]};if(!g(p.control.type))return{fields:u||[],metrics:h||[]};const s=p.selectedCardIds||[],S=zt({controlType:p.control.type,participants:w||[],selectedCardIds:s});return{fields:p.control.type==="field_selector"?S.choices.map(k=>({option:k,target:S.fieldTargetMap[k.value]})):[],metrics:p.control.type==="metric_selector"?S.choices.map(k=>({option:k,target:S.metricTargetMap[k.value]})):[]};},[u,h,p,g,w]);je(()=>{y==null||y(!!p);},[p,y]),je(()=>{const s=c&&!N.current;N.current=c,s&&(A({step:1,control:dt(e,r,Array.from(V))}),te(null),$(null));},[r,c,V,e]);const F=s=>{if(!g(s.type))return{fields:u||[],metrics:h||[]};const S=(v==null?void 0:v[s.id])||[];if(S.length===0)return{fields:u||[],metrics:h||[]};const k=zt({controlType:s.type,participants:w||[],selectedCardIds:S});return{fields:s.type==="field_selector"?k.choices.map(O=>({option:O,target:k.fieldTargetMap[O.value]})):[],metrics:s.type==="metric_selector"?k.choices.map(O=>({option:O,target:k.metricTargetMap[O.value]})):[]};},W=s=>{if(!g(s.control.type))return{nextControl:s.control,cardBindingsById:void 0};const S=(v==null?void 0:v[s.control.id])||[],k=zt({controlType:s.control.type,participants:w||[],selectedCardIds:s.nextSelectedCardIds}),O=Un({control:s.control,choices:k.choices}),q=Object.fromEntries(S.filter(Q=>!s.nextSelectedCardIds.includes(Q)).map(Q=>[Q,void 0]));return s.nextSelectedCardIds.length>0&&O.source.kind==="manual"&&O.source.options.length>0&&Object.assign(q,zr({control:O,participants:w||[],selectedCardIds:s.nextSelectedCardIds,matrixTargetIds:s.matrixTargetIds})),{nextControl:O,cardBindingsById:q};},B=j((s,S=n,k={type:"update"})=>{const O=s.map(q=>($t({control:q,defaultValues:S}),On(q)));o(O,S,k);},[n,o]),ee=(s,S)=>{const k=r.find(Z=>Z.id===s);let O=r.map(Z=>Z.id!==s?Z:S(Z));const q=O.find(Z=>Z.id===s);let Q,z;if(q&&(!k||Gn({control:k},{control:q}))&&e==="dashboard"&&(q.type==="field_selector"||q.type==="metric_selector")){const Z=(v==null?void 0:v[q.id])||[],pe=W({control:q,nextSelectedCardIds:Z});O=O.map(fe=>fe.id===s?pe.nextControl:fe),Q=pe.cardBindingsById,z=[q.id];}else if(k&&(!q||!Bn(q.type))&&e==="dashboard"&&(k.type==="field_selector"||k.type==="metric_selector")){const Z=(v==null?void 0:v[k.id])||[];Q=Object.fromEntries(Z.map(pe=>[pe,void 0])),z=[k.id];}const X=O.find(Z=>Z.id===s);let re=n;if(k&&X){const Z=$t({control:k,defaultValues:n});k.source.kind==="manual"&&X.source.kind==="sql_query"&&(I.current[s]=Z);const pe=Z===void 0&&k.source.kind==="sql_query"&&X.source.kind==="manual"?I.current[s]:Z,fe=Or({previousControl:k,nextControl:X,currentDefaultValue:pe});X.source.kind==="manual"&&(I.current[s]=fe),n&&(re={...n},fe===void 0?delete re[s]:re[s]=fe),O=O.map(Ie=>Ie.id===s?{...X,defaultValue:fe}:Ie);}B(O,re,{type:"update",cardBindingsById:Q,affectedBindingControlIds:z});},ae=(s,S)=>{if(!S.trim())return;const k=jn(S);if(k===s||V.has(k)||r.some(Q=>Q.id===k&&Q.id!==s))return;const O=r.map(Q=>Q.id===s?{...Q,id:k}:Q);if(!n){B(O,void 0,{type:"rename",oldId:s,newId:k});return;}const q={...n};Object.prototype.hasOwnProperty.call(q,s)&&(q[k]=q[s],delete q[s]),B(O,q,{type:"rename",oldId:s,newId:k});},oe=s=>{const S=r.filter(O=>O.id!==s);if(!n){B(S,void 0,{type:"remove",controlId:s});return;}const k={...n};delete k[s],B(S,k,{type:"remove",controlId:s});},ge=j(()=>{E.current=void 0,A({step:1,control:dt(e,r,Array.from(V))}),te(null),$(null);},[r,V,e]),De=s=>{A(S=>S&&(()=>{const k=s(S.control);S.control.source.kind==="manual"&&k.source.kind==="sql_query"&&(E.current=S.defaultValue);const O=S.defaultValue===void 0&&S.control.source.kind==="sql_query"&&k.source.kind==="manual"?E.current:S.defaultValue,q=Or({previousControl:S.control,nextControl:k,currentDefaultValue:O});return k.source.kind==="manual"&&(E.current=q),{...S,control:k,defaultValue:q};})());},ye=s=>{A(S=>S&&(S.control.source.kind==="manual"&&(E.current=s),{...S,defaultValue:s}));},Te=(()=>{if(!p)return!1;if(p.step===2&&g(p.control.type))return(p.selectedCardIds||[]).length>0&&zn({participants:w||[],selectedCardIds:p.selectedCardIds||[],control:p.control,selected:p.matrixTargetIds});if(p.step!==2&&p.step!==3||!p.control.label.trim())return!1;const S=p.control.source.kind==="sql_query"?p.control:Ar(p.control);if(S.source.kind==="manual"&&($n(S)&&S.source.options.length===0||S.source.options.some(O=>O.label.trim().length===0||O.value.trim().length===0)))return!1;if(S.source.kind==="sql_query"){const{connectionId:k,sql:O,valueColumn:q}=S.source;return k.trim().length>0&&O.trim().length>0&&q.trim().length>0;}return Vn(ct(S,p.defaultValue));})(),rt=()=>{var Q;if(!p)return;const s=Ar(p.control),S=qn({label:s.label,fallbackId:s.id,existingControls:r,reservedIds:Array.from(V)}),k={...s,id:S},O=e==="dashboard"&&(k.type==="field_selector"||k.type==="metric_selector")&&(Q=p.selectedCardIds)!=null&&Q.length?zr({control:k,participants:w||[],selectedCardIds:p.selectedCardIds,matrixTargetIds:p.matrixTargetIds}):void 0,q=ct(k,p.defaultValue);A({step:e==="dashboard"&&(k.type==="field_selector"||k.type==="metric_selector")?4:3,control:k,defaultValue:q,createdControlId:S,selectedCardIds:p.selectedCardIds,matrixTargetIds:p.matrixTargetIds,cardBindingsById:O});},Ne=j(()=>{A(null);},[]),at=j(()=>{if(!(p!=null&&p.createdControlId)){A(null);return;}const s=p.control,S=p.createdControlId,k=ct(s,p.defaultValue);if(n){const O={...n};k===void 0?delete O[S]:O[S]=k,B([...r,{...s,defaultValue:k}],O,{type:"add",cardBindingsById:p.cardBindingsById});}else B([...r,{...s,defaultValue:k}],void 0,{type:"add",cardBindingsById:p.cardBindingsById});te(S),A(null),m==null||m();},[r,p,n,B,m]),ue=p?g(p.control.type)?["Choose type","Select cards","Configure","Finish"]:["Choose type","Configure","Finish"]:[],me=p!=null&&p.createdControlId?`[[param.${p.createdControlId}]]`:p?`[[param.${_n(p.control.label)||p.control.id}]]`:"",Pe=Rr({controls:r,defaultValues:n}),Ee=p?[...r,p.control]:r,be=p?Rr({controls:Ee,defaultValues:n,overrides:[{controlId:p.control.id,value:p.defaultValue}]}):Pe;return/* @__PURE__ */l("div",{className:"space-y-4",children:[p?/* @__PURE__ */l("div",{className:"space-y-4 pb-1",children:[/* @__PURE__ */t(rl,{currentStep:p.step,labels:ue}),p.step===1&&(()=>{const s=/* @__PURE__ */new Set(["grain_selector","aggregation_selector","field_selector","metric_selector"]),S=/* @__PURE__ */new Set(["date","text"]),k=b.filter(Q=>!s.has(Q.value)&&!S.has(Q.value)),O=b.filter(Q=>s.has(Q.value)),q=Q=>/* @__PURE__ */l("button",{type:"button",className:"rounded-control border border-border/60 bg-background px-3 py-2.5 text-left transition-colors hover:bg-muted/40 focus-visible:bg-muted/40 focus-visible:outline-none",onClick:()=>A(sl({scope:e,existingControls:r,reservedIds:Array.from(V),type:Q.value})),children:[/* @__PURE__ */t("div",{className:"text-[13px] font-medium text-foreground",children:Q.label}),/* @__PURE__ */t("p",{className:"mt-0.5 text-[12px] text-muted-foreground",children:Q.description})]},Q.value);return/* @__PURE__ */l("div",{className:"space-y-4",children:[e==="card"&&(D==null?void 0:D.sql)==null?/* @__PURE__ */t("p",{className:"text-[12px] text-muted-foreground",children:"Explorer cards support displayed metric, group by field, aggregation, and time grain controls here."}):null,k.length>0&&/* @__PURE__ */l("div",{className:"space-y-1.5",children:[/* @__PURE__ */t("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Input controls"}),/* @__PURE__ */t("div",{className:"grid gap-1.5 sm:grid-cols-2",children:k.map(q)})]}),O.length>0&&/* @__PURE__ */l("div",{className:"space-y-1.5",children:[/* @__PURE__ */t("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Data-driven controls"}),/* @__PURE__ */t("div",{className:"grid gap-1.5 sm:grid-cols-2",children:O.map(q)})]}),/* @__PURE__ */t(xt,{secondary:/* @__PURE__ */t(K,{type:"button",variant:"outline",size:"xs",onClick:Ne,children:"Back to controls"})})]});})(),p.step===2&&g(p.control.type)&&/* @__PURE__ */l("div",{className:"space-y-3",children:[/* @__PURE__ */l("div",{className:"space-y-3",children:[/* @__PURE__ */t(Ca,{control:p.control,onChange:s=>De(S=>({...S,label:s}))}),/* @__PURE__ */t("p",{className:"text-[12px] text-muted-foreground",children:"Choose which cards should respond to this shared control."})]}),C.length===0?/* @__PURE__ */t("div",{className:"rounded-control border border-border/60 bg-muted/30 px-3 py-2.5 text-[12px] text-muted-foreground",children:"No eligible cards are available yet. Add compatible metrics or group-by fields to cards first."}):/* @__PURE__ */t("div",{className:"space-y-1 rounded-control border border-border/60 bg-background p-2",children:C.map(s=>{const S=(p.selectedCardIds||[]).includes(s.cardId);return/* @__PURE__ */l("label",{className:"flex items-start gap-2 rounded-control px-1.5 py-1 text-[13px] hover:bg-muted/40",children:[/* @__PURE__ */t(Gs,{checked:S,onCheckedChange:k=>A(O=>O&&{...O,selectedCardIds:k===!0?[...(O.selectedCardIds||[]),s.cardId]:(O.selectedCardIds||[]).filter(q=>q!==s.cardId)})}),/* @__PURE__ */l("div",{className:"min-w-0",children:[/* @__PURE__ */t("div",{className:"font-medium text-foreground",children:s.title}),/* @__PURE__ */t("div",{className:"text-[12px] text-muted-foreground",children:p.control.type==="field_selector"?`${s.fieldChoices.length} compatible group-by fields`:`${s.metricChoices.length} compatible metrics`})]})]},s.cardId);})}),/* @__PURE__ */t(Fr,{participants:C,selectedCardIds:p.selectedCardIds||[],control:p.control,selected:p.matrixTargetIds,onChange:(s,S)=>A(k=>k&&{...k,matrixTargetIds:{...k.matrixTargetIds,[s]:S}})}),/* @__PURE__ */t(xt,{secondary:/* @__PURE__ */t(K,{type:"button",variant:"outline",size:"xs",onClick:()=>A(s=>s&&{...s,step:1,selectedCardIds:[]}),children:"Back"}),primary:/* @__PURE__ */t(K,{type:"button",size:"xs",onClick:()=>A(s=>s&&{...s,step:3}),disabled:!Te,children:"Next"})})]}),p.step===2&&!g(p.control.type)&&/* @__PURE__ */t(Pr,{control:p.control,defaultValue:p.defaultValue,availableFieldChoices:R.fields,availableMetricChoices:R.metrics,previewControlDefinitions:Ee,previewControlValues:be,onControlChange:s=>De(()=>s),onLabelChange:s=>De(S=>({...S,label:s})),onDefaultValueChange:ye,onBack:()=>A(s=>s&&{...s,step:1}),onNext:rt,nextDisabled:!Te}),p.step===3&&g(p.control.type)&&/* @__PURE__ */t(Pr,{control:p.control,defaultValue:p.defaultValue,availableFieldChoices:R.fields,availableMetricChoices:R.metrics,previewControlDefinitions:Ee,previewControlValues:be,onControlChange:s=>De(()=>s),onLabelChange:s=>De(S=>({...S,label:s})),onDefaultValueChange:ye,onBack:()=>A(s=>s&&{...s,step:2}),onNext:rt,nextDisabled:!Te}),p.step===3&&!g(p.control.type)&&/* @__PURE__ */t(Wr,{control:p.control,scope:e,createdReference:me,explorerContent:/* @__PURE__ */l(de,{children:["Open the card and use"," ",/* @__PURE__ */t("span",{className:"font-medium text-foreground",children:"Settings → Controls"})," ","to choose what this control changes."]}),sqlDescription:"Reference this control directly in the SQL editor.",onBack:()=>A(s=>s&&{...s,step:2}),onCancel:Ne,onDone:at}),p.step===4&&g(p.control.type)&&/* @__PURE__ */t(Wr,{control:p.control,scope:e,createdReference:me,summaryDetail:/* @__PURE__ */l(de,{children:["Used by ",(p.selectedCardIds||[]).length," selected card",(p.selectedCardIds||[]).length===1?"":"s"]}),explorerContent:/* @__PURE__ */t(de,{children:"Selected cards have been set up to respond to this control automatically."}),sqlDescription:"SQL cards can still reference this control directly in the SQL editor.",onBack:()=>A(s=>s&&{...s,step:3}),onCancel:Ne,onDone:at})]}):null,!p&&r.length===0?/* @__PURE__ */t("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:d}):null,!p&&r.map(s=>{const S=F(s),k=i==null?void 0:i[s.id],O=$t({control:s,defaultValues:n}),q=M===s.id,Q="inline-flex shrink-0 items-center rounded-[4px] border border-border/60 bg-muted/40 px-1.5 py-0.5 text-[11px] font-medium text-muted-foreground";return/* @__PURE__ */l("div",{className:"rounded-control border border-border/60",children:[/* @__PURE__ */l("div",{className:"flex items-center gap-2 px-3 py-2.5",children:[/* @__PURE__ */l("button",{type:"button",className:"flex min-w-0 flex-1 items-start gap-2 rounded-control text-left focus:outline-none focus-visible:bg-muted/40",onClick:()=>te(z=>z===s.id?null:s.id),children:[q?/* @__PURE__ */t(Qe,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}):/* @__PURE__ */t(Mr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),/* @__PURE__ */l("div",{className:"min-w-0",children:[/* @__PURE__ */l("div",{className:"flex flex-wrap items-center gap-1.5",children:[/* @__PURE__ */t("span",{className:"truncate text-[13px] font-medium text-foreground",children:s.label||"Untitled control"}),/* @__PURE__ */t("span",{className:Q,children:ta(s.type).label}),/* @__PURE__ */t("span",{className:Q,children:ra(e,s.placement)})]}),/* @__PURE__ */l("div",{className:"mt-0.5 text-[12px] text-muted-foreground",children:[aa(s),k!=null&&k.status?` · ${k.status}`:""]})]})]}),/* @__PURE__ */t(K,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 shrink-0 p-0 text-muted-foreground",onClick:()=>oe(s.id),"aria-label":`Remove ${s.label}`,children:/* @__PURE__ */t(ca,{className:"h-3.5 w-3.5"})})]}),q&&/* @__PURE__ */l("div",{className:"space-y-4 border-t border-border/60 px-3 py-3",children:[/* @__PURE__ */l("div",{className:"grid gap-3 md:grid-cols-3",children:[/* @__PURE__ */l("div",{className:"flex flex-col gap-1.5",children:[/* @__PURE__ */t(ce,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Label"}),/* @__PURE__ */t(Be,{size:"xs",value:s.label,placeholder:"Control label",onChange:z=>ee(s.id,X=>({...X,label:z.target.value}))})]}),/* @__PURE__ */l("div",{className:"flex flex-col gap-1.5",children:[/* @__PURE__ */t(ce,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Type"}),/* @__PURE__ */l(Oe,{value:s.type,onValueChange:z=>{const X=na({controls:r,controlId:s.id,nextType:z,defaultValues:n});B(X.controls,X.defaultValues);},children:[/* @__PURE__ */t(ze,{size:"xs",children:/* @__PURE__ */t($e,{})}),/* @__PURE__ */t(Ve,{children:T(s.type).map(z=>/* @__PURE__ */t(ve,{value:z.value,children:z.label},z.value))})]})]}),/* @__PURE__ */l("div",{className:"flex flex-col gap-1.5",children:[/* @__PURE__ */t(ce,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Show in"}),/* @__PURE__ */l(Oe,{value:s.placement||J,onValueChange:z=>ee(s.id,X=>({...X,placement:z})),children:[/* @__PURE__ */t(ze,{size:"xs",children:/* @__PURE__ */t($e,{})}),/* @__PURE__ */t(Ve,{children:L.map(z=>/* @__PURE__ */t(ve,{value:z.value,children:z.label},z.value))})]})]})]}),g(s.type)?/* @__PURE__ */l(de,{children:[/* @__PURE__ */t(Bs,{type:s.type,participants:Lr(w||[],s.type).map(z=>({cardId:z.cardId,title:z.title,choiceCount:s.type==="field_selector"?z.fieldChoices.length:z.metricChoices.length})),selectedCardIds:(v==null?void 0:v[s.id])||[],onChange:z=>{const X=W({control:s,nextSelectedCardIds:z}),re=r.map(Z=>Z.id===s.id?X.nextControl:Z);B(re,n,{type:"update",cardBindingsById:X.cardBindingsById});}}),/* @__PURE__ */t(Fr,{participants:w||[],selectedCardIds:(v==null?void 0:v[s.id])||[],control:s,onChange:(z,X)=>{const re=W({control:s,nextSelectedCardIds:(v==null?void 0:v[s.id])||[],matrixTargetIds:{[z]:X}});B(r.map(Z=>Z.id===s.id?re.nextControl:Z),n,{type:"update",cardBindingsById:re.cardBindingsById});}})]}):null,/* @__PURE__ */t(ua,{control:s,availableFieldChoices:S.fields,availableMetricChoices:S.metrics,previewControlDefinitions:r,previewControlValues:Pe,controlLifecycle:"edit",onChange:z=>ee(s.id,()=>z)}),s.initialValueStrategy==="saved_default"&&/* @__PURE__ */t(ma,{control:s,value:O,allowNoDefault:!0,allowCardDefault:!0,previewControlDefinitions:r,previewControlValues:Pe,onChange:z=>{const X=r.map(re=>re.id===s.id?{...re,defaultValue:z}:re);if(s.source.kind==="manual"&&(I.current[s.id]=z),n){const re={...n};z===void 0?delete re[s.id]:re[s.id]=z,B(X,re);return;}B(X,void 0);}}),/* @__PURE__ */l(Us,{open:_===s.id,onOpenChange:z=>$(z?s.id:null),children:[/* @__PURE__ */t(js,{asChild:!0,children:/* @__PURE__ */l(K,{type:"button",variant:"ghost",size:"xs",className:"-ml-2 gap-1 text-muted-foreground hover:text-foreground",children:[_===s.id?/* @__PURE__ */t(Qe,{className:"h-3.5 w-3.5"}):/* @__PURE__ */t(Mr,{className:"h-3.5 w-3.5"}),"Advanced"]})}),/* @__PURE__ */l(Ps,{className:"space-y-3 pt-2",children:[/* @__PURE__ */l("div",{className:"grid gap-3 md:grid-cols-2",children:[/* @__PURE__ */l("div",{className:"flex flex-col gap-1.5",children:[/* @__PURE__ */t(ce,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Variable name"}),/* @__PURE__ */t(Ks,{controlId:s.id,onCommit:z=>ae(s.id,z)},s.id)]}),/* @__PURE__ */l("div",{className:"flex flex-col gap-1.5",children:[/* @__PURE__ */t(ce,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Initial value"}),/* @__PURE__ */l(Oe,{value:s.initialValueStrategy,onValueChange:z=>ee(s.id,X=>({...X,initialValueStrategy:z})),children:[/* @__PURE__ */t(ze,{size:"xs",children:/* @__PURE__ */t($e,{})}),/* @__PURE__ */t(Ve,{children:Mn.map(z=>/* @__PURE__ */t(ve,{value:z.value,children:z.label},z.value))})]})]})]}),/* @__PURE__ */t(Ws,{control:s,onChange:z=>ee(s.id,()=>z)})]})]})]})]},s.id);}),!p&&/* @__PURE__ */l(K,{type:"button",variant:"outline",size:"xs",onClick:ge,children:[/* @__PURE__ */t(mt,{className:"h-3.5 w-3.5"}),"Add control"]})]});}function ql(e){const{open:r,onOpenChange:a,initialCreateFlowActive:n=!1,dismissMode:o="passive"}=e,d=r!==void 0,[c,i]=U(!1),[u,h]=U(n),w=d?r:c,v=j(y=>{!y&&u&&o==="passive"||(d||i(y),y||h(!1),a==null||a(y));},[d,u,o,a]),D=j(()=>{d||i(!1),h(!1),a==null||a(!1);},[d,a]);je(()=>{w||h(!1);},[w]);const x=j(y=>{u&&y.preventDefault();},[u]);return{forceClose:D,handleOpenChange:v,isCreateFlowActive:u,preventPassiveDismissDuringCreate:x,resolvedOpen:w,setIsCreateFlowActive:h};}function Sa(e){const{relativeMeta:r,latestValue:a,...n}=e;return n;}function er(e,r){const a=Sa(e);return r.relativeMeta?{...a,value:r.value,relativeMeta:r.relativeMeta}:{...a,value:r.value};}function ol(e,r){const a=r==="in"||r==="not in"||r==="between"||r==="not between"?[]:r==="isNull"||r==="isNotNull"?null:"";return er({...e,operator:r},{value:a});}function ll(e,r){const a=Ue(r.dataType)==="date";return er({...e,field:r,operator:a?"between":"="},{value:""});}function il({initialFilters:e,availableFields:r,onChange:a}={}){const[n,o]=U(e||{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[],groups:[]}),d=A=>{o(A),a==null||a(A);};Se(A=>A.card.dataSource);const{filterableFields:c,isLoading:i}=Hs(),u=r||c||[],h={id:"default",qualifiedFieldName:"default",name:"default",dataType:"string",label:"Default",entityId:"default",entityName:"Default",entityType:"table"},w=A=>{const I=E=>{if(E.id===A){const N=u[0]||h,b=Ue(N.dataType)==="date";return{...E,conditions:[...E.conditions,{id:`condition-${Date.now()}`,field:N,operator:b?"between":"=",value:b?[]:""}]};}return{...E,groups:E.groups.map(I)};};d(I(n));},v=A=>{const I=E=>{if(E.id===A){const N=u[0]||h,b=Ue(N.dataType)==="date";return{...E,groups:[...E.groups,{id:`group-${Date.now()}`,logicalOperator:"AND",negate:!1,conditions:[{id:`condition-${Date.now()}`,field:N,operator:b?"between":"=",value:b?[]:""}],groups:[]}]};}return{...E,groups:E.groups.map(I)};};d(I(n));},D=(A,I)=>{const E=N=>N.id===A?{...N,conditions:N.conditions.filter(b=>b.id!==I)}:{...N,groups:N.groups.map(E)};d(E(n));},x=(A,I)=>{const E=N=>N.id===A?{...N,groups:N.groups.filter(b=>b.id!==I)}:{...N,groups:N.groups.map(E)};d(E(n));},y=(A,I,E)=>{const N=b=>b.id===A?{...b,conditions:b.conditions.map(T=>T.id===I?E(T):T)}:{...b,groups:b.groups.map(N)};d(N(n));},m=(A,I,E)=>y(A,I,N=>({...("value"in E||"operator"in E||"field"in E?Sa(N):N),...E})),V=(A,I,E)=>y(A,I,()=>E),L=Ys(),J=(A,I)=>{const E=N=>N.id===A?{...N,logicalOperator:I}:{...N,groups:N.groups.map(E)};d(E(n));},_=(A,I)=>{const E=N=>N.id===A?{...N,negate:I}:{...N,groups:N.groups.map(E)};d(E(n));},$=(A,I,E)=>{const N=b=>b.id===A?{...b,conditions:qr(b.conditions,I,E)}:{...b,groups:b.groups.map(N)};d(N(n));},M=(A,I,E)=>{const N=b=>b.id===A?{...b,groups:qr(b.groups,I,E)}:{...b,groups:b.groups.map(N)};d(N(n));},te=A=>{if(!A||A.conditions.length===0&&A.groups.length===0)return"-- No filters defined";const I=N=>{let b="";typeof N.field=="object"?b=N.field.entityName?`${N.field.entityName}.${N.field.name}`:N.field.name:b=String(N.field);const T=N.operator;let g=N.value;if(N.latestValue&&T==="=")return`${b} = ${pa} /* the latest value each time the card runs */`;const C=sa(N.relativeMeta);if(C&&rs(T)&&oa(T,C)){const R=oo(T,C),{label:F,range:W}=Gr(C,{tz:(L==null?void 0:L.tz)??"UTC",weekStart:(L==null?void 0:L.weekStart)??1,anchor:(L==null?void 0:L.anchor)??"now"}),B=R?lo(R):F;if(W){const[ee]=la(T,[W.start,W.end]);return`${b} ${T} '${ee.toISOString()}' /* ${B}: the date updates each time the card runs */`;}return`${b} ${T} ${B} /* the date follows your calendar each time the card runs */`;}if(C&&(T==="between"||T==="not between")){const R=T==="between"?"BETWEEN":"NOT BETWEEN",{label:F,range:W}=Gr(C,{tz:(L==null?void 0:L.tz)??"UTC",weekStart:(L==null?void 0:L.weekStart)??1,anchor:(L==null?void 0:L.anchor)??"now"});return W?`${b} ${R} '${W.start.toISOString()}' AND '${W.end.toISOString()}' /* ${F}: dates update each time the card runs */`:xa(C).dataAnchored?`${b} ${R} ${F} /* dates count back from the latest data each time the card runs */`:`${b} ${R} ${F} /* dates follow your calendar each time the card runs */`;}if(N.field.dataType==="string"&&!["in","not in"].includes(N.operator))typeof g=="string"?g=`'${g}'`:Array.isArray(g)&&(g=`'${g.join(", ")}'`);else if(N.field.dataType==="date"||N.field.dataType==="datetime"||N.field.dataType==="timestamp"){if(N.operator==="between"&&Array.isArray(g)&&g.length===2){const R=g[0]?`'${g[0]}'`:"NULL",F=g[1]?`'${g[1]}'`:"NULL";return`${b} BETWEEN ${R} AND ${F}`;}else if((N.operator==="in"||N.operator==="not in")&&Array.isArray(g)){const R=g.map(F=>F?`'${F}'`:"NULL").join(", ");return`${b} ${T} (${R})`;}else typeof g=="string"||g instanceof Date?g=`'${g}'`:Array.isArray(g)&&g.length>0&&(g=`'${g[0]}'`);}else if(["in","not in"].includes(N.operator)){let R=[];Array.isArray(g)?R=g.map(F=>typeof F=="string"?`'${F}'`:String(F)):typeof g=="string"?R=g.split(",").map(F=>{const W=F.trim();return N.field.dataType==="string"?`'${W}'`:W;}):typeof g=="number"&&(R=[String(g)]),g=`(${R.join(", ")})`;}switch(T){case"contains":return typeof g=="string"?`${b} LIKE '%${g.replace(/'/g,"")}'`:`${b} LIKE '%${String(g)}'`;case"startsWith":return typeof g=="string"?`${b} LIKE '${g.replace(/'/g,"")}%'`:`${b} LIKE '${String(g)}%'`;case"endsWith":return typeof g=="string"?`${b} LIKE '%${g.replace(/'/g,"")}'`:`${b} LIKE '%${String(g)}'`;case"isNull":return`${b} IS NULL`;case"isNotNull":return`${b} IS NOT NULL`;default:return`${b} ${T} ${g}`;}},E=N=>{const b=N.conditions.map(I),T=N.groups.map(F=>E(F)),g=[...b,...T].filter(Boolean);if(g.length===0)return"";const C=g.join(` ${N.logicalOperator} `),R=g.length>1?`(${C})`:C;return N.negate?`NOT ${R}`:R;};return E(A);},p=n.conditions.length>0||n.groups.length>0;return{currentFilters:n,setCurrentFilters:d,availableFields:u,isLoading:i,addCondition:w,addGroup:v,removeCondition:D,removeGroup:x,updateConditionFields:m,replaceCondition:V,updateGroupOperator:J,updateGroupNegate:_,reorderConditions:$,reorderGroups:M,generateSQLPreview:te,hasAnyFilters:p};}function Da(e,r){const a=Se(h=>h.card.dataSource),n=Se(h=>h.card.connectionId),o=Se(h=>h.selectedConnectionId),{dataSource:d,connectionId:c}=r?$r(r):$r({dataSource:a,connectionId:n},o),i=P(()=>({id:`card-filter-option:${e.id}`,...Pn(e,{dataSource:d,connectionId:c})}),[c,d,e]),u=P(()=>Xs({filter:i}),[i]);return Js(i,{inputContext:u,currentSelectionPolicy:"exclude"});}function dl({field:e,source:r,selected:a,onChange:n,placeholder:o="Select values…",className:d}){const[c,i]=He.useState(!1),u=Da(e,r),h=He.useMemo(()=>new Set(a.map(x=>Ge(x))),[a]),w=x=>{var y,m;return((m=(y=u.allRecords.find(V=>Ge(V.value)===Ge(x)))==null?void 0:y.label)==null?void 0:m.toString())??x;},v=x=>{n(a.filter(y=>y!==x));},D=x=>{i(x),!x&&u.query&&u.setQuery("");};return/* @__PURE__ */t("div",{className:H("w-full",d),children:/* @__PURE__ */l(Je,{open:c,onOpenChange:D,modal:!0,children:[/* @__PURE__ */t(yt,{asChild:!0,children:/* @__PURE__ */l(K,{variant:"outline",size:"xs",role:"combobox","aria-expanded":c,className:"h-auto min-h-7 w-full justify-between gap-1.5 px-2 py-0.5 font-normal",children:[/* @__PURE__ */t("div",{className:"flex min-w-0 flex-1 flex-wrap gap-1",children:a.length>0?a.map(x=>{const y=w(x);return(/* @__PURE__ */l("span",{className:"inline-flex max-w-full items-center gap-1 rounded-[4px] border border-border/70 bg-muted/40 px-1.5 py-0.5 text-[11px] leading-[14px] text-foreground",children:[/* @__PURE__ */t("span",{className:"truncate",children:y}),/* @__PURE__ */t("span",{role:"button",tabIndex:0,"aria-label":`Remove ${y}`,className:"shrink-0 rounded-[2px] text-muted-foreground outline-none hover:text-foreground focus-visible:ring-1 focus-visible:ring-ring",onKeyDown:m=>{m.key==="Enter"&&v(x);},onMouseDown:m=>{m.preventDefault(),m.stopPropagation();},onClick:m=>{m.stopPropagation(),v(x);},children:/* @__PURE__ */t(et,{className:"h-3 w-3"})})]},x));}):/* @__PURE__ */t("span",{className:"truncate text-muted-foreground",children:o})}),/* @__PURE__ */t(Qe,{className:"h-3.5 w-3.5 shrink-0 opacity-50"})]})}),/* @__PURE__ */t(Ze,{className:"w-[var(--radix-popover-trigger-width)] min-w-[240px] rounded-control p-1.5",align:"start",onOpenAutoFocus:x=>{var y,m;x.preventDefault(),(m=(y=x.currentTarget)==null?void 0:y.querySelector('input[type="text"]'))==null||m.focus();},children:/* @__PURE__ */t(fa,{records:u.displayRecords,selectedIdentities:h,onToggle:x=>{const y=String(x.value);a.includes(y)?v(y):n([...a,y]);},browse:u,searchPlaceholder:`Search ${(e.label||e.name).toLowerCase()}`,listLabel:e.label||e.name,density:"compact"})})]})});}function cl({field:e,source:r,value:a,onChange:n,placeholder:o="Select value…",className:d}){var D,x;const[c,i]=He.useState(!1),u=Da(e,r),h=He.useMemo(()=>new Set(a?[Ge(a)]:[]),[a]),w=a?((x=(D=u.allRecords.find(y=>Ge(y.value)===Ge(a)))==null?void 0:D.label)==null?void 0:x.toString())??a:"",v=y=>{i(y),!y&&u.query&&u.setQuery("");};return/* @__PURE__ */l(Je,{open:c,onOpenChange:v,modal:!0,children:[/* @__PURE__ */t(yt,{asChild:!0,children:/* @__PURE__ */l(K,{variant:"outline",size:"xs",role:"combobox","aria-expanded":c,className:H("min-w-0 flex-1 justify-between gap-1.5 px-2 font-normal",d),children:[/* @__PURE__ */t("span",{className:H("truncate",!a&&"text-muted-foreground"),children:a?w:o}),/* @__PURE__ */t(Qe,{className:"h-3.5 w-3.5 shrink-0 opacity-50"})]})}),/* @__PURE__ */t(Ze,{className:"w-[var(--radix-popover-trigger-width)] min-w-[240px] rounded-control p-1.5",align:"start",onOpenAutoFocus:y=>{var m,V;y.preventDefault(),(V=(m=y.currentTarget)==null?void 0:m.querySelector('input[type="text"]'))==null||V.focus();},children:/* @__PURE__ */t(fa,{records:u.displayRecords,selectedIdentities:h,onToggle:y=>{n(String(y.value)),v(!1);},selectionMode:"single",browse:u,searchPlaceholder:`Search ${(e.label||e.name).toLowerCase()}`,listLabel:e.label||e.name,density:"compact"})})]});}function ul({value:e,operator:r,relativeMeta:a,latestValue:n,field:o,onChange:d,className:c}){const i=Zs(),u=eo(),h=r==="between"||r==="not between",w=oa(r),v=w?a:void 0,D=P(()=>{if(!h||!a)return;const _=u(a);return{..._,tooltip:_.dates?void 0:xa(a).dataAnchored?to:ro};},[h,a,u]),x=P(()=>{if(h){if(D){const{range:_}=D;return _?{from:_.start,to:_.end}:void 0;}if(e&&Array.isArray(e)&&e.length===2){const _=_t(e[0],i,"start"),$=_t(e[1],i,"end");if(_&&$)return{from:_,to:$};}}},[e,h,D,i]),y=P(()=>{if(!e||h||n)return;const _=Array.isArray(e)?e[0]:e;return _t(_,i,"start");},[e,h,n,i]),m=_=>r==="<="||r===">"?Qn(_,i):Hn(_,i);return/* @__PURE__ */t(ao,{value:h?x:void 0,selectionMode:h?"range":"single",singleValue:h?void 0:y,singleValueLabel:!h&&n?pa:void 0,onChange:_=>{if(_!=null&&_.from&&_.to){d({value:[_.from.toISOString(),_.to.toISOString()]});return;}d({value:[]});},onSingleChange:_=>{if(!_){d({value:""});return;}const $=m(_),M=Wn($,r,{timezone:i});d({value:typeof M=="string"?M:M.toISOString()});},onRelativeSelect:w?(_,$)=>{if(!_.from||!_.to){d({value:h?[]:""});return;}const M=la(r,[_.from.toISOString(),_.to.toISOString()]);d({value:M.length===1?M[0]:M,relativeMeta:$});}:void 0,relativeValue:v,comparisonValue:!h&&w?r:void 0,relativePoints:!h&&w?{operator:r}:"none",relativeSummary:D,supplementalFooter:w?/* @__PURE__ */t("p",{className:"border-t border-border px-3 py-2 text-[11px] text-muted-foreground",children:"Presets and Relative update each time the card runs. Static dates stay fixed."}):void 0,timezone:i,enableTimePrecision:Kn(o),staticTimeInputs:!1,showRelativeTab:w,className:H("min-w-0",c),buttonClassName:"h-7 text-[12px] [&>span]:text-[12px]",placeholder:"Select date…"});}const ml=e=>e.conditions.length>0||e.groups.length>0,tr=["contains","startsWith","endsWith","like","not like"],pl=["=","!=",">",">=","<","<=",...tr,"in","not in","isNull","isNotNull"],fl=["=","!=",...tr,"in","not in","isNull","isNotNull"],hl=["=","!=",">",">=","<","<=","in","not in","isNull","isNotNull"],gl=["=","!=","isNull","isNotNull"],bl=["between","=","!=","<","<=",">",">=","isNull","isNotNull"],xl={"=":"Equals","!=":"Not equals",">":"Greater than",">=":"Greater than or equal","<":"Less than","<=":"Less than or equal",contains:"Contains",startsWith:"Starts with",endsWith:"Ends with",like:"Like","not like":"Not like",in:"In","not in":"Not in",between:"Between",isNull:"Is null",isNotNull:"Is not null","not between":"Not between"};function Gt(e){return xl[e]||Yn(e);}function yl(e){switch(e){case"string":return fl;case"number":return hl;case"boolean":return gl;case"date":return bl;default:return pl;}}const Ta="w-[68px] shrink-0",Qr="group-data-[inline]/filters:w-auto group-data-[inline]/filters:min-w-0 group-data-[inline]/filters:flex-1 group-data-[inline]/filters:shrink",rr="text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground";function Ea({value:e,onValueChange:r,"aria-label":a}){return/* @__PURE__ */l(Oe,{value:e,onValueChange:n=>r(n),children:[/* @__PURE__ */t(ze,{size:"xs","aria-label":a,className:H(Ta,"font-medium"),children:/* @__PURE__ */t($e,{})}),/* @__PURE__ */l(Ve,{className:"min-w-[var(--radix-select-trigger-width)]",children:[/* @__PURE__ */t(ve,{value:"AND",className:"text-[12px] font-medium",children:"AND"}),/* @__PURE__ */t(ve,{value:"OR",className:"text-[12px] font-medium",children:"OR"})]})]});}function Ia({condition:e,index:r,groupId:a,groupLogicalOperator:n,onRemoveCondition:o,onUpdateGroupOperator:d,availableFields:c,source:i,updateConditionFields:u,replaceCondition:h}){const{attributes:w,listeners:v,setNodeRef:D,transform:x,transition:y,isDragging:m}=ha({id:e.id}),V={transform:ga.Transform.toString(x),transition:y},L=Ue(e.field.dataType),J=e.operator==="isNull"||e.operator==="isNotNull",_=e.operator==="in"||e.operator==="not in";return/* @__PURE__ */l("div",{ref:D,style:V,className:H("flex items-center gap-2 rounded-control px-1.5 py-1 transition-colors hover:bg-muted/40",m&&"z-50 opacity-50"),children:[/* @__PURE__ */t("button",{type:"button",...w,...v,"aria-label":"Drag to reorder condition",className:"flex h-7 w-5 shrink-0 cursor-grab items-center justify-center rounded-control text-muted-foreground/60 hover:text-foreground focus-visible:outline-none active:cursor-grabbing",children:/* @__PURE__ */t(ba,{className:"h-3.5 w-3.5"})}),r>0?/* @__PURE__ */t(Ea,{value:n,onValueChange:$=>d(a,$),"aria-label":"Logical operator"}):/* @__PURE__ */t("span",{className:H(Ta,"text-center",rr),children:"Where"}),/* @__PURE__ */t(mo,{value:e.field,onValueChange:$=>{h(a,e.id,ll(e,$));},availableFields:c,placeholder:"Select field",className:H("w-60 shrink-0",Qr)}),/* @__PURE__ */l(Oe,{value:e.operator,onValueChange:$=>h(a,e.id,ol(e,$)),children:[/* @__PURE__ */t(ze,{size:"xs","aria-label":"Operator",className:H("w-40 shrink-0",Qr),children:/* @__PURE__ */t($e,{children:e.operator?Gt(e.operator):""})}),/* @__PURE__ */t(Ve,{children:yl(L).map($=>/* @__PURE__ */t(ve,{value:$,children:Gt($)},$))})]}),J?/* @__PURE__ */t("div",{className:"min-w-0 flex-1"}):L==="string"?_?/* @__PURE__ */t(dl,{field:e.field,source:i,selected:Array.isArray(e.value)&&e.value.every($=>typeof $=="string")?e.value:[],onChange:$=>u(a,e.id,{value:$}),placeholder:"Select values…",className:"min-w-0 flex-1"}):tr.includes(e.operator)?/* @__PURE__ */t(Be,{size:"xs",value:typeof e.value=="string"?e.value:"",onChange:$=>u(a,e.id,{value:$.target.value}),className:"min-w-0 flex-1",placeholder:`${Gt(e.operator)}…`}):/* @__PURE__ */t(cl,{field:e.field,source:i,value:typeof e.value=="string"?e.value:"",onChange:$=>u(a,e.id,{value:$}),placeholder:"Select value…",className:"min-w-0 flex-1"}):L==="boolean"?/* @__PURE__ */l(Oe,{value:typeof e.value=="boolean"?String(e.value):"",onValueChange:$=>u(a,e.id,{value:$==="true"}),children:[/* @__PURE__ */t(ze,{size:"xs",className:"min-w-0 flex-1",children:/* @__PURE__ */t($e,{placeholder:"Select value…"})}),/* @__PURE__ */l(Ve,{children:[/* @__PURE__ */t(ve,{value:"true",children:"True"}),/* @__PURE__ */t(ve,{value:"false",children:"False"})]})]}):L==="date"?/* @__PURE__ */t(ul,{value:e.value,operator:e.operator,relativeMeta:sa(e.relativeMeta),latestValue:e.latestValue===!0,field:e.field,onChange:$=>h(a,e.id,er(e,$)),className:"min-w-0 flex-1"}):/* @__PURE__ */t(Be,{size:"xs",value:typeof e.value=="string"||typeof e.value=="number"?e.value:"",onChange:$=>u(a,e.id,{value:$.target.value}),className:"min-w-0 flex-1",placeholder:_?"value1, value2, value3":"Value"}),/* @__PURE__ */t(K,{variant:"ghost",size:"xs","aria-label":"Remove condition",className:"h-7 w-7 shrink-0 p-0 text-muted-foreground hover:text-foreground",onClick:()=>o(a,e.id),children:/* @__PURE__ */t(et,{className:"h-3.5 w-3.5"})})]});}const Hr="group-data-[inline]/filters:h-auto group-data-[inline]/filters:gap-1 group-data-[inline]/filters:border-0 group-data-[inline]/filters:bg-transparent group-data-[inline]/filters:px-0 group-data-[inline]/filters:py-0.5 group-data-[inline]/filters:text-[11px] group-data-[inline]/filters:font-medium group-data-[inline]/filters:text-muted-foreground group-data-[inline]/filters:shadow-none group-data-[inline]/filters:underline-offset-2 group-data-[inline]/filters:hover:bg-transparent group-data-[inline]/filters:hover:text-foreground group-data-[inline]/filters:hover:underline";function La({onAddCondition:e,onAddGroup:r}){return/* @__PURE__ */l("div",{className:"mt-2 flex items-center gap-1.5 group-data-[inline]/filters:mt-1 group-data-[inline]/filters:gap-3",children:[/* @__PURE__ */l(K,{type:"button",size:"xs",variant:"outline",className:H("gap-1.5",Hr),onClick:e,children:[/* @__PURE__ */t(mt,{className:"h-3 w-3"}),"Add condition"]}),r&&/* @__PURE__ */l(K,{type:"button",size:"xs",variant:"ghost",className:H("gap-1.5 text-muted-foreground hover:text-foreground",Hr),onClick:r,children:[/* @__PURE__ */t(mt,{className:"h-3 w-3"}),"Add group"]})]});}function vl({group:e,depth:r,parentGroupId:a,onUpdateGroupOperator:n,onUpdateGroupNegate:o,onRemoveGroup:d,onRemoveCondition:c,onReorderConditions:i,onReorderGroups:u,onAddCondition:h,onAddGroup:w,availableFields:v,source:D,renderFilterGroup:x,updateConditionFields:y,replaceCondition:m}){const{attributes:V,listeners:L,setNodeRef:J,transform:_,transition:$,isDragging:M}=ha({id:e.id}),te={transform:ga.Transform.toString(_),transition:$},p=I=>{const{active:E,over:N}=I;if(N&&E.id!==N.id){const b=e.conditions.findIndex(g=>g.id===E.id),T=e.conditions.findIndex(g=>g.id===N.id);b!==-1&&T!==-1&&i(e.id,b,T);}},A=I=>{const{active:E,over:N}=I;if(N&&E.id!==N.id&&a){const b=e.groups.findIndex(g=>g.id===E.id),T=e.groups.findIndex(g=>g.id===N.id);b!==-1&&T!==-1&&u(a,b,T);}};return/* @__PURE__ */l("div",{ref:J,style:te,className:H(r>0&&"mt-2 overflow-hidden rounded-[6px] border border-border/60",M&&"z-50 opacity-50"),children:[r>0&&/* @__PURE__ */l("div",{className:"flex items-center justify-between gap-2 border-b border-border/60 bg-muted/40 px-2 py-1",children:[/* @__PURE__ */l("div",{className:"flex items-center gap-1.5",children:[/* @__PURE__ */t("button",{type:"button",...V,...L,"aria-label":"Drag to reorder group",className:"flex h-7 w-5 shrink-0 cursor-grab items-center justify-center rounded-control text-muted-foreground/60 hover:text-foreground focus-visible:outline-none active:cursor-grabbing",children:/* @__PURE__ */t(ba,{className:"h-3.5 w-3.5"})}),/* @__PURE__ */t(K,{type:"button",variant:e.negate?"default":"outline",size:"xs","aria-pressed":e.negate,className:"px-2",onClick:()=>o(e.id,!e.negate),children:"NOT"}),/* @__PURE__ */t(Ea,{value:e.logicalOperator,onValueChange:I=>n(e.id,I),"aria-label":"Group logical operator"}),/* @__PURE__ */t("span",{className:rr,children:"Group"})]}),/* @__PURE__ */t(K,{type:"button",variant:"ghost",size:"xs","aria-label":"Remove group",className:"h-7 w-7 p-0 text-muted-foreground hover:text-foreground",onClick:()=>a&&d(a,e.id),children:/* @__PURE__ */t(ca,{className:"h-3.5 w-3.5"})})]}),/* @__PURE__ */l("div",{className:H(r>0&&"p-2"),children:[/* @__PURE__ */t(pt,{sensors:jt(qe(Wt),qe(Kt,{coordinateGetter:Pt})),collisionDetection:ft,onDragEnd:p,children:/* @__PURE__ */t(ht,{items:e.conditions.map(I=>I.id),strategy:gt,children:/* @__PURE__ */t("div",{className:"space-y-0.5",children:e.conditions.map((I,E)=>/* @__PURE__ */t(Ia,{condition:I,index:E,groupId:e.id,groupLogicalOperator:e.logicalOperator,onRemoveCondition:c,onUpdateGroupOperator:n,availableFields:v,source:D,updateConditionFields:y,replaceCondition:m},I.id))})})}),/* @__PURE__ */t(pt,{sensors:jt(qe(Wt),qe(Kt,{coordinateGetter:Pt})),collisionDetection:ft,onDragEnd:A,children:/* @__PURE__ */t(ht,{items:e.groups.map(I=>I.id),strategy:gt,children:e.groups.map(I=>x(I,r+1,e.id))})}),e.conditions.length===0&&e.groups.length===0&&/* @__PURE__ */t("p",{className:"rounded-control border border-dashed border-border/60 px-3 py-2 text-center text-[11.5px] text-muted-foreground",children:"No conditions in this group."}),/* @__PURE__ */t(La,{onAddCondition:()=>h(e.id),onAddGroup:()=>w(e.id)})]})]});}function Gl({filters:e,availableFields:r,source:a,onSave:n,onClearAll:o,onCancel:d,onChange:c}){const i=c!==void 0,{currentFilters:u,availableFields:h,isLoading:w,addCondition:v,addGroup:D,removeCondition:x,removeGroup:y,updateConditionFields:m,replaceCondition:V,updateGroupOperator:L,updateGroupNegate:J,reorderConditions:_,reorderGroups:$,generateSQLPreview:M,hasAnyFilters:te}=il({initialFilters:e,availableFields:r,...(c?{onChange:b=>c(ml(b)?b:null)}:{})}),p=jt(qe(Wt),qe(Kt,{coordinateGetter:Pt})),[A,I]=U(!1),E=(b,T=0,g)=>{if(T===0){const C=b.conditions.length===0&&b.groups.length===0;return/* @__PURE__ */l("div",{children:[/* @__PURE__ */t(pt,{sensors:p,collisionDetection:ft,onDragEnd:R=>{const{active:F,over:W}=R;if(W&&F.id!==W.id){const B=b.conditions.findIndex(ae=>ae.id===F.id),ee=b.conditions.findIndex(ae=>ae.id===W.id);B!==-1&&ee!==-1&&_(b.id,B,ee);}},children:/* @__PURE__ */t(ht,{items:b.conditions.map(R=>R.id),strategy:gt,children:/* @__PURE__ */t("div",{className:"space-y-0.5",children:b.conditions.map((R,F)=>/* @__PURE__ */t(Ia,{condition:R,index:F,groupId:b.id,groupLogicalOperator:b.logicalOperator,onRemoveCondition:x,onUpdateGroupOperator:L,availableFields:h,source:a,updateConditionFields:m,replaceCondition:V},R.id))})})}),/* @__PURE__ */t(pt,{sensors:p,collisionDetection:ft,onDragEnd:R=>{const{active:F,over:W}=R;if(W&&F.id!==W.id){const B=b.groups.findIndex(ae=>ae.id===F.id),ee=b.groups.findIndex(ae=>ae.id===W.id);B!==-1&&ee!==-1&&$(b.id,B,ee);}},children:/* @__PURE__ */t(ht,{items:b.groups.map(R=>R.id),strategy:gt,children:b.groups.map(R=>E(R,T+1,b.id))})}),C&&!i&&/* @__PURE__ */t("p",{className:"rounded-control border border-dashed border-border/60 px-3 py-2 text-center text-[11.5px] text-muted-foreground",children:"No filters yet. Add a condition to limit the rows this card shows."}),/* @__PURE__ */t(La,{onAddCondition:()=>v(b.id),onAddGroup:(i?b.conditions.length+b.groups.length>=2:A)?()=>D(b.id):void 0})]},b.id);}return/* @__PURE__ */t(vl,{group:b,depth:T,parentGroupId:g,onUpdateGroupOperator:L,onUpdateGroupNegate:J,onRemoveGroup:y,onRemoveCondition:x,onReorderConditions:_,onReorderGroups:$,onAddCondition:v,onAddGroup:D,availableFields:h,source:a,renderFilterGroup:E,updateConditionFields:m,replaceCondition:V},b.id);},N=no(e);return/* @__PURE__ */l("div",{className:H("group/filters",i?"flex flex-col":"flex min-h-0 flex-1 flex-col"),"data-inline":i||void 0,children:[/* @__PURE__ */l("div",{className:i?"":"min-h-0 flex-1 overflow-y-auto px-3 py-3",children:[w?/* @__PURE__ */l("div",{className:"flex items-center justify-center gap-2 py-6 text-[12px] text-muted-foreground",children:[/* @__PURE__ */t(Xt,{className:"h-3.5 w-3.5 animate-spin"}),"Loading columns…"]}):E(u),!i&&/* @__PURE__ */l("div",{className:"mt-3 flex items-center gap-2 border-t border-border/60 pt-3",children:[/* @__PURE__ */t(Nn,{size:"xs",id:"advanced-mode",checked:A,onCheckedChange:b=>I(b)}),/* @__PURE__ */t(ce,{htmlFor:"advanced-mode",className:"text-[12px] font-normal leading-none text-foreground",children:"Advanced mode"}),/* @__PURE__ */t("span",{className:"text-[11px] text-muted-foreground",children:"Nest conditions in groups"})]}),te&&!i&&/* @__PURE__ */l("div",{className:"mt-3 border-t border-border/60 pt-3",children:[/* @__PURE__ */t("div",{className:H("mb-1.5",rr),children:"Where clause"}),/* @__PURE__ */t("pre",{className:"overflow-x-auto whitespace-pre-wrap break-words rounded-[6px] border border-border bg-muted/40 px-3 py-2 font-mono text-[12px] leading-[1.55] text-foreground",children:M(u)})]})]}),i?null:/* @__PURE__ */l("div",{className:"flex shrink-0 items-center justify-between gap-2 border-t border-border px-3 py-2.5",children:[/* @__PURE__ */t("div",{children:N>0&&/* @__PURE__ */t(K,{size:"xs",variant:"ghost",className:"text-muted-foreground hover:text-foreground",onClick:()=>o==null?void 0:o(),children:"Clear all"})}),/* @__PURE__ */l("div",{className:"flex items-center gap-1.5",children:[/* @__PURE__ */t(K,{size:"xs",variant:"ghost",onClick:()=>d==null?void 0:d(),children:"Cancel"}),/* @__PURE__ */t(K,{size:"xs",onClick:()=>n==null?void 0:n(te?u:null),children:"Apply filters"})]})]})]});}export{_l as C,Vl as F,tl as I,co as L,mo as S,Fl as V,Ml as a,Gl as b,Ko as c,ql as u};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{aJ as Q,i as ee,k as T,n as te,T as V,aK as R,aL as X,aM as re,aN as G,aO as q,an as ne,ap as oe,aP as w,aQ as $}from"./pivot-result-contract-expectations-DTQAgr4n.js";import{h as S}from"./export-file-format-B-wQNHIn.js";import{a6 as ae,aX as H,m as E,k as se}from"./validators-CqV3Yka1.js";import"./matrix-operation-contract-D1RC1bfi.js";import"./analytics-base-schemas-BREc5WGv.js";import{readPdfCapacityFacts as ie,PDF_SAFETY_LIMIT_EXCEEDED as O,PDF_CAPACITY as P,PDF_NUMBER_COLUMN_TOO_WIDE as K,getUtf8ByteLength as ue,FAST_PDF_POLICY as ce,isPdfCapacityRefusalCode as le}from"../pdf-export-policy/index.js";import{w as me}from"./raw-temporal-value-DeyEhL0S.js";function de(e,t,r){const n={...t,locale:t.locale??r};if(n.type==="number")return T(e,n);const{prefix:o,suffix:a,...s}=n;return`${o??""}${T(e,{...s,negativeStyle:n.type==="currency"?n.negativeStyle:"minus"})}${a??""}`;}function F(e,t,r){return e===null?{value:e,text:null}:!t||!ee(t)&&t.type!=="duration"?{value:e,text:T(e,{type:"number",locale:r})}:t.type==="duration"?{value:e,text:te(e,{inputUnit:t.inputUnit,outputStyle:t.outputStyle,largestUnit:t.largestUnit,smallestUnit:t.smallestUnit,maxUnits:t.maxUnits,prefix:t.prefix,suffix:t.suffix,negativeInParentheses:t.negativeStyle==="parentheses"})}:{value:e,text:de(e,t,r)};}function U(e,t,r,n){return e===null?{value:e,text:null}:n==="percent"?{value:e,text:T(e,{type:"percent",locale:r,minimumFractionDigits:t,maximumFractionDigits:t,percentValueMode:"fraction"})}:{value:e,text:T(e,{type:"number",locale:r,minimumFractionDigits:t,maximumFractionDigits:t,suffix:"×"})};}function j(e,t){if(e===void 0)return t;if(!Number.isInteger(e)||e<0||e>6)throw new RangeError("Comparison precision must be an integer from 0 to 6.");return e;}function He(e,t){const r={mode:t.displayMode,current:F(e.currentValue,t.metricFormat,t.locale),comparison:F(e.comparisonValue,t.metricFormat,t.locale)};return(t.displayMode==="difference"||t.displayMode==="both")&&(r.difference=F(e.delta,Q(t.metricFormat),t.locale)),(t.displayMode==="percent_change"||t.displayMode==="both")&&(r.percentChange=U(e.percentChange,j(t.precision,1),t.locale,"percent")),t.displayMode==="ratio"&&(r.ratio=U(e.ratio,j(t.precision,2),t.locale,"ratio")),r;}const Ke={rowLabels:"tabular",subtotals:"after"};function We(e,t){const r=t.rowLabels==="outline"?{kind:"compact"}:e.layout.kind==="tabular"?e.layout:{kind:"tabular",repeatLabels:!1},n=e.totals.rows;return{...e,layout:r,totals:{...e.totals,rows:{...n,levels:Object.fromEntries(Object.entries(n.levels).map(([o,a])=>[o,{...a,position:t.subtotals}]))}}};}const fe=2;function he(e){return typeof e=="number"?Number.isInteger(e):H(e)?!e.value.includes("."):!0;}function pe(e,t,r){const n=e.descriptors.measures.filter(s=>r.measureFormats[s.id]===void 0&&s.semanticFormat===void 0&&ae(s.column.dataType)==="number");if(n.length===0)return r;const o=/* @__PURE__ */new Set();e.columns.forEach((s,u)=>{if(!(s.kind!=="measure"||o.has(s.measureId)))for(const m of t){const c=m.values[u];if((c==null?void 0:c.kind)==="value"&&!he(c.value)){o.add(s.measureId);return;}}});const a={...r.measureFormats};for(const{id:s}of n){const u=o.has(s)?fe:0;a[s]={type:"number",minimumFractionDigits:u,maximumFractionDigits:u,useGrouping:!0};}return{...r,measureFormats:a};}function L(e){return E(e.slice(0,-1));}function ge(e,t){return t.length>e.length&&E(t.slice(0,e.length))===E(e);}function ye(e){return e.map((t,r)=>{if(r===0||t.kind!=="layout")return!1;const n=e[r-1];if(n.kind!=="layout")return!1;if(t.role!=="member"||ge(n.rowPath,t.rowPath))return!0;const o=e[r-2];return n.role==="member"&&(!o||o.kind!=="layout"||o.role!=="member"||L(o.rowPath)!==L(n.rowPath))&&t.rowPath.length===n.rowPath.length&&L(t.rowPath)===L(n.rowPath);});}const we="pdf-group-continuation";function W(e,t,r){return!(r!=null&&r.hasTextAffixes)&&t.kind==="value"&&(typeof t.value=="number"||H(t.value))?e:S(e);}function be(e,t,r){const n=V(e.descriptors,t.presentation,r),o=e.columns.map(i=>{var l;return i.kind==="measure"&&((l=n.measureSemantics.get(i.measureId))==null?void 0:l.isNumeric)===!0;}),a=i=>R([i],n.levels),s=(i,l,d)=>X(i,l,t.presentation.totals[d],n.levels),u=e.columns.map(i=>{if(i.kind!=="measure")return i.label;const l=i.columnPath.map(a);return i.role!=="member"&&l.push(s(i.columnPath,i.role,"columns")),[...l,i.label].join(" / ");}),m=Math.min(t.spec.columns.length,Math.max(0,...e.columns.map(i=>i.kind==="measure"?i.columnPath.length+(i.role!=="member"?1:0):0))),c=Array.from({length:m+1},(i,l)=>e.columns.map(d=>l===m?d.label:d.kind!=="measure"?"":l<d.columnPath.length?a(d.columnPath[l]):l===d.columnPath.length&&d.role!=="member"?s(d.columnPath,d.role,"columns"):"")),f=(i,l)=>re({path:i.rowPath,role:i.kind==="layout"?i.role:"member",levelCount:Math.max(1,t.spec.rows.length),repeatLabels:t.presentation.layout.kind!=="tabular"||t.presentation.layout.repeatLabels,previousPath:l==null?void 0:l.rowPath}),v=(i,l)=>{if(i.kind!=="layout")throw new Error("Layout presentation requires layout rows.");if(i.values.length!==e.columns.length)throw new Error("Matrix row does not match its frozen layout.");const d=f(i,l);return e.columns.map((h,p)=>{if(h.kind==="hierarchy")return`${" ".repeat(Math.max(0,i.rowPath.length-1))}${s(i.rowPath,i.role,"rows")}`;if(h.kind==="level"){const D=t.spec.rows.findIndex(J=>J.id===h.levelId),b=d[D];return b!=null&&b.visible?b.total?s(i.rowPath,i.role,"rows"):R(b.path,n.levels):"";}const C=i.values[p],x=n.measures.get(h.measureId);if(C.kind==="value"&&!x)throw new Error("Matrix value is missing its measure descriptor.");return G(C,x,t.presentation.absence);});},_=(i,l)=>v(i,l).map((d,h)=>{const p=e.columns[h];return p.kind==="measure"?W(d,i.values[h],n.measureSemantics.get(p.measureId)):S(d);});return{headers:u,headerBands:c,numericColumns:o,formatting:n,row:(i,l)=>v(i,l),continuedColumns:(i,l)=>{const d=p=>(p==null?void 0:p.kind)==="layout"&&p.role==="member";if(!d(i)||!d(l))return[];const h=f(i,l);return e.columns.flatMap((p,C)=>{var D;if(p.kind!=="level")return[];const x=t.spec.rows.findIndex(b=>b.id===p.levelId);return x<i.rowPath.length&&((D=h[x])==null?void 0:D.visible)===!1?[C]:[];});},csvRow:i=>_(i),csvRows:(i,l)=>i.map((d,h)=>_(d,h?i[h-1]:l??void 0))};}function Ye(e){return e.columns.map(t=>S(t.label));}function Ze(e,t,r){return _e(e,t,r).map((n,o)=>{const a=t.columns[o];return a.kind==="measure"?W(n,e.values[o],r.measureSemantics.get(a.measureId)):S(n);});}function _e(e,t,r){if(e.kind!=="flat")throw new Error("Flat Matrix CSV requires flat rows.");if(e.values.length!==t.columns.length)throw new Error("Matrix row does not match its frozen layout.");const n=[...e.rowPath,...e.columnPath];return t.columns.map((o,a)=>{if(o.kind==="measure"){const u=e.values[a],m=r.measures.get(o.measureId);if(u.kind==="value"&&!m)throw new Error("Matrix value is missing its measure descriptor.");return G(u,m,r.absence);}const s=o.kind==="level"?n.find(u=>u.levelId===o.levelId):void 0;if(!s)throw new Error("Flat Matrix row does not match its frozen layout.");return R([s],r.levels);});}function Pe(e){const t=be(e.layout,e.request,e.report),r=e.layout.columns.map((s,u)=>({index:u,columnId:`matrix:${u}`,label:t.headers[u],isNumeric:t.numericColumns[u]})),n=(s,u,m)=>({text:s,colspan:1,rowspan:1,columnId:r[u].columnId,isHeader:m,isNumeric:r[u].isNumeric,className:r[u].isNumeric?"numeric":e.layout.columns[u].kind==="hierarchy"?"matrix-hierarchy":""}),o=[],a=e.layout.columns.findIndex(s=>s.kind==="measure");e.request.spec.columns.length&&a>=0&&o.push({repeatHeader:!0,headerType:"pivot-axis",headerRowIndex:0,cells:[...(a?[{...n("",0,!0),colspan:a}]:[]),{...n(e.request.spec.columns.map(s=>q(s,e.request.presentation)).join(" / "),a,!0),colspan:e.layout.columns.length-a,isNumeric:!1,className:""}]});for(const[s,u]of t.headerBands.entries())o.push({repeatHeader:!0,headerType:s===t.headerBands.length-1?"metrics":"pivot-level",headerRowIndex:o.length,cells:u.map((m,c)=>n(m,c,!0))});return{headers:o,rows:e.rows.map((s,u)=>{const m=new Set(t.continuedColumns(s,e.rows[u-1]));return{index:u,type:s.kind==="layout"&&s.role!=="member"?"subtotal":"data",subtotalLevel:String(s.rowPath.length),cells:t.row(s,e.rows[u-1]).map((c,f)=>m.has(f)?{...n(c,f,!1),className:we}:n(c,f,!1))};}),grandTotal:null,metadata:{tableType:"pivot",totalRows:e.rows.length,totalColumns:r.length,rowLevels:e.layout.columns.filter(s=>s.kind!=="measure").length,pivotLevels:e.request.spec.columns.length,hasGrandTotal:!1,columnOrder:r.map(s=>s.columnId),columns:r}};}function ve(e,t,r){const{levels:n}=V(e.descriptors,t.presentation,r),o=t.spec.columns.length>0,a=[],s=[],u=e.columns.map((c,f)=>{if(c.kind!=="measure")return null;const v=o?`${c.role}:${E(c.columnPath)}`:`measure:${f}`;let _=a.indexOf(v);return _<0&&(_=a.push(v)-1,s.push(o?X(c.columnPath,c.role,t.presentation.totals.columns,n):c.label)),_;}),m=t.spec.columns[t.spec.columns.length-1];return{columnGroups:u,groupLabels:s,groupLevelLabel:m?q(m,t.presentation):"Measures"};}function ze(e){const{layout:t,rows:r,report:n}=e,o={...e.request,presentation:pe(t,r,e.request.presentation)},a=Pe({layout:t,rows:r,request:o,report:n}),s=ye(r),u=ve(t,o,n),m={...a,rows:a.rows.map((c,f)=>({...c,keepWithPrevious:s[f]})),metadata:{...a.metadata,...u}};return{request:o,table:m,...u};}const y=e=>e.toLocaleString("en-US"),M=e=>`${y(Math.ceil(e/1048576))} MB`,I="export the data as CSV or Excel";function Je(e){const t=ie(e.facts),r=e.dataExport?`Add a filter to narrow it, or ${I}.`:"Add a filter to narrow it, then export again.";switch(e.code){case"PDF_ROW_LIMIT_EXCEEDED":{const n=e.subject??"This table",o=t.rowLimit??P.maxTableRows;return t.rowCount!==void 0?`${n} has ${y(t.rowCount)} rows. A PDF holds up to ${y(o)} rows per table. ${r}`:`${n} has more than ${y(o)} rows, the most a PDF holds per table. ${r}`;}case"PDF_PAGE_LIMIT_EXCEEDED":{const n=e.subject??"This PDF",o=t.pageLimit??P.maxPages;return t.pageCount!==void 0?`${n} is ${y(t.pageCount)} pages. A PDF holds up to ${y(o)}. ${r}`:`${n} is longer than ${y(o)} pages, the most a PDF holds. ${r}`;}case"PDF_SIZE_LIMIT_EXCEEDED":{const n=e.subject??"This PDF",o=t.byteLimit??P.maxFileBytes;return t.bytes!==void 0?`${n} is ${M(t.bytes)}. A PDF file holds up to ${M(o)}. ${r}`:`${n} is larger than ${M(o)}, the most a PDF file holds. ${r}`;}case"PDF_CAPTURE_TOO_TALL":return`${e.subject??"This dashboard"} is too long to print as one PDF. Print one sheet or fewer cards${e.dataExport?`, or ${I}`:""}.`;case K:return`A number in this table is too wide for its column in a PDF. Use landscape or fewer columns${e.dataExport?`, or ${I}`:""}.`;case O:return`This PDF is over what a PDF holds: ${y(P.maxTableRows)} rows per table, ${y(P.maxPages)} pages and ${M(P.maxFileBytes)}. ${r}`;}}class xe extends Error{constructor(t,r=O){super(t),this.code=r;}}function Te(e){return le(e)||e===O||e===K;}function B(e){if(!e||typeof e!="object")return;const{error:t,message:r,detail:n}=e;for(const o of[t,r,n])if(typeof o=="string"&&o.trim())return o.trim();}async function $e(e){const t=`PDF request failed: ${e.status} ${e.statusText}`.trim(),r=e.headers.get("content-type")||"";try{if(r.includes("application/json")){const o=await e.json(),a=typeof o.code=="string"?o.code:typeof o.errorCode=="string"?o.errorCode:void 0;return{message:B(o)||t,code:a};}const n=await e.text();if(!n.trim())return{message:t};try{const o=JSON.parse(n),a=typeof o.code=="string"?o.code:typeof o.errorCode=="string"?o.errorCode:void 0;return{message:B(o)||n.trim(),code:a};}catch{return{message:n.trim()};}}catch{return{message:t};}}async function Qe(e){if(!e.token)throw new Error("Missing auth token for PDF export");if(ue(e.serializedPayload)>ce.maxRequestBytes)throw new Error("Fast-path PDF request exceeds the structured body limit");const t=await(e.fetchImpl??fetch)(e.url,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.token}`},body:e.serializedPayload,signal:e.signal});if(!t.ok){const n=await $e(t);throw Te(n.code)?new xe(n.message,n.code):new Error(n.message);}const r=await t.json();if(r!=null&&r.error)throw new Error(r.error);if(typeof(r==null?void 0:r.url)!="string"||!r.url.trim())throw new Error("Fast-path PDF response missing download URL");return r;}const et=1,Y=["loading","measuring","checking","laidOut"],Ce=["document_matrix_too_large","document_matrix_unavailable","document_matrix_too_wide","document_kpi_value_overflow","print_inputs_not_captured","document_section_setup","document_input_missing","document_section_query_failed","document_table_completeness_unverified","document_row_limit_exceeded","document_section_render_failed","document_page_overflow","document_sheet_not_found","document_print_timed_out","document_page_limit_exceeded"];function tt(e){return Ce.includes(e);}const De=64,Le=120,Me=3,Ee=80,Se=[...Y,"noPageStack","unknown"];function A(e,t){return typeof e!="string"?void 0:e.trim().slice(0,t).trim()||void 0;}function g(e,t){return typeof e=="number"&&Number.isInteger(e)&&e>=t?e:void 0;}function k(e,t){return t.includes(e)?e:void 0;}function Fe(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e);}catch{return{};}if(!t||typeof t!="object"||Array.isArray(t))return{};const r=t,n=Array.isArray(r.inputLabels)?r.inputLabels.map(a=>A(a,Ee)).filter(a=>a!==void 0).slice(0,Me):[],o={sectionId:A(r.sectionId,De),sectionTitle:A(r.sectionTitle,Le),pageNumber:g(r.pageNumber,1),rowCount:g(r.rowCount,0),rowLimit:g(r.rowLimit,1),inputLabels:n.length?n:void 0,overflowAxis:k(r.overflowAxis,["height","width"]),overflowPx:g(r.overflowPx,0),matrixLimit:k(r.matrixLimit,["rows","bytes"]),layoutStage:k(r.layoutStage,Se),loadingSectionCount:g(r.loadingSectionCount,0),measuredRowCount:g(r.measuredRowCount,0),totalRowCount:g(r.totalRowCount,0),pageCount:g(r.pageCount,0),pageLimit:g(r.pageLimit,1)};return Object.fromEntries(Object.entries(o).filter(([,a])=>a!==void 0));}function rt(e){const t=Fe(e.facts),r=t.sectionTitle?`Section "${t.sectionTitle}"`:t.sectionId?`Section ${t.sectionId}`:"A section",n=t.pageNumber!==void 0?` on page ${t.pageNumber}`:"";switch(e.code){case"document_section_setup":return`${r} is not set up to print.`;case"document_input_missing":return t.inputLabels?`${r} needs a value for ${t.inputLabels.join(", ")}.`:`${r} needs a value for a required input.`;case"document_section_query_failed":return`${r}: its data could not be loaded.`;case"document_table_completeness_unverified":return`${r}: the query returned no total row count, so the table could not be confirmed complete.`;case"document_row_limit_exceeded":return t.rowCount!==void 0&&t.rowLimit!==void 0?`${r} has ${t.rowCount} rows; a document table prints up to ${t.rowLimit}.`:`${r} has more rows than a document table prints.`;case"document_section_render_failed":return`${r} could not be drawn.`;case"document_page_overflow":return`${r}${n} does not fit the page${t.overflowAxis?` (${t.overflowAxis}`:""}${t.overflowAxis&&t.overflowPx!==void 0?`, ${t.overflowPx} px over`:""}${t.overflowAxis?")":""}.`;case"document_matrix_too_large":return t.matrixLimit==="rows"&&t.rowLimit!==void 0?`${r}: the Matrix has more than ${t.rowLimit} rows, the most a report prints.`:`${r}: the Matrix is too large to print.`;case"document_matrix_unavailable":return`${r}: the Matrix result could not be loaded.`;case"document_matrix_too_wide":return`${r}: the Matrix is wider than the page.`;case"document_kpi_value_overflow":return`${r}: a KPI value does not fit its tile.`;case"print_inputs_not_captured":return t.inputLabels?`The report's input values were not saved: ${t.inputLabels.join(", ")}.`:"The report's input values were not saved.";case"document_sheet_not_found":return"The requested Document sheet is not in the dashboard.";case"document_page_limit_exceeded":return t.pageCount!==void 0&&t.pageLimit!==void 0?`The Document is ${t.pageCount} pages; a PDF holds up to ${t.pageLimit}.`:"The Document has more pages than a PDF holds.";case"document_print_timed_out":return[`The Document did not finish preparing in time (stage ${t.layoutStage??"unknown"}`,t.measuredRowCount!==void 0?`; ${t.measuredRowCount} of ${t.totalRowCount??"unknown"} rows measured`:"",t.pageCount!==void 0?`; ${t.pageCount} pages`:"",t.loadingSectionCount?`; ${t.loadingSectionCount} sections loading`:"",")."].join("");}}function Ie(e){return Y.includes(e);}function N(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0;}function nt(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e);}catch{return;}if(!t||typeof t!="object"||Array.isArray(t))return;const{stage:r,measuredRowCount:n,totalRowCount:o,pageCount:a}=t;if(!(!Ie(r)||!N(n)||o!==null&&!N(o)||a!==null&&!N(a)))return{stage:r,measuredRowCount:n,totalRowCount:o,pageCount:a};}function ot(e,t,r){const n=t.from>e.start?t.from:e.start,o=t.to&&t.to<e.end?t.to:e.end,s=n<=r&&o>r?"running":n>e.start?"start":o<e.end?"end":void 0;return{start:n,end:o,...(s?{partial:s}:{})};}function at(e,t,r){switch(t){case"running":return`${e} (so far)`;case"start":return r?`${e} (from ${r.start})`:`${e} (partial)`;case"end":return r?`${e} (to ${r.end})`:`${e} (partial)`;default:return e;}}function st(e,t,r){const n=Date.parse(e.startInclusive),o=Date.parse(e.endExclusive);if(!Number.isFinite(n)||!Number.isFinite(o))return;if(t.granularity==="hour"||t.granularity==="minute"||t.granularity==="second"){const m=c=>{try{return new Intl.DateTimeFormat((r==null?void 0:r.locale)??"en-US",{timeStyle:(r==null?void 0:r.dateTime.timeStyle)??"short",timeZone:t.calendar.tz}).format(new Date(c));}catch{return new Date(c).toISOString();}};return{start:m(n),end:m(o)};}const a={kind:"temporal_bucket",granularity:"day",calendar:t.calendar};let s;try{s=ne({metadata:a,locale:(r==null?void 0:r.locale)??"en-US",...(r?{styles:{dateStyle:r.dateStyle,dateTime:r.dateTime}}:{})});}catch{s=void 0;}const u=m=>{const c=me(new Date(m),t.calendar.tz),f=`${String(c.year).padStart(4,"0")}-${String(c.month).padStart(2,"0")}-${String(c.day).padStart(2,"0")}`;try{return s?oe({value:f,metadata:a,format:s.format}):f;}catch{return f;}};return{start:u(n),end:u(o-1)};}function it(e){return((e==null?void 0:e.filterValues)??[]).filter(Ae).map(ke);}function Ae(e){return!!e&&typeof e=="object"&&typeof e.name=="string"&&Array.isArray(e.values);}function ke(e){if(!("relativeMeta"in e)||e.relativeMeta===void 0)return e;const{relativeMeta:t,...r}=e,n=se(t);return n?{...r,relativeMeta:n}:r;}const Ne=/* @__PURE__ */new Set(["day","week","month","quarter","year"]);function Re(e,t){try{const r=$(e),n=w(r,t,"yyyy-MM-dd");if(w(r,t,"HH:mm:ss.SSS")!=="00:00:00.000")return{date:n,time:w(r,t,"h:mm a")};const[o,a,s]=n.split("-").map(Number),u=new Date(Date.UTC(o,a-1,s));return u.setUTCDate(u.getUTCDate()-1),{date:w(u,"UTC","yyyy-MM-dd")};}catch{return;}}function Z(e,t,r){const n=Re(e.end,t);if(n)return{start:w($(e.start),t,r?"MMM d":"MMM d, yyyy"),endDate:w($(`${n.date}T00:00:00Z`),"UTC","MMM d, yyyy"),...(n.time?{endTime:n.time}:{})};}function z(e){return!!(e&&Ne.has(e));}function ut(e,t,r,n=!1){if(z(r))try{const a=Z(e,t,!1);if(a&&a.start===a.endDate)return a.endTime?`${a.endDate} until ${a.endTime}`:a.endDate;}catch{}const o=Oe(e,t,r,n);return`${o.start} – ${o.end}`;}function Oe(e,t,r,n=!1){try{if(z(r)){const o=Z(e,t,n);if(o)return{start:o.start,end:o.endTime?`${o.endDate}, ${o.endTime}`:o.endDate};}if(r==="second"||r==="minute"||r==="hour"){const o=n?"MMM d, h:mm a":"MMM d, yyyy, h:mm a";return{start:w($(e.start),t,o),end:`before ${w($(e.end),t,o)}`};}}catch{}return{start:e.start,end:`before ${e.end}`};}export{Oe as A,et as D,Ke as M,we as P,He as a,Ye as b,Ze as c,Pe as d,ze as e,ut as f,We as g,fe as h,pe as i,ye as j,Je as k,xe as l,_e as m,Te as n,Qe as o,be as p,Ce as q,$e as r,tt as s,Fe as t,rt as u,nt as v,ot as w,at as x,st as y,it as z};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{jsx as a,jsxs as n}from"react/jsx-runtime";import{E as o,F as i,S as d,B as s,a as c,U as l,D as t,A as h,C as f,b}from"./semaphor-ready-indicator-DzjorP3t.js";function u(e){if(typeof window>"u")return null;const{preferences:r}=e;return/* @__PURE__ */a(o,{FallbackComponent:i,children:/* @__PURE__ */a(d,{dashboardProps:e,children:/* @__PURE__ */n(s,{children:[/* @__PURE__ */a(c,{componentType:"dashboard",componentId:e.id}),/* @__PURE__ */a(l,{appearance:e.appearance,children:/* @__PURE__ */a(t,{preferences:r,children:/* @__PURE__ */a(h,{children:/* @__PURE__ */a("main",{className:"flex h-full flex-col",children:/* @__PURE__ */a(f,{...e,type:"dashboard",children:/* @__PURE__ */a(b,{})})})})})})]})})});}export{u as D};
|