@devtable/dashboard 13.28.1 → 13.28.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -51,7 +51,7 @@ Check the top-level render call using <`+q+">.")}return A}}function $g(C,A){{if(
51
51
  ${$m.map(Fm).join("")}
52
52
  </tbody>
53
53
  </table>
54
- `;function Di(e,t){const n=Object.keys(t),s=Object.values(t);try{return new Function(...n,`return \`${e}\`;`)(...s)}catch(i){throw n.length===0&&e.includes("$")?new Error("[formatSQL] insufficient payload"):i}}function Mi(e,t){try{return Di(e,t)}catch(n){return console.error(n),n.message}}function Wm({sql:e,pre_process:t}){if(!t.trim())return e;try{return new Function(`return ${t}`)()({sql:e},At)}catch(n){return console.error(n),e}}function Rm(e,t,n){if(!e.trim())return t;try{return new Function(`return ${e}`)()(t,At,n)}catch(s){return console.error(s),t}}function Qm(e){e=e||{};const t=Object.keys(e).sort(),n=[];for(let s=0;s<t.length;s++){const i=t[s];if(i!="authentication"&&e[i])n.push(t[s]+"="+(typeof e[i]=="object"?JSON.stringify(e[i]):e[i]));else{const a=Object.keys(e[i]).sort();for(let l=0;l<a.length;l++){const c=a[l];c!="sign"&&e[i][c]&&n.push(a[l]+"="+(typeof e[i][c]=="object"?JSON.stringify(e[i][c]):e[i][c]))}}}return n.sort().join("&")}function Um(e,t){let n=Qm(e);return n+="&key="+t,Lm.MD5(n).toString().toUpperCase()}class kc{constructor(){this.type="default_api_client",this.baseURL="http://localhost:31200",this.app_id="",this.app_secret=""}getAuthentication(t){if(!this.app_id||!this.app_secret)return;const n=new Date().getTime().toString();return{app_id:this.app_id,nonce_str:n,sign:Um({app_id:this.app_id,nonce_str:n,...t},this.app_secret)}}getRequest(t,n){return(s,i,a,l)=>{const c=this.buildHeader(a),u=this.buildAxiosConfig(t,s,i,a,c,n);return Rt(u).then(d=>l?d:d.data).catch(d=>{if(Rt.isCancel(d))return Promise.reject(d);const h=v.get(d,"response.data.detail.message",d.message);return Promise.reject(new Error(h))})}}get(t){return this.getRequest("GET",t)}post(t){return this.getRequest("POST",t)}put(t){return this.getRequest("PUT",t)}buildAxiosConfig(t,n,s,i,a,l){const c={baseURL:this.baseURL,method:t,url:n,params:t==="GET"?s:i.params,headers:a,signal:l};return["POST","PUT"].includes(t)&&(c.data=i.string?JSON.stringify(s):s,c.data.authentication=this.getAuthentication(c.data)),c}buildHeader(t){const n=window.localStorage.getItem("token");return{"X-Requested-With":"XMLHttpRequest","Content-Type":t.string?"application/x-www-form-urlencoded":"application/json",authorization:n?`bearer ${n}`:"",...t.headers}}}class Ym{constructor(t){this.implementation=t}getRequest(t,n){return this.implementation.getRequest(t,n)}get(t){return this.getRequest("GET",t)}post(t){return this.getRequest("POST",t)}put(t){return this.getRequest("PUT",t)}}class Tc extends kc{constructor(){super(...arguments);N(this,"makeQueryENV",null)}query(n){return async(s,i={})=>{var a;return s.env||(s.env=((a=this.makeQueryENV)==null?void 0:a.call(this))??{error:"failed to run makeQueryENV"}),this.post(n)("/query",s,i)}}httpDataSourceQuery(n){return async(s,i={})=>{var a;return s.env||(s.env=((a=this.makeQueryENV)==null?void 0:a.call(this))??{error:"failed to run makeQueryENV"}),this.getRequest("POST",n)("/query",s,i,!0)}}structure(n){return async(s,i={})=>this.post(n)("/query/structure",s,i)}}class Dc{constructor(t){this.implementation=t}query(t){return this.implementation.query(t)}httpDataSourceQuery(t){return this.implementation.httpDataSourceQuery(t)}structure(t){return this.implementation.structure(t)}getRequest(t,n){return this.implementation.getRequest(t,n)}get(t){return this.getRequest("GET",t)}post(t){return this.getRequest("POST",t)}put(t){return this.getRequest("PUT",t)}}const Qn=new Tc;function Ii(e){Qn.baseURL!==e.apiBaseURL&&(Qn.baseURL=e.apiBaseURL),e.app_id&&(Qn.app_id=e.app_id),e.app_secret&&(Qn.app_secret=e.app_secret),e.makeQueryENV&&(Qn.makeQueryENV=e.makeQueryENV)}const Mc=new Dc(Qn),Kt=Mc,ls=g.forwardRef(function({value:t,onChange:n,...s},i){return r.jsx(o.TextInput,{ref:i,value:t,onChange:n,...s})});function L(e){const[t,n]=e.split(".");return{queryID:t,columnKey:n}}function Km(e){return e.includes(".")?L(e):{queryID:"",columnKey:e}}function Pt(e,t){var i;const{queryID:n,columnKey:s}=L(t);return n?s?((i=e[n])==null?void 0:i.map(a=>a[s]))??[]:e[n]:[]}function cs(e,t){const{queryID:n}=L(t);return n?e[n]:[]}function Xm(e){return Object.values(e)[0]}function us(e,t){const{queryID:n,columnKey:s}=L(t);return e[s]}const Ic=["function aggregation({ queryData }, utils) {",' return "Aggregation Result";',"}"].join(`
54
+ `;function Di(e,t){const n=Object.keys(t),s=Object.values(t);try{return new Function(...n,`return \`${e}\`;`)(...s)}catch(i){throw n.length===0&&e.includes("$")?new Error("[formatSQL] insufficient payload"):i}}function Mi(e,t){try{return Di(e,t)}catch(n){return console.error(n),n.message}}function Wm({sql:e,pre_process:t}){if(!t.trim())return e;try{return new Function(`return ${t}`)()({sql:e},At)}catch(n){throw console.error(n),n}}function Rm(e,t,n){if(!e.trim())return t;try{return new Function(`return ${e}`)()(t,At,n)}catch(s){throw console.error(s),s}}function Qm(e){e=e||{};const t=Object.keys(e).sort(),n=[];for(let s=0;s<t.length;s++){const i=t[s];if(i!="authentication"&&e[i])n.push(t[s]+"="+(typeof e[i]=="object"?JSON.stringify(e[i]):e[i]));else{const a=Object.keys(e[i]).sort();for(let l=0;l<a.length;l++){const c=a[l];c!="sign"&&e[i][c]&&n.push(a[l]+"="+(typeof e[i][c]=="object"?JSON.stringify(e[i][c]):e[i][c]))}}}return n.sort().join("&")}function Um(e,t){let n=Qm(e);return n+="&key="+t,Lm.MD5(n).toString().toUpperCase()}class kc{constructor(){this.type="default_api_client",this.baseURL="http://localhost:31200",this.app_id="",this.app_secret=""}getAuthentication(t){if(!this.app_id||!this.app_secret)return;const n=new Date().getTime().toString();return{app_id:this.app_id,nonce_str:n,sign:Um({app_id:this.app_id,nonce_str:n,...t},this.app_secret)}}getRequest(t,n){return(s,i,a,l)=>{const c=this.buildHeader(a),u=this.buildAxiosConfig(t,s,i,a,c,n);return Rt(u).then(d=>l?d:d.data).catch(d=>{if(Rt.isCancel(d))return Promise.reject(d);const h=v.get(d,"response.data.detail.message",d.message);return Promise.reject(new Error(h))})}}get(t){return this.getRequest("GET",t)}post(t){return this.getRequest("POST",t)}put(t){return this.getRequest("PUT",t)}buildAxiosConfig(t,n,s,i,a,l){const c={baseURL:this.baseURL,method:t,url:n,params:t==="GET"?s:i.params,headers:a,signal:l};return["POST","PUT"].includes(t)&&(c.data=i.string?JSON.stringify(s):s,c.data.authentication=this.getAuthentication(c.data)),c}buildHeader(t){const n=window.localStorage.getItem("token");return{"X-Requested-With":"XMLHttpRequest","Content-Type":t.string?"application/x-www-form-urlencoded":"application/json",authorization:n?`bearer ${n}`:"",...t.headers}}}class Ym{constructor(t){this.implementation=t}getRequest(t,n){return this.implementation.getRequest(t,n)}get(t){return this.getRequest("GET",t)}post(t){return this.getRequest("POST",t)}put(t){return this.getRequest("PUT",t)}}class Tc extends kc{constructor(){super(...arguments);N(this,"makeQueryENV",null)}query(n){return async(s,i={})=>{var a;return s.env||(s.env=((a=this.makeQueryENV)==null?void 0:a.call(this))??{error:"failed to run makeQueryENV"}),this.post(n)("/query",s,i)}}httpDataSourceQuery(n){return async(s,i={})=>{var a;return s.env||(s.env=((a=this.makeQueryENV)==null?void 0:a.call(this))??{error:"failed to run makeQueryENV"}),this.getRequest("POST",n)("/query",s,i,!0)}}structure(n){return async(s,i={})=>this.post(n)("/query/structure",s,i)}}class Dc{constructor(t){this.implementation=t}query(t){return this.implementation.query(t)}httpDataSourceQuery(t){return this.implementation.httpDataSourceQuery(t)}structure(t){return this.implementation.structure(t)}getRequest(t,n){return this.implementation.getRequest(t,n)}get(t){return this.getRequest("GET",t)}post(t){return this.getRequest("POST",t)}put(t){return this.getRequest("PUT",t)}}const Qn=new Tc;function Ii(e){Qn.baseURL!==e.apiBaseURL&&(Qn.baseURL=e.apiBaseURL),e.app_id&&(Qn.app_id=e.app_id),e.app_secret&&(Qn.app_secret=e.app_secret),e.makeQueryENV&&(Qn.makeQueryENV=e.makeQueryENV)}const Mc=new Dc(Qn),Kt=Mc,ls=g.forwardRef(function({value:t,onChange:n,...s},i){return r.jsx(o.TextInput,{ref:i,value:t,onChange:n,...s})});function L(e){const[t,n]=e.split(".");return{queryID:t,columnKey:n}}function Km(e){return e.includes(".")?L(e):{queryID:"",columnKey:e}}function Pt(e,t){var i;const{queryID:n,columnKey:s}=L(t);return n?s?((i=e[n])==null?void 0:i.map(a=>a[s]))??[]:e[n]:[]}function cs(e,t){const{queryID:n}=L(t);return n?e[n]:[]}function Xm(e){return Object.values(e)[0]}function us(e,t){const{queryID:n,columnKey:s}=L(t);return e[s]}const Ic=["function aggregation({ queryData }, utils) {",' return "Aggregation Result";',"}"].join(`
55
55
  `),Un={type:"none",config:{},fallback:"0"};function Jm(e){const t=Array.from(e).sort((s,i)=>s-i),n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function Zm(e,t){switch(t.type){case"sum":return v.sum(e);case"mean":return v.mean(e);case"median":return Jm(e);case"max":return v.max(e);case"min":return v.min(e);case"quantile":return yr.quantile(e,t.config.p);case"CV":const n=Rn.std(...e),s=Rn.mean(...e);return s?n/s:Number.NaN;case"std":return Rn.std(...e);default:return e}}function zi(e,t){const n=e.map(Number),s=Zm(n,t);return typeof s=="number"?Number.isFinite(s)?s:t.fallback:s??t.fallback}function Hm(e,t,n){try{const s=cs(e,t);return new Function(`return ${n.config.func}`)()({queryData:s},At)}catch(s){return console.error(s),s.message}}function ex(e,t,n){try{const s=Pt(e,t),{method:i}=n.config;return v[i](s)}catch(s){return console.error(s),n.fallback}}function ds(e,t,n){try{return n.type==="custom"?Hm(e,t,n):n.type==="pick_record"?ex(e,t,n):zi(Pt(e,t),n)}catch(s){return console.error(s),null}}class tx{constructor({valueRange:t,colorRange:n}){N(this,"mapper");this.mapper=xn.interpolate(t,n)}getColor(t){return this.mapper(t)}}const Ei={fontSize:"14px",lineHeight:"32px",color:"#3D3E45",ul:{paddingLeft:"2em",margin:"6px 0 0"},p:{margin:"0 !important"},a:{WebkitTapHighlightColor:"transparent",color:"rgb(34, 139, 230)",textDecoration:"none","&:hover":{textDecoration:"underline"},"&:active, &:hover":{outlineWidth:0}},table:{tr:{"th, td":{padding:"0 .5em"}}},"table.rich-text-table-render, div.tableWrapper table":{"th, td":{border:"1px solid #eaeaea"},"tr:last-of-type td":{borderBottom:"1px solid #eaeaea"}},".resize-cursor":{cursor:"col-resize"},details:{summary:{listStyle:"none",cursor:"pointer",transition:"color 300ms ease",userSelect:"none"},"summary::-webkit-details-marker":{display:"none"},"summary:hover":{color:"black","&::before":{opacity:1}},"summary::before":{content:'"►"',fontSize:"10px",margin:"0px 5px",opacity:.5,display:"inline-block",transition:"opacity 300ms ease, transform 300ms ease"}},"details[open] summary::before":{transform:"rotate(90deg)"},"details + details":{marginTop:"10px"},blockquote:{fontSize:"14px",lineHeight:"32px",color:"#3D3E45",margin:"0 0 14px"}};function zc(e,t,n){for(let s=0;;s++){if(s==e.childCount||s==t.childCount)return e.childCount==t.childCount?null:n;let i=e.child(s),a=t.child(s);if(i==a){n+=i.nodeSize;continue}if(!i.sameMarkup(a))return n;if(i.isText&&i.text!=a.text){for(let l=0;i.text[l]==a.text[l];l++)n++;return n}if(i.content.size||a.content.size){let l=zc(i.content,a.content,n+1);if(l!=null)return l}n+=i.nodeSize}}function Ec(e,t,n,s){for(let i=e.childCount,a=t.childCount;;){if(i==0||a==0)return i==a?null:{a:n,b:s};let l=e.child(--i),c=t.child(--a),u=l.nodeSize;if(l==c){n-=u,s-=u;continue}if(!l.sameMarkup(c))return{a:n,b:s};if(l.isText&&l.text!=c.text){let d=0,h=Math.min(l.text.length,c.text.length);for(;d<h&&l.text[l.text.length-d-1]==c.text[c.text.length-d-1];)d++,n--,s--;return{a:n,b:s}}if(l.content.size||c.content.size){let d=Ec(l.content,c.content,n-1,s-1);if(d)return d}n-=u,s-=u}}class pe{constructor(t,n){if(this.content=t,this.size=n||0,n==null)for(let s=0;s<t.length;s++)this.size+=t[s].nodeSize}nodesBetween(t,n,s,i=0,a){for(let l=0,c=0;c<n;l++){let u=this.content[l],d=c+u.nodeSize;if(d>t&&s(u,i+c,a||null,l)!==!1&&u.content.size){let h=c+1;u.nodesBetween(Math.max(0,t-h),Math.min(u.content.size,n-h),s,i+h)}c=d}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,n,s,i){let a="",l=!0;return this.nodesBetween(t,n,(c,u)=>{c.isText?(a+=c.text.slice(Math.max(t,u)-u,n-u),l=!s):c.isLeaf?(i?a+=typeof i=="function"?i(c):i:c.type.spec.leafText&&(a+=c.type.spec.leafText(c)),l=!s):!l&&c.isBlock&&(a+=s,l=!0)},0),a}append(t){if(!t.size)return this;if(!this.size)return t;let n=this.lastChild,s=t.firstChild,i=this.content.slice(),a=0;for(n.isText&&n.sameMarkup(s)&&(i[i.length-1]=n.withText(n.text+s.text),a=1);a<t.content.length;a++)i.push(t.content[a]);return new pe(i,this.size+t.size)}cut(t,n=this.size){if(t==0&&n==this.size)return this;let s=[],i=0;if(n>t)for(let a=0,l=0;l<n;a++){let c=this.content[a],u=l+c.nodeSize;u>t&&((l<t||u>n)&&(c.isText?c=c.cut(Math.max(0,t-l),Math.min(c.text.length,n-l)):c=c.cut(Math.max(0,t-l-1),Math.min(c.content.size,n-l-1))),s.push(c),i+=c.nodeSize),l=u}return new pe(s,i)}cutByIndex(t,n){return t==n?pe.empty:t==0&&n==this.content.length?this:new pe(this.content.slice(t,n))}replaceChild(t,n){let s=this.content[t];if(s==n)return this;let i=this.content.slice(),a=this.size+n.nodeSize-s.nodeSize;return i[t]=n,new pe(i,a)}addToStart(t){return new pe([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new pe(this.content.concat(t),this.size+t.nodeSize)}eq(t){if(this.content.length!=t.content.length)return!1;for(let n=0;n<this.content.length;n++)if(!this.content[n].eq(t.content[n]))return!1;return!0}get firstChild(){return this.content.length?this.content[0]:null}get lastChild(){return this.content.length?this.content[this.content.length-1]:null}get childCount(){return this.content.length}child(t){let n=this.content[t];if(!n)throw new RangeError("Index "+t+" out of range for "+this);return n}maybeChild(t){return this.content[t]||null}forEach(t){for(let n=0,s=0;n<this.content.length;n++){let i=this.content[n];t(i,s,n),s+=i.nodeSize}}findDiffStart(t,n=0){return zc(this,t,n)}findDiffEnd(t,n=this.size,s=t.size){return Ec(this,t,n,s)}findIndex(t,n=-1){if(t==0)return ps(0,t);if(t==this.size)return ps(this.content.length,t);if(t>this.size||t<0)throw new RangeError(`Position ${t} outside of fragment (${this})`);for(let s=0,i=0;;s++){let a=this.child(s),l=i+a.nodeSize;if(l>=t)return l==t||n>0?ps(s+1,l):ps(s,i);i=l}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(t=>t.toJSON()):null}static fromJSON(t,n){if(!n)return pe.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new pe(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return pe.empty;let n,s=0;for(let i=0;i<t.length;i++){let a=t[i];s+=a.nodeSize,i&&a.isText&&t[i-1].sameMarkup(a)?(n||(n=t.slice(0,i)),n[n.length-1]=a.withText(n[n.length-1].text+a.text)):n&&n.push(a)}return new pe(n||t,s)}static from(t){if(!t)return pe.empty;if(t instanceof pe)return t;if(Array.isArray(t))return this.fromArray(t);if(t.attrs)return new pe([t],t.nodeSize);throw new RangeError("Can not convert "+t+" to a Fragment"+(t.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}}pe.empty=new pe([],0);const Ai={index:0,offset:0};function ps(e,t){return Ai.index=e,Ai.offset=t,Ai}function Pi(e,t){if(e===t)return!0;if(!(e&&typeof e=="object")||!(t&&typeof t=="object"))return!1;let n=Array.isArray(e);if(Array.isArray(t)!=n)return!1;if(n){if(e.length!=t.length)return!1;for(let s=0;s<e.length;s++)if(!Pi(e[s],t[s]))return!1}else{for(let s in e)if(!(s in t)||!Pi(e[s],t[s]))return!1;for(let s in t)if(!(s in e))return!1}return!0}let Xt=class Jl{constructor(t,n){this.type=t,this.attrs=n}addToSet(t){let n,s=!1;for(let i=0;i<t.length;i++){let a=t[i];if(this.eq(a))return t;if(this.type.excludes(a.type))n||(n=t.slice(0,i));else{if(a.type.excludes(this.type))return t;!s&&a.type.rank>this.type.rank&&(n||(n=t.slice(0,i)),n.push(this),s=!0),n&&n.push(a)}}return n||(n=t.slice()),s||n.push(this),n}removeFromSet(t){for(let n=0;n<t.length;n++)if(this.eq(t[n]))return t.slice(0,n).concat(t.slice(n+1));return t}isInSet(t){for(let n=0;n<t.length;n++)if(this.eq(t[n]))return!0;return!1}eq(t){return this==t||this.type==t.type&&Pi(this.attrs,t.attrs)}toJSON(){let t={type:this.type.name};for(let n in this.attrs){t.attrs=this.attrs;break}return t}static fromJSON(t,n){if(!n)throw new RangeError("Invalid input for Mark.fromJSON");let s=t.marks[n.type];if(!s)throw new RangeError(`There is no mark type ${n.type} in this schema`);return s.create(n.attrs)}static sameSet(t,n){if(t==n)return!0;if(t.length!=n.length)return!1;for(let s=0;s<t.length;s++)if(!t[s].eq(n[s]))return!1;return!0}static setFrom(t){if(!t||Array.isArray(t)&&t.length==0)return Jl.none;if(t instanceof Jl)return[t];let n=t.slice();return n.sort((s,i)=>s.type.rank-i.type.rank),n}};Xt.none=[];class nx extends Error{}class ve{constructor(t,n,s){this.content=t,this.openStart=n,this.openEnd=s}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,n){let s=Pc(this.content,t+this.openStart,n);return s&&new ve(s,this.openStart,this.openEnd)}removeBetween(t,n){return new ve(Ac(this.content,t+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(t){return this.content.eq(t.content)&&this.openStart==t.openStart&&this.openEnd==t.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let t={content:this.content.toJSON()};return this.openStart>0&&(t.openStart=this.openStart),this.openEnd>0&&(t.openEnd=this.openEnd),t}static fromJSON(t,n){if(!n)return ve.empty;let s=n.openStart||0,i=n.openEnd||0;if(typeof s!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new ve(pe.fromJSON(t,n.content),s,i)}static maxOpen(t,n=!0){let s=0,i=0;for(let a=t.firstChild;a&&!a.isLeaf&&(n||!a.type.spec.isolating);a=a.firstChild)s++;for(let a=t.lastChild;a&&!a.isLeaf&&(n||!a.type.spec.isolating);a=a.lastChild)i++;return new ve(t,s,i)}}ve.empty=new ve(pe.empty,0,0);function Ac(e,t,n){let{index:s,offset:i}=e.findIndex(t),a=e.maybeChild(s),{index:l,offset:c}=e.findIndex(n);if(i==t||a.isText){if(c!=n&&!e.child(l).isText)throw new RangeError("Removing non-flat range");return e.cut(0,t).append(e.cut(n))}if(s!=l)throw new RangeError("Removing non-flat range");return e.replaceChild(s,a.copy(Ac(a.content,t-i-1,n-i-1)))}function Pc(e,t,n,s){let{index:i,offset:a}=e.findIndex(t),l=e.maybeChild(i);if(a==t||l.isText)return s&&!s.canReplace(i,i,n)?null:e.cut(0,t).append(n).append(e.cut(t));let c=Pc(l.content,t-a-1,n);return c&&e.replaceChild(i,l.copy(c))}let rx=class Zl{constructor(t,n){this.schema=t,this.rules=n,this.tags=[],this.styles=[],n.forEach(s=>{s.tag?this.tags.push(s):s.style&&this.styles.push(s)}),this.normalizeLists=!this.tags.some(s=>{if(!/^(ul|ol)\b/.test(s.tag)||!s.node)return!1;let i=t.nodes[s.node];return i.contentMatch.matchType(i)})}parse(t,n={}){let s=new Bc(this,n,!1);return s.addAll(t,n.from,n.to),s.finish()}parseSlice(t,n={}){let s=new Bc(this,n,!0);return s.addAll(t,n.from,n.to),ve.maxOpen(s.finish())}matchTag(t,n,s){for(let i=s?this.tags.indexOf(s)+1:0;i<this.tags.length;i++){let a=this.tags[i];if(ax(t,a.tag)&&(a.namespace===void 0||t.namespaceURI==a.namespace)&&(!a.context||n.matchesContext(a.context))){if(a.getAttrs){let l=a.getAttrs(t);if(l===!1)continue;a.attrs=l||void 0}return a}}}matchStyle(t,n,s,i){for(let a=i?this.styles.indexOf(i)+1:0;a<this.styles.length;a++){let l=this.styles[a],c=l.style;if(!(c.indexOf(t)!=0||l.context&&!s.matchesContext(l.context)||c.length>t.length&&(c.charCodeAt(t.length)!=61||c.slice(t.length+1)!=n))){if(l.getAttrs){let u=l.getAttrs(n);if(u===!1)continue;l.attrs=u||void 0}return l}}}static schemaRules(t){let n=[];function s(i){let a=i.priority==null?50:i.priority,l=0;for(;l<n.length;l++){let c=n[l];if((c.priority==null?50:c.priority)<a)break}n.splice(l,0,i)}for(let i in t.marks){let a=t.marks[i].spec.parseDOM;a&&a.forEach(l=>{s(l=qc(l)),l.mark||l.ignore||l.clearMark||(l.mark=i)})}for(let i in t.nodes){let a=t.nodes[i].spec.parseDOM;a&&a.forEach(l=>{s(l=qc(l)),l.node||l.ignore||l.mark||(l.node=i)})}return n}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new Zl(t,Zl.schemaRules(t)))}};const Oc={address:!0,article:!0,aside:!0,blockquote:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},sx={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Lc={ol:!0,ul:!0},hs=1,fs=2,_r=4;function Vc(e,t,n){return t!=null?(t?hs:0)|(t==="full"?fs:0):e&&e.whitespace=="pre"?hs|fs:n&~_r}class gs{constructor(t,n,s,i,a,l,c){this.type=t,this.attrs=n,this.marks=s,this.pendingMarks=i,this.solid=a,this.options=c,this.content=[],this.activeMarks=Xt.none,this.stashMarks=[],this.match=l||(c&_r?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(pe.from(t));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let s=this.type.contentMatch,i;return(i=s.findWrapping(t.type))?(this.match=s,i):null}}return this.match.findWrapping(t.type)}finish(t){if(!(this.options&hs)){let s=this.content[this.content.length-1],i;if(s&&s.isText&&(i=/[ \t\r\n\u000c]+$/.exec(s.text))){let a=s;s.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=a.withText(a.text.slice(0,a.text.length-i[0].length))}}let n=pe.from(this.content);return!t&&this.match&&(n=n.append(this.match.fillBefore(pe.empty,!0))),this.type?this.type.create(this.attrs,n,this.marks):n}popFromStashMark(t){for(let n=this.stashMarks.length-1;n>=0;n--)if(t.eq(this.stashMarks[n]))return this.stashMarks.splice(n,1)[0]}applyPending(t){for(let n=0,s=this.pendingMarks;n<s.length;n++){let i=s[n];(this.type?this.type.allowsMarkType(i.type):lx(i.type,t))&&!i.isInSet(this.activeMarks)&&(this.activeMarks=i.addToSet(this.activeMarks),this.pendingMarks=i.removeFromSet(this.pendingMarks))}}inlineContext(t){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:t.parentNode&&!Oc.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class Bc{constructor(t,n,s){this.parser=t,this.options=n,this.isOpen=s,this.open=0;let i=n.topNode,a,l=Vc(null,n.preserveWhitespace,0)|(s?_r:0);i?a=new gs(i.type,i.attrs,Xt.none,Xt.none,!0,n.topMatch||i.type.contentMatch,l):s?a=new gs(null,null,Xt.none,Xt.none,!0,null,l):a=new gs(t.schema.topNodeType,null,Xt.none,Xt.none,!0,null,l),this.nodes=[a],this.find=n.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(t){if(t.nodeType==3)this.addTextNode(t);else if(t.nodeType==1){let n=t.getAttribute("style");if(!n)this.addElement(t);else{let s=this.readStyles(ox(n));if(!s)return;let[i,a]=s,l=this.top;for(let c=0;c<a.length;c++)this.removePendingMark(a[c],l);for(let c=0;c<i.length;c++)this.addPendingMark(i[c]);this.addElement(t);for(let c=0;c<i.length;c++)this.removePendingMark(i[c],l);for(let c=0;c<a.length;c++)this.addPendingMark(a[c])}}}addTextNode(t){let n=t.nodeValue,s=this.top;if(s.options&fs||s.inlineContext(t)||/[^ \t\r\n\u000c]/.test(n)){if(s.options&hs)s.options&fs?n=n.replace(/\r\n?/g,`
56
56
  `):n=n.replace(/\r?\n|\r/g," ");else if(n=n.replace(/[ \t\r\n\u000c]+/g," "),/^[ \t\r\n\u000c]/.test(n)&&this.open==this.nodes.length-1){let i=s.content[s.content.length-1],a=t.previousSibling;(!i||a&&a.nodeName=="BR"||i.isText&&/[ \t\r\n\u000c]$/.test(i.text))&&(n=n.slice(1))}n&&this.insertNode(this.parser.schema.text(n)),this.findInText(t)}else this.findInside(t)}addElement(t,n){let s=t.nodeName.toLowerCase(),i;Lc.hasOwnProperty(s)&&this.parser.normalizeLists&&ix(t);let a=this.options.ruleFromNode&&this.options.ruleFromNode(t)||(i=this.parser.matchTag(t,this,n));if(a?a.ignore:sx.hasOwnProperty(s))this.findInside(t),this.ignoreFallback(t);else if(!a||a.skip||a.closeParent){a&&a.closeParent?this.open=Math.max(0,this.open-1):a&&a.skip.nodeType&&(t=a.skip);let l,c=this.top,u=this.needsBlock;if(Oc.hasOwnProperty(s))c.content.length&&c.content[0].isInline&&this.open&&(this.open--,c=this.top),l=!0,c.type||(this.needsBlock=!0);else if(!t.firstChild){this.leafFallback(t);return}this.addAll(t),l&&this.sync(c),this.needsBlock=u}else this.addElementByRule(t,a,a.consuming===!1?i:void 0)}leafFallback(t){t.nodeName=="BR"&&this.top.type&&this.top.type.inlineContent&&this.addTextNode(t.ownerDocument.createTextNode(`
57
57
  `))}ignoreFallback(t){t.nodeName=="BR"&&(!this.top.type||!this.top.type.inlineContent)&&this.findPlace(this.parser.schema.text("-"))}readStyles(t){let n=Xt.none,s=Xt.none;for(let i=0;i<t.length;i+=2)for(let a=void 0;;){let l=this.parser.matchStyle(t[i],t[i+1],this,a);if(!l)break;if(l.ignore)return null;if(l.clearMark?this.top.pendingMarks.concat(this.top.activeMarks).forEach(c=>{l.clearMark(c)&&(s=c.addToSet(s))}):n=this.parser.schema.marks[l.mark].create(l.attrs).addToSet(n),l.consuming===!1)a=l;else break}return[n,s]}addElementByRule(t,n,s){let i,a,l;n.node?(a=this.parser.schema.nodes[n.node],a.isLeaf?this.insertNode(a.create(n.attrs))||this.leafFallback(t):i=this.enter(a,n.attrs||null,n.preserveWhitespace)):(l=this.parser.schema.marks[n.mark].create(n.attrs),this.addPendingMark(l));let c=this.top;if(a&&a.isLeaf)this.findInside(t);else if(s)this.addElement(t,s);else if(n.getContent)this.findInside(t),n.getContent(t,this.parser.schema).forEach(u=>this.insertNode(u));else{let u=t;typeof n.contentElement=="string"?u=t.querySelector(n.contentElement):typeof n.contentElement=="function"?u=n.contentElement(t):n.contentElement&&(u=n.contentElement),this.findAround(t,u,!0),this.addAll(u)}i&&this.sync(c)&&this.open--,l&&this.removePendingMark(l,c)}addAll(t,n,s){let i=n||0;for(let a=n?t.childNodes[n]:t.firstChild,l=s==null?null:t.childNodes[s];a!=l;a=a.nextSibling,++i)this.findAtPoint(t,i),this.addDOM(a);this.findAtPoint(t,i)}findPlace(t){let n,s;for(let i=this.open;i>=0;i--){let a=this.nodes[i],l=a.findWrapping(t);if(l&&(!n||n.length>l.length)&&(n=l,s=a,!l.length)||a.solid)break}if(!n)return!1;this.sync(s);for(let i=0;i<n.length;i++)this.enterInner(n[i],null,!1);return!0}insertNode(t){if(t.isInline&&this.needsBlock&&!this.top.type){let n=this.textblockFromContext();n&&this.enterInner(n)}if(this.findPlace(t)){this.closeExtra();let n=this.top;n.applyPending(t.type),n.match&&(n.match=n.match.matchType(t.type));let s=n.activeMarks;for(let i=0;i<t.marks.length;i++)(!n.type||n.type.allowsMarkType(t.marks[i].type))&&(s=t.marks[i].addToSet(s));return n.content.push(t.mark(s)),!0}return!1}enter(t,n,s){let i=this.findPlace(t.create(n));return i&&this.enterInner(t,n,!0,s),i}enterInner(t,n=null,s=!1,i){this.closeExtra();let a=this.top;a.applyPending(t),a.match=a.match&&a.match.matchType(t);let l=Vc(t,i,a.options);a.options&_r&&a.content.length==0&&(l|=_r),this.nodes.push(new gs(t,n,a.activeMarks,a.pendingMarks,s,null,l)),this.open++}closeExtra(t=!1){let n=this.nodes.length-1;if(n>this.open){for(;n>this.open;n--)this.nodes[n-1].content.push(this.nodes[n].finish(t));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(this.isOpen||this.options.topOpen)}sync(t){for(let n=this.open;n>=0;n--)if(this.nodes[n]==t)return this.open=n,!0;return!1}get currentPos(){this.closeExtra();let t=0;for(let n=this.open;n>=0;n--){let s=this.nodes[n].content;for(let i=s.length-1;i>=0;i--)t+=s[i].nodeSize;n&&t++}return t}findAtPoint(t,n){if(this.find)for(let s=0;s<this.find.length;s++)this.find[s].node==t&&this.find[s].offset==n&&(this.find[s].pos=this.currentPos)}findInside(t){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].pos==null&&t.nodeType==1&&t.contains(this.find[n].node)&&(this.find[n].pos=this.currentPos)}findAround(t,n,s){if(t!=n&&this.find)for(let i=0;i<this.find.length;i++)this.find[i].pos==null&&t.nodeType==1&&t.contains(this.find[i].node)&&n.compareDocumentPosition(this.find[i].node)&(s?2:4)&&(this.find[i].pos=this.currentPos)}findInText(t){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].node==t&&(this.find[n].pos=this.currentPos-(t.nodeValue.length-this.find[n].offset))}matchesContext(t){if(t.indexOf("|")>-1)return t.split(/\s*\|\s*/).some(this.matchesContext,this);let n=t.split("/"),s=this.options.context,i=!this.isOpen&&(!s||s.parent.type==this.nodes[0].type),a=-(s?s.depth+1:0)+(i?0:1),l=(c,u)=>{for(;c>=0;c--){let d=n[c];if(d==""){if(c==n.length-1||c==0)continue;for(;u>=a;u--)if(l(c-1,u))return!0;return!1}else{let h=u>0||u==0&&i?this.nodes[u].type:s&&u>=a?s.node(u-a).type:null;if(!h||h.name!=d&&h.groups.indexOf(d)==-1)return!1;u--}}return!0};return l(n.length-1,this.open)}textblockFromContext(){let t=this.options.context;if(t)for(let n=t.depth;n>=0;n--){let s=t.node(n).contentMatchAt(t.indexAfter(n)).defaultType;if(s&&s.isTextblock&&s.defaultAttrs)return s}for(let n in this.parser.schema.nodes){let s=this.parser.schema.nodes[n];if(s.isTextblock&&s.defaultAttrs)return s}}addPendingMark(t){let n=cx(t,this.top.pendingMarks);n&&this.top.stashMarks.push(n),this.top.pendingMarks=t.addToSet(this.top.pendingMarks)}removePendingMark(t,n){for(let s=this.open;s>=0;s--){let i=this.nodes[s];if(i.pendingMarks.lastIndexOf(t)>-1)i.pendingMarks=t.removeFromSet(i.pendingMarks);else{i.activeMarks=t.removeFromSet(i.activeMarks);let l=i.popFromStashMark(t);l&&i.type&&i.type.allowsMarkType(l.type)&&(i.activeMarks=l.addToSet(i.activeMarks))}if(i==n)break}}}function ix(e){for(let t=e.firstChild,n=null;t;t=t.nextSibling){let s=t.nodeType==1?t.nodeName.toLowerCase():null;s&&Lc.hasOwnProperty(s)&&n?(n.appendChild(t),t=n):s=="li"?n=t:s&&(n=null)}}function ax(e,t){return(e.matches||e.msMatchesSelector||e.webkitMatchesSelector||e.mozMatchesSelector).call(e,t)}function ox(e){let t=/\s*([\w-]+)\s*:\s*([^;]+)/g,n,s=[];for(;n=t.exec(e);)s.push(n[1],n[2].trim());return s}function qc(e){let t={};for(let n in e)t[n]=e[n];return t}function lx(e,t){let n=t.schema.nodes;for(let s in n){let i=n[s];if(!i.allowsMarkType(e))continue;let a=[],l=c=>{a.push(c);for(let u=0;u<c.edgeCount;u++){let{type:d,next:h}=c.edge(u);if(d==t||a.indexOf(h)<0&&l(h))return!0}};if(l(i.contentMatch))return!0}}function cx(e,t){for(let n=0;n<t.length;n++)if(e.eq(t[n]))return t[n]}const Nc=65535,$c=Math.pow(2,16);function ux(e,t){return e+t*$c}function Fc(e){return e&Nc}function dx(e){return(e-(e&Nc))/$c}const Gc=1,Wc=2,ms=4,Rc=8;class Qc{constructor(t,n,s){this.pos=t,this.delInfo=n,this.recover=s}get deleted(){return(this.delInfo&Rc)>0}get deletedBefore(){return(this.delInfo&(Gc|ms))>0}get deletedAfter(){return(this.delInfo&(Wc|ms))>0}get deletedAcross(){return(this.delInfo&ms)>0}}class Ct{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&Ct.empty)return Ct.empty}recover(t){let n=0,s=Fc(t);if(!this.inverted)for(let i=0;i<s;i++)n+=this.ranges[i*3+2]-this.ranges[i*3+1];return this.ranges[s*3]+n+dx(t)}mapResult(t,n=1){return this._map(t,n,!1)}map(t,n=1){return this._map(t,n,!0)}_map(t,n,s){let i=0,a=this.inverted?2:1,l=this.inverted?1:2;for(let c=0;c<this.ranges.length;c+=3){let u=this.ranges[c]-(this.inverted?i:0);if(u>t)break;let d=this.ranges[c+a],h=this.ranges[c+l],p=u+d;if(t<=p){let f=d?t==u?-1:t==p?1:n:n,m=u+i+(f<0?0:h);if(s)return m;let y=t==(n<0?u:p)?null:ux(c/3,t-u),_=t==u?Wc:t==p?Gc:ms;return(n<0?t!=u:t!=p)&&(_|=Rc),new Qc(m,_,y)}i+=h-d}return s?t+i:new Qc(t+i,0,null)}touches(t,n){let s=0,i=Fc(n),a=this.inverted?2:1,l=this.inverted?1:2;for(let c=0;c<this.ranges.length;c+=3){let u=this.ranges[c]-(this.inverted?s:0);if(u>t)break;let d=this.ranges[c+a],h=u+d;if(t<=h&&c==i*3)return!0;s+=this.ranges[c+l]-d}return!1}forEach(t){let n=this.inverted?2:1,s=this.inverted?1:2;for(let i=0,a=0;i<this.ranges.length;i+=3){let l=this.ranges[i],c=l-(this.inverted?a:0),u=l+(this.inverted?0:a),d=this.ranges[i+n],h=this.ranges[i+s];t(c,c+d,u,u+h),a+=h-d}}invert(){return new Ct(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(t){return t==0?Ct.empty:new Ct(t<0?[0,-t,0]:[0,0,t])}}Ct.empty=new Ct([]);const Oi=Object.create(null);class it{getMap(){return Ct.empty}merge(t){return null}static fromJSON(t,n){if(!n||!n.stepType)throw new RangeError("Invalid input for Step.fromJSON");let s=Oi[n.stepType];if(!s)throw new RangeError(`No step type ${n.stepType} defined`);return s.fromJSON(t,n)}static jsonID(t,n){if(t in Oi)throw new RangeError("Duplicate use of step JSON ID "+t);return Oi[t]=n,n.prototype.jsonID=t,n}}class Ve{constructor(t,n){this.doc=t,this.failed=n}static ok(t){return new Ve(t,null)}static fail(t){return new Ve(null,t)}static fromReplace(t,n,s,i){try{return Ve.ok(t.replace(n,s,i))}catch(a){if(a instanceof nx)return Ve.fail(a.message);throw a}}}function Li(e,t,n){let s=[];for(let i=0;i<e.childCount;i++){let a=e.child(i);a.content.size&&(a=a.copy(Li(a.content,t,a))),a.isInline&&(a=t(a,n,i)),s.push(a)}return pe.fromArray(s)}class Pn extends it{constructor(t,n,s){super(),this.from=t,this.to=n,this.mark=s}apply(t){let n=t.slice(this.from,this.to),s=t.resolve(this.from),i=s.node(s.sharedDepth(this.to)),a=new ve(Li(n.content,(l,c)=>!l.isAtom||!c.type.allowsMarkType(this.mark.type)?l:l.mark(this.mark.addToSet(l.marks)),i),n.openStart,n.openEnd);return Ve.fromReplace(t,this.from,this.to,a)}invert(){return new On(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),s=t.mapResult(this.to,-1);return n.deleted&&s.deleted||n.pos>=s.pos?null:new Pn(n.pos,s.pos,this.mark)}merge(t){return t instanceof Pn&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new Pn(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Pn(n.from,n.to,t.markFromJSON(n.mark))}}it.jsonID("addMark",Pn);class On extends it{constructor(t,n,s){super(),this.from=t,this.to=n,this.mark=s}apply(t){let n=t.slice(this.from,this.to),s=new ve(Li(n.content,i=>i.mark(this.mark.removeFromSet(i.marks)),t),n.openStart,n.openEnd);return Ve.fromReplace(t,this.from,this.to,s)}invert(){return new Pn(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),s=t.mapResult(this.to,-1);return n.deleted&&s.deleted||n.pos>=s.pos?null:new On(n.pos,s.pos,this.mark)}merge(t){return t instanceof On&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new On(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new On(n.from,n.to,t.markFromJSON(n.mark))}}it.jsonID("removeMark",On);class Ln extends it{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return Ve.fail("No node at mark step's position");let s=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return Ve.fromReplace(t,this.pos,this.pos+1,new ve(pe.from(s),0,n.isLeaf?0:1))}invert(t){let n=t.nodeAt(this.pos);if(n){let s=this.mark.addToSet(n.marks);if(s.length==n.marks.length){for(let i=0;i<n.marks.length;i++)if(!n.marks[i].isInSet(s))return new Ln(this.pos,n.marks[i]);return new Ln(this.pos,this.mark)}}return new jr(this.pos,this.mark)}map(t){let n=t.mapResult(this.pos,1);return n.deletedAfter?null:new Ln(n.pos,this.mark)}toJSON(){return{stepType:"addNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(t,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");return new Ln(n.pos,t.markFromJSON(n.mark))}}it.jsonID("addNodeMark",Ln);class jr extends it{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return Ve.fail("No node at mark step's position");let s=n.type.create(n.attrs,null,this.mark.removeFromSet(n.marks));return Ve.fromReplace(t,this.pos,this.pos+1,new ve(pe.from(s),0,n.isLeaf?0:1))}invert(t){let n=t.nodeAt(this.pos);return!n||!this.mark.isInSet(n.marks)?this:new Ln(this.pos,this.mark)}map(t){let n=t.mapResult(this.pos,1);return n.deletedAfter?null:new jr(n.pos,this.mark)}toJSON(){return{stepType:"removeNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(t,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");return new jr(n.pos,t.markFromJSON(n.mark))}}it.jsonID("removeNodeMark",jr);class Jt extends it{constructor(t,n,s,i=!1){super(),this.from=t,this.to=n,this.slice=s,this.structure=i}apply(t){return this.structure&&Vi(t,this.from,this.to)?Ve.fail("Structure replace would overwrite content"):Ve.fromReplace(t,this.from,this.to,this.slice)}getMap(){return new Ct([this.from,this.to-this.from,this.slice.size])}invert(t){return new Jt(this.from,this.from+this.slice.size,t.slice(this.from,this.to))}map(t){let n=t.mapResult(this.from,1),s=t.mapResult(this.to,-1);return n.deletedAcross&&s.deletedAcross?null:new Jt(n.pos,Math.max(n.pos,s.pos),this.slice)}merge(t){if(!(t instanceof Jt)||t.structure||this.structure)return null;if(this.from+this.slice.size==t.from&&!this.slice.openEnd&&!t.slice.openStart){let n=this.slice.size+t.slice.size==0?ve.empty:new ve(this.slice.content.append(t.slice.content),this.slice.openStart,t.slice.openEnd);return new Jt(this.from,this.to+(t.to-t.from),n,this.structure)}else if(t.to==this.from&&!this.slice.openStart&&!t.slice.openEnd){let n=this.slice.size+t.slice.size==0?ve.empty:new ve(t.slice.content.append(this.slice.content),t.slice.openStart,this.slice.openEnd);return new Jt(t.from,this.to,n,this.structure)}else return null}toJSON(){let t={stepType:"replace",from:this.from,to:this.to};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for ReplaceStep.fromJSON");return new Jt(n.from,n.to,ve.fromJSON(t,n.slice),!!n.structure)}}it.jsonID("replace",Jt);class Vn extends it{constructor(t,n,s,i,a,l,c=!1){super(),this.from=t,this.to=n,this.gapFrom=s,this.gapTo=i,this.slice=a,this.insert=l,this.structure=c}apply(t){if(this.structure&&(Vi(t,this.from,this.gapFrom)||Vi(t,this.gapTo,this.to)))return Ve.fail("Structure gap-replace would overwrite content");let n=t.slice(this.gapFrom,this.gapTo);if(n.openStart||n.openEnd)return Ve.fail("Gap is not a flat range");let s=this.slice.insertAt(this.insert,n.content);return s?Ve.fromReplace(t,this.from,this.to,s):Ve.fail("Content does not fit in gap")}getMap(){return new Ct([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(t){let n=this.gapTo-this.gapFrom;return new Vn(this.from,this.from+this.slice.size+n,this.from+this.insert,this.from+this.insert+n,t.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(t){let n=t.mapResult(this.from,1),s=t.mapResult(this.to,-1),i=t.map(this.gapFrom,-1),a=t.map(this.gapTo,1);return n.deletedAcross&&s.deletedAcross||i<n.pos||a>s.pos?null:new Vn(n.pos,s.pos,i,a,this.slice,this.insert,this.structure)}toJSON(){let t={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number"||typeof n.gapFrom!="number"||typeof n.gapTo!="number"||typeof n.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new Vn(n.from,n.to,n.gapFrom,n.gapTo,ve.fromJSON(t,n.slice),n.insert,!!n.structure)}}it.jsonID("replaceAround",Vn);function Vi(e,t,n){let s=e.resolve(t),i=n-t,a=s.depth;for(;i>0&&a>0&&s.indexAfter(a)==s.node(a).childCount;)a--,i--;if(i>0){let l=s.node(a).maybeChild(s.indexAfter(a));for(;i>0;){if(!l||l.isLeaf)return!0;l=l.firstChild,i--}}return!1}function px(e,t,n){return(t==0||e.canReplace(t,e.childCount))&&(n==e.childCount||e.canReplace(0,n))}function hx(e){let n=e.parent.content.cutByIndex(e.startIndex,e.endIndex);for(let s=e.depth;;--s){let i=e.$from.node(s),a=e.$from.index(s),l=e.$to.indexAfter(s);if(s<e.depth&&i.canReplace(a,l,n))return s;if(s==0||i.type.spec.isolating||!px(i,a,l))break}return null}function xs(e,t,n=1,s){let i=e.resolve(t),a=i.depth-n,l=s&&s[s.length-1]||i.parent;if(a<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!l.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let d=i.depth-1,h=n-2;d>a;d--,h--){let p=i.node(d),f=i.index(d);if(p.type.spec.isolating)return!1;let m=p.content.cutByIndex(f,p.childCount),y=s&&s[h+1];y&&(m=m.replaceChild(0,y.type.create(y.attrs)));let _=s&&s[h]||p;if(!p.canReplace(f+1,p.childCount)||!_.type.validContent(m))return!1}let c=i.indexAfter(a),u=s&&s[0];return i.node(a).canReplaceWith(c,c,u?u.type:i.node(a+1).type)}function Uc(e,t){let n=e.resolve(t),s=n.index();return fx(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(s,s+1)}function fx(e,t){return!!(e&&t&&!e.isLeaf&&e.canAppend(t))}class wr extends it{constructor(t,n,s){super(),this.pos=t,this.attr=n,this.value=s}apply(t){let n=t.nodeAt(this.pos);if(!n)return Ve.fail("No node at attribute step's position");let s=Object.create(null);for(let a in n.attrs)s[a]=n.attrs[a];s[this.attr]=this.value;let i=n.type.create(s,null,n.marks);return Ve.fromReplace(t,this.pos,this.pos+1,new ve(pe.from(i),0,n.isLeaf?0:1))}getMap(){return Ct.empty}invert(t){return new wr(this.pos,this.attr,t.nodeAt(this.pos).attrs[this.attr])}map(t){let n=t.mapResult(this.pos,1);return n.deletedAfter?null:new wr(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(t,n){if(typeof n.pos!="number"||typeof n.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new wr(n.pos,n.attr,n.value)}}it.jsonID("attr",wr);let Cr=class extends Error{};Cr=function e(t){let n=Error.call(this,t);return n.__proto__=e.prototype,n},Cr.prototype=Object.create(Error.prototype),Cr.prototype.constructor=Cr,Cr.prototype.name="TransformError";const Bi=Object.create(null);class De{constructor(t,n,s){this.$anchor=t,this.$head=n,this.ranges=s||[new gx(t.min(n),t.max(n))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let t=this.ranges;for(let n=0;n<t.length;n++)if(t[n].$from.pos!=t[n].$to.pos)return!1;return!0}content(){return this.$from.doc.slice(this.from,this.to,!0)}replace(t,n=ve.empty){let s=n.content.lastChild,i=null;for(let c=0;c<n.openEnd;c++)i=s,s=s.lastChild;let a=t.steps.length,l=this.ranges;for(let c=0;c<l.length;c++){let{$from:u,$to:d}=l[c],h=t.mapping.slice(a);t.replaceRange(h.map(u.pos),h.map(d.pos),c?ve.empty:n),c==0&&Xc(t,a,(s?s.isInline:i&&i.isTextblock)?-1:1)}}replaceWith(t,n){let s=t.steps.length,i=this.ranges;for(let a=0;a<i.length;a++){let{$from:l,$to:c}=i[a],u=t.mapping.slice(s),d=u.map(l.pos),h=u.map(c.pos);a?t.deleteRange(d,h):(t.replaceRangeWith(d,h,n),Xc(t,s,n.isInline?-1:1))}}static findFrom(t,n,s=!1){let i=t.parent.inlineContent?new Be(t):Yn(t.node(0),t.parent,t.pos,t.index(),n,s);if(i)return i;for(let a=t.depth-1;a>=0;a--){let l=n<0?Yn(t.node(0),t.node(a),t.before(a+1),t.index(a),n,s):Yn(t.node(0),t.node(a),t.after(a+1),t.index(a)+1,n,s);if(l)return l}return null}static near(t,n=1){return this.findFrom(t,n)||this.findFrom(t,-n)||new ln(t.node(0))}static atStart(t){return Yn(t,t,0,0,1)||new ln(t)}static atEnd(t){return Yn(t,t,t.content.size,t.childCount,-1)||new ln(t)}static fromJSON(t,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let s=Bi[n.type];if(!s)throw new RangeError(`No selection type ${n.type} defined`);return s.fromJSON(t,n)}static jsonID(t,n){if(t in Bi)throw new RangeError("Duplicate use of selection JSON ID "+t);return Bi[t]=n,n.prototype.jsonID=t,n}getBookmark(){return Be.between(this.$anchor,this.$head).getBookmark()}}De.prototype.visible=!0;class gx{constructor(t,n){this.$from=t,this.$to=n}}let Yc=!1;function Kc(e){!Yc&&!e.parent.inlineContent&&(Yc=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+e.parent.type.name+")"))}class Be extends De{constructor(t,n=t){Kc(t),Kc(n),super(t,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(t,n){let s=t.resolve(n.map(this.head));if(!s.parent.inlineContent)return De.near(s);let i=t.resolve(n.map(this.anchor));return new Be(i.parent.inlineContent?i:s,s)}replace(t,n=ve.empty){if(super.replace(t,n),n==ve.empty){let s=this.$from.marksAcross(this.$to);s&&t.ensureMarks(s)}}eq(t){return t instanceof Be&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new ys(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(t,n){if(typeof n.anchor!="number"||typeof n.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new Be(t.resolve(n.anchor),t.resolve(n.head))}static create(t,n,s=n){let i=t.resolve(n);return new this(i,s==n?i:t.resolve(s))}static between(t,n,s){let i=t.pos-n.pos;if((!s||i)&&(s=i>=0?1:-1),!n.parent.inlineContent){let a=De.findFrom(n,s,!0)||De.findFrom(n,-s,!0);if(a)n=a.$head;else return De.near(n,s)}return t.parent.inlineContent||(i==0?t=n:(t=(De.findFrom(t,-s,!0)||De.findFrom(t,s,!0)).$anchor,t.pos<n.pos!=i<0&&(t=n))),new Be(t,n)}}De.jsonID("text",Be);class ys{constructor(t,n){this.anchor=t,this.head=n}map(t){return new ys(t.map(this.anchor),t.map(this.head))}resolve(t){return Be.between(t.resolve(this.anchor),t.resolve(this.head))}}class mt extends De{constructor(t){let n=t.nodeAfter,s=t.node(0).resolve(t.pos+n.nodeSize);super(t,s),this.node=n}map(t,n){let{deleted:s,pos:i}=n.mapResult(this.anchor),a=t.resolve(i);return s?De.near(a):new mt(a)}content(){return new ve(pe.from(this.node),0,0)}eq(t){return t instanceof mt&&t.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new qi(this.anchor)}static fromJSON(t,n){if(typeof n.anchor!="number")throw new RangeError("Invalid input for NodeSelection.fromJSON");return new mt(t.resolve(n.anchor))}static create(t,n){return new mt(t.resolve(n))}static isSelectable(t){return!t.isText&&t.type.spec.selectable!==!1}}mt.prototype.visible=!1,De.jsonID("node",mt);class qi{constructor(t){this.anchor=t}map(t){let{deleted:n,pos:s}=t.mapResult(this.anchor);return n?new ys(s,s):new qi(s)}resolve(t){let n=t.resolve(this.anchor),s=n.nodeAfter;return s&&mt.isSelectable(s)?new mt(n):De.near(n)}}class ln extends De{constructor(t){super(t.resolve(0),t.resolve(t.content.size))}replace(t,n=ve.empty){if(n==ve.empty){t.delete(0,t.doc.content.size);let s=De.atStart(t.doc);s.eq(t.selection)||t.setSelection(s)}else super.replace(t,n)}toJSON(){return{type:"all"}}static fromJSON(t){return new ln(t)}map(t){return new ln(t)}eq(t){return t instanceof ln}getBookmark(){return mx}}De.jsonID("all",ln);const mx={map(){return this},resolve(e){return new ln(e)}};function Yn(e,t,n,s,i,a=!1){if(t.inlineContent)return Be.create(e,n);for(let l=s-(i>0?0:1);i>0?l<t.childCount:l>=0;l+=i){let c=t.child(l);if(c.isAtom){if(!a&&mt.isSelectable(c))return mt.create(e,n-(i<0?c.nodeSize:0))}else{let u=Yn(e,c,n+i,i<0?c.childCount:0,i,a);if(u)return u}n+=c.nodeSize*i}return null}function Xc(e,t,n){let s=e.steps.length-1;if(s<t)return;let i=e.steps[s];if(!(i instanceof Jt||i instanceof Vn))return;let a=e.mapping.maps[s],l;a.forEach((c,u,d,h)=>{l==null&&(l=h)}),e.setSelection(De.near(e.doc.resolve(l),n))}function Jc(e,t){return!t||!e?e:e.bind(t)}class bs{constructor(t,n,s){this.name=t,this.init=Jc(n.init,s),this.apply=Jc(n.apply,s)}}new bs("doc",{init(e){return e.doc||e.schema.topNodeType.createAndFill()},apply(e){return e.doc}}),new bs("selection",{init(e,t){return e.selection||De.atStart(t.doc)},apply(e){return e.selection}}),new bs("storedMarks",{init(e){return e.storedMarks||null},apply(e,t,n,s){return s.selection.$cursor?e.storedMarks:null}}),new bs("scrollToSelection",{init(){return 0},apply(e,t){return e.scrolledIntoView?t+1:t}});function Zc(e,t,n){for(let s in e){let i=e[s];i instanceof Function?i=i.bind(t):s=="handleDOMEvents"&&(i=Zc(i,t,{})),n[s]=i}return n}let Sr=class{constructor(t){this.spec=t,this.props={},t.props&&Zc(t.props,this,this.props),this.key=t.key?t.key.key:Hc("plugin")}getState(t){return t[this.key]}};const Ni=Object.create(null);function Hc(e){return e in Ni?e+"$"+ ++Ni[e]:(Ni[e]=0,e+"$")}class kr{constructor(t="key"){this.key=Hc(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}function eu(e){const{state:t,transaction:n}=e;let{selection:s}=n,{doc:i}=n,{storedMarks:a}=n;return{...t,apply:t.apply.bind(t),applyTransaction:t.applyTransaction.bind(t),filterTransaction:t.filterTransaction,plugins:t.plugins,schema:t.schema,reconfigure:t.reconfigure.bind(t),toJSON:t.toJSON.bind(t),get storedMarks(){return a},get selection(){return s},get doc(){return i},get tr(){return s=n.selection,i=n.doc,a=n.storedMarks,n}}}class xx{constructor(t){this.editor=t.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=t.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:t,editor:n,state:s}=this,{view:i}=n,{tr:a}=s,l=this.buildProps(a);return Object.fromEntries(Object.entries(t).map(([c,u])=>[c,(...h)=>{const p=u(...h)(l);return!a.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(a),p}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,n=!0){const{rawCommands:s,editor:i,state:a}=this,{view:l}=i,c=[],u=!!t,d=t||a.tr,h=()=>(!u&&n&&!d.getMeta("preventDispatch")&&!this.hasCustomState&&l.dispatch(d),c.every(f=>f===!0)),p={...Object.fromEntries(Object.entries(s).map(([f,m])=>[f,(..._)=>{const k=this.buildProps(d,n),S=m(..._)(k);return c.push(S),p}])),run:h};return p}createCan(t){const{rawCommands:n,state:s}=this,i=!1,a=t||s.tr,l=this.buildProps(a,i);return{...Object.fromEntries(Object.entries(n).map(([u,d])=>[u,(...h)=>d(...h)({...l,dispatch:void 0})])),chain:()=>this.createChain(a,i)}}buildProps(t,n=!0){const{rawCommands:s,editor:i,state:a}=this,{view:l}=i;a.storedMarks&&t.setStoredMarks(a.storedMarks);const c={tr:t,editor:i,view:l,state:eu({state:a,transaction:t}),dispatch:n?()=>{}:void 0,chain:()=>this.createChain(t),can:()=>this.createCan(t),get commands(){return Object.fromEntries(Object.entries(s).map(([u,d])=>[u,(...h)=>d(...h)(c)]))}};return c}}function xt(e,t,n){return e.config[t]===void 0&&e.parent?xt(e.parent,t,n):typeof e.config[t]=="function"?e.config[t].bind({...n,parent:e.parent?xt(e.parent,t,n):null}):e.config[t]}function yx(e){const t=e.filter(i=>i.type==="extension"),n=e.filter(i=>i.type==="node"),s=e.filter(i=>i.type==="mark");return{baseExtensions:t,nodeExtensions:n,markExtensions:s}}function Xe(e,t){if(typeof e=="string"){if(!t.nodes[e])throw Error(`There is no node type named '${e}'. Maybe you forgot to add the extension?`);return t.nodes[e]}return e}function bx(e){return typeof e=="function"}function Ot(e,t=void 0,...n){return bx(e)?t?e.bind(t)(...n):e(...n):e}function vx(e){return Object.prototype.toString.call(e)==="[object RegExp]"}function _x(e){return Object.prototype.toString.call(e).slice(8,-1)}function $i(e){return _x(e)!=="Object"?!1:e.constructor===Object&&Object.getPrototypeOf(e)===Object.prototype}function Fi(e,t){const n={...e};return $i(e)&&$i(t)&&Object.keys(t).forEach(s=>{$i(t[s])?s in e?n[s]=Fi(e[s],t[s]):Object.assign(n,{[s]:t[s]}):Object.assign(n,{[s]:t[s]})}),n}class Zt{constructor(t={}){this.type="extension",this.name="extension",this.parent=null,this.child=null,this.config={name:this.name,defaultOptions:{}},this.config={...this.config,...t},this.name=this.config.name,t.defaultOptions&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${this.name}".`),this.options=this.config.defaultOptions,this.config.addOptions&&(this.options=Ot(xt(this,"addOptions",{name:this.name}))),this.storage=Ot(xt(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new Zt(t)}configure(t={}){const n=this.extend();return n.options=Fi(this.options,t),n.storage=Ot(xt(n,"addStorage",{name:n.name,options:n.options})),n}extend(t={}){const n=new Zt(t);return n.parent=this,this.child=n,n.name=t.name?t.name:n.parent.name,t.defaultOptions&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${n.name}".`),n.options=Ot(xt(n,"addOptions",{name:n.name})),n.storage=Ot(xt(n,"addStorage",{name:n.name,options:n.options})),n}}function jx(e,t,n){const{from:s,to:i}=t,{blockSeparator:a=`
@@ -89,7 +89,7 @@ Check the top-level render call using <`+q+">.")}return A}}function $g(C,A){{if(
89
89
  ${Object.entries(t).map(([s,i])=>`const ${s} = '${i}';`).join(`
90
90
  `)}
91
91
  return ${e};
92
- `)(n)}catch(s){return console.error(s),console.log(e),e}}function Np(e,t,n,s){const i=w_(t,s);return e.replaceAll(/(\{\{([^{\}]+(?=}))\}\})/g,(...l)=>{const c=l[2];if(!c)return c;const u=i[c];if(u)return u;const d=C_(c);return S_(d,i,n)})}function k_(e,t){const n=xc.decode(t);n!==e&&(console.error("Inconsistent sql"),console.groupCollapsed("Inconsistent sql"),console.table({before:e,after:t,v:n}),console.groupEnd())}async function T_({query:e,name:t,payload:n,additionals:s},i){if(!e.sql)return[];const{type:a,key:l,sql:c,pre_process:u,post_process:d}=e,h=Di(c,n),p=Wm({sql:h,pre_process:u}),f=xc.encode(p);k_(p,f);let m=await Kt.query(i)({type:a,key:l,query:f,...s},{params:{name:t}});return m=Rm(d,m,po(n)),m}async function D_({type:e,key:t,configString:n,name:s,additionals:i},a){try{return await Kt.httpDataSourceQuery(a)({type:e,key:t,query:n,...i},{params:{name:s}})}catch(l){if(Rt.isCancel(l))throw l;return console.error(l),l}}async function ho(){try{return(await Kt.post()("/datasource/list",{filter:{},sort:[{field:"create_time",order:"ASC"}],pagination:{page:1,pagesize:100}},{})).data}catch(e){return console.error(e),[]}}async function $p(){try{return(await Kt.post()("/sql_snippet/list",{filter:{},sort:[{field:"id",order:"ASC"}],pagination:{page:1,pagesize:1e3}},{})).data}catch(e){return console.error(e),[]}}class Fp{constructor(t){N(this,"rootRef");this.rootRef=ae.observable({current:t})}async deleteItem(t){ae.runInAction(()=>{v.unset(this.rootRef.current,[t])})}getItem(t){const n=this.getValueFromRoot(t);return Promise.resolve(n)}getValueFromRoot(t){return t===null?ae.toJS(this.rootRef.current):v.get(this.rootRef.current,[t])}setItem(t,n){if(t===null)if(v.isObject(n))ae.runInAction(()=>{this.rootRef.current=n});else throw new Error("Cannot set root value to non-object");else ae.runInAction(()=>{v.set(this.rootRef.current,[t],n)});return Promise.resolve(this.getItem(t))}watchItem(t,n,s){return ae.reaction(()=>this.getValueFromRoot(t),(i,a)=>{n(i,a)},{requiresObservable:!0,fireImmediately:v.get(s,"fireImmediately",!1)})}}class M_{constructor(){N(this,"channels",new Map);N(this,"globalChannel",new yc)}getChannel(t){const n=this.channels.get(t);if(n)return n;const s=new yc;return this.channels.set(t,s),s}}class I_{constructor(t){N(this,"instances",new Map);this.pluginManager=t}get availableVizList(){return this.pluginManager.installedPlugins.flatMap(t=>t.manifest.viz)}resolveComponent(t){return this.pluginManager.factory.viz(t)}getOrCreateInstance(t){const n=this.instances.get(t.id);if(n)return n;const s={id:t.id,name:t.viz.type,type:t.viz.type,messageChannels:new M_,instanceData:new Fp(t.viz.conf)};return this.instances.set(t.id,s),s}}function Gp(e,t,n,s){return{vizManager:n,locale:"zh",msgChannels:e.messageChannels,instanceData:e.instanceData,pluginData:new Fp({}),colorPalette:{getColor(){return()=>""}},data:t,variables:s}}const z_=e=>{const{panel:t,measure:n,vizManager:s,data:i,variables:a}=e,l=s.resolveComponent(t.viz.type),c=s.getOrCreateInstance(t),u={...Gp(c,i,s,a),viewport:{width:n.w,height:n.h}},d=l.viewRender;return r.jsx(d,{context:u,instance:c,...v.omit(e,["panel","vizManager","data"])})},E_=e=>{const{vizManager:t,panel:n,data:s,variables:i}=e,a=t.resolveComponent(n.viz.type),l=t.getOrCreateInstance(n),c={...Gp(l,s,t,i)},u=a.configRender;return r.jsx(u,{context:c,instance:l,...v.omit(e,["panel","vizManager","data"])})},Wp=(e,t)=>{const n=Ut.bezier(e),s=Ut.bezier(t);return function(i){return i<50?n(i*2/100).hex():s((i-50)*2/100).hex()}},Js=e=>{const t=Ut.bezier(e);return function(n){return t(n/100).hex()}},A_={type:"interpolation",displayName:"style.color.interpolation.palette.red_green",getColor:Wp(["darkred","deeppink","lightyellow"],["lightyellow","lightgreen","teal"]),name:"red-green",category:"diverging"},P_={type:"interpolation",displayName:"style.color.interpolation.palette.yellow_blue",getColor:Wp(["#8f531d","#ffd347","#e3efe3"],["#eefaee","#4ecbbf","#003f94"]),name:"yellow-blue",category:"diverging"},O_={type:"interpolation",displayName:"style.color.interpolation.palette.red",getColor:Js(["#fff7f1","darkred"]),name:"red",category:"sequential"},L_={type:"interpolation",displayName:"style.color.interpolation.palette.green",getColor:Js(["#f0ffed","darkgreen"]),name:"green",category:"sequential"},V_={type:"interpolation",displayName:"style.color.interpolation.palette.blue",getColor:Js(["#f9fcff","#48b3e9","darkblue"]),name:"blue",category:"sequential"},B_={type:"interpolation",displayName:"style.color.interpolation.palette.orange",getColor:Js(["#fff7f1","darkorange","#b60000"]),name:"orange",category:"sequential"};class q_{constructor(t){N(this,"symbol");this.symbol=Symbol(t)}}function hn(e){return new q_(e)}class fo{constructor(){N(this,"parent");N(this,"factoryRegistry",new Map);N(this,"instanceRegistry",new Map)}createScoped(){const t=new fo;return t.parent=this,t}getRequired(t){return this.get(t)}get(t){if(this.instanceRegistry.has(t.symbol))return this.instanceRegistry.get(t.symbol);const n=this.factoryRegistry.get(t.symbol);if(n){const s=n(this);return this.instanceRegistry.set(t.symbol,s),s}if(this.parent)return this.parent.get(t)}provideFactory(t,n){return this.factoryRegistry.has(t.symbol)?console.warn(`Token ${t.symbol.toString()} is already registered`):this.factoryRegistry.set(t.symbol,n),this}provideValue(t,n){return this.factoryRegistry.has(t.symbol)?console.warn(`Token ${t.symbol.toString()} is already registered`):this.factoryRegistry.set(t.symbol,()=>n),this}dispose(){this.instanceRegistry.forEach(t=>{const n=v.get(t,"dispose");v.isFunction(n)&&n.bind(t)()}),this.instanceRegistry.clear(),this.factoryRegistry.clear()}}const Rp="13.28.1",N_=Object.freeze(Object.defineProperty({__proto__:null,version:Rp},Symbol.toStringTag,{value:"Module"}));class $_{constructor(t){N(this,"staticColors",new Map);N(this,"interpolations",new Map);t.installedPlugins.forEach(n=>{n.manifest.color.forEach(s=>{this.register(s)})})}getStaticColors(){return Array.from(this.staticColors.values())}register(t){const n=this.encodeColor(t);t.type==="single"?(this.staticColors.has(n)&&console.warn(`the color '${t.name}' has been registered under '${t.category}', previous registered value will be overridden`),this.staticColors.set(n,t)):t.type==="interpolation"&&(this.interpolations.has(n)&&console.warn(`the interpolation '${t.name}' has been registered under '${t.category}', previous registered value will be overridden`,`the interpolation '${t.name}' has been registered under '${t.category}', previous registered value will be overridden`),this.interpolations.set(n,t))}decodeStaticColor(t){return this.staticColors.get(t)}encodeColor(t){return`\${${t.category}}.{${t.name}}`}decodeInterpolation(t){return this.interpolations.get(t)}getColorInterpolations(){return Array.from(this.interpolations.values())}}class F_{constructor(){N(this,"plugins",new Map);N(this,"vizComponents",new Map);N(this,"factory",{viz:t=>{const n=this.vizComponents.get(t);if(n)return n;throw new Error(`Viz Component (${t}) not found`)}})}install(t){if(this.plugins.has(t.id))throw new Error(`Plugin (${t.id}) has been installed before`);this.plugins.set(t.id,t);for(const n of t.manifest.viz){if(this.vizComponents.has(n.name))throw new Error(`Viz Component (${n.name}) has been installed before`);this.vizComponents.set(n.name,n)}}get installedPlugins(){return Array.from(this.plugins.values())}}class G_{constructor(){N(this,"migrations",[])}version(t,n){return this.migrations.push({version:t,handler:n}),this}run(t,n,s){var l;if(t.from===t.to)return n;if(t.from>t.to)throw new Error(`Can not downgrade from version '${t.from}' to (${t.to})`);const i=this.migrations.filter(c=>c.version>t.from&&c.version<=t.to),a=v.orderBy(i,"version","asc");if(((l=v.last(a))==null?void 0:l.version)!==t.to)throw new Error(`Migration to version ${t.to} not found`);return a.reduce((c,u)=>u.handler(c,s),n)}}class Me extends G_{constructor(){super(),this.configVersions()}version(t,n){return super.version(t,(s,i)=>({version:t,...n(s,i)}))}async migrate({configData:t,panelModel:n}){const s=await t.getItem(null),i=v.get(s,"version",0),a=this.run({from:i,to:this.VERSION},s,{panelModel:n});await t.setItem(null,a)}async needMigration({configData:t}){const n=await t.getItem(null);return v.get(n,"version",0)<this.VERSION}}const Q=(e,t)=>{const[n,{setFalse:s}]=J.useBoolean(!0),[i,a]=g.useState();g.useEffect(()=>(e.getItem(t).then(c=>{a(c),s()}),e.watchItem(t,c=>{a(c)})));const l=g.useCallback(async c=>{await e.setItem(t,c),a(c)},[e,t]);return{loading:n,value:i,set:l}},ut={top:16,right:16,bottom:16,left:16},Bt=e=>Math.max(0,e-ut.left-ut.right),qt=e=>Math.max(0,e-ut.top-ut.bottom),Jr=(e,t)=>({width:Bt(e),height:qt(t)}),dt=({width:e,height:t,children:n})=>r.jsx(o.Box,{pt:ut.top,pr:ut.right,pb:ut.bottom,pl:ut.left,sx:{width:e,height:t,overflow:"hidden",position:"relative"},children:n}),go={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 W_({context:e}){const{value:t}=Q(e.instanceData,"config"),n=e.data,{width:s,height:i}=e.viewport,{x_axis_data_key:a,y_axis_data_key:l,z_axis_data_key:c,xAxis3D:u,yAxis3D:d,zAxis3D:h}=v.defaults({},t,go),p=g.useMemo(()=>cs(n,a),[n,a]),{x:f,y:m,z:y}=g.useMemo(()=>({x:L(a),y:L(l),z:L(c)}),[a,l,c]),{min:_,max:k}=g.useMemo(()=>{const T=v.minBy(p,z=>z[y.columnKey]),I=v.maxBy(p,z=>z[y.columnKey]);return{min:v.get(T,y.columnKey),max:v.get(I,y.columnKey)}},[p,y]),S={tooltip:{},backgroundColor:"#fff",visualMap:{show:!0,dimension:2,min:_,max:k,inRange:{color:["#313695","#4575b4","#74add1","#abd9e9","#e0f3f8","#ffffbf","#fee090","#fdae61","#f46d43","#d73027","#a50026"]}},xAxis3D:u,yAxis3D:d,zAxis3D:h,grid3D:{viewControl:{projection:"orthographic",autoRotate:!1},light:{main:{shadow:!0,quality:"ultra",intensity:1.5}}},series:[{type:"bar3D",wireframe:{},data:p.map(T=>[T[f.columnKey],T[m.columnKey],T[y.columnKey]])}]};return t?r.jsx(dt,{width:s,height:i,children:r.jsx(Ke,{echarts:Ye,option:S,style:Jr(s,i),notMerge:!0,theme:"merico-light"})}):null}const U=D.observer(g.forwardRef(({label:e,required:t,description:n,value:s,onChange:i,queryID:a,clearable:l=!1,sx:c,...u},d)=>{const{panel:h}=Je(),p=g.useMemo(()=>h.dataFieldOptions(s,l,a),[s,l,a]);if(p.length===0){const f=h.explainDataKey(s);return r.jsxs(o.HoverCard,{shadow:"md",position:"bottom-start",withinPortal:!0,zIndex:320,children:[r.jsx(o.HoverCard.Target,{children:r.jsx(o.Box,{children:r.jsx(o.TextInput,{label:e,required:t,defaultValue:f.columnKey,readOnly:!0,disabled:!0})})}),r.jsx(o.HoverCard.Dropdown,{children:r.jsxs(o.Group,{position:"left",spacing:0,children:[r.jsx(o.Text,{size:"xs",color:f.queryName?"black":"red",sx:{fontFamily:"monospace"},children:f.queryName??f.queryID}),r.jsx(o.Text,{size:"xs",color:"black",sx:{fontFamily:"monospace"},children:"."}),r.jsx(o.Text,{size:"xs",color:"red",sx:{fontFamily:"monospace"},children:f.columnKey})]})})]})}return r.jsx(o.Select,{ref:d,label:e,description:n,data:p,value:s,onChange:i,required:t,sx:c,maxDropdownHeight:500,...u})}));function R_({context:e}){const{value:t,set:n}=Q(e.instanceData,"config"),s=v.defaults({},t,go),{control:i,handleSubmit:a,reset:l}=b.useForm({defaultValues:s});return g.useEffect(()=>{l(s)},[t]),t?r.jsx(o.Stack,{spacing:"xs",children:r.jsxs("form",{onSubmit:a(n),children:[r.jsx(o.Text,{children:"X Axis"}),r.jsxs(o.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[r.jsx(b.Controller,{name:"x_axis_data_key",control:i,render:({field:c})=>r.jsx(U,{label:"Data Field",required:!0,...c})}),r.jsx(b.Controller,{name:"xAxis3D.name",control:i,render:({field:c})=>r.jsx(o.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...c})})]}),r.jsx(o.Text,{mt:"lg",children:"Y Axis"}),r.jsxs(o.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[r.jsx(b.Controller,{name:"y_axis_data_key",control:i,render:({field:c})=>r.jsx(U,{label:"Data Field",required:!0,...c})}),r.jsx(b.Controller,{name:"yAxis3D.name",control:i,render:({field:c})=>r.jsx(o.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...c})})]}),r.jsx(o.Text,{mt:"lg",children:"Z Axis"}),r.jsxs(o.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[r.jsx(b.Controller,{name:"z_axis_data_key",control:i,render:({field:c})=>r.jsx(U,{label:"Data Field",required:!0,...c})}),r.jsx(b.Controller,{name:"zAxis3D.name",control:i,render:({field:c})=>r.jsx(o.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...c})})]}),r.jsx(o.Group,{position:"center",mt:"xl",grow:!0,sx:{width:"60%"},mx:"auto",children:r.jsxs(o.Button,{color:"blue",type:"submit",children:[r.jsx(W.DeviceFloppy,{size:20}),r.jsx(o.Text,{ml:"md",children:"Save"})]})})]})}):null}const Q_=[{lang:"en",resources:{bar_chart_3d:{viz_name:"Bar Chart(3D)"}}},{lang:"zh",resources:{bar_chart_3d:{viz_name:"柱图(3D)"}}}];function U_(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const s=u=>u&&`${n}.${u}`,{x_axis_data_key:i,y_axis_data_key:a,z_axis_data_key:l,...c}=e;return{...c,x_axis_data_key:s(i),y_axis_data_key:s(a),z_axis_data_key:s(l)}}catch(n){throw console.error("[Migration failed]",n),n}}class Y_ extends Me{constructor(){super(...arguments);N(this,"VERSION",2)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,(n,s)=>{const{config:i}=n;return{...n,version:2,config:U_(i,s)}})}}const K_={displayName:"viz.bar_chart_3d.viz_name",displayGroup:"chart.groups.echarts_based_charts",migrator:new Y_,name:"bar-3d",viewRender:W_,configRender:R_,createConfig(){return{version:2,config:v.cloneDeep(go)}},translation:Q_},X_=({disabled:e,value:t,onChange:n})=>{const s=i=>{i&&n(i)};return r.jsxs(o.Box,{sx:{position:"relative"},children:[e&&r.jsx(o.Overlay,{opacity:.6,color:"#fff",zIndex:5,blur:2}),r.jsx(gt,{height:"500px",defaultLanguage:"javascript",value:t,onChange:s,theme:"vs-dark",options:{minimap:{enabled:!1},readOnly:e}})]})};function pt({enabled:e,func_content:t}){return(n,s)=>{if(!e)return n;try{return new Function(`return ${t}`)()(n,s)}catch(i){return console.error(`[getEchartsXAxisLabel] failed parsing custom function, error: ${i.message}`),n}}}function nt(){return{enabled:!1,func_content:["function label(value, index) {"," // your code goes here"," // return value","}"].join(`
92
+ `)(n)}catch(s){return console.error(s),console.log(e),e}}function Np(e,t,n,s){const i=w_(t,s);return e.replaceAll(/(\{\{([^{\}]+(?=}))\}\})/g,(...l)=>{const c=l[2];if(!c)return c;const u=i[c];if(u)return u;const d=C_(c);return S_(d,i,n)})}function k_(e,t){const n=xc.decode(t);n!==e&&(console.error("Inconsistent sql"),console.groupCollapsed("Inconsistent sql"),console.table({before:e,after:t,v:n}),console.groupEnd())}async function T_({query:e,name:t,payload:n,additionals:s},i){if(!e.sql)return[];const{type:a,key:l,sql:c,pre_process:u,post_process:d}=e,h=Di(c,n),p=Wm({sql:h,pre_process:u}),f=xc.encode(p);k_(p,f);let m=await Kt.query(i)({type:a,key:l,query:f,...s},{params:{name:t}});return m=Rm(d,m,po(n)),m}async function D_({type:e,key:t,configString:n,name:s,additionals:i},a){try{return await Kt.httpDataSourceQuery(a)({type:e,key:t,query:n,...i},{params:{name:s}})}catch(l){if(Rt.isCancel(l))throw l;return console.error(l),l}}async function ho(){try{return(await Kt.post()("/datasource/list",{filter:{},sort:[{field:"create_time",order:"ASC"}],pagination:{page:1,pagesize:100}},{})).data}catch(e){return console.error(e),[]}}async function $p(){try{return(await Kt.post()("/sql_snippet/list",{filter:{},sort:[{field:"id",order:"ASC"}],pagination:{page:1,pagesize:1e3}},{})).data}catch(e){return console.error(e),[]}}class Fp{constructor(t){N(this,"rootRef");this.rootRef=ae.observable({current:t})}async deleteItem(t){ae.runInAction(()=>{v.unset(this.rootRef.current,[t])})}getItem(t){const n=this.getValueFromRoot(t);return Promise.resolve(n)}getValueFromRoot(t){return t===null?ae.toJS(this.rootRef.current):v.get(this.rootRef.current,[t])}setItem(t,n){if(t===null)if(v.isObject(n))ae.runInAction(()=>{this.rootRef.current=n});else throw new Error("Cannot set root value to non-object");else ae.runInAction(()=>{v.set(this.rootRef.current,[t],n)});return Promise.resolve(this.getItem(t))}watchItem(t,n,s){return ae.reaction(()=>this.getValueFromRoot(t),(i,a)=>{n(i,a)},{requiresObservable:!0,fireImmediately:v.get(s,"fireImmediately",!1)})}}class M_{constructor(){N(this,"channels",new Map);N(this,"globalChannel",new yc)}getChannel(t){const n=this.channels.get(t);if(n)return n;const s=new yc;return this.channels.set(t,s),s}}class I_{constructor(t){N(this,"instances",new Map);this.pluginManager=t}get availableVizList(){return this.pluginManager.installedPlugins.flatMap(t=>t.manifest.viz)}resolveComponent(t){return this.pluginManager.factory.viz(t)}getOrCreateInstance(t){const n=this.instances.get(t.id);if(n)return n;const s={id:t.id,name:t.viz.type,type:t.viz.type,messageChannels:new M_,instanceData:new Fp(t.viz.conf)};return this.instances.set(t.id,s),s}}function Gp(e,t,n,s){return{vizManager:n,locale:"zh",msgChannels:e.messageChannels,instanceData:e.instanceData,pluginData:new Fp({}),colorPalette:{getColor(){return()=>""}},data:t,variables:s}}const z_=e=>{const{panel:t,measure:n,vizManager:s,data:i,variables:a}=e,l=s.resolveComponent(t.viz.type),c=s.getOrCreateInstance(t),u={...Gp(c,i,s,a),viewport:{width:n.w,height:n.h}},d=l.viewRender;return r.jsx(d,{context:u,instance:c,...v.omit(e,["panel","vizManager","data"])})},E_=e=>{const{vizManager:t,panel:n,data:s,variables:i}=e,a=t.resolveComponent(n.viz.type),l=t.getOrCreateInstance(n),c={...Gp(l,s,t,i)},u=a.configRender;return r.jsx(u,{context:c,instance:l,...v.omit(e,["panel","vizManager","data"])})},Wp=(e,t)=>{const n=Ut.bezier(e),s=Ut.bezier(t);return function(i){return i<50?n(i*2/100).hex():s((i-50)*2/100).hex()}},Js=e=>{const t=Ut.bezier(e);return function(n){return t(n/100).hex()}},A_={type:"interpolation",displayName:"style.color.interpolation.palette.red_green",getColor:Wp(["darkred","deeppink","lightyellow"],["lightyellow","lightgreen","teal"]),name:"red-green",category:"diverging"},P_={type:"interpolation",displayName:"style.color.interpolation.palette.yellow_blue",getColor:Wp(["#8f531d","#ffd347","#e3efe3"],["#eefaee","#4ecbbf","#003f94"]),name:"yellow-blue",category:"diverging"},O_={type:"interpolation",displayName:"style.color.interpolation.palette.red",getColor:Js(["#fff7f1","darkred"]),name:"red",category:"sequential"},L_={type:"interpolation",displayName:"style.color.interpolation.palette.green",getColor:Js(["#f0ffed","darkgreen"]),name:"green",category:"sequential"},V_={type:"interpolation",displayName:"style.color.interpolation.palette.blue",getColor:Js(["#f9fcff","#48b3e9","darkblue"]),name:"blue",category:"sequential"},B_={type:"interpolation",displayName:"style.color.interpolation.palette.orange",getColor:Js(["#fff7f1","darkorange","#b60000"]),name:"orange",category:"sequential"};class q_{constructor(t){N(this,"symbol");this.symbol=Symbol(t)}}function hn(e){return new q_(e)}class fo{constructor(){N(this,"parent");N(this,"factoryRegistry",new Map);N(this,"instanceRegistry",new Map)}createScoped(){const t=new fo;return t.parent=this,t}getRequired(t){return this.get(t)}get(t){if(this.instanceRegistry.has(t.symbol))return this.instanceRegistry.get(t.symbol);const n=this.factoryRegistry.get(t.symbol);if(n){const s=n(this);return this.instanceRegistry.set(t.symbol,s),s}if(this.parent)return this.parent.get(t)}provideFactory(t,n){return this.factoryRegistry.has(t.symbol)?console.warn(`Token ${t.symbol.toString()} is already registered`):this.factoryRegistry.set(t.symbol,n),this}provideValue(t,n){return this.factoryRegistry.has(t.symbol)?console.warn(`Token ${t.symbol.toString()} is already registered`):this.factoryRegistry.set(t.symbol,()=>n),this}dispose(){this.instanceRegistry.forEach(t=>{const n=v.get(t,"dispose");v.isFunction(n)&&n.bind(t)()}),this.instanceRegistry.clear(),this.factoryRegistry.clear()}}const Rp="13.28.3",N_=Object.freeze(Object.defineProperty({__proto__:null,version:Rp},Symbol.toStringTag,{value:"Module"}));class $_{constructor(t){N(this,"staticColors",new Map);N(this,"interpolations",new Map);t.installedPlugins.forEach(n=>{n.manifest.color.forEach(s=>{this.register(s)})})}getStaticColors(){return Array.from(this.staticColors.values())}register(t){const n=this.encodeColor(t);t.type==="single"?(this.staticColors.has(n)&&console.warn(`the color '${t.name}' has been registered under '${t.category}', previous registered value will be overridden`),this.staticColors.set(n,t)):t.type==="interpolation"&&(this.interpolations.has(n)&&console.warn(`the interpolation '${t.name}' has been registered under '${t.category}', previous registered value will be overridden`,`the interpolation '${t.name}' has been registered under '${t.category}', previous registered value will be overridden`),this.interpolations.set(n,t))}decodeStaticColor(t){return this.staticColors.get(t)}encodeColor(t){return`\${${t.category}}.{${t.name}}`}decodeInterpolation(t){return this.interpolations.get(t)}getColorInterpolations(){return Array.from(this.interpolations.values())}}class F_{constructor(){N(this,"plugins",new Map);N(this,"vizComponents",new Map);N(this,"factory",{viz:t=>{const n=this.vizComponents.get(t);if(n)return n;throw new Error(`Viz Component (${t}) not found`)}})}install(t){if(this.plugins.has(t.id))throw new Error(`Plugin (${t.id}) has been installed before`);this.plugins.set(t.id,t);for(const n of t.manifest.viz){if(this.vizComponents.has(n.name))throw new Error(`Viz Component (${n.name}) has been installed before`);this.vizComponents.set(n.name,n)}}get installedPlugins(){return Array.from(this.plugins.values())}}class G_{constructor(){N(this,"migrations",[])}version(t,n){return this.migrations.push({version:t,handler:n}),this}run(t,n,s){var l;if(t.from===t.to)return n;if(t.from>t.to)throw new Error(`Can not downgrade from version '${t.from}' to (${t.to})`);const i=this.migrations.filter(c=>c.version>t.from&&c.version<=t.to),a=v.orderBy(i,"version","asc");if(((l=v.last(a))==null?void 0:l.version)!==t.to)throw new Error(`Migration to version ${t.to} not found`);return a.reduce((c,u)=>u.handler(c,s),n)}}class Me extends G_{constructor(){super(),this.configVersions()}version(t,n){return super.version(t,(s,i)=>({version:t,...n(s,i)}))}async migrate({configData:t,panelModel:n}){const s=await t.getItem(null),i=v.get(s,"version",0),a=this.run({from:i,to:this.VERSION},s,{panelModel:n});await t.setItem(null,a)}async needMigration({configData:t}){const n=await t.getItem(null);return v.get(n,"version",0)<this.VERSION}}const Q=(e,t)=>{const[n,{setFalse:s}]=J.useBoolean(!0),[i,a]=g.useState();g.useEffect(()=>(e.getItem(t).then(c=>{a(c),s()}),e.watchItem(t,c=>{a(c)})));const l=g.useCallback(async c=>{await e.setItem(t,c),a(c)},[e,t]);return{loading:n,value:i,set:l}},ut={top:16,right:16,bottom:16,left:16},Bt=e=>Math.max(0,e-ut.left-ut.right),qt=e=>Math.max(0,e-ut.top-ut.bottom),Jr=(e,t)=>({width:Bt(e),height:qt(t)}),dt=({width:e,height:t,children:n})=>r.jsx(o.Box,{pt:ut.top,pr:ut.right,pb:ut.bottom,pl:ut.left,sx:{width:e,height:t,overflow:"hidden",position:"relative"},children:n}),go={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 W_({context:e}){const{value:t}=Q(e.instanceData,"config"),n=e.data,{width:s,height:i}=e.viewport,{x_axis_data_key:a,y_axis_data_key:l,z_axis_data_key:c,xAxis3D:u,yAxis3D:d,zAxis3D:h}=v.defaults({},t,go),p=g.useMemo(()=>cs(n,a),[n,a]),{x:f,y:m,z:y}=g.useMemo(()=>({x:L(a),y:L(l),z:L(c)}),[a,l,c]),{min:_,max:k}=g.useMemo(()=>{const T=v.minBy(p,z=>z[y.columnKey]),I=v.maxBy(p,z=>z[y.columnKey]);return{min:v.get(T,y.columnKey),max:v.get(I,y.columnKey)}},[p,y]),S={tooltip:{},backgroundColor:"#fff",visualMap:{show:!0,dimension:2,min:_,max:k,inRange:{color:["#313695","#4575b4","#74add1","#abd9e9","#e0f3f8","#ffffbf","#fee090","#fdae61","#f46d43","#d73027","#a50026"]}},xAxis3D:u,yAxis3D:d,zAxis3D:h,grid3D:{viewControl:{projection:"orthographic",autoRotate:!1},light:{main:{shadow:!0,quality:"ultra",intensity:1.5}}},series:[{type:"bar3D",wireframe:{},data:p.map(T=>[T[f.columnKey],T[m.columnKey],T[y.columnKey]])}]};return t?r.jsx(dt,{width:s,height:i,children:r.jsx(Ke,{echarts:Ye,option:S,style:Jr(s,i),notMerge:!0,theme:"merico-light"})}):null}const U=D.observer(g.forwardRef(({label:e,required:t,description:n,value:s,onChange:i,queryID:a,clearable:l=!1,sx:c,...u},d)=>{const{panel:h}=Je(),p=g.useMemo(()=>h.dataFieldOptions(s,l,a),[s,l,a]);if(p.length===0){const f=h.explainDataKey(s);return r.jsxs(o.HoverCard,{shadow:"md",position:"bottom-start",withinPortal:!0,zIndex:320,children:[r.jsx(o.HoverCard.Target,{children:r.jsx(o.Box,{children:r.jsx(o.TextInput,{label:e,required:t,defaultValue:f.columnKey,readOnly:!0,disabled:!0})})}),r.jsx(o.HoverCard.Dropdown,{children:r.jsxs(o.Group,{position:"left",spacing:0,children:[r.jsx(o.Text,{size:"xs",color:f.queryName?"black":"red",sx:{fontFamily:"monospace"},children:f.queryName??f.queryID}),r.jsx(o.Text,{size:"xs",color:"black",sx:{fontFamily:"monospace"},children:"."}),r.jsx(o.Text,{size:"xs",color:"red",sx:{fontFamily:"monospace"},children:f.columnKey})]})})]})}return r.jsx(o.Select,{ref:d,label:e,description:n,data:p,value:s,onChange:i,required:t,sx:c,maxDropdownHeight:500,...u})}));function R_({context:e}){const{value:t,set:n}=Q(e.instanceData,"config"),s=v.defaults({},t,go),{control:i,handleSubmit:a,reset:l}=b.useForm({defaultValues:s});return g.useEffect(()=>{l(s)},[t]),t?r.jsx(o.Stack,{spacing:"xs",children:r.jsxs("form",{onSubmit:a(n),children:[r.jsx(o.Text,{children:"X Axis"}),r.jsxs(o.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[r.jsx(b.Controller,{name:"x_axis_data_key",control:i,render:({field:c})=>r.jsx(U,{label:"Data Field",required:!0,...c})}),r.jsx(b.Controller,{name:"xAxis3D.name",control:i,render:({field:c})=>r.jsx(o.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...c})})]}),r.jsx(o.Text,{mt:"lg",children:"Y Axis"}),r.jsxs(o.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[r.jsx(b.Controller,{name:"y_axis_data_key",control:i,render:({field:c})=>r.jsx(U,{label:"Data Field",required:!0,...c})}),r.jsx(b.Controller,{name:"yAxis3D.name",control:i,render:({field:c})=>r.jsx(o.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...c})})]}),r.jsx(o.Text,{mt:"lg",children:"Z Axis"}),r.jsxs(o.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[r.jsx(b.Controller,{name:"z_axis_data_key",control:i,render:({field:c})=>r.jsx(U,{label:"Data Field",required:!0,...c})}),r.jsx(b.Controller,{name:"zAxis3D.name",control:i,render:({field:c})=>r.jsx(o.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...c})})]}),r.jsx(o.Group,{position:"center",mt:"xl",grow:!0,sx:{width:"60%"},mx:"auto",children:r.jsxs(o.Button,{color:"blue",type:"submit",children:[r.jsx(W.DeviceFloppy,{size:20}),r.jsx(o.Text,{ml:"md",children:"Save"})]})})]})}):null}const Q_=[{lang:"en",resources:{bar_chart_3d:{viz_name:"Bar Chart(3D)"}}},{lang:"zh",resources:{bar_chart_3d:{viz_name:"柱图(3D)"}}}];function U_(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const s=u=>u&&`${n}.${u}`,{x_axis_data_key:i,y_axis_data_key:a,z_axis_data_key:l,...c}=e;return{...c,x_axis_data_key:s(i),y_axis_data_key:s(a),z_axis_data_key:s(l)}}catch(n){throw console.error("[Migration failed]",n),n}}class Y_ extends Me{constructor(){super(...arguments);N(this,"VERSION",2)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,(n,s)=>{const{config:i}=n;return{...n,version:2,config:U_(i,s)}})}}const K_={displayName:"viz.bar_chart_3d.viz_name",displayGroup:"chart.groups.echarts_based_charts",migrator:new Y_,name:"bar-3d",viewRender:W_,configRender:R_,createConfig(){return{version:2,config:v.cloneDeep(go)}},translation:Q_},X_=({disabled:e,value:t,onChange:n})=>{const s=i=>{i&&n(i)};return r.jsxs(o.Box,{sx:{position:"relative"},children:[e&&r.jsx(o.Overlay,{opacity:.6,color:"#fff",zIndex:5,blur:2}),r.jsx(gt,{height:"500px",defaultLanguage:"javascript",value:t,onChange:s,theme:"vs-dark",options:{minimap:{enabled:!1},readOnly:e}})]})};function pt({enabled:e,func_content:t}){return(n,s)=>{if(!e)return n;try{return new Function(`return ${t}`)()(n,s)}catch(i){return console.error(`[getEchartsXAxisLabel] failed parsing custom function, error: ${i.message}`),n}}}function nt(){return{enabled:!1,func_content:["function label(value, index) {"," // your code goes here"," // return value","}"].join(`
93
93
  `)}}const Nt=g.forwardRef(({value:e,onChange:t,triggerButtonText:n},s)=>{const{t:i}=j.useTranslation(),[a,{setTrue:l,setFalse:c}]=J.useBoolean(),[u,d]=g.useState(e);g.useEffect(()=>{d(e)},[e]);const h=k=>{d({...u,enabled:k})},p=()=>{c();const{enabled:k,func_content:S}=u,T={enabled:k,func_content:S};d(T),t(T)},f=()=>{c(),d(e)},m=k=>{d(S=>({...S,func_content:k}))},y=()=>{m(nt().func_content)},_=n??i("chart.axis.customize_label");return r.jsxs(r.Fragment,{children:[r.jsx(o.Button,{variant:"filled",color:"grape",leftIcon:r.jsx(M.IconMathFunction,{size:16}),mt:24,onClick:l,sx:{flexGrow:0},children:_}),r.jsx(o.Modal,{size:800,title:_,opened:a,onClose:c,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:a&&r.jsxs(o.Stack,{children:[r.jsx(o.Checkbox,{mt:10,label:i("common.enabled"),checked:u.enabled,onChange:k=>h(k.currentTarget.checked)}),r.jsx(X_,{value:u.func_content,onChange:m,disabled:!u.enabled}),r.jsxs(o.Group,{position:"apart",children:[r.jsx(o.Button,{onClick:y,color:"red",leftIcon:r.jsx(W.Recycle,{size:20}),children:i("common.actions.reset_to_default")}),r.jsxs(o.Group,{position:"right",children:[r.jsx(o.Button,{onClick:f,variant:"subtle",children:i("common.actions.cancel")}),r.jsx(o.Button,{color:"green",leftIcon:r.jsx(M.IconDeviceFloppy,{size:16}),onClick:p,children:i("common.actions.save")})]})]})]})})]})}),$n={x_axis_scroll:!1,y_axis_scroll:!1,x_axis_slider:!1,y_axis_slider:!1};function Qp(){return v.cloneDeep($n)}const J_=[{lang:"en",resources:{boxplot:{viz_name:"Boxplot Chart",box:"Box",outlier:"Outlier",scatter:"Scatter",click_series:{label:"Click box, scatter or outlier"}}}},{lang:"zh",resources:{boxplot:{viz_name:"箱线图",box:"箱体",outlier:"异常点",scatter:"散点",click_series:{label:"点击箱体、散点或异常点"}}}}],Up={id:"builtin:echarts:click-echart:series",displayName:"viz.boxplot.click_series.label",nameRender:H_,configRender:Z_,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 Z_(e){return r.jsx(r.Fragment,{})}function H_(e){const{t}=j.useTranslation();return r.jsx(o.Text,{children:t("viz.boxplot.click_series.label")})}const Zs=g.forwardRef(({sectionTitle:e,value:t,onChange:n},s)=>{const{t:i,i18n:a}=j.useTranslation(),l=u=>d=>{const h=v.cloneDeep(t);v.set(h,u,d),n(h)},c=g.useMemo(()=>[{label:i("chart.axis.overflow.truncate"),value:"truncate"},{label:i("chart.axis.overflow.break_line"),value:"break"},{label:i("chart.axis.overflow.break_word"),value:"breakAll"}],[a.language]);return r.jsxs(o.Stack,{spacing:0,children:[e&&r.jsx(o.Divider,{mb:-5,mt:5,variant:"dotted",label:e,labelPosition:"right",labelProps:{color:"dimmed"}}),r.jsxs(o.Group,{grow:!0,noWrap:!0,children:[r.jsx(o.NumberInput,{label:i("chart.axis.overflow.max_width"),hideControls:!0,value:t.width,onChange:l("width")}),r.jsx(o.Select,{label:i("chart.axis.overflow.label"),data:c,value:t.overflow,onChange:l("overflow")}),r.jsx(o.TextInput,{label:i("chart.axis.overflow.ellipsis"),value:t.ellipsis,disabled:!0})]})]})}),$t=g.forwardRef(({value:e,onChange:t},n)=>{const{t:s}=j.useTranslation(),i=l=>{t({...e,on_axis:l})},a=l=>{t({...e,in_tooltip:l})};return r.jsxs(o.Stack,{ref:n,spacing:0,children:[r.jsx(Zs,{sectionTitle:s("chart.axis.overflow.section_title.on_axis"),value:e.on_axis,onChange:i}),r.jsx(Zs,{sectionTitle:s("chart.axis.overflow.section_title.in_tooltip"),value:e.in_tooltip,onChange:a})]})});function ht(){return{on_axis:{width:80,overflow:"truncate",ellipsis:"..."},in_tooltip:{width:200,overflow:"break",ellipsis:"..."}}}function Dt({overflow:e,width:t}){const n={truncate:"initial",break:"break-all",breakAll:"break-word"}[e],s=e==="truncate"?"nowrap":"initial",i={truncate:"ellipsis",break:"clip",breakAll:"clip"}[e];return`
94
94
  max-width: ${t}px;
95
95
  word-break: ${n};
@@ -467,7 +467,7 @@ Check the top-level render call using <`+q+">.")}return A}}function $g(C,A){{if(
467
467
  <tbody>${f.join("")}</tbody>
468
468
  </table>
469
469
  `}})}function Pz(e,t,n){const{overflow:s,rotate:i}=e.x_axis.axisLabel,a=Mt(s.on_axis);return me.getXAxis({id:"main-x-axis",type:"category",data:t,name:e.x_axis.name??"",align:"center",axisTick:{show:!0,alignWithLabel:!0},axisLabel:{rotate:i,...a,formatter:n},splitArea:{show:!1,areaStyle:{color:"#E7E7E9"}},splitLine:{show:!1},nameLocation:"center",nameGap:25,nameTextStyle:{fontWeight:"bold",align:"center"},z:3})}function Oz(e,t){const{nameAlignment:n,data_key:s,...i}=e.y_axis,{overflow:a,rotate:l}=e.y_axis.axisLabel,c=Mt(a.on_axis);return me.getYAxis({...i,type:"category",axisLabel:{rotate:l,...c,formatter:t},axisLine:{show:!0,lineStyle:{width:3}},axisTick:{show:!0,alignWithLabel:!0},splitArea:{show:!1,areaStyle:{color:"#E7E7E9"}},splitLine:{show:!1},nameTextStyle:{fontWeight:"bold",align:n},nameLocation:"end",nameGap:15,z:3})}function Lz(e,t,n){if(!e.x_axis.data_key||!e.y_axis.data_key||!e.heat_block.data_key)return{};const s=n.reduce((_,k)=>{const S=nn(k,t);return _[k.name]=vt(k,S),_},{}),i=Tz(e),a=Dz(e),l=Us(e.visualMap,s),{min:c,max:u}=l,d=L(e.x_axis.data_key),h=L(e.y_axis.data_key),p=L(e.heat_block.data_key),f=v.uniq(t[d.queryID].map(_=>_[d.columnKey])),m=t[d.queryID].map(_=>{const k=v.get(_,d.columnKey),S=v.get(_,h.columnKey),T=v.get(_,p.columnKey),I={value:[k,S,T]},{followVisualMap:z,color:E}=oo(T,c,u,e.visualMap);return z||(I.visualMap=!1,I.itemStyle={color:E}),I});return{xAxis:Pz(e,f,i.x_axis),yAxis:Oz(e,i.y_axis),series:Iz(e,m),tooltip:Az(e,t,i,a),grid:Mz(e),visualMap:l}}function Vz({conf:e,data:t,width:n,height:s,interactionManager:i,variables:a}){const l=g.useMemo(()=>{const p=L(e.x_axis.data_key),f=L(e.y_axis.data_key);return v.keyBy(t[p.queryID],m=>`${m[p.columnKey]}---${m[f.columnKey]}`)},[t,e.x_axis.data_key,e.y_axis.data_key]),c=_t(i.triggerManager,Uh.id),u=g.useCallback(p=>{const[f,m]=p.value,y=v.get(l,`${f}---${m}`,{error:"rowData is not found"});c.forEach(_=>{i.runInteraction(_.id,{...p,rowData:y})})},[l,c,i]),d=g.useMemo(()=>({click:u}),[u]),h=g.useMemo(()=>Lz(e,t,a),[e,t]);return r.jsx(Ke,{echarts:Ye,option:h,style:{width:n,height:s},onEvents:d,notMerge:!0,theme:"merico-light"})}function Bz({context:e,instance:t}){const n=jt({vizManager:e.vizManager,instance:t}),{value:s}=Q(e.instanceData,"config"),{variables:i}=e,a=g.useMemo(()=>v.defaults({},s,Ho),[s]),l=e.data,{width:c,height:u}=e.viewport;return!c||!u?null:r.jsx(dt,{width:c,height:u,children:r.jsx(Vz,{variables:i,width:Bt(c),height:qt(u),data:l,conf:a,interactionManager:n})})}const qz=[{lang:"en",resources:{merico_heatmap:{viz_name:"Merico Heatmap",click_heatmap:{heatblock:{label:"Click heat block"}}}}},{lang:"zh",resources:{merico_heatmap:{viz_name:"思码逸热力图",click_heatmap:{heatblock:{label:"点击热力块"}}}}}];function Nz(e){const{visualMap:t=pn(),heat_block:{min:n,max:s,...i},...a}=e;return{...a,heat_block:i,visualMap:{...pn(),min:n,max:s}}}class $z extends Me{constructor(){super(...arguments);N(this,"VERSION",2)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,n=>({...n,version:2,config:Nz(n.config)}))}}const Fz={displayName:"viz.merico_heatmap.viz_name",displayGroup:"chart.groups.merico_suite",migrator:new $z,name:"merico-heatmap",viewRender:Bz,configRender:Cz,createConfig:()=>({version:2,config:Ho}),triggers:[Uh],translation:qz},Gz=[{value:"#25262B",name:"Dark"},{value:"#868E96",name:"Gray"},{value:"#FA5252",name:"Red"},{value:"#E64980",name:"Pink"},{value:"#BE4BDB",name:"Grape"},{value:"#7950F2",name:"Violet"},{value:"#4C6EF5",name:"Indigo"},{value:"#228BE6",name:"Blue"},{value:"#15AABF",name:"Cyan"},{value:"#12B886",name:"Teal"},{value:"#40C057",name:"Green"},{value:"#82C91E",name:"Lime"},{value:"#FAB005",name:"Yellow"},{value:"#FD7E14",name:"Orange"}].map(e=>({name:e.name,value:e.value,type:"single",category:"basic"})),Wz=[A_,P_,V_,L_,O_,B_],Yh=[Wo,W1,aM,MT,dD,Ck,kI,K_,Xw,YC,IS,WM,pk,MC,T1,Xk,CT,gM,iz,Fz,xz,o0],Kh=()=>({id:"dashboard",version:Rp,manifest:{viz:Yh,color:[...Gz,...Wz]}}),Hr=new F_,Oe={pluginManager:hn("pluginManager"),vizManager:hn("vizManager"),colorManager:hn("colorManager"),instanceScope:{panelModel:hn("panelModel"),vizInstance:hn("vizInstance"),interactionManager:hn("interactionManager"),migrator:hn("migrator"),operationManager:hn("operationManager"),triggerManager:hn("triggerManager")}},el=()=>{try{Hr.install(Kh())}catch{}const e=new I_(Hr),t=new $_(Hr);return{pluginManager:Hr,vizManager:e,colorManager:t}},rn=g.createContext(el());try{Hr.install(Kh())}catch{}const tl=g.createContext(null);function di(e){const t=g.useContext(tl),n=J.useCreation(()=>e.configure(t||new fo),[e.configure]),s=J.usePrevious(n);return s&&s!==n&&s.dispose(),r.jsx(tl.Provider,{value:n,children:e.children})}function Xh(){return g.useContext(tl)}const Rz=({description:e,isDescriptionEmpty:t})=>t?null:r.jsx(o.Tooltip,{color:"white",label:r.jsx(Kr,{value:e,styles:{root:{border:"none"},content:{padding:0}}}),styles:{tooltip:{border:"0.0625rem solid rgb(233, 236, 239)",boxShadow:"rgb(0 0 0 / 5%) 0px 0.0625rem 0.1875rem, rgb(0 0 0 / 5%) 0px 1.25rem 1.5625rem -0.3125rem, rgb(0 0 0 / 4%) 0px 0.625rem 0.625rem -0.3125rem"}},withArrow:!0,children:r.jsx(o.Box,{sx:{height:"16px",alignSelf:"center"},children:r.jsx(M.IconInfoCircle,{size:16,color:"gray"})})}),Qz=D.observer(({label:e,config:{default_value:t,description:n,isDescriptionEmpty:s,...i},value:a,onChange:l})=>r.jsxs(o.Box,{children:[r.jsx(o.Text,{children:" "}),r.jsx(o.Checkbox,{label:r.jsxs(o.Group,{noWrap:!0,position:"apart",align:"middle",spacing:6,children:[r.jsx(o.Box,{sx:{flexGrow:1},children:e}),r.jsx(Rz,{description:n,isDescriptionEmpty:s})]}),checked:a||!1,onChange:c=>l(c.currentTarget.checked),...i,pt:".4em",styles:{input:{borderColor:"#e9ecef"}}})]})),Uz=({value:e,onChange:t,close:n,max_days:s,allowSingleDateInRange:i})=>{const{i18n:a}=j.useTranslation(),[l,c]=e,u=g.useMemo(()=>l||new Date,[l]),d=g.useMemo(()=>{if(l&&!c)return l},[l,c]),h=g.useMemo(()=>{if(l&&!c&&s>0)return P(l).add(s-1,"days").toDate()},[l,c,s]),p=f=>{const[m,y]=f;t(f),m&&y&&n()};return r.jsx(mc.DatePicker,{defaultDate:u,numberOfColumns:2,type:"range",value:e,onChange:p,onNextMonth:console.log,minDate:d,maxDate:h,allowSingleDateInRange:i,locale:a.language})},Yz=({begin:e,end:t})=>{const{t:n}=j.useTranslation(),s=g.useMemo(()=>P(t).diff(P(e),"days")+1,[e,t]);if(Number.isNaN(s))return r.jsx("span",{style:{userSelect:"none",opacity:0,visibility:"hidden"},children:"."});const i=s===1?n("filter.widget.date_range.one_day"):n("filter.widget.date_range.x_days",{count:s});return r.jsx(o.Tooltip,{label:i,children:r.jsx(o.Badge,{size:"sm",children:s})})},Kz=({max_days:e})=>{const{t}=j.useTranslation();return e?r.jsxs(r.Fragment,{children:[r.jsx(o.Group,{position:"right",children:r.jsx(o.Badge,{size:"xs",children:t("filter.widget.date_range.x_max_days",{max_days:e})})}),r.jsx(o.Divider,{variant:"dashed",my:10})]}):null},nl=()=>[{key:"d",value:"yesterday",group:"last",getRange:()=>{const e=Date.now();return[P(e).subtract(1,"day").startOf("day").toDate(),P(e).subtract(1,"day").endOf("day").toDate()]}},{key:"w",value:"last week",group:"last",getRange:()=>{const e=Date.now();return[P(e).subtract(1,"week").startOf("week").toDate(),P(e).subtract(1,"week").endOf("week").toDate()]}},{key:"m",value:"last month",group:"last",getRange:()=>{const e=Date.now();return[P(e).subtract(1,"month").startOf("month").toDate(),P(e).subtract(1,"month").endOf("month").toDate()]}},{key:"m2",value:"last 2 months",group:"last",getRange:()=>{const e=Date.now();return[P(e).subtract(2,"month").startOf("month").toDate(),P(e).subtract(1,"month").endOf("month").toDate()]}},{key:"m3",value:"last 3 months",group:"last",getRange:()=>{const e=Date.now();return[P(e).subtract(3,"month").startOf("month").toDate(),P(e).subtract(1,"month").endOf("month").toDate()]}},{key:"y",value:"last year",group:"last",getRange:()=>{const e=Date.now();return[P(e).subtract(1,"year").startOf("year").toDate(),P(e).subtract(1,"year").endOf("year").toDate()]}},{key:"d7",value:"recent 7 days",group:"recent",getRange:()=>{const e=Date.now();return[P(e).subtract(7,"day").startOf("day").toDate(),P(e).subtract(1,"day").endOf("day").toDate()]}},{key:"d30",value:"recent 30 days",group:"recent",getRange:()=>{const e=Date.now();return[P(e).subtract(30,"day").startOf("day").toDate(),P(e).subtract(1,"day").endOf("day").toDate()]}},{key:"d60",value:"recent 60 days",group:"recent",getRange:()=>{const e=Date.now();return[P(e).subtract(60,"day").startOf("day").toDate(),P(e).subtract(1,"day").endOf("day").toDate()]}},{key:"d90",value:"recent 90 days",group:"recent",getRange:()=>{const e=Date.now();return[P(e).subtract(90,"day").startOf("day").toDate(),P(e).subtract(1,"day").endOf("day").toDate()]}},{key:"d180",value:"recent 180 days",group:"recent",getRange:()=>{const e=Date.now();return[P(e).subtract(180,"day").startOf("day").toDate(),P(e).subtract(1,"day").endOf("day").toDate()]}},{key:"d365",value:"recent 365 days",group:"recent",getRange:()=>{const e=Date.now();return[P(e).subtract(365,"day").startOf("day").toDate(),P(e).subtract(1,"day").endOf("day").toDate()]}},{key:"d",value:"today",group:"this",getRange:()=>{const e=Date.now();return[P(e).startOf("day").toDate(),P(e).endOf("day").toDate()]}},{key:"w",value:"this week",group:"this",getRange:()=>{const e=Date.now();return[P(e).startOf("week").toDate(),P(e).endOf("week").toDate()]}},{key:"m",value:"this month",group:"this",getRange:()=>{const e=Date.now();return[P(e).startOf("month").toDate(),P(e).endOf("month").toDate()]}},{key:"y",value:"this year",group:"this",getRange:()=>{const e=Date.now();return[P(e).startOf("year").toDate(),P(e).endOf("year").toDate()]}},{key:"w",value:"this week so far",group:"this_so_far",getRange:()=>{const e=Date.now();return[P(e).startOf("week").toDate(),P(e).toDate()]}},{key:"m",value:"this month so far",group:"this_so_far",getRange:()=>{const e=Date.now();return[P(e).startOf("month").toDate(),P(e).toDate()]}},{key:"y",value:"this year so far",group:"this_so_far",getRange:()=>{const e=Date.now();return[P(e).startOf("year").toDate(),P(e).toDate()]}}];function Jh(e){const n=nl().find(s=>s.value===e);return n?n.getRange():null}const Xz=({onChange:e})=>{const{t,i18n:n}=j.useTranslation(),s=l=>()=>{const c=l();e(c)},i=g.useMemo(()=>v.groupBy(nl(),"group"),[]),a=n.language==="zh";return r.jsxs(r.Fragment,{children:[r.jsx(o.Divider,{variant:"dashed",my:10}),r.jsx(o.Table,{withBorder:!1,sx:{"tbody > tr > th, tbody > tr > td":{borderTop:"none",padding:"2px 6px"},"tbody > tr > th":{cursor:"default",userSelect:"none"},td:{paddingLeft:"1px"}},children:r.jsx("tbody",{children:Object.entries(i).map(([l,c])=>r.jsxs("tr",{children:[r.jsx("th",{children:r.jsx(o.Text,{size:"xs",color:"#555",children:t(`filter.widget.date_range.shortcut.${l}.label`)})}),c.map(({key:u,value:d,getRange:h})=>r.jsx("td",{children:r.jsx(o.Button,{compact:!0,size:"xs",variant:"subtle",onClick:s(h),children:t(`filter.widget.date_range.shortcut.${l}.${a?"full.":""}${u}`)})},u))]},l))})})]})},Zh=e=>({label:{display:"block",height:"21.7px"},input:{borderColor:e?"#228be6":"#e9ecef"}}),Jz=({label:e,required:t,value:n,onChange:s,max_days:i,allowSingleDateInRange:a,inputFormat:l})=>{const{t:c}=j.useTranslation(),[u,{open:d,close:h}]=Se.useDisclosure(!1),[p,f]=n,m=p?P(p).format(l):"",y=f?P(f).format(l):"";return r.jsxs(o.Popover,{opened:u,onClose:h,position:"bottom-start",shadow:"md",children:[r.jsxs(o.Group,{position:"left",grow:!0,noWrap:!0,spacing:0,w:"288px",sx:{marginTop:"3px"},children:[r.jsx(o.Popover.Target,{children:r.jsx(o.TextInput,{label:e,labelProps:{title:e},required:t,icon:r.jsx(M.IconCalendar,{size:16}),placeholder:c("filter.widget.date_range.start_date"),readOnly:!0,value:m,onFocus:d,styles:Zh(u),sx:{".mantine-TextInput-label":{textOverflow:"ellipsis",overflow:"hidden",whiteSpace:"nowrap",width:"calc(240px)",position:"relative",zIndex:1},".mantine-Input-input":{borderRight:"none",borderTopRightRadius:0,borderBottomRightRadius:0}}})}),r.jsx(o.TextInput,{label:r.jsx(o.Group,{position:"right",children:r.jsx(Yz,{begin:p,end:f})}),icon:r.jsx(M.IconMinus,{size:16}),placeholder:c("filter.widget.date_range.end_date"),readOnly:!0,disabled:!p,value:y,onFocus:d,styles:Zh(u),sx:{".mantine-Input-icon":{transform:"translateX(-22px)"},".mantine-Input-input":{borderLeft:"none",borderTopLeftRadius:0,borderBottomLeftRadius:0},".mantine-Input-input[data-disabled]":{backgroundColor:"transparent",backgroundImage:"linear-gradient(to right, #fff 0%, #f1f3f5 30%)",opacity:1},".mantine-Input-input[data-disabled]::placeholder":{opacity:.6}}})]}),r.jsxs(o.Popover.Dropdown,{p:"sm",children:[r.jsx(Kz,{max_days:i}),r.jsx(Uz,{value:n,onChange:s,close:h,allowSingleDateInRange:a,max_days:i}),r.jsx(Xz,{onChange:s})]})]})},Hh=D.observer(({label:e,config:t,value:n=[null,null],onChange:s})=>{const{inputFormat:i,required:a,max_days:l,allowSingleDateInRange:c}=t,u=Array.isArray(n)?n.map(h=>h?P(h).toDate():null):[null,null],d=h=>{s(h.map(p=>p&&P(p).format(i)))};return r.jsx(Jz,{label:e,value:u,onChange:d,inputFormat:i,allowSingleDateInRange:c,max_days:l,required:a})}),Zz=o.createStyles((e,{radius:t=4})=>({root:{borderRadius:e.fn.radius(t),display:"flex",flexWrap:"nowrap",border:"1px solid #ced4da",paddingLeft:"0px",paddingRight:"30px",backgroundColor:"#fff",transition:"border-color 100ms ease",borderColor:"#e9ecef","&.rc-select.rc-select-open":{borderColor:"#228be6 !important",".rc-select-selection-overflow-item-rest":{display:"none"},".rc-select-selection-overflow-item-suffix":{display:"block"}},".rc-select-selector":{height:"auto",lineHeight:1.55,paddingLeft:"12px",resize:"none",boxSizing:"border-box",fontSize:"14px",width:"100%",color:"#000",display:"block",textAlign:"left",minHeight:"36px",cursor:"pointer",flexGrow:1},".rc-select-selection-search-mirror":{display:"none"},".rc-select-selection-search":{flexGrow:1,width:"auto !important"},".rc-select-selection-overflow":{display:"flex",minHeight:"34px",alignItems:"center",flexWrap:"nowrap",marginLeft:"calc(-10px / 2)",boxSizing:"border-box"},".rc-select-selection-overflow-item":{display:"flex",alignItems:"center",backgroundColor:"#f1f3f5",color:"#495057",height:"24px",paddingLeft:"12px",paddingRight:"12px",fontWeight:500,fontSize:"12px",borderRadius:"4px",cursor:"default",userSelect:"none",maxWidth:"calc(100% - 20px)",margin:"calc(10px / 2 - 2px) calc(10px / 2)"},".rc-select-selection-overflow-item-rest":{cursor:"pointer"},".rc-select-selection-overflow-item-suffix":{display:"none",backgroundColor:"transparent",width:"100%",maxWidth:"100%",height:"28px",margin:0,paddingLeft:0,paddingRight:0},input:{flex:1,minWidth:"60px",backgroundColor:"transparent",border:0,outline:0,fontSize:"14px",padding:0,marginLeft:0,color:"inherit",height:"28px",lineHeight:"32px",cursor:"pointer",width:"100%","&::-webkit-search-decoration, &::-webkit-search-cancel-button, &::-webkit-search-results-button, &::-webkit-search-results-decoration":{display:"none"}},".rc-select-clear":{marginRight:"-24px",alignSelf:"center",cursor:"pointer"},"&.rc-select-disabled":{backgroundColor:"rgb(241, 243, 245)",color:"rgb(144, 146, 150)",opacity:.6,"&, .rc-select-selector, input":{cursor:"not-allowed"}}},label:{fontSize:e.fontSizes.sm,fontWeight:500,color:"#212529"},required:{color:"#fa5252",paddingLeft:"3px"},dropdown:{fontSize:e.fontSizes.xs,zIndex:300,backgroundColor:"#fff",border:"1px solid #e9ecef",marginTop:6,padding:0,boxShadow:"0 1px 3px rgb(0 0 0 / 5%), rgb(0 0 0 / 5%) 0px 10px 15px -5px, rgb(0 0 0 / 4%) 0px 7px 7px -5px",borderRadius:"4px","&.rc-select-dropdown-slide-up-leave-active":{display:"none"},".rc-select-item-empty":{padding:"8px 12px"},".rc-select-item-option":{boxSizing:"border-box",textAlign:"left",width:"100%",padding:"8px 12px 8px 2px",cursor:"pointer",fontSize:"14px",color:"#000",borderRadius:"4px",display:"flex",flexWrap:"nowrap",overflow:"hidden","&:hover":{backgroundColor:"#f1f3f5"},flexDirection:"row-reverse",".rc-select-item-option-state":{flexGrow:0,flexShrink:0,width:"30px",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},".rc-select-item-option-content":{width:"calc(100% - 30px)",overflow:"hidden",'div[data-role="label"]':{overflowWrap:"break-word"}}},".rc-virtual-list-holder-inner":{alignItems:"flex-start"}}})),rl=({errorMessage:e})=>{const{t}=j.useTranslation();return e?r.jsx(o.Text,{color:"red",size:12,children:e}):r.jsx(o.Text,{color:"dimmed",size:12,children:t("filter.widget.common.selector_option_empty")})},Hz=({disabled:e,classNames:t,styles:n,unstyled:s,radius:i,style:a,label:l,value:c,onChange:u,options:d,errorMessage:h,required:p})=>{const{t:f}=j.useTranslation(),{classes:m,cx:y}=Zz({radius:i},{name:"MultiSelectWidget",classNames:t,styles:n,unstyled:s}),[_,k]=g.useState(!1),S=R=>{k(R)},T=_&&(c==null?void 0:c.length)>0,[I,z]=g.useState(""),E=g.useMemo(()=>{if(!I)return d;const R=I.toLowerCase(),K=ye=>{var xe;return((xe=ye.description)==null?void 0:xe.toLowerCase().includes(R))||ye.label.toLowerCase().includes(R)};return d.filter(K)},[I,d]);return r.jsxs(o.Stack,{spacing:3,children:[r.jsxs(o.Group,{position:"apart",children:[r.jsxs(o.Text,{className:m.label,children:[l,p&&r.jsx("span",{className:m.required,"aria-hidden":"true",children:"*"})]}),T&&r.jsx(o.Tooltip,{label:f("filter.widget.common.x_selected",{count:c.length}),children:r.jsx(o.Badge,{children:c.length})})]}),r.jsx(bc,{disabled:e,allowClear:!0,className:y(m.root,"check-select"),dropdownClassName:y(m.dropdown,""),onDropdownVisibleChange:S,transitionName:"rc-select-dropdown-slide-up",choiceTransitionName:"rc-select-selection__choice-zoom",style:a,clearIcon:()=>r.jsx(o.CloseButton,{}),value:c,onChange:u,onSelect:console.log,mode:"multiple",maxTagCount:0,notFoundContent:r.jsx(rl,{errorMessage:h}),maxTagTextLength:10,maxTagPlaceholder:R=>f("filter.widget.common.x_selected",{count:R.length}),searchValue:I,onSearch:z,filterOption:!1,children:E.map(R=>r.jsxs(bc.Option,{title:R.label,children:[r.jsx(o.Text,{size:"sm","data-role":"label",children:R.label}),R.description&&r.jsx(o.Text,{size:"xs",color:"dimmed","data-role":"description",children:R.description})]},R.value))})]})},eE=D.observer(({label:e,config:t,value:n,onChange:s})=>{const i=Pe(),a=!!t.options_query_id,{state:l,error:c}=i.getDataStuffByID(t.options_query_id),u=l==="loading",d=t.min_width?t.min_width:"200px",h=a?u:!1,p=g.useMemo(()=>t.initialSelection(n),[n,t.initialSelection]),f=m=>s(m,!1);return r.jsx(Hz,{label:e,options:t.options,style:{minWidth:"160px",width:d,maxWidth:h?d:"unset",borderColor:"#e9ecef"},disabled:h,value:[...p],onChange:f,errorMessage:c,required:t.required})}),tE=g.forwardRef(({label:e,description:t,...n},s)=>r.jsx("div",{ref:s,...n,children:r.jsx(o.Group,{noWrap:!0,children:r.jsxs("div",{children:[r.jsx(o.Text,{size:"sm","data-role":"label",children:e}),r.jsx(o.Text,{size:"xs",color:"dimmed","data-role":"description",children:t})]})})})),nE=D.observer(({label:e,config:t,value:n,onChange:s})=>{const i=Pe(),a=!!t.options_query_id,{state:l,error:c}=i.getDataStuffByID(t.options_query_id),u=l==="loading";return r.jsx(o.Select,{label:e,data:t.options,disabled:a?u:!1,value:n,onChange:s,maxDropdownHeight:500,styles:{root:{width:t.width?t.width:"200px"},input:{borderColor:"#e9ecef"}},sx:{".mantine-Select-item[data-selected] .mantine-Text-root[data-role=description]":{color:"rgba(255,255,255,.7)"},".mantine-Select-nothingFound":{fontSize:"0.75rem",textAlign:"left",padding:"4px 10px"}},itemComponent:tE,searchable:!c,nothingFound:r.jsx(rl,{errorMessage:c}),clearable:t.clearable})});function rE({label:e,config:t,value:n,onChange:s}){return r.jsx(o.TextInput,{label:e,value:n||"",onChange:i=>s(i.currentTarget.value),...t,styles:{input:{borderColor:"#e9ecef"}}})}const sE=({rotate:e,onClick:t})=>r.jsx("svg",{onClick:t,className:"caret-icon",viewBox:"0 0 1024 1024",focusable:"false","data-icon":"caret-down",width:"14px",height:"14px",fill:"currentColor","aria-hidden":"true",transform:`rotate(${e})`,children:r.jsx("path",{d:"M840.4 300H183.6c-19.7 0-30.7 20.8-18.5 35l328.4 380.8c9.4 10.9 27.5 10.9 37 0L858.9 335c12.2-14.2 1.2-35-18.5-35z"})}),iE=({expanded:e,isLeaf:t,value:n,onClick:s,...i})=>(n==="0-0-value"&&console.log(i),t?r.jsx("span",{style:{width:"14px",display:"inline-block"}}):r.jsx(sE,{rotate:e?"0":"-90",onClick:s,...i})),aE=({onClick:e})=>r.jsxs("svg",{onClick:e,className:"checkbox-icon",width:"16",height:"16",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:"2",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),r.jsx("rect",{className:"border",x:"4",y:"4",width:"16",height:"16",rx:"2"}),r.jsx("rect",{className:"checkmark-indeterminate",x:"8",y:"8",width:"8",height:"8",rx:"2",stroke:"none"}),r.jsx("path",{className:"checkmark-checked",d:"M9 12l2 2l4 -4"})]}),oE=({onClick:e,...t})=>r.jsx(aE,{onClick:e,...t}),lE=o.createStyles((e,{radius:t=4})=>({root:{borderRadius:e.fn.radius(t),display:"flex",flexWrap:"nowrap",border:"1px solid #ced4da",paddingLeft:"0px",paddingRight:"30px",backgroundColor:"#fff",transition:"border-color 100ms ease",borderColor:"#e9ecef","&.rc-tree-select.rc-tree-select-open":{borderColor:"#228be6 !important",".rc-tree-select-selection-overflow-item-rest":{display:"none"},".rc-tree-select-selection-overflow-item-suffix":{display:"block"}},".rc-tree-select-selector":{height:"auto",lineHeight:1.55,paddingLeft:"12px",resize:"none",boxSizing:"border-box",fontSize:"14px",width:"100%",color:"#000",display:"block",textAlign:"left",minHeight:"36px",cursor:"pointer",flexGrow:1},".rc-tree-select-selection-search-mirror":{display:"none"},".rc-tree-select-selection-search":{flexGrow:1,width:"auto !important"},".rc-tree-select-selection-overflow":{display:"flex",minHeight:"34px",alignItems:"center",flexWrap:"nowrap",marginLeft:"calc(-10px / 2)",boxSizing:"border-box"},".rc-tree-select-selection-overflow-item":{display:"flex",alignItems:"center",backgroundColor:"#f1f3f5",color:"#495057",height:"24px",paddingLeft:"12px",paddingRight:"12px",fontWeight:500,fontSize:"12px",borderRadius:"4px",cursor:"default",userSelect:"none",maxWidth:"calc(100% - 20px)",margin:"calc(10px / 2 - 2px) calc(10px / 2)"},".rc-tree-select-selection-overflow-item-rest":{cursor:"pointer"},".rc-tree-select-selection-overflow-item-suffix":{display:"none",backgroundColor:"transparent",width:"100%",maxWidth:"100%",height:"28px",margin:0,paddingLeft:0,paddingRight:0},input:{flex:1,minWidth:"60px",backgroundColor:"transparent",border:0,outline:0,fontSize:"14px",padding:0,marginLeft:0,color:"inherit",height:"28px",lineHeight:"32px",cursor:"pointer",width:"100%","&::-webkit-search-decoration, &::-webkit-search-cancel-button, &::-webkit-search-results-button, &::-webkit-search-results-decoration":{display:"none"}},".rc-tree-select-clear":{marginRight:"-24px",alignSelf:"center",cursor:"pointer"},"&.rc-tree-select-disabled":{backgroundColor:"rgb(241, 243, 245)",color:"rgb(144, 146, 150)",opacity:.6,"&, .rc-tree-select-selector, input":{cursor:"not-allowed"}}},label:{fontSize:e.fontSizes.sm,fontWeight:500,color:"#212529"},required:{color:"#fa5252",paddingLeft:"3px"},dropdown:{fontSize:e.fontSizes.xs,zIndex:300,paddingTop:"6px","&.rc-tree-select-dropdown-slide-up-leave-active":{display:"none"},".rc-tree-select-tree-list .rc-tree-select-tree-list-holder":{},".rc-tree-select-tree-list, .rc-tree-select-empty":{backgroundColor:"#fff",border:"1px solid #e9ecef",padding:0,boxShadow:"0 1px 3px rgb(0 0 0 / 5%), rgb(0 0 0 / 5%) 0px 10px 15px -5px, rgb(0 0 0 / 4%) 0px 7px 7px -5px",borderRadius:"4px"},".rc-tree-select-empty":{padding:"8px 12px"},".rc-tree-select-tree-treenode":{boxSizing:"border-box",textAlign:"left",width:"100%",padding:"8px 12px",cursor:"pointer",fontSize:"14px",color:"#000",borderRadius:"4px",display:"flex",flexWrap:"nowrap",overflow:"hidden","&:hover":{backgroundColor:"#f1f3f5"},"&.rc-tree-select-tree-treenode-checkbox-checked":{".rc-tree-select-tree-iconEle .checkbox-icon .checkmark-checked":{stroke:"rgb(64, 192, 87)",animation:"check 200ms linear forwards"}},"&.rc-tree-select-tree-treenode-checkbox-indeterminate":{".rc-tree-select-tree-iconEle .checkbox-icon .checkmark-indeterminate":{fill:"rgb(64, 192, 87)"}},".rc-tree-select-tree-switcher":{height:"16px",alignSelf:"center",paddingRight:"2px",transition:"color 200ms ease","&:hover":{color:"#228be6","svg.caret-icon":{color:"#228be6"}},"svg.caret-icon":{color:"#ced4da",transition:"all 200ms ease"}},".rc-tree-select-tree-node-content-wrapper":{display:"flex",flexWrap:"nowrap",overflow:"hidden",alignItems:"center",gap:"8px",transition:"color 200ms ease","&:hover":{color:"#228be6"}},".rc-tree-select-tree-iconEle":{height:"16px","svg .border":{stroke:"#ced4da"},".checkbox-icon .checkmark-indeterminate":{fill:"transparent",transition:"fill 200ms ease"},".checkbox-icon .checkmark-checked":{transform:"scale(1.2)",transformOrigin:"center center",strokeDasharray:10,strokeDashoffset:-10},"@keyframes check":{"0%":{strokeDashoffset:10},"100%":{strokeDashoffset:0}}},".rc-tree-select-tree-title":{textOverflow:"ellipsis",whiteSpace:"nowrap",overflow:"hidden",".rc-tree-select-tree-title-desc":{fontSize:"12px",maxWidth:"100%",textOverflow:"ellipsis",whiteSpace:"nowrap",overflow:"hidden"}},".rc-tree-select-tree-indent":{flexGrow:0,height:0,verticalAlign:"bottom"},".rc-tree-select-tree-indent-unit":{display:"inline-block",width:"1em"}}}})),cE=({disabled:e,classNames:t,styles:n,unstyled:s,radius:i,style:a,label:l,value:c,onChange:u,treeData:d,errorMessage:h,required:p,treeCheckStrictly:f})=>{const{t:m}=j.useTranslation(),{classes:y,cx:_}=lE({radius:i},{name:"FilterTreeSelectWidget",classNames:t,styles:n,unstyled:s}),[k,S]=g.useState(!1),T=z=>{S(z)},I=k&&(c==null?void 0:c.length)>0;return r.jsxs(o.Stack,{spacing:3,children:[r.jsxs(o.Group,{position:"apart",children:[r.jsxs(o.Text,{className:y.label,children:[l,p&&r.jsx("span",{className:y.required,"aria-hidden":"true",children:"*"})]}),I&&r.jsx(o.Tooltip,{label:m("filter.widget.common.x_selected",{count:c.length}),children:r.jsx(o.Badge,{children:c.length})})]}),r.jsx(vc,{disabled:e,allowClear:!0,treeCheckStrictly:f,labelInValue:!0,className:_(y.root,"check-select"),dropdownClassName:_(y.dropdown,""),onDropdownVisibleChange:T,transitionName:"rc-tree-select-dropdown-slide-up",choiceTransitionName:"rc-tree-select-selection__choice-zoom",style:a,listHeight:510,treeLine:!0,clearIcon:()=>r.jsx(o.CloseButton,{}),switcherIcon:iE,treeIcon:oE,maxTagTextLength:10,value:c,treeData:d,notFoundContent:r.jsx(rl,{errorMessage:h}),treeNodeFilterProp:"filterBasis",treeCheckable:!0,showCheckedStrategy:vc.SHOW_PARENT,onChange:u,onSelect:console.log,maxTagCount:0,maxTagPlaceholder:()=>m("filter.widget.common.x_selected",{count:c.length})})]})},uE=D.observer(({label:e,config:t,value:n,onChange:s})=>{const{treeData:i,treeDataLoading:a,errorMessage:l}=t,c=f=>{const m=f.map(y=>y.value);s(m,!1)},u=g.useMemo(()=>t.initialSelection(n),[n,t.initialSelection]),d=t.min_width?t.min_width:"200px",p=!!t.options_query_id?a:!1;return r.jsx(cE,{disabled:p,style:{minWidth:"160px",width:d,maxWidth:p?d:"unset",borderColor:"#e9ecef"},value:[...u],onChange:c,treeData:i,errorMessage:l,label:e,required:t.required,treeCheckStrictly:t.treeCheckStrictly})}),dE=D.observer(({filter:{type:e,config:t,key:n,...s},formFieldProps:i})=>{switch(e){case"select":return r.jsx(nE,{...s,...i,config:t});case"multi-select":return r.jsx(eE,{...s,...i,config:t});case"tree-select":return r.jsx(uE,{...s,...i,config:t});case"text-input":return r.jsx(rE,{...s,...i,config:t});case"date-range":return r.jsx(Hh,{...s,...i,config:t});case"checkbox":return r.jsx(Qz,{...s,...i,config:t});default:return null}}),pE=D.observer(g.forwardRef(({filter:e,...t},n)=>r.jsx("div",{className:"filter-root",ref:n,children:r.jsx(Re,{children:r.jsx(dE,{filter:e,formFieldProps:t})})}))),hE=({disabled:e})=>{const{searchButtonProps:t}=Su(),{children:n="Search",type:s,...i}=t;return r.jsx(o.Button,{color:"blue",size:"sm",type:"submit",...i,disabled:e||i.disabled,children:n})};function fE(e){const t=re();g.useEffect(()=>{var n,s;(s=(n=t.filters).updatePreviewValues)==null||s.call(n,e)},[e])}const gE=({opened:e,toggle:t})=>{const{t:n}=j.useTranslation();return r.jsx(o.Group,{position:"right",ml:-4,mt:-4,mb:e?4:0,children:r.jsx(o.Button,{size:"xs",compact:!0,variant:"subtle",color:e?"gray":"blue",leftIcon:e?r.jsx(M.IconChevronsUp,{size:14}):r.jsx(M.IconChevronsDown,{size:14}),onClick:t,children:n(e?"filter.hide_filters":"filter.show_filters")})})},ef=D.observer(function({view:t}){const[n,{toggle:s}]=Se.useDisclosure(!0),i=Pe(),{control:a,handleSubmit:l,reset:c}=b.useForm({defaultValues:i.filters.values,reValidateMode:"onBlur"}),u=b.useWatch({control:a});g.useEffect(()=>{c(i.filters.values)},[i.filters.values,c]),fE(u);const d=i.filters.visibleInView(t.id),h=g.useMemo(()=>d.every(y=>y.should_auto_submit),[d]),p=g.useMemo(()=>d.filter(y=>v.get(y,"config.required",!1)),[d]),f=g.useMemo(()=>p.length===0?!1:p.some(y=>!y.requiredAndPass(u[y.key])),[u,p]);if(d.length===0)return null;const m=(y,_)=>(k,S)=>{_(k),(y.should_auto_submit||S)&&i.filters.setValueByKey(y.key,k)};return r.jsxs("form",{onSubmit:l(i.filters.setValues),children:[r.jsx(gE,{opened:n,toggle:s}),r.jsx(o.Collapse,{in:n,children:r.jsxs(o.Group,{className:"dashboard-filters",position:"apart",noWrap:!0,sx:h?{}:{border:"1px solid #e9ecef",borderRadius:"4px",padding:"16px"},children:[r.jsx(o.Group,{align:"flex-start",children:d.map(y=>r.jsx(b.Controller,{name:y.key,control:a,render:({field:_})=>r.jsx(pE,{filter:y,value:_.value,onChange:m(y,_.onChange)})},y.id))}),!h&&r.jsx(o.Group,{sx:{alignSelf:"flex-end"},children:r.jsx(hE,{disabled:f})})]})})]})}),mE={viewPanelInFullScreen:v.noop,inFullScreen:!1},pi=g.createContext(mE),sl=x.types.model("MockContextMeta",{current:x.types.optional(x.types.frozen(),{})}).views(e=>({get keys(){return Object.keys(e.current)},get keySet(){return new Set(this.keys)},get entries(){return Object.entries(e.current)}})).actions(e=>({replace(t){e.current=t},defaults(t){e.current={...t,...e.current}},get(t){return e.current[t]},set(t,n){e.current[t]=n}}));function il(e){return{current:e}}const xE=x.types.model("PanelStyleBorderMeta",{enabled:x.types.boolean}).views(e=>({get json(){const{enabled:t}=e;return{enabled:t}}})).actions(e=>({setEnabled(t){e.enabled=t}})),tf=x.types.model("PanelStyleMeta",{border:xE}).views(e=>({get json(){const{border:t}=e;return{border:t.json}}})).actions(e=>({})),nf=x.types.model("PanelTitleMeta",{show:x.types.optional(x.types.boolean,!0)}).views(e=>({get json(){const{show:t}=e;return{show:t}}})).actions(e=>({setShow(t){e.show=t}})),rf=x.types.model("VariableMeta",{name:x.types.string,size:x.types.string,weight:x.types.string,color:x.types.union(x.types.model({type:x.types.literal("static"),staticColor:x.types.string}),x.types.model({type:x.types.literal("continuous"),valueRange:x.types.array(x.types.number),colorRange:x.types.array(x.types.string)}),x.types.model({type:x.types.literal("piecewise")})),formatter:x.types.model({output:x.types.enumeration("Output",["number","percent"]),average:x.types.optional(x.types.boolean,!1),mantissa:x.types.number,trimMantissa:x.types.optional(x.types.boolean,!1),absolute:x.types.optional(x.types.boolean,!1)}),data_field:x.types.string,aggregation:x.types.union(x.types.model({type:x.types.enumeration(["none","sum","mean","median","min","max","CV","std"]),config:x.types.frozen(),fallback:x.types.optional(x.types.string,"0")}),x.types.model({type:x.types.literal("quantile"),config:x.types.model({p:x.types.number}),fallback:x.types.optional(x.types.string,"0")}),x.types.model({type:x.types.literal("pick_record"),config:x.types.model({method:x.types.enumeration("Pick Record Method",["first","last"])}),fallback:x.types.optional(x.types.string,"0")}),x.types.model({type:x.types.literal("custom"),config:x.types.model({func:x.types.string}),fallback:x.types.optional(x.types.string,"0")}))}).views(e=>({get json(){const{name:t,size:n,weight:s,color:i,formatter:a,data_field:l,aggregation:c}=e;return v.cloneDeep({name:t,size:n,color:i,weight:s,formatter:a,data_field:l,aggregation:c})}})),sf=x.types.model("PanelVizMeta",{type:x.types.string,conf:x.types.frozen()}).views(e=>({get json(){return{conf:e.conf,type:e.type}}})).actions(e=>({setType(t){e.type=t},setConf(t){e.conf=t}})),af=x.types.model({id:x.types.string,name:x.types.optional(x.types.string,""),title:nf,description:x.types.string,queryIDs:x.types.array(x.types.string),viz:sf,style:tf,variables:x.types.optional(x.types.array(rf),[])}).views(e=>({get json(){const{id:t,name:n,title:s,description:i,queryIDs:a}=e;return{id:t,viz:e.viz.json,name:n,style:e.style.json,title:s.json,queryIDs:[...a],variables:e.variables.map(l=>l.json),description:i}},get queryIDSet(){return new Set(e.queryIDs)}})).actions(e=>({setID(t){e.id=t},setName(t){e.name=t},setDescription(t){e.description=t},addQueryID(t){e.queryIDSet.has(t)||e.queryIDs.push(t)},removeQueryID(t){if(!e.queryIDSet.has(t))return;const n=new Set(e.queryIDSet);n.delete(t),e.queryIDs=x.cast(Array.from(n))},setQueryIDs(t){e.queryIDs=x.cast(t)},addVariable(t){e.variables.push(t)},removeVariable(t){e.variables.remove(t)}}));var Ee=(e=>(e.Postgresql="postgresql",e.MySQL="mysql",e.HTTP="http",e.Transform="transform",e))(Ee||{});const of=x.types.model("QueryMeta",{id:x.types.string,name:x.types.string,type:x.types.enumeration("DataSourceType",[Ee.Postgresql,Ee.MySQL,Ee.HTTP,Ee.Transform]),key:x.types.string,sql:x.types.string,pre_process:x.types.optional(x.types.string,""),post_process:x.types.optional(x.types.string,""),run_by:x.types.optional(x.types.array(x.types.string),[]),react_to:x.types.optional(x.types.array(x.types.string),[]),dep_query_ids:x.types.optional(x.types.array(x.types.string),[])}).views(e=>({get valid(){return e.id&&e.type&&e.key&&e.name?e.type===Ee.HTTP?!!e.pre_process:!!e.sql:!1},get json(){const{id:t,name:n,type:s,key:i,sql:a,run_by:l,react_to:c,pre_process:u,post_process:d,dep_query_ids:h}=e;return cr({id:t,key:i,sql:a,name:n,type:s,run_by:l,react_to:c,pre_process:u,post_process:d,dep_query_ids:h})}})).actions(e=>({setName(t){e.name=t},setKey(t){e.key=t},setType(t){e.type=t},setSQL(t){e.sql=t},setRunBy(t){e.run_by.length=0,e.run_by.push(...t)},setReactTo(t){e.react_to.length=0,e.react_to.push(...t)},setPreProcess(t){e.pre_process=t},setPostProcess(t){e.post_process=t},setDependantQueryIDs(t){e.dep_query_ids.length=0,e.dep_query_ids.push(...t)}})),lf=x.types.model("LayoutItemMeta",{id:x.types.identifier,panelID:x.types.string,x:x.types.number,y:x.types.maybeNull(x.types.number),w:x.types.number,h:x.types.number,moved:x.types.optional(x.types.boolean,!1),static:x.types.optional(x.types.boolean,!1)}).views(e=>({get json(){const{id:t,panelID:n,x:s,y:i,w:a,h:l,moved:c}=e;return{h:l,w:a,x:s,y:i===null?0:i,id:t,moved:c,static:e.static,panelID:n}},get contentModel(){return x.getRoot(e).content},get panel(){const{panelID:t}=e;return this.contentModel.panels.findByID(t)},get layoutProperies(){const{id:t,x:n,y:s,w:i,h:a,moved:l}=e;return{id:t,i:t,x:n,y:s===null?1/0:s,w:i,h:a,moved:l,static:e.static}}})).actions(e=>({set(t){const{isDraggable:n,x:s,y:i,w:a,h:l,moved:c}=t;e.x=s,e.y=i,e.w=a,e.h=l,e.moved=!!c,e.static=!!t.static},setWidth(t){e.w=t},setHeight(t){e.h=t}})),cf=x.types.model("LayoutSetMeta",{id:x.types.identifier,name:x.types.string,breakpoint:x.types.number,list:x.types.optional(x.types.array(lf),[])}).views(e=>({get contentModel(){return x.getRoot(e).content},get json(){const{id:t,name:n,breakpoint:s,list:i}=e;return{id:t,name:n,breakpoint:s,list:i.map(a=>cr(a.json))}},jsonByPanelIDSet(t){const{id:n,name:s,breakpoint:i,list:a}=e;return{id:n,name:s,breakpoint:i,list:a.filter(l=>t.has(l.panelID)).map(l=>cr(l.json))}},findByID(t){return e.list.find(n=>n.id===t)},findByPanelID(t){return e.list.find(n=>n.panelID===t)}})).actions(e=>({setName(t){e.name=t},setBreakpoint(t){e.breakpoint=t},addLayout(t){e.list.push(t)},addNewLayout(t){e.list.push({id:on.v4(),panelID:t,x:0,y:1/0,w:18,h:300,static:!1,moved:!1})},removeByPanelID(t){const n=e.list.findIndex(s=>s.panelID===t);n>=0&&e.list.splice(n,1)},updateLayoutItem(t){const n=e.list.find(s=>s.id===t.i);if(!n){console.error("Trying to update a layout that doesn't exist"),console.log({strangeLayoutItem:t});return}n.set(t)}})).actions(e=>({afterCreate(){x.addDisposer(e,ae.reaction(()=>{const t=e.list.length,n=e.contentModel.panels.list.length;return{match:t===n,layoutCount:t,panelCount:n}},({match:t,panelCount:n,layoutCount:s})=>{if(t)return;const i={id:"layout panel count mismatch",title:"Error detected, please don't save changes.",message:`${s} layout items against and ${n} panels.`,color:"red",autoClose:!1};Yt.showNotification(i),Yt.updateNotification(i)},{fireImmediately:!0,delay:0}))}})),uf=x.types.model("SQLSnippetMeta",{key:x.types.string,value:x.types.string}).views(e=>({get json(){const{key:t,value:n}=e;return{key:t,value:n}}})).actions(e=>({setKey(t){e.key=t},setValue(t){e.value=t}}));var Ce=(e=>(e.Select="select",e.MultiSelect="multi-select",e.TreeSelect="tree-select",e.TextInput="text-input",e.Checkbox="checkbox",e.DateRange="date-range",e))(Ce||{});const al=x.types.model("FilterCheckboxConfigMeta",{_name:x.types.literal("checkbox"),description:x.types.optional(x.types.string,""),default_value:x.types.boolean}).views(e=>({get json(){const{_name:t,description:n,default_value:s}=e;return{_name:t,description:n,default_value:s}},get isDescriptionEmpty(){const{description:t}=e;return t===""||t==="<p></p>"}})).actions(e=>({setDefaultValue(t){e.default_value=t},setDescription(t){e.description=t}})),df=()=>al.create({_name:"checkbox",description:"",default_value:!1});function pf(e,t){return e.map(n=>{try{return n?P.tz(n,"UTC").format(t):null}catch{return console.log(`[date-range] failed parsing ${n}`),null}})}const yE=x.types.model("FilterDateRangeConfigMeta",{_name:x.types.literal("date-range"),required:x.types.boolean,inputFormat:x.types.enumeration("DateRangeInputFormat",["YYYY","YYYYMM","YYYYMMDD","YYYY-MM","YYYY-MM-DD"]),default_value:x.types.optional(x.types.array(x.types.union(x.types.string,x.types.null)),[null,null]),default_shortcut:x.types.optional(x.types.string,""),clearable:x.types.boolean,max_days:x.types.optional(x.types.number,0),allowSingleDateInRange:x.types.optional(x.types.boolean,!1)}).views(e=>({get json(){const{_name:t,max_days:n,required:s,clearable:i,inputFormat:a,default_value:l,default_shortcut:c,allowSingleDateInRange:u}=e;return{_name:t,max_days:n,required:s,clearable:i,inputFormat:a,default_value:pf(l,a),default_shortcut:c,allowSingleDateInRange:u}},truthy(t){return Array.isArray(t)&&t.length===2&&t.every(n=>!!n)},get filter(){return x.getParent(e)}})).actions(e=>({setFilterValue(t){try{e.filter.setValue(t)}catch(n){console.error(n)}}})).actions(e=>({setRequired(t){e.required=t},setClearable(t){e.clearable=t},setInputFormat(t){e.inputFormat=t},setDefaultValue(t){e.default_value.length=0,e.default_value.push(...t),e.setFilterValue(t)},setDefaultShortcut(t){if(e.default_shortcut=t,!t)return;const n=Jh(e.default_shortcut);if(console.log(n),n){const s=n.map(i=>P(i).format(e.inputFormat));e.setFilterValue(s)}},setMaxDays(t){e.max_days=t,t>0&&(e.clearable=!0)},setAllowSingleDateInRange(t){e.allowSingleDateInRange=t}})),ol=x.types.snapshotProcessor(yE,{preProcessor({default_value:e,...t}){return{...t,default_value:e.map(n=>n===null?null:P.tz(n,"UTC").toISOString())}},postProcessor(e){const{default_value:t,...n}=e;return{...n,default_value:pf(t,n.inputFormat)}}}),hf=()=>ol.create({_name:"date-range",required:!1,inputFormat:"YYYY-MM-DD",clearable:!1,default_value:[null,null]}),bE=x.types.model({label:x.types.string,value:x.types.string}).actions(e=>({setLabel(t){e.label=t},setValue(t){e.value=t}})),ll=x.types.model("FilterConfigModel_BaseSelect",{static_options:x.types.optional(x.types.array(bE),[]),options_query_id:x.types.optional(x.types.string,""),default_selection_count:x.types.optional(x.types.number,0),required:x.types.optional(x.types.boolean,!1)}).views(e=>({get contentModel(){return x.getRoot(e).content},get filter(){return x.getParent(e)},get usingQuery(){return!!e.options_query_id}})).views(e=>({get optionsLoading(){if(!e.usingQuery)return!1;const{state:t}=e.contentModel.getDataStuffByID(e.options_query_id);return t==="loading"},get options(){if(!e.usingQuery)return e.static_options;const{data:t,state:n}=e.contentModel.getDataStuffByID(e.options_query_id);return n==="error"?[]:Array.isArray(t)?t.filter(s=>"label"in s&&"value"in s):[]}})).actions(e=>({setRequired(t){e.required=t},addStaticOption(t){e.static_options.push(t)},removeStaticOption(t){e.static_options.splice(t,1)},setDefaultSelectionCount(t){e.default_selection_count=t},setOptionsQueryID(t){e.options_query_id=t??""}})),cl=x.types.compose("FilterMultiSelectConfigMeta",x.types.model({_name:x.types.literal("multi-select"),min_width:x.types.optional(x.types.string,""),default_value:x.types.optional(x.types.array(x.types.string),[])}),ll).views(e=>({get json(){const{_name:t,default_value:n,required:s,min_width:i,static_options:a,options_query_id:l,default_selection_count:c}=e;return cr({_name:t,required:!!s,min_width:i,default_value:n,static_options:a,options_query_id:l,default_selection_count:c})},get defaultSelection(){const t=e.filter.formattedDefaultValue;return Array.isArray(t)&&t.length>0||!e.usingQuery?t:e.options.slice(0,e.default_selection_count).map(n=>n.value)},initialSelection(t){return t||this.defaultSelection},truthy(t){return Array.isArray(t)&&t.length>0}})).actions(e=>({setDefaultValue(t){e.default_value=x.cast(t)},setMinWidth(t){e.min_width=t},setDefaultSelection(){if(e.optionsLoading)return;const t=new Set(e.options.map(i=>i.value)),s=(e.filter.value??[]).filter(i=>t.has(i));s.length>0?e.filter.setValue(s):e.filter.setValue(e.defaultSelection)}})).actions(e=>({afterCreate(){x.addDisposer(e,ae.reaction(()=>ae.toJS(e.defaultSelection),e.setDefaultSelection,{fireImmediately:!1,delay:0}))}})),ff=()=>cl.create({_name:"multi-select",default_value:[],static_options:[],options_query_id:"",default_selection_count:0}),ul=x.types.compose("FilterConfigModel_Select",x.types.model({_name:x.types.literal("select"),default_value:x.types.string,width:x.types.optional(x.types.string,""),clearable:x.types.optional(x.types.boolean,!1)}),ll).views(e=>({get json(){const{_name:t,clearable:n,default_value:s,required:i,width:a,static_options:l,options_query_id:c,default_selection_count:u}=e;return cr({_name:t,width:a,required:i,clearable:n,default_value:s,static_options:l,options_query_id:c,default_selection_count:u})},truthy(t){return!!t},getSelectOption(t){return e.options.find(n=>n.value===t)},get default_selection(){return e.usingQuery?e.default_selection_count>0&&e.options.length>0?e.options[0].value:"":e.filter.formattedDefaultValue}})).actions(e=>({setDefaultValue(t){e.default_value=t},setWidth(t){e.width=t},setClearable(t){e.clearable=t},setDefaultSelection(){var s;const t=e.filter.value,n=(s=e.options.find(i=>i.value===t))==null?void 0:s.value;n?e.filter.setValue(n):e.filter.setValue(e.default_selection)}})).actions(e=>({afterCreate(){x.addDisposer(e,ae.reaction(()=>ae.toJS(e.default_selection),e.setDefaultSelection,{fireImmediately:!1,delay:0}))}})),gf=()=>ul.create({_name:"select",required:!1,default_value:"",static_options:[],options_query_id:"",default_selection_count:0}),dl=x.types.model("FilterTextInputConfigMeta",{_name:x.types.literal("text-input"),required:x.types.boolean,default_value:x.types.string}).views(e=>({get json(){const{_name:t,required:n,default_value:s}=e;return{_name:t,required:n,default_value:s}},truthy(t){return typeof t!="string"?!1:!!t.trim()}})).actions(e=>({setRequired(t){e.required=t},setDefaultValue(t){e.default_value=t}})),pl=()=>dl.create({_name:"text-input",required:!1,default_value:""});function vE(e){return Hg.arrayToTree(e,{id:"value",parentId:"parent_value",childrenField:"children",dataField:null})}function _E(e){return e.map(t=>{const{label:n,description:s,...i}=t,a={...i,filterBasis:`${n}___${s??""}`,description:s,label:n};return s&&(a.label=g.createElement("div",{},[g.createElement(o.Text,{key:0,title:t.label},t.label),g.createElement(o.Text,{key:1,className:"rc-tree-select-tree-title-desc",color:"dimmed",title:t.description},t.description)])),a})}const hl=x.types.compose("FilterTreeSelectConfigMeta",x.types.model({_name:x.types.literal("tree-select"),min_width:x.types.optional(x.types.string,""),default_value:x.types.optional(x.types.array(x.types.string),[]),treeCheckStrictly:x.types.optional(x.types.boolean,!1)}),ll).views(e=>({get json(){const{_name:t,default_value:n,required:s,min_width:i,static_options:a,options_query_id:l,default_selection_count:c,treeCheckStrictly:u}=e;return{_name:t,required:!!s,min_width:i,default_value:n,static_options:a,options_query_id:l,treeCheckStrictly:u,default_selection_count:c}},get plainData(){const{data:t}=e.contentModel.getDataStuffByID(e.options_query_id);return t},get treeData(){const t=this.plainData,n=_E(t);return vE(n)},get errorMessage(){const{error:t}=e.contentModel.getDataStuffByID(e.options_query_id);return t},get treeDataLoading(){const{state:t}=e.contentModel.getDataStuffByID(e.options_query_id);return t==="loading"},get defaultSelection(){const t=e.filter.formattedDefaultValue;if(Array.isArray(t)&&t.length>0)return t;const{default_selection_count:n}=e;return n?this.treeData.slice(0,n).map(i=>i.value):[]},valueObjects(t){const n=new Set(t);return this.plainData.filter(s=>n.has(s.value))},initialSelection(t){return t?this.valueObjects(t):this.valueObjects(this.defaultSelection)},truthy(t){return Array.isArray(t)&&t.length>0}})).actions(e=>({setDefaultValue(t){e.default_value=x.cast(t)},setMinWidth(t){e.min_width=t},setTreeCheckStrictly(t){e.treeCheckStrictly=t},applyDefaultSelection(){const t=e.filter.value,n=new Set(e.plainData.map(i=>i.value)),s=(t??[]).filter(i=>n.has(i));s.length>0?e.filter.setValue(s):e.filter.setValue(e.defaultSelection)},afterCreate(){x.addDisposer(e,ae.reaction(()=>JSON.stringify(e.defaultSelection),this.applyDefaultSelection,{fireImmediately:!0,delay:0}))}})),mf=()=>hl.create({_name:"tree-select",default_value:[],static_options:[],options_query_id:"",default_selection_count:0}),fl=x.types.model("FilterMeta",{id:x.types.identifier,key:x.types.string,label:x.types.string,order:x.types.number,visibleInViewsIDs:x.types.array(x.types.string),auto_submit:x.types.optional(x.types.boolean,!1),default_value_func:x.types.optional(x.types.string,""),type:x.types.enumeration("DashboardFilterType",[Ce.Select,Ce.MultiSelect,Ce.TreeSelect,Ce.TextInput,Ce.Checkbox,Ce.DateRange]),config:x.types.union(ul,cl,hl,dl,al,ol)}).views(e=>({get contentModel(){return x.getRoot(e).content},get filters(){return this.contentModel.filters},get value(){return this.filters.values[e.key]},get plainDefaultValue(){const t=e.config.default_value;return Array.isArray(t)?[...t]:t},get usingDefaultValue(){return e.type!==Ce.TreeSelect},get usingDefaultValueFunc(){return!!e.default_value_func},get formattedDefaultValue(){return this.filters.formattedDefaultValues[e.key]},get auto_submit_supported(){return[Ce.Select,Ce.Checkbox,Ce.DateRange].includes(e.type)}})).views(e=>({get json(){const{id:t,key:n,label:s,order:i,visibleInViewsIDs:a,default_value_func:l,auto_submit:c,type:u,config:d}=e;return{id:t,key:n,type:u,label:s,order:i,config:d.json,auto_submit:c,visibleInViewsIDs:ae.toJS(a),default_value_func:l}},get visibleInViewsIDSet(){return new Set(e.visibleInViewsIDs)},get should_auto_submit(){return e.auto_submit_supported&&e.auto_submit},requiredAndPass(t){return v.get(e.config,"required",!1)?v.get(e.config,"truthy",()=>!0)(t):!1}})).actions(e=>({setKey(t){e.key=t},setValue(t){e.filters.setValueByKey(e.key,t)},setLabel(t){e.label=t},setOrder(t){e.order=t},setType(t){switch(t){case Ce.Select:e.config=gf();break;case Ce.MultiSelect:e.config=ff();break;case Ce.TreeSelect:e.config=mf();break;case Ce.TextInput:e.config=pl();break;case Ce.Checkbox:e.config=df();break;case Ce.DateRange:e.config=hf();break}e.type=t},setVisibleInViewsIDs(t){e.visibleInViewsIDs.length=0,e.visibleInViewsIDs.push(...t)},setAutoSubmit(t){e.auto_submit=e.auto_submit_supported&&t},setDefaultValueFunc(t){e.default_value_func=t}}));var G=(e=>(e.Division="div",e.Modal="modal",e.Tabs="tabs",e))(G||{});const gl=x.types.model("ViewDivisionConfig",{_name:x.types.literal(G.Division)}).views(e=>({get json(){const{_name:t}=e;return{_name:t}}})),xf=()=>gl.create({_name:G.Division}),jE=x.types.model("CustomModalTitleModel",{enabled:x.types.optional(x.types.boolean,!1),func_content:x.types.optional(x.types.string,"")}).views(e=>({get json(){const{enabled:t,func_content:n}=e;return{enabled:t,func_content:n}},get value(){const{enabled:t,func_content:n}=e,s=x.getParent(e,2),i=x.getRoot(e);if(!t)return s.name;try{const a={filters:i.content.filters.values,context:i.context.current};return new Function(`return ${n}`)()(a)}catch(a){return console.error(a),s.name}}})).actions(e=>({setEnabled(t){e.enabled=t},setFuncContent(t){e.func_content=t},replace({enabled:t,func_content:n}){e.enabled=t,e.func_content=n}})),hi={enabled:!1,func_content:["function text({ filters, context}) {"," // your code goes here",' return "text"',"}"].join(`
470
- `)},ml=x.types.model("ViewModalConfig",{_name:x.types.literal(G.Modal),width:x.types.string,height:x.types.string,custom_modal_title:x.types.optional(jE,hi)}).views(e=>({get json(){const{_name:t,width:n,height:s,custom_modal_title:i}=e;return{_name:t,width:n,height:s,custom_modal_title:i.json}}})).actions(e=>({setWidth(t){e.width=t},setHeight(t){e.height=t}})),yf=()=>ml.create({_name:G.Modal,width:"90vw",height:"90vh"}),wE=x.types.model("ViewTabsTabModel",{id:x.types.identifier,name:x.types.string,view_id:x.types.string,color:x.types.optional(x.types.string,""),order:x.types.optional(x.types.number,0)}).views(e=>({get json(){const{id:t,name:n,view_id:s,color:i,order:a}=e;return{id:t,name:n,color:i,order:a,view_id:s}}})).actions(e=>({setName(t){e.name=t},setViewID(t){e.view_id=t},setColor(t){e.color=t},setOrder(t){e.order=t}})),xl=x.types.model("ViewTabsConfig",{_name:x.types.literal(G.Modal),tabs:x.types.optional(x.types.array(wE),[]),variant:x.types.optional(x.types.enumeration("variant",["default","outline","pills"]),"default"),orientation:x.types.optional(x.types.enumeration("orientation",["horizontal","vertical"]),"horizontal"),grow:x.types.optional(x.types.boolean,!1)}).views(e=>({get json(){const{_name:t,variant:n,orientation:s,tabs:i,grow:a}=e;return{grow:a,tabs:i.map(l=>l.json),_name:t,variant:n,orientation:s}},get tabsInOrder(){return v.sortBy(e.tabs,"order")}})).actions(e=>({setVariant(t){e.variant=t},setOrientation(t){e.orientation=t},setGrow(t){e.grow=t},setTabs(t){e.tabs.length=0,e.tabs=x.cast(t)},addTab(){const t=Se.randomId(),n={id:t,name:t,view_id:""};e.tabs.push(n)},removeTab(t){e.tabs.splice(t,1)}})),bf=()=>xl.create({_name:G.Modal,tabs:[]}),vf=x.types.model({id:x.types.identifier,name:x.types.string,type:x.types.enumeration("EViewComponentType",[G.Division,G.Modal,G.Tabs]),config:x.types.union(gl,ml,xl),panelIDs:x.types.optional(x.types.array(x.types.string),[])}).views(e=>({get json(){const{id:t,name:n,type:s,config:i}=e;return{id:t,name:n,type:s,config:i.json,panelIDs:e.panelIDs.map(a=>a)}}})).actions(e=>({setName(t){e.name=t},setType(t){if(e.type!==t){switch(t){case G.Division:e.config=xf();break;case G.Modal:e.config=yf();break;case G.Tabs:e.config=bf();break}e.type=t}},appendPanelID(t){e.panelIDs.push(t)},appendPanelIDs(t){e.panelIDs.push(...t)},removePanelID(t){const n=e.panelIDs.filter(s=>s!==t);e.panelIDs.length=0,e.panelIDs.push(...n)}})),gn="11.10.0",CE={definition:{sqlSnippets:[],queries:[],mock_context:{}},views:[{id:"Main",name:"Main",type:G.Division,config:{},panelIDs:[]}],panels:[],filters:[],version:gn,layouts:[{id:"basis",name:"basis",list:[],breakpoint:0}]},yl=x.types.model("DataSourceMetaModel",{id:x.types.string,type:x.types.enumeration("DataSourceType",[Ee.HTTP,Ee.MySQL,Ee.Postgresql]),key:x.types.string,config:x.types.frozen()}),_f=x.types.model("DataSourcesMetaModel",{list:x.types.optional(x.types.array(yl),[])}).views(e=>({find({type:t,key:n}){return e.list.find(s=>s.key===n&&s.type===t)},get options(){return e.list.map(t=>({value:t.key,label:t.key}))}})).actions(e=>({replace(t){e.list.length=0,e.list.push(...t)}})),jf=x.types.model({id:x.types.string,content:x.types.string,create_time:x.types.string,update_time:x.types.string,is_preset:x.types.boolean}),bl=x.types.model("GlobalSQLSnippetsMeta",{list:x.types.optional(x.types.array(jf),[])}).views(e=>({find(t){return e.list.find(n=>n.id===t)},get options(){return e.list.map(t=>({value:t.id,label:t.id}))}})).actions(e=>({replace(t){e.list.length=0,e.list.push(...t)}})),fi=x.types.model("ContextMeta",{current:x.types.optional(x.types.frozen(),{})}).views(e=>({get keys(){return Object.keys(e.current)},get entries(){return Object.entries(e.current)}})).actions(e=>({replace(t){e.current=t},get(t){return e.current[t]},set(t,n){e.current[t]=n}}));function vl(e){return fi.create({current:e})}const _l=x.types.compose("ViewRenderModel",vf,x.types.model({tab:x.types.optional(x.types.string,"")})).views(e=>({get tabs(){return e.config.tabs},get tabInfo(){const t=this.tabs.find(n=>n.id===e.tab);return t?{id:t.id,name:t.name}:null},get tabView(){return e.type!==G.Tabs?null:this.tabs.find(t=>t.id===e.tab)},get tabViewID(){return this.tabView?this.tabView.view_id??"":""},get contentModel(){return x.getParent(e,3)},get panels(){if(e.type!==G.Tabs)return this.contentModel.panels.panelsByIDs(e.panelIDs);const t=this.tabViewID,n=this.contentModel.views.findByID(t);return(n==null?void 0:n.panels)??[]},get renderViewIDs(){const t=[e.id];return e.type===G.Tabs&&t.push(this.tabViewID),t},async downloadScreenshot(t){const n=t.offsetWidth*2+10,s=t.offsetHeight*2+10,i=new jc,a=new Date().getTime(),l=await _c.toBlob(t,{bgcolor:"white",width:n,height:s,style:{transformOrigin:"0 0",transform:"scale(2)"}});i.file(`${e.name}_${a}.png`,l),i.file(`dashboard_state_${a}.json`,JSON.stringify(this.contentModel.dashboardState,null,4)),i.generateAsync({type:"blob"}).then(c=>{os.saveAs(c,`${e.name}_${a}.zip`)}).catch(c=>{console.error(c),Yt.notifications.show({color:"red",title:"Failed to download screenshot with dashboard state",message:c.message})})}})).actions(e=>({setTab(t){e.tab=t??""},setTabByTabInfo(t){e.tab=t.id??""}})),jl=x.types.model("ViewsRenderModel",{current:x.types.optional(x.types.array(_l),[]),visibleViewIDs:x.types.array(x.types.string)}).views(e=>({get json(){return e.current.map(t=>cr(t.json))},get idMap(){const t=new Map;return e.current.forEach(n=>{t.set(n.id,n)}),t},findByID(t){return e.current.find(n=>n.id===t)},get firstVisibleView(){const[t]=e.visibleViewIDs;return e.current.find(({id:n})=>n===t)},get visibleViews(){const t=new Set(e.visibleViewIDs);return e.current.filter(({id:n})=>t.has(n))},get firstVisibleTabsView(){return this.visibleViews.find(t=>t.type===G.Tabs)},get firstVisibleTabsViewActiveTab(){const t=this.firstVisibleTabsView;return t?t.tabInfo:null}})).actions(e=>({appendToVisibles(t){new Set(e.visibleViewIDs.map(s=>s)).has(t)||e.visibleViewIDs.push(t)},rmVisibleViewID(t){const n=e.visibleViewIDs.findIndex(s=>s===t);n!==-1&&e.visibleViewIDs.splice(n,1)},setFirstVisibleTabsViewActiveTab(t){if(!t)return;const n=e.firstVisibleTabsView;n==null||n.setTabByTabInfo(t)}}));function wf(e,t){const n=e.length>0?[e[0].id]:[],s=e.map(i=>{const{_name:a=i.type}=i.config,l={...i,tab:"",config:{...i.config,_name:a},panelIDs:i.panelIDs};if(i.type===G.Tabs){const c=v.minBy(i.config.tabs,u=>u.order);l.tab=(c==null?void 0:c.id)??""}return l});return t&&(s[0].tab=t.id),{current:s,visibleViewIDs:n}}const SE=new em.AsyncParser({withBOM:!0});async function Cf(e){return!Array.isArray(e)||e.length===0?"":await SE.parse(e).promise()}async function kE(e,t){const n=await Cf(t),s=new Blob([n],{type:"text/csv"});os.saveAs(s,`${e}.csv`)}function Sf(e){const t=new jc,n=e.map(async({id:s,data:i})=>{const a=await Cf(i);t.file(`${s}.csv`,a)});Promise.all(n).then(()=>{t.generateAsync({type:"blob"}).then(s=>{os.saveAs(s,"dashboard_data.zip")})}).catch(s=>{console.error(s),Yt.notifications.show({color:"red",title:"Failed to download data",message:s.message})})}function fr(e,t){const n=new Blob([t],{type:"application/json"});os.saveAs(n,`${e}.json`)}const wl=af.views(e=>({get contentModel(){return x.getRoot(e).content}})).views(e=>({get queries(){return e.contentModel.queries.findByIDSet(e.queryIDSet)},get firstQuery(){return this.queries.length>0?this.queries[0]:null},get firstQueryData(){return this.firstQuery?this.firstQuery.data:[]},queryByID(t){return this.queries.find(n=>n.id===t)},get data(){return this.queries.reduce((t,n)=>(t[n.id]=n.data,t),{})},get variableStrings(){return Bp(e.variables,this.data)},get variableAggValueMap(){const t={},n=this.data;return e.variables.reduce((s,i)=>(s[i.name]=nn(i,n),s),t),t},get variableValueMap(){const t={},n=this.variableAggValueMap;return e.variables.reduce((s,i)=>(s[i.name]=vt(i,n[i.name]),s),t),t},get variableStyleMap(){const t=this.variableValueMap,n={};return e.variables.reduce((s,i)=>{const a=u_(i.color,t[i.name]);return s[i.name]={color:a,"font-size":i.size,"font-weight":i.weight,variable:i},s},n),n},get dataLoading(){return this.queries.some(t=>t.state==="loading")},get queryStateMessages(){const t=this.queries.filter(a=>!a.runByConditionsMet);if(t.length===0)return"";const n=new Set,s=new Set;t.forEach(a=>{const l=a.conditionNames;l.context.forEach(c=>n.add(c)),l.filters.forEach(c=>s.add(c))});const i=[];return n.size>0&&(console.log(n),i.push(`context: ${Array.from(n).join(", ")}`)),s.size>0&&i.push(`filter${s.size>1?"s":""}: ${Array.from(s).join(", ")}`),i.length===2&&i.splice(1,0,"and"),i.unshift("Waiting for"),i.join(" ")},get queryErrors(){return this.queries.map(t=>t.error).filter(t=>!!t)},get canRenderViz(){return this.queryErrors.length===0&&this.queryStateMessages===""&&!this.dataLoading}})).actions(e=>({refreshData(){e.queries.forEach(t=>t.fetchData(!0))},downloadData(){e.contentModel.queries.downloadDataByQueryIDs(e.queryIDs)},getSchema(){const t=e.json;return t.viz.conf={...t.viz.conf,__INTERACTIONS:{},__OPERATIONS:{},__TRIGGERS:{}},{panel:t,queries:e.queries.map(n=>n.json),layouts:e.contentModel.layouts.jsonByPanelIDSet(new Set([e.id]))}},downloadSchema(){const{panel:t,queries:n,layouts:s}=this.getSchema(),a=JSON.stringify({panels:[t],definition:{queries:n},layouts:s,version:gn},null,2),l=e.name;fr(l,a)}}));function kf(e){return{id:e,name:"Panel",title:{show:!0},description:"<p></p>",queryIDs:[],viz:{type:Wo.name,conf:Wo.createConfig()},style:{border:{enabled:!0}}}}const Cl=x.types.model("PanelsRenderModel",{list:x.types.optional(x.types.array(wl),[])}).views(e=>({get json(){return e.list.map(t=>t.json)},findByID(t){return e.list.find(n=>n.id===t)},get idMap(){const t=new Map;return e.list.forEach(n=>{t.set(n.id,n)}),t}})).views(e=>({panelsByIDs(t){const n=[];return t.forEach(s=>{const i=e.idMap.get(s);i?n.push(i):console.warn(`Panel is not found, id:${s}`)}),n}}));function Tf(e){const t=e.config,n=t.default_value;if(n===void 0)return n;if(t._name==="date-range")try{if(t.default_shortcut){const i=Jh(t.default_shortcut);if(i)return i.map(a=>P(a).format(t.inputFormat))}const[...s]=n;return s.map(i=>i===null?i:P.tz(i,"UTC").format(t.inputFormat)??i)}catch(s){return console.error(s),n}return n}function TE(e,t){const n=e.default_value_func;try{return new Function(`return ${n}`)()(e,At,t)}catch(s){return console.error(s),Tf(e)}}function Df(e,t){var n;return(n=e.default_value_func)!=null&&n.trim()?TE(e,t):Tf(e)}function Mf(e,t){return e.reduce((n,s)=>(n[s.key]=Df(s,t),n),{})}const Sl=x.types.model("FiltersRenderModel",{current:x.types.optional(x.types.array(fl),[]),values:x.types.optional(x.types.frozen(),{})}).views(e=>({get json(){return e.current.map(t=>t.json)},get valuesString(){return JSON.stringify(e.values)},get contentModel(){return x.getRoot(e).content},get context(){return this.contentModel.payloadForSQL.context},get initialValuesDep(){return JSON.stringify({filters:e.current.map(({default_value_func:t,config:n})=>({default_value_func:t,config:n})),context:this.contentModel.payloadForSQL.context})},get formattedDefaultValues(){return Mf(this.json,this.contentModel.context)},get firstID(){if(e.current.length!==0)return e.current[0].id},findByID(t){return e.current.find(n=>n.id===t)},findByIDSet(t){return e.current.filter(n=>t.has(n.id))},get inOrder(){return v.sortBy(e.current,"order")},get empty(){return e.current.length===0},visibleInView(t){return v.sortBy(e.current.filter(n=>n.visibleInViewsIDSet.has(t)),"order")},get firstFilterValueKey(){return Object.keys(e.values)[0]??""},get keySet(){return new Set(e.current.map(t=>t.key))},get keyLabelMap(){return e.current.reduce((t,n)=>(t[n.key]=n.label,t),{})},getSelectOption(t){const n=this.findByID(t);if(!n||!("getSelectOption"in n.config))return null;const s=e.values[n.key];return n.config.getSelectOption(s)}})).actions(e=>({setValues(t){console.debug("⚪️ setting filter values: ",JSON.stringify(t)),e.values=t},patchValues(t){console.debug("⚪️ patching filter values: ",JSON.stringify(t)),e.values=v.defaults({},t,e.values)},setValueByKey(t,n){console.debug(`⚪️ setting filter[${t}] to value: `,JSON.stringify(n)),e.values={...e.values,[t]:n}},applyValuesPatch(t){e.values={...e.values,...t}},getValueByKey(t){return e.values[t]},getSchema(t,n){return{filters:e.findByIDSet(new Set(t)).map(a=>({...a.json,visibleInViewsIDs:n?a.json.visibleInViewsIDs:[]})),version:gn}},downloadSchema(t){const n=JSON.stringify(this.getSchema(t,!1),null,2);fr("Filters",n)}}));function kl(e,t,n,s){const i=v.defaults({},s,Mf(e,{...n,...t}));return{current:e,values:i}}const If=of.views(e=>({get rootModel(){return x.getRoot(e)},get contentModel(){return this.rootModel.content},get conditionOptions(){if(!x.isAlive(e))return[];const{context:t}=this.contentModel.payloadForSQL,n=Object.keys(t).map(l=>({group:"Context",label:l,value:`context.${l}`,description:void 0})),s=this.contentModel.filters.keyLabelOptions.map(l=>({group:"Filters",label:l.label,value:`filters.${l.value}`,description:l.value})),i=[...n,...s],a=new Set(i.map(l=>l.value));return e.run_by.forEach(l=>{a.has(l)||i.push({group:"Invalid",label:l,value:l})}),i},get unmetRunByConditions(){if(!x.isAlive(e))return[];const{run_by:t}=e;if(t.length===0)return[];const n=this.contentModel.payloadForSQL;return t.filter(s=>{const i=v.get(n,s);return Array.isArray(i)?i.length===0:typeof i=="number"?Number.isNaN(i):!i})}})).views(e=>({get payload(){return e.contentModel.payloadForSQL},get formattedSQL(){return Mi(e.sql,this.payload)},get httpConfigString(){const{context:t,filters:n}=this.payload,{name:s,pre_process:i}=e.json,a=b_(i,t,n);return console.groupCollapsed(`Request config for: ${s}`),console.log(a),console.groupEnd(),JSON.stringify(a)},get typedAsSQL(){return[Ee.Postgresql,Ee.MySQL].includes(e.type)},get typedAsHTTP(){return[Ee.HTTP].includes(e.type)},get isTransform(){return e.type===Ee.Transform},get reQueryKey(){const{react_to:t=[]}=e;if(t.length===0)return"";const n=e.contentModel.payloadForSQL,s=[...t].reduce((i,a)=>(i[a]=v.get(n,a),i),{});return JSON.stringify(s)},get runByConditionsMet(){return e.unmetRunByConditions.length===0},get conditionNames(){if(e.unmetRunByConditions.length===0)return{context:[],filters:[]};const{keyLabelMap:t}=e.contentModel.filters,n=e.unmetRunByConditions.filter(i=>i.startsWith("context.")).map(i=>i.replace("context.","")),s=e.unmetRunByConditions.filter(i=>i.startsWith("filters.")).map(i=>v.get({filters:t},i,i.replace("filters.",""))).filter(i=>!!i);return{context:n,filters:s}},get queries(){return x.getParent(e,2)},get inUse(){return this.queries.isQueryInUse(e.id)},get dependencies(){if(!this.typedAsSQL)return[];const t=v.uniq(e.sql.match(Xs.sqlSnippet)),n=v.uniq(e.sql.match(Xs.filter)),s=v.uniq(e.sql.match(Xs.context)),i=[];return t.forEach(a=>{i.push({type:"sql_snippet",key:a,valid:e.contentModel.sqlSnippets.keySet.has(a)})}),n.forEach(a=>{i.push({type:"filter",key:a,valid:e.contentModel.filters.keySet.has(a)})}),s.forEach(a=>{i.push({type:"context",key:a,valid:e.contentModel.mock_context.keySet.has(a)})}),i}})),Tl=x.types.compose("QueryRenderModel",If,x.types.model({state:x.types.optional(x.types.enumeration(["idle","loading","error"]),"idle"),data:x.types.optional(x.types.frozen([]),[]),error:x.types.frozen()})).views(e=>({get datasource(){const{key:t,type:n}=e;return e.rootModel.datasources.find({type:n,key:t})},get additionalQueryInfo(){return e.contentModel.getAdditionalQueryInfo(e.id)},get depQueryModels(){return e.contentModel.queries.findByIDSet(new Set(e.dep_query_ids))},get depQueryModelStates(){return this.depQueryModels.map(t=>t.state)},get depQueryModelStatesString(){return this.depQueryModelStates.toString()}})).views(e=>({get stateMessage(){if(e.state!=="idle")return"";if(!e.runByConditionsMet){const{context:t,filters:n}=e.conditionNames;if(t.length===0&&n.length===0)return"Waiting";const s=[];return t.length>0&&s.push(`context: ${t.join(", ")}`),n.length>0&&s.push(`filter${n.length>1?"s":""}: ${n.join(", ")}`),s.length===2&&s.splice(1,0,"and"),s.unshift("Waiting for"),s.join(" ")}return e.data.length>0?"":"Empty Data"}})).volatile(()=>({controller:new AbortController})).actions(e=>({runSQL:x.flow(function*(){var t;if(e.valid&&((t=e.controller)==null||t.abort(),!!e.runByConditionsMet)){e.controller=new AbortController,e.state="loading";try{const n=e.payload;e.data=yield*x.toGenerator(T_({payload:n,name:e.name,query:e.json,additionals:e.additionalQueryInfo},e.controller.signal)),e.state="idle",e.error=null}catch(n){if(!Rt.isCancel(n)){e.data=[];const s=v.get(n,"message","unkown error");e.error=v.get(n,"response.data.detail.message",s),e.state="error"}}}}),runHTTP:x.flow(function*(){var t;if(!(!e.valid||!e.datasource)&&((t=e.controller)==null||t.abort(),!!e.runByConditionsMet)){e.controller=new AbortController,e.state="loading";try{const{type:n,key:s,post_process:i}=e.json;let a=JSON.parse(e.httpConfigString);a=v_(e.datasource,a);const l=yield*x.toGenerator(D_({type:n,key:s,configString:JSON.stringify(a),name:e.name,additionals:e.additionalQueryInfo},e.controller.signal)),c=__(e.datasource,l),u=j_(i,c,e.contentModel.dashboardState);e.data=u,e.state="idle",e.error=null}catch(n){if(console.error(n),!Rt.isCancel(n)){e.data=[];const s=v.get(n,"message","unkown error");e.error=v.get(n,"response.data.detail.message",s),e.state="error"}}}}),runTransformation(){e.state="loading";try{const n=e.contentModel.queries.findByIDSet(new Set(e.dep_query_ids)).map(l=>({id:l.id,name:l.name,data:v.cloneDeep(l.data)})),s=e.contentModel.dashboardState,i=e.pre_process,a=new Function(`return ${i}`)()(n,s,At);e.data=a,e.state="idle",e.error=null}catch(t){e.data=[],e.error=t.message,e.state="error"}}})).actions(e=>({fetchData:t=>{if(!e.inUse&&!t){console.debug(`🟡 Skipping query[${e.name}]`);return}return console.debug(`🔵 Running query[${e.name}]`),e.isTransform?e.runTransformation():e.typedAsHTTP?e.runHTTP():e.runSQL()},beforeDestroy(){var t;(t=e.controller)==null||t.abort()}})).actions(e=>({afterCreate(){x.addDisposer(e,ae.reaction(()=>{var n;return e.isTransform?[e.inUse,e.id,e.key,e.dep_query_ids.toString(),e.pre_process,e.depQueryModelStatesString].join("--"):e.typedAsHTTP?`${e.inUse}--${e.id}--${e.key}--${e.reQueryKey}--${(n=e.datasource)==null?void 0:n.id}`:[e.inUse,e.id,e.key,e.formattedSQL,e.pre_process,e.post_process].join("--")},t=>(e.name==="getProjectGroupContributors"&&console.log("🔵 deps: ",t),e.fetchData(!1)),{fireImmediately:!0,delay:0}))}})),Dl=x.types.model("QueriesRenderModel",{current:x.types.optional(x.types.array(Tl),[])}).views(e=>({get idSet(){return new Set(e.current.map(t=>t.id))},get firstID(){if(e.current.length!==0)return e.current[0].id},findByID(t){return e.current.find(n=>n.id===t)},findByIDSet(t){return e.current.filter(n=>t.has(n.id))},get json(){return e.current.filter(t=>t.id&&t.key).map(t=>t.json)},get contentModel(){return x.getParent(e,1)},get visibleQueryIDSet(){const{views:t,filters:n,queries:s}=this.contentModel,i=[];t.visibleViews.forEach(c=>{c.panels.forEach(u=>{i.push(...u.queryIDs)})});const a=v.uniq(t.visibleViews.map(c=>c.renderViewIDs).flat());n.current.forEach(c=>{const u=v.get(c,"config.options_query_id");if(!u)return;a.some(h=>c.visibleInViewsIDSet.has(h))&&i.push(u)}),s.findByIDSet(new Set(i)).forEach(c=>{!c.isTransform||c.dep_query_ids.length===0||i.push(...c.dep_query_ids)});const l=new Set(i);return console.debug("QueryIDs:",l),l},isQueryInUse(t){return this.visibleQueryIDSet.has(t)}})).actions(e=>({downloadAllData(){const t=e.current.map(({name:n,data:s})=>({id:n,data:s}));Sf(t)},downloadDataByQueryIDs(t){const n=new Set(t),s=e.current.filter(i=>n.has(i.id)).map(({name:i,data:a})=>({id:i,data:a}));Sf(s)},downloadDataByQueryID(t){const n=e.findByID(t);if(!n){console.log("[downloadDataByQueryID] query not found");return}const{name:s,data:i}=n;kE(s,i)},refetchDataByQueryID(t){const n=e.findByID(t);if(!n){console.error(new Error(`[downloadDataByQueryID] query by ID[${t}] not found`));return}return n.fetchData(!0)},getSchema(t){return{definition:{queries:e.findByIDSet(new Set(t)).map(i=>i.json)},version:gn}},downloadSchema(t){const n=JSON.stringify(this.getSchema(t),null,2);fr("Queries",n)}}));function zf(e){return{current:e}}function Ef({min:e,max:t}){const n=`${e}px`,s=Number.isFinite(t)?`${t}px`:"∞";return`[${n}, ${s})`}const Ml=x.types.model("LayoutsRenderModel",{list:x.types.array(cf),currentBreakpoint:x.types.string}).views(e=>({get json(){return e.list.map(t=>t.json)},jsonByPanelIDSet(t){return e.list.map(n=>n.jsonByPanelIDSet(t))},get root(){return x.getRoot(e)},get contentModel(){return this.root.content},get basisLayoutSet(){return e.list.find(t=>t.id==="basis")},get currentLayoutSet(){return e.list.find(t=>t.id===e.currentBreakpoint)},get currentLayoutRange(){return this.breakpointRanges.find(t=>t.id===e.currentBreakpoint)},get currentRangeText(){const t=this.currentLayoutRange;return Ef(t)},get cols(){const t={};return e.list.forEach(n=>{t[n.id]=36}),t},get breakpoints(){const t={};return e.list.forEach(n=>{t[n.id]=n.breakpoint}),t},get breakpointNameRecord(){const t={};return e.list.forEach(n=>{t[n.name]=n.breakpoint}),t},get breakpointRanges(){const t=e.list.map(n=>({id:n.id,name:n.name,min:n.breakpoint,max:1/0,text:""}));return t.sort((n,s)=>n.min-s.min).forEach((n,s)=>{s!==t.length-1&&(n.max=t[s+1].min)}),t.forEach(n=>{n.text=Ef(n)}),t},get breakpointsInfo(){return e.list.map(t=>({id:t.id,name:t.name,breakpoint:t.breakpoint})).sort((t,n)=>t.breakpoint-n.breakpoint)},get currentBreakpointRange(){return this.breakpointRanges.find(t=>t.id===e.currentBreakpoint)},get currentLayoutPreviewWidth(){const t=this.currentBreakpointRange;if(t)return t.max===1/0?t.min===0?void 0:t.min+1:t.max},items(t){const n=new Set(t);return this.currentLayoutSet.list.filter(i=>n.has(i.panelID))},gridLayouts(t){const n=new Set(t),s={};return e.list.forEach(i=>{s[i.id]=i.list.filter(a=>n.has(a.panelID)).map(a=>a.layoutProperies)}),s},findItemByPanelID(t){return this.currentLayoutSet.findByPanelID(t)}})).actions(e=>({setCurrentBreakpoint(t){console.log("🔴 onBreakpointChange:",t),e.currentBreakpoint=t},afterCreate(){x.addDisposer(e,ae.reaction(()=>e.currentBreakpoint,()=>{setTimeout(()=>{window.dispatchEvent(new Event("resize"))},32)},{fireImmediately:!1,delay:0}))}})),Af=uf.views(e=>({isADuplicatedKey(t){return!t||t===e.key?!1:!!x.getParent(e,2).findByKey(t)}})),Il=x.types.model("SQLSnippetsRenderModel",{current:x.types.optional(x.types.array(Af),[])}).views(e=>({get json(){return e.current.map(t=>t.json)},get record(){return e.current.reduce((t,n)=>(t[n.key]=n.value,t),{})},get keySet(){return new Set(e.current.map(t=>t.key))},get firstKey(){if(e.current.length!==0)return e.current[0].key},findByKey(t){return e.current.find(n=>n.key===t)},findByKeySet(t){return e.current.filter(n=>t.has(n.key))}})).actions(e=>({getSchema(t){return{definition:{sqlSnippets:e.findByKeySet(new Set(t)).map(i=>i.json)},version:gn}},downloadSchema(t){const n=JSON.stringify(this.getSchema(t),null,2);fr("SQL Snippets",n)}}));function Pf(e){return{current:e}}function es(e,t,n,s){return e.reduce((i,a)=>{try{i[a[t]]=Di(a[n],s)}catch(l){i[a[t]]=l.message}return i},{})}class Of{constructor(t){N(this,"origin");N(this,"copy");this.origin=t,this.copy=x.clone(t),ae.makeAutoObservable(this,{},{autoBind:!0,deep:!1})}get changed(){return!v.isEqual(x.getSnapshot(this.origin),x.getSnapshot(this.copy))}commit(){x.applySnapshot(this.origin,x.getSnapshot(this.copy))}reset(){x.applySnapshot(this.copy,x.getSnapshot(this.origin))}update(t){x.applySnapshot(this.copy,t)}}const Lf=e=>new Of(e),DE=D.observer(()=>{const{t:e}=j.useTranslation(),t=le(),{panel:n}=Je(),s=n.realQueryOptions,i=a=>{t.editor.open(["_QUERIES_",a])};return s.length===0?null:r.jsxs(r.Fragment,{children:[r.jsx(o.Divider,{label:e(s.length>1?"query.labels":"query.label"),labelPosition:"center"}),s.map(a=>r.jsx(o.Menu.Item,{onClick:()=>i(a.value),icon:r.jsx(M.IconDatabase,{size:14}),children:a.label},a.value))]})}),ME=D.observer(({view:e,title:t})=>{const{t:n}=j.useTranslation(),s=le(),i=re(),a=wt.useModals(),{panel:l,downloadPanelScreenshot:c}=Je(),{id:u}=l,{viewPanelInFullScreen:d,inFullScreen:h}=g.useContext(pi),p=()=>{i.duplicatePanelByID(u,e.id)},f=()=>{s.editor.open(["_VIEWS_",e.id,"_PANELS_",u])},m=()=>a.openConfirmModal({title:`${n("panel.delete")}?`,labels:{confirm:n("common.actions.confirm"),cancel:n("common.actions.cancel")},onCancel:()=>console.log("Cancel"),onConfirm:()=>i.removePanelByID(u,e.id),confirmProps:{color:"red"},zIndex:320}),y=g.useCallback(()=>{d(u)},[u,d]),_=!h&&e.type!==G.Modal;return r.jsx(r.Fragment,{children:r.jsx(o.Box,{sx:{position:"absolute",top:0,left:0,right:0,zIndex:300},title:t,children:r.jsxs(o.Menu,{withinPortal:!0,children:[r.jsx(o.Menu.Target,{children:r.jsx(o.Box,{className:"panel-dropdown-target",sx:{width:"100%"}})}),r.jsxs(o.Menu.Dropdown,{children:[r.jsx(o.Menu.Item,{onClick:l.refreshData,icon:r.jsx(W.Refresh,{size:14}),children:n("common.actions.refresh")}),r.jsx(o.Menu.Item,{onClick:l.downloadData,icon:r.jsx(W.Download,{size:14}),children:n("common.actions.download_data")}),r.jsx(o.Menu.Item,{onClick:l.downloadSchema,icon:r.jsx(M.IconCode,{size:14}),children:n("common.actions.download_schema")}),r.jsx(o.Menu.Item,{onClick:c,icon:r.jsx(M.IconCamera,{size:14}),children:n("common.actions.download_screenshot")}),_&&r.jsx(o.Menu.Item,{onClick:y,icon:r.jsx(W.ArrowsMaximize,{size:14}),disabled:!0,children:n("common.actions.enter_fullscreen")}),r.jsx(DE,{}),r.jsx(o.Divider,{label:n("common.actions.edit"),labelPosition:"center"}),r.jsx(o.Menu.Item,{onClick:f,icon:r.jsx(W.Settings,{size:14}),children:n("common.titles.settings")}),r.jsx(o.Menu.Item,{onClick:p,icon:r.jsx(W.Copy,{size:14}),children:n("common.actions.duplicate")}),r.jsx(o.Menu.Item,{color:"red",onClick:m,icon:r.jsx(W.Trash,{size:14}),children:n("common.actions.delete")})]})]})})})});function IE(e){return e?["<p><br></p>","<p></p>"].includes(e):!0}const zl=D.observer(()=>{const{t:e}=j.useTranslation(),[t,n]=g.useState(!1),{panel:s}=Lt();return IE(s.description)?null:r.jsxs(r.Fragment,{children:[r.jsx(o.Modal,{opened:t,onClose:()=>n(!1),title:s.title.show?s.name:"",withCloseButton:!1,withinPortal:!0,zIndex:310,children:r.jsx(Kr,{value:s.description,styles:{root:{border:"none"},content:{padding:0}},sx:{".mantine-RichTextEditor-content .ProseMirror":{padding:"0 !important"}}})}),r.jsx(o.Tooltip,{label:e("panel.panel_description_click"),position:"top-start",withinPortal:!0,children:r.jsx(o.ActionIcon,{variant:"subtle",color:"blue",onClick:()=>n(i=>!i),sx:{verticalAlign:"baseline",cursor:"pointer"},children:r.jsx(W.InfoCircle,{size:20})})})]})}),bV="",zE=D.observer(function(){const{panel:t}=Lt(),{name:n,title:s}=t;return s.show?r.jsx(o.Group,{grow:!0,position:"center",className:"panel-title-wrapper",sx:{flexGrow:1},children:r.jsx(o.Text,{align:"center",lineClamp:1,className:"panel-title-text",children:n})}):null});function EE(e){const t=g.useRef(null);return{ref:t,downloadPanelScreenshot:()=>{const s=t.current;if(!s)return;const i=s.offsetWidth*2,a=s.offsetHeight*2;_c.toBlob(t.current,{bgcolor:"white",width:i,height:a,style:{border:"none",borderRadius:0,transformOrigin:"0 0",transform:"scale(2)"}}).then(l=>{window.saveAs(l,`${e.name?e.name:e.viz.type}.png`)})}}}var Vf=(e=>(e.migrated="migrated",e.nothingToMigrate="nothingToMigrate",e.checkFailed="checkFailed",e.migrationFailed="migrationFailed",e))(Vf||{}),gi=(e=>(e.notStarted="notStarted",e.inProgress="inProgress",e.done="done",e))(gi||{});class AE{constructor(t){N(this,"vizInstance");N(this,"operationManager");N(this,"triggerManager");N(this,"vizManager");N(this,"runningMigration");N(this,"panelModel");N(this,"status","notStarted");this.panelModel=t.getRequired(Oe.instanceScope.panelModel),this.vizInstance=t.getRequired(Oe.instanceScope.vizInstance),this.operationManager=t.getRequired(Oe.instanceScope.operationManager),this.triggerManager=t.getRequired(Oe.instanceScope.triggerManager),this.vizManager=t.getRequired(Oe.vizManager)}async createMigrationTask(){const t=[];try{await this.instanceNeedMigration()&&t.push(()=>this.runInstanceMigration()),await this.interactionNeedMigration()&&t.push(()=>this.runInteractionMigration())}catch(n){return console.warn("check migration failed",n),"checkFailed"}if(t.length===0)return"nothingToMigrate";try{return await Promise.all(t.map(n=>n())),"migrated"}catch(n){return console.warn("migration failed",n),"migrationFailed"}}async runMigration(){return this.runningMigration||(this.status="inProgress",this.runningMigration=this.createMigrationTask().then(t=>(this.status="done",t))),this.runningMigration}async runInteractionMigration(){await this.operationManager.runMigration(),await this.triggerManager.runMigration()}async runInstanceMigration(){const t=this.vizManager.resolveComponent(this.vizInstance.type),n={configData:this.vizInstance.instanceData,panelModel:this.panelModel};await t.migrator.migrate(n)}async instanceNeedMigration(){const t=this.vizManager.resolveComponent(this.vizInstance.type),n={configData:this.vizInstance.instanceData};return t.migrator.needMigration(n)}async interactionNeedMigration(){return await this.operationManager.needMigration()||await this.triggerManager.needMigration()}}function Bf(e){const{panel:t}=Lt();return g.useCallback(n=>{const s=n.getRequired(Oe.vizManager),i=s.resolveComponent(e.viz.type);return n.createScoped().provideFactory(Oe.instanceScope.vizInstance,()=>s.getOrCreateInstance(e)).provideFactory(Oe.instanceScope.interactionManager,a=>{const l=a.getRequired(Oe.instanceScope.vizInstance);return new yo(l,i,Hs)}).provideFactory(Oe.instanceScope.operationManager,a=>a.getRequired(Oe.instanceScope.interactionManager).operationManager).provideFactory(Oe.instanceScope.triggerManager,a=>a.getRequired(Oe.instanceScope.interactionManager).triggerManager).provideValue(Oe.instanceScope.panelModel,t).provideFactory(Oe.instanceScope.migrator,a=>new AE(a))},[e.viz.type,e.viz.conf])}function qf(e){const[t,n]=g.useState(!1),s=Xh().getRequired(Oe.instanceScope.migrator);return J.useAsyncEffect(async()=>{const i=s.status===gi.notStarted;n(s.status===gi.done),s.status===gi.notStarted&&s.runMigration().then(a=>{a===Vf.migrated&&i&&(e==null||e())}).finally(()=>{n(!0)})},[s]),t}function Nf(e,t){const n=Xh().getRequired(Oe.instanceScope.vizInstance);return g.useEffect(()=>(n.instanceData.setItem(null,t.viz.conf),n.instanceData.watchItem(null,s=>{e(s)})),[e,t.viz.type]),n}function PE({setVizConf:e,...t}){const{panel:n}=t,s=Nf(e,n),i=qf(()=>{Yt.showNotification({title:`${n.name} - Updated`,message:"Your plugin configuration has been migrated to the latest version"})});return J.useAsyncEffect(async()=>{await s.instanceData.setItem(null,n.viz.conf)},[s,n.viz.type]),i?r.jsx(E_,{...t}):r.jsx(o.Text,{children:"Checking update..."})}function OE(e){const{panel:t,setVizConf:n}=e;Nf(n,t);const{inEditMode:s}=g.useContext(Ss);return qf(()=>{s&&Yt.showNotification({title:`${t.name} - Updated`,message:"Your plugin configuration has been migrated to the latest version"})})?r.jsx(z_,{...e}):r.jsx(o.Text,{children:"Checking update"})}const vV="";function LE(e,t){const{vizManager:n}=g.useContext(rn),{panel:{viz:s,title:i,id:a,name:l,description:c,queryIDs:u,variables:d}}=Lt(),h={id:a,name:l,title:i,description:c,queryIDs:u,viz:s},p=Bf(h);try{return n.resolveComponent(s.type),r.jsx(di,{configure:p,children:r.jsx(OE,{setVizConf:s.setConf,panel:h,measure:t,data:e,variables:d,vizManager:n})})}catch(f){return console.info(v.get(f,"message")),null}}const $f=D.observer(function({data:t}){const{ref:n,width:s,height:i}=Se.useElementSize(),a=LE(t,{w:s,h:i}),l=s>0&&i>0;return r.jsx("div",{className:"viz-root",ref:n,children:r.jsx(o.Box,{sx:{width:s,height:i,overflow:"hidden"},children:l&&r.jsx(Re,{children:a})})})}),Ff=D.observer(({panel:e})=>r.jsxs(o.Stack,{children:[e.queryErrors.map((t,n)=>r.jsx(o.Text,{color:"red",size:"sm",align:"center",sx:{fontFamily:"monospace"},children:t},`${n}-${t}`)),r.jsx(o.Text,{color:"gray",align:"center",size:"sm",children:e.queryStateMessages})]})),El=D.observer(({panel:e})=>r.jsxs(o.Flex,{className:"panel-viz-section",direction:"column",sx:{position:"relative",width:"100%"},children:[r.jsx(o.LoadingOverlay,{visible:e.dataLoading,exitTransitionDuration:0}),!e.canRenderViz&&r.jsx(Ff,{panel:e}),e.canRenderViz&&r.jsx($f,{data:e.data})]})),VE={border:"1px solid #e9ecef"},Gf=D.observer(({panel:e,panelStyle:t,dropdownContent:n})=>{const{ref:s,downloadPanelScreenshot:i}=EE(e);return e.title.show,r.jsx(ra,{value:{panel:e,data:e.data,loading:e.dataLoading,errors:e.queryErrors,downloadPanelScreenshot:i},children:r.jsxs(o.Box,{className:`panel-root ${e.title.show?"panel-root--show-title":""}`,ref:s,p:0,sx:{...VE,...t},children:[r.jsx(o.Box,{className:"panel-description-popover-wrapper",children:r.jsx(zl,{})}),n,r.jsx(zE,{}),r.jsx(El,{panel:e})]})})}),BE={border:"1px dashed transparent",transition:"border-color 300ms ease","&:hover":{borderColor:"#e9ecef"}};function qE(e){return e.style.border.enabled?{}:BE}const Wf=D.observer(function({panel:t,view:n}){const s=qE(t);return r.jsx(Gf,{panel:t,panelStyle:s,dropdownContent:r.jsx(ME,{view:n,title:t.name})})});function NE(e){return!["richText","button"].includes(e)}const $E=D.observer(({view:e,title:t})=>{const{t:n}=j.useTranslation(),{panel:s,downloadPanelScreenshot:i}=Lt(),{id:a}=s,{viewPanelInFullScreen:l,inFullScreen:c}=g.useContext(pi),u=g.useCallback(()=>{l(a)},[a,l]),d=!c&&e.type!==G.Modal;return NE(s.viz.type)?r.jsx(o.Box,{sx:{position:"absolute",top:0,left:0,right:0,zIndex:300},title:t,children:r.jsxs(o.Menu,{withinPortal:!0,children:[r.jsx(o.Menu.Target,{children:r.jsx(o.Box,{className:"panel-dropdown-target"})}),r.jsxs(o.Menu.Dropdown,{children:[r.jsx(o.Menu.Item,{onClick:s.refreshData,icon:r.jsx(W.Refresh,{size:14}),children:n("common.actions.refresh")}),r.jsx(o.Menu.Item,{onClick:s.downloadData,icon:r.jsx(W.Download,{size:14}),children:n("common.actions.download_data")}),r.jsx(o.Menu.Item,{onClick:i,icon:r.jsx(M.IconCamera,{size:14}),children:n("common.actions.download_screenshot")}),d&&r.jsx(o.Menu.Item,{onClick:u,icon:r.jsx(W.ArrowsMaximize,{size:14}),children:n("common.actions.enter_fullscreen")})]})]})}):null});function FE(e){return e.style.border.enabled?{}:{border:"1px dashed transparent"}}const Al=D.observer(({panel:e,view:t})=>{const n=FE(e);return r.jsx(Gf,{panel:e,panelStyle:n,dropdownContent:r.jsx($E,{title:e.name,view:t})})}),GE={modal:{display:"flex",flexDirection:"column",flexWrap:"nowrap"},body:{display:"flex",height:"calc(100vh - 88px)"}},Rf=D.observer(function({view:t,panel:n,exitFullScreen:s}){return r.jsx(o.Modal,{opened:!0,fullScreen:!0,onClose:s,title:r.jsx(o.Button,{color:"blue",size:"xs",onClick:s,leftIcon:r.jsx(W.ArrowLeft,{size:20}),children:"Exit fullscreen"}),styles:GE,children:r.jsx(o.Group,{grow:!0,sx:{flexGrow:1,flexShrink:0},children:r.jsx(Al,{view:t,panel:n})})})});function Qf(e,t,n){const{panels:s}=Pe(),i=e.id==="Main",[a,l]=g.useState(()=>i&&s.findByID(t)?t:null),c=g.useCallback(p=>{l(p),i&&n(p)},[i,n]),u=g.useCallback(()=>{l(null),i&&n("")},[i,n]),d=a?s.findByID(a):null;return{viewPanelInFullScreen:c,exitFullScreen:u,inFullScreen:!!d,fullScreenPanel:d}}const _V="",WE=g.forwardRef(({h:e},t)=>r.jsx(o.ActionIcon,{ref:t,className:"react-grid-customDragHandle",sx:{userSelect:"none",cursor:"grab",position:"absolute",top:5,right:e>38?5:20,zIndex:400,"&:hover":{color:"#228be6"}},variant:"transparent",children:r.jsx(W.ArrowsMove,{size:16})})),RE=g.forwardRef(({handleAxis:e,...t},n)=>r.jsx(o.ActionIcon,{ref:n,className:"react-grid-customResizeHandle",sx:{userSelect:"none",cursor:"nwse-resize",position:"absolute",bottom:0,right:0,zIndex:400,"&:hover":{color:"#228be6"}},variant:"transparent",...t,children:r.jsx(W.ChevronDownRight,{size:16})})),QE=as.WidthProvider(as.Responsive),UE=D.observer(({view:e,className:t="layout"})=>{const s=re().layouts,i=s.items(e.panelIDs),a=s.gridLayouts(e.panelIDs),l=(d,h,p,f)=>{console.log("🔴 onResize",d),p.h<30&&(p.h=30,f.h=30),p.w<4&&(p.w=4,f.w=4)},c=(d,h,p)=>{console.log("🔴 onResizeStop",{layouts:d,oldItem:h,newItem:p}),s.updateCurrentLayoutItem(p)},u=(d,h,p)=>{console.log("🔴 onDragStop",{layouts:d,oldItem:h,newItem:p}),s.updateCurrentLayoutItems(d)};return r.jsx(QE,{className:`dashboard-layout ${t}`,rowHeight:1,margin:[0,0],isBounded:!0,isDraggable:!0,isResizable:!0,cols:s.cols,layouts:a,draggableHandle:".react-grid-customDragHandle",resizeHandle:r.jsx(RE,{}),onResize:l,breakpoints:s.breakpoints,onBreakpointChange:s.setCurrentBreakpoint,onResizeStop:c,onDragStop:u,width:s.currentLayoutPreviewWidth,children:i.map(d=>r.jsxs("div",{"data-grid":d.layoutProperies,className:"panel-grid-item",children:[r.jsx(WE,{h:d.h}),r.jsx(Wf,{view:e,panel:d.panel})]},d.id))})}),YE=as.WidthProvider(as.Responsive),KE=D.observer(({view:e,className:t="layout"})=>{const n=Pe(),s=n.layouts.items(e.panelIDs),i=n.layouts.gridLayouts(e.panelIDs);return r.jsx(YE,{className:`dashboard-layout ${t}`,rowHeight:1,margin:[0,0],isDraggable:!1,isResizable:!1,cols:n.layouts.cols,layouts:i,breakpoints:n.layouts.breakpoints,onBreakpointChange:n.layouts.setCurrentBreakpoint,children:s.map(a=>r.jsx("div",{"data-grid":a.layoutProperies,className:"panel-grid-item",children:r.jsx(Al,{view:e,panel:a.panel})},a.id))})});function Pl(e){const t=g.useRef(null);return{ref:t,downloadScreenshot:()=>{var i;const s=(i=t.current)==null?void 0:i.querySelector(".react-grid-layout");s&&e.downloadScreenshot(s)}}}const XE=D.observer(({downloadScreenshot:e})=>{const{t}=j.useTranslation(),[n,{setTrue:s,setFalse:i}]=J.useBoolean(!1),a=wu(),l=Pe(),c=()=>{const u=JSON.stringify(l.contentJSON,null,2),d=`${a.name}__${l.name}`;fr(d,u)};return r.jsxs(o.Menu,{shadow:"md",width:200,trigger:"hover",openDelay:200,closeDelay:400,withinPortal:!0,position:"bottom-end",children:[r.jsx(o.Menu.Target,{children:r.jsx(o.Affix,{position:{bottom:"20px",right:"10px"},zIndex:1,children:r.jsx(o.ActionIcon,{size:"md",variant:"gradient",gradient:{from:"indigo",to:"cyan"},onMouseEnter:s,onMouseLeave:i,sx:{opacity:n?1:.6,transform:`translateX(${n?0:"2px"})`,transition:"all ease 300ms",borderRadius:"50%"},children:r.jsx(M.IconShare3,{size:"1rem"})})})}),r.jsxs(o.Menu.Dropdown,{children:[r.jsx(o.Menu.Item,{icon:r.jsx(M.IconCamera,{size:14}),onClick:e,children:t("common.actions.download_screenshot")}),r.jsx(o.Menu.Divider,{}),r.jsx(o.Menu.Item,{icon:r.jsx(M.IconDownload,{size:14}),onClick:l.queries.downloadAllData,children:t("common.actions.download_data")}),r.jsx(o.Menu.Item,{icon:r.jsx(M.IconCode,{size:14}),onClick:c,children:t("common.actions.download_schema")})]})]})}),Uf=D.observer(({children:e,view:t,sx:n={}})=>{const{ref:s,downloadScreenshot:i}=Pl(t);return r.jsxs(r.Fragment,{children:[r.jsx(o.Box,{ref:s,pt:10,pb:10,sx:n,children:e}),r.jsx(XE,{downloadScreenshot:i})]})}),Yf=D.observer(({downloadScreenshot:e})=>r.jsx(o.ActionIcon,{className:"download-screenshot-button",color:"blue",onClick:e,children:r.jsx(M.IconCamera,{size:14})})),JE=D.observer(({children:e,view:t})=>{const n=Pe(),s=t.config,i=n.views.visibleViewIDs.includes(t.id),a=()=>n.views.rmVisibleViewID(t.id),{ref:l,downloadScreenshot:c}=Pl(t);return r.jsx(o.Modal,{size:s.width,centered:!0,opened:i,onClose:a,withCloseButton:!1,title:r.jsxs(o.Group,{position:"apart",px:"1rem",h:"48px",children:[r.jsx(o.Box,{children:s.custom_modal_title.value}),r.jsx(Yf,{downloadScreenshot:c})]}),trapFocus:!0,onDragStart:u=>{u.stopPropagation()},styles:{root:{position:"fixed",zIndex:200,inset:0},overlay:{zIndex:"unset"},inner:{zIndex:"unset",padding:"0 !important"},content:{border:"1px solid #efefef",maxHeight:"unset !important",overflow:"hidden"},body:{maxHeight:s.height,overflow:"auto",position:"relative",paddingBottom:10},header:{padding:0},title:{flexGrow:1}},transitionProps:{duration:0},children:r.jsx(o.Box,{ref:l,children:e})})}),ZE=e=>e.color?{"&[data-active], &[data-active]:hover":{borderColor:e.color?e.color:"..."}}:{},HE=D.observer(({view:e})=>{const t=Pe(),n=e.config;return r.jsxs(o.Tabs,{className:"render-view-tabs",variant:n.variant,orientation:n.orientation,value:e.tab,onTabChange:e.setTab,styles:{root:{height:"100%",overflow:n.orientation==="horizontal"?"hidden":"auto"},panel:{padding:n.orientation==="horizontal"?"0px 0px 36px":"0",height:"100%",overflow:"auto"}},keepMounted:!1,children:[r.jsx(o.Tabs.List,{grow:n.grow,children:n.tabsInOrder.map(s=>r.jsx(o.Tabs.Tab,{value:s.id,sx:ZE(s),disabled:!s.view_id,children:s.name??s.id},s.id))}),n.tabsInOrder.map(s=>{const i=t.views.findByID(s.view_id);return i?r.jsx(o.Tabs.Panel,{value:s.id,children:r.jsx(mi,{view:i})},s.id):null})]})}),eA=D.observer(({view:e,children:t})=>{switch(e.type){case G.Modal:return r.jsx(JE,{view:e,children:t});case G.Tabs:return r.jsx(HE,{view:e});case G.Division:default:return r.jsx(Uf,{view:e,children:t})}}),tA=D.observer(({children:e,view:t})=>{const s=re().layouts,[i,a]=Se.useResizeObserver();return g.useEffect(()=>{s.setCurrentLayoutWrapperWidth(a.width)},[a.width]),r.jsx(o.Box,{sx:{height:"100%"},ref:i,children:r.jsx(o.Box,{sx:{paddingBottom:"100px",background:"white",margin:"0 auto",width:s.currentLayoutPreviewWidth??"100%",transform:`scale(${s.divisionPreviewScale})`,transformOrigin:"0 0"},children:r.jsx(Uf,{view:t,sx:{paddingTop:"0px !important",".dashboard-sticky-area > form":{paddingBottom:"5px"},".dashboard-layout":{marginTop:0,marginBottom:0}},children:e})})})});function Kf(e){return e.replace(/(vw|vh)/,"%")}const nA=D.observer(({children:e,view:t})=>{const n=t.config,{width:s,height:i}=g.useMemo(()=>({width:Kf(n.width),height:Kf(n.height)}),[n.width,n.height]),{ref:a,downloadScreenshot:l}=Pl(t);return r.jsx(o.Box,{sx:{height:"100%","> div:not(.mantine-Modal-root)":{height:"100%"}},children:r.jsx(o.Modal,{size:n.width,opened:!0,onClose:v.noop,withCloseButton:!1,title:r.jsxs(o.Group,{position:"apart",px:"1rem",h:"48px",children:[r.jsx(o.Box,{children:n.custom_modal_title.value}),r.jsx(Yf,{downloadScreenshot:l})]}),trapFocus:!0,onDragStart:c=>{c.stopPropagation()},styles:{root:{position:"relative",height:"100%"},overlay:{position:"absolute !important"},inner:{position:"relative",top:"50%",left:"50%",right:"unset",bottom:"unset",transform:"translate(-50%, -50%)",padding:"0 !important",width:s,height:i,maxHeight:i},content:{border:"1px solid #efefef",height:"100%"},body:{maxHeight:"calc(100% - 48px)",overflow:"auto"},header:{padding:0},title:{flexGrow:1}},withinPortal:!1,transitionProps:{duration:0},children:r.jsx(o.Box,{ref:a,children:e})})})}),rA=({variant:e,orientation:t})=>{const n={root:{height:"100%",overflow:"hidden"},tabsList:{backgroundColor:"white"},tab:{},panel:{padding:"16px"}};return e==="pills"&&t==="horizontal"&&(n.tab.paddingTop="6px",n.tab.paddingBottom="6px"),t==="vertical"&&(n.tab["&.add-a-tab"]={paddingTop:"1px",paddingBottom:"1px"},n.tab["&.add-a-tab .mantine-Tabs-tabLabel"]={marginLeft:"auto",marginRight:"auto"}),n},sA=e=>e.color?{"&[data-active], &[data-active]:hover":{borderColor:e.color?e.color:"..."}}:{},iA=D.observer(({view:e})=>{const{t}=j.useTranslation(),n=wt.useModals(),s=re(),i=g.useMemo(()=>s.views.options.filter(u=>u.type===G.Division),[e.id,s.views.options]),a=e.config,l=u=>n.openConfirmModal({title:`${t("view.component.tabs.tab.delete")}?`,labels:{confirm:t("common.actions.confirm"),cancel:t("common.actions.cancel")},onCancel:()=>console.log("Cancel"),onConfirm:()=>{a.removeTab(u)},confirmProps:{color:"red"},zIndex:320}),c=a.tabs.length===0;return r.jsxs(o.Tabs,{className:"preview-view-tabs",variant:a.variant,orientation:a.orientation,value:e.tab,onTabChange:e.setTab,styles:rA(a),children:[r.jsxs(o.Tabs.List,{grow:a.grow,children:[a.tabsInOrder.map(u=>r.jsx(o.Tabs.Tab,{value:u.id,sx:sA(u),children:u.name??u.id},u.id)),r.jsx(o.Tabs.Tab,{onClick:a.addTab,value:"add",className:"add-a-tab",children:r.jsx(W.Plus,{size:18,color:"#228be6"})})]}),a.tabsInOrder.map((u,d)=>{const h=s.views.findByID(u.view_id);return r.jsxs(o.Tabs.Panel,{value:u.id,sx:{position:"relative"},children:[r.jsxs(o.Box,{sx:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:200},children:[r.jsx(o.Overlay,{opacity:.8,color:"#FFF",blur:10,zIndex:100}),r.jsxs(o.Stack,{mx:"auto",mt:100,sx:{width:"300px",position:"relative",zIndex:200},children:[r.jsx(o.TextInput,{label:t("view.component.tabs.tab.name"),required:!0,value:u.name,onChange:p=>u.setName(p.currentTarget.value)}),r.jsx(o.Select,{label:"View",value:u.view_id,onChange:u.setViewID,data:i}),r.jsx(o.NumberInput,{label:t("view.component.tabs.tab.order"),required:!0,value:u.order,onChange:p=>u.setOrder(p||0),min:0,max:1e3,step:1}),r.jsx(o.ColorInput,{label:t("view.component.tabs.tab.color"),value:u.color,onChange:u.setColor,disabled:a.variant!=="default"}),h&&r.jsx(o.Button,{mt:20,variant:"gradient",leftIcon:r.jsx(M.IconArrowsLeftRight,{size:18}),gradient:{from:"cyan",to:"indigo"},onClick:()=>s.views.setIDOfVIE(h.id),children:t("view.component.tabs.tab.switch_to_view",{name:h.name})}),r.jsx(o.Button,{mt:20,variant:"subtle",color:"red",onClick:()=>l(d),disabled:c,leftIcon:r.jsx(M.IconTrash,{size:14}),children:t("view.component.tabs.tab.delete")})]})]}),h&&r.jsx(mi,{view:h})]},u.id)})]})}),aA=D.observer(({view:e,children:t})=>{switch(e.type){case G.Modal:return r.jsx(nA,{view:e,children:t});case G.Tabs:return r.jsx(iA,{view:e});case G.Division:default:return r.jsx(tA,{view:e,children:t})}}),Xf=D.observer(function({view:t}){const s=re().layouts.divisionPreviewScale!==1;return r.jsx(pi.Provider,{value:{viewPanelInFullScreen:v.noop,inFullScreen:!1},children:r.jsx(o.Box,{className:"dashboard-view","data-enable-scrollbar":!0,sx:{background:s?"transparent":"#efefef"},children:r.jsx(aA,{view:t,children:r.jsxs(o.Box,{sx:{position:"relative"},children:[r.jsx(o.Box,{className:"dashboard-sticky-area",sx:{position:"sticky",top:"0px"},children:r.jsx(ef,{view:t})}),r.jsx(UE,{view:t})]})})})})}),mi=D.observer(function({view:t}){const{fullScreenPanelID:n,setFullScreenPanelID:s}=Eu(),{viewPanelInFullScreen:i,exitFullScreen:a,inFullScreen:l,fullScreenPanel:c}=Qf(t,n,s);return r.jsx(pi.Provider,{value:{viewPanelInFullScreen:i,inFullScreen:l},children:r.jsxs(o.Box,{className:"dashboard-view","data-enable-scrollbar":!0,sx:{height:t.type===G.Modal?"0 !important":"100%"},children:[l&&r.jsx(Rf,{view:t,panel:c,exitFullScreen:a}),r.jsx(eA,{view:t,children:r.jsxs(o.Box,{sx:{position:"relative"},children:[!l&&r.jsx(o.Box,{className:"dashboard-sticky-area",sx:{position:"sticky",top:"0px"},children:r.jsx(ef,{view:t})}),!l&&r.jsx(KE,{view:t})]})})]})})});var Jf=(e=>(e.Use="use",e.Edit="edit",e))(Jf||{});const oA={[G.Division]:"Division",[G.Tabs]:"Tabs",[G.Modal]:"Modal"},Zf={[G.Division]:"rgba(255, 0, 0, 0.2)",[G.Modal]:"rgba(0, 0, 0, 0.2)",[G.Tabs]:"rgba(255, 200, 100, 0.4)"},lA={[G.Division]:"#ff4000",[G.Modal]:"#000",[G.Tabs]:"#ffad18"};function cA(e,t,n){x.addDisposer(e,x.addMiddleware(e,(s,i)=>{i(s,()=>{x.getType(s.context)===t&&s.type==="action"&&n(s.name,s.context)})}))}const Hf=x.types.compose("FiltersModel",Sl,x.types.model("FiltersModel",{previewValues:x.types.optional(x.types.frozen(),{})})).views(e=>({get idSet(){return new Set(e.current.map(t=>t.id))},get keySet(){return new Set(e.current.map(t=>t.key))},get options(){return e.current.map(t=>({label:t.label??t.id,value:t.id,_type:"filter"}))},get selects(){return e.current.filter(t=>t.type===Ce.Select).map(t=>({label:t.label??t.id,value:t.id}))},get keyLabelOptions(){return e.current.map(t=>({label:t.label??t.key,value:t.key}))},get sortedList(){return v.sortBy(e.current,t=>t.label.toLowerCase())}})).actions(e=>({replace(t){e.current=x.cast(t)},append(t){e.current.push(t)},appendMultiple(t){if(t.length===0)return;const n=t.filter(s=>!e.idSet.has(s.id));e.current.push(...n)},remove(t){e.current.splice(t,1)},removeByID(t){const n=e.current.findIndex(s=>s.id===t);n>=0&&e.current.splice(n,1)},updatePreviewValues(t){e.previewValues=t}})).actions(e=>{function t(){cA(e.current,fl,(n,s)=>{if(n==="setType"){const i=Df(s.config.default_value,s.config);e.setValueByKey(s.key,i),e.updatePreviewValues({...e.previewValues,[s.key]:i})}})}return{afterCreate(){t()}}}),eg=Tl.views(e=>({get canPreviewData(){return e.isTransform?e.dep_query_ids.length>0&&!!e.pre_process:!!e.datasource},get guideToPreviewData(){return e.isTransform?"Need to complete settings in Transform tab":"Need to pick a Data Source first"}})),tg=x.types.compose("QueriesModel",Dl,x.types.model({current:x.types.optional(x.types.array(eg),[])})).views(e=>({get options(){const t=e.current.map(n=>({value:n.id,label:n.name,_type:"query"}));return v.sortBy(t,n=>n.label.toLowerCase())},get optionsWithoutTransform(){const t=e.current.filter(n=>n.type!==Ee.Transform).map(n=>({value:n.id,label:n.name,_type:"query"}));return v.sortBy(t,n=>n.label.toLowerCase())},get sortedList(){return v.sortBy(e.current,t=>t.name.toLowerCase())}})).actions(e=>({replace(t){e.current=x.cast(t)},append(t){e.current.push(t)},appendMultiple(t){if(t.length===0)return;const n=t.filter(s=>!e.idSet.has(s.id));e.current.push(...n)},remove(t){e.current.splice(t,1)},replaceByIndex(t,n){e.current.splice(t,1,n)},removeQuery(t){const n=e.current.find(s=>s.id===t);n&&(x.detach(n),e.current.remove(n))},removeQueries(t){const n=new Set(t);e.current.forEach(i=>{n.has(i.id)&&x.detach(i)});const s=[...e.current];v.remove(s,i=>n.has(i.id)),e.current=x.cast(s)}})),ng=Il.views(e=>({get sortedList(){return v.sortBy(e.current,t=>t.key.toLowerCase())},get options(){const t=e.current.map(n=>({label:n.key,value:n.key,_type:"sql_snippet"}));return v.sortBy(t,n=>n.label.toLowerCase())}})).actions(e=>({replace(t){e.current=x.cast(t)},append(t){e.current.push(t)},appendMultiple(t){if(t.length===0)return;const n=t.filter(s=>!e.keySet.has(s.key));e.current.push(...n)},remove(t){e.current.splice(t,1)},removeByKey(t){const n=e.current.findIndex(s=>s.key===t);n>=0&&e.current.splice(n,1)},removeByKeys(t){const n=new Set(t);e.current.forEach(i=>{n.has(i.key)&&x.detach(i)});const s=[...e.current];v.remove(s,i=>n.has(i.key)),e.current=x.cast(s)},replaceByIndex(t,n){e.current.splice(t,1,n)}})),uA=x.types.model({data:x.types.optional(x.types.frozen(),[]),state:x.types.optional(x.types.enumeration(["idle","loading","error"]),"idle"),error:x.types.frozen()}).views(e=>({get loading(){return e.state==="loading"},get empty(){return e.data.length===0}})),dA=x.types.model({data:x.types.optional(x.types.frozen(),[]),state:x.types.optional(x.types.enumeration(["idle","loading","error"]),"idle"),error:x.types.frozen()}).views(e=>({get loading(){return e.state==="loading"},get empty(){return e.data.length===0}})),pA=x.types.model({page:x.types.optional(x.types.number,1),limit:x.types.optional(x.types.number,20),data:x.types.optional(x.types.frozen(),[]),total:x.types.optional(x.types.number,0),state:x.types.optional(x.types.enumeration(["idle","loading","error"]),"idle"),error:x.types.frozen()}).views(e=>({get keywords(){return x.getParent(e,1)},get keywordString(){const{table_name:t,table_schema:n}=x.getParent(e,1);return`${n}||${t}`}})).views(e=>({get loading(){return e.state==="loading"},get empty(){return e.data.length===0},get maxPage(){return Math.ceil(e.total/e.limit)},get offset(){return(e.page-1)*e.limit},get countSql(){const{table_name:t,table_schema:n}=e.keywords;return`
470
+ `)},ml=x.types.model("ViewModalConfig",{_name:x.types.literal(G.Modal),width:x.types.string,height:x.types.string,custom_modal_title:x.types.optional(jE,hi)}).views(e=>({get json(){const{_name:t,width:n,height:s,custom_modal_title:i}=e;return{_name:t,width:n,height:s,custom_modal_title:i.json}}})).actions(e=>({setWidth(t){e.width=t},setHeight(t){e.height=t}})),yf=()=>ml.create({_name:G.Modal,width:"90vw",height:"90vh"}),wE=x.types.model("ViewTabsTabModel",{id:x.types.identifier,name:x.types.string,view_id:x.types.string,color:x.types.optional(x.types.string,""),order:x.types.optional(x.types.number,0)}).views(e=>({get json(){const{id:t,name:n,view_id:s,color:i,order:a}=e;return{id:t,name:n,color:i,order:a,view_id:s}}})).actions(e=>({setName(t){e.name=t},setViewID(t){e.view_id=t},setColor(t){e.color=t},setOrder(t){e.order=t}})),xl=x.types.model("ViewTabsConfig",{_name:x.types.literal(G.Modal),tabs:x.types.optional(x.types.array(wE),[]),variant:x.types.optional(x.types.enumeration("variant",["default","outline","pills"]),"default"),orientation:x.types.optional(x.types.enumeration("orientation",["horizontal","vertical"]),"horizontal"),grow:x.types.optional(x.types.boolean,!1)}).views(e=>({get json(){const{_name:t,variant:n,orientation:s,tabs:i,grow:a}=e;return{grow:a,tabs:i.map(l=>l.json),_name:t,variant:n,orientation:s}},get tabsInOrder(){return v.sortBy(e.tabs,"order")}})).actions(e=>({setVariant(t){e.variant=t},setOrientation(t){e.orientation=t},setGrow(t){e.grow=t},setTabs(t){e.tabs.length=0,e.tabs=x.cast(t)},addTab(){const t=Se.randomId(),n={id:t,name:t,view_id:""};e.tabs.push(n)},removeTab(t){e.tabs.splice(t,1)}})),bf=()=>xl.create({_name:G.Modal,tabs:[]}),vf=x.types.model({id:x.types.identifier,name:x.types.string,type:x.types.enumeration("EViewComponentType",[G.Division,G.Modal,G.Tabs]),config:x.types.union(gl,ml,xl),panelIDs:x.types.optional(x.types.array(x.types.string),[])}).views(e=>({get json(){const{id:t,name:n,type:s,config:i}=e;return{id:t,name:n,type:s,config:i.json,panelIDs:e.panelIDs.map(a=>a)}}})).actions(e=>({setName(t){e.name=t},setType(t){if(e.type!==t){switch(t){case G.Division:e.config=xf();break;case G.Modal:e.config=yf();break;case G.Tabs:e.config=bf();break}e.type=t}},appendPanelID(t){e.panelIDs.push(t)},appendPanelIDs(t){e.panelIDs.push(...t)},removePanelID(t){const n=e.panelIDs.filter(s=>s!==t);e.panelIDs.length=0,e.panelIDs.push(...n)}})),gn="11.10.0",CE={definition:{sqlSnippets:[],queries:[],mock_context:{}},views:[{id:"Main",name:"Main",type:G.Division,config:{},panelIDs:[]}],panels:[],filters:[],version:gn,layouts:[{id:"basis",name:"basis",list:[],breakpoint:0}]},yl=x.types.model("DataSourceMetaModel",{id:x.types.string,type:x.types.enumeration("DataSourceType",[Ee.HTTP,Ee.MySQL,Ee.Postgresql]),key:x.types.string,config:x.types.frozen()}),_f=x.types.model("DataSourcesMetaModel",{list:x.types.optional(x.types.array(yl),[])}).views(e=>({find({type:t,key:n}){return e.list.find(s=>s.key===n&&s.type===t)},get options(){return e.list.map(t=>({value:t.key,label:t.key}))}})).actions(e=>({replace(t){e.list.length=0,e.list.push(...t)}})),jf=x.types.model({id:x.types.string,content:x.types.string,create_time:x.types.string,update_time:x.types.string,is_preset:x.types.boolean}),bl=x.types.model("GlobalSQLSnippetsMeta",{list:x.types.optional(x.types.array(jf),[])}).views(e=>({find(t){return e.list.find(n=>n.id===t)},get options(){return e.list.map(t=>({value:t.id,label:t.id}))}})).actions(e=>({replace(t){e.list.length=0,e.list.push(...t)}})),fi=x.types.model("ContextMeta",{current:x.types.optional(x.types.frozen(),{})}).views(e=>({get keys(){return Object.keys(e.current)},get entries(){return Object.entries(e.current)}})).actions(e=>({replace(t){e.current=t},get(t){return e.current[t]},set(t,n){e.current[t]=n}}));function vl(e){return fi.create({current:e})}const _l=x.types.compose("ViewRenderModel",vf,x.types.model({tab:x.types.optional(x.types.string,"")})).views(e=>({get tabs(){return e.config.tabs},get tabInfo(){const t=this.tabs.find(n=>n.id===e.tab);return t?{id:t.id,name:t.name}:null},get tabView(){return e.type!==G.Tabs?null:this.tabs.find(t=>t.id===e.tab)},get tabViewID(){return this.tabView?this.tabView.view_id??"":""},get contentModel(){return x.getParent(e,3)},get panels(){if(e.type!==G.Tabs)return this.contentModel.panels.panelsByIDs(e.panelIDs);const t=this.tabViewID,n=this.contentModel.views.findByID(t);return(n==null?void 0:n.panels)??[]},get renderViewIDs(){const t=[e.id];return e.type===G.Tabs&&t.push(this.tabViewID),t},async downloadScreenshot(t){const n=t.offsetWidth*2+10,s=t.offsetHeight*2+10,i=new jc,a=new Date().getTime(),l=await _c.toBlob(t,{bgcolor:"white",width:n,height:s,style:{transformOrigin:"0 0",transform:"scale(2)"}});i.file(`${e.name}_${a}.png`,l),i.file(`dashboard_state_${a}.json`,JSON.stringify(this.contentModel.dashboardState,null,4)),i.generateAsync({type:"blob"}).then(c=>{os.saveAs(c,`${e.name}_${a}.zip`)}).catch(c=>{console.error(c),Yt.notifications.show({color:"red",title:"Failed to download screenshot with dashboard state",message:c.message})})}})).actions(e=>({setTab(t){e.tab=t??""},setTabByTabInfo(t){e.tab=t.id??""}})),jl=x.types.model("ViewsRenderModel",{current:x.types.optional(x.types.array(_l),[]),visibleViewIDs:x.types.array(x.types.string)}).views(e=>({get json(){return e.current.map(t=>cr(t.json))},get idMap(){const t=new Map;return e.current.forEach(n=>{t.set(n.id,n)}),t},findByID(t){return e.current.find(n=>n.id===t)},get firstVisibleView(){const[t]=e.visibleViewIDs;return e.current.find(({id:n})=>n===t)},get visibleViews(){const t=new Set(e.visibleViewIDs);return e.current.filter(({id:n})=>t.has(n))},get firstVisibleTabsView(){return this.visibleViews.find(t=>t.type===G.Tabs)},get firstVisibleTabsViewActiveTab(){const t=this.firstVisibleTabsView;return t?t.tabInfo:null}})).actions(e=>({appendToVisibles(t){new Set(e.visibleViewIDs.map(s=>s)).has(t)||e.visibleViewIDs.push(t)},rmVisibleViewID(t){const n=e.visibleViewIDs.findIndex(s=>s===t);n!==-1&&e.visibleViewIDs.splice(n,1)},setFirstVisibleTabsViewActiveTab(t){if(!t)return;const n=e.firstVisibleTabsView;n==null||n.setTabByTabInfo(t)}}));function wf(e,t){const n=e.length>0?[e[0].id]:[],s=e.map(i=>{const{_name:a=i.type}=i.config,l={...i,tab:"",config:{...i.config,_name:a},panelIDs:i.panelIDs};if(i.type===G.Tabs){const c=v.minBy(i.config.tabs,u=>u.order);l.tab=(c==null?void 0:c.id)??""}return l});return t&&(s[0].tab=t.id),{current:s,visibleViewIDs:n}}const SE=new em.AsyncParser({withBOM:!0});async function Cf(e){return!Array.isArray(e)||e.length===0?"":await SE.parse(e).promise()}async function kE(e,t){const n=await Cf(t),s=new Blob([n],{type:"text/csv"});os.saveAs(s,`${e}.csv`)}function Sf(e){const t=new jc,n=e.map(async({id:s,data:i})=>{const a=await Cf(i);t.file(`${s}.csv`,a)});Promise.all(n).then(()=>{t.generateAsync({type:"blob"}).then(s=>{os.saveAs(s,"dashboard_data.zip")})}).catch(s=>{console.error(s),Yt.notifications.show({color:"red",title:"Failed to download data",message:s.message})})}function fr(e,t){const n=new Blob([t],{type:"application/json"});os.saveAs(n,`${e}.json`)}const wl=af.views(e=>({get contentModel(){return x.getRoot(e).content}})).views(e=>({get queries(){return e.contentModel.queries.findByIDSet(e.queryIDSet)},get firstQuery(){return this.queries.length>0?this.queries[0]:null},get firstQueryData(){return this.firstQuery?this.firstQuery.data:[]},queryByID(t){return this.queries.find(n=>n.id===t)},get data(){return this.queries.reduce((t,n)=>(t[n.id]=n.data,t),{})},get variableStrings(){return Bp(e.variables,this.data)},get variableAggValueMap(){const t={},n=this.data;return e.variables.reduce((s,i)=>(s[i.name]=nn(i,n),s),t),t},get variableValueMap(){const t={},n=this.variableAggValueMap;return e.variables.reduce((s,i)=>(s[i.name]=vt(i,n[i.name]),s),t),t},get variableStyleMap(){const t=this.variableValueMap,n={};return e.variables.reduce((s,i)=>{const a=u_(i.color,t[i.name]);return s[i.name]={color:a,"font-size":i.size,"font-weight":i.weight,variable:i},s},n),n},get dataLoading(){return this.queries.some(t=>t.state==="loading")},get queryStateMessages(){const t=this.queries.filter(a=>!a.runByConditionsMet);if(t.length===0)return"";const n=new Set,s=new Set;t.forEach(a=>{const l=a.conditionNames;l.context.forEach(c=>n.add(c)),l.filters.forEach(c=>s.add(c))});const i=[];return n.size>0&&(console.log(n),i.push(`context: ${Array.from(n).join(", ")}`)),s.size>0&&i.push(`filter${s.size>1?"s":""}: ${Array.from(s).join(", ")}`),i.length===2&&i.splice(1,0,"and"),i.unshift("Waiting for"),i.join(" ")},get queryErrors(){return this.queries.map(t=>t.error).filter(t=>!!t)},get canRenderViz(){return this.queryErrors.length===0&&this.queryStateMessages===""&&!this.dataLoading}})).actions(e=>({refreshData(){e.queries.forEach(t=>t.fetchData(!0))},downloadData(){e.contentModel.queries.downloadDataByQueryIDs(e.queryIDs)},getSchema(){const t=e.json;return t.viz.conf={...t.viz.conf,__INTERACTIONS:{},__OPERATIONS:{},__TRIGGERS:{}},{panel:t,queries:e.queries.map(n=>n.json),layouts:e.contentModel.layouts.jsonByPanelIDSet(new Set([e.id]))}},downloadSchema(){const{panel:t,queries:n,layouts:s}=this.getSchema(),a=JSON.stringify({panels:[t],definition:{queries:n},layouts:s,version:gn},null,2),l=e.name;fr(l,a)}}));function kf(e){return{id:e,name:"Panel",title:{show:!0},description:"<p></p>",queryIDs:[],viz:{type:Wo.name,conf:Wo.createConfig()},style:{border:{enabled:!0}}}}const Cl=x.types.model("PanelsRenderModel",{list:x.types.optional(x.types.array(wl),[])}).views(e=>({get json(){return e.list.map(t=>t.json)},findByID(t){return e.list.find(n=>n.id===t)},get idMap(){const t=new Map;return e.list.forEach(n=>{t.set(n.id,n)}),t}})).views(e=>({panelsByIDs(t){const n=[];return t.forEach(s=>{const i=e.idMap.get(s);i?n.push(i):console.warn(`Panel is not found, id:${s}`)}),n}}));function Tf(e){const t=e.config,n=t.default_value;if(n===void 0)return n;if(t._name==="date-range")try{if(t.default_shortcut){const i=Jh(t.default_shortcut);if(i)return i.map(a=>P(a).format(t.inputFormat))}const[...s]=n;return s.map(i=>i===null?i:P.tz(i,"UTC").format(t.inputFormat)??i)}catch(s){return console.error(s),n}return n}function TE(e,t){const n=e.default_value_func;try{return new Function(`return ${n}`)()(e,At,t)}catch(s){return console.error(s),Tf(e)}}function Df(e,t){var n;return(n=e.default_value_func)!=null&&n.trim()?TE(e,t):Tf(e)}function Mf(e,t){return e.reduce((n,s)=>(n[s.key]=Df(s,t),n),{})}const Sl=x.types.model("FiltersRenderModel",{current:x.types.optional(x.types.array(fl),[]),values:x.types.optional(x.types.frozen(),{})}).views(e=>({get json(){return e.current.map(t=>t.json)},get valuesString(){return JSON.stringify(e.values)},get contentModel(){return x.getRoot(e).content},get context(){return this.contentModel.payloadForSQL.context},get initialValuesDep(){return JSON.stringify({filters:e.current.map(({default_value_func:t,config:n})=>({default_value_func:t,config:n})),context:this.contentModel.payloadForSQL.context})},get formattedDefaultValues(){return Mf(this.json,this.contentModel.context)},get firstID(){if(e.current.length!==0)return e.current[0].id},findByID(t){return e.current.find(n=>n.id===t)},findByIDSet(t){return e.current.filter(n=>t.has(n.id))},get inOrder(){return v.sortBy(e.current,"order")},get empty(){return e.current.length===0},visibleInView(t){return v.sortBy(e.current.filter(n=>n.visibleInViewsIDSet.has(t)),"order")},get firstFilterValueKey(){return Object.keys(e.values)[0]??""},get keySet(){return new Set(e.current.map(t=>t.key))},get keyLabelMap(){return e.current.reduce((t,n)=>(t[n.key]=n.label,t),{})},getSelectOption(t){const n=this.findByID(t);if(!n||!("getSelectOption"in n.config))return null;const s=e.values[n.key];return n.config.getSelectOption(s)}})).actions(e=>({setValues(t){console.debug("⚪️ setting filter values: ",JSON.stringify(t)),e.values=t},patchValues(t){console.debug("⚪️ patching filter values: ",JSON.stringify(t)),e.values=v.defaults({},t,e.values)},setValueByKey(t,n){console.debug(`⚪️ setting filter[${t}] to value: `,JSON.stringify(n)),e.values={...e.values,[t]:n}},applyValuesPatch(t){e.values={...e.values,...t}},getValueByKey(t){return e.values[t]},getSchema(t,n){return{filters:e.findByIDSet(new Set(t)).map(a=>({...a.json,visibleInViewsIDs:n?a.json.visibleInViewsIDs:[]})),version:gn}},downloadSchema(t){const n=JSON.stringify(this.getSchema(t,!1),null,2);fr("Filters",n)}}));function kl(e,t,n,s){const i=v.defaults({},s,Mf(e,{...n,...t}));return{current:e,values:i}}const If=of.views(e=>({get rootModel(){return x.getRoot(e)},get contentModel(){return this.rootModel.content},get conditionOptions(){if(!x.isAlive(e))return[];const{context:t}=this.contentModel.payloadForSQL,n=Object.keys(t).map(l=>({group:"Context",label:l,value:`context.${l}`,description:void 0})),s=this.contentModel.filters.keyLabelOptions.map(l=>({group:"Filters",label:l.label,value:`filters.${l.value}`,description:l.value})),i=[...n,...s],a=new Set(i.map(l=>l.value));return e.run_by.forEach(l=>{a.has(l)||i.push({group:"Invalid",label:l,value:l})}),i},get unmetRunByConditions(){if(!x.isAlive(e))return[];const{run_by:t}=e;if(t.length===0)return[];const n=this.contentModel.payloadForSQL;return t.filter(s=>{const i=v.get(n,s);return Array.isArray(i)?i.length===0:typeof i=="number"?Number.isNaN(i):!i})}})).views(e=>({get payload(){return e.contentModel.payloadForSQL},get formattedSQL(){return Mi(e.sql,this.payload)},get httpConfigString(){const{context:t,filters:n}=this.payload,{name:s,pre_process:i}=e.json,a=b_(i,t,n);return console.groupCollapsed(`Request config for: ${s}`),console.log(a),console.groupEnd(),JSON.stringify(a)},get typedAsSQL(){return[Ee.Postgresql,Ee.MySQL].includes(e.type)},get typedAsHTTP(){return[Ee.HTTP].includes(e.type)},get isTransform(){return e.type===Ee.Transform},get reQueryKey(){const{react_to:t=[]}=e;if(t.length===0)return"";const n=e.contentModel.payloadForSQL,s=[...t].reduce((i,a)=>(i[a]=v.get(n,a),i),{});return JSON.stringify(s)},get runByConditionsMet(){return e.unmetRunByConditions.length===0},get conditionNames(){if(e.unmetRunByConditions.length===0)return{context:[],filters:[]};const{keyLabelMap:t}=e.contentModel.filters,n=e.unmetRunByConditions.filter(i=>i.startsWith("context.")).map(i=>i.replace("context.","")),s=e.unmetRunByConditions.filter(i=>i.startsWith("filters.")).map(i=>v.get({filters:t},i,i.replace("filters.",""))).filter(i=>!!i);return{context:n,filters:s}},get queries(){return x.getParent(e,2)},get inUse(){return this.queries.isQueryInUse(e.id)},get dependencies(){if(!this.typedAsSQL)return[];const t=v.uniq(e.sql.match(Xs.sqlSnippet)),n=v.uniq(e.sql.match(Xs.filter)),s=v.uniq(e.sql.match(Xs.context)),i=[];return t.forEach(a=>{i.push({type:"sql_snippet",key:a,valid:e.contentModel.sqlSnippets.keySet.has(a)})}),n.forEach(a=>{i.push({type:"filter",key:a,valid:e.contentModel.filters.keySet.has(a)})}),s.forEach(a=>{i.push({type:"context",key:a,valid:e.contentModel.mock_context.keySet.has(a)})}),i}})),Tl=x.types.compose("QueryRenderModel",If,x.types.model({state:x.types.optional(x.types.enumeration(["idle","loading","error"]),"idle"),data:x.types.optional(x.types.frozen([]),[]),error:x.types.frozen()})).views(e=>({get datasource(){const{key:t,type:n}=e;return e.rootModel.datasources.find({type:n,key:t})},get additionalQueryInfo(){return e.contentModel.getAdditionalQueryInfo(e.id)},get depQueryModels(){return e.contentModel.queries.findByIDSet(new Set(e.dep_query_ids))},get depQueryModelStates(){return this.depQueryModels.map(t=>t.state)},get depQueryModelStatesString(){return this.depQueryModelStates.toString()}})).views(e=>({get stateMessage(){if(e.state!=="idle")return"";if(!e.runByConditionsMet){const{context:t,filters:n}=e.conditionNames;if(t.length===0&&n.length===0)return"Waiting";const s=[];return t.length>0&&s.push(`context: ${t.join(", ")}`),n.length>0&&s.push(`filter${n.length>1?"s":""}: ${n.join(", ")}`),s.length===2&&s.splice(1,0,"and"),s.unshift("Waiting for"),s.join(" ")}return e.data.length>0?"":"Empty Data"}})).volatile(()=>({controller:new AbortController})).actions(e=>({runSQL:x.flow(function*(){var t;if(e.valid&&((t=e.controller)==null||t.abort(),!!e.runByConditionsMet)){e.controller=new AbortController,e.state="loading";try{const n=e.payload;e.data=yield*x.toGenerator(T_({payload:n,name:e.name,query:e.json,additionals:e.additionalQueryInfo},e.controller.signal)),e.state="idle",e.error=null}catch(n){if(Rt.isCancel(n))console.debug(`🟡 Query[${e.name}] is cancelled`),e.data=[],e.state="idle";else{e.data=[];const s=v.get(n,"message","unkown error");e.error=v.get(n,"response.data.detail.message",s),e.state="error"}}}}),runHTTP:x.flow(function*(){var t;if(!(!e.valid||!e.datasource)&&((t=e.controller)==null||t.abort(),!!e.runByConditionsMet)){e.controller=new AbortController,e.state="loading";try{const{type:n,key:s,post_process:i}=e.json;let a=JSON.parse(e.httpConfigString);a=v_(e.datasource,a);const l=yield*x.toGenerator(D_({type:n,key:s,configString:JSON.stringify(a),name:e.name,additionals:e.additionalQueryInfo},e.controller.signal)),c=__(e.datasource,l),u=j_(i,c,e.contentModel.dashboardState);e.data=u,e.state="idle",e.error=null}catch(n){if(console.error(n),Rt.isCancel(n))console.debug(`🟡 Query[${e.name}] is cancelled`),e.data=[],e.state="idle";else{e.data=[];const s=v.get(n,"message","unkown error");e.error=v.get(n,"response.data.detail.message",s),e.state="error"}}}}),runTransformation(){e.state="loading";try{const n=e.contentModel.queries.findByIDSet(new Set(e.dep_query_ids)).map(l=>({id:l.id,name:l.name,data:v.cloneDeep(l.data)})),s=e.contentModel.dashboardState,i=e.pre_process,a=new Function(`return ${i}`)()(n,s,At);e.data=a,e.state="idle",e.error=null}catch(t){e.data=[],e.error=t.message,e.state="error"}}})).actions(e=>({fetchData:t=>{if(!e.inUse&&!t){console.debug(`🟡 Skipping query[${e.name}]`);return}return console.debug(`🔵 Running query[${e.name}]`),e.isTransform?e.runTransformation():e.typedAsHTTP?e.runHTTP():e.runSQL()},beforeDestroy(){var t;(t=e.controller)==null||t.abort()}})).actions(e=>({afterCreate(){x.addDisposer(e,ae.reaction(()=>{var n;return e.isTransform?[e.inUse,e.id,e.key,e.dep_query_ids.toString(),e.pre_process,e.depQueryModelStatesString].join("--"):e.typedAsHTTP?`${e.inUse}--${e.id}--${e.key}--${e.reQueryKey}--${(n=e.datasource)==null?void 0:n.id}`:[e.inUse,e.id,e.key,e.formattedSQL,e.pre_process,e.post_process].join("--")},t=>(e.name==="getProjectGroupContributors"&&console.log("🔵 deps: ",t),e.fetchData(!1)),{fireImmediately:!0,delay:0}))}})),Dl=x.types.model("QueriesRenderModel",{current:x.types.optional(x.types.array(Tl),[])}).views(e=>({get idSet(){return new Set(e.current.map(t=>t.id))},get firstID(){if(e.current.length!==0)return e.current[0].id},findByID(t){return e.current.find(n=>n.id===t)},findByIDSet(t){return e.current.filter(n=>t.has(n.id))},get json(){return e.current.filter(t=>t.id&&t.key).map(t=>t.json)},get contentModel(){return x.getParent(e,1)},get visibleQueryIDSet(){const{views:t,filters:n,queries:s}=this.contentModel,i=[];t.visibleViews.forEach(c=>{c.panels.forEach(u=>{i.push(...u.queryIDs)})});const a=v.uniq(t.visibleViews.map(c=>c.renderViewIDs).flat());n.current.forEach(c=>{const u=v.get(c,"config.options_query_id");if(!u)return;a.some(h=>c.visibleInViewsIDSet.has(h))&&i.push(u)}),s.findByIDSet(new Set(i)).forEach(c=>{!c.isTransform||c.dep_query_ids.length===0||i.push(...c.dep_query_ids)});const l=new Set(i);return console.debug("QueryIDs:",l),l},isQueryInUse(t){return this.visibleQueryIDSet.has(t)}})).actions(e=>({downloadAllData(){const t=e.current.map(({name:n,data:s})=>({id:n,data:s}));Sf(t)},downloadDataByQueryIDs(t){const n=new Set(t),s=e.current.filter(i=>n.has(i.id)).map(({name:i,data:a})=>({id:i,data:a}));Sf(s)},downloadDataByQueryID(t){const n=e.findByID(t);if(!n){console.log("[downloadDataByQueryID] query not found");return}const{name:s,data:i}=n;kE(s,i)},refetchDataByQueryID(t){const n=e.findByID(t);if(!n){console.error(new Error(`[downloadDataByQueryID] query by ID[${t}] not found`));return}return n.fetchData(!0)},getSchema(t){return{definition:{queries:e.findByIDSet(new Set(t)).map(i=>i.json)},version:gn}},downloadSchema(t){const n=JSON.stringify(this.getSchema(t),null,2);fr("Queries",n)}}));function zf(e){return{current:e}}function Ef({min:e,max:t}){const n=`${e}px`,s=Number.isFinite(t)?`${t}px`:"∞";return`[${n}, ${s})`}const Ml=x.types.model("LayoutsRenderModel",{list:x.types.array(cf),currentBreakpoint:x.types.string}).views(e=>({get json(){return e.list.map(t=>t.json)},jsonByPanelIDSet(t){return e.list.map(n=>n.jsonByPanelIDSet(t))},get root(){return x.getRoot(e)},get contentModel(){return this.root.content},get basisLayoutSet(){return e.list.find(t=>t.id==="basis")},get currentLayoutSet(){return e.list.find(t=>t.id===e.currentBreakpoint)},get currentLayoutRange(){return this.breakpointRanges.find(t=>t.id===e.currentBreakpoint)},get currentRangeText(){const t=this.currentLayoutRange;return Ef(t)},get cols(){const t={};return e.list.forEach(n=>{t[n.id]=36}),t},get breakpoints(){const t={};return e.list.forEach(n=>{t[n.id]=n.breakpoint}),t},get breakpointNameRecord(){const t={};return e.list.forEach(n=>{t[n.name]=n.breakpoint}),t},get breakpointRanges(){const t=e.list.map(n=>({id:n.id,name:n.name,min:n.breakpoint,max:1/0,text:""}));return t.sort((n,s)=>n.min-s.min).forEach((n,s)=>{s!==t.length-1&&(n.max=t[s+1].min)}),t.forEach(n=>{n.text=Ef(n)}),t},get breakpointsInfo(){return e.list.map(t=>({id:t.id,name:t.name,breakpoint:t.breakpoint})).sort((t,n)=>t.breakpoint-n.breakpoint)},get currentBreakpointRange(){return this.breakpointRanges.find(t=>t.id===e.currentBreakpoint)},get currentLayoutPreviewWidth(){const t=this.currentBreakpointRange;if(t)return t.max===1/0?t.min===0?void 0:t.min+1:t.max},items(t){const n=new Set(t);return this.currentLayoutSet.list.filter(i=>n.has(i.panelID))},gridLayouts(t){const n=new Set(t),s={};return e.list.forEach(i=>{s[i.id]=i.list.filter(a=>n.has(a.panelID)).map(a=>a.layoutProperies)}),s},findItemByPanelID(t){return this.currentLayoutSet.findByPanelID(t)}})).actions(e=>({setCurrentBreakpoint(t){console.log("🔴 onBreakpointChange:",t),e.currentBreakpoint=t},afterCreate(){x.addDisposer(e,ae.reaction(()=>e.currentBreakpoint,()=>{setTimeout(()=>{window.dispatchEvent(new Event("resize"))},32)},{fireImmediately:!1,delay:0}))}})),Af=uf.views(e=>({isADuplicatedKey(t){return!t||t===e.key?!1:!!x.getParent(e,2).findByKey(t)}})),Il=x.types.model("SQLSnippetsRenderModel",{current:x.types.optional(x.types.array(Af),[])}).views(e=>({get json(){return e.current.map(t=>t.json)},get record(){return e.current.reduce((t,n)=>(t[n.key]=n.value,t),{})},get keySet(){return new Set(e.current.map(t=>t.key))},get firstKey(){if(e.current.length!==0)return e.current[0].key},findByKey(t){return e.current.find(n=>n.key===t)},findByKeySet(t){return e.current.filter(n=>t.has(n.key))}})).actions(e=>({getSchema(t){return{definition:{sqlSnippets:e.findByKeySet(new Set(t)).map(i=>i.json)},version:gn}},downloadSchema(t){const n=JSON.stringify(this.getSchema(t),null,2);fr("SQL Snippets",n)}}));function Pf(e){return{current:e}}function es(e,t,n,s){return e.reduce((i,a)=>{try{i[a[t]]=Di(a[n],s)}catch(l){i[a[t]]=l.message}return i},{})}class Of{constructor(t){N(this,"origin");N(this,"copy");this.origin=t,this.copy=x.clone(t),ae.makeAutoObservable(this,{},{autoBind:!0,deep:!1})}get changed(){return!v.isEqual(x.getSnapshot(this.origin),x.getSnapshot(this.copy))}commit(){x.applySnapshot(this.origin,x.getSnapshot(this.copy))}reset(){x.applySnapshot(this.copy,x.getSnapshot(this.origin))}update(t){x.applySnapshot(this.copy,t)}}const Lf=e=>new Of(e),DE=D.observer(()=>{const{t:e}=j.useTranslation(),t=le(),{panel:n}=Je(),s=n.realQueryOptions,i=a=>{t.editor.open(["_QUERIES_",a])};return s.length===0?null:r.jsxs(r.Fragment,{children:[r.jsx(o.Divider,{label:e(s.length>1?"query.labels":"query.label"),labelPosition:"center"}),s.map(a=>r.jsx(o.Menu.Item,{onClick:()=>i(a.value),icon:r.jsx(M.IconDatabase,{size:14}),children:a.label},a.value))]})}),ME=D.observer(({view:e,title:t})=>{const{t:n}=j.useTranslation(),s=le(),i=re(),a=wt.useModals(),{panel:l,downloadPanelScreenshot:c}=Je(),{id:u}=l,{viewPanelInFullScreen:d,inFullScreen:h}=g.useContext(pi),p=()=>{i.duplicatePanelByID(u,e.id)},f=()=>{s.editor.open(["_VIEWS_",e.id,"_PANELS_",u])},m=()=>a.openConfirmModal({title:`${n("panel.delete")}?`,labels:{confirm:n("common.actions.confirm"),cancel:n("common.actions.cancel")},onCancel:()=>console.log("Cancel"),onConfirm:()=>i.removePanelByID(u,e.id),confirmProps:{color:"red"},zIndex:320}),y=g.useCallback(()=>{d(u)},[u,d]),_=!h&&e.type!==G.Modal;return r.jsx(r.Fragment,{children:r.jsx(o.Box,{sx:{position:"absolute",top:0,left:0,right:0,zIndex:300},title:t,children:r.jsxs(o.Menu,{withinPortal:!0,children:[r.jsx(o.Menu.Target,{children:r.jsx(o.Box,{className:"panel-dropdown-target",sx:{width:"100%"}})}),r.jsxs(o.Menu.Dropdown,{children:[r.jsx(o.Menu.Item,{onClick:l.refreshData,icon:r.jsx(W.Refresh,{size:14}),children:n("common.actions.refresh")}),r.jsx(o.Menu.Item,{onClick:l.downloadData,icon:r.jsx(W.Download,{size:14}),children:n("common.actions.download_data")}),r.jsx(o.Menu.Item,{onClick:l.downloadSchema,icon:r.jsx(M.IconCode,{size:14}),children:n("common.actions.download_schema")}),r.jsx(o.Menu.Item,{onClick:c,icon:r.jsx(M.IconCamera,{size:14}),children:n("common.actions.download_screenshot")}),_&&r.jsx(o.Menu.Item,{onClick:y,icon:r.jsx(W.ArrowsMaximize,{size:14}),disabled:!0,children:n("common.actions.enter_fullscreen")}),r.jsx(DE,{}),r.jsx(o.Divider,{label:n("common.actions.edit"),labelPosition:"center"}),r.jsx(o.Menu.Item,{onClick:f,icon:r.jsx(W.Settings,{size:14}),children:n("common.titles.settings")}),r.jsx(o.Menu.Item,{onClick:p,icon:r.jsx(W.Copy,{size:14}),children:n("common.actions.duplicate")}),r.jsx(o.Menu.Item,{color:"red",onClick:m,icon:r.jsx(W.Trash,{size:14}),children:n("common.actions.delete")})]})]})})})});function IE(e){return e?["<p><br></p>","<p></p>"].includes(e):!0}const zl=D.observer(()=>{const{t:e}=j.useTranslation(),[t,n]=g.useState(!1),{panel:s}=Lt();return IE(s.description)?null:r.jsxs(r.Fragment,{children:[r.jsx(o.Modal,{opened:t,onClose:()=>n(!1),title:s.title.show?s.name:"",withCloseButton:!1,withinPortal:!0,zIndex:310,children:r.jsx(Kr,{value:s.description,styles:{root:{border:"none"},content:{padding:0}},sx:{".mantine-RichTextEditor-content .ProseMirror":{padding:"0 !important"}}})}),r.jsx(o.Tooltip,{label:e("panel.panel_description_click"),position:"top-start",withinPortal:!0,children:r.jsx(o.ActionIcon,{variant:"subtle",color:"blue",onClick:()=>n(i=>!i),sx:{verticalAlign:"baseline",cursor:"pointer"},children:r.jsx(W.InfoCircle,{size:20})})})]})}),bV="",zE=D.observer(function(){const{panel:t}=Lt(),{name:n,title:s}=t;return s.show?r.jsx(o.Group,{grow:!0,position:"center",className:"panel-title-wrapper",sx:{flexGrow:1},children:r.jsx(o.Text,{align:"center",lineClamp:1,className:"panel-title-text",children:n})}):null});function EE(e){const t=g.useRef(null);return{ref:t,downloadPanelScreenshot:()=>{const s=t.current;if(!s)return;const i=s.offsetWidth*2,a=s.offsetHeight*2;_c.toBlob(t.current,{bgcolor:"white",width:i,height:a,style:{border:"none",borderRadius:0,transformOrigin:"0 0",transform:"scale(2)"}}).then(l=>{window.saveAs(l,`${e.name?e.name:e.viz.type}.png`)})}}}var Vf=(e=>(e.migrated="migrated",e.nothingToMigrate="nothingToMigrate",e.checkFailed="checkFailed",e.migrationFailed="migrationFailed",e))(Vf||{}),gi=(e=>(e.notStarted="notStarted",e.inProgress="inProgress",e.done="done",e))(gi||{});class AE{constructor(t){N(this,"vizInstance");N(this,"operationManager");N(this,"triggerManager");N(this,"vizManager");N(this,"runningMigration");N(this,"panelModel");N(this,"status","notStarted");this.panelModel=t.getRequired(Oe.instanceScope.panelModel),this.vizInstance=t.getRequired(Oe.instanceScope.vizInstance),this.operationManager=t.getRequired(Oe.instanceScope.operationManager),this.triggerManager=t.getRequired(Oe.instanceScope.triggerManager),this.vizManager=t.getRequired(Oe.vizManager)}async createMigrationTask(){const t=[];try{await this.instanceNeedMigration()&&t.push(()=>this.runInstanceMigration()),await this.interactionNeedMigration()&&t.push(()=>this.runInteractionMigration())}catch(n){return console.warn("check migration failed",n),"checkFailed"}if(t.length===0)return"nothingToMigrate";try{return await Promise.all(t.map(n=>n())),"migrated"}catch(n){return console.warn("migration failed",n),"migrationFailed"}}async runMigration(){return this.runningMigration||(this.status="inProgress",this.runningMigration=this.createMigrationTask().then(t=>(this.status="done",t))),this.runningMigration}async runInteractionMigration(){await this.operationManager.runMigration(),await this.triggerManager.runMigration()}async runInstanceMigration(){const t=this.vizManager.resolveComponent(this.vizInstance.type),n={configData:this.vizInstance.instanceData,panelModel:this.panelModel};await t.migrator.migrate(n)}async instanceNeedMigration(){const t=this.vizManager.resolveComponent(this.vizInstance.type),n={configData:this.vizInstance.instanceData};return t.migrator.needMigration(n)}async interactionNeedMigration(){return await this.operationManager.needMigration()||await this.triggerManager.needMigration()}}function Bf(e){const{panel:t}=Lt();return g.useCallback(n=>{const s=n.getRequired(Oe.vizManager),i=s.resolveComponent(e.viz.type);return n.createScoped().provideFactory(Oe.instanceScope.vizInstance,()=>s.getOrCreateInstance(e)).provideFactory(Oe.instanceScope.interactionManager,a=>{const l=a.getRequired(Oe.instanceScope.vizInstance);return new yo(l,i,Hs)}).provideFactory(Oe.instanceScope.operationManager,a=>a.getRequired(Oe.instanceScope.interactionManager).operationManager).provideFactory(Oe.instanceScope.triggerManager,a=>a.getRequired(Oe.instanceScope.interactionManager).triggerManager).provideValue(Oe.instanceScope.panelModel,t).provideFactory(Oe.instanceScope.migrator,a=>new AE(a))},[e.viz.type,e.viz.conf])}function qf(e){const[t,n]=g.useState(!1),s=Xh().getRequired(Oe.instanceScope.migrator);return J.useAsyncEffect(async()=>{const i=s.status===gi.notStarted;n(s.status===gi.done),s.status===gi.notStarted&&s.runMigration().then(a=>{a===Vf.migrated&&i&&(e==null||e())}).finally(()=>{n(!0)})},[s]),t}function Nf(e,t){const n=Xh().getRequired(Oe.instanceScope.vizInstance);return g.useEffect(()=>(n.instanceData.setItem(null,t.viz.conf),n.instanceData.watchItem(null,s=>{e(s)})),[e,t.viz.type]),n}function PE({setVizConf:e,...t}){const{panel:n}=t,s=Nf(e,n),i=qf(()=>{Yt.showNotification({title:`${n.name} - Updated`,message:"Your plugin configuration has been migrated to the latest version"})});return J.useAsyncEffect(async()=>{await s.instanceData.setItem(null,n.viz.conf)},[s,n.viz.type]),i?r.jsx(E_,{...t}):r.jsx(o.Text,{children:"Checking update..."})}function OE(e){const{panel:t,setVizConf:n}=e;Nf(n,t);const{inEditMode:s}=g.useContext(Ss);return qf(()=>{s&&Yt.showNotification({title:`${t.name} - Updated`,message:"Your plugin configuration has been migrated to the latest version"})})?r.jsx(z_,{...e}):r.jsx(o.Text,{children:"Checking update"})}const vV="";function LE(e,t){const{vizManager:n}=g.useContext(rn),{panel:{viz:s,title:i,id:a,name:l,description:c,queryIDs:u,variables:d}}=Lt(),h={id:a,name:l,title:i,description:c,queryIDs:u,viz:s},p=Bf(h);try{return n.resolveComponent(s.type),r.jsx(di,{configure:p,children:r.jsx(OE,{setVizConf:s.setConf,panel:h,measure:t,data:e,variables:d,vizManager:n})})}catch(f){return console.info(v.get(f,"message")),null}}const $f=D.observer(function({data:t}){const{ref:n,width:s,height:i}=Se.useElementSize(),a=LE(t,{w:s,h:i}),l=s>0&&i>0;return r.jsx("div",{className:"viz-root",ref:n,children:r.jsx(o.Box,{sx:{width:s,height:i,overflow:"hidden"},children:l&&r.jsx(Re,{children:a})})})}),Ff=D.observer(({panel:e})=>r.jsxs(o.Stack,{children:[e.queryErrors.map((t,n)=>r.jsx(o.Text,{color:"red",size:"sm",align:"center",sx:{fontFamily:"monospace"},children:t},`${n}-${t}`)),r.jsx(o.Text,{color:"gray",align:"center",size:"sm",children:e.queryStateMessages})]})),El=D.observer(({panel:e})=>r.jsxs(o.Flex,{className:"panel-viz-section",direction:"column",sx:{position:"relative",width:"100%"},children:[r.jsx(o.LoadingOverlay,{visible:e.dataLoading,exitTransitionDuration:0}),!e.canRenderViz&&r.jsx(Ff,{panel:e}),e.canRenderViz&&r.jsx($f,{data:e.data})]})),VE={border:"1px solid #e9ecef"},Gf=D.observer(({panel:e,panelStyle:t,dropdownContent:n})=>{const{ref:s,downloadPanelScreenshot:i}=EE(e);return e.title.show,r.jsx(ra,{value:{panel:e,data:e.data,loading:e.dataLoading,errors:e.queryErrors,downloadPanelScreenshot:i},children:r.jsxs(o.Box,{className:`panel-root ${e.title.show?"panel-root--show-title":""}`,ref:s,p:0,sx:{...VE,...t},children:[r.jsx(o.Box,{className:"panel-description-popover-wrapper",children:r.jsx(zl,{})}),n,r.jsx(zE,{}),r.jsx(El,{panel:e})]})})}),BE={border:"1px dashed transparent",transition:"border-color 300ms ease","&:hover":{borderColor:"#e9ecef"}};function qE(e){return e.style.border.enabled?{}:BE}const Wf=D.observer(function({panel:t,view:n}){const s=qE(t);return r.jsx(Gf,{panel:t,panelStyle:s,dropdownContent:r.jsx(ME,{view:n,title:t.name})})});function NE(e){return!["richText","button"].includes(e)}const $E=D.observer(({view:e,title:t})=>{const{t:n}=j.useTranslation(),{panel:s,downloadPanelScreenshot:i}=Lt(),{id:a}=s,{viewPanelInFullScreen:l,inFullScreen:c}=g.useContext(pi),u=g.useCallback(()=>{l(a)},[a,l]),d=!c&&e.type!==G.Modal;return NE(s.viz.type)?r.jsx(o.Box,{sx:{position:"absolute",top:0,left:0,right:0,zIndex:300},title:t,children:r.jsxs(o.Menu,{withinPortal:!0,children:[r.jsx(o.Menu.Target,{children:r.jsx(o.Box,{className:"panel-dropdown-target"})}),r.jsxs(o.Menu.Dropdown,{children:[r.jsx(o.Menu.Item,{onClick:s.refreshData,icon:r.jsx(W.Refresh,{size:14}),children:n("common.actions.refresh")}),r.jsx(o.Menu.Item,{onClick:s.downloadData,icon:r.jsx(W.Download,{size:14}),children:n("common.actions.download_data")}),r.jsx(o.Menu.Item,{onClick:i,icon:r.jsx(M.IconCamera,{size:14}),children:n("common.actions.download_screenshot")}),d&&r.jsx(o.Menu.Item,{onClick:u,icon:r.jsx(W.ArrowsMaximize,{size:14}),children:n("common.actions.enter_fullscreen")})]})]})}):null});function FE(e){return e.style.border.enabled?{}:{border:"1px dashed transparent"}}const Al=D.observer(({panel:e,view:t})=>{const n=FE(e);return r.jsx(Gf,{panel:e,panelStyle:n,dropdownContent:r.jsx($E,{title:e.name,view:t})})}),GE={modal:{display:"flex",flexDirection:"column",flexWrap:"nowrap"},body:{display:"flex",height:"calc(100vh - 88px)"}},Rf=D.observer(function({view:t,panel:n,exitFullScreen:s}){return r.jsx(o.Modal,{opened:!0,fullScreen:!0,onClose:s,title:r.jsx(o.Button,{color:"blue",size:"xs",onClick:s,leftIcon:r.jsx(W.ArrowLeft,{size:20}),children:"Exit fullscreen"}),styles:GE,children:r.jsx(o.Group,{grow:!0,sx:{flexGrow:1,flexShrink:0},children:r.jsx(Al,{view:t,panel:n})})})});function Qf(e,t,n){const{panels:s}=Pe(),i=e.id==="Main",[a,l]=g.useState(()=>i&&s.findByID(t)?t:null),c=g.useCallback(p=>{l(p),i&&n(p)},[i,n]),u=g.useCallback(()=>{l(null),i&&n("")},[i,n]),d=a?s.findByID(a):null;return{viewPanelInFullScreen:c,exitFullScreen:u,inFullScreen:!!d,fullScreenPanel:d}}const _V="",WE=g.forwardRef(({h:e},t)=>r.jsx(o.ActionIcon,{ref:t,className:"react-grid-customDragHandle",sx:{userSelect:"none",cursor:"grab",position:"absolute",top:5,right:e>38?5:20,zIndex:400,"&:hover":{color:"#228be6"}},variant:"transparent",children:r.jsx(W.ArrowsMove,{size:16})})),RE=g.forwardRef(({handleAxis:e,...t},n)=>r.jsx(o.ActionIcon,{ref:n,className:"react-grid-customResizeHandle",sx:{userSelect:"none",cursor:"nwse-resize",position:"absolute",bottom:0,right:0,zIndex:400,"&:hover":{color:"#228be6"}},variant:"transparent",...t,children:r.jsx(W.ChevronDownRight,{size:16})})),QE=as.WidthProvider(as.Responsive),UE=D.observer(({view:e,className:t="layout"})=>{const s=re().layouts,i=s.items(e.panelIDs),a=s.gridLayouts(e.panelIDs),l=(d,h,p,f)=>{console.log("🔴 onResize",d),p.h<30&&(p.h=30,f.h=30),p.w<4&&(p.w=4,f.w=4)},c=(d,h,p)=>{console.log("🔴 onResizeStop",{layouts:d,oldItem:h,newItem:p}),s.updateCurrentLayoutItem(p)},u=(d,h,p)=>{console.log("🔴 onDragStop",{layouts:d,oldItem:h,newItem:p}),s.updateCurrentLayoutItems(d)};return r.jsx(QE,{className:`dashboard-layout ${t}`,rowHeight:1,margin:[0,0],isBounded:!0,isDraggable:!0,isResizable:!0,cols:s.cols,layouts:a,draggableHandle:".react-grid-customDragHandle",resizeHandle:r.jsx(RE,{}),onResize:l,breakpoints:s.breakpoints,onBreakpointChange:s.setCurrentBreakpoint,onResizeStop:c,onDragStop:u,width:s.currentLayoutPreviewWidth,children:i.map(d=>r.jsxs("div",{"data-grid":d.layoutProperies,className:"panel-grid-item",children:[r.jsx(WE,{h:d.h}),r.jsx(Wf,{view:e,panel:d.panel})]},d.id))})}),YE=as.WidthProvider(as.Responsive),KE=D.observer(({view:e,className:t="layout"})=>{const n=Pe(),s=n.layouts.items(e.panelIDs),i=n.layouts.gridLayouts(e.panelIDs);return r.jsx(YE,{className:`dashboard-layout ${t}`,rowHeight:1,margin:[0,0],isDraggable:!1,isResizable:!1,cols:n.layouts.cols,layouts:i,breakpoints:n.layouts.breakpoints,onBreakpointChange:n.layouts.setCurrentBreakpoint,children:s.map(a=>r.jsx("div",{"data-grid":a.layoutProperies,className:"panel-grid-item",children:r.jsx(Al,{view:e,panel:a.panel})},a.id))})});function Pl(e){const t=g.useRef(null);return{ref:t,downloadScreenshot:()=>{var i;const s=(i=t.current)==null?void 0:i.querySelector(".react-grid-layout");s&&e.downloadScreenshot(s)}}}const XE=D.observer(({downloadScreenshot:e})=>{const{t}=j.useTranslation(),[n,{setTrue:s,setFalse:i}]=J.useBoolean(!1),a=wu(),l=Pe(),c=()=>{const u=JSON.stringify(l.contentJSON,null,2),d=`${a.name}__${l.name}`;fr(d,u)};return r.jsxs(o.Menu,{shadow:"md",width:200,trigger:"hover",openDelay:200,closeDelay:400,withinPortal:!0,position:"bottom-end",children:[r.jsx(o.Menu.Target,{children:r.jsx(o.Affix,{position:{bottom:"20px",right:"10px"},zIndex:1,children:r.jsx(o.ActionIcon,{size:"md",variant:"gradient",gradient:{from:"indigo",to:"cyan"},onMouseEnter:s,onMouseLeave:i,sx:{opacity:n?1:.6,transform:`translateX(${n?0:"2px"})`,transition:"all ease 300ms",borderRadius:"50%"},children:r.jsx(M.IconShare3,{size:"1rem"})})})}),r.jsxs(o.Menu.Dropdown,{children:[r.jsx(o.Menu.Item,{icon:r.jsx(M.IconCamera,{size:14}),onClick:e,children:t("common.actions.download_screenshot")}),r.jsx(o.Menu.Divider,{}),r.jsx(o.Menu.Item,{icon:r.jsx(M.IconDownload,{size:14}),onClick:l.queries.downloadAllData,children:t("common.actions.download_data")}),r.jsx(o.Menu.Item,{icon:r.jsx(M.IconCode,{size:14}),onClick:c,children:t("common.actions.download_schema")})]})]})}),Uf=D.observer(({children:e,view:t,sx:n={}})=>{const{ref:s,downloadScreenshot:i}=Pl(t);return r.jsxs(r.Fragment,{children:[r.jsx(o.Box,{ref:s,pt:10,pb:10,sx:n,children:e}),r.jsx(XE,{downloadScreenshot:i})]})}),Yf=D.observer(({downloadScreenshot:e})=>r.jsx(o.ActionIcon,{className:"download-screenshot-button",color:"blue",onClick:e,children:r.jsx(M.IconCamera,{size:14})})),JE=D.observer(({children:e,view:t})=>{const n=Pe(),s=t.config,i=n.views.visibleViewIDs.includes(t.id),a=()=>n.views.rmVisibleViewID(t.id),{ref:l,downloadScreenshot:c}=Pl(t);return r.jsx(o.Modal,{size:s.width,centered:!0,opened:i,onClose:a,withCloseButton:!1,title:r.jsxs(o.Group,{position:"apart",px:"1rem",h:"48px",children:[r.jsx(o.Box,{children:s.custom_modal_title.value}),r.jsx(Yf,{downloadScreenshot:c})]}),trapFocus:!0,onDragStart:u=>{u.stopPropagation()},styles:{root:{position:"fixed",zIndex:200,inset:0},overlay:{zIndex:"unset"},inner:{zIndex:"unset",padding:"0 !important"},content:{border:"1px solid #efefef",maxHeight:"unset !important",overflow:"hidden"},body:{maxHeight:s.height,overflow:"auto",position:"relative",paddingBottom:10},header:{padding:0},title:{flexGrow:1}},transitionProps:{duration:0},children:r.jsx(o.Box,{ref:l,children:e})})}),ZE=e=>e.color?{"&[data-active], &[data-active]:hover":{borderColor:e.color?e.color:"..."}}:{},HE=D.observer(({view:e})=>{const t=Pe(),n=e.config;return r.jsxs(o.Tabs,{className:"render-view-tabs",variant:n.variant,orientation:n.orientation,value:e.tab,onTabChange:e.setTab,styles:{root:{height:"100%",overflow:n.orientation==="horizontal"?"hidden":"auto"},panel:{padding:n.orientation==="horizontal"?"0px 0px 36px":"0",height:"100%",overflow:"auto"}},keepMounted:!1,children:[r.jsx(o.Tabs.List,{grow:n.grow,children:n.tabsInOrder.map(s=>r.jsx(o.Tabs.Tab,{value:s.id,sx:ZE(s),disabled:!s.view_id,children:s.name??s.id},s.id))}),n.tabsInOrder.map(s=>{const i=t.views.findByID(s.view_id);return i?r.jsx(o.Tabs.Panel,{value:s.id,children:r.jsx(mi,{view:i})},s.id):null})]})}),eA=D.observer(({view:e,children:t})=>{switch(e.type){case G.Modal:return r.jsx(JE,{view:e,children:t});case G.Tabs:return r.jsx(HE,{view:e});case G.Division:default:return r.jsx(Uf,{view:e,children:t})}}),tA=D.observer(({children:e,view:t})=>{const s=re().layouts,[i,a]=Se.useResizeObserver();return g.useEffect(()=>{s.setCurrentLayoutWrapperWidth(a.width)},[a.width]),r.jsx(o.Box,{sx:{height:"100%"},ref:i,children:r.jsx(o.Box,{sx:{paddingBottom:"100px",background:"white",margin:"0 auto",width:s.currentLayoutPreviewWidth??"100%",transform:`scale(${s.divisionPreviewScale})`,transformOrigin:"0 0"},children:r.jsx(Uf,{view:t,sx:{paddingTop:"0px !important",".dashboard-sticky-area > form":{paddingBottom:"5px"},".dashboard-layout":{marginTop:0,marginBottom:0}},children:e})})})});function Kf(e){return e.replace(/(vw|vh)/,"%")}const nA=D.observer(({children:e,view:t})=>{const n=t.config,{width:s,height:i}=g.useMemo(()=>({width:Kf(n.width),height:Kf(n.height)}),[n.width,n.height]),{ref:a,downloadScreenshot:l}=Pl(t);return r.jsx(o.Box,{sx:{height:"100%","> div:not(.mantine-Modal-root)":{height:"100%"}},children:r.jsx(o.Modal,{size:n.width,opened:!0,onClose:v.noop,withCloseButton:!1,title:r.jsxs(o.Group,{position:"apart",px:"1rem",h:"48px",children:[r.jsx(o.Box,{children:n.custom_modal_title.value}),r.jsx(Yf,{downloadScreenshot:l})]}),trapFocus:!0,onDragStart:c=>{c.stopPropagation()},styles:{root:{position:"relative",height:"100%"},overlay:{position:"absolute !important"},inner:{position:"relative",top:"50%",left:"50%",right:"unset",bottom:"unset",transform:"translate(-50%, -50%)",padding:"0 !important",width:s,height:i,maxHeight:i},content:{border:"1px solid #efefef",height:"100%"},body:{maxHeight:"calc(100% - 48px)",overflow:"auto"},header:{padding:0},title:{flexGrow:1}},withinPortal:!1,transitionProps:{duration:0},children:r.jsx(o.Box,{ref:a,children:e})})})}),rA=({variant:e,orientation:t})=>{const n={root:{height:"100%",overflow:"hidden"},tabsList:{backgroundColor:"white"},tab:{},panel:{padding:"16px"}};return e==="pills"&&t==="horizontal"&&(n.tab.paddingTop="6px",n.tab.paddingBottom="6px"),t==="vertical"&&(n.tab["&.add-a-tab"]={paddingTop:"1px",paddingBottom:"1px"},n.tab["&.add-a-tab .mantine-Tabs-tabLabel"]={marginLeft:"auto",marginRight:"auto"}),n},sA=e=>e.color?{"&[data-active], &[data-active]:hover":{borderColor:e.color?e.color:"..."}}:{},iA=D.observer(({view:e})=>{const{t}=j.useTranslation(),n=wt.useModals(),s=re(),i=g.useMemo(()=>s.views.options.filter(u=>u.type===G.Division),[e.id,s.views.options]),a=e.config,l=u=>n.openConfirmModal({title:`${t("view.component.tabs.tab.delete")}?`,labels:{confirm:t("common.actions.confirm"),cancel:t("common.actions.cancel")},onCancel:()=>console.log("Cancel"),onConfirm:()=>{a.removeTab(u)},confirmProps:{color:"red"},zIndex:320}),c=a.tabs.length===0;return r.jsxs(o.Tabs,{className:"preview-view-tabs",variant:a.variant,orientation:a.orientation,value:e.tab,onTabChange:e.setTab,styles:rA(a),children:[r.jsxs(o.Tabs.List,{grow:a.grow,children:[a.tabsInOrder.map(u=>r.jsx(o.Tabs.Tab,{value:u.id,sx:sA(u),children:u.name??u.id},u.id)),r.jsx(o.Tabs.Tab,{onClick:a.addTab,value:"add",className:"add-a-tab",children:r.jsx(W.Plus,{size:18,color:"#228be6"})})]}),a.tabsInOrder.map((u,d)=>{const h=s.views.findByID(u.view_id);return r.jsxs(o.Tabs.Panel,{value:u.id,sx:{position:"relative"},children:[r.jsxs(o.Box,{sx:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:200},children:[r.jsx(o.Overlay,{opacity:.8,color:"#FFF",blur:10,zIndex:100}),r.jsxs(o.Stack,{mx:"auto",mt:100,sx:{width:"300px",position:"relative",zIndex:200},children:[r.jsx(o.TextInput,{label:t("view.component.tabs.tab.name"),required:!0,value:u.name,onChange:p=>u.setName(p.currentTarget.value)}),r.jsx(o.Select,{label:"View",value:u.view_id,onChange:u.setViewID,data:i}),r.jsx(o.NumberInput,{label:t("view.component.tabs.tab.order"),required:!0,value:u.order,onChange:p=>u.setOrder(p||0),min:0,max:1e3,step:1}),r.jsx(o.ColorInput,{label:t("view.component.tabs.tab.color"),value:u.color,onChange:u.setColor,disabled:a.variant!=="default"}),h&&r.jsx(o.Button,{mt:20,variant:"gradient",leftIcon:r.jsx(M.IconArrowsLeftRight,{size:18}),gradient:{from:"cyan",to:"indigo"},onClick:()=>s.views.setIDOfVIE(h.id),children:t("view.component.tabs.tab.switch_to_view",{name:h.name})}),r.jsx(o.Button,{mt:20,variant:"subtle",color:"red",onClick:()=>l(d),disabled:c,leftIcon:r.jsx(M.IconTrash,{size:14}),children:t("view.component.tabs.tab.delete")})]})]}),h&&r.jsx(mi,{view:h})]},u.id)})]})}),aA=D.observer(({view:e,children:t})=>{switch(e.type){case G.Modal:return r.jsx(nA,{view:e,children:t});case G.Tabs:return r.jsx(iA,{view:e});case G.Division:default:return r.jsx(tA,{view:e,children:t})}}),Xf=D.observer(function({view:t}){const s=re().layouts.divisionPreviewScale!==1;return r.jsx(pi.Provider,{value:{viewPanelInFullScreen:v.noop,inFullScreen:!1},children:r.jsx(o.Box,{className:"dashboard-view","data-enable-scrollbar":!0,sx:{background:s?"transparent":"#efefef"},children:r.jsx(aA,{view:t,children:r.jsxs(o.Box,{sx:{position:"relative"},children:[r.jsx(o.Box,{className:"dashboard-sticky-area",sx:{position:"sticky",top:"0px"},children:r.jsx(ef,{view:t})}),r.jsx(UE,{view:t})]})})})})}),mi=D.observer(function({view:t}){const{fullScreenPanelID:n,setFullScreenPanelID:s}=Eu(),{viewPanelInFullScreen:i,exitFullScreen:a,inFullScreen:l,fullScreenPanel:c}=Qf(t,n,s);return r.jsx(pi.Provider,{value:{viewPanelInFullScreen:i,inFullScreen:l},children:r.jsxs(o.Box,{className:"dashboard-view","data-enable-scrollbar":!0,sx:{height:t.type===G.Modal?"0 !important":"100%"},children:[l&&r.jsx(Rf,{view:t,panel:c,exitFullScreen:a}),r.jsx(eA,{view:t,children:r.jsxs(o.Box,{sx:{position:"relative"},children:[!l&&r.jsx(o.Box,{className:"dashboard-sticky-area",sx:{position:"sticky",top:"0px"},children:r.jsx(ef,{view:t})}),!l&&r.jsx(KE,{view:t})]})})]})})});var Jf=(e=>(e.Use="use",e.Edit="edit",e))(Jf||{});const oA={[G.Division]:"Division",[G.Tabs]:"Tabs",[G.Modal]:"Modal"},Zf={[G.Division]:"rgba(255, 0, 0, 0.2)",[G.Modal]:"rgba(0, 0, 0, 0.2)",[G.Tabs]:"rgba(255, 200, 100, 0.4)"},lA={[G.Division]:"#ff4000",[G.Modal]:"#000",[G.Tabs]:"#ffad18"};function cA(e,t,n){x.addDisposer(e,x.addMiddleware(e,(s,i)=>{i(s,()=>{x.getType(s.context)===t&&s.type==="action"&&n(s.name,s.context)})}))}const Hf=x.types.compose("FiltersModel",Sl,x.types.model("FiltersModel",{previewValues:x.types.optional(x.types.frozen(),{})})).views(e=>({get idSet(){return new Set(e.current.map(t=>t.id))},get keySet(){return new Set(e.current.map(t=>t.key))},get options(){return e.current.map(t=>({label:t.label??t.id,value:t.id,_type:"filter"}))},get selects(){return e.current.filter(t=>t.type===Ce.Select).map(t=>({label:t.label??t.id,value:t.id}))},get keyLabelOptions(){return e.current.map(t=>({label:t.label??t.key,value:t.key}))},get sortedList(){return v.sortBy(e.current,t=>t.label.toLowerCase())}})).actions(e=>({replace(t){e.current=x.cast(t)},append(t){e.current.push(t)},appendMultiple(t){if(t.length===0)return;const n=t.filter(s=>!e.idSet.has(s.id));e.current.push(...n)},remove(t){e.current.splice(t,1)},removeByID(t){const n=e.current.findIndex(s=>s.id===t);n>=0&&e.current.splice(n,1)},updatePreviewValues(t){e.previewValues=t}})).actions(e=>{function t(){cA(e.current,fl,(n,s)=>{if(n==="setType"){const i=Df(s.config.default_value,s.config);e.setValueByKey(s.key,i),e.updatePreviewValues({...e.previewValues,[s.key]:i})}})}return{afterCreate(){t()}}}),eg=Tl.views(e=>({get canPreviewData(){return e.isTransform?e.dep_query_ids.length>0&&!!e.pre_process:!!e.datasource},get guideToPreviewData(){return e.isTransform?"Need to complete settings in Transform tab":"Need to pick a Data Source first"}})),tg=x.types.compose("QueriesModel",Dl,x.types.model({current:x.types.optional(x.types.array(eg),[])})).views(e=>({get options(){const t=e.current.map(n=>({value:n.id,label:n.name,_type:"query"}));return v.sortBy(t,n=>n.label.toLowerCase())},get optionsWithoutTransform(){const t=e.current.filter(n=>n.type!==Ee.Transform).map(n=>({value:n.id,label:n.name,_type:"query"}));return v.sortBy(t,n=>n.label.toLowerCase())},get sortedList(){return v.sortBy(e.current,t=>t.name.toLowerCase())}})).actions(e=>({replace(t){e.current=x.cast(t)},append(t){e.current.push(t)},appendMultiple(t){if(t.length===0)return;const n=t.filter(s=>!e.idSet.has(s.id));e.current.push(...n)},remove(t){e.current.splice(t,1)},replaceByIndex(t,n){e.current.splice(t,1,n)},removeQuery(t){const n=e.current.find(s=>s.id===t);n&&(x.detach(n),e.current.remove(n))},removeQueries(t){const n=new Set(t);e.current.forEach(i=>{n.has(i.id)&&x.detach(i)});const s=[...e.current];v.remove(s,i=>n.has(i.id)),e.current=x.cast(s)}})),ng=Il.views(e=>({get sortedList(){return v.sortBy(e.current,t=>t.key.toLowerCase())},get options(){const t=e.current.map(n=>({label:n.key,value:n.key,_type:"sql_snippet"}));return v.sortBy(t,n=>n.label.toLowerCase())}})).actions(e=>({replace(t){e.current=x.cast(t)},append(t){e.current.push(t)},appendMultiple(t){if(t.length===0)return;const n=t.filter(s=>!e.keySet.has(s.key));e.current.push(...n)},remove(t){e.current.splice(t,1)},removeByKey(t){const n=e.current.findIndex(s=>s.key===t);n>=0&&e.current.splice(n,1)},removeByKeys(t){const n=new Set(t);e.current.forEach(i=>{n.has(i.key)&&x.detach(i)});const s=[...e.current];v.remove(s,i=>n.has(i.key)),e.current=x.cast(s)},replaceByIndex(t,n){e.current.splice(t,1,n)}})),uA=x.types.model({data:x.types.optional(x.types.frozen(),[]),state:x.types.optional(x.types.enumeration(["idle","loading","error"]),"idle"),error:x.types.frozen()}).views(e=>({get loading(){return e.state==="loading"},get empty(){return e.data.length===0}})),dA=x.types.model({data:x.types.optional(x.types.frozen(),[]),state:x.types.optional(x.types.enumeration(["idle","loading","error"]),"idle"),error:x.types.frozen()}).views(e=>({get loading(){return e.state==="loading"},get empty(){return e.data.length===0}})),pA=x.types.model({page:x.types.optional(x.types.number,1),limit:x.types.optional(x.types.number,20),data:x.types.optional(x.types.frozen(),[]),total:x.types.optional(x.types.number,0),state:x.types.optional(x.types.enumeration(["idle","loading","error"]),"idle"),error:x.types.frozen()}).views(e=>({get keywords(){return x.getParent(e,1)},get keywordString(){const{table_name:t,table_schema:n}=x.getParent(e,1);return`${n}||${t}`}})).views(e=>({get loading(){return e.state==="loading"},get empty(){return e.data.length===0},get maxPage(){return Math.ceil(e.total/e.limit)},get offset(){return(e.page-1)*e.limit},get countSql(){const{table_name:t,table_schema:n}=e.keywords;return`
471
471
  SELECT count(*) AS total
472
472
  FROM ${n}.${t}
473
473
  `}})).actions(e=>({setPage(t){e.page=t},resetPage(){e.page=1},setLimit(t){e.limit=t}})).actions(e=>({afterCreate(){x.addDisposer(e,ae.reaction(()=>e.keywordString,e.resetPage,{fireImmediately:!1,delay:0})),x.addDisposer(e,ae.reaction(()=>e.limit,e.resetPage,{fireImmediately:!1,delay:0}))}})),hA=x.types.model({data:x.types.optional(x.types.frozen(),{}),state:x.types.optional(x.types.enumeration(["idle","loading","error"]),"idle"),error:x.types.frozen()}).views(e=>({get loading(){return e.state==="loading"},get empty(){return Object.keys(e.data).length===0}})),fA=x.types.compose("DataSourceModel",yl,x.types.model({tables:x.types.optional(hA,{}),columns:x.types.optional(uA,{}),tableData:x.types.optional(pA,{}),indexes:x.types.optional(dA,{}),table_schema:x.types.optional(x.types.string,""),table_name:x.types.optional(x.types.string,"")})).views(e=>({get sqlDataSourceType(){return e.type},get reloadConditionString(){const{type:t,table_name:n,table_schema:s}=e;return`${t};${n};${s}`}})).volatile(()=>({controllers:{tables:new AbortController,columns:new AbortController,indexes:new AbortController,tableData:new AbortController}})).actions(e=>({setKeywords(t,n){e.table_schema=t,e.table_name=n}})).actions(e=>({initKeywords(){if(e.tables.empty)return;const t=Object.keys(e.tables.data)[0],n=e.tables.data[t][0].table_name;e.setKeywords(t,n)}})).actions(e=>{const t=x.flow(function*(){var n;(n=e.controllers.tables)==null||n.abort(),e.controllers.tables=new AbortController,e.tables.state="loading";try{const s=yield*x.toGenerator(Kt.structure(e.controllers.tables.signal)({query_type:"TABLES",type:e.sqlDataSourceType,key:e.key,table_schema:"",table_name:""},{params:{query_type:"TABLES"}}));e.tables.data=v.groupBy(s,"table_schema"),e.tables.state="idle",e.tables.error=null,e.initKeywords()}catch(s){if(!Rt.isCancel(s)){e.tables.data={};const i=v.get(s,"message","unkown error");e.tables.error=v.get(s,"response.data.detail.message",i),e.tables.state="error"}}});return{loadTables:t,loadTablesIfEmpty(){e.tables.empty&&t()},loadColumns:x.flow(function*(){var n;(n=e.controllers.columns)==null||n.abort(),e.controllers.columns=new AbortController,e.columns.state="loading";try{e.columns.data=yield*x.toGenerator(Kt.structure(e.controllers.columns.signal)({query_type:"COLUMNS",type:e.sqlDataSourceType,key:e.key,table_schema:e.table_schema,table_name:e.table_name},{params:{query_type:"COLUMNS"}})),e.columns.state="idle",e.columns.error=null}catch(s){if(Rt.isCancel(s))e.columns.state="idle",e.columns.error=null;else{e.columns.data=[];const i=v.get(s,"message","unkown error");e.columns.error=v.get(s,"response.data.detail.message",i),e.columns.state="error"}}}),loadIndexes:x.flow(function*(){var n;(n=e.controllers.indexes)==null||n.abort(),e.controllers.indexes=new AbortController,e.indexes.state="loading";try{e.indexes.data=yield*x.toGenerator(Kt.structure(e.controllers.indexes.signal)({query_type:"INDEXES",type:e.sqlDataSourceType,key:e.key,table_schema:e.table_schema,table_name:e.table_name},{params:{query_type:"INDEXES"}})),e.indexes.state="idle",e.indexes.error=null}catch(s){if(Rt.isCancel(s))e.indexes.state="idle",e.indexes.error=null;else{e.indexes.data=[];const i=v.get(s,"message","unkown error");e.indexes.error=v.get(s,"response.data.detail.message",i),e.indexes.state="error"}}}),loadTableData:x.flow(function*(){var s;(s=e.controllers.tableData)==null||s.abort(),e.controllers.tableData=new AbortController;const n=e.tableData;n.state="loading";try{n.data=yield*x.toGenerator(Kt.structure(e.controllers.tableData.signal)({query_type:"DATA",type:e.sqlDataSourceType,key:e.key,table_schema:e.table_schema,table_name:e.table_name,limit:n.limit,offset:n.offset},{params:{query_type:"DATA"}}));const[{total:i}]=yield*x.toGenerator(Kt.structure(e.controllers.tableData.signal)({query_type:"COUNT",type:e.sqlDataSourceType,key:e.key,table_schema:e.table_schema,table_name:e.table_name},{params:{query_type:"COUNT"}}));n.total=Number(i),n.state="idle",n.error=null}catch(i){if(Rt.isCancel(i))n.state="idle",n.error=null;else{n.data=[];const a=v.get(i,"message","unkown error");n.error=v.get(i,"response.data.detail.message",a),n.state="error"}}})}}).actions(e=>({afterCreate(){x.addDisposer(e,ae.reaction(()=>e.reloadConditionString,e.loadColumns,{fireImmediately:!1,delay:500}))}})).actions(e=>({afterCreate(){x.addDisposer(e,ae.reaction(()=>e.reloadConditionString,e.loadIndexes,{fireImmediately:!1,delay:500})),x.addDisposer(e,ae.reaction(()=>`${e.reloadConditionString};limit:${e.tableData.limit};offset:${e.tableData.offset}`,e.loadTableData,{fireImmediately:!1,delay:0}))}})),gA=x.types.model("DataSourcesModel",{list:x.types.optional(x.types.array(fA),[])}).views(e=>({find({type:t,key:n}){return e.list.find(s=>s.key===n&&s.type===t)},get options(){return e.list.map(t=>({value:t.key,label:t.key}))}})).actions(e=>({replace(t){e.list.length=0,e.list.push(...t)}}));function Gn(e){return{label:e,value:e,_type:"ACTION",_action_type:e,Icon:null,children:null}}function mA(e){switch(e._type){case"GROUP":case"ACTION":return null;case"query_variables":return["_QUERY_VARS_"];case"mock_context":return["_MOCK_CONTEXT_"];case"filter":return["_FILTERS_",e.value];case"sql_snippet":return["_SQL_SNIPPETS_",e.value];case"query":return["_QUERIES_",e.value];case"view":return["_VIEWS_",e.value];case"panel":return e.parentID?["_VIEWS_",e.parentID,"_PANELS_",e.value]:(console.error("[getPathFromOption] parentID is required"),null)}}const xA=x.types.model("EditorModel",{path:x.types.optional(x.types.frozen(),[]),settings_open:x.types.optional(x.types.boolean,!1)}).views(e=>({get navOptions(){const{content:t}=x.getRoot(e),{filters:n,views:s,sqlSnippets:i,queries:a}=t;return[{label:"query_variable.labels",value:"_QUERY_VARS_",_type:"query_variables",Icon:M.IconVariable},{label:"mock_context.label",value:"_MOCK_CONTEXT_",Icon:M.IconCodeDots,_type:"mock_context"},{label:"filter.labels",value:"_FILTERS_",Icon:M.IconFilter,children:[Gn("_FILTERS_SETTINGS_"),...n.options,Gn("_Add_A_Filter_")],_type:"GROUP"},{label:"sql_snippet.labels",value:"_SQL_SNIPPETS_",Icon:M.IconCopy,children:[Gn("_SQL_SNIPPETS_SETTINGS_"),...i.options,Gn("_Add_A_SQL_SNIPPET_")],_type:"GROUP"},{label:"query.labels",value:"_QUERIES_",Icon:M.IconDatabase,children:[Gn("_QUERIES_SETTINGS_"),...a.options,Gn("_Add_A_QUERY_")],_type:"GROUP"},{label:"view.labels",value:"_VIEWS_",Icon:M.IconBoxMultiple,children:[...s.editorOptions,Gn("_Add_A_VIEW_")],_type:"GROUP"}]},isOptionActive(t,n){return t.length===0?!1:t[t.length-1]===n.value},isOptionOpened(t){const{path:n}=e;return n.length===0||!t.children||t.children.length===0?!1:n.includes(t.value)}})).actions(e=>({setPath(t){e.path=t},setSettingsOpen(t){e.settings_open=t}})).actions(e=>({open(t){e.setPath(t),e.setSettingsOpen(!0)},close(){e.setSettingsOpen(!1)},navigate(t){const n=mA(t);n&&e.setPath(n)}})),yA=x.types.compose("LayoutsModel",Ml,x.types.model({currentLayoutWrapperWidth:x.types.optional(x.types.number,0)})).views(e=>({get divisionPreviewScale(){const t=e.currentLayoutPreviewWidth,n=e.currentLayoutWrapperWidth;return!t||!n||t<=n?1:n/t}})).actions(e=>({addALayoutItem(t){e.list.forEach(n=>{n.addNewLayout(t)})},duplicateLayoutItemsByPanelID(t,n){e.list.forEach(s=>{const i=s.findByPanelID(t);if(!i){console.error(`Can't find a layout item by panelID[${t}] in layoutSet[${s.name}]`);return}s.list.push({...i,id:on.v4(),panelID:n,y:1/0})})},removeByPanelID(t){e.list.forEach(n=>{n.removeByPanelID(t)})},setCurrentLayoutWrapperWidth(t){e.currentLayoutWrapperWidth=t},addALayoutSet(t,n,s){const i=e.basisLayoutSet,a={id:t,name:n,breakpoint:s,list:i.json.list.map(l=>({...l,id:on.v4()}))};e.list.push(a)},updateLayoutSetsInfo(t){const n=v.keyBy(e.list,"id");t.forEach(a=>{const l=n[a.id];if(l){l.setName(a.name),l.setBreakpoint(a.breakpoint),delete n[a.id];return}this.addALayoutSet(a.id,a.name,a.breakpoint)});const s=new Set(Object.keys(n)),i=s.size>0;s.forEach(a=>{const l=e.list.findIndex(c=>c.id===a);e.list.splice(l,1)}),i&&e.setCurrentBreakpoint("basis")},updateCurrentLayoutItem(t){e.currentLayoutSet.updateLayoutItem(t)},updateCurrentLayoutItems(t){t.forEach(n=>{e.currentLayoutSet.updateLayoutItem(n)})},append(t){e.list.push(t)},appendMultiple(t){t.length!==0&&e.list.push(...t)},remove(t){e.list.splice(t,1)},removeByID(t){const n=e.list.findIndex(s=>s.id===t);n!==-1&&e.list.splice(n,1)},removeByIDs(t){t.forEach(n=>{this.removeByID(n)})}})),rg=wl.views(e=>({get realDataFieldOptions(){return e.queryIDs.length===0?[]:e.queries.map(t=>{const n=t.data;return n.length===0?[]:Object.keys(n[0]).map(i=>({label:i,value:`${t.id}.${i}`,group:t.name,group_id:t.id,disabled:!1}))}).flat()},get realQueryOptions(){return e.queryIDs.length===0?[]:e.queries.map(t=>({label:t.name,value:t.id,disabled:!1}))},queryOptions(t,n){const s=[...this.realQueryOptions];return t&&!s.find(i=>i.value===t)&&s.unshift({label:t,value:t,disabled:!0}),n&&s.unshift({label:"unset",value:"",disabled:!1}),s},get realVariableOptions(){const t=e.variableValueMap;return Object.entries(e.variableAggValueMap).map(([n,s])=>({label:n,value:n,formattedValue:t[n],aggValue:s,disabled:!1}))},variableOptions(t,n){const s=[...this.realVariableOptions];return t&&!s.find(i=>i.value===t)&&s.unshift({label:t,value:t,formattedValue:"",aggValue:"",disabled:!0}),n&&s.unshift({label:"unset",value:"",formattedValue:"",aggValue:"",disabled:!1}),s},dataFieldOptions(t,n,s){let i=[...this.realDataFieldOptions];if(s&&(i=i.filter(a=>a.group_id===s)),t&&!i.find(a=>a.value===t)){const a=L(t),l=e.queryByID(a.queryID);i.unshift({label:a.columnKey,value:t,group:l?l.name:a.queryID,group_id:l?l.id:"",disabled:!0})}return n&&i.unshift({label:"unset",value:"",group:"",group_id:"",disabled:!1}),i},explainDataKey(t){const{queryID:n,columnKey:s}=L(t),i=e.queries.find(a=>a.id===n);return i?{queryID:n,queryName:i.name,columnKey:s}:{queryID:n,queryName:null,columnKey:s}}})).actions(e=>({removeSelf(){x.getParent(e,2).removeByID(e.id)}})).actions(e=>({moveToView(t,n){x.getRoot(e).content.views.findByID(t).removePanelID(e.id),x.getRoot(e).content.views.findByID(n).appendPanelID(e.id),x.getRoot(e).editor.setPath(["_VIEWS_",n,"_PANELS_",e.id])}})),sg=x.types.compose("PanelsModel",Cl,x.types.model({list:x.types.optional(x.types.array(rg),[])})).views(e=>({get contentModel(){return x.getRoot(e).content},editorOptions(t,n){const s=e.panelsByIDs(n);s.length!==n.length&&console.warn(`Unfulfilled panels for View[${t}]`);const i=s.map(l=>({label:l.name,value:l.id,_type:"panel",parentID:t})),a="_Add_A_PANEL_";return i.push({label:a,value:a,_type:"ACTION",_action_type:a,parentID:t,Icon:null,children:null}),i}})).actions(e=>({replace(t){e.list=x.castToSnapshot(t)},append(t){e.list.push(t)},appendMultiple(t){t.length!==0&&e.list.push(...t)},remove(t){e.list.splice(t,1)},removeByID(t){const n=e.list.findIndex(s=>s.id===t);n!==-1&&e.list.splice(n,1)},removeByIDs(t){t.forEach(n=>{this.removeByID(n)})},duplicateByID(t){const n=e.list.find(i=>i.id===t);if(!n){console.error(new Error(`[duplicate panel] Can't find a panel by id[${t}]`));return}const s=new Date().getTime().toString();return e.list.push({...n.json,id:s,title:{...n.json.title}}),e.contentModel.layouts.duplicateLayoutItemsByPanelID(n.id,s),s},replaceByIndex(t,n){e.list.splice(t,1,n)}})),bA=_l.actions(e=>({getSchema(){const t=e.json,n=[],s=[];e.panels.forEach(l=>{const c=l.getSchema();n.push(c.panel),c.queries.length>0&&s.push(...c.queries)});const i=e.contentModel.layouts.jsonByPanelIDSet(new Set(e.panelIDs));return{views:[t],panels:n,definition:{queries:v.uniqBy(s,l=>l.id)},layouts:i,version:gn}},downloadSchema(){if(e.type===G.Tabs){console.error(new Error("Please choose a tab first"));return}const t=JSON.stringify(this.getSchema(),null,2),n=e.name;fr(n,t)}})),ig=x.types.compose("ViewsModel",jl,x.types.model({current:x.types.optional(x.types.array(bA),[]),idOfVIE:x.types.string})).views(e=>({get isVIETheFirstView(){return e.current.length===0||!e.idOfVIE?!1:e.current[0].id===e.idOfVIE},get VIE(){return e.current.find(({id:t})=>t===e.idOfVIE)},get options(){return e.current.map(t=>({label:t.name,value:t.id,type:t.type}))},get editorOptions(){const t=x.getRoot(e).content.panels;return e.current.map(n=>({label:n.name,value:n.id,_type:"view",children:t.editorOptions(n.id,n.panelIDs)}))}})).actions(e=>({setIDOfVIE(t){e.idOfVIE=t,e.visibleViewIDs.length=0,e.visibleViewIDs.push(t)},replace(t){e.current.replace(t)},addANewView(t,n,s,i){e.current.push({id:t,name:n,type:s,config:i,panelIDs:[]})},append(t){e.current.push(t)},appendMultiple(t){t.length!==0&&e.current.push(...t)},remove(t){e.current.splice(t,1)},removeByID(t){const n=e.current.findIndex(a=>a.id===t);if(n===-1)return;const s=e.current[n];x.getRoot(e).content.panels.removeByIDs(s.panelIDs),e.current.splice(n,1)},replaceByIndex(t,n){e.current.splice(t,1,n)},addARandomNewView(){const t=new Date().getTime().toString();this.addANewView(t,G.Division,G.Division,{_name:G.Division}),this.setIDOfVIE(t)},removeVIE(){e.current.length!==1&&(this.removeByID(e.idOfVIE),this.setIDOfVIE(e.current[0].id))}}));function Ol(e){const t=e.length>0?[e[0].id]:[],n=e.length>0?e[0].id:"";return{current:e.map(i=>{const{_name:a=i.type}=i.config;return{...i,config:{...i.config,_name:a},panelIDs:i.panelIDs}}),visibleViewIDs:t,idOfVIE:n}}const vA=x.types.model({id:x.types.string,name:x.types.string,dashboard_id:x.types.string,create_time:x.types.string,update_time:x.types.string,version:x.types.string,filters:Hf,queries:tg,sqlSnippets:ng,views:ig,panels:sg,layouts:yA,mock_context:sl,origin:x.types.maybe(x.types.frozen())}).views(e=>({get json(){return{id:e.id,name:e.name,create_time:e.create_time,update_time:e.update_time,dashboard_id:e.dashboard_id,content:{views:e.views.json,panels:e.panels.json,filters:e.filters.json,version:e.version,layouts:e.layouts.json,definition:{queries:e.queries.json,sqlSnippets:e.sqlSnippets.json,mock_context:e.mock_context.current}}}},get contentJSON(){return this.json.content},get filtersChanged(){const t="filters.current";return!v.isEqual(x.getSnapshot(v.get(e,t)),v.get(e.origin,t))},get queriesChanged(){const t="queries.current",n=x.getSnapshot(v.get(e,t)).map(s=>v.pick(s,["id","name","key","type","sql","run_by","react_to","pre_process","post_process","dep_query_ids"]));return!v.isEqual(n,v.get(e.origin,t))},get sqlSnippetsChanged(){const t="sqlSnippets.current";return!v.isEqual(x.getSnapshot(v.get(e,t)),v.get(e.origin,t))},get viewsChanged(){const t="views.current";return!v.isEqual(e.views.json,v.get(e.origin,t))},get panelsChanged(){const t="panels.list";return!v.isEqual(x.getSnapshot(v.get(e,t)),v.get(e.origin,t))},get layoutsChanged(){const t="layouts.list";return!v.isEqual(x.getSnapshot(v.get(e,t)),v.get(e.origin,t))},get mockContextChanged(){const t="mock_context.current";return!v.isEqual(v.get(e,t),v.get(e.origin,t))},get context(){const t=x.getParent(e).context.current;return{...e.mock_context.current,...t}},get payloadForSQL(){const t=x.getParent(e).globalSQLSnippets,n={context:this.context,filters:e.filters.values};return{...n,sql_snippets:es(e.sqlSnippets.current,"key","value",n),global_sql_snippets:es(t.list,"id","content",n)}},get payloadForViz(){const t=x.getParent(e).context.current;return{context:{...e.mock_context.current,...t},filters:e.filters.values}},get dashboardState(){return po(this.payloadForSQL)},getAdditionalQueryInfo(t){return{content_id:e.id,query_id:t,params:this.dashboardState}},get changed(){return this.filtersChanged||this.queriesChanged||this.sqlSnippetsChanged||this.viewsChanged||this.panelsChanged||this.layoutsChanged||this.mockContextChanged},get data(){return e.queries.current.map(({id:n,data:s})=>({id:n,data:s})).reduce((n,s)=>(n[s.id]=s.data,n),{})},getDataStuffByID(t){const n=e.queries.findByID(t);return n?{data:n.data,len:n.data.length,state:n.state,error:n.error}:{data:[],len:0,state:"idle",error:void 0}}})).views(e=>({get queriesUsage(){const t=e.panels.idMap,n=[];e.views.current.forEach(i=>{i.panelIDs.forEach(a=>{const l=t.get(a);if(!l)return;const c="panel",u=l.name,d=[{id:i.id,label:i.name}];l.queryIDs.forEach(h=>{n.push({id:a,queryID:h,type:c,type_label:"panel.label",label:u,views:d})})})});const s=e.views.idMap;return e.filters.current.filter(i=>!!v.get(i,"config.options_query_id")).forEach(i=>{n.push({type:"filter",type_label:"filter.label",id:i.id,queryID:v.get(i,"config.options_query_id"),label:i.label,views:i.visibleInViewsIDs.map(a=>{var l;return{id:a,label:((l=s.get(a))==null?void 0:l.name)??a}})})}),e.queries.current.forEach(i=>{i.isTransform&&i.dep_query_ids.forEach(a=>{n.push({type:"transform-query",type_label:"query.transform.full_label",id:i.id,queryID:a,label:i.name,views:[]})})}),v.groupBy(n,"queryID")},get hasUnusedQueries(){return e.queries.current.length>Object.keys(this.queriesUsage).length},findQueryUsage(t){return this.queriesUsage[t]??[]},get sqlSnippetsUsage(){const t=[];return e.queries.current.forEach(n=>{if(!n.typedAsSQL)return;v.uniq(n.sql.match(Xs.sqlSnippet)).forEach(i=>{t.push({queryID:n.id,sqlSnippetKey:i,queryName:n.name})})}),v.groupBy(t,"sqlSnippetKey")},get hasUnusedSQLSnippets(){return e.sqlSnippets.current.length>Object.keys(this.sqlSnippetsUsage).length},findSQLSnippetUsage(t){return this.sqlSnippetsUsage[t]??[]}})).actions(e=>({removeUnusedQueries(){const t=new Set(Object.keys(e.queriesUsage)),n=e.queries.current.filter(s=>!t.has(s.id)).map(s=>s.id);e.queries.removeQueries(n)},removeUnusedSQLSnippets(){const t=new Set(Object.keys(e.sqlSnippetsUsage)),n=e.sqlSnippets.current.filter(s=>!t.has(s.key)).map(s=>s.key);e.sqlSnippets.removeByKeys(n)},duplicatePanelByID(t,n){var i;const s=e.panels.duplicateByID(t);s&&((i=e.views.findByID(n))==null||i.appendPanelID(s))},removePanelByID(t,n){var s;e.panels.removeByID(t),e.layouts.removeByPanelID(t),(s=e.views.findByID(n))==null||s.removePanelID(t)},addANewPanel(t){var s;const n=on.v4();e.panels.append(kf(n)),(s=e.views.findByID(t))==null||s.appendPanelID(n),e.layouts.addALayoutItem(n)},applyJSONSchema(t){var p;const{views:n,panels:s,filters:i,definition:a={},layouts:l}=t,{queries:c,sqlSnippets:u,mock_context:d}=a,h=new Map;if(Array.isArray(s)){const f=s.map(m=>{const y=on.v4();return h.set(m.id,y),{...m,id:y}});if(e.panels.appendMultiple(f),!Array.isArray(n)||n.length===0){const m=f.map(y=>y.id);(p=e.views.VIE)==null||p.appendPanelIDs(m)}}if(Array.isArray(n)){const f=n.map(m=>{const y=m.panelIDs.map(_=>h.get(_)??_);return{...m,id:on.v4(),panelIDs:y}});e.views.appendMultiple(f)}if(Array.isArray(l)){const f=(_,k)=>e.layouts.breakpointNameRecord[_]===k;let m=[];const y=l.filter(_=>f(_.name,_.breakpoint));y.forEach(_=>{_.id==="basis"&&(m=_.list),_.list.forEach(k=>{const S=h.get(k.panelID);k.id=on.v4(),k.panelID=S})}),e.layouts.list.forEach(_=>{const k=y.find(S=>S.name===_.name&&S.breakpoint===_.breakpoint);if(!k){m.forEach(S=>{_.addLayout(S)});return}k.list.forEach(S=>{_.addLayout(S)})})}Array.isArray(i)&&e.filters.appendMultiple(i),Array.isArray(c)&&e.queries.appendMultiple(c),Array.isArray(u)&&e.sqlSnippets.appendMultiple(u),d&&Object.keys(d).length>0&&e.mock_context.defaults(d)}})).actions(e=>({reset(){x.applySnapshot(e.filters.current,e.origin.filters.current),x.applySnapshot(e.queries.current,e.origin.queries.current),x.applySnapshot(e.sqlSnippets.current,e.origin.sqlSnippets.current),x.applySnapshot(e.views.current,e.origin.views.current),x.applySnapshot(e.panels.list,e.origin.panels.list),x.applySnapshot(e.layouts.list,e.origin.layouts.list),e.mock_context.current=e.origin.mock_context.current},resetFilters(){x.applySnapshot(e.filters.current,e.origin.filters.current)},updateCurrent(t){const{id:n,name:s,content:i}=t;if(!i)throw new Error("unexpected null content when updating a content model");const{version:a,filters:l,views:c,panels:u,definition:{queries:d,sqlSnippets:h,mock_context:p={}}}=i;e.id=n,e.name=s,e.version=a,x.applySnapshot(e.filters.current,l),x.applySnapshot(e.views.current,Ol(c).current),x.applySnapshot(e.panels.list,u),x.applySnapshot(e.queries.current,d),x.applySnapshot(e.sqlSnippets.current,h),e.mock_context.current=p}})),Ll=x.types.snapshotProcessor(vA,{preProcessor(e){return{...e,origin:e}},postProcessor(e){delete e.origin;const t=x.castToSnapshot(e.queries.current.map(n=>v.pick(n,["id","key","type","sql"])));return v.defaults({},{queries:{current:t}},e)}});function _A(e,t){t.filters&&x.applySnapshot(e.filters.current,t.filters)}function ag({id:e,name:t,dashboard_id:n,create_time:s,update_time:i,content:a},l,c){if(!a)throw new Error("unexpected null content when creating a content model");const{version:u,filters:d,views:h,panels:p,layouts:f,definition:{queries:m,sqlSnippets:y,mock_context:_={}}}=a;return Ll.create({id:e,name:t,dashboard_id:n,create_time:s,update_time:i,version:u,filters:kl(d,l,_,c),queries:{current:m},sqlSnippets:{current:y},mock_context:il(_),views:Ol(h),panels:{list:p},layouts:{list:f,currentBreakpoint:f[0].id}})}const og=x.types.model({id:x.types.identifier,name:x.types.string,group:x.types.string,content:Ll,content_id:x.types.string,datasources:gA,globalSQLSnippets:bl,context:fi,editor:xA}).views(e=>({get json(){return{id:e.id,name:e.name,group:e.group,content_id:e.content_id}}})).actions(e=>({updateCurrentContent(t){e.content.updateCurrent(t)},updateCurrent(t,n){const{id:s,name:i,group:a,content_id:l}=t;e.id=s,e.name=i,e.group=a,e.content_id=l,this.updateCurrentContent(n)}}));function lg({id:e,name:t,group:n,content_id:s},i,a,l,c,u){return og.create({id:e,name:t,group:n,content_id:s,content:ag(i,c,u),datasources:{list:a},globalSQLSnippets:{list:l},context:vl(c),editor:{}})}const jA={translation:{filter:{label:"Filter",labels:"Filters",add:"Add a Filter",manage:"Manage Filters",show_filters:"Show Filters",hide_filters:"Hide Filters",field:{widget:"Widget",visible_in:"Visible in...",key_placeholder:"A unique key to refer",label_placeholder:"Label for this field",auto_submit:"Submit automatically",order:"Placement Order",custom_default_value:{trigger:"Custom",title:"Custom default value",tips:"Tips",tip_1:"Function has the highest priority of getting filter's default value",tip_2:"Leave this editor empty to disable this feature"}},widget:{names:{select:"Select",multi_select:"Multi Select",tree_select:"Tree Select",text_input:"Text Input",checkbox:"Checkbox",date_range:"Date Range"},common:{use_query_data_as_options:"Use query data as options",fetch_options_from_datasource:"Fetch options from datasource",or_fetch_options_from_datasource:"Or fetch options from datasource",selector_option_empty:"Not found",see_data_structure:"Click to see expected data structure",using_query:"Using query",default_selection_count:"Select first N options by default",min_width:"Min width",x_selected:"{{count}} selected"},text_input:{default_value:"Default Value",required:"Required"},select:{width:"Width",required:"Required",clearable:"Clearable",configure_options:"Configure options",default_selection:"Default Selection",no_default_selection:"none",select_first_option_by_default:"Select the first option by default"},multi_select:{width_description:"At least 160px"},tree_select:{strictly:"Parent and children nodes are not associated"},checkbox:{description:"Description",default_checked:"Default checked"},date_range:{required:"Required",allow_single_date:"Allow choosing 1 day",display_format:"Display format",max_days:"Max days",one_day:"1 day",x_days:"{{count}} days",x_max_days:"{{max_days}} days max",default_value:"Default value",default_by_shortcut:"Default by shortcut",default_by_shortcut_placeholder:"Priors default value",start_date:"Start date",end_date:"End date",shortcut:{last:{label:"last",d:"yesterday",w:"week",m:"month",m2:"2 months",m3:"3 months",y:"year",full:{d:"yesterday",w:"last week",m:"last month",m2:"last 2 months",m3:"last 3 months",y:"last year"}},recent:{label:"recent",d7:"7 days",d30:"30 days",d60:"60 days",d90:"90 days",d180:"180 days",d365:"365 days",full:{d7:"recent 7 days",d30:"recent 30 days",d60:"recent 60 days",d90:"recent 90 days",d180:"recent 180 days",d365:"recent 365 days"}},this:{label:"this",d:"today",w:"week",m:"month",y:"year",full:{d:"today",w:"this week",m:"this month",y:"this year"}},this_so_far:{label:"this...so far",w:"week",m:"month",y:"year",full:{w:"this week so far",m:"this month so far",y:"this year so far"}}}}}},view:{label:"View",labels:"Views",add:"Add a View",delete:"Delete this View",download_schema:"Download this View",component:{div:{label:"Division"},tabs:{label:"Tabs",tabs_settings:"Tabs Settings",tab:{name:"Tab Name",view:"View",order:"Placement Order",color:"Color",delete:"Delete this tab",switch_to_view:"Swith to View: {{name}}"}},modal:{label:"Modal",modal_settings:"Modal settings",title:"Modal Title",custom_title:"Customize modal title",width:"Width",height:"Height"}}},interactions:{label:"Interactions",add:"Add an interaction",interactions_viewer:"Interactions Viewer",unavailable:"Unavailable",unavailable_reason:"This visualization does not have available interactions to choose from",trigger:{setup:"Setup Trigger",label:"Trigger",payload:"Payload"},operation:{setup:"Operation Settings",label:"Operation",settings:"Settings",variables:"Variables",console_log:{label:"console.log | debug",log_content:"log content"},open_link:{label:"Open Link",url:"URL",open_in_new_tab:"Open in new tab"},open_view:{label:"Open View",view:"View"},set_filter_values:{label:"Set Filter Values",set_filter:"Set filter",with:"with"},clear_filter_values:{label:"Clear Filter Values",select_filter:"Select filters to clear"}}},query_variable:{label:"Query Variable",labels:"Query Variables",add:"Add a Variable",guide:{tabs:{guide:"Guide",variables_in_this_dashboard:"Variables in this dashboard",global_sql_snippets:"Global SQL Snippets"}},open:"See Query Variables"},sql_snippet:{label:"SQL Snippet",labels:"SQL Snippets",add:"Add a SQL Snippet",delete:"Delete this SQL Snippet",delete_unused:"Delete unused SQL Snippets",manage:"Manage SQL Snippets",key:"Key",key_occupied:"This key is occupied by another snippet",edit_snippet:"Edit SQL Snippet",preview_snippet:"Preview SQL Snippet",usage:{label:"Usage"}},global_sql_snippet:{label:"Global SQL Snippet",labels:"Global SQL Snippets",description:"SQL snippets worth sharing between dashboards are managed in System Settings by admins."},common:{titles:{settings:"Settings",edit:"Edit",config:"Config"},pagination:{page_size:"Page Size",total:"Total",total_rows:"Total {{total}} row(s)"},align:{horizontal:{label:"Horizontal Align",left:"left",center:"center",right:"right"},vertical:{label:"Vertical Align",top:"top",center:"center",bottom:"bottom"}},id:"ID",name:"Name",key:"Key",label:"Label",value:"Value",type:"Type",info:"Info",min:"Min",max:"Max",data_field:"Data Field",name_data_field:"Name Data Field",value_data_field:"Value Data Field",color_data_field:"Color Data Field",enabled:"Enabled",copied:"Copied to clipboard",action:"Action",actions:{open:"Open",close:"Close",save:"Save",save_changes:"Save Changes",revert:"Revert",revert_changes:"Revert Changes",reset_to_default:"Reset to default",init_with_default:"Init with default",select_all:"Select All",clear:"Clear",clear_selection:"Clear Selection",refresh:"Refresh",download_data:"Download Data",download_schema:"Download Schema",download_screenshot:"Screenshot",enter_fullscreen:"Full Screen",duplicate:"Duplicate",delete:"Delete",cancel:"Cancel",confirm:"Confirm",add_an_option:"Add an Option",edit:"Edit",end_editing:"End editing <1>{{name}}</1>"},tabs:{variant:{label:"Variant",default:"Default",outline:"Outline",pills:"Pills"},orientation:{label:"Orientation",horizontal:"Horizontal",vertical:"Vertical"},grow_tabs:"Grow Tabs"},choose_a_tab_first:"Please choose a tab first"},breakpoint:{label_one:"Screen size",label_other:"Screen sizes",add:"Add a screen size",manage:"Manage screen sizes",breakpoint:"Min Width"},context:{label:"Context"},mock_context:{label:"Mock Context",hint:"A valid json string is required"},panel:{label:"Panel",labels:"Panels",add:"Add a Panel",delete:"Delete This Panel",panel_name:"Panel Name",panel_description:"Description",panel_description_click:"Click to see description",show_title:"Show title",use_name_as_title:"Use name as title",settings:{change_view:"Move into Another View",change_view_title:"Move panel into another view",choose_queries:"Choose queries",need_to_choose_queries:"Choose at least 1 query for its data"},style:{label:"Style",width:"Width",width_postfix:"of 36 columns",height:"Height",height_postfix:"px",border:"Border"},variable:{label:"Variable",labels:"Variables",add:"Add a Variable",delete:"Delete this Variable",aggregation:{label:"Aggregation",fallback_value:"Fallback Value",fallback_value_description:"Used when data is empty or the aggregation yields NaN"}}},style:{label:"Style",font_size:{label:"Font Size",placeholder:"10px, 1em, 1rem, 100%..."},font_weight:{label:"Font Weight"},size:{xs:"xs",sm:"sm",md:"md",lg:"lg",xl:"xl"},flex:{justify_content:{label:"Justify Content",left:"Left",center:"Center",right:"Right",space_between:"Space Between",space_around:"Space Around",space_evenly:"Space Evenly"},align_items:{label:"Align Items",start:"Start",center:"Center",end:"End",stretch:"Stretch"}},color:{type:{label:"Color Type",static:"Static",interpolation:"Interpolation",none:"None"},interpolation:{setup:"Setup color interpolation",palette:{label:"Palette",category:{sequential:"Sequential",diverging:"Diverging"},red_green:"Red / Green",yellow_blue:"Yellow / Blue",red:"Red",green:"Green",blue:"Blue",orange:"Orange",mapping:{value_input_label:"Map a value to this color"}}}}},query:{label:"Query",labels:"Queries",add:"Add a Query",delete:"Delete this Query",cant_delete:"Can't delete this query for it's being used, check out Usage tab for details",delete_unused:"Delete unused queries",name:"Name",name_description:"A unique name",manage:"Manage Queries",open:"Open this query",configurations:"Configurations",basics:"Basics",conditions:"Conditions",run_by_condition:{label:"Run query when these are truthy",unset:"Always run this query on load"},re_run_condition:{label:"Re-run query when these changed",unset:"Leave it empty to never re-run this query"},dependency:{label:"Dependency",has_none:"This query has no dependency"},edit_sql:"Edit SQL",preview_sql:"Preview SQL",request:"Request",build_request:"Build Request",process_request:"Process Request",process_result:"Process Result",usage:{label:"Usage",in_views:"In View(s)",unused_description:"This query is not used by any filter or panel"},transform:{label:"Transform",full_label:"Transform Query",data_source:"Use other queries' data",guide:{pick_queries:"Pick queries for data input",write_function:"Write a function for making new data"}}},data:{label:"Data",preview_data:"Preview Data",empty_data:"Empty Data",requires_data:"Requires data"},data_source:{label:"Data Source",explore:"Explore Data Source",explorer:"Data Source Explorer",table_structure:"Table Structure",table_structure_short:"Structure",see_table_structure:"See Table Structure"},visualization:{label:"Visualization",component:"Visualization",label_short:"Viz"},numbro:{format:{label:"Format",absolute:"Absolute",absolute_description:"Non-negative",abbreviation:"Abbreviation",abbreviation_description:"like 1.23k, 1.23m",mantissa:"Mantissa",trim_mantissa:"Trim mantissa",trim_mantissa_description:"hide trailing zero(s)",preview:{open:"Open Preview",close:"Close Preview",input:"In",output:"Out"}}},import:{label:"Import...",title:"Import content with schema json",json_file:"JSON File",this_dashboard:"This dashboard",this_file:"This file"},function_utils:{trigger_text:"About parameter 'utils'",modal_title:"About FunctionUtils",description:"Parameter <code>utils</code> is <code>FunctionUtils</code>, which contains:",document:"Document"},aggregation:{option:{none:"None",sum:"Sum",mean:"Mean",median:"Median",min:"Min",max:"Max",cov:"Coefficient of Variation",std:"Standard Variation",quantile:{label:"Quantile",label_with_hint:"Quantile(99%, 95%, ...)"},custom:{label:"Custom",label_trigger:"Edit Function",title:"Custom Aggregation"},pick_record:{label:"Pick Record",method:{label:"Record",first:"First Record",last:"Last Record"}}}},rich_text:{label:"Rich Text",content:{label:"Content"},dynamic_color:{label:"Dynamic Color",edit:"Edit dynamic color",clear:"Clear dynamic color"},color_mapping:{label:"Color Mapping",edit:"Edit color mapping",clear:"Clear color mapping",choose_value_var:"Choose a variable for color mapping",min:{val:"Fallback value",var:"Min value variable"},max:{val:"Fallback value",var:"Max value variable"}}},chart:{chart_config:"Chart Config",data_field:"Data Field",groups:{merico_suite:"Merico suite",echarts_based_charts:"ECharts-based charts",others:"Others"},label:{label:"Label",label_full:"Label",label_style:"Label Style",label_format:"Label Format"},label_position:{label:"Label Position",off:"Off",top:"Top",left:"Left",right:"Right",bottom:"Bottom",inside:"Inside",inside_top:"Inside Top",inside_left:"Inside Left",inside_center:"Inside Center",inside_right:"Inside Right",inside_bottom:"Inside Bottom",inside_top_left:"Inside Top Left",inside_top_right:"Inside Top Right",inside_bottom_left:"Inside Bottom Left",inside_bottom_right:"Inside Bottom Right",outside:"Outside"},visual_map:{label:"Visual Map",continuous:{label:"Continuous"},piecewise:{label:"Piecewise",mode:{pieces:"Pieces",categories:"Categories"},add_a_piece:"Add a piece",interval:"Interval",piece_label:"Label"},bar_width:"Bar Width",bar_height:"Bar Height",item_width:"Item Width",item_height:"Item Height",calculable:"Show drag handle",min_value:"Min Value",max_value:"Max Value",min_text:"Min Text",max_text:"Max Text",use_palette_x:'Use palette "{{x}}"',built_in_palettes:"Built-in Palettes",precision:"Data Precision",skip_range:{lt_min:"Color for smaller values than min value",min:"Color for min value",max:"Color for max value",gt_max:"Color for greater values than max value",follow_visual_map:"follow gradient rule"}},number_or_dynamic_value:{type:{static:"Static",dynamic:"Dynamic"},dynamic:{setup:"Setup",setup_title:"Setup dynamic value",guide:"Dyanmic by a custom function"}},orientation:{label:"Orientation",horizontal:"Horizontal",vertical:"Vertical"},symbol_size:{label:"Symbol Size",static:"Static",dynamic:"Dynamic",setup:{label:"Setup",title:"Setup dynamic size",description:"Dynamic by a custom function"}},series:{label:"Series",name:"Name",y_axis:"Y Axis",data_field:"Data Field",add:"Add a series",delete:"Delete this series",line:{label:"Line",line_settings:"Line Settings",line_style:"Line Style",type:{label:"Line Type",solid:"Solid",dashed:"Dashed",dotted:"Dotted"},line_width:"Line Width",step:{label:"Step",off:"Off",start:"Start",middle:"Middle",end:"End"},smooth_line:"Smooth Line",show_name_on_line:"Display Name on Line",show_symbol_on_line:"Show Symbol on Line"},bar:{label:"Bar",stack:"Stack",stack_hint:"Stack bars by this ID",bar_gap:{label:"Bar Gap",no_gap:"No gap between bars",overlap:"Bars overlapping on each other"},bar_width:{min:"Bar Width(min)",exact:"Bar Width",max:"Bar Width(max)"}},scatter:{label:"Scatter"},group_by:{label:"Split into multiple seires by this field...",label_line:"Split into multiple lines by this field..."}},axis:{tick_label:"Tick Label",customize_label:"Customize Label",overflow:{label:"Overflow",max_width:"Max Width",truncate:"Truncate",break_line:"Break Line",break_word:"Break Word",ellipsis:"Ellipsis",section_title:{on_axis:"Overflow on Axis",in_tooltip:"Overflow in Tooltip"}},section_title:{label_format:"Label Format"},type:{value:"Value",category:"Category",time:"Time",log:"Log",click_to_learn_more:"Click <1>here</1> to learn more about these options"}},name_text:{align:{label:"Name Anchor",left:"Left",center:"Center",right:"Right"}},rotate:"Rotate",degree:"degree",padding:"Padding",content_template:{label:"Content Template",hint:"Average: ${avg}"},x_axis:{label:"X Axis",labels:"X Axes",label_format:"Label Format",add:"Add an X Axis",delete:"Delete this X Axis",x_axis_name:"X Axis Name",x_axis_data_field:"X Axis Data Field",x_axis_type:"X Axis Type",layout:"Layout",position:{label:"Position",top:"Top",bottom:"Bottom"},value_range:"Value Range",value_min:"Min",value_max:"Max",behavior:"Behavior",visible:"Visible"},y_axis:{label:"Y Axis",labels:"Y Axes",label_format:"Label Format",add:"Add a Y Axis",delete:"Delete this Y Axis",y_axis_name:"Y Axis Name",y_axis_name_anchor:"Name Anchor",y_axis_data_field:"Y Axis Data Field",layout:"Layout",position:{label:"Position",left:"Left",right:"Right"},value_range:"Value Range",value_min:"Min",value_max:"Max",behavior:"Behavior",visible:"Visible"},stats:{label:"Stats",template:{above_chart:"Template for stats above the chart",under_chart:"Template for stats under the chart"}},legend:{label:"Legend",show_legend:"Show Legend",show_in_legend:"Show in legend",hide_in_legend:"Hide in legend",orientation:{label:"Orientation",horizontal:"Horizontal",vertical:"Vertical"}},tooltip:{label:"Tooltip",additional_metrics:{description:"Set additional metrics to show in scatter's tooltip",add:"Add a metic",delete:"Delete this Metric"},trigger:{label:"Trigger",scatter_point:"Scatter Point",x_axis:"X Axis"}},style:{label:"Style"},color:{label:"Color",or:"or",set_any_color:"Set any color",pick_a_theme_color:"Pick a theme color",background_color:"Background Color",text_color:"Text Color",click_to_add_a_color:"Click to add a color",color_gradient:"Color Gradient"},behavior:{label:"Behavior",invisible:"Invisible"},heatmap:{heatblock:{label:"Heat Block",show_label:"Show Label"}},reference_line:{label:"Reference Line",labels:"Reference Lines",add:"Add a reference line",name_placeholder:"Average Reference Line",delete:"Remove this Reference Line",orientation:{vertical_hint:"Works only when xAxis values are numbers"}},regression_line:{label:"Regression Line",labels:"Regression Lines",add:"Add a line",delete:"Delete this line",method:{label:"Method",linear:"Linear",exponential:"Exponential",logistic:"Logistic",polynomial:"Polynomial",polynomial_order:"Order"}},reference_area:{label:"Reference Area",labels:"Reference Areas",add:"Add a reference area",delete:"Remove this reference area",type:{label:"Type",rectangle:"Rectangle"},direction:{label:"Direction",horizontal:"Horizontal"},boundary:{upper:"Upper Boundary",lower:"Lower Boundary"},content:{label:"Content",content_text:"Content Text",text_position:"Text Position"},endpoint:{labels:"Endpoints",left_bottom_point:"Left-Bottom Point",right_top_point:"Right-Top Point"}},zooming:{label:"Zooming",scroll:{label:"Scroll to zoom",x_axis:"Enable on X Axis",y_axis:"Enable on Y Axis"},slider:{label:"Slider for zooming",x_axis:"Slider for X Axis",y_axis:"Slider for Y Axis",y_axis_disabled:"Not available for now, will overlap y-axis's label"}}},viz:{viz_config_banner:"Visualization Settings"},validation:{number:{require_a_number:"A number is required"}}}},wA={translation:{filter:{label:"筛选器",labels:"筛选器",add:"新增筛选器",manage:"管理筛选器",show_filters:"展开筛选器",hide_filters:"收起筛选器",field:{widget:"控件",visible_in:"在...视图中可见",key_placeholder:"用于引用此筛选器,需保持唯一",label_placeholder:"用于展示的标签文案",auto_submit:"自动提交",order:"排列次序",custom_default_value:{trigger:"自定义",title:"自定义默认值",tips:"提示",tip_1:"在指定筛选器默认值这事上,自定义函数具备最高优先级",tip_2:"清空下方编辑器来禁用本功能"}},widget:{names:{select:"单选",multi_select:"多选",tree_select:"树形选择器",text_input:"文本框",checkbox:"勾选框",date_range:"日期范围"},common:{use_query_data_as_options:"使用所查数据为选项",fetch_options_from_datasource:"从数据源查选项",or_fetch_options_from_datasource:"或从数据源查选项",selector_option_empty:"无选项可用",see_data_structure:"点击查看期望的数据格式",using_query:"在用查询获取选项",default_selection_count:"默认选中前N项",min_width:"控件最小宽度",x_selected:"已选数:{{count}}"},text_input:{default_value:"默认值",required:"必填"},select:{width:"控件宽度",required:"必选",clearable:"可取消选择",configure_options:"配置选项",default_selection:"默认选项",no_default_selection:"无",select_first_option_by_default:"默认选中第一个选项"},multi_select:{width_description:"至少160px"},tree_select:{strictly:"枝叶节点不相关,各选各的"},checkbox:{description:"描述信息",default_checked:"默认勾选"},date_range:{required:"必选",allow_single_date:"允许选一天作为范围",display_format:"展示格式",max_days:"最大选择天数",one_day:"1天",x_days:"{{count}}天",x_max_days:"最多可选{{max_days}}天",default_value:"默认日期范围(具体)",default_by_shortcut:"默认日期范围(快捷方式)",default_by_shortcut_placeholder:"优先于左侧",start_date:"开始日期",end_date:"结束日期",shortcut:{last:{label:"过往整周期",d:"昨天",w:"周",m:"月",m2:"两个月",m3:"三个月",y:"年",full:{d:"昨天",w:"上周",m:"上个月",m2:"上两月",m3:"上三月",y:"去年"}},recent:{label:"最近",d7:"7天",d30:"30天",d60:"60天",d90:"90天",d180:"180天",d365:"365天",full:{d7:"近7天",d30:"近30天",d60:"近60天",d90:"近90天",d180:"近180天",d365:"近365天"}},this:{label:"当前整周期",d:"今天",w:"周",m:"月",y:"年",full:{d:"今天",w:"本周",m:"本月",y:"今年"}},this_so_far:{label:"至今",w:"周",m:"月",y:"年",full:{w:"本周至今",m:"本月至今",y:"本年至今"}}}}}},view:{label:"视图",labels:"视图",add:"新增视图",delete:"删除此视图",download_schema:"下载此视图描述文件",component:{div:{label:"内容"},tabs:{label:"标签页",tabs_settings:"标签页设置",tab:{name:"名称",view:"内容视图",order:"排列次序",color:"颜色",delete:"删除这个标签页",switch_to_view:"打开视图: {{name}}"}},modal:{label:"弹窗",modal_settings:"弹窗设置",title:"弹窗标题",custom_title:"自定义弹窗标题",width:"宽度",height:"高度"}}},interactions:{label:"交互",add:"新增交互",interactions_viewer:"纵览交互",unavailable:"不可用",unavailable_reason:"此可视化组件没有交互功能",trigger:{setup:"设置触发动作",label:"触发动作",payload:"触发时的参数"},operation:{setup:"操作设置",label:"操作",settings:"设置",variables:"变量",console_log:{label:"console.log | 调试用",log_content:"打印内容"},open_link:{label:"打开链接",url:"URL",open_in_new_tab:"在新标签页中打开"},open_view:{label:"唤出视图",view:"视图"},set_filter_values:{label:"设置筛选器值",set_filter:"将筛选器的值",with:"设为"},clear_filter_values:{label:"清除筛选器值",select_filter:"选择筛选器以清除其值"}}},query_variable:{label:"查询变量",labels:"查询变量",add:"新增变量",guide:{tabs:{guide:"使用指南",variables_in_this_dashboard:"本看板中的查询变量",global_sql_snippets:"全局SQL片段"}},open:"查看查询变量"},sql_snippet:{label:"SQL片段",labels:"SQL片段",add:"新增SQL片段",delete:"删除这个SQL片段",delete_unused:"删除未用到的SQL片段",manage:"管理SQL片段",key:"键",key_occupied:"此键已被其他SQL片段占用",edit_snippet:"编辑SQL片段",preview_snippet:"预览SQL片段",usage:{label:"使用情况"}},global_sql_snippet:{label:"全局SQL片段",labels:"全局SQL片段",description:"管理员负责在系统设置中维护全局SQL片段"},common:{titles:{settings:"设置",edit:"编辑",config:"配置"},pagination:{page_size:"页容量",total:"共",total_rows:"共 {{total}} 行"},align:{horizontal:{label:"水平对齐",left:"居左",center:"居中",right:"居右"},vertical:{label:"垂直对齐",top:"居上",center:"居中",bottom:"居下"}},id:"ID",name:"名称",key:"键",label:"标签",value:"值",type:"类型",info:"信息",min:"最小值",max:"最大值",data_field:"数据字段",name_data_field:"名称字段",value_data_field:"值字段",color_data_field:"颜色字段",enabled:"启用",copied:"已复制到剪切板",action:"操作",actions:{open:"打开",close:"关闭",save:"保存",save_changes:"保存改动",revert:"还原",revert_changes:"还原改动",reset_to_default:"重置为初始值",init_with_default:"初始化",select_all:"全选",clear:"清除",clear_selection:"撤销选择",refresh:"刷新",download_data:"下载数据",download_schema:"下载描述文件",download_screenshot:"下载截图",enter_fullscreen:"全屏",duplicate:"复制",delete:"删除",cancel:"取消",confirm:"确认",add_an_option:"新增选项",edit:"编辑",end_editing:"结束编辑 <1>{{name}}</1>"},tabs:{variant:{label:"风格",default:"默认",outline:"轮廓",pills:"胶囊"},orientation:{label:"朝向",horizontal:"水平",vertical:"垂直"},grow_tabs:"拉伸标签卡宽度"},choose_a_tab_first:"请先选择一个标签页"},breakpoint:{label_one:"屏幕尺寸",label_other:"屏幕尺寸",add:"新增屏幕尺寸",manage:"管理屏幕尺寸",breakpoint:"最小宽度"},context:{label:"上下文"},mock_context:{label:"模拟上下文",hint:"内容格式为JSON"},panel:{label:"卡片",labels:"卡片",add:"新增卡片",delete:"删除这个卡片",panel_name:"卡片名",panel_description:"卡片描述",panel_description_click:"点击查看卡片描述",show_title:"展示卡片标题",use_name_as_title:"使用卡片名作为标题",settings:{change_view:"移至另一个视图下",change_view_title:"移动此卡片至另一个视图下",choose_queries:"关联查询",need_to_choose_queries:"请关联至少一个查询以使用其数据"},style:{label:"样式",width:"宽",width_postfix:"之 36 栏",height:"高",height_postfix:"px",border:"边框"},variable:{label:"变量",labels:"变量",add:"新增变量",delete:"删除此变量",aggregation:{label:"聚合",fallback_value:"兜底值",fallback_value_description:"当数据为空或聚合结果非数字时,使用此兜底值"}}},style:{label:"样式",font_size:{label:"字号",placeholder:"10px, 1em, 1rem, 100%..."},font_weight:{label:"字重"},size:{xs:"特小",sm:"小",md:"中",lg:"大",xl:"特大"},flex:{justify_content:{label:"内容分布",left:"从左起",center:"居中",right:"从右起",space_between:"均匀分布,首尾顶格",space_around:"均匀分布,首尾留空一半",space_evenly:"均匀分布,首尾留空"},align_items:{label:"对齐位置",start:"起点对齐",center:"居中对齐",end:"末端对齐",stretch:"拉伸对齐"}},color:{type:{label:"颜色类型",static:"单色",interpolation:"插值取色",none:"无"},interpolation:{setup:"设置取色方案",palette:{label:"色板",category:{sequential:"单色渐变",diverging:"双色渐变"},red_green:"红 / 绿",yellow_blue:"黄 / 蓝",red:"红",green:"绿",blue:"蓝",orange:"橙",mapping:{value_input_label:"映射一个值到此颜色"}}}}},query:{label:"查询",labels:"查询",add:"新增查询",delete:"删除这个查询",cant_delete:"此查询在使用中,不能删除。请查看“使用情况”标签页以了解详情",delete_unused:"删除未用到的查询",name:"名称",name_description:"唯一名称",manage:"管理查询",open:"打开此查询",configurations:"配置",basics:"基本信息",conditions:"条件",run_by_condition:{label:"以下条件满足时,才运行本查询",unset:"看板加载时便运行本查询"},re_run_condition:{label:"当以下条件改变时,重新运行此查询",unset:"留空则永不重新运行此查询"},dependency:{label:"依赖",has_none:"此查询无依赖"},edit_sql:"编辑SQL",preview_sql:"预览SQL",request:"请求",build_request:"构造请求",process_request:"加工请求",process_result:"加工结果",usage:{label:"使用情况",in_views:"所在视图",unused_description:"此查询未被任何筛选器或卡片用到"},transform:{label:"查询变形",full_label:"查询变形",data_source:"基于其他查询的数据,加工出新数据",guide:{pick_queries:"选择一至多个查询作为数据输入",write_function:"编写函数,返回新数据"}}},data:{label:"数据",preview_data:"预览数据",empty_data:"无数据",requires_data:"请先关联查询"},data_source:{label:"数据源",explore:"查看数据源",explorer:"数据源查看器",table_structure:"数据表结构",table_structure_short:"表结构",see_table_structure:"查看数据表结构"},visualization:{label:"可视化",component:"可视化组件",label_short:"可视化"},numbro:{format:{label:"格式",absolute:"绝对值",absolute_description:"非负",abbreviation:"缩写",abbreviation_description:"如1.23k、1.23m",mantissa:"小数",trim_mantissa:"抹零",trim_mantissa_description:"省略末尾的零",preview:{open:"展开预览",close:"收起预览",input:"输入",output:"输出"}}},import:{label:"导入...",title:"自描述文件导入看板内容",json_file:"描述文件(JSON格式)",this_dashboard:"此看板",this_file:"此文件"},function_utils:{trigger_text:"关于utils参数",modal_title:"关于utils参数",description:"参数 <code>utils</code> 是 <code>FunctionUtils</code>,包含以下内容:",document:"文档"},aggregation:{option:{none:"无",sum:"和",mean:"平均值",median:"中位数",min:"最小值",max:"最大值",cov:"变异系数",std:"标准差",quantile:{label:"分位",label_with_hint:"分位(99%, 95%, ...)"},custom:{label:"自定义",label_trigger:"编写函数",title:"自定义聚合方式"},pick_record:{label:"直接选择数据",method:{label:"数据记录",first:"第一条",last:"最后一条"}}}},rich_text:{label:"富文本",content:{label:"内容"},dynamic_color:{label:"动态颜色",edit:"编辑动态颜色",clear:"清除动态颜色"},color_mapping:{label:"颜色映射",edit:"编辑颜色映射",clear:"清除颜色映射",choose_value_var:"选择用于映射颜色的变量",min:{val:"固定最小值",var:"动态最小值(优先)"},max:{val:"固定最大值",var:"动态最大值(优先)"}}},chart:{chart_config:"图表设置",data_field:"数据字段",groups:{merico_suite:"思码逸套件",echarts_based_charts:"基于ECharts的图表",others:"其他"},label:{label:"文案",label_full:"标签文案",label_style:"标签文案样式",label_format:"标签文案格式"},label_position:{label:"文案位置",off:"不显示文案",top:"上",left:"左",right:"右",bottom:"下",inside:"内",inside_top:"内-上",inside_left:"内-左",inside_center:"内-中",inside_right:"内-右",inside_bottom:"内-下",inside_top_left:"内-上-左",inside_top_right:"内-上-右",inside_bottom_left:"内-下-左",inside_bottom_right:"内-下-右",outside:"外"},visual_map:{label:"视觉映射",continuous:{label:"连续型"},piecewise:{label:"分段型",mode:{pieces:"连续数据",categories:"离散数据"},add_a_piece:"加一个分段",interval:"值区间",piece_label:"文案"},bar_width:"长条的宽度",bar_height:"长条的高度",item_width:"小块的宽度",item_height:"小块的高度",calculable:"显示拖拽手柄",min_value:"最小值",max_value:"最大值",min_text:"最小值文案",max_text:"最大值文案",use_palette_x:'使用配色方案"{{x}}"',built_in_palettes:"内置配色方案",precision:"数据精度",skip_range:{lt_min:"小于最小值时的颜色",min:"最小值的颜色",max:"最大值的颜色",gt_max:"大于最大值时的颜色",follow_visual_map:"颜色跟随渐变规则"}},number_or_dynamic_value:{type:{static:"具体值",dynamic:"动态值"},dynamic:{setup:"设置",setup_title:"设置动态值",guide:"由函数确定动态值"}},orientation:{label:"朝向",horizontal:"水平",vertical:"垂直"},symbol_size:{label:"标记点大小",static:"固定值",dynamic:"动态值",setup:{label:"设置",title:"设置动态值",description:"由函数确定动态值"}},series:{label:"系列",name:"名称",y_axis:"Y轴",data_field:"数据字段",add:"增加一个系列",delete:"删除这个系列",line:{label:"线",line_settings:"线段设置",line_style:"线条样式",type:{label:"类型",solid:"实线",dashed:"方虚线",dotted:"圆点虚线"},line_width:"线宽",step:{label:"阶梯状",off:"不启用",start:"在当前点拐弯",middle:"在当前点与下个点中间拐弯",end:"在下个点拐弯"},smooth_line:"平滑曲线",show_name_on_line:"显示标签文案",show_symbol_on_line:"显示标记点"},bar:{label:"柱",stack:"堆放",stack_hint:"此值相同的柱系列会堆叠在一起",bar_gap:{label:"柱间隔",no_gap:"柱子之间无间隔",overlap:"柱子可互相重叠"},bar_width:{min:"最小柱宽",exact:"柱宽",max:"最大柱宽"}},scatter:{label:"散点"},group_by:{label:"按此字段拆分为多个系列",label_line:"按此字段拆分为多条线"}},axis:{tick_label:"刻度文案",customize_label:"自定义文案",overflow:{label:"溢出",max_width:"最大宽度",truncate:"截断",break_line:"换行",break_word:"断词换行",ellipsis:"省略符",section_title:{on_axis:"轴刻度上文案的溢出",in_tooltip:"提示框中的文案溢出"}},section_title:{label_format:"文案格式"},type:{value:"数值轴",category:"类目轴",time:"时间轴",log:"对数轴",click_to_learn_more:"点击 <1>这里</1> 以进一步了解这些选项"}},name_text:{align:{label:"名称贴靠侧",left:"左",center:"中",right:"右"}},rotate:"旋转",degree:"度",padding:"内间距",content_template:{label:"内容模板",hint:"均值: ${avg}"},x_axis:{label:"X轴",labels:"X轴",label_format:"刻度文案格式",add:"增加一条X轴",delete:"删除这条X轴",x_axis_name:"X轴名称",x_axis_data_field:"X轴数据字段",x_axis_type:"X轴类型",layout:"布局",position:{label:"位置",top:"上",bottom:"下"},value_range:"值范围",value_min:"最小值",value_max:"最大值",behavior:"表现",visible:"可见"},y_axis:{label:"Y轴",labels:"Y轴",label_format:"刻度文案格式",add:"增加一条Y轴",delete:"删除这条Y轴",y_axis_name:"Y轴名称",y_axis_name_anchor:"名称贴靠侧",y_axis_data_field:"Y轴数据字段",layout:"布局",position:{label:"位置",left:"左",right:"右"},value_range:"值范围",value_min:"最小值",value_max:"最大值",behavior:"表现",visible:"可见"},stats:{label:"统计内容",template:{above_chart:"统计内容模板(图表上方)",under_chart:"统计内容模板(图表下方)"}},legend:{label:"图例",show_legend:"显示图例",show_in_legend:"显示在图例中",hide_in_legend:"不显示在图例中",orientation:{label:"布局朝向",horizontal:"横向",vertical:"纵向"}},tooltip:{label:"提示框",additional_metrics:{description:"在此设置更多指标,来展示在散点的提示框",add:"增加一个指标",delete:"删除这个指标"},trigger:{label:"触发者",scatter_point:"散点",x_axis:"X轴"}},style:{label:"样式"},color:{label:"颜色",or:"或",set_any_color:"输入色号",pick_a_theme_color:"选择一个主题色",background_color:"背景色",text_color:"文字颜色",click_to_add_a_color:"点击增加一个颜色",color_gradient:"颜色渐变"},behavior:{label:"表现",invisible:"隐藏不可见"},heatmap:{heatblock:{label:"热力块",show_label:"展示值文案"}},reference_line:{label:"参考线",labels:"参考线",add:"增加一条参考线",name_placeholder:"均值参考线",delete:"删除这条参考线",orientation:{vertical_hint:"仅当X轴值为数字时可绘制"}},regression_line:{label:"回归线",labels:"回归线",add:"增加一条回归线",delete:"删除这条回归线",method:{label:"方法",linear:"线性回归",exponential:"指数回归",logistic:"指数回归",polynomial:"多项式回归",polynomial_order:"次"}},reference_area:{label:"参考区域",labels:"参考区域",add:"增加一面参考区域",delete:"删除这面参考区域",type:{label:"形状",rectangle:"矩形"},direction:{label:"方向",horizontal:"水平"},boundary:{upper:"上边界",lower:"下边界"},content:{label:"内容",content_text:"内容文字",text_position:"文字位置"},endpoint:{labels:"端点",left_bottom_point:"左下点",right_top_point:"右上点"}},zooming:{label:"缩放",scroll:{label:"滚轮缩放",x_axis:"对X轴启用",y_axis:"对Y轴启用"},slider:{label:"滚动条缩放",x_axis:"对X轴启用",y_axis:"对Y轴启用",y_axis_disabled:"暂不可用,会与Y轴刻度文字重叠"}}},viz:{viz_config_banner:"可视化参数配置"},validation:{number:{require_a_number:"请填写一个数字"}}}},xi=Pm.createInstance({debug:!1,fallbackLng:"en",interpolation:{escapeValue:!1},resources:{en:jA,zh:wA}}).use(Om).use(j.initReactI18next);xi.init(),Yh.forEach(e=>{var t;(t=e.translation)==null||t.forEach(n=>{xi.addResourceBundle(n.lang,"translation",{viz:n.resources},!0,!0)})});function cg({lang:e,children:t}){return g.useEffect(()=>{xi.changeLanguage(e)},[e]),r.jsx(j.I18nextProvider,{i18n:xi,children:t})}function yi(e){console.groupCollapsed("Running operation ",e.type),console.log(e),console.groupEnd()}function ug(e,t){g.useEffect(()=>{const n=s=>{yi(s);const{viewID:i}=s.detail;if(!i){console.error(new Error("[Open View] Needs to pick a view first"));return}e.views.appendToVisibles(i),t&&e.views.setIDOfVIE(i)};return window.addEventListener("open-view",n),()=>{window.removeEventListener("open-view",n)}},[e,t]),g.useEffect(()=>{const n=s=>{yi(s);const{dictionary:i,payload:a}=s.detail;if(!a||Object.keys(a).length===0){console.error(new Error("[Set Filter Values] payload is empty"));return}const l={};Object.entries(i).forEach(([c,u])=>{const d=v.get(a,u);l[c]=d}),e.filters.applyValuesPatch(l)};return window.addEventListener("set-filter-values",n),()=>{window.removeEventListener("set-filter-values",n)}},[e]),g.useEffect(()=>{function n(i){return Array.isArray(i)?[]:typeof i=="object"?{}:typeof i=="boolean"?!1:typeof i=="string"?"":typeof i=="number"?0:i}const s=i=>{yi(i);const a={},{filter_keys:l}=i.detail;l.forEach(c=>{const u=v.get(e.filters.values,c),d=n(u);a[c]=d}),e.filters.applyValuesPatch(a)};return window.addEventListener("clear-filter-values",s),()=>{window.removeEventListener("clear-filter-values",s)}},[e]),g.useEffect(()=>{const n=s=>{yi(s);const{urlTemplate:i,openInNewTab:a,enableEncoding:l=!1,payload:c}=s.detail;if(!i){console.error(new Error("[Open Link] URL is empty"));return}function u(p){return v.cloneDeepWith(p,m=>{if(l&&typeof m=="string")return encodeURIComponent(m)})}const h=v.template(i||"")(u({...c,filters:e.payloadForSQL.filters,context:e.payloadForSQL.context}));window.open(h,a?"_blank":"_self","noopener")};return window.addEventListener("open-link",n),()=>{window.removeEventListener("open-link",n)}},[e])}function dg(e){return g.useCallback(t=>t.provideValue(Oe.pluginManager,e.pluginManager).provideValue(Oe.vizManager,e.vizManager).provideValue(Oe.colorManager,e.colorManager),[])}const jV="",CA=D.observer(({saveDashboardChanges:e})=>{const{t}=j.useTranslation(),n=wt.useModals(),s=re(),i=()=>{n.openConfirmModal({title:r.jsxs(o.Group,{position:"left",children:[r.jsx(M.IconAlertTriangle,{size:18,color:"red"}),r.jsx(o.Text,{children:"You are reverting changes"})]}),labels:{confirm:t("common.actions.confirm"),cancel:t("common.actions.cancel")},confirmProps:{color:"red"},onCancel:()=>console.log("Cancel"),onConfirm:()=>s.reset(),zIndex:320,withCloseButton:!1})},a=s.changed;return r.jsxs(o.Group,{spacing:0,children:[r.jsx(o.Button,{color:"green",variant:"filled",size:"xs",leftIcon:r.jsx(M.IconDeviceFloppy,{size:18}),onClick:e,disabled:!a,sx:{borderTopRightRadius:0,borderBottomRightRadius:0},children:t("common.actions.save_changes")}),r.jsxs(o.Menu,{width:200,trigger:"hover",openDelay:100,closeDelay:400,withinPortal:!0,zIndex:320,disabled:!a,children:[r.jsx(o.Menu.Target,{children:r.jsx(o.ActionIcon,{variant:"default",disabled:!a,sx:{height:"30px",borderTopLeftRadius:0,borderBottomLeftRadius:0,svg:{fill:"rgb(173, 181, 189)",stroke:"none"}},children:r.jsx(M.IconCaretDown,{size:18})})}),r.jsx(o.Menu.Dropdown,{children:r.jsx(o.Menu.Item,{icon:r.jsx(M.IconRecycle,{size:14,color:"red"}),disabled:!a,onClick:i,children:t("common.actions.revert_changes")})})]})]})}),SA=D.observer(({saveDashboardChanges:e,onExit:t,headerSlot:n=null})=>{j.useTranslation();const s=le(),i=s.content.changed,a=()=>{t({hasChanges:i,dashboardId:s.id})};return r.jsx(o.Header,{height:60,px:"md",py:0,sx:{zIndex:299},children:r.jsxs(o.Group,{position:"apart",sx:{height:60,minWidth:"1000px",position:"relative"},children:[r.jsxs(o.Group,{children:[r.jsx(o.Button,{size:"xs",color:i?"red":"green",leftIcon:r.jsx(M.IconArrowLeft,{size:20}),onClick:a,children:r.jsx(o.Group,{spacing:4,children:r.jsxs(j.Trans,{i18nKey:"common.actions.end_editing",values:{name:s.name},children:["End Editing ",r.jsx(o.Text,{td:"underline",children:s.name})]})})}),r.jsx(CA,{saveDashboardChanges:e})]}),r.jsx(o.Group,{position:"right",sx:{flexGrow:1},children:n})]})})}),pg={height:"30px",borderLeft:"none",borderTop:"none",borderRight:"1px solid #e9ecef",borderBottom:"1px solid #e9ecef"},kA=D.observer(()=>{var i;const{t:e}=j.useTranslation(),t=re(),n=((i=t.views.VIE)==null?void 0:i.type)===G.Tabs,s=()=>t.addANewPanel(t.views.idOfVIE);return n?r.jsx(o.Tooltip,{label:e("common.choose_a_tab_first"),children:r.jsx(o.Button,{variant:"outline",color:"gray",radius:0,size:"xs",leftIcon:r.jsx(M.IconPlaylistAdd,{size:20}),sx:{...pg,transform:"none !important"},children:e("panel.add")})}):r.jsx(o.Button,{variant:"outline",color:"blue",radius:0,size:"xs",onClick:s,leftIcon:r.jsx(M.IconPlaylistAdd,{size:20}),sx:{...pg,background:"rgb(231, 245, 255)"},children:e("panel.add")})}),TA=D.observer(({done:e})=>{var E,R;const{t}=j.useTranslation(),s=re().layouts,i=g.useMemo(()=>({list:s.breakpointsInfo}),[s.breakpointsInfo]),{control:a,handleSubmit:l,watch:c,getValues:u,reset:d,formState:h}=b.useForm({defaultValues:i}),{fields:p,append:f,remove:m}=b.useFieldArray({control:a,name:"list",rules:{validate:K=>{if(console.log({values:K}),v.uniqBy(K,"breakpoint").length!==K.length)return"Screen sizes should be unique by min width"}}}),y=c("list"),_=p.map((K,ye)=>({...K,...y[ye]})),k=()=>{f({id:on.v4(),name:"",breakpoint:""})},S=({list:K})=>{const ye=K.filter(xe=>Number.isFinite(xe.breakpoint));s.updateLayoutSetsInfo(ye),e()},T=u(),I=g.useMemo(()=>{const K={list:T.list.filter(ye=>!!ye.name&&Number.isFinite(ye.breakpoint))};return!v.isEqual(K,i)},[T,i]),z=(R=(E=h.errors.list)==null?void 0:E.root)==null?void 0:R.message;return r.jsx(r.Fragment,{children:r.jsxs("form",{onSubmit:l(S),children:[r.jsxs(o.Table,{fontSize:"sm",highlightOnHover:!0,withBorder:!0,sx:{tableLayout:"fixed"},children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{style:{width:"340px"},children:t("common.name")}),r.jsx("th",{style:{width:"160px"},children:t("breakpoint.breakpoint")}),r.jsx("th",{})]})}),r.jsxs("tbody",{children:[_.map((K,ye)=>r.jsxs("tr",{children:[r.jsx("th",{children:K.id==="basis"?K.name:r.jsx(b.Controller,{name:`list.${ye}.name`,control:a,render:({field:xe})=>r.jsx(o.TextInput,{size:"xs",label:"",required:!0,sx:{flex:1},...xe})})}),r.jsx("td",{children:K.id==="basis"?r.jsxs(o.Text,{ff:"monospace",children:[K.breakpoint,"px"]}):r.jsx(b.Controller,{name:`list.${ye}.breakpoint`,control:a,render:({field:xe})=>r.jsx(o.NumberInput,{size:"xs",label:"",required:!0,max:1e4,hideControls:!0,rightSection:r.jsx(o.Text,{color:"dimmed",children:"px"}),rightSectionProps:{style:{width:"30px"}},sx:{flex:1,fontFamily:"monospace"},styles:{input:{paddingRight:"30px"}},...xe})})}),r.jsx("td",{children:K.id!=="basis"&&r.jsx(o.ActionIcon,{mx:"auto",size:"xs",variant:"subtle",color:"red",onClick:()=>m(ye),children:r.jsx(M.IconTrash,{})})})]},K.id)),r.jsx("tr",{style:{backgroundColor:"transparent"},children:r.jsx("td",{colSpan:3,style:{padding:"0"},children:r.jsx(o.Tooltip,{label:t("breakpoint.add"),children:r.jsx(o.ActionIcon,{variant:"subtle",size:"md",color:"blue",onClick:k,sx:{width:"100%"},children:r.jsx(M.IconPlus,{size:18})})})})})]})]}),r.jsx(o.Text,{mt:6,ta:"right",size:"xs",color:"red",children:z??" "}),r.jsxs(o.Group,{mt:6,position:"apart",children:[r.jsx(o.Button,{color:"orange",size:"xs",onClick:()=>d(),leftIcon:r.jsx(M.IconRecycle,{size:18}),disabled:!I,children:t("common.actions.revert")}),r.jsx(o.Button,{color:"green",size:"xs",type:"submit",leftIcon:r.jsx(M.IconDeviceFloppy,{size:18}),disabled:!I,children:t("common.actions.save_changes")})]})]})})}),DA=D.observer(()=>{const{t:e}=j.useTranslation(),[t,{open:n,close:s}]=Se.useDisclosure(!1),i=re(),a=i.layouts.currentBreakpoint,l=i.layouts.currentLayoutRange,c=()=>{setTimeout(()=>{window.dispatchEvent(new Event("resize"))},32)},u=()=>{s(),c()};return r.jsxs(r.Fragment,{children:[r.jsxs(o.Group,{children:[r.jsxs(o.Menu,{withArrow:!0,withinPortal:!0,zIndex:320,trigger:"hover",children:[r.jsx(o.Menu.Target,{children:r.jsx(o.Button,{size:"xs",variant:"subtle",leftIcon:r.jsx(M.IconDevices,{size:16}),sx:{borderRadius:0},children:r.jsxs(o.Group,{spacing:6,children:[r.jsx(o.Text,{size:"xs",fw:"normal",children:l.name}),r.jsx(o.Text,{size:"xs",color:"#777",children:i.layouts.currentRangeText})]})})}),r.jsxs(o.Menu.Dropdown,{children:[i.layouts.breakpointRanges.map(d=>r.jsx(o.Menu.Item,{onClick:()=>i.layouts.setCurrentBreakpoint(d.id),disabled:a===d.id,children:r.jsxs(o.Group,{position:"apart",children:[r.jsx(o.Text,{size:"sm",children:d.name}),r.jsx(o.Text,{size:"xs",color:"dimmed",children:d.text})]})},d.id)),r.jsx(o.Menu.Divider,{}),r.jsx(o.Menu.Item,{color:"blue",icon:r.jsx(M.IconSettings,{size:14}),onClick:n,children:r.jsx(o.Text,{size:"sm",children:e("breakpoint.manage")})})]})]}),i.layouts.divisionPreviewScale<1&&r.jsx(o.Text,{size:"xs",color:"dimmed",children:ss(i.layouts.divisionPreviewScale).format({output:"percent",mantissa:0})})]}),r.jsx(o.Modal,{opened:t,onClose:u,title:e("breakpoint.label",{count:2}),withinPortal:!0,zIndex:320,size:600,closeOnClickOutside:!1,children:r.jsx(TA,{done:u})})]})}),hg={height:"30px",borderRight:"none",borderTop:"none",borderLeft:"1px solid #e9ecef",borderBottom:"1px solid #e9ecef"},MA=D.observer(()=>{var i;const{t:e}=j.useTranslation(),t=re(),n=((i=t.views.VIE)==null?void 0:i.type)===G.Tabs,s=()=>{var a;return(a=t.views.VIE)==null?void 0:a.downloadSchema()};return n?r.jsx(o.Tooltip,{label:e("common.choose_a_tab_first"),children:r.jsx(o.Button,{variant:"outline",color:"gray",radius:0,size:"xs",leftIcon:r.jsx(M.IconCode,{size:16}),sx:{...hg,transform:"none !important"},children:e("view.download_schema")})}):r.jsx(o.Button,{variant:"outline",color:"blue",radius:0,size:"xs",onClick:s,leftIcon:r.jsx(M.IconCode,{size:16}),sx:{...hg},children:e("view.download_schema")})}),bi=({headers:e,rows:t})=>r.jsxs(o.Table,{fontSize:"xs",highlightOnHover:!0,sx:{tableLayout:"fixed",fontFamily:"monospace"},children:[r.jsx("thead",{children:e}),r.jsx("tbody",{children:t})]}),IA=({content:e})=>{const{t}=j.useTranslation(),n=e.views;return!Array.isArray(n)||n.length===0?null:r.jsxs(o.Box,{children:[r.jsx(o.Text,{pl:10,size:"sm",fw:500,c:"dimmed",ta:"center",children:t("view.labels")}),r.jsx(bi,{headers:r.jsxs("tr",{children:[r.jsx("th",{style:{width:"160px"},children:t("common.id")}),r.jsx("th",{children:t("common.name")}),r.jsx("th",{children:t("common.type")})]}),rows:n.map(s=>r.jsxs("tr",{children:[r.jsx("td",{children:s.id}),r.jsx("td",{children:s.name}),r.jsx("td",{children:t(`view.component.${s.type}.label`)})]},s.id))})]})},zA=({content:e})=>{const{t}=j.useTranslation(),n=e.filters;return!Array.isArray(n)||n.length===0?null:r.jsxs(o.Box,{children:[r.jsx(o.Text,{pl:10,size:"sm",fw:500,c:"dimmed",ta:"center",children:t("filter.labels")}),r.jsx(bi,{headers:r.jsxs("tr",{children:[r.jsx("th",{style:{width:"160px"},children:t("common.id")}),r.jsx("th",{children:t("common.key")}),r.jsx("th",{children:t("common.label")})]}),rows:n.map(s=>r.jsxs("tr",{children:[r.jsx("td",{children:s.id}),r.jsx("td",{children:s.key}),r.jsx("td",{children:s.label})]},s.id))})]})},EA=({content:e})=>{const{t}=j.useTranslation(),n=e.panels;return!Array.isArray(n)||n.length===0?null:r.jsxs(o.Box,{children:[r.jsx(o.Text,{pl:10,size:"sm",fw:500,c:"dimmed",ta:"center",children:t("panel.labels")}),r.jsx(bi,{headers:r.jsxs("tr",{children:[r.jsx("th",{style:{width:"160px"},children:t("common.id")}),r.jsx("th",{children:t("common.name")}),r.jsx("th",{children:t("visualization.component")})]}),rows:n.map(s=>r.jsxs("tr",{children:[r.jsx("td",{children:s.id}),r.jsx("td",{children:s.name}),r.jsx("td",{children:s.viz.type})]},s.id))})]})},AA=({content:e})=>{var s;const{t}=j.useTranslation(),n=(s=e.definition)==null?void 0:s.queries;return!Array.isArray(n)||n.length===0?null:r.jsxs(o.Box,{children:[r.jsx(o.Text,{pl:10,size:"sm",fw:500,c:"dimmed",ta:"center",children:t("query.labels")}),r.jsx(bi,{headers:r.jsxs("tr",{children:[r.jsx("th",{style:{width:"160px"},children:t("common.id")}),r.jsx("th",{children:t("common.name")}),r.jsx("th",{style:{width:"140px"},children:t("common.type")}),r.jsx("th",{style:{width:"260px"},children:t("data_source.label")})]}),rows:n.map(i=>r.jsxs("tr",{children:[r.jsx("td",{children:i.id}),r.jsx("td",{children:i.name}),r.jsx("td",{children:i.type}),r.jsx("td",{children:i.key})]},i.id))})]})},PA=({content:e})=>{var s;const{t}=j.useTranslation(),n=(s=e.definition)==null?void 0:s.sqlSnippets;return!Array.isArray(n)||n.length===0?null:r.jsxs(o.Box,{children:[r.jsx(o.Text,{pl:10,size:"sm",fw:500,c:"dimmed",ta:"center",children:t("sql_snippet.labels")}),r.jsx(o.List,{size:"sm",pl:10,ff:"monospace",icon:r.jsx(M.IconPointFilled,{size:10}),children:n.map(i=>r.jsx(o.List.Item,{children:i.key},i.key))})]})},OA=({content:e})=>{var s;const{t}=j.useTranslation(),n=Object.keys(((s=e.definition)==null?void 0:s.mock_context)??{});return n.length===0?null:r.jsxs(o.Box,{children:[r.jsx(o.Text,{pl:10,size:"sm",fw:500,c:"dimmed",ta:"center",children:t("mock_context.label")}),r.jsx(o.List,{size:"sm",pl:10,ff:"monospace",icon:r.jsx(M.IconPointFilled,{size:10}),children:n.map(i=>r.jsx(o.List.Item,{children:i},i))})]})},LA=({content:e})=>e?r.jsxs(o.Box,{children:[r.jsx(o.Divider,{mt:20,mb:10,variant:"dashed"}),r.jsx(o.Text,{ta:"left",c:"dimmed",children:"Preview"}),r.jsxs(o.Stack,{children:[r.jsx(IA,{content:e}),r.jsx(zA,{content:e}),r.jsx(EA,{content:e}),r.jsx(AA,{content:e}),r.jsx(PA,{content:e}),r.jsx(OA,{content:e})]})]}):null;function VA(e){if(e.target===null)throw new Error("FileReader failed with null result");if(typeof e.target.result!="string")throw new Error(`Unparsable file content of type: ${typeof e.target.result}`);let t=JSON.parse(e.target.result);if("content"in t&&(t=t.content),t.version!==gn)throw new Error("Schema version mismatch");return t}const BA=D.observer(({onSuccess:e,stretchModal:t,shrinkModal:n})=>{var S,T;const{t:s}=j.useTranslation(),i=re(),{handleSubmit:a,formState:{errors:l},setValue:c,watch:u,setError:d,clearErrors:h}=b.useForm({defaultValues:{content:null}}),p=({content:I})=>{try{if(!I)throw new Error("please use a valid json file");i.applyJSONSchema(I),Yt.showNotification({title:"Successful",message:"",color:"green"}),e()}catch(z){console.error(z),Yt.showNotification({title:"Failed",message:z.message,color:"red"})}},[f,m]=g.useState(null);g.useEffect(()=>{if(!f)return;const I=new FileReader;I.readAsText(f,"UTF-8"),I.onload=z=>{try{const E=VA(z);c("content",E),h("content")}catch(E){console.error(E),d("content",{type:"custom",message:E.message})}},I.onabort=()=>console.log("🟨 abort"),I.onerror=()=>{I.error&&(console.error(I.error),d("content",{type:"custom",message:I.error.message}))}},[f]);const[y]=u(["content"]),_=!y,k=(S=l==null?void 0:l.content)==null?void 0:S.message;return g.useEffect(()=>{!y||k?n():t()},[y,k]),r.jsx(o.Box,{mx:"auto",sx:{position:"relative"},children:r.jsxs("form",{onSubmit:a(p),children:[r.jsx(o.FileInput,{label:s("import.json_file"),required:!0,value:f,onChange:m,error:(T=l==null?void 0:l.content)==null?void 0:T.message,sx:{maxWidth:500}}),k?r.jsx(o.Table,{fontSize:12,mt:10,children:r.jsxs("tbody",{children:[r.jsxs("tr",{children:[r.jsx("th",{children:s("import.this_dashboard")}),r.jsx("td",{children:gn})]}),r.jsxs("tr",{children:[r.jsx("th",{children:s("import.this_file")}),r.jsx("td",{style:{color:"red"},children:y==null?void 0:y.version})]})]})}):r.jsxs(r.Fragment,{children:[r.jsx(LA,{content:y}),r.jsx(o.Group,{position:"right",my:"md",children:r.jsx(o.Button,{type:"submit",color:"green",disabled:_,children:s("common.actions.confirm")})})]})]})})}),fg={height:"30px",borderLeft:"none",borderTop:"none",borderRight:"1px solid #e9ecef",borderBottom:"1px solid #e9ecef"},qA=D.observer(()=>{var d;const{t:e}=j.useTranslation(),[t,{open:n,close:s}]=Se.useDisclosure(!1),[i,{setTrue:a,setFalse:l}]=J.useBoolean(!1),u=((d=le().content.views.VIE)==null?void 0:d.type)===G.Tabs;return u?r.jsx(o.Tooltip,{label:e("common.choose_a_tab_first"),children:r.jsx(o.Button,{variant:"outline",color:"gray",radius:0,size:"xs",leftIcon:r.jsx(M.IconFileImport,{size:16}),sx:{...fg,transform:"none !important"},children:e("import.label")})}):r.jsxs(r.Fragment,{children:[r.jsx(o.Button,{variant:"subtle",color:"blue",radius:0,size:"xs",disabled:u||t,onClick:n,leftIcon:r.jsx(M.IconFileImport,{size:16}),sx:{...fg},children:e("import.label")}),r.jsx(o.Modal,{opened:t,onClose:s,title:e("import.title"),trapFocus:!0,onDragStart:h=>{h.stopPropagation()},withinPortal:!0,zIndex:320,size:i?"90vw":500,children:r.jsx(BA,{onSuccess:s,stretchModal:a,shrinkModal:l})})]})}),NA={position:"fixed",top:60,left:0,right:0,height:30,zIndex:299,borderBottom:"1px solid #e9ecef",background:"rgba(233,236,239, 0.15)"},$A=D.observer(()=>r.jsx(o.Box,{sx:NA,pl:{base:200,xs:200,sm:200,md:220,lg:240,xl:260},children:r.jsxs(o.Group,{position:"apart",align:"center",sx:{height:"30px"},children:[r.jsxs(o.Group,{position:"left",spacing:0,children:[r.jsx(kA,{}),r.jsx(qA,{})]}),r.jsx(DA,{}),r.jsx(o.Group,{position:"right",spacing:0,children:r.jsx(MA,{})})]})})),FA=D.observer(e=>r.jsxs(r.Fragment,{children:[r.jsx(SA,{...e}),r.jsx($A,{})]})),wV="";function GA(e,t,n){const s=[];return e.filter(i=>"__INTERACTIONS"in i.viz.conf).forEach((i,a)=>{const l=t[i.id];l.data.interactions=v.get(l,"data.interactions",[]);const{__INTERACTIONS:c,__OPERATIONS:u,__TRIGGERS:d}=i.viz.conf;Object.entries(u).forEach(([h,p])=>{const{schemaRef:f,data:m}=p,{config:y}=m;switch(f){case"builtin:op:open-link":let _=y.urlTemplate.substring(0,100);y.urlTemplate.length>=20&&(_+="..."),l.type="interaction",l.data.interactions.push({schemaRef:f,urlTemplate:y.urlTemplate,shortURLTemplate:_});return;case"builtin:op:open_view":s.push({id:`OPERATION--${h}`,source:i.id,target:y.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:f,filters:Object.keys(y.dictionary).map(k=>({key:k,label:n[k]}))});return;case"builtin:op:clear_filter_values":l.type="interaction",l.data.interactions.push({schemaRef:f,filters:y.filter_keys.map(k=>({key:k,label:n[k]}))});return;default:return}})}),s}function WA(e,t){const n=e.filters.keyLabelMap;return{edges:GA(e.panels.list,t,n),edgeNodes:[]}}function gg(e,t,n){return e*t+e*n}function RA(e,t,n){return e*t+(e-1)*n}const vi=25,Vl=40,mg=25,Bl=350,QA=150,UA=150,xg=150,yg=300,_i=40,bg=25,YA=300;function KA(e,t){const n=v.keyBy(t,i=>i.id),s=[];return e.current.forEach((i,a)=>{i.panelIDs.forEach((l,c)=>{const u=gg(c,_i,bg)+Vl,d=n[l];if(!d){s.push({id:l,_node_type:"panel",parentNode:i.id,data:{label:`!: ${l}`},position:{x:vi,y:u},sourcePosition:Ue.Position.Right,targetPosition:Ue.Position.Left,style:{width:yg,height:_i}});return}const h=d.name;s.push({id:d.id,_node_type:"panel",parentNode:i.id,data:{label:h},position:{x:vi,y:u},sourcePosition:Ue.Position.Right,targetPosition:Ue.Position.Left,style:{width:yg,height:_i}})})}),s}const XA={[G.Division]:"Div",[G.Modal]:"Modal",[G.Tabs]:"Tabs"},JA=Zf;function ZA(e){return e.current.map((n,s)=>{const i=RA(n.panelIDs.length,_i,bg)+Vl+mg;let a=[];return n.type===G.Tabs&&(a=n.config.tabsInOrder.map(c=>c.view_id)),{id:n.id,_node_type:"view-root",_view_type:n.type,_view_level:0,_sub_view_ids:[],_tab_view_ids:a,data:{label:`${XA[n.type]}:${n.name}`},position:{x:0,y:0},sourcePosition:Ue.Position.Right,targetPosition:Ue.Position.Left,className:"light",style:{backgroundColor:JA[n.type],width:Bl,height:i}}})}function HA(e){const t=v.keyBy(e,n=>n.id);e.forEach(n=>{n._node_type!=="view-root"||n._view_type!==G.Tabs||n._tab_view_ids.forEach(s=>{t[s].parentNode=n.id})})}function eP(e){const t=ZA(e.views);HA(t);const n=KA(e.views,e.panels.list);return[...t,...n]}function tP({nodeMap:e,nodes:t,edges:n}){t.forEach(s=>{s._node_type!=="view-root"||s._view_type!==G.Tabs||(s.sourcePosition=Ue.Position.Bottom,s.style.width=Bl+vi*2,s.style.height=mg+s._tab_view_ids.reduce((i,a)=>{const l=e[a];l.position.y=i,l.position.x=vi;const c=l.style.height;return i+c+20},Vl))})}function nP({nodeMap:e,nodes:t,edges:n}){n.filter(s=>s.label==="Open View").forEach(s=>{const i=e[s.source],a=e[s.target];if(!i||!a||!i.parentNode)return;const l=e[i.parentNode];l._node_type!=="view-root"||a._node_type!=="view-root"||(a._view_level+=1+l._view_level,l._sub_view_ids.push(a.id))}),t.sort((s,i)=>s._node_type==="view-root"&&i._node_type==="view-root"?s._view_level-i._view_level:s._node_type!=="view-root"&&i._node_type!=="view-root"?0:s._node_type==="view-root"?-1:1)}function rP({nodeMap:e,nodes:t,edges:n}){const s={};n.forEach(i=>{if(i.label!=="Open View")return;const a=e[i.source],l=e[i.target];if(a&&l&&a.parentNode){const c=e[a.parentNode],u=c.position.x,d=Number(v.get(l,"style.height",0)),h=Number(c.style.width);l.position.x=u+h+YA,c._view_level===0&&l._sub_view_ids.length===0&&(a.sourcePosition=Ue.Position.Left,l.targetPosition=Ue.Position.Right,l.position.x*=-1);const f=l.position.x,m=v.get(s,f,0);l.position.y=m,s[f]=m+d+xg}})}function sP({nodeMap:e,nodes:t,edges:n}){const s=new Set,i=new Set;n.forEach(l=>{s.add(l.source),i.add(l.target)}),t.filter(l=>l._node_type!=="view-root"||l.id==="Main"||l.parentNode?!1:!s.has(l.id)&&!i.has(l.id)).forEach((l,c)=>{l.position.x=gg(c,Bl,UA),l.position.y=0-QA-xg})}function iP({nodeMap:e,nodes:t,edges:n}){const s={nodeMap:e,nodes:t,edges:n};return sP(s),nP(s),tP(s),rP(s),{nodes:t,edges:n}}function aP(e){const t=eP(e),n=v.keyBy(t,u=>u.id),{edges:s,edgeNodes:i}=WA(e,n),a=[...t,...i],l=v.keyBy(a,u=>u.id),c={edges:v.uniqBy(s,u=>u.id),nodes:a,nodeMap:l};return iP(c)}const CV="",ql={"builtin:op:open-link":r.jsx(o.ThemeIcon,{color:"blue",size:20,radius:"xl",children:r.jsx(M.IconCircleDashed,{size:14})}),"builtin:op:set_filter_values":r.jsx(o.ThemeIcon,{color:"orange",size:20,radius:"xl",children:r.jsx(M.IconCircleDot,{size:14})}),"builtin:op:clear_filter_values":r.jsx(o.ThemeIcon,{color:"orange",size:20,radius:"xl",children:r.jsx(M.IconCircleOff,{size:14})})};function oP(e){const t=[];return e.forEach(n=>{switch(n.schemaRef){case"builtin:op:open-link":t.push({key:n.urlTemplate,icon:ql[n.schemaRef],text:r.jsxs(o.Group,{spacing:4,children:[r.jsx(o.Text,{children:"Open: "}),r.jsx(o.Text,{color:"dimmed",children:n.shortURLTemplate})]})});return;case"builtin:op:set_filter_values":n.filters.forEach(({key:s,label:i})=>{t.push({key:n.schemaRef+s,icon:ql[n.schemaRef],text:r.jsx(o.Group,{spacing:4,children:r.jsxs(o.Text,{children:["Set Filter: ",i]})})})});return;case"builtin:op:clear_filter_values":n.filters.forEach(({key:s,label:i})=>{t.push({key:n.schemaRef+s,icon:ql[n.schemaRef],text:r.jsx(o.Group,{spacing:4,children:r.jsxs(o.Text,{children:["Clear Filter: ",i]})})})});return}}),t}const lP=g.memo(({data:e,isConnectable:t,sourcePosition:n=Ue.Position.Right,targetPosition:s=Ue.Position.Left,...i})=>{const a=g.useMemo(()=>oP(e.interactions),[e.interactions]);return r.jsxs(r.Fragment,{children:[r.jsx(Ue.Handle,{type:"target",position:s,isConnectable:t}),r.jsx(o.Box,{sx:{position:"absolute",top:0,right:0},children:r.jsx(W.ChevronsUpRight,{size:12})}),r.jsxs(o.HoverCard,{shadow:"xl",withinPortal:!0,children:[r.jsx(o.HoverCard.Target,{children:r.jsx(o.Text,{children:e.label})}),r.jsx(o.HoverCard.Dropdown,{children:r.jsx(o.List,{spacing:"xs",size:"sm",center:!0,children:a.map(l=>r.jsx(o.List.Item,{icon:l.icon,children:l.text},l.key))})})]}),r.jsx(Ue.Handle,{type:"source",position:n,isConnectable:t})]})}),SV="",cP={interaction:lP},uP=D.observer(()=>{const e=Pe(),{edges:t,nodes:n}=aP(e);return r.jsxs(Ue,{nodes:n,edges:t,onNodesChange:v.noop,onEdgesChange:v.noop,onConnect:v.noop,className:"interactions-viewer",fitView:!0,nodeTypes:cP,children:[r.jsx(Ue.MiniMap,{}),r.jsx(Ue.Controls,{}),r.jsx(Ue.Background,{})]})}),dP=D.observer(({opened:e,close:t})=>{const{t:n}=j.useTranslation();return r.jsx(o.Modal,{size:"96vw",opened:e,onClose:t,title:n("interactions.interactions_viewer"),trapFocus:!0,onDragStart:s=>{s.stopPropagation()},styles:{body:{height:"calc(90vh - 54px)"},content:{transform:"none !important"}},zIndex:300,children:r.jsx(uP,{})})}),pP={"> 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 hP({onClick:e,name:t,active:n,openSettings:s}){return r.jsxs(o.Box,{sx:{position:"relative"},children:[r.jsx(o.UnstyledButton,{sx:i=>({display:"block",width:"100%",padding:i.spacing.xs,borderRadius:0,position:"relative",color:i.black,"&:hover":{backgroundColor:i.colors.gray[0]},backgroundColor:n?i.colors.gray[2]:"transparent"}),children:r.jsx(o.Group,{sx:{width:"calc(100% - 28px)"},onClick:e,children:r.jsx(o.Text,{size:"sm",children:t})})}),n&&r.jsx(o.Tooltip,{label:"Edit",position:"right",withinPortal:!0,children:r.jsx(o.ActionIcon,{onClick:s,variant:"light",color:"blue",sx:{position:"absolute",top:0,bottom:0,height:"100%",right:0,zIndex:0,borderRadius:0},children:r.jsx(M.IconAdjustments,{size:16})})})]})}const fP=D.observer(()=>{const{t:e}=j.useTranslation(),t=le(),n=re(),s=g.useCallback(a=>()=>n.views.setIDOfVIE(a),[n]),i=a=>{t.editor.open(["_VIEWS_",a])};return r.jsxs(o.Box,{sx:{position:"relative"},children:[n.views.options.map(a=>r.jsx(hP,{active:n.views.idOfVIE===a.value,name:a.label,onClick:s(a.value),openSettings:()=>i(a.value)},a.value)),r.jsx(o.Divider,{variant:"dashed"}),r.jsx(o.Button,{variant:"subtle",rightIcon:r.jsx(M.IconPlus,{size:14}),size:"sm",px:"xs",color:"blue",onClick:n.views.addARandomNewView,sx:{width:"100%",borderRadius:0},styles:{inner:{justifyContent:"space-between"}},children:e("view.add")})]})}),gP=D.observer(()=>{const{t:e}=j.useTranslation(),t=le(),n=re(),s=()=>{if(!n.queries.firstID){t.editor.open(["_QUERIES_",""]);return}t.editor.open(["_QUERIES_",n.queries.firstID])},i=()=>{if(!n.filters.firstID){t.editor.open(["_FILTERS_",""]);return}t.editor.open(["_FILTERS_",n.filters.firstID])},[a,l]=g.useState(!1),c=()=>l(!0),u=()=>l(!1);return r.jsxs(o.Navbar,{p:0,width:{base:200,xs:200,sm:200,md:220,lg:240,xl:260},zIndex:299,children:[r.jsxs(o.Navbar.Section,{children:[r.jsxs(o.Group,{grow:!0,spacing:0,sx:{...pP,button:{borderWidth:0,borderBottomWidth:1,borderColor:"#e9ecef"}},children:[r.jsx(o.Tooltip,{label:e("filter.labels"),withinPortal:!0,children:r.jsx(o.ActionIcon,{variant:"default",radius:0,size:"md",sx:{height:"30px"},onClick:i,children:r.jsx(M.IconFilter,{size:18})})}),r.jsx(o.Tooltip,{label:e("query.labels"),withinPortal:!0,children:r.jsx(o.ActionIcon,{variant:"default",radius:0,size:"md",sx:{height:"30px"},onClick:s,children:r.jsx(M.IconDatabase,{size:18})})}),r.jsx(o.Tooltip,{label:e("interactions.interactions_viewer"),withinPortal:!0,children:r.jsx(o.ActionIcon,{variant:"default",radius:0,size:"md",sx:{height:"30px"},onClick:c,children:r.jsx(M.IconLink,{size:18})})})]}),r.jsx(dP,{opened:a,close:u})]}),r.jsx(o.Navbar.Section,{py:5,sx:{borderBottom:"1px solid #eee"},children:r.jsx(o.Text,{align:"center",sx:{userSelect:"none",cursor:"default"},children:e("view.labels")})}),r.jsx(o.Navbar.Section,{grow:!0,sx:{overflow:"auto"},children:r.jsx(fP,{})}),r.jsx(o.Navbar.Section,{children:r.jsx(o.Group,{grow:!0,p:"md",pt:"sm",sx:{borderTop:"1px solid #eee"},children:r.jsx(o.Button,{size:"xs",leftIcon:r.jsx(M.IconSettings,{size:20}),onClick:()=>t.editor.open([]),children:e("common.titles.settings")})})})]})}),mP={[Ce.Checkbox]:"true",[Ce.DateRange]:"[new Date('2023-01-01 00:00:00'), new Date('2024-01-01 00:00:00')]",[Ce.MultiSelect]:"[]",[Ce.Select]:'""',[Ce.TreeSelect]:"[]",[Ce.TextInput]:'""'},xP=e=>["function getDefaultValue(filter, utils, context) {",` return ${mP[e]};`,"}"].join(`