@devtable/dashboard 12.2.0 → 12.3.0
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/dashboard.es.js +9 -9
- package/dist/dashboard.umd.js +3 -3
- package/dist/stats.html +1 -1
- package/package.json +1 -1
package/dist/dashboard.umd.js
CHANGED
|
@@ -53,7 +53,7 @@ Check the top-level render call using <`+E+">.")}return I}}function iu(w,I){{if(
|
|
|
53
53
|
</table>
|
|
54
54
|
`;function hs(e,t){const n=Object.keys(t),r=Object.values(t);try{return new Function(...n,`return \`${e}\`;`)(...r)}catch(i){throw n.length===0&&e.includes("$")?new Error("[formatSQL] insufficient payload"):i}}function xs(e,t){try{return hs(e,t)}catch(n){return console.error(n),n.message}}function sd({sql:e,pre_process:t}){if(!t.trim())return e;try{return new Function(`return ${t}`)()({sql:e},nt)}catch(n){return console.error(n),e}}function rd(e,t,n){if(!e.trim())return t;try{return new Function(`return ${e}`)()(t,nt,n)}catch(r){return console.error(r),t}}function id(e){e=e||{};const t=Object.keys(e).sort(),n=[];for(let r=0;r<t.length;r++){const i=t[r];if(i!="authentication"&&e[i])n.push(t[r]+"="+(typeof e[i]=="object"?JSON.stringify(e[i]):e[i]));else{const o=Object.keys(e[i]).sort();for(let l=0;l<o.length;l++){const c=o[l];c!="sign"&&e[i][c]&&n.push(o[l]+"="+(typeof e[i][c]=="object"?JSON.stringify(e[i][c]):e[i][c]))}}}return n.sort().join("&")}function ad(e,t){let n=id(e);return n+="&key="+t,Xu.MD5(n).toString().toUpperCase()}class Ji{constructor(){this.type="default_api_client",this.baseURL="http://localhost:31200",this.app_id="",this.app_secret=""}getAuthentication(t){if(!this.app_id||!this.app_secret)return;const n=new Date().getTime().toString();return{app_id:this.app_id,nonce_str:n,sign:ad({app_id:this.app_id,nonce_str:n,...t},this.app_secret)}}getRequest(t,n){return(r,i,o,l)=>{const c=this.buildHeader(o),u=this.buildAxiosConfig(t,r,i,o,c,n);return He(u).then(d=>l?d:d.data).catch(d=>Promise.reject(d))}}get(t){return this.getRequest("GET",t)}post(t){return this.getRequest("POST",t)}put(t){return this.getRequest("PUT",t)}buildAxiosConfig(t,n,r,i,o,l){const c={baseURL:this.baseURL,method:t,url:n,params:t==="GET"?r:i.params,headers:o,signal:l};return["POST","PUT"].includes(t)&&(c.data=i.string?JSON.stringify(r):r,c.data.authentication=this.getAuthentication(c.data)),c}buildHeader(t){const n=window.localStorage.getItem("token");return{"X-Requested-With":"XMLHttpRequest","Content-Type":t.string?"application/x-www-form-urlencoded":"application/json",authorization:n?`bearer ${n}`:"",...t.headers}}}class od{constructor(t){this.implementation=t}getRequest(t,n){return this.implementation.getRequest(t,n)}get(t){return this.getRequest("GET",t)}post(t){return this.getRequest("POST",t)}put(t){return this.getRequest("PUT",t)}}class Zi extends Ji{constructor(){super(...arguments);P(this,"makeQueryENV",null)}query(n){return async(r,i={})=>{var o;return r.env||(r.env=((o=this.makeQueryENV)==null?void 0:o.call(this))??{error:"failed to run makeQueryENV"}),this.post(n)("/query",r,i)}}httpDataSourceQuery(n){return async(r,i={})=>{var o;return r.env||(r.env=((o=this.makeQueryENV)==null?void 0:o.call(this))??{error:"failed to run makeQueryENV"}),this.getRequest("POST",n)("/query",r,i,!0)}}structure(n){return async(r,i={})=>this.post(n)("/query/structure",r,i)}}class Hi{constructor(t){this.implementation=t}query(t){return this.implementation.query(t)}httpDataSourceQuery(t){return this.implementation.httpDataSourceQuery(t)}structure(t){return this.implementation.structure(t)}getRequest(t,n){return this.implementation.getRequest(t,n)}get(t){return this.getRequest("GET",t)}post(t){return this.getRequest("POST",t)}put(t){return this.getRequest("PUT",t)}}const Mt=new Zi;function fs(e){Mt.baseURL!==e.apiBaseURL&&(Mt.baseURL=e.apiBaseURL),e.app_id&&(Mt.app_id=e.app_id),e.app_secret&&(Mt.app_secret=e.app_secret),e.makeQueryENV&&(Mt.makeQueryENV=e.makeQueryENV)}const ea=new Hi(Mt),Ke=ea,Yt=g.forwardRef(function({value:t,onChange:n,...r},i){return s.jsx(a.TextInput,{ref:i,value:t,onChange:n,...r})});function z(e){const[t,n]=e.split(".");return{queryID:t,columnKey:n}}function ld(e){return e.includes(".")?z(e):{queryID:"",columnKey:e}}function Ye(e,t){var i;const{queryID:n,columnKey:r}=z(t);return n?r?((i=e[n])==null?void 0:i.map(o=>o[r]))??[]:e[n]:[]}function Xt(e,t){const{queryID:n}=z(t);return n?e[n]:[]}function cd(e){return Object.values(e)[0]}function mn(e,t){const{queryID:n,columnKey:r}=z(t);return e[r]}const ta=["function aggregation({ queryData }, utils) {",' return "Aggregation Result";',"}"].join(`
|
|
55
55
|
`),zt={type:"none",config:{},fallback:"0"};function ud(e){const t=Array.from(e).sort((r,i)=>r-i),n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function dd(e,t){switch(t.type){case"sum":return y.sum(e);case"mean":return y.mean(e);case"median":return ud(e);case"max":return y.max(e);case"min":return y.min(e);case"quantile":return Rt.quantile(e,t.config.p);case"CV":const n=It.std(...e),r=It.mean(...e);return r?n/r:Number.NaN;case"std":return It.std(...e);default:return e}}function gs(e,t){const n=e.map(Number),r=dd(n,t);return typeof r=="number"?Number.isFinite(r)?r:t.fallback:r??t.fallback}function pd(e,t,n){try{const r=Xt(e,t);return new Function(`return ${n.config.func}`)()({queryData:r},nt)}catch(r){return console.error(r),r.message}}function yn(e,t,n){try{return n.type==="custom"?pd(e,t,n):gs(Ye(e,t),n)}catch(r){return console.error(r),null}}class hd{constructor({valueRange:t,colorRange:n}){P(this,"mapper");this.mapper=yt.interpolate(t,n)}getColor(t){return this.mapper(t)}}const me={mantissa:0,output:"number",trimMantissa:!1,average:!1,absolute:!1};function G(e,{absolute:t,...n}){if(e===null)return String(e);try{let r=xn(e).value();if(r===void 0||Number.isNaN(r))throw new Error(`[formatNumber]Not a number: ${e}`);return t&&(r=Math.abs(r)),xn(r).format(n)}catch(r){return console.debug(r),String(e)}}function xd(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?`Array(${e.length})`:e.toString()}function st({data_field:e,aggregation:t},n){return yn(n,e,t)}function Ae({formatter:e,aggregation:t},n){if(typeof n!="string"&&typeof n!="number")return xd(n);if(t.type==="custom")return n;try{return G(n,e)}catch(r){return console.error(r),n}}function fd(e,t){if(e.type==="static")return e.staticColor;if(e.type==="continuous")try{if(typeof t!="number")throw new Error(`[getColorByColorConf] Invalid type of aggregated value: ${t}`);return new hd(e).getColor(t)}catch(n){return console.error(n),"black"}return"black"}function gd(e,t){const{color:n,data_field:r,aggregation:i,size:o,weight:l}=e,c=yn(t,r,i),u=Ae(e,c);return s.jsx(a.Text,{sx:{fontSize:o,display:"inline"},color:fd(n,c),weight:l,children:u})}function md(e,t){const n={};return e.forEach(r=>{const i=r.name;n[i]=gd(r,t)}),n}function yd(e){return e.split(" ").map((t,n)=>s.jsxs(g.Fragment,{children:[t," "]},n))}function bd(e){const n=e.replaceAll("<br />","<br/>").replaceAll(`
|
|
56
|
-
`,"<br/>").split("<br/>");return n.map((i,o)=>{const l=[yd(i)];return o!==n.length-1&&l.push(s.jsx("br",{},`br-${o}`)),l}).flat().filter(i=>i!==void 0)}function ms(e){return bd(e)}function Jt(e,t,n){const r=md(t,n),i=/^\{(.+)\}(.*)$/;return e.split("$").map((o,l)=>{const c=i.exec(o);if(!c)return ms(o);const u=r[c[1]];if(!u)return ms(o);const d=c[2]??"";return s.jsxs(g.Fragment,{children:[u,ms(d)]},`${o}-${l}`)})}function jd(e,t){const{data_field:n,aggregation:r}=e,i=yn(t,n,r);return Ae(e,i)}function na(e,t){const n={};return e.forEach(r=>{n[r.name]=jd(r,t)}),n}function bn(e,t,n){const r=na(t,n),i=/^\{(.+)\}(.*)$/;return e.split("$").map(o=>{const l=i.exec(o);if(!l)return o;const c=r[l[1]];if(!c)return o;const u=l[2]??"";return`${c}${u}`}).join("")}const ys={grid:{axis:"#97999D",scope:"rgba(47,140,192,0.1)",boundary:"#789AB4",reference:"#CFCFD8"},graphics:{compared:{blueDark:"#3E7CAB",blue:"#6398C7",blueLight:"#7CB0DF",blue10:"#6398C71a",redDark:"#AF5F6B",red:"#CD7C88",redLight:"#E794A0",red10:"#CD7C881a"},gradient:{distributed:"linear-gradient(90deg, #1babe6 0%, #2fc8c8 28.63%, #98d44b 48.86%, #ffd057 67.53%, #f5ae53 80.6%, #e76441 91.18%, #b90000 100%)",protrude:"linear-gradient(180deg, #ec73734d 0%, #ec737300 100%)"},level:{lv0:"#6398C7",lv1:"#61B5BF",lv2:"#54D4BB",lv3:"#F5D277",lv4:"#E8BB7F",lv5:"#DB9E84",lv6:"#CB8089"},depth:{dp0:"#FFF7F8",dp1:"#FFE1E1",dp2:"#FDBCBC",dp3:"#F39494",dp4:"#FA4242",dp5:"#E21212"},multiple:{c1:"#66B4DB",c2:"#E46464",c3:"#EEBA00",c4:"#33A678",c5:"#9D88CB",c6:"#939943",c7:"#E49792",c8:"#09A2B8",c9:"#AF5F6B",c10:"#6CA157",c11:"#3E7CAB",c12:"#6398C7",c13:"#E692BA",c14:"#97B566",c15:"#8CACE2",c16:"#CA79AC",c17:"#6DBC80",c18:"#B08F4B",c19:"#39BFA2",c20:"#826BAF"}}};function vd(){be.registerTheme("merico-light",{color:Object.values(ys.graphics.multiple),visualMap:{color:Object.values(ys.graphics.depth).reverse()},axes:[{type:"all",name:"通用坐标轴",axisLineColor:"#97999D",axisTickColor:"#97999D",axisLabelShow:!0,axisLabelColor:"#818388",splitLineShow:!0,splitLineColor:["#E0E6F1"]}]})}function sa(){vd()}function*wd(e){const t=ys.graphics[e];if(!t)throw new Error("Invalid palette key provided");const n=Object.values(t);let r=0;for(;;)yield n[r%n.length],r++}function ra(){return{filters:{},context:{}}}function bs(e){const t=ra();if(!e)return ra();const{filters:n=t.filters,context:r=t.context}=e;return{filters:n,context:r}}class je extends g.Component{constructor(t){super(t),this.state={error:null}}componentDidCatch(t){this.setState({error:t})}render(){var t;if(this.state.error){const n=()=>{this.setState({error:null})};return s.jsxs(a.Box,{children:[s.jsx(a.Text,{size:"xs",children:(t=this.state.error)==null?void 0:t.message}),s.jsx(a.Button,{variant:"subtle",size:"xs",mx:"auto",compact:!0,sx:{display:"block"},onClick:n,children:"Retry"})]})}return this.props.children}}function Cd(e,t={handleError:!0}){return n=>s.jsx(je,{...t,children:s.jsx(e,{...n})})}function Sd(e,t){return new Function(`return ${e}`)()(t,nt)}function _d(e,t,n){return Sd(e,{context:t,filters:n})}function kd(e,t){try{return new Function(`return ${e.config.processing.pre}`)()(t,nt)}catch(n){return console.error(n),t}}function Td(e,t){return new Function(`return ${e.config.processing.post}`)()(t,nt)}function Dd(e,t,n){return e?new Function(`return ${e}`)()(t,nt,n):t}function ia(){Di.use([du.CanvasRenderer,et.BarChart,et.BoxplotChart,et.FunnelChart,et.HeatmapChart,et.LineChart,et.PieChart,et.RadarChart,et.ScatterChart,et.SunburstChart,ct.CalendarComponent,ct.DataZoomComponent,ct.GridComponent,ct.LegendComponent,ct.TooltipComponent,ct.MarkLineComponent,ct.MarkAreaComponent,ct.VisualMapComponent])}const At=e=>y.cloneDeepWith(e,(t,n)=>{if(n!==void 0&&t)return U.toJS(t)}),jn={sqlSnippet:new RegExp("(?<=sql_snippets\\.)([^\\?}.]+)","gm"),context:new RegExp("(?<=context\\.)([^\\?}.]+)","gm"),filter:new RegExp("(?<=filters\\.)([^\\?}.]+)","gm")};function Id(e,t){const n=Ii.decode(t);n!==e&&(console.error("Inconsistent sql"),console.groupCollapsed("Inconsistent sql"),console.table({before:e,after:t,v:n}),console.groupEnd())}async function Md({query:e,name:t,payload:n,additionals:r},i){if(!e.sql)return[];const{type:o,key:l,sql:c,pre_process:u,post_process:d}=e,h=hs(c,n),p=sd({sql:h,pre_process:u}),x=Ii.encode(p);Id(p,x);let m=await Ke.query(i)({type:o,key:l,query:x,...r},{params:{name:t}});return m=rd(d,m,bs(n)),m}async function zd({type:e,key:t,configString:n,name:r,additionals:i},o){try{return await Ke.httpDataSourceQuery(o)({type:e,key:t,query:n,...i},{params:{name:r}})}catch(l){if(He.isCancel(l))throw l;return console.error(l),l}}async function js(){try{return(await Ke.post()("/datasource/list",{filter:{},sort:[{field:"create_time",order:"ASC"}],pagination:{page:1,pagesize:100}},{})).data}catch(e){return console.error(e),[]}}async function aa(){try{return(await Ke.post()("/sql_snippet/list",{filter:{},sort:[{field:"id",order:"ASC"}],pagination:{page:1,pagesize:1e3}},{})).data}catch(e){return console.error(e),[]}}class oa{constructor(t){P(this,"rootRef");this.rootRef=U.observable({current:t})}async deleteItem(t){U.runInAction(()=>{y.unset(this.rootRef.current,[t])})}getItem(t){const n=this.getValueFromRoot(t);return Promise.resolve(n)}getValueFromRoot(t){return t===null?U.toJS(this.rootRef.current):y.get(this.rootRef.current,[t])}setItem(t,n){if(t===null)if(y.isObject(n))U.runInAction(()=>{this.rootRef.current=n});else throw new Error("Cannot set root value to non-object");else U.runInAction(()=>{y.set(this.rootRef.current,[t],n)});return Promise.resolve(this.getItem(t))}watchItem(t,n,r){return U.reaction(()=>this.getValueFromRoot(t),(i,o)=>{n(i,o)},{requiresObservable:!0,fireImmediately:y.get(r,"fireImmediately",!1)})}}class Ad{constructor(){P(this,"channels",new Map);P(this,"globalChannel",new Mi)}getChannel(t){const n=this.channels.get(t);if(n)return n;const r=new Mi;return this.channels.set(t,r),r}}class Ed{constructor(t){P(this,"instances",new Map);this.pluginManager=t}get availableVizList(){return this.pluginManager.installedPlugins.flatMap(t=>t.manifest.viz)}resolveComponent(t){return this.pluginManager.factory.viz(t)}getOrCreateInstance(t){const n=this.instances.get(t.id);if(n)return n;const r={id:t.id,name:t.viz.type,type:t.viz.type,messageChannels:new Ad,instanceData:new oa(t.viz.conf)};return this.instances.set(t.id,r),r}}function la(e,t,n,r){return{vizManager:n,locale:"zh",msgChannels:e.messageChannels,instanceData:e.instanceData,pluginData:new oa({}),colorPalette:{getColor(){return()=>""}},data:t,variables:r}}const Pd=e=>{const{panel:t,measure:n,vizManager:r,data:i,variables:o}=e,l=r.resolveComponent(t.viz.type),c=r.getOrCreateInstance(t),u={...la(c,i,r,o),viewport:{width:n.w,height:n.h}},d=l.viewRender;return s.jsx(d,{context:u,instance:c,...y.omit(e,["panel","vizManager","data"])})},Ld=e=>{const{vizManager:t,panel:n,data:r,variables:i}=e,o=t.resolveComponent(n.viz.type),l=t.getOrCreateInstance(n),c={...la(l,r,t,i)},u=o.configRender;return s.jsx(u,{context:c,instance:l,...y.omit(e,["panel","vizManager","data"])})},ca=(e,t)=>{const n=tt.bezier(e),r=tt.bezier(t);return function(i){return i<50?n(i*2/100).hex():r((i-50)*2/100).hex()}},vn=e=>{const t=tt.bezier(e);return function(n){return t(n/100).hex()}},Bd={type:"interpolation",displayName:"Red / Green",getColor:ca(["darkred","deeppink","lightyellow"],["lightyellow","lightgreen","teal"]),name:"red-green",category:"diverging"},Od={type:"interpolation",displayName:"Yellow / Blue",getColor:ca(["#8f531d","#ffd347","#e3efe3"],["#eefaee","#4ecbbf","#003f94"]),name:"yellow-blue",category:"diverging"},$d={type:"interpolation",displayName:"Red",getColor:vn(["#fff7f1","darkred"]),name:"red",category:"sequential"},Vd={type:"interpolation",displayName:"Green",getColor:vn(["#f0ffed","darkgreen"]),name:"green",category:"sequential"},qd={type:"interpolation",displayName:"Blue",getColor:vn(["#f9fcff","#48b3e9","darkblue"]),name:"blue",category:"sequential"},Nd={type:"interpolation",displayName:"Orange",getColor:vn(["#fff7f1","darkorange","#b60000"]),name:"orange",category:"sequential"};class Fd{constructor(t){P(this,"symbol");this.symbol=Symbol(t)}}function rt(e){return new Fd(e)}class vs{constructor(){P(this,"parent");P(this,"factoryRegistry",new Map);P(this,"instanceRegistry",new Map)}createScoped(){const t=new vs;return t.parent=this,t}getRequired(t){return this.get(t)}get(t){if(this.instanceRegistry.has(t.symbol))return this.instanceRegistry.get(t.symbol);const n=this.factoryRegistry.get(t.symbol);if(n){const r=n(this);return this.instanceRegistry.set(t.symbol,r),r}if(this.parent)return this.parent.get(t)}provideFactory(t,n){return this.factoryRegistry.has(t.symbol)?console.warn(`Token ${t.symbol.toString()} is already registered`):this.factoryRegistry.set(t.symbol,n),this}provideValue(t,n){return this.factoryRegistry.has(t.symbol)?console.warn(`Token ${t.symbol.toString()} is already registered`):this.factoryRegistry.set(t.symbol,()=>n),this}dispose(){this.instanceRegistry.forEach(t=>{const n=y.get(t,"dispose");y.isFunction(n)&&n.bind(t)()}),this.instanceRegistry.clear(),this.factoryRegistry.clear()}}const ua="12.2.0",Gd=Object.freeze(Object.defineProperty({__proto__:null,version:ua},Symbol.toStringTag,{value:"Module"}));class Wd{constructor(t){P(this,"staticColors",new Map);P(this,"interpolations",new Map);t.installedPlugins.forEach(n=>{n.manifest.color.forEach(r=>{this.register(r)})})}getStaticColors(){return Array.from(this.staticColors.values())}register(t){const n=this.encodeColor(t);t.type==="single"?(this.staticColors.has(n)&&console.warn(`the color '${t.name}' has been registered under '${t.category}', previous registered value will be overridden`),this.staticColors.set(n,t)):t.type==="interpolation"&&(this.interpolations.has(n)&&console.warn(`the interpolation '${t.name}' has been registered under '${t.category}', previous registered value will be overridden`,`the interpolation '${t.name}' has been registered under '${t.category}', previous registered value will be overridden`),this.interpolations.set(n,t))}decodeStaticColor(t){return this.staticColors.get(t)}encodeColor(t){return`\${${t.category}}.{${t.name}}`}decodeInterpolation(t){return this.interpolations.get(t)}getColorInterpolations(){return Array.from(this.interpolations.values())}}class Rd{constructor(){P(this,"plugins",new Map);P(this,"vizComponents",new Map);P(this,"factory",{viz:t=>{const n=this.vizComponents.get(t);if(n)return n;throw new Error(`Viz Component (${t}) not found`)}})}install(t){if(this.plugins.has(t.id))throw new Error(`Plugin (${t.id}) has been installed before`);this.plugins.set(t.id,t);for(const n of t.manifest.viz){if(this.vizComponents.has(n.name))throw new Error(`Viz Component (${n.name}) has been installed before`);this.vizComponents.set(n.name,n)}}get installedPlugins(){return Array.from(this.plugins.values())}}class Qd{constructor(){P(this,"migrations",[])}version(t,n){return this.migrations.push({version:t,handler:n}),this}run(t,n,r){var l;if(t.from===t.to)return n;if(t.from>t.to)throw new Error(`Can not downgrade from version '${t.from}' to (${t.to})`);const i=this.migrations.filter(c=>c.version>t.from&&c.version<=t.to),o=y.orderBy(i,"version","asc");if(((l=y.last(o))==null?void 0:l.version)!==t.to)throw new Error(`Migration to version ${t.to} not found`);return o.reduce((c,u)=>u.handler(c,r),n)}}class ae extends Qd{constructor(){super(),this.configVersions()}version(t,n){return super.version(t,(r,i)=>({version:t,...n(r,i)}))}async migrate({configData:t,panelModel:n}){const r=await t.getItem(null),i=y.get(r,"version",0),o=this.run({from:i,to:this.VERSION},r,{panelModel:n});await t.setItem(null,o)}async needMigration({configData:t}){const n=await t.getItem(null);return y.get(n,"version",0)<this.VERSION}}const O=(e,t)=>{const[n,{setFalse:r}]=$.useBoolean(!0),[i,o]=g.useState();g.useEffect(()=>(e.getItem(t).then(c=>{o(c),r()}),e.watchItem(t,c=>{o(c)})));const l=g.useCallback(async c=>{await e.setItem(t,c),o(c)},[e,t]);return{loading:n,value:i,set:l}},_e={top:16,right:16,bottom:16,left:16},Ge=e=>Math.max(0,e-_e.left-_e.right),We=e=>Math.max(0,e-_e.top-_e.bottom),Zt=(e,t)=>({width:Ge(e),height:We(t)}),ke=({width:e,height:t,children:n})=>s.jsx(a.Box,{pt:_e.top,pr:_e.right,pb:_e.bottom,pl:_e.left,sx:{width:e,height:t,overflow:"hidden",position:"relative"},children:n}),ws={x_axis_data_key:"",y_axis_data_key:"",z_axis_data_key:"",xAxis3D:{type:"value",name:"X Axis Name"},yAxis3D:{type:"value",name:"Y Axis Name"},zAxis3D:{type:"value",name:"Z Axis Name"}};function Ud({context:e}){const{value:t}=O(e.instanceData,"config"),n=e.data,{width:r,height:i}=e.viewport,{x_axis_data_key:o,y_axis_data_key:l,z_axis_data_key:c,xAxis3D:u,yAxis3D:d,zAxis3D:h}=y.defaults({},t,ws),p=g.useMemo(()=>Xt(n,o),[n,o]),{x,y:m,z:j}=g.useMemo(()=>({x:z(o),y:z(l),z:z(c)}),[o,l,c]),{min:C,max:T}=g.useMemo(()=>{const A=y.minBy(p,Y=>Y[j.columnKey]),N=y.maxBy(p,Y=>Y[j.columnKey]);return{min:y.get(A,j.columnKey),max:y.get(N,j.columnKey)}},[p,j]),D={tooltip:{},backgroundColor:"#fff",visualMap:{show:!0,dimension:2,min:C,max:T,inRange:{color:["#313695","#4575b4","#74add1","#abd9e9","#e0f3f8","#ffffbf","#fee090","#fdae61","#f46d43","#d73027","#a50026"]}},xAxis3D:u,yAxis3D:d,zAxis3D:h,grid3D:{viewControl:{projection:"orthographic",autoRotate:!1},light:{main:{shadow:!0,quality:"ultra",intensity:1.5}}},series:[{type:"bar3D",wireframe:{},data:p.map(A=>[A[x.columnKey],A[m.columnKey],A[j.columnKey]])}]};return t?s.jsx(ke,{width:r,height:i,children:s.jsx(we,{echarts:be,option:D,style:Zt(r,i),notMerge:!0,theme:"merico-light"})}):null}const da=g.createContext(null),Cs=da.Provider;function Ss(){const e=g.useContext(da);if(!e)throw new Error("Please use DashboardModelContextProvider");return e}const X=()=>Ss(),pa=()=>Ss(),ha=g.createContext({searchButtonProps:{}}),_s=ha.Provider;function xa(){return g.useContext(ha)}const fa=g.createContext(null),ks=fa.Provider;function ga(){const e=g.useContext(fa);if(!e)throw new Error("Please use ContentModelContextProvider");return e}const W=()=>ga(),ce=()=>ga(),Kd={inEditMode:!1},wn=g.createContext(Kd),ma=g.createContext({panel:null,data:{},loading:!1,errors:[],downloadPanelScreenshot:()=>{}}),Ts=ma.Provider;function ya(){const e=g.useContext(ma);if(!e.panel)throw new Error("Please use PanelContextProvider");return e}const xt=()=>ya(),Ee=()=>ya(),Yd={fullScreenPanelID:"",setFullScreenPanelID:y.noop},Ds=g.createContext(Yd);function ba(){const e=g.useContext(Ds);if(!e)throw new Error("Please use FullScreenPanelContext.Provider");return e}const B=S.observer(g.forwardRef(({label:e,required:t,value:n,onChange:r,clearable:i=!1,sx:o,...l},c)=>{const{panel:u}=Ee(),d=g.useMemo(()=>u.dataFieldOptions(n,i),[n,i]);if(d.length===0){const h=u.explainDataKey(n);return s.jsxs(a.HoverCard,{shadow:"md",position:"bottom-start",withinPortal:!0,zIndex:320,children:[s.jsx(a.HoverCard.Target,{children:s.jsx(a.Box,{children:s.jsx(a.TextInput,{label:e,required:t,defaultValue:h.columnKey,readOnly:!0,disabled:!0})})}),s.jsx(a.HoverCard.Dropdown,{children:s.jsxs(a.Group,{position:"left",spacing:0,children:[s.jsx(a.Text,{size:"xs",color:h.queryName?"black":"red",sx:{fontFamily:"monospace"},children:h.queryName??h.queryID}),s.jsx(a.Text,{size:"xs",color:"black",sx:{fontFamily:"monospace"},children:"."}),s.jsx(a.Text,{size:"xs",color:"red",sx:{fontFamily:"monospace"},children:h.columnKey})]})})]})}return s.jsx(a.Select,{ref:c,label:e,data:d,value:n,onChange:r,required:t,sx:o,maxDropdownHeight:500,...l})}));function Xd({context:e}){const{value:t,set:n}=O(e.instanceData,"config"),r=y.defaults({},t,ws),{control:i,handleSubmit:o,reset:l}=b.useForm({defaultValues:r});return g.useEffect(()=>{l(r)},[t]),t?s.jsx(a.Stack,{spacing:"xs",children:s.jsxs("form",{onSubmit:o(n),children:[s.jsx(a.Text,{children:"X Axis"}),s.jsxs(a.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[s.jsx(b.Controller,{name:"x_axis_data_key",control:i,render:({field:c})=>s.jsx(B,{label:"Data Field",required:!0,...c})}),s.jsx(b.Controller,{name:"xAxis3D.name",control:i,render:({field:c})=>s.jsx(a.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...c})})]}),s.jsx(a.Text,{mt:"lg",children:"Y Axis"}),s.jsxs(a.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[s.jsx(b.Controller,{name:"y_axis_data_key",control:i,render:({field:c})=>s.jsx(B,{label:"Data Field",required:!0,...c})}),s.jsx(b.Controller,{name:"yAxis3D.name",control:i,render:({field:c})=>s.jsx(a.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...c})})]}),s.jsx(a.Text,{mt:"lg",children:"Z Axis"}),s.jsxs(a.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[s.jsx(b.Controller,{name:"z_axis_data_key",control:i,render:({field:c})=>s.jsx(B,{label:"Data Field",required:!0,...c})}),s.jsx(b.Controller,{name:"zAxis3D.name",control:i,render:({field:c})=>s.jsx(a.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...c})})]}),s.jsx(a.Group,{position:"center",mt:"xl",grow:!0,sx:{width:"60%"},mx:"auto",children:s.jsxs(a.Button,{color:"blue",type:"submit",children:[s.jsx(k.DeviceFloppy,{size:20}),s.jsx(a.Text,{ml:"md",children:"Save"})]})})]})}):null}function Jd(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=u=>u&&`${n}.${u}`,{x_axis_data_key:i,y_axis_data_key:o,z_axis_data_key:l,...c}=e;return{...c,x_axis_data_key:r(i),y_axis_data_key:r(o),z_axis_data_key:r(l)}}catch(n){throw console.error("[Migration failed]",n),n}}class Zd extends ae{constructor(){super(...arguments);P(this,"VERSION",2)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,(n,r)=>{const{config:i}=n;return{...n,version:2,config:Jd(i,r)}})}}const Hd={displayName:"Bar Chart (3D)",displayGroup:"ECharts-based charts",migrator:new Zd,name:"bar-3d",viewRender:Ud,configRender:Xd,createConfig(){return{version:2,config:y.cloneDeep(ws)}}},Pe={enabled:!1,func_content:["function label(value, index) {"," // your code goes here"," // return value","}"].join(`
|
|
56
|
+
`,"<br/>").split("<br/>");return n.map((i,o)=>{const l=[yd(i)];return o!==n.length-1&&l.push(s.jsx("br",{},`br-${o}`)),l}).flat().filter(i=>i!==void 0)}function ms(e){return bd(e)}function Jt(e,t,n){const r=md(t,n),i=/^\{(.+)\}(.*)$/;return e.split("$").map((o,l)=>{const c=i.exec(o);if(!c)return ms(o);const u=r[c[1]];if(!u)return ms(o);const d=c[2]??"";return s.jsxs(g.Fragment,{children:[u,ms(d)]},`${o}-${l}`)})}function jd(e,t){const{data_field:n,aggregation:r}=e,i=yn(t,n,r);return Ae(e,i)}function na(e,t){const n={};return e.forEach(r=>{n[r.name]=jd(r,t)}),n}function bn(e,t,n){const r=na(t,n),i=/^\{(.+)\}(.*)$/;return e.split("$").map(o=>{const l=i.exec(o);if(!l)return o;const c=r[l[1]];if(!c)return o;const u=l[2]??"";return`${c}${u}`}).join("")}const ys={grid:{axis:"#97999D",scope:"rgba(47,140,192,0.1)",boundary:"#789AB4",reference:"#CFCFD8"},graphics:{compared:{blueDark:"#3E7CAB",blue:"#6398C7",blueLight:"#7CB0DF",blue10:"#6398C71a",redDark:"#AF5F6B",red:"#CD7C88",redLight:"#E794A0",red10:"#CD7C881a"},gradient:{distributed:"linear-gradient(90deg, #1babe6 0%, #2fc8c8 28.63%, #98d44b 48.86%, #ffd057 67.53%, #f5ae53 80.6%, #e76441 91.18%, #b90000 100%)",protrude:"linear-gradient(180deg, #ec73734d 0%, #ec737300 100%)"},level:{lv0:"#6398C7",lv1:"#61B5BF",lv2:"#54D4BB",lv3:"#F5D277",lv4:"#E8BB7F",lv5:"#DB9E84",lv6:"#CB8089"},depth:{dp0:"#FFF7F8",dp1:"#FFE1E1",dp2:"#FDBCBC",dp3:"#F39494",dp4:"#FA4242",dp5:"#E21212"},multiple:{c1:"#66B4DB",c2:"#E46464",c3:"#EEBA00",c4:"#33A678",c5:"#9D88CB",c6:"#939943",c7:"#E49792",c8:"#09A2B8",c9:"#AF5F6B",c10:"#6CA157",c11:"#3E7CAB",c12:"#6398C7",c13:"#E692BA",c14:"#97B566",c15:"#8CACE2",c16:"#CA79AC",c17:"#6DBC80",c18:"#B08F4B",c19:"#39BFA2",c20:"#826BAF"}}};function vd(){be.registerTheme("merico-light",{color:Object.values(ys.graphics.multiple),visualMap:{color:Object.values(ys.graphics.depth).reverse()},axes:[{type:"all",name:"通用坐标轴",axisLineColor:"#97999D",axisTickColor:"#97999D",axisLabelShow:!0,axisLabelColor:"#818388",splitLineShow:!0,splitLineColor:["#E0E6F1"]}]})}function sa(){vd()}function*wd(e){const t=ys.graphics[e];if(!t)throw new Error("Invalid palette key provided");const n=Object.values(t);let r=0;for(;;)yield n[r%n.length],r++}function ra(){return{filters:{},context:{}}}function bs(e){const t=ra();if(!e)return ra();const{filters:n=t.filters,context:r=t.context}=e;return{filters:n,context:r}}class je extends g.Component{constructor(t){super(t),this.state={error:null}}componentDidCatch(t){this.setState({error:t})}render(){var t;if(this.state.error){const n=()=>{this.setState({error:null})};return s.jsxs(a.Box,{children:[s.jsx(a.Text,{size:"xs",children:(t=this.state.error)==null?void 0:t.message}),s.jsx(a.Button,{variant:"subtle",size:"xs",mx:"auto",compact:!0,sx:{display:"block"},onClick:n,children:"Retry"})]})}return this.props.children}}function Cd(e,t={handleError:!0}){return n=>s.jsx(je,{...t,children:s.jsx(e,{...n})})}function Sd(e,t){return new Function(`return ${e}`)()(t,nt)}function _d(e,t,n){return Sd(e,{context:t,filters:n})}function kd(e,t){try{return new Function(`return ${e.config.processing.pre}`)()(t,nt)}catch(n){return console.error(n),t}}function Td(e,t){return new Function(`return ${e.config.processing.post}`)()(t,nt)}function Dd(e,t,n){return e?new Function(`return ${e}`)()(t,nt,n):t}function ia(){Di.use([du.CanvasRenderer,et.BarChart,et.BoxplotChart,et.FunnelChart,et.HeatmapChart,et.LineChart,et.PieChart,et.RadarChart,et.ScatterChart,et.SunburstChart,ct.CalendarComponent,ct.DataZoomComponent,ct.GridComponent,ct.LegendComponent,ct.TooltipComponent,ct.MarkLineComponent,ct.MarkAreaComponent,ct.VisualMapComponent])}const At=e=>y.cloneDeepWith(e,(t,n)=>{if(n!==void 0&&t)return U.toJS(t)}),jn={sqlSnippet:new RegExp("(?<=sql_snippets\\.)([^\\?}.]+)","gm"),context:new RegExp("(?<=context\\.)([^\\?}.]+)","gm"),filter:new RegExp("(?<=filters\\.)([^\\?}.]+)","gm")};function Id(e,t){const n=Ii.decode(t);n!==e&&(console.error("Inconsistent sql"),console.groupCollapsed("Inconsistent sql"),console.table({before:e,after:t,v:n}),console.groupEnd())}async function Md({query:e,name:t,payload:n,additionals:r},i){if(!e.sql)return[];const{type:o,key:l,sql:c,pre_process:u,post_process:d}=e,h=hs(c,n),p=sd({sql:h,pre_process:u}),x=Ii.encode(p);Id(p,x);let m=await Ke.query(i)({type:o,key:l,query:x,...r},{params:{name:t}});return m=rd(d,m,bs(n)),m}async function zd({type:e,key:t,configString:n,name:r,additionals:i},o){try{return await Ke.httpDataSourceQuery(o)({type:e,key:t,query:n,...i},{params:{name:r}})}catch(l){if(He.isCancel(l))throw l;return console.error(l),l}}async function js(){try{return(await Ke.post()("/datasource/list",{filter:{},sort:[{field:"create_time",order:"ASC"}],pagination:{page:1,pagesize:100}},{})).data}catch(e){return console.error(e),[]}}async function aa(){try{return(await Ke.post()("/sql_snippet/list",{filter:{},sort:[{field:"id",order:"ASC"}],pagination:{page:1,pagesize:1e3}},{})).data}catch(e){return console.error(e),[]}}class oa{constructor(t){P(this,"rootRef");this.rootRef=U.observable({current:t})}async deleteItem(t){U.runInAction(()=>{y.unset(this.rootRef.current,[t])})}getItem(t){const n=this.getValueFromRoot(t);return Promise.resolve(n)}getValueFromRoot(t){return t===null?U.toJS(this.rootRef.current):y.get(this.rootRef.current,[t])}setItem(t,n){if(t===null)if(y.isObject(n))U.runInAction(()=>{this.rootRef.current=n});else throw new Error("Cannot set root value to non-object");else U.runInAction(()=>{y.set(this.rootRef.current,[t],n)});return Promise.resolve(this.getItem(t))}watchItem(t,n,r){return U.reaction(()=>this.getValueFromRoot(t),(i,o)=>{n(i,o)},{requiresObservable:!0,fireImmediately:y.get(r,"fireImmediately",!1)})}}class Ad{constructor(){P(this,"channels",new Map);P(this,"globalChannel",new Mi)}getChannel(t){const n=this.channels.get(t);if(n)return n;const r=new Mi;return this.channels.set(t,r),r}}class Ed{constructor(t){P(this,"instances",new Map);this.pluginManager=t}get availableVizList(){return this.pluginManager.installedPlugins.flatMap(t=>t.manifest.viz)}resolveComponent(t){return this.pluginManager.factory.viz(t)}getOrCreateInstance(t){const n=this.instances.get(t.id);if(n)return n;const r={id:t.id,name:t.viz.type,type:t.viz.type,messageChannels:new Ad,instanceData:new oa(t.viz.conf)};return this.instances.set(t.id,r),r}}function la(e,t,n,r){return{vizManager:n,locale:"zh",msgChannels:e.messageChannels,instanceData:e.instanceData,pluginData:new oa({}),colorPalette:{getColor(){return()=>""}},data:t,variables:r}}const Pd=e=>{const{panel:t,measure:n,vizManager:r,data:i,variables:o}=e,l=r.resolveComponent(t.viz.type),c=r.getOrCreateInstance(t),u={...la(c,i,r,o),viewport:{width:n.w,height:n.h}},d=l.viewRender;return s.jsx(d,{context:u,instance:c,...y.omit(e,["panel","vizManager","data"])})},Ld=e=>{const{vizManager:t,panel:n,data:r,variables:i}=e,o=t.resolveComponent(n.viz.type),l=t.getOrCreateInstance(n),c={...la(l,r,t,i)},u=o.configRender;return s.jsx(u,{context:c,instance:l,...y.omit(e,["panel","vizManager","data"])})},ca=(e,t)=>{const n=tt.bezier(e),r=tt.bezier(t);return function(i){return i<50?n(i*2/100).hex():r((i-50)*2/100).hex()}},vn=e=>{const t=tt.bezier(e);return function(n){return t(n/100).hex()}},Bd={type:"interpolation",displayName:"Red / Green",getColor:ca(["darkred","deeppink","lightyellow"],["lightyellow","lightgreen","teal"]),name:"red-green",category:"diverging"},Od={type:"interpolation",displayName:"Yellow / Blue",getColor:ca(["#8f531d","#ffd347","#e3efe3"],["#eefaee","#4ecbbf","#003f94"]),name:"yellow-blue",category:"diverging"},$d={type:"interpolation",displayName:"Red",getColor:vn(["#fff7f1","darkred"]),name:"red",category:"sequential"},Vd={type:"interpolation",displayName:"Green",getColor:vn(["#f0ffed","darkgreen"]),name:"green",category:"sequential"},qd={type:"interpolation",displayName:"Blue",getColor:vn(["#f9fcff","#48b3e9","darkblue"]),name:"blue",category:"sequential"},Nd={type:"interpolation",displayName:"Orange",getColor:vn(["#fff7f1","darkorange","#b60000"]),name:"orange",category:"sequential"};class Fd{constructor(t){P(this,"symbol");this.symbol=Symbol(t)}}function rt(e){return new Fd(e)}class vs{constructor(){P(this,"parent");P(this,"factoryRegistry",new Map);P(this,"instanceRegistry",new Map)}createScoped(){const t=new vs;return t.parent=this,t}getRequired(t){return this.get(t)}get(t){if(this.instanceRegistry.has(t.symbol))return this.instanceRegistry.get(t.symbol);const n=this.factoryRegistry.get(t.symbol);if(n){const r=n(this);return this.instanceRegistry.set(t.symbol,r),r}if(this.parent)return this.parent.get(t)}provideFactory(t,n){return this.factoryRegistry.has(t.symbol)?console.warn(`Token ${t.symbol.toString()} is already registered`):this.factoryRegistry.set(t.symbol,n),this}provideValue(t,n){return this.factoryRegistry.has(t.symbol)?console.warn(`Token ${t.symbol.toString()} is already registered`):this.factoryRegistry.set(t.symbol,()=>n),this}dispose(){this.instanceRegistry.forEach(t=>{const n=y.get(t,"dispose");y.isFunction(n)&&n.bind(t)()}),this.instanceRegistry.clear(),this.factoryRegistry.clear()}}const ua="12.3.0",Gd=Object.freeze(Object.defineProperty({__proto__:null,version:ua},Symbol.toStringTag,{value:"Module"}));class Wd{constructor(t){P(this,"staticColors",new Map);P(this,"interpolations",new Map);t.installedPlugins.forEach(n=>{n.manifest.color.forEach(r=>{this.register(r)})})}getStaticColors(){return Array.from(this.staticColors.values())}register(t){const n=this.encodeColor(t);t.type==="single"?(this.staticColors.has(n)&&console.warn(`the color '${t.name}' has been registered under '${t.category}', previous registered value will be overridden`),this.staticColors.set(n,t)):t.type==="interpolation"&&(this.interpolations.has(n)&&console.warn(`the interpolation '${t.name}' has been registered under '${t.category}', previous registered value will be overridden`,`the interpolation '${t.name}' has been registered under '${t.category}', previous registered value will be overridden`),this.interpolations.set(n,t))}decodeStaticColor(t){return this.staticColors.get(t)}encodeColor(t){return`\${${t.category}}.{${t.name}}`}decodeInterpolation(t){return this.interpolations.get(t)}getColorInterpolations(){return Array.from(this.interpolations.values())}}class Rd{constructor(){P(this,"plugins",new Map);P(this,"vizComponents",new Map);P(this,"factory",{viz:t=>{const n=this.vizComponents.get(t);if(n)return n;throw new Error(`Viz Component (${t}) not found`)}})}install(t){if(this.plugins.has(t.id))throw new Error(`Plugin (${t.id}) has been installed before`);this.plugins.set(t.id,t);for(const n of t.manifest.viz){if(this.vizComponents.has(n.name))throw new Error(`Viz Component (${n.name}) has been installed before`);this.vizComponents.set(n.name,n)}}get installedPlugins(){return Array.from(this.plugins.values())}}class Qd{constructor(){P(this,"migrations",[])}version(t,n){return this.migrations.push({version:t,handler:n}),this}run(t,n,r){var l;if(t.from===t.to)return n;if(t.from>t.to)throw new Error(`Can not downgrade from version '${t.from}' to (${t.to})`);const i=this.migrations.filter(c=>c.version>t.from&&c.version<=t.to),o=y.orderBy(i,"version","asc");if(((l=y.last(o))==null?void 0:l.version)!==t.to)throw new Error(`Migration to version ${t.to} not found`);return o.reduce((c,u)=>u.handler(c,r),n)}}class ae extends Qd{constructor(){super(),this.configVersions()}version(t,n){return super.version(t,(r,i)=>({version:t,...n(r,i)}))}async migrate({configData:t,panelModel:n}){const r=await t.getItem(null),i=y.get(r,"version",0),o=this.run({from:i,to:this.VERSION},r,{panelModel:n});await t.setItem(null,o)}async needMigration({configData:t}){const n=await t.getItem(null);return y.get(n,"version",0)<this.VERSION}}const O=(e,t)=>{const[n,{setFalse:r}]=$.useBoolean(!0),[i,o]=g.useState();g.useEffect(()=>(e.getItem(t).then(c=>{o(c),r()}),e.watchItem(t,c=>{o(c)})));const l=g.useCallback(async c=>{await e.setItem(t,c),o(c)},[e,t]);return{loading:n,value:i,set:l}},_e={top:16,right:16,bottom:16,left:16},Ge=e=>Math.max(0,e-_e.left-_e.right),We=e=>Math.max(0,e-_e.top-_e.bottom),Zt=(e,t)=>({width:Ge(e),height:We(t)}),ke=({width:e,height:t,children:n})=>s.jsx(a.Box,{pt:_e.top,pr:_e.right,pb:_e.bottom,pl:_e.left,sx:{width:e,height:t,overflow:"hidden",position:"relative"},children:n}),ws={x_axis_data_key:"",y_axis_data_key:"",z_axis_data_key:"",xAxis3D:{type:"value",name:"X Axis Name"},yAxis3D:{type:"value",name:"Y Axis Name"},zAxis3D:{type:"value",name:"Z Axis Name"}};function Ud({context:e}){const{value:t}=O(e.instanceData,"config"),n=e.data,{width:r,height:i}=e.viewport,{x_axis_data_key:o,y_axis_data_key:l,z_axis_data_key:c,xAxis3D:u,yAxis3D:d,zAxis3D:h}=y.defaults({},t,ws),p=g.useMemo(()=>Xt(n,o),[n,o]),{x,y:m,z:j}=g.useMemo(()=>({x:z(o),y:z(l),z:z(c)}),[o,l,c]),{min:C,max:T}=g.useMemo(()=>{const A=y.minBy(p,Y=>Y[j.columnKey]),N=y.maxBy(p,Y=>Y[j.columnKey]);return{min:y.get(A,j.columnKey),max:y.get(N,j.columnKey)}},[p,j]),D={tooltip:{},backgroundColor:"#fff",visualMap:{show:!0,dimension:2,min:C,max:T,inRange:{color:["#313695","#4575b4","#74add1","#abd9e9","#e0f3f8","#ffffbf","#fee090","#fdae61","#f46d43","#d73027","#a50026"]}},xAxis3D:u,yAxis3D:d,zAxis3D:h,grid3D:{viewControl:{projection:"orthographic",autoRotate:!1},light:{main:{shadow:!0,quality:"ultra",intensity:1.5}}},series:[{type:"bar3D",wireframe:{},data:p.map(A=>[A[x.columnKey],A[m.columnKey],A[j.columnKey]])}]};return t?s.jsx(ke,{width:r,height:i,children:s.jsx(we,{echarts:be,option:D,style:Zt(r,i),notMerge:!0,theme:"merico-light"})}):null}const da=g.createContext(null),Cs=da.Provider;function Ss(){const e=g.useContext(da);if(!e)throw new Error("Please use DashboardModelContextProvider");return e}const X=()=>Ss(),pa=()=>Ss(),ha=g.createContext({searchButtonProps:{}}),_s=ha.Provider;function xa(){return g.useContext(ha)}const fa=g.createContext(null),ks=fa.Provider;function ga(){const e=g.useContext(fa);if(!e)throw new Error("Please use ContentModelContextProvider");return e}const W=()=>ga(),ce=()=>ga(),Kd={inEditMode:!1},wn=g.createContext(Kd),ma=g.createContext({panel:null,data:{},loading:!1,errors:[],downloadPanelScreenshot:()=>{}}),Ts=ma.Provider;function ya(){const e=g.useContext(ma);if(!e.panel)throw new Error("Please use PanelContextProvider");return e}const xt=()=>ya(),Ee=()=>ya(),Yd={fullScreenPanelID:"",setFullScreenPanelID:y.noop},Ds=g.createContext(Yd);function ba(){const e=g.useContext(Ds);if(!e)throw new Error("Please use FullScreenPanelContext.Provider");return e}const B=S.observer(g.forwardRef(({label:e,required:t,value:n,onChange:r,clearable:i=!1,sx:o,...l},c)=>{const{panel:u}=Ee(),d=g.useMemo(()=>u.dataFieldOptions(n,i),[n,i]);if(d.length===0){const h=u.explainDataKey(n);return s.jsxs(a.HoverCard,{shadow:"md",position:"bottom-start",withinPortal:!0,zIndex:320,children:[s.jsx(a.HoverCard.Target,{children:s.jsx(a.Box,{children:s.jsx(a.TextInput,{label:e,required:t,defaultValue:h.columnKey,readOnly:!0,disabled:!0})})}),s.jsx(a.HoverCard.Dropdown,{children:s.jsxs(a.Group,{position:"left",spacing:0,children:[s.jsx(a.Text,{size:"xs",color:h.queryName?"black":"red",sx:{fontFamily:"monospace"},children:h.queryName??h.queryID}),s.jsx(a.Text,{size:"xs",color:"black",sx:{fontFamily:"monospace"},children:"."}),s.jsx(a.Text,{size:"xs",color:"red",sx:{fontFamily:"monospace"},children:h.columnKey})]})})]})}return s.jsx(a.Select,{ref:c,label:e,data:d,value:n,onChange:r,required:t,sx:o,maxDropdownHeight:500,...l})}));function Xd({context:e}){const{value:t,set:n}=O(e.instanceData,"config"),r=y.defaults({},t,ws),{control:i,handleSubmit:o,reset:l}=b.useForm({defaultValues:r});return g.useEffect(()=>{l(r)},[t]),t?s.jsx(a.Stack,{spacing:"xs",children:s.jsxs("form",{onSubmit:o(n),children:[s.jsx(a.Text,{children:"X Axis"}),s.jsxs(a.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[s.jsx(b.Controller,{name:"x_axis_data_key",control:i,render:({field:c})=>s.jsx(B,{label:"Data Field",required:!0,...c})}),s.jsx(b.Controller,{name:"xAxis3D.name",control:i,render:({field:c})=>s.jsx(a.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...c})})]}),s.jsx(a.Text,{mt:"lg",children:"Y Axis"}),s.jsxs(a.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[s.jsx(b.Controller,{name:"y_axis_data_key",control:i,render:({field:c})=>s.jsx(B,{label:"Data Field",required:!0,...c})}),s.jsx(b.Controller,{name:"yAxis3D.name",control:i,render:({field:c})=>s.jsx(a.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...c})})]}),s.jsx(a.Text,{mt:"lg",children:"Z Axis"}),s.jsxs(a.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[s.jsx(b.Controller,{name:"z_axis_data_key",control:i,render:({field:c})=>s.jsx(B,{label:"Data Field",required:!0,...c})}),s.jsx(b.Controller,{name:"zAxis3D.name",control:i,render:({field:c})=>s.jsx(a.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...c})})]}),s.jsx(a.Group,{position:"center",mt:"xl",grow:!0,sx:{width:"60%"},mx:"auto",children:s.jsxs(a.Button,{color:"blue",type:"submit",children:[s.jsx(k.DeviceFloppy,{size:20}),s.jsx(a.Text,{ml:"md",children:"Save"})]})})]})}):null}function Jd(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=u=>u&&`${n}.${u}`,{x_axis_data_key:i,y_axis_data_key:o,z_axis_data_key:l,...c}=e;return{...c,x_axis_data_key:r(i),y_axis_data_key:r(o),z_axis_data_key:r(l)}}catch(n){throw console.error("[Migration failed]",n),n}}class Zd extends ae{constructor(){super(...arguments);P(this,"VERSION",2)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,(n,r)=>{const{config:i}=n;return{...n,version:2,config:Jd(i,r)}})}}const Hd={displayName:"Bar Chart (3D)",displayGroup:"ECharts-based charts",migrator:new Zd,name:"bar-3d",viewRender:Ud,configRender:Xd,createConfig(){return{version:2,config:y.cloneDeep(ws)}}},Pe={enabled:!1,func_content:["function label(value, index) {"," // your code goes here"," // return value","}"].join(`
|
|
57
57
|
`)},ja={id:"builtin:echarts:click-echart:series",displayName:"Click Chart Series",nameRender:tp,configRender:ep,payload:[{name:"type",description:"Always 'click'",valueType:"string"},{name:"seriesType",description:"'boxplot'",valueType:"string"},{name:"name",description:"Name of the series clicked",valueType:"string"},{name:"color",description:"Color",valueType:"string"},{name:"value",description:"Record of 'name', 'min', 'q1', 'median', 'q3', 'max'",valueType:"object"},{name:"rowData",description:"Data of the row",valueType:"object"}]};function ep(e){return s.jsx(s.Fragment,{})}function tp(e){return s.jsx(a.Text,{children:"Click chart's series"})}const np=[{label:"Truncate",value:"truncate"},{label:"Break Line",value:"break"},{label:"Break Word",value:"breakAll"}],Cn=g.forwardRef(({sectionTitle:e,value:t,onChange:n},r)=>{const i=o=>l=>{const c=y.cloneDeep(t);y.set(c,o,l),n(c)};return s.jsxs(a.Stack,{spacing:0,children:[e&&s.jsx(a.Divider,{mb:-5,mt:5,variant:"dotted",label:e,labelPosition:"right",labelProps:{color:"dimmed"}}),s.jsxs(a.Group,{grow:!0,noWrap:!0,children:[s.jsx(a.NumberInput,{label:"Max Width",hideControls:!0,value:t.width,onChange:i("width")}),s.jsx(a.Select,{label:"Overflow",data:np,value:t.overflow,onChange:i("overflow")}),s.jsx(a.TextInput,{label:"Ellipsis",value:t.ellipsis,disabled:!0})]})]})}),Re=g.forwardRef(({value:e,onChange:t},n)=>{const r=o=>{t({...e,on_axis:o})},i=o=>{t({...e,in_tooltip:o})};return s.jsxs(a.Stack,{ref:n,spacing:0,children:[s.jsx(Cn,{sectionTitle:"Overflow on Axis",value:e.on_axis,onChange:r}),s.jsx(Cn,{sectionTitle:"Overflow in Tooltip",value:e.in_tooltip,onChange:i})]})});function Te(){return{on_axis:{width:80,overflow:"truncate",ellipsis:"..."},in_tooltip:{width:200,overflow:"break",ellipsis:"..."}}}function Le({overflow:e,width:t}){const n={truncate:"initial",break:"break-all",breakAll:"break-word"}[e],r=e==="truncate"?"nowrap":"initial",i={truncate:"ellipsis",break:"clip",breakAll:"clip"}[e];return`
|
|
58
58
|
max-width: ${t}px;
|
|
59
59
|
word-break: ${n};
|
|
@@ -446,8 +446,8 @@ Check the top-level render call using <`+E+">.")}return I}}function iu(w,I){{if(
|
|
|
446
446
|
</thead>
|
|
447
447
|
<tbody>${x.join("")}</tbody>
|
|
448
448
|
</table>
|
|
449
|
-
`}})}function QS(e,t){const n=Vt(e.heat_block.min,t),r=Vt(e.heat_block.max,t);return{min:n,max:r,calculable:!0,orient:"horizontal",left:"center",top:0,itemWidth:15}}function US(e,t,n){const r=z(e.x_axis.data_key),i=y.uniq(t[r.queryID].map(u=>u[r.columnKey])),{overflow:o,rotate:l}=e.x_axis.axisLabel,c=Be(o.on_axis);return ee.getXAxis({id:"main-x-axis",type:"category",data:i,name:e.x_axis.name??"",align:"center",axisTick:{show:!0,alignWithLabel:!0},axisLabel:{rotate:l,...c,formatter:n},splitArea:{show:!1,areaStyle:{color:"#E7E7E9"}},splitLine:{show:!1},nameLocation:"center",nameGap:25,nameTextStyle:{fontWeight:"bold",align:"center"},z:3})}function KS(e,t,n){const r=z(e.x_axis.data_key),i=z(e.y_axis.data_key),{nameAlignment:o,data_key:l,...c}=e.y_axis,u=y.uniq(t[r.queryID].map(x=>x[i.columnKey])),{overflow:d,rotate:h}=e.y_axis.axisLabel,p=Be(d.on_axis);return ee.getYAxis({...c,type:"category",data:u,axisLabel:{rotate:h,...p,formatter:n},axisLine:{show:!0,lineStyle:{width:3}},axisTick:{show:!0,alignWithLabel:!0},splitArea:{show:!1,areaStyle:{color:"#E7E7E9"}},splitLine:{show:!1},nameTextStyle:{fontWeight:"bold",align:o},nameLocation:"end",nameGap:15,z:3})}function YS(e,t,n){if(!e.x_axis.data_key||!e.y_axis.data_key||!e.heat_block.data_key)return{};const r=n.reduce((c,u)=>{const d=st(u,t);return c[u.name]=Ae(u,d),c},{}),i=VS(e),o=qS(e);return{xAxis:US(e,t,i.x_axis),yAxis:KS(e,t,i.y_axis),series:FS(e,t),tooltip:RS(e,t,i,o),grid:NS(e),visualMap:QS(e,r)}}function XS({conf:e,data:t,width:n,height:r,interactionManager:i,variables:o}){const l=g.useMemo(()=>{const p=z(e.x_axis.data_key),x=z(e.y_axis.data_key);return y.keyBy(t[p.queryID],m=>`${m[p.columnKey]}---${m[x.columnKey]}`)},[t,e.x_axis.data_key,e.y_axis.data_key]),c=Oe(i.triggerManager,nl.id),u=g.useCallback(p=>{const[x,m]=p.value,j=y.get(l,`${x}---${m}`,{error:"rowData is not found"});c.forEach(C=>{i.runInteraction(C.id,{...p,rowData:j})})},[l,c,i]),d=g.useMemo(()=>({click:u}),[u]),h=g.useMemo(()=>YS(e,t,o),[e,t]);return s.jsx(we,{echarts:be,option:h,style:{width:n,height:r},onEvents:d,notMerge:!0,theme:"merico-light"})}function JS({context:e,instance:t}){const n=$e({vizManager:e.vizManager,instance:t}),{value:r}=O(e.instanceData,"config"),{variables:i}=e,o=g.useMemo(()=>y.defaults({},r,_r),[r]),l=e.data,{width:c,height:u}=e.viewport;return!c||!u?null:s.jsx(ke,{width:c,height:u,children:s.jsx(XS,{variables:i,width:Ge(c),height:We(u),data:l,conf:o,interactionManager:n})})}class ZS extends ae{constructor(){super(...arguments);P(this,"VERSION",1)}configVersions(){this.version(1,n=>({version:1,config:n}))}}const HS={displayName:"Merico Heatmap",displayGroup:"Merico suite",migrator:new ZS,name:"merico-heatmap",viewRender:JS,configRender:BS,createConfig:()=>({version:1,config:_r}),triggers:[nl]},e1=[{value:"#25262B",name:"Dark"},{value:"#868E96",name:"Gray"},{value:"#FA5252",name:"Red"},{value:"#E64980",name:"Pink"},{value:"#BE4BDB",name:"Grape"},{value:"#7950F2",name:"Violet"},{value:"#4C6EF5",name:"Indigo"},{value:"#228BE6",name:"Blue"},{value:"#15AABF",name:"Cyan"},{value:"#12B886",name:"Teal"},{value:"#40C057",name:"Green"},{value:"#82C91E",name:"Lime"},{value:"#FAB005",name:"Yellow"},{value:"#FD7E14",name:"Orange"}].map(e=>({name:e.name,value:e.value,type:"single",category:"basic"})),t1=[Bd,Od,qd,Vd,$d,Nd],rl=()=>({id:"dashboard",version:ua,manifest:{viz:[gr,qv,d0,gj,lw,ob,PC,Hd,Nh,Lm,my,K0,Xy,pm,Dv,Ab,oj,b0,pS,HS,kS,tx],color:[...e1,...t1]}}),on=new Rd,ue={pluginManager:rt("pluginManager"),vizManager:rt("vizManager"),colorManager:rt("colorManager"),instanceScope:{panelModel:rt("panelModel"),vizInstance:rt("vizInstance"),interactionManager:rt("interactionManager"),migrator:rt("migrator"),operationManager:rt("operationManager"),triggerManager:rt("triggerManager")}},kr=()=>{try{on.install(rl())}catch{}const e=new Ed(on),t=new Wd(on);return{pluginManager:on,vizManager:e,colorManager:t}},Ze=g.createContext(kr());try{on.install(rl())}catch{}const Tr=g.createContext(null);function Xn(e){const t=g.useContext(Tr),n=$.useCreation(()=>e.configure(t||new vs),[e.configure]),r=$.usePrevious(n);return r&&r!==n&&r.dispose(),s.jsx(Tr.Provider,{value:n,children:e.children})}function il(){return g.useContext(Tr)}const n1=({description:e,isDescriptionEmpty:t})=>t?null:s.jsx(a.Tooltip,{color:"white",label:s.jsx(Nn,{value:e,styles:{root:{border:"none"},content:{padding:0}}}),styles:{tooltip:{border:"0.0625rem solid rgb(233, 236, 239)",boxShadow:"rgb(0 0 0 / 5%) 0px 0.0625rem 0.1875rem, rgb(0 0 0 / 5%) 0px 1.25rem 1.5625rem -0.3125rem, rgb(0 0 0 / 4%) 0px 0.625rem 0.625rem -0.3125rem"}},withArrow:!0,children:s.jsx(a.Box,{sx:{height:"16px",alignSelf:"center"},children:s.jsx(_.IconInfoCircle,{size:16,color:"gray"})})}),s1=S.observer(({label:e,config:{default_value:t,description:n,isDescriptionEmpty:r,...i},value:o,onChange:l})=>s.jsxs(a.Box,{children:[s.jsx(a.Text,{children:" "}),s.jsx(a.Checkbox,{label:s.jsxs(a.Group,{noWrap:!0,position:"apart",align:"middle",spacing:6,children:[s.jsx(a.Box,{sx:{flexGrow:1},children:e}),s.jsx(n1,{description:n,isDescriptionEmpty:r})]}),checked:o||!1,onChange:c=>l(c.currentTarget.checked),...i,pt:".4em",styles:{input:{borderColor:"#e9ecef"}}})]})),r1=({value:e,onChange:t,close:n,max_days:r,allowSingleDateInRange:i})=>{const[o,l]=e,c=g.useMemo(()=>o||new Date,[o]),u=g.useMemo(()=>{if(o&&!l)return o},[o,l]),d=g.useMemo(()=>{if(o&&!l&&r>0)return M(o).add(r-1,"days").toDate()},[o,l,r]),h=p=>{const[x,m]=p;t(p),x&&m&&n()};return s.jsx(xu.DatePicker,{defaultDate:c,numberOfColumns:2,type:"range",value:e,onChange:h,onNextMonth:console.log,minDate:u,maxDate:d,allowSingleDateInRange:i})},i1=({begin:e,end:t})=>{const n=g.useMemo(()=>M(t).diff(M(e),"days")+1,[e,t]);if(Number.isNaN(n))return s.jsx("span",{style:{userSelect:"none",opacity:0,visibility:"hidden"},children:"."});const r=n===1?"day":"days";return s.jsx(a.Tooltip,{label:`${n}${r}`,children:s.jsx(a.Badge,{size:"sm",children:n})})},a1=({max_days:e})=>e?s.jsxs(s.Fragment,{children:[s.jsx(a.Group,{position:"right",children:s.jsxs(a.Badge,{size:"xs",children:[e," days max"]})}),s.jsx(a.Divider,{variant:"dashed",my:10})]}):null,Dr=()=>[{label:"yesterday",value:"yesterday",group:"last",getRange:()=>{const e=Date.now();return[M(e).subtract(1,"day").startOf("day").toDate(),M(e).subtract(1,"day").endOf("day").toDate()]}},{label:"week",value:"last week",group:"last",getRange:()=>{const e=Date.now();return[M(e).subtract(1,"week").startOf("week").toDate(),M(e).subtract(1,"week").endOf("week").toDate()]}},{label:"month",value:"last month",group:"last",getRange:()=>{const e=Date.now();return[M(e).subtract(1,"month").startOf("month").toDate(),M(e).subtract(1,"month").endOf("month").toDate()]}},{label:"2 months",value:"last 2 months",group:"last",getRange:()=>{const e=Date.now();return[M(e).subtract(2,"month").startOf("month").toDate(),M(e).subtract(1,"month").endOf("month").toDate()]}},{label:"3 months",value:"last 3 months",group:"last",getRange:()=>{const e=Date.now();return[M(e).subtract(3,"month").startOf("month").toDate(),M(e).subtract(1,"month").endOf("month").toDate()]}},{label:"year",value:"last year",group:"last",getRange:()=>{const e=Date.now();return[M(e).subtract(1,"year").startOf("year").toDate(),M(e).subtract(1,"year").endOf("year").toDate()]}},{label:"7 days",value:"recent 7 days",group:"recent",getRange:()=>{const e=Date.now();return[M(e).subtract(7,"day").startOf("day").toDate(),M(e).subtract(1,"day").endOf("day").toDate()]}},{label:"30 days",value:"recent 30 days",group:"recent",getRange:()=>{const e=Date.now();return[M(e).subtract(30,"day").startOf("day").toDate(),M(e).subtract(1,"day").endOf("day").toDate()]}},{label:"60 days",value:"recent 60 days",group:"recent",getRange:()=>{const e=Date.now();return[M(e).subtract(60,"day").startOf("day").toDate(),M(e).subtract(1,"day").endOf("day").toDate()]}},{label:"90 days",value:"recent 90 days",group:"recent",getRange:()=>{const e=Date.now();return[M(e).subtract(90,"day").startOf("day").toDate(),M(e).subtract(1,"day").endOf("day").toDate()]}},{label:"180 days",value:"recent 180 days",group:"recent",getRange:()=>{const e=Date.now();return[M(e).subtract(180,"day").startOf("day").toDate(),M(e).subtract(1,"day").endOf("day").toDate()]}},{label:"365 days",value:"recent 365 days",group:"recent",getRange:()=>{const e=Date.now();return[M(e).subtract(365,"day").startOf("day").toDate(),M(e).subtract(1,"day").endOf("day").toDate()]}},{label:"today",value:"today",group:"this",getRange:()=>{const e=Date.now();return[M(e).startOf("day").toDate(),M(e).endOf("day").toDate()]}},{label:"week",value:"this week",group:"this",getRange:()=>{const e=Date.now();return[M(e).startOf("week").toDate(),M(e).endOf("week").toDate()]}},{label:"month",value:"this month",group:"this",getRange:()=>{const e=Date.now();return[M(e).startOf("month").toDate(),M(e).endOf("month").toDate()]}},{label:"2 months",value:"this 2 months",group:"this",getRange:()=>{const e=Date.now();return[M(e).startOf("month").toDate(),M(e).add(1,"month").endOf("week").toDate()]}},{label:"3 months",value:"this 3 months",group:"this",getRange:()=>{const e=Date.now();return[M(e).startOf("month").toDate(),M(e).add(2,"month").endOf("week").toDate()]}},{label:"year",value:"this year",group:"this",getRange:()=>{const e=Date.now();return[M(e).startOf("year").toDate(),M(e).endOf("year").toDate()]}}];function al(e){const n=Dr().find(r=>r.value===e);return n?n.getRange():null}const o1=({onChange:e})=>{const t=r=>()=>{const i=r();e(i)},n=g.useMemo(()=>y.groupBy(Dr(),"group"),[]);return s.jsxs(s.Fragment,{children:[s.jsx(a.Divider,{variant:"dashed",my:10}),s.jsx(a.Table,{withBorder:!1,sx:{"tbody > tr > th, tbody > tr > td":{borderTop:"none",padding:"2px 6px"},"tbody > tr > th":{cursor:"default",userSelect:"none"},td:{paddingLeft:"1px"}},children:s.jsx("tbody",{children:Object.entries(n).map(([r,i])=>s.jsxs("tr",{children:[s.jsx("th",{children:s.jsx(a.Text,{size:"xs",color:"#555",children:r})}),i.map(({label:o,value:l,getRange:c})=>s.jsx("td",{children:s.jsx(a.Button,{compact:!0,size:"xs",variant:"subtle",onClick:t(c),children:o})},o))]},r))})})]})},ol=e=>({label:{display:"block",height:"21.7px"},input:{borderColor:e?"#228be6":"#e9ecef"}}),l1=({label:e,required:t,value:n,onChange:r,max_days:i,allowSingleDateInRange:o,inputFormat:l})=>{const[c,{open:u,close:d}]=re.useDisclosure(!1),[h,p]=n,x=h?M(h).format(l):"",m=p?M(p).format(l):"";return s.jsxs(a.Popover,{opened:c,onClose:d,position:"bottom-start",shadow:"md",children:[s.jsxs(a.Group,{position:"left",grow:!0,noWrap:!0,spacing:0,w:"18em",sx:{marginTop:"3px"},children:[s.jsx(a.Popover.Target,{children:s.jsx(a.TextInput,{label:e,required:t,icon:s.jsx(_.IconCalendar,{size:16}),placeholder:"Start date",readOnly:!0,value:x,onFocus:u,styles:ol(c),sx:{".mantine-Input-input":{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}}})}),s.jsx(a.TextInput,{label:s.jsx(a.Group,{position:"right",children:s.jsx(i1,{begin:h,end:p})}),icon:s.jsx(_.IconMinus,{size:16}),placeholder:"End date",readOnly:!0,disabled:!h,value:m,onFocus:u,styles:ol(c),sx:{".mantine-Input-icon":{transform:"translateX(-22px)"},".mantine-Input-input":{borderLeft:"none",borderTopLeftRadius:0,borderBottomLeftRadius:0},".mantine-Input-input[data-disabled]":{backgroundColor:"transparent",backgroundImage:"linear-gradient(to right, #fff 0%, #f1f3f5 30%)",opacity:1},".mantine-Input-input[data-disabled]::placeholder":{opacity:.6}}})]}),s.jsxs(a.Popover.Dropdown,{p:"sm",children:[s.jsx(a1,{max_days:i}),s.jsx(r1,{value:n,onChange:r,close:d,allowSingleDateInRange:o,max_days:i}),s.jsx(o1,{onChange:r})]})]})},ll=S.observer(({label:e,config:t,value:n=[null,null],onChange:r})=>{const{inputFormat:i,required:o,max_days:l,allowSingleDateInRange:c}=t,u=Array.isArray(n)?n.map(h=>h?M(h).toDate():null):[null,null],d=h=>{r(h.map(p=>p&&M(p).format(i)))};return s.jsx(l1,{label:e,value:u,onChange:d,inputFormat:i,allowSingleDateInRange:c,max_days:l,required:o})}),c1=a.createStyles((e,{radius:t=4})=>({root:{borderRadius:e.fn.radius(t),display:"flex",flexWrap:"nowrap",border:"1px solid #ced4da",paddingLeft:"0px",paddingRight:"30px",backgroundColor:"#fff",transition:"border-color 100ms ease",borderColor:"#e9ecef","&.rc-select.rc-select-open":{borderColor:"#228be6 !important",".rc-select-selection-overflow-item-rest":{display:"none"},".rc-select-selection-overflow-item-suffix":{display:"block"}},".rc-select-selector":{height:"auto",lineHeight:1.55,paddingLeft:"12px",resize:"none",boxSizing:"border-box",fontSize:"14px",width:"100%",color:"#000",display:"block",textAlign:"left",minHeight:"36px",cursor:"pointer",flexGrow:1},".rc-select-selection-search-mirror":{display:"none"},".rc-select-selection-search":{flexGrow:1,width:"auto !important"},".rc-select-selection-overflow":{display:"flex",minHeight:"34px",alignItems:"center",flexWrap:"nowrap",marginLeft:"calc(-10px / 2)",boxSizing:"border-box"},".rc-select-selection-overflow-item":{display:"flex",alignItems:"center",backgroundColor:"#f1f3f5",color:"#495057",height:"24px",paddingLeft:"12px",paddingRight:"12px",fontWeight:500,fontSize:"12px",borderRadius:"4px",cursor:"default",userSelect:"none",maxWidth:"calc(100% - 20px)",margin:"calc(10px / 2 - 2px) calc(10px / 2)"},".rc-select-selection-overflow-item-rest":{cursor:"pointer"},".rc-select-selection-overflow-item-suffix":{display:"none",backgroundColor:"transparent",width:"100%",maxWidth:"100%",height:"28px",margin:0,paddingLeft:0,paddingRight:0},input:{flex:1,minWidth:"60px",backgroundColor:"transparent",border:0,outline:0,fontSize:"14px",padding:0,marginLeft:0,color:"inherit",height:"28px",lineHeight:"32px",cursor:"pointer",width:"100%","&::-webkit-search-decoration, &::-webkit-search-cancel-button, &::-webkit-search-results-button, &::-webkit-search-results-decoration":{display:"none"}},".rc-select-clear":{marginRight:"-24px",alignSelf:"center",cursor:"pointer"},"&.rc-select-disabled":{backgroundColor:"rgb(241, 243, 245)",color:"rgb(144, 146, 150)",opacity:.6,"&, .rc-select-selector, input":{cursor:"not-allowed"}}},label:{fontSize:e.fontSizes.sm,fontWeight:500,color:"#212529"},required:{color:"#fa5252",paddingLeft:"3px"},dropdown:{fontSize:e.fontSizes.xs,zIndex:300,backgroundColor:"#fff",border:"1px solid #e9ecef",marginTop:6,padding:0,boxShadow:"0 1px 3px rgb(0 0 0 / 5%), rgb(0 0 0 / 5%) 0px 10px 15px -5px, rgb(0 0 0 / 4%) 0px 7px 7px -5px",borderRadius:"4px","&.rc-select-dropdown-slide-up-leave-active":{display:"none"},".rc-select-item-empty":{padding:"8px 12px"},".rc-select-item-option":{boxSizing:"border-box",textAlign:"left",width:"100%",padding:"8px 12px 8px 2px",cursor:"pointer",fontSize:"14px",color:"#000",borderRadius:"4px",display:"flex",flexWrap:"nowrap",overflow:"hidden","&:hover":{backgroundColor:"#f1f3f5"},flexDirection:"row-reverse",".rc-select-item-option-state":{flexGrow:0,flexShrink:0,width:"30px",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},".rc-select-item-option-content":{width:"calc(100% - 30px)",overflow:"hidden",'div[data-role="label"]':{overflowWrap:"break-word"}}},".rc-virtual-list-holder-inner":{alignItems:"flex-start"}}})),cl=({errorMessage:e})=>e?s.jsx(a.Text,{color:"red",size:12,children:e}):s.jsx(a.Text,{color:"dimmed",size:12,children:"Not found"}),u1=({disabled:e,classNames:t,styles:n,unstyled:r,radius:i,style:o,label:l,value:c,onChange:u,options:d,errorMessage:h,required:p})=>{const{classes:x,cx:m}=c1({radius:i},{name:"MultiSelectWidget",classNames:t,styles:n,unstyled:r}),[j,C]=g.useState(!1),T=R=>{C(R)},D=j&&(c==null?void 0:c.length)>0,[A,N]=g.useState(""),Y=g.useMemo(()=>{if(!A)return d;const R=A.toLowerCase(),F=Z=>{var se;return((se=Z.description)==null?void 0:se.toLowerCase().includes(R))||Z.label.toLowerCase().includes(R)};return d.filter(F)},[A,d]);return s.jsxs(a.Stack,{spacing:3,children:[s.jsxs(a.Group,{position:"apart",children:[s.jsxs(a.Text,{className:x.label,children:[l,p&&s.jsx("span",{className:x.required,"aria-hidden":"true",children:"*"})]}),D&&s.jsx(a.Tooltip,{label:`${c.length} selected`,children:s.jsx(a.Badge,{children:c.length})})]}),s.jsx(Ri,{disabled:e,allowClear:!0,className:m(x.root,"check-select"),dropdownClassName:m(x.dropdown,""),onDropdownVisibleChange:T,transitionName:"rc-select-dropdown-slide-up",choiceTransitionName:"rc-select-selection__choice-zoom",style:o,clearIcon:()=>s.jsx(a.CloseButton,{}),value:c,onChange:u,onSelect:console.log,mode:"multiple",maxTagCount:0,notFoundContent:s.jsx(cl,{errorMessage:h}),maxTagTextLength:10,maxTagPlaceholder:R=>`${R.length} selected`,searchValue:A,onSearch:N,filterOption:!1,children:Y.map(R=>s.jsxs(Ri.Option,{title:R.label,children:[s.jsx(a.Text,{size:"sm","data-role":"label",children:R.label}),R.description&&s.jsx(a.Text,{size:"xs",color:"dimmed","data-role":"description",children:R.description})]},R.value))})]})},d1=S.observer(({label:e,config:t,value:n,onChange:r})=>{const i=ce(),o=!!t.options_query_id,{state:l,error:c}=i.getDataStuffByID(t.options_query_id),u=l==="loading",d=t.min_width?t.min_width:"200px",h=o?u:!1,p=x=>r(x,!1);return s.jsx(u1,{label:e,options:t.options,style:{minWidth:"160px",width:d,maxWidth:h?d:"unset",borderColor:"#e9ecef"},disabled:h,value:n,onChange:p,errorMessage:c,required:t.required})}),p1=g.forwardRef(({label:e,description:t,...n},r)=>s.jsx("div",{ref:r,...n,children:s.jsx(a.Group,{noWrap:!0,children:s.jsxs("div",{children:[s.jsx(a.Text,{size:"sm","data-role":"label",children:e}),s.jsx(a.Text,{size:"xs",color:"dimmed","data-role":"description",children:t})]})})})),h1=S.observer(({label:e,config:t,value:n,onChange:r})=>{const i=ce(),o=!!t.options_query_id,{state:l,error:c}=i.getDataStuffByID(t.options_query_id),u=l==="loading";return s.jsx(a.Select,{label:e,data:t.options,disabled:o?u:!1,value:n,onChange:r,error:!!c,placeholder:c,maxDropdownHeight:500,styles:{root:{width:t.width?t.width:"200px"},input:{borderColor:"#e9ecef"}},sx:{".mantine-Select-item[data-selected] .mantine-Text-root[data-role=description]":{color:"rgba(255,255,255,.7)"}},itemComponent:p1})});function x1({label:e,config:t,value:n,onChange:r}){return s.jsx(a.TextInput,{label:e,value:n||"",onChange:i=>r(i.currentTarget.value),...t,styles:{input:{borderColor:"#e9ecef"}}})}const f1=({rotate:e,onClick:t})=>s.jsx("svg",{onClick:t,className:"caret-icon",viewBox:"0 0 1024 1024",focusable:"false","data-icon":"caret-down",width:"14px",height:"14px",fill:"currentColor","aria-hidden":"true",transform:`rotate(${e})`,children:s.jsx("path",{d:"M840.4 300H183.6c-19.7 0-30.7 20.8-18.5 35l328.4 380.8c9.4 10.9 27.5 10.9 37 0L858.9 335c12.2-14.2 1.2-35-18.5-35z"})}),g1=({expanded:e,isLeaf:t,value:n,onClick:r,...i})=>(n==="0-0-value"&&console.log(i),t?s.jsx("span",{style:{width:"14px",display:"inline-block"}}):s.jsx(f1,{rotate:e?"0":"-90",onClick:r,...i})),m1=({onClick:e})=>s.jsxs("svg",{onClick:e,className:"checkbox-icon",width:"16",height:"16",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:"2",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),s.jsx("rect",{className:"border",x:"4",y:"4",width:"16",height:"16",rx:"2"}),s.jsx("rect",{className:"checkmark-indeterminate",x:"8",y:"8",width:"8",height:"8",rx:"2",stroke:"none"}),s.jsx("path",{className:"checkmark-checked",d:"M9 12l2 2l4 -4"})]}),y1=({onClick:e,...t})=>s.jsx(m1,{onClick:e,...t}),b1=a.createStyles((e,{radius:t=4})=>({root:{borderRadius:e.fn.radius(t),display:"flex",flexWrap:"nowrap",border:"1px solid #ced4da",paddingLeft:"0px",paddingRight:"30px",backgroundColor:"#fff",transition:"border-color 100ms ease",borderColor:"#e9ecef","&.rc-tree-select.rc-tree-select-open":{borderColor:"#228be6 !important",".rc-tree-select-selection-overflow-item-rest":{display:"none"},".rc-tree-select-selection-overflow-item-suffix":{display:"block"}},".rc-tree-select-selector":{height:"auto",lineHeight:1.55,paddingLeft:"12px",resize:"none",boxSizing:"border-box",fontSize:"14px",width:"100%",color:"#000",display:"block",textAlign:"left",minHeight:"36px",cursor:"pointer",flexGrow:1},".rc-tree-select-selection-search-mirror":{display:"none"},".rc-tree-select-selection-search":{flexGrow:1,width:"auto !important"},".rc-tree-select-selection-overflow":{display:"flex",minHeight:"34px",alignItems:"center",flexWrap:"nowrap",marginLeft:"calc(-10px / 2)",boxSizing:"border-box"},".rc-tree-select-selection-overflow-item":{display:"flex",alignItems:"center",backgroundColor:"#f1f3f5",color:"#495057",height:"24px",paddingLeft:"12px",paddingRight:"12px",fontWeight:500,fontSize:"12px",borderRadius:"4px",cursor:"default",userSelect:"none",maxWidth:"calc(100% - 20px)",margin:"calc(10px / 2 - 2px) calc(10px / 2)"},".rc-tree-select-selection-overflow-item-rest":{cursor:"pointer"},".rc-tree-select-selection-overflow-item-suffix":{display:"none",backgroundColor:"transparent",width:"100%",maxWidth:"100%",height:"28px",margin:0,paddingLeft:0,paddingRight:0},input:{flex:1,minWidth:"60px",backgroundColor:"transparent",border:0,outline:0,fontSize:"14px",padding:0,marginLeft:0,color:"inherit",height:"28px",lineHeight:"32px",cursor:"pointer",width:"100%","&::-webkit-search-decoration, &::-webkit-search-cancel-button, &::-webkit-search-results-button, &::-webkit-search-results-decoration":{display:"none"}},".rc-tree-select-clear":{marginRight:"-24px",alignSelf:"center",cursor:"pointer"},"&.rc-tree-select-disabled":{backgroundColor:"rgb(241, 243, 245)",color:"rgb(144, 146, 150)",opacity:.6,"&, .rc-tree-select-selector, input":{cursor:"not-allowed"}}},label:{fontSize:e.fontSizes.sm,fontWeight:500,color:"#212529"},required:{color:"#fa5252",paddingLeft:"3px"},dropdown:{fontSize:e.fontSizes.xs,zIndex:300,paddingTop:"6px","&.rc-tree-select-dropdown-slide-up-leave-active":{display:"none"},".rc-tree-select-tree-list .rc-tree-select-tree-list-holder":{},".rc-tree-select-tree-list, .rc-tree-select-empty":{backgroundColor:"#fff",border:"1px solid #e9ecef",padding:0,boxShadow:"0 1px 3px rgb(0 0 0 / 5%), rgb(0 0 0 / 5%) 0px 10px 15px -5px, rgb(0 0 0 / 4%) 0px 7px 7px -5px",borderRadius:"4px"},".rc-tree-select-empty":{padding:"8px 12px"},".rc-tree-select-tree-treenode":{boxSizing:"border-box",textAlign:"left",width:"100%",padding:"8px 12px",cursor:"pointer",fontSize:"14px",color:"#000",borderRadius:"4px",display:"flex",flexWrap:"nowrap",overflow:"hidden","&:hover":{backgroundColor:"#f1f3f5"},"&.rc-tree-select-tree-treenode-checkbox-checked":{".rc-tree-select-tree-iconEle .checkbox-icon .checkmark-checked":{stroke:"rgb(64, 192, 87)",animation:"check 200ms linear forwards"}},"&.rc-tree-select-tree-treenode-checkbox-indeterminate":{".rc-tree-select-tree-iconEle .checkbox-icon .checkmark-indeterminate":{fill:"rgb(64, 192, 87)"}},".rc-tree-select-tree-switcher":{height:"16px",alignSelf:"center",paddingRight:"2px",transition:"color 200ms ease","&:hover":{color:"#228be6","svg.caret-icon":{color:"#228be6"}},"svg.caret-icon":{color:"#ced4da",transition:"all 200ms ease"}},".rc-tree-select-tree-node-content-wrapper":{display:"flex",flexWrap:"nowrap",overflow:"hidden",alignItems:"center",gap:"8px",transition:"color 200ms ease","&:hover":{color:"#228be6"}},".rc-tree-select-tree-iconEle":{height:"16px","svg .border":{stroke:"#ced4da"},".checkbox-icon .checkmark-indeterminate":{fill:"transparent",transition:"fill 200ms ease"},".checkbox-icon .checkmark-checked":{transform:"scale(1.2)",transformOrigin:"center center",strokeDasharray:10,strokeDashoffset:-10},"@keyframes check":{"0%":{strokeDashoffset:10},"100%":{strokeDashoffset:0}}},".rc-tree-select-tree-title":{textOverflow:"ellipsis",whiteSpace:"nowrap",overflow:"hidden",".rc-tree-select-tree-title-desc":{fontSize:"12px",maxWidth:"100%",textOverflow:"ellipsis",whiteSpace:"nowrap",overflow:"hidden"}},".rc-tree-select-tree-indent":{flexGrow:0,height:0,verticalAlign:"bottom"},".rc-tree-select-tree-indent-unit":{display:"inline-block",width:"1em"}}}})),j1=({disabled:e,classNames:t,styles:n,unstyled:r,radius:i,style:o,label:l,value:c,onChange:u,treeData:d,errorMessage:h,required:p,treeCheckStrictly:x})=>{const{classes:m,cx:j}=b1({radius:i},{name:"FilterTreeSelectWidget",classNames:t,styles:n,unstyled:r}),[C,T]=g.useState(!1),D=N=>{T(N)},A=C&&(c==null?void 0:c.length)>0;return s.jsxs(a.Stack,{spacing:3,children:[s.jsxs(a.Group,{position:"apart",children:[s.jsxs(a.Text,{className:m.label,children:[l,p&&s.jsx("span",{className:m.required,"aria-hidden":"true",children:"*"})]}),A&&s.jsx(a.Tooltip,{label:`${c.length} selected`,children:s.jsx(a.Badge,{children:c.length})})]}),s.jsx(Qi,{disabled:e,allowClear:!0,treeCheckStrictly:x,labelInValue:!0,className:j(m.root,"check-select"),dropdownClassName:j(m.dropdown,""),onDropdownVisibleChange:D,transitionName:"rc-tree-select-dropdown-slide-up",choiceTransitionName:"rc-tree-select-selection__choice-zoom",style:o,listHeight:510,treeLine:!0,clearIcon:()=>s.jsx(a.CloseButton,{}),switcherIcon:g1,treeIcon:y1,maxTagTextLength:10,value:c,treeData:d,notFoundContent:s.jsx(cl,{errorMessage:h}),treeNodeFilterProp:"filterBasis",treeCheckable:!0,showCheckedStrategy:Qi.SHOW_PARENT,onChange:u,onSelect:console.log,maxTagCount:0,maxTagPlaceholder:()=>`${c.length} selected`})]})},v1=S.observer(({label:e,config:t,value:n,onChange:r})=>{const{treeData:i,treeDataLoading:o,errorMessage:l}=t,c=x=>{const m=x.map(j=>j.value);r(m,!1)},u=g.useMemo(()=>t.initialSelection(n),[n,t.plainData,t.defaultSelection,t.initialSelection]),d=t.min_width?t.min_width:"200px",p=!!t.options_query_id?o:!1;return s.jsx(j1,{disabled:p,style:{minWidth:"160px",width:d,maxWidth:p?d:"unset",borderColor:"#e9ecef"},value:[...u],onChange:c,treeData:i,errorMessage:l,label:e,required:t.required,treeCheckStrictly:t.treeCheckStrictly})}),w1=S.observer(({filter:{type:e,config:t,key:n,...r},formFieldProps:i})=>{switch(e){case"select":return s.jsx(h1,{...r,...i,config:t});case"multi-select":return s.jsx(d1,{...r,...i,config:t});case"tree-select":return s.jsx(v1,{...r,...i,config:t});case"text-input":return s.jsx(x1,{...r,...i,config:t});case"date-range":return s.jsx(ll,{...r,...i,config:t});case"checkbox":return s.jsx(s1,{...r,...i,config:t});default:return null}}),C1=S.observer(g.forwardRef(({filter:e,...t},n)=>s.jsx("div",{className:"filter-root",ref:n,children:s.jsx(je,{children:s.jsx(w1,{filter:e,formFieldProps:t})})}))),S1=({disabled:e})=>{const{searchButtonProps:t}=xa(),{children:n="Search",type:r,...i}=t;return s.jsx(a.Button,{color:"blue",size:"sm",type:"submit",...i,disabled:e||i.disabled,children:n})};function _1(e){const t=W();g.useEffect(()=>{var n,r;(r=(n=t.filters).updatePreviewValues)==null||r.call(n,e)},[e])}const k1=({opened:e,toggle:t})=>s.jsx(a.Group,{position:"right",ml:-4,mt:-4,mb:e?4:0,children:s.jsx(a.Button,{size:"xs",compact:!0,variant:"subtle",color:e?"gray":"blue",leftIcon:e?s.jsx(_.IconChevronsUp,{size:14}):s.jsx(_.IconChevronsDown,{size:14}),onClick:t,children:e?"Hide Filters":"Show Filters"})}),ul=S.observer(function({view:t}){const[n,{toggle:r}]=re.useDisclosure(!0),i=ce(),{control:o,handleSubmit:l,reset:c}=b.useForm({defaultValues:i.filters.values,reValidateMode:"onBlur"}),u=b.useWatch({control:o});g.useEffect(()=>{c(i.filters.values)},[i.filters.values,c]),_1(u);const d=i.filters.visibleInView(t.id),h=g.useMemo(()=>d.every(j=>j.should_auto_submit),[d]),p=g.useMemo(()=>d.filter(j=>y.get(j,"config.required",!1)),[d]),x=g.useMemo(()=>p.length===0?!1:p.some(j=>!j.requiredAndPass(u[j.key])),[u,p]);if(d.length===0)return null;const m=(j,C)=>(T,D)=>{C(T),(j.should_auto_submit||D)&&i.filters.setValueByKey(j.key,T)};return s.jsxs("form",{onSubmit:l(i.filters.setValues),children:[s.jsx(k1,{opened:n,toggle:r}),s.jsx(a.Collapse,{in:n,children:s.jsxs(a.Group,{className:"dashboard-filters",position:"apart",noWrap:!0,sx:h?{}:{border:"1px solid #e9ecef",borderRadius:"4px",padding:"16px"},children:[s.jsx(a.Group,{align:"flex-start",children:d.map(j=>s.jsx(b.Controller,{name:j.key,control:o,render:({field:C})=>s.jsx(C1,{filter:j,value:C.value,onChange:m(j,C.onChange)})},j.id))}),!h&&s.jsx(a.Group,{sx:{alignSelf:"flex-end"},children:s.jsx(S1,{disabled:x})})]})})]})}),T1={viewPanelInFullScreen:y.noop,inFullScreen:!1},Jn=g.createContext(T1),Ir=f.types.model("MockContextMeta",{current:f.types.optional(f.types.frozen(),{})}).views(e=>({get keys(){return Object.keys(e.current)},get keySet(){return new Set(this.keys)},get entries(){return Object.entries(e.current)}})).actions(e=>({replace(t){e.current=t},defaults(t){e.current={...t,...e.current}},get(t){return e.current[t]},set(t,n){e.current[t]=n}}));function Mr(e){return{current:e}}const D1=f.types.model("PanelStyleBorderMeta",{enabled:f.types.boolean}).views(e=>({get json(){const{enabled:t}=e;return{enabled:t}}})).actions(e=>({setEnabled(t){e.enabled=t}})),dl=f.types.model("PanelStyleMeta",{border:D1}).views(e=>({get json(){const{border:t}=e;return{border:t.json}}})).actions(e=>({})),pl=f.types.model("PanelTitleMeta",{show:f.types.optional(f.types.boolean,!0)}).views(e=>({get json(){const{show:t}=e;return{show:t}}})).actions(e=>({setShow(t){e.show=t}})),hl=f.types.model("VariableMeta",{name:f.types.string,size:f.types.string,weight:f.types.string,color:f.types.union(f.types.model({type:f.types.literal("static"),staticColor:f.types.string}),f.types.model({type:f.types.literal("continuous"),valueRange:f.types.array(f.types.number),colorRange:f.types.array(f.types.string)}),f.types.model({type:f.types.literal("piecewise")})),formatter:f.types.model({output:f.types.enumeration("Output",["number","percent"]),average:f.types.optional(f.types.boolean,!1),mantissa:f.types.number,trimMantissa:f.types.optional(f.types.boolean,!1),absolute:f.types.optional(f.types.boolean,!1)}),data_field:f.types.string,aggregation:f.types.union(f.types.model({type:f.types.enumeration(["none","sum","mean","median","min","max","CV","std"]),config:f.types.frozen(),fallback:f.types.optional(f.types.string,"0")}),f.types.model({type:f.types.literal("quantile"),config:f.types.model({p:f.types.number}),fallback:f.types.optional(f.types.string,"0")}),f.types.model({type:f.types.literal("custom"),config:f.types.model({func:f.types.string}),fallback:f.types.optional(f.types.string,"0")}))}).views(e=>({get json(){const{name:t,size:n,weight:r,color:i,formatter:o,data_field:l,aggregation:c}=e;return y.cloneDeep({name:t,size:n,color:i,weight:r,formatter:o,data_field:l,aggregation:c})}})),xl=f.types.model("PanelVizMeta",{type:f.types.string,conf:f.types.frozen()}).views(e=>({get json(){return{conf:e.conf,type:e.type}}})).actions(e=>({setType(t){e.type=t},setConf(t){e.conf=t}})),fl=f.types.model({id:f.types.string,name:f.types.optional(f.types.string,""),title:pl,description:f.types.string,queryIDs:f.types.array(f.types.string),viz:xl,style:dl,variables:f.types.optional(f.types.array(hl),[])}).views(e=>({get json(){const{id:t,name:n,title:r,description:i,queryIDs:o}=e;return{id:t,viz:e.viz.json,name:n,style:e.style.json,title:r.json,queryIDs:[...o],variables:e.variables.map(l=>l.json),description:i}},get queryIDSet(){return new Set(e.queryIDs)}})).actions(e=>({setID(t){e.id=t},setName(t){e.name=t},setDescription(t){e.description=t},addQueryID(t){e.queryIDSet.has(t)||e.queryIDs.push(t)},removeQueryID(t){if(!e.queryIDSet.has(t))return;const n=new Set(e.queryIDSet);n.delete(t),e.queryIDs=f.cast(Array.from(n))},setQueryIDs(t){e.queryIDs=f.cast(t)},addVariable(t){e.variables.push(t)},removeVariable(t){e.variables.remove(t)}}));var oe=(e=>(e.Postgresql="postgresql",e.MySQL="mysql",e.HTTP="http",e.Transform="transform",e))(oe||{});const gl=f.types.model("QueryMeta",{id:f.types.string,name:f.types.string,type:f.types.enumeration("DataSourceType",[oe.Postgresql,oe.MySQL,oe.HTTP,oe.Transform]),key:f.types.string,sql:f.types.string,pre_process:f.types.optional(f.types.string,""),post_process:f.types.optional(f.types.string,""),run_by:f.types.optional(f.types.array(f.types.string),[]),react_to:f.types.optional(f.types.array(f.types.string),[]),dep_query_ids:f.types.optional(f.types.array(f.types.string),[])}).views(e=>({get valid(){return e.id&&e.type&&e.key&&e.name?e.type===oe.HTTP?!!e.pre_process:!!e.sql:!1},get json(){const{id:t,name:n,type:r,key:i,sql:o,run_by:l,react_to:c,pre_process:u,post_process:d,dep_query_ids:h}=e;return At({id:t,key:i,sql:o,name:n,type:r,run_by:l,react_to:c,pre_process:u,post_process:d,dep_query_ids:h})}})).actions(e=>({setName(t){e.name=t},setKey(t){e.key=t},setType(t){e.type=t},setSQL(t){e.sql=t},setRunBy(t){e.run_by.length=0,e.run_by.push(...t)},setReactTo(t){e.react_to.length=0,e.react_to.push(...t)},setPreProcess(t){e.pre_process=t},setPostProcess(t){e.post_process=t},setDependantQueryIDs(t){e.dep_query_ids.length=0,e.dep_query_ids.push(...t)}})),ml=f.types.model("LayoutItemMeta",{id:f.types.identifier,panelID:f.types.string,x:f.types.number,y:f.types.maybeNull(f.types.number),w:f.types.number,h:f.types.number,moved:f.types.optional(f.types.boolean,!1),static:f.types.optional(f.types.boolean,!1)}).views(e=>({get json(){const{id:t,panelID:n,x:r,y:i,w:o,h:l,moved:c}=e;return{h:l,w:o,x:r,y:i===null?0:i,id:t,moved:c,static:e.static,panelID:n}},get contentModel(){return f.getRoot(e).content},get panel(){const{panelID:t}=e;return this.contentModel.panels.findByID(t)},get layoutProperies(){const{id:t,x:n,y:r,w:i,h:o,moved:l}=e;return{id:t,i:t,x:n,y:r===null?1/0:r,w:i,h:o,moved:l,static:e.static}}})).actions(e=>({set(t){const{isDraggable:n,x:r,y:i,w:o,h:l,moved:c}=t;e.x=r,e.y=i,e.w=o,e.h=l,e.moved=!!c,e.static=!!t.static},setWidth(t){e.w=t},setHeight(t){e.h=t}})),yl=f.types.model("LayoutSetMeta",{id:f.types.identifier,name:f.types.string,breakpoint:f.types.number,list:f.types.optional(f.types.array(ml),[])}).views(e=>({get json(){const{id:t,name:n,breakpoint:r,list:i}=e;return{id:t,name:n,breakpoint:r,list:i.map(o=>At(o.json))}},jsonByPanelIDSet(t){const{id:n,name:r,breakpoint:i,list:o}=e;return{id:n,name:r,breakpoint:i,list:o.filter(l=>t.has(l.panelID)).map(l=>At(l.json))}},findByID(t){return e.list.find(n=>n.id===t)},findByPanelID(t){return e.list.find(n=>n.panelID===t)}})).actions(e=>({setName(t){e.name=t},setBreakpoint(t){e.breakpoint=t},addLayout(t){e.list.push(t)},addNewLayout(t){e.list.push({id:pt.v4(),panelID:t,x:0,y:1/0,w:18,h:300,static:!1,moved:!1})},removeByPanelID(t){const n=e.list.findIndex(r=>r.panelID===t);n>=0&&e.list.splice(n,1)},updateLayoutItem(t){const n=e.list.find(r=>r.id===t.i);if(!n){console.error("Trying to update a layout that doesn't exist"),console.log({strangeLayoutItem:t});return}n.set(t)}})),bl=f.types.model("SQLSnippetMeta",{key:f.types.string,value:f.types.string}).views(e=>({get json(){const{key:t,value:n}=e;return{key:t,value:n}}})).actions(e=>({setKey(t){e.key=t},setValue(t){e.value=t}}));var de=(e=>(e.Select="select",e.MultiSelect="multi-select",e.TreeSelect="tree-select",e.TextInput="text-input",e.Checkbox="checkbox",e.DateRange="date-range",e))(de||{});const zr=f.types.model("FilterCheckboxConfigMeta",{_name:f.types.literal("checkbox"),description:f.types.optional(f.types.string,""),default_value:f.types.boolean}).views(e=>({get json(){const{_name:t,description:n,default_value:r}=e;return{_name:t,description:n,default_value:r}},get isDescriptionEmpty(){const{description:t}=e;return t===""||t==="<p></p>"}})).actions(e=>({setDefaultValue(t){e.default_value=t},setDescription(t){e.description=t}})),jl=()=>zr.create({_name:"checkbox",description:"",default_value:!1});function vl(e,t){return e.map(n=>{try{return n?M.tz(n,"UTC").format(t):null}catch{return console.log(`[date-range] failed parsing ${n}`),null}})}const I1=f.types.model("FilterDateRangeConfigMeta",{_name:f.types.literal("date-range"),required:f.types.boolean,inputFormat:f.types.enumeration("DateRangeInputFormat",["YYYY","YYYYMM","YYYYMMDD","YYYY-MM","YYYY-MM-DD"]),default_value:f.types.optional(f.types.array(f.types.union(f.types.string,f.types.null)),[null,null]),default_shortcut:f.types.optional(f.types.string,""),clearable:f.types.boolean,max_days:f.types.optional(f.types.number,0),allowSingleDateInRange:f.types.optional(f.types.boolean,!1)}).views(e=>({get json(){const{_name:t,max_days:n,required:r,clearable:i,inputFormat:o,default_value:l,default_shortcut:c,allowSingleDateInRange:u}=e;return{_name:t,max_days:n,required:r,clearable:i,inputFormat:o,default_value:vl(l,o),default_shortcut:c,allowSingleDateInRange:u}},truthy(t){return Array.isArray(t)&&t.length===2&&t.every(n=>!!n)}})).actions(e=>({setFilterValue(t){try{const n=f.getParent(e);f.getParent(n,2).setValueByKey(n.key,t)}catch(n){console.error(n)}}})).actions(e=>({setRequired(t){e.required=t},setClearable(t){e.clearable=t},setInputFormat(t){e.inputFormat=t},setDefaultValue(t){e.default_value.length=0,e.default_value.push(...t),e.setFilterValue(t)},setDefaultShortcut(t){if(e.default_shortcut=t,!t)return;const n=al(e.default_shortcut);if(console.log(n),n){const r=n.map(i=>M(i).format(e.inputFormat));e.setFilterValue(r)}},setMaxDays(t){e.max_days=t,t>0&&(e.clearable=!0)},setAllowSingleDateInRange(t){e.allowSingleDateInRange=t}})),Ar=f.types.snapshotProcessor(I1,{preProcessor({default_value:e,...t}){return{...t,default_value:e.map(n=>n===null?null:M.tz(n,"UTC").toISOString())}},postProcessor(e){const{default_value:t,...n}=e;return{...n,default_value:vl(t,n.inputFormat)}}}),wl=()=>Ar.create({_name:"date-range",required:!1,inputFormat:"YYYY-MM-DD",clearable:!1,default_value:[null,null]}),M1=f.types.model({label:f.types.string,value:f.types.string}).actions(e=>({setLabel(t){e.label=t},setValue(t){e.value=t}})),Er=f.types.model("FilterConfigModel_BaseSelect",{static_options:f.types.optional(f.types.array(M1),[]),options_query_id:f.types.optional(f.types.string,""),default_selection_count:f.types.optional(f.types.number,0),required:f.types.optional(f.types.boolean,!1)}).views(e=>({get contentModel(){return f.getRoot(e).content},get filter(){return f.getParent(e)},get usingQuery(){return!!e.options_query_id}})).views(e=>({get options(){if(!e.usingQuery)return e.static_options;const{data:t,state:n,error:r}=e.contentModel.getDataStuffByID(e.options_query_id);return n==="idle"?Array.isArray(t)?t:[]:[]}})).actions(e=>({setRequired(t){e.required=t},addStaticOption(t){e.static_options.push(t)},removeStaticOption(t){e.static_options.splice(t,1)},setDefaultSelectionCount(t){e.default_selection_count=t},setOptionsQueryID(t){e.options_query_id=t??""}})),Pr=f.types.compose("FilterMultiSelectConfigMeta",f.types.model({_name:f.types.literal("multi-select"),min_width:f.types.optional(f.types.string,""),default_value:f.types.optional(f.types.array(f.types.string),[])}),Er).views(e=>({get json(){const{_name:t,default_value:n,required:r,min_width:i,static_options:o,options_query_id:l,default_selection_count:c}=e;return At({_name:t,required:!!r,min_width:i,default_value:n,static_options:o,options_query_id:l,default_selection_count:c})},get default_selection(){return e.usingQuery?e.options.slice(0,e.default_selection_count).map(t=>t.value):e.filter.formattedDefaultValue},truthy(t){return Array.isArray(t)&&t.length>0}})).actions(e=>({setDefaultValue(t){e.default_value=f.cast(t)},setMinWidth(t){e.min_width=t},setDefaultSelection(){const t=f.getRoot(e).content.filters,n=f.getParent(e).key;t.setValueByKey(n,e.default_selection)}})).actions(e=>({afterCreate(){f.addDisposer(e,U.reaction(()=>U.toJS(e.default_selection),e.setDefaultSelection,{fireImmediately:!0,delay:0}))}})),Cl=()=>Pr.create({_name:"multi-select",default_value:[],static_options:[],options_query_id:"",default_selection_count:0}),Lr=f.types.compose("FilterConfigModel_Select",f.types.model({_name:f.types.literal("select"),default_value:f.types.string,width:f.types.optional(f.types.string,"")}),Er).views(e=>({get json(){const{_name:t,default_value:n,required:r,width:i,static_options:o,options_query_id:l,default_selection_count:c}=e;return At({_name:t,width:i,required:r,default_value:n,static_options:o,options_query_id:l,default_selection_count:c})},truthy(t){return!!t},getSelectOption(t){return e.options.find(n=>n.value===t)},get default_selection(){return e.usingQuery?e.default_selection_count>0&&e.options.length>0?e.options[0].value:"":e.filter.formattedDefaultValue}})).actions(e=>({setDefaultValue(t){e.default_value=t},setWidth(t){e.width=t},setDefaultSelection(){const t=f.getRoot(e).content.filters,n=f.getParent(e).key;t.setValueByKey(n,e.default_selection)}})).actions(e=>({afterCreate(){f.addDisposer(e,U.reaction(()=>U.toJS(e.default_selection),e.setDefaultSelection,{fireImmediately:!0,delay:0}))}})),Sl=()=>Lr.create({_name:"select",required:!1,default_value:"",static_options:[],options_query_id:"",default_selection_count:0}),Br=f.types.model("FilterTextInputConfigMeta",{_name:f.types.literal("text-input"),required:f.types.boolean,default_value:f.types.string}).views(e=>({get json(){const{_name:t,required:n,default_value:r}=e;return{_name:t,required:n,default_value:r}},truthy(t){return typeof t!="string"?!1:!!t.trim()}})).actions(e=>({setRequired(t){e.required=t},setDefaultValue(t){e.default_value=t}})),Or=()=>Br.create({_name:"text-input",required:!1,default_value:""});function z1(e){return fu.arrayToTree(e,{id:"value",parentId:"parent_value",childrenField:"children",dataField:null})}function A1(e){return e.map(t=>{const{label:n,description:r,...i}=t,o={...i,filterBasis:`${n}___${r??""}`,description:r,label:n};return r&&(o.label=g.createElement("div",{},[g.createElement(a.Text,{key:0,title:t.label},t.label),g.createElement(a.Text,{key:1,className:"rc-tree-select-tree-title-desc",color:"dimmed",title:t.description},t.description)])),o})}const $r=f.types.compose("FilterTreeSelectConfigMeta",f.types.model({_name:f.types.literal("tree-select"),min_width:f.types.optional(f.types.string,""),default_value:f.types.optional(f.types.array(f.types.string),[]),treeCheckStrictly:f.types.optional(f.types.boolean,!1)}),Er).views(e=>({get json(){const{_name:t,default_value:n,required:r,min_width:i,static_options:o,options_query_id:l,default_selection_count:c,treeCheckStrictly:u}=e;return{_name:t,required:!!r,min_width:i,default_value:n,static_options:o,options_query_id:l,treeCheckStrictly:u,default_selection_count:c}},get plainData(){const{data:t}=e.contentModel.getDataStuffByID(e.options_query_id);return t},get treeData(){const t=this.plainData,n=A1(t);return z1(n)},get errorMessage(){const{error:t}=e.contentModel.getDataStuffByID(e.options_query_id);return t},get treeDataLoading(){const{state:t}=e.contentModel.getDataStuffByID(e.options_query_id);return t==="loading"},get defaultSelection(){const t=e.filter.formattedDefaultValue;if(Array.isArray(t)&&t.length>0)return t;const{default_selection_count:n}=e;return n?this.treeData.slice(0,n).map(i=>i.value):[]},valueObjects(t){const n=new Set(t);return this.plainData.filter(r=>n.has(r.value))},initialSelection(t){return!t||t.length===0?this.valueObjects(this.defaultSelection):this.valueObjects(t)},truthy(t){return Array.isArray(t)&&t.length>0}})).actions(e=>({setDefaultValue(t){e.default_value=f.cast(t)},setMinWidth(t){e.min_width=t},setTreeCheckStrictly(t){e.treeCheckStrictly=t},applyDefaultSelection(){const t=f.getParent(e,1).key;e.contentModel.filters.setValueByKey(t,e.defaultSelection)},afterCreate(){f.addDisposer(e,U.reaction(()=>JSON.stringify(e.defaultSelection),this.applyDefaultSelection,{fireImmediately:!0,delay:0}))}})),_l=()=>$r.create({_name:"tree-select",default_value:[],static_options:[],options_query_id:"",default_selection_count:0}),Vr=f.types.model("FilterMeta",{id:f.types.identifier,key:f.types.string,label:f.types.string,order:f.types.number,visibleInViewsIDs:f.types.array(f.types.string),auto_submit:f.types.optional(f.types.boolean,!1),default_value_func:f.types.optional(f.types.string,""),type:f.types.enumeration("DashboardFilterType",[de.Select,de.MultiSelect,de.TreeSelect,de.TextInput,de.Checkbox,de.DateRange]),config:f.types.union(Lr,Pr,$r,Br,zr,Ar)}).views(e=>({get contentModel(){return f.getRoot(e).content},get filters(){return this.contentModel.filters},get plainDefaultValue(){const t=e.config.default_value;return Array.isArray(t)?[...t]:t},get usingDefaultValue(){return e.type!==de.TreeSelect},get usingDefaultValueFunc(){return!!e.default_value_func},get formattedDefaultValue(){return this.filters.formattedDefaultValues[e.key]},get auto_submit_supported(){return[de.Select,de.Checkbox,de.DateRange].includes(e.type)}})).views(e=>({get json(){const{id:t,key:n,label:r,order:i,visibleInViewsIDs:o,default_value_func:l,auto_submit:c,type:u,config:d}=e;return{id:t,key:n,type:u,label:r,order:i,config:d.json,auto_submit:c,visibleInViewsIDs:U.toJS(o),default_value_func:l}},get visibleInViewsIDSet(){return new Set(e.visibleInViewsIDs)},get should_auto_submit(){return e.auto_submit_supported&&e.auto_submit},requiredAndPass(t){return y.get(e.config,"required",!1)?y.get(e.config,"truthy",()=>!0)(t):!1}})).actions(e=>({setKey(t){e.key=t},setLabel(t){e.label=t},setOrder(t){e.order=t},setType(t){switch(t){case de.Select:e.config=Sl();break;case de.MultiSelect:e.config=Cl();break;case de.TreeSelect:e.config=_l();break;case de.TextInput:e.config=Or();break;case de.Checkbox:e.config=jl();break;case de.DateRange:e.config=wl();break}e.type=t},setVisibleInViewsIDs(t){e.visibleInViewsIDs.length=0,e.visibleInViewsIDs.push(...t)},setAutoSubmit(t){e.auto_submit=e.auto_submit_supported&&t},setDefaultValueFunc(t){e.default_value_func=t}}));var L=(e=>(e.Division="div",e.Modal="modal",e.Tabs="tabs",e))(L||{});const qr=f.types.model("ViewDivisionConfig",{_name:f.types.literal(L.Division)}).views(e=>({get json(){const{_name:t}=e;return{_name:t}}})),kl=()=>qr.create({_name:L.Division}),E1=f.types.model("CustomModalTitleModel",{enabled:f.types.optional(f.types.boolean,!1),func_content:f.types.optional(f.types.string,"")}).views(e=>({get json(){const{enabled:t,func_content:n}=e;return{enabled:t,func_content:n}},get value(){const{enabled:t,func_content:n}=e,r=f.getParent(e,2),i=f.getRoot(e);if(!t)return r.name;try{const o={filters:i.content.filters.values,context:i.context.current};return new Function(`return ${n}`)()(o)}catch(o){return console.error(o),r.name}}})).actions(e=>({setEnabled(t){e.enabled=t},setFuncContent(t){e.func_content=t},replace({enabled:t,func_content:n}){e.enabled=t,e.func_content=n}})),Zn={enabled:!1,func_content:["function text({ filters, context}) {"," // your code goes here",' return "text"',"}"].join(`
|
|
450
|
-
`)},Nr=f.types.model("ViewModalConfig",{_name:f.types.literal(L.Modal),width:f.types.string,height:f.types.string,custom_modal_title:f.types.optional(E1,Zn)}).views(e=>({get json(){const{_name:t,width:n,height:r,custom_modal_title:i}=e;return{_name:t,width:n,height:r,custom_modal_title:i.json}}})).actions(e=>({setWidth(t){e.width=t},setHeight(t){e.height=t}})),Tl=()=>Nr.create({_name:L.Modal,width:"90vw",height:"90vh"}),P1=f.types.model("ViewTabsTabModel",{id:f.types.identifier,name:f.types.string,view_id:f.types.string,color:f.types.optional(f.types.string,""),order:f.types.optional(f.types.number,0)}).views(e=>({get json(){const{id:t,name:n,view_id:r,color:i,order:o}=e;return{id:t,name:n,color:i,order:o,view_id:r}}})).actions(e=>({setName(t){e.name=t},setViewID(t){e.view_id=t},setColor(t){e.color=t},setOrder(t){e.order=t}})),Fr=f.types.model("ViewTabsConfig",{_name:f.types.literal(L.Modal),tabs:f.types.optional(f.types.array(P1),[]),variant:f.types.optional(f.types.enumeration("variant",["default","outline","pills"]),"default"),orientation:f.types.optional(f.types.enumeration("orientation",["horizontal","vertical"]),"horizontal"),grow:f.types.optional(f.types.boolean,!1)}).views(e=>({get json(){const{_name:t,variant:n,orientation:r,tabs:i,grow:o}=e;return{grow:o,tabs:i.map(l=>l.json),_name:t,variant:n,orientation:r}},get tabsInOrder(){return y.sortBy(e.tabs,"order")}})).actions(e=>({setVariant(t){e.variant=t},setOrientation(t){e.orientation=t},setGrow(t){e.grow=t},setTabs(t){e.tabs.length=0,e.tabs=f.cast(t)},addTab(){const t=re.randomId(),n={id:t,name:t,view_id:""};e.tabs.push(n)},removeTab(t){e.tabs.splice(t,1)}})),Dl=()=>Fr.create({_name:L.Modal,tabs:[]}),Il=f.types.model({id:f.types.identifier,name:f.types.string,type:f.types.enumeration("EViewComponentType",[L.Division,L.Modal,L.Tabs]),config:f.types.union(qr,Nr,Fr),panelIDs:f.types.optional(f.types.array(f.types.string),[])}).views(e=>({get json(){const{id:t,name:n,type:r,config:i}=e;return{id:t,name:n,type:r,config:i.json,panelIDs:e.panelIDs.map(o=>o)}}})).actions(e=>({setName(t){e.name=t},setType(t){if(e.type!==t){switch(t){case L.Division:e.config=kl();break;case L.Modal:e.config=Tl();break;case L.Tabs:e.config=Dl();break}e.type=t}},appendPanelID(t){e.panelIDs.push(t)},appendPanelIDs(t){e.panelIDs.push(...t)},removePanelID(t){const n=e.panelIDs.filter(r=>r!==t);e.panelIDs.length=0,e.panelIDs.push(...n)}})),at="11.10.0",L1={definition:{sqlSnippets:[],queries:[],mock_context:{}},views:[{id:"Main",name:"Main",type:L.Division,config:{},panelIDs:[]}],panels:[],filters:[],version:at,layouts:[{id:"basis",name:"basis",list:[],breakpoint:0}]},Gr=f.types.model("DataSourceMetaModel",{id:f.types.string,type:f.types.enumeration("DataSourceType",[oe.HTTP,oe.MySQL,oe.Postgresql]),key:f.types.string,config:f.types.frozen()}),Ml=f.types.model("DataSourcesMetaModel",{list:f.types.optional(f.types.array(Gr),[])}).views(e=>({find({type:t,key:n}){return e.list.find(r=>r.key===n&&r.type===t)},get options(){return e.list.map(t=>({value:t.key,label:t.key}))}})).actions(e=>({replace(t){e.list.length=0,e.list.push(...t)}})),zl=f.types.model({id:f.types.string,content:f.types.string,create_time:f.types.string,update_time:f.types.string,is_preset:f.types.boolean}),Wr=f.types.model("GlobalSQLSnippetsMeta",{list:f.types.optional(f.types.array(zl),[])}).views(e=>({find(t){return e.list.find(n=>n.id===t)},get options(){return e.list.map(t=>({value:t.id,label:t.id}))}})).actions(e=>({replace(t){e.list.length=0,e.list.push(...t)}})),Hn=f.types.model("ContextMeta",{current:f.types.optional(f.types.frozen(),{})}).views(e=>({get keys(){return Object.keys(e.current)},get entries(){return Object.entries(e.current)}})).actions(e=>({replace(t){e.current=t},get(t){return e.current[t]},set(t,n){e.current[t]=n}}));function Rr(e){return Hn.create({current:e})}const Qr=f.types.compose("ViewRenderModel",Il,f.types.model({tab:f.types.optional(f.types.string,"")})).views(e=>({get defaultTab(){if(e.type!==L.Tabs)return"";const t=e.config;return t.tabs.length>0?t.tabs[0].id:""},get tabViewID(){var n;return e.type!==L.Tabs?"":((n=e.config.tabs.find(r=>r.id===e.tab))==null?void 0:n.view_id)??""},get contentModel(){return f.getParent(e,3)},get panels(){if(e.type!==L.Tabs)return this.contentModel.panels.panelsByIDs(e.panelIDs);const t=this.tabViewID,n=this.contentModel.views.findByID(t);return(n==null?void 0:n.panels)??[]},get renderViewIDs(){const t=[e.id];return e.type===L.Tabs&&t.push(this.tabViewID),t},async downloadScreenshot(t){const n=t.offsetWidth*2+10,r=t.offsetHeight*2+10,i=new Ki,o=new Date().getTime(),l=await Ui.toBlob(t,{bgcolor:"white",width:n,height:r,style:{transformOrigin:"0 0",transform:"scale(2)"}});i.file(`${e.name}_${o}.png`,l),i.file(`dashboard_state_${o}.json`,JSON.stringify(this.contentModel.dashboardState,null,4)),i.generateAsync({type:"blob"}).then(c=>{gn.saveAs(c,`${e.name}_${o}.zip`)}).catch(c=>{console.error(c),ut.notifications.show({color:"red",title:"Failed to download screenshot with dashboard state",message:c.message})})}})).actions(e=>({setTab(t){e.tab=t??""},afterCreate(){f.addDisposer(e,U.reaction(()=>e.defaultTab,t=>this.setTab(t),{fireImmediately:!0,delay:0}))}})),Ur=f.types.model("ViewsRenderModel",{current:f.types.optional(f.types.array(Qr),[]),visibleViewIDs:f.types.array(f.types.string)}).views(e=>({get json(){return e.current.map(t=>At(t.json))},get idMap(){const t=new Map;return e.current.forEach(n=>{t.set(n.id,n)}),t},findByID(t){return e.current.find(n=>n.id===t)},get firstVisibleView(){const[t]=e.visibleViewIDs;return e.current.find(({id:n})=>n===t)},get visibleViews(){const t=new Set(e.visibleViewIDs);return e.current.filter(({id:n})=>t.has(n))}})).actions(e=>({appendToVisibles(t){new Set(e.visibleViewIDs.map(r=>r)).has(t)||e.visibleViewIDs.push(t)},rmVisibleViewID(t){const n=e.visibleViewIDs.findIndex(r=>r===t);n!==-1&&e.visibleViewIDs.splice(n,1)}}));function Al(e){const t=e.length>0?[e[0].id]:[];return{current:e.map(r=>{const{_name:i=r.type}=r.config;return{...r,config:{...r.config,_name:i},panelIDs:r.panelIDs}}),visibleViewIDs:t}}const B1=new gu.AsyncParser({withBOM:!0});async function El(e){return!Array.isArray(e)||e.length===0?"":await B1.parse(e).promise()}async function O1(e,t){const n=await El(t),r=new Blob([n],{type:"text/csv"});gn.saveAs(r,`${e}.csv`)}function Pl(e){const t=new Ki,n=e.map(async({id:r,data:i})=>{const o=await El(i);t.file(`${r}.csv`,o)});Promise.all(n).then(()=>{t.generateAsync({type:"blob"}).then(r=>{gn.saveAs(r,"dashboard_data.zip")})}).catch(r=>{console.error(r),ut.notifications.show({color:"red",title:"Failed to download data",message:r.message})})}function Nt(e,t){const n=new Blob([t],{type:"application/json"});gn.saveAs(n,`${e}.json`)}const Kr=fl.views(e=>({get contentModel(){return f.getRoot(e).content}})).views(e=>({get queries(){return e.contentModel.queries.findByIDSet(e.queryIDSet)},queryByID(t){return this.queries.find(n=>n.id===t)},get data(){return this.queries.reduce((t,n)=>(t[n.id]=n.data,t),{})},get variableStrings(){return na(e.variables,this.data)},get dataLoading(){return this.queries.some(t=>t.state==="loading")},get queryStateMessages(){const t=this.queries.filter(o=>!o.runByConditionsMet);if(t.length===0)return"";const n=new Set,r=new Set;t.forEach(o=>{const l=o.conditionNames;l.context.forEach(c=>n.add(c)),l.filters.forEach(c=>r.add(c))});const i=[];return n.size>0&&(console.log(n),i.push(`context: ${Array.from(n).join(", ")}`)),r.size>0&&i.push(`filter${r.size>1?"s":""}: ${Array.from(r).join(", ")}`),i.length===2&&i.splice(1,0,"and"),i.unshift("Waiting for"),i.join(" ")},get queryErrors(){return this.queries.map(t=>t.error).filter(t=>!!t)},get canRenderViz(){return this.queryErrors.length===0&&this.queryStateMessages===""&&!this.dataLoading}})).actions(e=>({refreshData(){e.queries.forEach(t=>t.fetchData(!0))},downloadData(){e.contentModel.queries.downloadDataByQueryIDs(e.queryIDs)},getSchema(){const t=e.json;return t.viz.conf={...t.viz.conf,__INTERACTIONS:{},__OPERATIONS:{},__TRIGGERS:{}},{panel:t,queries:e.queries.map(n=>n.json),layouts:e.contentModel.layouts.jsonByPanelIDSet(new Set([e.id]))}},downloadSchema(){const{panel:t,queries:n,layouts:r}=this.getSchema(),o=JSON.stringify({panels:[t],definition:{queries:n},layouts:r,version:at},null,2),l=e.name;Nt(l,o)}}));function Ll(e){return{id:e,name:e,title:{show:!0},description:"<p></p>",queryIDs:[],viz:{type:gr.name,conf:gr.createConfig()},style:{border:{enabled:!0}}}}const Yr=f.types.model("PanelsRenderModel",{list:f.types.optional(f.types.array(Kr),[])}).views(e=>({get json(){return e.list.map(t=>t.json)},findByID(t){return e.list.find(n=>n.id===t)},get idMap(){const t=new Map;return e.list.forEach(n=>{t.set(n.id,n)}),t}})).views(e=>({panelsByIDs(t){const n=[];return t.forEach(r=>{const i=e.idMap.get(r);i?n.push(i):console.warn(`Panel is not found, id:${r}`)}),n}}));function Bl(e){const t=e.config,n=t.default_value;if(n===void 0)return n;if(t._name==="date-range")try{if(t.default_shortcut){const i=al(t.default_shortcut);if(i)return i.map(o=>M(o).format(t.inputFormat))}const[...r]=n;return r.map(i=>i===null?i:M.tz(i,"UTC").format(t.inputFormat)??i)}catch(r){return console.error(r),n}return n}function $1(e,t){const n=e.default_value_func;try{return new Function(`return ${n}`)()(e,nt,t)}catch(r){return console.error(r),Bl(e)}}function Ol(e,t){var n;return(n=e.default_value_func)!=null&&n.trim()?$1(e,t):Bl(e)}function $l(e,t){return e.reduce((n,r)=>(n[r.key]=Ol(r,t),n),{})}const Xr=f.types.model("FiltersRenderModel",{current:f.types.optional(f.types.array(Vr),[]),values:f.types.optional(f.types.frozen(),{})}).views(e=>({get json(){return e.current.map(t=>t.json)},get contentModel(){return f.getRoot(e).content},get context(){return this.contentModel.payloadForSQL.context},get initialValuesDep(){return JSON.stringify({filters:e.current.map(({default_value_func:t,config:n})=>({default_value_func:t,config:n})),context:this.contentModel.payloadForSQL.context})},get formattedDefaultValues(){return $l(this.json,this.contentModel.context)},get firstID(){if(e.current.length!==0)return e.current[0].id},findByID(t){return e.current.find(n=>n.id===t)},findByIDSet(t){return e.current.filter(n=>t.has(n.id))},get inOrder(){return y.sortBy(e.current,"order")},get empty(){return e.current.length===0},visibleInView(t){return y.sortBy(e.current.filter(n=>n.visibleInViewsIDSet.has(t)),"order")},get firstFilterValueKey(){return Object.keys(e.values)[0]??""},get keySet(){return new Set(e.current.map(t=>t.key))},get keyLabelMap(){return e.current.reduce((t,n)=>(t[n.key]=n.label,t),{})},getSelectOption(t){const n=this.findByID(t);if(!n||!("getSelectOption"in n.config))return null;const r=e.values[n.key];return n.config.getSelectOption(r)}})).actions(e=>({setValues(t){e.values=t},patchValues(t){e.values=y.defaults({},t,e.values)},setValueByKey(t,n){e.values={...e.values,[t]:n}},getValueByKey(t){return e.values[t]},getSchema(t,n){return{filters:e.findByIDSet(new Set(t)).map(o=>({...o.json,visibleInViewsIDs:n?o.json.visibleInViewsIDs:[]})),version:at}},downloadSchema(t){const n=JSON.stringify(this.getSchema(t,!1),null,2);Nt("Filters",n)}}));function Jr(e,t,n,r){const i=y.defaults({},r,$l(e,{...n,...t}));return{current:e,values:i}}const Vl=gl.views(e=>({get rootModel(){return f.getRoot(e)},get contentModel(){return this.rootModel.content},get conditionOptions(){if(!f.isAlive(e))return[];const{context:t}=this.contentModel.payloadForSQL,n=Object.keys(t).map(l=>({group:"Context",label:l,value:`context.${l}`,description:void 0})),r=this.contentModel.filters.keyLabelOptions.map(l=>({group:"Filters",label:l.label,value:`filters.${l.value}`,description:l.value})),i=[...n,...r],o=new Set(i.map(l=>l.value));return e.run_by.forEach(l=>{o.has(l)||i.push({group:"Invalid",label:l,value:l})}),i},get unmetRunByConditions(){if(!f.isAlive(e))return[];const{run_by:t}=e;if(t.length===0)return[];const n=this.contentModel.payloadForSQL;return t.filter(r=>{const i=y.get(n,r);return Array.isArray(i)?i.length===0:typeof i=="number"?Number.isNaN(i):!i})}})).views(e=>({get payload(){return e.contentModel.payloadForSQL},get formattedSQL(){return xs(e.sql,this.payload)},get httpConfigString(){const{context:t,filters:n}=this.payload,{name:r,pre_process:i}=e.json,o=_d(i,t,n);return console.groupCollapsed(`Request config for: ${r}`),console.log(o),console.groupEnd(),JSON.stringify(o)},get typedAsSQL(){return[oe.Postgresql,oe.MySQL].includes(e.type)},get typedAsHTTP(){return[oe.HTTP].includes(e.type)},get isTransform(){return e.type===oe.Transform},get reQueryKey(){const{react_to:t=[]}=e;if(t.length===0)return"";const n=e.contentModel.payloadForSQL,r=[...t].reduce((i,o)=>(i[o]=y.get(n,o),i),{});return JSON.stringify(r)},get runByConditionsMet(){return e.unmetRunByConditions.length===0},get conditionNames(){if(e.unmetRunByConditions.length===0)return{context:[],filters:[]};const{keyLabelMap:t}=e.contentModel.filters,n=e.unmetRunByConditions.filter(i=>i.startsWith("context.")).map(i=>i.replace("context.","")),r=e.unmetRunByConditions.filter(i=>i.startsWith("filters.")).map(i=>y.get({filters:t},i,i.replace("filters.",""))).filter(i=>!!i);return{context:n,filters:r}},get queries(){return f.getParent(e,2)},get inUse(){return this.queries.isQueryInUse(e.id)},get dependencies(){if(!this.typedAsSQL)return[];const t=y.uniq(e.sql.match(jn.sqlSnippet)),n=y.uniq(e.sql.match(jn.filter)),r=y.uniq(e.sql.match(jn.context)),i=[];return t.forEach(o=>{i.push({type:"SQL Snippet",key:o,valid:e.contentModel.sqlSnippets.keySet.has(o)})}),n.forEach(o=>{i.push({type:"Filter",key:o,valid:e.contentModel.filters.keySet.has(o)})}),r.forEach(o=>{i.push({type:"Context",key:o,valid:e.contentModel.mock_context.keySet.has(o)})}),i}})),Zr=f.types.compose("QueryRenderModel",Vl,f.types.model({state:f.types.optional(f.types.enumeration(["idle","loading","error"]),"idle"),data:f.types.optional(f.types.frozen([]),[]),error:f.types.frozen()})).views(e=>({get datasource(){const{key:t,type:n}=e;return e.rootModel.datasources.find({type:n,key:t})},get additionalQueryInfo(){return e.contentModel.getAdditionalQueryInfo(e.id)},get depQueryModels(){return e.contentModel.queries.findByIDSet(new Set(e.dep_query_ids))},get depQueryModelStates(){return this.depQueryModels.map(t=>t.state)},get depQueryModelStatesString(){return this.depQueryModelStates.toString()}})).views(e=>({get stateMessage(){if(e.state!=="idle")return"";if(!e.runByConditionsMet){const{context:t,filters:n}=e.conditionNames;if(t.length===0&&n.length===0)return"Waiting";const r=[];return t.length>0&&r.push(`context: ${t.join(", ")}`),n.length>0&&r.push(`filter${n.length>1?"s":""}: ${n.join(", ")}`),r.length===2&&r.splice(1,0,"and"),r.unshift("Waiting for"),r.join(" ")}return e.data.length>0?"":"Empty Data"}})).volatile(()=>({controller:new AbortController})).actions(e=>({runSQL:f.flow(function*(){var t;if(e.valid&&((t=e.controller)==null||t.abort(),!!e.runByConditionsMet)){e.controller=new AbortController,e.state="loading";try{const n=e.payload;e.data=yield*f.toGenerator(Md({payload:n,name:e.name,query:e.json,additionals:e.additionalQueryInfo},e.controller.signal)),e.state="idle",e.error=null}catch(n){if(!He.isCancel(n)){e.data=[];const r=y.get(n,"message","unkown error");e.error=y.get(n,"response.data.detail.message",r),e.state="error"}}}}),runHTTP:f.flow(function*(){var t;if(!(!e.valid||!e.datasource)&&((t=e.controller)==null||t.abort(),!!e.runByConditionsMet)){e.controller=new AbortController,e.state="loading";try{const{type:n,key:r,post_process:i}=e.json;let o=JSON.parse(e.httpConfigString);o=kd(e.datasource,o);const l=yield*f.toGenerator(zd({type:n,key:r,configString:JSON.stringify(o),name:e.name,additionals:e.additionalQueryInfo},e.controller.signal)),c=Td(e.datasource,l),u=Dd(i,c,e.contentModel.dashboardState);e.data=u,e.state="idle",e.error=null}catch(n){if(console.error(n),!He.isCancel(n)){e.data=[];const r=y.get(n,"message","unkown error");e.error=y.get(n,"response.data.detail.message",r),e.state="error"}}}}),runTransformation(){e.state="loading";try{const n=e.contentModel.queries.findByIDSet(new Set(e.dep_query_ids)).map(l=>({id:l.id,name:l.name,data:l.data})),r=e.contentModel.dashboardState,i=e.pre_process,o=new Function(`return ${i}`)()(n,r,nt);e.data=o,e.state="idle",e.error=null}catch(t){e.data=[],e.error=t.message,e.state="error"}}})).actions(e=>({fetchData:t=>{if(!e.inUse&&!t){console.debug(`🟡 Skipping query[${e.name}]`);return}return console.debug(`🔵 Running query[${e.name}]`),e.isTransform?e.runTransformation():e.typedAsHTTP?e.runHTTP():e.runSQL()},beforeDestroy(){var t;(t=e.controller)==null||t.abort()}})).actions(e=>({afterCreate(){f.addDisposer(e,U.reaction(()=>{var n;return e.isTransform?[e.inUse,e.id,e.key,e.dep_query_ids.toString(),e.pre_process,e.depQueryModelStatesString].join("--"):e.typedAsHTTP?`${e.inUse}--${e.id}--${e.key}--${e.reQueryKey}--${(n=e.datasource)==null?void 0:n.id}`:[e.inUse,e.id,e.key,e.formattedSQL,e.pre_process,e.post_process].join("--")},()=>e.fetchData(!1),{fireImmediately:!0,delay:0}))}})),Hr=f.types.model("QueriesRenderModel",{current:f.types.optional(f.types.array(Zr),[])}).views(e=>({get idSet(){return new Set(e.current.map(t=>t.id))},get firstID(){if(e.current.length!==0)return e.current[0].id},findByID(t){return e.current.find(n=>n.id===t)},findByIDSet(t){return e.current.filter(n=>t.has(n.id))},get json(){return e.current.filter(t=>t.id&&t.key).map(t=>t.json)},get contentModel(){return f.getParent(e,1)},get visibleQueryIDSet(){const{views:t,filters:n,queries:r}=this.contentModel,i=[];t.visibleViews.forEach(c=>{c.panels.forEach(u=>{i.push(...u.queryIDs)})});const o=y.uniq(t.visibleViews.map(c=>c.renderViewIDs).flat());n.current.forEach(c=>{const u=y.get(c,"config.options_query_id");if(!u)return;o.some(h=>c.visibleInViewsIDSet.has(h))&&i.push(u)}),r.findByIDSet(new Set(i)).forEach(c=>{!c.isTransform||c.dep_query_ids.length===0||i.push(...c.dep_query_ids)});const l=new Set(i);return console.debug("QueryIDs:",l),l},isQueryInUse(t){return this.visibleQueryIDSet.has(t)}})).actions(e=>({downloadAllData(){const t=e.current.map(({name:n,data:r})=>({id:n,data:r}));Pl(t)},downloadDataByQueryIDs(t){const n=new Set(t),r=e.current.filter(i=>n.has(i.id)).map(({name:i,data:o})=>({id:i,data:o}));Pl(r)},downloadDataByQueryID(t){const n=e.findByID(t);if(!n){console.log("[downloadDataByQueryID] query not found");return}const{name:r,data:i}=n;O1(r,i)},refetchDataByQueryID(t){const n=e.findByID(t);if(!n){console.error(new Error(`[downloadDataByQueryID] query by ID[${t}] not found`));return}return n.fetchData(!0)},getSchema(t){return{definition:{queries:e.findByIDSet(new Set(t)).map(i=>i.json)},version:at}},downloadSchema(t){const n=JSON.stringify(this.getSchema(t),null,2);Nt("Queries",n)}}));function ql(e){return{current:e}}function Nl({min:e,max:t}){const n=`${e}px`,r=Number.isFinite(t)?`${t}px`:"∞";return`[${n}, ${r})`}const ei=f.types.model("LayoutsRenderModel",{list:f.types.array(yl),currentBreakpoint:f.types.string}).views(e=>({get json(){return e.list.map(t=>t.json)},jsonByPanelIDSet(t){return e.list.map(n=>n.jsonByPanelIDSet(t))},get root(){return f.getRoot(e)},get contentModel(){return this.root.content},get basisLayoutSet(){return e.list.find(t=>t.id==="basis")},get currentLayoutSet(){return e.list.find(t=>t.id===e.currentBreakpoint)},get currentLayoutRange(){return this.breakpointRanges.find(t=>t.id===e.currentBreakpoint)},get currentRangeText(){const t=this.currentLayoutRange;return Nl(t)},get cols(){const t={};return e.list.forEach(n=>{t[n.id]=36}),t},get breakpoints(){const t={};return e.list.forEach(n=>{t[n.id]=n.breakpoint}),t},get breakpointNameRecord(){const t={};return e.list.forEach(n=>{t[n.name]=n.breakpoint}),t},get breakpointRanges(){const t=e.list.map(n=>({id:n.id,name:n.name,min:n.breakpoint,max:1/0,text:""}));return t.sort((n,r)=>n.min-r.min).forEach((n,r)=>{r!==t.length-1&&(n.max=t[r+1].min)}),t.forEach(n=>{n.text=Nl(n)}),t},get breakpointsInfo(){return e.list.map(t=>({id:t.id,name:t.name,breakpoint:t.breakpoint})).sort((t,n)=>t.breakpoint-n.breakpoint)},get currentBreakpointRange(){return this.breakpointRanges.find(t=>t.id===e.currentBreakpoint)},get currentLayoutPreviewWidth(){const t=this.currentBreakpointRange;if(t)return t.max===1/0?t.min===0?void 0:t.min+1:t.max},items(t){const n=new Set(t);return this.currentLayoutSet.list.filter(i=>n.has(i.panelID))},gridLayouts(t){const n=new Set(t),r={};return e.list.forEach(i=>{r[i.id]=i.list.filter(o=>n.has(o.panelID)).map(o=>o.layoutProperies)}),r},findItemByPanelID(t){return this.currentLayoutSet.findByPanelID(t)}})).actions(e=>({setCurrentBreakpoint(t){console.log("🔴 onBreakpointChange:",t),e.currentBreakpoint=t},afterCreate(){f.addDisposer(e,U.reaction(()=>e.currentBreakpoint,()=>{setTimeout(()=>{window.dispatchEvent(new Event("resize"))},32)},{fireImmediately:!1,delay:0}))}})),Fl=bl.views(e=>({isADuplicatedKey(t){return!t||t===e.key?!1:!!f.getParent(e,2).findByKey(t)}})),ti=f.types.model("SQLSnippetsRenderModel",{current:f.types.optional(f.types.array(Fl),[])}).views(e=>({get json(){return e.current.map(t=>t.json)},get record(){return e.current.reduce((t,n)=>(t[n.key]=n.value,t),{})},get keySet(){return new Set(e.current.map(t=>t.key))},get firstKey(){if(e.current.length!==0)return e.current[0].key},findByKey(t){return e.current.find(n=>n.key===t)},findByKeySet(t){return e.current.filter(n=>t.has(n.key))}})).actions(e=>({getSchema(t){return{definition:{sqlSnippets:e.findByKeySet(new Set(t)).map(i=>i.json)},version:at}},downloadSchema(t){const n=JSON.stringify(this.getSchema(t),null,2);Nt("SQL Snippets",n)}}));function Gl(e){return{current:e}}function ln(e,t,n,r){return e.reduce((i,o)=>{try{i[o[t]]=hs(o[n],r)}catch(l){i[o[t]]=l.message}return i},{})}class Wl{constructor(t){P(this,"origin");P(this,"copy");this.origin=t,this.copy=f.clone(t),U.makeAutoObservable(this,{},{autoBind:!0,deep:!1})}get changed(){return!y.isEqual(f.getSnapshot(this.origin),f.getSnapshot(this.copy))}commit(){f.applySnapshot(this.origin,f.getSnapshot(this.copy))}reset(){f.applySnapshot(this.copy,f.getSnapshot(this.origin))}update(t){f.applySnapshot(this.copy,t)}}const Rl=e=>new Wl(e),V1=S.observer(({view:e})=>{const t=X(),n=W(),r=ze.useModals(),{panel:i,downloadPanelScreenshot:o}=Ee(),{id:l}=i,{viewPanelInFullScreen:c,inFullScreen:u}=g.useContext(Jn),d=()=>{n.duplicatePanelByID(l,e.id)},h=()=>{t.editor.open(["_VIEWS_",e.id,"_PANELS_",l])},p=()=>r.openConfirmModal({title:"Delete this panel?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>n.removePanelByID(l,e.id),confirmProps:{color:"red"},zIndex:320}),x=g.useCallback(()=>{c(l)},[l,c]),m=!u&&e.type!==L.Modal;return s.jsx(s.Fragment,{children:s.jsx(a.Box,{sx:{position:"absolute",top:0,left:0,right:0,zIndex:300},children:s.jsxs(a.Menu,{withinPortal:!0,children:[s.jsx(a.Menu.Target,{children:s.jsx(a.Box,{className:"panel-dropdown-target",sx:{width:"100%"}})}),s.jsxs(a.Menu.Dropdown,{children:[s.jsx(a.Menu.Item,{onClick:i.refreshData,icon:s.jsx(k.Refresh,{size:14}),children:"Refresh"}),s.jsx(a.Menu.Item,{onClick:i.downloadData,icon:s.jsx(k.Download,{size:14}),children:"Download Data"}),s.jsx(a.Menu.Item,{onClick:i.downloadSchema,icon:s.jsx(_.IconCode,{size:14}),children:"Download Schema"}),s.jsx(a.Menu.Item,{onClick:o,icon:s.jsx(_.IconCamera,{size:14}),children:"Screenshot"}),m&&s.jsx(a.Menu.Item,{onClick:x,icon:s.jsx(k.ArrowsMaximize,{size:14}),disabled:!0,children:"Full Screen"}),s.jsx(a.Divider,{label:"Edit",labelPosition:"center"}),s.jsx(a.Menu.Item,{onClick:h,icon:s.jsx(k.Settings,{size:14}),children:"Settings"}),s.jsx(a.Menu.Item,{onClick:d,icon:s.jsx(k.Copy,{size:14}),children:"Duplicate"}),s.jsx(a.Menu.Item,{color:"red",onClick:p,icon:s.jsx(k.Trash,{size:14}),children:"Delete"})]})]})})})});function q1(e){return e?["<p><br></p>","<p></p>"].includes(e):!0}const ni=S.observer(()=>{const[e,t]=g.useState(!1),{panel:n}=xt();return q1(n.description)?null:s.jsxs(s.Fragment,{children:[s.jsx(a.Modal,{opened:e,onClose:()=>t(!1),title:n.title.show?n.name:"",withCloseButton:!1,withinPortal:!0,zIndex:310,children:s.jsx(Nn,{value:n.description,styles:{root:{border:"none"},content:{padding:0}},sx:{".mantine-RichTextEditor-content .ProseMirror":{padding:"0 !important"}}})}),s.jsx(a.Tooltip,{label:"Click to see description",position:"top-start",withinPortal:!0,children:s.jsx(a.ActionIcon,{variant:"subtle",color:"blue",onClick:()=>t(r=>!r),sx:{verticalAlign:"baseline",cursor:"pointer"},children:s.jsx(k.InfoCircle,{size:20})})})]})}),GI="",N1=S.observer(function(){const{panel:t}=xt(),{name:n,title:r}=t;return r.show?s.jsx(a.Group,{grow:!0,position:"center",className:"panel-title-wrapper",sx:{flexGrow:1},children:s.jsx(a.Text,{align:"center",lineClamp:1,className:"panel-title-text",children:n})}):null});function F1(e){const t=g.useRef(null);return{ref:t,downloadPanelScreenshot:()=>{const r=t.current;if(!r)return;const i=r.offsetWidth*2,o=r.offsetHeight*2;Ui.toBlob(t.current,{bgcolor:"white",width:i,height:o,style:{border:"none",borderRadius:0,transformOrigin:"0 0",transform:"scale(2)"}}).then(l=>{window.saveAs(l,`${e.name?e.name:e.viz.type}.png`)})}}}var Ql=(e=>(e.migrated="migrated",e.nothingToMigrate="nothingToMigrate",e.checkFailed="checkFailed",e.migrationFailed="migrationFailed",e))(Ql||{}),es=(e=>(e.notStarted="notStarted",e.inProgress="inProgress",e.done="done",e))(es||{});class G1{constructor(t){P(this,"vizInstance");P(this,"operationManager");P(this,"triggerManager");P(this,"vizManager");P(this,"runningMigration");P(this,"panelModel");P(this,"status","notStarted");this.panelModel=t.getRequired(ue.instanceScope.panelModel),this.vizInstance=t.getRequired(ue.instanceScope.vizInstance),this.operationManager=t.getRequired(ue.instanceScope.operationManager),this.triggerManager=t.getRequired(ue.instanceScope.triggerManager),this.vizManager=t.getRequired(ue.vizManager)}async createMigrationTask(){const t=[];try{await this.instanceNeedMigration()&&t.push(()=>this.runInstanceMigration()),await this.interactionNeedMigration()&&t.push(()=>this.runInteractionMigration())}catch(n){return console.warn("check migration failed",n),"checkFailed"}if(t.length===0)return"nothingToMigrate";try{return await Promise.all(t.map(n=>n())),"migrated"}catch(n){return console.warn("migration failed",n),"migrationFailed"}}async runMigration(){return this.runningMigration||(this.status="inProgress",this.runningMigration=this.createMigrationTask().then(t=>(this.status="done",t))),this.runningMigration}async runInteractionMigration(){await this.operationManager.runMigration(),await this.triggerManager.runMigration()}async runInstanceMigration(){const t=this.vizManager.resolveComponent(this.vizInstance.type),n={configData:this.vizInstance.instanceData,panelModel:this.panelModel};await t.migrator.migrate(n)}async instanceNeedMigration(){const t=this.vizManager.resolveComponent(this.vizInstance.type),n={configData:this.vizInstance.instanceData};return t.migrator.needMigration(n)}async interactionNeedMigration(){return await this.operationManager.needMigration()||await this.triggerManager.needMigration()}}function Ul(e){const{panel:t}=xt();return g.useCallback(n=>{const r=n.getRequired(ue.vizManager),i=r.resolveComponent(e.viz.type);return n.createScoped().provideFactory(ue.instanceScope.vizInstance,()=>r.getOrCreateInstance(e)).provideFactory(ue.instanceScope.interactionManager,o=>{const l=o.getRequired(ue.instanceScope.vizInstance);return new zs(l,i,Sn)}).provideFactory(ue.instanceScope.operationManager,o=>o.getRequired(ue.instanceScope.interactionManager).operationManager).provideFactory(ue.instanceScope.triggerManager,o=>o.getRequired(ue.instanceScope.interactionManager).triggerManager).provideValue(ue.instanceScope.panelModel,t).provideFactory(ue.instanceScope.migrator,o=>new G1(o))},[e.viz.type,e.viz.conf])}function Kl(e){const[t,n]=g.useState(!1),r=il().getRequired(ue.instanceScope.migrator);return $.useAsyncEffect(async()=>{const i=r.status===es.notStarted;n(r.status===es.done),r.status===es.notStarted&&r.runMigration().then(o=>{o===Ql.migrated&&i&&(e==null||e())}).finally(()=>{n(!0)})},[r]),t}function Yl(e,t){const n=il().getRequired(ue.instanceScope.vizInstance);return g.useEffect(()=>(n.instanceData.setItem(null,t.viz.conf),n.instanceData.watchItem(null,r=>{e(r)})),[e,t.viz.type]),n}function W1({setVizConf:e,...t}){const{panel:n}=t,r=Yl(e,n),i=Kl(()=>{ut.showNotification({title:`${n.name} - Updated`,message:"Your plugin configuration has been migrated to the latest version"})});return $.useAsyncEffect(async()=>{await r.instanceData.setItem(null,n.viz.conf)},[r,n.viz.type]),i?s.jsx(Ld,{...t}):s.jsx(a.Text,{children:"Checking update..."})}function R1(e){const{panel:t,setVizConf:n}=e;Yl(n,t);const{inEditMode:r}=g.useContext(wn);return Kl(()=>{r&&ut.showNotification({title:`${t.name} - Updated`,message:"Your plugin configuration has been migrated to the latest version"})})?s.jsx(Pd,{...e}):s.jsx(a.Text,{children:"Checking update"})}const WI="";function Q1(e,t){const{vizManager:n}=g.useContext(Ze),{panel:{viz:r,title:i,id:o,name:l,description:c,queryIDs:u,variables:d}}=xt(),h={id:o,name:l,title:i,description:c,queryIDs:u,viz:r},p=Ul(h);try{return n.resolveComponent(r.type),s.jsx(Xn,{configure:p,children:s.jsx(R1,{setVizConf:r.setConf,panel:h,measure:t,data:e,variables:d,vizManager:n})})}catch(x){return console.info(y.get(x,"message")),null}}const Xl=S.observer(function({data:t}){const{ref:n,width:r,height:i}=re.useElementSize(),o=Q1(t,{w:r,h:i}),l=r>0&&i>0;return s.jsx("div",{className:"viz-root",ref:n,children:s.jsx(a.Box,{sx:{width:r,height:i,overflow:"hidden"},children:l&&s.jsx(je,{children:o})})})}),Jl=S.observer(({panel:e})=>s.jsxs(a.Stack,{children:[e.queryErrors.map((t,n)=>s.jsx(a.Text,{color:"red",size:"sm",align:"center",sx:{fontFamily:"monospace"},children:t},`${n}-${t}`)),s.jsx(a.Text,{color:"gray",align:"center",size:"sm",children:e.queryStateMessages})]})),si=S.observer(({panel:e})=>s.jsxs(a.Flex,{className:"panel-viz-section",direction:"column",sx:{position:"relative",width:"100%"},children:[s.jsx(a.LoadingOverlay,{visible:e.dataLoading,exitTransitionDuration:0}),!e.canRenderViz&&s.jsx(Jl,{panel:e}),e.canRenderViz&&s.jsx(Xl,{data:e.data})]})),U1={border:"1px solid #e9ecef"},Zl=S.observer(({panel:e,panelStyle:t,dropdownContent:n})=>{const{ref:r,downloadPanelScreenshot:i}=F1(e);return e.title.show,s.jsx(Ts,{value:{panel:e,data:e.data,loading:e.dataLoading,errors:e.queryErrors,downloadPanelScreenshot:i},children:s.jsxs(a.Box,{className:`panel-root ${e.title.show?"panel-root--show-title":""}`,ref:r,p:0,sx:{...U1,...t},children:[s.jsx(a.Box,{className:"panel-description-popover-wrapper",children:s.jsx(ni,{})}),n,s.jsx(N1,{}),s.jsx(si,{panel:e})]})})}),K1={border:"1px dashed transparent",transition:"border-color 300ms ease","&:hover":{borderColor:"#e9ecef"}};function Y1(e){return e.style.border.enabled?{}:K1}const Hl=S.observer(function({panel:t,view:n}){const r=Y1(t);return s.jsx(Zl,{panel:t,panelStyle:r,dropdownContent:s.jsx(V1,{view:n})})});function X1(e){return!["richText","button"].includes(e)}const J1=S.observer(({view:e})=>{const{panel:t,downloadPanelScreenshot:n}=xt(),{id:r}=t,{viewPanelInFullScreen:i,inFullScreen:o}=g.useContext(Jn),l=g.useCallback(()=>{i(r)},[r,i]),c=!o&&e.type!==L.Modal;return X1(t.viz.type)?s.jsx(a.Box,{sx:{position:"absolute",top:0,left:0,right:0,zIndex:300},children:s.jsxs(a.Menu,{withinPortal:!0,children:[s.jsx(a.Menu.Target,{children:s.jsx(a.Box,{className:"panel-dropdown-target"})}),s.jsxs(a.Menu.Dropdown,{children:[s.jsx(a.Menu.Item,{onClick:t.refreshData,icon:s.jsx(k.Refresh,{size:14}),children:"Refresh"}),s.jsx(a.Menu.Item,{onClick:t.downloadData,icon:s.jsx(k.Download,{size:14}),children:"Download Data"}),s.jsx(a.Menu.Item,{onClick:n,icon:s.jsx(_.IconCamera,{size:14}),children:"Screenshot"}),c&&s.jsx(a.Menu.Item,{onClick:l,icon:s.jsx(k.ArrowsMaximize,{size:14}),children:"Full Screen"})]})]})}):null});function Z1(e){return e.style.border.enabled?{}:{border:"1px dashed transparent"}}const ri=S.observer(({panel:e,view:t})=>{const n=Z1(e);return s.jsx(Zl,{panel:e,panelStyle:n,dropdownContent:s.jsx(J1,{view:t})})}),H1={modal:{display:"flex",flexDirection:"column",flexWrap:"nowrap"},body:{display:"flex",height:"calc(100vh - 88px)"}},ec=S.observer(function({view:t,panel:n,exitFullScreen:r}){return s.jsx(a.Modal,{opened:!0,fullScreen:!0,onClose:r,title:s.jsx(a.Button,{color:"blue",size:"xs",onClick:r,leftIcon:s.jsx(k.ArrowLeft,{size:20}),children:"Exit fullscreen"}),styles:H1,children:s.jsx(a.Group,{grow:!0,sx:{flexGrow:1,flexShrink:0},children:s.jsx(ri,{view:t,panel:n})})})});function tc(e,t,n){const{panels:r}=ce(),i=e.id==="Main",[o,l]=g.useState(()=>i&&r.findByID(t)?t:null),c=g.useCallback(p=>{l(p),i&&n(p)},[i,n]),u=g.useCallback(()=>{l(null),i&&n("")},[i,n]),d=o?r.findByID(o):null;return{viewPanelInFullScreen:c,exitFullScreen:u,inFullScreen:!!d,fullScreenPanel:d}}const RI="",e_=g.forwardRef(({h:e},t)=>s.jsx(a.ActionIcon,{ref:t,className:"react-grid-customDragHandle",sx:{userSelect:"none",cursor:"grab",position:"absolute",top:5,right:e>38?5:20,zIndex:400,"&:hover":{color:"#228be6"}},variant:"transparent",children:s.jsx(k.ArrowsMove,{size:16})})),t_=g.forwardRef(({handleAxis:e,...t},n)=>s.jsx(a.ActionIcon,{ref:n,className:"react-grid-customResizeHandle",sx:{userSelect:"none",cursor:"nwse-resize",position:"absolute",bottom:0,right:0,zIndex:400,"&:hover":{color:"#228be6"}},variant:"transparent",...t,children:s.jsx(k.ChevronDownRight,{size:16})})),n_=fn.WidthProvider(fn.Responsive),s_=S.observer(({view:e,className:t="layout"})=>{const r=W().layouts,i=r.items(e.panelIDs),o=r.gridLayouts(e.panelIDs),l=(d,h,p,x)=>{console.log("🔴 onResize",d),p.h<30&&(p.h=30,x.h=30),p.w<4&&(p.w=4,x.w=4)},c=(d,h,p)=>{console.log("🔴 onResizeStop",{layouts:d,oldItem:h,newItem:p}),r.updateCurrentLayoutItem(p)},u=(d,h,p)=>{console.log("🔴 onDragStop",{layouts:d,oldItem:h,newItem:p}),r.updateCurrentLayoutItem(p)};return s.jsx(n_,{className:`dashboard-layout ${t}`,rowHeight:1,margin:[0,0],isBounded:!0,isDraggable:!0,isResizable:!0,cols:r.cols,layouts:o,draggableHandle:".react-grid-customDragHandle",resizeHandle:s.jsx(t_,{}),onResize:l,breakpoints:r.breakpoints,onBreakpointChange:r.setCurrentBreakpoint,onResizeStop:c,onDragStop:u,width:r.currentLayoutPreviewWidth,children:i.map(d=>s.jsxs("div",{"data-grid":d.layoutProperies,className:"panel-grid-item",children:[s.jsx(e_,{h:d.h}),s.jsx(Hl,{view:e,panel:d.panel})]},d.id))})}),r_=fn.WidthProvider(fn.Responsive),i_=S.observer(({view:e,className:t="layout"})=>{const n=ce(),r=n.layouts.items(e.panelIDs),i=n.layouts.gridLayouts(e.panelIDs);return s.jsx(r_,{className:`dashboard-layout ${t}`,rowHeight:1,margin:[0,0],isDraggable:!1,isResizable:!1,cols:n.layouts.cols,layouts:i,breakpoints:n.layouts.breakpoints,onBreakpointChange:n.layouts.setCurrentBreakpoint,children:r.map(o=>s.jsx("div",{"data-grid":o.layoutProperies,className:"panel-grid-item",children:s.jsx(ri,{view:e,panel:o.panel})},o.id))})});function ii(e){const t=g.useRef(null);return{ref:t,downloadScreenshot:()=>{var i;const r=(i=t.current)==null?void 0:i.querySelector(".react-grid-layout");r&&e.downloadScreenshot(r)}}}const a_=S.observer(({downloadScreenshot:e})=>{const[t,{setTrue:n,setFalse:r}]=$.useBoolean(!1),i=pa(),o=ce(),l=()=>{const c=JSON.stringify(o.contentJSON,null,2),u=`${i.name}__${o.name}`;Nt(u,c)};return s.jsxs(a.Menu,{shadow:"md",width:200,trigger:"hover",openDelay:200,closeDelay:400,withinPortal:!0,position:"bottom-end",children:[s.jsx(a.Menu.Target,{children:s.jsx(a.Affix,{position:{bottom:"20px",right:"10px"},zIndex:1,children:s.jsx(a.ActionIcon,{size:"md",variant:"gradient",gradient:{from:"indigo",to:"cyan"},onMouseEnter:n,onMouseLeave:r,sx:{opacity:t?1:.6,transform:`translateX(${t?0:"2px"})`,transition:"all ease 300ms",borderRadius:"50%"},children:s.jsx(_.IconShare3,{size:"1rem"})})})}),s.jsxs(a.Menu.Dropdown,{children:[s.jsx(a.Menu.Item,{icon:s.jsx(_.IconCamera,{size:14}),onClick:e,children:"Screenshot"}),s.jsx(a.Menu.Divider,{}),s.jsx(a.Menu.Item,{icon:s.jsx(_.IconDownload,{size:14}),onClick:o.queries.downloadAllData,children:"Download Data"}),s.jsx(a.Menu.Item,{icon:s.jsx(_.IconCode,{size:14}),onClick:l,children:"Download Schema"})]})]})}),nc=S.observer(({children:e,view:t,sx:n={}})=>{const{ref:r,downloadScreenshot:i}=ii(t);return s.jsxs(s.Fragment,{children:[s.jsx(a.Box,{ref:r,pt:10,pb:10,sx:n,children:e}),s.jsx(a_,{downloadScreenshot:i})]})}),sc=S.observer(({downloadScreenshot:e})=>s.jsx(a.ActionIcon,{className:"download-screenshot-button",color:"blue",onClick:e,children:s.jsx(_.IconCamera,{size:14})})),o_=S.observer(({children:e,view:t})=>{const n=ce(),r=t.config,i=n.views.visibleViewIDs.includes(t.id),o=()=>n.views.rmVisibleViewID(t.id),{ref:l,downloadScreenshot:c}=ii(t);return s.jsx(a.Modal,{size:r.width,centered:!0,opened:i,onClose:o,withCloseButton:!1,title:s.jsxs(a.Group,{position:"apart",px:"1rem",h:"48px",children:[s.jsx(a.Box,{children:r.custom_modal_title.value}),s.jsx(sc,{downloadScreenshot:c})]}),trapFocus:!0,onDragStart:u=>{u.stopPropagation()},styles:{root:{position:"fixed",zIndex:200,inset:0},overlay:{zIndex:"unset"},inner:{zIndex:"unset",padding:"0 !important"},content:{border:"1px solid #efefef",maxHeight:"unset !important",overflow:"hidden"},body:{maxHeight:r.height,overflow:"auto",position:"relative",paddingBottom:10},header:{padding:0},title:{flexGrow:1}},transitionProps:{duration:0},children:s.jsx(a.Box,{ref:l,children:e})})}),l_=e=>e.color?{"&[data-active], &[data-active]:hover":{borderColor:e.color?e.color:"..."}}:{},c_=S.observer(({view:e})=>{const t=ce(),n=e.config;return s.jsxs(a.Tabs,{className:"render-view-tabs",variant:n.variant,orientation:n.orientation,value:e.tab,onTabChange:e.setTab,styles:{root:{height:"100%",overflow:n.orientation==="horizontal"?"hidden":"auto"},panel:{padding:n.orientation==="horizontal"?"0px 0px 36px":"0",height:"100%",overflow:"auto"}},keepMounted:!1,children:[s.jsx(a.Tabs.List,{grow:n.grow,children:n.tabsInOrder.map(r=>s.jsx(a.Tabs.Tab,{value:r.id,sx:l_(r),disabled:!r.view_id,children:r.name??r.id},r.id))}),n.tabsInOrder.map(r=>{const i=t.views.findByID(r.view_id);return i?s.jsx(a.Tabs.Panel,{value:r.id,children:s.jsx(ts,{view:i})},r.id):null})]})}),u_=S.observer(({view:e,children:t})=>{switch(e.type){case L.Modal:return s.jsx(o_,{view:e,children:t});case L.Tabs:return s.jsx(c_,{view:e});case L.Division:default:return s.jsx(nc,{view:e,children:t})}}),d_=S.observer(({children:e,view:t})=>{const r=W().layouts,[i,o]=re.useResizeObserver();return g.useEffect(()=>{r.setCurrentLayoutWrapperWidth(o.width)},[o.width]),s.jsx(a.Box,{sx:{height:"100%"},ref:i,children:s.jsx(a.Box,{sx:{paddingBottom:"100px",background:"white",margin:"0 auto",width:r.currentLayoutPreviewWidth??"100%",transform:`scale(${r.divisionPreviewScale})`,transformOrigin:"0 0"},children:s.jsx(nc,{view:t,sx:{paddingTop:"0px !important",".dashboard-sticky-area > form":{paddingBottom:"5px"},".dashboard-layout":{marginTop:0,marginBottom:0}},children:e})})})});function rc(e){return e.replace(/(vw|vh)/,"%")}const p_=S.observer(({children:e,view:t})=>{const n=t.config,{width:r,height:i}=g.useMemo(()=>({width:rc(n.width),height:rc(n.height)}),[n.width,n.height]),{ref:o,downloadScreenshot:l}=ii(t);return s.jsx(a.Box,{sx:{height:"100%","> div:not(.mantine-Modal-root)":{height:"100%"}},children:s.jsx(a.Modal,{size:n.width,opened:!0,onClose:y.noop,withCloseButton:!1,title:s.jsxs(a.Group,{position:"apart",px:"1rem",h:"48px",children:[s.jsx(a.Box,{children:n.custom_modal_title.value}),s.jsx(sc,{downloadScreenshot:l})]}),trapFocus:!0,onDragStart:c=>{c.stopPropagation()},styles:{root:{position:"relative",height:"100%"},overlay:{position:"absolute !important"},inner:{position:"relative",top:"50%",left:"50%",right:"unset",bottom:"unset",transform:"translate(-50%, -50%)",padding:"0 !important",width:r,height:i,maxHeight:i},content:{border:"1px solid #efefef",height:"100%"},body:{maxHeight:"calc(100% - 48px)",overflow:"auto"},header:{padding:0},title:{flexGrow:1}},withinPortal:!1,transitionProps:{duration:0},children:s.jsx(a.Box,{ref:o,children:e})})})}),h_=({variant:e,orientation:t})=>{const n={root:{height:"100%",overflow:"hidden"},tabsList:{backgroundColor:"white"},tab:{},panel:{padding:"16px"}};return e==="pills"&&t==="horizontal"&&(n.tab.paddingTop="6px",n.tab.paddingBottom="6px"),t==="vertical"&&(n.tab["&.add-a-tab"]={paddingTop:"1px",paddingBottom:"1px"},n.tab["&.add-a-tab .mantine-Tabs-tabLabel"]={marginLeft:"auto",marginRight:"auto"}),n},x_=e=>e.color?{"&[data-active], &[data-active]:hover":{borderColor:e.color?e.color:"..."}}:{},f_=S.observer(({view:e})=>{const t=ze.useModals(),n=W(),r=g.useMemo(()=>n.views.options.filter(c=>c.type===L.Division),[e.id,n.views.options]),i=e.config,o=c=>t.openConfirmModal({title:"Delete this tab?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>{i.removeTab(c)},confirmProps:{color:"red"},zIndex:320}),l=i.tabs.length===0;return s.jsxs(a.Tabs,{className:"preview-view-tabs",variant:i.variant,orientation:i.orientation,value:e.tab,onTabChange:e.setTab,styles:h_(i),children:[s.jsxs(a.Tabs.List,{grow:i.grow,children:[i.tabsInOrder.map(c=>s.jsx(a.Tabs.Tab,{value:c.id,sx:x_(c),children:c.name??c.id},c.id)),s.jsx(a.Tabs.Tab,{onClick:i.addTab,value:"add",className:"add-a-tab",children:s.jsx(k.Plus,{size:18,color:"#228be6"})})]}),i.tabsInOrder.map((c,u)=>{const d=n.views.findByID(c.view_id);return s.jsxs(a.Tabs.Panel,{value:c.id,sx:{position:"relative"},children:[s.jsxs(a.Box,{sx:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:200},children:[s.jsx(a.Overlay,{opacity:.8,color:"#FFF",blur:10,zIndex:100}),s.jsxs(a.Stack,{mx:"auto",mt:100,sx:{width:"300px",position:"relative",zIndex:200},children:[s.jsx(a.TextInput,{label:"Tab Name",required:!0,value:c.name,onChange:h=>c.setName(h.currentTarget.value)}),s.jsx(a.Select,{label:"View",value:c.view_id,onChange:c.setViewID,data:r}),s.jsx(a.NumberInput,{label:"Placement Order",required:!0,value:c.order,onChange:h=>c.setOrder(h||0),min:0,max:1e3,step:1}),s.jsx(a.ColorInput,{label:"Color",value:c.color,onChange:c.setColor,disabled:i.variant!=="default"}),d&&s.jsxs(a.Button,{mt:20,variant:"gradient",leftIcon:s.jsx(_.IconArrowsLeftRight,{size:18}),gradient:{from:"cyan",to:"indigo"},onClick:()=>n.views.setIDOfVIE(d.id),children:["Swith to View: ",d.name]}),s.jsx(a.Button,{mt:20,variant:"subtle",color:"red",onClick:()=>o(u),disabled:l,leftIcon:s.jsx(_.IconTrash,{size:14}),children:"Delete This Tab"})]})]}),d&&s.jsx(ts,{view:d})]},c.id)})]})}),g_=S.observer(({view:e,children:t})=>{switch(e.type){case L.Modal:return s.jsx(p_,{view:e,children:t});case L.Tabs:return s.jsx(f_,{view:e});case L.Division:default:return s.jsx(d_,{view:e,children:t})}}),ic=S.observer(function({view:t}){const r=W().layouts.divisionPreviewScale!==1;return s.jsx(Jn.Provider,{value:{viewPanelInFullScreen:y.noop,inFullScreen:!1},children:s.jsx(a.Box,{className:"dashboard-view","data-enable-scrollbar":!0,sx:{background:r?"transparent":"#efefef"},children:s.jsx(g_,{view:t,children:s.jsxs(a.Box,{sx:{position:"relative"},children:[s.jsx(a.Box,{className:"dashboard-sticky-area",sx:{position:"sticky",top:"0px"},children:s.jsx(ul,{view:t})}),s.jsx(s_,{view:t})]})})})})}),ts=S.observer(function({view:t}){const{fullScreenPanelID:n,setFullScreenPanelID:r}=ba(),{viewPanelInFullScreen:i,exitFullScreen:o,inFullScreen:l,fullScreenPanel:c}=tc(t,n,r);return s.jsx(Jn.Provider,{value:{viewPanelInFullScreen:i,inFullScreen:l},children:s.jsxs(a.Box,{className:"dashboard-view","data-enable-scrollbar":!0,sx:{height:t.type===L.Modal?"0 !important":"100%"},children:[l&&s.jsx(ec,{view:t,panel:c,exitFullScreen:o}),s.jsx(u_,{view:t,children:s.jsxs(a.Box,{sx:{position:"relative"},children:[!l&&s.jsx(a.Box,{className:"dashboard-sticky-area",sx:{position:"sticky",top:"0px"},children:s.jsx(ul,{view:t})}),!l&&s.jsx(i_,{view:t})]})})]})})});var ac=(e=>(e.Use="use",e.Edit="edit",e))(ac||{});const m_={[L.Division]:"Division",[L.Tabs]:"Tabs",[L.Modal]:"Modal"},oc={[L.Division]:"rgba(255, 0, 0, 0.2)",[L.Modal]:"rgba(0, 0, 0, 0.2)",[L.Tabs]:"rgba(255, 200, 100, 0.4)"},y_={[L.Division]:"#ff4000",[L.Modal]:"#000",[L.Tabs]:"#ffad18"};function b_(e,t,n){f.addDisposer(e,f.addMiddleware(e,(r,i)=>{i(r,()=>{f.getType(r.context)===t&&r.type==="action"&&n(r.name,r.context)})}))}const lc=f.types.compose("FiltersModel",Xr,f.types.model("FiltersModel",{previewValues:f.types.optional(f.types.frozen(),{})})).views(e=>({get idSet(){return new Set(e.current.map(t=>t.id))},get keySet(){return new Set(e.current.map(t=>t.key))},get options(){return e.current.map(t=>({label:t.label??t.id,value:t.id,_type:"filter"}))},get selects(){return e.current.filter(t=>t.type===de.Select).map(t=>({label:t.label??t.id,value:t.id}))},get keyLabelOptions(){return e.current.map(t=>({label:t.label??t.key,value:t.key}))},get sortedList(){return y.sortBy(e.current,t=>t.label.toLowerCase())}})).actions(e=>({replace(t){e.current=f.cast(t)},append(t){e.current.push(t)},appendMultiple(t){if(t.length===0)return;const n=t.filter(r=>!e.idSet.has(r.id));e.current.push(...n)},remove(t){e.current.splice(t,1)},removeByID(t){const n=e.current.findIndex(r=>r.id===t);n>=0&&e.current.splice(n,1)},updatePreviewValues(t){e.previewValues=t}})).actions(e=>{function t(){b_(e.current,Vr,(n,r)=>{if(n==="setType"){const i=Ol(r.config.default_value,r.config);e.setValueByKey(r.key,i),e.updatePreviewValues({...e.previewValues,[r.key]:i})}})}return{afterCreate(){t()}}}),cc=Zr.views(e=>({get canPreviewData(){return e.isTransform?e.dep_query_ids.length>0&&!!e.pre_process:!!e.datasource},get guideToPreviewData(){return e.isTransform?"Need to complete settings in Transform tab":"Need to pick a Data Source first"}})),uc=f.types.compose("QueriesModel",Hr,f.types.model({current:f.types.optional(f.types.array(cc),[])})).views(e=>({get options(){const t=e.current.map(n=>({value:n.id,label:n.name,_type:"query"}));return y.sortBy(t,n=>n.label.toLowerCase())},get optionsWithoutTransform(){const t=e.current.filter(n=>n.type!==oe.Transform).map(n=>({value:n.id,label:n.name,_type:"query"}));return y.sortBy(t,n=>n.label.toLowerCase())},get sortedList(){return y.sortBy(e.current,t=>t.name.toLowerCase())}})).actions(e=>({replace(t){e.current=f.cast(t)},append(t){e.current.push(t)},appendMultiple(t){if(t.length===0)return;const n=t.filter(r=>!e.idSet.has(r.id));e.current.push(...n)},remove(t){e.current.splice(t,1)},replaceByIndex(t,n){e.current.splice(t,1,n)},removeQuery(t){const n=e.current.find(r=>r.id===t);n&&(f.detach(n),e.current.remove(n))},removeQueries(t){const n=new Set(t);e.current.forEach(i=>{n.has(i.id)&&f.detach(i)});const r=[...e.current];y.remove(r,i=>n.has(i.id)),e.current=f.cast(r)}})),dc=ti.views(e=>({get sortedList(){return y.sortBy(e.current,t=>t.key.toLowerCase())},get options(){const t=e.current.map(n=>({label:n.key,value:n.key,_type:"sql_snippet"}));return y.sortBy(t,n=>n.label.toLowerCase())}})).actions(e=>({replace(t){e.current=f.cast(t)},append(t){e.current.push(t)},appendMultiple(t){if(t.length===0)return;const n=t.filter(r=>!e.keySet.has(r.key));e.current.push(...n)},remove(t){e.current.splice(t,1)},removeByKey(t){const n=e.current.findIndex(r=>r.key===t);n>=0&&e.current.splice(n,1)},removeByKeys(t){const n=new Set(t);e.current.forEach(i=>{n.has(i.key)&&f.detach(i)});const r=[...e.current];y.remove(r,i=>n.has(i.key)),e.current=f.cast(r)},replaceByIndex(t,n){e.current.splice(t,1,n)}})),j_=f.types.model({data:f.types.optional(f.types.frozen(),[]),state:f.types.optional(f.types.enumeration(["idle","loading","error"]),"idle"),error:f.types.frozen()}).views(e=>({get loading(){return e.state==="loading"},get empty(){return e.data.length===0}})),v_=f.types.model({data:f.types.optional(f.types.frozen(),[]),state:f.types.optional(f.types.enumeration(["idle","loading","error"]),"idle"),error:f.types.frozen()}).views(e=>({get loading(){return e.state==="loading"},get empty(){return e.data.length===0}})),w_=f.types.model({page:f.types.optional(f.types.number,1),limit:f.types.optional(f.types.number,20),data:f.types.optional(f.types.frozen(),[]),total:f.types.optional(f.types.number,0),state:f.types.optional(f.types.enumeration(["idle","loading","error"]),"idle"),error:f.types.frozen()}).views(e=>({get keywords(){return f.getParent(e,1)},get keywordString(){const{table_name:t,table_schema:n}=f.getParent(e,1);return`${n}||${t}`}})).views(e=>({get loading(){return e.state==="loading"},get empty(){return e.data.length===0},get maxPage(){return Math.ceil(e.total/e.limit)},get offset(){return(e.page-1)*e.limit},get countSql(){const{table_name:t,table_schema:n}=e.keywords;return`
|
|
449
|
+
`}})}function QS(e,t){const n=Vt(e.heat_block.min,t),r=Vt(e.heat_block.max,t);return{min:n,max:r,calculable:!0,orient:"horizontal",left:"center",top:0,itemWidth:15}}function US(e,t,n){const r=z(e.x_axis.data_key),i=y.uniq(t[r.queryID].map(u=>u[r.columnKey])),{overflow:o,rotate:l}=e.x_axis.axisLabel,c=Be(o.on_axis);return ee.getXAxis({id:"main-x-axis",type:"category",data:i,name:e.x_axis.name??"",align:"center",axisTick:{show:!0,alignWithLabel:!0},axisLabel:{rotate:l,...c,formatter:n},splitArea:{show:!1,areaStyle:{color:"#E7E7E9"}},splitLine:{show:!1},nameLocation:"center",nameGap:25,nameTextStyle:{fontWeight:"bold",align:"center"},z:3})}function KS(e,t,n){const r=z(e.x_axis.data_key),i=z(e.y_axis.data_key),{nameAlignment:o,data_key:l,...c}=e.y_axis,u=y.uniq(t[r.queryID].map(x=>x[i.columnKey])),{overflow:d,rotate:h}=e.y_axis.axisLabel,p=Be(d.on_axis);return ee.getYAxis({...c,type:"category",data:u,axisLabel:{rotate:h,...p,formatter:n},axisLine:{show:!0,lineStyle:{width:3}},axisTick:{show:!0,alignWithLabel:!0},splitArea:{show:!1,areaStyle:{color:"#E7E7E9"}},splitLine:{show:!1},nameTextStyle:{fontWeight:"bold",align:o},nameLocation:"end",nameGap:15,z:3})}function YS(e,t,n){if(!e.x_axis.data_key||!e.y_axis.data_key||!e.heat_block.data_key)return{};const r=n.reduce((c,u)=>{const d=st(u,t);return c[u.name]=Ae(u,d),c},{}),i=VS(e),o=qS(e);return{xAxis:US(e,t,i.x_axis),yAxis:KS(e,t,i.y_axis),series:FS(e,t),tooltip:RS(e,t,i,o),grid:NS(e),visualMap:QS(e,r)}}function XS({conf:e,data:t,width:n,height:r,interactionManager:i,variables:o}){const l=g.useMemo(()=>{const p=z(e.x_axis.data_key),x=z(e.y_axis.data_key);return y.keyBy(t[p.queryID],m=>`${m[p.columnKey]}---${m[x.columnKey]}`)},[t,e.x_axis.data_key,e.y_axis.data_key]),c=Oe(i.triggerManager,nl.id),u=g.useCallback(p=>{const[x,m]=p.value,j=y.get(l,`${x}---${m}`,{error:"rowData is not found"});c.forEach(C=>{i.runInteraction(C.id,{...p,rowData:j})})},[l,c,i]),d=g.useMemo(()=>({click:u}),[u]),h=g.useMemo(()=>YS(e,t,o),[e,t]);return s.jsx(we,{echarts:be,option:h,style:{width:n,height:r},onEvents:d,notMerge:!0,theme:"merico-light"})}function JS({context:e,instance:t}){const n=$e({vizManager:e.vizManager,instance:t}),{value:r}=O(e.instanceData,"config"),{variables:i}=e,o=g.useMemo(()=>y.defaults({},r,_r),[r]),l=e.data,{width:c,height:u}=e.viewport;return!c||!u?null:s.jsx(ke,{width:c,height:u,children:s.jsx(XS,{variables:i,width:Ge(c),height:We(u),data:l,conf:o,interactionManager:n})})}class ZS extends ae{constructor(){super(...arguments);P(this,"VERSION",1)}configVersions(){this.version(1,n=>({version:1,config:n}))}}const HS={displayName:"Merico Heatmap",displayGroup:"Merico suite",migrator:new ZS,name:"merico-heatmap",viewRender:JS,configRender:BS,createConfig:()=>({version:1,config:_r}),triggers:[nl]},e1=[{value:"#25262B",name:"Dark"},{value:"#868E96",name:"Gray"},{value:"#FA5252",name:"Red"},{value:"#E64980",name:"Pink"},{value:"#BE4BDB",name:"Grape"},{value:"#7950F2",name:"Violet"},{value:"#4C6EF5",name:"Indigo"},{value:"#228BE6",name:"Blue"},{value:"#15AABF",name:"Cyan"},{value:"#12B886",name:"Teal"},{value:"#40C057",name:"Green"},{value:"#82C91E",name:"Lime"},{value:"#FAB005",name:"Yellow"},{value:"#FD7E14",name:"Orange"}].map(e=>({name:e.name,value:e.value,type:"single",category:"basic"})),t1=[Bd,Od,qd,Vd,$d,Nd],rl=()=>({id:"dashboard",version:ua,manifest:{viz:[gr,qv,d0,gj,lw,ob,PC,Hd,Nh,Lm,my,K0,Xy,pm,Dv,Ab,oj,b0,pS,HS,kS,tx],color:[...e1,...t1]}}),on=new Rd,ue={pluginManager:rt("pluginManager"),vizManager:rt("vizManager"),colorManager:rt("colorManager"),instanceScope:{panelModel:rt("panelModel"),vizInstance:rt("vizInstance"),interactionManager:rt("interactionManager"),migrator:rt("migrator"),operationManager:rt("operationManager"),triggerManager:rt("triggerManager")}},kr=()=>{try{on.install(rl())}catch{}const e=new Ed(on),t=new Wd(on);return{pluginManager:on,vizManager:e,colorManager:t}},Ze=g.createContext(kr());try{on.install(rl())}catch{}const Tr=g.createContext(null);function Xn(e){const t=g.useContext(Tr),n=$.useCreation(()=>e.configure(t||new vs),[e.configure]),r=$.usePrevious(n);return r&&r!==n&&r.dispose(),s.jsx(Tr.Provider,{value:n,children:e.children})}function il(){return g.useContext(Tr)}const n1=({description:e,isDescriptionEmpty:t})=>t?null:s.jsx(a.Tooltip,{color:"white",label:s.jsx(Nn,{value:e,styles:{root:{border:"none"},content:{padding:0}}}),styles:{tooltip:{border:"0.0625rem solid rgb(233, 236, 239)",boxShadow:"rgb(0 0 0 / 5%) 0px 0.0625rem 0.1875rem, rgb(0 0 0 / 5%) 0px 1.25rem 1.5625rem -0.3125rem, rgb(0 0 0 / 4%) 0px 0.625rem 0.625rem -0.3125rem"}},withArrow:!0,children:s.jsx(a.Box,{sx:{height:"16px",alignSelf:"center"},children:s.jsx(_.IconInfoCircle,{size:16,color:"gray"})})}),s1=S.observer(({label:e,config:{default_value:t,description:n,isDescriptionEmpty:r,...i},value:o,onChange:l})=>s.jsxs(a.Box,{children:[s.jsx(a.Text,{children:" "}),s.jsx(a.Checkbox,{label:s.jsxs(a.Group,{noWrap:!0,position:"apart",align:"middle",spacing:6,children:[s.jsx(a.Box,{sx:{flexGrow:1},children:e}),s.jsx(n1,{description:n,isDescriptionEmpty:r})]}),checked:o||!1,onChange:c=>l(c.currentTarget.checked),...i,pt:".4em",styles:{input:{borderColor:"#e9ecef"}}})]})),r1=({value:e,onChange:t,close:n,max_days:r,allowSingleDateInRange:i})=>{const[o,l]=e,c=g.useMemo(()=>o||new Date,[o]),u=g.useMemo(()=>{if(o&&!l)return o},[o,l]),d=g.useMemo(()=>{if(o&&!l&&r>0)return M(o).add(r-1,"days").toDate()},[o,l,r]),h=p=>{const[x,m]=p;t(p),x&&m&&n()};return s.jsx(xu.DatePicker,{defaultDate:c,numberOfColumns:2,type:"range",value:e,onChange:h,onNextMonth:console.log,minDate:u,maxDate:d,allowSingleDateInRange:i})},i1=({begin:e,end:t})=>{const n=g.useMemo(()=>M(t).diff(M(e),"days")+1,[e,t]);if(Number.isNaN(n))return s.jsx("span",{style:{userSelect:"none",opacity:0,visibility:"hidden"},children:"."});const r=n===1?"day":"days";return s.jsx(a.Tooltip,{label:`${n}${r}`,children:s.jsx(a.Badge,{size:"sm",children:n})})},a1=({max_days:e})=>e?s.jsxs(s.Fragment,{children:[s.jsx(a.Group,{position:"right",children:s.jsxs(a.Badge,{size:"xs",children:[e," days max"]})}),s.jsx(a.Divider,{variant:"dashed",my:10})]}):null,Dr=()=>[{label:"yesterday",value:"yesterday",group:"last",getRange:()=>{const e=Date.now();return[M(e).subtract(1,"day").startOf("day").toDate(),M(e).subtract(1,"day").endOf("day").toDate()]}},{label:"week",value:"last week",group:"last",getRange:()=>{const e=Date.now();return[M(e).subtract(1,"week").startOf("week").toDate(),M(e).subtract(1,"week").endOf("week").toDate()]}},{label:"month",value:"last month",group:"last",getRange:()=>{const e=Date.now();return[M(e).subtract(1,"month").startOf("month").toDate(),M(e).subtract(1,"month").endOf("month").toDate()]}},{label:"2 months",value:"last 2 months",group:"last",getRange:()=>{const e=Date.now();return[M(e).subtract(2,"month").startOf("month").toDate(),M(e).subtract(1,"month").endOf("month").toDate()]}},{label:"3 months",value:"last 3 months",group:"last",getRange:()=>{const e=Date.now();return[M(e).subtract(3,"month").startOf("month").toDate(),M(e).subtract(1,"month").endOf("month").toDate()]}},{label:"year",value:"last year",group:"last",getRange:()=>{const e=Date.now();return[M(e).subtract(1,"year").startOf("year").toDate(),M(e).subtract(1,"year").endOf("year").toDate()]}},{label:"7 days",value:"recent 7 days",group:"recent",getRange:()=>{const e=Date.now();return[M(e).subtract(7,"day").startOf("day").toDate(),M(e).subtract(1,"day").endOf("day").toDate()]}},{label:"30 days",value:"recent 30 days",group:"recent",getRange:()=>{const e=Date.now();return[M(e).subtract(30,"day").startOf("day").toDate(),M(e).subtract(1,"day").endOf("day").toDate()]}},{label:"60 days",value:"recent 60 days",group:"recent",getRange:()=>{const e=Date.now();return[M(e).subtract(60,"day").startOf("day").toDate(),M(e).subtract(1,"day").endOf("day").toDate()]}},{label:"90 days",value:"recent 90 days",group:"recent",getRange:()=>{const e=Date.now();return[M(e).subtract(90,"day").startOf("day").toDate(),M(e).subtract(1,"day").endOf("day").toDate()]}},{label:"180 days",value:"recent 180 days",group:"recent",getRange:()=>{const e=Date.now();return[M(e).subtract(180,"day").startOf("day").toDate(),M(e).subtract(1,"day").endOf("day").toDate()]}},{label:"365 days",value:"recent 365 days",group:"recent",getRange:()=>{const e=Date.now();return[M(e).subtract(365,"day").startOf("day").toDate(),M(e).subtract(1,"day").endOf("day").toDate()]}},{label:"today",value:"today",group:"this",getRange:()=>{const e=Date.now();return[M(e).startOf("day").toDate(),M(e).endOf("day").toDate()]}},{label:"week",value:"this week",group:"this",getRange:()=>{const e=Date.now();return[M(e).startOf("week").toDate(),M(e).endOf("week").toDate()]}},{label:"month",value:"this month",group:"this",getRange:()=>{const e=Date.now();return[M(e).startOf("month").toDate(),M(e).endOf("month").toDate()]}},{label:"2 months",value:"this 2 months",group:"this",getRange:()=>{const e=Date.now();return[M(e).startOf("month").toDate(),M(e).add(1,"month").endOf("week").toDate()]}},{label:"3 months",value:"this 3 months",group:"this",getRange:()=>{const e=Date.now();return[M(e).startOf("month").toDate(),M(e).add(2,"month").endOf("week").toDate()]}},{label:"year",value:"this year",group:"this",getRange:()=>{const e=Date.now();return[M(e).startOf("year").toDate(),M(e).endOf("year").toDate()]}}];function al(e){const n=Dr().find(r=>r.value===e);return n?n.getRange():null}const o1=({onChange:e})=>{const t=r=>()=>{const i=r();e(i)},n=g.useMemo(()=>y.groupBy(Dr(),"group"),[]);return s.jsxs(s.Fragment,{children:[s.jsx(a.Divider,{variant:"dashed",my:10}),s.jsx(a.Table,{withBorder:!1,sx:{"tbody > tr > th, tbody > tr > td":{borderTop:"none",padding:"2px 6px"},"tbody > tr > th":{cursor:"default",userSelect:"none"},td:{paddingLeft:"1px"}},children:s.jsx("tbody",{children:Object.entries(n).map(([r,i])=>s.jsxs("tr",{children:[s.jsx("th",{children:s.jsx(a.Text,{size:"xs",color:"#555",children:r})}),i.map(({label:o,value:l,getRange:c})=>s.jsx("td",{children:s.jsx(a.Button,{compact:!0,size:"xs",variant:"subtle",onClick:t(c),children:o})},o))]},r))})})]})},ol=e=>({label:{display:"block",height:"21.7px"},input:{borderColor:e?"#228be6":"#e9ecef"}}),l1=({label:e,required:t,value:n,onChange:r,max_days:i,allowSingleDateInRange:o,inputFormat:l})=>{const[c,{open:u,close:d}]=re.useDisclosure(!1),[h,p]=n,x=h?M(h).format(l):"",m=p?M(p).format(l):"";return s.jsxs(a.Popover,{opened:c,onClose:d,position:"bottom-start",shadow:"md",children:[s.jsxs(a.Group,{position:"left",grow:!0,noWrap:!0,spacing:0,w:"18em",sx:{marginTop:"3px"},children:[s.jsx(a.Popover.Target,{children:s.jsx(a.TextInput,{label:e,required:t,icon:s.jsx(_.IconCalendar,{size:16}),placeholder:"Start date",readOnly:!0,value:x,onFocus:u,styles:ol(c),sx:{".mantine-Input-input":{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}}})}),s.jsx(a.TextInput,{label:s.jsx(a.Group,{position:"right",children:s.jsx(i1,{begin:h,end:p})}),icon:s.jsx(_.IconMinus,{size:16}),placeholder:"End date",readOnly:!0,disabled:!h,value:m,onFocus:u,styles:ol(c),sx:{".mantine-Input-icon":{transform:"translateX(-22px)"},".mantine-Input-input":{borderLeft:"none",borderTopLeftRadius:0,borderBottomLeftRadius:0},".mantine-Input-input[data-disabled]":{backgroundColor:"transparent",backgroundImage:"linear-gradient(to right, #fff 0%, #f1f3f5 30%)",opacity:1},".mantine-Input-input[data-disabled]::placeholder":{opacity:.6}}})]}),s.jsxs(a.Popover.Dropdown,{p:"sm",children:[s.jsx(a1,{max_days:i}),s.jsx(r1,{value:n,onChange:r,close:d,allowSingleDateInRange:o,max_days:i}),s.jsx(o1,{onChange:r})]})]})},ll=S.observer(({label:e,config:t,value:n=[null,null],onChange:r})=>{const{inputFormat:i,required:o,max_days:l,allowSingleDateInRange:c}=t,u=Array.isArray(n)?n.map(h=>h?M(h).toDate():null):[null,null],d=h=>{r(h.map(p=>p&&M(p).format(i)))};return s.jsx(l1,{label:e,value:u,onChange:d,inputFormat:i,allowSingleDateInRange:c,max_days:l,required:o})}),c1=a.createStyles((e,{radius:t=4})=>({root:{borderRadius:e.fn.radius(t),display:"flex",flexWrap:"nowrap",border:"1px solid #ced4da",paddingLeft:"0px",paddingRight:"30px",backgroundColor:"#fff",transition:"border-color 100ms ease",borderColor:"#e9ecef","&.rc-select.rc-select-open":{borderColor:"#228be6 !important",".rc-select-selection-overflow-item-rest":{display:"none"},".rc-select-selection-overflow-item-suffix":{display:"block"}},".rc-select-selector":{height:"auto",lineHeight:1.55,paddingLeft:"12px",resize:"none",boxSizing:"border-box",fontSize:"14px",width:"100%",color:"#000",display:"block",textAlign:"left",minHeight:"36px",cursor:"pointer",flexGrow:1},".rc-select-selection-search-mirror":{display:"none"},".rc-select-selection-search":{flexGrow:1,width:"auto !important"},".rc-select-selection-overflow":{display:"flex",minHeight:"34px",alignItems:"center",flexWrap:"nowrap",marginLeft:"calc(-10px / 2)",boxSizing:"border-box"},".rc-select-selection-overflow-item":{display:"flex",alignItems:"center",backgroundColor:"#f1f3f5",color:"#495057",height:"24px",paddingLeft:"12px",paddingRight:"12px",fontWeight:500,fontSize:"12px",borderRadius:"4px",cursor:"default",userSelect:"none",maxWidth:"calc(100% - 20px)",margin:"calc(10px / 2 - 2px) calc(10px / 2)"},".rc-select-selection-overflow-item-rest":{cursor:"pointer"},".rc-select-selection-overflow-item-suffix":{display:"none",backgroundColor:"transparent",width:"100%",maxWidth:"100%",height:"28px",margin:0,paddingLeft:0,paddingRight:0},input:{flex:1,minWidth:"60px",backgroundColor:"transparent",border:0,outline:0,fontSize:"14px",padding:0,marginLeft:0,color:"inherit",height:"28px",lineHeight:"32px",cursor:"pointer",width:"100%","&::-webkit-search-decoration, &::-webkit-search-cancel-button, &::-webkit-search-results-button, &::-webkit-search-results-decoration":{display:"none"}},".rc-select-clear":{marginRight:"-24px",alignSelf:"center",cursor:"pointer"},"&.rc-select-disabled":{backgroundColor:"rgb(241, 243, 245)",color:"rgb(144, 146, 150)",opacity:.6,"&, .rc-select-selector, input":{cursor:"not-allowed"}}},label:{fontSize:e.fontSizes.sm,fontWeight:500,color:"#212529"},required:{color:"#fa5252",paddingLeft:"3px"},dropdown:{fontSize:e.fontSizes.xs,zIndex:300,backgroundColor:"#fff",border:"1px solid #e9ecef",marginTop:6,padding:0,boxShadow:"0 1px 3px rgb(0 0 0 / 5%), rgb(0 0 0 / 5%) 0px 10px 15px -5px, rgb(0 0 0 / 4%) 0px 7px 7px -5px",borderRadius:"4px","&.rc-select-dropdown-slide-up-leave-active":{display:"none"},".rc-select-item-empty":{padding:"8px 12px"},".rc-select-item-option":{boxSizing:"border-box",textAlign:"left",width:"100%",padding:"8px 12px 8px 2px",cursor:"pointer",fontSize:"14px",color:"#000",borderRadius:"4px",display:"flex",flexWrap:"nowrap",overflow:"hidden","&:hover":{backgroundColor:"#f1f3f5"},flexDirection:"row-reverse",".rc-select-item-option-state":{flexGrow:0,flexShrink:0,width:"30px",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},".rc-select-item-option-content":{width:"calc(100% - 30px)",overflow:"hidden",'div[data-role="label"]':{overflowWrap:"break-word"}}},".rc-virtual-list-holder-inner":{alignItems:"flex-start"}}})),cl=({errorMessage:e})=>e?s.jsx(a.Text,{color:"red",size:12,children:e}):s.jsx(a.Text,{color:"dimmed",size:12,children:"Not found"}),u1=({disabled:e,classNames:t,styles:n,unstyled:r,radius:i,style:o,label:l,value:c,onChange:u,options:d,errorMessage:h,required:p})=>{const{classes:x,cx:m}=c1({radius:i},{name:"MultiSelectWidget",classNames:t,styles:n,unstyled:r}),[j,C]=g.useState(!1),T=R=>{C(R)},D=j&&(c==null?void 0:c.length)>0,[A,N]=g.useState(""),Y=g.useMemo(()=>{if(!A)return d;const R=A.toLowerCase(),F=Z=>{var se;return((se=Z.description)==null?void 0:se.toLowerCase().includes(R))||Z.label.toLowerCase().includes(R)};return d.filter(F)},[A,d]);return s.jsxs(a.Stack,{spacing:3,children:[s.jsxs(a.Group,{position:"apart",children:[s.jsxs(a.Text,{className:x.label,children:[l,p&&s.jsx("span",{className:x.required,"aria-hidden":"true",children:"*"})]}),D&&s.jsx(a.Tooltip,{label:`${c.length} selected`,children:s.jsx(a.Badge,{children:c.length})})]}),s.jsx(Ri,{disabled:e,allowClear:!0,className:m(x.root,"check-select"),dropdownClassName:m(x.dropdown,""),onDropdownVisibleChange:T,transitionName:"rc-select-dropdown-slide-up",choiceTransitionName:"rc-select-selection__choice-zoom",style:o,clearIcon:()=>s.jsx(a.CloseButton,{}),value:c,onChange:u,onSelect:console.log,mode:"multiple",maxTagCount:0,notFoundContent:s.jsx(cl,{errorMessage:h}),maxTagTextLength:10,maxTagPlaceholder:R=>`${R.length} selected`,searchValue:A,onSearch:N,filterOption:!1,children:Y.map(R=>s.jsxs(Ri.Option,{title:R.label,children:[s.jsx(a.Text,{size:"sm","data-role":"label",children:R.label}),R.description&&s.jsx(a.Text,{size:"xs",color:"dimmed","data-role":"description",children:R.description})]},R.value))})]})},d1=S.observer(({label:e,config:t,value:n,onChange:r})=>{const i=ce(),o=!!t.options_query_id,{state:l,error:c}=i.getDataStuffByID(t.options_query_id),u=l==="loading",d=t.min_width?t.min_width:"200px",h=o?u:!1,p=x=>r(x,!1);return s.jsx(u1,{label:e,options:t.options,style:{minWidth:"160px",width:d,maxWidth:h?d:"unset",borderColor:"#e9ecef"},disabled:h,value:n,onChange:p,errorMessage:c,required:t.required})}),p1=g.forwardRef(({label:e,description:t,...n},r)=>s.jsx("div",{ref:r,...n,children:s.jsx(a.Group,{noWrap:!0,children:s.jsxs("div",{children:[s.jsx(a.Text,{size:"sm","data-role":"label",children:e}),s.jsx(a.Text,{size:"xs",color:"dimmed","data-role":"description",children:t})]})})})),h1=S.observer(({label:e,config:t,value:n,onChange:r})=>{const i=ce(),o=!!t.options_query_id,{state:l,error:c}=i.getDataStuffByID(t.options_query_id),u=l==="loading";return s.jsx(a.Select,{label:e,data:t.options,disabled:o?u:!1,value:n,onChange:r,error:!!c,placeholder:c,maxDropdownHeight:500,styles:{root:{width:t.width?t.width:"200px"},input:{borderColor:"#e9ecef"}},sx:{".mantine-Select-item[data-selected] .mantine-Text-root[data-role=description]":{color:"rgba(255,255,255,.7)"}},itemComponent:p1})});function x1({label:e,config:t,value:n,onChange:r}){return s.jsx(a.TextInput,{label:e,value:n||"",onChange:i=>r(i.currentTarget.value),...t,styles:{input:{borderColor:"#e9ecef"}}})}const f1=({rotate:e,onClick:t})=>s.jsx("svg",{onClick:t,className:"caret-icon",viewBox:"0 0 1024 1024",focusable:"false","data-icon":"caret-down",width:"14px",height:"14px",fill:"currentColor","aria-hidden":"true",transform:`rotate(${e})`,children:s.jsx("path",{d:"M840.4 300H183.6c-19.7 0-30.7 20.8-18.5 35l328.4 380.8c9.4 10.9 27.5 10.9 37 0L858.9 335c12.2-14.2 1.2-35-18.5-35z"})}),g1=({expanded:e,isLeaf:t,value:n,onClick:r,...i})=>(n==="0-0-value"&&console.log(i),t?s.jsx("span",{style:{width:"14px",display:"inline-block"}}):s.jsx(f1,{rotate:e?"0":"-90",onClick:r,...i})),m1=({onClick:e})=>s.jsxs("svg",{onClick:e,className:"checkbox-icon",width:"16",height:"16",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:"2",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),s.jsx("rect",{className:"border",x:"4",y:"4",width:"16",height:"16",rx:"2"}),s.jsx("rect",{className:"checkmark-indeterminate",x:"8",y:"8",width:"8",height:"8",rx:"2",stroke:"none"}),s.jsx("path",{className:"checkmark-checked",d:"M9 12l2 2l4 -4"})]}),y1=({onClick:e,...t})=>s.jsx(m1,{onClick:e,...t}),b1=a.createStyles((e,{radius:t=4})=>({root:{borderRadius:e.fn.radius(t),display:"flex",flexWrap:"nowrap",border:"1px solid #ced4da",paddingLeft:"0px",paddingRight:"30px",backgroundColor:"#fff",transition:"border-color 100ms ease",borderColor:"#e9ecef","&.rc-tree-select.rc-tree-select-open":{borderColor:"#228be6 !important",".rc-tree-select-selection-overflow-item-rest":{display:"none"},".rc-tree-select-selection-overflow-item-suffix":{display:"block"}},".rc-tree-select-selector":{height:"auto",lineHeight:1.55,paddingLeft:"12px",resize:"none",boxSizing:"border-box",fontSize:"14px",width:"100%",color:"#000",display:"block",textAlign:"left",minHeight:"36px",cursor:"pointer",flexGrow:1},".rc-tree-select-selection-search-mirror":{display:"none"},".rc-tree-select-selection-search":{flexGrow:1,width:"auto !important"},".rc-tree-select-selection-overflow":{display:"flex",minHeight:"34px",alignItems:"center",flexWrap:"nowrap",marginLeft:"calc(-10px / 2)",boxSizing:"border-box"},".rc-tree-select-selection-overflow-item":{display:"flex",alignItems:"center",backgroundColor:"#f1f3f5",color:"#495057",height:"24px",paddingLeft:"12px",paddingRight:"12px",fontWeight:500,fontSize:"12px",borderRadius:"4px",cursor:"default",userSelect:"none",maxWidth:"calc(100% - 20px)",margin:"calc(10px / 2 - 2px) calc(10px / 2)"},".rc-tree-select-selection-overflow-item-rest":{cursor:"pointer"},".rc-tree-select-selection-overflow-item-suffix":{display:"none",backgroundColor:"transparent",width:"100%",maxWidth:"100%",height:"28px",margin:0,paddingLeft:0,paddingRight:0},input:{flex:1,minWidth:"60px",backgroundColor:"transparent",border:0,outline:0,fontSize:"14px",padding:0,marginLeft:0,color:"inherit",height:"28px",lineHeight:"32px",cursor:"pointer",width:"100%","&::-webkit-search-decoration, &::-webkit-search-cancel-button, &::-webkit-search-results-button, &::-webkit-search-results-decoration":{display:"none"}},".rc-tree-select-clear":{marginRight:"-24px",alignSelf:"center",cursor:"pointer"},"&.rc-tree-select-disabled":{backgroundColor:"rgb(241, 243, 245)",color:"rgb(144, 146, 150)",opacity:.6,"&, .rc-tree-select-selector, input":{cursor:"not-allowed"}}},label:{fontSize:e.fontSizes.sm,fontWeight:500,color:"#212529"},required:{color:"#fa5252",paddingLeft:"3px"},dropdown:{fontSize:e.fontSizes.xs,zIndex:300,paddingTop:"6px","&.rc-tree-select-dropdown-slide-up-leave-active":{display:"none"},".rc-tree-select-tree-list .rc-tree-select-tree-list-holder":{},".rc-tree-select-tree-list, .rc-tree-select-empty":{backgroundColor:"#fff",border:"1px solid #e9ecef",padding:0,boxShadow:"0 1px 3px rgb(0 0 0 / 5%), rgb(0 0 0 / 5%) 0px 10px 15px -5px, rgb(0 0 0 / 4%) 0px 7px 7px -5px",borderRadius:"4px"},".rc-tree-select-empty":{padding:"8px 12px"},".rc-tree-select-tree-treenode":{boxSizing:"border-box",textAlign:"left",width:"100%",padding:"8px 12px",cursor:"pointer",fontSize:"14px",color:"#000",borderRadius:"4px",display:"flex",flexWrap:"nowrap",overflow:"hidden","&:hover":{backgroundColor:"#f1f3f5"},"&.rc-tree-select-tree-treenode-checkbox-checked":{".rc-tree-select-tree-iconEle .checkbox-icon .checkmark-checked":{stroke:"rgb(64, 192, 87)",animation:"check 200ms linear forwards"}},"&.rc-tree-select-tree-treenode-checkbox-indeterminate":{".rc-tree-select-tree-iconEle .checkbox-icon .checkmark-indeterminate":{fill:"rgb(64, 192, 87)"}},".rc-tree-select-tree-switcher":{height:"16px",alignSelf:"center",paddingRight:"2px",transition:"color 200ms ease","&:hover":{color:"#228be6","svg.caret-icon":{color:"#228be6"}},"svg.caret-icon":{color:"#ced4da",transition:"all 200ms ease"}},".rc-tree-select-tree-node-content-wrapper":{display:"flex",flexWrap:"nowrap",overflow:"hidden",alignItems:"center",gap:"8px",transition:"color 200ms ease","&:hover":{color:"#228be6"}},".rc-tree-select-tree-iconEle":{height:"16px","svg .border":{stroke:"#ced4da"},".checkbox-icon .checkmark-indeterminate":{fill:"transparent",transition:"fill 200ms ease"},".checkbox-icon .checkmark-checked":{transform:"scale(1.2)",transformOrigin:"center center",strokeDasharray:10,strokeDashoffset:-10},"@keyframes check":{"0%":{strokeDashoffset:10},"100%":{strokeDashoffset:0}}},".rc-tree-select-tree-title":{textOverflow:"ellipsis",whiteSpace:"nowrap",overflow:"hidden",".rc-tree-select-tree-title-desc":{fontSize:"12px",maxWidth:"100%",textOverflow:"ellipsis",whiteSpace:"nowrap",overflow:"hidden"}},".rc-tree-select-tree-indent":{flexGrow:0,height:0,verticalAlign:"bottom"},".rc-tree-select-tree-indent-unit":{display:"inline-block",width:"1em"}}}})),j1=({disabled:e,classNames:t,styles:n,unstyled:r,radius:i,style:o,label:l,value:c,onChange:u,treeData:d,errorMessage:h,required:p,treeCheckStrictly:x})=>{const{classes:m,cx:j}=b1({radius:i},{name:"FilterTreeSelectWidget",classNames:t,styles:n,unstyled:r}),[C,T]=g.useState(!1),D=N=>{T(N)},A=C&&(c==null?void 0:c.length)>0;return s.jsxs(a.Stack,{spacing:3,children:[s.jsxs(a.Group,{position:"apart",children:[s.jsxs(a.Text,{className:m.label,children:[l,p&&s.jsx("span",{className:m.required,"aria-hidden":"true",children:"*"})]}),A&&s.jsx(a.Tooltip,{label:`${c.length} selected`,children:s.jsx(a.Badge,{children:c.length})})]}),s.jsx(Qi,{disabled:e,allowClear:!0,treeCheckStrictly:x,labelInValue:!0,className:j(m.root,"check-select"),dropdownClassName:j(m.dropdown,""),onDropdownVisibleChange:D,transitionName:"rc-tree-select-dropdown-slide-up",choiceTransitionName:"rc-tree-select-selection__choice-zoom",style:o,listHeight:510,treeLine:!0,clearIcon:()=>s.jsx(a.CloseButton,{}),switcherIcon:g1,treeIcon:y1,maxTagTextLength:10,value:c,treeData:d,notFoundContent:s.jsx(cl,{errorMessage:h}),treeNodeFilterProp:"filterBasis",treeCheckable:!0,showCheckedStrategy:Qi.SHOW_PARENT,onChange:u,onSelect:console.log,maxTagCount:0,maxTagPlaceholder:()=>`${c.length} selected`})]})},v1=S.observer(({label:e,config:t,value:n,onChange:r})=>{const{treeData:i,treeDataLoading:o,errorMessage:l}=t,c=x=>{const m=x.map(j=>j.value);r(m,!1)},u=g.useMemo(()=>t.initialSelection(n),[n,t.plainData,t.defaultSelection,t.initialSelection]),d=t.min_width?t.min_width:"200px",p=!!t.options_query_id?o:!1;return s.jsx(j1,{disabled:p,style:{minWidth:"160px",width:d,maxWidth:p?d:"unset",borderColor:"#e9ecef"},value:[...u],onChange:c,treeData:i,errorMessage:l,label:e,required:t.required,treeCheckStrictly:t.treeCheckStrictly})}),w1=S.observer(({filter:{type:e,config:t,key:n,...r},formFieldProps:i})=>{switch(e){case"select":return s.jsx(h1,{...r,...i,config:t});case"multi-select":return s.jsx(d1,{...r,...i,config:t});case"tree-select":return s.jsx(v1,{...r,...i,config:t});case"text-input":return s.jsx(x1,{...r,...i,config:t});case"date-range":return s.jsx(ll,{...r,...i,config:t});case"checkbox":return s.jsx(s1,{...r,...i,config:t});default:return null}}),C1=S.observer(g.forwardRef(({filter:e,...t},n)=>s.jsx("div",{className:"filter-root",ref:n,children:s.jsx(je,{children:s.jsx(w1,{filter:e,formFieldProps:t})})}))),S1=({disabled:e})=>{const{searchButtonProps:t}=xa(),{children:n="Search",type:r,...i}=t;return s.jsx(a.Button,{color:"blue",size:"sm",type:"submit",...i,disabled:e||i.disabled,children:n})};function _1(e){const t=W();g.useEffect(()=>{var n,r;(r=(n=t.filters).updatePreviewValues)==null||r.call(n,e)},[e])}const k1=({opened:e,toggle:t})=>s.jsx(a.Group,{position:"right",ml:-4,mt:-4,mb:e?4:0,children:s.jsx(a.Button,{size:"xs",compact:!0,variant:"subtle",color:e?"gray":"blue",leftIcon:e?s.jsx(_.IconChevronsUp,{size:14}):s.jsx(_.IconChevronsDown,{size:14}),onClick:t,children:e?"Hide Filters":"Show Filters"})}),ul=S.observer(function({view:t}){const[n,{toggle:r}]=re.useDisclosure(!0),i=ce(),{control:o,handleSubmit:l,reset:c}=b.useForm({defaultValues:i.filters.values,reValidateMode:"onBlur"}),u=b.useWatch({control:o});g.useEffect(()=>{c(i.filters.values)},[i.filters.values,c]),_1(u);const d=i.filters.visibleInView(t.id),h=g.useMemo(()=>d.every(j=>j.should_auto_submit),[d]),p=g.useMemo(()=>d.filter(j=>y.get(j,"config.required",!1)),[d]),x=g.useMemo(()=>p.length===0?!1:p.some(j=>!j.requiredAndPass(u[j.key])),[u,p]);if(d.length===0)return null;const m=(j,C)=>(T,D)=>{C(T),(j.should_auto_submit||D)&&i.filters.setValueByKey(j.key,T)};return s.jsxs("form",{onSubmit:l(i.filters.setValues),children:[s.jsx(k1,{opened:n,toggle:r}),s.jsx(a.Collapse,{in:n,children:s.jsxs(a.Group,{className:"dashboard-filters",position:"apart",noWrap:!0,sx:h?{}:{border:"1px solid #e9ecef",borderRadius:"4px",padding:"16px"},children:[s.jsx(a.Group,{align:"flex-start",children:d.map(j=>s.jsx(b.Controller,{name:j.key,control:o,render:({field:C})=>s.jsx(C1,{filter:j,value:C.value,onChange:m(j,C.onChange)})},j.id))}),!h&&s.jsx(a.Group,{sx:{alignSelf:"flex-end"},children:s.jsx(S1,{disabled:x})})]})})]})}),T1={viewPanelInFullScreen:y.noop,inFullScreen:!1},Jn=g.createContext(T1),Ir=f.types.model("MockContextMeta",{current:f.types.optional(f.types.frozen(),{})}).views(e=>({get keys(){return Object.keys(e.current)},get keySet(){return new Set(this.keys)},get entries(){return Object.entries(e.current)}})).actions(e=>({replace(t){e.current=t},defaults(t){e.current={...t,...e.current}},get(t){return e.current[t]},set(t,n){e.current[t]=n}}));function Mr(e){return{current:e}}const D1=f.types.model("PanelStyleBorderMeta",{enabled:f.types.boolean}).views(e=>({get json(){const{enabled:t}=e;return{enabled:t}}})).actions(e=>({setEnabled(t){e.enabled=t}})),dl=f.types.model("PanelStyleMeta",{border:D1}).views(e=>({get json(){const{border:t}=e;return{border:t.json}}})).actions(e=>({})),pl=f.types.model("PanelTitleMeta",{show:f.types.optional(f.types.boolean,!0)}).views(e=>({get json(){const{show:t}=e;return{show:t}}})).actions(e=>({setShow(t){e.show=t}})),hl=f.types.model("VariableMeta",{name:f.types.string,size:f.types.string,weight:f.types.string,color:f.types.union(f.types.model({type:f.types.literal("static"),staticColor:f.types.string}),f.types.model({type:f.types.literal("continuous"),valueRange:f.types.array(f.types.number),colorRange:f.types.array(f.types.string)}),f.types.model({type:f.types.literal("piecewise")})),formatter:f.types.model({output:f.types.enumeration("Output",["number","percent"]),average:f.types.optional(f.types.boolean,!1),mantissa:f.types.number,trimMantissa:f.types.optional(f.types.boolean,!1),absolute:f.types.optional(f.types.boolean,!1)}),data_field:f.types.string,aggregation:f.types.union(f.types.model({type:f.types.enumeration(["none","sum","mean","median","min","max","CV","std"]),config:f.types.frozen(),fallback:f.types.optional(f.types.string,"0")}),f.types.model({type:f.types.literal("quantile"),config:f.types.model({p:f.types.number}),fallback:f.types.optional(f.types.string,"0")}),f.types.model({type:f.types.literal("custom"),config:f.types.model({func:f.types.string}),fallback:f.types.optional(f.types.string,"0")}))}).views(e=>({get json(){const{name:t,size:n,weight:r,color:i,formatter:o,data_field:l,aggregation:c}=e;return y.cloneDeep({name:t,size:n,color:i,weight:r,formatter:o,data_field:l,aggregation:c})}})),xl=f.types.model("PanelVizMeta",{type:f.types.string,conf:f.types.frozen()}).views(e=>({get json(){return{conf:e.conf,type:e.type}}})).actions(e=>({setType(t){e.type=t},setConf(t){e.conf=t}})),fl=f.types.model({id:f.types.string,name:f.types.optional(f.types.string,""),title:pl,description:f.types.string,queryIDs:f.types.array(f.types.string),viz:xl,style:dl,variables:f.types.optional(f.types.array(hl),[])}).views(e=>({get json(){const{id:t,name:n,title:r,description:i,queryIDs:o}=e;return{id:t,viz:e.viz.json,name:n,style:e.style.json,title:r.json,queryIDs:[...o],variables:e.variables.map(l=>l.json),description:i}},get queryIDSet(){return new Set(e.queryIDs)}})).actions(e=>({setID(t){e.id=t},setName(t){e.name=t},setDescription(t){e.description=t},addQueryID(t){e.queryIDSet.has(t)||e.queryIDs.push(t)},removeQueryID(t){if(!e.queryIDSet.has(t))return;const n=new Set(e.queryIDSet);n.delete(t),e.queryIDs=f.cast(Array.from(n))},setQueryIDs(t){e.queryIDs=f.cast(t)},addVariable(t){e.variables.push(t)},removeVariable(t){e.variables.remove(t)}}));var oe=(e=>(e.Postgresql="postgresql",e.MySQL="mysql",e.HTTP="http",e.Transform="transform",e))(oe||{});const gl=f.types.model("QueryMeta",{id:f.types.string,name:f.types.string,type:f.types.enumeration("DataSourceType",[oe.Postgresql,oe.MySQL,oe.HTTP,oe.Transform]),key:f.types.string,sql:f.types.string,pre_process:f.types.optional(f.types.string,""),post_process:f.types.optional(f.types.string,""),run_by:f.types.optional(f.types.array(f.types.string),[]),react_to:f.types.optional(f.types.array(f.types.string),[]),dep_query_ids:f.types.optional(f.types.array(f.types.string),[])}).views(e=>({get valid(){return e.id&&e.type&&e.key&&e.name?e.type===oe.HTTP?!!e.pre_process:!!e.sql:!1},get json(){const{id:t,name:n,type:r,key:i,sql:o,run_by:l,react_to:c,pre_process:u,post_process:d,dep_query_ids:h}=e;return At({id:t,key:i,sql:o,name:n,type:r,run_by:l,react_to:c,pre_process:u,post_process:d,dep_query_ids:h})}})).actions(e=>({setName(t){e.name=t},setKey(t){e.key=t},setType(t){e.type=t},setSQL(t){e.sql=t},setRunBy(t){e.run_by.length=0,e.run_by.push(...t)},setReactTo(t){e.react_to.length=0,e.react_to.push(...t)},setPreProcess(t){e.pre_process=t},setPostProcess(t){e.post_process=t},setDependantQueryIDs(t){e.dep_query_ids.length=0,e.dep_query_ids.push(...t)}})),ml=f.types.model("LayoutItemMeta",{id:f.types.identifier,panelID:f.types.string,x:f.types.number,y:f.types.maybeNull(f.types.number),w:f.types.number,h:f.types.number,moved:f.types.optional(f.types.boolean,!1),static:f.types.optional(f.types.boolean,!1)}).views(e=>({get json(){const{id:t,panelID:n,x:r,y:i,w:o,h:l,moved:c}=e;return{h:l,w:o,x:r,y:i===null?0:i,id:t,moved:c,static:e.static,panelID:n}},get contentModel(){return f.getRoot(e).content},get panel(){const{panelID:t}=e;return this.contentModel.panels.findByID(t)},get layoutProperies(){const{id:t,x:n,y:r,w:i,h:o,moved:l}=e;return{id:t,i:t,x:n,y:r===null?1/0:r,w:i,h:o,moved:l,static:e.static}}})).actions(e=>({set(t){const{isDraggable:n,x:r,y:i,w:o,h:l,moved:c}=t;e.x=r,e.y=i,e.w=o,e.h=l,e.moved=!!c,e.static=!!t.static},setWidth(t){e.w=t},setHeight(t){e.h=t}})),yl=f.types.model("LayoutSetMeta",{id:f.types.identifier,name:f.types.string,breakpoint:f.types.number,list:f.types.optional(f.types.array(ml),[])}).views(e=>({get json(){const{id:t,name:n,breakpoint:r,list:i}=e;return{id:t,name:n,breakpoint:r,list:i.map(o=>At(o.json))}},jsonByPanelIDSet(t){const{id:n,name:r,breakpoint:i,list:o}=e;return{id:n,name:r,breakpoint:i,list:o.filter(l=>t.has(l.panelID)).map(l=>At(l.json))}},findByID(t){return e.list.find(n=>n.id===t)},findByPanelID(t){return e.list.find(n=>n.panelID===t)}})).actions(e=>({setName(t){e.name=t},setBreakpoint(t){e.breakpoint=t},addLayout(t){e.list.push(t)},addNewLayout(t){e.list.push({id:pt.v4(),panelID:t,x:0,y:1/0,w:18,h:300,static:!1,moved:!1})},removeByPanelID(t){const n=e.list.findIndex(r=>r.panelID===t);n>=0&&e.list.splice(n,1)},updateLayoutItem(t){const n=e.list.find(r=>r.id===t.i);if(!n){console.error("Trying to update a layout that doesn't exist"),console.log({strangeLayoutItem:t});return}n.set(t)}})),bl=f.types.model("SQLSnippetMeta",{key:f.types.string,value:f.types.string}).views(e=>({get json(){const{key:t,value:n}=e;return{key:t,value:n}}})).actions(e=>({setKey(t){e.key=t},setValue(t){e.value=t}}));var de=(e=>(e.Select="select",e.MultiSelect="multi-select",e.TreeSelect="tree-select",e.TextInput="text-input",e.Checkbox="checkbox",e.DateRange="date-range",e))(de||{});const zr=f.types.model("FilterCheckboxConfigMeta",{_name:f.types.literal("checkbox"),description:f.types.optional(f.types.string,""),default_value:f.types.boolean}).views(e=>({get json(){const{_name:t,description:n,default_value:r}=e;return{_name:t,description:n,default_value:r}},get isDescriptionEmpty(){const{description:t}=e;return t===""||t==="<p></p>"}})).actions(e=>({setDefaultValue(t){e.default_value=t},setDescription(t){e.description=t}})),jl=()=>zr.create({_name:"checkbox",description:"",default_value:!1});function vl(e,t){return e.map(n=>{try{return n?M.tz(n,"UTC").format(t):null}catch{return console.log(`[date-range] failed parsing ${n}`),null}})}const I1=f.types.model("FilterDateRangeConfigMeta",{_name:f.types.literal("date-range"),required:f.types.boolean,inputFormat:f.types.enumeration("DateRangeInputFormat",["YYYY","YYYYMM","YYYYMMDD","YYYY-MM","YYYY-MM-DD"]),default_value:f.types.optional(f.types.array(f.types.union(f.types.string,f.types.null)),[null,null]),default_shortcut:f.types.optional(f.types.string,""),clearable:f.types.boolean,max_days:f.types.optional(f.types.number,0),allowSingleDateInRange:f.types.optional(f.types.boolean,!1)}).views(e=>({get json(){const{_name:t,max_days:n,required:r,clearable:i,inputFormat:o,default_value:l,default_shortcut:c,allowSingleDateInRange:u}=e;return{_name:t,max_days:n,required:r,clearable:i,inputFormat:o,default_value:vl(l,o),default_shortcut:c,allowSingleDateInRange:u}},truthy(t){return Array.isArray(t)&&t.length===2&&t.every(n=>!!n)}})).actions(e=>({setFilterValue(t){try{const n=f.getParent(e);f.getParent(n,2).setValueByKey(n.key,t)}catch(n){console.error(n)}}})).actions(e=>({setRequired(t){e.required=t},setClearable(t){e.clearable=t},setInputFormat(t){e.inputFormat=t},setDefaultValue(t){e.default_value.length=0,e.default_value.push(...t),e.setFilterValue(t)},setDefaultShortcut(t){if(e.default_shortcut=t,!t)return;const n=al(e.default_shortcut);if(console.log(n),n){const r=n.map(i=>M(i).format(e.inputFormat));e.setFilterValue(r)}},setMaxDays(t){e.max_days=t,t>0&&(e.clearable=!0)},setAllowSingleDateInRange(t){e.allowSingleDateInRange=t}})),Ar=f.types.snapshotProcessor(I1,{preProcessor({default_value:e,...t}){return{...t,default_value:e.map(n=>n===null?null:M.tz(n,"UTC").toISOString())}},postProcessor(e){const{default_value:t,...n}=e;return{...n,default_value:vl(t,n.inputFormat)}}}),wl=()=>Ar.create({_name:"date-range",required:!1,inputFormat:"YYYY-MM-DD",clearable:!1,default_value:[null,null]}),M1=f.types.model({label:f.types.string,value:f.types.string}).actions(e=>({setLabel(t){e.label=t},setValue(t){e.value=t}})),Er=f.types.model("FilterConfigModel_BaseSelect",{static_options:f.types.optional(f.types.array(M1),[]),options_query_id:f.types.optional(f.types.string,""),default_selection_count:f.types.optional(f.types.number,0),required:f.types.optional(f.types.boolean,!1)}).views(e=>({get contentModel(){return f.getRoot(e).content},get filter(){return f.getParent(e)},get usingQuery(){return!!e.options_query_id}})).views(e=>({get options(){if(!e.usingQuery)return e.static_options;const{data:t,state:n}=e.contentModel.getDataStuffByID(e.options_query_id);return n==="error"?[]:Array.isArray(t)?t:[]}})).actions(e=>({setRequired(t){e.required=t},addStaticOption(t){e.static_options.push(t)},removeStaticOption(t){e.static_options.splice(t,1)},setDefaultSelectionCount(t){e.default_selection_count=t},setOptionsQueryID(t){e.options_query_id=t??""}})),Pr=f.types.compose("FilterMultiSelectConfigMeta",f.types.model({_name:f.types.literal("multi-select"),min_width:f.types.optional(f.types.string,""),default_value:f.types.optional(f.types.array(f.types.string),[])}),Er).views(e=>({get json(){const{_name:t,default_value:n,required:r,min_width:i,static_options:o,options_query_id:l,default_selection_count:c}=e;return At({_name:t,required:!!r,min_width:i,default_value:n,static_options:o,options_query_id:l,default_selection_count:c})},get default_selection(){return e.usingQuery?e.options.slice(0,e.default_selection_count).map(t=>t.value):e.filter.formattedDefaultValue},truthy(t){return Array.isArray(t)&&t.length>0}})).actions(e=>({setDefaultValue(t){e.default_value=f.cast(t)},setMinWidth(t){e.min_width=t},setDefaultSelection(){const t=f.getRoot(e).content.filters,n=f.getParent(e).key,r=new Set(e.options.map(o=>o.value)),i=(t.values[n]??[]).filter(o=>r.has(o));i.length>0?t.setValueByKey(n,i):t.setValueByKey(n,e.default_selection)}})).actions(e=>({afterCreate(){f.addDisposer(e,U.reaction(()=>U.toJS(e.default_selection),e.setDefaultSelection,{fireImmediately:!0,delay:0}))}})),Cl=()=>Pr.create({_name:"multi-select",default_value:[],static_options:[],options_query_id:"",default_selection_count:0}),Lr=f.types.compose("FilterConfigModel_Select",f.types.model({_name:f.types.literal("select"),default_value:f.types.string,width:f.types.optional(f.types.string,"")}),Er).views(e=>({get json(){const{_name:t,default_value:n,required:r,width:i,static_options:o,options_query_id:l,default_selection_count:c}=e;return At({_name:t,width:i,required:r,default_value:n,static_options:o,options_query_id:l,default_selection_count:c})},truthy(t){return!!t},getSelectOption(t){return e.options.find(n=>n.value===t)},get default_selection(){return e.usingQuery?e.default_selection_count>0&&e.options.length>0?e.options[0].value:"":e.filter.formattedDefaultValue}})).actions(e=>({setDefaultValue(t){e.default_value=t},setWidth(t){e.width=t},setDefaultSelection(){var o;const t=f.getRoot(e).content.filters,n=f.getParent(e).key,r=t.values[n],i=(o=e.options.find(l=>l.value===r))==null?void 0:o.value;i?t.setValueByKey(n,i):t.setValueByKey(n,e.default_selection)}})).actions(e=>({afterCreate(){f.addDisposer(e,U.reaction(()=>U.toJS(e.default_selection),e.setDefaultSelection,{fireImmediately:!0,delay:0}))}})),Sl=()=>Lr.create({_name:"select",required:!1,default_value:"",static_options:[],options_query_id:"",default_selection_count:0}),Br=f.types.model("FilterTextInputConfigMeta",{_name:f.types.literal("text-input"),required:f.types.boolean,default_value:f.types.string}).views(e=>({get json(){const{_name:t,required:n,default_value:r}=e;return{_name:t,required:n,default_value:r}},truthy(t){return typeof t!="string"?!1:!!t.trim()}})).actions(e=>({setRequired(t){e.required=t},setDefaultValue(t){e.default_value=t}})),Or=()=>Br.create({_name:"text-input",required:!1,default_value:""});function z1(e){return fu.arrayToTree(e,{id:"value",parentId:"parent_value",childrenField:"children",dataField:null})}function A1(e){return e.map(t=>{const{label:n,description:r,...i}=t,o={...i,filterBasis:`${n}___${r??""}`,description:r,label:n};return r&&(o.label=g.createElement("div",{},[g.createElement(a.Text,{key:0,title:t.label},t.label),g.createElement(a.Text,{key:1,className:"rc-tree-select-tree-title-desc",color:"dimmed",title:t.description},t.description)])),o})}const $r=f.types.compose("FilterTreeSelectConfigMeta",f.types.model({_name:f.types.literal("tree-select"),min_width:f.types.optional(f.types.string,""),default_value:f.types.optional(f.types.array(f.types.string),[]),treeCheckStrictly:f.types.optional(f.types.boolean,!1)}),Er).views(e=>({get json(){const{_name:t,default_value:n,required:r,min_width:i,static_options:o,options_query_id:l,default_selection_count:c,treeCheckStrictly:u}=e;return{_name:t,required:!!r,min_width:i,default_value:n,static_options:o,options_query_id:l,treeCheckStrictly:u,default_selection_count:c}},get plainData(){const{data:t}=e.contentModel.getDataStuffByID(e.options_query_id);return t},get treeData(){const t=this.plainData,n=A1(t);return z1(n)},get errorMessage(){const{error:t}=e.contentModel.getDataStuffByID(e.options_query_id);return t},get treeDataLoading(){const{state:t}=e.contentModel.getDataStuffByID(e.options_query_id);return t==="loading"},get defaultSelection(){const t=e.filter.formattedDefaultValue;if(Array.isArray(t)&&t.length>0)return t;const{default_selection_count:n}=e;return n?this.treeData.slice(0,n).map(i=>i.value):[]},valueObjects(t){const n=new Set(t);return this.plainData.filter(r=>n.has(r.value))},initialSelection(t){return!t||t.length===0?this.valueObjects(this.defaultSelection):this.valueObjects(t)},truthy(t){return Array.isArray(t)&&t.length>0}})).actions(e=>({setDefaultValue(t){e.default_value=f.cast(t)},setMinWidth(t){e.min_width=t},setTreeCheckStrictly(t){e.treeCheckStrictly=t},applyDefaultSelection(){const t=f.getParent(e,1).key;e.contentModel.filters.setValueByKey(t,e.defaultSelection)},afterCreate(){f.addDisposer(e,U.reaction(()=>JSON.stringify(e.defaultSelection),this.applyDefaultSelection,{fireImmediately:!0,delay:0}))}})),_l=()=>$r.create({_name:"tree-select",default_value:[],static_options:[],options_query_id:"",default_selection_count:0}),Vr=f.types.model("FilterMeta",{id:f.types.identifier,key:f.types.string,label:f.types.string,order:f.types.number,visibleInViewsIDs:f.types.array(f.types.string),auto_submit:f.types.optional(f.types.boolean,!1),default_value_func:f.types.optional(f.types.string,""),type:f.types.enumeration("DashboardFilterType",[de.Select,de.MultiSelect,de.TreeSelect,de.TextInput,de.Checkbox,de.DateRange]),config:f.types.union(Lr,Pr,$r,Br,zr,Ar)}).views(e=>({get contentModel(){return f.getRoot(e).content},get filters(){return this.contentModel.filters},get plainDefaultValue(){const t=e.config.default_value;return Array.isArray(t)?[...t]:t},get usingDefaultValue(){return e.type!==de.TreeSelect},get usingDefaultValueFunc(){return!!e.default_value_func},get formattedDefaultValue(){return this.filters.formattedDefaultValues[e.key]},get auto_submit_supported(){return[de.Select,de.Checkbox,de.DateRange].includes(e.type)}})).views(e=>({get json(){const{id:t,key:n,label:r,order:i,visibleInViewsIDs:o,default_value_func:l,auto_submit:c,type:u,config:d}=e;return{id:t,key:n,type:u,label:r,order:i,config:d.json,auto_submit:c,visibleInViewsIDs:U.toJS(o),default_value_func:l}},get visibleInViewsIDSet(){return new Set(e.visibleInViewsIDs)},get should_auto_submit(){return e.auto_submit_supported&&e.auto_submit},requiredAndPass(t){return y.get(e.config,"required",!1)?y.get(e.config,"truthy",()=>!0)(t):!1}})).actions(e=>({setKey(t){e.key=t},setLabel(t){e.label=t},setOrder(t){e.order=t},setType(t){switch(t){case de.Select:e.config=Sl();break;case de.MultiSelect:e.config=Cl();break;case de.TreeSelect:e.config=_l();break;case de.TextInput:e.config=Or();break;case de.Checkbox:e.config=jl();break;case de.DateRange:e.config=wl();break}e.type=t},setVisibleInViewsIDs(t){e.visibleInViewsIDs.length=0,e.visibleInViewsIDs.push(...t)},setAutoSubmit(t){e.auto_submit=e.auto_submit_supported&&t},setDefaultValueFunc(t){e.default_value_func=t}}));var L=(e=>(e.Division="div",e.Modal="modal",e.Tabs="tabs",e))(L||{});const qr=f.types.model("ViewDivisionConfig",{_name:f.types.literal(L.Division)}).views(e=>({get json(){const{_name:t}=e;return{_name:t}}})),kl=()=>qr.create({_name:L.Division}),E1=f.types.model("CustomModalTitleModel",{enabled:f.types.optional(f.types.boolean,!1),func_content:f.types.optional(f.types.string,"")}).views(e=>({get json(){const{enabled:t,func_content:n}=e;return{enabled:t,func_content:n}},get value(){const{enabled:t,func_content:n}=e,r=f.getParent(e,2),i=f.getRoot(e);if(!t)return r.name;try{const o={filters:i.content.filters.values,context:i.context.current};return new Function(`return ${n}`)()(o)}catch(o){return console.error(o),r.name}}})).actions(e=>({setEnabled(t){e.enabled=t},setFuncContent(t){e.func_content=t},replace({enabled:t,func_content:n}){e.enabled=t,e.func_content=n}})),Zn={enabled:!1,func_content:["function text({ filters, context}) {"," // your code goes here",' return "text"',"}"].join(`
|
|
450
|
+
`)},Nr=f.types.model("ViewModalConfig",{_name:f.types.literal(L.Modal),width:f.types.string,height:f.types.string,custom_modal_title:f.types.optional(E1,Zn)}).views(e=>({get json(){const{_name:t,width:n,height:r,custom_modal_title:i}=e;return{_name:t,width:n,height:r,custom_modal_title:i.json}}})).actions(e=>({setWidth(t){e.width=t},setHeight(t){e.height=t}})),Tl=()=>Nr.create({_name:L.Modal,width:"90vw",height:"90vh"}),P1=f.types.model("ViewTabsTabModel",{id:f.types.identifier,name:f.types.string,view_id:f.types.string,color:f.types.optional(f.types.string,""),order:f.types.optional(f.types.number,0)}).views(e=>({get json(){const{id:t,name:n,view_id:r,color:i,order:o}=e;return{id:t,name:n,color:i,order:o,view_id:r}}})).actions(e=>({setName(t){e.name=t},setViewID(t){e.view_id=t},setColor(t){e.color=t},setOrder(t){e.order=t}})),Fr=f.types.model("ViewTabsConfig",{_name:f.types.literal(L.Modal),tabs:f.types.optional(f.types.array(P1),[]),variant:f.types.optional(f.types.enumeration("variant",["default","outline","pills"]),"default"),orientation:f.types.optional(f.types.enumeration("orientation",["horizontal","vertical"]),"horizontal"),grow:f.types.optional(f.types.boolean,!1)}).views(e=>({get json(){const{_name:t,variant:n,orientation:r,tabs:i,grow:o}=e;return{grow:o,tabs:i.map(l=>l.json),_name:t,variant:n,orientation:r}},get tabsInOrder(){return y.sortBy(e.tabs,"order")}})).actions(e=>({setVariant(t){e.variant=t},setOrientation(t){e.orientation=t},setGrow(t){e.grow=t},setTabs(t){e.tabs.length=0,e.tabs=f.cast(t)},addTab(){const t=re.randomId(),n={id:t,name:t,view_id:""};e.tabs.push(n)},removeTab(t){e.tabs.splice(t,1)}})),Dl=()=>Fr.create({_name:L.Modal,tabs:[]}),Il=f.types.model({id:f.types.identifier,name:f.types.string,type:f.types.enumeration("EViewComponentType",[L.Division,L.Modal,L.Tabs]),config:f.types.union(qr,Nr,Fr),panelIDs:f.types.optional(f.types.array(f.types.string),[])}).views(e=>({get json(){const{id:t,name:n,type:r,config:i}=e;return{id:t,name:n,type:r,config:i.json,panelIDs:e.panelIDs.map(o=>o)}}})).actions(e=>({setName(t){e.name=t},setType(t){if(e.type!==t){switch(t){case L.Division:e.config=kl();break;case L.Modal:e.config=Tl();break;case L.Tabs:e.config=Dl();break}e.type=t}},appendPanelID(t){e.panelIDs.push(t)},appendPanelIDs(t){e.panelIDs.push(...t)},removePanelID(t){const n=e.panelIDs.filter(r=>r!==t);e.panelIDs.length=0,e.panelIDs.push(...n)}})),at="11.10.0",L1={definition:{sqlSnippets:[],queries:[],mock_context:{}},views:[{id:"Main",name:"Main",type:L.Division,config:{},panelIDs:[]}],panels:[],filters:[],version:at,layouts:[{id:"basis",name:"basis",list:[],breakpoint:0}]},Gr=f.types.model("DataSourceMetaModel",{id:f.types.string,type:f.types.enumeration("DataSourceType",[oe.HTTP,oe.MySQL,oe.Postgresql]),key:f.types.string,config:f.types.frozen()}),Ml=f.types.model("DataSourcesMetaModel",{list:f.types.optional(f.types.array(Gr),[])}).views(e=>({find({type:t,key:n}){return e.list.find(r=>r.key===n&&r.type===t)},get options(){return e.list.map(t=>({value:t.key,label:t.key}))}})).actions(e=>({replace(t){e.list.length=0,e.list.push(...t)}})),zl=f.types.model({id:f.types.string,content:f.types.string,create_time:f.types.string,update_time:f.types.string,is_preset:f.types.boolean}),Wr=f.types.model("GlobalSQLSnippetsMeta",{list:f.types.optional(f.types.array(zl),[])}).views(e=>({find(t){return e.list.find(n=>n.id===t)},get options(){return e.list.map(t=>({value:t.id,label:t.id}))}})).actions(e=>({replace(t){e.list.length=0,e.list.push(...t)}})),Hn=f.types.model("ContextMeta",{current:f.types.optional(f.types.frozen(),{})}).views(e=>({get keys(){return Object.keys(e.current)},get entries(){return Object.entries(e.current)}})).actions(e=>({replace(t){e.current=t},get(t){return e.current[t]},set(t,n){e.current[t]=n}}));function Rr(e){return Hn.create({current:e})}const Qr=f.types.compose("ViewRenderModel",Il,f.types.model({tab:f.types.optional(f.types.string,"")})).views(e=>({get defaultTab(){if(e.type!==L.Tabs)return"";const t=e.config;return t.tabs.length>0?t.tabs[0].id:""},get tabViewID(){var n;return e.type!==L.Tabs?"":((n=e.config.tabs.find(r=>r.id===e.tab))==null?void 0:n.view_id)??""},get contentModel(){return f.getParent(e,3)},get panels(){if(e.type!==L.Tabs)return this.contentModel.panels.panelsByIDs(e.panelIDs);const t=this.tabViewID,n=this.contentModel.views.findByID(t);return(n==null?void 0:n.panels)??[]},get renderViewIDs(){const t=[e.id];return e.type===L.Tabs&&t.push(this.tabViewID),t},async downloadScreenshot(t){const n=t.offsetWidth*2+10,r=t.offsetHeight*2+10,i=new Ki,o=new Date().getTime(),l=await Ui.toBlob(t,{bgcolor:"white",width:n,height:r,style:{transformOrigin:"0 0",transform:"scale(2)"}});i.file(`${e.name}_${o}.png`,l),i.file(`dashboard_state_${o}.json`,JSON.stringify(this.contentModel.dashboardState,null,4)),i.generateAsync({type:"blob"}).then(c=>{gn.saveAs(c,`${e.name}_${o}.zip`)}).catch(c=>{console.error(c),ut.notifications.show({color:"red",title:"Failed to download screenshot with dashboard state",message:c.message})})}})).actions(e=>({setTab(t){e.tab=t??""},afterCreate(){f.addDisposer(e,U.reaction(()=>e.defaultTab,t=>this.setTab(t),{fireImmediately:!0,delay:0}))}})),Ur=f.types.model("ViewsRenderModel",{current:f.types.optional(f.types.array(Qr),[]),visibleViewIDs:f.types.array(f.types.string)}).views(e=>({get json(){return e.current.map(t=>At(t.json))},get idMap(){const t=new Map;return e.current.forEach(n=>{t.set(n.id,n)}),t},findByID(t){return e.current.find(n=>n.id===t)},get firstVisibleView(){const[t]=e.visibleViewIDs;return e.current.find(({id:n})=>n===t)},get visibleViews(){const t=new Set(e.visibleViewIDs);return e.current.filter(({id:n})=>t.has(n))}})).actions(e=>({appendToVisibles(t){new Set(e.visibleViewIDs.map(r=>r)).has(t)||e.visibleViewIDs.push(t)},rmVisibleViewID(t){const n=e.visibleViewIDs.findIndex(r=>r===t);n!==-1&&e.visibleViewIDs.splice(n,1)}}));function Al(e){const t=e.length>0?[e[0].id]:[];return{current:e.map(r=>{const{_name:i=r.type}=r.config;return{...r,config:{...r.config,_name:i},panelIDs:r.panelIDs}}),visibleViewIDs:t}}const B1=new gu.AsyncParser({withBOM:!0});async function El(e){return!Array.isArray(e)||e.length===0?"":await B1.parse(e).promise()}async function O1(e,t){const n=await El(t),r=new Blob([n],{type:"text/csv"});gn.saveAs(r,`${e}.csv`)}function Pl(e){const t=new Ki,n=e.map(async({id:r,data:i})=>{const o=await El(i);t.file(`${r}.csv`,o)});Promise.all(n).then(()=>{t.generateAsync({type:"blob"}).then(r=>{gn.saveAs(r,"dashboard_data.zip")})}).catch(r=>{console.error(r),ut.notifications.show({color:"red",title:"Failed to download data",message:r.message})})}function Nt(e,t){const n=new Blob([t],{type:"application/json"});gn.saveAs(n,`${e}.json`)}const Kr=fl.views(e=>({get contentModel(){return f.getRoot(e).content}})).views(e=>({get queries(){return e.contentModel.queries.findByIDSet(e.queryIDSet)},queryByID(t){return this.queries.find(n=>n.id===t)},get data(){return this.queries.reduce((t,n)=>(t[n.id]=n.data,t),{})},get variableStrings(){return na(e.variables,this.data)},get dataLoading(){return this.queries.some(t=>t.state==="loading")},get queryStateMessages(){const t=this.queries.filter(o=>!o.runByConditionsMet);if(t.length===0)return"";const n=new Set,r=new Set;t.forEach(o=>{const l=o.conditionNames;l.context.forEach(c=>n.add(c)),l.filters.forEach(c=>r.add(c))});const i=[];return n.size>0&&(console.log(n),i.push(`context: ${Array.from(n).join(", ")}`)),r.size>0&&i.push(`filter${r.size>1?"s":""}: ${Array.from(r).join(", ")}`),i.length===2&&i.splice(1,0,"and"),i.unshift("Waiting for"),i.join(" ")},get queryErrors(){return this.queries.map(t=>t.error).filter(t=>!!t)},get canRenderViz(){return this.queryErrors.length===0&&this.queryStateMessages===""&&!this.dataLoading}})).actions(e=>({refreshData(){e.queries.forEach(t=>t.fetchData(!0))},downloadData(){e.contentModel.queries.downloadDataByQueryIDs(e.queryIDs)},getSchema(){const t=e.json;return t.viz.conf={...t.viz.conf,__INTERACTIONS:{},__OPERATIONS:{},__TRIGGERS:{}},{panel:t,queries:e.queries.map(n=>n.json),layouts:e.contentModel.layouts.jsonByPanelIDSet(new Set([e.id]))}},downloadSchema(){const{panel:t,queries:n,layouts:r}=this.getSchema(),o=JSON.stringify({panels:[t],definition:{queries:n},layouts:r,version:at},null,2),l=e.name;Nt(l,o)}}));function Ll(e){return{id:e,name:e,title:{show:!0},description:"<p></p>",queryIDs:[],viz:{type:gr.name,conf:gr.createConfig()},style:{border:{enabled:!0}}}}const Yr=f.types.model("PanelsRenderModel",{list:f.types.optional(f.types.array(Kr),[])}).views(e=>({get json(){return e.list.map(t=>t.json)},findByID(t){return e.list.find(n=>n.id===t)},get idMap(){const t=new Map;return e.list.forEach(n=>{t.set(n.id,n)}),t}})).views(e=>({panelsByIDs(t){const n=[];return t.forEach(r=>{const i=e.idMap.get(r);i?n.push(i):console.warn(`Panel is not found, id:${r}`)}),n}}));function Bl(e){const t=e.config,n=t.default_value;if(n===void 0)return n;if(t._name==="date-range")try{if(t.default_shortcut){const i=al(t.default_shortcut);if(i)return i.map(o=>M(o).format(t.inputFormat))}const[...r]=n;return r.map(i=>i===null?i:M.tz(i,"UTC").format(t.inputFormat)??i)}catch(r){return console.error(r),n}return n}function $1(e,t){const n=e.default_value_func;try{return new Function(`return ${n}`)()(e,nt,t)}catch(r){return console.error(r),Bl(e)}}function Ol(e,t){var n;return(n=e.default_value_func)!=null&&n.trim()?$1(e,t):Bl(e)}function $l(e,t){return e.reduce((n,r)=>(n[r.key]=Ol(r,t),n),{})}const Xr=f.types.model("FiltersRenderModel",{current:f.types.optional(f.types.array(Vr),[]),values:f.types.optional(f.types.frozen(),{})}).views(e=>({get json(){return e.current.map(t=>t.json)},get contentModel(){return f.getRoot(e).content},get context(){return this.contentModel.payloadForSQL.context},get initialValuesDep(){return JSON.stringify({filters:e.current.map(({default_value_func:t,config:n})=>({default_value_func:t,config:n})),context:this.contentModel.payloadForSQL.context})},get formattedDefaultValues(){return $l(this.json,this.contentModel.context)},get firstID(){if(e.current.length!==0)return e.current[0].id},findByID(t){return e.current.find(n=>n.id===t)},findByIDSet(t){return e.current.filter(n=>t.has(n.id))},get inOrder(){return y.sortBy(e.current,"order")},get empty(){return e.current.length===0},visibleInView(t){return y.sortBy(e.current.filter(n=>n.visibleInViewsIDSet.has(t)),"order")},get firstFilterValueKey(){return Object.keys(e.values)[0]??""},get keySet(){return new Set(e.current.map(t=>t.key))},get keyLabelMap(){return e.current.reduce((t,n)=>(t[n.key]=n.label,t),{})},getSelectOption(t){const n=this.findByID(t);if(!n||!("getSelectOption"in n.config))return null;const r=e.values[n.key];return n.config.getSelectOption(r)}})).actions(e=>({setValues(t){e.values=t},patchValues(t){e.values=y.defaults({},t,e.values)},setValueByKey(t,n){e.values={...e.values,[t]:n}},getValueByKey(t){return e.values[t]},getSchema(t,n){return{filters:e.findByIDSet(new Set(t)).map(o=>({...o.json,visibleInViewsIDs:n?o.json.visibleInViewsIDs:[]})),version:at}},downloadSchema(t){const n=JSON.stringify(this.getSchema(t,!1),null,2);Nt("Filters",n)}}));function Jr(e,t,n,r){const i=y.defaults({},r,$l(e,{...n,...t}));return{current:e,values:i}}const Vl=gl.views(e=>({get rootModel(){return f.getRoot(e)},get contentModel(){return this.rootModel.content},get conditionOptions(){if(!f.isAlive(e))return[];const{context:t}=this.contentModel.payloadForSQL,n=Object.keys(t).map(l=>({group:"Context",label:l,value:`context.${l}`,description:void 0})),r=this.contentModel.filters.keyLabelOptions.map(l=>({group:"Filters",label:l.label,value:`filters.${l.value}`,description:l.value})),i=[...n,...r],o=new Set(i.map(l=>l.value));return e.run_by.forEach(l=>{o.has(l)||i.push({group:"Invalid",label:l,value:l})}),i},get unmetRunByConditions(){if(!f.isAlive(e))return[];const{run_by:t}=e;if(t.length===0)return[];const n=this.contentModel.payloadForSQL;return t.filter(r=>{const i=y.get(n,r);return Array.isArray(i)?i.length===0:typeof i=="number"?Number.isNaN(i):!i})}})).views(e=>({get payload(){return e.contentModel.payloadForSQL},get formattedSQL(){return xs(e.sql,this.payload)},get httpConfigString(){const{context:t,filters:n}=this.payload,{name:r,pre_process:i}=e.json,o=_d(i,t,n);return console.groupCollapsed(`Request config for: ${r}`),console.log(o),console.groupEnd(),JSON.stringify(o)},get typedAsSQL(){return[oe.Postgresql,oe.MySQL].includes(e.type)},get typedAsHTTP(){return[oe.HTTP].includes(e.type)},get isTransform(){return e.type===oe.Transform},get reQueryKey(){const{react_to:t=[]}=e;if(t.length===0)return"";const n=e.contentModel.payloadForSQL,r=[...t].reduce((i,o)=>(i[o]=y.get(n,o),i),{});return JSON.stringify(r)},get runByConditionsMet(){return e.unmetRunByConditions.length===0},get conditionNames(){if(e.unmetRunByConditions.length===0)return{context:[],filters:[]};const{keyLabelMap:t}=e.contentModel.filters,n=e.unmetRunByConditions.filter(i=>i.startsWith("context.")).map(i=>i.replace("context.","")),r=e.unmetRunByConditions.filter(i=>i.startsWith("filters.")).map(i=>y.get({filters:t},i,i.replace("filters.",""))).filter(i=>!!i);return{context:n,filters:r}},get queries(){return f.getParent(e,2)},get inUse(){return this.queries.isQueryInUse(e.id)},get dependencies(){if(!this.typedAsSQL)return[];const t=y.uniq(e.sql.match(jn.sqlSnippet)),n=y.uniq(e.sql.match(jn.filter)),r=y.uniq(e.sql.match(jn.context)),i=[];return t.forEach(o=>{i.push({type:"SQL Snippet",key:o,valid:e.contentModel.sqlSnippets.keySet.has(o)})}),n.forEach(o=>{i.push({type:"Filter",key:o,valid:e.contentModel.filters.keySet.has(o)})}),r.forEach(o=>{i.push({type:"Context",key:o,valid:e.contentModel.mock_context.keySet.has(o)})}),i}})),Zr=f.types.compose("QueryRenderModel",Vl,f.types.model({state:f.types.optional(f.types.enumeration(["idle","loading","error"]),"idle"),data:f.types.optional(f.types.frozen([]),[]),error:f.types.frozen()})).views(e=>({get datasource(){const{key:t,type:n}=e;return e.rootModel.datasources.find({type:n,key:t})},get additionalQueryInfo(){return e.contentModel.getAdditionalQueryInfo(e.id)},get depQueryModels(){return e.contentModel.queries.findByIDSet(new Set(e.dep_query_ids))},get depQueryModelStates(){return this.depQueryModels.map(t=>t.state)},get depQueryModelStatesString(){return this.depQueryModelStates.toString()}})).views(e=>({get stateMessage(){if(e.state!=="idle")return"";if(!e.runByConditionsMet){const{context:t,filters:n}=e.conditionNames;if(t.length===0&&n.length===0)return"Waiting";const r=[];return t.length>0&&r.push(`context: ${t.join(", ")}`),n.length>0&&r.push(`filter${n.length>1?"s":""}: ${n.join(", ")}`),r.length===2&&r.splice(1,0,"and"),r.unshift("Waiting for"),r.join(" ")}return e.data.length>0?"":"Empty Data"}})).volatile(()=>({controller:new AbortController})).actions(e=>({runSQL:f.flow(function*(){var t;if(e.valid&&((t=e.controller)==null||t.abort(),!!e.runByConditionsMet)){e.controller=new AbortController,e.state="loading";try{const n=e.payload;e.data=yield*f.toGenerator(Md({payload:n,name:e.name,query:e.json,additionals:e.additionalQueryInfo},e.controller.signal)),e.state="idle",e.error=null}catch(n){if(!He.isCancel(n)){e.data=[];const r=y.get(n,"message","unkown error");e.error=y.get(n,"response.data.detail.message",r),e.state="error"}}}}),runHTTP:f.flow(function*(){var t;if(!(!e.valid||!e.datasource)&&((t=e.controller)==null||t.abort(),!!e.runByConditionsMet)){e.controller=new AbortController,e.state="loading";try{const{type:n,key:r,post_process:i}=e.json;let o=JSON.parse(e.httpConfigString);o=kd(e.datasource,o);const l=yield*f.toGenerator(zd({type:n,key:r,configString:JSON.stringify(o),name:e.name,additionals:e.additionalQueryInfo},e.controller.signal)),c=Td(e.datasource,l),u=Dd(i,c,e.contentModel.dashboardState);e.data=u,e.state="idle",e.error=null}catch(n){if(console.error(n),!He.isCancel(n)){e.data=[];const r=y.get(n,"message","unkown error");e.error=y.get(n,"response.data.detail.message",r),e.state="error"}}}}),runTransformation(){e.state="loading";try{const n=e.contentModel.queries.findByIDSet(new Set(e.dep_query_ids)).map(l=>({id:l.id,name:l.name,data:y.cloneDeep(l.data)})),r=e.contentModel.dashboardState,i=e.pre_process,o=new Function(`return ${i}`)()(n,r,nt);e.data=o,e.state="idle",e.error=null}catch(t){e.data=[],e.error=t.message,e.state="error"}}})).actions(e=>({fetchData:t=>{if(!e.inUse&&!t){console.debug(`🟡 Skipping query[${e.name}]`);return}return console.debug(`🔵 Running query[${e.name}]`),e.isTransform?e.runTransformation():e.typedAsHTTP?e.runHTTP():e.runSQL()},beforeDestroy(){var t;(t=e.controller)==null||t.abort()}})).actions(e=>({afterCreate(){f.addDisposer(e,U.reaction(()=>{var n;return e.isTransform?[e.inUse,e.id,e.key,e.dep_query_ids.toString(),e.pre_process,e.depQueryModelStatesString].join("--"):e.typedAsHTTP?`${e.inUse}--${e.id}--${e.key}--${e.reQueryKey}--${(n=e.datasource)==null?void 0:n.id}`:[e.inUse,e.id,e.key,e.formattedSQL,e.pre_process,e.post_process].join("--")},()=>e.fetchData(!1),{fireImmediately:!0,delay:0}))}})),Hr=f.types.model("QueriesRenderModel",{current:f.types.optional(f.types.array(Zr),[])}).views(e=>({get idSet(){return new Set(e.current.map(t=>t.id))},get firstID(){if(e.current.length!==0)return e.current[0].id},findByID(t){return e.current.find(n=>n.id===t)},findByIDSet(t){return e.current.filter(n=>t.has(n.id))},get json(){return e.current.filter(t=>t.id&&t.key).map(t=>t.json)},get contentModel(){return f.getParent(e,1)},get visibleQueryIDSet(){const{views:t,filters:n,queries:r}=this.contentModel,i=[];t.visibleViews.forEach(c=>{c.panels.forEach(u=>{i.push(...u.queryIDs)})});const o=y.uniq(t.visibleViews.map(c=>c.renderViewIDs).flat());n.current.forEach(c=>{const u=y.get(c,"config.options_query_id");if(!u)return;o.some(h=>c.visibleInViewsIDSet.has(h))&&i.push(u)}),r.findByIDSet(new Set(i)).forEach(c=>{!c.isTransform||c.dep_query_ids.length===0||i.push(...c.dep_query_ids)});const l=new Set(i);return console.debug("QueryIDs:",l),l},isQueryInUse(t){return this.visibleQueryIDSet.has(t)}})).actions(e=>({downloadAllData(){const t=e.current.map(({name:n,data:r})=>({id:n,data:r}));Pl(t)},downloadDataByQueryIDs(t){const n=new Set(t),r=e.current.filter(i=>n.has(i.id)).map(({name:i,data:o})=>({id:i,data:o}));Pl(r)},downloadDataByQueryID(t){const n=e.findByID(t);if(!n){console.log("[downloadDataByQueryID] query not found");return}const{name:r,data:i}=n;O1(r,i)},refetchDataByQueryID(t){const n=e.findByID(t);if(!n){console.error(new Error(`[downloadDataByQueryID] query by ID[${t}] not found`));return}return n.fetchData(!0)},getSchema(t){return{definition:{queries:e.findByIDSet(new Set(t)).map(i=>i.json)},version:at}},downloadSchema(t){const n=JSON.stringify(this.getSchema(t),null,2);Nt("Queries",n)}}));function ql(e){return{current:e}}function Nl({min:e,max:t}){const n=`${e}px`,r=Number.isFinite(t)?`${t}px`:"∞";return`[${n}, ${r})`}const ei=f.types.model("LayoutsRenderModel",{list:f.types.array(yl),currentBreakpoint:f.types.string}).views(e=>({get json(){return e.list.map(t=>t.json)},jsonByPanelIDSet(t){return e.list.map(n=>n.jsonByPanelIDSet(t))},get root(){return f.getRoot(e)},get contentModel(){return this.root.content},get basisLayoutSet(){return e.list.find(t=>t.id==="basis")},get currentLayoutSet(){return e.list.find(t=>t.id===e.currentBreakpoint)},get currentLayoutRange(){return this.breakpointRanges.find(t=>t.id===e.currentBreakpoint)},get currentRangeText(){const t=this.currentLayoutRange;return Nl(t)},get cols(){const t={};return e.list.forEach(n=>{t[n.id]=36}),t},get breakpoints(){const t={};return e.list.forEach(n=>{t[n.id]=n.breakpoint}),t},get breakpointNameRecord(){const t={};return e.list.forEach(n=>{t[n.name]=n.breakpoint}),t},get breakpointRanges(){const t=e.list.map(n=>({id:n.id,name:n.name,min:n.breakpoint,max:1/0,text:""}));return t.sort((n,r)=>n.min-r.min).forEach((n,r)=>{r!==t.length-1&&(n.max=t[r+1].min)}),t.forEach(n=>{n.text=Nl(n)}),t},get breakpointsInfo(){return e.list.map(t=>({id:t.id,name:t.name,breakpoint:t.breakpoint})).sort((t,n)=>t.breakpoint-n.breakpoint)},get currentBreakpointRange(){return this.breakpointRanges.find(t=>t.id===e.currentBreakpoint)},get currentLayoutPreviewWidth(){const t=this.currentBreakpointRange;if(t)return t.max===1/0?t.min===0?void 0:t.min+1:t.max},items(t){const n=new Set(t);return this.currentLayoutSet.list.filter(i=>n.has(i.panelID))},gridLayouts(t){const n=new Set(t),r={};return e.list.forEach(i=>{r[i.id]=i.list.filter(o=>n.has(o.panelID)).map(o=>o.layoutProperies)}),r},findItemByPanelID(t){return this.currentLayoutSet.findByPanelID(t)}})).actions(e=>({setCurrentBreakpoint(t){console.log("🔴 onBreakpointChange:",t),e.currentBreakpoint=t},afterCreate(){f.addDisposer(e,U.reaction(()=>e.currentBreakpoint,()=>{setTimeout(()=>{window.dispatchEvent(new Event("resize"))},32)},{fireImmediately:!1,delay:0}))}})),Fl=bl.views(e=>({isADuplicatedKey(t){return!t||t===e.key?!1:!!f.getParent(e,2).findByKey(t)}})),ti=f.types.model("SQLSnippetsRenderModel",{current:f.types.optional(f.types.array(Fl),[])}).views(e=>({get json(){return e.current.map(t=>t.json)},get record(){return e.current.reduce((t,n)=>(t[n.key]=n.value,t),{})},get keySet(){return new Set(e.current.map(t=>t.key))},get firstKey(){if(e.current.length!==0)return e.current[0].key},findByKey(t){return e.current.find(n=>n.key===t)},findByKeySet(t){return e.current.filter(n=>t.has(n.key))}})).actions(e=>({getSchema(t){return{definition:{sqlSnippets:e.findByKeySet(new Set(t)).map(i=>i.json)},version:at}},downloadSchema(t){const n=JSON.stringify(this.getSchema(t),null,2);Nt("SQL Snippets",n)}}));function Gl(e){return{current:e}}function ln(e,t,n,r){return e.reduce((i,o)=>{try{i[o[t]]=hs(o[n],r)}catch(l){i[o[t]]=l.message}return i},{})}class Wl{constructor(t){P(this,"origin");P(this,"copy");this.origin=t,this.copy=f.clone(t),U.makeAutoObservable(this,{},{autoBind:!0,deep:!1})}get changed(){return!y.isEqual(f.getSnapshot(this.origin),f.getSnapshot(this.copy))}commit(){f.applySnapshot(this.origin,f.getSnapshot(this.copy))}reset(){f.applySnapshot(this.copy,f.getSnapshot(this.origin))}update(t){f.applySnapshot(this.copy,t)}}const Rl=e=>new Wl(e),V1=S.observer(({view:e})=>{const t=X(),n=W(),r=ze.useModals(),{panel:i,downloadPanelScreenshot:o}=Ee(),{id:l}=i,{viewPanelInFullScreen:c,inFullScreen:u}=g.useContext(Jn),d=()=>{n.duplicatePanelByID(l,e.id)},h=()=>{t.editor.open(["_VIEWS_",e.id,"_PANELS_",l])},p=()=>r.openConfirmModal({title:"Delete this panel?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>n.removePanelByID(l,e.id),confirmProps:{color:"red"},zIndex:320}),x=g.useCallback(()=>{c(l)},[l,c]),m=!u&&e.type!==L.Modal;return s.jsx(s.Fragment,{children:s.jsx(a.Box,{sx:{position:"absolute",top:0,left:0,right:0,zIndex:300},children:s.jsxs(a.Menu,{withinPortal:!0,children:[s.jsx(a.Menu.Target,{children:s.jsx(a.Box,{className:"panel-dropdown-target",sx:{width:"100%"}})}),s.jsxs(a.Menu.Dropdown,{children:[s.jsx(a.Menu.Item,{onClick:i.refreshData,icon:s.jsx(k.Refresh,{size:14}),children:"Refresh"}),s.jsx(a.Menu.Item,{onClick:i.downloadData,icon:s.jsx(k.Download,{size:14}),children:"Download Data"}),s.jsx(a.Menu.Item,{onClick:i.downloadSchema,icon:s.jsx(_.IconCode,{size:14}),children:"Download Schema"}),s.jsx(a.Menu.Item,{onClick:o,icon:s.jsx(_.IconCamera,{size:14}),children:"Screenshot"}),m&&s.jsx(a.Menu.Item,{onClick:x,icon:s.jsx(k.ArrowsMaximize,{size:14}),disabled:!0,children:"Full Screen"}),s.jsx(a.Divider,{label:"Edit",labelPosition:"center"}),s.jsx(a.Menu.Item,{onClick:h,icon:s.jsx(k.Settings,{size:14}),children:"Settings"}),s.jsx(a.Menu.Item,{onClick:d,icon:s.jsx(k.Copy,{size:14}),children:"Duplicate"}),s.jsx(a.Menu.Item,{color:"red",onClick:p,icon:s.jsx(k.Trash,{size:14}),children:"Delete"})]})]})})})});function q1(e){return e?["<p><br></p>","<p></p>"].includes(e):!0}const ni=S.observer(()=>{const[e,t]=g.useState(!1),{panel:n}=xt();return q1(n.description)?null:s.jsxs(s.Fragment,{children:[s.jsx(a.Modal,{opened:e,onClose:()=>t(!1),title:n.title.show?n.name:"",withCloseButton:!1,withinPortal:!0,zIndex:310,children:s.jsx(Nn,{value:n.description,styles:{root:{border:"none"},content:{padding:0}},sx:{".mantine-RichTextEditor-content .ProseMirror":{padding:"0 !important"}}})}),s.jsx(a.Tooltip,{label:"Click to see description",position:"top-start",withinPortal:!0,children:s.jsx(a.ActionIcon,{variant:"subtle",color:"blue",onClick:()=>t(r=>!r),sx:{verticalAlign:"baseline",cursor:"pointer"},children:s.jsx(k.InfoCircle,{size:20})})})]})}),GI="",N1=S.observer(function(){const{panel:t}=xt(),{name:n,title:r}=t;return r.show?s.jsx(a.Group,{grow:!0,position:"center",className:"panel-title-wrapper",sx:{flexGrow:1},children:s.jsx(a.Text,{align:"center",lineClamp:1,className:"panel-title-text",children:n})}):null});function F1(e){const t=g.useRef(null);return{ref:t,downloadPanelScreenshot:()=>{const r=t.current;if(!r)return;const i=r.offsetWidth*2,o=r.offsetHeight*2;Ui.toBlob(t.current,{bgcolor:"white",width:i,height:o,style:{border:"none",borderRadius:0,transformOrigin:"0 0",transform:"scale(2)"}}).then(l=>{window.saveAs(l,`${e.name?e.name:e.viz.type}.png`)})}}}var Ql=(e=>(e.migrated="migrated",e.nothingToMigrate="nothingToMigrate",e.checkFailed="checkFailed",e.migrationFailed="migrationFailed",e))(Ql||{}),es=(e=>(e.notStarted="notStarted",e.inProgress="inProgress",e.done="done",e))(es||{});class G1{constructor(t){P(this,"vizInstance");P(this,"operationManager");P(this,"triggerManager");P(this,"vizManager");P(this,"runningMigration");P(this,"panelModel");P(this,"status","notStarted");this.panelModel=t.getRequired(ue.instanceScope.panelModel),this.vizInstance=t.getRequired(ue.instanceScope.vizInstance),this.operationManager=t.getRequired(ue.instanceScope.operationManager),this.triggerManager=t.getRequired(ue.instanceScope.triggerManager),this.vizManager=t.getRequired(ue.vizManager)}async createMigrationTask(){const t=[];try{await this.instanceNeedMigration()&&t.push(()=>this.runInstanceMigration()),await this.interactionNeedMigration()&&t.push(()=>this.runInteractionMigration())}catch(n){return console.warn("check migration failed",n),"checkFailed"}if(t.length===0)return"nothingToMigrate";try{return await Promise.all(t.map(n=>n())),"migrated"}catch(n){return console.warn("migration failed",n),"migrationFailed"}}async runMigration(){return this.runningMigration||(this.status="inProgress",this.runningMigration=this.createMigrationTask().then(t=>(this.status="done",t))),this.runningMigration}async runInteractionMigration(){await this.operationManager.runMigration(),await this.triggerManager.runMigration()}async runInstanceMigration(){const t=this.vizManager.resolveComponent(this.vizInstance.type),n={configData:this.vizInstance.instanceData,panelModel:this.panelModel};await t.migrator.migrate(n)}async instanceNeedMigration(){const t=this.vizManager.resolveComponent(this.vizInstance.type),n={configData:this.vizInstance.instanceData};return t.migrator.needMigration(n)}async interactionNeedMigration(){return await this.operationManager.needMigration()||await this.triggerManager.needMigration()}}function Ul(e){const{panel:t}=xt();return g.useCallback(n=>{const r=n.getRequired(ue.vizManager),i=r.resolveComponent(e.viz.type);return n.createScoped().provideFactory(ue.instanceScope.vizInstance,()=>r.getOrCreateInstance(e)).provideFactory(ue.instanceScope.interactionManager,o=>{const l=o.getRequired(ue.instanceScope.vizInstance);return new zs(l,i,Sn)}).provideFactory(ue.instanceScope.operationManager,o=>o.getRequired(ue.instanceScope.interactionManager).operationManager).provideFactory(ue.instanceScope.triggerManager,o=>o.getRequired(ue.instanceScope.interactionManager).triggerManager).provideValue(ue.instanceScope.panelModel,t).provideFactory(ue.instanceScope.migrator,o=>new G1(o))},[e.viz.type,e.viz.conf])}function Kl(e){const[t,n]=g.useState(!1),r=il().getRequired(ue.instanceScope.migrator);return $.useAsyncEffect(async()=>{const i=r.status===es.notStarted;n(r.status===es.done),r.status===es.notStarted&&r.runMigration().then(o=>{o===Ql.migrated&&i&&(e==null||e())}).finally(()=>{n(!0)})},[r]),t}function Yl(e,t){const n=il().getRequired(ue.instanceScope.vizInstance);return g.useEffect(()=>(n.instanceData.setItem(null,t.viz.conf),n.instanceData.watchItem(null,r=>{e(r)})),[e,t.viz.type]),n}function W1({setVizConf:e,...t}){const{panel:n}=t,r=Yl(e,n),i=Kl(()=>{ut.showNotification({title:`${n.name} - Updated`,message:"Your plugin configuration has been migrated to the latest version"})});return $.useAsyncEffect(async()=>{await r.instanceData.setItem(null,n.viz.conf)},[r,n.viz.type]),i?s.jsx(Ld,{...t}):s.jsx(a.Text,{children:"Checking update..."})}function R1(e){const{panel:t,setVizConf:n}=e;Yl(n,t);const{inEditMode:r}=g.useContext(wn);return Kl(()=>{r&&ut.showNotification({title:`${t.name} - Updated`,message:"Your plugin configuration has been migrated to the latest version"})})?s.jsx(Pd,{...e}):s.jsx(a.Text,{children:"Checking update"})}const WI="";function Q1(e,t){const{vizManager:n}=g.useContext(Ze),{panel:{viz:r,title:i,id:o,name:l,description:c,queryIDs:u,variables:d}}=xt(),h={id:o,name:l,title:i,description:c,queryIDs:u,viz:r},p=Ul(h);try{return n.resolveComponent(r.type),s.jsx(Xn,{configure:p,children:s.jsx(R1,{setVizConf:r.setConf,panel:h,measure:t,data:e,variables:d,vizManager:n})})}catch(x){return console.info(y.get(x,"message")),null}}const Xl=S.observer(function({data:t}){const{ref:n,width:r,height:i}=re.useElementSize(),o=Q1(t,{w:r,h:i}),l=r>0&&i>0;return s.jsx("div",{className:"viz-root",ref:n,children:s.jsx(a.Box,{sx:{width:r,height:i,overflow:"hidden"},children:l&&s.jsx(je,{children:o})})})}),Jl=S.observer(({panel:e})=>s.jsxs(a.Stack,{children:[e.queryErrors.map((t,n)=>s.jsx(a.Text,{color:"red",size:"sm",align:"center",sx:{fontFamily:"monospace"},children:t},`${n}-${t}`)),s.jsx(a.Text,{color:"gray",align:"center",size:"sm",children:e.queryStateMessages})]})),si=S.observer(({panel:e})=>s.jsxs(a.Flex,{className:"panel-viz-section",direction:"column",sx:{position:"relative",width:"100%"},children:[s.jsx(a.LoadingOverlay,{visible:e.dataLoading,exitTransitionDuration:0}),!e.canRenderViz&&s.jsx(Jl,{panel:e}),e.canRenderViz&&s.jsx(Xl,{data:e.data})]})),U1={border:"1px solid #e9ecef"},Zl=S.observer(({panel:e,panelStyle:t,dropdownContent:n})=>{const{ref:r,downloadPanelScreenshot:i}=F1(e);return e.title.show,s.jsx(Ts,{value:{panel:e,data:e.data,loading:e.dataLoading,errors:e.queryErrors,downloadPanelScreenshot:i},children:s.jsxs(a.Box,{className:`panel-root ${e.title.show?"panel-root--show-title":""}`,ref:r,p:0,sx:{...U1,...t},children:[s.jsx(a.Box,{className:"panel-description-popover-wrapper",children:s.jsx(ni,{})}),n,s.jsx(N1,{}),s.jsx(si,{panel:e})]})})}),K1={border:"1px dashed transparent",transition:"border-color 300ms ease","&:hover":{borderColor:"#e9ecef"}};function Y1(e){return e.style.border.enabled?{}:K1}const Hl=S.observer(function({panel:t,view:n}){const r=Y1(t);return s.jsx(Zl,{panel:t,panelStyle:r,dropdownContent:s.jsx(V1,{view:n})})});function X1(e){return!["richText","button"].includes(e)}const J1=S.observer(({view:e})=>{const{panel:t,downloadPanelScreenshot:n}=xt(),{id:r}=t,{viewPanelInFullScreen:i,inFullScreen:o}=g.useContext(Jn),l=g.useCallback(()=>{i(r)},[r,i]),c=!o&&e.type!==L.Modal;return X1(t.viz.type)?s.jsx(a.Box,{sx:{position:"absolute",top:0,left:0,right:0,zIndex:300},children:s.jsxs(a.Menu,{withinPortal:!0,children:[s.jsx(a.Menu.Target,{children:s.jsx(a.Box,{className:"panel-dropdown-target"})}),s.jsxs(a.Menu.Dropdown,{children:[s.jsx(a.Menu.Item,{onClick:t.refreshData,icon:s.jsx(k.Refresh,{size:14}),children:"Refresh"}),s.jsx(a.Menu.Item,{onClick:t.downloadData,icon:s.jsx(k.Download,{size:14}),children:"Download Data"}),s.jsx(a.Menu.Item,{onClick:n,icon:s.jsx(_.IconCamera,{size:14}),children:"Screenshot"}),c&&s.jsx(a.Menu.Item,{onClick:l,icon:s.jsx(k.ArrowsMaximize,{size:14}),children:"Full Screen"})]})]})}):null});function Z1(e){return e.style.border.enabled?{}:{border:"1px dashed transparent"}}const ri=S.observer(({panel:e,view:t})=>{const n=Z1(e);return s.jsx(Zl,{panel:e,panelStyle:n,dropdownContent:s.jsx(J1,{view:t})})}),H1={modal:{display:"flex",flexDirection:"column",flexWrap:"nowrap"},body:{display:"flex",height:"calc(100vh - 88px)"}},ec=S.observer(function({view:t,panel:n,exitFullScreen:r}){return s.jsx(a.Modal,{opened:!0,fullScreen:!0,onClose:r,title:s.jsx(a.Button,{color:"blue",size:"xs",onClick:r,leftIcon:s.jsx(k.ArrowLeft,{size:20}),children:"Exit fullscreen"}),styles:H1,children:s.jsx(a.Group,{grow:!0,sx:{flexGrow:1,flexShrink:0},children:s.jsx(ri,{view:t,panel:n})})})});function tc(e,t,n){const{panels:r}=ce(),i=e.id==="Main",[o,l]=g.useState(()=>i&&r.findByID(t)?t:null),c=g.useCallback(p=>{l(p),i&&n(p)},[i,n]),u=g.useCallback(()=>{l(null),i&&n("")},[i,n]),d=o?r.findByID(o):null;return{viewPanelInFullScreen:c,exitFullScreen:u,inFullScreen:!!d,fullScreenPanel:d}}const RI="",e_=g.forwardRef(({h:e},t)=>s.jsx(a.ActionIcon,{ref:t,className:"react-grid-customDragHandle",sx:{userSelect:"none",cursor:"grab",position:"absolute",top:5,right:e>38?5:20,zIndex:400,"&:hover":{color:"#228be6"}},variant:"transparent",children:s.jsx(k.ArrowsMove,{size:16})})),t_=g.forwardRef(({handleAxis:e,...t},n)=>s.jsx(a.ActionIcon,{ref:n,className:"react-grid-customResizeHandle",sx:{userSelect:"none",cursor:"nwse-resize",position:"absolute",bottom:0,right:0,zIndex:400,"&:hover":{color:"#228be6"}},variant:"transparent",...t,children:s.jsx(k.ChevronDownRight,{size:16})})),n_=fn.WidthProvider(fn.Responsive),s_=S.observer(({view:e,className:t="layout"})=>{const r=W().layouts,i=r.items(e.panelIDs),o=r.gridLayouts(e.panelIDs),l=(d,h,p,x)=>{console.log("🔴 onResize",d),p.h<30&&(p.h=30,x.h=30),p.w<4&&(p.w=4,x.w=4)},c=(d,h,p)=>{console.log("🔴 onResizeStop",{layouts:d,oldItem:h,newItem:p}),r.updateCurrentLayoutItem(p)},u=(d,h,p)=>{console.log("🔴 onDragStop",{layouts:d,oldItem:h,newItem:p}),r.updateCurrentLayoutItem(p)};return s.jsx(n_,{className:`dashboard-layout ${t}`,rowHeight:1,margin:[0,0],isBounded:!0,isDraggable:!0,isResizable:!0,cols:r.cols,layouts:o,draggableHandle:".react-grid-customDragHandle",resizeHandle:s.jsx(t_,{}),onResize:l,breakpoints:r.breakpoints,onBreakpointChange:r.setCurrentBreakpoint,onResizeStop:c,onDragStop:u,width:r.currentLayoutPreviewWidth,children:i.map(d=>s.jsxs("div",{"data-grid":d.layoutProperies,className:"panel-grid-item",children:[s.jsx(e_,{h:d.h}),s.jsx(Hl,{view:e,panel:d.panel})]},d.id))})}),r_=fn.WidthProvider(fn.Responsive),i_=S.observer(({view:e,className:t="layout"})=>{const n=ce(),r=n.layouts.items(e.panelIDs),i=n.layouts.gridLayouts(e.panelIDs);return s.jsx(r_,{className:`dashboard-layout ${t}`,rowHeight:1,margin:[0,0],isDraggable:!1,isResizable:!1,cols:n.layouts.cols,layouts:i,breakpoints:n.layouts.breakpoints,onBreakpointChange:n.layouts.setCurrentBreakpoint,children:r.map(o=>s.jsx("div",{"data-grid":o.layoutProperies,className:"panel-grid-item",children:s.jsx(ri,{view:e,panel:o.panel})},o.id))})});function ii(e){const t=g.useRef(null);return{ref:t,downloadScreenshot:()=>{var i;const r=(i=t.current)==null?void 0:i.querySelector(".react-grid-layout");r&&e.downloadScreenshot(r)}}}const a_=S.observer(({downloadScreenshot:e})=>{const[t,{setTrue:n,setFalse:r}]=$.useBoolean(!1),i=pa(),o=ce(),l=()=>{const c=JSON.stringify(o.contentJSON,null,2),u=`${i.name}__${o.name}`;Nt(u,c)};return s.jsxs(a.Menu,{shadow:"md",width:200,trigger:"hover",openDelay:200,closeDelay:400,withinPortal:!0,position:"bottom-end",children:[s.jsx(a.Menu.Target,{children:s.jsx(a.Affix,{position:{bottom:"20px",right:"10px"},zIndex:1,children:s.jsx(a.ActionIcon,{size:"md",variant:"gradient",gradient:{from:"indigo",to:"cyan"},onMouseEnter:n,onMouseLeave:r,sx:{opacity:t?1:.6,transform:`translateX(${t?0:"2px"})`,transition:"all ease 300ms",borderRadius:"50%"},children:s.jsx(_.IconShare3,{size:"1rem"})})})}),s.jsxs(a.Menu.Dropdown,{children:[s.jsx(a.Menu.Item,{icon:s.jsx(_.IconCamera,{size:14}),onClick:e,children:"Screenshot"}),s.jsx(a.Menu.Divider,{}),s.jsx(a.Menu.Item,{icon:s.jsx(_.IconDownload,{size:14}),onClick:o.queries.downloadAllData,children:"Download Data"}),s.jsx(a.Menu.Item,{icon:s.jsx(_.IconCode,{size:14}),onClick:l,children:"Download Schema"})]})]})}),nc=S.observer(({children:e,view:t,sx:n={}})=>{const{ref:r,downloadScreenshot:i}=ii(t);return s.jsxs(s.Fragment,{children:[s.jsx(a.Box,{ref:r,pt:10,pb:10,sx:n,children:e}),s.jsx(a_,{downloadScreenshot:i})]})}),sc=S.observer(({downloadScreenshot:e})=>s.jsx(a.ActionIcon,{className:"download-screenshot-button",color:"blue",onClick:e,children:s.jsx(_.IconCamera,{size:14})})),o_=S.observer(({children:e,view:t})=>{const n=ce(),r=t.config,i=n.views.visibleViewIDs.includes(t.id),o=()=>n.views.rmVisibleViewID(t.id),{ref:l,downloadScreenshot:c}=ii(t);return s.jsx(a.Modal,{size:r.width,centered:!0,opened:i,onClose:o,withCloseButton:!1,title:s.jsxs(a.Group,{position:"apart",px:"1rem",h:"48px",children:[s.jsx(a.Box,{children:r.custom_modal_title.value}),s.jsx(sc,{downloadScreenshot:c})]}),trapFocus:!0,onDragStart:u=>{u.stopPropagation()},styles:{root:{position:"fixed",zIndex:200,inset:0},overlay:{zIndex:"unset"},inner:{zIndex:"unset",padding:"0 !important"},content:{border:"1px solid #efefef",maxHeight:"unset !important",overflow:"hidden"},body:{maxHeight:r.height,overflow:"auto",position:"relative",paddingBottom:10},header:{padding:0},title:{flexGrow:1}},transitionProps:{duration:0},children:s.jsx(a.Box,{ref:l,children:e})})}),l_=e=>e.color?{"&[data-active], &[data-active]:hover":{borderColor:e.color?e.color:"..."}}:{},c_=S.observer(({view:e})=>{const t=ce(),n=e.config;return s.jsxs(a.Tabs,{className:"render-view-tabs",variant:n.variant,orientation:n.orientation,value:e.tab,onTabChange:e.setTab,styles:{root:{height:"100%",overflow:n.orientation==="horizontal"?"hidden":"auto"},panel:{padding:n.orientation==="horizontal"?"0px 0px 36px":"0",height:"100%",overflow:"auto"}},keepMounted:!1,children:[s.jsx(a.Tabs.List,{grow:n.grow,children:n.tabsInOrder.map(r=>s.jsx(a.Tabs.Tab,{value:r.id,sx:l_(r),disabled:!r.view_id,children:r.name??r.id},r.id))}),n.tabsInOrder.map(r=>{const i=t.views.findByID(r.view_id);return i?s.jsx(a.Tabs.Panel,{value:r.id,children:s.jsx(ts,{view:i})},r.id):null})]})}),u_=S.observer(({view:e,children:t})=>{switch(e.type){case L.Modal:return s.jsx(o_,{view:e,children:t});case L.Tabs:return s.jsx(c_,{view:e});case L.Division:default:return s.jsx(nc,{view:e,children:t})}}),d_=S.observer(({children:e,view:t})=>{const r=W().layouts,[i,o]=re.useResizeObserver();return g.useEffect(()=>{r.setCurrentLayoutWrapperWidth(o.width)},[o.width]),s.jsx(a.Box,{sx:{height:"100%"},ref:i,children:s.jsx(a.Box,{sx:{paddingBottom:"100px",background:"white",margin:"0 auto",width:r.currentLayoutPreviewWidth??"100%",transform:`scale(${r.divisionPreviewScale})`,transformOrigin:"0 0"},children:s.jsx(nc,{view:t,sx:{paddingTop:"0px !important",".dashboard-sticky-area > form":{paddingBottom:"5px"},".dashboard-layout":{marginTop:0,marginBottom:0}},children:e})})})});function rc(e){return e.replace(/(vw|vh)/,"%")}const p_=S.observer(({children:e,view:t})=>{const n=t.config,{width:r,height:i}=g.useMemo(()=>({width:rc(n.width),height:rc(n.height)}),[n.width,n.height]),{ref:o,downloadScreenshot:l}=ii(t);return s.jsx(a.Box,{sx:{height:"100%","> div:not(.mantine-Modal-root)":{height:"100%"}},children:s.jsx(a.Modal,{size:n.width,opened:!0,onClose:y.noop,withCloseButton:!1,title:s.jsxs(a.Group,{position:"apart",px:"1rem",h:"48px",children:[s.jsx(a.Box,{children:n.custom_modal_title.value}),s.jsx(sc,{downloadScreenshot:l})]}),trapFocus:!0,onDragStart:c=>{c.stopPropagation()},styles:{root:{position:"relative",height:"100%"},overlay:{position:"absolute !important"},inner:{position:"relative",top:"50%",left:"50%",right:"unset",bottom:"unset",transform:"translate(-50%, -50%)",padding:"0 !important",width:r,height:i,maxHeight:i},content:{border:"1px solid #efefef",height:"100%"},body:{maxHeight:"calc(100% - 48px)",overflow:"auto"},header:{padding:0},title:{flexGrow:1}},withinPortal:!1,transitionProps:{duration:0},children:s.jsx(a.Box,{ref:o,children:e})})})}),h_=({variant:e,orientation:t})=>{const n={root:{height:"100%",overflow:"hidden"},tabsList:{backgroundColor:"white"},tab:{},panel:{padding:"16px"}};return e==="pills"&&t==="horizontal"&&(n.tab.paddingTop="6px",n.tab.paddingBottom="6px"),t==="vertical"&&(n.tab["&.add-a-tab"]={paddingTop:"1px",paddingBottom:"1px"},n.tab["&.add-a-tab .mantine-Tabs-tabLabel"]={marginLeft:"auto",marginRight:"auto"}),n},x_=e=>e.color?{"&[data-active], &[data-active]:hover":{borderColor:e.color?e.color:"..."}}:{},f_=S.observer(({view:e})=>{const t=ze.useModals(),n=W(),r=g.useMemo(()=>n.views.options.filter(c=>c.type===L.Division),[e.id,n.views.options]),i=e.config,o=c=>t.openConfirmModal({title:"Delete this tab?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>{i.removeTab(c)},confirmProps:{color:"red"},zIndex:320}),l=i.tabs.length===0;return s.jsxs(a.Tabs,{className:"preview-view-tabs",variant:i.variant,orientation:i.orientation,value:e.tab,onTabChange:e.setTab,styles:h_(i),children:[s.jsxs(a.Tabs.List,{grow:i.grow,children:[i.tabsInOrder.map(c=>s.jsx(a.Tabs.Tab,{value:c.id,sx:x_(c),children:c.name??c.id},c.id)),s.jsx(a.Tabs.Tab,{onClick:i.addTab,value:"add",className:"add-a-tab",children:s.jsx(k.Plus,{size:18,color:"#228be6"})})]}),i.tabsInOrder.map((c,u)=>{const d=n.views.findByID(c.view_id);return s.jsxs(a.Tabs.Panel,{value:c.id,sx:{position:"relative"},children:[s.jsxs(a.Box,{sx:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:200},children:[s.jsx(a.Overlay,{opacity:.8,color:"#FFF",blur:10,zIndex:100}),s.jsxs(a.Stack,{mx:"auto",mt:100,sx:{width:"300px",position:"relative",zIndex:200},children:[s.jsx(a.TextInput,{label:"Tab Name",required:!0,value:c.name,onChange:h=>c.setName(h.currentTarget.value)}),s.jsx(a.Select,{label:"View",value:c.view_id,onChange:c.setViewID,data:r}),s.jsx(a.NumberInput,{label:"Placement Order",required:!0,value:c.order,onChange:h=>c.setOrder(h||0),min:0,max:1e3,step:1}),s.jsx(a.ColorInput,{label:"Color",value:c.color,onChange:c.setColor,disabled:i.variant!=="default"}),d&&s.jsxs(a.Button,{mt:20,variant:"gradient",leftIcon:s.jsx(_.IconArrowsLeftRight,{size:18}),gradient:{from:"cyan",to:"indigo"},onClick:()=>n.views.setIDOfVIE(d.id),children:["Swith to View: ",d.name]}),s.jsx(a.Button,{mt:20,variant:"subtle",color:"red",onClick:()=>o(u),disabled:l,leftIcon:s.jsx(_.IconTrash,{size:14}),children:"Delete This Tab"})]})]}),d&&s.jsx(ts,{view:d})]},c.id)})]})}),g_=S.observer(({view:e,children:t})=>{switch(e.type){case L.Modal:return s.jsx(p_,{view:e,children:t});case L.Tabs:return s.jsx(f_,{view:e});case L.Division:default:return s.jsx(d_,{view:e,children:t})}}),ic=S.observer(function({view:t}){const r=W().layouts.divisionPreviewScale!==1;return s.jsx(Jn.Provider,{value:{viewPanelInFullScreen:y.noop,inFullScreen:!1},children:s.jsx(a.Box,{className:"dashboard-view","data-enable-scrollbar":!0,sx:{background:r?"transparent":"#efefef"},children:s.jsx(g_,{view:t,children:s.jsxs(a.Box,{sx:{position:"relative"},children:[s.jsx(a.Box,{className:"dashboard-sticky-area",sx:{position:"sticky",top:"0px"},children:s.jsx(ul,{view:t})}),s.jsx(s_,{view:t})]})})})})}),ts=S.observer(function({view:t}){const{fullScreenPanelID:n,setFullScreenPanelID:r}=ba(),{viewPanelInFullScreen:i,exitFullScreen:o,inFullScreen:l,fullScreenPanel:c}=tc(t,n,r);return s.jsx(Jn.Provider,{value:{viewPanelInFullScreen:i,inFullScreen:l},children:s.jsxs(a.Box,{className:"dashboard-view","data-enable-scrollbar":!0,sx:{height:t.type===L.Modal?"0 !important":"100%"},children:[l&&s.jsx(ec,{view:t,panel:c,exitFullScreen:o}),s.jsx(u_,{view:t,children:s.jsxs(a.Box,{sx:{position:"relative"},children:[!l&&s.jsx(a.Box,{className:"dashboard-sticky-area",sx:{position:"sticky",top:"0px"},children:s.jsx(ul,{view:t})}),!l&&s.jsx(i_,{view:t})]})})]})})});var ac=(e=>(e.Use="use",e.Edit="edit",e))(ac||{});const m_={[L.Division]:"Division",[L.Tabs]:"Tabs",[L.Modal]:"Modal"},oc={[L.Division]:"rgba(255, 0, 0, 0.2)",[L.Modal]:"rgba(0, 0, 0, 0.2)",[L.Tabs]:"rgba(255, 200, 100, 0.4)"},y_={[L.Division]:"#ff4000",[L.Modal]:"#000",[L.Tabs]:"#ffad18"};function b_(e,t,n){f.addDisposer(e,f.addMiddleware(e,(r,i)=>{i(r,()=>{f.getType(r.context)===t&&r.type==="action"&&n(r.name,r.context)})}))}const lc=f.types.compose("FiltersModel",Xr,f.types.model("FiltersModel",{previewValues:f.types.optional(f.types.frozen(),{})})).views(e=>({get idSet(){return new Set(e.current.map(t=>t.id))},get keySet(){return new Set(e.current.map(t=>t.key))},get options(){return e.current.map(t=>({label:t.label??t.id,value:t.id,_type:"filter"}))},get selects(){return e.current.filter(t=>t.type===de.Select).map(t=>({label:t.label??t.id,value:t.id}))},get keyLabelOptions(){return e.current.map(t=>({label:t.label??t.key,value:t.key}))},get sortedList(){return y.sortBy(e.current,t=>t.label.toLowerCase())}})).actions(e=>({replace(t){e.current=f.cast(t)},append(t){e.current.push(t)},appendMultiple(t){if(t.length===0)return;const n=t.filter(r=>!e.idSet.has(r.id));e.current.push(...n)},remove(t){e.current.splice(t,1)},removeByID(t){const n=e.current.findIndex(r=>r.id===t);n>=0&&e.current.splice(n,1)},updatePreviewValues(t){e.previewValues=t}})).actions(e=>{function t(){b_(e.current,Vr,(n,r)=>{if(n==="setType"){const i=Ol(r.config.default_value,r.config);e.setValueByKey(r.key,i),e.updatePreviewValues({...e.previewValues,[r.key]:i})}})}return{afterCreate(){t()}}}),cc=Zr.views(e=>({get canPreviewData(){return e.isTransform?e.dep_query_ids.length>0&&!!e.pre_process:!!e.datasource},get guideToPreviewData(){return e.isTransform?"Need to complete settings in Transform tab":"Need to pick a Data Source first"}})),uc=f.types.compose("QueriesModel",Hr,f.types.model({current:f.types.optional(f.types.array(cc),[])})).views(e=>({get options(){const t=e.current.map(n=>({value:n.id,label:n.name,_type:"query"}));return y.sortBy(t,n=>n.label.toLowerCase())},get optionsWithoutTransform(){const t=e.current.filter(n=>n.type!==oe.Transform).map(n=>({value:n.id,label:n.name,_type:"query"}));return y.sortBy(t,n=>n.label.toLowerCase())},get sortedList(){return y.sortBy(e.current,t=>t.name.toLowerCase())}})).actions(e=>({replace(t){e.current=f.cast(t)},append(t){e.current.push(t)},appendMultiple(t){if(t.length===0)return;const n=t.filter(r=>!e.idSet.has(r.id));e.current.push(...n)},remove(t){e.current.splice(t,1)},replaceByIndex(t,n){e.current.splice(t,1,n)},removeQuery(t){const n=e.current.find(r=>r.id===t);n&&(f.detach(n),e.current.remove(n))},removeQueries(t){const n=new Set(t);e.current.forEach(i=>{n.has(i.id)&&f.detach(i)});const r=[...e.current];y.remove(r,i=>n.has(i.id)),e.current=f.cast(r)}})),dc=ti.views(e=>({get sortedList(){return y.sortBy(e.current,t=>t.key.toLowerCase())},get options(){const t=e.current.map(n=>({label:n.key,value:n.key,_type:"sql_snippet"}));return y.sortBy(t,n=>n.label.toLowerCase())}})).actions(e=>({replace(t){e.current=f.cast(t)},append(t){e.current.push(t)},appendMultiple(t){if(t.length===0)return;const n=t.filter(r=>!e.keySet.has(r.key));e.current.push(...n)},remove(t){e.current.splice(t,1)},removeByKey(t){const n=e.current.findIndex(r=>r.key===t);n>=0&&e.current.splice(n,1)},removeByKeys(t){const n=new Set(t);e.current.forEach(i=>{n.has(i.key)&&f.detach(i)});const r=[...e.current];y.remove(r,i=>n.has(i.key)),e.current=f.cast(r)},replaceByIndex(t,n){e.current.splice(t,1,n)}})),j_=f.types.model({data:f.types.optional(f.types.frozen(),[]),state:f.types.optional(f.types.enumeration(["idle","loading","error"]),"idle"),error:f.types.frozen()}).views(e=>({get loading(){return e.state==="loading"},get empty(){return e.data.length===0}})),v_=f.types.model({data:f.types.optional(f.types.frozen(),[]),state:f.types.optional(f.types.enumeration(["idle","loading","error"]),"idle"),error:f.types.frozen()}).views(e=>({get loading(){return e.state==="loading"},get empty(){return e.data.length===0}})),w_=f.types.model({page:f.types.optional(f.types.number,1),limit:f.types.optional(f.types.number,20),data:f.types.optional(f.types.frozen(),[]),total:f.types.optional(f.types.number,0),state:f.types.optional(f.types.enumeration(["idle","loading","error"]),"idle"),error:f.types.frozen()}).views(e=>({get keywords(){return f.getParent(e,1)},get keywordString(){const{table_name:t,table_schema:n}=f.getParent(e,1);return`${n}||${t}`}})).views(e=>({get loading(){return e.state==="loading"},get empty(){return e.data.length===0},get maxPage(){return Math.ceil(e.total/e.limit)},get offset(){return(e.page-1)*e.limit},get countSql(){const{table_name:t,table_schema:n}=e.keywords;return`
|
|
451
451
|
SELECT count(*) AS total
|
|
452
452
|
FROM ${n}.${t}
|
|
453
453
|
`}})).actions(e=>({setPage(t){e.page=t},resetPage(){e.page=1},setLimit(t){e.limit=t}})).actions(e=>({afterCreate(){f.addDisposer(e,U.reaction(()=>e.keywordString,e.resetPage,{fireImmediately:!1,delay:0})),f.addDisposer(e,U.reaction(()=>e.limit,e.resetPage,{fireImmediately:!1,delay:0}))}})),C_=f.types.model({data:f.types.optional(f.types.frozen(),{}),state:f.types.optional(f.types.enumeration(["idle","loading","error"]),"idle"),error:f.types.frozen()}).views(e=>({get loading(){return e.state==="loading"},get empty(){return Object.keys(e.data).length===0}})),S_=f.types.compose("DataSourceModel",Gr,f.types.model({tables:f.types.optional(C_,{}),columns:f.types.optional(j_,{}),tableData:f.types.optional(w_,{}),indexes:f.types.optional(v_,{}),table_schema:f.types.optional(f.types.string,""),table_name:f.types.optional(f.types.string,"")})).views(e=>({get sqlDataSourceType(){return e.type},get reloadConditionString(){const{type:t,table_name:n,table_schema:r}=e;return`${t};${n};${r}`}})).volatile(()=>({controllers:{tables:new AbortController,columns:new AbortController,indexes:new AbortController,tableData:new AbortController}})).actions(e=>({setKeywords(t,n){e.table_schema=t,e.table_name=n}})).actions(e=>({initKeywords(){if(e.tables.empty)return;const t=Object.keys(e.tables.data)[0],n=e.tables.data[t][0].table_name;e.setKeywords(t,n)}})).actions(e=>{const t=f.flow(function*(){var n;(n=e.controllers.tables)==null||n.abort(),e.controllers.tables=new AbortController,e.tables.state="loading";try{const r=yield*f.toGenerator(Ke.structure(e.controllers.tables.signal)({query_type:"TABLES",type:e.sqlDataSourceType,key:e.key,table_schema:"",table_name:""},{params:{query_type:"TABLES"}}));e.tables.data=y.groupBy(r,"table_schema"),e.tables.state="idle",e.tables.error=null,e.initKeywords()}catch(r){if(!He.isCancel(r)){e.tables.data={};const i=y.get(r,"message","unkown error");e.tables.error=y.get(r,"response.data.detail.message",i),e.tables.state="error"}}});return{loadTables:t,loadTablesIfEmpty(){e.tables.empty&&t()},loadColumns:f.flow(function*(){var n;(n=e.controllers.columns)==null||n.abort(),e.controllers.columns=new AbortController,e.columns.state="loading";try{e.columns.data=yield*f.toGenerator(Ke.structure(e.controllers.columns.signal)({query_type:"COLUMNS",type:e.sqlDataSourceType,key:e.key,table_schema:e.table_schema,table_name:e.table_name},{params:{query_type:"COLUMNS"}})),e.columns.state="idle",e.columns.error=null}catch(r){if(He.isCancel(r))e.columns.state="idle",e.columns.error=null;else{e.columns.data=[];const i=y.get(r,"message","unkown error");e.columns.error=y.get(r,"response.data.detail.message",i),e.columns.state="error"}}}),loadIndexes:f.flow(function*(){var n;(n=e.controllers.indexes)==null||n.abort(),e.controllers.indexes=new AbortController,e.indexes.state="loading";try{e.indexes.data=yield*f.toGenerator(Ke.structure(e.controllers.indexes.signal)({query_type:"INDEXES",type:e.sqlDataSourceType,key:e.key,table_schema:e.table_schema,table_name:e.table_name},{params:{query_type:"INDEXES"}})),e.indexes.state="idle",e.indexes.error=null}catch(r){if(He.isCancel(r))e.indexes.state="idle",e.indexes.error=null;else{e.indexes.data=[];const i=y.get(r,"message","unkown error");e.indexes.error=y.get(r,"response.data.detail.message",i),e.indexes.state="error"}}}),loadTableData:f.flow(function*(){var r;(r=e.controllers.tableData)==null||r.abort(),e.controllers.tableData=new AbortController;const n=e.tableData;n.state="loading";try{n.data=yield*f.toGenerator(Ke.structure(e.controllers.tableData.signal)({query_type:"DATA",type:e.sqlDataSourceType,key:e.key,table_schema:e.table_schema,table_name:e.table_name,limit:n.limit,offset:n.offset},{params:{query_type:"DATA"}}));const[{total:i}]=yield*f.toGenerator(Ke.structure(e.controllers.tableData.signal)({query_type:"COUNT",type:e.sqlDataSourceType,key:e.key,table_schema:e.table_schema,table_name:e.table_name},{params:{query_type:"COUNT"}}));n.total=Number(i),n.state="idle",n.error=null}catch(i){if(He.isCancel(i))n.state="idle",n.error=null;else{n.data=[];const o=y.get(i,"message","unkown error");n.error=y.get(i,"response.data.detail.message",o),n.state="error"}}})}}).actions(e=>({afterCreate(){f.addDisposer(e,U.reaction(()=>e.reloadConditionString,e.loadColumns,{fireImmediately:!1,delay:500}))}})).actions(e=>({afterCreate(){f.addDisposer(e,U.reaction(()=>e.reloadConditionString,e.loadIndexes,{fireImmediately:!1,delay:500})),f.addDisposer(e,U.reaction(()=>`${e.reloadConditionString};limit:${e.tableData.limit};offset:${e.tableData.offset}`,e.loadTableData,{fireImmediately:!1,delay:0}))}})),__=f.types.model("DataSourcesModel",{list:f.types.optional(f.types.array(S_),[])}).views(e=>({find({type:t,key:n}){return e.list.find(r=>r.key===n&&r.type===t)},get options(){return e.list.map(t=>({value:t.key,label:t.key}))}})).actions(e=>({replace(t){e.list.length=0,e.list.push(...t)}}));function kt(e){return{label:e,value:e,_type:"ACTION",_action_type:e,Icon:null,children:null}}function k_(e){switch(e._type){case"GROUP":case"ACTION":return null;case"query_variables":return["_QUERY_VARS_"];case"mock_context":return["_MOCK_CONTEXT_"];case"filter":return["_FILTERS_",e.value];case"sql_snippet":return["_SQL_SNIPPETS_",e.value];case"query":return["_QUERIES_",e.value];case"view":return["_VIEWS_",e.value];case"panel":return e.parentID?["_VIEWS_",e.parentID,"_PANELS_",e.value]:(console.error("[getPathFromOption] parentID is required"),null)}}const T_=f.types.model("EditorModel",{path:f.types.optional(f.types.frozen(),[]),settings_open:f.types.optional(f.types.boolean,!1)}).views(e=>({get navOptions(){const{content:t}=f.getRoot(e),{filters:n,views:r,sqlSnippets:i,queries:o}=t;return[{label:"Query Variables",value:"_QUERY_VARS_",_type:"query_variables",Icon:_.IconVariable},{label:"Mock Context",value:"_MOCK_CONTEXT_",Icon:_.IconCodeDots,_type:"mock_context"},{label:"Filters",value:"_FILTERS_",Icon:_.IconFilter,children:[kt("_FILTERS_SETTINGS_"),...n.options,kt("_Add_A_Filter_")],_type:"GROUP"},{label:"SQL Snippets",value:"_SQL_SNIPPETS_",Icon:_.IconCopy,children:[kt("_SQL_SNIPPETS_SETTINGS_"),...i.options,kt("_Add_A_SQL_SNIPPET_")],_type:"GROUP"},{label:"Queries",value:"_QUERIES_",Icon:_.IconDatabase,children:[kt("_QUERIES_SETTINGS_"),...o.options,kt("_Add_A_QUERY_")],_type:"GROUP"},{label:"Views",value:"_VIEWS_",Icon:_.IconBoxMultiple,children:[...r.editorOptions,kt("_Add_A_VIEW_")],_type:"GROUP"}]},isOptionActive(t,n){return t.length===0?!1:t[t.length-1]===n.value},isOptionOpened(t){const{path:n}=e;return n.length===0||!t.children||t.children.length===0?!1:n.includes(t.value)}})).actions(e=>({setPath(t){e.path=t},setSettingsOpen(t){e.settings_open=t}})).actions(e=>({open(t){e.setPath(t),e.setSettingsOpen(!0)},close(){e.setSettingsOpen(!1)},navigate(t){const n=k_(t);n&&e.setPath(n)}})),D_=f.types.compose("LayoutsModel",ei,f.types.model({currentLayoutWrapperWidth:f.types.optional(f.types.number,0)})).views(e=>({get divisionPreviewScale(){const t=e.currentLayoutPreviewWidth,n=e.currentLayoutWrapperWidth;return!t||!n||t<=n?1:n/t}})).actions(e=>({addALayoutItem(t){e.list.forEach(n=>{n.addNewLayout(t)})},duplicateLayoutItemsByPanelID(t,n){e.list.forEach(r=>{const i=r.findByPanelID(t);if(!i){console.error(`Can't find a layout item by panelID[${t}] in layoutSet[${r.name}]`);return}r.list.push({...i,id:pt.v4(),panelID:n,y:1/0})})},removeByPanelID(t){e.list.forEach(n=>{n.removeByPanelID(t)})},setCurrentLayoutWrapperWidth(t){e.currentLayoutWrapperWidth=t},addALayoutSet(t,n,r){const i=e.basisLayoutSet,o={id:t,name:n,breakpoint:r,list:i.json.list.map(l=>({...l,id:pt.v4()}))};e.list.push(o)},updateLayoutSetsInfo(t){const n=y.keyBy(e.list,"id");t.forEach(o=>{const l=n[o.id];if(l){l.setName(o.name),l.setBreakpoint(o.breakpoint),delete n[o.id];return}this.addALayoutSet(o.id,o.name,o.breakpoint)});const r=new Set(Object.keys(n)),i=r.size>0;r.forEach(o=>{const l=e.list.findIndex(c=>c.id===o);e.list.splice(l,1)}),i&&e.setCurrentBreakpoint("basis")},updateCurrentLayoutItem(t){e.currentLayoutSet.updateLayoutItem(t)},append(t){e.list.push(t)},appendMultiple(t){t.length!==0&&e.list.push(...t)},remove(t){e.list.splice(t,1)},removeByID(t){const n=e.list.findIndex(r=>r.id===t);n!==-1&&e.list.splice(n,1)},removeByIDs(t){t.forEach(n=>{this.removeByID(n)})}})),pc=Kr.views(e=>({get realDataFieldOptions(){return e.queryIDs.length===0?[]:e.queries.map(t=>{const n=t.data;return n.length===0?[]:Object.keys(n[0]).map(i=>({label:i,value:`${t.id}.${i}`,group:t.name,disabled:!1}))}).flat()},dataFieldOptions(t,n){const r=[...this.realDataFieldOptions];if(t&&!r.find(i=>i.value===t)){const i=z(t),o=e.queryByID(i.queryID);r.unshift({label:i.columnKey,value:t,group:o?o.name:i.queryID,disabled:!0})}return n&&r.unshift({label:"unset",value:"",group:"",disabled:!1}),r},explainDataKey(t){const{queryID:n,columnKey:r}=z(t),i=e.queries.find(o=>o.id===n);return i?{queryID:n,queryName:i.name,columnKey:r}:{queryID:n,queryName:null,columnKey:r}}})).actions(e=>({removeSelf(){f.getParent(e,2).removeByID(e.id)}})).actions(e=>({moveToView(t,n){f.getRoot(e).content.views.findByID(t).removePanelID(e.id),f.getRoot(e).content.views.findByID(n).appendPanelID(e.id),f.getRoot(e).editor.setPath(["_VIEWS_",n,"_PANELS_",e.id])}})),hc=f.types.compose("PanelsModel",Yr,f.types.model({list:f.types.optional(f.types.array(pc),[])})).views(e=>({get contentModel(){return f.getRoot(e).content},editorOptions(t,n){const r=e.panelsByIDs(n);r.length!==n.length&&console.warn(`Unfulfilled panels for View[${t}]`);const i=r.map(l=>({label:l.name,value:l.id,_type:"panel",parentID:t})),o="_Add_A_PANEL_";return i.push({label:o,value:o,_type:"ACTION",_action_type:o,parentID:t,Icon:null,children:null}),i}})).actions(e=>({replace(t){e.list=f.castToSnapshot(t)},append(t){e.list.push(t)},appendMultiple(t){t.length!==0&&e.list.push(...t)},remove(t){e.list.splice(t,1)},removeByID(t){const n=e.list.findIndex(r=>r.id===t);n!==-1&&e.list.splice(n,1)},removeByIDs(t){t.forEach(n=>{this.removeByID(n)})},duplicateByID(t){const n=e.list.find(i=>i.id===t);if(!n){console.error(new Error(`[duplicate panel] Can't find a panel by id[${t}]`));return}const r=new Date().getTime().toString();return e.list.push({...n.json,id:r,title:{...n.json.title}}),e.contentModel.layouts.duplicateLayoutItemsByPanelID(n.id,r),r},replaceByIndex(t,n){e.list.splice(t,1,n)}})),I_=Qr.actions(e=>({getSchema(){const t=e.json,n=[],r=[];e.panels.forEach(l=>{const c=l.getSchema();n.push(c.panel),c.queries.length>0&&r.push(...c.queries)});const i=e.contentModel.layouts.jsonByPanelIDSet(new Set(e.panelIDs));return{views:[t],panels:n,definition:{queries:y.uniqBy(r,l=>l.id)},layouts:i,version:at}},downloadSchema(){if(e.type===L.Tabs){console.error(new Error("Please choose a tab first"));return}const t=JSON.stringify(this.getSchema(),null,2),n=e.name;Nt(n,t)}})),xc=f.types.compose("ViewsModel",Ur,f.types.model({current:f.types.optional(f.types.array(I_),[]),idOfVIE:f.types.string})).views(e=>({get isVIETheFirstView(){return e.current.length===0||!e.idOfVIE?!1:e.current[0].id===e.idOfVIE},get VIE(){return e.current.find(({id:t})=>t===e.idOfVIE)},get options(){return e.current.map(t=>({label:t.name,value:t.id,type:t.type}))},get editorOptions(){const t=f.getRoot(e).content.panels;return e.current.map(n=>({label:n.name,value:n.id,_type:"view",children:t.editorOptions(n.id,n.panelIDs)}))}})).actions(e=>({setIDOfVIE(t){e.idOfVIE=t,e.visibleViewIDs.length=0,e.visibleViewIDs.push(t)},replace(t){e.current.replace(t)},addANewView(t,n,r,i){e.current.push({id:t,name:n,type:r,config:i,panelIDs:[]})},append(t){e.current.push(t)},appendMultiple(t){t.length!==0&&e.current.push(...t)},remove(t){e.current.splice(t,1)},removeByID(t){const n=e.current.findIndex(o=>o.id===t);if(n===-1)return;const r=e.current[n];f.getRoot(e).content.panels.removeByIDs(r.panelIDs),e.current.splice(n,1)},replaceByIndex(t,n){e.current.splice(t,1,n)},addARandomNewView(){const t=new Date().getTime().toString();this.addANewView(t,L.Division,L.Division,{_name:L.Division}),this.setIDOfVIE(t)},removeVIE(){e.current.length!==1&&(this.removeByID(e.idOfVIE),this.setIDOfVIE(e.current[0].id))}}));function ai(e){const t=e.length>0?[e[0].id]:[],n=e.length>0?e[0].id:"";return{current:e.map(i=>{const{_name:o=i.type}=i.config;return{...i,config:{...i.config,_name:o},panelIDs:i.panelIDs}}),visibleViewIDs:t,idOfVIE:n}}const M_=f.types.model({id:f.types.string,name:f.types.string,dashboard_id:f.types.string,create_time:f.types.string,update_time:f.types.string,version:f.types.string,filters:lc,queries:uc,sqlSnippets:dc,views:xc,panels:hc,layouts:D_,mock_context:Ir,origin:f.types.maybe(f.types.frozen())}).views(e=>({get json(){return{id:e.id,name:e.name,create_time:e.create_time,update_time:e.update_time,dashboard_id:e.dashboard_id,content:{views:e.views.json,panels:e.panels.json,filters:e.filters.json,version:e.version,layouts:e.layouts.json,definition:{queries:e.queries.json,sqlSnippets:e.sqlSnippets.json,mock_context:e.mock_context.current}}}},get contentJSON(){return this.json.content},get filtersChanged(){const t="filters.current";return!y.isEqual(f.getSnapshot(y.get(e,t)),y.get(e.origin,t))},get queriesChanged(){const t="queries.current",n=f.getSnapshot(y.get(e,t)).map(r=>y.pick(r,["id","name","key","type","sql","run_by","react_to","pre_process","post_process","dep_query_ids"]));return!y.isEqual(n,y.get(e.origin,t))},get sqlSnippetsChanged(){const t="sqlSnippets.current";return!y.isEqual(f.getSnapshot(y.get(e,t)),y.get(e.origin,t))},get viewsChanged(){const t="views.current";return!y.isEqual(e.views.json,y.get(e.origin,t))},get panelsChanged(){const t="panels.list";return!y.isEqual(f.getSnapshot(y.get(e,t)),y.get(e.origin,t))},get layoutsChanged(){const t="layouts.list";return!y.isEqual(f.getSnapshot(y.get(e,t)),y.get(e.origin,t))},get mockContextChanged(){const t="mock_context.current";return!y.isEqual(y.get(e,t),y.get(e.origin,t))},get context(){const t=f.getParent(e).context.current;return{...e.mock_context.current,...t}},get payloadForSQL(){const t=f.getParent(e).globalSQLSnippets,n={context:this.context,filters:e.filters.values};return{...n,sql_snippets:ln(e.sqlSnippets.current,"key","value",n),global_sql_snippets:ln(t.list,"id","content",n)}},get payloadForViz(){const t=f.getParent(e).context.current;return{context:{...e.mock_context.current,...t},filters:e.filters.values}},get dashboardState(){return bs(this.payloadForSQL)},getAdditionalQueryInfo(t){return{content_id:e.id,query_id:t,params:this.dashboardState}},get changed(){return this.filtersChanged||this.queriesChanged||this.sqlSnippetsChanged||this.viewsChanged||this.panelsChanged||this.layoutsChanged||this.mockContextChanged},get data(){return e.queries.current.map(({id:n,data:r})=>({id:n,data:r})).reduce((n,r)=>(n[r.id]=r.data,n),{})},getDataStuffByID(t){const n=e.queries.findByID(t);return n?{data:n.data,len:n.data.length,state:n.state,error:n.error}:{data:[],len:0,state:"idle",error:void 0}}})).views(e=>({get queriesUsage(){const t=e.panels.idMap,n=[];e.views.current.forEach(i=>{i.panelIDs.forEach(o=>{const l=t.get(o);if(!l)return;const c="panel",u=l.name,d=[{id:i.id,label:i.name}];l.queryIDs.forEach(h=>{n.push({id:o,queryID:h,type:c,label:u,views:d})})})});const r=e.views.idMap;return e.filters.current.filter(i=>!!y.get(i,"config.options_query_id")).forEach(i=>{n.push({type:"filter",id:i.id,queryID:y.get(i,"config.options_query_id"),label:i.label,views:i.visibleInViewsIDs.map(o=>{var l;return{id:o,label:((l=r.get(o))==null?void 0:l.name)??o}})})}),y.groupBy(n,"queryID")},get hasUnusedQueries(){return e.queries.current.length>Object.keys(this.queriesUsage).length},findQueryUsage(t){return this.queriesUsage[t]??[]},get sqlSnippetsUsage(){const t=[];return e.queries.current.forEach(n=>{if(!n.typedAsSQL)return;y.uniq(n.sql.match(jn.sqlSnippet)).forEach(i=>{t.push({queryID:n.id,sqlSnippetKey:i,queryName:n.name})})}),y.groupBy(t,"sqlSnippetKey")},get hasUnusedSQLSnippets(){return e.sqlSnippets.current.length>Object.keys(this.sqlSnippetsUsage).length},findSQLSnippetUsage(t){return this.sqlSnippetsUsage[t]??[]}})).actions(e=>({removeUnusedQueries(){const t=new Set(Object.keys(e.queriesUsage)),n=e.queries.current.filter(r=>!t.has(r.id)).map(r=>r.id);e.queries.removeQueries(n)},removeUnusedSQLSnippets(){const t=new Set(Object.keys(e.sqlSnippetsUsage)),n=e.sqlSnippets.current.filter(r=>!t.has(r.key)).map(r=>r.key);e.sqlSnippets.removeByKeys(n)},duplicatePanelByID(t,n){var i;const r=e.panels.duplicateByID(t);r&&((i=e.views.findByID(n))==null||i.appendPanelID(r))},removePanelByID(t,n){var r;e.panels.removeByID(t),e.layouts.removeByPanelID(t),(r=e.views.findByID(n))==null||r.removePanelID(t)},addANewPanel(t){var r;const n=pt.v4();e.panels.append(Ll(n)),(r=e.views.findByID(t))==null||r.appendPanelID(n),e.layouts.addALayoutItem(n)},applyJSONSchema(t){var p;const{views:n,panels:r,filters:i,definition:o={},layouts:l}=t,{queries:c,sqlSnippets:u,mock_context:d}=o,h=new Map;if(Array.isArray(r)){const x=r.map(m=>{const j=pt.v4();return h.set(m.id,j),{...m,id:j}});if(e.panels.appendMultiple(x),!Array.isArray(n)||n.length===0){const m=x.map(j=>j.id);(p=e.views.VIE)==null||p.appendPanelIDs(m)}}if(Array.isArray(n)){const x=n.map(m=>{const j=m.panelIDs.map(C=>h.get(C)??C);return{...m,id:pt.v4(),panelIDs:j}});e.views.appendMultiple(x)}if(Array.isArray(l)){const x=(C,T)=>e.layouts.breakpointNameRecord[C]===T;let m=[];const j=l.filter(C=>x(C.name,C.breakpoint));j.forEach(C=>{C.id==="basis"&&(m=C.list),C.list.forEach(T=>{const D=h.get(T.panelID);T.id=pt.v4(),T.panelID=D})}),e.layouts.list.forEach(C=>{const T=j.find(D=>D.name===C.name&&D.breakpoint===C.breakpoint);if(!T){m.forEach(D=>{C.addLayout(D)});return}T.list.forEach(D=>{C.addLayout(D)})})}Array.isArray(i)&&e.filters.appendMultiple(i),Array.isArray(c)&&e.queries.appendMultiple(c),Array.isArray(u)&&e.sqlSnippets.appendMultiple(u),d&&Object.keys(d).length>0&&e.mock_context.defaults(d)}})).actions(e=>({reset(){f.applySnapshot(e.filters.current,e.origin.filters.current),f.applySnapshot(e.queries.current,e.origin.queries.current),f.applySnapshot(e.sqlSnippets.current,e.origin.sqlSnippets.current),f.applySnapshot(e.views.current,e.origin.views.current),f.applySnapshot(e.panels.list,e.origin.panels.list),f.applySnapshot(e.layouts.list,e.origin.layouts.list),e.mock_context.current=e.origin.mock_context.current},resetFilters(){f.applySnapshot(e.filters.current,e.origin.filters.current)},updateCurrent(t){const{id:n,name:r,content:i}=t;if(!i)throw new Error("unexpected null content when updating a content model");const{version:o,filters:l,views:c,panels:u,definition:{queries:d,sqlSnippets:h,mock_context:p={}}}=i;e.id=n,e.name=r,e.version=o,f.applySnapshot(e.filters.current,l),f.applySnapshot(e.views.current,ai(c).current),f.applySnapshot(e.panels.list,u),f.applySnapshot(e.queries.current,d),f.applySnapshot(e.sqlSnippets.current,h),e.mock_context.current=p}})),oi=f.types.snapshotProcessor(M_,{preProcessor(e){return{...e,origin:e}},postProcessor(e){delete e.origin;const t=f.castToSnapshot(e.queries.current.map(n=>y.pick(n,["id","key","type","sql"])));return y.defaults({},{queries:{current:t}},e)}});function z_(e,t){t.filters&&f.applySnapshot(e.filters.current,t.filters)}function fc({id:e,name:t,dashboard_id:n,create_time:r,update_time:i,content:o},l,c){if(!o)throw new Error("unexpected null content when creating a content model");const{version:u,filters:d,views:h,panels:p,layouts:x,definition:{queries:m,sqlSnippets:j,mock_context:C={}}}=o;return oi.create({id:e,name:t,dashboard_id:n,create_time:r,update_time:i,version:u,filters:Jr(d,l,C,c),queries:{current:m},sqlSnippets:{current:j},mock_context:Mr(C),views:ai(h),panels:{list:p},layouts:{list:x,currentBreakpoint:x[0].id}})}const gc=f.types.model({id:f.types.identifier,name:f.types.string,group:f.types.string,content:oi,content_id:f.types.string,datasources:__,globalSQLSnippets:Wr,context:Hn,editor:T_}).views(e=>({get json(){return{id:e.id,name:e.name,group:e.group,content_id:e.content_id}}})).actions(e=>({updateCurrentContent(t){e.content.updateCurrent(t)},updateCurrent(t,n){const{id:r,name:i,group:o,content_id:l}=t;e.id=r,e.name=i,e.group=o,e.content_id=l,this.updateCurrentContent(n)}}));function mc({id:e,name:t,group:n,content_id:r},i,o,l,c,u){return gc.create({id:e,name:t,group:n,content_id:r,content:fc(i,c,u),datasources:{list:o},globalSQLSnippets:{list:l},context:Rr(c),editor:{}})}function yc(e,t){g.useEffect(()=>{const n=r=>{console.log(r);const{viewID:i}=r.detail;if(!i){console.error(new Error("[Open View] Needs to pick a view first"));return}e.views.appendToVisibles(i),t&&e.views.setIDOfVIE(i)};return window.addEventListener("open-view",n),()=>{window.removeEventListener("open-view",n)}},[e,t]),g.useEffect(()=>{const n=r=>{console.log(r);const{dictionary:i,payload:o}=r.detail;if(!o||Object.keys(o).length===0){console.error(new Error("[Set Filter Values] payload is empty"));return}Object.entries(i).forEach(([l,c])=>{e.filters.setValueByKey(l,y.get(o,c))})};return window.addEventListener("set-filter-values",n),()=>{window.removeEventListener("set-filter-values",n)}},[e]),g.useEffect(()=>{function n(i){return Array.isArray(i)?[]:typeof i=="object"?{}:typeof i=="boolean"?!1:typeof i=="string"?"":typeof i=="number"?0:i}const r=i=>{console.log(i);const{filter_keys:o}=i.detail;o.forEach(l=>{const c=y.get(e.filters.values,l),u=n(c);console.log(`${l}: ${u}`),e.filters.setValueByKey(l,u)})};return window.addEventListener("clear-filter-values",r),()=>{window.removeEventListener("clear-filter-values",r)}},[e]),g.useEffect(()=>{const n=r=>{console.log(r);const{urlTemplate:i,openInNewTab:o,enableEncoding:l=!1,payload:c}=r.detail;if(!i){console.error(new Error("[Open Link] URL is empty"));return}function u(p){return y.cloneDeepWith(p,m=>{if(l&&typeof m=="string")return encodeURIComponent(m)})}const h=y.template(i||"")(u({...c,filters:e.payloadForSQL.filters,context:e.payloadForSQL.context}));window.open(h,o?"_blank":"_self","noopener")};return window.addEventListener("open-link",n),()=>{window.removeEventListener("open-link",n)}},[e])}function bc(e){return g.useCallback(t=>t.provideValue(ue.pluginManager,e.pluginManager).provideValue(ue.vizManager,e.vizManager).provideValue(ue.colorManager,e.colorManager),[])}const QI="",A_=S.observer(({saveDashboardChanges:e})=>{const t=ze.useModals(),n=W(),r=()=>{t.openConfirmModal({title:s.jsxs(a.Group,{position:"left",children:[s.jsx(_.IconAlertTriangle,{size:18,color:"red"}),s.jsx(a.Text,{children:"You are reverting changes"})]}),labels:{confirm:"Confirm",cancel:"Cancel"},confirmProps:{color:"red"},onCancel:()=>console.log("Cancel"),onConfirm:()=>n.reset(),zIndex:320,withCloseButton:!1})},i=n.changed;return s.jsxs(a.Group,{spacing:0,children:[s.jsx(a.Button,{color:"green",variant:"filled",size:"xs",leftIcon:s.jsx(_.IconDeviceFloppy,{size:18}),onClick:e,disabled:!i,sx:{borderTopRightRadius:0,borderBottomRightRadius:0},children:"Save Changes"}),s.jsxs(a.Menu,{width:200,trigger:"hover",openDelay:100,closeDelay:400,withinPortal:!0,zIndex:320,disabled:!i,children:[s.jsx(a.Menu.Target,{children:s.jsx(a.ActionIcon,{variant:"default",disabled:!i,sx:{height:"30px",borderTopLeftRadius:0,borderBottomLeftRadius:0,svg:{fill:"rgb(173, 181, 189)",stroke:"none"}},children:s.jsx(_.IconCaretDown,{size:18})})}),s.jsx(a.Menu.Dropdown,{children:s.jsx(a.Menu.Item,{icon:s.jsx(_.IconRecycle,{size:14,color:"red"}),disabled:!i,onClick:r,children:"Revert Changes"})})]})]})}),E_=S.observer(({saveDashboardChanges:e,onExit:t,headerSlot:n=null})=>{const r=X(),i=r.content.changed,o=()=>{t({hasChanges:i,dashboardId:r.id})};return s.jsx(a.Header,{height:60,px:"md",py:0,sx:{zIndex:299},children:s.jsxs(a.Group,{position:"apart",sx:{height:60,minWidth:"1000px",position:"relative"},children:[s.jsxs(a.Group,{children:[s.jsx(a.Button,{size:"xs",color:i?"red":"green",leftIcon:s.jsx(_.IconArrowLeft,{size:20}),onClick:o,children:s.jsxs(a.Group,{spacing:4,children:["End Editing",s.jsx(a.Text,{td:"underline",children:r.name})]})}),s.jsx(A_,{saveDashboardChanges:e})]}),s.jsx(a.Group,{position:"right",sx:{flexGrow:1},children:n})]})})}),jc={height:"30px",borderLeft:"none",borderTop:"none",borderRight:"1px solid #e9ecef",borderBottom:"1px solid #e9ecef"},P_=S.observer(()=>{var r;const e=W(),t=((r=e.views.VIE)==null?void 0:r.type)===L.Tabs,n=()=>e.addANewPanel(e.views.idOfVIE);return t?s.jsx(a.Tooltip,{label:"Please choose a tab first",children:s.jsx(a.Button,{variant:"outline",color:"gray",radius:0,size:"xs",leftIcon:s.jsx(_.IconPlaylistAdd,{size:20}),sx:{...jc,transform:"none !important"},children:"Add a Panel"})}):s.jsx(a.Button,{variant:"outline",color:"blue",radius:0,size:"xs",onClick:n,leftIcon:s.jsx(_.IconPlaylistAdd,{size:20}),sx:{...jc,background:"rgb(231, 245, 255)"},children:"Add a Panel"})}),L_=S.observer(({done:e})=>{var Y,R;const n=W().layouts,r=g.useMemo(()=>({list:n.breakpointsInfo}),[n.breakpointsInfo]),{control:i,handleSubmit:o,watch:l,getValues:c,reset:u,formState:d}=b.useForm({defaultValues:r}),{fields:h,append:p,remove:x}=b.useFieldArray({control:i,name:"list",rules:{validate:F=>{if(console.log({values:F}),y.uniqBy(F,"breakpoint").length!==F.length)return"Screen sizes should be unique by min width"}}}),m=l("list"),j=h.map((F,Z)=>({...F,...m[Z]})),C=()=>{p({id:pt.v4(),name:"",breakpoint:""})},T=({list:F})=>{const Z=F.filter(se=>Number.isFinite(se.breakpoint));n.updateLayoutSetsInfo(Z),e()},D=c(),A=g.useMemo(()=>{const F={list:D.list.filter(Z=>!!Z.name&&Number.isFinite(Z.breakpoint))};return!y.isEqual(F,r)},[D,r]),N=(R=(Y=d.errors.list)==null?void 0:Y.root)==null?void 0:R.message;return s.jsx(s.Fragment,{children:s.jsxs("form",{onSubmit:o(T),children:[s.jsxs(a.Table,{fontSize:"sm",highlightOnHover:!0,withBorder:!0,sx:{tableLayout:"fixed"},children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{style:{width:"340px"},children:"Name"}),s.jsx("th",{style:{width:"160px"},children:"Min Width"}),s.jsx("th",{})]})}),s.jsxs("tbody",{children:[j.map((F,Z)=>s.jsxs("tr",{children:[s.jsx("th",{children:F.id==="basis"?F.name:s.jsx(b.Controller,{name:`list.${Z}.name`,control:i,render:({field:se})=>s.jsx(a.TextInput,{size:"xs",label:"",required:!0,sx:{flex:1},...se})})}),s.jsx("td",{children:F.id==="basis"?s.jsxs(a.Text,{ff:"monospace",children:[F.breakpoint,"px"]}):s.jsx(b.Controller,{name:`list.${Z}.breakpoint`,control:i,render:({field:se})=>s.jsx(a.NumberInput,{size:"xs",label:"",required:!0,max:1e4,hideControls:!0,rightSection:s.jsx(a.Text,{color:"dimmed",children:"px"}),rightSectionProps:{style:{width:"30px"}},sx:{flex:1,fontFamily:"monospace"},styles:{input:{paddingRight:"30px"}},...se})})}),s.jsx("td",{children:F.id!=="basis"&&s.jsx(a.ActionIcon,{mx:"auto",size:"xs",variant:"subtle",color:"red",onClick:()=>x(Z),children:s.jsx(_.IconTrash,{})})})]},F.id)),s.jsx("tr",{style:{backgroundColor:"transparent"},children:s.jsx("td",{colSpan:3,style:{padding:"0"},children:s.jsx(a.Tooltip,{label:"Add a screen size",children:s.jsx(a.ActionIcon,{variant:"subtle",size:"md",color:"blue",onClick:C,sx:{width:"100%"},children:s.jsx(_.IconPlus,{size:18})})})})})]})]}),s.jsx(a.Text,{mt:6,ta:"right",size:"xs",color:"red",children:N??" "}),s.jsxs(a.Group,{mt:6,position:"apart",children:[s.jsx(a.Button,{color:"orange",size:"xs",onClick:()=>u(),leftIcon:s.jsx(_.IconRecycle,{size:18}),disabled:!A,children:"Revert"}),s.jsx(a.Button,{color:"green",size:"xs",type:"submit",leftIcon:s.jsx(_.IconDeviceFloppy,{size:18}),disabled:!A,children:"Save changes"})]})]})})}),B_=S.observer(()=>{const[e,{open:t,close:n}]=re.useDisclosure(!1),r=W(),i=r.layouts.currentBreakpoint,o=r.layouts.currentLayoutRange,l=()=>{setTimeout(()=>{window.dispatchEvent(new Event("resize"))},32)},c=()=>{n(),l()};return s.jsxs(s.Fragment,{children:[s.jsxs(a.Group,{children:[s.jsxs(a.Menu,{withArrow:!0,withinPortal:!0,zIndex:320,trigger:"hover",children:[s.jsx(a.Menu.Target,{children:s.jsx(a.Button,{size:"xs",variant:"subtle",leftIcon:s.jsx(_.IconDevices,{size:16}),sx:{borderRadius:0},children:s.jsxs(a.Group,{spacing:6,children:[s.jsx(a.Text,{size:"xs",fw:"normal",children:o.name}),s.jsx(a.Text,{size:"xs",color:"#777",children:r.layouts.currentRangeText})]})})}),s.jsxs(a.Menu.Dropdown,{children:[r.layouts.breakpointRanges.map(u=>s.jsx(a.Menu.Item,{onClick:()=>r.layouts.setCurrentBreakpoint(u.id),disabled:i===u.id,children:s.jsxs(a.Group,{position:"apart",children:[s.jsx(a.Text,{size:"sm",children:u.name}),s.jsx(a.Text,{size:"xs",color:"dimmed",children:u.text})]})},u.id)),s.jsx(a.Menu.Divider,{}),s.jsx(a.Menu.Item,{color:"blue",icon:s.jsx(_.IconSettings,{size:14}),onClick:t,children:s.jsx(a.Text,{size:"sm",children:"Manage screen sizes"})})]})]}),r.layouts.divisionPreviewScale<1&&s.jsx(a.Text,{size:"xs",color:"dimmed",children:xn(r.layouts.divisionPreviewScale).format({output:"percent",mantissa:0})})]}),s.jsx(a.Modal,{opened:e,onClose:c,title:"Screen sizes",withinPortal:!0,zIndex:320,size:600,closeOnClickOutside:!1,children:s.jsx(L_,{done:c})})]})}),vc={height:"30px",borderRight:"none",borderTop:"none",borderLeft:"1px solid #e9ecef",borderBottom:"1px solid #e9ecef"},O_=S.observer(()=>{var r;const e=W(),t=((r=e.views.VIE)==null?void 0:r.type)===L.Tabs,n=()=>{var i;return(i=e.views.VIE)==null?void 0:i.downloadSchema()};return t?s.jsx(a.Tooltip,{label:"Please choose a tab first",children:s.jsx(a.Button,{variant:"outline",color:"gray",radius:0,size:"xs",leftIcon:s.jsx(_.IconCode,{size:16}),sx:{...vc,transform:"none !important"},children:"Download this View"})}):s.jsx(a.Button,{variant:"outline",color:"blue",radius:0,size:"xs",onClick:n,leftIcon:s.jsx(_.IconCode,{size:16}),sx:{...vc},children:"Download this View"})}),$_=S.observer(({view:e})=>!e||e.type!==L.Division?null:s.jsxs(a.Stack,{children:[s.jsx(a.Divider,{mt:8,mb:0,label:"Division settings",labelPosition:"center"}),s.jsx(a.Text,{align:"center",size:"xs",color:"dimmed",children:"Under construction"})]})),V_=[{value:"default",label:"Default"},{value:"outline",label:"Outline"},{value:"pills",label:"Pills"}],q_=[{value:"horizontal",label:"Horizontal"},{value:"vertical",label:"Vertical"}],N_=S.observer(({view:e})=>{if(!e||e.type!==L.Tabs)return null;const t=e.config;return s.jsxs(a.Stack,{children:[s.jsx(a.Divider,{mt:8,mb:0,label:"Tabs settings",labelPosition:"center"}),s.jsx(a.Select,{label:"Variant",value:t.variant,onChange:t.setVariant,data:V_}),s.jsx(a.Select,{label:"Orientation",value:t.orientation,onChange:t.setOrientation,data:q_}),s.jsx(a.Switch,{label:"Grow Tabs",checked:t.grow,onChange:n=>t.setGrow(n.currentTarget.checked)})]})}),F_=({disabled:e,value:t,onChange:n})=>{const r=i=>{i&&n(i)};return s.jsxs(a.Box,{sx:{position:"relative"},children:[e&&s.jsx(a.Overlay,{opacity:.6,color:"#fff",zIndex:5,blur:2}),s.jsx(fe,{height:"500px",defaultLanguage:"javascript",value:t,onChange:r,theme:"vs-dark",options:{minimap:{enabled:!1},readOnly:e}})]})},G_=({value:e,onChange:t})=>{const[n,{setTrue:r,setFalse:i}]=$.useBoolean(),[o,l]=g.useState(e??Zn),c=x=>{l({...o,enabled:x})},u=()=>{i();const{enabled:x,func_content:m}=o,j={enabled:x,func_content:m};l(j),t(j)},d=()=>{i(),l(e)},h=x=>{l(m=>({...m,func_content:x}))},p=()=>{h(Zn.func_content)};return s.jsxs(s.Fragment,{children:[s.jsx(a.ActionIcon,{size:"lg",color:"blue",variant:"filled",mt:26,onClick:r,sx:{flexGrow:0},children:s.jsx(k.Settings,{size:14})}),s.jsx(a.Modal,{size:800,title:"Customize modal title",opened:n,onClose:i,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:n&&s.jsxs(a.Stack,{children:[s.jsx(a.Checkbox,{mt:10,label:"Enabled",checked:o.enabled,onChange:x=>c(x.currentTarget.checked)}),s.jsx(F_,{value:o.func_content,onChange:h,disabled:!o.enabled}),s.jsxs(a.Group,{position:"apart",children:[s.jsx(a.Button,{onClick:p,color:"red",leftIcon:s.jsx(k.Recycle,{size:20}),children:"Reset"}),s.jsxs(a.Group,{position:"right",children:[s.jsx(a.Button,{onClick:d,variant:"subtle",children:"Cancel"}),s.jsx(a.Button,{onClick:u,children:"OK"})]})]})]})})]})},W_=S.observer(({view:e})=>{if(!e||e.type!==L.Modal)return null;const t=e.config,n=t.custom_modal_title.value;return s.jsxs(a.Stack,{children:[s.jsx(a.Divider,{mt:8,label:"Modal settings",labelPosition:"center"}),s.jsxs(a.Flex,{gap:10,children:[s.jsx(a.TextInput,{label:"Modal Title",value:n,onChange:y.noop,disabled:!0,sx:{flexGrow:1}}),s.jsx(G_,{value:t.custom_modal_title,onChange:t.custom_modal_title.replace})]}),s.jsxs(a.Group,{grow:!0,children:[s.jsx(a.TextInput,{label:"Width",value:t.width,onChange:r=>t.setWidth(r.currentTarget.value),placeholder:"600px / 50vw"}),s.jsx(a.TextInput,{label:"Height",value:t.height,onChange:r=>t.setHeight(r.currentTarget.value),placeholder:"600px / 50vw"})]})]})}),R_=S.observer(({view:e})=>s.jsxs(s.Fragment,{children:[s.jsx($_,{view:e}),s.jsx(W_,{view:e}),s.jsx(N_,{view:e})]})),ns={[L.Division]:"Division",[L.Modal]:"Modal",[L.Tabs]:"Tabs"},Q_=[{label:ns[L.Division],value:L.Division},{label:ns[L.Modal],value:L.Modal},{label:ns[L.Tabs],value:L.Tabs}],U_=S.observer(({view:e})=>e?s.jsxs(a.Stack,{sx:{position:"relative"},children:[s.jsx(a.TextInput,{label:"Name",value:e.name,onChange:t=>{e.setName(t.currentTarget.value)}}),s.jsx(a.Select,{label:"Type",withinPortal:!0,zIndex:320,value:e.type,onChange:e.setType,data:Q_}),s.jsx(R_,{view:e})]}):null),ss=({headers:e,rows:t})=>s.jsxs(a.Table,{fontSize:"xs",highlightOnHover:!0,sx:{tableLayout:"fixed",fontFamily:"monospace"},children:[s.jsx("thead",{children:e}),s.jsx("tbody",{children:t})]}),K_=({content:e})=>{const t=e.views;return!Array.isArray(t)||t.length===0?null:s.jsxs(a.Box,{children:[s.jsx(a.Text,{pl:10,size:"sm",fw:500,c:"dimmed",ta:"center",children:"Views"}),s.jsx(ss,{headers:s.jsxs("tr",{children:[s.jsx("th",{style:{width:"160px"},children:"ID"}),s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Type"})]}),rows:t.map(n=>s.jsxs("tr",{children:[s.jsx("td",{children:n.id}),s.jsx("td",{children:n.name}),s.jsx("td",{children:ns[n.type]})]},n.id))})]})},Y_=({content:e})=>{const t=e.filters;return!Array.isArray(t)||t.length===0?null:s.jsxs(a.Box,{children:[s.jsx(a.Text,{pl:10,size:"sm",fw:500,c:"dimmed",ta:"center",children:"Filters"}),s.jsx(ss,{headers:s.jsxs("tr",{children:[s.jsx("th",{style:{width:"160px"},children:"ID"}),s.jsx("th",{children:"Key"}),s.jsx("th",{children:"Label"})]}),rows:t.map(n=>s.jsxs("tr",{children:[s.jsx("td",{children:n.id}),s.jsx("td",{children:n.key}),s.jsx("td",{children:n.label})]},n.id))})]})},X_=({content:e})=>{const t=e.panels;return!Array.isArray(t)||t.length===0?null:s.jsxs(a.Box,{children:[s.jsx(a.Text,{pl:10,size:"sm",fw:500,c:"dimmed",ta:"center",children:"Panels"}),s.jsx(ss,{headers:s.jsxs("tr",{children:[s.jsx("th",{style:{width:"160px"},children:"ID"}),s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Visualization"})]}),rows:t.map(n=>s.jsxs("tr",{children:[s.jsx("td",{children:n.id}),s.jsx("td",{children:n.name}),s.jsx("td",{children:n.viz.type})]},n.id))})]})},J_=({content:e})=>{var n;const t=(n=e.definition)==null?void 0:n.queries;return!Array.isArray(t)||t.length===0?null:s.jsxs(a.Box,{children:[s.jsx(a.Text,{pl:10,size:"sm",fw:500,c:"dimmed",ta:"center",children:"Queries"}),s.jsx(ss,{headers:s.jsxs("tr",{children:[s.jsx("th",{style:{width:"160px"},children:"ID"}),s.jsx("th",{children:"Name"}),s.jsx("th",{style:{width:"140px"},children:"Type"}),s.jsx("th",{style:{width:"260px"},children:"Data Source"})]}),rows:t.map(r=>s.jsxs("tr",{children:[s.jsx("td",{children:r.id}),s.jsx("td",{children:r.name}),s.jsx("td",{children:r.type}),s.jsx("td",{children:r.key})]},r.id))})]})},Z_=({content:e})=>{var n;const t=(n=e.definition)==null?void 0:n.sqlSnippets;return!Array.isArray(t)||t.length===0?null:s.jsxs(a.Box,{children:[s.jsx(a.Text,{pl:10,size:"sm",fw:500,c:"dimmed",ta:"center",children:"SQL Snippets"}),s.jsx(a.List,{size:"sm",pl:10,ff:"monospace",icon:s.jsx(_.IconPointFilled,{size:10}),children:t.map(r=>s.jsx(a.List.Item,{children:r.key},r.key))})]})},H_=({content:e})=>{var n;const t=Object.keys(((n=e.definition)==null?void 0:n.mock_context)??{});return t.length===0?null:s.jsxs(a.Box,{children:[s.jsx(a.Text,{pl:10,size:"sm",fw:500,c:"dimmed",ta:"center",children:"Mock Context"}),s.jsx(a.List,{size:"sm",pl:10,ff:"monospace",icon:s.jsx(_.IconPointFilled,{size:10}),children:t.map(r=>s.jsx(a.List.Item,{children:r},r))})]})},ek=({content:e})=>e?s.jsxs(a.Box,{children:[s.jsx(a.Divider,{mt:20,mb:10,variant:"dashed"}),s.jsx(a.Text,{ta:"left",c:"dimmed",children:"Preview"}),s.jsxs(a.Stack,{children:[s.jsx(K_,{content:e}),s.jsx(Y_,{content:e}),s.jsx(X_,{content:e}),s.jsx(J_,{content:e}),s.jsx(Z_,{content:e}),s.jsx(H_,{content:e})]})]}):null;function tk(e){if(e.target===null)throw new Error("FileReader failed with null result");if(typeof e.target.result!="string")throw new Error(`Unparsable file content of type: ${typeof e.target.result}`);let t=JSON.parse(e.target.result);if("content"in t&&(t=t.content),t.version!==at)throw new Error("Schema version mismatch");return t}const nk=S.observer(({onSuccess:e,stretchModal:t,shrinkModal:n})=>{var T,D;const r=W(),{handleSubmit:i,formState:{errors:o},setValue:l,watch:c,setError:u,clearErrors:d}=b.useForm({defaultValues:{content:null}}),h=({content:A})=>{try{if(!A)throw new Error("please use a valid json file");r.applyJSONSchema(A),ut.showNotification({title:"Successful",message:"",color:"green"}),e()}catch(N){console.error(N),ut.showNotification({title:"Failed",message:N.message,color:"red"})}},[p,x]=g.useState(null);g.useEffect(()=>{if(!p)return;const A=new FileReader;A.readAsText(p,"UTF-8"),A.onload=N=>{try{const Y=tk(N);l("content",Y),d("content")}catch(Y){console.error(Y),u("content",{type:"custom",message:Y.message})}},A.onabort=()=>console.log("🟨 abort"),A.onerror=()=>{A.error&&(console.error(A.error),u("content",{type:"custom",message:A.error.message}))}},[p]);const[m]=c(["content"]),j=!m,C=(T=o==null?void 0:o.content)==null?void 0:T.message;return g.useEffect(()=>{!m||C?n():t()},[m,C]),s.jsx(a.Box,{mx:"auto",sx:{position:"relative"},children:s.jsxs("form",{onSubmit:i(h),children:[s.jsx(a.FileInput,{label:"JSON File",required:!0,value:p,onChange:x,error:(D=o==null?void 0:o.content)==null?void 0:D.message,sx:{maxWidth:500}}),C?s.jsx(a.Table,{fontSize:12,mt:10,children:s.jsxs("tbody",{children:[s.jsxs("tr",{children:[s.jsx("th",{children:"Dashboard"}),s.jsx("td",{children:at})]}),s.jsxs("tr",{children:[s.jsx("th",{children:"This file"}),s.jsx("td",{style:{color:"red"},children:m==null?void 0:m.version})]})]})}):s.jsxs(s.Fragment,{children:[s.jsx(ek,{content:m}),s.jsx(a.Group,{position:"right",my:"md",children:s.jsx(a.Button,{type:"submit",color:"green",disabled:j,children:"Confirm"})})]})]})})}),wc={height:"30px",borderLeft:"none",borderTop:"none",borderRight:"1px solid #e9ecef",borderBottom:"1px solid #e9ecef"},sk=S.observer(()=>{var u;const[e,{open:t,close:n}]=re.useDisclosure(!1),[r,{setTrue:i,setFalse:o}]=$.useBoolean(!1),c=((u=X().content.views.VIE)==null?void 0:u.type)===L.Tabs;return c?s.jsx(a.Tooltip,{label:"Please choose a tab first",children:s.jsx(a.Button,{variant:"outline",color:"gray",radius:0,size:"xs",leftIcon:s.jsx(_.IconFileImport,{size:16}),sx:{...wc,transform:"none !important"},children:"Import..."})}):s.jsxs(s.Fragment,{children:[s.jsx(a.Button,{variant:"subtle",color:"blue",radius:0,size:"xs",disabled:c||e,onClick:t,leftIcon:s.jsx(_.IconFileImport,{size:16}),sx:{...wc},children:"Import..."}),s.jsx(a.Modal,{opened:e,onClose:n,title:"Import content with schema json",trapFocus:!0,onDragStart:d=>{d.stopPropagation()},withinPortal:!0,zIndex:320,size:r?"90vw":500,children:s.jsx(nk,{onSuccess:n,stretchModal:i,shrinkModal:o})})]})}),rk={position:"fixed",top:60,left:0,right:0,height:30,zIndex:299,borderBottom:"1px solid #e9ecef",background:"rgba(233,236,239, 0.15)"},ik=S.observer(()=>s.jsx(a.Box,{sx:rk,pl:{base:200,xs:200,sm:200,md:220,lg:240,xl:260},children:s.jsxs(a.Group,{position:"apart",align:"center",sx:{height:"30px"},children:[s.jsxs(a.Group,{position:"left",spacing:0,children:[s.jsx(P_,{}),s.jsx(sk,{})]}),s.jsx(B_,{}),s.jsx(a.Group,{position:"right",spacing:0,children:s.jsx(O_,{})})]})})),ak=S.observer(e=>s.jsxs(s.Fragment,{children:[s.jsx(E_,{...e}),s.jsx(ik,{})]})),UI="";function ok(e,t,n){const r=[];return e.filter(i=>"__INTERACTIONS"in i.viz.conf).forEach((i,o)=>{const l=t[i.id];l.data.interactions=y.get(l,"data.interactions",[]);const{__INTERACTIONS:c,__OPERATIONS:u,__TRIGGERS:d}=i.viz.conf;Object.entries(u).forEach(([h,p])=>{const{schemaRef:x,data:m}=p,{config:j}=m;switch(x){case"builtin:op:open-link":let C=j.urlTemplate.substring(0,100);j.urlTemplate.length>=20&&(C+="..."),l.type="interaction",l.data.interactions.push({schemaRef:x,urlTemplate:j.urlTemplate,shortURLTemplate:C});return;case"builtin:op:open_view":r.push({id:`OPERATION--${h}`,source:i.id,target:j.viewID,label:"Open View",style:{stroke:"rgba(0,0,0,0.8)"},type:"default"});return;case"builtin:op:set_filter_values":l.type="interaction",l.data.interactions.push({schemaRef:x,filters:Object.keys(j.dictionary).map(T=>({key:T,label:n[T]}))});return;case"builtin:op:clear_filter_values":l.type="interaction",l.data.interactions.push({schemaRef:x,filters:j.filter_keys.map(T=>({key:T,label:n[T]}))});return;default:return}})}),r}function lk(e,t){const n=e.filters.keyLabelMap;return{edges:ok(e.panels.list,t,n),edgeNodes:[]}}function Cc(e,t,n){return e*t+e*n}function ck(e,t,n){return e*t+(e-1)*n}const rs=25,li=40,Sc=25,ci=350,uk=150,dk=150,_c=150,kc=300,is=40,Tc=25,pk=300;function hk(e,t){const n=y.keyBy(t,i=>i.id),r=[];return e.current.forEach((i,o)=>{i.panelIDs.forEach((l,c)=>{const u=Cc(c,is,Tc)+li,d=n[l];if(!d){r.push({id:l,_node_type:"panel",parentNode:i.id,data:{label:`!: ${l}`},position:{x:rs,y:u},sourcePosition:ye.Position.Right,targetPosition:ye.Position.Left,style:{width:kc,height:is}});return}const h=d.name;r.push({id:d.id,_node_type:"panel",parentNode:i.id,data:{label:h},position:{x:rs,y:u},sourcePosition:ye.Position.Right,targetPosition:ye.Position.Left,style:{width:kc,height:is}})})}),r}const xk={[L.Division]:"Div",[L.Modal]:"Modal",[L.Tabs]:"Tabs"},fk=oc;function gk(e){return e.current.map((n,r)=>{const i=ck(n.panelIDs.length,is,Tc)+li+Sc;let o=[];return n.type===L.Tabs&&(o=n.config.tabsInOrder.map(c=>c.view_id)),{id:n.id,_node_type:"view-root",_view_type:n.type,_view_level:0,_sub_view_ids:[],_tab_view_ids:o,data:{label:`${xk[n.type]}:${n.name}`},position:{x:0,y:0},sourcePosition:ye.Position.Right,targetPosition:ye.Position.Left,className:"light",style:{backgroundColor:fk[n.type],width:ci,height:i}}})}function mk(e){const t=y.keyBy(e,n=>n.id);e.forEach(n=>{n._node_type!=="view-root"||n._view_type!==L.Tabs||n._tab_view_ids.forEach(r=>{t[r].parentNode=n.id})})}function yk(e){const t=gk(e.views);mk(t);const n=hk(e.views,e.panels.list);return[...t,...n]}function bk({nodeMap:e,nodes:t,edges:n}){t.forEach(r=>{r._node_type!=="view-root"||r._view_type!==L.Tabs||(r.sourcePosition=ye.Position.Bottom,r.style.width=ci+rs*2,r.style.height=Sc+r._tab_view_ids.reduce((i,o)=>{const l=e[o];l.position.y=i,l.position.x=rs;const c=l.style.height;return i+c+20},li))})}function jk({nodeMap:e,nodes:t,edges:n}){n.filter(r=>r.label==="Open View").forEach(r=>{const i=e[r.source],o=e[r.target];if(!i||!o||!i.parentNode)return;const l=e[i.parentNode];l._node_type!=="view-root"||o._node_type!=="view-root"||(o._view_level+=1+l._view_level,l._sub_view_ids.push(o.id))}),t.sort((r,i)=>r._node_type==="view-root"&&i._node_type==="view-root"?r._view_level-i._view_level:r._node_type!=="view-root"&&i._node_type!=="view-root"?0:r._node_type==="view-root"?-1:1)}function vk({nodeMap:e,nodes:t,edges:n}){const r={};n.forEach(i=>{if(i.label!=="Open View")return;const o=e[i.source],l=e[i.target];if(o&&l&&o.parentNode){const c=e[o.parentNode],u=c.position.x,d=Number(y.get(l,"style.height",0)),h=Number(c.style.width);l.position.x=u+h+pk,c._view_level===0&&l._sub_view_ids.length===0&&(o.sourcePosition=ye.Position.Left,l.targetPosition=ye.Position.Right,l.position.x*=-1);const x=l.position.x,m=y.get(r,x,0);l.position.y=m,r[x]=m+d+_c}})}function wk({nodeMap:e,nodes:t,edges:n}){const r=new Set,i=new Set;n.forEach(l=>{r.add(l.source),i.add(l.target)}),t.filter(l=>l._node_type!=="view-root"||l.id==="Main"||l.parentNode?!1:!r.has(l.id)&&!i.has(l.id)).forEach((l,c)=>{l.position.x=Cc(c,ci,dk),l.position.y=0-uk-_c})}function Ck({nodeMap:e,nodes:t,edges:n}){const r={nodeMap:e,nodes:t,edges:n};return wk(r),jk(r),bk(r),vk(r),{nodes:t,edges:n}}function Sk(e){const t=yk(e),n=y.keyBy(t,u=>u.id),{edges:r,edgeNodes:i}=lk(e,n),o=[...t,...i],l=y.keyBy(o,u=>u.id),c={edges:y.uniqBy(r,u=>u.id),nodes:o,nodeMap:l};return Ck(c)}const KI="",ui={"builtin:op:open-link":s.jsx(a.ThemeIcon,{color:"blue",size:20,radius:"xl",children:s.jsx(_.IconCircleDashed,{size:14})}),"builtin:op:set_filter_values":s.jsx(a.ThemeIcon,{color:"orange",size:20,radius:"xl",children:s.jsx(_.IconCircleDot,{size:14})}),"builtin:op:clear_filter_values":s.jsx(a.ThemeIcon,{color:"orange",size:20,radius:"xl",children:s.jsx(_.IconCircleOff,{size:14})})};function _k(e){const t=[];return e.forEach(n=>{switch(n.schemaRef){case"builtin:op:open-link":t.push({key:n.urlTemplate,icon:ui[n.schemaRef],text:s.jsxs(a.Group,{spacing:4,children:[s.jsx(a.Text,{children:"Open: "}),s.jsx(a.Text,{color:"dimmed",children:n.shortURLTemplate})]})});return;case"builtin:op:set_filter_values":n.filters.forEach(({key:r,label:i})=>{t.push({key:n.schemaRef+r,icon:ui[n.schemaRef],text:s.jsx(a.Group,{spacing:4,children:s.jsxs(a.Text,{children:["Set Filter: ",i]})})})});return;case"builtin:op:clear_filter_values":n.filters.forEach(({key:r,label:i})=>{t.push({key:n.schemaRef+r,icon:ui[n.schemaRef],text:s.jsx(a.Group,{spacing:4,children:s.jsxs(a.Text,{children:["Clear Filter: ",i]})})})});return}}),t}const kk=g.memo(({data:e,isConnectable:t,sourcePosition:n=ye.Position.Right,targetPosition:r=ye.Position.Left,...i})=>{const o=g.useMemo(()=>_k(e.interactions),[e.interactions]);return s.jsxs(s.Fragment,{children:[s.jsx(ye.Handle,{type:"target",position:r,isConnectable:t}),s.jsx(a.Box,{sx:{position:"absolute",top:0,right:0},children:s.jsx(k.ChevronsUpRight,{size:12})}),s.jsxs(a.HoverCard,{shadow:"xl",withinPortal:!0,children:[s.jsx(a.HoverCard.Target,{children:s.jsx(a.Text,{children:e.label})}),s.jsx(a.HoverCard.Dropdown,{children:s.jsx(a.List,{spacing:"xs",size:"sm",center:!0,children:o.map(l=>s.jsx(a.List.Item,{icon:l.icon,children:l.text},l.key))})})]}),s.jsx(ye.Handle,{type:"source",position:n,isConnectable:t})]})}),YI="",Tk={interaction:kk},Dk=S.observer(()=>{const e=ce(),{edges:t,nodes:n}=Sk(e);return s.jsxs(ye,{nodes:n,edges:t,onNodesChange:y.noop,onEdgesChange:y.noop,onConnect:y.noop,className:"interactions-viewer",fitView:!0,nodeTypes:Tk,children:[s.jsx(ye.MiniMap,{}),s.jsx(ye.Controls,{}),s.jsx(ye.Background,{})]})}),Ik=S.observer(({opened:e,close:t})=>s.jsx(a.Modal,{size:"96vw",opened:e,onClose:t,title:"Interactions",trapFocus:!0,onDragStart:n=>{n.stopPropagation()},styles:{body:{height:"calc(90vh - 54px)"},content:{transform:"none !important"}},zIndex:300,children:s.jsx(Dk,{})})),Mk={"> button":{"&:first-of-type":{borderTopRightRadius:0,borderBottomRightRadius:0,borderRightWidth:.5},":not(:first-of-type):not(:last-of-type)":{borderTopRightRadius:0,borderBottomRightRadius:0,borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeftWidth:.5,borderRightWidth:.5},"&:last-of-type":{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeftWidth:.5}}};function zk({onClick:e,name:t,active:n,openSettings:r}){return s.jsxs(a.Box,{sx:{position:"relative"},children:[s.jsx(a.UnstyledButton,{sx:i=>({display:"block",width:"100%",padding:i.spacing.xs,borderRadius:0,position:"relative",color:i.black,"&:hover":{backgroundColor:i.colors.gray[0]},backgroundColor:n?i.colors.gray[2]:"transparent"}),children:s.jsx(a.Group,{sx:{width:"calc(100% - 28px)"},onClick:e,children:s.jsx(a.Text,{size:"sm",children:t})})}),n&&s.jsx(a.Tooltip,{label:"Edit",position:"right",withinPortal:!0,children:s.jsx(a.ActionIcon,{onClick:r,variant:"light",color:"blue",sx:{position:"absolute",top:0,bottom:0,height:"100%",right:0,zIndex:0,borderRadius:0},children:s.jsx(_.IconAdjustments,{size:16})})})]})}const Ak=S.observer(()=>{const e=X(),t=W(),n=g.useCallback(i=>()=>t.views.setIDOfVIE(i),[t]),r=i=>{e.editor.open(["_VIEWS_",i])};return s.jsxs(a.Box,{sx:{position:"relative"},children:[t.views.options.map(i=>s.jsx(zk,{active:t.views.idOfVIE===i.value,name:i.label,onClick:n(i.value),openSettings:()=>r(i.value)},i.value)),s.jsx(a.Divider,{variant:"dashed"}),s.jsx(a.Button,{variant:"subtle",rightIcon:s.jsx(_.IconPlus,{size:14}),size:"sm",px:"xs",color:"blue",onClick:t.views.addARandomNewView,sx:{width:"100%",borderRadius:0},styles:{inner:{justifyContent:"space-between"}},children:"Add a View"})]})}),Ek=S.observer(()=>{const e=X(),t=W(),n=()=>{if(!t.queries.firstID){e.editor.open(["_QUERIES_",""]);return}e.editor.open(["_QUERIES_",t.queries.firstID])},r=()=>{if(!t.filters.firstID){e.editor.open(["_FILTERS_",""]);return}e.editor.open(["_FILTERS_",t.filters.firstID])},[i,o]=g.useState(!1),l=()=>o(!0),c=()=>o(!1);return s.jsxs(a.Navbar,{p:0,width:{base:200,xs:200,sm:200,md:220,lg:240,xl:260},zIndex:299,children:[s.jsxs(a.Navbar.Section,{children:[s.jsxs(a.Group,{grow:!0,spacing:0,sx:{...Mk,button:{borderWidth:0,borderBottomWidth:1,borderColor:"#e9ecef"}},children:[s.jsx(a.Tooltip,{label:"Filters",withinPortal:!0,children:s.jsx(a.ActionIcon,{variant:"default",radius:0,size:"md",sx:{height:"30px"},onClick:r,children:s.jsx(_.IconFilter,{size:18})})}),s.jsx(a.Tooltip,{label:"Queries",withinPortal:!0,children:s.jsx(a.ActionIcon,{variant:"default",radius:0,size:"md",sx:{height:"30px"},onClick:n,children:s.jsx(_.IconDatabase,{size:18})})}),s.jsx(a.Tooltip,{label:"Interactions Viewer",withinPortal:!0,children:s.jsx(a.ActionIcon,{variant:"default",radius:0,size:"md",sx:{height:"30px"},onClick:l,children:s.jsx(_.IconLink,{size:18})})})]}),s.jsx(Ik,{opened:i,close:c})]}),s.jsx(a.Navbar.Section,{py:5,sx:{borderBottom:"1px solid #eee"},children:s.jsx(a.Text,{align:"center",sx:{userSelect:"none",cursor:"default"},children:"Views"})}),s.jsx(a.Navbar.Section,{grow:!0,sx:{overflow:"auto"},children:s.jsx(Ak,{})}),s.jsx(a.Navbar.Section,{children:s.jsx(a.Group,{grow:!0,p:"md",pt:"sm",sx:{borderTop:"1px solid #eee"},children:s.jsx(a.Button,{size:"xs",leftIcon:s.jsx(_.IconSettings,{size:20}),onClick:()=>e.editor.open([]),children:"Settings"})})})]})}),Pk=["function getDefaultValue(filter, utils, context) {",' return "";',"}"].join(`
|