@devtable/dashboard 10.22.0 → 10.23.1

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.
@@ -51,7 +51,7 @@ Check the top-level render call using <`+V+">.")}return E}}function ku(S,E){{if(
51
51
  ${Gu.map(Wu).join("")}
52
52
  </tbody>
53
53
  </table>
54
- `;function fr(e,t){const n=Object.keys(t),r=Object.values(t);try{return new Function(...n,`return \`${e}\`;`)(...r)}catch(a){throw n.length===0&&e.includes("$")?new Error("[formatSQL] insufficient payload"):a}}function gr(e,t){try{return fr(e,t)}catch(n){return console.error(n),n.message}}function Ru({sql:e,pre_process:t}){if(!t.trim())return e;try{return new Function(`return ${t}`)()({sql:e},Tt)}catch(n){return console.error(n),e}}function Yu(e,t){if(!e.trim())return t;try{return new Function(`return ${e}`)()(t,Tt)}catch(n){return console.error(n),t}}function Qu(e){e=e||{};const t=Object.keys(e).sort(),n=[];for(let r=0;r<t.length;r++){const a=t[r];if(a!="authentication"&&e[a])n.push(t[r]+"="+(typeof e[a]=="object"?JSON.stringify(e[a]):e[a]));else{const o=Object.keys(e[a]).sort();for(let l=0;l<o.length;l++){const u=o[l];u!="sign"&&e[a][u]&&n.push(o[l]+"="+(typeof e[a][u]=="object"?JSON.stringify(e[a][u]):e[a][u]))}}}return n.sort().join("&")}function Ku(e,t){let n=Qu(e);return n+="&key="+t,Ia.MD5(n).toString().toUpperCase()}const qe={baseURL:"http://localhost:31200",app_id:"",app_secret:"",getAuthentication(e){if(!this.app_id||!this.app_secret)return;const t=new Date().getTime().toString();return{app_id:this.app_id,nonce_str:t,sign:Ku({app_id:this.app_id,nonce_str:t,...e},this.app_secret)}},getRequest(e,t){return(n,r,a={})=>{const o=window.localStorage.getItem("token"),l={"X-Requested-With":"XMLHttpRequest","Content-Type":a.string?"application/x-www-form-urlencoded":"application/json",authorization:o?`bearer ${o}`:"",...a.headers},u={baseURL:this.baseURL,method:e,url:n,params:e==="GET"?r:a.params,headers:l,signal:t};return["POST","PUT"].includes(e)&&(u.data=a.string?JSON.stringify(r):r,u.data.authentication=this.getAuthentication(u.data)),mt(u).then(c=>c.data).catch(c=>Promise.reject(c))}},makeQueryENV:null,query(e){return async(t,n={})=>{var r;return t.env||(t.env=((r=this.makeQueryENV)==null?void 0:r.call(this))??{error:"failed to run makeQueryENV"}),this.getRequest("POST",e)("/query",t,n)}}};function Xa(e){qe.baseURL!==e.apiBaseURL&&(qe.baseURL=e.apiBaseURL),e.app_id&&(qe.app_id=e.app_id),e.app_secret&&(qe.app_secret=e.app_secret),e.makeQueryENV&&(qe.makeQueryENV=e.makeQueryENV)}async function Uu({query:e,payload:t},n){if(!e.sql)return[];const{type:r,key:a,sql:o,pre_process:l,post_process:u}=e,c=fr(o,t),d=Ru({sql:c,pre_process:l});let f=await qe.query(n)({type:r,key:a,query:d},{});return f=Yu(u,f),f}async function Xu({type:e,key:t,configString:n},r){return await qe.query(r)({type:e,key:t,query:n},{})}async function mr(){try{return(await qe.getRequest("POST")("/datasource/list",{filter:{},sort:[{field:"create_time",order:"ASC"}],pagination:{page:1,pagesize:100}})).data}catch(e){return console.error(e),[]}}async function Ja(){try{return(await qe.getRequest("POST")("/sql_snippet/list",{filter:{},sort:[{field:"id",order:"ASC"}],pagination:{page:1,pagesize:1e3}})).data}catch(e){return console.error(e),[]}}class Za{constructor(t){q(this,"rootRef");this.rootRef=re.observable({current:t})}async deleteItem(t){re.runInAction(()=>{x.unset(this.rootRef.current,[t])})}getItem(t){const n=this.getValueFromRoot(t);return Promise.resolve(n)}getValueFromRoot(t){return t===null?re.toJS(this.rootRef.current):x.get(this.rootRef.current,[t])}setItem(t,n){if(t===null)if(x.isObject(n))re.runInAction(()=>{this.rootRef.current=n});else throw new Error("Cannot set root value to non-object");else re.runInAction(()=>{x.set(this.rootRef.current,[t],n)});return Promise.resolve(this.getItem(t))}watchItem(t,n,r){return re.reaction(()=>this.getValueFromRoot(t),(a,o)=>{n(a,o)},{requiresObservable:!0,fireImmediately:x.get(r,"fireImmediately",!1)})}}class Ju{constructor(){q(this,"channels",new Map);q(this,"globalChannel",new Aa)}getChannel(t){const n=this.channels.get(t);if(n)return n;const r=new Aa;return this.channels.set(t,r),r}}class Zu{constructor(t){q(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 Ju,instanceData:new Za(t.viz.conf)};return this.instances.set(t.id,r),r}}function Ha(e,t,n,r){return{vizManager:n,locale:"zh",msgChannels:e.messageChannels,instanceData:e.instanceData,pluginData:new Za({}),colorPalette:{getColor(){return()=>""}},data:t,variables:r}}const Hu=e=>{const{panel:t,vizManager:n,data:r,variables:a}=e,o=n.resolveComponent(t.viz.type),l=n.getOrCreateInstance(t),u={...Ha(l,r,n,a),viewport:{width:t.layout.w,height:t.layout.h}},c=o.viewRender;return i(c,{context:u,instance:l,...x.omit(e,["panel","vizManager","data"])})},ec=e=>{const{vizManager:t,panel:n,panelInfoEditor:r,data:a,variables:o}=e,l=t.resolveComponent(n.viz.type),u=t.getOrCreateInstance(n),c={...Ha(u,a,t,o),panelInfoEditor:r},d=l.configRender;return i(d,{context:c,instance:u,...x.omit(e,["panel","vizManager","data","panelInfoEditor"])})},es=(e,t)=>{const n=ct.bezier(e),r=ct.bezier(t);return function(a){return a<50?n(a*2/100).hex():r((a-50)*2/100).hex()}},Cn=e=>{const t=ct.bezier(e);return function(n){return t(n/100).hex()}},tc={type:"interpolation",displayName:"Red / Green",getColor:es(["darkred","deeppink","lightyellow"],["lightyellow","lightgreen","teal"]),name:"red-green",category:"diverging"},nc={type:"interpolation",displayName:"Yellow / Blue",getColor:es(["#8f531d","#ffd347","#e3efe3"],["#eefaee","#4ecbbf","#003f94"]),name:"yellow-blue",category:"diverging"},rc={type:"interpolation",displayName:"Red",getColor:Cn(["#fff7f1","darkred"]),name:"red",category:"sequential"},ic={type:"interpolation",displayName:"Green",getColor:Cn(["#f0ffed","darkgreen"]),name:"green",category:"sequential"},ac={type:"interpolation",displayName:"Blue",getColor:Cn(["#f9fcff","#48b3e9","darkblue"]),name:"blue",category:"sequential"},sc={type:"interpolation",displayName:"Orange",getColor:Cn(["#fff7f1","darkorange","#b60000"]),name:"orange",category:"sequential"};class oc{constructor(t){q(this,"symbol");this.symbol=Symbol(t)}}function dt(e){return new oc(e)}class yr{constructor(){q(this,"parent");q(this,"factoryRegistry",new Map);q(this,"instanceRegistry",new Map)}createScoped(){const t=new yr;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=x.get(t,"dispose");x.isFunction(n)&&n.bind(t)()}),this.instanceRegistry.clear(),this.factoryRegistry.clear()}}const ts="10.22.0",lc=Object.freeze(Object.defineProperty({__proto__:null,version:ts},Symbol.toStringTag,{value:"Module"}));class uc{constructor(t){q(this,"staticColors",new Map);q(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 cc{constructor(){q(this,"plugins",new Map);q(this,"vizComponents",new Map);q(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 dc{constructor(){q(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 a=this.migrations.filter(u=>u.version>t.from&&u.version<=t.to),o=x.orderBy(a,"version","asc");if(((l=x.last(o))==null?void 0:l.version)!==t.to)throw new Error(`Migration to version ${t.to} not found`);return o.reduce((u,c)=>c.handler(u,r),n)}}class me extends dc{constructor(){super(),this.configVersions()}version(t,n){return super.version(t,(r,a)=>({version:t,...n(r,a)}))}async migrate({configData:t,panelModel:n}){const r=await t.getItem(null),a=x.get(r,"version",0),o=this.run({from:a,to:this.VERSION},r,{panelModel:n});await t.setItem(null,o)}async needMigration({configData:t}){const n=await t.getItem(null);return x.get(n,"version",0)<this.VERSION}}const j=(e,t)=>{const[n,{setFalse:r}]=U.useBoolean(!0),[a,o]=y.useState();y.useEffect(()=>(e.getItem(t).then(u=>{o(u),r()}),e.watchItem(t,u=>{o(u)})));const l=y.useCallback(async u=>{await e.setItem(t,u),o(u)},[e,t]);return{loading:n,value:a,set:l}},br={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 L(e){const[t,n]=e.split(".");return{queryID:t,columnKey:n}}function pc(e){return e.includes(".")?L(e):{queryID:"",columnKey:e}}function pt(e,t){var a;const{queryID:n,columnKey:r}=L(t);return n?r?((a=e[n])==null?void 0:a.map(o=>o[r]))??[]:e[n]:[]}function Ht(e,t){const{queryID:n}=L(t);return n?e[n]:[]}function hc(e){return Object.values(e)[0]}function Sn(e,t){const{queryID:n,columnKey:r}=L(t);return e[r]}ie.use([F.GridComponent,F.VisualMapComponent,F.LegendComponent,F.TooltipComponent,Pe.CanvasRenderer]);function fc({context:e}){const{value:t}=j(e.instanceData,"config"),n=e.data,{width:r,height:a}=e.viewport,{x_axis_data_key:o,y_axis_data_key:l,z_axis_data_key:u,xAxis3D:c,yAxis3D:d,zAxis3D:f}=x.defaults({},t,br),h=y.useMemo(()=>Ht(n,o),[n,o]),{x:g,y:m,z:C}=y.useMemo(()=>({x:L(o),y:L(l),z:L(u)}),[o,l,u]),{min:w,max:_}=y.useMemo(()=>{const I=x.minBy(h,N=>N[C.columnKey]),B=x.maxBy(h,N=>N[C.columnKey]);return{min:x.get(I,C.columnKey),max:x.get(B,C.columnKey)}},[h,C]),D={tooltip:{},backgroundColor:"#fff",visualMap:{show:!0,dimension:2,min:w,max:_,inRange:{color:["#313695","#4575b4","#74add1","#abd9e9","#e0f3f8","#ffffbf","#fee090","#fdae61","#f46d43","#d73027","#a50026"]}},xAxis3D:c,yAxis3D:d,zAxis3D:f,grid3D:{viewControl:{projection:"orthographic",autoRotate:!1},light:{main:{shadow:!0,quality:"ultra",intensity:1.5}}},series:[{type:"bar3D",wireframe:{},data:h.map(I=>[I[g.columnKey],I[m.columnKey],I[C.columnKey]])}]};return t?i(Be,{echarts:ie,option:D,style:{width:r,height:a},notMerge:!0,theme:"merico-light"}):null}const ns=y.createContext(null),vr=ns.Provider;function xr(){const e=y.useContext(ns);if(!e)throw new Error("Please use DashboardModelContextProvider");return e}const ye=()=>xr(),wr=()=>xr(),rs=y.createContext(null),Cr=rs.Provider;function is(){const e=y.useContext(rs);if(!e)throw new Error("Please use ContentModelContextProvider");return e}const le=()=>is(),we=()=>is(),gc={inEditMode:!1},_n=y.createContext(gc),as=y.createContext({panel:null,data:{},loading:!1,errors:[],downloadPanelScreenshot:()=>{}}),Sr=as.Provider;function ss(){const e=y.useContext(as);if(!e.panel)throw new Error("Please use PanelContextProvider");return e}const bt=()=>ss(),nt=()=>ss(),mc={fullScreenPanelID:"",setFullScreenPanelID:x.noop},_r=y.createContext(mc);function os(){const e=y.useContext(_r);if(!e)throw new Error("Please use FullScreenPanelContext.Provider");return e}const W=k.observer(y.forwardRef(({label:e,required:t,value:n,onChange:r,clearable:a=!1,sx:o,...l},u)=>{const{panel:c}=nt(),d=y.useMemo(()=>{const f=[...c.dataFieldOptions];return a&&f.unshift({label:"unset",value:"",group:""}),f},[c.dataFieldOptions]);return i(s.Select,{ref:u,label:e,data:d,value:n,onChange:r,required:t,sx:o,maxDropdownHeight:500,...l})}));function yc({context:e}){const{value:t,set:n}=j(e.instanceData,"config"),r=x.defaults({},t,br),{control:a,handleSubmit:o,reset:l}=v.useForm({defaultValues:r});return y.useEffect(()=>{l(r)},[t]),t?i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:o(n),children:[i(s.Text,{children:"X Axis"}),p(s.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[i(v.Controller,{name:"x_axis_data_key",control:a,render:({field:u})=>i(W,{label:"Data Field",required:!0,...u})}),i(v.Controller,{name:"xAxis3D.name",control:a,render:({field:u})=>i(s.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...u})})]}),i(s.Text,{mt:"lg",children:"Y Axis"}),p(s.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[i(v.Controller,{name:"y_axis_data_key",control:a,render:({field:u})=>i(W,{label:"Data Field",required:!0,...u})}),i(v.Controller,{name:"yAxis3D.name",control:a,render:({field:u})=>i(s.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...u})})]}),i(s.Text,{mt:"lg",children:"Z Axis"}),p(s.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[i(v.Controller,{name:"z_axis_data_key",control:a,render:({field:u})=>i(W,{label:"Data Field",required:!0,...u})}),i(v.Controller,{name:"zAxis3D.name",control:a,render:({field:u})=>i(s.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...u})})]}),i(s.Group,{position:"center",mt:"xl",grow:!0,sx:{width:"60%"},mx:"auto",children:p(s.Button,{color:"blue",type:"submit",children:[i(T.DeviceFloppy,{size:20}),i(s.Text,{ml:"md",children:"Save"})]})})]})}):null}function bc(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=c=>c&&`${n}.${c}`,{x_axis_data_key:a,y_axis_data_key:o,z_axis_data_key:l,...u}=e;return{...u,x_axis_data_key:r(a),y_axis_data_key:r(o),z_axis_data_key:r(l)}}catch(n){throw console.error("[Migration failed]",n),n}}class vc extends me{constructor(){super(...arguments);q(this,"VERSION",2)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,(n,r)=>{const{config:a}=n;return{...n,version:2,config:bc(a,r)}})}}const xc={displayName:"Bar Chart (3D)",displayGroup:"ECharts-based charts",migrator:new vc,name:"bar-3d",viewRender:fc,configRender:yc,createConfig(){return{version:2,config:x.cloneDeep(br)}}};class Fe extends y.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 p(s.Box,{children:[i(s.Text,{size:"xs",children:(t=this.state.error)==null?void 0:t.message}),i(s.Button,{variant:"subtle",size:"xs",mx:"auto",compact:!0,sx:{display:"block"},onClick:n,children:"Retry"})]})}return this.props.children}}const ze={mantissa:0,output:"number",trimMantissa:!1,average:!1};function wc({value:e,onChange:t},n){const r=u=>{t({...e,output:u})},a=u=>{const c=u===0?!1:e.trimMantissa;t({...e,mantissa:u,trimMantissa:c})},o=u=>{t({...e,trimMantissa:u.currentTarget.checked})},l=u=>{t({...e,average:u.currentTarget.checked})};return p(s.Stack,{ref:n,children:[p(s.Group,{grow:!0,children:[i(s.Select,{label:"Format",data:[{label:"1234",value:"number"},{label:"99%",value:"percent"}],value:e.output,onChange:r,sx:{flexGrow:1}}),i(s.Switch,{label:p(s.Stack,{spacing:0,children:[i(s.Text,{children:"Average"}),i(s.Text,{size:12,color:"gray",children:"like 1.234k, 1.234m"})]}),checked:e.average,onChange:l,disabled:e.output!=="number",sx:{flexGrow:1},styles:{root:{alignSelf:"flex-end"},body:{alignItems:"center"},label:{display:"block"}}})]}),p(s.Group,{grow:!0,children:[i(s.NumberInput,{label:"Mantissa",defaultValue:0,min:0,step:1,max:4,value:e.mantissa,onChange:a}),i(s.Switch,{label:"Trim mantissa",checked:e.trimMantissa,onChange:o,disabled:e.mantissa===0,styles:{root:{alignSelf:"flex-end"},body:{alignItems:"center"}}})]}),p(s.Stack,{spacing:0,children:[i(s.Text,{weight:"bold",children:"Preview"}),i(Fe,{children:p(s.Group,{position:"apart",children:[p(s.Text,{size:12,color:"gray",children:["123456789 ",i(T.ArrowRight,{size:9})," ",Z(123456789).format(e)]}),p(s.Text,{size:12,color:"gray",children:["1234 ",i(T.ArrowRight,{size:9})," ",Z(1234).format(e)]}),p(s.Text,{size:12,color:"gray",children:["0.1234 ",i(T.ArrowRight,{size:9})," ",Z(.1234).format(e)]})]})})]})]})}const We=y.forwardRef(wc),Qe={enabled:!1,func_content:["function label(value, index) {"," // your code goes here"," // return value","}"].join(`
54
+ `;function fr(e,t){const n=Object.keys(t),r=Object.values(t);try{return new Function(...n,`return \`${e}\`;`)(...r)}catch(a){throw n.length===0&&e.includes("$")?new Error("[formatSQL] insufficient payload"):a}}function gr(e,t){try{return fr(e,t)}catch(n){return console.error(n),n.message}}function Ru({sql:e,pre_process:t}){if(!t.trim())return e;try{return new Function(`return ${t}`)()({sql:e},Tt)}catch(n){return console.error(n),e}}function Yu(e,t){if(!e.trim())return t;try{return new Function(`return ${e}`)()(t,Tt)}catch(n){return console.error(n),t}}function Qu(e){e=e||{};const t=Object.keys(e).sort(),n=[];for(let r=0;r<t.length;r++){const a=t[r];if(a!="authentication"&&e[a])n.push(t[r]+"="+(typeof e[a]=="object"?JSON.stringify(e[a]):e[a]));else{const o=Object.keys(e[a]).sort();for(let l=0;l<o.length;l++){const u=o[l];u!="sign"&&e[a][u]&&n.push(o[l]+"="+(typeof e[a][u]=="object"?JSON.stringify(e[a][u]):e[a][u]))}}}return n.sort().join("&")}function Ku(e,t){let n=Qu(e);return n+="&key="+t,Ia.MD5(n).toString().toUpperCase()}const qe={baseURL:"http://localhost:31200",app_id:"",app_secret:"",getAuthentication(e){if(!this.app_id||!this.app_secret)return;const t=new Date().getTime().toString();return{app_id:this.app_id,nonce_str:t,sign:Ku({app_id:this.app_id,nonce_str:t,...e},this.app_secret)}},getRequest(e,t){return(n,r,a={})=>{const o=window.localStorage.getItem("token"),l={"X-Requested-With":"XMLHttpRequest","Content-Type":a.string?"application/x-www-form-urlencoded":"application/json",authorization:o?`bearer ${o}`:"",...a.headers},u={baseURL:this.baseURL,method:e,url:n,params:e==="GET"?r:a.params,headers:l,signal:t};return["POST","PUT"].includes(e)&&(u.data=a.string?JSON.stringify(r):r,u.data.authentication=this.getAuthentication(u.data)),mt(u).then(c=>c.data).catch(c=>Promise.reject(c))}},makeQueryENV:null,query(e){return async(t,n={})=>{var r;return t.env||(t.env=((r=this.makeQueryENV)==null?void 0:r.call(this))??{error:"failed to run makeQueryENV"}),this.getRequest("POST",e)("/query",t,n)}}};function Xa(e){qe.baseURL!==e.apiBaseURL&&(qe.baseURL=e.apiBaseURL),e.app_id&&(qe.app_id=e.app_id),e.app_secret&&(qe.app_secret=e.app_secret),e.makeQueryENV&&(qe.makeQueryENV=e.makeQueryENV)}async function Uu({query:e,payload:t},n){if(!e.sql)return[];const{type:r,key:a,sql:o,pre_process:l,post_process:u}=e,c=fr(o,t),d=Ru({sql:c,pre_process:l});let f=await qe.query(n)({type:r,key:a,query:d},{});return f=Yu(u,f),f}async function Xu({type:e,key:t,configString:n},r){return await qe.query(r)({type:e,key:t,query:n},{})}async function mr(){try{return(await qe.getRequest("POST")("/datasource/list",{filter:{},sort:[{field:"create_time",order:"ASC"}],pagination:{page:1,pagesize:100}})).data}catch(e){return console.error(e),[]}}async function Ja(){try{return(await qe.getRequest("POST")("/sql_snippet/list",{filter:{},sort:[{field:"id",order:"ASC"}],pagination:{page:1,pagesize:1e3}})).data}catch(e){return console.error(e),[]}}class Za{constructor(t){q(this,"rootRef");this.rootRef=re.observable({current:t})}async deleteItem(t){re.runInAction(()=>{x.unset(this.rootRef.current,[t])})}getItem(t){const n=this.getValueFromRoot(t);return Promise.resolve(n)}getValueFromRoot(t){return t===null?re.toJS(this.rootRef.current):x.get(this.rootRef.current,[t])}setItem(t,n){if(t===null)if(x.isObject(n))re.runInAction(()=>{this.rootRef.current=n});else throw new Error("Cannot set root value to non-object");else re.runInAction(()=>{x.set(this.rootRef.current,[t],n)});return Promise.resolve(this.getItem(t))}watchItem(t,n,r){return re.reaction(()=>this.getValueFromRoot(t),(a,o)=>{n(a,o)},{requiresObservable:!0,fireImmediately:x.get(r,"fireImmediately",!1)})}}class Ju{constructor(){q(this,"channels",new Map);q(this,"globalChannel",new Aa)}getChannel(t){const n=this.channels.get(t);if(n)return n;const r=new Aa;return this.channels.set(t,r),r}}class Zu{constructor(t){q(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 Ju,instanceData:new Za(t.viz.conf)};return this.instances.set(t.id,r),r}}function Ha(e,t,n,r){return{vizManager:n,locale:"zh",msgChannels:e.messageChannels,instanceData:e.instanceData,pluginData:new Za({}),colorPalette:{getColor(){return()=>""}},data:t,variables:r}}const Hu=e=>{const{panel:t,vizManager:n,data:r,variables:a}=e,o=n.resolveComponent(t.viz.type),l=n.getOrCreateInstance(t),u={...Ha(l,r,n,a),viewport:{width:t.layout.w,height:t.layout.h}},c=o.viewRender;return i(c,{context:u,instance:l,...x.omit(e,["panel","vizManager","data"])})},ec=e=>{const{vizManager:t,panel:n,panelInfoEditor:r,data:a,variables:o}=e,l=t.resolveComponent(n.viz.type),u=t.getOrCreateInstance(n),c={...Ha(u,a,t,o),panelInfoEditor:r},d=l.configRender;return i(d,{context:c,instance:u,...x.omit(e,["panel","vizManager","data","panelInfoEditor"])})},es=(e,t)=>{const n=ct.bezier(e),r=ct.bezier(t);return function(a){return a<50?n(a*2/100).hex():r((a-50)*2/100).hex()}},Cn=e=>{const t=ct.bezier(e);return function(n){return t(n/100).hex()}},tc={type:"interpolation",displayName:"Red / Green",getColor:es(["darkred","deeppink","lightyellow"],["lightyellow","lightgreen","teal"]),name:"red-green",category:"diverging"},nc={type:"interpolation",displayName:"Yellow / Blue",getColor:es(["#8f531d","#ffd347","#e3efe3"],["#eefaee","#4ecbbf","#003f94"]),name:"yellow-blue",category:"diverging"},rc={type:"interpolation",displayName:"Red",getColor:Cn(["#fff7f1","darkred"]),name:"red",category:"sequential"},ic={type:"interpolation",displayName:"Green",getColor:Cn(["#f0ffed","darkgreen"]),name:"green",category:"sequential"},ac={type:"interpolation",displayName:"Blue",getColor:Cn(["#f9fcff","#48b3e9","darkblue"]),name:"blue",category:"sequential"},sc={type:"interpolation",displayName:"Orange",getColor:Cn(["#fff7f1","darkorange","#b60000"]),name:"orange",category:"sequential"};class oc{constructor(t){q(this,"symbol");this.symbol=Symbol(t)}}function dt(e){return new oc(e)}class yr{constructor(){q(this,"parent");q(this,"factoryRegistry",new Map);q(this,"instanceRegistry",new Map)}createScoped(){const t=new yr;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=x.get(t,"dispose");x.isFunction(n)&&n.bind(t)()}),this.instanceRegistry.clear(),this.factoryRegistry.clear()}}const ts="10.23.1",lc=Object.freeze(Object.defineProperty({__proto__:null,version:ts},Symbol.toStringTag,{value:"Module"}));class uc{constructor(t){q(this,"staticColors",new Map);q(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 cc{constructor(){q(this,"plugins",new Map);q(this,"vizComponents",new Map);q(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 dc{constructor(){q(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 a=this.migrations.filter(u=>u.version>t.from&&u.version<=t.to),o=x.orderBy(a,"version","asc");if(((l=x.last(o))==null?void 0:l.version)!==t.to)throw new Error(`Migration to version ${t.to} not found`);return o.reduce((u,c)=>c.handler(u,r),n)}}class me extends dc{constructor(){super(),this.configVersions()}version(t,n){return super.version(t,(r,a)=>({version:t,...n(r,a)}))}async migrate({configData:t,panelModel:n}){const r=await t.getItem(null),a=x.get(r,"version",0),o=this.run({from:a,to:this.VERSION},r,{panelModel:n});await t.setItem(null,o)}async needMigration({configData:t}){const n=await t.getItem(null);return x.get(n,"version",0)<this.VERSION}}const j=(e,t)=>{const[n,{setFalse:r}]=U.useBoolean(!0),[a,o]=y.useState();y.useEffect(()=>(e.getItem(t).then(u=>{o(u),r()}),e.watchItem(t,u=>{o(u)})));const l=y.useCallback(async u=>{await e.setItem(t,u),o(u)},[e,t]);return{loading:n,value:a,set:l}},br={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 L(e){const[t,n]=e.split(".");return{queryID:t,columnKey:n}}function pc(e){return e.includes(".")?L(e):{queryID:"",columnKey:e}}function pt(e,t){var a;const{queryID:n,columnKey:r}=L(t);return n?r?((a=e[n])==null?void 0:a.map(o=>o[r]))??[]:e[n]:[]}function Ht(e,t){const{queryID:n}=L(t);return n?e[n]:[]}function hc(e){return Object.values(e)[0]}function Sn(e,t){const{queryID:n,columnKey:r}=L(t);return e[r]}ie.use([F.GridComponent,F.VisualMapComponent,F.LegendComponent,F.TooltipComponent,Pe.CanvasRenderer]);function fc({context:e}){const{value:t}=j(e.instanceData,"config"),n=e.data,{width:r,height:a}=e.viewport,{x_axis_data_key:o,y_axis_data_key:l,z_axis_data_key:u,xAxis3D:c,yAxis3D:d,zAxis3D:f}=x.defaults({},t,br),h=y.useMemo(()=>Ht(n,o),[n,o]),{x:g,y:m,z:C}=y.useMemo(()=>({x:L(o),y:L(l),z:L(u)}),[o,l,u]),{min:w,max:_}=y.useMemo(()=>{const I=x.minBy(h,N=>N[C.columnKey]),B=x.maxBy(h,N=>N[C.columnKey]);return{min:x.get(I,C.columnKey),max:x.get(B,C.columnKey)}},[h,C]),D={tooltip:{},backgroundColor:"#fff",visualMap:{show:!0,dimension:2,min:w,max:_,inRange:{color:["#313695","#4575b4","#74add1","#abd9e9","#e0f3f8","#ffffbf","#fee090","#fdae61","#f46d43","#d73027","#a50026"]}},xAxis3D:c,yAxis3D:d,zAxis3D:f,grid3D:{viewControl:{projection:"orthographic",autoRotate:!1},light:{main:{shadow:!0,quality:"ultra",intensity:1.5}}},series:[{type:"bar3D",wireframe:{},data:h.map(I=>[I[g.columnKey],I[m.columnKey],I[C.columnKey]])}]};return t?i(Be,{echarts:ie,option:D,style:{width:r,height:a},notMerge:!0,theme:"merico-light"}):null}const ns=y.createContext(null),vr=ns.Provider;function xr(){const e=y.useContext(ns);if(!e)throw new Error("Please use DashboardModelContextProvider");return e}const ye=()=>xr(),wr=()=>xr(),rs=y.createContext(null),Cr=rs.Provider;function is(){const e=y.useContext(rs);if(!e)throw new Error("Please use ContentModelContextProvider");return e}const le=()=>is(),we=()=>is(),gc={inEditMode:!1},_n=y.createContext(gc),as=y.createContext({panel:null,data:{},loading:!1,errors:[],downloadPanelScreenshot:()=>{}}),Sr=as.Provider;function ss(){const e=y.useContext(as);if(!e.panel)throw new Error("Please use PanelContextProvider");return e}const bt=()=>ss(),nt=()=>ss(),mc={fullScreenPanelID:"",setFullScreenPanelID:x.noop},_r=y.createContext(mc);function os(){const e=y.useContext(_r);if(!e)throw new Error("Please use FullScreenPanelContext.Provider");return e}const W=k.observer(y.forwardRef(({label:e,required:t,value:n,onChange:r,clearable:a=!1,sx:o,...l},u)=>{const{panel:c}=nt(),d=y.useMemo(()=>{const f=[...c.dataFieldOptions];return a&&f.unshift({label:"unset",value:"",group:""}),f},[c.dataFieldOptions]);return i(s.Select,{ref:u,label:e,data:d,value:n,onChange:r,required:t,sx:o,maxDropdownHeight:500,...l})}));function yc({context:e}){const{value:t,set:n}=j(e.instanceData,"config"),r=x.defaults({},t,br),{control:a,handleSubmit:o,reset:l}=v.useForm({defaultValues:r});return y.useEffect(()=>{l(r)},[t]),t?i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:o(n),children:[i(s.Text,{children:"X Axis"}),p(s.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[i(v.Controller,{name:"x_axis_data_key",control:a,render:({field:u})=>i(W,{label:"Data Field",required:!0,...u})}),i(v.Controller,{name:"xAxis3D.name",control:a,render:({field:u})=>i(s.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...u})})]}),i(s.Text,{mt:"lg",children:"Y Axis"}),p(s.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[i(v.Controller,{name:"y_axis_data_key",control:a,render:({field:u})=>i(W,{label:"Data Field",required:!0,...u})}),i(v.Controller,{name:"yAxis3D.name",control:a,render:({field:u})=>i(s.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...u})})]}),i(s.Text,{mt:"lg",children:"Z Axis"}),p(s.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[i(v.Controller,{name:"z_axis_data_key",control:a,render:({field:u})=>i(W,{label:"Data Field",required:!0,...u})}),i(v.Controller,{name:"zAxis3D.name",control:a,render:({field:u})=>i(s.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...u})})]}),i(s.Group,{position:"center",mt:"xl",grow:!0,sx:{width:"60%"},mx:"auto",children:p(s.Button,{color:"blue",type:"submit",children:[i(T.DeviceFloppy,{size:20}),i(s.Text,{ml:"md",children:"Save"})]})})]})}):null}function bc(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=c=>c&&`${n}.${c}`,{x_axis_data_key:a,y_axis_data_key:o,z_axis_data_key:l,...u}=e;return{...u,x_axis_data_key:r(a),y_axis_data_key:r(o),z_axis_data_key:r(l)}}catch(n){throw console.error("[Migration failed]",n),n}}class vc extends me{constructor(){super(...arguments);q(this,"VERSION",2)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,(n,r)=>{const{config:a}=n;return{...n,version:2,config:bc(a,r)}})}}const xc={displayName:"Bar Chart (3D)",displayGroup:"ECharts-based charts",migrator:new vc,name:"bar-3d",viewRender:fc,configRender:yc,createConfig(){return{version:2,config:x.cloneDeep(br)}}};class Fe extends y.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 p(s.Box,{children:[i(s.Text,{size:"xs",children:(t=this.state.error)==null?void 0:t.message}),i(s.Button,{variant:"subtle",size:"xs",mx:"auto",compact:!0,sx:{display:"block"},onClick:n,children:"Retry"})]})}return this.props.children}}const ze={mantissa:0,output:"number",trimMantissa:!1,average:!1};function wc({value:e,onChange:t},n){const r=u=>{t({...e,output:u})},a=u=>{const c=u===0?!1:e.trimMantissa;t({...e,mantissa:u,trimMantissa:c})},o=u=>{t({...e,trimMantissa:u.currentTarget.checked})},l=u=>{t({...e,average:u.currentTarget.checked})};return p(s.Stack,{ref:n,children:[p(s.Group,{grow:!0,children:[i(s.Select,{label:"Format",data:[{label:"1234",value:"number"},{label:"99%",value:"percent"}],value:e.output,onChange:r,sx:{flexGrow:1}}),i(s.Switch,{label:p(s.Stack,{spacing:0,children:[i(s.Text,{children:"Average"}),i(s.Text,{size:12,color:"gray",children:"like 1.234k, 1.234m"})]}),checked:e.average,onChange:l,disabled:e.output!=="number",sx:{flexGrow:1},styles:{root:{alignSelf:"flex-end"},body:{alignItems:"center"},label:{display:"block"}}})]}),p(s.Group,{grow:!0,children:[i(s.NumberInput,{label:"Mantissa",defaultValue:0,min:0,step:1,max:4,value:e.mantissa,onChange:a}),i(s.Switch,{label:"Trim mantissa",checked:e.trimMantissa,onChange:o,disabled:e.mantissa===0,styles:{root:{alignSelf:"flex-end"},body:{alignItems:"center"}}})]}),p(s.Stack,{spacing:0,children:[i(s.Text,{weight:"bold",children:"Preview"}),i(Fe,{children:p(s.Group,{position:"apart",children:[p(s.Text,{size:12,color:"gray",children:["123456789 ",i(T.ArrowRight,{size:9})," ",Z(123456789).format(e)]}),p(s.Text,{size:12,color:"gray",children:["1234 ",i(T.ArrowRight,{size:9})," ",Z(1234).format(e)]}),p(s.Text,{size:12,color:"gray",children:["0.1234 ",i(T.ArrowRight,{size:9})," ",Z(.1234).format(e)]})]})})]})]})}const We=y.forwardRef(wc),Qe={enabled:!1,func_content:["function label(value, index) {"," // your code goes here"," // return value","}"].join(`
55
55
  `)},ls={id:"builtin:echarts:click-echart:series",displayName:"Click Chart Series",nameRender:Sc,configRender:Cc,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 Cc(e){return i(P,{})}function Sc(e){return i(s.Text,{children:"Click chart's series"})}const _c=[{label:"Truncate",value:"truncate"},{label:"Break Line",value:"break"},{label:"Break Word",value:"breakAll"}],kn=y.forwardRef(({sectionTitle:e,value:t,onChange:n},r)=>{const a=o=>l=>{const u=x.cloneDeep(t);x.set(u,o,l),n(u)};return p(s.Stack,{spacing:0,children:[e&&i(s.Divider,{mb:-5,mt:5,variant:"dotted",label:e,labelPosition:"right",labelProps:{color:"dimmed"}}),p(s.Group,{grow:!0,noWrap:!0,children:[i(s.NumberInput,{label:"Max Width",hideControls:!0,value:t.width,onChange:a("width")}),i(s.Select,{label:"Overflow",data:_c,value:t.overflow,onChange:a("overflow")}),i(s.TextInput,{label:"Ellipsis",value:t.ellipsis,disabled:!0})]})]})}),at=y.forwardRef(({value:e,onChange:t},n)=>{const r=o=>{t({...e,on_axis:o})},a=o=>{t({...e,in_tooltip:o})};return p(s.Stack,{ref:n,spacing:0,children:[i(kn,{sectionTitle:"Overflow on Axis",value:e.on_axis,onChange:r}),i(kn,{sectionTitle:"Overflow in Tooltip",value:e.in_tooltip,onChange:a})]})}),je={on_axis:{width:80,overflow:"truncate",ellipsis:"..."},in_tooltip:{width:200,overflow:"break",ellipsis:"..."}};function st({overflow:e,width:t}){const n={truncate:"initial",break:"break-all",breakAll:"break-word"}[e],r=e==="truncate"?"nowrap":"initial",a={truncate:"ellipsis",break:"clip",breakAll:"clip"}[e];return`
56
56
  max-width: ${t}px;
57
57
  word-break: ${n};
@@ -102,7 +102,7 @@ Check the top-level render call using <`+V+">.")}return E}}function ku(S,E){{if(
102
102
  `))}ignoreFallback(t){t.nodeName=="BR"&&(!this.top.type||!this.top.type.inlineContent)&&this.findPlace(this.parser.schema.text("-"))}readStyles(t){let n=Re.none,r=Re.none;for(let a=0;a<t.length;a+=2)for(let o=void 0;;){let l=this.parser.matchStyle(t[a],t[a+1],this,o);if(!l)break;if(l.ignore)return null;if(l.clearMark?this.top.pendingMarks.concat(this.top.activeMarks).forEach(u=>{l.clearMark(u)&&(r=u.addToSet(r))}):n=this.parser.schema.marks[l.mark].create(l.attrs).addToSet(n),l.consuming===!1)o=l;else break}return[n,r]}addElementByRule(t,n,r){let a,o,l;n.node?(o=this.parser.schema.nodes[n.node],o.isLeaf?this.insertNode(o.create(n.attrs))||this.leafFallback(t):a=this.enter(o,n.attrs||null,n.preserveWhitespace)):(l=this.parser.schema.marks[n.mark].create(n.attrs),this.addPendingMark(l));let u=this.top;if(o&&o.isLeaf)this.findInside(t);else if(r)this.addElement(t,r);else if(n.getContent)this.findInside(t),n.getContent(t,this.parser.schema).forEach(c=>this.insertNode(c));else{let c=t;typeof n.contentElement=="string"?c=t.querySelector(n.contentElement):typeof n.contentElement=="function"?c=n.contentElement(t):n.contentElement&&(c=n.contentElement),this.findAround(t,c,!0),this.addAll(c)}a&&this.sync(u)&&this.open--,l&&this.removePendingMark(l,u)}addAll(t,n,r){let a=n||0;for(let o=n?t.childNodes[n]:t.firstChild,l=r==null?null:t.childNodes[r];o!=l;o=o.nextSibling,++a)this.findAtPoint(t,a),this.addDOM(o);this.findAtPoint(t,a)}findPlace(t){let n,r;for(let a=this.open;a>=0;a--){let o=this.nodes[a],l=o.findWrapping(t);if(l&&(!n||n.length>l.length)&&(n=l,r=o,!l.length)||o.solid)break}if(!n)return!1;this.sync(r);for(let a=0;a<n.length;a++)this.enterInner(n[a],null,!1);return!0}insertNode(t){if(t.isInline&&this.needsBlock&&!this.top.type){let n=this.textblockFromContext();n&&this.enterInner(n)}if(this.findPlace(t)){this.closeExtra();let n=this.top;n.applyPending(t.type),n.match&&(n.match=n.match.matchType(t.type));let r=n.activeMarks;for(let a=0;a<t.marks.length;a++)(!n.type||n.type.allowsMarkType(t.marks[a].type))&&(r=t.marks[a].addToSet(r));return n.content.push(t.mark(r)),!0}return!1}enter(t,n,r){let a=this.findPlace(t.create(n));return a&&this.enterInner(t,n,!0,r),a}enterInner(t,n=null,r=!1,a){this.closeExtra();let o=this.top;o.applyPending(t),o.match=o.match&&o.match.matchType(t);let l=ys(t,a,o.options);o.options&tn&&o.content.length==0&&(l|=tn),this.nodes.push(new zn(t,n,o.activeMarks,o.pendingMarks,r,null,l)),this.open++}closeExtra(t=!1){let n=this.nodes.length-1;if(n>this.open){for(;n>this.open;n--)this.nodes[n-1].content.push(this.nodes[n].finish(t));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(this.isOpen||this.options.topOpen)}sync(t){for(let n=this.open;n>=0;n--)if(this.nodes[n]==t)return this.open=n,!0;return!1}get currentPos(){this.closeExtra();let t=0;for(let n=this.open;n>=0;n--){let r=this.nodes[n].content;for(let a=r.length-1;a>=0;a--)t+=r[a].nodeSize;n&&t++}return t}findAtPoint(t,n){if(this.find)for(let r=0;r<this.find.length;r++)this.find[r].node==t&&this.find[r].offset==n&&(this.find[r].pos=this.currentPos)}findInside(t){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].pos==null&&t.nodeType==1&&t.contains(this.find[n].node)&&(this.find[n].pos=this.currentPos)}findAround(t,n,r){if(t!=n&&this.find)for(let a=0;a<this.find.length;a++)this.find[a].pos==null&&t.nodeType==1&&t.contains(this.find[a].node)&&n.compareDocumentPosition(this.find[a].node)&(r?2:4)&&(this.find[a].pos=this.currentPos)}findInText(t){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].node==t&&(this.find[n].pos=this.currentPos-(t.nodeValue.length-this.find[n].offset))}matchesContext(t){if(t.indexOf("|")>-1)return t.split(/\s*\|\s*/).some(this.matchesContext,this);let n=t.split("/"),r=this.options.context,a=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),o=-(r?r.depth+1:0)+(a?0:1),l=(u,c)=>{for(;u>=0;u--){let d=n[u];if(d==""){if(u==n.length-1||u==0)continue;for(;c>=o;c--)if(l(u-1,c))return!0;return!1}else{let f=c>0||c==0&&a?this.nodes[c].type:r&&c>=o?r.node(c-o).type:null;if(!f||f.name!=d&&f.groups.indexOf(d)==-1)return!1;c--}}return!0};return l(n.length-1,this.open)}textblockFromContext(){let t=this.options.context;if(t)for(let n=t.depth;n>=0;n--){let r=t.node(n).contentMatchAt(t.indexAfter(n)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let n in this.parser.schema.nodes){let r=this.parser.schema.nodes[n];if(r.isTextblock&&r.defaultAttrs)return r}}addPendingMark(t){let n=Md(t,this.top.pendingMarks);n&&this.top.stashMarks.push(n),this.top.pendingMarks=t.addToSet(this.top.pendingMarks)}removePendingMark(t,n){for(let r=this.open;r>=0;r--){let a=this.nodes[r];if(a.pendingMarks.lastIndexOf(t)>-1)a.pendingMarks=t.removeFromSet(a.pendingMarks);else{a.activeMarks=t.removeFromSet(a.activeMarks);let l=a.popFromStashMark(t);l&&a.type&&a.type.allowsMarkType(l.type)&&(a.activeMarks=l.addToSet(a.activeMarks))}if(a==n)break}}}function _d(e){for(let t=e.firstChild,n=null;t;t=t.nextSibling){let r=t.nodeType==1?t.nodeName.toLowerCase():null;r&&ms.hasOwnProperty(r)&&n?(n.appendChild(t),t=n):r=="li"?n=t:r&&(n=null)}}function kd(e,t){return(e.matches||e.msMatchesSelector||e.webkitMatchesSelector||e.mozMatchesSelector).call(e,t)}function Td(e){let t=/\s*([\w-]+)\s*:\s*([^;]+)/g,n,r=[];for(;n=t.exec(e);)r.push(n[1],n[2].trim());return r}function vs(e){let t={};for(let n in e)t[n]=e[n];return t}function Dd(e,t){let n=t.schema.nodes;for(let r in n){let a=n[r];if(!a.allowsMarkType(e))continue;let o=[],l=u=>{o.push(u);for(let c=0;c<u.edgeCount;c++){let{type:d,next:f}=u.edge(c);if(d==t||o.indexOf(f)<0&&l(f))return!0}};if(l(a.contentMatch))return!0}}function Md(e,t){for(let n=0;n<t.length;n++)if(e.eq(t[n]))return t[n]}const xs=65535,ws=Math.pow(2,16);function Id(e,t){return e+t*ws}function Cs(e){return e&xs}function Ad(e){return(e-(e&xs))/ws}const Ss=1,_s=2,En=4,ks=8;class Ts{constructor(t,n,r){this.pos=t,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&ks)>0}get deletedBefore(){return(this.delInfo&(Ss|En))>0}get deletedAfter(){return(this.delInfo&(_s|En))>0}get deletedAcross(){return(this.delInfo&En)>0}}class Xe{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&Xe.empty)return Xe.empty}recover(t){let n=0,r=Cs(t);if(!this.inverted)for(let a=0;a<r;a++)n+=this.ranges[a*3+2]-this.ranges[a*3+1];return this.ranges[r*3]+n+Ad(t)}mapResult(t,n=1){return this._map(t,n,!1)}map(t,n=1){return this._map(t,n,!0)}_map(t,n,r){let a=0,o=this.inverted?2:1,l=this.inverted?1:2;for(let u=0;u<this.ranges.length;u+=3){let c=this.ranges[u]-(this.inverted?a:0);if(c>t)break;let d=this.ranges[u+o],f=this.ranges[u+l],h=c+d;if(t<=h){let g=d?t==c?-1:t==h?1:n:n,m=c+a+(g<0?0:f);if(r)return m;let C=t==(n<0?c:h)?null:Id(u/3,t-c),w=t==c?_s:t==h?Ss:En;return(n<0?t!=c:t!=h)&&(w|=ks),new Ts(m,w,C)}a+=f-d}return r?t+a:new Ts(t+a,0,null)}touches(t,n){let r=0,a=Cs(n),o=this.inverted?2:1,l=this.inverted?1:2;for(let u=0;u<this.ranges.length;u+=3){let c=this.ranges[u]-(this.inverted?r:0);if(c>t)break;let d=this.ranges[u+o],f=c+d;if(t<=f&&u==a*3)return!0;r+=this.ranges[u+l]-d}return!1}forEach(t){let n=this.inverted?2:1,r=this.inverted?1:2;for(let a=0,o=0;a<this.ranges.length;a+=3){let l=this.ranges[a],u=l-(this.inverted?o:0),c=l+(this.inverted?0:o),d=this.ranges[a+n],f=this.ranges[a+r];t(u,u+d,c,c+f),o+=f-d}}invert(){return new Xe(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(t){return t==0?Xe.empty:new Xe(t<0?[0,-t,0]:[0,0,t])}}Xe.empty=new Xe([]);const Er=Object.create(null);class Ge{getMap(){return Xe.empty}merge(t){return null}static fromJSON(t,n){if(!n||!n.stepType)throw new RangeError("Invalid input for Step.fromJSON");let r=Er[n.stepType];if(!r)throw new RangeError(`No step type ${n.stepType} defined`);return r.fromJSON(t,n)}static jsonID(t,n){if(t in Er)throw new RangeError("Duplicate use of step JSON ID "+t);return Er[t]=n,n.prototype.jsonID=t,n}}class Te{constructor(t,n){this.doc=t,this.failed=n}static ok(t){return new Te(t,null)}static fail(t){return new Te(null,t)}static fromReplace(t,n,r,a){try{return Te.ok(t.replace(n,r,a))}catch(o){if(o instanceof Cd)return Te.fail(o.message);throw o}}}function $r(e,t,n){let r=[];for(let a=0;a<e.childCount;a++){let o=e.child(a);o.content.size&&(o=o.copy($r(o.content,t,o))),o.isInline&&(o=t(o,n,a)),r.push(o)}return ae.fromArray(r)}class Mt extends Ge{constructor(t,n,r){super(),this.from=t,this.to=n,this.mark=r}apply(t){let n=t.slice(this.from,this.to),r=t.resolve(this.from),a=r.node(r.sharedDepth(this.to)),o=new ce($r(n.content,(l,u)=>!l.isAtom||!u.type.allowsMarkType(this.mark.type)?l:l.mark(this.mark.addToSet(l.marks)),a),n.openStart,n.openEnd);return Te.fromReplace(t,this.from,this.to,o)}invert(){return new It(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new Mt(n.pos,r.pos,this.mark)}merge(t){return t instanceof Mt&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new Mt(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Mt(n.from,n.to,t.markFromJSON(n.mark))}}Ge.jsonID("addMark",Mt);class It extends Ge{constructor(t,n,r){super(),this.from=t,this.to=n,this.mark=r}apply(t){let n=t.slice(this.from,this.to),r=new ce($r(n.content,a=>a.mark(this.mark.removeFromSet(a.marks)),t),n.openStart,n.openEnd);return Te.fromReplace(t,this.from,this.to,r)}invert(){return new Mt(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new It(n.pos,r.pos,this.mark)}merge(t){return t instanceof It&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new It(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new It(n.from,n.to,t.markFromJSON(n.mark))}}Ge.jsonID("removeMark",It);class At extends Ge{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return Te.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return Te.fromReplace(t,this.pos,this.pos+1,new ce(ae.from(r),0,n.isLeaf?0:1))}invert(t){let n=t.nodeAt(this.pos);if(n){let r=this.mark.addToSet(n.marks);if(r.length==n.marks.length){for(let a=0;a<n.marks.length;a++)if(!n.marks[a].isInSet(r))return new At(this.pos,n.marks[a]);return new At(this.pos,this.mark)}}return new nn(this.pos,this.mark)}map(t){let n=t.mapResult(this.pos,1);return n.deletedAfter?null:new At(n.pos,this.mark)}toJSON(){return{stepType:"addNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(t,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");return new At(n.pos,t.markFromJSON(n.mark))}}Ge.jsonID("addNodeMark",At);class nn extends Ge{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return Te.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.removeFromSet(n.marks));return Te.fromReplace(t,this.pos,this.pos+1,new ce(ae.from(r),0,n.isLeaf?0:1))}invert(t){let n=t.nodeAt(this.pos);return!n||!this.mark.isInSet(n.marks)?this:new At(this.pos,this.mark)}map(t){let n=t.mapResult(this.pos,1);return n.deletedAfter?null:new nn(n.pos,this.mark)}toJSON(){return{stepType:"removeNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(t,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");return new nn(n.pos,t.markFromJSON(n.mark))}}Ge.jsonID("removeNodeMark",nn);class ot extends Ge{constructor(t,n,r,a=!1){super(),this.from=t,this.to=n,this.slice=r,this.structure=a}apply(t){return this.structure&&Lr(t,this.from,this.to)?Te.fail("Structure replace would overwrite content"):Te.fromReplace(t,this.from,this.to,this.slice)}getMap(){return new Xe([this.from,this.to-this.from,this.slice.size])}invert(t){return new ot(this.from,this.from+this.slice.size,t.slice(this.from,this.to))}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1);return n.deletedAcross&&r.deletedAcross?null:new ot(n.pos,Math.max(n.pos,r.pos),this.slice)}merge(t){if(!(t instanceof ot)||t.structure||this.structure)return null;if(this.from+this.slice.size==t.from&&!this.slice.openEnd&&!t.slice.openStart){let n=this.slice.size+t.slice.size==0?ce.empty:new ce(this.slice.content.append(t.slice.content),this.slice.openStart,t.slice.openEnd);return new ot(this.from,this.to+(t.to-t.from),n,this.structure)}else if(t.to==this.from&&!this.slice.openStart&&!t.slice.openEnd){let n=this.slice.size+t.slice.size==0?ce.empty:new ce(t.slice.content.append(this.slice.content),t.slice.openStart,this.slice.openEnd);return new ot(t.from,this.to,n,this.structure)}else return null}toJSON(){let t={stepType:"replace",from:this.from,to:this.to};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for ReplaceStep.fromJSON");return new ot(n.from,n.to,ce.fromJSON(t,n.slice),!!n.structure)}}Ge.jsonID("replace",ot);class zt extends Ge{constructor(t,n,r,a,o,l,u=!1){super(),this.from=t,this.to=n,this.gapFrom=r,this.gapTo=a,this.slice=o,this.insert=l,this.structure=u}apply(t){if(this.structure&&(Lr(t,this.from,this.gapFrom)||Lr(t,this.gapTo,this.to)))return Te.fail("Structure gap-replace would overwrite content");let n=t.slice(this.gapFrom,this.gapTo);if(n.openStart||n.openEnd)return Te.fail("Gap is not a flat range");let r=this.slice.insertAt(this.insert,n.content);return r?Te.fromReplace(t,this.from,this.to,r):Te.fail("Content does not fit in gap")}getMap(){return new Xe([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(t){let n=this.gapTo-this.gapFrom;return new zt(this.from,this.from+this.slice.size+n,this.from+this.insert,this.from+this.insert+n,t.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1),a=t.map(this.gapFrom,-1),o=t.map(this.gapTo,1);return n.deletedAcross&&r.deletedAcross||a<n.pos||o>r.pos?null:new zt(n.pos,r.pos,a,o,this.slice,this.insert,this.structure)}toJSON(){let t={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number"||typeof n.gapFrom!="number"||typeof n.gapTo!="number"||typeof n.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new zt(n.from,n.to,n.gapFrom,n.gapTo,ce.fromJSON(t,n.slice),n.insert,!!n.structure)}}Ge.jsonID("replaceAround",zt);function Lr(e,t,n){let r=e.resolve(t),a=n-t,o=r.depth;for(;a>0&&o>0&&r.indexAfter(o)==r.node(o).childCount;)o--,a--;if(a>0){let l=r.node(o).maybeChild(r.indexAfter(o));for(;a>0;){if(!l||l.isLeaf)return!0;l=l.firstChild,a--}}return!1}function zd(e,t,n){return(t==0||e.canReplace(t,e.childCount))&&(n==e.childCount||e.canReplace(0,n))}function Ed(e){let n=e.parent.content.cutByIndex(e.startIndex,e.endIndex);for(let r=e.depth;;--r){let a=e.$from.node(r),o=e.$from.index(r),l=e.$to.indexAfter(r);if(r<e.depth&&a.canReplace(o,l,n))return r;if(r==0||a.type.spec.isolating||!zd(a,o,l))break}return null}function $n(e,t,n=1,r){let a=e.resolve(t),o=a.depth-n,l=r&&r[r.length-1]||a.parent;if(o<0||a.parent.type.spec.isolating||!a.parent.canReplace(a.index(),a.parent.childCount)||!l.type.validContent(a.parent.content.cutByIndex(a.index(),a.parent.childCount)))return!1;for(let d=a.depth-1,f=n-2;d>o;d--,f--){let h=a.node(d),g=a.index(d);if(h.type.spec.isolating)return!1;let m=h.content.cutByIndex(g,h.childCount),C=r&&r[f+1];C&&(m=m.replaceChild(0,C.type.create(C.attrs)));let w=r&&r[f]||h;if(!h.canReplace(g+1,h.childCount)||!w.type.validContent(m))return!1}let u=a.indexAfter(o),c=r&&r[0];return a.node(o).canReplaceWith(u,u,c?c.type:a.node(o+1).type)}function Ds(e,t){let n=e.resolve(t),r=n.index();return $d(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function $d(e,t){return!!(e&&t&&!e.isLeaf&&e.canAppend(t))}class rn extends Ge{constructor(t,n,r){super(),this.pos=t,this.attr=n,this.value=r}apply(t){let n=t.nodeAt(this.pos);if(!n)return Te.fail("No node at attribute step's position");let r=Object.create(null);for(let o in n.attrs)r[o]=n.attrs[o];r[this.attr]=this.value;let a=n.type.create(r,null,n.marks);return Te.fromReplace(t,this.pos,this.pos+1,new ce(ae.from(a),0,n.isLeaf?0:1))}getMap(){return Xe.empty}invert(t){return new rn(this.pos,this.attr,t.nodeAt(this.pos).attrs[this.attr])}map(t){let n=t.mapResult(this.pos,1);return n.deletedAfter?null:new rn(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(t,n){if(typeof n.pos!="number"||typeof n.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new rn(n.pos,n.attr,n.value)}}Ge.jsonID("attr",rn);let an=class extends Error{};an=function e(t){let n=Error.call(this,t);return n.__proto__=e.prototype,n},an.prototype=Object.create(Error.prototype),an.prototype.constructor=an,an.prototype.name="TransformError";const Or=Object.create(null);class he{constructor(t,n,r){this.$anchor=t,this.$head=n,this.ranges=r||[new Ld(t.min(n),t.max(n))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let t=this.ranges;for(let n=0;n<t.length;n++)if(t[n].$from.pos!=t[n].$to.pos)return!1;return!0}content(){return this.$from.doc.slice(this.from,this.to,!0)}replace(t,n=ce.empty){let r=n.content.lastChild,a=null;for(let u=0;u<n.openEnd;u++)a=r,r=r.lastChild;let o=t.steps.length,l=this.ranges;for(let u=0;u<l.length;u++){let{$from:c,$to:d}=l[u],f=t.mapping.slice(o);t.replaceRange(f.map(c.pos),f.map(d.pos),u?ce.empty:n),u==0&&As(t,o,(r?r.isInline:a&&a.isTextblock)?-1:1)}}replaceWith(t,n){let r=t.steps.length,a=this.ranges;for(let o=0;o<a.length;o++){let{$from:l,$to:u}=a[o],c=t.mapping.slice(r),d=c.map(l.pos),f=c.map(u.pos);o?t.deleteRange(d,f):(t.replaceRangeWith(d,f,n),As(t,r,n.isInline?-1:1))}}static findFrom(t,n,r=!1){let a=t.parent.inlineContent?new De(t):Bt(t.node(0),t.parent,t.pos,t.index(),n,r);if(a)return a;for(let o=t.depth-1;o>=0;o--){let l=n<0?Bt(t.node(0),t.node(o),t.before(o+1),t.index(o),n,r):Bt(t.node(0),t.node(o),t.after(o+1),t.index(o)+1,n,r);if(l)return l}return null}static near(t,n=1){return this.findFrom(t,n)||this.findFrom(t,-n)||new ht(t.node(0))}static atStart(t){return Bt(t,t,0,0,1)||new ht(t)}static atEnd(t){return Bt(t,t,t.content.size,t.childCount,-1)||new ht(t)}static fromJSON(t,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=Or[n.type];if(!r)throw new RangeError(`No selection type ${n.type} defined`);return r.fromJSON(t,n)}static jsonID(t,n){if(t in Or)throw new RangeError("Duplicate use of selection JSON ID "+t);return Or[t]=n,n.prototype.jsonID=t,n}getBookmark(){return De.between(this.$anchor,this.$head).getBookmark()}}he.prototype.visible=!0;class Ld{constructor(t,n){this.$from=t,this.$to=n}}let Ms=!1;function Is(e){!Ms&&!e.parent.inlineContent&&(Ms=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+e.parent.type.name+")"))}class De extends he{constructor(t,n=t){Is(t),Is(n),super(t,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(t,n){let r=t.resolve(n.map(this.head));if(!r.parent.inlineContent)return he.near(r);let a=t.resolve(n.map(this.anchor));return new De(a.parent.inlineContent?a:r,r)}replace(t,n=ce.empty){if(super.replace(t,n),n==ce.empty){let r=this.$from.marksAcross(this.$to);r&&t.ensureMarks(r)}}eq(t){return t instanceof De&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new Ln(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(t,n){if(typeof n.anchor!="number"||typeof n.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new De(t.resolve(n.anchor),t.resolve(n.head))}static create(t,n,r=n){let a=t.resolve(n);return new this(a,r==n?a:t.resolve(r))}static between(t,n,r){let a=t.pos-n.pos;if((!r||a)&&(r=a>=0?1:-1),!n.parent.inlineContent){let o=he.findFrom(n,r,!0)||he.findFrom(n,-r,!0);if(o)n=o.$head;else return he.near(n,r)}return t.parent.inlineContent||(a==0?t=n:(t=(he.findFrom(t,-r,!0)||he.findFrom(t,r,!0)).$anchor,t.pos<n.pos!=a<0&&(t=n))),new De(t,n)}}he.jsonID("text",De);class Ln{constructor(t,n){this.anchor=t,this.head=n}map(t){return new Ln(t.map(this.anchor),t.map(this.head))}resolve(t){return De.between(t.resolve(this.anchor),t.resolve(this.head))}}class Ye extends he{constructor(t){let n=t.nodeAfter,r=t.node(0).resolve(t.pos+n.nodeSize);super(t,r),this.node=n}map(t,n){let{deleted:r,pos:a}=n.mapResult(this.anchor),o=t.resolve(a);return r?he.near(o):new Ye(o)}content(){return new ce(ae.from(this.node),0,0)}eq(t){return t instanceof Ye&&t.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new Pr(this.anchor)}static fromJSON(t,n){if(typeof n.anchor!="number")throw new RangeError("Invalid input for NodeSelection.fromJSON");return new Ye(t.resolve(n.anchor))}static create(t,n){return new Ye(t.resolve(n))}static isSelectable(t){return!t.isText&&t.type.spec.selectable!==!1}}Ye.prototype.visible=!1,he.jsonID("node",Ye);class Pr{constructor(t){this.anchor=t}map(t){let{deleted:n,pos:r}=t.mapResult(this.anchor);return n?new Ln(r,r):new Pr(r)}resolve(t){let n=t.resolve(this.anchor),r=n.nodeAfter;return r&&Ye.isSelectable(r)?new Ye(n):he.near(n)}}class ht extends he{constructor(t){super(t.resolve(0),t.resolve(t.content.size))}replace(t,n=ce.empty){if(n==ce.empty){t.delete(0,t.doc.content.size);let r=he.atStart(t.doc);r.eq(t.selection)||t.setSelection(r)}else super.replace(t,n)}toJSON(){return{type:"all"}}static fromJSON(t){return new ht(t)}map(t){return new ht(t)}eq(t){return t instanceof ht}getBookmark(){return Od}}he.jsonID("all",ht);const Od={map(){return this},resolve(e){return new ht(e)}};function Bt(e,t,n,r,a,o=!1){if(t.inlineContent)return De.create(e,n);for(let l=r-(a>0?0:1);a>0?l<t.childCount:l>=0;l+=a){let u=t.child(l);if(u.isAtom){if(!o&&Ye.isSelectable(u))return Ye.create(e,n-(a<0?u.nodeSize:0))}else{let c=Bt(e,u,n+a,a<0?u.childCount:0,a,o);if(c)return c}n+=u.nodeSize*a}return null}function As(e,t,n){let r=e.steps.length-1;if(r<t)return;let a=e.steps[r];if(!(a instanceof ot||a instanceof zt))return;let o=e.mapping.maps[r],l;o.forEach((u,c,d,f)=>{l==null&&(l=f)}),e.setSelection(he.near(e.doc.resolve(l),n))}function zs(e,t){return!t||!e?e:e.bind(t)}class On{constructor(t,n,r){this.name=t,this.init=zs(n.init,r),this.apply=zs(n.apply,r)}}new On("doc",{init(e){return e.doc||e.schema.topNodeType.createAndFill()},apply(e){return e.doc}}),new On("selection",{init(e,t){return e.selection||he.atStart(t.doc)},apply(e){return e.selection}}),new On("storedMarks",{init(e){return e.storedMarks||null},apply(e,t,n,r){return r.selection.$cursor?e.storedMarks:null}}),new On("scrollToSelection",{init(){return 0},apply(e,t){return e.scrolledIntoView?t+1:t}});function Es(e,t,n){for(let r in e){let a=e[r];a instanceof Function?a=a.bind(t):r=="handleDOMEvents"&&(a=Es(a,t,{})),n[r]=a}return n}class sn{constructor(t){this.spec=t,this.props={},t.props&&Es(t.props,this,this.props),this.key=t.key?t.key.key:$s("plugin")}getState(t){return t[this.key]}}const Br=Object.create(null);function $s(e){return e in Br?e+"$"+ ++Br[e]:(Br[e]=0,e+"$")}class on{constructor(t="key"){this.key=$s(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}function Ls(e){const{state:t,transaction:n}=e;let{selection:r}=n,{doc:a}=n,{storedMarks:o}=n;return{...t,apply:t.apply.bind(t),applyTransaction:t.applyTransaction.bind(t),filterTransaction:t.filterTransaction,plugins:t.plugins,schema:t.schema,reconfigure:t.reconfigure.bind(t),toJSON:t.toJSON.bind(t),get storedMarks(){return o},get selection(){return r},get doc(){return a},get tr(){return r=n.selection,a=n.doc,o=n.storedMarks,n}}}class Pd{constructor(t){this.editor=t.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=t.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:t,editor:n,state:r}=this,{view:a}=n,{tr:o}=r,l=this.buildProps(o);return Object.fromEntries(Object.entries(t).map(([u,c])=>[u,(...f)=>{const h=c(...f)(l);return!o.getMeta("preventDispatch")&&!this.hasCustomState&&a.dispatch(o),h}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,n=!0){const{rawCommands:r,editor:a,state:o}=this,{view:l}=a,u=[],c=!!t,d=t||o.tr,f=()=>(!c&&n&&!d.getMeta("preventDispatch")&&!this.hasCustomState&&l.dispatch(d),u.every(g=>g===!0)),h={...Object.fromEntries(Object.entries(r).map(([g,m])=>[g,(...w)=>{const _=this.buildProps(d,n),D=m(...w)(_);return u.push(D),h}])),run:f};return h}createCan(t){const{rawCommands:n,state:r}=this,a=!1,o=t||r.tr,l=this.buildProps(o,a);return{...Object.fromEntries(Object.entries(n).map(([c,d])=>[c,(...f)=>d(...f)({...l,dispatch:void 0})])),chain:()=>this.createChain(o,a)}}buildProps(t,n=!0){const{rawCommands:r,editor:a,state:o}=this,{view:l}=a;o.storedMarks&&t.setStoredMarks(o.storedMarks);const u={tr:t,editor:a,view:l,state:Ls({state:o,transaction:t}),dispatch:n?()=>{}:void 0,chain:()=>this.createChain(t),can:()=>this.createCan(t),get commands(){return Object.fromEntries(Object.entries(r).map(([c,d])=>[c,(...f)=>d(...f)(u)]))}};return u}}function vt(e,t,n){return e.config[t]===void 0&&e.parent?vt(e.parent,t,n):typeof e.config[t]=="function"?e.config[t].bind({...n,parent:e.parent?vt(e.parent,t,n):null}):e.config[t]}function Bd(e){const t=e.filter(a=>a.type==="extension"),n=e.filter(a=>a.type==="node"),r=e.filter(a=>a.type==="mark");return{baseExtensions:t,nodeExtensions:n,markExtensions:r}}function Le(e,t){if(typeof e=="string"){if(!t.nodes[e])throw Error(`There is no node type named '${e}'. Maybe you forgot to add the extension?`);return t.nodes[e]}return e}function Vd(e){return typeof e=="function"}function Vt(e,t=void 0,...n){return Vd(e)?t?e.bind(t)(...n):e(...n):e}function Nd(e){return Object.prototype.toString.call(e)==="[object RegExp]"}function qd(e){return Object.prototype.toString.call(e).slice(8,-1)}function Vr(e){return qd(e)!=="Object"?!1:e.constructor===Object&&Object.getPrototypeOf(e)===Object.prototype}function Os(e,t){const n={...e};return Vr(e)&&Vr(t)&&Object.keys(t).forEach(r=>{Vr(t[r])?r in e?n[r]=Os(e[r],t[r]):Object.assign(n,{[r]:t[r]}):Object.assign(n,{[r]:t[r]})}),n}class lt{constructor(t={}){this.type="extension",this.name="extension",this.parent=null,this.child=null,this.config={name:this.name,defaultOptions:{}},this.config={...this.config,...t},this.name=this.config.name,t.defaultOptions&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${this.name}".`),this.options=this.config.defaultOptions,this.config.addOptions&&(this.options=Vt(vt(this,"addOptions",{name:this.name}))),this.storage=Vt(vt(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new lt(t)}configure(t={}){const n=this.extend();return n.options=Os(this.options,t),n.storage=Vt(vt(n,"addStorage",{name:n.name,options:n.options})),n}extend(t={}){const n=new lt(t);return n.parent=this,this.child=n,n.name=t.name?t.name:n.parent.name,t.defaultOptions&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${n.name}".`),n.options=Vt(vt(n,"addOptions",{name:n.name})),n.storage=Vt(vt(n,"addStorage",{name:n.name,options:n.options})),n}}function Fd(e,t,n){const{from:r,to:a}=t,{blockSeparator:o=`
103
103
 
104
104
  `,textSerializers:l={}}=n||{};let u="",c=!0;return e.nodesBetween(r,a,(d,f,h,g)=>{var m;const C=l==null?void 0:l[d.type.name];C?(d.isBlock&&!c&&(u+=o,c=!0),h&&(u+=C({node:d,pos:f,parent:h,index:g,range:t}))):d.isText?(u+=(m=d==null?void 0:d.text)===null||m===void 0?void 0:m.slice(Math.max(r,f)-f,a-f),c=!1):d.isBlock&&!c&&(u+=o,c=!0)}),u}function Gd(e){return Object.fromEntries(Object.entries(e.nodes).filter(([,t])=>t.spec.toText).map(([t,n])=>[t,n.spec.toText]))}lt.create({name:"clipboardTextSerializer",addProseMirrorPlugins(){return[new sn({key:new on("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:e}=this,{state:t,schema:n}=e,{doc:r,selection:a}=t,{ranges:o}=a,l=Math.min(...o.map(f=>f.$from.pos)),u=Math.max(...o.map(f=>f.$to.pos)),c=Gd(n);return Fd(r,{from:l,to:u},{textSerializers:c})}}})]}});const Wd=()=>({editor:e,view:t})=>(requestAnimationFrame(()=>{var n;e.isDestroyed||(t.dom.blur(),(n=window==null?void 0:window.getSelection())===null||n===void 0||n.removeAllRanges())}),!0),jd=(e=!1)=>({commands:t})=>t.setContent("",e),Rd=()=>({state:e,tr:t,dispatch:n})=>{const{selection:r}=t,{ranges:a}=r;return n&&a.forEach(({$from:o,$to:l})=>{e.doc.nodesBetween(o.pos,l.pos,(u,c)=>{if(u.type.isText)return;const{doc:d,mapping:f}=t,h=d.resolve(f.map(c)),g=d.resolve(f.map(c+u.nodeSize)),m=h.blockRange(g);if(!m)return;const C=Ed(m);if(u.type.isTextblock){const{defaultType:w}=h.parent.contentMatchAt(h.index());t.setNodeMarkup(m.start,w)}(C||C===0)&&t.lift(m,C)})}),!0},Yd=e=>t=>e(t),Qd=()=>({state:e,dispatch:t})=>Ie.createParagraphNear(e,t),Kd=()=>({tr:e,dispatch:t})=>{const{selection:n}=e,r=n.$anchor.node();if(r.content.size>0)return!1;const a=e.selection.$anchor;for(let o=a.depth;o>0;o-=1)if(a.node(o).type===r.type){if(t){const u=a.before(o),c=a.after(o);e.delete(u,c).scrollIntoView()}return!0}return!1},Ud=e=>({tr:t,state:n,dispatch:r})=>{const a=Le(e,n.schema),o=t.selection.$anchor;for(let l=o.depth;l>0;l-=1)if(o.node(l).type===a){if(r){const c=o.before(l),d=o.after(l);t.delete(c,d).scrollIntoView()}return!0}return!1},Xd=e=>({tr:t,dispatch:n})=>{const{from:r,to:a}=e;return n&&t.delete(r,a),!0},Jd=()=>({state:e,dispatch:t})=>Ie.deleteSelection(e,t),Zd=()=>({commands:e})=>e.keyboardShortcut("Enter"),Hd=()=>({state:e,dispatch:t})=>Ie.exitCode(e,t);function Pn(e,t,n={strict:!0}){const r=Object.keys(t);return r.length?r.every(a=>n.strict?t[a]===e[a]:Nd(t[a])?t[a].test(e[a]):t[a]===e[a]):!0}function Nr(e,t,n={}){return e.find(r=>r.type===t&&Pn(r.attrs,n))}function ep(e,t,n={}){return!!Nr(e,t,n)}function Ps(e,t,n={}){if(!e||!t)return;let r=e.parent.childAfter(e.parentOffset);if(e.parentOffset===r.offset&&r.offset!==0&&(r=e.parent.childBefore(e.parentOffset)),!r.node)return;const a=Nr([...r.node.marks],t,n);if(!a)return;let o=r.index,l=e.start()+r.offset,u=o+1,c=l+r.node.nodeSize;for(Nr([...r.node.marks],t,n);o>0&&a.isInSet(e.parent.child(o-1).marks);)o-=1,l-=e.parent.child(o).nodeSize;for(;u<e.parent.childCount&&ep([...e.parent.child(u).marks],t,n);)c+=e.parent.child(u).nodeSize,u+=1;return{from:l,to:c}}function xt(e,t){if(typeof e=="string"){if(!t.marks[e])throw Error(`There is no mark type named '${e}'. Maybe you forgot to add the extension?`);return t.marks[e]}return e}const tp=(e,t={})=>({tr:n,state:r,dispatch:a})=>{const o=xt(e,r.schema),{doc:l,selection:u}=n,{$from:c,from:d,to:f}=u;if(a){const h=Ps(c,o,t);if(h&&h.from<=d&&h.to>=f){const g=De.create(l,h.from,h.to);n.setSelection(g)}}return!0},np=e=>t=>{const n=typeof e=="function"?e(t):e;for(let r=0;r<n.length;r+=1)if(n[r](t))return!0;return!1};function Bs(e){return e instanceof De}function Et(e=0,t=0,n=0){return Math.min(Math.max(e,t),n)}function rp(e,t=null){if(!t)return null;const n=he.atStart(e),r=he.atEnd(e);if(t==="start"||t===!0)return n;if(t==="end")return r;const a=n.from,o=r.to;return t==="all"?De.create(e,Et(0,a,o),Et(e.content.size,a,o)):De.create(e,Et(t,a,o),Et(t,a,o))}function qr(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}const ip=(e=null,t={})=>({editor:n,view:r,tr:a,dispatch:o})=>{t={scrollIntoView:!0,...t};const l=()=>{qr()&&r.dom.focus(),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),t!=null&&t.scrollIntoView&&n.commands.scrollIntoView())})};if(r.hasFocus()&&e===null||e===!1)return!0;if(o&&e===null&&!Bs(n.state.selection))return l(),!0;const u=rp(a.doc,e)||n.state.selection,c=n.state.selection.eq(u);return o&&(c||a.setSelection(u),c&&a.storedMarks&&a.setStoredMarks(a.storedMarks),l()),!0},ap=(e,t)=>n=>e.every((r,a)=>t(r,{...n,index:a})),sp=(e,t)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},e,t);function Vs(e){const t=`<body>${e}</body>`;return new window.DOMParser().parseFromString(t,"text/html").body}function Bn(e,t,n){if(n={slice:!0,parseOptions:{},...n},typeof e=="object"&&e!==null)try{return Array.isArray(e)&&e.length>0?ae.fromArray(e.map(r=>t.nodeFromJSON(r))):t.nodeFromJSON(e)}catch(r){return console.warn("[tiptap warn]: Invalid content.","Passed value:",e,"Error:",r),Bn("",t,n)}if(typeof e=="string"){const r=Mn.fromSchema(t);return n.slice?r.parseSlice(Vs(e),n.parseOptions).content:r.parse(Vs(e),n.parseOptions)}return Bn("",t,n)}function op(e,t,n){const r=e.steps.length-1;if(r<t)return;const a=e.steps[r];if(!(a instanceof ot||a instanceof zt))return;const o=e.mapping.maps[r];let l=0;o.forEach((u,c,d,f)=>{l===0&&(l=f)}),e.setSelection(he.near(e.doc.resolve(l),n))}const lp=e=>e.toString().startsWith("<"),up=(e,t,n)=>({tr:r,dispatch:a,editor:o})=>{if(a){n={parseOptions:{},updateSelection:!0,...n};const l=Bn(t,o.schema,{parseOptions:{preserveWhitespace:"full",...n.parseOptions}});if(l.toString()==="<>")return!0;let{from:u,to:c}=typeof e=="number"?{from:e,to:e}:e,d=!0,f=!0;if((lp(l)?l:[l]).forEach(g=>{g.check(),d=d?g.isText&&g.marks.length===0:!1,f=f?g.isBlock:!1}),u===c&&f){const{parent:g}=r.doc.resolve(u);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(u-=1,c+=1)}d?Array.isArray(t)?r.insertText(t.map(g=>g.text||"").join(""),u,c):typeof t=="object"&&t&&t.text?r.insertText(t.text,u,c):r.insertText(t,u,c):r.replaceWith(u,c,l),n.updateSelection&&op(r,r.steps.length-1,-1)}return!0},cp=()=>({state:e,dispatch:t})=>Ie.joinUp(e,t),dp=()=>({state:e,dispatch:t})=>Ie.joinDown(e,t),pp=()=>({state:e,dispatch:t})=>Ie.joinBackward(e,t),hp=()=>({state:e,dispatch:t})=>Ie.joinForward(e,t);function Ns(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function fp(e){const t=e.split(/-(?!$)/);let n=t[t.length-1];n==="Space"&&(n=" ");let r,a,o,l;for(let u=0;u<t.length-1;u+=1){const c=t[u];if(/^(cmd|meta|m)$/i.test(c))l=!0;else if(/^a(lt)?$/i.test(c))r=!0;else if(/^(c|ctrl|control)$/i.test(c))a=!0;else if(/^s(hift)?$/i.test(c))o=!0;else if(/^mod$/i.test(c))qr()||Ns()?l=!0:a=!0;else throw new Error(`Unrecognized modifier name: ${c}`)}return r&&(n=`Alt-${n}`),a&&(n=`Ctrl-${n}`),l&&(n=`Meta-${n}`),o&&(n=`Shift-${n}`),n}const gp=e=>({editor:t,view:n,tr:r,dispatch:a})=>{const o=fp(e).split(/-(?!$)/),l=o.find(d=>!["Alt","Ctrl","Meta","Shift"].includes(d)),u=new KeyboardEvent("keydown",{key:l==="Space"?" ":l,altKey:o.includes("Alt"),ctrlKey:o.includes("Ctrl"),metaKey:o.includes("Meta"),shiftKey:o.includes("Shift"),bubbles:!0,cancelable:!0}),c=t.captureTransaction(()=>{n.someProp("handleKeyDown",d=>d(n,u))});return c==null||c.steps.forEach(d=>{const f=d.map(r.mapping);f&&a&&r.maybeStep(f)}),!0};function Fr(e,t,n={}){const{from:r,to:a,empty:o}=e.selection,l=t?Le(t,e.schema):null,u=[];e.doc.nodesBetween(r,a,(h,g)=>{if(h.isText)return;const m=Math.max(r,g),C=Math.min(a,g+h.nodeSize);u.push({node:h,from:m,to:C})});const c=a-r,d=u.filter(h=>l?l.name===h.node.type.name:!0).filter(h=>Pn(h.node.attrs,n,{strict:!1}));return o?!!d.length:d.reduce((h,g)=>h+g.to-g.from,0)>=c}const mp=(e,t={})=>({state:n,dispatch:r})=>{const a=Le(e,n.schema);return Fr(n,a,t)?Ie.lift(n,r):!1},yp=()=>({state:e,dispatch:t})=>Ie.liftEmptyBlock(e,t),bp=e=>({state:t,dispatch:n})=>{const r=Le(e,t.schema);return pr.liftListItem(r)(t,n)},vp=()=>({state:e,dispatch:t})=>Ie.newlineInCode(e,t);function qs(e,t){return t.nodes[e]?"node":t.marks[e]?"mark":null}function Fs(e,t){const n=typeof t=="string"?[t]:t;return Object.keys(e).reduce((r,a)=>(n.includes(a)||(r[a]=e[a]),r),{})}const xp=(e,t)=>({tr:n,state:r,dispatch:a})=>{let o=null,l=null;const u=qs(typeof e=="string"?e:e.name,r.schema);return u?(u==="node"&&(o=Le(e,r.schema)),u==="mark"&&(l=xt(e,r.schema)),a&&n.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(d,f)=>{o&&o===d.type&&n.setNodeMarkup(f,void 0,Fs(d.attrs,t)),l&&d.marks.length&&d.marks.forEach(h=>{l===h.type&&n.addMark(f,f+d.nodeSize,l.create(Fs(h.attrs,t)))})})}),!0):!1},wp=()=>({tr:e,dispatch:t})=>(t&&e.scrollIntoView(),!0),Cp=()=>({tr:e,commands:t})=>t.setTextSelection({from:0,to:e.doc.content.size}),Sp=()=>({state:e,dispatch:t})=>Ie.selectNodeBackward(e,t),_p=()=>({state:e,dispatch:t})=>Ie.selectNodeForward(e,t),kp=()=>({state:e,dispatch:t})=>Ie.selectParentNode(e,t),Tp=()=>({state:e,dispatch:t})=>Ie.selectTextblockEnd(e,t),Dp=()=>({state:e,dispatch:t})=>Ie.selectTextblockStart(e,t);function Mp(e,t,n={}){return Bn(e,t,{slice:!1,parseOptions:n})}const Ip=(e,t=!1,n={})=>({tr:r,editor:a,dispatch:o})=>{const{doc:l}=r,u=Mp(e,a.schema,n);return o&&r.replaceWith(0,l.content.size,u).setMeta("preventUpdate",!t),!0};function Ap(e){for(let t=0;t<e.edgeCount;t+=1){const{type:n}=e.edge(t);if(n.isTextblock&&!n.hasRequiredAttrs())return n}return null}function zp(e,t){for(let n=e.depth;n>0;n-=1){const r=e.node(n);if(t(r))return{pos:n>0?e.before(n):0,start:e.start(n),depth:n,node:r}}}function Gr(e){return t=>zp(t.$from,e)}function Ep(e,t){const n=xt(t,e.schema),{from:r,to:a,empty:o}=e.selection,l=[];o?(e.storedMarks&&l.push(...e.storedMarks),l.push(...e.selection.$head.marks())):e.doc.nodesBetween(r,a,c=>{l.push(...c.marks)});const u=l.find(c=>c.type.name===n.name);return u?{...u.attrs}:{}}function Vn(e,t,n){return Object.fromEntries(Object.entries(n).filter(([r])=>{const a=e.find(o=>o.type===t&&o.name===r);return a?a.attribute.keepOnSplit:!1}))}function $p(e,t,n={}){const{empty:r,ranges:a}=e.selection,o=t?xt(t,e.schema):null;if(r)return!!(e.storedMarks||e.selection.$from.marks()).filter(h=>o?o.name===h.type.name:!0).find(h=>Pn(h.attrs,n,{strict:!1}));let l=0;const u=[];if(a.forEach(({$from:h,$to:g})=>{const m=h.pos,C=g.pos;e.doc.nodesBetween(m,C,(w,_)=>{if(!w.isText&&!w.marks.length)return;const D=Math.max(m,_),I=Math.min(C,_+w.nodeSize),B=I-D;l+=B,u.push(...w.marks.map(N=>({mark:N,from:D,to:I})))})}),l===0)return!1;const c=u.filter(h=>o?o.name===h.mark.type.name:!0).filter(h=>Pn(h.mark.attrs,n,{strict:!1})).reduce((h,g)=>h+g.to-g.from,0),d=u.filter(h=>o?h.mark.type!==o&&h.mark.type.excludes(o):!0).reduce((h,g)=>h+g.to-g.from,0);return(c>0?c+d:c)>=l}function Gs(e,t){const{nodeExtensions:n}=Bd(t),r=n.find(l=>l.name===e);if(!r)return!1;const a={name:r.name,options:r.options,storage:r.storage},o=Vt(vt(r,"group",a));return typeof o!="string"?!1:o.split(" ").includes("list")}function Lp(e,t,n){var r;const{selection:a}=t;let o=null;if(Bs(a)&&(o=a.$cursor),o){const u=(r=e.storedMarks)!==null&&r!==void 0?r:o.marks();return!!n.isInSet(u)||!u.some(c=>c.type.excludes(n))}const{ranges:l}=a;return l.some(({$from:u,$to:c})=>{let d=u.depth===0?e.doc.inlineContent&&e.doc.type.allowsMarkType(n):!1;return e.doc.nodesBetween(u.pos,c.pos,(f,h,g)=>{if(d)return!1;if(f.isInline){const m=!g||g.type.allowsMarkType(n),C=!!n.isInSet(f.marks)||!f.marks.some(w=>w.type.excludes(n));d=m&&C}return!d}),d})}const Op=(e,t={})=>({tr:n,state:r,dispatch:a})=>{const{selection:o}=n,{empty:l,ranges:u}=o,c=xt(e,r.schema);if(a)if(l){const d=Ep(r,c);n.addStoredMark(c.create({...d,...t}))}else u.forEach(d=>{const f=d.$from.pos,h=d.$to.pos;r.doc.nodesBetween(f,h,(g,m)=>{const C=Math.max(m,f),w=Math.min(m+g.nodeSize,h);g.marks.find(D=>D.type===c)?g.marks.forEach(D=>{c===D.type&&n.addMark(C,w,c.create({...D.attrs,...t}))}):n.addMark(C,w,c.create(t))})});return Lp(r,n,c)},Pp=(e,t)=>({tr:n})=>(n.setMeta(e,t),!0),Bp=(e,t={})=>({state:n,dispatch:r,chain:a})=>{const o=Le(e,n.schema);return o.isTextblock?a().command(({commands:l})=>Ie.setBlockType(o,t)(n)?!0:l.clearNodes()).command(({state:l})=>Ie.setBlockType(o,t)(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},Vp=e=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,a=Et(e,0,r.content.size),o=Ye.create(r,a);t.setSelection(o)}return!0},Np=e=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,{from:a,to:o}=typeof e=="number"?{from:e,to:e}:e,l=De.atStart(r).from,u=De.atEnd(r).to,c=Et(a,l,u),d=Et(o,l,u),f=De.create(r,c,d);t.setSelection(f)}return!0},qp=e=>({state:t,dispatch:n})=>{const r=Le(e,t.schema);return pr.sinkListItem(r)(t,n)};function Ws(e,t){const n=e.storedMarks||e.selection.$to.parentOffset&&e.selection.$from.marks();if(n){const r=n.filter(a=>t==null?void 0:t.includes(a.type.name));e.tr.ensureMarks(r)}}const Fp=({keepMarks:e=!0}={})=>({tr:t,state:n,dispatch:r,editor:a})=>{const{selection:o,doc:l}=t,{$from:u,$to:c}=o,d=a.extensionManager.attributes,f=Vn(d,u.node().type.name,u.node().attrs);if(o instanceof Ye&&o.node.isBlock)return!u.parentOffset||!$n(l,u.pos)?!1:(r&&(e&&Ws(n,a.extensionManager.splittableMarks),t.split(u.pos).scrollIntoView()),!0);if(!u.parent.isBlock)return!1;if(r){const h=c.parentOffset===c.parent.content.size;o instanceof De&&t.deleteSelection();const g=u.depth===0?void 0:Ap(u.node(-1).contentMatchAt(u.indexAfter(-1)));let m=h&&g?[{type:g,attrs:f}]:void 0,C=$n(t.doc,t.mapping.map(u.pos),1,m);if(!m&&!C&&$n(t.doc,t.mapping.map(u.pos),1,g?[{type:g}]:void 0)&&(C=!0,m=g?[{type:g,attrs:f}]:void 0),C&&(t.split(t.mapping.map(u.pos),1,m),g&&!h&&!u.parentOffset&&u.parent.type!==g)){const w=t.mapping.map(u.before()),_=t.doc.resolve(w);u.node(-1).canReplaceWith(_.index(),_.index()+1,g)&&t.setNodeMarkup(t.mapping.map(u.before()),g)}e&&Ws(n,a.extensionManager.splittableMarks),t.scrollIntoView()}return!0},Gp=e=>({tr:t,state:n,dispatch:r,editor:a})=>{var o;const l=Le(e,n.schema),{$from:u,$to:c}=n.selection,d=n.selection.node;if(d&&d.isBlock||u.depth<2||!u.sameParent(c))return!1;const f=u.node(-1);if(f.type!==l)return!1;const h=a.extensionManager.attributes;if(u.parent.content.size===0&&u.node(-1).childCount===u.indexAfter(-1)){if(u.depth===2||u.node(-3).type!==l||u.index(-2)!==u.node(-2).childCount-1)return!1;if(r){let _=ae.empty;const D=u.index(-1)?1:u.index(-2)?2:3;for(let A=u.depth-D;A>=u.depth-3;A-=1)_=ae.from(u.node(A).copy(_));const I=u.indexAfter(-1)<u.node(-2).childCount?1:u.indexAfter(-2)<u.node(-3).childCount?2:3,B=Vn(h,u.node().type.name,u.node().attrs),N=((o=l.contentMatch.defaultType)===null||o===void 0?void 0:o.createAndFill(B))||void 0;_=_.append(ae.from(l.createAndFill(null,N)||void 0));const O=u.before(u.depth-(D-1));t.replace(O,u.after(-I),new ce(_,4-D,0));let z=-1;t.doc.nodesBetween(O,t.doc.content.size,(A,G)=>{if(z>-1)return!1;A.isTextblock&&A.content.size===0&&(z=G+1)}),z>-1&&t.setSelection(De.near(t.doc.resolve(z))),t.scrollIntoView()}return!0}const g=c.pos===u.end()?f.contentMatchAt(0).defaultType:null,m=Vn(h,f.type.name,f.attrs),C=Vn(h,u.node().type.name,u.node().attrs);t.delete(u.pos,c.pos);const w=g?[{type:l,attrs:m},{type:g,attrs:C}]:[{type:l,attrs:m}];if(!$n(t.doc,u.pos,2))return!1;if(r){const{selection:_,storedMarks:D}=n,{splittableMarks:I}=a.extensionManager,B=D||_.$to.parentOffset&&_.$from.marks();if(t.split(u.pos,2,w).scrollIntoView(),!B||!r)return!0;const N=B.filter(O=>I.includes(O.type.name));t.ensureMarks(N)}return!0},Wr=(e,t)=>{const n=Gr(l=>l.type===t)(e.selection);if(!n)return!0;const r=e.doc.resolve(Math.max(0,n.pos-1)).before(n.depth);if(r===void 0)return!0;const a=e.doc.nodeAt(r);return n.node.type===(a==null?void 0:a.type)&&Ds(e.doc,n.pos)&&e.join(n.pos),!0},jr=(e,t)=>{const n=Gr(l=>l.type===t)(e.selection);if(!n)return!0;const r=e.doc.resolve(n.start).after(n.depth);if(r===void 0)return!0;const a=e.doc.nodeAt(r);return n.node.type===(a==null?void 0:a.type)&&Ds(e.doc,r)&&e.join(r),!0};var Wp=Object.freeze({__proto__:null,blur:Wd,clearContent:jd,clearNodes:Rd,command:Yd,createParagraphNear:Qd,deleteCurrentNode:Kd,deleteNode:Ud,deleteRange:Xd,deleteSelection:Jd,enter:Zd,exitCode:Hd,extendMarkRange:tp,first:np,focus:ip,forEach:ap,insertContent:sp,insertContentAt:up,joinUp:cp,joinDown:dp,joinBackward:pp,joinForward:hp,keyboardShortcut:gp,lift:mp,liftEmptyBlock:yp,liftListItem:bp,newlineInCode:vp,resetAttributes:xp,scrollIntoView:wp,selectAll:Cp,selectNodeBackward:Sp,selectNodeForward:_p,selectParentNode:kp,selectTextblockEnd:Tp,selectTextblockStart:Dp,setContent:Ip,setMark:Op,setMeta:Pp,setNode:Bp,setNodeSelection:Vp,setTextSelection:Np,sinkListItem:qp,splitBlock:Fp,splitListItem:Gp,toggleList:(e,t,n,r={})=>({editor:a,tr:o,state:l,dispatch:u,chain:c,commands:d,can:f})=>{const{extensions:h,splittableMarks:g}=a.extensionManager,m=Le(e,l.schema),C=Le(t,l.schema),{selection:w,storedMarks:_}=l,{$from:D,$to:I}=w,B=D.blockRange(I),N=_||w.$to.parentOffset&&w.$from.marks();if(!B)return!1;const O=Gr(z=>Gs(z.type.name,h))(w);if(B.depth>=1&&O&&B.depth-O.depth<=1){if(O.node.type===m)return d.liftListItem(C);if(Gs(O.node.type.name,h)&&m.validContent(O.node.content)&&u)return c().command(()=>(o.setNodeMarkup(O.pos,m),!0)).command(()=>Wr(o,m)).command(()=>jr(o,m)).run()}return!n||!N||!u?c().command(()=>f().wrapInList(m,r)?!0:d.clearNodes()).wrapInList(m,r).command(()=>Wr(o,m)).command(()=>jr(o,m)).run():c().command(()=>{const z=f().wrapInList(m,r),A=N.filter(G=>g.includes(G.type.name));return o.ensureMarks(A),z?!0:d.clearNodes()}).wrapInList(m,r).command(()=>Wr(o,m)).command(()=>jr(o,m)).run()},toggleMark:(e,t={},n={})=>({state:r,commands:a})=>{const{extendEmptyMarkRange:o=!1}=n,l=xt(e,r.schema);return $p(r,l,t)?a.unsetMark(l,{extendEmptyMarkRange:o}):a.setMark(l,t)},toggleNode:(e,t,n={})=>({state:r,commands:a})=>{const o=Le(e,r.schema),l=Le(t,r.schema);return Fr(r,o,n)?a.setNode(l):a.setNode(o,n)},toggleWrap:(e,t={})=>({state:n,commands:r})=>{const a=Le(e,n.schema);return Fr(n,a,t)?r.lift(a):r.wrapIn(a,t)},undoInputRule:()=>({state:e,dispatch:t})=>{const n=e.plugins;for(let r=0;r<n.length;r+=1){const a=n[r];let o;if(a.spec.isInputRules&&(o=a.getState(e))){if(t){const l=e.tr,u=o.transform;for(let c=u.steps.length-1;c>=0;c-=1)l.step(u.steps[c].invert(u.docs[c]));if(o.text){const c=l.doc.resolve(o.from).marks();l.replaceWith(o.from,o.to,e.schema.text(o.text,c))}else l.delete(o.from,o.to)}return!0}}return!1},unsetAllMarks:()=>({tr:e,dispatch:t})=>{const{selection:n}=e,{empty:r,ranges:a}=n;return r||t&&a.forEach(o=>{e.removeMark(o.$from.pos,o.$to.pos)}),!0},unsetMark:(e,t={})=>({tr:n,state:r,dispatch:a})=>{var o;const{extendEmptyMarkRange:l=!1}=t,{selection:u}=n,c=xt(e,r.schema),{$from:d,empty:f,ranges:h}=u;if(!a)return!0;if(f&&l){let{from:g,to:m}=u;const C=(o=d.marks().find(_=>_.type===c))===null||o===void 0?void 0:o.attrs,w=Ps(d,c,C);w&&(g=w.from,m=w.to),n.removeMark(g,m,c)}else h.forEach(g=>{n.removeMark(g.$from.pos,g.$to.pos,c)});return n.removeStoredMark(c),!0},updateAttributes:(e,t={})=>({tr:n,state:r,dispatch:a})=>{let o=null,l=null;const u=qs(typeof e=="string"?e:e.name,r.schema);return u?(u==="node"&&(o=Le(e,r.schema)),u==="mark"&&(l=xt(e,r.schema)),a&&n.selection.ranges.forEach(c=>{const d=c.$from.pos,f=c.$to.pos;r.doc.nodesBetween(d,f,(h,g)=>{o&&o===h.type&&n.setNodeMarkup(g,void 0,{...h.attrs,...t}),l&&h.marks.length&&h.marks.forEach(m=>{if(l===m.type){const C=Math.max(g,d),w=Math.min(g+h.nodeSize,f);n.addMark(C,w,l.create({...m.attrs,...t}))}})})}),!0):!1},wrapIn:(e,t={})=>({state:n,dispatch:r})=>{const a=Le(e,n.schema);return Ie.wrapIn(a,t)(n,r)},wrapInList:(e,t={})=>({state:n,dispatch:r})=>{const a=Le(e,n.schema);return pr.wrapInList(a,t)(n,r)}});lt.create({name:"commands",addCommands(){return{...Wp}}}),lt.create({name:"editable",addProseMirrorPlugins(){return[new sn({key:new on("editable"),props:{editable:()=>this.editor.options.editable}})]}}),lt.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:e}=this;return[new sn({key:new on("focusEvents"),props:{handleDOMEvents:{focus:(t,n)=>{e.isFocused=!0;const r=e.state.tr.setMeta("focus",{event:n}).setMeta("addToHistory",!1);return t.dispatch(r),!1},blur:(t,n)=>{e.isFocused=!1;const r=e.state.tr.setMeta("blur",{event:n}).setMeta("addToHistory",!1);return t.dispatch(r),!1}}}})]}}),lt.create({name:"keymap",addKeyboardShortcuts(){const e=()=>this.editor.commands.first(({commands:l})=>[()=>l.undoInputRule(),()=>l.command(({tr:u})=>{const{selection:c,doc:d}=u,{empty:f,$anchor:h}=c,{pos:g,parent:m}=h,C=he.atStart(d).from===g;return!f||!C||!m.type.isTextblock||m.textContent.length?!1:l.clearNodes()}),()=>l.deleteSelection(),()=>l.joinBackward(),()=>l.selectNodeBackward()]),t=()=>this.editor.commands.first(({commands:l})=>[()=>l.deleteSelection(),()=>l.deleteCurrentNode(),()=>l.joinForward(),()=>l.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:l})=>[()=>l.newlineInCode(),()=>l.createParagraphNear(),()=>l.liftEmptyBlock(),()=>l.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:e,"Mod-Backspace":e,"Shift-Backspace":e,Delete:t,"Mod-Delete":t,"Mod-a":()=>this.editor.commands.selectAll()},a={...r},o={...r,"Ctrl-h":e,"Alt-Backspace":e,"Ctrl-d":t,"Ctrl-Alt-Backspace":t,"Alt-Delete":t,"Alt-d":t,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return qr()||Ns()?o:a},addProseMirrorPlugins(){return[new sn({key:new on("clearDocument"),appendTransaction:(e,t,n)=>{if(!(e.some(C=>C.docChanged)&&!t.doc.eq(n.doc)))return;const{empty:a,from:o,to:l}=t.selection,u=he.atStart(t.doc).from,c=he.atEnd(t.doc).to;if(a||!(o===u&&l===c)||!(n.doc.textBetween(0,n.doc.content.size," "," ").length===0))return;const h=n.tr,g=Ls({state:n,transaction:h}),{commands:m}=new Pd({editor:this.editor,state:g});if(m.clearNodes(),!!h.steps.length)return h}})]}}),lt.create({name:"tabindex",addProseMirrorPlugins(){return[new sn({key:new on("tabindex"),props:{attributes:this.editor.isEditable?{tabindex:"0"}:{}}})]}});const js=lt.create({name:"fontSize",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{fontSize:{default:null,parseHTML:e=>e.style.fontSize.replace(/['"]+/g,""),renderHTML:e=>e.fontSize?{style:`font-size: ${e.fontSize}`}:{}}}}]},addCommands(){return{setFontSize:e=>({chain:t})=>t().setMark("textStyle",{fontSize:e}).run(),unsetFontSize:()=>({chain:e})=>e().setMark("textStyle",{fontSize:null}).removeEmptyTextStyle().run()}}}),jp=["8","10","12","14","16","18","20","24","30","36","48","60","72"].map(e=>`${e}px`),Rp=[{label:"auto",value:""}].concat(jp.map(e=>({label:e,value:e}))),Yp={input:{height:"26px",minHeight:"26px",lineHeight:"26px",borderColor:"#ced4da !important"}},Qp=({editor:e})=>{const t=e.getAttributes("textStyle").fontSize;return i(J.RichTextEditor.ControlsGroup,{children:i(s.NativeSelect,{size:"xs",icon:i($.IconTextSize,{stroke:1.5,size:16}),data:Rp,styles:Yp,value:t||"",onChange:n=>{const r=n.currentTarget.value;r?e.chain().focus().setFontSize(r).run():e.chain().focus().unsetFontSize().run()}})})},Nn=({value:e,styles:t={}})=>{const n=Wa.useEditor({extensions:[ja,Ga,J.Link,Oa,La,Ea,Va.configure({resizable:!1,HTMLAttributes:{class:"rich-text-table-render"}}),Fa,qa,Na,Pa.configure({types:["heading","paragraph"]}),$a.configure({placeholder:"This is placeholder"}),Ba,za.Color,js],content:e,editable:!1});y.useEffect(()=>{n==null||n.commands.setContent(e)},[e,n]);const r=y.useMemo(()=>x.defaultsDeep({},{content:Ir},t),[t]);return i(J.RichTextEditor,{editor:n,styles:r,children:i(J.RichTextEditor.Content,{})})};function Kp(){const[e,{open:t,close:n}]=Me.useDisclosure(!1);return p(P,{children:[i(s.Modal,{opened:e,onClose:n,title:"About FunctionUtils",zIndex:330,withinPortal:!0,children:i(Nn,{value:ju,styles:{root:{border:"none"},content:{padding:0,table:{marginBottom:0}}}})}),i(s.Button,{variant:"light",color:"violet",size:"xs",onClick:t,leftIcon:i($.IconInfoCircle,{size:16}),children:"About parameter 'utils'"})]})}const Up=({value:e,onChange:t})=>{const n=r=>{r&&t(r)};return i(s.Box,{sx:{position:"relative",flexGrow:1},children:i(Ae,{className:"function-editor",height:"100%",defaultLanguage:"javascript",value:e,onChange:n,theme:"vs-dark",options:{lineNumbers:"off",folding:!1,lineDecorationsWidth:20,lineNumbersMinChars:0,wordWrap:"on",minimap:{enabled:!1}}})})},ln=y.forwardRef(({value:e,onChange:t,label:n,defaultValue:r},a)=>{const[o,l]=y.useState(e),u=()=>{t(o)},c=()=>{l(e)},d=()=>{l(r)};y.useEffect(()=>{l(e)},[e]);const f=o!==e;return p(s.Stack,{spacing:4,sx:{height:"100%"},children:[p(s.Group,{mb:6,position:"apart",sx:{flexShrink:0,flexGrow:0},children:[i(s.Group,{position:"left",children:i(Kp,{})}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:d,size:"xs",variant:"default",leftIcon:i($.IconPlayerSkipBack,{size:16}),children:"Reset to default"}),i(s.Button,{onClick:c,color:"red",size:"xs",disabled:!f,leftIcon:i($.IconRecycle,{size:16}),children:"Revert Changes"}),i(s.Button,{size:"xs",onClick:u,disabled:!f,leftIcon:i($.IconDeviceFloppy,{size:16}),children:"Confirm Changes"})]})]}),i(s.Text,{size:14,children:n}),i(Up,{value:o,onChange:l})]})}),Xp=y.forwardRef(({value:e,onChange:t,label:n,triggerLabel:r="Edit",triggerButtonProps:a={},defaultValue:o},l)=>{const[u,{open:c,close:d}]=Me.useDisclosure(!1);return p(P,{children:[i(s.Modal,{opened:u,onClose:d,title:"Authentication",withinPortal:!0,zIndex:320,size:"900px",children:i(s.Box,{h:600,children:i(ln,{value:e,onChange:t,defaultValue:o,label:n})})}),i(s.Button,{onClick:c,...a,children:r})]})}),Rs=["function aggregation({ queryData }, utils) {",' return "Aggregation Result";',"}"].join(`
105
- `),Nt={type:"none",config:{}};function Jp(e){const t=Array.from(e).sort((r,a)=>r-a),n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function Zp(e){const t=Number(e);return isFinite(t)?t:0}function Hp(e,t){switch(t.type){case"sum":return x.sum(e);case"mean":return x.mean(e);case"median":return Jp(e);case"max":return x.max(e)??0;case"min":return x.min(e)??0;case"quantile":return Ut.quantile(e,t.config.p)??0;case"CV":const n=wn.std(...e),r=wn.mean(...e);return r?n/r:"N/A";case"std":return wn.std(...e);default:return e}}function Rr(e,t){const n=e.map(Zp);return Hp(n,t)}function eh(e,t,n){try{const r=Ht(e,t);return new Function(`return ${n.config.func}`)()({queryData:r},Tt)}catch(r){return console.error(r),r.message}}function qn(e,t,n){try{return n.type==="custom"?eh(e,t,n):Rr(pt(e,t),n)}catch(r){return console.error(r),null}}const th=[{label:"None",value:"none"},{label:"Sum",value:"sum"},{label:"Mean",value:"mean"},{label:"Median",value:"median"},{label:"Max",value:"max"},{label:"Min",value:"min"},{label:"Coefficient of Variation",value:"CV"},{label:"Standard Variation",value:"std"},{label:"Quantile(99%, 95%, ...)",value:"quantile"},{label:"Custom",value:"custom"}];function nh({label:e,value:t,onChange:n,pt:r="sm"},a){y.useEffect(()=>{typeof t=="string"&&n({type:t,config:{}})},[t,n]);const o=c=>{n(c==="quantile"?{type:"quantile",config:{p:.99}}:c==="custom"?{type:"custom",config:{func:Rs}}:{type:c,config:{}})},l=c=>{n({type:"quantile",config:{p:c}})},u=c=>{n({type:"custom",config:{func:c}})};return p(s.Group,{grow:!0,noWrap:!0,pt:r,children:[i(s.Select,{ref:a,label:e,data:th,value:t.type,onChange:o}),t.type==="quantile"&&i(s.NumberInput,{label:"p",value:t.config.p,onChange:l,precision:2,min:.05,step:.05,max:1}),t.type==="custom"&&i(Xp,{label:"",triggerLabel:"Edit Function",value:t.config.func,onChange:u,defaultValue:Rs,triggerButtonProps:{size:"xs",sx:{flexGrow:0,alignSelf:"center",marginTop:"22px"},leftIcon:i($.IconMathFunction,{size:16})}})]})}const Fn=y.forwardRef(nh);function rh({label:e,value:t,onChange:n},r){const[a,o]=y.useState(Array.isArray(t)?[...t]:[]),l=y.useCallback(()=>{o(g=>[...g,""])},[o]),u=y.useCallback(g=>{o(m=>(m.splice(g,1),[...m]))},[o]),c=y.useMemo(()=>!x.isEqual(a,t),[a,t]),d=()=>{n(a.map(g=>g.toString()))},f=s.useMantineTheme(),h=y.useMemo(()=>Object.entries(f.colors).map(([g,m])=>m[6]),[f]);return p(P,{children:[p(s.Group,{position:"left",ref:r,children:[i(s.Text,{children:e}),i(s.ActionIcon,{mr:5,variant:"filled",color:"blue",disabled:!c,onClick:d,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Group,{children:[a.map((g,m)=>i(s.ColorInput,{value:g,onChange:C=>{o(w=>(w.splice(m,1,C),[...w]))},swatches:h,rightSection:i(s.ActionIcon,{onClick:()=>u(m),color:"red",children:i(T.Trash,{size:14})}),sx:{width:"45%"}})),i(s.ActionIcon,{onClick:l,color:"blue",variant:"outline",children:i(T.PlaylistAdd,{size:20})})]})]})}const ih=y.forwardRef(rh);function ah({value:e,onChange:t},n){const{colorManager:r}=y.useContext(ut),a=y.useMemo(()=>r.getStaticColors().map(u=>({label:u.name,group:u.category,value:u.value})),[r]),o=y.useMemo(()=>a.some(l=>l.value===e),[e,a]);return p(s.Group,{position:"apart",spacing:4,ref:n,children:[i(s.TextInput,{placeholder:"Set any color",value:o?"":e,onChange:l=>t(l.currentTarget.value),rightSection:i(s.ColorSwatch,{color:o?"transparent":e,radius:4}),variant:o?"filled":"default",sx:{maxWidth:"46%",flexGrow:1}}),i(s.Text,{sx:{flexGrow:0},children:"or"}),i(s.Select,{data:a,value:e,onChange:t,variant:o?"default":"filled",placeholder:"Pick a theme color",icon:i(s.ColorSwatch,{color:o?e:"transparent",radius:4}),sx:{maxWidth:"46%",flexGrow:1}})]})}const Ve=y.forwardRef(ah),Gn=[{label:"initial",value:0},{label:"500",value:25},{label:"700",value:50},{label:"semibold",value:75},{label:"bold",value:100}];function sh({label:e,value:t,onChange:n},r){var l;const[a,o]=y.useState(((l=Gn.find(u=>u.label===t))==null?void 0:l.value)??Gn[0].value);return y.useEffect(()=>{const u=Gn.find(c=>c.value===a);u&&n(u.label)},[a]),p(s.Stack,{spacing:0,mt:"sm",mb:"lg",children:[i(s.Text,{size:"sm",children:e}),i(s.Slider,{label:null,marks:Gn,value:a,onChange:o,step:25,placeholder:"Pick a font size",px:"1em",ref:r})]})}const Ys=y.forwardRef(sh);function oh({label:e,value:t,onChange:n,type:r},a){const[o,l]=y.useState(Array.isArray(t)?[...t]:[]),u=y.useCallback(()=>{l(h=>[...h,""])},[l]),c=y.useCallback(h=>{l(g=>(g.splice(h,1),[...g]))},[l]),d=y.useMemo(()=>!x.isEqual(o.map(String),t.map(String)),[o,t]),f=()=>{n(o.map(h=>r==="number"?Number(h):h.toString()))};return p(P,{children:[p(s.Group,{position:"left",ref:a,children:[i(s.Text,{children:e}),i(s.ActionIcon,{mr:5,variant:"filled",color:"blue",disabled:!d,onClick:f,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Group,{children:[o.map((h,g)=>i(s.TextInput,{type:r,value:h,onChange:m=>{const C=m.currentTarget.value;l(w=>(w.splice(g,1,C),[...w]))},rightSection:i(s.ActionIcon,{onClick:()=>c(g),color:"red",children:i(T.Trash,{size:14})}),sx:{width:"45%"}})),i(s.ActionIcon,{onClick:u,color:"blue",variant:"outline",children:i(T.PlaylistAdd,{size:20})})]})]})}const lh=y.forwardRef(oh),Qs=y.forwardRef(function({value:t,onChange:n},r){const a=t.color.type,o=(l,u)=>{const c=x.cloneDeep(t);x.set(c,l,u),n(c)};return p(P,{children:[i(s.Divider,{my:"xs",label:"Typography",labelPosition:"center"}),i(s.Stack,{children:i(s.TextInput,{label:"Font Size",placeholder:"10px, 1em, 1rem, 100%...",sx:{flex:1},value:t.size,onChange:l=>o("size",l.currentTarget.value)})}),i(s.Group,{position:"apart",grow:!0,sx:{"> *":{flexGrow:1,maxWidth:"100%"}},children:i(Ys,{label:"Font Weight",value:t.weight,onChange:l=>o("weight",l)})}),i(s.Divider,{my:"xs",label:"Style",labelPosition:"center"}),p(s.Stack,{children:[i(s.Select,{label:"Color Type",data:[{label:"Static Color",value:"static"},{label:"Continuous Color",value:"continuous"}],value:t.color.type,onChange:l=>o("color.type",l)}),a==="static"&&i(Ve,{value:t.color.staticColor,onChange:l=>o("color.staticColor",l)}),a==="continuous"&&p(P,{children:[i(lh,{label:"Value Range",value:t.color.valueRange,type:"number",onChange:l=>o("color.valueRange",l)}),i(ih,{label:"Color Range",value:t.color.colorRange,onChange:l=>o("color.colorRange",l)})]})]})]})});y.forwardRef(function({value:t,onChange:n,withStyle:r=!0},a){const o=(l,u)=>{const c=x.cloneDeep(t);x.set(c,l,u),n(c)};return p(s.Box,{px:"sm",py:"md",ref:a,children:[i(s.Text,{weight:"bold",pb:0,children:t.name}),i(s.Divider,{my:"xs",label:"Data",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(s.TextInput,{label:"Name",required:!0,value:t.name,onChange:l=>o("name",l.currentTarget.value)}),i(W,{label:"Data Field",required:!0,value:t.data_field,onChange:l=>o("data_field",l)})]}),i(Fn,{label:"Aggregation",value:t.aggregation,onChange:l=>o("aggregation",l)}),i(s.Divider,{my:"xs",label:"Format",labelPosition:"center"}),t.aggregation.type!=="custom"&&i(We,{value:t.formatter,onChange:l=>o("formatter",l)}),r&&i(Qs,{value:t,onChange:n})]})});class uh{constructor({valueRange:t,colorRange:n}){q(this,"mapper");this.mapper=_t.interpolate(t,n)}getColor(t){return this.mapper(t)}}function ch(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?`Array(${e.length})`:e.toString()}function ft({data_field:e,aggregation:t},n){return qn(n,e,t)}function Je({formatter:e,aggregation:t},n){if(!["string","number"].includes(typeof n))return ch(n);if(t.type==="custom")return n;try{return Z(n).format(e)}catch(r){return console.error(r),n}}function dh(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 uh(e).getColor(t)}catch(n){return console.error(n),"black"}return"black"}function Ks(e,t){const{color:n,data_field:r,aggregation:a,size:o,weight:l}=e,u=qn(t,r,a),c=Je(e,u);return i(s.Text,{sx:{fontSize:o,display:"inline"},color:dh(n,u),weight:l,children:c})}function ph(e,t){const n={};return e.forEach(r=>{const a=r.name;n[a]=Ks(r,t)}),n}function hh(e){return e.split(" ").map((t,n)=>p(y.Fragment,{children:[t," "]},n))}function fh(e){const n=e.replaceAll("<br />","<br/>").replaceAll(`
105
+ `),Nt={type:"none",config:{}};function Jp(e){const t=Array.from(e).sort((r,a)=>r-a),n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function Zp(e){const t=Number(e);return isFinite(t)?t:0}function Hp(e,t){switch(t.type){case"sum":return x.sum(e);case"mean":return x.mean(e);case"median":return Jp(e);case"max":return x.max(e)??0;case"min":return x.min(e)??0;case"quantile":return Ut.quantile(e,t.config.p)??0;case"CV":const n=wn.std(...e),r=wn.mean(...e);return r?n/r:"N/A";case"std":return wn.std(...e);default:return e}}function Rr(e,t){const n=e.map(Zp);return Hp(n,t)}function eh(e,t,n){try{const r=Ht(e,t);return new Function(`return ${n.config.func}`)()({queryData:r},Tt)}catch(r){return console.error(r),r.message}}function qn(e,t,n){try{return n.type==="custom"?eh(e,t,n):Rr(pt(e,t),n)}catch(r){return console.error(r),null}}const th=[{label:"None",value:"none"},{label:"Sum",value:"sum"},{label:"Mean",value:"mean"},{label:"Median",value:"median"},{label:"Max",value:"max"},{label:"Min",value:"min"},{label:"Coefficient of Variation",value:"CV"},{label:"Standard Variation",value:"std"},{label:"Quantile(99%, 95%, ...)",value:"quantile"},{label:"Custom",value:"custom"}];function nh({label:e,value:t,onChange:n,pt:r="sm"},a){y.useEffect(()=>{typeof t=="string"&&n({type:t,config:{}})},[t,n]);const o=c=>{n(c==="quantile"?{type:"quantile",config:{p:.99}}:c==="custom"?{type:"custom",config:{func:Rs}}:{type:c,config:{}})},l=c=>{n({type:"quantile",config:{p:c}})},u=c=>{n({type:"custom",config:{func:c}})};return p(s.Group,{grow:!0,noWrap:!0,pt:r,children:[i(s.Select,{ref:a,label:e,data:th,value:t.type,onChange:o}),t.type==="quantile"&&i(s.NumberInput,{label:"p",value:t.config.p,onChange:l,precision:2,min:.05,step:.05,max:1}),t.type==="custom"&&i(Xp,{label:"",triggerLabel:"Edit Function",value:t.config.func,onChange:u,defaultValue:Rs,triggerButtonProps:{size:"xs",sx:{flexGrow:0,alignSelf:"center",marginTop:"22px"},leftIcon:i($.IconMathFunction,{size:16})}})]})}const Fn=y.forwardRef(nh);function rh({label:e,value:t,onChange:n},r){const[a,o]=y.useState(Array.isArray(t)?[...t]:[]),l=y.useCallback(()=>{o(g=>[...g,""])},[o]),u=y.useCallback(g=>{o(m=>(m.splice(g,1),[...m]))},[o]),c=y.useMemo(()=>!x.isEqual(a,t),[a,t]),d=()=>{n(a.map(g=>g.toString()))},f=s.useMantineTheme(),h=y.useMemo(()=>Object.entries(f.colors).map(([g,m])=>m[6]),[f]);return p(P,{children:[p(s.Group,{position:"left",ref:r,children:[i(s.Text,{children:e}),i(s.ActionIcon,{mr:5,variant:"filled",color:"blue",disabled:!c,onClick:d,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Group,{children:[a.map((g,m)=>i(s.ColorInput,{value:g,onChange:C=>{o(w=>(w.splice(m,1,C),[...w]))},swatches:h,rightSection:i(s.ActionIcon,{onClick:()=>u(m),color:"red",children:i(T.Trash,{size:14})}),sx:{width:"45%"}})),i(s.ActionIcon,{onClick:l,color:"blue",variant:"outline",children:i(T.PlaylistAdd,{size:20})})]})]})}const ih=y.forwardRef(rh);function ah({value:e,onChange:t},n){const{colorManager:r}=y.useContext(ut),a=y.useMemo(()=>r.getStaticColors().map(u=>({label:u.name,group:u.category,value:u.value})),[r]),o=y.useMemo(()=>a.some(l=>l.value===e),[e,a]);return p(s.Group,{position:"apart",spacing:4,ref:n,children:[i(s.TextInput,{placeholder:"Set any color",value:o?"":e,onChange:l=>t(l.currentTarget.value),rightSection:i(s.ColorSwatch,{color:o?"transparent":e,radius:4}),variant:o?"filled":"default",sx:{maxWidth:"46%",flexGrow:1}}),i(s.Text,{sx:{flexGrow:0},children:"or"}),i(s.Select,{data:a,value:e,onChange:t,variant:o?"default":"filled",placeholder:"Pick a theme color",icon:i(s.ColorSwatch,{color:o?e:"transparent",radius:4}),sx:{maxWidth:"46%",flexGrow:1}})]})}const Ve=y.forwardRef(ah),Gn=[{label:"initial",value:0},{label:"500",value:25},{label:"700",value:50},{label:"semibold",value:75},{label:"bold",value:100}];function sh({label:e,value:t,onChange:n},r){var l;const[a,o]=y.useState(((l=Gn.find(u=>u.label===t))==null?void 0:l.value)??Gn[0].value);return y.useEffect(()=>{const u=Gn.find(c=>c.value===a);u&&n(u.label)},[a]),p(s.Stack,{spacing:0,mt:"sm",mb:"lg",children:[i(s.Text,{size:"sm",children:e}),i(s.Slider,{label:null,marks:Gn,value:a,onChange:o,step:25,placeholder:"Pick a font size",px:"1em",ref:r})]})}const Ys=y.forwardRef(sh);function oh({label:e,value:t,onChange:n,type:r},a){const[o,l]=y.useState(Array.isArray(t)?[...t]:[]),u=y.useCallback(()=>{l(h=>[...h,""])},[l]),c=y.useCallback(h=>{l(g=>(g.splice(h,1),[...g]))},[l]),d=y.useMemo(()=>!x.isEqual(o.map(String),t.map(String)),[o,t]),f=()=>{n(o.map(h=>r==="number"?Number(h):h.toString()))};return p(P,{children:[p(s.Group,{position:"left",ref:a,children:[i(s.Text,{children:e}),i(s.ActionIcon,{mr:5,variant:"filled",color:"blue",disabled:!d,onClick:f,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Group,{children:[o.map((h,g)=>i(s.TextInput,{type:r,value:h,onChange:m=>{const C=m.currentTarget.value;l(w=>(w.splice(g,1,C),[...w]))},rightSection:i(s.ActionIcon,{onClick:()=>c(g),color:"red",children:i(T.Trash,{size:14})}),sx:{width:"45%"}})),i(s.ActionIcon,{onClick:u,color:"blue",variant:"outline",children:i(T.PlaylistAdd,{size:20})})]})]})}const lh=y.forwardRef(oh),Qs=y.forwardRef(function({value:t,onChange:n},r){const a=t.color.type,o=(u,c)=>{const d=x.cloneDeep(t);x.set(d,u,c),n(d)},l=u=>{if(u==="static"){n({...t,color:{type:"static",staticColor:"#25262B"}});return}n({...t,color:{type:"continuous",colorRange:[],valueRange:[]}})};return p(P,{children:[i(s.Divider,{my:"xs",label:"Typography",labelPosition:"center"}),i(s.Stack,{children:i(s.TextInput,{label:"Font Size",placeholder:"10px, 1em, 1rem, 100%...",sx:{flex:1},value:t.size,onChange:u=>o("size",u.currentTarget.value)})}),i(s.Group,{position:"apart",grow:!0,sx:{"> *":{flexGrow:1,maxWidth:"100%"}},children:i(Ys,{label:"Font Weight",value:t.weight,onChange:u=>o("weight",u)})}),i(s.Divider,{my:"xs",label:"Style",labelPosition:"center"}),p(s.Stack,{children:[i(s.Select,{label:"Color Type",data:[{label:"Static Color",value:"static"},{label:"Continuous Color",value:"continuous"}],value:t.color.type,onChange:l}),a==="static"&&i(Ve,{value:t.color.staticColor,onChange:u=>o("color.staticColor",u)}),a==="continuous"&&p(P,{children:[i(lh,{label:"Value Range",value:t.color.valueRange,type:"number",onChange:u=>o("color.valueRange",u)}),i(ih,{label:"Color Range",value:t.color.colorRange,onChange:u=>o("color.colorRange",u)})]})]})]})});y.forwardRef(function({value:t,onChange:n,withStyle:r=!0},a){const o=(l,u)=>{const c=x.cloneDeep(t);x.set(c,l,u),n(c)};return p(s.Box,{px:"sm",py:"md",ref:a,children:[i(s.Text,{weight:"bold",pb:0,children:t.name}),i(s.Divider,{my:"xs",label:"Data",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(s.TextInput,{label:"Name",required:!0,value:t.name,onChange:l=>o("name",l.currentTarget.value)}),i(W,{label:"Data Field",required:!0,value:t.data_field,onChange:l=>o("data_field",l)})]}),i(Fn,{label:"Aggregation",value:t.aggregation,onChange:l=>o("aggregation",l)}),i(s.Divider,{my:"xs",label:"Format",labelPosition:"center"}),t.aggregation.type!=="custom"&&i(We,{value:t.formatter,onChange:l=>o("formatter",l)}),r&&i(Qs,{value:t,onChange:n})]})});class uh{constructor({valueRange:t,colorRange:n}){q(this,"mapper");this.mapper=_t.interpolate(t,n)}getColor(t){return this.mapper(t)}}function ch(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?`Array(${e.length})`:e.toString()}function ft({data_field:e,aggregation:t},n){return qn(n,e,t)}function Je({formatter:e,aggregation:t},n){if(!["string","number"].includes(typeof n))return ch(n);if(t.type==="custom")return n;try{return Z(n).format(e)}catch(r){return console.error(r),n}}function dh(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 uh(e).getColor(t)}catch(n){return console.error(n),"black"}return"black"}function Ks(e,t){const{color:n,data_field:r,aggregation:a,size:o,weight:l}=e,u=qn(t,r,a),c=Je(e,u);return i(s.Text,{sx:{fontSize:o,display:"inline"},color:dh(n,u),weight:l,children:c})}function ph(e,t){const n={};return e.forEach(r=>{const a=r.name;n[a]=Ks(r,t)}),n}function hh(e){return e.split(" ").map((t,n)=>p(y.Fragment,{children:[t," "]},n))}function fh(e){const n=e.replaceAll("<br />","<br/>").replaceAll(`
106
106
  `,"<br/>").split("<br/>");return n.map((a,o)=>{const l=[hh(a)];return o!==n.length-1&&l.push(i("br",{},`br-${o}`)),l}).flat().filter(a=>a!==void 0)}function Yr(e){return fh(e)}function un(e,t,n){const r=ph(t,n),a=/^\{(.+)\}(.*)$/;return e.split("$").map((o,l)=>{const u=a.exec(o);if(!u)return Yr(o);const c=r[u[1]];if(!c)return Yr(o);const d=u[2]??"";return p(y.Fragment,{children:[c,Yr(d)]},`${o}-${l}`)})}function gh(e,t){const n={};return e.forEach(r=>{const{name:a,data_field:o,aggregation:l}=r,u=qn(t,o,l);n[a]=Je(r,u)}),n}function Wn(e,t,n){const r=gh(t,n),a=/^\{(.+)\}(.*)$/;return e.split("$").map(o=>{const l=a.exec(o);if(!l)return o;const u=r[l[1]];if(!u)return o;const c=l[2]??"";return`${u}${c}`}).join("")}function mh(e,t,n){const r=t.reduce((a,o)=>{const l=ft(o,n);return a[o.name]=Je(o,l),a},{});return e.map(a=>({name:"refs",type:"scatter",data:[],markLine:{data:[{name:a.name,yAxis:Number(r[a.variable_key])}],silent:!0,symbol:["none","none"],label:{formatter:function(){return Wn(a.template,t,n)},position:"insideEndTop"}}}))}function yh(e){const t={top:30,left:20,right:15,bottom:25,containLabel:!0};return e.legend.orient==="vertical"&&(t.right=80),t}function bh({config:e,data:t,variables:n}){const{x_axis:r,y_axis:a,reference_lines:o}=e,l=hd(e,t),u=rt(r.axisLabel.overflow.on_axis),c=gd(e);return{grid:yh(e),dataset:l,legend:fd({config:e}),tooltip:wd({config:e}),xAxis:[{type:"category",name:r.name,nameGap:25,nameLocation:"center",nameTextStyle:{fontWeight:"bold",align:"center"},axisTick:{show:!0,alignWithLabel:!0},axisLabel:{...r.axisLabel,...u,formatter:Pt(r.axisLabel.formatter)}}],yAxis:[{name:a.name,minInterval:1,nameTextStyle:{fontWeight:"bold"},axisLine:{show:!0},axisLabel:{formatter:function(d){return Z(d).format(a.label_formatter)}}}],series:[...c,...mh(o,n,t)]}}ie.use([F.DataZoomComponent,pe.BoxplotChart,F.MarkLineComponent,F.GridComponent,F.LegendComponent,F.TooltipComponent,Pe.CanvasRenderer]);function vh({context:e,instance:t}){const{value:n}=j(e.instanceData,"config"),{variables:r}=e,a=e.data,{width:o,height:l}=e.viewport,u=x.defaults({},n,kr),c=Ue({vizManager:e.vizManager,instance:t}),d=Ke(c.triggerManager,ls.id),f=Dt(a,u.x_axis.data_key),h=y.useCallback(C=>{const w=x.get(f,C.name,{error:"rowData is not found"});d.forEach(_=>{c.runInteraction(_.id,{...C,rowData:w})})},[f,d,c]),g=y.useMemo(()=>({click:h}),[h]),m=y.useMemo(()=>bh({config:u,data:a,variables:r}),[u,a,r]);return!n||!o||!l?null:i(s.Box,{sx:{width:o,height:l,overflow:"hidden"},children:i(Be,{echarts:ie,option:m,style:{width:o,height:l},onEvents:g,notMerge:!0,theme:"merico-light"})})}function xh({control:e,index:t,remove:n,variableOptions:r}){return p(s.Stack,{my:0,p:"md",pr:40,sx:{border:"1px solid #eee",position:"relative"},children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`reference_lines.${t}.name`,control:e,render:({field:a})=>i(s.TextInput,{label:"Name",placeholder:"Average Reference Line",required:!0,sx:{flex:1},...a})}),i(v.Controller,{name:`reference_lines.${t}.variable_key`,control:e,render:({field:a})=>i(s.Select,{label:"Value",required:!0,data:r,sx:{flex:1},...a})})]}),i(v.Controller,{name:`reference_lines.${t}.template`,control:e,render:({field:a})=>i(s.TextInput,{label:"Content Template",placeholder:"Average: ${avg}",required:!0,sx:{flex:1},...a})}),i(s.ActionIcon,{color:"red",variant:"subtle",onClick:()=>n(t),sx:{position:"absolute",top:15,right:5},children:i(T.Trash,{size:16})})]},t)}function wh({control:e,watch:t,variables:n}){const{fields:r,append:a,remove:o}=v.useFieldArray({control:e,name:"reference_lines"}),l=t("reference_lines"),u=r.map((f,h)=>({...f,...l[h]})),c=()=>a({name:"",template:"",variable_key:""}),d=y.useMemo(()=>n.map(f=>({label:f.name,value:f.name})),[n]);return p(s.Stack,{children:[u.map((f,h)=>i(xh,{control:e,index:h,remove:o,variableOptions:d},f.id)),i(s.Group,{position:"center",mt:"xs",children:i(s.Button,{onClick:c,children:"Add a Reference Line"})})]})}const Ch=({disabled:e,value:t,onChange:n})=>{const r=a=>{a&&n(a)};return p(s.Box,{sx:{position:"relative"},children:[e&&i(s.Overlay,{opacity:.6,color:"#fff",zIndex:5,blur:2}),i(Ae,{height:"500px",defaultLanguage:"javascript",value:t,onChange:r,theme:"vs-dark",options:{minimap:{enabled:!1},readOnly:e}})]})},jn=y.forwardRef(({value:e,onChange:t},n)=>{const[r,{setTrue:a,setFalse:o}]=U.useBoolean(),[l,u]=y.useState(e);y.useEffect(()=>{u(e)},[e]);const c=m=>{u({...l,enabled:m})},d=()=>{o();const{enabled:m,func_content:C}=l,w={enabled:m,func_content:C};u(w),t(w)},f=()=>{o(),u(e)},h=m=>{u(C=>({...C,func_content:m}))},g=()=>{h(Qe.func_content)};return p(P,{children:[i(s.Button,{variant:"filled",mt:24,onClick:a,sx:{flexGrow:0},children:"Customize Label"}),i(s.Modal,{size:800,title:"Customize label content",opened:r,onClose:o,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:r&&p(s.Stack,{children:[i(s.Checkbox,{mt:10,label:"Enabled",checked:l.enabled,onChange:m=>c(m.currentTarget.checked)}),i(Ch,{value:l.func_content,onChange:h,disabled:!l.enabled}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:g,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:f,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:d,children:"OK"})]})]})]})})]})}),Sh=({control:e,watch:t})=>(t(["x_axis"]),p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"X Axis Name",sx:{flex:1},...n})}),i(v.Controller,{name:"x_axis.data_key",control:e,render:({field:n})=>i(W,{label:"X Axis Data Field",required:!0,sx:{flex:1},...n})})]}),i(s.Divider,{mb:-15,label:"Tick Label",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.axisLabel.rotate",control:e,render:({field:n})=>i(s.NumberInput,{label:"Rotate",hideControls:!0,min:-90,max:90,rightSection:i(s.Text,{color:"dimmed",children:"degree"}),sx:{width:"48%"},styles:{rightSection:{width:"4em",justifyContent:"flex-end",paddingRight:"6px"}},...n})}),i(v.Controller,{name:"x_axis.axisLabel.formatter",control:e,render:({field:n})=>i(jn,{...n})})]}),i(v.Controller,{name:"x_axis.axisLabel.overflow",control:e,render:({field:n})=>i(at,{...n})})]})),_h=({control:e,watch:t})=>(t(["y_axis"]),p(P,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"y_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Y Axis Name",sx:{flex:1},...n})}),i(v.Controller,{name:"y_axis.data_key",control:e,render:({field:n})=>i(W,{label:"Y Axis Data Field",required:!0,sx:{flex:1},...n})})]}),p(s.Stack,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Label Format",labelPosition:"center"}),i(v.Controller,{name:"y_axis.label_formatter",control:e,render:({field:n})=>i(We,{...n})})]})]})),kh=({control:e,index:t,remove:n})=>p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`tooltip.metrics.${t}.name`,control:e,render:({field:r})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:`tooltip.metrics.${t}.data_key`,control:e,render:({field:r})=>i(W,{label:"Value Field",required:!0,sx:{flex:1},...r})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed"}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Metric"})]}),Th=({control:e,watch:t})=>{const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"tooltip.metrics"}),o=t("tooltip.metrics"),l=n.map((h,g)=>({...h,...o[g]})),u=()=>r({id:Date.now().toString(),data_key:"",name:""}),c=t("tooltip.metrics.0.id"),[d,f]=y.useState(()=>c??null);return y.useEffect(()=>{c&&f(h=>h!==null?h:c)},[c]),p(P,{children:[p(s.Group,{spacing:2,sx:{cursor:"default",userSelect:"none"},children:[i(T.InfoCircle,{size:14,color:"#888"}),i(s.Text,{size:14,color:"#888",children:"Set additional metrics to show in scatter's tooltip"})]}),p(s.Tabs,{value:d,onTabChange:h=>f(h),styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map((h,g)=>i(s.Tabs.Tab,{value:h.id,children:h.name?h.name:g},h.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((h,g)=>i(s.Tabs.Panel,{value:h.id,children:i(kh,{control:e,index:g,remove:a},h.id)},h.id))]})]})};function Dh({control:e,watch:t}){return i(s.Stack,{children:i(Th,{control:e,watch:t})})}const Mh=[{label:"Horizontal",value:"horizontal"},{label:"Vertical",value:"vertical"}],Ih=({control:e,watch:t})=>{const n=t("legend"),r=(a,o)=>{const l={...n,orient:a};a==="horizontal"?(l.top="0",l.left="auto",l.right="10",l.bottom="auto"):(l.top="10",l.left="auto",l.right="0",l.bottom="auto"),o(l)};return p(s.Stack,{children:[i(s.Group,{grow:!0,noWrap:!0,mt:20,children:i(v.Controller,{name:"legend.show",control:e,render:({field:a})=>i(s.Switch,{label:"Show Legend",sx:{flex:1},checked:a.value,onChange:o=>a.onChange(o.currentTarget.checked)})})}),i(s.Group,{children:i(v.Controller,{name:"legend",control:e,render:({field:a})=>i(s.Select,{label:"Orientation",data:Mh,sx:{flex:1},value:a.value.orient,onChange:o=>{r(o,a.onChange)},disabled:!n.show})})})]})};function Ah({context:e}){const{value:t,set:n}=j(e.instanceData,"config"),{variables:r}=e,a=y.useMemo(()=>x.defaults({},t,kr),[t]),{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});y.useEffect(()=>{d(a)},[a]),u(["x_axis","y_axis","reference_lines","color"]);const f=c(),h=y.useMemo(()=>!x.isEqual(f,t),[f,t]);return i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:l(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"X Axis",orientation:"vertical",styles:{tab:{paddingLeft:"6px",paddingRight:"6px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"X Axis",children:"X Axis"}),i(s.Tabs.Tab,{value:"Y Axis",children:"Y Axis"}),i(s.Tabs.Tab,{value:"Legend",children:"Legend"}),i(s.Tabs.Tab,{value:"Tooltip",children:"Tooltip"}),i(s.Tabs.Tab,{value:"Style",children:"Style"}),i(s.Tabs.Tab,{value:"Reference Lines",children:"Reference Lines"})]}),i(s.Tabs.Panel,{value:"X Axis",children:i(Sh,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Y Axis",children:i(_h,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Legend",children:i(Ih,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Tooltip",children:i(Dh,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Style",children:p(s.Stack,{spacing:4,children:[i(s.Text,{size:"sm",children:"Color"}),i(v.Controller,{name:"color",control:o,render:({field:g})=>i(Ve,{...g})})]})}),i(s.Tabs.Panel,{value:"Reference Lines",children:i(wh,{variables:r,control:o,watch:u})})]})]})})}function zh(e){return x.omit(e,"variables")}function Eh(e){const{label_formatter:t=ze,...n}=e.y_axis;return{...e,y_axis:{...n,label_formatter:t}}}function $h(e){const t={rotate:0,formatter:{...Qe}},{axisLabel:n=t,...r}=e.x_axis;return{...e,x_axis:{...r,axisLabel:n}}}function Lh(e){const t={x_axis:{axisLabel:{overflow:{x_axis:{width:80,overflow:"truncate",ellipsis:"..."},tooltip:{width:200,overflow:"break",ellipsis:"..."}}}}};return x.defaultsDeep(t,e)}function Oh(e){delete e.config;const{x_axis:t,tooltip:n}=e.x_axis.axisLabel.overflow,r={x_axis:{axisLabel:{overflow:{on_axis:t,in_tooltip:n}}}};return x.defaultsDeep(r,e)}function Ph(e){const t={tooltip:{metrics:[]}};return x.defaultsDeep(t,e)}function Bh(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=c=>c&&`${n}.${c}`,{x_axis:a,y_axis:o,tooltip:l,...u}=e;return{...u,x_axis:{...a,data_key:r(a.data_key)},y_axis:{...o,data_key:r(o.data_key)},tooltip:{...l,metrics:l.metrics.map(c=>({...c,data_key:r(c.data_key)}))}}}catch(n){throw console.error("[Migration failed]",n),n}}function Vh(e){const t={legend:{show:!0,top:"0",right:"10",left:"auto",bottom:"auto",orient:"horizontal",type:"scroll"}};return x.defaultsDeep(t,e)}class Nh extends me{constructor(){super(...arguments);q(this,"VERSION",9)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,(n,{panelModel:r})=>{const{config:a}=n;return(a.variables||[]).forEach(l=>{r.variables.find(u=>u.name===l.name)||r.addVariable(l)}),{...n,version:2,config:zh(a)}}),this.version(3,n=>{const{config:r}=n;return{...n,version:3,config:Eh(r)}}),this.version(4,n=>{const{config:r}=n;return{...n,version:4,config:$h(r)}}),this.version(5,n=>{const{config:r}=n;return{...n,version:5,config:Lh(r)}}),this.version(6,n=>{const{config:r}=n;return{...n,version:6,config:Oh(r)}}),this.version(7,n=>{const{config:r}=n;return{...n,version:7,config:Ph(r)}}),this.version(8,(n,r)=>{const{config:a}=n;return{...n,version:8,config:Bh(a,r)}}),this.version(9,n=>{const{config:r}=n;return{...n,version:9,config:Vh(r)}})}}const qh={displayName:"Boxplot Chart",displayGroup:"ECharts-based charts",migrator:new Nh,name:"boxplot",viewRender:vh,configRender:Ah,createConfig(){return{version:9,config:x.cloneDeep(kr)}},triggers:[ls]},Us={id:"builtin:button:click-button",displayName:"Click Button",nameRender:Gh,configRender:Fh,payload:[]};function Fh(e){return i(P,{})}function Gh(e){return i(s.Text,{children:"Click this button"})}const Qr={content:"Button",variant:"filled",color:"blue",size:"xs",compact:!1,horizontal_align:"left",vertical_align:"center"},Wh={left:"flex-start",center:"center",right:"flex-end"},jh={top:"flex-start",center:"center",bottom:"flex-end"},Rh=k.observer(({context:e,instance:t})=>{const n=Ue({vizManager:e.vizManager,instance:t}),r=Ke(n.triggerManager,Us.id),a=we(),{value:o}=j(e.instanceData,"config"),l=y.useMemo(()=>x.defaultsDeep({},o,Qr),[o]),{content:u,horizontal_align:c,vertical_align:d,...f}=l,{width:h,height:g}=e.viewport,m=a.payloadForSQL,C=()=>{r.forEach(w=>{n.runInteraction(w.id,{})})};return i(s.Center,{sx:{width:h,height:g,justifyContent:Wh[c],alignItems:jh[d]},children:i(s.Button,{...f,onClick:C,children:x.template(u)(m)})})}),Yh=({value:e,onChange:t,label:n})=>{const r=s.useMantineTheme(),a=y.useCallback(l=>()=>t(l),[t]),o=l=>e===l;return p(s.Stack,{spacing:2,children:[i(s.Text,{size:14,sx:{fontWeight:500},children:n}),i(s.Group,{position:"left",spacing:"xs",children:Object.keys(r.colors).map(l=>{const u=r.colors[l][6];return i(s.ColorSwatch,{color:u,onClick:a(l),radius:4,size:26,sx:{cursor:"pointer"},children:o(l)&&i(s.CheckIcon,{width:10,color:"white"})},l)})})]})},Qh=s.MANTINE_SIZES.map(e=>({label:e.toUpperCase(),value:e})),Kh=({label:e,value:t,onChange:n})=>i(s.Select,{data:Qh,label:e,value:t,onChange:n}),Uh=[{label:"Filled",value:"filled"},{label:"Outline",value:"outline"},{label:"Light",value:"light"},{label:"White",value:"white"},{label:"Default",value:"default"},{label:"Subtle",value:"subtle"},{label:"Gradient",value:"gradient",disabled:!0}],Xh=[{label:"Left",value:"left"},{label:"Center",value:"center"},{label:"Right",value:"right"}],Jh=[{label:"Top",value:"top"},{label:"Center",value:"center"},{label:"Bottom",value:"bottom"}];function Zh({context:e}){const{value:t,set:n}=j(e.instanceData,"config"),r=y.useMemo(()=>x.defaultsDeep({},t,Qr),[t]),a=r;y.useEffect(()=>{!x.isEqual(r,a)&&(console.log("config malformed, resetting to defaults",r,a),n(a))},[r,a]);const{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});y.useEffect(()=>{d(a)},[a]);const f=c(),h=y.useMemo(()=>!x.isEqual(f,r),[f,r]);return u(["content","variant","color","size","compact","horizontal_align","vertical_align"]),p("form",{onSubmit:l(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Stack,{children:[i(v.Controller,{control:o,name:"content",render:({field:g})=>i(s.TextInput,{label:"Content Template",description:"Filter values & context entries are supported",...g,required:!0})}),i(s.Divider,{mt:"xs",mb:0,label:"Styles",labelPosition:"center",variant:"dashed"}),p(s.SimpleGrid,{cols:2,children:[i(v.Controller,{control:o,name:"variant",render:({field:g})=>i(s.Select,{label:"Variant",data:Uh,...g})}),i(v.Controller,{control:o,name:"color",render:({field:g})=>i(Yh,{label:"Theme",...g})})]}),p(s.SimpleGrid,{cols:2,children:[i(v.Controller,{control:o,name:"size",render:({field:g})=>i(Kh,{label:"Size",...g})}),i(v.Controller,{control:o,name:"compact",render:({field:g})=>i(s.Checkbox,{label:"Compact",checked:g.value,onChange:m=>g.onChange(m.currentTarget.checked),mt:26})})]}),p(s.SimpleGrid,{cols:2,children:[i(v.Controller,{control:o,name:"horizontal_align",render:({field:g})=>i(s.Select,{label:"Horizontal Alignment",data:Xh,...g})}),i(v.Controller,{control:o,name:"vertical_align",render:({field:g})=>i(s.Select,{label:"Vertical Alignment",data:Jh,...g})})]})]})]})}class Hh extends me{constructor(){super(...arguments);q(this,"VERSION",2)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,n=>{const{horizontal_align:r="left",vertical_align:a="center",...o}=n.config;return{...n,version:2,config:{...o,horizontal_align:r,vertical_align:a}}})}}const ef={displayName:"Button",displayGroup:"Others",migrator:new Hh,name:"button",viewRender:Rh,configRender:Zh,createConfig(){return{version:2,config:x.cloneDeep(Qr)}},triggers:[Us]},Kr={id:"builtin:echarts:click-echart:series",displayName:"Click Chart Series",nameRender:nf,configRender:tf,payload:[{name:"seriesType",description:"'line' | 'scatter' | 'bar'",valueType:"string"},{name:"componentType",description:"'series'",valueType:"string"},{name:"name",description:"Name of the series clicked",valueType:"string"},{name:"color",description:"Color",valueType:"string"},{name:"value",description:"String-typed number, or series' actual value",valueType:"string"},{name:"rowData",description:"Data of the row",valueType:"object"}]};function tf(e){return i(P,{})}function nf(e){return i(s.Text,{children:"Click chart's series"})}const qt={x_axis_scroll:!1,y_axis_scroll:!1,x_axis_slider:!1,y_axis_slider:!1},Ur={regressions:[],series:[],stats:{templates:{bottom:"",top:""}},x_axis:{type:"category",axisLabel:{rotate:0,formatter:{...Qe},overflow:je}},x_axis_data_key:"",x_axis_name:"",y_axes:[{min:"",max:"",name:"Y Axis",show:!0,position:"left",nameAlignment:"center",label_formatter:ze}],reference_lines:[],reference_areas:[],dataZoom:qt};function Xr(e){const t=[];return e.x_axis_scroll&&t.push({type:"inside",xAxisIndex:[0],filterMode:"none",minSpan:1}),e.y_axis_scroll&&t.push({type:"inside",yAxisIndex:[0],filterMode:"none",minSpan:1}),e.x_axis_slider&&t.push({type:"slider",xAxisIndex:[0],filterMode:"none",bottom:"auto",top:0,height:15,moveHandleSize:0,showDataShadow:!1,minSpan:1}),t}function rf(e){const t=e.y_axes.some(a=>!!a.name);let n=15;t&&(n+=20),e.dataZoom.x_axis_slider&&(n+=20);let r=5;return e.x_axis_name&&(r+=15),e.series.some(a=>!a.hide_in_legend)&&(r+=20),{top:n,right:15,bottom:r,left:20,containLabel:!0}}function af(e){return e!=="line"?{}:{itemStyle:{opacity:0}}}function sf(e){switch(e){case"line":return;case"bar":return"roundRect";case"scatter":return"circle"}}function of(e){const t={show:!0,bottom:0,left:"center",type:"scroll"};return t.data=e.filter(n=>!n.hide_in_legend).map(({name:n,type:r})=>({name:n,icon:sf(r),...af(r)})),t}function Rn(e,t){switch(e.config.method){case"linear":return[...yt.regressionLinear()(t)];case"exponential":return[...yt.regressionExp()(t)];case"logarithmic":return[...yt.regressionLog()(t)];case"polynomial":return[...yt.regressionPoly().order(e.config.order)(t)];default:return[]}}function lf(e,t,n,r){const{transform:a,plot:o}=e,l={...o,name:t,data:Rn(a,r),showSymbol:!1,tooltip:{show:!1},smooth:!1,custom:{}};return n&&(l.custom={type:"regression-line",targetSeries:n}),l}function uf({regressions:e=[],x_axis_data_key:t},n){const r=[];if(Object.keys(n).length===0)return r;function a(o,l,u,c){const d=lf(o,l,u,c);r.push(d)}return e.forEach(o=>{const{name:l,group_by_key:u}=o;if(!u||u===t){const h=pt(n,o.y_axis_data_key).map((g,m)=>[m,Number(g)]);a(o,l,"",h);return}const{columnKey:c}=L(o.y_axis_data_key),d=x.groupBy(Ht(n,o.y_axis_data_key),u);Object.entries(d).forEach(([f,h])=>{const g=h.map((C,w)=>[w,Number(C[c])]);a(o,f,f,g)})}),r}function cf(e,t){return e.map(n=>({name:"",type:"line",hide_in_legend:!0,data:[],markArea:{itemStyle:{color:n.color},data:[[{yAxis:t[n.y_keys.upper]},{yAxis:t[n.y_keys.lower]}]],silent:!0}}))}function df(e,t,n,r){return e.map(a=>{const o=a.orientation==="horizontal",l=o?"yAxis":"xAxis",u=o?"insideEndTop":"end";return{name:a.name,type:"line",hide_in_legend:!a.show_in_legend,yAxisIndex:a.yAxisIndex,data:[],lineStyle:a.lineStyle,markLine:{data:[{name:a.name,[l]:n[a.variable_key]}],silent:!0,symbol:["none","none"],lineStyle:a.lineStyle,label:{formatter:function(){return a.template?Wn(a.template,t,r):""},position:u}}}})}function pf({type:e,...t},n,r,a){if(!e)return 10;if(e==="static"){const{size:d}=t;return d}const{func_content:o}=t,{queryID:l,columnKey:u}=L(r),c=x.keyBy(Ht(n,l),u);return(d,f)=>{let h;f.name?h=c[f.name]:h=n[f.dataIndex];try{return new Function(`return ${o}`)()({rowData:h,params:f,variables:a},{lodash:x,interpolate:_t.interpolate})}catch(g){return console.error(`[getEchartsSymbolSize] failed parsing custom function, error: ${g.message}`),10}}}function Jr(e,t,n){const r=pt(e,t),a=pt(e,n);return x.zip(r,a)}function hf(e,t,n,r){const a=Jr(t,n,r);return x.unionBy(a,e,0)}function ff({dataTemplate:e,data:t,x_axis_data_key:n,y_axis_data_key:r,valueTypedXAxis:a}){return a?hf(e,t,n,r):pt(t,r)}function gf({dataTemplate:e,data:t,aggregation_on_value:n,x_axis_data_key:r,y_axis_data_key:a,valueTypedXAxis:o}){if(!n||n.type==="none")return ff({dataTemplate:e,data:t,x_axis_data_key:r,y_axis_data_key:a,valueTypedXAxis:o});const l=Jr(t,r,a),u=x.groupBy(l,"0");return e.map(([d])=>{const h=u[d].map(m=>m[1]),g=Rr(h,n);return[d,g]})}function mf({group_by_key:e,data:t,x_axis_data_key:n,y_axis_data_key:r}){const{queryID:a,columnKey:o}=L(e),l=x.groupBy(t[a],o);return Object.entries(l).forEach(([u,c])=>{l[u]=Jr({[a]:c},n,r)}),l}function yf({x_axis_data_key:e,x_axis:t},{y_axis_data_key:n,yAxisIndex:r,label_position:a,name:o,group_by_key:l,aggregation_on_value:u,stack:c,color:d,display_name_on_line:f,symbolSize:h,hide_in_legend:g,...m},C,w,_,D){const I=t.type!=="category",B={label:{show:!!a,position:a,formatter:D[r??"default"]},name:o,xAxisId:"main-x-axis",yAxisIndex:r,stack:c,color:d,symbolSize:pf(h,w,e,_),hide_in_legend:g,labelLayout:{hideOverlap:!0},...m};if(f&&(B.endLabel={show:!0,formatter:o,offset:[-12,12],align:"right"}),!l||l===e)return B.data=gf({dataTemplate:C,data:w,aggregation_on_value:u,x_axis_data_key:e,y_axis_data_key:n,valueTypedXAxis:I}),B;const N=mf({group_by_key:l,data:w,x_axis_data_key:e,y_axis_data_key:n});return Object.entries(N).map(([O,z])=>{const A=x.cloneDeep(B);return A.name=O,A.color=void 0,A.data=z,A})}function bf(e,t,n,r,a,o){const l=t.map(c=>[c,0]);return e.series.map(c=>yf(e,c,l,n,o,r)).flat().concat(df(e.reference_lines,a,o,n)).concat(cf(e.reference_areas,o))}function vf(e,t){const n=e.find(o=>o.axisDim==="x"&&o.axisId==="main-x-axis");if(!n)return"";const{axisValue:r,axisIndex:a}=n;return Pt(t.x_axis.axisLabel.formatter)(r,a)}function xf(e,t,n){const r=t.reduce((a,{yAxisIndex:o,name:l})=>(a[l]=o,a),{});return{trigger:"axis",confine:!0,formatter:function(a){const o=Array.isArray(a)?a:[a];if(o.length===0)return"";const l=o.map(({seriesName:d,marker:f,value:h})=>{if(Array.isArray(h)&&h.length===2&&(h=h[1]),!d)return h;const g=r[d],m=n[g]??n.default;return`
107
107
  <tr>
108
108
  <td>${f}</td>
@@ -436,7 +436,7 @@ Check the top-level render call using <`+V+">.")}return E}}function ku(S,E){{if(
436
436
  </thead>
437
437
  <tbody>${g.join("")}</tbody>
438
438
  </table>
439
- `}}}function n1(e,t){const n=Gt(e.heat_block.min,t),r=Gt(e.heat_block.max,t);return{min:n,max:r,calculable:!0,orient:"horizontal",left:"center",top:0,itemWidth:15}}function r1(e,t,n){const r=L(e.x_axis.data_key),a=x.uniq(t[r.queryID].map(c=>c[r.columnKey])),{overflow:o,rotate:l}=e.x_axis.axisLabel,u=rt(o.on_axis);return{id:"main-x-axis",type:"category",data:a,name:e.x_axis.name??"",align:"center",axisTick:{show:!0,alignWithLabel:!0},axisLabel:{rotate:l,...u,formatter:n},splitArea:{show:!0},nameLocation:"center",nameGap:25,nameTextStyle:{fontWeight:"bold",align:"center"},z:2}}function i1(e,t,n){const r=L(e.x_axis.data_key),a=L(e.y_axis.data_key),{nameAlignment:o,data_key:l,...u}=e.y_axis,c=x.uniq(t[r.queryID].map(g=>g[a.columnKey])),{overflow:d,rotate:f}=e.y_axis.axisLabel,h=rt(d.on_axis);return{...u,type:"category",data:c,axisLabel:{rotate:f,...h,formatter:n},axisLine:{show:!0,color:"blue"},axisTick:{show:!0,alignWithLabel:!0},splitArea:{show:!0},nameTextStyle:{fontWeight:"bold",align:o},nameLocation:"end",nameGap:15,z:2}}const a1={tooltip:{confine:!0}};function s1(e,t,n){if(!e.x_axis.data_key||!e.y_axis.data_key||!e.heat_block.data_key)return{};const r=n.reduce((u,c)=>{const d=ft(c,t);return u[c.name]=Je(c,d),u},{}),a=UC(e),o=XC(e),l={xAxis:r1(e,t,a.x_axis),yAxis:i1(e,t,a.y_axis),series:ZC(e,t),tooltip:t1(e,t,a,o),grid:JC(e),visualMap:n1(e,r)};return x.defaultsDeep({},l,a1)}function o1(e){return i(P,{})}function l1(e){return i(s.Text,{children:"Click heat block"})}const Go={id:"builtin:echarts:click-heatmap:heat-block",displayName:"Click Heat Block",nameRender:l1,configRender:o1,payload:[{name:"seriesType",description:"'heatmap'",valueType:"string"},{name:"componentType",description:"'series'",valueType:"string"},{name:"name",description:"Name of the series clicked",valueType:"string"},{name:"color",description:"Color",valueType:"string"},{name:"value",description:"String-typed number, or series' actual value",valueType:"string"},{name:"rowData",description:"Data of the row",valueType:"object"}]};ie.use([F.DataZoomComponent,pe.HeatmapChart,F.GridComponent,F.LegendComponent,F.TooltipComponent,F.VisualMapComponent,Pe.CanvasRenderer]);function u1({conf:e,data:t,width:n,height:r,interactionManager:a,variables:o}){const l=y.useMemo(()=>{const h=L(e.x_axis.data_key),g=L(e.y_axis.data_key);return x.keyBy(t[h.queryID],m=>`${m[h.columnKey]}---${m[g.columnKey]}`)},[t,e.x_axis.data_key,e.y_axis.data_key]),u=Ke(a.triggerManager,Go.id),c=y.useCallback(h=>{const[g,m]=h.value,C=x.get(l,`${g}---${m}`,{error:"rowData is not found"});u.forEach(w=>{a.runInteraction(w.id,{...h,rowData:C})})},[l,u,a]),d=y.useMemo(()=>({click:c}),[c]),f=y.useMemo(()=>s1(e,t,o),[e,t]);return!n||!r?null:i(Be,{echarts:ie,option:f,style:{width:n,height:r},onEvents:d,notMerge:!0,theme:"merico-light"})}function c1({context:e,instance:t}){const n=Ue({vizManager:e.vizManager,instance:t}),{value:r}=j(e.instanceData,"config"),{variables:a}=e,o=y.useMemo(()=>x.defaults({},r,Ci),[r]),l=e.data,{width:u,height:c}=e.viewport;return i(u1,{variables:a,width:u,height:c,data:l,conf:o,interactionManager:n})}class d1 extends me{constructor(){super(...arguments);q(this,"VERSION",1)}configVersions(){this.version(1,n=>({version:1,config:n}))}}const p1={displayName:"Merico Heatmap",displayGroup:"Merico suite",migrator:new d1,name:"merico-heatmap",viewRender:c1,configRender:KC,createConfig:()=>({version:1,config:Ci}),triggers:[Go]},h1=[{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"})),f1=[tc,nc,ac,ic,rc,sc],Wo=()=>({id:"dashboard",version:ts,manifest:{viz:[hi,tx,S0,Eb,Sx,_y,Yw,xc,qh,Xg,Em,sw,dy,Dg,Wv,Ky,Sb,z0,_C,p1,VC,ef],color:[...h1,...f1]}}),dn=new cc,Ce={pluginManager:dt("pluginManager"),vizManager:dt("vizManager"),colorManager:dt("colorManager"),instanceScope:{panelModel:dt("panelModel"),vizInstance:dt("vizInstance"),interactionManager:dt("interactionManager"),migrator:dt("migrator"),operationManager:dt("operationManager"),triggerManager:dt("triggerManager")}},Si=()=>{try{dn.install(Wo())}catch{}const e=new Zu(dn),t=new uc(dn);return{pluginManager:dn,vizManager:e,colorManager:t}},ut=y.createContext(Si());try{dn.install(Wo())}catch{}const _i=y.createContext(null);function Hn(e){const t=y.useContext(_i),n=U.useCreation(()=>e.configure(t||new yr),[e.configure]),r=U.usePrevious(n);return r&&r!==n&&r.dispose(),i(_i.Provider,{value:n,children:e.children})}function jo(){return y.useContext(_i)}const g1={viewPanelInFullScreen:x.noop,inFullScreen:!1},er=y.createContext(g1),m1=({description:e,isDescriptionEmpty:t})=>t?null:i(s.Tooltip,{color:"white",label:i(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:i(s.Box,{sx:{height:"16px",alignSelf:"center"},children:i($.IconInfoCircle,{size:16,color:"gray"})})}),y1=k.observer(({label:e,config:{default_value:t,description:n,isDescriptionEmpty:r,...a},value:o,onChange:l})=>p(s.Box,{children:[i(s.Text,{children:" "}),i(s.Checkbox,{label:p(s.Group,{noWrap:!0,position:"apart",align:"middle",spacing:6,children:[i(s.Box,{sx:{flexGrow:1},children:e}),i(m1,{description:n,isDescriptionEmpty:r})]}),checked:o||!1,onChange:u=>l(u.currentTarget.checked),...a,pt:".4em",styles:{input:{borderColor:"#e9ecef"}}})]})),Ro=k.observer(({label:e,config:t,value:n=[null,null],onChange:r})=>{const{inputFormat:a,...o}=t,l=Array.isArray(n)?n.map(f=>f?Y(f).toDate():null):[null,null],u=f=>{r(f.map(h=>h&&Y(h).format(a)))},c=t.getMinDate(l[0]),d=t.getMaxDate(l[0]);return i(Lu.DatePickerInput,{type:"range",label:e,value:l,onChange:u,icon:i(T.Calendar,{size:16}),sx:{minWidth:"16em"},minDate:c,maxDate:d,valueFormat:a,styles:{input:{borderColor:"#e9ecef"}},...o})}),b1=s.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"},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"}}})),Yo=({errorMessage:e})=>e?i(s.Text,{color:"red",size:12,children:e}):i(s.Text,{color:"dimmed",size:12,children:"Not found"}),v1=({disabled:e,classNames:t,styles:n,unstyled:r,radius:a,style:o,label:l,value:u,onChange:c,options:d,errorMessage:f})=>{const{classes:h,cx:g}=b1({radius:a},{name:"MultiSelectWidget",classNames:t,styles:n,unstyled:r}),[m,C]=y.useState(!1),w=N=>{C(N)},_=m&&(u==null?void 0:u.length)>0,[D,I]=y.useState(""),B=y.useMemo(()=>{if(!D)return d;const N=D.toLowerCase(),O=z=>{var A;return((A=z.description)==null?void 0:A.toLowerCase().includes(N))||z.label.toLowerCase().includes(N)};return d.filter(O)},[D,d]);return p(s.Stack,{spacing:3,children:[p(s.Group,{position:"apart",children:[i(s.Text,{className:h.label,children:l}),_&&i(s.Tooltip,{label:`${u.length} selected`,children:i(s.Badge,{children:u.length})})]}),i(Ra,{disabled:e,allowClear:!0,className:g(h.root,"check-select"),dropdownClassName:g(h.dropdown,""),onDropdownVisibleChange:w,transitionName:"rc-select-dropdown-slide-up",choiceTransitionName:"rc-select-selection__choice-zoom",style:o,clearIcon:()=>i(s.CloseButton,{}),value:u,onChange:c,onSelect:console.log,mode:"multiple",maxTagCount:0,notFoundContent:i(Yo,{errorMessage:f}),maxTagTextLength:10,maxTagPlaceholder:N=>`${N.length} selected`,searchValue:D,onSearch:I,filterOption:!1,children:B.map(N=>p(Ra.Option,{title:N.label,children:[i(s.Text,{size:"sm","data-role":"label",children:N.label}),N.description&&i(s.Text,{size:"xs",color:"dimmed","data-role":"description",children:N.description})]},N.value))})]})},x1=k.observer(({label:e,config:t,value:n,onChange:r})=>{const a=we(),o=!!t.options_query_id,{state:l,error:u}=a.getDataStuffByID(t.options_query_id),c=l==="loading",d=t.min_width?t.min_width:"200px",f=o?c:!1,h=g=>r(g,!1);return i(v1,{label:e,options:t.options,style:{minWidth:"160px",width:d,maxWidth:f?d:"unset",borderColor:"#e9ecef"},disabled:f,value:n,onChange:h,errorMessage:u})}),w1=y.forwardRef(({label:e,description:t,...n},r)=>i("div",{ref:r,...n,children:i(s.Group,{noWrap:!0,children:p("div",{children:[i(s.Text,{size:"sm","data-role":"label",children:e}),i(s.Text,{size:"xs",color:"dimmed","data-role":"description",children:t})]})})})),C1=k.observer(({label:e,config:t,value:n,onChange:r})=>{const a=we(),o=!!t.options_query_id,{state:l,error:u}=a.getDataStuffByID(t.options_query_id),c=l==="loading";return i(s.Select,{label:e,data:t.options,disabled:o?c:!1,value:n,onChange:r,error:!!u,placeholder:u,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:w1})});function S1({label:e,config:t,value:n,onChange:r}){return i(s.TextInput,{label:e,value:n||"",onChange:a=>r(a.currentTarget.value),...t,styles:{input:{borderColor:"#e9ecef"}}})}const _1=({rotate:e,onClick:t})=>i("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:i("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"})}),k1=({expanded:e,isLeaf:t,value:n,onClick:r,...a})=>(n==="0-0-value"&&console.log(a),t?i("span",{style:{width:"14px",display:"inline-block"}}):i(_1,{rotate:e?"0":"-90",onClick:r,...a})),T1=({onClick:e})=>p("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:[i("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),i("rect",{className:"border",x:"4",y:"4",width:"16",height:"16",rx:"2"}),i("rect",{className:"checkmark-indeterminate",x:"8",y:"8",width:"8",height:"8",rx:"2",stroke:"none"}),i("path",{className:"checkmark-checked",d:"M9 12l2 2l4 -4"})]}),D1=({onClick:e,...t})=>i(T1,{onClick:e,...t}),M1=s.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"},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"}}}})),I1=({disabled:e,classNames:t,styles:n,unstyled:r,radius:a,style:o,label:l,value:u,onChange:c,treeData:d,errorMessage:f})=>{const{classes:h,cx:g}=M1({radius:a},{name:"FilterTreeSelectWidget",classNames:t,styles:n,unstyled:r}),[m,C]=y.useState(!1),w=D=>{C(D)},_=m&&(u==null?void 0:u.length)>0;return p(s.Stack,{spacing:3,children:[p(s.Group,{position:"apart",children:[i(s.Text,{className:h.label,children:l}),_&&i(s.Tooltip,{label:`${u.length} selected`,children:i(s.Badge,{children:u.length})})]}),i(Ya,{disabled:e,allowClear:!0,className:g(h.root,"check-select"),dropdownClassName:g(h.dropdown,""),onDropdownVisibleChange:w,transitionName:"rc-tree-select-dropdown-slide-up",choiceTransitionName:"rc-tree-select-selection__choice-zoom",style:o,treeLine:!0,clearIcon:()=>i(s.CloseButton,{}),switcherIcon:k1,treeIcon:D1,maxTagTextLength:10,value:u,treeData:d,notFoundContent:i(Yo,{errorMessage:f}),treeNodeFilterProp:"filterBasis",treeCheckable:!0,showCheckedStrategy:Ya.SHOW_PARENT,onChange:c,onSelect:console.log,maxTagCount:0,maxTagPlaceholder:D=>`${D.length} selected`})]})},A1=k.observer(({label:e,config:t,value:n,onChange:r})=>{const{treeData:a,treeDataLoading:o,errorMessage:l}=t,u=t.min_width?t.min_width:"200px",d=!!t.options_query_id?o:!1;return i(I1,{disabled:d,style:{minWidth:"160px",width:u,maxWidth:d?u:"unset",borderColor:"#e9ecef"},value:n,onChange:f=>r(f,!1),treeData:a,errorMessage:l,label:e})}),z1=k.observer(({filter:{type:e,config:t,key:n,...r},formFieldProps:a})=>{switch(e){case"select":return i(C1,{...r,...a,config:t});case"multi-select":return i(x1,{...r,...a,config:t});case"tree-select":return i(A1,{...r,...a,config:t});case"text-input":return i(S1,{...r,...a,config:t});case"date-range":return i(Ro,{...r,...a,config:t});case"checkbox":return i(y1,{...r,...a,config:t});default:return null}}),Qo=k.observer(y.forwardRef(({filter:e,...t},n)=>i("div",{className:"filter-root",ref:n,children:i(Fe,{children:i(z1,{filter:e,formFieldProps:t})})})));function E1(e){const t=le();y.useEffect(()=>{var n,r;(r=(n=t.filters).updatePreviewValues)==null||r.call(n,e)},[e])}const Ko=k.observer(function({view:t}){const n=we(),{control:r,handleSubmit:a,reset:o}=v.useForm({defaultValues:n.filters.values,reValidateMode:"onBlur"}),l=v.useWatch({control:r});y.useEffect(()=>{o(n.filters.values)},[n.filters.values,o]),E1(l);const u=n.filters.visibleInView(t.id),c=y.useMemo(()=>u.every(g=>g.should_auto_submit),[u]),d=y.useMemo(()=>u.filter(g=>x.get(g,"config.required",!1)),[u]),f=y.useMemo(()=>d.length===0?!1:d.some(g=>!g.requiredAndPass(l[g.key])),[l,d]);if(u.length===0)return null;const h=(g,m)=>(C,w)=>{m(C),(g.should_auto_submit||w)&&n.filters.setValueByKey(g.key,C)};return i("form",{onSubmit:a(n.filters.setValues),children:p(s.Group,{className:"dashboard-filters",position:"apart",noWrap:!0,sx:c?{}:{border:"1px solid #e9ecef",borderRadius:"4px",padding:"16px"},children:[i(s.Group,{align:"flex-start",children:u.map(g=>i(v.Controller,{name:g.key,control:r,render:({field:m})=>i(Qo,{filter:g,value:m.value,onChange:h(g,m.onChange)})},g.id))}),!c&&i(s.Group,{sx:{alignSelf:"flex-end"},children:i(s.Button,{color:"blue",size:"sm",type:"submit",disabled:f,children:"Search"})})]})})}),Uo=b.types.model("MockContextMeta",{current:b.types.optional(b.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 Xo(e){return{current:e}}const $1=b.types.model("PanelLayoutMeta",{x:b.types.number,y:b.types.maybeNull(b.types.number),w:b.types.number,h:b.types.number,moved:b.types.optional(b.types.boolean,!1),static:b.types.optional(b.types.boolean,!1)}).views(e=>({get json(){const{x:t,y:n,w:r,h:a,moved:o}=e;return{h:a,w:r,x:t,y:n===null?0:n,moved:o,static:e.static}}})).actions(e=>({set(t){const{x:n,y:r,w:a,h:o,moved:l}=t;e.x=n,e.y=r,e.w=a,e.h=o,e.moved=!!l,e.static=!!t.static}})),L1=b.types.model("PanelStyleBorderMeta",{enabled:b.types.boolean}).views(e=>({get json(){const{enabled:t}=e;return{enabled:t}}})).actions(e=>({setEnabled(t){e.enabled=t}})),O1=b.types.model("PanelStyleMeta",{border:L1}).views(e=>({get json(){const{border:t}=e;return{border:t.json}}})).actions(e=>({})),P1=b.types.model("VariableMeta",{name:b.types.string,size:b.types.string,weight:b.types.string,color:b.types.union(b.types.model({type:b.types.literal("static"),staticColor:b.types.string}),b.types.model({type:b.types.literal("continuous"),valueRange:b.types.array(b.types.number),colorRange:b.types.array(b.types.string)}),b.types.model({type:b.types.literal("piecewise")})),formatter:b.types.model({output:b.types.enumeration("Output",["number","percent"]),average:b.types.optional(b.types.boolean,!1),mantissa:b.types.number,trimMantissa:b.types.optional(b.types.boolean,!1)}),data_field:b.types.string,aggregation:b.types.union(b.types.model({type:b.types.enumeration(["none","sum","mean","median","min","max","CV","std"]),config:b.types.frozen()}),b.types.model({type:b.types.literal("quantile"),config:b.types.model({p:b.types.number})}),b.types.model({type:b.types.literal("custom"),config:b.types.model({func:b.types.string})}))}).views(e=>({get json(){const{name:t,size:n,weight:r,color:a,formatter:o,data_field:l,aggregation:u}=e;return x.cloneDeep({name:t,size:n,color:a,weight:r,formatter:o,data_field:l,aggregation:u})}})),B1=b.types.model("PanelVizMeta",{type:b.types.string,conf:b.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}})),V1=b.types.model({id:b.types.string,title:b.types.string,description:b.types.string,layout:$1,queryIDs:b.types.array(b.types.string),viz:B1,style:O1,variables:b.types.optional(b.types.array(P1),[])}).views(e=>({get json(){const{id:t,title:n,description:r,queryIDs:a}=e;return{id:t,viz:e.viz.json,style:e.style.json,title:n,layout:e.layout.json,queryIDs:[...a],variables:e.variables.map(o=>o.json),description:r}},get queryIDSet(){return new Set(e.queryIDs)}})).actions(e=>({setID(t){e.id=t},setTitle(t){e.title=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=b.cast(Array.from(n))},setQueryIDs(t){e.queryIDs=b.cast(t)},addVariable(t){e.variables.push(t)},removeVariable(t){e.variables.remove(t)}})),tr=e=>x.cloneDeepWith(e,(t,n)=>{if(n!==void 0&&t)return re.toJS(t)});var Se=(e=>(e.Postgresql="postgresql",e.MySQL="mysql",e.HTTP="http",e))(Se||{});const N1=b.types.model("QueryMeta",{id:b.types.string,name:b.types.string,type:b.types.enumeration("DataSourceType",[Se.Postgresql,Se.MySQL,Se.HTTP]),key:b.types.string,sql:b.types.string,pre_process:b.types.optional(b.types.string,""),post_process:b.types.optional(b.types.string,""),run_by:b.types.optional(b.types.array(b.types.string),[]),react_to:b.types.optional(b.types.array(b.types.string),[])}).views(e=>({get valid(){return e.id&&e.type&&e.key&&e.name?e.type===Se.HTTP?!!e.pre_process:!!e.sql:!1},get json(){const{id:t,name:n,type:r,key:a,sql:o,run_by:l,react_to:u,pre_process:c,post_process:d}=e;return tr({id:t,key:a,sql:o,name:n,type:r,run_by:l,react_to:u,pre_process:c,post_process:d})}})).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}})),q1=b.types.model("SQLSnippetMeta",{key:b.types.string,value:b.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 _e=(e=>(e.Select="select",e.MultiSelect="multi-select",e.TreeSelect="tree-select",e.TextInput="text-input",e.Checkbox="checkbox",e.DateRange="date-range",e))(_e||{});const Jo=b.types.model("FilterCheckboxConfigMeta",{_name:b.types.literal("checkbox"),description:b.types.optional(b.types.string,""),default_value:b.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}})),F1=()=>Jo.create({_name:"checkbox",description:"",default_value:!1});function Zo(e,t){return e.map(n=>{try{return n?Y.tz(n,"UTC").format(t):null}catch{return console.log(`[date-range] failed parsing ${n}`),null}})}const G1=b.types.model("FilterDateRangeConfigMeta",{_name:b.types.literal("date-range"),required:b.types.boolean,inputFormat:b.types.enumeration("DateRangeInputFormat",["YYYY","YYYYMM","YYYYMMDD","YYYY-MM","YYYY-MM-DD"]),default_value:b.types.optional(b.types.array(b.types.union(b.types.string,b.types.null)),[null,null]),clearable:b.types.boolean,max_days:b.types.optional(b.types.number,0),allowSingleDateInRange:b.types.optional(b.types.boolean,!1)}).views(e=>({get json(){const{_name:t,max_days:n,required:r,clearable:a,inputFormat:o,default_value:l,allowSingleDateInRange:u}=e;return{_name:t,max_days:n,required:r,clearable:a,inputFormat:o,default_value:Zo(l,o),allowSingleDateInRange:u}},truthy(t){return Array.isArray(t)&&t.length===2&&t.every(n=>!!n)}})).views(e=>({getMaxDate(t){const{max_days:n}=e;if(!(!n||!t))return Y(t).startOf("day").add(n,"days").toDate()},getMinDate(t){const{max_days:n}=e;if(!(!n||!t))return Y(t).startOf("day").subtract(n,"days").toDate()}})).actions(e=>({setFilterValue(t){try{const n=b.getParent(e);b.getRoot(e).filters.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)},setMaxDays(t){e.max_days=t,t>0&&(e.clearable=!0)},setAllowSingleDateInRange(t){e.allowSingleDateInRange=t}})),Ho=b.types.snapshotProcessor(G1,{preProcessor({default_value:e,...t}){return{...t,default_value:e.map(n=>n===null?null:Y.tz(n,"UTC").toISOString())}},postProcessor(e){const{default_value:t,...n}=e;return{...n,default_value:Zo(t,n.inputFormat)}}}),W1=()=>Ho.create({_name:"date-range",required:!1,inputFormat:"YYYY-MM-DD",clearable:!1,default_value:[null,null]}),j1=b.types.model({label:b.types.string,value:b.types.string}).actions(e=>({setLabel(t){e.label=t},setValue(t){e.value=t}})),ki=b.types.model("FilterConfigModel_BaseSelect",{static_options:b.types.optional(b.types.array(j1),[]),options_query_id:b.types.optional(b.types.string,""),default_selection_count:b.types.optional(b.types.number,0)}).views(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}=b.getRoot(e).content.getDataStuffByID(e.options_query_id);return n==="idle"?t:[]}})).actions(e=>({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??""}})),el=b.types.compose("FilterMultiSelectConfigMeta",b.types.model({_name:b.types.literal("multi-select"),min_width:b.types.optional(b.types.string,""),default_value:b.types.optional(b.types.array(b.types.string),[])}),ki).views(e=>({get json(){const{_name:t,default_value:n,min_width:r,static_options:a,options_query_id:o,default_selection_count:l}=e;return tr({_name:t,min_width:r,default_value:n,static_options:a,options_query_id:o,default_selection_count:l})},get default_selection(){return e.usingQuery?e.options.slice(0,e.default_selection_count).map(t=>t.value):e.default_value}})).actions(e=>({setDefaultValue(t){e.default_value=b.cast(t)},setMinWidth(t){e.min_width=t},setDefaultSelection(){const t=b.getRoot(e).content.filters,n=b.getParent(e).key;t.setValueByKey(n,e.default_selection)}})).actions(e=>({afterCreate(){b.addDisposer(e,re.reaction(()=>re.toJS(e.default_selection),e.setDefaultSelection,{fireImmediately:!0,delay:0}))}})),R1=()=>el.create({_name:"multi-select",default_value:[],static_options:[],options_query_id:"",default_selection_count:0}),tl=b.types.compose("FilterConfigModel_Select",b.types.model({_name:b.types.literal("select"),default_value:b.types.string,required:b.types.boolean,width:b.types.optional(b.types.string,"")}),ki).views(e=>({get json(){const{_name:t,default_value:n,required:r,width:a,static_options:o,options_query_id:l,default_selection_count:u}=e;return tr({_name:t,width:a,required:r,default_value:n,static_options:o,options_query_id:l,default_selection_count:u})},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.default_value}})).actions(e=>({setRequired(t){e.required=t},setDefaultValue(t){e.default_value=t},setWidth(t){e.width=t},setDefaultSelection(){const t=b.getRoot(e).content.filters,n=b.getParent(e).key;t.setValueByKey(n,e.default_selection)}})).actions(e=>({afterCreate(){b.addDisposer(e,re.reaction(()=>re.toJS(e.default_selection),e.setDefaultSelection,{fireImmediately:!0,delay:0}))}})),Y1=()=>tl.create({_name:"select",required:!1,default_value:"",static_options:[],options_query_id:"",default_selection_count:0}),nl=b.types.model("FilterTextInputConfigMeta",{_name:b.types.literal("text-input"),required:b.types.boolean,default_value:b.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}})),rl=()=>nl.create({_name:"text-input",required:!1,default_value:""});function Q1(e){return Ou.arrayToTree(e,{id:"value",parentId:"parent_value",childrenField:"children",dataField:null})}function K1(e){return e.map(t=>{const{label:n,description:r,...a}=t,o={...a,filterBasis:`${n}___${r??""}`,description:r,label:n};return r&&(o.label=y.createElement("div",{},[y.createElement(s.Text,{key:0,title:t.label},t.label),y.createElement(s.Text,{key:1,className:"rc-tree-select-tree-title-desc",color:"dimmed",title:t.description},t.description)])),o})}const il=b.types.compose("FilterTreeSelectConfigMeta",b.types.model({_name:b.types.literal("tree-select"),min_width:b.types.optional(b.types.string,""),default_value:b.types.optional(b.types.array(b.types.string),[])}),ki).views(e=>({get json(){const{_name:t,default_value:n,min_width:r,static_options:a,options_query_id:o,default_selection_count:l}=e;return{_name:t,min_width:r,default_value:n,static_options:a,options_query_id:o,default_selection_count:l}},get treeData(){const{data:t}=b.getRoot(e).content.getDataStuffByID(e.options_query_id),n=K1(t);return Q1(n)},get errorMessage(){const{error:t}=b.getRoot(e).content.getDataStuffByID(e.options_query_id);return t},get treeDataLoading(){const{state:t}=b.getRoot(e).content.getDataStuffByID(e.options_query_id);return t==="loading"},get defaultSelection(){const{default_selection_count:t}=e;return t?this.treeData.slice(0,t).map(r=>r.value):[]}})).actions(e=>({setDefaultValue(t){e.default_value=b.cast(t)},setMinWidth(t){e.min_width=t},applyDefaultSelection(){const t=b.getParent(e,1).key;b.getRoot(e).content.filters.setValueByKey(t,e.defaultSelection)},afterCreate(){b.addDisposer(e,re.reaction(()=>JSON.stringify(e.defaultSelection),this.applyDefaultSelection,{fireImmediately:!0,delay:0}))}})),U1=()=>il.create({_name:"tree-select",default_value:[],static_options:[],options_query_id:"",default_selection_count:0}),al=b.types.model("FilterMeta",{id:b.types.identifier,key:b.types.string,label:b.types.string,order:b.types.number,visibleInViewsIDs:b.types.array(b.types.string),auto_submit:b.types.optional(b.types.boolean,!1),type:b.types.enumeration("DashboardFilterType",[_e.Select,_e.MultiSelect,_e.TreeSelect,_e.TextInput,_e.Checkbox,_e.DateRange]),config:b.types.union(tl,el,il,nl,Jo,Ho)}).views(e=>({get plainDefaultValue(){const t=e.config.default_value;return Array.isArray(t)?[...t]:t},get usingDefaultValue(){return e.type!==_e.TreeSelect},get auto_submit_supported(){return[_e.Select,_e.Checkbox,_e.DateRange].includes(e.type)}})).views(e=>({get json(){const{id:t,key:n,label:r,order:a,visibleInViewsIDs:o,auto_submit:l,type:u,config:c}=e;return{id:t,key:n,type:u,label:r,order:a,config:c.json,auto_submit:l,visibleInViewsIDs:re.toJS(o)}},get should_auto_submit(){return e.auto_submit_supported&&e.auto_submit},requiredAndPass(t){return x.get(e.config,"required",!1)?x.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 _e.Select:e.config=Y1();break;case _e.MultiSelect:e.config=R1();break;case _e.TreeSelect:e.config=U1();break;case _e.TextInput:e.config=rl();break;case _e.Checkbox:e.config=F1();break;case _e.DateRange:e.config=W1();break}e.type=t},setVisibleInViewsIDs(t){e.visibleInViewsIDs.length=0,e.visibleInViewsIDs.push(...t)},setAutoSubmit(t){e.auto_submit=e.auto_submit_supported&&t}}));var R=(e=>(e.Division="div",e.Modal="modal",e.Tabs="tabs",e))(R||{});const sl=b.types.model("ViewDivisionConfig",{_name:b.types.literal(R.Division)}).views(e=>({get json(){const{_name:t}=e;return{_name:t}}})),X1=()=>sl.create({_name:R.Division}),J1=b.types.model("CustomModalTitleModel",{enabled:b.types.optional(b.types.boolean,!1),func_content:b.types.optional(b.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=b.getParent(e,2),a=b.getRoot(e);if(!t)return r.name;try{const o={filters:a.content.filters.values,context:a.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}})),Ti={enabled:!1,func_content:["function text({ filters, context}) {"," // your code goes here",' return "text"',"}"].join(`
439
+ `}}}function n1(e,t){const n=Gt(e.heat_block.min,t),r=Gt(e.heat_block.max,t);return{min:n,max:r,calculable:!0,orient:"horizontal",left:"center",top:0,itemWidth:15}}function r1(e,t,n){const r=L(e.x_axis.data_key),a=x.uniq(t[r.queryID].map(c=>c[r.columnKey])),{overflow:o,rotate:l}=e.x_axis.axisLabel,u=rt(o.on_axis);return{id:"main-x-axis",type:"category",data:a,name:e.x_axis.name??"",align:"center",axisTick:{show:!0,alignWithLabel:!0},axisLabel:{rotate:l,...u,formatter:n},splitArea:{show:!0},nameLocation:"center",nameGap:25,nameTextStyle:{fontWeight:"bold",align:"center"},z:2}}function i1(e,t,n){const r=L(e.x_axis.data_key),a=L(e.y_axis.data_key),{nameAlignment:o,data_key:l,...u}=e.y_axis,c=x.uniq(t[r.queryID].map(g=>g[a.columnKey])),{overflow:d,rotate:f}=e.y_axis.axisLabel,h=rt(d.on_axis);return{...u,type:"category",data:c,axisLabel:{rotate:f,...h,formatter:n},axisLine:{show:!0,color:"blue"},axisTick:{show:!0,alignWithLabel:!0},splitArea:{show:!0},nameTextStyle:{fontWeight:"bold",align:o},nameLocation:"end",nameGap:15,z:2}}const a1={tooltip:{confine:!0}};function s1(e,t,n){if(!e.x_axis.data_key||!e.y_axis.data_key||!e.heat_block.data_key)return{};const r=n.reduce((u,c)=>{const d=ft(c,t);return u[c.name]=Je(c,d),u},{}),a=UC(e),o=XC(e),l={xAxis:r1(e,t,a.x_axis),yAxis:i1(e,t,a.y_axis),series:ZC(e,t),tooltip:t1(e,t,a,o),grid:JC(e),visualMap:n1(e,r)};return x.defaultsDeep({},l,a1)}function o1(e){return i(P,{})}function l1(e){return i(s.Text,{children:"Click heat block"})}const Go={id:"builtin:echarts:click-heatmap:heat-block",displayName:"Click Heat Block",nameRender:l1,configRender:o1,payload:[{name:"seriesType",description:"'heatmap'",valueType:"string"},{name:"componentType",description:"'series'",valueType:"string"},{name:"name",description:"Name of the series clicked",valueType:"string"},{name:"color",description:"Color",valueType:"string"},{name:"value",description:"String-typed number, or series' actual value",valueType:"string"},{name:"rowData",description:"Data of the row",valueType:"object"}]};ie.use([F.DataZoomComponent,pe.HeatmapChart,F.GridComponent,F.LegendComponent,F.TooltipComponent,F.VisualMapComponent,Pe.CanvasRenderer]);function u1({conf:e,data:t,width:n,height:r,interactionManager:a,variables:o}){const l=y.useMemo(()=>{const h=L(e.x_axis.data_key),g=L(e.y_axis.data_key);return x.keyBy(t[h.queryID],m=>`${m[h.columnKey]}---${m[g.columnKey]}`)},[t,e.x_axis.data_key,e.y_axis.data_key]),u=Ke(a.triggerManager,Go.id),c=y.useCallback(h=>{const[g,m]=h.value,C=x.get(l,`${g}---${m}`,{error:"rowData is not found"});u.forEach(w=>{a.runInteraction(w.id,{...h,rowData:C})})},[l,u,a]),d=y.useMemo(()=>({click:c}),[c]),f=y.useMemo(()=>s1(e,t,o),[e,t]);return!n||!r?null:i(Be,{echarts:ie,option:f,style:{width:n,height:r},onEvents:d,notMerge:!0,theme:"merico-light"})}function c1({context:e,instance:t}){const n=Ue({vizManager:e.vizManager,instance:t}),{value:r}=j(e.instanceData,"config"),{variables:a}=e,o=y.useMemo(()=>x.defaults({},r,Ci),[r]),l=e.data,{width:u,height:c}=e.viewport;return i(u1,{variables:a,width:u,height:c,data:l,conf:o,interactionManager:n})}class d1 extends me{constructor(){super(...arguments);q(this,"VERSION",1)}configVersions(){this.version(1,n=>({version:1,config:n}))}}const p1={displayName:"Merico Heatmap",displayGroup:"Merico suite",migrator:new d1,name:"merico-heatmap",viewRender:c1,configRender:KC,createConfig:()=>({version:1,config:Ci}),triggers:[Go]},h1=[{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"})),f1=[tc,nc,ac,ic,rc,sc],Wo=()=>({id:"dashboard",version:ts,manifest:{viz:[hi,tx,S0,Eb,Sx,_y,Yw,xc,qh,Xg,Em,sw,dy,Dg,Wv,Ky,Sb,z0,_C,p1,VC,ef],color:[...h1,...f1]}}),dn=new cc,Ce={pluginManager:dt("pluginManager"),vizManager:dt("vizManager"),colorManager:dt("colorManager"),instanceScope:{panelModel:dt("panelModel"),vizInstance:dt("vizInstance"),interactionManager:dt("interactionManager"),migrator:dt("migrator"),operationManager:dt("operationManager"),triggerManager:dt("triggerManager")}},Si=()=>{try{dn.install(Wo())}catch{}const e=new Zu(dn),t=new uc(dn);return{pluginManager:dn,vizManager:e,colorManager:t}},ut=y.createContext(Si());try{dn.install(Wo())}catch{}const _i=y.createContext(null);function Hn(e){const t=y.useContext(_i),n=U.useCreation(()=>e.configure(t||new yr),[e.configure]),r=U.usePrevious(n);return r&&r!==n&&r.dispose(),i(_i.Provider,{value:n,children:e.children})}function jo(){return y.useContext(_i)}const g1={viewPanelInFullScreen:x.noop,inFullScreen:!1},er=y.createContext(g1),m1=({description:e,isDescriptionEmpty:t})=>t?null:i(s.Tooltip,{color:"white",label:i(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:i(s.Box,{sx:{height:"16px",alignSelf:"center"},children:i($.IconInfoCircle,{size:16,color:"gray"})})}),y1=k.observer(({label:e,config:{default_value:t,description:n,isDescriptionEmpty:r,...a},value:o,onChange:l})=>p(s.Box,{children:[i(s.Text,{children:" "}),i(s.Checkbox,{label:p(s.Group,{noWrap:!0,position:"apart",align:"middle",spacing:6,children:[i(s.Box,{sx:{flexGrow:1},children:e}),i(m1,{description:n,isDescriptionEmpty:r})]}),checked:o||!1,onChange:u=>l(u.currentTarget.checked),...a,pt:".4em",styles:{input:{borderColor:"#e9ecef"}}})]})),Ro=k.observer(({label:e,config:t,value:n=[null,null],onChange:r})=>{const{inputFormat:a,...o}=t,l=Array.isArray(n)?n.map(f=>f?Y(f).toDate():null):[null,null],u=f=>{r(f.map(h=>h&&Y(h).format(a)))},c=t.getMinDate(l[0]),d=t.getMaxDate(l[0]);return i(Lu.DatePickerInput,{type:"range",label:e,value:l,onChange:u,icon:i(T.Calendar,{size:16}),sx:{minWidth:"16em"},minDate:c,maxDate:d,valueFormat:a,styles:{input:{borderColor:"#e9ecef"}},...o})}),b1=s.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"},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"}}})),Yo=({errorMessage:e})=>e?i(s.Text,{color:"red",size:12,children:e}):i(s.Text,{color:"dimmed",size:12,children:"Not found"}),v1=({disabled:e,classNames:t,styles:n,unstyled:r,radius:a,style:o,label:l,value:u,onChange:c,options:d,errorMessage:f})=>{const{classes:h,cx:g}=b1({radius:a},{name:"MultiSelectWidget",classNames:t,styles:n,unstyled:r}),[m,C]=y.useState(!1),w=N=>{C(N)},_=m&&(u==null?void 0:u.length)>0,[D,I]=y.useState(""),B=y.useMemo(()=>{if(!D)return d;const N=D.toLowerCase(),O=z=>{var A;return((A=z.description)==null?void 0:A.toLowerCase().includes(N))||z.label.toLowerCase().includes(N)};return d.filter(O)},[D,d]);return p(s.Stack,{spacing:3,children:[p(s.Group,{position:"apart",children:[i(s.Text,{className:h.label,children:l}),_&&i(s.Tooltip,{label:`${u.length} selected`,children:i(s.Badge,{children:u.length})})]}),i(Ra,{disabled:e,allowClear:!0,className:g(h.root,"check-select"),dropdownClassName:g(h.dropdown,""),onDropdownVisibleChange:w,transitionName:"rc-select-dropdown-slide-up",choiceTransitionName:"rc-select-selection__choice-zoom",style:o,clearIcon:()=>i(s.CloseButton,{}),value:u,onChange:c,onSelect:console.log,mode:"multiple",maxTagCount:0,notFoundContent:i(Yo,{errorMessage:f}),maxTagTextLength:10,maxTagPlaceholder:N=>`${N.length} selected`,searchValue:D,onSearch:I,filterOption:!1,children:B.map(N=>p(Ra.Option,{title:N.label,children:[i(s.Text,{size:"sm","data-role":"label",children:N.label}),N.description&&i(s.Text,{size:"xs",color:"dimmed","data-role":"description",children:N.description})]},N.value))})]})},x1=k.observer(({label:e,config:t,value:n,onChange:r})=>{const a=we(),o=!!t.options_query_id,{state:l,error:u}=a.getDataStuffByID(t.options_query_id),c=l==="loading",d=t.min_width?t.min_width:"200px",f=o?c:!1,h=g=>r(g,!1);return i(v1,{label:e,options:t.options,style:{minWidth:"160px",width:d,maxWidth:f?d:"unset",borderColor:"#e9ecef"},disabled:f,value:n,onChange:h,errorMessage:u})}),w1=y.forwardRef(({label:e,description:t,...n},r)=>i("div",{ref:r,...n,children:i(s.Group,{noWrap:!0,children:p("div",{children:[i(s.Text,{size:"sm","data-role":"label",children:e}),i(s.Text,{size:"xs",color:"dimmed","data-role":"description",children:t})]})})})),C1=k.observer(({label:e,config:t,value:n,onChange:r})=>{const a=we(),o=!!t.options_query_id,{state:l,error:u}=a.getDataStuffByID(t.options_query_id),c=l==="loading";return i(s.Select,{label:e,data:t.options,disabled:o?c:!1,value:n,onChange:r,error:!!u,placeholder:u,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:w1})});function S1({label:e,config:t,value:n,onChange:r}){return i(s.TextInput,{label:e,value:n||"",onChange:a=>r(a.currentTarget.value),...t,styles:{input:{borderColor:"#e9ecef"}}})}const _1=({rotate:e,onClick:t})=>i("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:i("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"})}),k1=({expanded:e,isLeaf:t,value:n,onClick:r,...a})=>(n==="0-0-value"&&console.log(a),t?i("span",{style:{width:"14px",display:"inline-block"}}):i(_1,{rotate:e?"0":"-90",onClick:r,...a})),T1=({onClick:e})=>p("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:[i("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),i("rect",{className:"border",x:"4",y:"4",width:"16",height:"16",rx:"2"}),i("rect",{className:"checkmark-indeterminate",x:"8",y:"8",width:"8",height:"8",rx:"2",stroke:"none"}),i("path",{className:"checkmark-checked",d:"M9 12l2 2l4 -4"})]}),D1=({onClick:e,...t})=>i(T1,{onClick:e,...t}),M1=s.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"},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"}}}})),I1=({disabled:e,classNames:t,styles:n,unstyled:r,radius:a,style:o,label:l,value:u,onChange:c,treeData:d,errorMessage:f})=>{const{classes:h,cx:g}=M1({radius:a},{name:"FilterTreeSelectWidget",classNames:t,styles:n,unstyled:r}),[m,C]=y.useState(!1),w=D=>{C(D)},_=m&&(u==null?void 0:u.length)>0;return p(s.Stack,{spacing:3,children:[p(s.Group,{position:"apart",children:[i(s.Text,{className:h.label,children:l}),_&&i(s.Tooltip,{label:`${u.length} selected`,children:i(s.Badge,{children:u.length})})]}),i(Ya,{disabled:e,allowClear:!0,className:g(h.root,"check-select"),dropdownClassName:g(h.dropdown,""),onDropdownVisibleChange:w,transitionName:"rc-tree-select-dropdown-slide-up",choiceTransitionName:"rc-tree-select-selection__choice-zoom",style:o,treeLine:!0,clearIcon:()=>i(s.CloseButton,{}),switcherIcon:k1,treeIcon:D1,maxTagTextLength:10,value:u,treeData:d,notFoundContent:i(Yo,{errorMessage:f}),treeNodeFilterProp:"filterBasis",treeCheckable:!0,showCheckedStrategy:Ya.SHOW_PARENT,onChange:c,onSelect:console.log,maxTagCount:0,maxTagPlaceholder:D=>`${D.length} selected`})]})},A1=k.observer(({label:e,config:t,value:n,onChange:r})=>{const{treeData:a,treeDataLoading:o,errorMessage:l}=t,u=t.min_width?t.min_width:"200px",d=!!t.options_query_id?o:!1;return i(I1,{disabled:d,style:{minWidth:"160px",width:u,maxWidth:d?u:"unset",borderColor:"#e9ecef"},value:n,onChange:f=>r(f,!1),treeData:a,errorMessage:l,label:e})}),z1=k.observer(({filter:{type:e,config:t,key:n,...r},formFieldProps:a})=>{switch(e){case"select":return i(C1,{...r,...a,config:t});case"multi-select":return i(x1,{...r,...a,config:t});case"tree-select":return i(A1,{...r,...a,config:t});case"text-input":return i(S1,{...r,...a,config:t});case"date-range":return i(Ro,{...r,...a,config:t});case"checkbox":return i(y1,{...r,...a,config:t});default:return null}}),Qo=k.observer(y.forwardRef(({filter:e,...t},n)=>i("div",{className:"filter-root",ref:n,children:i(Fe,{children:i(z1,{filter:e,formFieldProps:t})})})));function E1(e){const t=le();y.useEffect(()=>{var n,r;(r=(n=t.filters).updatePreviewValues)==null||r.call(n,e)},[e])}const Ko=k.observer(function({view:t}){const n=we(),{control:r,handleSubmit:a,reset:o}=v.useForm({defaultValues:n.filters.values,reValidateMode:"onBlur"}),l=v.useWatch({control:r});y.useEffect(()=>{o(n.filters.values)},[n.filters.values,o]),E1(l);const u=n.filters.visibleInView(t.id),c=y.useMemo(()=>u.every(g=>g.should_auto_submit),[u]),d=y.useMemo(()=>u.filter(g=>x.get(g,"config.required",!1)),[u]),f=y.useMemo(()=>d.length===0?!1:d.some(g=>!g.requiredAndPass(l[g.key])),[l,d]);if(u.length===0)return null;const h=(g,m)=>(C,w)=>{m(C),(g.should_auto_submit||w)&&n.filters.setValueByKey(g.key,C)};return i("form",{onSubmit:a(n.filters.setValues),children:p(s.Group,{className:"dashboard-filters",position:"apart",noWrap:!0,sx:c?{}:{border:"1px solid #e9ecef",borderRadius:"4px",padding:"16px"},children:[i(s.Group,{align:"flex-start",children:u.map(g=>i(v.Controller,{name:g.key,control:r,render:({field:m})=>i(Qo,{filter:g,value:m.value,onChange:h(g,m.onChange)})},g.id))}),!c&&i(s.Group,{sx:{alignSelf:"flex-end"},children:i(s.Button,{color:"blue",size:"sm",type:"submit",disabled:f,children:"Search"})})]})})}),Uo=b.types.model("MockContextMeta",{current:b.types.optional(b.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 Xo(e){return{current:e}}const $1=b.types.model("PanelLayoutMeta",{x:b.types.number,y:b.types.maybeNull(b.types.number),w:b.types.number,h:b.types.number,moved:b.types.optional(b.types.boolean,!1),static:b.types.optional(b.types.boolean,!1)}).views(e=>({get json(){const{x:t,y:n,w:r,h:a,moved:o}=e;return{h:a,w:r,x:t,y:n===null?0:n,moved:o,static:e.static}}})).actions(e=>({set(t){const{x:n,y:r,w:a,h:o,moved:l}=t;e.x=n,e.y=r,e.w=a,e.h=o,e.moved=!!l,e.static=!!t.static},setWidth(t){e.w=t},setHeight(t){e.h=t}})),L1=b.types.model("PanelStyleBorderMeta",{enabled:b.types.boolean}).views(e=>({get json(){const{enabled:t}=e;return{enabled:t}}})).actions(e=>({setEnabled(t){e.enabled=t}})),O1=b.types.model("PanelStyleMeta",{border:L1}).views(e=>({get json(){const{border:t}=e;return{border:t.json}}})).actions(e=>({})),P1=b.types.model("VariableMeta",{name:b.types.string,size:b.types.string,weight:b.types.string,color:b.types.union(b.types.model({type:b.types.literal("static"),staticColor:b.types.string}),b.types.model({type:b.types.literal("continuous"),valueRange:b.types.array(b.types.number),colorRange:b.types.array(b.types.string)}),b.types.model({type:b.types.literal("piecewise")})),formatter:b.types.model({output:b.types.enumeration("Output",["number","percent"]),average:b.types.optional(b.types.boolean,!1),mantissa:b.types.number,trimMantissa:b.types.optional(b.types.boolean,!1)}),data_field:b.types.string,aggregation:b.types.union(b.types.model({type:b.types.enumeration(["none","sum","mean","median","min","max","CV","std"]),config:b.types.frozen()}),b.types.model({type:b.types.literal("quantile"),config:b.types.model({p:b.types.number})}),b.types.model({type:b.types.literal("custom"),config:b.types.model({func:b.types.string})}))}).views(e=>({get json(){const{name:t,size:n,weight:r,color:a,formatter:o,data_field:l,aggregation:u}=e;return x.cloneDeep({name:t,size:n,color:a,weight:r,formatter:o,data_field:l,aggregation:u})}})),B1=b.types.model("PanelVizMeta",{type:b.types.string,conf:b.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}})),V1=b.types.model({id:b.types.string,title:b.types.string,description:b.types.string,layout:$1,queryIDs:b.types.array(b.types.string),viz:B1,style:O1,variables:b.types.optional(b.types.array(P1),[])}).views(e=>({get json(){const{id:t,title:n,description:r,queryIDs:a}=e;return{id:t,viz:e.viz.json,style:e.style.json,title:n,layout:e.layout.json,queryIDs:[...a],variables:e.variables.map(o=>o.json),description:r}},get queryIDSet(){return new Set(e.queryIDs)}})).actions(e=>({setID(t){e.id=t},setTitle(t){e.title=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=b.cast(Array.from(n))},setQueryIDs(t){e.queryIDs=b.cast(t)},addVariable(t){e.variables.push(t)},removeVariable(t){e.variables.remove(t)}})),tr=e=>x.cloneDeepWith(e,(t,n)=>{if(n!==void 0&&t)return re.toJS(t)});var Se=(e=>(e.Postgresql="postgresql",e.MySQL="mysql",e.HTTP="http",e))(Se||{});const N1=b.types.model("QueryMeta",{id:b.types.string,name:b.types.string,type:b.types.enumeration("DataSourceType",[Se.Postgresql,Se.MySQL,Se.HTTP]),key:b.types.string,sql:b.types.string,pre_process:b.types.optional(b.types.string,""),post_process:b.types.optional(b.types.string,""),run_by:b.types.optional(b.types.array(b.types.string),[]),react_to:b.types.optional(b.types.array(b.types.string),[])}).views(e=>({get valid(){return e.id&&e.type&&e.key&&e.name?e.type===Se.HTTP?!!e.pre_process:!!e.sql:!1},get json(){const{id:t,name:n,type:r,key:a,sql:o,run_by:l,react_to:u,pre_process:c,post_process:d}=e;return tr({id:t,key:a,sql:o,name:n,type:r,run_by:l,react_to:u,pre_process:c,post_process:d})}})).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}})),q1=b.types.model("SQLSnippetMeta",{key:b.types.string,value:b.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 _e=(e=>(e.Select="select",e.MultiSelect="multi-select",e.TreeSelect="tree-select",e.TextInput="text-input",e.Checkbox="checkbox",e.DateRange="date-range",e))(_e||{});const Jo=b.types.model("FilterCheckboxConfigMeta",{_name:b.types.literal("checkbox"),description:b.types.optional(b.types.string,""),default_value:b.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}})),F1=()=>Jo.create({_name:"checkbox",description:"",default_value:!1});function Zo(e,t){return e.map(n=>{try{return n?Y.tz(n,"UTC").format(t):null}catch{return console.log(`[date-range] failed parsing ${n}`),null}})}const G1=b.types.model("FilterDateRangeConfigMeta",{_name:b.types.literal("date-range"),required:b.types.boolean,inputFormat:b.types.enumeration("DateRangeInputFormat",["YYYY","YYYYMM","YYYYMMDD","YYYY-MM","YYYY-MM-DD"]),default_value:b.types.optional(b.types.array(b.types.union(b.types.string,b.types.null)),[null,null]),clearable:b.types.boolean,max_days:b.types.optional(b.types.number,0),allowSingleDateInRange:b.types.optional(b.types.boolean,!1)}).views(e=>({get json(){const{_name:t,max_days:n,required:r,clearable:a,inputFormat:o,default_value:l,allowSingleDateInRange:u}=e;return{_name:t,max_days:n,required:r,clearable:a,inputFormat:o,default_value:Zo(l,o),allowSingleDateInRange:u}},truthy(t){return Array.isArray(t)&&t.length===2&&t.every(n=>!!n)}})).views(e=>({getMaxDate(t){const{max_days:n}=e;if(!(!n||!t))return Y(t).startOf("day").add(n,"days").toDate()},getMinDate(t){const{max_days:n}=e;if(!(!n||!t))return Y(t).startOf("day").subtract(n,"days").toDate()}})).actions(e=>({setFilterValue(t){try{const n=b.getParent(e);b.getRoot(e).filters.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)},setMaxDays(t){e.max_days=t,t>0&&(e.clearable=!0)},setAllowSingleDateInRange(t){e.allowSingleDateInRange=t}})),Ho=b.types.snapshotProcessor(G1,{preProcessor({default_value:e,...t}){return{...t,default_value:e.map(n=>n===null?null:Y.tz(n,"UTC").toISOString())}},postProcessor(e){const{default_value:t,...n}=e;return{...n,default_value:Zo(t,n.inputFormat)}}}),W1=()=>Ho.create({_name:"date-range",required:!1,inputFormat:"YYYY-MM-DD",clearable:!1,default_value:[null,null]}),j1=b.types.model({label:b.types.string,value:b.types.string}).actions(e=>({setLabel(t){e.label=t},setValue(t){e.value=t}})),ki=b.types.model("FilterConfigModel_BaseSelect",{static_options:b.types.optional(b.types.array(j1),[]),options_query_id:b.types.optional(b.types.string,""),default_selection_count:b.types.optional(b.types.number,0)}).views(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}=b.getRoot(e).content.getDataStuffByID(e.options_query_id);return n==="idle"?t:[]}})).actions(e=>({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??""}})),el=b.types.compose("FilterMultiSelectConfigMeta",b.types.model({_name:b.types.literal("multi-select"),min_width:b.types.optional(b.types.string,""),default_value:b.types.optional(b.types.array(b.types.string),[])}),ki).views(e=>({get json(){const{_name:t,default_value:n,min_width:r,static_options:a,options_query_id:o,default_selection_count:l}=e;return tr({_name:t,min_width:r,default_value:n,static_options:a,options_query_id:o,default_selection_count:l})},get default_selection(){return e.usingQuery?e.options.slice(0,e.default_selection_count).map(t=>t.value):e.default_value}})).actions(e=>({setDefaultValue(t){e.default_value=b.cast(t)},setMinWidth(t){e.min_width=t},setDefaultSelection(){const t=b.getRoot(e).content.filters,n=b.getParent(e).key;t.setValueByKey(n,e.default_selection)}})).actions(e=>({afterCreate(){b.addDisposer(e,re.reaction(()=>re.toJS(e.default_selection),e.setDefaultSelection,{fireImmediately:!0,delay:0}))}})),R1=()=>el.create({_name:"multi-select",default_value:[],static_options:[],options_query_id:"",default_selection_count:0}),tl=b.types.compose("FilterConfigModel_Select",b.types.model({_name:b.types.literal("select"),default_value:b.types.string,required:b.types.boolean,width:b.types.optional(b.types.string,"")}),ki).views(e=>({get json(){const{_name:t,default_value:n,required:r,width:a,static_options:o,options_query_id:l,default_selection_count:u}=e;return tr({_name:t,width:a,required:r,default_value:n,static_options:o,options_query_id:l,default_selection_count:u})},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.default_value}})).actions(e=>({setRequired(t){e.required=t},setDefaultValue(t){e.default_value=t},setWidth(t){e.width=t},setDefaultSelection(){const t=b.getRoot(e).content.filters,n=b.getParent(e).key;t.setValueByKey(n,e.default_selection)}})).actions(e=>({afterCreate(){b.addDisposer(e,re.reaction(()=>re.toJS(e.default_selection),e.setDefaultSelection,{fireImmediately:!0,delay:0}))}})),Y1=()=>tl.create({_name:"select",required:!1,default_value:"",static_options:[],options_query_id:"",default_selection_count:0}),nl=b.types.model("FilterTextInputConfigMeta",{_name:b.types.literal("text-input"),required:b.types.boolean,default_value:b.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}})),rl=()=>nl.create({_name:"text-input",required:!1,default_value:""});function Q1(e){return Ou.arrayToTree(e,{id:"value",parentId:"parent_value",childrenField:"children",dataField:null})}function K1(e){return e.map(t=>{const{label:n,description:r,...a}=t,o={...a,filterBasis:`${n}___${r??""}`,description:r,label:n};return r&&(o.label=y.createElement("div",{},[y.createElement(s.Text,{key:0,title:t.label},t.label),y.createElement(s.Text,{key:1,className:"rc-tree-select-tree-title-desc",color:"dimmed",title:t.description},t.description)])),o})}const il=b.types.compose("FilterTreeSelectConfigMeta",b.types.model({_name:b.types.literal("tree-select"),min_width:b.types.optional(b.types.string,""),default_value:b.types.optional(b.types.array(b.types.string),[])}),ki).views(e=>({get json(){const{_name:t,default_value:n,min_width:r,static_options:a,options_query_id:o,default_selection_count:l}=e;return{_name:t,min_width:r,default_value:n,static_options:a,options_query_id:o,default_selection_count:l}},get treeData(){const{data:t}=b.getRoot(e).content.getDataStuffByID(e.options_query_id),n=K1(t);return Q1(n)},get errorMessage(){const{error:t}=b.getRoot(e).content.getDataStuffByID(e.options_query_id);return t},get treeDataLoading(){const{state:t}=b.getRoot(e).content.getDataStuffByID(e.options_query_id);return t==="loading"},get defaultSelection(){const{default_selection_count:t}=e;return t?this.treeData.slice(0,t).map(r=>r.value):[]}})).actions(e=>({setDefaultValue(t){e.default_value=b.cast(t)},setMinWidth(t){e.min_width=t},applyDefaultSelection(){const t=b.getParent(e,1).key;b.getRoot(e).content.filters.setValueByKey(t,e.defaultSelection)},afterCreate(){b.addDisposer(e,re.reaction(()=>JSON.stringify(e.defaultSelection),this.applyDefaultSelection,{fireImmediately:!0,delay:0}))}})),U1=()=>il.create({_name:"tree-select",default_value:[],static_options:[],options_query_id:"",default_selection_count:0}),al=b.types.model("FilterMeta",{id:b.types.identifier,key:b.types.string,label:b.types.string,order:b.types.number,visibleInViewsIDs:b.types.array(b.types.string),auto_submit:b.types.optional(b.types.boolean,!1),type:b.types.enumeration("DashboardFilterType",[_e.Select,_e.MultiSelect,_e.TreeSelect,_e.TextInput,_e.Checkbox,_e.DateRange]),config:b.types.union(tl,el,il,nl,Jo,Ho)}).views(e=>({get plainDefaultValue(){const t=e.config.default_value;return Array.isArray(t)?[...t]:t},get usingDefaultValue(){return e.type!==_e.TreeSelect},get auto_submit_supported(){return[_e.Select,_e.Checkbox,_e.DateRange].includes(e.type)}})).views(e=>({get json(){const{id:t,key:n,label:r,order:a,visibleInViewsIDs:o,auto_submit:l,type:u,config:c}=e;return{id:t,key:n,type:u,label:r,order:a,config:c.json,auto_submit:l,visibleInViewsIDs:re.toJS(o)}},get should_auto_submit(){return e.auto_submit_supported&&e.auto_submit},requiredAndPass(t){return x.get(e.config,"required",!1)?x.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 _e.Select:e.config=Y1();break;case _e.MultiSelect:e.config=R1();break;case _e.TreeSelect:e.config=U1();break;case _e.TextInput:e.config=rl();break;case _e.Checkbox:e.config=F1();break;case _e.DateRange:e.config=W1();break}e.type=t},setVisibleInViewsIDs(t){e.visibleInViewsIDs.length=0,e.visibleInViewsIDs.push(...t)},setAutoSubmit(t){e.auto_submit=e.auto_submit_supported&&t}}));var R=(e=>(e.Division="div",e.Modal="modal",e.Tabs="tabs",e))(R||{});const sl=b.types.model("ViewDivisionConfig",{_name:b.types.literal(R.Division)}).views(e=>({get json(){const{_name:t}=e;return{_name:t}}})),X1=()=>sl.create({_name:R.Division}),J1=b.types.model("CustomModalTitleModel",{enabled:b.types.optional(b.types.boolean,!1),func_content:b.types.optional(b.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=b.getParent(e,2),a=b.getRoot(e);if(!t)return r.name;try{const o={filters:a.content.filters.values,context:a.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}})),Ti={enabled:!1,func_content:["function text({ filters, context}) {"," // your code goes here",' return "text"',"}"].join(`
440
440
  `)},ol=b.types.model("ViewModalConfig",{_name:b.types.literal(R.Modal),width:b.types.string,height:b.types.string,custom_modal_title:b.types.optional(J1,Ti)}).views(e=>({get json(){const{_name:t,width:n,height:r,custom_modal_title:a}=e;return{_name:t,width:n,height:r,custom_modal_title:a.json}}})).actions(e=>({setWidth(t){e.width=t},setHeight(t){e.height=t}})),Z1=()=>ol.create({_name:R.Modal,width:"90vw",height:"90vh"}),H1=b.types.model("ViewTabsTabModel",{id:b.types.identifier,name:b.types.string,view_id:b.types.string,color:b.types.optional(b.types.string,"")}).views(e=>({get json(){const{id:t,name:n,view_id:r,color:a}=e;return{id:t,name:n,color:a,view_id:r}}})).actions(e=>({setName(t){e.name=t},setViewID(t){e.view_id=t},setColor(t){e.color=t}})),ll=b.types.model("ViewTabsConfig",{_name:b.types.literal(R.Modal),tabs:b.types.optional(b.types.array(H1),[]),variant:b.types.optional(b.types.enumeration("variant",["default","outline","pills"]),"default"),orientation:b.types.optional(b.types.enumeration("orientation",["horizontal","vertical"]),"horizontal"),grow:b.types.optional(b.types.boolean,!1)}).views(e=>({get json(){const{_name:t,variant:n,orientation:r,tabs:a,grow:o}=e;return{grow:o,tabs:a.map(l=>l.json),_name:t,variant:n,orientation:r}}})).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=b.cast(t)},addTab(){const t=Me.randomId(),n={id:t,name:t,view_id:""};e.tabs.push(n)},removeTab(t){e.tabs.splice(t,1)}})),eS=()=>ll.create({_name:R.Modal,tabs:[]}),tS=b.types.model({id:b.types.identifier,name:b.types.string,type:b.types.enumeration("EViewComponentType",[R.Division,R.Modal,R.Tabs]),config:b.types.union(sl,ol,ll),panelIDs:b.types.optional(b.types.array(b.types.string),[])}).views(e=>({get json(){const{id:t,name:n,type:r,config:a}=e;return{id:t,name:n,type:r,config:a.json,panelIDs:e.panelIDs}}})).actions(e=>({setName(t){e.name=t},setType(t){if(e.type!==t){switch(t){case R.Division:e.config=X1();break;case R.Modal:e.config=Z1();break;case R.Tabs:e.config=eS();break}e.type=t}},appendPanelID(t){e.panelIDs.push(t)},removePanelID(t){const n=e.panelIDs.filter(r=>r!==t);e.panelIDs.length=0,e.panelIDs.push(...n)}})),ul=b.types.model("DataSourceMetaModel",{id:b.types.string,type:b.types.enumeration("DataSourceType",[Se.HTTP,Se.MySQL,Se.Postgresql]),key:b.types.string,config:b.types.frozen()}),nS=b.types.model("DataSourcesMetaModel",{list:b.types.optional(b.types.array(ul),[])}).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)}})),rS=b.types.model({id:b.types.string,content:b.types.string,create_time:b.types.string,update_time:b.types.string,is_preset:b.types.boolean}),cl=b.types.model("GlobalSQLSnippetsMeta",{list:b.types.optional(b.types.array(rS),[])}).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)}})),Di=b.types.model("ContextMeta",{current:b.types.optional(b.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 dl(e){return Di.create({current:e})}const pl=b.types.model("ViewsRenderModel",{current:b.types.optional(b.types.array(tS),[]),visibleViewIDs:b.types.array(b.types.string)}).views(e=>({get json(){return e.current.map(t=>tr(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 iS(e){const t=e.length>0?[e[0].id]:[];return{current:e.map(r=>{const{_name:a=r.type}=r.config;return{...r,config:{...r.config,_name:a},panelIDs:r.panelIDs}}),visibleViewIDs:t}}const hl=V1.views(e=>({get contentModel(){return b.getRoot(e).content}})).views(e=>({get queries(){return e.contentModel.queries.findByIDSet(e.queryIDSet)},get data(){return this.queries.reduce((t,n)=>(t[n.id]=n.data.toJSON(),t),{})},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(u=>n.add(u)),l.filters.forEach(u=>r.add(u))});const a=[];return n.size>0&&(console.log(n),a.push(`context: ${Array.from(n).join(", ")}`)),r.size>0&&a.push(`filter${r.size>1?"s":""}: ${Array.from(r).join(", ")}`),a.length===2&&a.splice(1,0,"and"),a.unshift("Waiting for"),a.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())},downloadData(){b.getRoot(e).content.queries.downloadDataByQueryIDs(e.queryIDs)}}));function aS(e){return{id:e,layout:{x:0,y:1/0,w:18,h:300},title:e,description:"<p></p>",queryIDs:[],viz:{type:hi.name,conf:hi.createConfig()},style:{border:{enabled:!0}}}}const fl=b.types.model("PanelsRenderModel",{list:b.types.optional(b.types.array(hl),[])}).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=[];t.forEach(a=>{const o=e.idMap.get(a);o?n.push(o):console.warn(`Panel is not found, id:${a}`)});const r=n.map(a=>({...a.layout.json,i:a.id}));return{panels:n,layouts:r}}}));function gl(e,t){if(e===void 0)return e;if(t._name==="date-range")try{const[...n]=e;return n.map(r=>r===null?r:Y.tz(r,"UTC").format(t.inputFormat)??r)}catch(n){return console.error(n),e}return e}function sS(e){return e.reduce((t,n)=>(t[n.key]=gl(n.config.default_value,n.config),t),{})}const ml=b.types.model("FiltersRenderModel",{current:b.types.optional(b.types.array(al),[]),values:b.types.optional(b.types.frozen(),{})}).views(e=>({get json(){return e.current.map(t=>t.json)},get firstID(){if(e.current.length!==0)return e.current[0].id},findByID(t){return e.current.find(n=>n.id===t)},get inOrder(){return x.sortBy(e.current,"order")},get empty(){return e.current.length===0},visibleInView(t){return x.sortBy(e.current.filter(n=>n.visibleInViewsIDs.includes(t)),"order")},get firstFilterValueKey(){return Object.keys(e.values)[0]??""},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},setValueByKey(t,n){e.values={...e.values,[t]:n}},getValueByKey(t){return e.values[t]}}));function yl(e){return{current:e,values:sS(e)}}const oS=N1.views(e=>({get conditionOptions(){if(!b.isAlive(e))return[];const t=b.getRoot(e).content,{context:n}=t.payloadForSQL,r=Object.keys(n).map(o=>({group:"Context",label:o,value:`context.${o}`,description:void 0})),a=t.filters.keyLabelOptions.map(o=>({group:"Filters",label:o.label,value:`filters.${o.value}`,description:o.value}));return[...r,...a]},get unmetRunByConditions(){if(!b.isAlive(e))return[];const{run_by:t}=e;if(t.length===0)return[];const n=b.getRoot(e).content.payloadForSQL;return t.filter(r=>{const a=x.get(n,r);return Array.isArray(a)?a.length===0:typeof a=="number"?Number.isNaN(a):!a})}})).views(e=>({get reQueryKey(){const{react_to:t=[]}=e;if(t.length===0)return"";const n=b.getRoot(e).content.payloadForSQL,r=[...t].reduce((a,o)=>(a[o]=x.get(n,o),a),{});return JSON.stringify(r)},get runByConditionsMet(){return e.unmetRunByConditions.length===0},get conditionNames(){if(e.unmetRunByConditions.length===0)return{context:[],filters:[]};const{keyLabelMap:t}=b.getRoot(e).content.filters,n=e.unmetRunByConditions.filter(a=>a.startsWith("context.")).map(a=>a.split("context.")[0]),r=e.unmetRunByConditions.filter(a=>a.startsWith("filters.")).map(a=>x.get({filters:t},a)).filter(a=>!!a);return{context:n,filters:r}}}));function lS(e,t){return new Function(`return ${e}`)()(t,Tt)}function uS(e,t,n){return lS(e,{context:t,filters:n})}function cS(e,t){try{return new Function(`return ${e.config.processing.pre}`)()(t,Tt)}catch(n){return console.error(n),t}}function dS(e,t){return new Function(`return ${e.config.processing.post}`)()(t,Tt)}function pS(e,t){return e?new Function(`return ${e}`)()(t,Tt):t}const hS=b.types.compose("QueryRenderModel",oS,b.types.model({state:b.types.optional(b.types.enumeration(["idle","loading","error"]),"idle"),data:b.types.optional(b.types.array(b.types.frozen()),[]),error:b.types.frozen()})).views(e=>({get formattedSQL(){const t=b.getRoot(e).content.payloadForSQL;return gr(e.sql,t)},get typedAsSQL(){return[Se.Postgresql,Se.MySQL].includes(e.type)},get typedAsHTTP(){return[Se.HTTP].includes(e.type)},get datasource(){const{key:t,type:n}=e;return b.getRoot(e).datasources.find({type:n,key:t})},get httpConfigString(){const{context:t,filters:n}=b.getRoot(e).content.payloadForSQL,{name:r,pre_process:a}=e.json,o=uS(a,t,n);return console.groupCollapsed(`Request config for: ${r}`),console.log(o),console.groupEnd(),JSON.stringify(o)}})).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:b.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=b.getRoot(e).content.payloadForSQL;e.data=yield*b.toGenerator(Uu({payload:n,title:e.name,query:e.json},e.controller.signal)),e.state="idle",e.error=null}catch(n){if(!mt.isCancel(n)){e.data.length=0;const r=x.get(n,"message","unkown error");e.error=x.get(n,"response.data.detail.message",r),e.state="error"}}}}),runHTTP:b.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:a}=e.json;let o=JSON.parse(e.httpConfigString);o=cS(e.datasource,o);const l=yield*b.toGenerator(Xu({type:n,key:r,configString:JSON.stringify(o)},e.controller.signal));let u=dS(e.datasource,l);u=pS(a,u),e.data=u,e.state="idle",e.error=null}catch(n){if(console.error(n),!mt.isCancel(n)){e.data.length=0;const r=x.get(n,"message","unkown error");e.error=x.get(n,"response.data.detail.message",r),e.state="error"}}}})})).actions(e=>({fetchData:()=>e.typedAsHTTP?e.runHTTP():e.runSQL(),beforeDestroy(){var t;(t=e.controller)==null||t.abort()}})).actions(e=>({afterCreate(){b.addDisposer(e,re.reaction(()=>{var t,n;return e.typedAsHTTP?`${e.id}--${e.key}--${e.reQueryKey}--${(t=e.datasource)==null?void 0:t.id}`:`${e.id}--${e.key}--${e.formattedSQL}--${e.pre_process}--${e.post_process}--${(n=e.datasource)==null?void 0:n.id}`},e.fetchData,{fireImmediately:!0,delay:0}))}})),bl="\uFEFF";function fS(e,t){const n=new Blob([bl+t],{type:"text/csv"});hr.saveAs(n,`${e}.csv`)}function vl(e,t){const n=new Blob([t],{type:"application/json"});hr.saveAs(n,`${e}.json`)}function xl(e){const t=new Pu;e.forEach(({id:n,data:r})=>{t.file(`${n}.csv`,Cl(r))}),t.generateAsync({type:"blob"}).then(n=>{hr.saveAs(n,"dashboard_data.zip")})}function wl(e){return typeof e=="string"&&e.includes(",")?`"${e}"`:e}function Cl(e){if(!Array.isArray(e)||e.length===0)return"";const t=[],n=Object.keys(e[0]).map(wl);return t.push(n.join(",")),e.forEach(r=>{const a=Object.values(r).map(wl).join(",");t.push(a)}),bl+t.join(`
441
441
  `)}const Sl=b.types.model("QueriesRenderModel",{current:b.types.optional(b.types.array(hS),[])}).views(e=>({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)}})).actions(e=>({downloadAllData(){const t=e.current.map(({name:n,data:r})=>({id:n,data:r.toJSON()}));xl(t)},downloadDataByQueryIDs(t){const n=new Set(t),r=e.current.filter(a=>n.has(a.id)).map(({name:a,data:o})=>({id:a,data:o.toJSON()}));xl(r)},downloadDataByQueryID(t){const n=e.findByID(t);if(!n){console.log("[downloadDataByQueryID] query not found");return}const{name:r,data:a}=n,o=Cl(a);fS(r,o)},refetchDataByQueryID(t){const n=e.findByID(t);if(!n){console.error(new Error(`[downloadDataByQueryID] query by ID[${t}] not found`));return}return n.fetchData()}}));function gS(e){return{current:e}}const mS=q1.views(e=>({isADuplicatedKey(t){return!t||t===e.key?!1:!!b.getParent(e,2).findByKey(t)}})),_l=b.types.model("SQLSnippetsRenderModel",{current:b.types.optional(b.types.array(mS),[])}).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 firstKey(){if(e.current.length!==0)return e.current[0].key},findByKey(t){return e.current.find(n=>n.key===t)}}));function yS(e){return{current:e}}function nr(e,t,n,r){return e.reduce((a,o)=>{try{a[o[t]]=fr(o[n],r)}catch(l){a[o[t]]=l.message}return a},{})}class bS{constructor(t){q(this,"origin");q(this,"copy");this.origin=t,this.copy=b.clone(t),re.makeAutoObservable(this,{},{autoBind:!0,deep:!1})}get changed(){return!x.isEqual(b.getSnapshot(this.origin),b.getSnapshot(this.copy))}commit(){b.applySnapshot(this.origin,b.getSnapshot(this.copy))}update(t){b.applySnapshot(this.copy,t)}}const vS=e=>new bS(e),xS=k.observer(({view:e})=>{const t=ye(),n=le(),r=et.useModals(),{panel:a,downloadPanelScreenshot:o}=nt(),{id:l}=a,{viewPanelInFullScreen:u,inFullScreen:c}=y.useContext(er),d=()=>{n.duplicatePanelByID(l,e.id)},f=()=>{t.editor.open(["_VIEWS_",e.id,"_PANELS_",l])},h=()=>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}),g=y.useCallback(()=>{u(l)},[l,u]),m=!c&&e.type!==R.Modal;return i(P,{children:i(s.Box,{sx:{position:"absolute",top:0,left:0,right:0,zIndex:300},children:p(s.Menu,{withinPortal:!0,children:[i(s.Menu.Target,{children:i(s.Box,{className:"panel-dropdown-target",sx:{width:"100%",height:"25px"}})}),p(s.Menu.Dropdown,{children:[i(s.Menu.Item,{onClick:a.refreshData,icon:i(T.Refresh,{size:14}),children:"Refresh"}),i(s.Menu.Item,{onClick:a.downloadData,icon:i(T.Download,{size:14}),children:"Download Data"}),i(s.Menu.Item,{onClick:o,icon:i($.IconCamera,{size:14}),children:"Screenshot"}),m&&i(s.Menu.Item,{onClick:g,icon:i(T.ArrowsMaximize,{size:14}),disabled:!0,children:"Full Screen"}),i(s.Divider,{label:"Edit",labelPosition:"center"}),i(s.Menu.Item,{onClick:f,icon:i(T.Settings,{size:14}),children:"Settings"}),i(s.Menu.Item,{onClick:d,icon:i(T.Copy,{size:14}),children:"Duplicate"}),i(s.Menu.Item,{color:"red",onClick:h,icon:i(T.Trash,{size:14}),children:"Delete"})]})]})})})});function wS(e){return e?["<p><br></p>","<p></p>"].includes(e):!0}const Mi=k.observer(()=>{const[e,t]=y.useState(!1),{panel:n}=bt();return wS(n.description)?null:p(P,{children:[i(s.Modal,{opened:e,onClose:()=>t(!1),title:n.title,withCloseButton:!1,withinPortal:!0,zIndex:310,children:i(Nn,{value:n.description,styles:{root:{border:"none"},content:{padding:0}}})}),i(s.Tooltip,{label:"Click to see description",position:"top-start",withinPortal:!0,children:i(s.ActionIcon,{variant:"subtle",color:"blue",onClick:()=>t(r=>!r),sx:{verticalAlign:"baseline",cursor:"pointer"},children:i(T.InfoCircle,{size:20})})})]})}),HM="",eI="",CS=k.observer(function(){const{panel:t}=bt(),{title:n}=t;return n?i(s.Group,{grow:!0,position:"center",px:20,className:"panel-title-wrapper",sx:{flexGrow:1},children:i(s.Text,{align:"center",lineClamp:1,weight:"bold",children:n})}):null});function SS(e){const t=y.useRef(null);return{ref:t,downloadPanelScreenshot:()=>{const r=t.current;if(!r)return;const a=r.offsetWidth*2,o=r.offsetHeight*2;Qa.toBlob(t.current,{bgcolor:"white",width:a,height:o,style:{border:"none",borderRadius:0,transformOrigin:"0 0",transform:"scale(2)"}}).then(l=>{window.saveAs(l,`${e.title?e.title:e.viz.type}.png`)})}}}var kl=(e=>(e.migrated="migrated",e.nothingToMigrate="nothingToMigrate",e.checkFailed="checkFailed",e.migrationFailed="migrationFailed",e))(kl||{}),rr=(e=>(e.notStarted="notStarted",e.inProgress="inProgress",e.done="done",e))(rr||{});class _S{constructor(t){q(this,"vizInstance");q(this,"operationManager");q(this,"triggerManager");q(this,"vizManager");q(this,"runningMigration");q(this,"panelModel");q(this,"status","notStarted");this.panelModel=t.getRequired(Ce.instanceScope.panelModel),this.vizInstance=t.getRequired(Ce.instanceScope.vizInstance),this.operationManager=t.getRequired(Ce.instanceScope.operationManager),this.triggerManager=t.getRequired(Ce.instanceScope.triggerManager),this.vizManager=t.getRequired(Ce.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 Tl(e){const{panel:t}=bt();return y.useCallback(n=>{const r=n.getRequired(Ce.vizManager),a=r.resolveComponent(e.viz.type);return n.createScoped().provideFactory(Ce.instanceScope.vizInstance,()=>r.getOrCreateInstance(e)).provideFactory(Ce.instanceScope.interactionManager,o=>{const l=o.getRequired(Ce.instanceScope.vizInstance);return new Dr(l,a,Tn)}).provideFactory(Ce.instanceScope.operationManager,o=>o.getRequired(Ce.instanceScope.interactionManager).operationManager).provideFactory(Ce.instanceScope.triggerManager,o=>o.getRequired(Ce.instanceScope.interactionManager).triggerManager).provideValue(Ce.instanceScope.panelModel,t).provideFactory(Ce.instanceScope.migrator,o=>new _S(o))},[e.viz.type,e.viz.conf])}function Dl(e){const[t,n]=y.useState(!1),r=jo().getRequired(Ce.instanceScope.migrator);return U.useAsyncEffect(async()=>{const a=r.status===rr.notStarted;n(r.status===rr.done),r.status===rr.notStarted&&r.runMigration().then(o=>{o===kl.migrated&&a&&(e==null||e())}).finally(()=>{n(!0)})},[r]),t}function Ml(e,t){const n=jo().getRequired(Ce.instanceScope.vizInstance);return y.useEffect(()=>(n.instanceData.setItem(null,t.viz.conf),n.instanceData.watchItem(null,r=>{e(r)})),[e,t.viz.type]),n}function kS({setVizConf:e,...t}){const{panel:n}=t,r=Ml(e,n),a=Dl(()=>{bn.showNotification({title:`${n.title} - Updated`,message:"Your plugin configuration has been migrated to the latest version"})});return U.useAsyncEffect(async()=>{await r.instanceData.setItem(null,n.viz.conf)},[r,n.viz.type]),a?i(ec,{...t}):i(s.Text,{children:"Checking update..."})}function TS(e){const{panel:t,setVizConf:n}=e;Ml(n,t);const{inEditMode:r}=y.useContext(_n);return Dl(()=>{r&&bn.showNotification({title:`${t.title} - Updated`,message:"Your plugin configuration has been migrated to the latest version"})})?i(Hu,{...e}):i(s.Text,{children:"Checking update"})}const tI="";function DS(e,t){const{vizManager:n}=y.useContext(ut),{panel:{viz:r,title:a,id:o,description:l,queryIDs:u,variables:c}}=bt(),d={title:a,id:o,description:l,queryIDs:u,viz:r,layout:t},f=Tl(d);try{return n.resolveComponent(r.type),i(Hn,{configure:f,children:i(TS,{setVizConf:r.setConf,panel:d,data:e,variables:c,vizManager:n})})}catch(h){return console.info(x.get(h,"message")),null}}const Il=k.observer(function({data:t}){const{ref:n,width:r,height:a}=Me.useElementSize(),o=DS(t,{w:r,h:a}),l=r>0&&a>0;return i("div",{className:"viz-root",ref:n,children:l&&i(Fe,{children:o})})}),Al=k.observer(({panel:e})=>p(s.Stack,{children:[e.queryErrors.map((t,n)=>i(s.Text,{color:"red",size:"sm",align:"center",sx:{fontFamily:"monospace"},children:t},`${n}-${t}`)),i(s.Text,{color:"gray",align:"center",size:"sm",children:e.queryStateMessages})]})),Ii=k.observer(({panel:e,height:t})=>p(s.Flex,{direction:"column",sx:{height:t,position:"relative",width:"100%"},children:[i(s.LoadingOverlay,{visible:e.dataLoading,exitTransitionDuration:0}),!e.canRenderViz&&i(Al,{panel:e}),e.canRenderViz&&i(Il,{data:e.data})]})),MS={border:"1px solid #e9ecef"},zl=k.observer(({panel:e,panelStyle:t,dropdownContent:n})=>{const{ref:r,downloadPanelScreenshot:a}=SS(e),o=e.title?"calc(100% - 25px - 5px)":"100%";return i(Sr,{value:{panel:e,data:e.data,loading:e.dataLoading,errors:e.queryErrors,downloadPanelScreenshot:a},children:p(s.Box,{className:"panel-root",ref:r,p:5,pt:0,sx:{...MS,...t},children:[i(s.Box,{sx:{position:"absolute",left:0,top:0,height:28,zIndex:310},children:i(Mi,{})}),n,i(CS,{}),i(Ii,{panel:e,height:o})]})})}),IS={border:"1px dashed transparent",transition:"border-color 300ms ease","&:hover":{borderColor:"#e9ecef"}};function AS(e){return e.style.border.enabled?{}:IS}const El=k.observer(function({panel:t,view:n}){const r=AS(t);return i(zl,{panel:t,panelStyle:r,dropdownContent:i(xS,{view:n})})});function zS(e){return!["richText","button"].includes(e)}const ES=k.observer(({view:e})=>{const{panel:t,downloadPanelScreenshot:n}=bt(),{id:r}=t,{viewPanelInFullScreen:a,inFullScreen:o}=y.useContext(er),l=y.useCallback(()=>{a(r)},[r,a]),u=!o&&e.type!==R.Modal;return zS(t.viz.type)?i(s.Box,{sx:{position:"absolute",top:0,left:0,right:0,zIndex:300},children:p(s.Menu,{withinPortal:!0,children:[i(s.Menu.Target,{children:i(s.Box,{className:"panel-dropdown-target",sx:{width:"100%",height:"25px"}})}),p(s.Menu.Dropdown,{children:[i(s.Menu.Item,{onClick:t.refreshData,icon:i(T.Refresh,{size:14}),children:"Refresh"}),i(s.Menu.Item,{onClick:t.downloadData,icon:i(T.Download,{size:14}),children:"Download Data"}),i(s.Menu.Item,{onClick:n,icon:i($.IconCamera,{size:14}),children:"Screenshot"}),u&&i(s.Menu.Item,{onClick:l,icon:i(T.ArrowsMaximize,{size:14}),children:"Full Screen"})]})]})}):null});function $S(e){return e.style.border.enabled?{}:{border:"1px dashed transparent"}}const Ai=k.observer(({panel:e,view:t})=>{const n=$S(e);return i(zl,{panel:e,panelStyle:n,dropdownContent:i(ES,{view:t})})}),LS={modal:{display:"flex",flexDirection:"column",flexWrap:"nowrap"},body:{display:"flex",height:"calc(100vh - 88px)"}},$l=k.observer(function({view:t,panel:n,exitFullScreen:r}){return i(s.Modal,{opened:!0,fullScreen:!0,onClose:r,title:i(s.Button,{color:"blue",size:"xs",onClick:r,leftIcon:i(T.ArrowLeft,{size:20}),children:"Exit fullscreen"}),styles:LS,children:i(s.Group,{grow:!0,sx:{flexGrow:1,flexShrink:0},children:i(Ai,{view:t,panel:n})})})});function Ll(e,t,n){const{panels:r}=we(),a=e.id==="Main",[o,l]=y.useState(()=>a&&r.findByID(t)?t:null),u=y.useCallback(h=>{l(h),a&&n(h)},[a,n]),c=y.useCallback(()=>{l(null),a&&n("")},[a,n]),d=o?r.findByID(o):null;return{viewPanelInFullScreen:u,exitFullScreen:c,inFullScreen:!!d,fullScreenPanel:d}}const nI="",OS=y.forwardRef(({h:e},t)=>i(s.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:i(T.ArrowsMove,{size:16})})),PS=y.forwardRef(({handleAxis:e,...t},n)=>i(s.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:i(T.ChevronDownRight,{size:16})})),BS=vn.WidthProvider(vn),VS=k.observer(({view:e,className:t="layout"})=>{const n=we(),{panels:r,layouts:a}=n.panels.panelsByIDs(e.panelIDs),o=y.useCallback(u=>{u.forEach(({i:c,...d})=>{const f=n.panels.findByID(c);f&&f.layout.set(d)})},[n]),l=(u,c,d,f)=>{d.h<30&&(d.h=30,f.h=30),d.w<4&&(d.w=4,f.w=4)};return i(BS,{onLayoutChange:o,className:`dashboard-layout ${t}`,rowHeight:1,cols:36,margin:[0,0],isBounded:!0,isDraggable:!0,isResizable:!0,layout:a,draggableHandle:".react-grid-customDragHandle",resizeHandle:i(PS,{}),onResize:l,children:r.map((u,c)=>p("div",{"data-grid":{...u.layout},className:"panel-grid-item",children:[i(OS,{h:u.layout.h}),i(El,{view:e,panel:u})]},u.id))})}),NS=vn.WidthProvider(vn),qS=k.observer(function({view:t,className:n="layout"}){const{panels:r,layouts:a}=we().panels.panelsByIDs(t.panelIDs);return i(NS,{className:`dashboard-layout ${n}`,cols:36,rowHeight:1,margin:[0,0],isDraggable:!1,isResizable:!1,layout:a,children:r.map(o=>i("div",{"data-grid":{...o.layout},className:"panel-grid-item",children:i(Ai,{view:t,panel:o})},o.id))})});function zi(e){const t=y.useRef(null);return{ref:t,downloadScreenshot:()=>{var l;const r=(l=t.current)==null?void 0:l.querySelector(".react-grid-layout");if(!r)return;const a=r.offsetWidth*2+10,o=r.offsetHeight*2+10;Qa.toBlob(r,{bgcolor:"white",width:a,height:o,style:{transformOrigin:"0 0",transform:"scale(2)"}}).then(u=>{window.saveAs(u,`${e.name}.png`)})}}}const FS=k.observer(({downloadScreenShot:e})=>{const[t,{setTrue:n,setFalse:r}]=U.useBoolean(!1),a=wr(),o=we(),l=()=>{const u=JSON.stringify(o.json,null,2),c=`${a.name}__${o.name}`;vl(c,u)};return p(s.Menu,{shadow:"md",width:200,trigger:"hover",openDelay:200,closeDelay:400,withinPortal:!0,position:"bottom-end",children:[i(s.Menu.Target,{children:i(s.Affix,{position:{bottom:"20px",right:"10px"},zIndex:1,children:i(s.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:i($.IconShare3,{size:"1rem"})})})}),p(s.Menu.Dropdown,{children:[i(s.Menu.Item,{icon:i($.IconCamera,{size:14}),onClick:e,children:"Screenshot"}),i(s.Menu.Divider,{}),i(s.Menu.Item,{icon:i($.IconDownload,{size:14}),onClick:o.queries.downloadAllData,children:"Download Data"}),i(s.Menu.Item,{icon:i($.IconCode,{size:14}),onClick:l,children:"Download Schema"})]})]})}),Ol=k.observer(({children:e,view:t,sx:n={}})=>{const{ref:r,downloadScreenshot:a}=zi(t);return p(P,{children:[i(s.Box,{ref:r,sx:n,children:e}),i(FS,{downloadScreenShot:a})]})}),Pl=k.observer(({downloadScreenshot:e})=>i(s.ActionIcon,{className:"download-screenshot-button",color:"blue",onClick:e,children:i($.IconCamera,{size:14})})),GS=k.observer(({children:e,view:t})=>{const n=we(),r=t.config,a=n.views.visibleViewIDs.includes(t.id),o=()=>n.views.rmVisibleViewID(t.id),{ref:l,downloadScreenshot:u}=zi(t);return i(s.Modal,{size:r.width,centered:!0,opened:a,onClose:o,withCloseButton:!1,title:p(s.Group,{position:"apart",px:"1rem",h:"48px",children:[i(s.Box,{children:r.custom_modal_title.value}),i(Pl,{downloadScreenshot:u})]}),trapFocus:!0,onDragStart:c=>{c.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"},header:{padding:0},title:{flexGrow:1}},transitionProps:{duration:0},children:i(s.Box,{ref:l,children:e})})}),WS=e=>e.color?{"&[data-active], &[data-active]:hover":{borderColor:e.color?e.color:"..."}}:{},jS=k.observer(({view:e})=>{const t=we(),n=e.config;return p(s.Tabs,{className:"render-view-tabs",variant:n.variant,orientation:n.orientation,defaultValue:n.tabs.length>0?n.tabs[0].id:"0",styles:{root:{height:"100%",overflow:n.orientation==="horizontal"?"hidden":"auto"},panel:{padding:n.orientation==="horizontal"?"8px 0px 8px":"0",height:"100%",overflow:"auto"}},keepMounted:!1,children:[i(s.Tabs.List,{grow:n.grow,children:n.tabs.map(r=>i(s.Tabs.Tab,{value:r.id,sx:WS(r),disabled:!r.view_id,children:r.name??r.id},r.id))}),n.tabs.map(r=>{const a=t.views.findByID(r.view_id);return a?i(s.Tabs.Panel,{value:r.id,children:i(ir,{view:a})},r.id):null})]})}),RS=k.observer(({view:e,children:t})=>{switch(e.type){case R.Modal:return i(GS,{view:e,children:t});case R.Tabs:return i(jS,{view:e});case R.Division:default:return i(Ol,{view:e,children:t})}}),YS=k.observer(({children:e,view:t})=>i(Ol,{sx:{paddingTop:"10px",paddingBottom:"100px"},view:t,children:e}));function Bl(e){return e.replace(/(vw|vh)/,"%")}const QS=k.observer(({children:e,view:t})=>{const n=t.config,{width:r,height:a}=y.useMemo(()=>({width:Bl(n.width),height:Bl(n.height)}),[n.width,n.height]),{ref:o,downloadScreenshot:l}=zi(t);return i(s.Box,{sx:{height:"100%","> div:not(.mantine-Modal-root)":{height:"100%"}},children:i(s.Modal,{size:n.width,opened:!0,onClose:x.noop,withCloseButton:!1,title:p(s.Group,{position:"apart",px:"1rem",h:"48px",children:[i(s.Box,{children:n.custom_modal_title.value}),i(Pl,{downloadScreenshot:l})]}),trapFocus:!0,onDragStart:u=>{u.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:a,maxHeight:a},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:i(s.Box,{ref:o,children:e})})})}),KS=({variant:e,orientation:t})=>{const n={root:{height:"100%",overflow:"hidden"},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},US=e=>e.color?{"&[data-active], &[data-active]:hover":{borderColor:e.color?e.color:"..."}}:{},XS=k.observer(({view:e})=>{const t=et.useModals(),n=le(),r=y.useMemo(()=>n.views.options.filter(u=>u.type===R.Division),[e.id,n.views.options]),a=e.config,o=u=>t.openConfirmModal({title:"Delete this tab?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>{a.removeTab(u)},confirmProps:{color:"red"},zIndex:320}),l=a.tabs.length===0;return p(s.Tabs,{className:"preview-view-tabs",variant:a.variant,orientation:a.orientation,defaultValue:a.tabs.length>0?a.tabs[0].id:"0",styles:KS(a),children:[p(s.Tabs.List,{grow:a.grow,children:[a.tabs.map(u=>i(s.Tabs.Tab,{value:u.id,sx:US(u),children:u.name??u.id},u.id)),i(s.Tabs.Tab,{onClick:a.addTab,value:"add",className:"add-a-tab",children:i(T.Plus,{size:18,color:"#228be6"})})]}),a.tabs.map((u,c)=>{const d=n.views.findByID(u.view_id);return p(s.Tabs.Panel,{value:u.id,sx:{position:"relative"},children:[p(s.Box,{sx:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:200},children:[i(s.Overlay,{opacity:.8,color:"#FFF",blur:10,zIndex:100}),p(s.Stack,{mx:"auto",mt:100,sx:{width:"300px",position:"relative",zIndex:200},children:[i(s.TextInput,{label:"Tab Name",value:u.name,onChange:f=>u.setName(f.currentTarget.value)}),i(s.Select,{label:"View",value:u.view_id,onChange:u.setViewID,data:r}),i(s.ColorInput,{label:"Color",value:u.color,onChange:u.setColor,disabled:a.variant!=="default"}),d&&p(s.Button,{mt:20,variant:"gradient",leftIcon:i($.IconArrowsLeftRight,{size:18}),gradient:{from:"cyan",to:"indigo"},onClick:()=>n.views.setIDOfVIE(d.id),children:["Swith to View: ",d.name]}),i(s.Button,{mt:20,variant:"subtle",color:"red",onClick:()=>o(c),disabled:l,leftIcon:i($.IconTrash,{size:14}),children:"Delete This Tab"})]})]}),d&&i(ir,{view:d})]},u.id)})]})}),JS=k.observer(({view:e,children:t})=>{switch(e.type){case R.Modal:return i(QS,{view:e,children:t});case R.Tabs:return i(XS,{view:e});case R.Division:default:return i(YS,{view:e,children:t})}}),Vl=k.observer(function({view:t}){return i(er.Provider,{value:{viewPanelInFullScreen:x.noop,inFullScreen:!1},children:i(s.Box,{className:"dashboard-view","data-enable-scrollbar":!0,children:i(JS,{view:t,children:p(s.Box,{sx:{position:"relative"},children:[i(s.Box,{className:"dashboard-sticky-area",sx:{position:"sticky",top:"0px"},children:i(Ko,{view:t})}),i(VS,{view:t})]})})})})}),ir=k.observer(function({view:t}){const{fullScreenPanelID:n,setFullScreenPanelID:r}=os(),{viewPanelInFullScreen:a,exitFullScreen:o,inFullScreen:l,fullScreenPanel:u}=Ll(t,n,r);return i(er.Provider,{value:{viewPanelInFullScreen:a,inFullScreen:l},children:p(s.Box,{className:"dashboard-view","data-enable-scrollbar":!0,sx:{height:t.type===R.Modal?"0 !important":"100%"},children:[l&&i($l,{view:t,panel:u,exitFullScreen:o}),i(RS,{view:t,children:p(s.Box,{sx:{position:"relative"},children:[!l&&i(s.Box,{className:"dashboard-sticky-area",sx:{position:"sticky",top:"0px"},children:i(Ko,{view:t})}),!l&&i(qS,{view:t})]})})]})})});var Nl=(e=>(e.Use="use",e.Edit="edit",e))(Nl||{});const ZS={[R.Division]:"Division",[R.Tabs]:"Tabs",[R.Modal]:"Modal"},ql={[R.Division]:"rgba(255, 0, 0, 0.2)",[R.Modal]:"rgba(0, 0, 0, 0.2)",[R.Tabs]:"rgba(255, 200, 100, 0.4)"},HS={[R.Division]:"#ff4000",[R.Modal]:"#000",[R.Tabs]:"#ffad18"},e_={definition:{sqlSnippets:[],queries:[],mock_context:{}},views:[{id:"Main",name:"Main",type:R.Division,config:{},panelIDs:[]}],panels:[],filters:[],version:"9.19.0"};function t_(e,t,n){b.addDisposer(e,b.addMiddleware(e,(r,a)=>{a(r,()=>{b.getType(r.context)===t&&r.type==="action"&&n(r.name,r.context)})}))}const Fl=b.types.compose("FiltersModel",ml,b.types.model("FiltersModel",{previewValues:b.types.optional(b.types.frozen(),{})})).views(e=>({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===_e.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}))}})).actions(e=>({replace(t){e.current=b.cast(t)},append(t){e.current.push(t)},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(){t_(e.current,al,(n,r)=>{if(n==="setType"){const a=gl(r.config.default_value,r.config);e.setValueByKey(r.key,a),e.updatePreviewValues({...e.previewValues,[r.key]:a})}})}return{afterCreate(){t()}}}),Gl=Sl.views(e=>({get options(){const t=e.current.map(n=>({value:n.id,label:n.name,_type:"query"}));return x.sortBy(t,n=>n.label.toLowerCase())}})).actions(e=>({replace(t){e.current=b.cast(t)},append(t){e.current.push(t)},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&&(b.detach(n),e.current.remove(n))}})),Wl=_l.views(e=>({get options(){const t=e.current.map(n=>({label:n.key,value:n.key,_type:"sql_snippet"}));return x.sortBy(t,n=>n.label.toLowerCase())}})).actions(e=>({replace(t){e.current=b.cast(t)},append(t){e.current.push(t)},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)},replaceByIndex(t,n){e.current.splice(t,1,n)}})),n_=b.types.model({data:b.types.optional(b.types.frozen(),[]),state:b.types.optional(b.types.enumeration(["idle","loading","error"]),"idle"),error:b.types.frozen()}).views(e=>({get loading(){return e.state==="loading"},get empty(){return e.data.length===0},get sql(){const t=b.getParent(e,1),{type:n,table_name:r,table_schema:a}=t;if(n===Se.MySQL)return`
442
442
  SELECT ordinal_position, column_key, column_name, column_type, is_nullable, column_default, column_comment
@@ -516,7 +516,7 @@ Check the top-level render call using <`+V+">.")}return E}}function ku(S,E){{if(
516
516
  parent_value: string;
517
517
  description?: string;
518
518
  }
519
- `,H_=()=>{const[e,t]=y.useState(!1);return p(P,{children:[i(s.Button,{variant:"subtle",compact:!0,onClick:()=>t(n=>!n),children:e?"Close":"Click to see expected data structure"}),i(s.Collapse,{in:e,children:i(kt.Prism,{language:"typescript",noCopy:!0,colorScheme:"dark",children:Z_})})]})},ek=k.observer(function({config:t}){return p(P,{children:[i(s.TextInput,{label:"Min-width",value:t.min_width,onChange:n=>t.setMinWidth(n.currentTarget.value),placeholder:"200px"}),i(s.Divider,{label:"Fetch options from database",labelPosition:"center"}),i(s.NumberInput,{value:t.default_selection_count,onChange:t.setDefaultSelectionCount,label:"Select first N options by default"}),i(Bi,{value:t.options_query_id,onChange:t.setOptionsQueryID}),i(H_,{})]})}),tk=k.observer(function({filter:t}){const[n,r]=y.useState(t.plainDefaultValue);return y.useEffect(()=>{r(t.plainDefaultValue)},[t]),p(s.Box,{sx:{maxWidth:"480px"},children:[i(s.Text,{pb:"md",color:"gray",children:"Preview"}),i(Qo,{filter:t,value:n,onChange:r}),i(s.Text,{pt:"lg",pb:"md",color:"gray",children:"Config"}),i(kt.Prism,{language:"json",colorScheme:"dark",noCopy:!0,children:JSON.stringify(t,null,4)})]})}),nk={select:X_,"multi-select":U_,"tree-select":ek,"text-input":J_,checkbox:R_,"date-range":Q_},rk=[{label:"Select",value:"select"},{label:"Multi Select",value:"multi-select"},{label:"Tree Select",value:"tree-select"},{label:"Text Input",value:"text-input"},{label:"Checkbox",value:"checkbox"},{label:"Date Range",value:"date-range"}],ik=k.observer(function({filter:t}){const n=le(),r=y.useMemo(()=>nk[t.type],[t.type]);return p(s.Group,{grow:!0,spacing:20,align:"top",children:[p(s.Box,{sx:{maxWidth:"600px"},children:[i(s.Text,{pb:"md",color:"gray",children:"Edit"}),p(s.Stack,{children:[p(s.Group,{noWrap:!0,children:[i(s.NumberInput,{label:"Placement Order",required:!0,value:t.order,onChange:t.setOrder,hideControls:!0,sx:{flexGrow:"1 !important"}}),t.auto_submit_supported&&i(s.Checkbox,{label:"Submit automatically",checked:t.auto_submit,onChange:a=>t.setAutoSubmit(a.currentTarget.checked),mt:22})]}),i(s.MultiSelect,{label:"Visible in...",data:n.views.options,value:[...t.visibleInViewsIDs],onChange:t.setVisibleInViewsIDs}),i(s.TextInput,{label:"Key",placeholder:"A unique key to refer",required:!0,value:t.key,onChange:a=>{t.setKey(a.currentTarget.value)}}),i(s.TextInput,{label:"Label",placeholder:"Label for this field",required:!0,value:t.label,onChange:a=>{t.setLabel(a.currentTarget.value)}}),i(s.Select,{label:"Widget",data:rk,required:!0,value:t.type,onChange:t.setType}),i(r,{config:t.config})]})]}),i(tk,{filter:t})]})}),ak=k.observer(({id:e})=>{const t=et.useModals(),n=ye(),r=le();if(e==="")return null;const a=r.filters.findByID(e);if(!a)return p(s.Text,{size:14,children:["Filter by ID[",e,"] is not found"]});const o=()=>{n.editor.setPath(["_FILTERS_",""])},l=()=>{t.openConfirmModal({title:"Delete this filter?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>{r.filters.removeByID(e),o()},confirmProps:{color:"red"},zIndex:320})};return p(s.Stack,{sx:{maxWidth:"1100px",height:"100vh"},spacing:"sm",pb:30,children:[i(s.Group,{position:"right",pt:10,children:i(s.Button,{size:"xs",color:"red",leftIcon:i(T.Trash,{size:16}),onClick:l,children:"Delete this filter"})}),i(s.Box,{sx:{flexGrow:1,maxHeight:"calc(100% - 52px)",overflow:"auto"},children:i(ik,{filter:a})})]})}),sk=k.observer(()=>{const e=le(),[t,n]=y.useState(()=>JSON.stringify(e.mock_context.current,null,4)),r=()=>{try{e.mock_context.replace(JSON.parse(t))}catch(o){bn.showNotification({title:"Failed",message:o.message,color:"red"})}},a=y.useMemo(()=>{try{return JSON.stringify(JSON.parse(t))!==JSON.stringify(e.mock_context.current)}catch{return!1}},[t,e.mock_context.current]);return p(s.Stack,{sx:{border:"1px solid #eee",borderLeft:"none",borderRight:"none",flexGrow:1,maxWidth:"unset"},children:[i(s.Group,{position:"left",pl:"md",py:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef",flexGrow:0},children:i(s.Text,{weight:500,children:"Mock Context"})}),p(s.Group,{grow:!0,px:"md",pb:"md",pt:0,sx:{flexGrow:1,position:"relative",alignItems:"flex-start"},children:[p(s.Stack,{spacing:10,sx:{maxWidth:"unset !important"},children:[i(s.Text,{children:"A valid json string is required"}),i(s.JsonInput,{validationError:"Invalid json",formatOnBlur:!0,autosize:!0,minRows:30,value:t,onChange:n,sx:{flexGrow:1}})]}),i(s.ActionIcon,{mr:5,variant:"filled",color:"blue",sx:{position:"absolute",right:12,top:0},disabled:!a,onClick:r,children:i(T.DeviceFloppy,{size:20})})]})]})}),ok=k.observer(()=>{const{panel:e}=nt();return i(oi,{label:"Description",value:e.description,onChange:e.setDescription,styles:{root:{flexGrow:1}}})}),lk=k.observer(()=>{const{panel:e}=nt(),{style:t}=e;return i(P,{children:i(s.Switch,{label:"Border",checked:t.border.enabled,onChange:n=>t.border.setEnabled(n.currentTarget.checked)})})}),uk=k.observer(()=>{const{panel:e}=nt(),{title:t,setTitle:n}=e,[r,a]=Me.useInputState(t),o=t!==r,l=y.useCallback(()=>{o&&n(r)},[o,r]);return y.useEffect(()=>{a(t)},[t]),i(s.TextInput,{value:r,onChange:a,label:p(s.Group,{children:[i(s.Text,{children:"Panel Title"}),i(s.ActionIcon,{variant:"subtle",color:"blue",disabled:!o,onClick:l,children:i(T.DeviceFloppy,{size:20})})]}),styles:{label:{display:"block",paddingBottom:"4px"}}})});function ck(){return p(s.Stack,{sx:{height:"100%"},children:[i(s.Divider,{label:"Style",labelPosition:"center",variant:"dashed"}),i(lk,{}),i(s.Divider,{label:"Info",labelPosition:"center",variant:"dashed"}),i(uk,{}),i(ok,{})]})}const dk={width:"fit-content",minWidth:"100%",tableLayout:"fixed",tr:{width:"fit-content"},th:{position:"relative"},"th, td":{wordBreak:"break-word"},".resizer":{position:"absolute",right:0,top:"50%",transform:"translateY(-50%)",cursor:"col-resize",userSelect:"none",touchAction:"none"},".resizer.isResizing":{color:"#228be6",opacity:"1"},"@media (hover: hover)":{".resizer":{opacity:"0"},"*:hover > .resizer":{color:"#228be6",opacity:"1"}}};function iu({data:e}){const t=y.useMemo(()=>{if(!Array.isArray(e)||e.length===0)return[];const r=tt.createColumnHelper();return Object.keys(e[0]).map(a=>r.accessor(a,{cell:o=>o.getValue()}))},[e]),n=tt.useReactTable({data:e,columns:t,columnResizeMode:"onChange",getCoreRowModel:tt.getCoreRowModel()});return e.length===0?i(s.Box,{sx:{height:"5em"}}):i(Fe,{children:p(s.Table,{sx:dk,children:[i("thead",{children:n.getHeaderGroups().map(r=>i("tr",{children:r.headers.map(a=>p("th",{style:{width:a.getSize()},children:[a.isPlaceholder?null:tt.flexRender(a.column.columnDef.header,a.getContext()),i(s.ActionIcon,{onMouseDown:a.getResizeHandler(),onTouchStart:a.getResizeHandler(),className:`resizer ${a.column.getIsResizing()?"isResizing":""}`,children:i(T.ArrowBarToRight,{})})]},a.id))},r.id))}),i("tbody",{children:n.getRowModel().rows.map(r=>i("tr",{children:r.getVisibleCells().map(a=>i("td",{children:i(Fe,{children:tt.flexRender(a.column.columnDef.cell,a.getContext())})},a.id))},r.id))})]})})}const pk=({queryID:e})=>{const t=we(),{state:n,error:r}=t.getDataStuffByID(e),a=y.useMemo(()=>t.queries.findByID(e),[t,e]);return n==="loading"?null:r?i(s.Text,{color:"red",size:"md",align:"center",sx:{fontFamily:"monospace"},children:r}):a!=null&&a.stateMessage?i(s.Text,{color:"gray",align:"center",children:a.stateMessage}):null},Vi=k.observer(function({id:t,moreActions:n=null}){const r=we(),{data:a,state:o}=r.getDataStuffByID(t),l=o==="loading",u=()=>{r.queries.refetchDataByQueryID(t)},c=()=>{r.queries.downloadDataByQueryID(t)},d=y.useMemo(()=>Array.isArray(a)?a.slice(0,10):[],[a]),f=!Array.isArray(a)||a.length===0;return p(s.Stack,{sx:{border:"1px solid #eee"},children:[p(s.Group,{position:"apart",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[p(s.Group,{position:"left",children:[i(s.Text,{weight:500,children:"Preview Data"}),a.length>10&&p(s.Text,{size:"sm",color:"gray",children:["Showing 10 rows of ",a.length]})]}),p(s.Group,{pr:15,children:[n,i(s.ActionIcon,{variant:"subtle",color:"blue",disabled:l,onClick:u,children:i(T.Refresh,{size:16})}),i(s.ActionIcon,{variant:"subtle",color:"blue",disabled:l||f,onClick:c,children:i(T.Download,{size:16})})]})]}),p(s.Box,{sx:{position:"relative",overflow:"auto"},children:[i(s.LoadingOverlay,{visible:l}),i(pk,{queryID:t}),i(iu,{data:d})]})]})}),hk=k.observer(function(){const t=ye(),n=le(),{panel:r}=nt(),[a,o]=y.useState(!1),l=u=>{t.editor.setPath(["_QUERIES_",u])};return p(P,{children:[i(s.Drawer,{opened:a,onClose:()=>o(!1),title:"Choose queries",padding:"xl",size:500,zIndex:320,children:i(s.Checkbox.Group,{value:[...r.queryIDs],onChange:r.setQueryIDs,children:i(s.Stack,{spacing:"lg",children:n.queries.options.map(u=>i(s.Checkbox,{label:u.label,value:u.value},u.value))})})}),p(s.Stack,{spacing:6,children:[i(s.Group,{position:"right",children:i(s.Button,{variant:"light",size:"sm",leftIcon:i($.IconLine,{size:16}),onClick:()=>o(!0),children:"Click me to choose queries for this panel"})}),r.queryIDs.length===1&&i(Vi,{id:r.queryIDs[0],moreActions:i(s.Tooltip,{label:"Open this query",children:i(s.ActionIcon,{variant:"subtle",color:"blue",onClick:()=>l(r.queryIDs[0]),children:i($.IconArrowCurveRight,{size:16})})})}),r.queryIDs.length>1&&p(s.Tabs,{defaultValue:r.queryIDs[0],children:[i(s.Tabs.List,{children:r.queries.map(u=>i(s.Tabs.Tab,{value:u.id,children:u.name},u.id))}),r.queries.map(u=>i(s.Tabs.Panel,{value:u.id,children:i(Vi,{id:u.id,moreActions:i(s.Tooltip,{label:"Open this query",children:i(s.ActionIcon,{variant:"subtle",color:"blue",onClick:()=>l(u.id),children:i($.IconArrowCurveRight,{size:16})})})})},u.id))]})]})]})}),fk=k.observer(()=>{const{panel:e}=bt();return i(Fe,{children:i(s.Box,{sx:{height:"100%",flexGrow:0,flexShrink:0,width:"600px"},children:p(s.Stack,{mt:24,spacing:5,sx:{width:"600px",height:"450px",background:"transparent",borderRadius:"5px",border:"1px solid #e9ecef",borderWidth:e.style.border.enabled?"1px":"0px"},children:[p(s.Group,{position:"apart",noWrap:!0,sx:{flexGrow:0,flexShrink:0},children:[i(s.Group,{children:i(Mi,{})}),i(s.Group,{grow:!0,position:"center",children:i(s.Text,{lineClamp:1,weight:"bold",children:e.title})}),i(s.Group,{position:"right",spacing:0,sx:{height:"28px"}})]}),i(s.Group,{px:5,pb:5,sx:{flexGrow:1},children:i(Ii,{panel:e,height:"410px"})})]})})})}),Ni={name:"new_var",size:"1rem",weight:"initial",color:{type:"static",staticColor:"Red"},data_field:"",aggregation:{type:"sum",config:{}},formatter:{output:"number",mantissa:0,trimMantissa:!1,average:!1}};class gk{constructor(t){q(this,"panel");q(this,"selected");this.panel=t,re.makeAutoObservable(this,{},{deep:!1,autoBind:!0})}get variables(){return this.panel.variables}addNew(){const t=this.panel.variables.filter(n=>n.name.startsWith(Ni.name)).length;this.panel.addVariable(x.cloneDeep({...Ni,name:`${Ni.name}${t||""}`})),this.selected=x.last(this.panel.variables)}select(t){this.selected=t}remove(t){this.selected===t&&(this.selected=void 0);const n=this.panel.variables.indexOf(t);if(this.panel.removeVariable(t),!this.selected&&!x.isEmpty(this.panel.variables)){const r=Math.min(this.panel.variables.length-1,n);this.selected=this.panel.variables[r]}}}function mk(){const{panel:e}=nt();return U.useCreation(()=>new gk(e),[e])}const au=s.createStyles(e=>({root:{height:"100%",overflow:"hidden",".var-list-container":{"& > *":{height:"100%"},width:250,height:"100%"},".var-list-actions":{height:"fit-content",flexShrink:0,width:"100%"},".var-list":{flex:"1 1 auto",overflow:"auto",minHeight:0,"& > *":{flex:"0 0 auto"}}},config:{height:"100%",overflow:"auto",paddingRight:10}})),yk=y.forwardRef(function({value:t,onChange:n,data:r,withStyle:a=!0},o){const l=(u,c)=>{const d=x.cloneDeep(t);x.set(d,u,c),n(d)};return p(s.Box,{px:"sm",py:"md",ref:o,children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(s.TextInput,{label:"Name",required:!0,value:t.name,onChange:u=>l("name",u.currentTarget.value)}),i(W,{label:"Data Field",required:!0,value:t.data_field,onChange:u=>l("data_field",u)})]}),i(Fn,{label:"Aggregation",value:t.aggregation,onChange:u=>l("aggregation",u)}),t.aggregation.type!=="custom"&&p(P,{children:[i(s.Divider,{my:"xs",label:"Format",labelPosition:"center"}),i(We,{value:t.formatter,onChange:u=>l("formatter",u)})]}),a&&i(Qs,{value:t,onChange:n})]})}),bk=e=>{const{uiModel:t}=e;return i(s.Stack,{className:"var-list",children:t.variables.map(n=>i(s.Button,{variant:t.selected===n?"filled":"subtle",color:"gray",onClick:()=>t.select(n),children:n.name},n.name))})},vk=k.observer(bk),xk=({variable:e,data:t})=>i(s.Group,{style:{minHeight:0,height:"calc(100% - 68px)"},children:i(s.Paper,{withBorder:!0,p:"md",children:Ks(e,t)})}),wk=k.observer(xk),Ck=e=>{const t=U.useCreation(()=>vS(e.variable),[e.variable]),{classes:n}=au(),{data:r}=nt();return p(s.Group,{style:{height:"100%"},align:"start",children:[p(s.Stack,{"data-testid":"variable-editor",align:"stretch",className:n.config,children:[p(s.Group,{position:"right",children:[i(s.ActionIcon,{variant:"filled",disabled:!t.changed,color:"primary",onClick:t.commit,children:i($.IconDeviceFloppy,{size:18})}),i(s.ActionIcon,{color:"red",onClick:()=>e.uiModel.remove(e.variable),children:i($.IconTrash,{size:18})})]}),i(yk,{value:b.getSnapshot(t.copy),onChange:t.update,data:r})]}),i(wk,{variable:b.getSnapshot(t.copy),data:r})]})},Sk=k.observer(Ck),_k=()=>{const e=mk(),{classes:t}=au();return p(s.Group,{className:t.root,noWrap:!0,align:"start",children:[i(s.Paper,{withBorder:!0,p:"md",className:"var-list-container",children:p(s.Stack,{justify:"space-between",children:[i(s.Box,{className:"var-list-actions",children:i(s.Button,{variant:"light",size:"sm",onClick:e.addNew,fullWidth:!0,children:"Add Variable"})}),i(vk,{uiModel:e})]})}),e.selected?i(P,{children:i(Sk,{uiModel:e,variable:e.selected})}):i("span",{children:"Select or create a new variable on right side"})]})},kk=k.observer(_k);function Tk(){const{vizManager:e}=y.useContext(ut);return y.useMemo(()=>{const t=e.availableVizList.map(n=>({value:n.name,label:n.displayName??n.name,group:n.displayGroup??""}));return x.orderBy(t,[n=>n.group,n=>n.label],["asc","asc"])},[e])}const Dk=k.observer(({value:e,submit:t})=>{const[n,r]=Me.useInputState(e);y.useEffect(()=>{r(e)},[e]);const a=Tk(),o=e!==n;return i(s.Select,{label:"Visualization",value:n,searchable:!0,onChange:r,data:a,rightSection:i(s.ActionIcon,{disabled:!o,onClick:()=>t(n),children:i(T.DeviceFloppy,{size:20})}),maxDropdownHeight:600})}),su=[];function Mk(e,t){try{return e.resolveComponent(t).createConfig()}catch{return null}}function Ik(){const{data:e,panel:{variables:t,viz:n,title:r,queryIDs:a,description:o,setDescription:l,setTitle:u,addQueryID:c,removeQueryID:d,id:f}}=nt(),{vizManager:h}=y.useContext(ut),g={title:r,description:o,viz:n,queryIDs:a,id:f},m={setDescription:l,addQueryID:c,removeQueryID:d,setTitle:u},C=Tl(g);try{return h.resolveComponent(g.viz.type),i(Hn,{configure:C,children:i(kS,{variables:t,setVizConf:n.setConf,panel:g,panelInfoEditor:m,vizManager:h,data:e})})}catch(w){return console.info(x.get(w,"message")),null}}const Ak=k.observer(()=>{const{data:e,panel:{viz:t}}=nt(),{vizManager:n}=y.useContext(ut),r=y.useCallback(d=>{if(d===t.type)return;const f=Mk(n,d);t.setType(d),t.setConf(f||{})},[t.type]),a=d=>{try{t.setConf(JSON.parse(d))}catch(f){console.error(f)}},o=y.useMemo(()=>{var d;return(d=su.find(f=>f.value===t.type))==null?void 0:d.Panel},[t.type,su]),l=Ik(),u=o?y.createElement(o,{data:e,conf:t.conf,setConf:t.setConf}):null,c=l||u;return p(s.Stack,{align:"stretch",sx:{height:"100%",overflow:"hidden"},children:[i(Dk,{submit:r,value:t.type}),p(Fe,{children:[i(s.Stack,{pb:10,sx:{flexGrow:1,maxHeight:"100%",overflow:"auto"},children:c}),!c&&i(s.JsonInput,{minRows:20,label:"Config",value:JSON.stringify(t.conf,null,2),onChange:a})]})]})}),zk=k.observer(({panel:e,sourceViewID:t})=>{const n=le(),[r,a]=y.useState(t);y.useEffect(()=>{a(t)},[t]);const[o,{open:l,close:u}]=Me.useDisclosure(!1),c=()=>{e.moveToView(t,r),u()};return p(P,{children:[i(s.Button,{size:"xs",variant:"subtle",color:"blue",onClick:l,leftIcon:i($.IconBoxMultiple,{size:14}),children:"Move into Another View"}),i(s.Modal,{opened:o,onClose:u,title:"Move panel into another view",zIndex:320,children:p(s.Stack,{sx:{maxHeight:"calc(100vh - 185px)",overflow:"hidden"},children:[i(s.Radio.Group,{value:r,onChange:a,pb:10,sx:{flexGrow:1,maxHeight:"calc(100vh - 185px - 30px)",overflow:"auto"},children:i(s.Stack,{spacing:"xs",children:n.views.options.map(d=>i(s.Radio,{value:d.value,label:d.label},d.value))})}),p(s.Group,{noWrap:!0,position:"apart",sx:{flexGrow:0,flexShrink:0},children:[i(s.Button,{size:"xs",color:"red",leftIcon:i($.IconX,{size:14}),onClick:u,children:"Cancel"}),i(s.Button,{size:"xs",color:"blue",leftIcon:i($.IconDeviceFloppy,{size:14}),onClick:c,disabled:r===t,children:"Confirm"})]})]})})]})}),Ek={root:{flexGrow:1,width:"100%",overflow:"hidden"},panel:{width:"100%",height:"calc(100% - 44px)",padding:10,overflow:"scroll"}},ou=({children:e})=>p(s.Group,{noWrap:!0,grow:!0,position:"left",spacing:20,sx:{width:"100%",height:"100%"},children:[i(s.Box,{sx:{maxWidth:"calc(100% - 610px - 10px)",height:"100%",overflow:"auto"},children:e}),i(fk,{})]});function $k(e){return!["richText","button"].includes(e)}const Lk=k.observer(({panel:e})=>{const t=et.useModals(),n=ye(),r=le(),[a,o]=y.useState("Data"),l=e.queries,c=$k(e.viz.type)&&e.dataLoading,d=c||e.queryErrors.length>0||e.queryStateMessages!==""||l.length===0,f=n.editor.path[1];y.useEffect(()=>{o(m=>d&&m==="Visualization"?"Data":m)},[e.id,d]);const h=()=>{n.editor.setPath(["_VIEWS_",f])},g=()=>t.openConfirmModal({title:"Delete this panel?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>{r.removePanelByID(e.id,f),h()},confirmProps:{color:"red"},zIndex:320});return p(Sr,{value:{panel:e,data:e.data,loading:c,errors:e.queryErrors,downloadPanelScreenshot:()=>{}},children:[p(s.Group,{px:16,position:"apart",sx:{borderBottom:"1px solid #eee"},children:[p(s.Text,{pt:9,pb:8,children:[e.title?e.title:e.viz.type," "]}),p(s.Group,{position:"right",noWrap:!0,children:[i(zk,{panel:e,sourceViewID:f}),i(s.Button,{size:"xs",variant:"subtle",color:"red",onClick:g,leftIcon:i($.IconTrash,{size:14}),children:"Delete This Panel"})]})]}),p(s.Tabs,{value:a,onTabChange:o,keepMounted:!1,styles:Ek,children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"Data",disabled:c,children:"Data"}),i(s.Tabs.Tab,{value:"Panel",children:"Panel"}),i(s.Tabs.Tab,{value:"Variables",disabled:d,children:i(s.Tooltip,{label:"Requires data",disabled:!d,withinPortal:!0,zIndex:310,children:i(s.Text,{children:"Variables"})})}),i(s.Tabs.Tab,{value:"Visualization",disabled:d,children:i(s.Tooltip,{label:"Requires data",disabled:!d,withinPortal:!0,zIndex:310,children:i(s.Text,{children:"Visualization"})})}),i(s.Tabs.Tab,{value:"Interactions",children:"Interactions"})]}),p(s.Tabs.Panel,{value:"Data",children:[i(s.LoadingOverlay,{visible:c,exitTransitionDuration:0}),i(hk,{})]}),i(s.Tabs.Panel,{value:"Panel",children:i(ou,{children:i(ck,{})})}),i(s.Tabs.Panel,{value:"Variables",children:i(kk,{})}),i(s.Tabs.Panel,{value:"Visualization",children:i(Fe,{children:i(ou,{children:i(Ak,{})})})}),i(s.Tabs.Panel,{value:"Interactions",children:i(Fe,{children:i(dd,{})})})]})]})}),Ok=k.observer(({viewID:e,panelID:t})=>{const n=le();if(!n.views.findByID(e))return p(s.Text,{size:14,children:["View by ID[",e,"] is not found"]});const a=n.panels.findByID(t);return a?i(Lk,{panel:a}):p(s.Text,{size:14,children:["Panel by ID[",t,"] is not found"]})}),Pk=e=>{const{queryModel:t}=e,n=ye(),r=le(),o=r.findQueryUsage(t.id).length>0,l=et.useModals(),u=()=>{l.openConfirmModal({title:"Delete this query?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>{r.queries.removeQuery(t.id),n.editor.setPath(["_QUERIES_",""])},confirmProps:{color:"red"},zIndex:320})};return o?i(s.Tooltip,{label:"Can't delete this query for it's being used, check out Usage tab for details",withArrow:!0,events:{hover:!0,focus:!1,touch:!1},withinPortal:!0,children:i(s.Button,{color:"gray",size:"xs",leftIcon:i($.IconTrash,{size:16}),sx:{alignSelf:"flex-end"},children:"Delete this Query"})}):i(s.Button,{color:"red",size:"xs",onClick:u,leftIcon:i($.IconTrash,{size:16}),sx:{alignSelf:"flex-end"},children:"Delete this Query"})},Bk=k.observer(Pk),lu=({width:e="calc(100% - 32px)",lastWidth:t="50%",height:n,count:r,spacing:a=16,pl:o=0})=>p(s.Stack,{spacing:a,mt:6,pl:o,children:[Array.from(new Array(r-1),(l,u)=>i(s.Skeleton,{width:e,height:n,radius:"xs"},u)),i(s.Skeleton,{width:t,height:n,radius:"xs"})]}),pn=({value:e})=>e===null||e===""?null:i(s.Tooltip,{label:e,disabled:!e,multiline:!0,children:i(s.ActionIcon,{children:i($.IconInfoCircle,{size:14})})}),Vk=({column:e})=>{const{column_key:t,column_key_text:n}=e;return t?i(s.Tooltip,{label:n,disabled:!n,children:i(s.Badge,{children:t})}):null},Nk=k.observer(({dataSource:e})=>{const{columns:t}=e;return t.loading?i(lu,{height:"24px",width:"100%",lastWidth:"100%",count:20,pl:6}):t.empty?null:p(s.Table,{highlightOnHover:!0,fontSize:14,sx:{width:"auto",minWidth:"1000px",alignSelf:"flex-start",flexGrow:0,tableLayout:"fixed",tbody:{fontFamily:"monospace"}},children:[p("colgroup",{children:[i("col",{style:{width:50}}),i("col",{style:{minWidth:300}}),i("col",{style:{width:30}}),i("col",{style:{width:70}}),i("col",{style:{minWidth:300}}),i("col",{style:{minWidth:80,width:80}}),i("col",{style:{minWidth:120,width:120}})]}),i("thead",{children:p("tr",{children:[i("th",{children:"#"}),i("th",{children:"Column Name"}),i("th",{}),i("th",{}),i("th",{children:"Type"}),i("th",{children:"Nullable"}),i("th",{children:"Default Value"})]})}),i("tbody",{children:t.data.map(n=>p("tr",{children:[i("td",{children:n.ordinal_position}),i("td",{children:n.column_name}),i("td",{children:i(pn,{value:n.column_comment})}),i("td",{children:i(Vk,{column:n})}),i("td",{children:n.column_type}),i("td",{children:n.is_nullable}),i("td",{children:i(pn,{value:n.column_default})})]},n.column_name))})]})}),qk=k.observer(({dataSource:e})=>{const{indexes:t}=e,n=t.data;return p(s.Table,{highlightOnHover:!0,fontSize:14,sx:{width:"auto",minWidth:"950px",alignSelf:"flex-start",flexGrow:0,tableLayout:"fixed",tbody:{fontFamily:"monospace"}},children:[p("colgroup",{children:[i("col",{style:{width:100}}),i("col",{style:{minWidth:300}}),i("col",{style:{width:150}}),i("col",{style:{width:150}}),i("col",{style:{width:250}})]}),i("thead",{children:p("tr",{children:[i("th",{children:"Index Length"}),i("th",{children:"Index Name"}),i("th",{children:"Index Algorithm"}),i("th",{children:"Unique"}),i("th",{children:"Column Name"})]})}),i("tbody",{children:n.map(r=>p("tr",{children:[i("td",{children:r.index_length}),i("td",{children:r.index_name}),i("td",{children:r.index_algorithm}),i("td",{children:r.is_unique?"YES":"NO"}),i("td",{children:r.column_name})]},r.index_name))})]})}),Fk=k.observer(({dataSource:e})=>{const{indexes:t}=e,n=t.data;return p(s.Table,{highlightOnHover:!0,fontSize:14,sx:{width:"auto",minWidth:"850px",alignSelf:"flex-start",flexGrow:0,tableLayout:"fixed",tbody:{fontFamily:"monospace"}},children:[p("colgroup",{children:[i("col",{style:{minWidth:300}}),i("col",{style:{width:150}}),i("col",{style:{width:100}}),i("col",{style:{width:100}}),i("col",{style:{width:100}}),i("col",{style:{width:100}})]}),i("thead",{children:p("tr",{children:[i("th",{children:"Index Name"}),i("th",{children:"Index Algorithm"}),i("th",{children:"Unique"}),i("th",{children:"Definition"}),i("th",{children:"Condition"}),i("th",{children:"Comment"})]})}),i("tbody",{children:n.map(r=>p("tr",{children:[i("td",{children:r.index_name}),i("td",{children:r.index_algorithm}),i("td",{children:r.is_unique?"YES":"NO"}),i("td",{children:i(pn,{value:r.index_definition})}),i("td",{children:i(pn,{value:r.condition})}),i("td",{children:i(pn,{value:r.comment})})]},r.index_name))})]})}),Gk=k.observer(({dataSource:e})=>{const{indexes:t}=e;return t.loading||t.empty?null:e.type===Se.MySQL?i(qk,{dataSource:e}):e.type===Se.Postgresql?i(Fk,{dataSource:e}):null}),Wk=k.observer(({dataSource:e})=>p(s.Stack,{spacing:40,pt:10,sx:{flexGrow:1,overflow:"auto",position:"relative"},children:[i(Fe,{children:i(Nk,{dataSource:e})}),i(Fe,{children:i(Gk,{dataSource:e})})]}));function jk({table_type:e}){return e==="VIEW"?i($.IconEye,{size:14}):e==="BASE TABLE"?i($.IconTable,{size:14}):null}const Rk=k.observer(({dataSource:e})=>{const{tables:t}=e;return t.loading?i(lu,{height:"24px",lastWidth:"50%",count:15}):i(s.Box,{h:"100%",sx:{overflow:"auto",".mantine-NavLink-label":{fontFamily:"monospace"}},children:Object.entries(t.data).map(([n,r])=>i(s.NavLink,{label:n,icon:i($.IconDatabase,{size:14}),defaultOpened:e.table_schema===n,pl:0,childrenOffset:14,children:r.map(a=>i(s.NavLink,{label:a.table_name,icon:i(jk,{table_type:a.table_type}),onClick:()=>{e.setKeywords(n,a.table_name)},active:e.table_name===a.table_name},a.table_name))},n))})}),Yk=({visible:e})=>i(s.Box,{py:10,sx:{width:"100%",height:"100%",overflow:"hidden",position:"relative"},children:i(s.LoadingOverlay,{visible:e})}),Qk=[{label:"10",value:"10"},{label:"20",value:"20"},{label:"50",value:"50"},{label:"100",value:"100"}],Kk={icon:{width:"50px",textAlign:"center"},input:{"&[data-with-icon]":{paddingLeft:"50px"}}},Uk=k.observer(({dataSource:e})=>{const{tableData:t}=e;return p(s.Group,{pt:10,px:10,position:"apart",children:[p(s.Group,{position:"left",children:[t.maxPage>1&&i(s.Pagination,{size:"sm",value:t.page,onChange:t.setPage,total:t.maxPage,withEdges:t.maxPage>7,styles:{control:{height:"30px"}}}),i(s.Select,{icon:i(s.Text,{ta:"center",color:"dimmed",size:14,children:"Limit"}),size:"xs",styles:Kk,data:Qk,value:String(t.limit),onChange:n=>t.setLimit(Number(n))})]}),i(s.Group,{position:"right",children:p(s.Text,{color:"dimmed",my:0,size:14,children:["Total ",t.total," rows"]})})]})}),Xk=k.observer(({dataSource:e})=>{const t=e.tableData;return t.maxPage===0?i(s.Text,{mt:20,color:"red",size:"md",align:"center",sx:{fontFamily:"monospace"},children:"This table is empty"}):t.error?i(s.Text,{mt:20,color:"red",size:"md",align:"center",sx:{fontFamily:"monospace"},children:t.error}):t.page===1&&t.loading?i(Yk,{visible:!0}):p(Fe,{children:[i(Uk,{dataSource:e}),p(s.Box,{py:10,sx:{width:"100%",height:"calc(100% - 42px)",overflow:"auto",position:"relative"},children:[i(s.LoadingOverlay,{visible:t.loading,overlayBlur:2}),i(iu,{data:t.data})]})]})}),Jk={root:{flexGrow:1,overflow:"auto",borderLeft:"1px solid #efefef"},tabsList:{borderBottom:"1px solid #efefef"},tab:{minWidth:120}},Zk=k.observer(({dataSource:e})=>(y.useEffect(()=>{e.loadTablesIfEmpty()},[e]),e.tables.error?i(s.Text,{color:"red",size:"md",align:"center",sx:{fontFamily:"monospace"},children:e.tables.error}):p(s.Flex,{sx:{height:"100%"},children:[i(s.Box,{w:300,sx:{flexGrow:0,flexShrink:0,position:"relative"},children:i(Fe,{children:i(Rk,{dataSource:e})})}),p(s.Tabs,{defaultValue:"structure",styles:Jk,children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"structure",icon:i($.IconColumns,{size:14}),children:"Structure"}),i(s.Tabs.Tab,{value:"data",icon:i($.IconDatabase,{size:14}),children:"Data"})]}),i(s.Tabs.Panel,{value:"structure",children:i(Wk,{dataSource:e})}),i(s.Tabs.Panel,{value:"data",sx:{width:"100%",height:"calc(100% - 36px)",overflow:"hidden"},children:i(Xk,{dataSource:e})})]})]}))),Hk={modal:{paddingLeft:"0px !important",paddingRight:"0px !important"},header:{marginBottom:0,padding:"20px 20px 10px",borderBottom:"1px solid #efefef",gap:"20px"},title:{flexGrow:1},body:{padding:"0 0 0 20px"}},uu=k.observer(({dataSource:e,triggerButtonProps:t={}})=>{const[n,r]=y.useState(!1);return e.type==="http"?null:p(P,{children:[i(s.Modal,{opened:n,onClose:()=>r(!1),title:p(s.Group,{position:"apart",sx:{flexGrow:1},children:[i(s.Text,{fw:500,children:"Explorer Data Source"}),p(s.Group,{spacing:7,children:[i(s.Badge,{variant:"gradient",gradient:{from:"indigo",to:"cyan"},children:e.key}),i(s.Badge,{variant:"gradient",gradient:{from:"orange",to:"red"},children:e.type})]})]}),zIndex:320,size:"96vw",styles:Hk,children:i(s.Box,{sx:{height:"calc(100vh - 220px)"},children:i(Zk,{dataSource:e})})}),i(s.Button,{variant:"subtle",onClick:()=>r(!0),px:16,styles:{inner:{justifyContent:"flex-start"}},...t,children:"See Table Structure"})]})}),eT=y.forwardRef(({label:e,type:t,...n},r)=>p(s.Group,{position:"apart",ref:r,...n,children:[i(s.Text,{children:e}),i(s.Text,{children:t})]})),tT=k.observer(({value:e,onChange:t})=>{const n=ye(),{data:r=[],loading:a}=U.useRequest(mr,{refreshDeps:[]},[]),o=y.useMemo(()=>r.map(d=>({label:d.key,value:d.key,type:d.type})),[r]),l=y.useMemo(()=>o.reduce((d,f)=>(d[f.value]=f.type,d),{}),[o]),u=d=>{d!==null&&t({key:d,type:l[d]})},c=y.useMemo(()=>n.datasources.find(e),[n,e]);return i(s.Select,{data:o,label:p(s.Group,{position:"apart",children:[i(s.Box,{children:"Data Source"}),c&&i(uu,{dataSource:c,triggerButtonProps:{compact:!0,size:"xs",px:10}})]}),itemComponent:eT,rightSection:c?i(s.Text,{size:"xs",color:"dimmed",children:c.type}):void 0,rightSectionWidth:85,maxDropdownHeight:280,styles:{root:{flex:1},label:{display:"block"},rightSection:{pointerEvents:"none",justifyContent:"flex-end",paddingRight:"10px",".mantine-Text-root":{userSelect:"none"}}},disabled:a,value:e.key,onChange:u})}),cu=y.forwardRef((e,t)=>{const{label:n,description:r,...a}=e;return i("div",{ref:t,...a,children:p(s.Group,{position:"apart",noWrap:!0,children:[i(s.Text,{children:n}),i(s.Text,{size:"xs",color:"dimmed",children:r})]})})}),nT=k.observer(({queryModel:e})=>{const[t,n]=y.useState(e.name);return y.useEffect(()=>{n(e.name)},[e.name]),i(s.Center,{ml:20,mt:20,sx:{maxWidth:"600px"},children:p(s.Stack,{spacing:10,sx:{width:"100%"},children:[i(s.Divider,{mb:-10,variant:"dashed",label:"Basics",labelPosition:"center"}),i(s.TextInput,{placeholder:"A unique name",label:"Name",required:!0,sx:{flex:1},value:t,onChange:r=>{n(r.currentTarget.value)},rightSection:i(s.ActionIcon,{variant:"filled",color:"blue",size:"sm",onClick:()=>e.setName(t),disabled:t===e.name,children:i($.IconDeviceFloppy,{size:16})}),onBlur:()=>{e.setName(t)}}),i(tT,{value:{type:e.type,key:e.key},onChange:({type:r,key:a})=>{e.setKey(a),e.setType(r)}}),i(s.Divider,{mt:10,mb:-10,variant:"dashed",label:"Conditions",labelPosition:"center"}),i(s.MultiSelect,{label:"Run query when these are truthy",placeholder:"Always run this query on load",data:e.conditionOptions,value:[...e.run_by],onChange:e.setRunBy,itemComponent:cu,maxDropdownHeight:500}),e.typedAsHTTP&&i(s.MultiSelect,{label:"Re-run query when these changed",placeholder:"Leave it empty to never re-run this query",data:e.conditionOptions,value:[...e.react_to],onChange:e.setReactTo,itemComponent:cu,maxDropdownHeight:500}),i(s.Divider,{mt:20,mb:10,variant:"dashed"}),i(Bk,{queryModel:e})]})})});function rT({content:e}){return p(s.HoverCard,{width:"60vw",shadow:"md",children:[i(s.HoverCard.Target,{children:i(s.ActionIcon,{size:16,color:"blue",children:i($.IconEye,{})})}),i(s.HoverCard.Dropdown,{children:i(kt.Prism,{language:"sql",noCopy:!0,withLineNumbers:!0,children:e})})]})}const iT=k.observer(()=>{const t=[...ye().globalSQLSnippets.list];return t.length===0?null:p(s.Table,{horizontalSpacing:"xs",verticalSpacing:"xs",fontSize:"sm",highlightOnHover:!0,children:[i("thead",{children:p("tr",{children:[i("th",{children:"Key"}),i("th",{children:"Value"})]})}),i("tbody",{children:t.map(n=>{const{id:r,content:a}=n;return p("tr",{children:[i("td",{children:r}),i("td",{width:200,children:i(rT,{content:a})})]},r)})})]})}),aT=`
519
+ `,H_=()=>{const[e,t]=y.useState(!1);return p(P,{children:[i(s.Button,{variant:"subtle",compact:!0,onClick:()=>t(n=>!n),children:e?"Close":"Click to see expected data structure"}),i(s.Collapse,{in:e,children:i(kt.Prism,{language:"typescript",noCopy:!0,colorScheme:"dark",children:Z_})})]})},ek=k.observer(function({config:t}){return p(P,{children:[i(s.TextInput,{label:"Min-width",value:t.min_width,onChange:n=>t.setMinWidth(n.currentTarget.value),placeholder:"200px"}),i(s.Divider,{label:"Fetch options from database",labelPosition:"center"}),i(s.NumberInput,{value:t.default_selection_count,onChange:t.setDefaultSelectionCount,label:"Select first N options by default"}),i(Bi,{value:t.options_query_id,onChange:t.setOptionsQueryID}),i(H_,{})]})}),tk=k.observer(function({filter:t}){const[n,r]=y.useState(t.plainDefaultValue);return y.useEffect(()=>{r(t.plainDefaultValue)},[t]),p(s.Box,{sx:{maxWidth:"480px"},children:[i(s.Text,{pb:"md",color:"gray",children:"Preview"}),i(Qo,{filter:t,value:n,onChange:r}),i(s.Text,{pt:"lg",pb:"md",color:"gray",children:"Config"}),i(kt.Prism,{language:"json",colorScheme:"dark",noCopy:!0,children:JSON.stringify(t,null,4)})]})}),nk={select:X_,"multi-select":U_,"tree-select":ek,"text-input":J_,checkbox:R_,"date-range":Q_},rk=[{label:"Select",value:"select"},{label:"Multi Select",value:"multi-select"},{label:"Tree Select",value:"tree-select"},{label:"Text Input",value:"text-input"},{label:"Checkbox",value:"checkbox"},{label:"Date Range",value:"date-range"}],ik=k.observer(function({filter:t}){const n=le(),r=y.useMemo(()=>nk[t.type],[t.type]);return p(s.Group,{grow:!0,spacing:20,align:"top",children:[p(s.Box,{sx:{maxWidth:"600px"},children:[i(s.Text,{pb:"md",color:"gray",children:"Edit"}),p(s.Stack,{children:[p(s.Group,{noWrap:!0,children:[i(s.NumberInput,{label:"Placement Order",required:!0,value:t.order,onChange:t.setOrder,hideControls:!0,sx:{flexGrow:"1 !important"}}),t.auto_submit_supported&&i(s.Checkbox,{label:"Submit automatically",checked:t.auto_submit,onChange:a=>t.setAutoSubmit(a.currentTarget.checked),mt:22})]}),i(s.MultiSelect,{label:"Visible in...",data:n.views.options,value:[...t.visibleInViewsIDs],onChange:t.setVisibleInViewsIDs}),i(s.TextInput,{label:"Key",placeholder:"A unique key to refer",required:!0,value:t.key,onChange:a=>{t.setKey(a.currentTarget.value)}}),i(s.TextInput,{label:"Label",placeholder:"Label for this field",required:!0,value:t.label,onChange:a=>{t.setLabel(a.currentTarget.value)}}),i(s.Select,{label:"Widget",data:rk,required:!0,value:t.type,onChange:t.setType}),i(r,{config:t.config})]})]}),i(tk,{filter:t})]})}),ak=k.observer(({id:e})=>{const t=et.useModals(),n=ye(),r=le();if(e==="")return null;const a=r.filters.findByID(e);if(!a)return p(s.Text,{size:14,children:["Filter by ID[",e,"] is not found"]});const o=()=>{n.editor.setPath(["_FILTERS_",""])},l=()=>{t.openConfirmModal({title:"Delete this filter?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>{r.filters.removeByID(e),o()},confirmProps:{color:"red"},zIndex:320})};return p(s.Stack,{sx:{maxWidth:"1100px",height:"100vh"},spacing:"sm",pb:30,children:[i(s.Group,{position:"right",pt:10,children:i(s.Button,{size:"xs",color:"red",leftIcon:i(T.Trash,{size:16}),onClick:l,children:"Delete this filter"})}),i(s.Box,{sx:{flexGrow:1,maxHeight:"calc(100% - 52px)",overflow:"auto"},children:i(ik,{filter:a})})]})}),sk=k.observer(()=>{const e=le(),[t,n]=y.useState(()=>JSON.stringify(e.mock_context.current,null,4)),r=()=>{try{e.mock_context.replace(JSON.parse(t))}catch(o){bn.showNotification({title:"Failed",message:o.message,color:"red"})}},a=y.useMemo(()=>{try{return JSON.stringify(JSON.parse(t))!==JSON.stringify(e.mock_context.current)}catch{return!1}},[t,e.mock_context.current]);return p(s.Stack,{sx:{border:"1px solid #eee",borderLeft:"none",borderRight:"none",flexGrow:1,maxWidth:"unset"},children:[i(s.Group,{position:"left",pl:"md",py:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef",flexGrow:0},children:i(s.Text,{weight:500,children:"Mock Context"})}),p(s.Group,{grow:!0,px:"md",pb:"md",pt:0,sx:{flexGrow:1,position:"relative",alignItems:"flex-start"},children:[p(s.Stack,{spacing:10,sx:{maxWidth:"unset !important"},children:[i(s.Text,{children:"A valid json string is required"}),i(s.JsonInput,{validationError:"Invalid json",formatOnBlur:!0,autosize:!0,minRows:30,value:t,onChange:n,sx:{flexGrow:1}})]}),i(s.ActionIcon,{mr:5,variant:"filled",color:"blue",sx:{position:"absolute",right:12,top:0},disabled:!a,onClick:r,children:i(T.DeviceFloppy,{size:20})})]})]})}),ok=k.observer(()=>{const{panel:e}=nt();return i(oi,{label:"Description",value:e.description,onChange:e.setDescription,styles:{root:{flexGrow:1}}})}),lk=k.observer(()=>{const{panel:e}=nt(),{style:t}=e;return p(P,{children:[i(s.Divider,{mb:-10,label:"Style",labelPosition:"center",variant:"dashed"}),p(s.Stack,{spacing:20,children:[p(s.Group,{grow:!0,align:"top",children:[i(s.NumberInput,{label:"Width",min:1,max:36,step:1,precision:0,rightSection:i(s.Text,{size:12,children:"of 36 columns"}),styles:{rightSection:{width:"110px"}},value:e.layout.w,onChange:n=>{n&&e.layout.setWidth(n)}}),i(s.NumberInput,{label:"Height",rightSection:i(s.Text,{size:12,children:"px"}),styles:{rightSection:{width:"40px"}},value:e.layout.h,onChange:n=>{n&&e.layout.setHeight(n)}})]}),i(s.Switch,{label:"Border",checked:t.border.enabled,onChange:n=>t.border.setEnabled(n.currentTarget.checked)})]})]})}),uk=k.observer(()=>{const{panel:e}=nt(),{title:t,setTitle:n}=e,[r,a]=Me.useInputState(t),o=t!==r,l=y.useCallback(()=>{o&&n(r)},[o,r]);return y.useEffect(()=>{a(t)},[t]),i(s.TextInput,{value:r,onChange:a,label:p(s.Group,{children:[i(s.Text,{children:"Panel Title"}),i(s.ActionIcon,{variant:"subtle",color:"blue",disabled:!o,onClick:l,children:i(T.DeviceFloppy,{size:20})})]}),styles:{label:{display:"block",paddingBottom:"4px"}}})});function ck(){return p(s.Stack,{sx:{height:"100%"},children:[i(lk,{}),i(s.Divider,{label:"Info",labelPosition:"center",variant:"dashed"}),i(uk,{}),i(ok,{})]})}const dk={width:"fit-content",minWidth:"100%",tableLayout:"fixed",tr:{width:"fit-content"},th:{position:"relative"},"th, td":{wordBreak:"break-word"},".resizer":{position:"absolute",right:0,top:"50%",transform:"translateY(-50%)",cursor:"col-resize",userSelect:"none",touchAction:"none"},".resizer.isResizing":{color:"#228be6",opacity:"1"},"@media (hover: hover)":{".resizer":{opacity:"0"},"*:hover > .resizer":{color:"#228be6",opacity:"1"}}};function iu({data:e}){const t=y.useMemo(()=>{if(!Array.isArray(e)||e.length===0)return[];const r=tt.createColumnHelper();return Object.keys(e[0]).map(a=>r.accessor(a,{cell:o=>o.getValue()}))},[e]),n=tt.useReactTable({data:e,columns:t,columnResizeMode:"onChange",getCoreRowModel:tt.getCoreRowModel()});return e.length===0?i(s.Box,{sx:{height:"5em"}}):i(Fe,{children:p(s.Table,{sx:dk,children:[i("thead",{children:n.getHeaderGroups().map(r=>i("tr",{children:r.headers.map(a=>p("th",{style:{width:a.getSize()},children:[a.isPlaceholder?null:tt.flexRender(a.column.columnDef.header,a.getContext()),i(s.ActionIcon,{onMouseDown:a.getResizeHandler(),onTouchStart:a.getResizeHandler(),className:`resizer ${a.column.getIsResizing()?"isResizing":""}`,children:i(T.ArrowBarToRight,{})})]},a.id))},r.id))}),i("tbody",{children:n.getRowModel().rows.map(r=>i("tr",{children:r.getVisibleCells().map(a=>i("td",{children:i(Fe,{children:tt.flexRender(a.column.columnDef.cell,a.getContext())})},a.id))},r.id))})]})})}const pk=({queryID:e})=>{const t=we(),{state:n,error:r}=t.getDataStuffByID(e),a=y.useMemo(()=>t.queries.findByID(e),[t,e]);return n==="loading"?null:r?i(s.Text,{color:"red",size:"md",align:"center",sx:{fontFamily:"monospace"},children:r}):a!=null&&a.stateMessage?i(s.Text,{color:"gray",align:"center",children:a.stateMessage}):null},Vi=k.observer(function({id:t,moreActions:n=null}){const r=we(),{data:a,state:o}=r.getDataStuffByID(t),l=o==="loading",u=()=>{r.queries.refetchDataByQueryID(t)},c=()=>{r.queries.downloadDataByQueryID(t)},d=y.useMemo(()=>Array.isArray(a)?a.slice(0,10):[],[a]),f=!Array.isArray(a)||a.length===0;return p(s.Stack,{sx:{border:"1px solid #eee"},children:[p(s.Group,{position:"apart",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[p(s.Group,{position:"left",children:[i(s.Text,{weight:500,children:"Preview Data"}),a.length>10&&p(s.Text,{size:"sm",color:"gray",children:["Showing 10 rows of ",a.length]})]}),p(s.Group,{pr:15,children:[n,i(s.ActionIcon,{variant:"subtle",color:"blue",disabled:l,onClick:u,children:i(T.Refresh,{size:16})}),i(s.ActionIcon,{variant:"subtle",color:"blue",disabled:l||f,onClick:c,children:i(T.Download,{size:16})})]})]}),p(s.Box,{sx:{position:"relative",overflow:"auto"},children:[i(s.LoadingOverlay,{visible:l}),i(pk,{queryID:t}),i(iu,{data:d})]})]})}),hk=k.observer(function(){const t=ye(),n=le(),{panel:r}=nt(),[a,o]=y.useState(!1),l=u=>{t.editor.setPath(["_QUERIES_",u])};return p(P,{children:[i(s.Drawer,{opened:a,onClose:()=>o(!1),title:"Choose queries",padding:"xl",size:500,zIndex:320,children:i(s.Checkbox.Group,{value:[...r.queryIDs],onChange:r.setQueryIDs,children:i(s.Stack,{spacing:"lg",children:n.queries.options.map(u=>i(s.Checkbox,{label:u.label,value:u.value},u.value))})})}),p(s.Stack,{spacing:6,children:[i(s.Group,{position:"right",children:i(s.Button,{variant:"light",size:"sm",leftIcon:i($.IconLine,{size:16}),onClick:()=>o(!0),children:"Click me to choose queries for this panel"})}),r.queryIDs.length===1&&i(Vi,{id:r.queryIDs[0],moreActions:i(s.Tooltip,{label:"Open this query",children:i(s.ActionIcon,{variant:"subtle",color:"blue",onClick:()=>l(r.queryIDs[0]),children:i($.IconArrowCurveRight,{size:16})})})}),r.queryIDs.length>1&&p(s.Tabs,{defaultValue:r.queryIDs[0],children:[i(s.Tabs.List,{children:r.queries.map(u=>i(s.Tabs.Tab,{value:u.id,children:u.name},u.id))}),r.queries.map(u=>i(s.Tabs.Panel,{value:u.id,children:i(Vi,{id:u.id,moreActions:i(s.Tooltip,{label:"Open this query",children:i(s.ActionIcon,{variant:"subtle",color:"blue",onClick:()=>l(u.id),children:i($.IconArrowCurveRight,{size:16})})})})},u.id))]})]})]})}),fk=k.observer(()=>{const{panel:e}=bt();return i(Fe,{children:i(s.Box,{sx:{height:"100%",flexGrow:0,flexShrink:0,width:"600px"},children:p(s.Stack,{mt:24,spacing:5,sx:{width:"600px",height:"450px",background:"transparent",borderRadius:"5px",border:"1px solid #e9ecef",borderWidth:e.style.border.enabled?"1px":"0px"},children:[p(s.Group,{position:"apart",noWrap:!0,sx:{flexGrow:0,flexShrink:0},children:[i(s.Group,{children:i(Mi,{})}),i(s.Group,{grow:!0,position:"center",children:i(s.Text,{lineClamp:1,weight:"bold",children:e.title})}),i(s.Group,{position:"right",spacing:0,sx:{height:"28px"}})]}),i(s.Group,{px:5,pb:5,sx:{flexGrow:1},children:i(Ii,{panel:e,height:"410px"})})]})})})}),Ni={name:"new_var",size:"1rem",weight:"initial",color:{type:"static",staticColor:"Red"},data_field:"",aggregation:{type:"sum",config:{}},formatter:{output:"number",mantissa:0,trimMantissa:!1,average:!1}};class gk{constructor(t){q(this,"panel");q(this,"selected");this.panel=t,re.makeAutoObservable(this,{},{deep:!1,autoBind:!0})}get variables(){return this.panel.variables}addNew(){const t=this.panel.variables.filter(n=>n.name.startsWith(Ni.name)).length;this.panel.addVariable(x.cloneDeep({...Ni,name:`${Ni.name}${t||""}`})),this.selected=x.last(this.panel.variables)}select(t){this.selected=t}remove(t){this.selected===t&&(this.selected=void 0);const n=this.panel.variables.indexOf(t);if(this.panel.removeVariable(t),!this.selected&&!x.isEmpty(this.panel.variables)){const r=Math.min(this.panel.variables.length-1,n);this.selected=this.panel.variables[r]}}}function mk(){const{panel:e}=nt();return U.useCreation(()=>new gk(e),[e])}const au=s.createStyles(e=>({root:{height:"100%",overflow:"hidden",".var-list-container":{"& > *":{height:"100%"},width:250,height:"100%"},".var-list-actions":{height:"fit-content",flexShrink:0,width:"100%"},".var-list":{flex:"1 1 auto",overflow:"auto",minHeight:0,"& > *":{flex:"0 0 auto"}}},config:{height:"100%",overflow:"auto",paddingRight:10}})),yk=y.forwardRef(function({value:t,onChange:n,data:r,withStyle:a=!0},o){const l=(u,c)=>{const d=x.cloneDeep(t);x.set(d,u,c),n(d)};return p(s.Box,{px:"sm",py:"md",ref:o,children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(s.TextInput,{label:"Name",required:!0,value:t.name,onChange:u=>l("name",u.currentTarget.value)}),i(W,{label:"Data Field",required:!0,value:t.data_field,onChange:u=>l("data_field",u)})]}),i(Fn,{label:"Aggregation",value:t.aggregation,onChange:u=>l("aggregation",u)}),t.aggregation.type!=="custom"&&p(P,{children:[i(s.Divider,{my:"xs",label:"Format",labelPosition:"center"}),i(We,{value:t.formatter,onChange:u=>l("formatter",u)})]}),a&&i(Qs,{value:t,onChange:n})]})}),bk=e=>{const{uiModel:t}=e;return i(s.Stack,{className:"var-list",children:t.variables.map(n=>i(s.Button,{variant:t.selected===n?"filled":"subtle",color:"gray",onClick:()=>t.select(n),children:n.name},n.name))})},vk=k.observer(bk),xk=({variable:e,data:t})=>i(s.Group,{style:{minHeight:0,height:"calc(100% - 68px)"},children:i(s.Paper,{withBorder:!0,p:"md",children:Ks(e,t)})}),wk=k.observer(xk),Ck=e=>{const t=U.useCreation(()=>vS(e.variable),[e.variable]),{classes:n}=au(),{data:r}=nt();return p(s.Group,{style:{height:"100%"},align:"start",children:[p(s.Stack,{"data-testid":"variable-editor",align:"stretch",className:n.config,children:[p(s.Group,{position:"right",children:[i(s.ActionIcon,{variant:"filled",disabled:!t.changed,color:"primary",onClick:t.commit,children:i($.IconDeviceFloppy,{size:18})}),i(s.ActionIcon,{color:"red",onClick:()=>e.uiModel.remove(e.variable),children:i($.IconTrash,{size:18})})]}),i(yk,{value:b.getSnapshot(t.copy),onChange:t.update,data:r})]}),i(wk,{variable:b.getSnapshot(t.copy),data:r})]})},Sk=k.observer(Ck),_k=()=>{const e=mk(),{classes:t}=au();return p(s.Group,{className:t.root,noWrap:!0,align:"start",children:[i(s.Paper,{withBorder:!0,p:"md",className:"var-list-container",children:p(s.Stack,{justify:"space-between",children:[i(s.Box,{className:"var-list-actions",children:i(s.Button,{variant:"light",size:"sm",onClick:e.addNew,fullWidth:!0,children:"Add Variable"})}),i(vk,{uiModel:e})]})}),e.selected?i(P,{children:i(Sk,{uiModel:e,variable:e.selected})}):i("span",{children:"Select or create a new variable on right side"})]})},kk=k.observer(_k);function Tk(){const{vizManager:e}=y.useContext(ut);return y.useMemo(()=>{const t=e.availableVizList.map(n=>({value:n.name,label:n.displayName??n.name,group:n.displayGroup??""}));return x.orderBy(t,[n=>n.group,n=>n.label],["asc","asc"])},[e])}const Dk=k.observer(({value:e,submit:t})=>{const[n,r]=Me.useInputState(e);y.useEffect(()=>{r(e)},[e]);const a=Tk(),o=e!==n;return i(s.Select,{label:"Visualization",value:n,searchable:!0,onChange:r,data:a,rightSection:i(s.ActionIcon,{disabled:!o,onClick:()=>t(n),children:i(T.DeviceFloppy,{size:20})}),maxDropdownHeight:600})}),su=[];function Mk(e,t){try{return e.resolveComponent(t).createConfig()}catch{return null}}function Ik(){const{data:e,panel:{variables:t,viz:n,title:r,queryIDs:a,description:o,setDescription:l,setTitle:u,addQueryID:c,removeQueryID:d,id:f}}=nt(),{vizManager:h}=y.useContext(ut),g={title:r,description:o,viz:n,queryIDs:a,id:f},m={setDescription:l,addQueryID:c,removeQueryID:d,setTitle:u},C=Tl(g);try{return h.resolveComponent(g.viz.type),i(Hn,{configure:C,children:i(kS,{variables:t,setVizConf:n.setConf,panel:g,panelInfoEditor:m,vizManager:h,data:e})})}catch(w){return console.info(x.get(w,"message")),null}}const Ak=k.observer(()=>{const{data:e,panel:{viz:t}}=nt(),{vizManager:n}=y.useContext(ut),r=y.useCallback(d=>{if(d===t.type)return;const f=Mk(n,d);t.setType(d),t.setConf(f||{})},[t.type]),a=d=>{try{t.setConf(JSON.parse(d))}catch(f){console.error(f)}},o=y.useMemo(()=>{var d;return(d=su.find(f=>f.value===t.type))==null?void 0:d.Panel},[t.type,su]),l=Ik(),u=o?y.createElement(o,{data:e,conf:t.conf,setConf:t.setConf}):null,c=l||u;return p(s.Stack,{align:"stretch",sx:{height:"100%",overflow:"hidden"},children:[i(Dk,{submit:r,value:t.type}),p(Fe,{children:[i(s.Stack,{pb:10,sx:{flexGrow:1,maxHeight:"100%",overflow:"auto"},children:c}),!c&&i(s.JsonInput,{minRows:20,label:"Config",value:JSON.stringify(t.conf,null,2),onChange:a})]})]})}),zk=k.observer(({panel:e,sourceViewID:t})=>{const n=le(),[r,a]=y.useState(t);y.useEffect(()=>{a(t)},[t]);const[o,{open:l,close:u}]=Me.useDisclosure(!1),c=()=>{e.moveToView(t,r),u()};return p(P,{children:[i(s.Button,{size:"xs",variant:"subtle",color:"blue",onClick:l,leftIcon:i($.IconBoxMultiple,{size:14}),children:"Move into Another View"}),i(s.Modal,{opened:o,onClose:u,title:"Move panel into another view",zIndex:320,children:p(s.Stack,{sx:{maxHeight:"calc(100vh - 185px)",overflow:"hidden"},children:[i(s.Radio.Group,{value:r,onChange:a,pb:10,sx:{flexGrow:1,maxHeight:"calc(100vh - 185px - 30px)",overflow:"auto"},children:i(s.Stack,{spacing:"xs",children:n.views.options.map(d=>i(s.Radio,{value:d.value,label:d.label},d.value))})}),p(s.Group,{noWrap:!0,position:"apart",sx:{flexGrow:0,flexShrink:0},children:[i(s.Button,{size:"xs",color:"red",leftIcon:i($.IconX,{size:14}),onClick:u,children:"Cancel"}),i(s.Button,{size:"xs",color:"blue",leftIcon:i($.IconDeviceFloppy,{size:14}),onClick:c,disabled:r===t,children:"Confirm"})]})]})})]})}),Ek={root:{flexGrow:1,width:"100%",overflow:"hidden"},panel:{width:"100%",height:"calc(100% - 44px)",padding:10,overflow:"scroll"}},ou=({children:e})=>p(s.Group,{noWrap:!0,grow:!0,position:"left",spacing:20,sx:{width:"100%",height:"100%"},children:[i(s.Box,{sx:{maxWidth:"calc(100% - 610px - 10px)",height:"100%",overflow:"auto"},children:e}),i(fk,{})]});function $k(e){return!["richText","button"].includes(e)}const Lk=k.observer(({panel:e})=>{const t=et.useModals(),n=ye(),r=le(),[a,o]=y.useState("Data"),l=e.queries,c=$k(e.viz.type)&&e.dataLoading,d=c||e.queryErrors.length>0||e.queryStateMessages!==""||l.length===0,f=n.editor.path[1];y.useEffect(()=>{o(m=>d&&m==="Visualization"?"Data":m)},[e.id,d]);const h=()=>{n.editor.setPath(["_VIEWS_",f])},g=()=>t.openConfirmModal({title:"Delete this panel?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>{r.removePanelByID(e.id,f),h()},confirmProps:{color:"red"},zIndex:320});return p(Sr,{value:{panel:e,data:e.data,loading:c,errors:e.queryErrors,downloadPanelScreenshot:()=>{}},children:[p(s.Group,{px:16,position:"apart",sx:{borderBottom:"1px solid #eee"},children:[p(s.Text,{pt:9,pb:8,children:[e.title?e.title:e.viz.type," "]}),p(s.Group,{position:"right",noWrap:!0,children:[i(zk,{panel:e,sourceViewID:f}),i(s.Button,{size:"xs",variant:"subtle",color:"red",onClick:g,leftIcon:i($.IconTrash,{size:14}),children:"Delete This Panel"})]})]}),p(s.Tabs,{value:a,onTabChange:o,keepMounted:!1,styles:Ek,children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"Data",disabled:c,children:"Data"}),i(s.Tabs.Tab,{value:"Panel",children:"Panel"}),i(s.Tabs.Tab,{value:"Variables",disabled:d,children:i(s.Tooltip,{label:"Requires data",disabled:!d,withinPortal:!0,zIndex:310,children:i(s.Text,{children:"Variables"})})}),i(s.Tabs.Tab,{value:"Visualization",disabled:d,children:i(s.Tooltip,{label:"Requires data",disabled:!d,withinPortal:!0,zIndex:310,children:i(s.Text,{children:"Visualization"})})}),i(s.Tabs.Tab,{value:"Interactions",children:"Interactions"})]}),p(s.Tabs.Panel,{value:"Data",children:[i(s.LoadingOverlay,{visible:c,exitTransitionDuration:0}),i(hk,{})]}),i(s.Tabs.Panel,{value:"Panel",children:i(ou,{children:i(ck,{})})}),i(s.Tabs.Panel,{value:"Variables",children:i(kk,{})}),i(s.Tabs.Panel,{value:"Visualization",children:i(Fe,{children:i(ou,{children:i(Ak,{})})})}),i(s.Tabs.Panel,{value:"Interactions",children:i(Fe,{children:i(dd,{})})})]})]})}),Ok=k.observer(({viewID:e,panelID:t})=>{const n=le();if(!n.views.findByID(e))return p(s.Text,{size:14,children:["View by ID[",e,"] is not found"]});const a=n.panels.findByID(t);return a?i(Lk,{panel:a}):p(s.Text,{size:14,children:["Panel by ID[",t,"] is not found"]})}),Pk=e=>{const{queryModel:t}=e,n=ye(),r=le(),o=r.findQueryUsage(t.id).length>0,l=et.useModals(),u=()=>{l.openConfirmModal({title:"Delete this query?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>{r.queries.removeQuery(t.id),n.editor.setPath(["_QUERIES_",""])},confirmProps:{color:"red"},zIndex:320})};return o?i(s.Tooltip,{label:"Can't delete this query for it's being used, check out Usage tab for details",withArrow:!0,events:{hover:!0,focus:!1,touch:!1},withinPortal:!0,children:i(s.Button,{color:"gray",size:"xs",leftIcon:i($.IconTrash,{size:16}),sx:{alignSelf:"flex-end"},children:"Delete this Query"})}):i(s.Button,{color:"red",size:"xs",onClick:u,leftIcon:i($.IconTrash,{size:16}),sx:{alignSelf:"flex-end"},children:"Delete this Query"})},Bk=k.observer(Pk),lu=({width:e="calc(100% - 32px)",lastWidth:t="50%",height:n,count:r,spacing:a=16,pl:o=0})=>p(s.Stack,{spacing:a,mt:6,pl:o,children:[Array.from(new Array(r-1),(l,u)=>i(s.Skeleton,{width:e,height:n,radius:"xs"},u)),i(s.Skeleton,{width:t,height:n,radius:"xs"})]}),pn=({value:e})=>e===null||e===""?null:i(s.Tooltip,{label:e,disabled:!e,multiline:!0,children:i(s.ActionIcon,{children:i($.IconInfoCircle,{size:14})})}),Vk=({column:e})=>{const{column_key:t,column_key_text:n}=e;return t?i(s.Tooltip,{label:n,disabled:!n,children:i(s.Badge,{children:t})}):null},Nk=k.observer(({dataSource:e})=>{const{columns:t}=e;return t.loading?i(lu,{height:"24px",width:"100%",lastWidth:"100%",count:20,pl:6}):t.empty?null:p(s.Table,{highlightOnHover:!0,fontSize:14,sx:{width:"auto",minWidth:"1000px",alignSelf:"flex-start",flexGrow:0,tableLayout:"fixed",tbody:{fontFamily:"monospace"}},children:[p("colgroup",{children:[i("col",{style:{width:50}}),i("col",{style:{minWidth:300}}),i("col",{style:{width:30}}),i("col",{style:{width:70}}),i("col",{style:{minWidth:300}}),i("col",{style:{minWidth:80,width:80}}),i("col",{style:{minWidth:120,width:120}})]}),i("thead",{children:p("tr",{children:[i("th",{children:"#"}),i("th",{children:"Column Name"}),i("th",{}),i("th",{}),i("th",{children:"Type"}),i("th",{children:"Nullable"}),i("th",{children:"Default Value"})]})}),i("tbody",{children:t.data.map(n=>p("tr",{children:[i("td",{children:n.ordinal_position}),i("td",{children:n.column_name}),i("td",{children:i(pn,{value:n.column_comment})}),i("td",{children:i(Vk,{column:n})}),i("td",{children:n.column_type}),i("td",{children:n.is_nullable}),i("td",{children:i(pn,{value:n.column_default})})]},n.column_name))})]})}),qk=k.observer(({dataSource:e})=>{const{indexes:t}=e,n=t.data;return p(s.Table,{highlightOnHover:!0,fontSize:14,sx:{width:"auto",minWidth:"950px",alignSelf:"flex-start",flexGrow:0,tableLayout:"fixed",tbody:{fontFamily:"monospace"}},children:[p("colgroup",{children:[i("col",{style:{width:100}}),i("col",{style:{minWidth:300}}),i("col",{style:{width:150}}),i("col",{style:{width:150}}),i("col",{style:{width:250}})]}),i("thead",{children:p("tr",{children:[i("th",{children:"Index Length"}),i("th",{children:"Index Name"}),i("th",{children:"Index Algorithm"}),i("th",{children:"Unique"}),i("th",{children:"Column Name"})]})}),i("tbody",{children:n.map(r=>p("tr",{children:[i("td",{children:r.index_length}),i("td",{children:r.index_name}),i("td",{children:r.index_algorithm}),i("td",{children:r.is_unique?"YES":"NO"}),i("td",{children:r.column_name})]},r.index_name))})]})}),Fk=k.observer(({dataSource:e})=>{const{indexes:t}=e,n=t.data;return p(s.Table,{highlightOnHover:!0,fontSize:14,sx:{width:"auto",minWidth:"850px",alignSelf:"flex-start",flexGrow:0,tableLayout:"fixed",tbody:{fontFamily:"monospace"}},children:[p("colgroup",{children:[i("col",{style:{minWidth:300}}),i("col",{style:{width:150}}),i("col",{style:{width:100}}),i("col",{style:{width:100}}),i("col",{style:{width:100}}),i("col",{style:{width:100}})]}),i("thead",{children:p("tr",{children:[i("th",{children:"Index Name"}),i("th",{children:"Index Algorithm"}),i("th",{children:"Unique"}),i("th",{children:"Definition"}),i("th",{children:"Condition"}),i("th",{children:"Comment"})]})}),i("tbody",{children:n.map(r=>p("tr",{children:[i("td",{children:r.index_name}),i("td",{children:r.index_algorithm}),i("td",{children:r.is_unique?"YES":"NO"}),i("td",{children:i(pn,{value:r.index_definition})}),i("td",{children:i(pn,{value:r.condition})}),i("td",{children:i(pn,{value:r.comment})})]},r.index_name))})]})}),Gk=k.observer(({dataSource:e})=>{const{indexes:t}=e;return t.loading||t.empty?null:e.type===Se.MySQL?i(qk,{dataSource:e}):e.type===Se.Postgresql?i(Fk,{dataSource:e}):null}),Wk=k.observer(({dataSource:e})=>p(s.Stack,{spacing:40,pt:10,sx:{flexGrow:1,overflow:"auto",position:"relative"},children:[i(Fe,{children:i(Nk,{dataSource:e})}),i(Fe,{children:i(Gk,{dataSource:e})})]}));function jk({table_type:e}){return e==="VIEW"?i($.IconEye,{size:14}):e==="BASE TABLE"?i($.IconTable,{size:14}):null}const Rk=k.observer(({dataSource:e})=>{const{tables:t}=e;return t.loading?i(lu,{height:"24px",lastWidth:"50%",count:15}):i(s.Box,{h:"100%",sx:{overflow:"auto",".mantine-NavLink-label":{fontFamily:"monospace"}},children:Object.entries(t.data).map(([n,r])=>i(s.NavLink,{label:n,icon:i($.IconDatabase,{size:14}),defaultOpened:e.table_schema===n,pl:0,childrenOffset:14,children:r.map(a=>i(s.NavLink,{label:a.table_name,icon:i(jk,{table_type:a.table_type}),onClick:()=>{e.setKeywords(n,a.table_name)},active:e.table_name===a.table_name},a.table_name))},n))})}),Yk=({visible:e})=>i(s.Box,{py:10,sx:{width:"100%",height:"100%",overflow:"hidden",position:"relative"},children:i(s.LoadingOverlay,{visible:e})}),Qk=[{label:"10",value:"10"},{label:"20",value:"20"},{label:"50",value:"50"},{label:"100",value:"100"}],Kk={icon:{width:"50px",textAlign:"center"},input:{"&[data-with-icon]":{paddingLeft:"50px"}}},Uk=k.observer(({dataSource:e})=>{const{tableData:t}=e;return p(s.Group,{pt:10,px:10,position:"apart",children:[p(s.Group,{position:"left",children:[t.maxPage>1&&i(s.Pagination,{size:"sm",value:t.page,onChange:t.setPage,total:t.maxPage,withEdges:t.maxPage>7,styles:{control:{height:"30px"}}}),i(s.Select,{icon:i(s.Text,{ta:"center",color:"dimmed",size:14,children:"Limit"}),size:"xs",styles:Kk,data:Qk,value:String(t.limit),onChange:n=>t.setLimit(Number(n))})]}),i(s.Group,{position:"right",children:p(s.Text,{color:"dimmed",my:0,size:14,children:["Total ",t.total," rows"]})})]})}),Xk=k.observer(({dataSource:e})=>{const t=e.tableData;return t.maxPage===0?i(s.Text,{mt:20,color:"red",size:"md",align:"center",sx:{fontFamily:"monospace"},children:"This table is empty"}):t.error?i(s.Text,{mt:20,color:"red",size:"md",align:"center",sx:{fontFamily:"monospace"},children:t.error}):t.page===1&&t.loading?i(Yk,{visible:!0}):p(Fe,{children:[i(Uk,{dataSource:e}),p(s.Box,{py:10,sx:{width:"100%",height:"calc(100% - 42px)",overflow:"auto",position:"relative"},children:[i(s.LoadingOverlay,{visible:t.loading,overlayBlur:2}),i(iu,{data:t.data})]})]})}),Jk={root:{flexGrow:1,overflow:"auto",borderLeft:"1px solid #efefef"},tabsList:{borderBottom:"1px solid #efefef"},tab:{minWidth:120}},Zk=k.observer(({dataSource:e})=>(y.useEffect(()=>{e.loadTablesIfEmpty()},[e]),e.tables.error?i(s.Text,{color:"red",size:"md",align:"center",sx:{fontFamily:"monospace"},children:e.tables.error}):p(s.Flex,{sx:{height:"100%"},children:[i(s.Box,{w:300,sx:{flexGrow:0,flexShrink:0,position:"relative"},children:i(Fe,{children:i(Rk,{dataSource:e})})}),p(s.Tabs,{defaultValue:"structure",styles:Jk,children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"structure",icon:i($.IconColumns,{size:14}),children:"Structure"}),i(s.Tabs.Tab,{value:"data",icon:i($.IconDatabase,{size:14}),children:"Data"})]}),i(s.Tabs.Panel,{value:"structure",children:i(Wk,{dataSource:e})}),i(s.Tabs.Panel,{value:"data",sx:{width:"100%",height:"calc(100% - 36px)",overflow:"hidden"},children:i(Xk,{dataSource:e})})]})]}))),Hk={modal:{paddingLeft:"0px !important",paddingRight:"0px !important"},header:{marginBottom:0,padding:"20px 20px 10px",borderBottom:"1px solid #efefef",gap:"20px"},title:{flexGrow:1},body:{padding:"0 0 0 20px"}},uu=k.observer(({dataSource:e,triggerButtonProps:t={}})=>{const[n,r]=y.useState(!1);return e.type==="http"?null:p(P,{children:[i(s.Modal,{opened:n,onClose:()=>r(!1),title:p(s.Group,{position:"apart",sx:{flexGrow:1},children:[i(s.Text,{fw:500,children:"Explorer Data Source"}),p(s.Group,{spacing:7,children:[i(s.Badge,{variant:"gradient",gradient:{from:"indigo",to:"cyan"},children:e.key}),i(s.Badge,{variant:"gradient",gradient:{from:"orange",to:"red"},children:e.type})]})]}),zIndex:320,size:"96vw",styles:Hk,children:i(s.Box,{sx:{height:"calc(100vh - 220px)"},children:i(Zk,{dataSource:e})})}),i(s.Button,{variant:"subtle",onClick:()=>r(!0),px:16,styles:{inner:{justifyContent:"flex-start"}},...t,children:"See Table Structure"})]})}),eT=y.forwardRef(({label:e,type:t,...n},r)=>p(s.Group,{position:"apart",ref:r,...n,children:[i(s.Text,{children:e}),i(s.Text,{children:t})]})),tT=k.observer(({value:e,onChange:t})=>{const n=ye(),{data:r=[],loading:a}=U.useRequest(mr,{refreshDeps:[]},[]),o=y.useMemo(()=>r.map(d=>({label:d.key,value:d.key,type:d.type})),[r]),l=y.useMemo(()=>o.reduce((d,f)=>(d[f.value]=f.type,d),{}),[o]),u=d=>{d!==null&&t({key:d,type:l[d]})},c=y.useMemo(()=>n.datasources.find(e),[n,e]);return i(s.Select,{data:o,label:p(s.Group,{position:"apart",children:[i(s.Box,{children:"Data Source"}),c&&i(uu,{dataSource:c,triggerButtonProps:{compact:!0,size:"xs",px:10}})]}),itemComponent:eT,rightSection:c?i(s.Text,{size:"xs",color:"dimmed",children:c.type}):void 0,rightSectionWidth:85,maxDropdownHeight:280,styles:{root:{flex:1},label:{display:"block"},rightSection:{pointerEvents:"none",justifyContent:"flex-end",paddingRight:"10px",".mantine-Text-root":{userSelect:"none"}}},disabled:a,value:e.key,onChange:u})}),cu=y.forwardRef((e,t)=>{const{label:n,description:r,...a}=e;return i("div",{ref:t,...a,children:p(s.Group,{position:"apart",noWrap:!0,children:[i(s.Text,{children:n}),i(s.Text,{size:"xs",color:"dimmed",children:r})]})})}),nT=k.observer(({queryModel:e})=>{const[t,n]=y.useState(e.name);return y.useEffect(()=>{n(e.name)},[e.name]),i(s.Center,{ml:20,mt:20,sx:{maxWidth:"600px"},children:p(s.Stack,{spacing:10,sx:{width:"100%"},children:[i(s.Divider,{mb:-10,variant:"dashed",label:"Basics",labelPosition:"center"}),i(s.TextInput,{placeholder:"A unique name",label:"Name",required:!0,sx:{flex:1},value:t,onChange:r=>{n(r.currentTarget.value)},rightSection:i(s.ActionIcon,{variant:"filled",color:"blue",size:"sm",onClick:()=>e.setName(t),disabled:t===e.name,children:i($.IconDeviceFloppy,{size:16})}),onBlur:()=>{e.setName(t)}}),i(tT,{value:{type:e.type,key:e.key},onChange:({type:r,key:a})=>{e.setKey(a),e.setType(r)}}),i(s.Divider,{mt:10,mb:-10,variant:"dashed",label:"Conditions",labelPosition:"center"}),i(s.MultiSelect,{label:"Run query when these are truthy",placeholder:"Always run this query on load",data:e.conditionOptions,value:[...e.run_by],onChange:e.setRunBy,itemComponent:cu,maxDropdownHeight:500}),e.typedAsHTTP&&i(s.MultiSelect,{label:"Re-run query when these changed",placeholder:"Leave it empty to never re-run this query",data:e.conditionOptions,value:[...e.react_to],onChange:e.setReactTo,itemComponent:cu,maxDropdownHeight:500}),i(s.Divider,{mt:20,mb:10,variant:"dashed"}),i(Bk,{queryModel:e})]})})});function rT({content:e}){return p(s.HoverCard,{width:"60vw",shadow:"md",children:[i(s.HoverCard.Target,{children:i(s.ActionIcon,{size:16,color:"blue",children:i($.IconEye,{})})}),i(s.HoverCard.Dropdown,{children:i(kt.Prism,{language:"sql",noCopy:!0,withLineNumbers:!0,children:e})})]})}const iT=k.observer(()=>{const t=[...ye().globalSQLSnippets.list];return t.length===0?null:p(s.Table,{horizontalSpacing:"xs",verticalSpacing:"xs",fontSize:"sm",highlightOnHover:!0,children:[i("thead",{children:p("tr",{children:[i("th",{children:"Key"}),i("th",{children:"Value"})]})}),i("tbody",{children:t.map(n=>{const{id:r,content:a}=n;return p("tr",{children:[i("td",{children:r}),i("td",{width:200,children:i(rT,{content:a})})]},r)})})]})}),aT=`
520
520
  -- You may reference query variables in SQL or VizConfig.
521
521
  SELECT *
522
522
  FROM commit