@devtable/dashboard 10.9.5 → 10.9.7

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.
@@ -116,7 +116,7 @@ Check the top-level render call using <`+P+">.")}return z}}function Yl(S,z){{if(
116
116
  SELECT count(*) AS total
117
117
  FROM ${n}.${e}
118
118
  `}})).actions(t=>({setPage(e){t.page=e},resetPage(){t.page=1},setLimit(e){t.limit=e}})).actions(t=>({afterCreate(){b.addDisposer(t,ie.reaction(()=>t.keywordString,t.resetPage,{fireImmediately:!1,delay:0})),b.addDisposer(t,ie.reaction(()=>t.limit,t.resetPage,{fireImmediately:!1,delay:0}))}})),Gu=b.types.model("DataSourceModel",{id:b.types.string,type:b.types.enumeration("DataSourceType",[ye.HTTP,ye.MySQL,ye.Postgresql]),key:b.types.string,config:b.types.frozen(),tables:b.types.optional(qu,{}),columns:b.types.optional(Vu,{}),tableData:b.types.optional(Fu,{}),indexes:b.types.optional(Nu,{}),table_schema:b.types.optional(b.types.string,""),table_name:b.types.optional(b.types.string,"")}).volatile(()=>({controllers:{tables:new AbortController,columns:new AbortController,indexes:new AbortController,tableData:new AbortController}})).actions(t=>({setKeywords(e,n){t.table_schema=e,t.table_name=n}})).actions(t=>({initKeywords(){if(t.tables.empty)return;const e=Object.keys(t.tables.data)[0],n=t.tables.data[e][0].table_name;t.setKeywords(e,n)}})).actions(t=>{const e=b.flow(function*(){var n;(n=t.controllers.tables)==null||n.abort(),t.controllers.tables=new AbortController,t.tables.state="loading";try{const r=yield*b.toGenerator(qe.query(t.controllers.tables.signal)({type:t.type,key:t.key,query:t.tables.sql},{}));t.tables.data=x.groupBy(r,"table_schema"),t.tables.state="idle",t.tables.error=null,t.initKeywords()}catch(r){if(!pt.isCancel(r)){t.tables.data={};const a=x.get(r,"message","unkown error");t.tables.error=x.get(r,"response.data.detail.message",a),t.tables.state="error"}}});return{loadTables:e,loadTablesIfEmpty(){t.tables.empty&&e()},loadColumns:b.flow(function*(){var n;(n=t.controllers.columns)==null||n.abort(),t.controllers.columns=new AbortController,t.columns.state="loading";try{t.columns.data=yield*b.toGenerator(qe.query(t.controllers.columns.signal)({type:t.type,key:t.key,query:t.columns.sql},{})),t.columns.state="idle",t.columns.error=null}catch(r){if(pt.isCancel(r))t.columns.state="idle",t.columns.error=null;else{t.columns.data=[];const a=x.get(r,"message","unkown error");t.columns.error=x.get(r,"response.data.detail.message",a),t.columns.state="error"}}}),loadIndexes:b.flow(function*(){var n;(n=t.controllers.indexes)==null||n.abort(),t.controllers.indexes=new AbortController,t.indexes.state="loading";try{t.indexes.data=yield*b.toGenerator(qe.query(t.controllers.indexes.signal)({type:t.type,key:t.key,query:t.indexes.sql},{})),t.indexes.state="idle",t.indexes.error=null}catch(r){if(pt.isCancel(r))t.indexes.state="idle",t.indexes.error=null;else{t.indexes.data=[];const a=x.get(r,"message","unkown error");t.indexes.error=x.get(r,"response.data.detail.message",a),t.indexes.state="error"}}}),loadTableData:b.flow(function*(){var r;(r=t.controllers.tableData)==null||r.abort(),t.controllers.tableData=new AbortController;const n=t.tableData;n.state="loading";try{n.data=yield*b.toGenerator(qe.query(t.controllers.tableData.signal)({type:t.type,key:t.key,query:n.sql},{}));const[{total:a}]=yield*b.toGenerator(qe.query(t.controllers.tableData.signal)({type:t.type,key:t.key,query:n.countSql},{}));n.total=Number(a),n.state="idle",n.error=null}catch(a){if(pt.isCancel(a))n.state="idle",n.error=null;else{n.data=[];const o=x.get(a,"message","unkown error");n.error=x.get(a,"response.data.detail.message",o),n.state="error"}}})}}).actions(t=>({afterCreate(){b.addDisposer(t,ie.reaction(()=>t.columns.sql,t.loadColumns,{fireImmediately:!1,delay:500}))}})).actions(t=>({afterCreate(){b.addDisposer(t,ie.reaction(()=>t.indexes.sql,t.loadIndexes,{fireImmediately:!1,delay:500})),b.addDisposer(t,ie.reaction(()=>t.tableData.sql,t.loadTableData,{fireImmediately:!1,delay:0}))}})),Wu=b.types.model("DataSourcesModel",{list:b.types.optional(b.types.array(Gu),[])}).views(t=>({find({type:e,key:n}){return t.list.find(r=>r.key===n&&r.type===e)},get options(){return t.list.map(e=>({value:e.key,label:e.key}))}})).actions(t=>({replace(e){t.list.length=0,t.list.push(...e)}}));function bn(t){return{label:t,value:t,_type:"ACTION",_action_type:t,Icon:null,children:null}}function ju(t){switch(t._type){case"GROUP":case"ACTION":return null;case"query_variables":return["_QUERY_VARS_"];case"mock_context":return["_MOCK_CONTEXT_"];case"filter":return["_FILTERS_",t.value];case"sql_snippet":return["_SQL_SNIPPETS_",t.value];case"query":return["_QUERIES_",t.value];case"view":return["_VIEWS_",t.value];case"panel":return t.parentID?["_VIEWS_",t.parentID,"_PANELS_",t.value]:(console.error("[getPathFromOption] parentID is required"),null)}}const Ru=b.types.model("EditorModel",{path:b.types.optional(b.types.frozen(),[]),settings_open:b.types.optional(b.types.boolean,!1)}).views(t=>({get navOptions(){const{content:e}=b.getRoot(t),{filters:n,views:r,sqlSnippets:a,queries:o}=e;return[{label:"Query Variables",value:"_QUERY_VARS_",_type:"query_variables",Icon:L.IconVariable},{label:"Mock Context",value:"_MOCK_CONTEXT_",Icon:L.IconCodeDots,_type:"mock_context"},{label:"Filters",value:"_FILTERS_",Icon:L.IconFilter,children:[...n.options,bn("_Add_A_Filter_")],_type:"GROUP"},{label:"SQL Snippets",value:"_SQL_SNIPPETS_",Icon:L.IconCopy,children:[...a.options,bn("_Add_A_SQL_SNIPPET_")],_type:"GROUP"},{label:"Queries",value:"_QUERIES_",Icon:L.IconDatabase,children:[...o.options,bn("_Add_A_QUERY_")],_type:"GROUP"},{label:"Views",value:"_VIEWS_",Icon:L.IconBoxMultiple,children:[...r.editorOptions,bn("_Add_A_VIEW_")],_type:"GROUP"}]},isOptionActive(e,n){return e.length===0?!1:e[e.length-1]===n.value},isOptionOpened(e){const{path:n}=t;return n.length===0||!e.children||e.children.length===0?!1:n.includes(e.value)}})).actions(t=>({setPath(e){t.path=e},setSettingsOpen(e){t.settings_open=e}})).actions(t=>({open(e){t.setPath(e),t.setSettingsOpen(!0)},close(){t.setSettingsOpen(!1)},navigate(e){const n=ju(e);n&&t.setPath(n)}})),Yu=b.types.model("MockContextModel",{current:b.types.optional(b.types.frozen(),{})}).views(t=>({get keys(){return Object.keys(t.current)},get entries(){return Object.entries(t.current)}})).actions(t=>({replace(e){t.current=e},get(e){return t.current[e]},set(e,n){t.current[e]=n}})),Qu=b.types.model("VariableModel",{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})}))}).views(t=>({get json(){const{name:e,size:n,weight:r,color:a,formatter:o,data_field:l,aggregation:u}=t;return x.cloneDeep({name:e,size:n,color:a,weight:r,formatter:o,data_field:l,aggregation:u})}}));class Ku{constructor(e){N(this,"origin");N(this,"copy");this.origin=e,this.copy=b.clone(e),ie.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(e){b.applySnapshot(this.copy,e)}}const Uu=t=>new Ku(t);class Xu{constructor(){N(this,"migrations",[])}version(e,n){return this.migrations.push({version:e,handler:n}),this}run(e,n,r){var l;if(e.from===e.to)return n;if(e.from>e.to)throw new Error(`Can not downgrade from version '${e.from}' to (${e.to})`);const a=this.migrations.filter(u=>u.version>e.from&&u.version<=e.to),o=x.orderBy(a,"version","asc");if(((l=x.last(o))==null?void 0:l.version)!==e.to)throw new Error(`Migration to version ${e.to} not found`);return o.reduce((u,c)=>c.handler(u,r),n)}}class ve extends Xu{constructor(){super(),this.configVersions()}version(e,n){return super.version(e,(r,a)=>({version:e,...n(r,a)}))}async migrate({configData:e,panelModel:n}){const r=await e.getItem(null),a=x.get(r,"version",0),o=this.run({from:a,to:this.VERSION},r,{panelModel:n});await e.setItem(null,o)}async needMigration({configData:e}){const n=await e.getItem(null);return x.get(n,"version",0)<this.VERSION}}var Je=(t=>(t.string="string",t.number="number",t.eloc="eloc",t.percentage="percentage",t.custom="custom",t))(Je||{});const gs=["function text({ value }) {"," // your code goes here"," return value","}"].join(`
119
- `),vr={columns:[],fontSize:"14px",highlightOnHover:!0,horizontalSpacing:"14px",id_field:"",striped:!0,use_raw_columns:!0,verticalSpacing:"14px"};class Lt{constructor(e,n){this.root=e,this.path=n}async deleteItem(e){e===null&&await this.root.deleteItem(this.path);const n=await this.root.getItem(this.path)||{};await this.root.setItem(this.path,x.omit(n,e))}async getItem(e){const n=await this.root.getItem(this.path);return e===null?n:x.get(n,e)}async setItem(e,n){if(e===null)await this.root.setItem(this.path,n);else{const r=await this.root.getItem(this.path)||{};await this.root.setItem(this.path,{...r,[e]:n})}return await this.getItem(e)}watchItem(e,n,r){return e===null?this.root.watchItem(this.path,(a,o)=>{n(a,o)},r):this.root.watchItem(this.path,(a,o)=>{const l=x.get(a,e),u=x.get(o,e);l!==u&&n(l,u)},r)}}class xr{constructor(e,n,r){N(this,"attachmentStorage");this.instance=e,this.attachmentKey=n,this.constructInstance=r,this.attachmentStorage=new Lt(e.instanceData,n)}async getInstance(e){if(await this.attachmentStorage.getItem(e))return this.constructInstance(new Lt(this.attachmentStorage,e))}async create(e,n){return await this.attachmentStorage.setItem(e,n),this.constructInstance(new Lt(this.attachmentStorage,e))}async remove(e){await this.attachmentStorage.deleteItem(e)}async list(){const e=await this.attachmentStorage.getItem(null);return Promise.all(x.values(e).map(n=>this.constructInstance(new Lt(this.attachmentStorage,n.id))))}}class ms{constructor(e){N(this,"rootRef");this.rootRef=ie.observable({current:e})}async deleteItem(e){ie.runInAction(()=>{x.unset(this.rootRef.current,[e])})}getItem(e){const n=this.getValueFromRoot(e);return Promise.resolve(n)}getValueFromRoot(e){return e===null?ie.toJS(this.rootRef.current):x.get(this.rootRef.current,[e])}setItem(e,n){if(e===null)if(x.isObject(n))ie.runInAction(()=>{this.rootRef.current=n});else throw new Error("Cannot set root value to non-object");else ie.runInAction(()=>{x.set(this.rootRef.current,[e],n)});return Promise.resolve(this.getItem(e))}watchItem(e,n,r){return ie.reaction(()=>this.getValueFromRoot(e),(a,o)=>{n(a,o)},{requiresObservable:!0,fireImmediately:x.get(r,"fireImmediately",!1)})}}class Ju{constructor(){N(this,"channels",new Map);N(this,"globalChannel",new ka)}getChannel(e){const n=this.channels.get(e);if(n)return n;const r=new ka;return this.channels.set(e,r),r}}class Zu{constructor(e){N(this,"instances",new Map);this.pluginManager=e}get availableVizList(){return this.pluginManager.installedPlugins.flatMap(e=>e.manifest.viz)}resolveComponent(e){return this.pluginManager.factory.viz(e)}getOrCreateInstance(e){const n=this.instances.get(e.id);if(n)return n;const r={id:e.id,name:e.viz.type,type:e.viz.type,messageChannels:new Ju,instanceData:new ms(e.viz.conf)};return this.instances.set(e.id,r),r}}function ys(t,e,n,r){return{vizManager:n,locale:"zh",msgChannels:t.messageChannels,instanceData:t.instanceData,pluginData:new ms({}),colorPalette:{getColor(){return()=>""}},data:e,variables:r}}const Hu=t=>{const{panel:e,vizManager:n,data:r,variables:a}=t,o=n.resolveComponent(e.viz.type),l=n.getOrCreateInstance(e),u={...ys(l,r,n,a),viewport:{width:e.layout.w,height:e.layout.h}},c=o.viewRender;return i(c,{context:u,instance:l,...x.omit(t,["panel","vizManager","data"])})},ec=t=>{const{vizManager:e,panel:n,panelInfoEditor:r,data:a,variables:o}=t,l=e.resolveComponent(n.viz.type),u=e.getOrCreateInstance(n),c={...ys(u,a,e,o),panelInfoEditor:r},d=l.configRender;return i(d,{context:c,instance:u,...x.omit(t,["panel","vizManager","data","panelInfoEditor"])})},bs=(t,e)=>{const n=st.bezier(t),r=st.bezier(e);return function(a){return a<50?n(a*2/100).hex():r((a-50)*2/100).hex()}},vn=t=>{const e=st.bezier(t);return function(n){return e(n/100).hex()}},tc={type:"interpolation",displayName:"Red / Green",getColor:bs(["darkred","deeppink","lightyellow"],["lightyellow","lightgreen","teal"]),name:"red-green",category:"diverging"},nc={type:"interpolation",displayName:"Yellow / Blue",getColor:bs(["#8f531d","#ffd347","#e3efe3"],["#eefaee","#4ecbbf","#003f94"]),name:"yellow-blue",category:"diverging"},rc={type:"interpolation",displayName:"Red",getColor:vn(["#fff7f1","darkred"]),name:"red",category:"sequential"},ic={type:"interpolation",displayName:"Green",getColor:vn(["#f0ffed","darkgreen"]),name:"green",category:"sequential"},ac={type:"interpolation",displayName:"Blue",getColor:vn(["#f9fcff","#48b3e9","darkblue"]),name:"blue",category:"sequential"},sc={type:"interpolation",displayName:"Orange",getColor:vn(["#fff7f1","darkorange","#b60000"]),name:"orange",category:"sequential"};class oc{constructor(e){N(this,"symbol");this.symbol=Symbol(e)}}function ot(t){return new oc(t)}class wr{constructor(){N(this,"parent");N(this,"factoryRegistry",new Map);N(this,"instanceRegistry",new Map)}createScoped(){const e=new wr;return e.parent=this,e}getRequired(e){return this.get(e)}get(e){if(this.instanceRegistry.has(e.symbol))return this.instanceRegistry.get(e.symbol);const n=this.factoryRegistry.get(e.symbol);if(n){const r=n(this);return this.instanceRegistry.set(e.symbol,r),r}if(this.parent)return this.parent.get(e)}provideFactory(e,n){return this.factoryRegistry.has(e.symbol)?console.warn(`Token ${e.symbol.toString()} is already registered`):this.factoryRegistry.set(e.symbol,n),this}provideValue(e,n){return this.factoryRegistry.has(e.symbol)?console.warn(`Token ${e.symbol.toString()} is already registered`):this.factoryRegistry.set(e.symbol,()=>n),this}dispose(){this.instanceRegistry.forEach(e=>{const n=x.get(e,"dispose");x.isFunction(n)&&n.bind(e)()}),this.instanceRegistry.clear(),this.factoryRegistry.clear()}}const vs="10.9.5",lc=Object.freeze(Object.defineProperty({__proto__:null,version:vs},Symbol.toStringTag,{value:"Module"}));class uc{constructor(e){N(this,"staticColors",new Map);N(this,"interpolations",new Map);e.installedPlugins.forEach(n=>{n.manifest.color.forEach(r=>{this.register(r)})})}getStaticColors(){return Array.from(this.staticColors.values())}register(e){const n=this.encodeColor(e);e.type==="single"?(this.staticColors.has(n)&&console.warn(`the color '${e.name}' has been registered under '${e.category}', previous registered value will be overridden`),this.staticColors.set(n,e)):e.type==="interpolation"&&(this.interpolations.has(n)&&console.warn(`the interpolation '${e.name}' has been registered under '${e.category}', previous registered value will be overridden`,`the interpolation '${e.name}' has been registered under '${e.category}', previous registered value will be overridden`),this.interpolations.set(n,e))}decodeStaticColor(e){return this.staticColors.get(e)}encodeColor(e){return`\${${e.category}}.{${e.name}}`}decodeInterpolation(e){return this.interpolations.get(e)}getColorInterpolations(){return Array.from(this.interpolations.values())}}class cc{constructor(){N(this,"plugins",new Map);N(this,"vizComponents",new Map);N(this,"factory",{viz:e=>{const n=this.vizComponents.get(e);if(n)return n;throw new Error(`Viz Component (${e}) not found`)}})}install(e){if(this.plugins.has(e.id))throw new Error(`Plugin (${e.id}) has been installed before`);this.plugins.set(e.id,e);for(const n of e.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())}}const W=(t,e)=>{const[n,{setFalse:r}]=X.useBoolean(!0),[a,o]=y.useState();y.useEffect(()=>(t.getItem(e).then(u=>{o(u),r()}),t.watchItem(e,u=>{o(u)})));const l=y.useCallback(async u=>{await t.setItem(e,u),o(u)},[t,e]);return{loading:n,value:a,set:l}},Cr={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 q(t){const[e,n]=t.split(".");return{queryID:e,columnKey:n}}function lt(t,e){var a;const{queryID:n,columnKey:r}=q(e);return n?r?((a=t[n])==null?void 0:a.map(o=>o[r]))??[]:t[n]:[]}function xn(t,e){const{queryID:n}=q(e);return n?t[n]:[]}function dc(t){return Object.values(t)[0]}function wn(t,e){const{queryID:n,columnKey:r}=q(e);return t[r]}le.use([G.GridComponent,G.VisualMapComponent,G.LegendComponent,G.TooltipComponent,Ve.CanvasRenderer]);function pc({context:t}){const{value:e}=W(t.instanceData,"config"),n=t.data,{width:r,height:a}=t.viewport,{x_axis_data_key:o,y_axis_data_key:l,z_axis_data_key:u,xAxis3D:c,yAxis3D:d,zAxis3D:f}=x.defaults({},e,Cr),h=y.useMemo(()=>xn(n,o),[n,o]),{x:g,y:m,z:w}=y.useMemo(()=>({x:q(o),y:q(l),z:q(u)}),[o,l,u]),{min:C,max:_}=y.useMemo(()=>{const I=x.minBy(h,B=>B[w.columnKey]),O=x.maxBy(h,B=>B[w.columnKey]);return{min:x.get(I,w.columnKey),max:x.get(O,w.columnKey)}},[h,w]),T={tooltip:{},backgroundColor:"#fff",visualMap:{show:!0,dimension:2,min:C,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[w.columnKey]])}]};return e?i(Ne,{echarts:le,option:T,style:{width:r,height:a},notMerge:!0,theme:"merico-light"}):null}const xs=y.createContext({panel:null,data:{},loading:!1,errors:[]}),Sr=xs.Provider;function ze(){const t=y.useContext(xs);if(!t.panel)throw new Error("Please use PanelContextProvider");return t}const hc={fullScreenPanelID:"",setFullScreenPanelID:x.noop},_r=y.createContext(hc);function ws(){const t=y.useContext(_r);if(!t)throw new Error("Please use FullScreenPanelContext.Provider");return t}const j=k.observer(y.forwardRef(({label:t,required:e,value:n,onChange:r,clearable:a=!1,sx:o,...l},u)=>{const{panel:c}=ze(),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:t,data:d,value:n,onChange:r,required:e,sx:o,...l})}));function fc({context:t}){const{value:e,set:n}=W(t.instanceData,"config"),r=x.defaults({},e,Cr),{control:a,handleSubmit:o,reset:l}=v.useForm({defaultValues:r});return y.useEffect(()=>{l(r)},[e]),e?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(j,{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(j,{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(j,{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(D.DeviceFloppy,{size:20}),i(s.Text,{ml:"md",children:"Save"})]})})]})}):null}function gc(t,{panelModel:e}){try{const n=e.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}=t;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 mc extends ve{constructor(){super(...arguments);N(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:gc(a,r)}})}}const yc={displayName:"Bar Chart (3D)",displayGroup:"ECharts-based charts",migrator:new mc,name:"bar-3d",viewRender:pc,configRender:fc,createConfig(){return{version:2,config:x.cloneDeep(Cr)}}};class Fe extends y.Component{constructor(e){super(e),this.state={error:null}}componentDidCatch(e){this.setState({error:e})}render(){var e;if(this.state.error){const n=()=>{this.setState({error:null})};return p(s.Box,{children:[i(s.Text,{size:"xs",children:(e=this.state.error)==null?void 0:e.message}),i(s.Button,{variant:"subtle",size:"xs",mx:"auto",compact:!0,sx:{display:"block"},onClick:n,children:"Retry"})]})}return this.props.children}}const $e={mantissa:0,output:"number",trimMantissa:!1,average:!1};function bc({value:t,onChange:e},n){const r=u=>{e({...t,output:u})},a=u=>{const c=u===0?!1:t.trimMantissa;e({...t,mantissa:u,trimMantissa:c})},o=u=>{e({...t,trimMantissa:u.currentTarget.checked})},l=u=>{e({...t,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:t.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:t.average,onChange:l,disabled:t.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:t.mantissa,onChange:a}),i(s.Switch,{label:"Trim mantissa",checked:t.trimMantissa,onChange:o,disabled:t.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(D.ArrowRight,{size:9})," ",ee(123456789).format(t)]}),p(s.Text,{size:12,color:"gray",children:["1234 ",i(D.ArrowRight,{size:9})," ",ee(1234).format(t)]}),p(s.Text,{size:12,color:"gray",children:["0.1234 ",i(D.ArrowRight,{size:9})," ",ee(.1234).format(t)]})]})})]})]})}const Re=y.forwardRef(bc),nt={enabled:!1,func_content:["function label(value, index) {"," // your code goes here"," // return value","}"].join(`
119
+ `),vr={columns:[],fontSize:"14px",highlightOnHover:!0,horizontalSpacing:"14px",id_field:"",striped:!0,use_raw_columns:!0,verticalSpacing:"14px"};class Lt{constructor(e,n){this.root=e,this.path=n}async deleteItem(e){e===null&&await this.root.deleteItem(this.path);const n=await this.root.getItem(this.path)||{};await this.root.setItem(this.path,x.omit(n,e))}async getItem(e){const n=await this.root.getItem(this.path);return e===null?n:x.get(n,e)}async setItem(e,n){if(e===null)await this.root.setItem(this.path,n);else{const r=await this.root.getItem(this.path)||{};await this.root.setItem(this.path,{...r,[e]:n})}return await this.getItem(e)}watchItem(e,n,r){return e===null?this.root.watchItem(this.path,(a,o)=>{n(a,o)},r):this.root.watchItem(this.path,(a,o)=>{const l=x.get(a,e),u=x.get(o,e);l!==u&&n(l,u)},r)}}class xr{constructor(e,n,r){N(this,"attachmentStorage");this.instance=e,this.attachmentKey=n,this.constructInstance=r,this.attachmentStorage=new Lt(e.instanceData,n)}async getInstance(e){if(await this.attachmentStorage.getItem(e))return this.constructInstance(new Lt(this.attachmentStorage,e))}async create(e,n){return await this.attachmentStorage.setItem(e,n),this.constructInstance(new Lt(this.attachmentStorage,e))}async remove(e){await this.attachmentStorage.deleteItem(e)}async list(){const e=await this.attachmentStorage.getItem(null);return Promise.all(x.values(e).map(n=>this.constructInstance(new Lt(this.attachmentStorage,n.id))))}}class ms{constructor(e){N(this,"rootRef");this.rootRef=ie.observable({current:e})}async deleteItem(e){ie.runInAction(()=>{x.unset(this.rootRef.current,[e])})}getItem(e){const n=this.getValueFromRoot(e);return Promise.resolve(n)}getValueFromRoot(e){return e===null?ie.toJS(this.rootRef.current):x.get(this.rootRef.current,[e])}setItem(e,n){if(e===null)if(x.isObject(n))ie.runInAction(()=>{this.rootRef.current=n});else throw new Error("Cannot set root value to non-object");else ie.runInAction(()=>{x.set(this.rootRef.current,[e],n)});return Promise.resolve(this.getItem(e))}watchItem(e,n,r){return ie.reaction(()=>this.getValueFromRoot(e),(a,o)=>{n(a,o)},{requiresObservable:!0,fireImmediately:x.get(r,"fireImmediately",!1)})}}class Ju{constructor(){N(this,"channels",new Map);N(this,"globalChannel",new ka)}getChannel(e){const n=this.channels.get(e);if(n)return n;const r=new ka;return this.channels.set(e,r),r}}class Zu{constructor(e){N(this,"instances",new Map);this.pluginManager=e}get availableVizList(){return this.pluginManager.installedPlugins.flatMap(e=>e.manifest.viz)}resolveComponent(e){return this.pluginManager.factory.viz(e)}getOrCreateInstance(e){const n=this.instances.get(e.id);if(n)return n;const r={id:e.id,name:e.viz.type,type:e.viz.type,messageChannels:new Ju,instanceData:new ms(e.viz.conf)};return this.instances.set(e.id,r),r}}function ys(t,e,n,r){return{vizManager:n,locale:"zh",msgChannels:t.messageChannels,instanceData:t.instanceData,pluginData:new ms({}),colorPalette:{getColor(){return()=>""}},data:e,variables:r}}const Hu=t=>{const{panel:e,vizManager:n,data:r,variables:a}=t,o=n.resolveComponent(e.viz.type),l=n.getOrCreateInstance(e),u={...ys(l,r,n,a),viewport:{width:e.layout.w,height:e.layout.h}},c=o.viewRender;return i(c,{context:u,instance:l,...x.omit(t,["panel","vizManager","data"])})},ec=t=>{const{vizManager:e,panel:n,panelInfoEditor:r,data:a,variables:o}=t,l=e.resolveComponent(n.viz.type),u=e.getOrCreateInstance(n),c={...ys(u,a,e,o),panelInfoEditor:r},d=l.configRender;return i(d,{context:c,instance:u,...x.omit(t,["panel","vizManager","data","panelInfoEditor"])})},bs=(t,e)=>{const n=st.bezier(t),r=st.bezier(e);return function(a){return a<50?n(a*2/100).hex():r((a-50)*2/100).hex()}},vn=t=>{const e=st.bezier(t);return function(n){return e(n/100).hex()}},tc={type:"interpolation",displayName:"Red / Green",getColor:bs(["darkred","deeppink","lightyellow"],["lightyellow","lightgreen","teal"]),name:"red-green",category:"diverging"},nc={type:"interpolation",displayName:"Yellow / Blue",getColor:bs(["#8f531d","#ffd347","#e3efe3"],["#eefaee","#4ecbbf","#003f94"]),name:"yellow-blue",category:"diverging"},rc={type:"interpolation",displayName:"Red",getColor:vn(["#fff7f1","darkred"]),name:"red",category:"sequential"},ic={type:"interpolation",displayName:"Green",getColor:vn(["#f0ffed","darkgreen"]),name:"green",category:"sequential"},ac={type:"interpolation",displayName:"Blue",getColor:vn(["#f9fcff","#48b3e9","darkblue"]),name:"blue",category:"sequential"},sc={type:"interpolation",displayName:"Orange",getColor:vn(["#fff7f1","darkorange","#b60000"]),name:"orange",category:"sequential"};class oc{constructor(e){N(this,"symbol");this.symbol=Symbol(e)}}function ot(t){return new oc(t)}class wr{constructor(){N(this,"parent");N(this,"factoryRegistry",new Map);N(this,"instanceRegistry",new Map)}createScoped(){const e=new wr;return e.parent=this,e}getRequired(e){return this.get(e)}get(e){if(this.instanceRegistry.has(e.symbol))return this.instanceRegistry.get(e.symbol);const n=this.factoryRegistry.get(e.symbol);if(n){const r=n(this);return this.instanceRegistry.set(e.symbol,r),r}if(this.parent)return this.parent.get(e)}provideFactory(e,n){return this.factoryRegistry.has(e.symbol)?console.warn(`Token ${e.symbol.toString()} is already registered`):this.factoryRegistry.set(e.symbol,n),this}provideValue(e,n){return this.factoryRegistry.has(e.symbol)?console.warn(`Token ${e.symbol.toString()} is already registered`):this.factoryRegistry.set(e.symbol,()=>n),this}dispose(){this.instanceRegistry.forEach(e=>{const n=x.get(e,"dispose");x.isFunction(n)&&n.bind(e)()}),this.instanceRegistry.clear(),this.factoryRegistry.clear()}}const vs="10.9.7",lc=Object.freeze(Object.defineProperty({__proto__:null,version:vs},Symbol.toStringTag,{value:"Module"}));class uc{constructor(e){N(this,"staticColors",new Map);N(this,"interpolations",new Map);e.installedPlugins.forEach(n=>{n.manifest.color.forEach(r=>{this.register(r)})})}getStaticColors(){return Array.from(this.staticColors.values())}register(e){const n=this.encodeColor(e);e.type==="single"?(this.staticColors.has(n)&&console.warn(`the color '${e.name}' has been registered under '${e.category}', previous registered value will be overridden`),this.staticColors.set(n,e)):e.type==="interpolation"&&(this.interpolations.has(n)&&console.warn(`the interpolation '${e.name}' has been registered under '${e.category}', previous registered value will be overridden`,`the interpolation '${e.name}' has been registered under '${e.category}', previous registered value will be overridden`),this.interpolations.set(n,e))}decodeStaticColor(e){return this.staticColors.get(e)}encodeColor(e){return`\${${e.category}}.{${e.name}}`}decodeInterpolation(e){return this.interpolations.get(e)}getColorInterpolations(){return Array.from(this.interpolations.values())}}class cc{constructor(){N(this,"plugins",new Map);N(this,"vizComponents",new Map);N(this,"factory",{viz:e=>{const n=this.vizComponents.get(e);if(n)return n;throw new Error(`Viz Component (${e}) not found`)}})}install(e){if(this.plugins.has(e.id))throw new Error(`Plugin (${e.id}) has been installed before`);this.plugins.set(e.id,e);for(const n of e.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())}}const W=(t,e)=>{const[n,{setFalse:r}]=X.useBoolean(!0),[a,o]=y.useState();y.useEffect(()=>(t.getItem(e).then(u=>{o(u),r()}),t.watchItem(e,u=>{o(u)})));const l=y.useCallback(async u=>{await t.setItem(e,u),o(u)},[t,e]);return{loading:n,value:a,set:l}},Cr={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 q(t){const[e,n]=t.split(".");return{queryID:e,columnKey:n}}function lt(t,e){var a;const{queryID:n,columnKey:r}=q(e);return n?r?((a=t[n])==null?void 0:a.map(o=>o[r]))??[]:t[n]:[]}function xn(t,e){const{queryID:n}=q(e);return n?t[n]:[]}function dc(t){return Object.values(t)[0]}function wn(t,e){const{queryID:n,columnKey:r}=q(e);return t[r]}le.use([G.GridComponent,G.VisualMapComponent,G.LegendComponent,G.TooltipComponent,Ve.CanvasRenderer]);function pc({context:t}){const{value:e}=W(t.instanceData,"config"),n=t.data,{width:r,height:a}=t.viewport,{x_axis_data_key:o,y_axis_data_key:l,z_axis_data_key:u,xAxis3D:c,yAxis3D:d,zAxis3D:f}=x.defaults({},e,Cr),h=y.useMemo(()=>xn(n,o),[n,o]),{x:g,y:m,z:w}=y.useMemo(()=>({x:q(o),y:q(l),z:q(u)}),[o,l,u]),{min:C,max:_}=y.useMemo(()=>{const I=x.minBy(h,B=>B[w.columnKey]),O=x.maxBy(h,B=>B[w.columnKey]);return{min:x.get(I,w.columnKey),max:x.get(O,w.columnKey)}},[h,w]),T={tooltip:{},backgroundColor:"#fff",visualMap:{show:!0,dimension:2,min:C,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[w.columnKey]])}]};return e?i(Ne,{echarts:le,option:T,style:{width:r,height:a},notMerge:!0,theme:"merico-light"}):null}const xs=y.createContext({panel:null,data:{},loading:!1,errors:[]}),Sr=xs.Provider;function ze(){const t=y.useContext(xs);if(!t.panel)throw new Error("Please use PanelContextProvider");return t}const hc={fullScreenPanelID:"",setFullScreenPanelID:x.noop},_r=y.createContext(hc);function ws(){const t=y.useContext(_r);if(!t)throw new Error("Please use FullScreenPanelContext.Provider");return t}const j=k.observer(y.forwardRef(({label:t,required:e,value:n,onChange:r,clearable:a=!1,sx:o,...l},u)=>{const{panel:c}=ze(),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:t,data:d,value:n,onChange:r,required:e,sx:o,...l})}));function fc({context:t}){const{value:e,set:n}=W(t.instanceData,"config"),r=x.defaults({},e,Cr),{control:a,handleSubmit:o,reset:l}=v.useForm({defaultValues:r});return y.useEffect(()=>{l(r)},[e]),e?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(j,{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(j,{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(j,{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(D.DeviceFloppy,{size:20}),i(s.Text,{ml:"md",children:"Save"})]})})]})}):null}function gc(t,{panelModel:e}){try{const n=e.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}=t;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 mc extends ve{constructor(){super(...arguments);N(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:gc(a,r)}})}}const yc={displayName:"Bar Chart (3D)",displayGroup:"ECharts-based charts",migrator:new mc,name:"bar-3d",viewRender:pc,configRender:fc,createConfig(){return{version:2,config:x.cloneDeep(Cr)}}};class Fe extends y.Component{constructor(e){super(e),this.state={error:null}}componentDidCatch(e){this.setState({error:e})}render(){var e;if(this.state.error){const n=()=>{this.setState({error:null})};return p(s.Box,{children:[i(s.Text,{size:"xs",children:(e=this.state.error)==null?void 0:e.message}),i(s.Button,{variant:"subtle",size:"xs",mx:"auto",compact:!0,sx:{display:"block"},onClick:n,children:"Retry"})]})}return this.props.children}}const $e={mantissa:0,output:"number",trimMantissa:!1,average:!1};function bc({value:t,onChange:e},n){const r=u=>{e({...t,output:u})},a=u=>{const c=u===0?!1:t.trimMantissa;e({...t,mantissa:u,trimMantissa:c})},o=u=>{e({...t,trimMantissa:u.currentTarget.checked})},l=u=>{e({...t,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:t.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:t.average,onChange:l,disabled:t.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:t.mantissa,onChange:a}),i(s.Switch,{label:"Trim mantissa",checked:t.trimMantissa,onChange:o,disabled:t.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(D.ArrowRight,{size:9})," ",ee(123456789).format(t)]}),p(s.Text,{size:12,color:"gray",children:["1234 ",i(D.ArrowRight,{size:9})," ",ee(1234).format(t)]}),p(s.Text,{size:12,color:"gray",children:["0.1234 ",i(D.ArrowRight,{size:9})," ",ee(.1234).format(t)]})]})})]})]})}const Re=y.forwardRef(bc),nt={enabled:!1,func_content:["function label(value, index) {"," // your code goes here"," // return value","}"].join(`
120
120
  `)},Cs={id:"builtin:echarts:click-echart:series",displayName:"Click Chart Series",nameRender:xc,configRender:vc,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 vc(t){return i(V,{})}function xc(t){return i(s.Text,{children:"Click chart's series"})}const wc=[{label:"Truncate",value:"truncate"},{label:"Break Line",value:"break"},{label:"Break Word",value:"breakAll"}],Cn=y.forwardRef(({sectionTitle:t,value:e,onChange:n},r)=>{const a=o=>l=>{const u=x.cloneDeep(e);x.set(u,o,l),n(u)};return p(s.Stack,{spacing:0,children:[t&&i(s.Divider,{mb:-5,mt:5,variant:"dotted",label:t,labelPosition:"right",labelProps:{color:"dimmed"}}),p(s.Group,{grow:!0,noWrap:!0,children:[i(s.NumberInput,{label:"Max Width",hideControls:!0,value:e.width,onChange:a("width")}),i(s.Select,{label:"Overflow",data:wc,value:e.overflow,onChange:a("overflow")}),i(s.TextInput,{label:"Ellipsis",value:e.ellipsis,disabled:!0})]})]})}),gt=y.forwardRef(({value:t,onChange:e},n)=>{const r=o=>{e({...t,on_axis:o})},a=o=>{e({...t,in_tooltip:o})};return p(s.Stack,{ref:n,spacing:0,children:[i(Cn,{sectionTitle:"Overflow on Axis",value:t.on_axis,onChange:r}),i(Cn,{sectionTitle:"Overflow in Tooltip",value:t.in_tooltip,onChange:a})]})}),Ze={on_axis:{width:80,overflow:"truncate",ellipsis:"..."},in_tooltip:{width:200,overflow:"break",ellipsis:"..."}};function mt({overflow:t,width:e}){const n={truncate:"initial",break:"break-all",breakAll:"break-word"}[t],r=t==="truncate"?"nowrap":"initial",a={truncate:"ellipsis",break:"clip",breakAll:"clip"}[t];return`
121
121
  max-width: ${e}px;
122
122
  word-break: ${n};
@@ -478,7 +478,7 @@ Check the top-level render call using <`+P+">.")}return z}}function Yl(S,z){{if(
478
478
  </tbody>
479
479
  </table>
480
480
  `}},show_in_legend:!0}))}function w0(t,e,n,r){const a=q(e.data_key),o=e.name,l=n.map(u=>{const c=x.sumBy(r[u],a.columnKey);return[u,c]});return{type:"line",name:o,xAxisIndex:3,yAxisIndex:3,color:"#b41529",data:l,show_in_legend:!1}}function C0(t,e,n,r){const l={barMinWidth:5,barMaxWidth:20};return[m0(t,n,r),b0(t,n,r,l),...x0(t,n,r,l),w0(t,e,n,r)]}function S0(t,e){const{axisLabel:n}=t.x_axis;return[{data:e,id:"准确估算比例",gridIndex:0,axisTick:{show:!1},axisLabel:{show:!1},axisLine:{show:!1},type:"category"},{data:e,id:"平均偏差",gridIndex:1,axisTick:{show:!1},axisLabel:{show:!1},axisLine:{show:!0,lineStyle:{color:"#FFFFFF",width:2}},type:"category"},{data:e,id:"数量占比",gridIndex:2,axisTick:{show:!1},axisLabel:{show:!1},axisLine:{show:!1},type:"category"},{data:e,id:"代码当量",gridIndex:3,axisTick:{show:!1},type:"category",axisLabel:{...n,formatter:js(n.formatter)},axisLine:{show:!1}}]}function _0(t){return[{type:"category",name:"准确估算比例",nameRotate:0,nameGap:5,nameLocation:"end",nameTextStyle:{align:"left"},gridIndex:0,axisLabel:{show:!1},axisTick:{show:!1},axisLine:{show:!1},splitLine:{show:!1}},{type:"value",name:"平均偏差",nameGap:5,nameRotate:90,nameLocation:"middle",gridIndex:1,boundaryGap:[1,1],axisLabel:{show:!1},axisTick:{show:!1},axisLine:{show:!1},splitLine:{show:!1}},{type:"value",name:"数量占比",nameGap:5,nameRotate:90,nameLocation:"middle",gridIndex:2,axisLabel:{show:!1},axisTick:{show:!1},axisLine:{show:!1},splitLine:{show:!1},min:0,max:1},{type:"value",gridIndex:3,position:"right",splitNumber:3,axisLabel:{show:!0,verticalAlign:"top",showMinLabel:!1,lineHeight:14},axisTick:{show:!1},axisLine:{show:!1},splitLine:{show:!1}},{type:"value",name:t.name,nameGap:5,nameRotate:90,nameLocation:"middle",gridIndex:3,position:"left",axisLabel:{show:!1},axisTick:{show:!1},axisLine:{show:!1},splitLine:{show:!1}}]}function gi(t){return t==1||t==2?1:gi(t-2)+gi(t-1)}const k0=Array.from(new Array(20),(t,e)=>gi(e+1));function Go(t){return t<=1?t:k0.findIndex(e=>t<=e)-1}function T0(t,e){const{x_axis:n,deviation:r}=t,a=q(n.data_key),o=q(r.data_keys.estimated_value),l=q(r.data_keys.actual_value);return e[a.queryID].map(u=>{const c=Go(u[o.columnKey]),d=Go(u[l.columnKey]),f=c-d;return{...u,level:{estimated:c,actual:d,diff:f}}})}function D0(t){return t==="rgba(255, 255, 255, 1)"?{borderColor:"rgba(0,0,0,.1)",borderWidth:1}:{}}function M0(t){return{show:!0,orient:"vertical",top:"middle",right:0,data:t.filter(n=>n.show_in_legend).reverse().map(n=>({name:`${n.name}`,color:n.color,itemStyle:D0(n.color)})),tooltip:{show:!0,formatter:"档位偏差:{a}"}}}const I0={tooltip:{trigger:"axis"}};function E0(t,e){const{deviation:n,metrics:r}=t,a=r.find(l=>l.data_key===e);if(a)return a;const o=n.data_keys.actual_value;return{id:o,name:n.name,data_key:o}}function A0(t,e,n){const r=T0(t,n),a=q(t.x_axis.data_key),o=x.uniqBy(n[a.queryID],a.columnKey).map(f=>f[a.columnKey]),l=x.groupBy(r,a.columnKey),u=E0(t,e),c=C0(t,u,o,l),d={xAxis:S0(t,o),yAxis:_0(u),series:c,grid:g0(),visualMap:[{min:0,max:1,calculable:!0,show:!1,seriesIndex:0,color:["#F0F0F0","#418AAF"]}],legend:M0(c)};return x.defaultsDeep({},d,I0)}const z0={input:{border:"none !important",paddingLeft:0,lineHeight:"1.55 !important"}},$0=({conf:t,metricKey:e,setMetricKey:n})=>{const{deviation:r,metrics:a}=t,o=y.useMemo(()=>{const l=a.map(u=>({label:u.name,value:u.data_key}));return l.push({label:r.name?r.name:r.data_keys.actual_value,value:r.data_keys.actual_value}),l},[r,a]);return p(s.Group,{spacing:1,children:[i(s.Text,{size:12,color:"dimmed",sx:{cursor:"default",userSelect:"none"},children:"基线指标"}),i(s.NativeSelect,{size:"xs",data:o,value:e,onChange:l=>n(l.currentTarget.value),styles:z0})]})},L0={"tbody th, tbody td":{padding:"7px 10px"},"tbody tr:not(:first-of-type) th":{borderTop:"1px solid #dee2e6"}};function O0(){return p(s.HoverCard,{width:400,shadow:"md",children:[i(s.HoverCard.Target,{children:i(s.Button,{size:"xs",variant:"subtle",compact:!0,leftIcon:i(L.IconInfoCircle,{size:14}),children:"指标说明"})}),i(s.HoverCard.Dropdown,{children:i(s.Table,{fontSize:14,sx:L0,children:p("tbody",{children:[p("tr",{children:[i("th",{children:"估算偏差"}),i("td",{children:"使用斐波那契数列(1,2,3,5,8,13)估算故事点,每个数位为一个档位,计算issue实际故事点与估算故事点的档位偏差,即为估算偏差。如估算故事点为5,实际故事点为8,则估算偏差为-1。"})]}),p("tr",{children:[i("th",{children:"准确估算比例"}),i("td",{children:"偏差在 ± 1 档位内的 issue 均为准确估算,以此计算准确估算的比例。"})]})]})})})]})}function P0(t){return p(s.Group,{position:"apart",children:[i(O0,{}),i($0,{...t})]})}le.use([pe.BarChart,pe.LineChart,pe.HeatmapChart,G.GridComponent,G.LegendComponent,G.TooltipComponent,Ve.CanvasRenderer,G.VisualMapComponent]);function B0({conf:t,data:e,width:n,height:r,metricKey:a}){const o=y.useMemo(()=>A0(t,a,e),[t,e,a]);return i(Ne,{echarts:le,option:o,style:{width:n,height:r},notMerge:!0,theme:"merico-light"})}function V0({context:t}){const{value:e}=W(t.instanceData,"config"),n=y.useMemo(()=>x.defaults({},e,fi),[e]),r=t.data,{width:a,height:o}=t.viewport,{x_axis:l,deviation:u}=n,{estimated_value:c,actual_value:d}=u.data_keys,[f,h]=y.useState(d);if(y.useEffect(()=>{h(w=>w||d)},[d]),!l.data_key||!c||!d||!a||!o)return null;const g=Math.max(a,300),m=Math.max(o,370);return p(s.Box,{sx:{overflow:"hidden",height:m,width:g},children:[i(P0,{conf:n,metricKey:f,setMetricKey:h}),i(B0,{width:g,height:m-30,data:r,conf:n,metricKey:f})]})}function N0({control:t,watch:e}){return e(["deviation"]),p(s.Stack,{children:[i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:"deviation.name",control:t,render:({field:n})=>i(s.TextInput,{label:"指标名称",sx:{flex:1},...n})})}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"deviation.data_keys.estimated_value",control:t,render:({field:n})=>i(j,{label:"估算值字段",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"deviation.data_keys.actual_value",control:t,render:({field:n})=>i(j,{label:"实际值字段",required:!0,sx:{flex:1},...n})})]})]})}const q0=({control:t,index:e,remove:n})=>p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`metrics.${e}.name`,control:t,render:({field:r})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:`metrics.${e}.data_key`,control:t,render:({field:r})=>i(j,{label:"Value Field",required:!0,sx:{flex:1},...r})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed"}),i(s.Button,{leftIcon:i(D.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(e),sx:{top:15,right:5},children:"Delete this Metric"})]}),F0=({control:t,watch:e})=>{const{fields:n,append:r,remove:a}=v.useFieldArray({control:t,name:"metrics"}),o=e("metrics"),l=n.map((h,g)=>({...h,...o[g]})),u=()=>r({id:Date.now().toString(),data_key:"",name:""}),c=e("metrics.0.id"),[d,f]=y.useState(()=>c??null);return y.useEffect(()=>{c&&f(h=>h!==null?h:c)},[c]),p(V,{children:[p(s.Group,{spacing:2,sx:{cursor:"default",userSelect:"none"},children:[i(D.InfoCircle,{size:14,color:"#888"}),i(s.Text,{size:14,color:"#888",children:"设置可以展示在基线图的指标,例如代码当量"})]}),i(s.Divider,{variant:"dashed",my:10}),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(D.Plus,{size:18,color:"#228be6"})})]}),l.map((h,g)=>i(s.Tabs.Panel,{value:h.id,children:i(q0,{control:t,index:g,remove:a},h.id)},h.id))]})]})};function G0({control:t,watch:e}){return e(["x_axis"]),p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.data_key",control:t,render:({field:n})=>i(j,{label:"数据字段",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"x_axis.name",control:t,render:({field:n})=>i(s.TextInput,{label:"X轴名称",sx:{flex:1},...n})})]}),i(s.Divider,{mb:-15,label:"点位文案",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.axisLabel.rotate",control:t,render:({field:n})=>i(s.NumberInput,{label:"旋转",hideControls:!0,min:-90,max:90,rightSection:i(s.Text,{color:"dimmed",children:"度"}),sx:{width:"48%"},styles:{rightSection:{width:"4em",justifyContent:"flex-end",paddingRight:"6px"}},...n})}),i(v.Controller,{name:"x_axis.axisLabel.formatter",control:t,render:({field:n})=>i(Qs,{...n})})]})]})}function W0({context:t}){const{value:e,set:n}=W(t.instanceData,"config"),r=y.useMemo(()=>x.defaultsDeep({},e,fi),[e]),{control:a,handleSubmit:o,watch:l,getValues:u,reset:c}=v.useForm({defaultValues:r});y.useEffect(()=>{c(r)},[r]),l([]);const d=u(),f=y.useMemo(()=>!x.isEqual(d,r),[d,r]);return i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:o(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Merico Estimation Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!f,children:i(D.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"X Axis",orientation:"vertical",styles:{tab:{paddingLeft:"6px",paddingRight:"12px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"X Axis",children:"X 轴"}),i(s.Tabs.Tab,{value:"Deviation",children:"偏差"}),i(s.Tabs.Tab,{value:"Additional Metrics",children:"指标"})]}),i(s.Tabs.Panel,{value:"X Axis",children:i(G0,{control:a,watch:l})}),i(s.Tabs.Panel,{value:"Deviation",children:i(N0,{control:a,watch:l})}),i(s.Tabs.Panel,{value:"Additional Metrics",children:i(F0,{control:a,watch:l})})]})]})})}function j0(t,{panelModel:e}){try{const n=e.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=c=>c&&`${n}.${c}`,{x_axis:a,deviation:o,metrics:l,...u}=t;return{...u,x_axis:{...a,data_key:r(a.data_key)},deviation:{...o,data_keys:{estimated_value:r(o.data_keys.estimated_value),actual_value:r(o.data_keys.actual_value)}},metrics:l.map(c=>({...c,data_key:r(c.data_key)}))}}catch(n){throw console.error("[Migration failed]",n),n}}class R0 extends ve{constructor(){super(...arguments);N(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:j0(a,r)}})}}const Y0={displayName:"Merico Estimation Chart",displayGroup:"Merico suite",migrator:new R0,name:"mericoEstimationChart",viewRender:V0,configRender:W0,createConfig:()=>({version:2,config:fi})},mi={styles:{justify:"space-around",align:"start"},metrics:[]};function Q0(){return{id:new Date().getTime().toString(),names:{value:"Value",basis:"Basis"},data_keys:{value:"",basis:""},formatter:$e}}function K0({context:t,instance:e}){const{value:n}=W(t.instanceData,"config"),{variables:r}=t,a=y.useMemo(()=>x.defaults({},n,mi),[n]),o=t.data,l=y.useMemo(()=>Is(o,r),[r,o]),{width:u,height:c}=t.viewport;return!u||!c||!a?null:i(s.Flex,{w:`${u}px`,h:`${c}px`,justify:a.styles.justify,align:a.styles.align,direction:"row",wrap:"nowrap",sx:{overflow:"hidden"},children:a.metrics.map(d=>p(s.Stack,{spacing:18,children:[p(s.Stack,{spacing:12,children:[i(s.Text,{size:"14px",color:"#818388",children:d.names.value}),i(s.Text,{size:"24px",color:"#000000",sx:{lineHeight:1},children:ee(l[d.data_keys.value]).format(d.formatter)})]}),p(s.Stack,{spacing:12,children:[i(s.Text,{size:"14px",color:"#818388",children:d.names.basis}),i(s.Text,{size:"12px",color:"#000000",sx:{lineHeight:1},children:ee(l[d.data_keys.basis]).format(d.formatter)})]})]},d.id))})}function U0({control:t,index:e,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:`metrics.${e}.names.value`,control:t,render:({field:a})=>i(s.TextInput,{label:"Metric Name",required:!0,sx:{flex:1},...a})}),i(v.Controller,{name:`metrics.${e}.data_keys.value`,control:t,render:({field:a})=>i(s.Select,{label:"Metric Data",required:!0,data:r,sx:{flex:1},...a})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`metrics.${e}.names.basis`,control:t,render:({field:a})=>i(s.TextInput,{label:"Basis Name",required:!0,sx:{flex:1},...a})}),i(v.Controller,{name:`metrics.${e}.data_keys.basis`,control:t,render:({field:a})=>i(s.Select,{label:"Basis Data",required:!0,data:r,sx:{flex:1},...a})})]}),p(s.Stack,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Format",labelPosition:"center"}),i(v.Controller,{name:`metrics.${e}.formatter`,control:t,render:({field:a})=>i(Re,{...a})})]}),i(s.ActionIcon,{color:"red",variant:"subtle",onClick:()=>n(e),sx:{position:"absolute",top:15,right:5},disabled:e===0,children:i(D.Trash,{size:16})})]},e)}function X0({control:t,watch:e,variables:n}){const{fields:r,append:a,remove:o}=v.useFieldArray({control:t,name:"metrics"}),l=e("metrics"),u=r.map((w,C)=>({...w,...l[C]})),c=()=>{a(Q0())},d=y.useMemo(()=>n.map(w=>({label:w.name,value:w.name})),[n]),f=x.get(u,"0.id",null),[h,g]=y.useState(f);y.useEffect(()=>{g(w=>w||f)},[f]);const m=w=>{o(w);const C=x.get(u,"0.id",null);g(C)};return p(V,{children:[i(s.Divider,{mt:15,variant:"dashed",label:"Metrics",labelPosition:"center"}),p(s.Tabs,{value:h,onTabChange:g,styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px"}},children:[p(s.Tabs.List,{children:[u.map((w,C)=>i(s.Tabs.Tab,{value:w.id,children:w.names.value?w.names.value:C+1},C)),i(s.Tabs.Tab,{onClick:c,value:"add",children:i(L.IconPlus,{size:18,color:"#228be6"})})]}),u.map((w,C)=>i(s.Tabs.Panel,{value:w.id,children:i(U0,{control:t,index:C,remove:m,variableOptions:d})},C))]})]})}const J0=[{label:"Left",value:"left"},{label:"Center",value:"center"},{label:"Right",value:"right"},{label:"Space Between",value:"space-between"},{label:"Space Around",value:"space-around"},{label:"Space Evenly",value:"space-evenly"}],Z0=[{label:"Start",value:"start"},{label:"Center",value:"center"},{label:"End",value:"end"},{label:"Stretch",value:"stretch"}];function H0({control:t,watch:e}){return e("styles"),p(V,{children:[i(s.Divider,{mt:15,variant:"dashed",label:"Styles",labelPosition:"center"}),p(s.Group,{children:[i(v.Controller,{name:"styles.justify",control:t,render:({field:n})=>i(s.Select,{label:"Justify Content",required:!0,data:J0,sx:{flex:1},...n})}),i(v.Controller,{name:"styles.align",control:t,render:({field:n})=>i(s.Select,{label:"Align",required:!0,data:Z0,sx:{flex:1},...n})})]})]})}function ew({context:t}){const{value:e,set:n}=W(t.instanceData,"config"),{variables:r}=t,a=y.useMemo(()=>x.defaultsDeep({},e,mi),[e]),{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,a),[f,a]);return i("form",{onSubmit:l(n),children:p(s.Stack,{spacing:"xs",children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Merico Stats Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(D.DeviceFloppy,{size:20})})]}),i(H0,{control:o,watch:u}),i(X0,{control:o,watch:u,variables:r})]})})}class tw extends ve{constructor(){super(...arguments);N(this,"VERSION",1)}configVersions(){this.version(1,n=>({...n,version:1,config:n.config}))}}const nw={displayName:"Merico Stats",displayGroup:"Merico suite",migrator:new tw,name:"merico-stats",viewRender:K0,configRender:ew,createConfig:()=>({version:1,config:mi})},rw=[{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(t=>({name:t.name,value:t.value,type:"single",category:"basic"})),iw=[tc,nc,ac,ic,rc,sc],Wo=()=>({id:"dashboard",version:vs,manifest:{viz:[wi,mv,Rv,Qy,Vv,vg,f0,yc,Od,jh,Df,Mx,sg,wh,iv,Bg,pm,Hv,Y0,nw,Ud],color:[...rw,...iw]}}),sn=new cc,Ce={pluginManager:ot("pluginManager"),vizManager:ot("vizManager"),colorManager:ot("colorManager"),instanceScope:{panelModel:ot("panelModel"),vizInstance:ot("vizInstance"),interactionManager:ot("interactionManager"),migrator:ot("migrator"),operationManager:ot("operationManager"),triggerManager:ot("triggerManager")}},yi=()=>{try{sn.install(Wo())}catch{}const t=new Zu(sn),e=new uc(sn);return{pluginManager:sn,vizManager:t,colorManager:e}},at=y.createContext(yi());try{sn.install(Wo())}catch{}function aw(t,e){const{value:n,set:r}=W(t.operation.operationData,"config"),[a,o]=y.useState(x.defaults({},n,e)),l=async()=>{await r(a)};return y.useEffect(()=>{o(x.defaults({},n,e))},[n]),{config:a,setConfig:o,commit:l}}function sw(t){const{config:e,setConfig:n,commit:r}=aw(t,{urlTemplate:"",openInNewTab:!0});async function a(){await r()}async function o(u){n({...e,openInNewTab:u}),await r()}const l=u=>n({...e,urlTemplate:u.currentTarget.value});return p(s.Stack,{children:[i(s.TextInput,{label:"Url",value:e.urlTemplate,onChange:l,onBlur:a}),i(s.Switch,{label:"Open in new Tab",checked:e.openInNewTab,onChange:u=>o(u.currentTarget.checked)})]})}async function ow(t,e){const{urlTemplate:n,openInNewTab:r}=await e.operationData.getItem("config");window.dispatchEvent(new CustomEvent("open-link",{detail:{urlTemplate:n,openInNewTab:r,payload:t}}))}class lw extends ve{constructor(){super(...arguments);N(this,"VERSION",1)}configVersions(){this.version(1,n=>n)}}const uw={displayName:"Open Link",id:"builtin:op:open-link",configRender:sw,run:ow,migrator:new lw,createDefaultConfig:()=>({version:1,config:{urlTemplate:"",openInNewTab:!0}})};function cw(t){const{value:e,set:n}=W(t.operationData,"config"),r=a=>void n({template:a});return[(e==null?void 0:e.template)||"",r]}function dw(t){const[e,n]=cw(t.operation);return i(s.TextInput,{defaultValue:e,onBlur:r=>n(r.currentTarget.value),label:"console.log"})}async function pw(t,e){const n=await e.operationData.getItem("config"),r=x.template(n.template||"");console.log("run with payload",t),console.log(r(t))}const hw={displayName:"console.log (debug)",id:"builtin:op:debug",configRender:dw,run:pw},fw=k.observer(t=>{const e=K(),{value:n,set:r}=W(t.operation.operationData,"config");console.log({value:n,viewID:n==null?void 0:n.viewID});const a=(n==null?void 0:n.viewID)||"",o=l=>void r({viewID:l});return i(s.Select,{defaultValue:a,value:a,onChange:o,label:"View",data:e.views.options})});async function gw(t,e){const r=(await e.operationData.getItem("config")).viewID;window.dispatchEvent(new CustomEvent("open-view",{detail:{viewID:r}}))}const mw={displayName:"Open View",id:"builtin:op:open_view",configRender:fw,run:gw},yw={"tbody tr":{opacity:.5,transition:"opacity 200ms ease"},"tr[data-affected=true]":{opacity:1}},bw=({value:t="",onChange:e})=>{const[n,r]=y.useState(t);y.useEffect(()=>{r(t)},[t]);const a=()=>{e(n)};return i(s.TextInput,{size:"xs",label:"",value:n,onChange:o=>r(o.currentTarget.value),sx:{flexGrow:1},rightSection:i(s.ActionIcon,{color:"green",size:"xs",onClick:a,disabled:n===t,children:i(L.IconDeviceFloppy,{})})})},vw={dictionary:{}},xw=k.observer(t=>{const e=K(),{value:n=vw,set:r}=W(t.operation.operationData,"config"),{dictionary:a={}}=n;console.log({value:{...n},dictionary:{...a},filters:[...e.filters.keyLabelOptions]});const o=(l,u)=>{if(u===""){const c={...a};delete c[l],r({dictionary:c});return}r({dictionary:{...a,[l]:u}})};return p(s.Table,{sx:yw,children:[i("thead",{children:p("tr",{children:[i("th",{children:"Set filter"}),i("th",{children:"with"})]})}),i("tbody",{children:[...e.filters.keyLabelOptions].map(l=>{const u=l.value in a;return p("tr",{"data-affected":u,children:[i("td",{children:l.label}),i("td",{children:i(bw,{value:a[l.value],onChange:c=>o(l.value,c)})})]},l.value)})})]})});async function ww(t,e){const r=(await e.operationData.getItem("config")).dictionary;window.dispatchEvent(new CustomEvent("set-filter-values",{detail:{dictionary:r,payload:t}}))}const Cw={displayName:"Set Filter Values",id:"builtin:op:set_filter_values",configRender:xw,run:ww},Sw={filter_keys:[]},_w=k.observer(t=>{const e=K(),{value:n=Sw,set:r}=W(t.operation.operationData,"config"),{filter_keys:a=[]}=n,o=u=>{r({filter_keys:[...u]})},l=y.useMemo(()=>e.filters.current.map(u=>({label:u.label,value:u.key})),[e.filters.values]);return i(s.Stack,{spacing:10,children:i(s.MultiSelect,{label:"Select Filters to Clear",data:l,value:a,onChange:o})})});async function kw(t,e){const r=(await e.operationData.getItem("config")).filter_keys;window.dispatchEvent(new CustomEvent("clear-filter-values",{detail:{filter_keys:r,payload:t}}))}const Jn=[hw,uw,mw,Cw,{displayName:"Clear Filter Values",id:"builtin:op:clear_filter_values",configRender:_w,run:kw}];class Tw{constructor(e,n=Jn){N(this,"attachments");this.operations=n;const r=async a=>{const{id:o,schemaRef:l}=await a.getItem(null);return{id:o,schemaRef:l,operationData:new Lt(a,"data")}};this.attachments=new xr(e,"__OPERATIONS",r)}async runOperation(e,n){const r=await this.attachments.getInstance(e);if(!r){console.warn(`Operation '${e}' is not defined`);return}const a=this.tryGetSchema(r.schemaRef);if(!a){console.warn(`Operation schema '${r.schemaRef}' is not defined`);return}await a.run(n,r)}tryGetSchema(e){return this.operations.find(n=>n.id===e)}async needMigration(){const n=(await this.attachments.list()).map(async r=>{const a={configData:r.operationData},o=this.tryGetSchema(r.schemaRef),l=o==null?void 0:o.migrator;return l&&await l.needMigration(a)});return(await Promise.all(n)).some(r=>r)}async runMigration(){const n=(await this.attachments.list()).map(async r=>{const a={configData:r.operationData},o=this.tryGetSchema(r.schemaRef),l=o==null?void 0:o.migrator;l&&await l.needMigration(a)&&await l.migrate(a)});await Promise.all(n)}async createOrGetOperation(e,n){var l;if(!this.getOperationSchemaList().some(u=>u.id===n.id))throw new Error(`Operation schema '${n.id}' is not defined`);const a=await this.attachments.getInstance(e);return!a||a.schemaRef!==n.id?await this.attachments.create(e,{id:e,schemaRef:n.id,data:((l=n.createDefaultConfig)==null?void 0:l.call(n))??{}}):a}getOperationList(){return this.attachments.list()}getOperationSchemaList(){return this.operations}removeOperation(e){return this.attachments.remove(e)}async retrieveTrigger(e){return await this.attachments.getInstance(e)}}class bi{constructor(e,n,r){N(this,"operationManager");N(this,"triggerManager");N(this,"attachments");this.operationManager=new Tw(e,r),this.triggerManager=new qc(e,n);const a=async o=>{const{id:l,triggerRef:u,operationRef:c}=await o.getItem(null);return{id:l,triggerRef:u,operationRef:c}};this.attachments=new xr(e,"__INTERACTIONS",a)}async addInteraction(e,n){const r=e.id,a=n.id,o=`[${r}]:[${a}]`;await this.attachments.create(o,{id:o,triggerRef:r,operationRef:a})}getInteractionList(){return this.attachments.list()}async removeInteraction(e){const n=await this.attachments.getInstance(e);if(!n)return;const{triggerRef:r,operationRef:a}=n;await this.getTriggerRefCount(r)<=1&&await this.triggerManager.removeTrigger(r),await this.getOperationRefCount(a)<=1&&await this.operationManager.removeOperation(a),await this.attachments.remove(e)}async getOperationRefCount(e){return(await this.getInteractionList()).filter(r=>r.operationRef===e).length}async getTriggerRefCount(e){return(await this.getInteractionList()).filter(r=>r.triggerRef===e).length}async runInteraction(e,n){const a=(await this.getInteractionList()).filter(o=>o.triggerRef===e);await Promise.all(a.map(async o=>{try{return await this.operationManager.runOperation(o.operationRef,n)}catch(l){console.warn(`Failed to run operation '${o.operationRef}'`,l)}}))}}const tt=({vizManager:t,instance:e})=>X.useCreation(()=>new bi(e,t.resolveComponent(e.type),Jn),[e,t]),jo={left:"flex-start",center:"center",right:"flex-end"},Dw=({header:t,cx:e})=>{const n=x.get(t.column.columnDef.meta,"align","left");return p(s.Text,{className:e("table-head-cell",{"table-head-cell--sortable":t.column.getCanSort()}),onClick:t.column.getToggleSortingHandler(),align:n,sx:{justifyContent:jo[n]},children:[t.isPlaceholder?null:Xe.flexRender(t.column.columnDef.header,t.getContext()),i(Mw,{direction:t.column.getIsSorted()})]})},Mw=({direction:t})=>{switch(t){case"asc":return i(L.IconArrowUp,{size:16});case"desc":return i(L.IconArrowDown,{size:"1em"});default:return null}},vi={id:"builtin:table:click-cell-content",displayName:"Click Cell Content",nameRender:zw,configRender:Ew,payload:[{name:"row_index",description:"Index of the row that the cell belongs to",valueType:"number"},{name:"col_index",description:"Index of the column that the cell belongs to",valueType:"number"},{name:"row_data",description:"Data of the row that the cell belongs to",valueType:"object"}]},Iw={column:""};function Ro(t,e){const{value:n}=W(t.instanceData,"config"),r={columnsFromConfig:[],columnsFromData:[]};if(n&&(r.columnsFromConfig=n.columns.map((a,o)=>({label:a.label,value:o.toString()}))),!e)return r;if(n!=null&&n.id_field){const a=xn(e,n.id_field);(a==null?void 0:a.length)>0&&(r.columnsFromData=Object.keys(a[0]).map(o=>({label:o,value:o})))}return r}function Ew(t){const{columnsFromConfig:e,columnsFromData:n}=Ro(t.instance,t.sampleData),r=e.length>0?e:n,{value:a,set:o}=W(t.trigger.triggerData,"config"),{column:l}=x.defaults({},a,Iw),u=c=>{isNaN(+c)?o({column:c}):o({column:+c})};return i(s.Select,{clearable:!1,data:r,label:"Choose a column",value:l.toString(),onChange:u})}function Aw(t,e){return t?x.isNumber(t.column)?`Click cell of ${e[t.column].label}`:`Click cell of ${t.column}`:"Click cell content (click to config)"}function zw(t){const{columnsFromConfig:e}=Ro(t.instance),{value:n}=W(t.trigger.triggerData,"config");return i(s.Text,{children:Aw(n,e)})}const $w=s.createStyles(t=>({root:{overflow:"auto",position:"relative","& .table-head-cell":{display:"flex",flexFlow:"row nowrap",alignItems:"center",whiteSpace:"nowrap","&.table-head-cell--sortable":{cursor:"pointer",userSelect:"none"}},"&.table-highlight-on-hover tr":{transition:"background-color 0.2s","&:hover":{backgroundColor:t.colorScheme==="dark"?t.colors.dark[5]:t.colors.gray[0]}}},thead:{background:t.colorScheme==="dark"?t.colors.dark[7]:t.white,position:"sticky",top:24,transform:"translateY(-1px)",zIndex:10},info_bar:{position:"sticky",top:0,left:0,right:0,zIndex:10,background:"white"}})),Lw={tableLayout:"fixed","thead, tbody":{tr:{"th, td":{padding:"2px 10px",div:{overflow:"hidden",textOverflow:"ellipsis"},"&:first-of-type":{paddingLeft:2,paddingRight:2}}}}};function Yo(t,e,n){return Math.min(Math.max(t,e),n)}class Ow{constructor(e){this.steps=e;const n=[],r=new Set;for(const a of e)r.has(a.to)||(n.push(a),r.add(a.to));if(n.sort((a,o)=>a.from-o.from),n.length<2)throw new Error("MultiStepValueMapper requires at least 2 steps");this.steps=n}getLinearFunction(e,n){const r=(n.to-e.to)/(n.from-e.from),a=e.to-r*e.from;return o=>r*o+a}getStepFunctionForValue(e){let n=x.findLastIndex(this.steps,r=>r.from<=e);return n=Yo(n,0,this.steps.length-2),this.getLinearFunction(this.steps[n],this.steps[n+1])}mapValue(e){return Yo(this.getStepFunctionForValue(e)(e),0,100)}}class Pw{constructor(e,n,r,a,o){this.getColIndex=e,this.cell=n,this.triggers=r,this.interactionManager=a,this.colorManager=o}getClickHandler(){const e=this.getRelatedTrigger();if(e.length!==0)return()=>{const n={row_data:this.cell.row.original,row_index:this.cell.row.index,col_index:this.getColIndex(this.cell)};for(const r of e)this.interactionManager.runInteraction(r.id,n)}}getRelatedTrigger(){return this.triggers.filter(n=>n.schemaRef===vi.id).filter(n=>{const r=this.getColIndex(this.cell),a=x.get(this.cell.column.columnDef.meta,"value_field"),o=x.get(n.config,"column");return o==r||o==a})}isClickable(){return this.getRelatedTrigger().length>0}get columnConf(){return this.cell.column.columnDef.meta}get bgColor(){const e=this.columnConf.cellBackgroundColor;if(!e||e==="none")return;if(x.isString(e))return e;const n=+this.cell.getValue();if(isFinite(n)){const r=this.colorManager.decodeInterpolation(e.interpolation),o=new Ow(e.steps).mapValue(n);return r==null?void 0:r.getColor(o)}}}const Bw=s.createStyles((t,e)=>({content:{display:"flex",alignItems:"center",justifyContent:jo[e.align],".table-cell-text":{whiteSpace:"nowrap",cursor:e.clickable?"pointer":"default",textDecoration:e.clickable?"underline":"none"}}}));function Vw(t){return t?st(t).oklch()[0]>.7?"black":"white":"inherit"}function Nw(t){const e=t.tableCellContext.bgColor;return{backgroundColor:e,color:Vw(e)}}function qt(t){const e=t.tableCellContext.isClickable(),n=Bw({clickable:e,align:t.align});return i("div",{className:n.classes.content,style:{...Nw(t)},children:i(s.Text,{className:"table-cell-text",onClick:t.tableCellContext.getClickHandler(),children:i("span",{title:t.children,children:t.children})})})}function qw(t){return i(qt,{...t,children:t.value})}function Fw(t){const e=ee(t.value).format({average:!0,mantissa:2,trimMantissa:!0});return i(qt,{...t,children:e})}function Gw(t){const e=ee(t.value).format({thousandSeparated:!0});return i(qt,{...t,children:e})}function Ww(t){const e=ee(t.value).format({output:"percent",mantissa:3});return i(qt,{...t,children:e})}function jw(t){const e=t.value,n=t.func_content;if(!n)return i(qt,{...t,children:e});const r=new Function(`return ${n}`)()({value:e});return i(qt,{...t,children:r})}function Rw(t){switch(t.type){case Je.string:return i(qw,{...t});case Je.eloc:return i(Fw,{...t});case Je.number:return i(Gw,{...t});case Je.percentage:return i(Ww,{...t});case Je.custom:return i(jw,{...t})}}const Yw=t=>{const e=tt(t),n=He(e.triggerManager,vi.id),{colorManager:r}=y.useContext(at);return y.useCallback(a=>new Pw(t.getColIndex,a,n,e,r),[n,e,t.getColIndex])};function Qw({context:t,instance:e}){var be,De;const n=t.data,{height:r,width:a}=t.viewport,{value:o=vr}=W(t.instanceData,"config"),{id_field:l,use_raw_columns:u,columns:c,...d}=o,{classes:f,cx:h}=$w(),g=y.useMemo(()=>{if(!l)return[];const ge=q(l);return n[ge.queryID]},[n,l]),m=y.useMemo(()=>u?!Array.isArray(g)||g.length===0?[]:Object.keys(g[0]).map(ge=>({id:ge,label:ge,value_field:ge,value_type:Je.string,align:"left",width:"",cellBackgroundColor:""})):c,[u,c,g]),w=Yw({getColIndex:y.useCallback(ge=>m.indexOf(ge.column.columnDef.meta),[m]),vizManager:t.vizManager,instance:e}),C=y.useMemo(()=>{const ge=Xe.createColumnHelper();return m.map(me=>{const Oe=q(me.value_field);return ge.accessor(Oe.columnKey,{cell:Qe=>i(Rw,{tableCellContext:w(Qe.cell),value:Qe.getValue(),type:me.value_type,...me}),header:me.label,enableSorting:!0,meta:me,size:typeof me.width=="number"?me.width:void 0,minSize:typeof me.width=="number"?me.width:void 0})})},[m,w]),[_,T]=y.useState([]),I=Xe.useReactTable({data:g,state:{sorting:_},onSortingChange:T,columns:C,getCoreRowModel:Xe.getCoreRowModel(),getSortedRowModel:Xe.getSortedRowModel()}),{rows:O}=I.getRowModel(),B=y.useRef(null),$=eu.useVirtual({parentRef:B,size:O.length,estimateSize:y.useCallback(()=>28,[]),overscan:20}),{virtualItems:A,totalSize:E}=$,F=A.length>0&&((be=A==null?void 0:A[0])==null?void 0:be.start)||0,U=A.length>0?E-(((De=A==null?void 0:A[A.length-1])==null?void 0:De.end)||0):0,Y=O.length,Z=Y>0,oe=Z?r-22:r,ue=Z?22:0;return l?!Array.isArray(g)||g.length===0?i(s.Text,{color:"gray",align:"center",children:"Empty Data"}):p("div",{ref:B,style:{height:r,width:a},"data-enable-scrollbar":!0,className:h(f.root,{"table-highlight-on-hover":o.highlightOnHover}),children:[Y>0&&i(s.Box,{className:f.info_bar,sx:{height:22},children:p(s.Text,{align:"right",pr:6,size:14,color:"dimmed",fw:"normal",children:["Total: ",Y]})}),p(s.Table,{sx:{...Lw,maxHeight:oe},...d,striped:o.striped,children:[i("thead",{className:f.thead,style:{top:ue},children:I.getHeaderGroups().map(ge=>i("tr",{children:ge.headers.map(xe=>i("th",{style:{width:xe.getSize()},children:i(Dw,{header:xe,cx:h})},xe.id))},ge.id))}),p("tbody",{children:[F>0&&i("tr",{children:i("td",{style:{height:`${F}px`}})}),A.map(ge=>{const xe=O[ge.index];return i("tr",{children:xe.getVisibleCells().map(me=>i("td",{children:Xe.flexRender(me.column.columnDef.cell,me.getContext())},me.id))},xe.id)}),U>0&&i("tr",{children:i("td",{style:{height:`${U}px`}})})]})]})]}):i(s.Text,{color:"red",align:"center",children:"ID Field is not set, can't render a table without it"})}const Qo=s.createStyles(()=>({palette:{display:"flex",flexFlow:"row nowrap"},paletteItem:{".palette-value":{height:24,overflow:"visible",width:36},".palette-item":{width:"36px",height:36*.618,cursor:"pointer",transition:"transform 100ms ease-in-out","&:hover":{boxShadow:"0 0 0 2px var(--shadow-color)",borderRadius:2,transform:"scale(1.2)"}}}})),Kw=[{from:0,to:0},{from:100,to:100}];class Uw{constructor(){N(this,"steps",new Map);N(this,"interpolation");N(this,"onChange");ie.makeAutoObservable(this,{steps:ie.observable},{deep:!1}),ie.reaction(()=>ie.toJS(this.steps),()=>{this.notifyStepChange()})}setSteps(e){for(const n of e)this.steps.set(n.to,n.from)}notifyStepChange(){var e;(e=this.onChange)==null||e.call(this,Array.from(this.steps.entries()).map(([n,r])=>({to:n,from:r})).sort((n,r)=>n.to-r.to||n.from-r.from))}fromProps(e){e.steps.length<2?this.setSteps(Kw):this.setSteps(e.steps),this.interpolation=e.interpolation,this.onChange=e.onChange}changeStep(e,n){e==null?this.steps.delete(n):this.steps.set(n,e)}getStepFromValue(e){return this.steps.get(e)}}function Xw(t){const{onChange:e,color:n,index:r,value:a}=t,{classes:o}=Qo(),[l,u]=y.useState(a),[c,{setTrue:d,setFalse:f}]=X.useBoolean(!1),h=r%2===1,g=h&&a!=null,m=!h&&a!=null,w=`map ${a} to color ${r}`,C=()=>{u(a),f()},_=()=>{f(),e==null||e(l)},T=ee(a).format({average:!0});return p("div",{"data-testid":`palette-item-${r}`,className:o.paletteItem,children:[i(s.Text,{title:w,style:{opacity:g?1:0},color:"dimmed",size:"sm",className:"palette-value--up palette-value",children:T}),p(s.Popover,{width:200,trapFocus:!0,opened:c,onClose:f,children:[i(s.Popover.Target,{children:i("div",{"data-testid":"palette-item-target",className:"palette-item",onClick:d,style:{"--shadow-color":st(n).alpha(.5).hex(),backgroundColor:n}})}),i(s.Popover.Dropdown,{children:p(s.Stack,{children:[i(s.NumberInput,{size:"xs",label:"Map a value to this color",value:l,onChange:u}),p(s.Group,{position:"right",children:[i(s.Button,{variant:"subtle",size:"xs",onClick:C,children:"Cancel"}),i(s.Button,{"data-testid":"palette-item-ok",size:"xs",onClick:_,children:"OK"})]})]})})]}),i(s.Text,{title:w,style:{opacity:m?1:0},color:"dimmed",size:"sm",className:"palette-value--bottom palette-value",children:T})]})}const Jw=k.observer(({model:t})=>{const{classes:e}=Qo(),n=x.range(0,13,1).map(r=>100/12*r).map(r=>[t.interpolation.getColor(r),r]);return i("div",{className:e.palette,children:n.map(([r,a],o)=>i(Xw,{index:o,color:r,value:t.getStepFromValue(a),onChange:l=>t.changeStep(l,a)},r))})}),Zw=k.observer(function(e){const n=X.useCreation(()=>new Uw,[]);return y.useEffect(()=>{n.fromProps(e)}),n.interpolation==null?null:i(Jw,{model:n})}),Hw=t=>{const{value:e,onChange:n,colorManager:r}=t,a=r.getColorInterpolations(),[o,l]=y.useState(e),u=r.decodeInterpolation(o.interpolation)||a[0],[c,{setTrue:d,setFalse:f}]=X.useBoolean(),h=a.map(_=>({label:_.displayName,value:r.encodeColor(_),group:_.category}));function g(_){_&&l(T=>({...T,interpolation:_}))}const m=()=>{f(),n==null||n(ie.toJS(o))};function w(_){l(T=>({...T,steps:_}))}const C=()=>{f(),l(e)};return p(V,{children:[i(s.Button,{variant:"outline",onClick:d,children:u==null?void 0:u.displayName}),i(s.Modal,{size:508,title:"Setup color interpolation",opened:c,onClose:f,zIndex:320,children:c&&p(s.Stack,{"data-testid":"color-interpolation-modal",children:[i(s.Select,{label:"Color style",value:o.interpolation,data:h,onChange:g}),i(Zw,{steps:o.steps,interpolation:u,onChange:w}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:C,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:m,children:"OK"})]})]})})]})},eC=["static","interpolation","none"].map(t=>({label:x.capitalize(t),value:t})),tC=[{from:0,to:0},{from:100,to:100}];function Ko(t){return t?x.isString(t)?t==="none"?"none":"static":"interpolation":"none"}function nC(t,e){var n;return Ko(e)==="static"?e:(n=t.getStaticColors()[0])==null?void 0:n.value}function rC(t,e){return x.isObject(e)?e:{steps:tC,interpolation:t.encodeColor(t.getColorInterpolations()[0])}}const iC=y.forwardRef((t,e)=>{const{colorManager:n}=y.useContext(at),[r,a]=y.useState(Ko(t.value)),[o,l]=y.useState(nC(n,t.value)),u=X.useLatest(o),[c,d]=y.useState(rC(n,t.value)),f=X.useLatest(c),h=w=>{var C,_,T;a(w||"none"),w==="static"?(C=t.onChange)==null||C.call(t,u.current):w==="none"||!w?(_=t.onChange)==null||_.call(t,"none"):(T=t.onChange)==null||T.call(t,f.current)},g=w=>{var C;l(w),(C=t.onChange)==null||C.call(t,w)},m=w=>{var C;d(w),(C=t.onChange)==null||C.call(t,w)};return p(s.Stack,{align:"stretch",children:[i(s.Select,{label:"Cell background",value:r||"none",onChange:h,data:eC}),r==="static"&&i(Pe,{value:o,onChange:g}),r==="interpolation"&&i(Hw,{colorManager:n,value:c,onChange:m})]})}),aC={[Je.eloc]:"ELOC"},sC=Object.values(Je).map(t=>({label:x.get(aC,t,x.capitalize(t)),value:t})),oC=y.forwardRef(({label:t,value:e,onChange:n,sx:r},a)=>i(s.Select,{ref:a,label:t,data:sC,value:e,onChange:n,sx:r})),lC=y.forwardRef(({value:t,onChange:e},n)=>{const[r,{setTrue:a,setFalse:o}]=X.useBoolean(),[l,u]=y.useState(t),c=()=>{o(),e(l)},d=()=>{o(),u(t)},f=()=>{u(gs)};return y.useEffect(()=>{u(t)},[t]),p(V,{children:[i(s.Button,{variant:"filled",mt:24,onClick:a,sx:{flexGrow:0},children:"Custom Cell Content"}),i(s.Modal,{size:800,title:"Custom cell content",opened:r,onClose:o,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:r&&p(s.Stack,{children:[i(s.Box,{sx:{position:"relative"},children:i(Ie,{height:"500px",defaultLanguage:"javascript",value:l,onChange:h=>u(h??""),theme:"vs-dark",options:{minimap:{enabled:!1}}})}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:f,color:"red",leftIcon:i(D.Recycle,{size:20}),children:"Rest"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:d,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:c,children:"OK"})]})]})]})})]})}),uC=[{label:"Left",value:"left"},{label:"Center",value:"center"},{label:"Right",value:"right"}],xi=()=>i(s.Text,{color:"dimmed",size:12,children:"px"}),cC=({control:t,index:e,watch:n,remove:r,column:a})=>{const o=n(`columns.${e}.value_type`);return p(s.Stack,{my:0,sx:{position:"relative"},children:[p(s.Group,{grow:!0,children:[i(v.Controller,{name:`columns.${e}.label`,control:t,render:({field:l})=>i(s.TextInput,{label:"Label",required:!0,id:`col-label-${e}`,sx:{flex:1},...l})}),i(v.Controller,{name:`columns.${e}.value_field`,control:t,render:({field:l})=>i(j,{label:"Value Field",required:!0,...l})})]}),p(s.Group,{grow:!0,children:[i(v.Controller,{name:`columns.${e}.value_type`,control:t,render:({field:l})=>i(oC,{label:"Value Type",sx:{flex:1},...l})}),o===Je.custom&&i(v.Controller,{name:`columns.${e}.func_content`,control:t,render:({field:l})=>i(lC,{value:l.value??gs,onChange:u=>l.onChange(u??"")})})]}),i(s.Divider,{mb:-10,variant:"dashed",label:"Style",labelPosition:"center"}),p(s.Group,{grow:!0,children:[i(s.NumberInput,{hideControls:!0,label:"Min Width",rightSection:i(xi,{}),disabled:!0}),i(v.Controller,{name:`columns.${e}.width`,control:t,render:({field:l})=>i(s.NumberInput,{hideControls:!0,label:"Width",rightSection:i(xi,{}),...l})}),i(s.NumberInput,{hideControls:!0,label:"Max Width",rightSection:i(xi,{}),disabled:!0})]}),i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:`columns.${e}.align`,control:t,render:({field:l})=>i(s.Select,{label:"Alignment",data:uC,...l})})}),i(v.Controller,{name:`columns.${e}.cellBackgroundColor`,control:t,render:({field:l})=>i(iC,{...l})}),i(s.Divider,{mb:4,mt:12,variant:"dashed"}),i(s.Button,{leftIcon:i(D.Trash,{size:16}),color:"red",variant:"light",onClick:()=>r(e),children:"Delete this column"})]})},dC=({control:t,watch:e})=>{const{fields:n,append:r,remove:a,update:o}=v.useFieldArray({control:t,name:"columns"}),l=()=>{const c=Me.randomId();r({id:c,label:c,align:"center",value_field:"",value_type:Je.string,width:""})};e("columns");const u=e("use_raw_columns");return p(V,{children:[i(v.Controller,{name:"use_raw_columns",control:t,render:({field:c})=>i(s.Switch,{mt:20,mb:20,label:"Use Original Data Columns",checked:c.value,onChange:d=>c.onChange(d.currentTarget.checked)})}),!u&&i(s.Stack,{children:p(s.Tabs,{defaultValue:"0",styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[n.map((c,d)=>i(s.Tabs.Tab,{value:d.toString(),children:d+1},c.id)),i(s.Tabs.Tab,{onClick:l,value:"add",children:i(D.Plus,{size:18,color:"#228be6"})})]}),n.map((c,d)=>i(s.Tabs.Panel,{value:d.toString(),children:i(cC,{control:t,watch:e,index:d,column:c,remove:a},d)},c.id))]})})]})};function pC({control:t,watch:e}){return e(["horizontalSpacing","verticalSpacing","fontSize","striped","highlightOnHover"]),p(s.Stack,{spacing:"xs",children:[p(s.Group,{position:"apart",mb:"lg",grow:!0,sx:{"> *":{flexGrow:1}},children:[i(v.Controller,{name:"horizontalSpacing",control:t,render:({field:n})=>i(s.TextInput,{label:"Horizontal Spacing",placeholder:"10px, 1em, 1rem, 100%...",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"verticalSpacing",control:t,render:({field:n})=>i(s.TextInput,{label:"Vertical Spacing",placeholder:"10px, 1em, 1rem, 100%...",required:!0,sx:{flex:1},...n})})]}),i(s.Group,{position:"apart",mb:"lg",grow:!0,sx:{"> *":{flexGrow:1}},children:i(v.Controller,{name:"fontSize",control:t,render:({field:n})=>i(s.TextInput,{label:"Font Size",placeholder:"10px, 1em, 1rem, 100%...",required:!0,sx:{flex:1},...n})})}),p(s.Group,{position:"apart",grow:!0,children:[i(v.Controller,{name:"striped",control:t,render:({field:n})=>i(s.Switch,{label:"Striped",checked:n.value,onChange:r=>n.onChange(r.currentTarget.checked)})}),i(v.Controller,{name:"highlightOnHover",control:t,render:({field:n})=>i(s.Switch,{label:"Highlight on hover",checked:n.value,onChange:r=>n.onChange(r.currentTarget.checked)})})]})]})}function hC({columns:t,...e}){return{...e,columns:t.map(({id:n,...r})=>({id:n??Me.randomId(),...r}))}}function fC({context:t}){const{value:e,set:n}=W(t.instanceData,"config"),r=y.useMemo(()=>x.defaultsDeep({},e,vr),[e]),a=y.useMemo(()=>hC(r),[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(["id_field"]),p("form",{onSubmit:l(n),children:[p(s.Group,{position:"apart",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Table Config"}),i(s.ActionIcon,{type:"submit","aria-label":"save config",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(D.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"Columns",orientation:"vertical",styles:{tab:{paddingLeft:"6px",paddingRight:"6px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"Columns",children:"Columns"}),i(s.Tabs.Tab,{value:"Style",children:"Style"})]}),p(s.Tabs.Panel,{value:"Columns",children:[i(v.Controller,{name:"id_field",control:o,render:({field:g})=>i(j,{label:"ID Field",required:!0,...g})}),i(s.Divider,{mt:20,mb:10,variant:"dashed"}),i(dC,{control:o,watch:u})]}),i(s.Tabs.Panel,{value:"Style",children:i(pC,{control:o,watch:u})})]})]})}function gC(t){const{columns:e,...n}=t;return{...t,columns:e.map(r=>({...r,align:r.align??"left"}))}}function mC(t,{panelModel:e}){try{const n=e.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=u=>u&&`${n}.${u}`,{id_field:a,columns:o,...l}=t;return{...l,id_field:r(a),columns:o.map(u=>({...u,value_field:r(u.value_field)}))}}catch(n){throw console.error("[Migration failed]",n),n}}function yC(t){const{columns:e,...n}=t;return{...n,columns:e.map(r=>({...r,align:r.align??"left",cellBackgroundColor:r.cellBackgroundColor??"",width:r.width??""}))}}class bC extends ve{constructor(){super(...arguments);N(this,"VERSION",5)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,n=>{const{columns:r,...a}=n.config;return{...n,version:2,config:{...a,columns:r.map(({id:o,...l})=>({id:o??Me.randomId(),...l}))}}}),this.version(3,n=>({...n,version:3,config:gC(n.config)})),this.version(4,(n,r)=>({...n,version:4,config:mC(n.config,r)})),this.version(5,n=>({...n,version:5,config:yC(n.config)}))}}const wi={createConfig(){return{version:5,config:x.cloneDeep(vr)}},displayName:"Table",displayGroup:"Others",migrator:new bC,name:"table",viewRender:Qw,configRender:fC,triggers:[vi]},vC=b.types.model("PanelLayoutModel",{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(t=>({get json(){const{x:e,y:n,w:r,h:a,moved:o}=t;return{h:a,w:r,x:e,y:n===null?0:n,moved:o,static:t.static}}})).actions(t=>({set(e){const{x:n,y:r,w:a,h:o,moved:l}=e;t.x=n,t.y=r,t.w=a,t.h=o,t.moved=!!l,t.static=!!e.static}})),xC=b.types.model("PanelStyleBorderModel",{enabled:b.types.boolean}).views(t=>({get json(){const{enabled:e}=t;return{enabled:e}}})).actions(t=>({setEnabled(e){t.enabled=e}})),wC=b.types.model("PanelStyleModel",{border:xC}).views(t=>({get json(){const{border:e}=t;return{border:e.json}}})).actions(t=>({})),CC=b.types.model("PanelVizModel",{type:b.types.string,conf:b.types.frozen()}).views(t=>({get json(){return{conf:t.conf,type:t.type}}})).actions(t=>({setType(e){t.type=e},setConf(e){t.conf=e}})),Uo=b.types.model({id:b.types.string,title:b.types.string,description:b.types.string,layout:vC,queryIDs:b.types.array(b.types.string),viz:CC,style:wC,variables:b.types.optional(b.types.array(Qu),[])}).views(t=>({get contentModel(){return b.getParentOfType(t,Zn)}})).views(t=>({get queryIDSet(){return new Set(t.queryIDs)},get queries(){return t.contentModel.queries.findByIDSet(this.queryIDSet)},get data(){return this.queries.reduce((e,n)=>(e[n.id]=n.data.toJSON(),e),{})},get dataLoading(){return this.queries.some(e=>e.state==="loading")},get queryStateMessages(){return this.queries.map(e=>e.stateMessage).filter(e=>!!e)},get queryErrors(){return this.queries.map(e=>e.error).filter(e=>!!e)},get canRenderViz(){return this.queryErrors.length===0&&this.queryStateMessages.length===0&&!this.dataLoading},get json(){const{id:e,title:n,description:r,queryIDs:a}=t;return{id:e,viz:t.viz.json,style:t.style.json,title:n,layout:t.layout.json,queryIDs:[...a],variables:t.variables.map(o=>o.json),description:r}},get dataFieldOptions(){return t.queryIDs.length===0?[]:this.queries.map(e=>{const n=e.data;return n.length===0?[]:Object.keys(n[0]).map(a=>({label:a,value:`${e.id}.${a}`,group:e.name}))}).flat()}})).actions(t=>({setID(e){t.id=e},setTitle(e){t.title=e},setDescription(e){t.description=e},addQueryID(e){t.queryIDSet.has(e)||t.queryIDs.push(e)},removeQueryID(e){if(!t.queryIDSet.has(e))return;const n=new Set(t.queryIDSet);n.delete(e),t.queryIDs=b.cast(Array.from(n))},setQueryIDs(e){t.queryIDs=b.cast(e)},addVariable(e){t.variables.push(e)},removeVariable(e){t.variables.remove(e)},removeSelf(){b.getParent(t,2).removeByID(t.id)}})).actions(t=>({moveToView(e,n){b.getRoot(t).content.views.findByID(e).removePanelID(t.id),b.getRoot(t).content.views.findByID(n).appendPanelID(t.id),b.getRoot(t).editor.setPath(["_VIEWS_",n,"_PANELS_",t.id])},refreshData(){t.queries.forEach(e=>e.fetchData())},downloadData(){b.getRoot(t).content.queries.downloadDataByQueryIDs(t.queryIDs)}}));function Xo(t){return{id:t,layout:{x:0,y:1/0,w:18,h:300},title:t,description:"<p></p>",queryIDs:[],viz:{type:wi.name,conf:wi.createConfig()},style:{border:{enabled:!0}}}}const Jo=b.types.model("PanelsModel",{list:b.types.optional(b.types.array(Uo),[])}).views(t=>({get json(){return t.list.map(e=>e.json)},findByID(e){return t.list.find(n=>n.id===e)},get idMap(){const e=new Map;return t.list.forEach(n=>{e.set(n.id,n)}),e}})).views(t=>({panelsByIDs(e){const n=[];e.forEach(a=>{const o=t.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}}})).views(t=>({editorOptions(e,n){const{panels:r}=t.panelsByIDs(n);r.length!==n.length&&console.warn(`Unfulfilled panels for View[${e}]`);const a=r.map(l=>({label:l.title?l.title:x.capitalize(l.viz.type),value:l.id,_type:"panel",parentID:e})),o="_Add_A_PANEL_";return a.push({label:o,value:o,_type:"ACTION",_action_type:o,parentID:e,Icon:null,children:null}),a}})).actions(t=>({replace(e){t.list=b.castToSnapshot(e)},append(e){t.list.push(e)},remove(e){t.list.splice(e,1)},removeByID(e){const n=t.list.findIndex(r=>r.id===e);n!==-1&&t.list.splice(n,1)},duplicateByID(e){const n=t.list.find(a=>a.id===e);if(!n){console.error(new Error(`[duplicate panel] Can't find a panel by id[${e}]`));return}const r=new Date().getTime().toString();return t.list.push({...n.json,id:r,layout:{...n.layout,y:1/0,moved:!1}}),r},replaceByIndex(e,n){t.list.splice(e,1,n)}}));var Zo=(t=>(t.Use="use",t.Edit="edit",t))(Zo||{}),H=(t=>(t.Division="div",t.Modal="modal",t.Tabs="tabs",t))(H||{});const SC={div:"Division",tabs:"Tabs",modal:"Modal"},Ho={div:"rgba(255, 0, 0, 0.2)",modal:"rgba(0, 0, 0, 0.2)",tabs:"rgba(255, 200, 100, 0.4)"},_C={div:"#ff4000",modal:"#000",tabs:"#ffad18"},kC={definition:{sqlSnippets:[],queries:[],mock_context:{}},views:[{id:"Main",name:"Main",type:"div",config:{},panelIDs:[]}],panels:[],filters:[],version:"9.19.0"};var Ci=(t=>(t.Select="select",t.TreeSelect="tree-select",t.MultiSelect="multi-select",t.TextInput="text-input",t.Checkbox="checkbox",t.DateRange="date-range",t))(Ci||{});const el=b.types.model("ViewModel_Division",{_name:b.types.literal(H.Division)}).views(t=>({get json(){const{_name:e}=t;return{_name:e}}})).actions(t=>({})),TC=()=>el.create({_name:H.Division}),Si={enabled:!1,func_content:["function text({ filters, context}) {"," // your code goes here",' return "text"',"}"].join(`
481
- `)},DC=b.types.model("CustomModalTitleModel",{enabled:b.types.optional(b.types.boolean,!1),func_content:b.types.optional(b.types.string,"")}).views(t=>({get json(){const{enabled:e,func_content:n}=t;return{enabled:e,func_content:n}},get value(){const{enabled:e,func_content:n}=t,r=b.getParent(t,2),a=b.getRoot(t);if(!e)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(t=>({setEnabled(e){t.enabled=e},setFuncContent(e){t.func_content=e},replace({enabled:e,func_content:n}){t.enabled=e,t.func_content=n}})),tl=b.types.model("ViewModel_Modal",{_name:b.types.literal(H.Modal),width:b.types.string,height:b.types.string,custom_modal_title:b.types.optional(DC,Si)}).views(t=>({get json(){const{_name:e,width:n,height:r,custom_modal_title:a}=t;return{_name:e,width:n,height:r,custom_modal_title:a.json}}})).actions(t=>({setWidth(e){t.width=e},setHeight(e){t.height=e}})),MC=()=>tl.create({_name:H.Modal,width:"90vw",height:"90vh"}),IC=b.types.model("ViewModel_Tabs_Tab",{id:b.types.identifier,name:b.types.string,view_id:b.types.string,color:b.types.optional(b.types.string,"")}).views(t=>({get json(){const{id:e,name:n,view_id:r,color:a}=t;return{id:e,name:n,color:a,view_id:r}}})).actions(t=>({setName(e){t.name=e},setViewID(e){t.view_id=e},setColor(e){t.color=e}})),nl=b.types.model("ViewModel_Tabs",{_name:b.types.literal(H.Modal),tabs:b.types.optional(b.types.array(IC),[]),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(t=>({get json(){const{_name:e,variant:n,orientation:r,tabs:a,grow:o}=t;return{grow:o,tabs:a.map(l=>l.json),_name:e,variant:n,orientation:r}}})).actions(t=>({setVariant(e){t.variant=e},setOrientation(e){t.orientation=e},setGrow(e){t.grow=e},setTabs(e){t.tabs.length=0,t.tabs=b.cast(e)},addTab(){const e=Me.randomId(),n={id:e,name:e,view_id:""};t.tabs.push(n)},removeTab(e){t.tabs.splice(e,1)}})),EC=()=>nl.create({_name:H.Modal,tabs:[]}),rl=b.types.model({id:b.types.identifier,name:b.types.string,type:b.types.enumeration("EViewComponentType",[H.Division,H.Modal,H.Tabs]),config:b.types.union(el,tl,nl),panelIDs:b.types.optional(b.types.array(b.types.string),[])}).views(t=>({get json(){const{id:e,name:n,type:r,config:a}=t;return{id:e,name:n,type:r,config:a.json,panelIDs:t.panelIDs}}})).actions(t=>({setName(e){t.name=e},setType(e){if(t.type!==e){switch(e){case H.Division:t.config=TC();break;case H.Modal:t.config=MC();break;case H.Tabs:t.config=EC();break}t.type=e}},appendPanelID(e){t.panelIDs.push(e)},removePanelID(e){const n=t.panelIDs.filter(r=>r!==e);t.panelIDs.length=0,t.panelIDs.push(...n)}})).actions(t=>({})),il=b.types.model("ViewsModel",{current:b.types.optional(b.types.array(rl),[]),visibleViewIDs:b.types.array(b.types.string),idOfVIE:b.types.string}).views(t=>({get json(){return t.current.map(e=>yn(e.json))},get idMap(){const e=new Map;return t.current.forEach(n=>{e.set(n.id,n)}),e},findByID(e){return t.current.find(n=>n.id===e)},get isVIETheFirstView(){return t.current.length===0||!t.idOfVIE?!1:t.current[0].id===t.idOfVIE},get firstVisibleView(){const[e]=t.visibleViewIDs;return t.current.find(({id:n})=>n===e)},get visibleViews(){const e=new Set(t.visibleViewIDs);return t.current.filter(({id:n})=>e.has(n))},get VIE(){return t.current.find(({id:e})=>e===t.idOfVIE)},get options(){return t.current.map(e=>({label:e.name,value:e.id,type:e.type}))},get editorOptions(){const e=b.getRoot(t).content.panels;return t.current.map(n=>({label:n.name,value:n.id,_type:"view",children:e.editorOptions(n.id,n.panelIDs)}))}})).actions(t=>({replace(e){t.current.replace(e)},addANewView(e,n,r,a){t.current.push({id:e,name:n,type:r,config:a,panelIDs:[]})},append(e){t.current.push(e)},remove(e){t.current.splice(e,1)},removeByID(e){const n=t.current.findIndex(r=>r.id===e);n!==-1&&t.current.splice(n,1)},replaceByIndex(e,n){t.current.splice(e,1,n)},setIDOfVIE(e){t.idOfVIE=e,t.visibleViewIDs.length=0,t.visibleViewIDs.push(e)},appendToVisibles(e){new Set(t.visibleViewIDs.map(r=>r)).has(e)||t.visibleViewIDs.push(e)}})).actions(t=>({addARandomNewView(){const e=new Date().getTime().toString();t.addANewView(e,H.Division,H.Division,{_name:H.Division}),t.setIDOfVIE(e)},removeVIE(){t.current.length!==1&&(t.removeByID(t.idOfVIE),t.setIDOfVIE(t.current[0].id))},rmVisibleViewID(e){const n=t.visibleViewIDs.findIndex(r=>r===e);n!==-1&&t.visibleViewIDs.splice(n,1)}}));function _i(t){const e=t.length>0?[t[0].id]:[],n=t.length>0?t[0].id:"";return{current:t.map(a=>{const{_name:o=a.type}=a.config;return{...a,config:{...a.config,_name:o},panelIDs:a.panelIDs}}),visibleViewIDs:e,idOfVIE:n}}function al(t,e,n,r){return t.reduce((a,o)=>(a[o[e]]=pr(o[n],r),a),{})}const AC=b.types.model({id:b.types.string,name:b.types.string,dashboard_id:b.types.string,create_time:b.types.string,update_time:b.types.string,version:b.types.string,filters:is,queries:ds,sqlSnippets:hs,views:il,panels:Jo,mock_context:Yu,origin:b.types.maybe(b.types.frozen())}).views(t=>({get json(){return{id:t.id,name:t.name,create_time:t.create_time,update_time:t.update_time,dashboard_id:t.dashboard_id,content:{views:t.views.json,panels:t.panels.json,filters:t.filters.json,version:t.version,definition:{queries:t.queries.json,sqlSnippets:t.sqlSnippets.json,mock_context:t.mock_context.current}}}},get filtersChanged(){const e="filters.current";return!x.isEqual(b.getSnapshot(x.get(t,e)),x.get(t.origin,e))},get queriesChanged(){const e="queries.current",n=b.getSnapshot(x.get(t,e)).map(r=>x.pick(r,["id","name","key","type","sql","run_by","react_to","pre_process","post_process"]));return!x.isEqual(n,x.get(t.origin,e))},get sqlSnippetsChanged(){const e="sqlSnippets.current";return!x.isEqual(b.getSnapshot(x.get(t,e)),x.get(t.origin,e))},get viewsChanged(){const e="views.current";return!x.isEqual(b.getSnapshot(x.get(t,e)),x.get(t.origin,e))},get panelsChanged(){const e="panels.list";return!x.isEqual(b.getSnapshot(x.get(t,e)),x.get(t.origin,e))},get mockContextChanged(){const e="mock_context.current";return!x.isEqual(x.get(t,e),x.get(t.origin,e))},get payloadForSQL(){const e=b.getParent(t).context.current,n=b.getParent(t).globalSQLSnippets,r={context:{...t.mock_context.current,...e},filters:t.filters.values};return{...r,sql_snippets:al(t.sqlSnippets.current,"key","value",r),global_sql_snippets:al(n.list,"id","content",r)}},get payloadForViz(){const e=b.getParent(t).context.current;return{context:{...t.mock_context.current,...e},filters:t.filters.values}},get changed(){return this.filtersChanged||this.queriesChanged||this.sqlSnippetsChanged||this.viewsChanged||this.panelsChanged||this.mockContextChanged},get data(){return t.queries.current.map(({id:n,data:r})=>({id:n,data:r})).reduce((n,r)=>(n[r.id]=r.data,n),{})},getDataStuffByID(e){const n=t.queries.findByID(e);return n?{data:n.data.toJSON(),len:n.data.length,state:n.state,error:n.error}:{data:[],len:0,state:"idle",error:void 0}}})).views(t=>({findQueryUsage(e){const n=t.panels.idMap,r=t.views.current.flatMap(l=>l.panelIDs.map(u=>n.get(u)).filter(u=>(u==null?void 0:u.queryIDSet.has(e))??!1).map(u=>({type:"panel",id:u.id,label:u.title?u.title:u.viz.type,views:[{id:l.id,label:l.name}]}))),a=t.views.idMap,o=t.filters.current.filter(l=>x.get(l,"config.options_query_id")===e).map(l=>({type:"filter",id:l.id,label:l.label,views:l.visibleInViewsIDs.map(u=>{var c;return{id:u,label:((c=a.get(u))==null?void 0:c.name)??u}})}));return r.concat(o)}})).actions(t=>({duplicatePanelByID(e,n){var a;const r=t.panels.duplicateByID(e);r&&((a=t.views.findByID(n))==null||a.appendPanelID(r))},removePanelByID(e,n){var r;t.panels.removeByID(e),(r=t.views.findByID(n))==null||r.removePanelID(e)},addANewPanel(e){var r;const n=new Date().getTime().toString();t.panels.append(Xo(n)),(r=t.views.findByID(e))==null||r.appendPanelID(n)}})).actions(t=>({reset(){b.applySnapshot(t.filters.current,t.origin.filters.current),b.applySnapshot(t.queries.current,t.origin.queries.current),b.applySnapshot(t.sqlSnippets.current,t.origin.sqlSnippets.current),b.applySnapshot(t.views.current,t.origin.views.current),b.applySnapshot(t.panels.list,t.origin.panels.list),t.mock_context.current=t.origin.mock_context.current},resetFilters(){b.applySnapshot(t.filters.current,t.origin.filters.current)},updateCurrent(e){const{id:n,name:r,content:a}=e;if(!a)throw new Error("unexpected null content when updating a content model");const{version:o,filters:l,views:u,panels:c,definition:{queries:d,sqlSnippets:f,mock_context:h={}}}=a;t.id=n,t.name=r,t.version=o,b.applySnapshot(t.filters.current,l),b.applySnapshot(t.views.current,_i(u).current),b.applySnapshot(t.panels.list,c),b.applySnapshot(t.queries.current,d),b.applySnapshot(t.sqlSnippets.current,f),t.mock_context.current=h}})),Zn=b.types.snapshotProcessor(AC,{preProcessor(t){return{...t,origin:t}},postProcessor(t){delete t.origin;const e=b.castToSnapshot(t.queries.current.map(n=>x.pick(n,["id","key","type","sql"])));return x.defaults({},{queries:{current:e}},t)}});function zC(t,e){e.filters&&b.applySnapshot(t.filters.current,e.filters)}function sl({id:t,name:e,dashboard_id:n,create_time:r,update_time:a,content:o}){if(!o)throw new Error("unexpected null content when creating a content model");const{version:l,filters:u,views:c,panels:d,definition:{queries:f,sqlSnippets:h,mock_context:g={}}}=o;return Zn.create({id:t,name:e,dashboard_id:n,create_time:r,update_time:a,version:l,filters:as(u),queries:{current:f},sqlSnippets:{current:h},mock_context:{current:g},views:_i(c),panels:{list:d}})}const $C=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}),LC=b.types.model("GlobalSQLSnippetsModel",{list:b.types.optional(b.types.array($C),[])}).views(t=>({find(e){return t.list.find(n=>n.id===e)},get options(){return t.list.map(e=>({value:e.id,label:e.id}))}})).actions(t=>({replace(e){t.list.length=0,t.list.push(...e)}})),ol=b.types.model({id:b.types.identifier,name:b.types.string,group:b.types.string,content:Zn,content_id:b.types.string,datasources:Wu,globalSQLSnippets:LC,context:fs,editor:Ru}).views(t=>({get json(){return{id:t.id,name:t.name,group:t.group,content_id:t.content_id}}})).actions(t=>({updateCurrentContent(e){t.content.updateCurrent(e)},updateCurrent(e,n){const{id:r,name:a,group:o,content_id:l}=e;t.id=r,t.name=a,t.group=o,t.content_id=l,this.updateCurrentContent(n)}}));function ki({id:t,name:e,group:n,content_id:r},a,o,l,u){return ol.create({id:t,name:e,group:n,content_id:r,content:sl(a),datasources:{list:o},globalSQLSnippets:{list:l},context:{current:u},editor:{}})}const Ti=y.createContext(null);function Hn(t){const e=y.useContext(Ti),n=X.useCreation(()=>t.configure(e||new wr),[t.configure]),r=X.usePrevious(n);return r&&r!==n&&r.dispose(),i(Ti.Provider,{value:n,children:t.children})}function ll(){return y.useContext(Ti)}const OC={viewPanelInFullScreen:x.noop,inFullScreen:!1},Di=y.createContext(OC),PC=({description:t,isDescriptionEmpty:e})=>e?null:i(s.Tooltip,{color:"white",label:i(Kn,{value:t,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(L.IconInfoCircle,{size:16,color:"gray"})})}),BC=k.observer(({label:t,config:{default_value:e,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:t}),i(PC,{description:n,isDescriptionEmpty:r})]}),checked:o||!1,onChange:u=>l(u.currentTarget.checked),...a,pt:".4em",styles:{input:{borderColor:"#e9ecef"}}})]})),ul=k.observer(({label:t,config:e,value:n=[null,null],onChange:r})=>{const{inputFormat:a,...o}=e,l=Array.isArray(n)?n.map(f=>f?R(f).toDate():null):[null,null],u=f=>{r(f.map(h=>h&&R(h).format(a)))},c=e.getMinDate(l[0]),d=e.getMaxDate(l[0]);return i(ru.DatePickerInput,{type:"range",label:t,value:l,onChange:u,icon:i(D.Calendar,{size:16}),sx:{minWidth:"16em"},minDate:c,maxDate:d,valueFormat:a,styles:{input:{borderColor:"#e9ecef"}},...o})}),VC=s.createStyles((t,{radius:e=4})=>({root:{borderRadius:t.fn.radius(e),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:t.fontSizes.sm,fontWeight:500,color:"#212529"},dropdown:{fontSize:t.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":{flexGrow:1}}}})),cl=({errorMessage:t})=>t?i(s.Text,{color:"red",size:12,children:t}):i(s.Text,{color:"dimmed",size:12,children:"Not found"}),NC=({disabled:t,classNames:e,styles:n,unstyled:r,radius:a,style:o,label:l,value:u,onChange:c,options:d,errorMessage:f})=>{const{classes:h,cx:g}=VC({radius:a},{name:"MultiSelectWidget",classNames:e,styles:n,unstyled:r}),[m,w]=y.useState(!1),C=B=>{w(B)},_=m&&(u==null?void 0:u.length)>0,[T,I]=y.useState(""),O=y.useMemo(()=>{if(!T)return d;const B=T.toLowerCase(),$=A=>{var E;return((E=A.description)==null?void 0:E.toLowerCase().includes(B))||A.label.toLowerCase().includes(B)};return d.filter($)},[T,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(qa,{disabled:t,allowClear:!0,className:g(h.root,"check-select"),dropdownClassName:g(h.dropdown,""),onDropdownVisibleChange:C,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(cl,{errorMessage:f}),maxTagTextLength:10,maxTagPlaceholder:B=>`${B.length} selected`,searchValue:T,onSearch:I,filterOption:!1,children:O.map(B=>i(qa.Option,{children:i(s.Group,{noWrap:!0,children:p("div",{children:[i(s.Text,{size:"sm","data-role":"label",children:B.label}),B.description&&i(s.Text,{size:"xs",color:"dimmed","data-role":"description",children:B.description})]})})},B.value))})]})},qC=k.observer(({label:t,config:e,value:n,onChange:r})=>{const a=K(),o=!!e.options_query_id,{state:l,error:u}=a.getDataStuffByID(e.options_query_id),c=l==="loading",d=e.min_width?e.min_width:"200px",f=o?c:!1,h=g=>r(g,!1);return i(NC,{label:t,options:e.options,style:{minWidth:"160px",width:d,maxWidth:f?d:"unset",borderColor:"#e9ecef"},disabled:f,value:n,onChange:h,errorMessage:u})}),FC=y.forwardRef(({label:t,description:e,...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:t}),i(s.Text,{size:"xs",color:"dimmed","data-role":"description",children:e})]})})})),GC=k.observer(({label:t,config:e,value:n,onChange:r})=>{const a=K(),o=!!e.options_query_id,{state:l,error:u}=a.getDataStuffByID(e.options_query_id),c=l==="loading";return y.useEffect(()=>{var h;const{default_selection_count:d}=e;if(!d)return;const f=((h=e.options[0])==null?void 0:h.value)??"";console.log("Selecting the first option by default. New value: ",f),r(f,!0)},[e.default_selection_count,e.options]),i(s.Select,{label:t,data:e.options,disabled:o?c:!1,value:n,onChange:r,error:!!u,placeholder:u,maxDropdownHeight:500,styles:{root:{width:e.width?e.width:"200px"},input:{borderColor:"#e9ecef"}},sx:{".mantine-Select-item[data-selected] .mantine-Text-root[data-role=description]":{color:"rgba(255,255,255,.7)"}},itemComponent:FC})});function WC({label:t,config:e,value:n,onChange:r}){return i(s.TextInput,{label:t,value:n||"",onChange:a=>r(a.currentTarget.value),...e,styles:{input:{borderColor:"#e9ecef"}}})}const jC=({rotate:t,onClick:e})=>i("svg",{onClick:e,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(${t})`,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"})}),RC=({expanded:t,isLeaf:e,value:n,onClick:r,...a})=>(n==="0-0-value"&&console.log(a),e?i("span",{style:{width:"14px",display:"inline-block"}}):i(jC,{rotate:t?"0":"-90",onClick:r,...a})),YC=({onClick:t})=>p("svg",{onClick:t,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"})]}),QC=({onClick:t,...e})=>i(YC,{onClick:t,...e}),KC=s.createStyles((t,{radius:e=4})=>({root:{borderRadius:t.fn.radius(e),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:t.fontSizes.sm,fontWeight:500,color:"#212529"},dropdown:{fontSize:t.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"}}}})),UC=({disabled:t,classNames:e,styles:n,unstyled:r,radius:a,style:o,label:l,value:u,onChange:c,treeData:d,errorMessage:f})=>{const{classes:h,cx:g}=KC({radius:a},{name:"FilterTreeSelectWidget",classNames:e,styles:n,unstyled:r}),[m,w]=y.useState(!1),C=T=>{w(T)},_=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(Fa,{disabled:t,allowClear:!0,className:g(h.root,"check-select"),dropdownClassName:g(h.dropdown,""),onDropdownVisibleChange:C,transitionName:"rc-tree-select-dropdown-slide-up",choiceTransitionName:"rc-tree-select-selection__choice-zoom",style:o,treeLine:!0,clearIcon:()=>i(s.CloseButton,{}),switcherIcon:RC,treeIcon:QC,maxTagTextLength:10,value:u,treeData:d,notFoundContent:i(cl,{errorMessage:f}),treeNodeFilterProp:"filterBasis",treeCheckable:!0,showCheckedStrategy:Fa.SHOW_PARENT,onChange:c,onSelect:console.log,maxTagCount:0,maxTagPlaceholder:T=>`${T.length} selected`})]})},XC=k.observer(({label:t,config:e,value:n,onChange:r})=>{const{treeData:a,treeDataLoading:o,errorMessage:l}=e,u=e.min_width?e.min_width:"200px",d=!!e.options_query_id?o:!1;return i(UC,{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:t})}),JC=k.observer(({filter:{type:t,config:e,key:n,...r},formFieldProps:a})=>{switch(t){case"select":return i(GC,{...r,...a,config:e});case"multi-select":return i(qC,{...r,...a,config:e});case"tree-select":return i(XC,{...r,...a,config:e});case"text-input":return i(WC,{...r,...a,config:e});case"date-range":return i(ul,{...r,...a,config:e});case"checkbox":return i(BC,{...r,...a,config:e});default:return null}}),dl=k.observer(y.forwardRef(({filter:t,...e},n)=>i("div",{className:"filter-root",ref:n,children:i(Fe,{children:i(JC,{filter:t,formFieldProps:e})})}))),pl=k.observer(function({view:e}){const n=K(),{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]),y.useEffect(()=>{n.filters.updatePreviewValues(l)},[l]);const u=n.filters.visibleInView(e.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)=>(w,C)=>{m(w),(g.should_auto_submit||C)&&n.filters.setValueByKey(g.key,w)};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(dl,{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"})})]})})}),mD="";function ZC(t){return t?["<p><br></p>","<p></p>"].includes(t):!0}const hl=k.observer(()=>{const{freezeLayout:t}=y.useContext(ft),[e,n]=y.useState(!1),{panel:r}=ze();return y.useEffect(()=>{t(e)},[e]),ZC(r.description)?null:p(V,{children:[i(s.Modal,{opened:e,onClose:()=>n(!1),title:r.title,withCloseButton:!1,withinPortal:!0,zIndex:310,children:i(Kn,{value:r.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:()=>n(a=>!a),sx:{verticalAlign:"baseline",cursor:"pointer"},children:i(D.InfoCircle,{size:20})})})]})}),HC=k.observer(({view:t})=>{const e=he(),n=K(),r=Ue.useModals(),{panel:a}=ze(),{id:o}=a,{inEditMode:l}=y.useContext(ft),{viewPanelInFullScreen:u,inFullScreen:c}=y.useContext(Di),d=()=>{n.duplicatePanelByID(o,t.id)},f=()=>{e.editor.open(["_VIEWS_",t.id,"_PANELS_",o])},h=()=>r.openConfirmModal({title:"Delete this panel?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>n.removePanelByID(o,t.id),confirmProps:{color:"red"},zIndex:320}),g=y.useCallback(()=>{u(o)},[o,u]),m=!c&&t.type!==H.Modal;return i(V,{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(D.Refresh,{size:14}),children:"Refresh"}),i(s.Menu.Item,{onClick:a.downloadData,icon:i(D.Download,{size:14}),children:"Download Data"}),m&&i(s.Menu.Item,{onClick:g,icon:i(D.ArrowsMaximize,{size:14}),disabled:l,children:"Full Screen"}),l&&p(V,{children:[i(s.Divider,{label:"Edit",labelPosition:"center"}),i(s.Menu.Item,{onClick:f,icon:i(D.Settings,{size:14}),children:"Settings"}),i(s.Menu.Item,{onClick:d,icon:i(D.Copy,{size:14}),children:"Duplicate"}),i(s.Menu.Item,{color:"red",onClick:h,icon:i(D.Trash,{size:14}),children:"Delete"})]})]})]})})})}),e1=k.observer(({panel:t})=>p(s.Stack,{children:[t.queryErrors.map((e,n)=>i(s.Text,{color:"red",size:"md",align:"center",sx:{fontFamily:"monospace"},children:e},`${n}-${e}`)),t.queryStateMessages.map((e,n)=>i(s.Text,{color:"gray",align:"center",children:e},`${n}-${e}`))]}));var fl=(t=>(t.migrated="migrated",t.nothingToMigrate="nothingToMigrate",t.checkFailed="checkFailed",t.migrationFailed="migrationFailed",t))(fl||{}),er=(t=>(t.notStarted="notStarted",t.inProgress="inProgress",t.done="done",t))(er||{});class t1{constructor(e){N(this,"vizInstance");N(this,"operationManager");N(this,"triggerManager");N(this,"vizManager");N(this,"runningMigration");N(this,"panelModel");N(this,"status","notStarted");this.panelModel=e.getRequired(Ce.instanceScope.panelModel),this.vizInstance=e.getRequired(Ce.instanceScope.vizInstance),this.operationManager=e.getRequired(Ce.instanceScope.operationManager),this.triggerManager=e.getRequired(Ce.instanceScope.triggerManager),this.vizManager=e.getRequired(Ce.vizManager)}async createMigrationTask(){const e=[];try{await this.instanceNeedMigration()&&e.push(()=>this.runInstanceMigration()),await this.interactionNeedMigration()&&e.push(()=>this.runInteractionMigration())}catch(n){return console.warn("check migration failed",n),"checkFailed"}if(e.length===0)return"nothingToMigrate";try{return await Promise.all(e.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(e=>(this.status="done",e))),this.runningMigration}async runInteractionMigration(){await this.operationManager.runMigration(),await this.triggerManager.runMigration()}async runInstanceMigration(){const e=this.vizManager.resolveComponent(this.vizInstance.type),n={configData:this.vizInstance.instanceData,panelModel:this.panelModel};await e.migrator.migrate(n)}async instanceNeedMigration(){const e=this.vizManager.resolveComponent(this.vizInstance.type),n={configData:this.vizInstance.instanceData};return e.migrator.needMigration(n)}async interactionNeedMigration(){return await this.operationManager.needMigration()||await this.triggerManager.needMigration()}}function gl(t){const{panel:e}=ze();return y.useCallback(n=>{const r=n.getRequired(Ce.vizManager),a=r.resolveComponent(t.viz.type);return n.createScoped().provideFactory(Ce.instanceScope.vizInstance,()=>r.getOrCreateInstance(t)).provideFactory(Ce.instanceScope.interactionManager,o=>{const l=o.getRequired(Ce.instanceScope.vizInstance);return new bi(l,a,Jn)}).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,e).provideFactory(Ce.instanceScope.migrator,o=>new t1(o))},[t.viz.type,t.viz.conf])}function ml(t){const[e,n]=y.useState(!1),r=ll().getRequired(Ce.instanceScope.migrator);return X.useAsyncEffect(async()=>{const a=r.status===er.notStarted;n(r.status===er.done),r.status===er.notStarted&&r.runMigration().then(o=>{o===fl.migrated&&a&&(t==null||t())}).finally(()=>{n(!0)})},[r]),e}function yl(t,e){const n=ll().getRequired(Ce.instanceScope.vizInstance);return y.useEffect(()=>(n.instanceData.setItem(null,e.viz.conf),n.instanceData.watchItem(null,r=>{t(r)})),[t,e.viz.type]),n}function n1({setVizConf:t,...e}){const{panel:n}=e,r=yl(t,n),a=ml(()=>{hn.showNotification({title:`${n.title} - Updated`,message:"Your plugin configuration has been migrated to the latest version"})});return X.useAsyncEffect(async()=>{await r.instanceData.setItem(null,n.viz.conf)},[r,n.viz.type]),a?i(ec,{...e}):i(s.Text,{children:"Checking update..."})}function r1(t){const{panel:e,setVizConf:n}=t;yl(n,e);const{inEditMode:r}=y.useContext(ft);return ml(()=>{r&&hn.showNotification({title:`${e.title} - Updated`,message:"Your plugin configuration has been migrated to the latest version"})})?i(Hu,{...t}):i(s.Text,{children:"Checking update"})}const yD="";function i1(t,e){const{vizManager:n}=y.useContext(at),{panel:{viz:r,title:a,id:o,description:l,queryIDs:u,variables:c}}=ze(),d={title:a,id:o,description:l,queryIDs:u,viz:r,layout:e},f=gl(d);try{return n.resolveComponent(r.type),i(Hn,{configure:f,children:i(r1,{setVizConf:r.setConf,panel:d,data:t,variables:c,vizManager:n})})}catch(h){return console.info(x.get(h,"message")),null}}const a1=k.observer(function({data:e}){const{ref:n,width:r,height:a}=Me.useElementSize(),o=i1(e,{w:r,h:a}),l=r>0&&a>0;return i("div",{className:"viz-root",ref:n,children:l&&i(Fe,{children:o})})}),bl=k.observer(({panel:t,height:e})=>p(s.Flex,{direction:"column",sx:{height:e,position:"relative",width:"100%"},children:[i(s.LoadingOverlay,{visible:t.dataLoading,exitTransitionDuration:0}),!t.canRenderViz&&i(e1,{panel:t}),t.canRenderViz&&i(a1,{data:t.data})]})),bD="",s1=k.observer(function(){const{panel:e}=ze(),{title:n}=e;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 o1(t){return!["richText","button"].includes(t)}const l1={border:"1px solid #e9ecef"},u1={border:"1px dashed transparent",transition:"border-color 300ms ease","&:hover":{borderColor:"#e9ecef"}};function c1(t,e){return t.style.border.enabled?l1:e?u1:{border:"1px dashed transparent"}}const tr=k.observer(function({panel:e,view:n}){const{inEditMode:r}=y.useContext(ft),a=e.title?"calc(100% - 25px - 5px)":"100%",o=c1(e,r),u=o1(e.viz.type)||r;return i(Sr,{value:{panel:e,data:e.data,loading:e.dataLoading,errors:e.queryErrors},children:p(s.Box,{className:"panel-root",p:5,pt:0,sx:{...o},children:[i(s.Box,{sx:{position:"absolute",left:0,top:0,height:28,zIndex:310},children:i(hl,{})}),u&&i(HC,{view:n}),i(s1,{}),i(bl,{panel:e,height:a})]})})}),vD="",d1=y.forwardRef(({h:t},e)=>i(s.ActionIcon,{ref:e,className:"react-grid-customDragHandle",sx:{userSelect:"none",cursor:"grab",position:"absolute",top:5,right:t>38?5:20,zIndex:400,"&:hover":{color:"#228be6"}},variant:"transparent",children:i(D.ArrowsMove,{size:16})})),p1=y.forwardRef(({handleAxis:t,...e},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",...e,children:i(D.ChevronDownRight,{size:16})})),h1=fn.WidthProvider(fn),f1=k.observer(({view:t,className:e="layout"})=>{const n=K(),{panels:r,layouts:a}=n.panels.panelsByIDs(t.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(h1,{onLayoutChange:o,className:`dashboard-layout ${e}`,rowHeight:1,cols:36,margin:[0,0],isBounded:!0,isDraggable:!0,isResizable:!0,layout:a,draggableHandle:".react-grid-customDragHandle",resizeHandle:i(p1,{}),onResize:l,children:r.map((u,c)=>p("div",{"data-grid":{...u.layout},className:"panel-grid-item",children:[i(d1,{h:u.layout.h}),i(tr,{view:t,panel:u})]},u.id))})}),g1=fn.WidthProvider(fn),m1=k.observer(function({view:e,className:n="layout"}){const{panels:r,layouts:a}=K().panels.panelsByIDs(e.panelIDs);return i(g1,{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(tr,{view:e,panel:o})},o.id))})}),y1=k.observer(({children:t})=>i(s.Box,{pt:10,pb:100,children:t}));function vl(t){return t.replace(/(vw|vh)/,"%")}const b1=k.observer(({children:t,view:e})=>{const n=e.config,{width:r,height:a}=y.useMemo(()=>({width:vl(n.width),height:vl(n.height)}),[n.width,n.height]);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:n.custom_modal_title.value,trapFocus:!0,onDragStart:o=>{o.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%)",width:r,height:a},content:{border:"1px solid #efefef"},body:{maxHeight:"calc(100vh - 325px)"}},withinPortal:!1,transitionProps:{duration:0},children:t})})}),v1=({variant:t,orientation:e})=>{const n={tab:{},panel:{padding:"16px"}};return t==="pills"&&e==="horizontal"&&(n.tab.paddingTop="6px",n.tab.paddingBottom="6px"),e==="vertical"&&(n.tab["&.add-a-tab"]={paddingTop:"1px",paddingBottom:"1px"},n.tab["&.add-a-tab .mantine-Tabs-tabLabel"]={marginLeft:"auto",marginRight:"auto"}),n},x1=t=>t.color?{"&[data-active], &[data-active]:hover":{borderColor:t.color?t.color:"..."}}:{},w1=k.observer(({children:t,view:e})=>{const n=Ue.useModals(),r=K(),a=y.useMemo(()=>r.views.options.filter(c=>c.type===H.Division),[e.id,r.views.options]),o=e.config,l=c=>n.openConfirmModal({title:"Delete this tab?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>{o.removeTab(c)},confirmProps:{color:"red"},zIndex:320}),u=o.tabs.length===0;return p(s.Box,{className:"preview-view-tabs",children:[p(s.Tabs,{variant:o.variant,orientation:o.orientation,defaultValue:o.tabs.length>0?o.tabs[0].id:"0",styles:v1(o),children:[p(s.Tabs.List,{grow:o.grow,children:[o.tabs.map(c=>i(s.Tabs.Tab,{value:c.id,sx:x1(c),children:c.name??c.id},c.id)),i(s.Tabs.Tab,{onClick:o.addTab,value:"add",className:"add-a-tab",children:i(D.Plus,{size:18,color:"#228be6"})})]}),o.tabs.map((c,d)=>{const f=r.views.findByID(c.view_id);return p(s.Tabs.Panel,{value:c.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:c.name,onChange:h=>c.setName(h.currentTarget.value)}),i(s.Select,{label:"View",value:c.view_id,onChange:c.setViewID,data:a}),i(s.ColorInput,{label:"Color",value:c.color,onChange:c.setColor,disabled:o.variant!=="default"}),f&&p(s.Button,{mt:20,variant:"gradient",leftIcon:i(L.IconArrowsLeftRight,{size:18}),gradient:{from:"cyan",to:"indigo"},onClick:()=>r.views.setIDOfVIE(f.id),children:["Swith to View: ",f.name]}),i(s.Button,{mt:20,variant:"subtle",color:"red",onClick:()=>l(d),disabled:u,leftIcon:i(L.IconTrash,{size:14}),children:"Delete This Tab"})]})]}),f&&i(nr,{view:f})]},c.id)})]}),t]})}),C1=k.observer(({view:t,children:e})=>{switch(t.type){case H.Modal:return i(b1,{view:t,children:e});case H.Tabs:return i(w1,{view:t,children:e});case H.Division:default:return i(y1,{children:e})}}),xl=k.observer(function({view:e}){return i(Di.Provider,{value:{viewPanelInFullScreen:x.noop,inFullScreen:!1},children:i(s.Box,{className:"dashboard-view","data-enable-scrollbar":!0,children:i(C1,{view:e,children:p(s.Box,{sx:{position:"relative"},children:[i(s.Box,{className:"dashboard-sticky-area",sx:{position:"sticky",top:"0px"},children:i(pl,{view:e})}),i(f1,{view:e})]})})})})}),S1={modal:{display:"flex",flexDirection:"column",flexWrap:"nowrap"},body:{display:"flex",height:"calc(100vh - 88px)"}},_1=k.observer(function({view:e,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(D.ArrowLeft,{size:20}),children:"Exit fullscreen"}),styles:S1,children:i(s.Group,{grow:!0,sx:{flexGrow:1,flexShrink:0},children:i(tr,{view:e,panel:n})})})});function k1(t,e,n){const{panels:r}=K(),a=t.id==="Main",[o,l]=y.useState(()=>a&&r.findByID(e)?e: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 T1=k.observer(({children:t})=>i(s.Box,{children:t})),D1=k.observer(({children:t,view:e})=>{const n=K(),r=e.config,a=n.views.visibleViewIDs.includes(e.id),o=()=>n.views.rmVisibleViewID(e.id);return i(s.Modal,{size:r.width,centered:!0,opened:a,onClose:o,withCloseButton:!1,title:r.custom_modal_title.value,trapFocus:!0,onDragStart:l=>{l.stopPropagation()},styles:{content:{border:"1px solid #efefef"},body:{maxHeight:r.height,overflow:"auto"}},transitionProps:{duration:0},children:t})}),M1=t=>t.color?{"&[data-active], &[data-active]:hover":{borderColor:t.color?t.color:"..."}}:{},I1=k.observer(({children:t,view:e})=>{const n=K(),r=e.config;return p(s.Box,{className:"render-view-tabs",children:[p(s.Tabs,{variant:r.variant,orientation:r.orientation,defaultValue:r.tabs.length>0?r.tabs[0].id:"0",styles:{panel:{padding:r.orientation==="horizontal"?"16px 0px":"0"}},keepMounted:!1,children:[i(s.Tabs.List,{grow:r.grow,children:r.tabs.map(a=>i(s.Tabs.Tab,{value:a.id,sx:M1(a),disabled:!a.view_id,children:a.name??a.id},a.id))}),r.tabs.map(a=>{const o=n.views.findByID(a.view_id);return o?i(s.Tabs.Panel,{value:a.id,children:i(nr,{view:o})},a.id):null})]}),t]})}),E1=k.observer(({view:t,children:e})=>{switch(t.type){case H.Modal:return i(D1,{view:t,children:e});case H.Tabs:return i(I1,{view:t,children:e});case H.Division:default:return i(T1,{children:e})}}),nr=k.observer(function({view:e}){const{fullScreenPanelID:n,setFullScreenPanelID:r}=ws(),{viewPanelInFullScreen:a,exitFullScreen:o,inFullScreen:l,fullScreenPanel:u}=k1(e,n,r);return i(Di.Provider,{value:{viewPanelInFullScreen:a,inFullScreen:l},children:p(s.Box,{className:"dashboard-view","data-enable-scrollbar":!0,children:[l&&i(_1,{view:e,panel:u,exitFullScreen:o}),i(E1,{view:e,children:p(s.Box,{sx:{position:"relative"},children:[!l&&i(s.Box,{className:"dashboard-sticky-area",sx:{position:"sticky",top:"0px"},children:i(pl,{view:e})}),!l&&i(m1,{view:e})]})})]})})});function Mi(t){return y.useCallback(e=>e.provideValue(Ce.pluginManager,t.pluginManager).provideValue(Ce.vizManager,t.vizManager).provideValue(Ce.colorManager,t.colorManager),[])}const A1=k.observer(({headerMenuItems:t=null})=>{const e=he(),n=K(),r=()=>{const a=JSON.stringify(n.json,null,2),o=`${e.name}__${n.name}`;Au(o,a)};return p(s.Menu,{shadow:"md",width:200,trigger:"hover",openDelay:100,closeDelay:400,withinPortal:!0,zIndex:310,children:[i(s.Menu.Target,{children:i(s.ActionIcon,{variant:"light",color:"blue",children:i(L.IconMenu2,{size:14})})}),p(s.Menu.Dropdown,{children:[i(s.Menu.Item,{icon:i(L.IconDownload,{size:14}),onClick:n.queries.downloadAllData,children:"Download Data"}),i(s.Menu.Item,{icon:i(L.IconCode,{size:14}),onClick:r,children:"Download Schema"}),t]})]})}),z1=k.observer(({saveDashboardChanges:t})=>{const e=Ue.useModals(),n=K(),r=()=>{e.openConfirmModal({title:p(s.Group,{position:"left",children:[i(L.IconAlertTriangle,{size:18,color:"red"}),i(s.Text,{children:"You are reverting changes"})]}),labels:{confirm:"Confirm",cancel:"Cancel"},confirmProps:{color:"red"},onCancel:()=>console.log("Cancel"),onConfirm:()=>n.reset(),zIndex:320,withCloseButton:!1})},a=n.changed;return p(s.Group,{spacing:0,children:[i(s.Button,{color:"green",variant:"filled",size:"xs",leftIcon:i(L.IconDeviceFloppy,{size:18}),onClick:t,disabled:!a,sx:{borderTopRightRadius:0,borderBottomRightRadius:0},children:"Save Changes"}),p(s.Menu,{width:200,trigger:"hover",openDelay:100,closeDelay:400,withinPortal:!0,zIndex:320,disabled:!a,children:[i(s.Menu.Target,{children:i(s.ActionIcon,{variant:"default",disabled:!a,sx:{height:"30px",borderTopLeftRadius:0,borderBottomLeftRadius:0,svg:{fill:"rgb(173, 181, 189)",stroke:"none"}},children:i(L.IconCaretDown,{size:18})})}),i(s.Menu.Dropdown,{children:i(s.Menu.Item,{icon:i(L.IconRecycle,{size:14,color:"red"}),disabled:!a,onClick:r,children:"Revert Changes"})})]})]})}),$1=k.observer(({saveDashboardChanges:t,headerSlot:e=null,headerMenuItems:n})=>{const r=iu.useNavigate(),a=he(),o=()=>{r(`/dashboard/${a.id}`)},l=Ue.useModals(),u=()=>{l.openConfirmModal({title:p(s.Group,{position:"left",children:[i(L.IconAlertTriangle,{size:18,color:"red"}),i(s.Text,{children:"There are unsaved changes"})]}),labels:{confirm:"Discard",cancel:"Cancel"},confirmProps:{color:"red"},onCancel:()=>console.log("Cancel"),onConfirm:o,zIndex:320,withCloseButton:!1})},c=a.content.changed;return i(s.Header,{height:60,px:"md",py:0,sx:{zIndex:299},children:p(s.Group,{position:"apart",sx:{height:60,minWidth:"1000px",position:"relative"},children:[p(s.Group,{children:[i(s.Button,{size:"xs",color:c?"red":"green",leftIcon:i(L.IconArrowLeft,{size:20}),onClick:c?u:o,children:p(s.Group,{spacing:4,children:["End Editing",i(s.Text,{td:"underline",children:a.name})]})}),i(z1,{saveDashboardChanges:t})]}),p(s.Group,{position:"right",sx:{flexGrow:1},children:[e,i(A1,{headerMenuItems:n})]})]})})}),L1={position:"fixed",top:60,left:0,right:0,height:30,zIndex:299,borderBottom:"1px solid #e9ecef",background:"rgba(233,236,239, 0.15)"},O1=k.observer(()=>{const t=K();return i(s.Box,{sx:L1,pl:{base:200,xs:200,sm:200,md:220,lg:240,xl:260},children:p(s.Group,{position:"apart",align:"center",sx:{height:"30px"},pr:16,children:[i(s.Button,{variant:"outline",color:"blue",radius:0,size:"xs",disabled:!t.views.VIE,onClick:()=>t.addANewPanel(t.views.idOfVIE),leftIcon:i(L.IconPlaylistAdd,{size:20}),sx:{height:"30px",borderLeft:"none",borderTop:"none",borderRight:"1px solid #e9ecef",borderBottom:"1px solid #e9ecef",background:"rgb(231, 245, 255)"},children:"Add a Panel"}),i(s.Box,{}),i(s.Box,{})]})})}),P1=k.observer(t=>p(V,{children:[i($1,{...t}),i(O1,{})]})),xD="",wD="";function B1(t,e,n){const r=[];return t.filter(a=>"__INTERACTIONS"in a.viz.conf).forEach((a,o)=>{const l=e[a.id];l.data.interactions=x.get(l,"data.interactions",[]);const{__INTERACTIONS:u,__OPERATIONS:c,__TRIGGERS:d}=a.viz.conf;Object.entries(c).forEach(([f,h])=>{const{schemaRef:g,data:m}=h,{config:w}=m;switch(g){case"builtin:op:open-link":let C=w.urlTemplate.substring(0,100);w.urlTemplate.length>=20&&(C+="..."),l.type="interaction",l.data.interactions.push({schemaRef:g,urlTemplate:w.urlTemplate,shortURLTemplate:C});return;case"builtin:op:open_view":r.push({id:`OPERATION--${f}`,source:a.id,target:w.viewID,label:"Open View",style:{stroke:"rgba(0,0,0,0.8)"},type:"default"});return;case"builtin:op:set_filter_values":l.type="interaction",l.data.interactions.push({schemaRef:g,filters:Object.keys(w.dictionary).map(_=>({key:_,label:n[_]}))});return;case"builtin:op:clear_filter_values":l.type="interaction",l.data.interactions.push({schemaRef:g,filters:w.filter_keys.map(_=>({key:_,label:n[_]}))});return;default:return}})}),r}function V1(t,e){const n=t.filters.keyLabelMap;return{edges:B1(t.panels.list,e,n),edgeNodes:[]}}function wl(t,e,n){return t*e+t*n}function N1(t,e,n){return t*e+(t-1)*n}const rr=25,Ii=40,Cl=25,Ei=350,q1=150,F1=150,Sl=150,_l=300,ir=40,kl=25,G1=300;function W1(t,e){const n=x.keyBy(e,a=>a.id),r=[];return t.current.forEach((a,o)=>{a.panelIDs.forEach((l,u)=>{const c=wl(u,ir,kl)+Ii,d=n[l];if(!d){r.push({id:l,_node_type:"panel",parentNode:a.id,data:{label:`!: ${l}`},position:{x:rr,y:c},sourcePosition:Ee.Position.Right,targetPosition:Ee.Position.Left,style:{width:_l,height:ir}});return}const f=d.title.trim()?`${d.title}`:d.viz.type;r.push({id:d.id,_node_type:"panel",parentNode:a.id,data:{label:f},position:{x:rr,y:c},sourcePosition:Ee.Position.Right,targetPosition:Ee.Position.Left,style:{width:_l,height:ir}})})}),r}const j1={[H.Division]:"Div",[H.Modal]:"Modal",[H.Tabs]:"Tabs"},R1=Ho;function Y1(t){return t.current.map((n,r)=>{const a=N1(n.panelIDs.length,ir,kl)+Ii+Cl;let o=[];return n.type===H.Tabs&&(o=n.config.tabs.map(u=>u.view_id)),{id:n.id,_node_type:"view-root",_view_type:n.type,_view_level:0,_sub_view_ids:[],_tab_view_ids:o,data:{label:`${j1[n.type]}:${n.name}`},position:{x:0,y:0},sourcePosition:Ee.Position.Right,targetPosition:Ee.Position.Left,className:"light",style:{backgroundColor:R1[n.type],width:Ei,height:a}}})}function Q1(t){const e=x.keyBy(t,n=>n.id);t.forEach(n=>{n._node_type!=="view-root"||n._view_type!==H.Tabs||n._tab_view_ids.forEach(r=>{e[r].parentNode=n.id})})}function K1(t){const e=Y1(t.views);Q1(e);const n=W1(t.views,t.panels.list);return[...e,...n]}function U1({nodeMap:t,nodes:e,edges:n}){e.forEach(r=>{r._node_type!=="view-root"||r._view_type!==H.Tabs||(r.sourcePosition=Ee.Position.Bottom,r.style.width=Ei+rr*2,r.style.height=Cl+r._tab_view_ids.reduce((a,o)=>{const l=t[o];l.position.y=a,l.position.x=rr;const u=l.style.height;return a+u+20},Ii))})}function X1({nodeMap:t,nodes:e,edges:n}){n.filter(r=>r.label==="Open View").forEach(r=>{const a=t[r.source],o=t[r.target];if(!a||!o||!a.parentNode)return;const l=t[a.parentNode];l._node_type!=="view-root"||o._node_type!=="view-root"||(o._view_level+=1+l._view_level,l._sub_view_ids.push(o.id))}),e.sort((r,a)=>r._node_type==="view-root"&&a._node_type==="view-root"?r._view_level-a._view_level:r._node_type!=="view-root"&&a._node_type!=="view-root"?0:r._node_type==="view-root"?-1:1)}function J1({nodeMap:t,nodes:e,edges:n}){const r={};n.forEach(a=>{if(a.label!=="Open View")return;const o=t[a.source],l=t[a.target];if(o&&l&&o.parentNode){const u=t[o.parentNode],c=u.position.x,d=Number(x.get(l,"style.height",0)),f=Number(u.style.width);l.position.x=c+f+G1,u._view_level===0&&l._sub_view_ids.length===0&&(o.sourcePosition=Ee.Position.Left,l.targetPosition=Ee.Position.Right,l.position.x*=-1);const g=l.position.x,m=x.get(r,g,0);l.position.y=m,r[g]=m+d+Sl}})}function Z1({nodeMap:t,nodes:e,edges:n}){const r=new Set,a=new Set;n.forEach(l=>{r.add(l.source),a.add(l.target)}),e.filter(l=>l._node_type!=="view-root"||l.id==="Main"||l.parentNode?!1:!r.has(l.id)&&!a.has(l.id)).forEach((l,u)=>{l.position.x=wl(u,Ei,F1),l.position.y=0-q1-Sl})}function H1({nodeMap:t,nodes:e,edges:n}){const r={nodeMap:t,nodes:e,edges:n};return Z1(r),X1(r),U1(r),J1(r),{nodes:e,edges:n}}function eS(t){const e=K1(t),n=x.keyBy(e,c=>c.id),{edges:r,edgeNodes:a}=V1(t,n),o=[...e,...a],l=x.keyBy(o,c=>c.id),u={edges:x.uniqBy(r,c=>c.id),nodes:o,nodeMap:l};return H1(u)}const CD="",Ai={"builtin:op:open-link":i(s.ThemeIcon,{color:"blue",size:20,radius:"xl",children:i(L.IconCircleDashed,{size:14})}),"builtin:op:set_filter_values":i(s.ThemeIcon,{color:"orange",size:20,radius:"xl",children:i(L.IconCircleDot,{size:14})}),"builtin:op:clear_filter_values":i(s.ThemeIcon,{color:"orange",size:20,radius:"xl",children:i(L.IconCircleOff,{size:14})})};function tS(t){const e=[];return t.forEach(n=>{switch(n.schemaRef){case"builtin:op:open-link":e.push({key:n.urlTemplate,icon:Ai[n.schemaRef],text:p(s.Group,{spacing:4,children:[i(s.Text,{children:"Open: "}),i(s.Text,{color:"dimmed",children:n.shortURLTemplate})]})});return;case"builtin:op:set_filter_values":n.filters.forEach(({key:r,label:a})=>{e.push({key:n.schemaRef+r,icon:Ai[n.schemaRef],text:i(s.Group,{spacing:4,children:p(s.Text,{children:["Set Filter: ",a]})})})});return;case"builtin:op:clear_filter_values":n.filters.forEach(({key:r,label:a})=>{e.push({key:n.schemaRef+r,icon:Ai[n.schemaRef],text:i(s.Group,{spacing:4,children:p(s.Text,{children:["Clear Filter: ",a]})})})});return}}),e}const nS=y.memo(({data:t,isConnectable:e,sourcePosition:n=Ee.Position.Right,targetPosition:r=Ee.Position.Left,...a})=>{const o=y.useMemo(()=>tS(t.interactions),[t.interactions]);return p(V,{children:[i(Ee.Handle,{type:"target",position:r,isConnectable:e}),i(s.Box,{sx:{position:"absolute",top:0,right:0},children:i(D.ChevronsUpRight,{size:12})}),p(s.HoverCard,{shadow:"xl",withinPortal:!0,children:[i(s.HoverCard.Target,{children:i(s.Text,{children:t.label})}),i(s.HoverCard.Dropdown,{children:i(s.List,{spacing:"xs",size:"sm",center:!0,children:o.map(l=>i(s.List.Item,{icon:l.icon,children:l.text},l.key))})})]}),i(Ee.Handle,{type:"source",position:n,isConnectable:e})]})}),SD="",rS={interaction:nS},iS=k.observer(()=>{const t=K(),{edges:e,nodes:n}=eS(t);return p(Ee,{nodes:n,edges:e,onNodesChange:x.noop,onEdgesChange:x.noop,onConnect:x.noop,className:"interactions-viewer",fitView:!0,nodeTypes:rS,children:[i(Ee.MiniMap,{}),i(Ee.Controls,{}),i(Ee.Background,{})]})}),aS=k.observer(({opened:t,close:e})=>{const{freezeLayout:n}=y.useContext(ft);return y.useEffect(()=>{n(t)},[t]),i(s.Modal,{size:"96vw",opened:t,onClose:e,title:"Interactions",trapFocus:!0,onDragStart:r=>{r.stopPropagation()},styles:{body:{height:"90vh"},content:{transform:"none !important"}},zIndex:300,children:i(iS,{})})}),sS={"> button":{"&:first-of-type":{borderTopRightRadius:0,borderBottomRightRadius:0,borderRightWidth:.5},":not(:first-of-type):not(:last-of-type)":{borderTopRightRadius:0,borderBottomRightRadius:0,borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeftWidth:.5,borderRightWidth:.5},"&:last-of-type":{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeftWidth:.5}}};function oS({onClick:t,name:e,active:n,openSettings:r}){return p(s.Box,{sx:{position:"relative"},children:[i(s.UnstyledButton,{sx:a=>({display:"block",width:"100%",padding:a.spacing.xs,borderRadius:0,position:"relative",color:a.black,"&:hover":{backgroundColor:a.colors.gray[0]},backgroundColor:n?a.colors.gray[2]:"transparent"}),children:i(s.Group,{sx:{width:"calc(100% - 28px)"},onClick:t,children:i(s.Text,{size:"sm",children:e})})}),n&&i(s.Tooltip,{label:"Edit",position:"right",withinPortal:!0,children:i(s.ActionIcon,{onClick:r,variant:"light",color:"blue",sx:{position:"absolute",top:0,bottom:0,height:"100%",right:0,zIndex:0,borderRadius:0},children:i(L.IconAdjustments,{size:16})})})]})}const lS=k.observer(()=>{const t=he(),e=K(),n=y.useCallback(a=>()=>e.views.setIDOfVIE(a),[e]),r=a=>{t.editor.open(["_VIEWS_",a])};return p(s.Box,{sx:{position:"relative"},children:[e.views.options.map(a=>i(oS,{active:e.views.idOfVIE===a.value,name:a.label,onClick:n(a.value),openSettings:()=>r(a.value)},a.value)),i(s.Divider,{variant:"dashed"}),i(s.Button,{variant:"subtle",rightIcon:i(L.IconPlus,{size:14}),size:"sm",px:"xs",color:"blue",onClick:e.views.addARandomNewView,sx:{width:"100%",borderRadius:0},styles:{inner:{justifyContent:"space-between"}},children:"Add a View"})]})}),uS=k.observer(()=>{const t=he(),e=K(),n=()=>{if(!e.queries.firstID){t.editor.open(["_QUERIES_",""]);return}t.editor.open(["_QUERIES_",e.queries.firstID])},r=()=>{if(!e.filters.firstID){t.editor.open(["_FILTERS_",""]);return}t.editor.open(["_FILTERS_",e.filters.firstID])},[a,o]=y.useState(!1),l=()=>o(!0),u=()=>o(!1);return p(s.Navbar,{p:0,width:{base:200,xs:200,sm:200,md:220,lg:240,xl:260},zIndex:299,children:[p(s.Navbar.Section,{children:[p(s.Group,{grow:!0,spacing:0,sx:{...sS,button:{borderWidth:0,borderBottomWidth:1,borderColor:"#e9ecef"}},children:[i(s.Tooltip,{label:"Filters",withinPortal:!0,children:i(s.ActionIcon,{variant:"default",radius:0,size:"md",sx:{height:"30px"},onClick:r,children:i(L.IconFilter,{size:18})})}),i(s.Tooltip,{label:"Queries",withinPortal:!0,children:i(s.ActionIcon,{variant:"default",radius:0,size:"md",sx:{height:"30px"},onClick:n,children:i(L.IconDatabase,{size:18})})}),i(s.Tooltip,{label:"Interactions Viewer",withinPortal:!0,children:i(s.ActionIcon,{variant:"default",radius:0,size:"md",sx:{height:"30px"},onClick:l,children:i(L.IconLink,{size:18})})})]}),i(aS,{opened:a,close:u})]}),i(s.Navbar.Section,{py:5,sx:{borderBottom:"1px solid #eee"},children:i(s.Text,{align:"center",sx:{userSelect:"none",cursor:"default"},children:"Views"})}),i(s.Navbar.Section,{grow:!0,sx:{overflow:"auto"},children:i(lS,{})}),i(s.Navbar.Section,{children:i(s.Group,{grow:!0,p:"md",pt:"sm",sx:{borderTop:"1px solid #eee"},children:i(s.Button,{size:"xs",leftIcon:i(L.IconSettings,{size:20}),onClick:()=>t.editor.open([]),children:"Settings"})})})]})}),cS=k.observer(function({config:e}){return p(V,{children:[i(s.Checkbox,{checked:e.default_value,onChange:n=>e.setDefaultValue(n.currentTarget.checked),label:"Default Checked"}),i(ai,{label:"Description",value:e.description,onChange:e.setDescription,styles:{root:{flexGrow:1,minHeight:"400px"}}})]})}),dS=[{label:"2022",value:"YYYY"},{label:"202201",value:"YYYYMM"},{label:"20220101",value:"YYYYMMDD"},{label:"2022-01",value:"YYYY-MM"},{label:"2022-01-01",value:"YYYY-MM-DD"}],pS=k.observer(function({config:e}){return p(V,{children:[p(s.Group,{children:[i(s.Checkbox,{checked:e.required,onChange:n=>e.setRequired(n.currentTarget.checked),label:"Required"}),i(s.Checkbox,{checked:e.clearable,onChange:n=>e.setClearable(n.currentTarget.checked),disabled:e.max_days>0,label:"Clearable"}),i(s.Checkbox,{checked:e.allowSingleDateInRange,onChange:n=>e.setAllowSingleDateInRange(n.currentTarget.checked),label:"Allow choosing 1 day"})]}),i(s.Select,{data:dS,label:"Display Format",value:e.inputFormat,onChange:e.setInputFormat}),i(ul,{label:"Default Value",config:e,value:e.default_value,onChange:e.setDefaultValue}),i(s.NumberInput,{label:"Max Days",description:p(s.Group,{position:"apart",children:[i(s.Text,{children:"Set 0 to disable."}),p(s.Group,{spacing:4,children:[i(s.Text,{children:"This feature requires"}),i(s.Text,{color:"blue",children:"Clearable"}),i(s.Text,{children:"to be checked"})]})]}),min:0,value:e.max_days,onChange:e.setMaxDays,hideControls:!0})]})}),zi=k.observer(({value:t,onChange:e})=>{const n=K(),r=y.useMemo(()=>n.queries.options,[n.queries.current]),a=r.length===0;return i(s.Select,{label:"Pick a query",data:r,value:t,onChange:e,allowDeselect:!1,clearable:!0,sx:{flexGrow:1},disabled:a,error:a?"You need to add a query in Data Settings":void 0})}),hS=`
481
+ `)},DC=b.types.model("CustomModalTitleModel",{enabled:b.types.optional(b.types.boolean,!1),func_content:b.types.optional(b.types.string,"")}).views(t=>({get json(){const{enabled:e,func_content:n}=t;return{enabled:e,func_content:n}},get value(){const{enabled:e,func_content:n}=t,r=b.getParent(t,2),a=b.getRoot(t);if(!e)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(t=>({setEnabled(e){t.enabled=e},setFuncContent(e){t.func_content=e},replace({enabled:e,func_content:n}){t.enabled=e,t.func_content=n}})),tl=b.types.model("ViewModel_Modal",{_name:b.types.literal(H.Modal),width:b.types.string,height:b.types.string,custom_modal_title:b.types.optional(DC,Si)}).views(t=>({get json(){const{_name:e,width:n,height:r,custom_modal_title:a}=t;return{_name:e,width:n,height:r,custom_modal_title:a.json}}})).actions(t=>({setWidth(e){t.width=e},setHeight(e){t.height=e}})),MC=()=>tl.create({_name:H.Modal,width:"90vw",height:"90vh"}),IC=b.types.model("ViewModel_Tabs_Tab",{id:b.types.identifier,name:b.types.string,view_id:b.types.string,color:b.types.optional(b.types.string,"")}).views(t=>({get json(){const{id:e,name:n,view_id:r,color:a}=t;return{id:e,name:n,color:a,view_id:r}}})).actions(t=>({setName(e){t.name=e},setViewID(e){t.view_id=e},setColor(e){t.color=e}})),nl=b.types.model("ViewModel_Tabs",{_name:b.types.literal(H.Modal),tabs:b.types.optional(b.types.array(IC),[]),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(t=>({get json(){const{_name:e,variant:n,orientation:r,tabs:a,grow:o}=t;return{grow:o,tabs:a.map(l=>l.json),_name:e,variant:n,orientation:r}}})).actions(t=>({setVariant(e){t.variant=e},setOrientation(e){t.orientation=e},setGrow(e){t.grow=e},setTabs(e){t.tabs.length=0,t.tabs=b.cast(e)},addTab(){const e=Me.randomId(),n={id:e,name:e,view_id:""};t.tabs.push(n)},removeTab(e){t.tabs.splice(e,1)}})),EC=()=>nl.create({_name:H.Modal,tabs:[]}),rl=b.types.model({id:b.types.identifier,name:b.types.string,type:b.types.enumeration("EViewComponentType",[H.Division,H.Modal,H.Tabs]),config:b.types.union(el,tl,nl),panelIDs:b.types.optional(b.types.array(b.types.string),[])}).views(t=>({get json(){const{id:e,name:n,type:r,config:a}=t;return{id:e,name:n,type:r,config:a.json,panelIDs:t.panelIDs}}})).actions(t=>({setName(e){t.name=e},setType(e){if(t.type!==e){switch(e){case H.Division:t.config=TC();break;case H.Modal:t.config=MC();break;case H.Tabs:t.config=EC();break}t.type=e}},appendPanelID(e){t.panelIDs.push(e)},removePanelID(e){const n=t.panelIDs.filter(r=>r!==e);t.panelIDs.length=0,t.panelIDs.push(...n)}})).actions(t=>({})),il=b.types.model("ViewsModel",{current:b.types.optional(b.types.array(rl),[]),visibleViewIDs:b.types.array(b.types.string),idOfVIE:b.types.string}).views(t=>({get json(){return t.current.map(e=>yn(e.json))},get idMap(){const e=new Map;return t.current.forEach(n=>{e.set(n.id,n)}),e},findByID(e){return t.current.find(n=>n.id===e)},get isVIETheFirstView(){return t.current.length===0||!t.idOfVIE?!1:t.current[0].id===t.idOfVIE},get firstVisibleView(){const[e]=t.visibleViewIDs;return t.current.find(({id:n})=>n===e)},get visibleViews(){const e=new Set(t.visibleViewIDs);return t.current.filter(({id:n})=>e.has(n))},get VIE(){return t.current.find(({id:e})=>e===t.idOfVIE)},get options(){return t.current.map(e=>({label:e.name,value:e.id,type:e.type}))},get editorOptions(){const e=b.getRoot(t).content.panels;return t.current.map(n=>({label:n.name,value:n.id,_type:"view",children:e.editorOptions(n.id,n.panelIDs)}))}})).actions(t=>({replace(e){t.current.replace(e)},addANewView(e,n,r,a){t.current.push({id:e,name:n,type:r,config:a,panelIDs:[]})},append(e){t.current.push(e)},remove(e){t.current.splice(e,1)},removeByID(e){const n=t.current.findIndex(r=>r.id===e);n!==-1&&t.current.splice(n,1)},replaceByIndex(e,n){t.current.splice(e,1,n)},setIDOfVIE(e){t.idOfVIE=e,t.visibleViewIDs.length=0,t.visibleViewIDs.push(e)},appendToVisibles(e){new Set(t.visibleViewIDs.map(r=>r)).has(e)||t.visibleViewIDs.push(e)}})).actions(t=>({addARandomNewView(){const e=new Date().getTime().toString();t.addANewView(e,H.Division,H.Division,{_name:H.Division}),t.setIDOfVIE(e)},removeVIE(){t.current.length!==1&&(t.removeByID(t.idOfVIE),t.setIDOfVIE(t.current[0].id))},rmVisibleViewID(e){const n=t.visibleViewIDs.findIndex(r=>r===e);n!==-1&&t.visibleViewIDs.splice(n,1)}}));function _i(t){const e=t.length>0?[t[0].id]:[],n=t.length>0?t[0].id:"";return{current:t.map(a=>{const{_name:o=a.type}=a.config;return{...a,config:{...a.config,_name:o},panelIDs:a.panelIDs}}),visibleViewIDs:e,idOfVIE:n}}function al(t,e,n,r){return t.reduce((a,o)=>(a[o[e]]=pr(o[n],r),a),{})}const AC=b.types.model({id:b.types.string,name:b.types.string,dashboard_id:b.types.string,create_time:b.types.string,update_time:b.types.string,version:b.types.string,filters:is,queries:ds,sqlSnippets:hs,views:il,panels:Jo,mock_context:Yu,origin:b.types.maybe(b.types.frozen())}).views(t=>({get json(){return{id:t.id,name:t.name,create_time:t.create_time,update_time:t.update_time,dashboard_id:t.dashboard_id,content:{views:t.views.json,panels:t.panels.json,filters:t.filters.json,version:t.version,definition:{queries:t.queries.json,sqlSnippets:t.sqlSnippets.json,mock_context:t.mock_context.current}}}},get filtersChanged(){const e="filters.current";return!x.isEqual(b.getSnapshot(x.get(t,e)),x.get(t.origin,e))},get queriesChanged(){const e="queries.current",n=b.getSnapshot(x.get(t,e)).map(r=>x.pick(r,["id","name","key","type","sql","run_by","react_to","pre_process","post_process"]));return!x.isEqual(n,x.get(t.origin,e))},get sqlSnippetsChanged(){const e="sqlSnippets.current";return!x.isEqual(b.getSnapshot(x.get(t,e)),x.get(t.origin,e))},get viewsChanged(){const e="views.current";return!x.isEqual(b.getSnapshot(x.get(t,e)),x.get(t.origin,e))},get panelsChanged(){const e="panels.list";return!x.isEqual(b.getSnapshot(x.get(t,e)),x.get(t.origin,e))},get mockContextChanged(){const e="mock_context.current";return!x.isEqual(x.get(t,e),x.get(t.origin,e))},get payloadForSQL(){const e=b.getParent(t).context.current,n=b.getParent(t).globalSQLSnippets,r={context:{...t.mock_context.current,...e},filters:t.filters.values};return{...r,sql_snippets:al(t.sqlSnippets.current,"key","value",r),global_sql_snippets:al(n.list,"id","content",r)}},get payloadForViz(){const e=b.getParent(t).context.current;return{context:{...t.mock_context.current,...e},filters:t.filters.values}},get changed(){return this.filtersChanged||this.queriesChanged||this.sqlSnippetsChanged||this.viewsChanged||this.panelsChanged||this.mockContextChanged},get data(){return t.queries.current.map(({id:n,data:r})=>({id:n,data:r})).reduce((n,r)=>(n[r.id]=r.data,n),{})},getDataStuffByID(e){const n=t.queries.findByID(e);return n?{data:n.data.toJSON(),len:n.data.length,state:n.state,error:n.error}:{data:[],len:0,state:"idle",error:void 0}}})).views(t=>({findQueryUsage(e){const n=t.panels.idMap,r=t.views.current.flatMap(l=>l.panelIDs.map(u=>n.get(u)).filter(u=>(u==null?void 0:u.queryIDSet.has(e))??!1).map(u=>({type:"panel",id:u.id,label:u.title?u.title:u.viz.type,views:[{id:l.id,label:l.name}]}))),a=t.views.idMap,o=t.filters.current.filter(l=>x.get(l,"config.options_query_id")===e).map(l=>({type:"filter",id:l.id,label:l.label,views:l.visibleInViewsIDs.map(u=>{var c;return{id:u,label:((c=a.get(u))==null?void 0:c.name)??u}})}));return r.concat(o)}})).actions(t=>({duplicatePanelByID(e,n){var a;const r=t.panels.duplicateByID(e);r&&((a=t.views.findByID(n))==null||a.appendPanelID(r))},removePanelByID(e,n){var r;t.panels.removeByID(e),(r=t.views.findByID(n))==null||r.removePanelID(e)},addANewPanel(e){var r;const n=new Date().getTime().toString();t.panels.append(Xo(n)),(r=t.views.findByID(e))==null||r.appendPanelID(n)}})).actions(t=>({reset(){b.applySnapshot(t.filters.current,t.origin.filters.current),b.applySnapshot(t.queries.current,t.origin.queries.current),b.applySnapshot(t.sqlSnippets.current,t.origin.sqlSnippets.current),b.applySnapshot(t.views.current,t.origin.views.current),b.applySnapshot(t.panels.list,t.origin.panels.list),t.mock_context.current=t.origin.mock_context.current},resetFilters(){b.applySnapshot(t.filters.current,t.origin.filters.current)},updateCurrent(e){const{id:n,name:r,content:a}=e;if(!a)throw new Error("unexpected null content when updating a content model");const{version:o,filters:l,views:u,panels:c,definition:{queries:d,sqlSnippets:f,mock_context:h={}}}=a;t.id=n,t.name=r,t.version=o,b.applySnapshot(t.filters.current,l),b.applySnapshot(t.views.current,_i(u).current),b.applySnapshot(t.panels.list,c),b.applySnapshot(t.queries.current,d),b.applySnapshot(t.sqlSnippets.current,f),t.mock_context.current=h}})),Zn=b.types.snapshotProcessor(AC,{preProcessor(t){return{...t,origin:t}},postProcessor(t){delete t.origin;const e=b.castToSnapshot(t.queries.current.map(n=>x.pick(n,["id","key","type","sql"])));return x.defaults({},{queries:{current:e}},t)}});function zC(t,e){e.filters&&b.applySnapshot(t.filters.current,e.filters)}function sl({id:t,name:e,dashboard_id:n,create_time:r,update_time:a,content:o}){if(!o)throw new Error("unexpected null content when creating a content model");const{version:l,filters:u,views:c,panels:d,definition:{queries:f,sqlSnippets:h,mock_context:g={}}}=o;return Zn.create({id:t,name:e,dashboard_id:n,create_time:r,update_time:a,version:l,filters:as(u),queries:{current:f},sqlSnippets:{current:h},mock_context:{current:g},views:_i(c),panels:{list:d}})}const $C=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}),LC=b.types.model("GlobalSQLSnippetsModel",{list:b.types.optional(b.types.array($C),[])}).views(t=>({find(e){return t.list.find(n=>n.id===e)},get options(){return t.list.map(e=>({value:e.id,label:e.id}))}})).actions(t=>({replace(e){t.list.length=0,t.list.push(...e)}})),ol=b.types.model({id:b.types.identifier,name:b.types.string,group:b.types.string,content:Zn,content_id:b.types.string,datasources:Wu,globalSQLSnippets:LC,context:fs,editor:Ru}).views(t=>({get json(){return{id:t.id,name:t.name,group:t.group,content_id:t.content_id}}})).actions(t=>({updateCurrentContent(e){t.content.updateCurrent(e)},updateCurrent(e,n){const{id:r,name:a,group:o,content_id:l}=e;t.id=r,t.name=a,t.group=o,t.content_id=l,this.updateCurrentContent(n)}}));function ki({id:t,name:e,group:n,content_id:r},a,o,l,u){return ol.create({id:t,name:e,group:n,content_id:r,content:sl(a),datasources:{list:o},globalSQLSnippets:{list:l},context:{current:u},editor:{}})}const Ti=y.createContext(null);function Hn(t){const e=y.useContext(Ti),n=X.useCreation(()=>t.configure(e||new wr),[t.configure]),r=X.usePrevious(n);return r&&r!==n&&r.dispose(),i(Ti.Provider,{value:n,children:t.children})}function ll(){return y.useContext(Ti)}const OC={viewPanelInFullScreen:x.noop,inFullScreen:!1},Di=y.createContext(OC),PC=({description:t,isDescriptionEmpty:e})=>e?null:i(s.Tooltip,{color:"white",label:i(Kn,{value:t,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(L.IconInfoCircle,{size:16,color:"gray"})})}),BC=k.observer(({label:t,config:{default_value:e,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:t}),i(PC,{description:n,isDescriptionEmpty:r})]}),checked:o||!1,onChange:u=>l(u.currentTarget.checked),...a,pt:".4em",styles:{input:{borderColor:"#e9ecef"}}})]})),ul=k.observer(({label:t,config:e,value:n=[null,null],onChange:r})=>{const{inputFormat:a,...o}=e,l=Array.isArray(n)?n.map(f=>f?R(f).toDate():null):[null,null],u=f=>{r(f.map(h=>h&&R(h).format(a)))},c=e.getMinDate(l[0]),d=e.getMaxDate(l[0]);return i(ru.DatePickerInput,{type:"range",label:t,value:l,onChange:u,icon:i(D.Calendar,{size:16}),sx:{minWidth:"16em"},minDate:c,maxDate:d,valueFormat:a,styles:{input:{borderColor:"#e9ecef"}},...o})}),VC=s.createStyles((t,{radius:e=4})=>({root:{borderRadius:t.fn.radius(e),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:t.fontSizes.sm,fontWeight:500,color:"#212529"},dropdown:{fontSize:t.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":{flexGrow:1}}}})),cl=({errorMessage:t})=>t?i(s.Text,{color:"red",size:12,children:t}):i(s.Text,{color:"dimmed",size:12,children:"Not found"}),NC=({disabled:t,classNames:e,styles:n,unstyled:r,radius:a,style:o,label:l,value:u,onChange:c,options:d,errorMessage:f})=>{const{classes:h,cx:g}=VC({radius:a},{name:"MultiSelectWidget",classNames:e,styles:n,unstyled:r}),[m,w]=y.useState(!1),C=B=>{w(B)},_=m&&(u==null?void 0:u.length)>0,[T,I]=y.useState(""),O=y.useMemo(()=>{if(!T)return d;const B=T.toLowerCase(),$=A=>{var E;return((E=A.description)==null?void 0:E.toLowerCase().includes(B))||A.label.toLowerCase().includes(B)};return d.filter($)},[T,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(qa,{disabled:t,allowClear:!0,className:g(h.root,"check-select"),dropdownClassName:g(h.dropdown,""),onDropdownVisibleChange:C,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(cl,{errorMessage:f}),maxTagTextLength:10,maxTagPlaceholder:B=>`${B.length} selected`,searchValue:T,onSearch:I,filterOption:!1,children:O.map(B=>i(qa.Option,{children:i(s.Group,{noWrap:!0,children:p("div",{children:[i(s.Text,{size:"sm","data-role":"label",children:B.label}),B.description&&i(s.Text,{size:"xs",color:"dimmed","data-role":"description",children:B.description})]})})},B.value))})]})},qC=k.observer(({label:t,config:e,value:n,onChange:r})=>{const a=K(),o=!!e.options_query_id,{state:l,error:u}=a.getDataStuffByID(e.options_query_id),c=l==="loading",d=e.min_width?e.min_width:"200px",f=o?c:!1,h=g=>r(g,!1);return i(NC,{label:t,options:e.options,style:{minWidth:"160px",width:d,maxWidth:f?d:"unset",borderColor:"#e9ecef"},disabled:f,value:n,onChange:h,errorMessage:u})}),FC=y.forwardRef(({label:t,description:e,...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:t}),i(s.Text,{size:"xs",color:"dimmed","data-role":"description",children:e})]})})})),GC=k.observer(({label:t,config:e,value:n,onChange:r})=>{const a=K(),o=!!e.options_query_id,{state:l,error:u}=a.getDataStuffByID(e.options_query_id),c=l==="loading";return y.useEffect(()=>{var h;const{default_selection_count:d}=e;if(!d)return;const f=((h=e.options[0])==null?void 0:h.value)??"";console.log("Selecting the first option by default. New value: ",f),r(f,!0)},[e.default_selection_count,e.options]),i(s.Select,{label:t,data:e.options,disabled:o?c:!1,value:n,onChange:r,error:!!u,placeholder:u,maxDropdownHeight:500,styles:{root:{width:e.width?e.width:"200px"},input:{borderColor:"#e9ecef"}},sx:{".mantine-Select-item[data-selected] .mantine-Text-root[data-role=description]":{color:"rgba(255,255,255,.7)"}},itemComponent:FC})});function WC({label:t,config:e,value:n,onChange:r}){return i(s.TextInput,{label:t,value:n||"",onChange:a=>r(a.currentTarget.value),...e,styles:{input:{borderColor:"#e9ecef"}}})}const jC=({rotate:t,onClick:e})=>i("svg",{onClick:e,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(${t})`,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"})}),RC=({expanded:t,isLeaf:e,value:n,onClick:r,...a})=>(n==="0-0-value"&&console.log(a),e?i("span",{style:{width:"14px",display:"inline-block"}}):i(jC,{rotate:t?"0":"-90",onClick:r,...a})),YC=({onClick:t})=>p("svg",{onClick:t,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"})]}),QC=({onClick:t,...e})=>i(YC,{onClick:t,...e}),KC=s.createStyles((t,{radius:e=4})=>({root:{borderRadius:t.fn.radius(e),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:t.fontSizes.sm,fontWeight:500,color:"#212529"},dropdown:{fontSize:t.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"}}}})),UC=({disabled:t,classNames:e,styles:n,unstyled:r,radius:a,style:o,label:l,value:u,onChange:c,treeData:d,errorMessage:f})=>{const{classes:h,cx:g}=KC({radius:a},{name:"FilterTreeSelectWidget",classNames:e,styles:n,unstyled:r}),[m,w]=y.useState(!1),C=T=>{w(T)},_=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(Fa,{disabled:t,allowClear:!0,className:g(h.root,"check-select"),dropdownClassName:g(h.dropdown,""),onDropdownVisibleChange:C,transitionName:"rc-tree-select-dropdown-slide-up",choiceTransitionName:"rc-tree-select-selection__choice-zoom",style:o,treeLine:!0,clearIcon:()=>i(s.CloseButton,{}),switcherIcon:RC,treeIcon:QC,maxTagTextLength:10,value:u,treeData:d,notFoundContent:i(cl,{errorMessage:f}),treeNodeFilterProp:"filterBasis",treeCheckable:!0,showCheckedStrategy:Fa.SHOW_PARENT,onChange:c,onSelect:console.log,maxTagCount:0,maxTagPlaceholder:T=>`${T.length} selected`})]})},XC=k.observer(({label:t,config:e,value:n,onChange:r})=>{const{treeData:a,treeDataLoading:o,errorMessage:l}=e,u=e.min_width?e.min_width:"200px",d=!!e.options_query_id?o:!1;return i(UC,{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:t})}),JC=k.observer(({filter:{type:t,config:e,key:n,...r},formFieldProps:a})=>{switch(t){case"select":return i(GC,{...r,...a,config:e});case"multi-select":return i(qC,{...r,...a,config:e});case"tree-select":return i(XC,{...r,...a,config:e});case"text-input":return i(WC,{...r,...a,config:e});case"date-range":return i(ul,{...r,...a,config:e});case"checkbox":return i(BC,{...r,...a,config:e});default:return null}}),dl=k.observer(y.forwardRef(({filter:t,...e},n)=>i("div",{className:"filter-root",ref:n,children:i(Fe,{children:i(JC,{filter:t,formFieldProps:e})})}))),pl=k.observer(function({view:e}){const n=K(),{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]),y.useEffect(()=>{n.filters.updatePreviewValues(l)},[l]);const u=n.filters.visibleInView(e.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)=>(w,C)=>{m(w),(g.should_auto_submit||C)&&n.filters.setValueByKey(g.key,w)};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(dl,{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"})})]})})}),mD="";function ZC(t){return t?["<p><br></p>","<p></p>"].includes(t):!0}const hl=k.observer(()=>{const{freezeLayout:t}=y.useContext(ft),[e,n]=y.useState(!1),{panel:r}=ze();return y.useEffect(()=>{t(e)},[e]),ZC(r.description)?null:p(V,{children:[i(s.Modal,{opened:e,onClose:()=>n(!1),title:r.title,withCloseButton:!1,withinPortal:!0,zIndex:310,children:i(Kn,{value:r.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:()=>n(a=>!a),sx:{verticalAlign:"baseline",cursor:"pointer"},children:i(D.InfoCircle,{size:20})})})]})}),HC=k.observer(({view:t})=>{const e=he(),n=K(),r=Ue.useModals(),{panel:a}=ze(),{id:o}=a,{inEditMode:l}=y.useContext(ft),{viewPanelInFullScreen:u,inFullScreen:c}=y.useContext(Di),d=()=>{n.duplicatePanelByID(o,t.id)},f=()=>{e.editor.open(["_VIEWS_",t.id,"_PANELS_",o])},h=()=>r.openConfirmModal({title:"Delete this panel?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>n.removePanelByID(o,t.id),confirmProps:{color:"red"},zIndex:320}),g=y.useCallback(()=>{u(o)},[o,u]),m=!c&&t.type!==H.Modal;return i(V,{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(D.Refresh,{size:14}),children:"Refresh"}),i(s.Menu.Item,{onClick:a.downloadData,icon:i(D.Download,{size:14}),children:"Download Data"}),m&&i(s.Menu.Item,{onClick:g,icon:i(D.ArrowsMaximize,{size:14}),disabled:l,children:"Full Screen"}),l&&p(V,{children:[i(s.Divider,{label:"Edit",labelPosition:"center"}),i(s.Menu.Item,{onClick:f,icon:i(D.Settings,{size:14}),children:"Settings"}),i(s.Menu.Item,{onClick:d,icon:i(D.Copy,{size:14}),children:"Duplicate"}),i(s.Menu.Item,{color:"red",onClick:h,icon:i(D.Trash,{size:14}),children:"Delete"})]})]})]})})})}),e1=k.observer(({panel:t})=>p(s.Stack,{children:[t.queryErrors.map((e,n)=>i(s.Text,{color:"red",size:"md",align:"center",sx:{fontFamily:"monospace"},children:e},`${n}-${e}`)),t.queryStateMessages.map((e,n)=>i(s.Text,{color:"gray",align:"center",children:e},`${n}-${e}`))]}));var fl=(t=>(t.migrated="migrated",t.nothingToMigrate="nothingToMigrate",t.checkFailed="checkFailed",t.migrationFailed="migrationFailed",t))(fl||{}),er=(t=>(t.notStarted="notStarted",t.inProgress="inProgress",t.done="done",t))(er||{});class t1{constructor(e){N(this,"vizInstance");N(this,"operationManager");N(this,"triggerManager");N(this,"vizManager");N(this,"runningMigration");N(this,"panelModel");N(this,"status","notStarted");this.panelModel=e.getRequired(Ce.instanceScope.panelModel),this.vizInstance=e.getRequired(Ce.instanceScope.vizInstance),this.operationManager=e.getRequired(Ce.instanceScope.operationManager),this.triggerManager=e.getRequired(Ce.instanceScope.triggerManager),this.vizManager=e.getRequired(Ce.vizManager)}async createMigrationTask(){const e=[];try{await this.instanceNeedMigration()&&e.push(()=>this.runInstanceMigration()),await this.interactionNeedMigration()&&e.push(()=>this.runInteractionMigration())}catch(n){return console.warn("check migration failed",n),"checkFailed"}if(e.length===0)return"nothingToMigrate";try{return await Promise.all(e.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(e=>(this.status="done",e))),this.runningMigration}async runInteractionMigration(){await this.operationManager.runMigration(),await this.triggerManager.runMigration()}async runInstanceMigration(){const e=this.vizManager.resolveComponent(this.vizInstance.type),n={configData:this.vizInstance.instanceData,panelModel:this.panelModel};await e.migrator.migrate(n)}async instanceNeedMigration(){const e=this.vizManager.resolveComponent(this.vizInstance.type),n={configData:this.vizInstance.instanceData};return e.migrator.needMigration(n)}async interactionNeedMigration(){return await this.operationManager.needMigration()||await this.triggerManager.needMigration()}}function gl(t){const{panel:e}=ze();return y.useCallback(n=>{const r=n.getRequired(Ce.vizManager),a=r.resolveComponent(t.viz.type);return n.createScoped().provideFactory(Ce.instanceScope.vizInstance,()=>r.getOrCreateInstance(t)).provideFactory(Ce.instanceScope.interactionManager,o=>{const l=o.getRequired(Ce.instanceScope.vizInstance);return new bi(l,a,Jn)}).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,e).provideFactory(Ce.instanceScope.migrator,o=>new t1(o))},[t.viz.type,t.viz.conf])}function ml(t){const[e,n]=y.useState(!1),r=ll().getRequired(Ce.instanceScope.migrator);return X.useAsyncEffect(async()=>{const a=r.status===er.notStarted;n(r.status===er.done),r.status===er.notStarted&&r.runMigration().then(o=>{o===fl.migrated&&a&&(t==null||t())}).finally(()=>{n(!0)})},[r]),e}function yl(t,e){const n=ll().getRequired(Ce.instanceScope.vizInstance);return y.useEffect(()=>(n.instanceData.setItem(null,e.viz.conf),n.instanceData.watchItem(null,r=>{t(r)})),[t,e.viz.type]),n}function n1({setVizConf:t,...e}){const{panel:n}=e,r=yl(t,n),a=ml(()=>{hn.showNotification({title:`${n.title} - Updated`,message:"Your plugin configuration has been migrated to the latest version"})});return X.useAsyncEffect(async()=>{await r.instanceData.setItem(null,n.viz.conf)},[r,n.viz.type]),a?i(ec,{...e}):i(s.Text,{children:"Checking update..."})}function r1(t){const{panel:e,setVizConf:n}=t;yl(n,e);const{inEditMode:r}=y.useContext(ft);return ml(()=>{r&&hn.showNotification({title:`${e.title} - Updated`,message:"Your plugin configuration has been migrated to the latest version"})})?i(Hu,{...t}):i(s.Text,{children:"Checking update"})}const yD="";function i1(t,e){const{vizManager:n}=y.useContext(at),{panel:{viz:r,title:a,id:o,description:l,queryIDs:u,variables:c}}=ze(),d={title:a,id:o,description:l,queryIDs:u,viz:r,layout:e},f=gl(d);try{return n.resolveComponent(r.type),i(Hn,{configure:f,children:i(r1,{setVizConf:r.setConf,panel:d,data:t,variables:c,vizManager:n})})}catch(h){return console.info(x.get(h,"message")),null}}const a1=k.observer(function({data:e}){const{ref:n,width:r,height:a}=Me.useElementSize(),o=i1(e,{w:r,h:a}),l=r>0&&a>0;return i("div",{className:"viz-root",ref:n,children:l&&i(Fe,{children:o})})}),bl=k.observer(({panel:t,height:e})=>p(s.Flex,{direction:"column",sx:{height:e,position:"relative",width:"100%"},children:[i(s.LoadingOverlay,{visible:t.dataLoading,exitTransitionDuration:0}),!t.canRenderViz&&i(e1,{panel:t}),t.canRenderViz&&i(a1,{data:t.data})]})),bD="",s1=k.observer(function(){const{panel:e}=ze(),{title:n}=e;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 o1(t){return!["richText","button"].includes(t)}const l1={border:"1px solid #e9ecef"},u1={border:"1px dashed transparent",transition:"border-color 300ms ease","&:hover":{borderColor:"#e9ecef"}};function c1(t,e){return t.style.border.enabled?l1:e?u1:{border:"1px dashed transparent"}}const tr=k.observer(function({panel:e,view:n}){const{inEditMode:r}=y.useContext(ft),a=e.title?"calc(100% - 25px - 5px)":"100%",o=c1(e,r),u=o1(e.viz.type)||r;return i(Sr,{value:{panel:e,data:e.data,loading:e.dataLoading,errors:e.queryErrors},children:p(s.Box,{className:"panel-root",p:5,pt:0,sx:{...o},children:[i(s.Box,{sx:{position:"absolute",left:0,top:0,height:28,zIndex:310},children:i(hl,{})}),u&&i(HC,{view:n}),i(s1,{}),i(bl,{panel:e,height:a})]})})}),vD="",d1=y.forwardRef(({h:t},e)=>i(s.ActionIcon,{ref:e,className:"react-grid-customDragHandle",sx:{userSelect:"none",cursor:"grab",position:"absolute",top:5,right:t>38?5:20,zIndex:400,"&:hover":{color:"#228be6"}},variant:"transparent",children:i(D.ArrowsMove,{size:16})})),p1=y.forwardRef(({handleAxis:t,...e},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",...e,children:i(D.ChevronDownRight,{size:16})})),h1=fn.WidthProvider(fn),f1=k.observer(({view:t,className:e="layout"})=>{const n=K(),{panels:r,layouts:a}=n.panels.panelsByIDs(t.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(h1,{onLayoutChange:o,className:`dashboard-layout ${e}`,rowHeight:1,cols:36,margin:[0,0],isBounded:!0,isDraggable:!0,isResizable:!0,layout:a,draggableHandle:".react-grid-customDragHandle",resizeHandle:i(p1,{}),onResize:l,children:r.map((u,c)=>p("div",{"data-grid":{...u.layout},className:"panel-grid-item",children:[i(d1,{h:u.layout.h}),i(tr,{view:t,panel:u})]},u.id))})}),g1=fn.WidthProvider(fn),m1=k.observer(function({view:e,className:n="layout"}){const{panels:r,layouts:a}=K().panels.panelsByIDs(e.panelIDs);return i(g1,{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(tr,{view:e,panel:o})},o.id))})}),y1=k.observer(({children:t})=>i(s.Box,{pt:10,pb:100,children:t}));function vl(t){return t.replace(/(vw|vh)/,"%")}const b1=k.observer(({children:t,view:e})=>{const n=e.config,{width:r,height:a}=y.useMemo(()=>({width:vl(n.width),height:vl(n.height)}),[n.width,n.height]);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:n.custom_modal_title.value,trapFocus:!0,onDragStart:o=>{o.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%)",width:r,height:a},content:{border:"1px solid #efefef"},body:{maxHeight:"calc(100vh - 325px)"}},withinPortal:!1,transitionProps:{duration:0},children:t})})}),v1=({variant:t,orientation:e})=>{const n={tab:{},panel:{padding:"16px"}};return t==="pills"&&e==="horizontal"&&(n.tab.paddingTop="6px",n.tab.paddingBottom="6px"),e==="vertical"&&(n.tab["&.add-a-tab"]={paddingTop:"1px",paddingBottom:"1px"},n.tab["&.add-a-tab .mantine-Tabs-tabLabel"]={marginLeft:"auto",marginRight:"auto"}),n},x1=t=>t.color?{"&[data-active], &[data-active]:hover":{borderColor:t.color?t.color:"..."}}:{},w1=k.observer(({children:t,view:e})=>{const n=Ue.useModals(),r=K(),a=y.useMemo(()=>r.views.options.filter(c=>c.type===H.Division),[e.id,r.views.options]),o=e.config,l=c=>n.openConfirmModal({title:"Delete this tab?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>{o.removeTab(c)},confirmProps:{color:"red"},zIndex:320}),u=o.tabs.length===0;return p(s.Box,{className:"preview-view-tabs",children:[p(s.Tabs,{variant:o.variant,orientation:o.orientation,defaultValue:o.tabs.length>0?o.tabs[0].id:"0",styles:v1(o),children:[p(s.Tabs.List,{grow:o.grow,children:[o.tabs.map(c=>i(s.Tabs.Tab,{value:c.id,sx:x1(c),children:c.name??c.id},c.id)),i(s.Tabs.Tab,{onClick:o.addTab,value:"add",className:"add-a-tab",children:i(D.Plus,{size:18,color:"#228be6"})})]}),o.tabs.map((c,d)=>{const f=r.views.findByID(c.view_id);return p(s.Tabs.Panel,{value:c.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:c.name,onChange:h=>c.setName(h.currentTarget.value)}),i(s.Select,{label:"View",value:c.view_id,onChange:c.setViewID,data:a}),i(s.ColorInput,{label:"Color",value:c.color,onChange:c.setColor,disabled:o.variant!=="default"}),f&&p(s.Button,{mt:20,variant:"gradient",leftIcon:i(L.IconArrowsLeftRight,{size:18}),gradient:{from:"cyan",to:"indigo"},onClick:()=>r.views.setIDOfVIE(f.id),children:["Swith to View: ",f.name]}),i(s.Button,{mt:20,variant:"subtle",color:"red",onClick:()=>l(d),disabled:u,leftIcon:i(L.IconTrash,{size:14}),children:"Delete This Tab"})]})]}),f&&i(nr,{view:f})]},c.id)})]}),t]})}),C1=k.observer(({view:t,children:e})=>{switch(t.type){case H.Modal:return i(b1,{view:t,children:e});case H.Tabs:return i(w1,{view:t,children:e});case H.Division:default:return i(y1,{children:e})}}),xl=k.observer(function({view:e}){return i(Di.Provider,{value:{viewPanelInFullScreen:x.noop,inFullScreen:!1},children:i(s.Box,{className:"dashboard-view","data-enable-scrollbar":!0,children:i(C1,{view:e,children:p(s.Box,{sx:{position:"relative"},children:[i(s.Box,{className:"dashboard-sticky-area",sx:{position:"sticky",top:"0px"},children:i(pl,{view:e})}),i(f1,{view:e})]})})})})}),S1={modal:{display:"flex",flexDirection:"column",flexWrap:"nowrap"},body:{display:"flex",height:"calc(100vh - 88px)"}},_1=k.observer(function({view:e,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(D.ArrowLeft,{size:20}),children:"Exit fullscreen"}),styles:S1,children:i(s.Group,{grow:!0,sx:{flexGrow:1,flexShrink:0},children:i(tr,{view:e,panel:n})})})});function k1(t,e,n){const{panels:r}=K(),a=t.id==="Main",[o,l]=y.useState(()=>a&&r.findByID(e)?e: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 T1=k.observer(({children:t})=>i(s.Box,{children:t})),D1=k.observer(({children:t,view:e})=>{const n=K(),r=e.config,a=n.views.visibleViewIDs.includes(e.id),o=()=>n.views.rmVisibleViewID(e.id);return i(s.Modal,{size:r.width,centered:!0,opened:a,onClose:o,withCloseButton:!1,title:r.custom_modal_title.value,trapFocus:!0,onDragStart:l=>{l.stopPropagation()},styles:{root:{position:"fixed",zIndex:200,inset:0},overlay:{zIndex:"unset"},inner:{zIndex:"unset"},content:{border:"1px solid #efefef"},body:{maxHeight:r.height,overflow:"auto"}},transitionProps:{duration:0},children:t})}),M1=t=>t.color?{"&[data-active], &[data-active]:hover":{borderColor:t.color?t.color:"..."}}:{},I1=k.observer(({children:t,view:e})=>{const n=K(),r=e.config;return p(s.Box,{className:"render-view-tabs",children:[p(s.Tabs,{variant:r.variant,orientation:r.orientation,defaultValue:r.tabs.length>0?r.tabs[0].id:"0",styles:{panel:{padding:r.orientation==="horizontal"?"16px 0px":"0"}},keepMounted:!1,children:[i(s.Tabs.List,{grow:r.grow,children:r.tabs.map(a=>i(s.Tabs.Tab,{value:a.id,sx:M1(a),disabled:!a.view_id,children:a.name??a.id},a.id))}),r.tabs.map(a=>{const o=n.views.findByID(a.view_id);return o?i(s.Tabs.Panel,{value:a.id,children:i(nr,{view:o})},a.id):null})]}),t]})}),E1=k.observer(({view:t,children:e})=>{switch(t.type){case H.Modal:return i(D1,{view:t,children:e});case H.Tabs:return i(I1,{view:t,children:e});case H.Division:default:return i(T1,{children:e})}}),nr=k.observer(function({view:e}){const{fullScreenPanelID:n,setFullScreenPanelID:r}=ws(),{viewPanelInFullScreen:a,exitFullScreen:o,inFullScreen:l,fullScreenPanel:u}=k1(e,n,r);return i(Di.Provider,{value:{viewPanelInFullScreen:a,inFullScreen:l},children:p(s.Box,{className:"dashboard-view","data-enable-scrollbar":!0,children:[l&&i(_1,{view:e,panel:u,exitFullScreen:o}),i(E1,{view:e,children:p(s.Box,{sx:{position:"relative"},children:[!l&&i(s.Box,{className:"dashboard-sticky-area",sx:{position:"sticky",top:"0px"},children:i(pl,{view:e})}),!l&&i(m1,{view:e})]})})]})})});function Mi(t){return y.useCallback(e=>e.provideValue(Ce.pluginManager,t.pluginManager).provideValue(Ce.vizManager,t.vizManager).provideValue(Ce.colorManager,t.colorManager),[])}const A1=k.observer(({headerMenuItems:t=null})=>{const e=he(),n=K(),r=()=>{const a=JSON.stringify(n.json,null,2),o=`${e.name}__${n.name}`;Au(o,a)};return p(s.Menu,{shadow:"md",width:200,trigger:"hover",openDelay:100,closeDelay:400,withinPortal:!0,zIndex:310,children:[i(s.Menu.Target,{children:i(s.ActionIcon,{variant:"light",color:"blue",children:i(L.IconMenu2,{size:14})})}),p(s.Menu.Dropdown,{children:[i(s.Menu.Item,{icon:i(L.IconDownload,{size:14}),onClick:n.queries.downloadAllData,children:"Download Data"}),i(s.Menu.Item,{icon:i(L.IconCode,{size:14}),onClick:r,children:"Download Schema"}),t]})]})}),z1=k.observer(({saveDashboardChanges:t})=>{const e=Ue.useModals(),n=K(),r=()=>{e.openConfirmModal({title:p(s.Group,{position:"left",children:[i(L.IconAlertTriangle,{size:18,color:"red"}),i(s.Text,{children:"You are reverting changes"})]}),labels:{confirm:"Confirm",cancel:"Cancel"},confirmProps:{color:"red"},onCancel:()=>console.log("Cancel"),onConfirm:()=>n.reset(),zIndex:320,withCloseButton:!1})},a=n.changed;return p(s.Group,{spacing:0,children:[i(s.Button,{color:"green",variant:"filled",size:"xs",leftIcon:i(L.IconDeviceFloppy,{size:18}),onClick:t,disabled:!a,sx:{borderTopRightRadius:0,borderBottomRightRadius:0},children:"Save Changes"}),p(s.Menu,{width:200,trigger:"hover",openDelay:100,closeDelay:400,withinPortal:!0,zIndex:320,disabled:!a,children:[i(s.Menu.Target,{children:i(s.ActionIcon,{variant:"default",disabled:!a,sx:{height:"30px",borderTopLeftRadius:0,borderBottomLeftRadius:0,svg:{fill:"rgb(173, 181, 189)",stroke:"none"}},children:i(L.IconCaretDown,{size:18})})}),i(s.Menu.Dropdown,{children:i(s.Menu.Item,{icon:i(L.IconRecycle,{size:14,color:"red"}),disabled:!a,onClick:r,children:"Revert Changes"})})]})]})}),$1=k.observer(({saveDashboardChanges:t,headerSlot:e=null,headerMenuItems:n})=>{const r=iu.useNavigate(),a=he(),o=()=>{r(`/dashboard/${a.id}`)},l=Ue.useModals(),u=()=>{l.openConfirmModal({title:p(s.Group,{position:"left",children:[i(L.IconAlertTriangle,{size:18,color:"red"}),i(s.Text,{children:"There are unsaved changes"})]}),labels:{confirm:"Discard",cancel:"Cancel"},confirmProps:{color:"red"},onCancel:()=>console.log("Cancel"),onConfirm:o,zIndex:320,withCloseButton:!1})},c=a.content.changed;return i(s.Header,{height:60,px:"md",py:0,sx:{zIndex:299},children:p(s.Group,{position:"apart",sx:{height:60,minWidth:"1000px",position:"relative"},children:[p(s.Group,{children:[i(s.Button,{size:"xs",color:c?"red":"green",leftIcon:i(L.IconArrowLeft,{size:20}),onClick:c?u:o,children:p(s.Group,{spacing:4,children:["End Editing",i(s.Text,{td:"underline",children:a.name})]})}),i(z1,{saveDashboardChanges:t})]}),p(s.Group,{position:"right",sx:{flexGrow:1},children:[e,i(A1,{headerMenuItems:n})]})]})})}),L1={position:"fixed",top:60,left:0,right:0,height:30,zIndex:299,borderBottom:"1px solid #e9ecef",background:"rgba(233,236,239, 0.15)"},O1=k.observer(()=>{const t=K();return i(s.Box,{sx:L1,pl:{base:200,xs:200,sm:200,md:220,lg:240,xl:260},children:p(s.Group,{position:"apart",align:"center",sx:{height:"30px"},pr:16,children:[i(s.Button,{variant:"outline",color:"blue",radius:0,size:"xs",disabled:!t.views.VIE,onClick:()=>t.addANewPanel(t.views.idOfVIE),leftIcon:i(L.IconPlaylistAdd,{size:20}),sx:{height:"30px",borderLeft:"none",borderTop:"none",borderRight:"1px solid #e9ecef",borderBottom:"1px solid #e9ecef",background:"rgb(231, 245, 255)"},children:"Add a Panel"}),i(s.Box,{}),i(s.Box,{})]})})}),P1=k.observer(t=>p(V,{children:[i($1,{...t}),i(O1,{})]})),xD="",wD="";function B1(t,e,n){const r=[];return t.filter(a=>"__INTERACTIONS"in a.viz.conf).forEach((a,o)=>{const l=e[a.id];l.data.interactions=x.get(l,"data.interactions",[]);const{__INTERACTIONS:u,__OPERATIONS:c,__TRIGGERS:d}=a.viz.conf;Object.entries(c).forEach(([f,h])=>{const{schemaRef:g,data:m}=h,{config:w}=m;switch(g){case"builtin:op:open-link":let C=w.urlTemplate.substring(0,100);w.urlTemplate.length>=20&&(C+="..."),l.type="interaction",l.data.interactions.push({schemaRef:g,urlTemplate:w.urlTemplate,shortURLTemplate:C});return;case"builtin:op:open_view":r.push({id:`OPERATION--${f}`,source:a.id,target:w.viewID,label:"Open View",style:{stroke:"rgba(0,0,0,0.8)"},type:"default"});return;case"builtin:op:set_filter_values":l.type="interaction",l.data.interactions.push({schemaRef:g,filters:Object.keys(w.dictionary).map(_=>({key:_,label:n[_]}))});return;case"builtin:op:clear_filter_values":l.type="interaction",l.data.interactions.push({schemaRef:g,filters:w.filter_keys.map(_=>({key:_,label:n[_]}))});return;default:return}})}),r}function V1(t,e){const n=t.filters.keyLabelMap;return{edges:B1(t.panels.list,e,n),edgeNodes:[]}}function wl(t,e,n){return t*e+t*n}function N1(t,e,n){return t*e+(t-1)*n}const rr=25,Ii=40,Cl=25,Ei=350,q1=150,F1=150,Sl=150,_l=300,ir=40,kl=25,G1=300;function W1(t,e){const n=x.keyBy(e,a=>a.id),r=[];return t.current.forEach((a,o)=>{a.panelIDs.forEach((l,u)=>{const c=wl(u,ir,kl)+Ii,d=n[l];if(!d){r.push({id:l,_node_type:"panel",parentNode:a.id,data:{label:`!: ${l}`},position:{x:rr,y:c},sourcePosition:Ee.Position.Right,targetPosition:Ee.Position.Left,style:{width:_l,height:ir}});return}const f=d.title.trim()?`${d.title}`:d.viz.type;r.push({id:d.id,_node_type:"panel",parentNode:a.id,data:{label:f},position:{x:rr,y:c},sourcePosition:Ee.Position.Right,targetPosition:Ee.Position.Left,style:{width:_l,height:ir}})})}),r}const j1={[H.Division]:"Div",[H.Modal]:"Modal",[H.Tabs]:"Tabs"},R1=Ho;function Y1(t){return t.current.map((n,r)=>{const a=N1(n.panelIDs.length,ir,kl)+Ii+Cl;let o=[];return n.type===H.Tabs&&(o=n.config.tabs.map(u=>u.view_id)),{id:n.id,_node_type:"view-root",_view_type:n.type,_view_level:0,_sub_view_ids:[],_tab_view_ids:o,data:{label:`${j1[n.type]}:${n.name}`},position:{x:0,y:0},sourcePosition:Ee.Position.Right,targetPosition:Ee.Position.Left,className:"light",style:{backgroundColor:R1[n.type],width:Ei,height:a}}})}function Q1(t){const e=x.keyBy(t,n=>n.id);t.forEach(n=>{n._node_type!=="view-root"||n._view_type!==H.Tabs||n._tab_view_ids.forEach(r=>{e[r].parentNode=n.id})})}function K1(t){const e=Y1(t.views);Q1(e);const n=W1(t.views,t.panels.list);return[...e,...n]}function U1({nodeMap:t,nodes:e,edges:n}){e.forEach(r=>{r._node_type!=="view-root"||r._view_type!==H.Tabs||(r.sourcePosition=Ee.Position.Bottom,r.style.width=Ei+rr*2,r.style.height=Cl+r._tab_view_ids.reduce((a,o)=>{const l=t[o];l.position.y=a,l.position.x=rr;const u=l.style.height;return a+u+20},Ii))})}function X1({nodeMap:t,nodes:e,edges:n}){n.filter(r=>r.label==="Open View").forEach(r=>{const a=t[r.source],o=t[r.target];if(!a||!o||!a.parentNode)return;const l=t[a.parentNode];l._node_type!=="view-root"||o._node_type!=="view-root"||(o._view_level+=1+l._view_level,l._sub_view_ids.push(o.id))}),e.sort((r,a)=>r._node_type==="view-root"&&a._node_type==="view-root"?r._view_level-a._view_level:r._node_type!=="view-root"&&a._node_type!=="view-root"?0:r._node_type==="view-root"?-1:1)}function J1({nodeMap:t,nodes:e,edges:n}){const r={};n.forEach(a=>{if(a.label!=="Open View")return;const o=t[a.source],l=t[a.target];if(o&&l&&o.parentNode){const u=t[o.parentNode],c=u.position.x,d=Number(x.get(l,"style.height",0)),f=Number(u.style.width);l.position.x=c+f+G1,u._view_level===0&&l._sub_view_ids.length===0&&(o.sourcePosition=Ee.Position.Left,l.targetPosition=Ee.Position.Right,l.position.x*=-1);const g=l.position.x,m=x.get(r,g,0);l.position.y=m,r[g]=m+d+Sl}})}function Z1({nodeMap:t,nodes:e,edges:n}){const r=new Set,a=new Set;n.forEach(l=>{r.add(l.source),a.add(l.target)}),e.filter(l=>l._node_type!=="view-root"||l.id==="Main"||l.parentNode?!1:!r.has(l.id)&&!a.has(l.id)).forEach((l,u)=>{l.position.x=wl(u,Ei,F1),l.position.y=0-q1-Sl})}function H1({nodeMap:t,nodes:e,edges:n}){const r={nodeMap:t,nodes:e,edges:n};return Z1(r),X1(r),U1(r),J1(r),{nodes:e,edges:n}}function eS(t){const e=K1(t),n=x.keyBy(e,c=>c.id),{edges:r,edgeNodes:a}=V1(t,n),o=[...e,...a],l=x.keyBy(o,c=>c.id),u={edges:x.uniqBy(r,c=>c.id),nodes:o,nodeMap:l};return H1(u)}const CD="",Ai={"builtin:op:open-link":i(s.ThemeIcon,{color:"blue",size:20,radius:"xl",children:i(L.IconCircleDashed,{size:14})}),"builtin:op:set_filter_values":i(s.ThemeIcon,{color:"orange",size:20,radius:"xl",children:i(L.IconCircleDot,{size:14})}),"builtin:op:clear_filter_values":i(s.ThemeIcon,{color:"orange",size:20,radius:"xl",children:i(L.IconCircleOff,{size:14})})};function tS(t){const e=[];return t.forEach(n=>{switch(n.schemaRef){case"builtin:op:open-link":e.push({key:n.urlTemplate,icon:Ai[n.schemaRef],text:p(s.Group,{spacing:4,children:[i(s.Text,{children:"Open: "}),i(s.Text,{color:"dimmed",children:n.shortURLTemplate})]})});return;case"builtin:op:set_filter_values":n.filters.forEach(({key:r,label:a})=>{e.push({key:n.schemaRef+r,icon:Ai[n.schemaRef],text:i(s.Group,{spacing:4,children:p(s.Text,{children:["Set Filter: ",a]})})})});return;case"builtin:op:clear_filter_values":n.filters.forEach(({key:r,label:a})=>{e.push({key:n.schemaRef+r,icon:Ai[n.schemaRef],text:i(s.Group,{spacing:4,children:p(s.Text,{children:["Clear Filter: ",a]})})})});return}}),e}const nS=y.memo(({data:t,isConnectable:e,sourcePosition:n=Ee.Position.Right,targetPosition:r=Ee.Position.Left,...a})=>{const o=y.useMemo(()=>tS(t.interactions),[t.interactions]);return p(V,{children:[i(Ee.Handle,{type:"target",position:r,isConnectable:e}),i(s.Box,{sx:{position:"absolute",top:0,right:0},children:i(D.ChevronsUpRight,{size:12})}),p(s.HoverCard,{shadow:"xl",withinPortal:!0,children:[i(s.HoverCard.Target,{children:i(s.Text,{children:t.label})}),i(s.HoverCard.Dropdown,{children:i(s.List,{spacing:"xs",size:"sm",center:!0,children:o.map(l=>i(s.List.Item,{icon:l.icon,children:l.text},l.key))})})]}),i(Ee.Handle,{type:"source",position:n,isConnectable:e})]})}),SD="",rS={interaction:nS},iS=k.observer(()=>{const t=K(),{edges:e,nodes:n}=eS(t);return p(Ee,{nodes:n,edges:e,onNodesChange:x.noop,onEdgesChange:x.noop,onConnect:x.noop,className:"interactions-viewer",fitView:!0,nodeTypes:rS,children:[i(Ee.MiniMap,{}),i(Ee.Controls,{}),i(Ee.Background,{})]})}),aS=k.observer(({opened:t,close:e})=>{const{freezeLayout:n}=y.useContext(ft);return y.useEffect(()=>{n(t)},[t]),i(s.Modal,{size:"96vw",opened:t,onClose:e,title:"Interactions",trapFocus:!0,onDragStart:r=>{r.stopPropagation()},styles:{body:{height:"90vh"},content:{transform:"none !important"}},zIndex:300,children:i(iS,{})})}),sS={"> button":{"&:first-of-type":{borderTopRightRadius:0,borderBottomRightRadius:0,borderRightWidth:.5},":not(:first-of-type):not(:last-of-type)":{borderTopRightRadius:0,borderBottomRightRadius:0,borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeftWidth:.5,borderRightWidth:.5},"&:last-of-type":{borderTopLeftRadius:0,borderBottomLeftRadius:0,borderLeftWidth:.5}}};function oS({onClick:t,name:e,active:n,openSettings:r}){return p(s.Box,{sx:{position:"relative"},children:[i(s.UnstyledButton,{sx:a=>({display:"block",width:"100%",padding:a.spacing.xs,borderRadius:0,position:"relative",color:a.black,"&:hover":{backgroundColor:a.colors.gray[0]},backgroundColor:n?a.colors.gray[2]:"transparent"}),children:i(s.Group,{sx:{width:"calc(100% - 28px)"},onClick:t,children:i(s.Text,{size:"sm",children:e})})}),n&&i(s.Tooltip,{label:"Edit",position:"right",withinPortal:!0,children:i(s.ActionIcon,{onClick:r,variant:"light",color:"blue",sx:{position:"absolute",top:0,bottom:0,height:"100%",right:0,zIndex:0,borderRadius:0},children:i(L.IconAdjustments,{size:16})})})]})}const lS=k.observer(()=>{const t=he(),e=K(),n=y.useCallback(a=>()=>e.views.setIDOfVIE(a),[e]),r=a=>{t.editor.open(["_VIEWS_",a])};return p(s.Box,{sx:{position:"relative"},children:[e.views.options.map(a=>i(oS,{active:e.views.idOfVIE===a.value,name:a.label,onClick:n(a.value),openSettings:()=>r(a.value)},a.value)),i(s.Divider,{variant:"dashed"}),i(s.Button,{variant:"subtle",rightIcon:i(L.IconPlus,{size:14}),size:"sm",px:"xs",color:"blue",onClick:e.views.addARandomNewView,sx:{width:"100%",borderRadius:0},styles:{inner:{justifyContent:"space-between"}},children:"Add a View"})]})}),uS=k.observer(()=>{const t=he(),e=K(),n=()=>{if(!e.queries.firstID){t.editor.open(["_QUERIES_",""]);return}t.editor.open(["_QUERIES_",e.queries.firstID])},r=()=>{if(!e.filters.firstID){t.editor.open(["_FILTERS_",""]);return}t.editor.open(["_FILTERS_",e.filters.firstID])},[a,o]=y.useState(!1),l=()=>o(!0),u=()=>o(!1);return p(s.Navbar,{p:0,width:{base:200,xs:200,sm:200,md:220,lg:240,xl:260},zIndex:299,children:[p(s.Navbar.Section,{children:[p(s.Group,{grow:!0,spacing:0,sx:{...sS,button:{borderWidth:0,borderBottomWidth:1,borderColor:"#e9ecef"}},children:[i(s.Tooltip,{label:"Filters",withinPortal:!0,children:i(s.ActionIcon,{variant:"default",radius:0,size:"md",sx:{height:"30px"},onClick:r,children:i(L.IconFilter,{size:18})})}),i(s.Tooltip,{label:"Queries",withinPortal:!0,children:i(s.ActionIcon,{variant:"default",radius:0,size:"md",sx:{height:"30px"},onClick:n,children:i(L.IconDatabase,{size:18})})}),i(s.Tooltip,{label:"Interactions Viewer",withinPortal:!0,children:i(s.ActionIcon,{variant:"default",radius:0,size:"md",sx:{height:"30px"},onClick:l,children:i(L.IconLink,{size:18})})})]}),i(aS,{opened:a,close:u})]}),i(s.Navbar.Section,{py:5,sx:{borderBottom:"1px solid #eee"},children:i(s.Text,{align:"center",sx:{userSelect:"none",cursor:"default"},children:"Views"})}),i(s.Navbar.Section,{grow:!0,sx:{overflow:"auto"},children:i(lS,{})}),i(s.Navbar.Section,{children:i(s.Group,{grow:!0,p:"md",pt:"sm",sx:{borderTop:"1px solid #eee"},children:i(s.Button,{size:"xs",leftIcon:i(L.IconSettings,{size:20}),onClick:()=>t.editor.open([]),children:"Settings"})})})]})}),cS=k.observer(function({config:e}){return p(V,{children:[i(s.Checkbox,{checked:e.default_value,onChange:n=>e.setDefaultValue(n.currentTarget.checked),label:"Default Checked"}),i(ai,{label:"Description",value:e.description,onChange:e.setDescription,styles:{root:{flexGrow:1,minHeight:"400px"}}})]})}),dS=[{label:"2022",value:"YYYY"},{label:"202201",value:"YYYYMM"},{label:"20220101",value:"YYYYMMDD"},{label:"2022-01",value:"YYYY-MM"},{label:"2022-01-01",value:"YYYY-MM-DD"}],pS=k.observer(function({config:e}){return p(V,{children:[p(s.Group,{children:[i(s.Checkbox,{checked:e.required,onChange:n=>e.setRequired(n.currentTarget.checked),label:"Required"}),i(s.Checkbox,{checked:e.clearable,onChange:n=>e.setClearable(n.currentTarget.checked),disabled:e.max_days>0,label:"Clearable"}),i(s.Checkbox,{checked:e.allowSingleDateInRange,onChange:n=>e.setAllowSingleDateInRange(n.currentTarget.checked),label:"Allow choosing 1 day"})]}),i(s.Select,{data:dS,label:"Display Format",value:e.inputFormat,onChange:e.setInputFormat}),i(ul,{label:"Default Value",config:e,value:e.default_value,onChange:e.setDefaultValue}),i(s.NumberInput,{label:"Max Days",description:p(s.Group,{position:"apart",children:[i(s.Text,{children:"Set 0 to disable."}),p(s.Group,{spacing:4,children:[i(s.Text,{children:"This feature requires"}),i(s.Text,{color:"blue",children:"Clearable"}),i(s.Text,{children:"to be checked"})]})]}),min:0,value:e.max_days,onChange:e.setMaxDays,hideControls:!0})]})}),zi=k.observer(({value:t,onChange:e})=>{const n=K(),r=y.useMemo(()=>n.queries.options,[n.queries.current]),a=r.length===0;return i(s.Select,{label:"Pick a query",data:r,value:t,onChange:e,allowDeselect:!1,clearable:!0,sx:{flexGrow:1},disabled:a,error:a?"You need to add a query in Data Settings":void 0})}),hS=`
482
482
  // row
483
483
  {
484
484
  label: string;