@devtable/dashboard 10.32.0 → 10.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- (function(I,y){typeof exports=="object"&&typeof module<"u"?y(exports,require("react"),require("@mantine/core"),require("@mantine/modals"),require("ahooks"),require("mobx"),require("mobx-react-lite"),require("crypto-js"),require("dayjs"),require("lodash"),require("numbro"),require("d3-array"),require("mathjs"),require("@faker-js/faker"),require("axios"),require("eventemitter2"),require("chroma-js"),require("echarts-gl"),require("echarts/core"),require("echarts/components"),require("echarts/renderers"),require("echarts-for-react/lib/core"),require("react-hook-form"),require("tabler-icons-react"),require("echarts/charts"),require("@tabler/icons-react"),require("@mantine/hooks"),require("@mantine/notifications"),require("@mantine/tiptap"),require("@tiptap/extension-color"),require("@tiptap/extension-highlight"),require("@tiptap/extension-placeholder"),require("@tiptap/extension-subscript"),require("@tiptap/extension-superscript"),require("@tiptap/extension-text-align"),require("@tiptap/extension-text-style"),require("@tiptap/extension-table"),require("@tiptap/extension-table-cell"),require("@tiptap/extension-table-header"),require("@tiptap/extension-table-row"),require("@tiptap/extension-underline"),require("@tiptap/react"),require("@tiptap/starter-kit"),require("prosemirror-keymap"),require("prosemirror-commands"),require("prosemirror-schema-list"),require("@monaco-editor/react"),require("popmotion"),require("d3-regression"),require("@mantine/prism"),require("@tanstack/react-table"),require("react-virtual"),require("@mantine/dates"),require("rc-select"),require("rc-tree-select"),require("react-grid-layout"),require("mobx-state-tree"),require("performant-array-to-tree"),require("jszip"),require("file-saver"),require("dom-to-image-more"),require("react-router-dom"),require("reactflow")):typeof define=="function"&&define.amd?define(["exports","react","@mantine/core","@mantine/modals","ahooks","mobx","mobx-react-lite","crypto-js","dayjs","lodash","numbro","d3-array","mathjs","@faker-js/faker","axios","eventemitter2","chroma-js","echarts-gl","echarts/core","echarts/components","echarts/renderers","echarts-for-react/lib/core","react-hook-form","tabler-icons-react","echarts/charts","@tabler/icons-react","@mantine/hooks","@mantine/notifications","@mantine/tiptap","@tiptap/extension-color","@tiptap/extension-highlight","@tiptap/extension-placeholder","@tiptap/extension-subscript","@tiptap/extension-superscript","@tiptap/extension-text-align","@tiptap/extension-text-style","@tiptap/extension-table","@tiptap/extension-table-cell","@tiptap/extension-table-header","@tiptap/extension-table-row","@tiptap/extension-underline","@tiptap/react","@tiptap/starter-kit","prosemirror-keymap","prosemirror-commands","prosemirror-schema-list","@monaco-editor/react","popmotion","d3-regression","@mantine/prism","@tanstack/react-table","react-virtual","@mantine/dates","rc-select","rc-tree-select","react-grid-layout","mobx-state-tree","performant-array-to-tree","jszip","file-saver","dom-to-image-more","react-router-dom","reactflow"],y):(I=typeof globalThis<"u"?globalThis:I||self,y(I.dashboard={},I.react,I["@mantine/core"],I["@mantine/modals"],I.ahooks,I.mobx,I["mobx-react-lite"],I.CryptoJS,I.dayjs,I._,I.numbro,I["d3-array"],I.mathjs,I["@faker-js/faker"],I.axios,I.eventemitter2,I["chroma-js"],I["echarts-gl"],I["echarts/core"],I["echarts/components"],I["echarts/renderers"],I["echarts-for-react/lib/core"],I["react-hook-form"],I["tabler-icons-react"],I["echarts/charts"],I["@tabler/icons-react"],I["@mantine/hooks"],I["@mantine/notifications"],I["@mantine/tiptap"],I["@tiptap/extension-color"],I["@tiptap/extension-highlight"],I["@tiptap/extension-placeholder"],I["@tiptap/extension-subscript"],I["@tiptap/extension-superscript"],I["@tiptap/extension-text-align"],I["@tiptap/extension-text-style"],I["@tiptap/extension-table"],I["@tiptap/extension-table-cell"],I["@tiptap/extension-table-header"],I["@tiptap/extension-table-row"],I["@tiptap/extension-underline"],I["@tiptap/react"],I["@tiptap/starter-kit"],I["prosemirror-keymap"],I["prosemirror-commands"],I["prosemirror-schema-list"],I["@monaco-editor/react"],I.popmotion,I["d3-regression"],I["@mantine/prism"],I["@tanstack/react-table"],I["react-virtual"],I["@mantine/dates"],I["rc-select"],I["rc-tree-select"],I["react-grid-layout"],I["mobx-state-tree"],I["performant-array-to-tree"],I.jszip,I["file-saver"],I["dom-to-image-more"],I["react-router-dom"],I.reactflow))})(this,function(I,y,s,Qe,K,te,k,Ia,Y,x,Z,Kt,Du,Iu,mt,Ma,ct,GI,Mu,q,Pe,Be,v,T,he,$,Ie,vn,J,Aa,za,Ea,$a,La,Oa,Pa,Ba,Va,Na,qa,Fa,Ga,Wa,WI,Me,pr,Ae,_t,Au,kt,tt,zu,Eu,ja,Ra,xn,b,$u,Lu,hr,Ya,Ou,$e){"use strict";var qI=Object.defineProperty;var FI=(I,y,s)=>y in I?qI(I,y,{enumerable:!0,configurable:!0,writable:!0,value:s}):I[y]=s;var N=(I,y,s)=>(FI(I,typeof y!="symbol"?y+"":y,s),s);function wn(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const Pu=wn(Kt),Cn=wn(Du),ie=wn(Mu),yt=wn(Au);var re=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Xt={},Bu={get exports(){return Xt},set exports(e){Xt=e}},Jt={};/**
1
+ (function(I,b){typeof exports=="object"&&typeof module<"u"?b(exports,require("react"),require("@mantine/core"),require("@mantine/modals"),require("ahooks"),require("mobx"),require("mobx-react-lite"),require("crypto-js"),require("dayjs"),require("lodash"),require("numbro"),require("d3-array"),require("mathjs"),require("@faker-js/faker"),require("axios"),require("eventemitter2"),require("chroma-js"),require("echarts-gl"),require("echarts/core"),require("echarts/components"),require("echarts/renderers"),require("echarts-for-react/lib/core"),require("react-hook-form"),require("tabler-icons-react"),require("echarts/charts"),require("@tabler/icons-react"),require("@mantine/hooks"),require("@mantine/notifications"),require("@mantine/tiptap"),require("@tiptap/extension-color"),require("@tiptap/extension-highlight"),require("@tiptap/extension-placeholder"),require("@tiptap/extension-subscript"),require("@tiptap/extension-superscript"),require("@tiptap/extension-text-align"),require("@tiptap/extension-text-style"),require("@tiptap/extension-table"),require("@tiptap/extension-table-cell"),require("@tiptap/extension-table-header"),require("@tiptap/extension-table-row"),require("@tiptap/extension-underline"),require("@tiptap/react"),require("@tiptap/starter-kit"),require("prosemirror-keymap"),require("prosemirror-commands"),require("prosemirror-schema-list"),require("@monaco-editor/react"),require("popmotion"),require("d3-regression"),require("@mantine/prism"),require("@tanstack/react-table"),require("react-virtual"),require("@mantine/dates"),require("rc-select"),require("rc-tree-select"),require("react-grid-layout"),require("mobx-state-tree"),require("performant-array-to-tree"),require("jszip"),require("file-saver"),require("dom-to-image-more"),require("react-router-dom"),require("reactflow")):typeof define=="function"&&define.amd?define(["exports","react","@mantine/core","@mantine/modals","ahooks","mobx","mobx-react-lite","crypto-js","dayjs","lodash","numbro","d3-array","mathjs","@faker-js/faker","axios","eventemitter2","chroma-js","echarts-gl","echarts/core","echarts/components","echarts/renderers","echarts-for-react/lib/core","react-hook-form","tabler-icons-react","echarts/charts","@tabler/icons-react","@mantine/hooks","@mantine/notifications","@mantine/tiptap","@tiptap/extension-color","@tiptap/extension-highlight","@tiptap/extension-placeholder","@tiptap/extension-subscript","@tiptap/extension-superscript","@tiptap/extension-text-align","@tiptap/extension-text-style","@tiptap/extension-table","@tiptap/extension-table-cell","@tiptap/extension-table-header","@tiptap/extension-table-row","@tiptap/extension-underline","@tiptap/react","@tiptap/starter-kit","prosemirror-keymap","prosemirror-commands","prosemirror-schema-list","@monaco-editor/react","popmotion","d3-regression","@mantine/prism","@tanstack/react-table","react-virtual","@mantine/dates","rc-select","rc-tree-select","react-grid-layout","mobx-state-tree","performant-array-to-tree","jszip","file-saver","dom-to-image-more","react-router-dom","reactflow"],b):(I=typeof globalThis<"u"?globalThis:I||self,b(I.dashboard={},I.react,I["@mantine/core"],I["@mantine/modals"],I.ahooks,I.mobx,I["mobx-react-lite"],I.CryptoJS,I.dayjs,I._,I.numbro,I["d3-array"],I.mathjs,I["@faker-js/faker"],I.axios,I.eventemitter2,I["chroma-js"],I["echarts-gl"],I["echarts/core"],I["echarts/components"],I["echarts/renderers"],I["echarts-for-react/lib/core"],I["react-hook-form"],I["tabler-icons-react"],I["echarts/charts"],I["@tabler/icons-react"],I["@mantine/hooks"],I["@mantine/notifications"],I["@mantine/tiptap"],I["@tiptap/extension-color"],I["@tiptap/extension-highlight"],I["@tiptap/extension-placeholder"],I["@tiptap/extension-subscript"],I["@tiptap/extension-superscript"],I["@tiptap/extension-text-align"],I["@tiptap/extension-text-style"],I["@tiptap/extension-table"],I["@tiptap/extension-table-cell"],I["@tiptap/extension-table-header"],I["@tiptap/extension-table-row"],I["@tiptap/extension-underline"],I["@tiptap/react"],I["@tiptap/starter-kit"],I["prosemirror-keymap"],I["prosemirror-commands"],I["prosemirror-schema-list"],I["@monaco-editor/react"],I.popmotion,I["d3-regression"],I["@mantine/prism"],I["@tanstack/react-table"],I["react-virtual"],I["@mantine/dates"],I["rc-select"],I["rc-tree-select"],I["react-grid-layout"],I["mobx-state-tree"],I["performant-array-to-tree"],I.jszip,I["file-saver"],I["dom-to-image-more"],I["react-router-dom"],I.reactflow))})(this,function(I,b,s,We,K,te,k,Ia,Y,x,Z,Xt,Du,Iu,mt,Ma,ct,RI,Mu,q,Pe,Be,v,T,he,$,Ie,vn,J,Aa,za,Ea,$a,La,Oa,Pa,Ba,Va,Na,qa,Fa,Ga,Wa,YI,Me,pr,Ae,_t,Au,kt,tt,zu,Eu,ja,Ra,xn,y,$u,Lu,hr,Ya,Ou,$e){"use strict";var WI=Object.defineProperty;var jI=(I,b,s)=>b in I?WI(I,b,{enumerable:!0,configurable:!0,writable:!0,value:s}):I[b]=s;var N=(I,b,s)=>(jI(I,typeof b!="symbol"?b+"":b,s),s);function wn(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const Pu=wn(Xt),Cn=wn(Du),ie=wn(Mu),yt=wn(Au);var re=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Jt={},Bu={get exports(){return Jt},set exports(e){Jt=e}},Zt={};/**
2
2
  * @license React
3
3
  * react-jsx-runtime.production.min.js
4
4
  *
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * This source code is licensed under the MIT license found in the
8
8
  * LICENSE file in the root directory of this source tree.
9
- */var Qa;function Vu(){if(Qa)return Jt;Qa=1;var e=y,t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,a=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,o={key:!0,ref:!0,__self:!0,__source:!0};function l(u,c,d){var f,h={},g=null,m=null;d!==void 0&&(g=""+d),c.key!==void 0&&(g=""+c.key),c.ref!==void 0&&(m=c.ref);for(f in c)r.call(c,f)&&!o.hasOwnProperty(f)&&(h[f]=c[f]);if(u&&u.defaultProps)for(f in c=u.defaultProps,c)h[f]===void 0&&(h[f]=c[f]);return{$$typeof:t,type:u,key:g,ref:m,props:h,_owner:a.current}}return Jt.Fragment=n,Jt.jsx=l,Jt.jsxs=l,Jt}var Zt={};/**
9
+ */var Qa;function Vu(){if(Qa)return Zt;Qa=1;var e=b,t=Symbol.for("react.element"),n=Symbol.for("react.fragment"),r=Object.prototype.hasOwnProperty,a=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,o={key:!0,ref:!0,__self:!0,__source:!0};function l(u,c,d){var f,h={},g=null,m=null;d!==void 0&&(g=""+d),c.key!==void 0&&(g=""+c.key),c.ref!==void 0&&(m=c.ref);for(f in c)r.call(c,f)&&!o.hasOwnProperty(f)&&(h[f]=c[f]);if(u&&u.defaultProps)for(f in c=u.defaultProps,c)h[f]===void 0&&(h[f]=c[f]);return{$$typeof:t,type:u,key:g,ref:m,props:h,_owner:a.current}}return Zt.Fragment=n,Zt.jsx=l,Zt.jsxs=l,Zt}var Ht={};/**
10
10
  * @license React
11
11
  * react-jsx-runtime.development.js
12
12
  *
@@ -14,17 +14,17 @@
14
14
  *
15
15
  * This source code is licensed under the MIT license found in the
16
16
  * LICENSE file in the root directory of this source tree.
17
- */var Ua;function Nu(){return Ua||(Ua=1,process.env.NODE_ENV!=="production"&&function(){var e=y,t=Symbol.for("react.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),l=Symbol.for("react.provider"),u=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),d=Symbol.for("react.suspense"),f=Symbol.for("react.suspense_list"),h=Symbol.for("react.memo"),g=Symbol.for("react.lazy"),m=Symbol.for("react.offscreen"),C=Symbol.iterator,w="@@iterator";function _(S){if(S===null||typeof S!="object")return null;var E=C&&S[C]||S[w];return typeof E=="function"?E:null}var D=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function M(S){{for(var E=arguments.length,V=new Array(E>1?E-1:0),U=1;U<E;U++)V[U-1]=arguments[U];P("error",S,V)}}function P(S,E,V){{var U=D.ReactDebugCurrentFrame,se=U.getStackAddendum();se!==""&&(E+="%s",V=V.concat([se]));var de=V.map(function(ne){return String(ne)});de.unshift("Warning: "+E),Function.prototype.apply.call(console[S],console,de)}}var G=!1,L=!1,z=!1,A=!1,F=!1,X;X=Symbol.for("react.module.reference");function Q(S){return!!(typeof S=="string"||typeof S=="function"||S===r||S===o||F||S===a||S===d||S===f||A||S===m||G||L||z||typeof S=="object"&&S!==null&&(S.$$typeof===g||S.$$typeof===h||S.$$typeof===l||S.$$typeof===u||S.$$typeof===c||S.$$typeof===X||S.getModuleId!==void 0))}function H(S,E,V){var U=S.displayName;if(U)return U;var se=E.displayName||E.name||"";return se!==""?V+"("+se+")":V}function oe(S){return S.displayName||"Context"}function ue(S){if(S==null)return null;if(typeof S.tag=="number"&&M("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof S=="function")return S.displayName||S.name||null;if(typeof S=="string")return S;switch(S){case r:return"Fragment";case n:return"Portal";case o:return"Profiler";case a:return"StrictMode";case d:return"Suspense";case f:return"SuspenseList"}if(typeof S=="object")switch(S.$$typeof){case u:var E=S;return oe(E)+".Consumer";case l:var V=S;return oe(V._context)+".Provider";case c:return H(S,S.render,"ForwardRef");case h:var U=S.displayName||null;return U!==null?U:ue(S.type)||"Memo";case g:{var se=S,de=se._payload,ne=se._init;try{return ue(ne(de))}catch{return null}}}return null}var be=Object.assign,Ee=0,ge,ve,me,Oe,He,$t,ur;function cr(){}cr.__reactDisabledLog=!0;function wa(){{if(Ee===0){ge=console.log,ve=console.info,me=console.warn,Oe=console.error,He=console.group,$t=console.groupCollapsed,ur=console.groupEnd;var S={configurable:!0,enumerable:!0,value:cr,writable:!0};Object.defineProperties(console,{info:S,log:S,warn:S,error:S,group:S,groupCollapsed:S,groupEnd:S})}Ee++}}function Ca(){{if(Ee--,Ee===0){var S={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:be({},S,{value:ge}),info:be({},S,{value:ve}),warn:be({},S,{value:me}),error:be({},S,{value:Oe}),group:be({},S,{value:He}),groupCollapsed:be({},S,{value:$t}),groupEnd:be({},S,{value:ur})})}Ee<0&&M("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var fn=D.ReactCurrentDispatcher,jt;function wt(S,E,V){{if(jt===void 0)try{throw Error()}catch(se){var U=se.stack.trim().match(/\n( *(at )?)/);jt=U&&U[1]||""}return`
18
- `+jt+S}}var Lt=!1,Ct;{var Rt=typeof WeakMap=="function"?WeakMap:Map;Ct=new Rt}function Yt(S,E){if(!S||Lt)return"";{var V=Ct.get(S);if(V!==void 0)return V}var U;Lt=!0;var se=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var de;de=fn.current,fn.current=null,wa();try{if(E){var ne=function(){throw Error()};if(Object.defineProperty(ne.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ne,[])}catch(gt){U=gt}Reflect.construct(S,[],ne)}else{try{ne.call()}catch(gt){U=gt}S.call(ne.prototype)}}else{try{throw Error()}catch(gt){U=gt}S()}}catch(gt){if(gt&&U&&typeof gt.stack=="string"){for(var ee=gt.stack.split(`
17
+ */var Ua;function Nu(){return Ua||(Ua=1,process.env.NODE_ENV!=="production"&&function(){var e=b,t=Symbol.for("react.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),o=Symbol.for("react.profiler"),l=Symbol.for("react.provider"),u=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),d=Symbol.for("react.suspense"),f=Symbol.for("react.suspense_list"),h=Symbol.for("react.memo"),g=Symbol.for("react.lazy"),m=Symbol.for("react.offscreen"),C=Symbol.iterator,w="@@iterator";function _(S){if(S===null||typeof S!="object")return null;var E=C&&S[C]||S[w];return typeof E=="function"?E:null}var D=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function M(S){{for(var E=arguments.length,V=new Array(E>1?E-1:0),U=1;U<E;U++)V[U-1]=arguments[U];P("error",S,V)}}function P(S,E,V){{var U=D.ReactDebugCurrentFrame,se=U.getStackAddendum();se!==""&&(E+="%s",V=V.concat([se]));var pe=V.map(function(ne){return String(ne)});pe.unshift("Warning: "+E),Function.prototype.apply.call(console[S],console,pe)}}var G=!1,L=!1,z=!1,A=!1,F=!1,X;X=Symbol.for("react.module.reference");function Q(S){return!!(typeof S=="string"||typeof S=="function"||S===r||S===o||F||S===a||S===d||S===f||A||S===m||G||L||z||typeof S=="object"&&S!==null&&(S.$$typeof===g||S.$$typeof===h||S.$$typeof===l||S.$$typeof===u||S.$$typeof===c||S.$$typeof===X||S.getModuleId!==void 0))}function H(S,E,V){var U=S.displayName;if(U)return U;var se=E.displayName||E.name||"";return se!==""?V+"("+se+")":V}function oe(S){return S.displayName||"Context"}function ue(S){if(S==null)return null;if(typeof S.tag=="number"&&M("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof S=="function")return S.displayName||S.name||null;if(typeof S=="string")return S;switch(S){case r:return"Fragment";case n:return"Portal";case o:return"Profiler";case a:return"StrictMode";case d:return"Suspense";case f:return"SuspenseList"}if(typeof S=="object")switch(S.$$typeof){case u:var E=S;return oe(E)+".Consumer";case l:var V=S;return oe(V._context)+".Provider";case c:return H(S,S.render,"ForwardRef");case h:var U=S.displayName||null;return U!==null?U:ue(S.type)||"Memo";case g:{var se=S,pe=se._payload,ne=se._init;try{return ue(ne(pe))}catch{return null}}}return null}var be=Object.assign,Ee=0,ge,ve,me,Oe,He,$t,ur;function cr(){}cr.__reactDisabledLog=!0;function wa(){{if(Ee===0){ge=console.log,ve=console.info,me=console.warn,Oe=console.error,He=console.group,$t=console.groupCollapsed,ur=console.groupEnd;var S={configurable:!0,enumerable:!0,value:cr,writable:!0};Object.defineProperties(console,{info:S,log:S,warn:S,error:S,group:S,groupCollapsed:S,groupEnd:S})}Ee++}}function Ca(){{if(Ee--,Ee===0){var S={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:be({},S,{value:ge}),info:be({},S,{value:ve}),warn:be({},S,{value:me}),error:be({},S,{value:Oe}),group:be({},S,{value:He}),groupCollapsed:be({},S,{value:$t}),groupEnd:be({},S,{value:ur})})}Ee<0&&M("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var fn=D.ReactCurrentDispatcher,Rt;function wt(S,E,V){{if(Rt===void 0)try{throw Error()}catch(se){var U=se.stack.trim().match(/\n( *(at )?)/);Rt=U&&U[1]||""}return`
18
+ `+Rt+S}}var Lt=!1,Ct;{var Yt=typeof WeakMap=="function"?WeakMap:Map;Ct=new Yt}function Qt(S,E){if(!S||Lt)return"";{var V=Ct.get(S);if(V!==void 0)return V}var U;Lt=!0;var se=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var pe;pe=fn.current,fn.current=null,wa();try{if(E){var ne=function(){throw Error()};if(Object.defineProperty(ne.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ne,[])}catch(gt){U=gt}Reflect.construct(S,[],ne)}else{try{ne.call()}catch(gt){U=gt}S.call(ne.prototype)}}else{try{throw Error()}catch(gt){U=gt}S()}}catch(gt){if(gt&&U&&typeof gt.stack=="string"){for(var ee=gt.stack.split(`
19
19
  `),Ne=U.stack.split(`
20
20
  `),xe=ee.length-1,ke=Ne.length-1;xe>=1&&ke>=0&&ee[xe]!==Ne[ke];)ke--;for(;xe>=1&&ke>=0;xe--,ke--)if(ee[xe]!==Ne[ke]){if(xe!==1||ke!==1)do if(xe--,ke--,ke<0||ee[xe]!==Ne[ke]){var et=`
21
- `+ee[xe].replace(" at new "," at ");return S.displayName&&et.includes("<anonymous>")&&(et=et.replace("<anonymous>",S.displayName)),typeof S=="function"&&Ct.set(S,et),et}while(xe>=1&&ke>=0);break}}}finally{Lt=!1,fn.current=de,Ca(),Error.prepareStackTrace=se}var Ut=S?S.displayName||S.name:"",Tu=Ut?wt(Ut):"";return typeof S=="function"&&Ct.set(S,Tu),Tu}function gn(S,E,V){return Yt(S,!1)}function mn(S){var E=S.prototype;return!!(E&&E.isReactComponent)}function St(S,E,V){if(S==null)return"";if(typeof S=="function")return Yt(S,mn(S));if(typeof S=="string")return wt(S);switch(S){case d:return wt("Suspense");case f:return wt("SuspenseList")}if(typeof S=="object")switch(S.$$typeof){case c:return gn(S.render);case h:return St(S.type,E,V);case g:{var U=S,se=U._payload,de=U._init;try{return St(de(se),E,V)}catch{}}}return""}var yn=Object.prototype.hasOwnProperty,fu={},gu=D.ReactDebugCurrentFrame;function dr(S){if(S){var E=S._owner,V=St(S.type,S._source,E?E.type:null);gu.setExtraStackFrame(V)}else gu.setExtraStackFrame(null)}function xI(S,E,V,U,se){{var de=Function.call.bind(yn);for(var ne in S)if(de(S,ne)){var ee=void 0;try{if(typeof S[ne]!="function"){var Ne=Error((U||"React class")+": "+V+" type `"+ne+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof S[ne]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw Ne.name="Invariant Violation",Ne}ee=S[ne](E,ne,U,V,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(xe){ee=xe}ee&&!(ee instanceof Error)&&(dr(se),M("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",U||"React class",V,ne,typeof ee),dr(null)),ee instanceof Error&&!(ee.message in fu)&&(fu[ee.message]=!0,dr(se),M("Failed %s type: %s",V,ee.message),dr(null))}}}var wI=Array.isArray;function Sa(S){return wI(S)}function CI(S){{var E=typeof Symbol=="function"&&Symbol.toStringTag,V=E&&S[Symbol.toStringTag]||S.constructor.name||"Object";return V}}function SI(S){try{return mu(S),!1}catch{return!0}}function mu(S){return""+S}function yu(S){if(SI(S))return M("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",CI(S)),mu(S)}var bn=D.ReactCurrentOwner,_I={key:!0,ref:!0,__self:!0,__source:!0},bu,vu,_a;_a={};function kI(S){if(yn.call(S,"ref")){var E=Object.getOwnPropertyDescriptor(S,"ref").get;if(E&&E.isReactWarning)return!1}return S.ref!==void 0}function TI(S){if(yn.call(S,"key")){var E=Object.getOwnPropertyDescriptor(S,"key").get;if(E&&E.isReactWarning)return!1}return S.key!==void 0}function DI(S,E){if(typeof S.ref=="string"&&bn.current&&E&&bn.current.stateNode!==E){var V=ue(bn.current.type);_a[V]||(M('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref',ue(bn.current.type),S.ref),_a[V]=!0)}}function II(S,E){{var V=function(){bu||(bu=!0,M("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",E))};V.isReactWarning=!0,Object.defineProperty(S,"key",{get:V,configurable:!0})}}function MI(S,E){{var V=function(){vu||(vu=!0,M("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",E))};V.isReactWarning=!0,Object.defineProperty(S,"ref",{get:V,configurable:!0})}}var AI=function(S,E,V,U,se,de,ne){var ee={$$typeof:t,type:S,key:E,ref:V,props:ne,_owner:de};return ee._store={},Object.defineProperty(ee._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(ee,"_self",{configurable:!1,enumerable:!1,writable:!1,value:U}),Object.defineProperty(ee,"_source",{configurable:!1,enumerable:!1,writable:!1,value:se}),Object.freeze&&(Object.freeze(ee.props),Object.freeze(ee)),ee};function zI(S,E,V,U,se){{var de,ne={},ee=null,Ne=null;V!==void 0&&(yu(V),ee=""+V),TI(E)&&(yu(E.key),ee=""+E.key),kI(E)&&(Ne=E.ref,DI(E,se));for(de in E)yn.call(E,de)&&!_I.hasOwnProperty(de)&&(ne[de]=E[de]);if(S&&S.defaultProps){var xe=S.defaultProps;for(de in xe)ne[de]===void 0&&(ne[de]=xe[de])}if(ee||Ne){var ke=typeof S=="function"?S.displayName||S.name||"Unknown":S;ee&&II(ne,ke),Ne&&MI(ne,ke)}return AI(S,ee,Ne,se,U,bn.current,ne)}}var ka=D.ReactCurrentOwner,xu=D.ReactDebugCurrentFrame;function Qt(S){if(S){var E=S._owner,V=St(S.type,S._source,E?E.type:null);xu.setExtraStackFrame(V)}else xu.setExtraStackFrame(null)}var Ta;Ta=!1;function Da(S){return typeof S=="object"&&S!==null&&S.$$typeof===t}function wu(){{if(ka.current){var S=ue(ka.current.type);if(S)return`
21
+ `+ee[xe].replace(" at new "," at ");return S.displayName&&et.includes("<anonymous>")&&(et=et.replace("<anonymous>",S.displayName)),typeof S=="function"&&Ct.set(S,et),et}while(xe>=1&&ke>=0);break}}}finally{Lt=!1,fn.current=pe,Ca(),Error.prepareStackTrace=se}var Kt=S?S.displayName||S.name:"",Tu=Kt?wt(Kt):"";return typeof S=="function"&&Ct.set(S,Tu),Tu}function gn(S,E,V){return Qt(S,!1)}function mn(S){var E=S.prototype;return!!(E&&E.isReactComponent)}function St(S,E,V){if(S==null)return"";if(typeof S=="function")return Qt(S,mn(S));if(typeof S=="string")return wt(S);switch(S){case d:return wt("Suspense");case f:return wt("SuspenseList")}if(typeof S=="object")switch(S.$$typeof){case c:return gn(S.render);case h:return St(S.type,E,V);case g:{var U=S,se=U._payload,pe=U._init;try{return St(pe(se),E,V)}catch{}}}return""}var yn=Object.prototype.hasOwnProperty,fu={},gu=D.ReactDebugCurrentFrame;function dr(S){if(S){var E=S._owner,V=St(S.type,S._source,E?E.type:null);gu.setExtraStackFrame(V)}else gu.setExtraStackFrame(null)}function SI(S,E,V,U,se){{var pe=Function.call.bind(yn);for(var ne in S)if(pe(S,ne)){var ee=void 0;try{if(typeof S[ne]!="function"){var Ne=Error((U||"React class")+": "+V+" type `"+ne+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof S[ne]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw Ne.name="Invariant Violation",Ne}ee=S[ne](E,ne,U,V,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(xe){ee=xe}ee&&!(ee instanceof Error)&&(dr(se),M("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",U||"React class",V,ne,typeof ee),dr(null)),ee instanceof Error&&!(ee.message in fu)&&(fu[ee.message]=!0,dr(se),M("Failed %s type: %s",V,ee.message),dr(null))}}}var _I=Array.isArray;function Sa(S){return _I(S)}function kI(S){{var E=typeof Symbol=="function"&&Symbol.toStringTag,V=E&&S[Symbol.toStringTag]||S.constructor.name||"Object";return V}}function TI(S){try{return mu(S),!1}catch{return!0}}function mu(S){return""+S}function yu(S){if(TI(S))return M("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",kI(S)),mu(S)}var bn=D.ReactCurrentOwner,DI={key:!0,ref:!0,__self:!0,__source:!0},bu,vu,_a;_a={};function II(S){if(yn.call(S,"ref")){var E=Object.getOwnPropertyDescriptor(S,"ref").get;if(E&&E.isReactWarning)return!1}return S.ref!==void 0}function MI(S){if(yn.call(S,"key")){var E=Object.getOwnPropertyDescriptor(S,"key").get;if(E&&E.isReactWarning)return!1}return S.key!==void 0}function AI(S,E){if(typeof S.ref=="string"&&bn.current&&E&&bn.current.stateNode!==E){var V=ue(bn.current.type);_a[V]||(M('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref',ue(bn.current.type),S.ref),_a[V]=!0)}}function zI(S,E){{var V=function(){bu||(bu=!0,M("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",E))};V.isReactWarning=!0,Object.defineProperty(S,"key",{get:V,configurable:!0})}}function EI(S,E){{var V=function(){vu||(vu=!0,M("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",E))};V.isReactWarning=!0,Object.defineProperty(S,"ref",{get:V,configurable:!0})}}var $I=function(S,E,V,U,se,pe,ne){var ee={$$typeof:t,type:S,key:E,ref:V,props:ne,_owner:pe};return ee._store={},Object.defineProperty(ee._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(ee,"_self",{configurable:!1,enumerable:!1,writable:!1,value:U}),Object.defineProperty(ee,"_source",{configurable:!1,enumerable:!1,writable:!1,value:se}),Object.freeze&&(Object.freeze(ee.props),Object.freeze(ee)),ee};function LI(S,E,V,U,se){{var pe,ne={},ee=null,Ne=null;V!==void 0&&(yu(V),ee=""+V),MI(E)&&(yu(E.key),ee=""+E.key),II(E)&&(Ne=E.ref,AI(E,se));for(pe in E)yn.call(E,pe)&&!DI.hasOwnProperty(pe)&&(ne[pe]=E[pe]);if(S&&S.defaultProps){var xe=S.defaultProps;for(pe in xe)ne[pe]===void 0&&(ne[pe]=xe[pe])}if(ee||Ne){var ke=typeof S=="function"?S.displayName||S.name||"Unknown":S;ee&&zI(ne,ke),Ne&&EI(ne,ke)}return $I(S,ee,Ne,se,U,bn.current,ne)}}var ka=D.ReactCurrentOwner,xu=D.ReactDebugCurrentFrame;function Ut(S){if(S){var E=S._owner,V=St(S.type,S._source,E?E.type:null);xu.setExtraStackFrame(V)}else xu.setExtraStackFrame(null)}var Ta;Ta=!1;function Da(S){return typeof S=="object"&&S!==null&&S.$$typeof===t}function wu(){{if(ka.current){var S=ue(ka.current.type);if(S)return`
22
22
 
23
- Check the render method of \``+S+"`."}return""}}function EI(S){{if(S!==void 0){var E=S.fileName.replace(/^.*[\\\/]/,""),V=S.lineNumber;return`
23
+ Check the render method of \``+S+"`."}return""}}function OI(S){{if(S!==void 0){var E=S.fileName.replace(/^.*[\\\/]/,""),V=S.lineNumber;return`
24
24
 
25
- Check your code at `+E+":"+V+"."}return""}}var Cu={};function $I(S){{var E=wu();if(!E){var V=typeof S=="string"?S:S.displayName||S.name;V&&(E=`
25
+ Check your code at `+E+":"+V+"."}return""}}var Cu={};function PI(S){{var E=wu();if(!E){var V=typeof S=="string"?S:S.displayName||S.name;V&&(E=`
26
26
 
27
- Check the top-level render call using <`+V+">.")}return E}}function Su(S,E){{if(!S._store||S._store.validated||S.key!=null)return;S._store.validated=!0;var V=$I(E);if(Cu[V])return;Cu[V]=!0;var U="";S&&S._owner&&S._owner!==ka.current&&(U=" It was passed a child from "+ue(S._owner.type)+"."),Qt(S),M('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',V,U),Qt(null)}}function _u(S,E){{if(typeof S!="object")return;if(Sa(S))for(var V=0;V<S.length;V++){var U=S[V];Da(U)&&Su(U,E)}else if(Da(S))S._store&&(S._store.validated=!0);else if(S){var se=_(S);if(typeof se=="function"&&se!==S.entries)for(var de=se.call(S),ne;!(ne=de.next()).done;)Da(ne.value)&&Su(ne.value,E)}}}function LI(S){{var E=S.type;if(E==null||typeof E=="string")return;var V;if(typeof E=="function")V=E.propTypes;else if(typeof E=="object"&&(E.$$typeof===c||E.$$typeof===h))V=E.propTypes;else return;if(V){var U=ue(E);xI(V,S.props,"prop",U,S)}else if(E.PropTypes!==void 0&&!Ta){Ta=!0;var se=ue(E);M("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",se||"Unknown")}typeof E.getDefaultProps=="function"&&!E.getDefaultProps.isReactClassApproved&&M("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function OI(S){{for(var E=Object.keys(S.props),V=0;V<E.length;V++){var U=E[V];if(U!=="children"&&U!=="key"){Qt(S),M("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",U),Qt(null);break}}S.ref!==null&&(Qt(S),M("Invalid attribute `ref` supplied to `React.Fragment`."),Qt(null))}}function ku(S,E,V,U,se,de){{var ne=Q(S);if(!ne){var ee="";(S===void 0||typeof S=="object"&&S!==null&&Object.keys(S).length===0)&&(ee+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var Ne=EI(se);Ne?ee+=Ne:ee+=wu();var xe;S===null?xe="null":Sa(S)?xe="array":S!==void 0&&S.$$typeof===t?(xe="<"+(ue(S.type)||"Unknown")+" />",ee=" Did you accidentally export a JSX literal instead of a component?"):xe=typeof S,M("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",xe,ee)}var ke=zI(S,E,V,se,de);if(ke==null)return ke;if(ne){var et=E.children;if(et!==void 0)if(U)if(Sa(et)){for(var Ut=0;Ut<et.length;Ut++)_u(et[Ut],S);Object.freeze&&Object.freeze(et)}else M("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else _u(et,S)}return S===r?OI(ke):LI(ke),ke}}function PI(S,E,V){return ku(S,E,V,!0)}function BI(S,E,V){return ku(S,E,V,!1)}var VI=BI,NI=PI;Zt.Fragment=r,Zt.jsx=VI,Zt.jsxs=NI}()),Zt}(function(e){process.env.NODE_ENV==="production"?e.exports=Vu():e.exports=Nu()})(Bu);const B=Xt.Fragment,i=Xt.jsx,p=Xt.jsxs,Tt={CryptoJS:Ia,d3Array:Pu,dayjs:Y,lodash:x,numbro:Z,mathjs:Cn,faker:Iu.faker},qu=[{name:"CryptoJS",url:"https://github.com/brix/crypto-js",version:"4.1.1"},{name:"d3Array",url:"https://github.com/d3/d3-array",version:"3.2.0"},{name:"dayjs",url:"https://day.js.org/",version:"1.11.6"},{name:"lodash",url:"https://lodash.com/docs/4.17.15",version:"4.17.21"},{name:"mathjs",url:"https://mathjs.org/",version:"11.7.0"},{name:"numbro",url:"https://numbrojs.com/",version:"2.3.6"},{name:"faker",url:"https://fakerjs.dev/",version:"7.6.0"}],Fu=e=>`
27
+ Check the top-level render call using <`+V+">.")}return E}}function Su(S,E){{if(!S._store||S._store.validated||S.key!=null)return;S._store.validated=!0;var V=PI(E);if(Cu[V])return;Cu[V]=!0;var U="";S&&S._owner&&S._owner!==ka.current&&(U=" It was passed a child from "+ue(S._owner.type)+"."),Ut(S),M('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',V,U),Ut(null)}}function _u(S,E){{if(typeof S!="object")return;if(Sa(S))for(var V=0;V<S.length;V++){var U=S[V];Da(U)&&Su(U,E)}else if(Da(S))S._store&&(S._store.validated=!0);else if(S){var se=_(S);if(typeof se=="function"&&se!==S.entries)for(var pe=se.call(S),ne;!(ne=pe.next()).done;)Da(ne.value)&&Su(ne.value,E)}}}function BI(S){{var E=S.type;if(E==null||typeof E=="string")return;var V;if(typeof E=="function")V=E.propTypes;else if(typeof E=="object"&&(E.$$typeof===c||E.$$typeof===h))V=E.propTypes;else return;if(V){var U=ue(E);SI(V,S.props,"prop",U,S)}else if(E.PropTypes!==void 0&&!Ta){Ta=!0;var se=ue(E);M("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",se||"Unknown")}typeof E.getDefaultProps=="function"&&!E.getDefaultProps.isReactClassApproved&&M("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function VI(S){{for(var E=Object.keys(S.props),V=0;V<E.length;V++){var U=E[V];if(U!=="children"&&U!=="key"){Ut(S),M("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",U),Ut(null);break}}S.ref!==null&&(Ut(S),M("Invalid attribute `ref` supplied to `React.Fragment`."),Ut(null))}}function ku(S,E,V,U,se,pe){{var ne=Q(S);if(!ne){var ee="";(S===void 0||typeof S=="object"&&S!==null&&Object.keys(S).length===0)&&(ee+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var Ne=OI(se);Ne?ee+=Ne:ee+=wu();var xe;S===null?xe="null":Sa(S)?xe="array":S!==void 0&&S.$$typeof===t?(xe="<"+(ue(S.type)||"Unknown")+" />",ee=" Did you accidentally export a JSX literal instead of a component?"):xe=typeof S,M("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",xe,ee)}var ke=LI(S,E,V,se,pe);if(ke==null)return ke;if(ne){var et=E.children;if(et!==void 0)if(U)if(Sa(et)){for(var Kt=0;Kt<et.length;Kt++)_u(et[Kt],S);Object.freeze&&Object.freeze(et)}else M("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else _u(et,S)}return S===r?VI(ke):BI(ke),ke}}function NI(S,E,V){return ku(S,E,V,!0)}function qI(S,E,V){return ku(S,E,V,!1)}var FI=qI,GI=NI;Ht.Fragment=r,Ht.jsx=FI,Ht.jsxs=GI}()),Ht}(function(e){process.env.NODE_ENV==="production"?e.exports=Vu():e.exports=Nu()})(Bu);const B=Jt.Fragment,i=Jt.jsx,p=Jt.jsxs,Tt={CryptoJS:Ia,d3Array:Pu,dayjs:Y,lodash:x,numbro:Z,mathjs:Cn,faker:Iu.faker},qu=[{name:"CryptoJS",url:"https://github.com/brix/crypto-js",version:"4.1.1"},{name:"d3Array",url:"https://github.com/d3/d3-array",version:"3.2.0"},{name:"dayjs",url:"https://day.js.org/",version:"1.11.6"},{name:"lodash",url:"https://lodash.com/docs/4.17.15",version:"4.17.21"},{name:"mathjs",url:"https://mathjs.org/",version:"11.7.0"},{name:"numbro",url:"https://numbrojs.com/",version:"2.3.6"},{name:"faker",url:"https://fakerjs.dev/",version:"7.6.0"}],Fu=e=>`
28
28
  <tr>
29
29
  <td><code>${e.name}</code></td>
30
30
  <td>
@@ -51,14 +51,14 @@ Check the top-level render call using <`+V+">.")}return E}}function Su(S,E){{if(
51
51
  ${qu.map(Fu).join("")}
52
52
  </tbody>
53
53
  </table>
54
- `;function fr(e,t){const n=Object.keys(t),r=Object.values(t);try{return new Function(...n,`return \`${e}\`;`)(...r)}catch(a){throw n.length===0&&e.includes("$")?new Error("[formatSQL] insufficient payload"):a}}function gr(e,t){try{return fr(e,t)}catch(n){return console.error(n),n.message}}function Wu({sql:e,pre_process:t}){if(!t.trim())return e;try{return new Function(`return ${t}`)()({sql:e},Tt)}catch(n){return console.error(n),e}}function ju(e,t){if(!e.trim())return t;try{return new Function(`return ${e}`)()(t,Tt)}catch(n){return console.error(n),t}}function Ru(e){e=e||{};const t=Object.keys(e).sort(),n=[];for(let r=0;r<t.length;r++){const a=t[r];if(a!="authentication"&&e[a])n.push(t[r]+"="+(typeof e[a]=="object"?JSON.stringify(e[a]):e[a]));else{const o=Object.keys(e[a]).sort();for(let l=0;l<o.length;l++){const u=o[l];u!="sign"&&e[a][u]&&n.push(o[l]+"="+(typeof e[a][u]=="object"?JSON.stringify(e[a][u]):e[a][u]))}}}return n.sort().join("&")}function Yu(e,t){let n=Ru(e);return n+="&key="+t,Ia.MD5(n).toString().toUpperCase()}const qe={baseURL:"http://localhost:31200",app_id:"",app_secret:"",getAuthentication(e){if(!this.app_id||!this.app_secret)return;const t=new Date().getTime().toString();return{app_id:this.app_id,nonce_str:t,sign:Yu({app_id:this.app_id,nonce_str:t,...e},this.app_secret)}},getRequest(e,t){return(n,r,a={})=>{const o=window.localStorage.getItem("token"),l={"X-Requested-With":"XMLHttpRequest","Content-Type":a.string?"application/x-www-form-urlencoded":"application/json",authorization:o?`bearer ${o}`:"",...a.headers},u={baseURL:this.baseURL,method:e,url:n,params:e==="GET"?r:a.params,headers:l,signal:t};return["POST","PUT"].includes(e)&&(u.data=a.string?JSON.stringify(r):r,u.data.authentication=this.getAuthentication(u.data)),mt(u).then(c=>c.data).catch(c=>Promise.reject(c))}},makeQueryENV:null,query(e){return async(t,n={})=>{var r;return t.env||(t.env=((r=this.makeQueryENV)==null?void 0:r.call(this))??{error:"failed to run makeQueryENV"}),this.getRequest("POST",e)("/query",t,n)}}};function Ka(e){qe.baseURL!==e.apiBaseURL&&(qe.baseURL=e.apiBaseURL),e.app_id&&(qe.app_id=e.app_id),e.app_secret&&(qe.app_secret=e.app_secret),e.makeQueryENV&&(qe.makeQueryENV=e.makeQueryENV)}async function Qu({query:e,name:t,payload:n},r){if(!e.sql)return[];const{type:a,key:o,sql:l,pre_process:u,post_process:c}=e,d=fr(l,n),f=Wu({sql:d,pre_process:u});let h=await qe.query(r)({type:a,key:o,query:f},{params:{name:t}});return h=ju(c,h),h}async function Uu({type:e,key:t,configString:n,name:r},a){return await qe.query(a)({type:e,key:t,query:n},{params:{name:r}})}async function mr(){try{return(await qe.getRequest("POST")("/datasource/list",{filter:{},sort:[{field:"create_time",order:"ASC"}],pagination:{page:1,pagesize:100}})).data}catch(e){return console.error(e),[]}}async function Xa(){try{return(await qe.getRequest("POST")("/sql_snippet/list",{filter:{},sort:[{field:"id",order:"ASC"}],pagination:{page:1,pagesize:1e3}})).data}catch(e){return console.error(e),[]}}class Ja{constructor(t){N(this,"rootRef");this.rootRef=te.observable({current:t})}async deleteItem(t){te.runInAction(()=>{x.unset(this.rootRef.current,[t])})}getItem(t){const n=this.getValueFromRoot(t);return Promise.resolve(n)}getValueFromRoot(t){return t===null?te.toJS(this.rootRef.current):x.get(this.rootRef.current,[t])}setItem(t,n){if(t===null)if(x.isObject(n))te.runInAction(()=>{this.rootRef.current=n});else throw new Error("Cannot set root value to non-object");else te.runInAction(()=>{x.set(this.rootRef.current,[t],n)});return Promise.resolve(this.getItem(t))}watchItem(t,n,r){return te.reaction(()=>this.getValueFromRoot(t),(a,o)=>{n(a,o)},{requiresObservable:!0,fireImmediately:x.get(r,"fireImmediately",!1)})}}class Ku{constructor(){N(this,"channels",new Map);N(this,"globalChannel",new Ma)}getChannel(t){const n=this.channels.get(t);if(n)return n;const r=new Ma;return this.channels.set(t,r),r}}class Xu{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 r={id:t.id,name:t.viz.type,type:t.viz.type,messageChannels:new Ku,instanceData:new Ja(t.viz.conf)};return this.instances.set(t.id,r),r}}function Za(e,t,n,r){return{vizManager:n,locale:"zh",msgChannels:e.messageChannels,instanceData:e.instanceData,pluginData:new Ja({}),colorPalette:{getColor(){return()=>""}},data:t,variables:r}}const Ju=e=>{const{panel:t,vizManager:n,data:r,variables:a}=e,o=n.resolveComponent(t.viz.type),l=n.getOrCreateInstance(t),u={...Za(l,r,n,a),viewport:{width:t.layout.w,height:t.layout.h}},c=o.viewRender;return i(c,{context:u,instance:l,...x.omit(e,["panel","vizManager","data"])})},Zu=e=>{const{vizManager:t,panel:n,panelInfoEditor:r,data:a,variables:o}=e,l=t.resolveComponent(n.viz.type),u=t.getOrCreateInstance(n),c={...Za(u,a,t,o),panelInfoEditor:r},d=l.configRender;return i(d,{context:c,instance:u,...x.omit(e,["panel","vizManager","data","panelInfoEditor"])})},Ha=(e,t)=>{const n=ct.bezier(e),r=ct.bezier(t);return function(a){return a<50?n(a*2/100).hex():r((a-50)*2/100).hex()}},Sn=e=>{const t=ct.bezier(e);return function(n){return t(n/100).hex()}},Hu={type:"interpolation",displayName:"Red / Green",getColor:Ha(["darkred","deeppink","lightyellow"],["lightyellow","lightgreen","teal"]),name:"red-green",category:"diverging"},ec={type:"interpolation",displayName:"Yellow / Blue",getColor:Ha(["#8f531d","#ffd347","#e3efe3"],["#eefaee","#4ecbbf","#003f94"]),name:"yellow-blue",category:"diverging"},tc={type:"interpolation",displayName:"Red",getColor:Sn(["#fff7f1","darkred"]),name:"red",category:"sequential"},nc={type:"interpolation",displayName:"Green",getColor:Sn(["#f0ffed","darkgreen"]),name:"green",category:"sequential"},rc={type:"interpolation",displayName:"Blue",getColor:Sn(["#f9fcff","#48b3e9","darkblue"]),name:"blue",category:"sequential"},ic={type:"interpolation",displayName:"Orange",getColor:Sn(["#fff7f1","darkorange","#b60000"]),name:"orange",category:"sequential"};class ac{constructor(t){N(this,"symbol");this.symbol=Symbol(t)}}function dt(e){return new ac(e)}class yr{constructor(){N(this,"parent");N(this,"factoryRegistry",new Map);N(this,"instanceRegistry",new Map)}createScoped(){const t=new yr;return t.parent=this,t}getRequired(t){return this.get(t)}get(t){if(this.instanceRegistry.has(t.symbol))return this.instanceRegistry.get(t.symbol);const n=this.factoryRegistry.get(t.symbol);if(n){const r=n(this);return this.instanceRegistry.set(t.symbol,r),r}if(this.parent)return this.parent.get(t)}provideFactory(t,n){return this.factoryRegistry.has(t.symbol)?console.warn(`Token ${t.symbol.toString()} is already registered`):this.factoryRegistry.set(t.symbol,n),this}provideValue(t,n){return this.factoryRegistry.has(t.symbol)?console.warn(`Token ${t.symbol.toString()} is already registered`):this.factoryRegistry.set(t.symbol,()=>n),this}dispose(){this.instanceRegistry.forEach(t=>{const n=x.get(t,"dispose");x.isFunction(n)&&n.bind(t)()}),this.instanceRegistry.clear(),this.factoryRegistry.clear()}}const es="10.32.0",sc=Object.freeze(Object.defineProperty({__proto__:null,version:es},Symbol.toStringTag,{value:"Module"}));class oc{constructor(t){N(this,"staticColors",new Map);N(this,"interpolations",new Map);t.installedPlugins.forEach(n=>{n.manifest.color.forEach(r=>{this.register(r)})})}getStaticColors(){return Array.from(this.staticColors.values())}register(t){const n=this.encodeColor(t);t.type==="single"?(this.staticColors.has(n)&&console.warn(`the color '${t.name}' has been registered under '${t.category}', previous registered value will be overridden`),this.staticColors.set(n,t)):t.type==="interpolation"&&(this.interpolations.has(n)&&console.warn(`the interpolation '${t.name}' has been registered under '${t.category}', previous registered value will be overridden`,`the interpolation '${t.name}' has been registered under '${t.category}', previous registered value will be overridden`),this.interpolations.set(n,t))}decodeStaticColor(t){return this.staticColors.get(t)}encodeColor(t){return`\${${t.category}}.{${t.name}}`}decodeInterpolation(t){return this.interpolations.get(t)}getColorInterpolations(){return Array.from(this.interpolations.values())}}class lc{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 uc{constructor(){N(this,"migrations",[])}version(t,n){return this.migrations.push({version:t,handler:n}),this}run(t,n,r){var l;if(t.from===t.to)return n;if(t.from>t.to)throw new Error(`Can not downgrade from version '${t.from}' to (${t.to})`);const a=this.migrations.filter(u=>u.version>t.from&&u.version<=t.to),o=x.orderBy(a,"version","asc");if(((l=x.last(o))==null?void 0:l.version)!==t.to)throw new Error(`Migration to version ${t.to} not found`);return o.reduce((u,c)=>c.handler(u,r),n)}}class ye extends uc{constructor(){super(),this.configVersions()}version(t,n){return super.version(t,(r,a)=>({version:t,...n(r,a)}))}async migrate({configData:t,panelModel:n}){const r=await t.getItem(null),a=x.get(r,"version",0),o=this.run({from:a,to:this.VERSION},r,{panelModel:n});await t.setItem(null,o)}async needMigration({configData:t}){const n=await t.getItem(null);return x.get(n,"version",0)<this.VERSION}}const R=(e,t)=>{const[n,{setFalse:r}]=K.useBoolean(!0),[a,o]=y.useState();y.useEffect(()=>(e.getItem(t).then(u=>{o(u),r()}),e.watchItem(t,u=>{o(u)})));const l=y.useCallback(async u=>{await e.setItem(t,u),o(u)},[e,t]);return{loading:n,value:a,set:l}},br={x_axis_data_key:"",y_axis_data_key:"",z_axis_data_key:"",xAxis3D:{type:"value",name:"X Axis Name"},yAxis3D:{type:"value",name:"Y Axis Name"},zAxis3D:{type:"value",name:"Z Axis Name"}};function O(e){const[t,n]=e.split(".");return{queryID:t,columnKey:n}}function cc(e){return e.includes(".")?O(e):{queryID:"",columnKey:e}}function pt(e,t){var a;const{queryID:n,columnKey:r}=O(t);return n?r?((a=e[n])==null?void 0:a.map(o=>o[r]))??[]:e[n]:[]}function Ht(e,t){const{queryID:n}=O(t);return n?e[n]:[]}function dc(e){return Object.values(e)[0]}function _n(e,t){const{queryID:n,columnKey:r}=O(t);return e[r]}ie.use([q.GridComponent,q.VisualMapComponent,q.LegendComponent,q.TooltipComponent,Pe.CanvasRenderer]);function pc({context:e}){const{value:t}=R(e.instanceData,"config"),n=e.data,{width:r,height:a}=e.viewport,{x_axis_data_key:o,y_axis_data_key:l,z_axis_data_key:u,xAxis3D:c,yAxis3D:d,zAxis3D:f}=x.defaults({},t,br),h=y.useMemo(()=>Ht(n,o),[n,o]),{x:g,y:m,z:C}=y.useMemo(()=>({x:O(o),y:O(l),z:O(u)}),[o,l,u]),{min:w,max:_}=y.useMemo(()=>{const M=x.minBy(h,G=>G[C.columnKey]),P=x.maxBy(h,G=>G[C.columnKey]);return{min:x.get(M,C.columnKey),max:x.get(P,C.columnKey)}},[h,C]),D={tooltip:{},backgroundColor:"#fff",visualMap:{show:!0,dimension:2,min:w,max:_,inRange:{color:["#313695","#4575b4","#74add1","#abd9e9","#e0f3f8","#ffffbf","#fee090","#fdae61","#f46d43","#d73027","#a50026"]}},xAxis3D:c,yAxis3D:d,zAxis3D:f,grid3D:{viewControl:{projection:"orthographic",autoRotate:!1},light:{main:{shadow:!0,quality:"ultra",intensity:1.5}}},series:[{type:"bar3D",wireframe:{},data:h.map(M=>[M[g.columnKey],M[m.columnKey],M[C.columnKey]])}]};return t?i(Be,{echarts:ie,option:D,style:{width:r,height:a},notMerge:!0,theme:"merico-light"}):null}const ts=y.createContext(null),vr=ts.Provider;function xr(){const e=y.useContext(ts);if(!e)throw new Error("Please use DashboardModelContextProvider");return e}const pe=()=>xr(),wr=()=>xr(),ns=y.createContext(null),Cr=ns.Provider;function rs(){const e=y.useContext(ns);if(!e)throw new Error("Please use ContentModelContextProvider");return e}const le=()=>rs(),we=()=>rs(),hc={inEditMode:!1},kn=y.createContext(hc),is=y.createContext({panel:null,data:{},loading:!1,errors:[],downloadPanelScreenshot:()=>{}}),Sr=is.Provider;function as(){const e=y.useContext(is);if(!e.panel)throw new Error("Please use PanelContextProvider");return e}const bt=()=>as(),nt=()=>as(),fc={fullScreenPanelID:"",setFullScreenPanelID:x.noop},_r=y.createContext(fc);function ss(){const e=y.useContext(_r);if(!e)throw new Error("Please use FullScreenPanelContext.Provider");return e}const W=k.observer(y.forwardRef(({label:e,required:t,value:n,onChange:r,clearable:a=!1,sx:o,...l},u)=>{const{panel:c}=nt(),d=y.useMemo(()=>{const f=[...c.dataFieldOptions];return a&&f.unshift({label:"unset",value:"",group:""}),f},[c.dataFieldOptions]);return i(s.Select,{ref:u,label:e,data:d,value:n,onChange:r,required:t,sx:o,maxDropdownHeight:500,...l})}));function gc({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=x.defaults({},t,br),{control:a,handleSubmit:o,reset:l}=v.useForm({defaultValues:r});return y.useEffect(()=>{l(r)},[t]),t?i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:o(n),children:[i(s.Text,{children:"X Axis"}),p(s.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[i(v.Controller,{name:"x_axis_data_key",control:a,render:({field:u})=>i(W,{label:"Data Field",required:!0,...u})}),i(v.Controller,{name:"xAxis3D.name",control:a,render:({field:u})=>i(s.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...u})})]}),i(s.Text,{mt:"lg",children:"Y Axis"}),p(s.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[i(v.Controller,{name:"y_axis_data_key",control:a,render:({field:u})=>i(W,{label:"Data Field",required:!0,...u})}),i(v.Controller,{name:"yAxis3D.name",control:a,render:({field:u})=>i(s.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...u})})]}),i(s.Text,{mt:"lg",children:"Z Axis"}),p(s.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[i(v.Controller,{name:"z_axis_data_key",control:a,render:({field:u})=>i(W,{label:"Data Field",required:!0,...u})}),i(v.Controller,{name:"zAxis3D.name",control:a,render:({field:u})=>i(s.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...u})})]}),i(s.Group,{position:"center",mt:"xl",grow:!0,sx:{width:"60%"},mx:"auto",children:p(s.Button,{color:"blue",type:"submit",children:[i(T.DeviceFloppy,{size:20}),i(s.Text,{ml:"md",children:"Save"})]})})]})}):null}function mc(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=c=>c&&`${n}.${c}`,{x_axis_data_key:a,y_axis_data_key:o,z_axis_data_key:l,...u}=e;return{...u,x_axis_data_key:r(a),y_axis_data_key:r(o),z_axis_data_key:r(l)}}catch(n){throw console.error("[Migration failed]",n),n}}class yc extends ye{constructor(){super(...arguments);N(this,"VERSION",2)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,(n,r)=>{const{config:a}=n;return{...n,version:2,config:mc(a,r)}})}}const bc={displayName:"Bar Chart (3D)",displayGroup:"ECharts-based charts",migrator:new yc,name:"bar-3d",viewRender:pc,configRender:gc,createConfig(){return{version:2,config:x.cloneDeep(br)}}};class Fe extends y.Component{constructor(t){super(t),this.state={error:null}}componentDidCatch(t){this.setState({error:t})}render(){var t;if(this.state.error){const n=()=>{this.setState({error:null})};return p(s.Box,{children:[i(s.Text,{size:"xs",children:(t=this.state.error)==null?void 0:t.message}),i(s.Button,{variant:"subtle",size:"xs",mx:"auto",compact:!0,sx:{display:"block"},onClick:n,children:"Retry"})]})}return this.props.children}}const ze={mantissa:0,output:"number",trimMantissa:!1,average:!1};function vc({value:e,onChange:t},n){const r=u=>{t({...e,output:u})},a=u=>{const c=u===0?!1:e.trimMantissa;t({...e,mantissa:u,trimMantissa:c})},o=u=>{t({...e,trimMantissa:u.currentTarget.checked})},l=u=>{t({...e,average:u.currentTarget.checked})};return p(s.Stack,{ref:n,children:[p(s.Group,{grow:!0,children:[i(s.Select,{label:"Format",data:[{label:"1234",value:"number"},{label:"99%",value:"percent"}],value:e.output,onChange:r,sx:{flexGrow:1}}),i(s.Switch,{label:p(s.Stack,{spacing:0,children:[i(s.Text,{children:"Average"}),i(s.Text,{size:12,color:"gray",children:"like 1.234k, 1.234m"})]}),checked:e.average,onChange:l,disabled:e.output!=="number",sx:{flexGrow:1},styles:{root:{alignSelf:"flex-end"},body:{alignItems:"center"},label:{display:"block"}}})]}),p(s.Group,{grow:!0,children:[i(s.NumberInput,{label:"Mantissa",defaultValue:0,min:0,step:1,max:4,value:e.mantissa,onChange:a}),i(s.Switch,{label:"Trim mantissa",checked:e.trimMantissa,onChange:o,disabled:e.mantissa===0,styles:{root:{alignSelf:"flex-end"},body:{alignItems:"center"}}})]}),p(s.Stack,{spacing:0,children:[i(s.Text,{weight:"bold",children:"Preview"}),i(Fe,{children:p(s.Group,{position:"apart",children:[p(s.Text,{size:12,color:"gray",children:["123456789 ",i(T.ArrowRight,{size:9})," ",Z(123456789).format(e)]}),p(s.Text,{size:12,color:"gray",children:["1234 ",i(T.ArrowRight,{size:9})," ",Z(1234).format(e)]}),p(s.Text,{size:12,color:"gray",children:["0.1234 ",i(T.ArrowRight,{size:9})," ",Z(.1234).format(e)]})]})})]})]})}const We=y.forwardRef(vc),Ue={enabled:!1,func_content:["function label(value, index) {"," // your code goes here"," // return value","}"].join(`
55
- `)},os={id:"builtin:echarts:click-echart:series",displayName:"Click Chart Series",nameRender:wc,configRender:xc,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 xc(e){return i(B,{})}function wc(e){return i(s.Text,{children:"Click chart's series"})}const Cc=[{label:"Truncate",value:"truncate"},{label:"Break Line",value:"break"},{label:"Break Word",value:"breakAll"}],Tn=y.forwardRef(({sectionTitle:e,value:t,onChange:n},r)=>{const a=o=>l=>{const u=x.cloneDeep(t);x.set(u,o,l),n(u)};return p(s.Stack,{spacing:0,children:[e&&i(s.Divider,{mb:-5,mt:5,variant:"dotted",label:e,labelPosition:"right",labelProps:{color:"dimmed"}}),p(s.Group,{grow:!0,noWrap:!0,children:[i(s.NumberInput,{label:"Max Width",hideControls:!0,value:t.width,onChange:a("width")}),i(s.Select,{label:"Overflow",data:Cc,value:t.overflow,onChange:a("overflow")}),i(s.TextInput,{label:"Ellipsis",value:t.ellipsis,disabled:!0})]})]})}),at=y.forwardRef(({value:e,onChange:t},n)=>{const r=o=>{t({...e,on_axis:o})},a=o=>{t({...e,in_tooltip:o})};return p(s.Stack,{ref:n,spacing:0,children:[i(Tn,{sectionTitle:"Overflow on Axis",value:e.on_axis,onChange:r}),i(Tn,{sectionTitle:"Overflow in Tooltip",value:e.in_tooltip,onChange:a})]})}),je={on_axis:{width:80,overflow:"truncate",ellipsis:"..."},in_tooltip:{width:200,overflow:"break",ellipsis:"..."}};function st({overflow:e,width:t}){const n={truncate:"initial",break:"break-all",breakAll:"break-word"}[e],r=e==="truncate"?"nowrap":"initial",a={truncate:"ellipsis",break:"clip",breakAll:"clip"}[e];return`
54
+ `;function fr(e,t){const n=Object.keys(t),r=Object.values(t);try{return new Function(...n,`return \`${e}\`;`)(...r)}catch(a){throw n.length===0&&e.includes("$")?new Error("[formatSQL] insufficient payload"):a}}function gr(e,t){try{return fr(e,t)}catch(n){return console.error(n),n.message}}function Wu({sql:e,pre_process:t}){if(!t.trim())return e;try{return new Function(`return ${t}`)()({sql:e},Tt)}catch(n){return console.error(n),e}}function ju(e,t){if(!e.trim())return t;try{return new Function(`return ${e}`)()(t,Tt)}catch(n){return console.error(n),t}}function Ru(e){e=e||{};const t=Object.keys(e).sort(),n=[];for(let r=0;r<t.length;r++){const a=t[r];if(a!="authentication"&&e[a])n.push(t[r]+"="+(typeof e[a]=="object"?JSON.stringify(e[a]):e[a]));else{const o=Object.keys(e[a]).sort();for(let l=0;l<o.length;l++){const u=o[l];u!="sign"&&e[a][u]&&n.push(o[l]+"="+(typeof e[a][u]=="object"?JSON.stringify(e[a][u]):e[a][u]))}}}return n.sort().join("&")}function Yu(e,t){let n=Ru(e);return n+="&key="+t,Ia.MD5(n).toString().toUpperCase()}const qe={baseURL:"http://localhost:31200",app_id:"",app_secret:"",getAuthentication(e){if(!this.app_id||!this.app_secret)return;const t=new Date().getTime().toString();return{app_id:this.app_id,nonce_str:t,sign:Yu({app_id:this.app_id,nonce_str:t,...e},this.app_secret)}},getRequest(e,t){return(n,r,a={})=>{const o=window.localStorage.getItem("token"),l={"X-Requested-With":"XMLHttpRequest","Content-Type":a.string?"application/x-www-form-urlencoded":"application/json",authorization:o?`bearer ${o}`:"",...a.headers},u={baseURL:this.baseURL,method:e,url:n,params:e==="GET"?r:a.params,headers:l,signal:t};return["POST","PUT"].includes(e)&&(u.data=a.string?JSON.stringify(r):r,u.data.authentication=this.getAuthentication(u.data)),mt(u).then(c=>c.data).catch(c=>Promise.reject(c))}},makeQueryENV:null,query(e){return async(t,n={})=>{var r;return t.env||(t.env=((r=this.makeQueryENV)==null?void 0:r.call(this))??{error:"failed to run makeQueryENV"}),this.getRequest("POST",e)("/query",t,n)}}};function Ka(e){qe.baseURL!==e.apiBaseURL&&(qe.baseURL=e.apiBaseURL),e.app_id&&(qe.app_id=e.app_id),e.app_secret&&(qe.app_secret=e.app_secret),e.makeQueryENV&&(qe.makeQueryENV=e.makeQueryENV)}async function Qu({query:e,name:t,payload:n},r){if(!e.sql)return[];const{type:a,key:o,sql:l,pre_process:u,post_process:c}=e,d=fr(l,n),f=Wu({sql:d,pre_process:u});let h=await qe.query(r)({type:a,key:o,query:f},{params:{name:t}});return h=ju(c,h),h}async function Uu({type:e,key:t,configString:n,name:r},a){return await qe.query(a)({type:e,key:t,query:n},{params:{name:r}})}async function mr(){try{return(await qe.getRequest("POST")("/datasource/list",{filter:{},sort:[{field:"create_time",order:"ASC"}],pagination:{page:1,pagesize:100}})).data}catch(e){return console.error(e),[]}}async function Xa(){try{return(await qe.getRequest("POST")("/sql_snippet/list",{filter:{},sort:[{field:"id",order:"ASC"}],pagination:{page:1,pagesize:1e3}})).data}catch(e){return console.error(e),[]}}class Ja{constructor(t){N(this,"rootRef");this.rootRef=te.observable({current:t})}async deleteItem(t){te.runInAction(()=>{x.unset(this.rootRef.current,[t])})}getItem(t){const n=this.getValueFromRoot(t);return Promise.resolve(n)}getValueFromRoot(t){return t===null?te.toJS(this.rootRef.current):x.get(this.rootRef.current,[t])}setItem(t,n){if(t===null)if(x.isObject(n))te.runInAction(()=>{this.rootRef.current=n});else throw new Error("Cannot set root value to non-object");else te.runInAction(()=>{x.set(this.rootRef.current,[t],n)});return Promise.resolve(this.getItem(t))}watchItem(t,n,r){return te.reaction(()=>this.getValueFromRoot(t),(a,o)=>{n(a,o)},{requiresObservable:!0,fireImmediately:x.get(r,"fireImmediately",!1)})}}class Ku{constructor(){N(this,"channels",new Map);N(this,"globalChannel",new Ma)}getChannel(t){const n=this.channels.get(t);if(n)return n;const r=new Ma;return this.channels.set(t,r),r}}class Xu{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 r={id:t.id,name:t.viz.type,type:t.viz.type,messageChannels:new Ku,instanceData:new Ja(t.viz.conf)};return this.instances.set(t.id,r),r}}function Za(e,t,n,r){return{vizManager:n,locale:"zh",msgChannels:e.messageChannels,instanceData:e.instanceData,pluginData:new Ja({}),colorPalette:{getColor(){return()=>""}},data:t,variables:r}}const Ju=e=>{const{panel:t,vizManager:n,data:r,variables:a}=e,o=n.resolveComponent(t.viz.type),l=n.getOrCreateInstance(t),u={...Za(l,r,n,a),viewport:{width:t.layout.w,height:t.layout.h}},c=o.viewRender;return i(c,{context:u,instance:l,...x.omit(e,["panel","vizManager","data"])})},Zu=e=>{const{vizManager:t,panel:n,panelInfoEditor:r,data:a,variables:o}=e,l=t.resolveComponent(n.viz.type),u=t.getOrCreateInstance(n),c={...Za(u,a,t,o),panelInfoEditor:r},d=l.configRender;return i(d,{context:c,instance:u,...x.omit(e,["panel","vizManager","data","panelInfoEditor"])})},Ha=(e,t)=>{const n=ct.bezier(e),r=ct.bezier(t);return function(a){return a<50?n(a*2/100).hex():r((a-50)*2/100).hex()}},Sn=e=>{const t=ct.bezier(e);return function(n){return t(n/100).hex()}},Hu={type:"interpolation",displayName:"Red / Green",getColor:Ha(["darkred","deeppink","lightyellow"],["lightyellow","lightgreen","teal"]),name:"red-green",category:"diverging"},ec={type:"interpolation",displayName:"Yellow / Blue",getColor:Ha(["#8f531d","#ffd347","#e3efe3"],["#eefaee","#4ecbbf","#003f94"]),name:"yellow-blue",category:"diverging"},tc={type:"interpolation",displayName:"Red",getColor:Sn(["#fff7f1","darkred"]),name:"red",category:"sequential"},nc={type:"interpolation",displayName:"Green",getColor:Sn(["#f0ffed","darkgreen"]),name:"green",category:"sequential"},rc={type:"interpolation",displayName:"Blue",getColor:Sn(["#f9fcff","#48b3e9","darkblue"]),name:"blue",category:"sequential"},ic={type:"interpolation",displayName:"Orange",getColor:Sn(["#fff7f1","darkorange","#b60000"]),name:"orange",category:"sequential"};class ac{constructor(t){N(this,"symbol");this.symbol=Symbol(t)}}function dt(e){return new ac(e)}class yr{constructor(){N(this,"parent");N(this,"factoryRegistry",new Map);N(this,"instanceRegistry",new Map)}createScoped(){const t=new yr;return t.parent=this,t}getRequired(t){return this.get(t)}get(t){if(this.instanceRegistry.has(t.symbol))return this.instanceRegistry.get(t.symbol);const n=this.factoryRegistry.get(t.symbol);if(n){const r=n(this);return this.instanceRegistry.set(t.symbol,r),r}if(this.parent)return this.parent.get(t)}provideFactory(t,n){return this.factoryRegistry.has(t.symbol)?console.warn(`Token ${t.symbol.toString()} is already registered`):this.factoryRegistry.set(t.symbol,n),this}provideValue(t,n){return this.factoryRegistry.has(t.symbol)?console.warn(`Token ${t.symbol.toString()} is already registered`):this.factoryRegistry.set(t.symbol,()=>n),this}dispose(){this.instanceRegistry.forEach(t=>{const n=x.get(t,"dispose");x.isFunction(n)&&n.bind(t)()}),this.instanceRegistry.clear(),this.factoryRegistry.clear()}}const es="10.33.0",sc=Object.freeze(Object.defineProperty({__proto__:null,version:es},Symbol.toStringTag,{value:"Module"}));class oc{constructor(t){N(this,"staticColors",new Map);N(this,"interpolations",new Map);t.installedPlugins.forEach(n=>{n.manifest.color.forEach(r=>{this.register(r)})})}getStaticColors(){return Array.from(this.staticColors.values())}register(t){const n=this.encodeColor(t);t.type==="single"?(this.staticColors.has(n)&&console.warn(`the color '${t.name}' has been registered under '${t.category}', previous registered value will be overridden`),this.staticColors.set(n,t)):t.type==="interpolation"&&(this.interpolations.has(n)&&console.warn(`the interpolation '${t.name}' has been registered under '${t.category}', previous registered value will be overridden`,`the interpolation '${t.name}' has been registered under '${t.category}', previous registered value will be overridden`),this.interpolations.set(n,t))}decodeStaticColor(t){return this.staticColors.get(t)}encodeColor(t){return`\${${t.category}}.{${t.name}}`}decodeInterpolation(t){return this.interpolations.get(t)}getColorInterpolations(){return Array.from(this.interpolations.values())}}class lc{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 uc{constructor(){N(this,"migrations",[])}version(t,n){return this.migrations.push({version:t,handler:n}),this}run(t,n,r){var l;if(t.from===t.to)return n;if(t.from>t.to)throw new Error(`Can not downgrade from version '${t.from}' to (${t.to})`);const a=this.migrations.filter(u=>u.version>t.from&&u.version<=t.to),o=x.orderBy(a,"version","asc");if(((l=x.last(o))==null?void 0:l.version)!==t.to)throw new Error(`Migration to version ${t.to} not found`);return o.reduce((u,c)=>c.handler(u,r),n)}}class ye extends uc{constructor(){super(),this.configVersions()}version(t,n){return super.version(t,(r,a)=>({version:t,...n(r,a)}))}async migrate({configData:t,panelModel:n}){const r=await t.getItem(null),a=x.get(r,"version",0),o=this.run({from:a,to:this.VERSION},r,{panelModel:n});await t.setItem(null,o)}async needMigration({configData:t}){const n=await t.getItem(null);return x.get(n,"version",0)<this.VERSION}}const R=(e,t)=>{const[n,{setFalse:r}]=K.useBoolean(!0),[a,o]=b.useState();b.useEffect(()=>(e.getItem(t).then(u=>{o(u),r()}),e.watchItem(t,u=>{o(u)})));const l=b.useCallback(async u=>{await e.setItem(t,u),o(u)},[e,t]);return{loading:n,value:a,set:l}},br={x_axis_data_key:"",y_axis_data_key:"",z_axis_data_key:"",xAxis3D:{type:"value",name:"X Axis Name"},yAxis3D:{type:"value",name:"Y Axis Name"},zAxis3D:{type:"value",name:"Z Axis Name"}};function O(e){const[t,n]=e.split(".");return{queryID:t,columnKey:n}}function cc(e){return e.includes(".")?O(e):{queryID:"",columnKey:e}}function pt(e,t){var a;const{queryID:n,columnKey:r}=O(t);return n?r?((a=e[n])==null?void 0:a.map(o=>o[r]))??[]:e[n]:[]}function en(e,t){const{queryID:n}=O(t);return n?e[n]:[]}function dc(e){return Object.values(e)[0]}function _n(e,t){const{queryID:n,columnKey:r}=O(t);return e[r]}ie.use([q.GridComponent,q.VisualMapComponent,q.LegendComponent,q.TooltipComponent,Pe.CanvasRenderer]);function pc({context:e}){const{value:t}=R(e.instanceData,"config"),n=e.data,{width:r,height:a}=e.viewport,{x_axis_data_key:o,y_axis_data_key:l,z_axis_data_key:u,xAxis3D:c,yAxis3D:d,zAxis3D:f}=x.defaults({},t,br),h=b.useMemo(()=>en(n,o),[n,o]),{x:g,y:m,z:C}=b.useMemo(()=>({x:O(o),y:O(l),z:O(u)}),[o,l,u]),{min:w,max:_}=b.useMemo(()=>{const M=x.minBy(h,G=>G[C.columnKey]),P=x.maxBy(h,G=>G[C.columnKey]);return{min:x.get(M,C.columnKey),max:x.get(P,C.columnKey)}},[h,C]),D={tooltip:{},backgroundColor:"#fff",visualMap:{show:!0,dimension:2,min:w,max:_,inRange:{color:["#313695","#4575b4","#74add1","#abd9e9","#e0f3f8","#ffffbf","#fee090","#fdae61","#f46d43","#d73027","#a50026"]}},xAxis3D:c,yAxis3D:d,zAxis3D:f,grid3D:{viewControl:{projection:"orthographic",autoRotate:!1},light:{main:{shadow:!0,quality:"ultra",intensity:1.5}}},series:[{type:"bar3D",wireframe:{},data:h.map(M=>[M[g.columnKey],M[m.columnKey],M[C.columnKey]])}]};return t?i(Be,{echarts:ie,option:D,style:{width:r,height:a},notMerge:!0,theme:"merico-light"}):null}const ts=b.createContext(null),vr=ts.Provider;function xr(){const e=b.useContext(ts);if(!e)throw new Error("Please use DashboardModelContextProvider");return e}const ce=()=>xr(),wr=()=>xr(),ns=b.createContext(null),Cr=ns.Provider;function rs(){const e=b.useContext(ns);if(!e)throw new Error("Please use ContentModelContextProvider");return e}const le=()=>rs(),we=()=>rs(),hc={inEditMode:!1},kn=b.createContext(hc),is=b.createContext({panel:null,data:{},loading:!1,errors:[],downloadPanelScreenshot:()=>{}}),Sr=is.Provider;function as(){const e=b.useContext(is);if(!e.panel)throw new Error("Please use PanelContextProvider");return e}const bt=()=>as(),nt=()=>as(),fc={fullScreenPanelID:"",setFullScreenPanelID:x.noop},_r=b.createContext(fc);function ss(){const e=b.useContext(_r);if(!e)throw new Error("Please use FullScreenPanelContext.Provider");return e}const W=k.observer(b.forwardRef(({label:e,required:t,value:n,onChange:r,clearable:a=!1,sx:o,...l},u)=>{const{panel:c}=nt(),d=b.useMemo(()=>{const f=[...c.dataFieldOptions];return a&&f.unshift({label:"unset",value:"",group:""}),f},[c.dataFieldOptions]);return i(s.Select,{ref:u,label:e,data:d,value:n,onChange:r,required:t,sx:o,maxDropdownHeight:500,...l})}));function gc({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=x.defaults({},t,br),{control:a,handleSubmit:o,reset:l}=v.useForm({defaultValues:r});return b.useEffect(()=>{l(r)},[t]),t?i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:o(n),children:[i(s.Text,{children:"X Axis"}),p(s.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[i(v.Controller,{name:"x_axis_data_key",control:a,render:({field:u})=>i(W,{label:"Data Field",required:!0,...u})}),i(v.Controller,{name:"xAxis3D.name",control:a,render:({field:u})=>i(s.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...u})})]}),i(s.Text,{mt:"lg",children:"Y Axis"}),p(s.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[i(v.Controller,{name:"y_axis_data_key",control:a,render:({field:u})=>i(W,{label:"Data Field",required:!0,...u})}),i(v.Controller,{name:"yAxis3D.name",control:a,render:({field:u})=>i(s.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...u})})]}),i(s.Text,{mt:"lg",children:"Z Axis"}),p(s.Group,{position:"apart",grow:!0,p:"md",sx:{position:"relative",border:"1px solid #eee"},children:[i(v.Controller,{name:"z_axis_data_key",control:a,render:({field:u})=>i(W,{label:"Data Field",required:!0,...u})}),i(v.Controller,{name:"zAxis3D.name",control:a,render:({field:u})=>i(s.TextInput,{sx:{flexGrow:1},size:"md",label:"Name",...u})})]}),i(s.Group,{position:"center",mt:"xl",grow:!0,sx:{width:"60%"},mx:"auto",children:p(s.Button,{color:"blue",type:"submit",children:[i(T.DeviceFloppy,{size:20}),i(s.Text,{ml:"md",children:"Save"})]})})]})}):null}function mc(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=c=>c&&`${n}.${c}`,{x_axis_data_key:a,y_axis_data_key:o,z_axis_data_key:l,...u}=e;return{...u,x_axis_data_key:r(a),y_axis_data_key:r(o),z_axis_data_key:r(l)}}catch(n){throw console.error("[Migration failed]",n),n}}class yc extends ye{constructor(){super(...arguments);N(this,"VERSION",2)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,(n,r)=>{const{config:a}=n;return{...n,version:2,config:mc(a,r)}})}}const bc={displayName:"Bar Chart (3D)",displayGroup:"ECharts-based charts",migrator:new yc,name:"bar-3d",viewRender:pc,configRender:gc,createConfig(){return{version:2,config:x.cloneDeep(br)}}};class Fe extends b.Component{constructor(t){super(t),this.state={error:null}}componentDidCatch(t){this.setState({error:t})}render(){var t;if(this.state.error){const n=()=>{this.setState({error:null})};return p(s.Box,{children:[i(s.Text,{size:"xs",children:(t=this.state.error)==null?void 0:t.message}),i(s.Button,{variant:"subtle",size:"xs",mx:"auto",compact:!0,sx:{display:"block"},onClick:n,children:"Retry"})]})}return this.props.children}}const ze={mantissa:0,output:"number",trimMantissa:!1,average:!1};function vc({value:e,onChange:t},n){const r=u=>{t({...e,output:u})},a=u=>{const c=u===0?!1:e.trimMantissa;t({...e,mantissa:u,trimMantissa:c})},o=u=>{t({...e,trimMantissa:u.currentTarget.checked})},l=u=>{t({...e,average:u.currentTarget.checked})};return p(s.Stack,{ref:n,children:[p(s.Group,{grow:!0,children:[i(s.Select,{label:"Format",data:[{label:"1234",value:"number"},{label:"99%",value:"percent"}],value:e.output,onChange:r,sx:{flexGrow:1}}),i(s.Switch,{label:p(s.Stack,{spacing:0,children:[i(s.Text,{children:"Average"}),i(s.Text,{size:12,color:"gray",children:"like 1.234k, 1.234m"})]}),checked:e.average,onChange:l,disabled:e.output!=="number",sx:{flexGrow:1},styles:{root:{alignSelf:"flex-end"},body:{alignItems:"center"},label:{display:"block"}}})]}),p(s.Group,{grow:!0,children:[i(s.NumberInput,{label:"Mantissa",defaultValue:0,min:0,step:1,max:4,value:e.mantissa,onChange:a}),i(s.Switch,{label:"Trim mantissa",checked:e.trimMantissa,onChange:o,disabled:e.mantissa===0,styles:{root:{alignSelf:"flex-end"},body:{alignItems:"center"}}})]}),p(s.Stack,{spacing:0,children:[i(s.Text,{weight:"bold",children:"Preview"}),i(Fe,{children:p(s.Group,{position:"apart",children:[p(s.Text,{size:12,color:"gray",children:["123456789 ",i(T.ArrowRight,{size:9})," ",Z(123456789).format(e)]}),p(s.Text,{size:12,color:"gray",children:["1234 ",i(T.ArrowRight,{size:9})," ",Z(1234).format(e)]}),p(s.Text,{size:12,color:"gray",children:["0.1234 ",i(T.ArrowRight,{size:9})," ",Z(.1234).format(e)]})]})})]})]})}const je=b.forwardRef(vc),Ue={enabled:!1,func_content:["function label(value, index) {"," // your code goes here"," // return value","}"].join(`
55
+ `)},os={id:"builtin:echarts:click-echart:series",displayName:"Click Chart Series",nameRender:wc,configRender:xc,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 xc(e){return i(B,{})}function wc(e){return i(s.Text,{children:"Click chart's series"})}const Cc=[{label:"Truncate",value:"truncate"},{label:"Break Line",value:"break"},{label:"Break Word",value:"breakAll"}],Tn=b.forwardRef(({sectionTitle:e,value:t,onChange:n},r)=>{const a=o=>l=>{const u=x.cloneDeep(t);x.set(u,o,l),n(u)};return p(s.Stack,{spacing:0,children:[e&&i(s.Divider,{mb:-5,mt:5,variant:"dotted",label:e,labelPosition:"right",labelProps:{color:"dimmed"}}),p(s.Group,{grow:!0,noWrap:!0,children:[i(s.NumberInput,{label:"Max Width",hideControls:!0,value:t.width,onChange:a("width")}),i(s.Select,{label:"Overflow",data:Cc,value:t.overflow,onChange:a("overflow")}),i(s.TextInput,{label:"Ellipsis",value:t.ellipsis,disabled:!0})]})]})}),at=b.forwardRef(({value:e,onChange:t},n)=>{const r=o=>{t({...e,on_axis:o})},a=o=>{t({...e,in_tooltip:o})};return p(s.Stack,{ref:n,spacing:0,children:[i(Tn,{sectionTitle:"Overflow on Axis",value:e.on_axis,onChange:r}),i(Tn,{sectionTitle:"Overflow in Tooltip",value:e.in_tooltip,onChange:a})]})}),Re={on_axis:{width:80,overflow:"truncate",ellipsis:"..."},in_tooltip:{width:200,overflow:"break",ellipsis:"..."}};function st({overflow:e,width:t}){const n={truncate:"initial",break:"break-all",breakAll:"break-word"}[e],r=e==="truncate"?"nowrap":"initial",a={truncate:"ellipsis",break:"clip",breakAll:"clip"}[e];return`
56
56
  max-width: ${t}px;
57
57
  word-break: ${n};
58
58
  white-space: ${r};
59
59
  overflow: hidden;
60
60
  text-overflow: ${a};
61
- `}function rt(e){return{width:e.width,overflow:e.overflow,ellipsis:e.ellipsis}}const kr={x_axis:{name:"X Axis",data_key:"",axisLabel:{rotate:0,formatter:{...Ue},overflow:je}},y_axis:{name:"Y Axis",data_key:"value",label_formatter:ze},tooltip:{metrics:[]},color:"#228be6",reference_lines:[],legend:{show:!0,top:"10",right:"0",left:"auto",bottom:"auto",orient:"vertical",type:"scroll"}};function Dt(e,t){return y.useMemo(()=>{const{queryID:n,columnKey:r}=O(t);return x.keyBy(e[n],r)},[e,t])}const Ke=(e,t)=>{const[n,r]=y.useState([]);return y.useEffect(()=>e.watchTriggerSnapshotList(a=>r(a.filter(o=>o.schemaRef===t))),[]),n};class Ot{constructor(t,n){this.root=t,this.path=n}async deleteItem(t){t===null&&await this.root.deleteItem(this.path);const n=await this.root.getItem(this.path)||{};await this.root.setItem(this.path,x.omit(n,t))}async getItem(t){const n=await this.root.getItem(this.path);return t===null?n:x.get(n,t)}async setItem(t,n){if(t===null)await this.root.setItem(this.path,n);else{const r=await this.root.getItem(this.path)||{};await this.root.setItem(this.path,{...r,[t]:n})}return await this.getItem(t)}watchItem(t,n,r){return t===null?this.root.watchItem(this.path,(a,o)=>{n(a,o)},r):this.root.watchItem(this.path,(a,o)=>{const l=x.get(a,t),u=x.get(o,t);l!==u&&n(l,u)},r)}}class Tr{constructor(t,n,r){N(this,"attachmentStorage");this.instance=t,this.attachmentKey=n,this.constructInstance=r,this.attachmentStorage=new Ot(t.instanceData,n)}async getInstance(t){if(await this.attachmentStorage.getItem(t))return this.constructInstance(new Ot(this.attachmentStorage,t))}async create(t,n){return await this.attachmentStorage.setItem(t,n),this.constructInstance(new Ot(this.attachmentStorage,t))}async remove(t){await this.attachmentStorage.deleteItem(t)}async list(){const t=await this.attachmentStorage.getItem(null);return Promise.all(x.values(t).map(n=>this.constructInstance(new Ot(this.attachmentStorage,n.id))))}}function Sc(e,t){const{value:n,set:r}=R(e.operation.operationData,"config"),[a,o]=y.useState(x.defaults({},n,t)),l=async()=>{await r(a)};return y.useEffect(()=>{o(x.defaults({},n,t))},[n]),{config:a,setConfig:o,commit:l}}function _c(e){const{config:t,setConfig:n,commit:r}=Sc(e,{urlTemplate:"",openInNewTab:!0});async function a(){await r()}async function o(u){n({...t,openInNewTab:u}),await r()}const l=u=>n({...t,urlTemplate:u.currentTarget.value});return p(s.Stack,{children:[i(s.TextInput,{label:"Url",value:t.urlTemplate,onChange:l,onBlur:a}),i(s.Switch,{label:"Open in new Tab",checked:t.openInNewTab,onChange:u=>o(u.currentTarget.checked)})]})}async function kc(e,t){const{urlTemplate:n,openInNewTab:r}=await t.operationData.getItem("config");window.dispatchEvent(new CustomEvent("open-link",{detail:{urlTemplate:n,openInNewTab:r,payload:e}}))}class Tc extends ye{constructor(){super(...arguments);N(this,"VERSION",1)}configVersions(){this.version(1,n=>n)}}const Dc={displayName:"Open Link",id:"builtin:op:open-link",configRender:_c,run:kc,migrator:new Tc,createDefaultConfig:()=>({version:1,config:{urlTemplate:"",openInNewTab:!0}})};function Ic(e){const{value:t,set:n}=R(e.operationData,"config"),r=a=>void n({template:a});return[(t==null?void 0:t.template)||"",r]}function Mc(e){const[t,n]=Ic(e.operation);return i(s.TextInput,{defaultValue:t,onBlur:r=>n(r.currentTarget.value),label:"console.log"})}async function Ac(e,t){const n=await t.operationData.getItem("config"),r=x.template(n.template||"");console.log("run with payload",e),console.log(r(e))}const zc={displayName:"console.log (debug)",id:"builtin:op:debug",configRender:Mc,run:Ac},Ec=k.observer(e=>{const t=le(),{value:n,set:r}=R(e.operation.operationData,"config");console.log({value:n,viewID:n==null?void 0:n.viewID});const a=(n==null?void 0:n.viewID)||"",o=l=>void r({viewID:l});return i(s.Select,{defaultValue:a,value:a,onChange:o,label:"View",data:t.views.options,withinPortal:!0,zIndex:340,maxDropdownHeight:500})});async function $c(e,t){const r=(await t.operationData.getItem("config")).viewID;window.dispatchEvent(new CustomEvent("open-view",{detail:{viewID:r}}))}const Lc={displayName:"Open View",id:"builtin:op:open_view",configRender:Ec,run:$c},Oc={"tbody tr":{opacity:.5,transition:"opacity 200ms ease"},"tr[data-affected=true]":{opacity:1}},Pc=({value:e="",onChange:t})=>{const[n,r]=y.useState(e);y.useEffect(()=>{r(e)},[e]);const a=()=>{t(n)};return i(s.TextInput,{size:"xs",label:"",value:n,onChange:o=>r(o.currentTarget.value),sx:{flexGrow:1},rightSection:i(s.ActionIcon,{color:"green",size:"xs",onClick:a,disabled:n===e,children:i($.IconDeviceFloppy,{})})})},Bc={dictionary:{}},Vc=k.observer(e=>{const t=le(),{value:n=Bc,set:r}=R(e.operation.operationData,"config"),{dictionary:a={}}=n;console.log({value:{...n},dictionary:{...a},filters:[...t.filters.keyLabelOptions]});const o=(l,u)=>{if(u===""){const c={...a};delete c[l],r({dictionary:c});return}r({dictionary:{...a,[l]:u}})};return p(s.Table,{sx:Oc,children:[i("thead",{children:p("tr",{children:[i("th",{children:"Set filter"}),i("th",{children:"with"})]})}),i("tbody",{children:[...t.filters.keyLabelOptions].map(l=>{const u=l.value in a;return p("tr",{"data-affected":u,children:[i("td",{children:l.label}),i("td",{children:i(Pc,{value:a[l.value],onChange:c=>o(l.value,c)})})]},l.value)})})]})});async function Nc(e,t){const r=(await t.operationData.getItem("config")).dictionary;window.dispatchEvent(new CustomEvent("set-filter-values",{detail:{dictionary:r,payload:e}}))}const qc={displayName:"Set Filter Values",id:"builtin:op:set_filter_values",configRender:Vc,run:Nc},Fc={filter_keys:[]},Gc=k.observer(e=>{const t=le(),{value:n=Fc,set:r}=R(e.operation.operationData,"config"),{filter_keys:a=[]}=n,o=u=>{r({filter_keys:[...u]})},l=y.useMemo(()=>t.filters.current.map(u=>({label:u.label,value:u.key})),[t.filters.values]);return i(s.Stack,{spacing:10,children:i(s.MultiSelect,{label:"Select Filters to Clear",data:l,value:a,onChange:o})})});async function Wc(e,t){const r=(await t.operationData.getItem("config")).filter_keys;window.dispatchEvent(new CustomEvent("clear-filter-values",{detail:{filter_keys:r,payload:e}}))}const Dn=[zc,Dc,Lc,qc,{displayName:"Clear Filter Values",id:"builtin:op:clear_filter_values",configRender:Gc,run:Wc}];class jc{constructor(t,n=Dn){N(this,"attachments");this.operations=n;const r=async a=>{const{id:o,schemaRef:l}=await a.getItem(null);return{id:o,schemaRef:l,operationData:new Ot(a,"data")}};this.attachments=new Tr(t,"__OPERATIONS",r)}async runOperation(t,n){const r=await this.attachments.getInstance(t);if(!r){console.warn(`Operation '${t}' is not defined`);return}const a=this.tryGetSchema(r.schemaRef);if(!a){console.warn(`Operation schema '${r.schemaRef}' is not defined`);return}await a.run(n,r)}tryGetSchema(t){return this.operations.find(n=>n.id===t)}async needMigration(){const n=(await this.attachments.list()).map(async r=>{const a={configData:r.operationData},o=this.tryGetSchema(r.schemaRef),l=o==null?void 0:o.migrator;return l&&await l.needMigration(a)});return(await Promise.all(n)).some(r=>r)}async runMigration(){const n=(await this.attachments.list()).map(async r=>{const a={configData:r.operationData},o=this.tryGetSchema(r.schemaRef),l=o==null?void 0:o.migrator;l&&await l.needMigration(a)&&await l.migrate(a)});await Promise.all(n)}async createOrGetOperation(t,n){var l;if(!this.getOperationSchemaList().some(u=>u.id===n.id))throw new Error(`Operation schema '${n.id}' is not defined`);const a=await this.attachments.getInstance(t);return!a||a.schemaRef!==n.id?await this.attachments.create(t,{id:t,schemaRef:n.id,data:((l=n.createDefaultConfig)==null?void 0:l.call(n))??{}}):a}getOperationList(){return this.attachments.list()}getOperationSchemaList(){return this.operations}removeOperation(t){return this.attachments.remove(t)}async retrieveTrigger(t){return await this.attachments.getInstance(t)}}const ls="__TRIGGERS";class Rc{constructor(t,n){N(this,"attachments");this.instance=t,this.component=n;const r=async a=>{const{id:o,schemaRef:l}=await a.getItem(null);return{id:o,schemaRef:l,triggerData:new Ot(a,"data")}};this.attachments=new Tr(t,ls,r)}watchTriggerSnapshotList(t){return this.instance.instanceData.watchItem(ls,n=>{const r=x.values(n).map(a=>({id:x.get(a,"id"),schemaRef:x.get(a,"schemaRef"),config:te.toJS(x.get(a,"data.config"))}));t(r)},{fireImmediately:!0})}async createOrGetTrigger(t,n,r={recreate:!1}){var u;if(!this.getTriggerSchemaList().some(c=>c.id===n.id))throw new Error(`Trigger schema '${n.id}' is not defined in component '${this.component.name}'`);const o=await this.attachments.getInstance(t);return!o||r.recreate||o.schemaRef!==n.id?await this.attachments.create(t,{id:t,schemaRef:n.id,data:((u=n==null?void 0:n.createDefaultConfig)==null?void 0:u.call(n))||{}}):o}async getTriggerList(){return await this.attachments.list()}getTriggerSchemaList(){return this.component.triggers||[]}async removeTrigger(t){await this.attachments.remove(t)}async retrieveTrigger(t){return await this.attachments.getInstance(t)}async getMigrationTasks(){const n=(await this.getTriggerList()).map(async r=>{const a=this.getTriggerSchemaList().find(u=>u.id===r.schemaRef),o=a==null?void 0:a.migrator,l={configData:r.triggerData};return o&&await o.needMigration(l)?()=>o.migrate(l):null});return Promise.all(n).then(r=>r.filter(a=>a))}async needMigration(){return(await this.getMigrationTasks()).length>0}async runMigration(){const t=await this.getMigrationTasks();await Promise.all(t.map(n=>n()))}}class Dr{constructor(t,n,r){N(this,"operationManager");N(this,"triggerManager");N(this,"attachments");this.operationManager=new jc(t,r),this.triggerManager=new Rc(t,n);const a=async o=>{const{id:l,triggerRef:u,operationRef:c}=await o.getItem(null);return{id:l,triggerRef:u,operationRef:c}};this.attachments=new Tr(t,"__INTERACTIONS",a)}async addInteraction(t,n){const r=t.id,a=n.id,o=`[${r}]:[${a}]`;await this.attachments.create(o,{id:o,triggerRef:r,operationRef:a})}getInteractionList(){return this.attachments.list()}async removeInteraction(t){const n=await this.attachments.getInstance(t);if(!n)return;const{triggerRef:r,operationRef:a}=n;await this.getTriggerRefCount(r)<=1&&await this.triggerManager.removeTrigger(r),await this.getOperationRefCount(a)<=1&&await this.operationManager.removeOperation(a),await this.attachments.remove(t)}async getOperationRefCount(t){return(await this.getInteractionList()).filter(r=>r.operationRef===t).length}async getTriggerRefCount(t){return(await this.getInteractionList()).filter(r=>r.triggerRef===t).length}async runInteraction(t,n){const a=(await this.getInteractionList()).filter(o=>o.triggerRef===t);await Promise.all(a.map(async o=>{try{return await this.operationManager.runOperation(o.operationRef,n)}catch(l){console.warn(`Failed to run operation '${o.operationRef}'`,l)}}))}}const Xe=({vizManager:e,instance:t})=>K.useCreation(()=>new Dr(t,e.resolveComponent(t.type),Dn),[t,e]),us=e=>{const{title:t="Variables",variables:n}=e,r=Ie.useClipboard(),a=o=>{r.copy(o),vn.showNotification({color:"green",message:"Copied to clipboard"})};return p(s.Paper,{withBorder:!0,p:"sm",children:[i(s.Text,{size:"xs",color:"dimmed",mb:"sm",children:t}),i(s.Stack,{style:{maxHeight:"500px"},children:n.map(o=>p(s.Text,{size:"sm",children:[p(s.Code,{color:"teal",children:["// ",o.description]}),i("br",{}),p(s.Code,{onClick:()=>a(o.name),style:{cursor:"pointer"},children:[o.name," : ",o.valueType]})]},o.name))})]})};class Yc{constructor(t,n){N(this,"operationId");N(this,"operation");N(this,"operationSchema");N(this,"variables",[]);this.operationManager=t,this.instance=n,te.makeAutoObservable(this)}get schemaList(){return this.operationManager.getOperationSchemaList()}async configOperation(t,n){const r=await this.operationManager.retrieveTrigger(t),a=this.operationManager.getOperationSchemaList().find(o=>o.id===(r==null?void 0:r.schemaRef));te.runInAction(()=>{this.operationId=t,this.operation=r,this.operationSchema=a,this.variables=n})}async changeSchema(t){this.operationId&&(await this.operationManager.createOrGetOperation(this.operationId,t),await this.configOperation(this.operationId,this.variables))}}function Qc(e){return!!e.operationId}const Uc=k.observer(({model:e,onClick:t})=>{var r;const n=(r=e.operationSchema)==null?void 0:r.displayName;return i(s.Button,{variant:"outline",onClick:t,children:n})}),Kc=k.observer(({model:e})=>{const t={operation:e.operation,instance:e.instance,variables:[]};return y.createElement(e.operationSchema.configRender,t)}),Xc=k.observer(({model:e})=>{const t=e.schemaList,n=t.map(a=>({label:a.displayName,value:a.id}));async function r(a){await e.changeSchema(t.find(o=>o.id===a))}return i(s.Select,{label:"Operation",data:n,onChange:r,value:e.operationSchema.id,withinPortal:!0,zIndex:340})}),Jc=k.observer(e=>{const[t,{setTrue:n,setFalse:r}]=K.useBoolean(!1),{operationManager:a,operationId:o,instance:l,variables:u}=e,c=K.useCreation(()=>new Yc(a,l),[a,l]);return K.useAsyncEffect(async()=>{await c.configOperation(o,u)},[o,c]),Qc(c)?p(B,{children:[i(Uc,{model:c,onClick:n}),i(s.Modal,{size:600,opened:t,onClose:r,title:"Operation Settings",zIndex:320,children:p(s.Stack,{children:[i(Xc,{model:c}),p(s.Tabs,{defaultValue:"settings",children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"settings",children:"Settings"}),i(s.Tabs.Tab,{value:"variables",children:"Variables"})]}),i(s.Tabs.Panel,{value:"settings",pt:10,children:i(Kc,{model:c})}),i(s.Tabs.Panel,{value:"variables",pt:10,children:i(us,{title:"Variables",variables:c.variables})})]})]})})]}):null});class Zc{constructor(t,n){N(this,"triggerId");N(this,"trigger");N(this,"triggerSchema");N(this,"sampleData");this.triggerManager=t,this.instance=n,te.makeAutoObservable(this)}get schemaList(){return this.triggerManager.getTriggerSchemaList()}async configTrigger(t,n){const r=await this.triggerManager.retrieveTrigger(t),a=this.triggerManager.getTriggerSchemaList().find(o=>o.id===(r==null?void 0:r.schemaRef));te.runInAction(()=>{this.triggerId=t,this.trigger=r,this.triggerSchema=a,this.sampleData=n})}async changeSchema(t){this.triggerId&&(await this.triggerManager.createOrGetTrigger(this.triggerId,t),await this.configTrigger(this.triggerId,this.sampleData))}isReady(){return Hc(this)}}function Hc(e){return!!e.triggerId&&!!e.triggerSchema}function ed(e,t){return K.useCreation(()=>new Zc(e,t),[e,t])}const td=k.observer(({model:e,onClick:t})=>{const n=e.triggerSchema.nameRender,r={trigger:e.trigger,instance:e.instance,sampleData:e.sampleData};return i(s.Button,{variant:"outline",onClick:t,children:y.createElement(n,r)})}),nd=k.observer(({model:e})=>{const t=e.schemaList,n=t.map(a=>({label:a.displayName,value:a.id}));async function r(a){await e.changeSchema(t.find(o=>o.id===a))}return i(s.Select,{label:"Trigger",data:n,value:e.triggerSchema.id,onChange:r})}),rd=k.observer(({model:e})=>{const t={trigger:e.trigger,instance:e.instance,sampleData:e.sampleData};return y.createElement(e.triggerSchema.configRender,t)}),id=k.observer(e=>{const[t,{setTrue:n,setFalse:r}]=K.useBoolean(!1),a=e.model;return p(B,{children:[i(s.Modal,{opened:t,onClose:r,title:"Setup Trigger",zIndex:320,children:p(s.Stack,{children:[i(nd,{model:a}),i(rd,{model:a}),i(us,{title:"Payload",variables:a.triggerSchema.payload})]})}),i(td,{onClick:n,model:a})]})});function ad(e,t){const[n,r]=y.useState([]);return K.useAsyncEffect(async()=>{const a=await e.getInteractionList();r(a)},[t,e]),n}const sd=k.observer(({item:e,manager:t,instance:n,sampleData:r,variables:a,onRemove:o})=>{const{triggerRef:l,operationRef:u}=e,c=ed(t.triggerManager,n);if(K.useAsyncEffect(async()=>{await c.configTrigger(l,r)},[c,l,r]),c.isReady()){const d=[...c.triggerSchema.payload,...a];return p(s.Group,{children:[i(id,{model:c}),i(Jc,{instance:n,operationId:u,variables:d,operationManager:t.operationManager}),i(s.ActionIcon,{"aria-label":"delete-interaction",variant:"filled",color:"red",onClick:()=>o(e),children:i(T.Trash,{size:16})})]})}return null}),od=e=>{const[t,n]=y.useState(0),{interactionManager:r,instance:a,sampleData:o,variables:l}=e,u=ad(r,t),c=async()=>{const g=await r.triggerManager.createOrGetTrigger(Ie.randomId(),r.triggerManager.getTriggerSchemaList()[0]),m=await r.operationManager.createOrGetOperation(Ie.randomId(),r.operationManager.getOperationSchemaList()[0]);await r.addInteraction(g,m),n(C=>C+1)};async function d(g){await r.removeInteraction(g.id),n(m=>m+1)}const{data:f=0,loading:h}=K.useRequest(async()=>{try{return(await r.triggerManager.getTriggerSchemaList()).length}catch{return 0}});return p(s.Stack,{children:[i(s.LoadingOverlay,{visible:h}),f===0&&i(s.Alert,{icon:i(T.AlertCircle,{size:16}),title:"Unavailable",color:"gray",children:"This visualization does not have available interactions to choose from"}),u.map(g=>i(sd,{onRemove:d,instance:a,sampleData:o,variables:l,item:g,manager:e.interactionManager},g.id)),i(s.Button,{style:{width:"fit-content"},onClick:()=>c(),disabled:f===0,children:"Add interaction"})]})},ld=()=>{const{panel:e,data:t}=bt(),n=e.viz,{vizManager:r}=y.useContext(ut),a=e.json,o=K.useCreation(()=>r.getOrCreateInstance(a),[r,a]),l=K.useCreation(()=>new Dr(o,r.resolveComponent(n.type),Dn),[o,n.type]);return y.useEffect(()=>o.instanceData.watchItem(null,x.throttle(u=>{e.viz.setConf(u)},100,{leading:!1,trailing:!0})),[o]),{instance:o,vizManager:r,interactionManager:l,sampleData:t,variables:[]}},ud=()=>{const e=ld();return i(od,{...e})};function Pt({enabled:e,func_content:t}){return(n,r)=>{if(!e)return n;try{return new Function(`return ${t}`)()(n,r)}catch(a){return console.error(`[getEchartsXAxisLabel] failed parsing custom function, error: ${a.message}`),n}}}function cd(e,t){return Object.entries(e).map(([r,a])=>{const o=a.map(_=>_[t]).sort((_,D)=>_-D),l=Kt.quantile(o,.25)??0,u=Kt.quantile(o,.5)??0,c=Kt.quantile(o,.75)??0,d=c-l,f=l-1.5*d,h=c+1.5*d,g=Math.max(o[0],f),m=Math.min(x.last(o)??0,h),C=a.filter(_=>{const D=_[t];return D<g||D>m}).map(_=>[r,_[t],_]);return{name:r,min:g,q1:l,median:u,q3:c,max:m,outliers:C}})}function dd(e,t){const{x_axis:n,y_axis:r}=e;if(!n.data_key||!r.data_key)return[];const a=O(n.data_key),o=O(r.data_key);if(a.queryID!==o.queryID)throw new Error("Please use the same query for X & Y axis");const l=x.groupBy(t[a.queryID],a.columnKey),u=cd(l,o.columnKey),c=u.map(d=>d.outliers).flat();return[{source:u},{source:c}]}function pd({config:e}){return{...e.legend,data:[{name:"Box",icon:"roundRect",itemStyle:{color:e.color}},{name:"Outlier",icon:"circle",itemStyle:{color:"#2F8CC0"}}]}}const Ir=["max","q3","median","q1","min"];function hd(e){const{color:t}=e;return[{name:"Box",type:"boxplot",itemStyle:{color:t,borderColor:"#2F8CC0",borderWidth:2},emphasis:{disabled:!0},boxWidth:[10,40],datasetIndex:0,encode:{y:Ir,x:"name",itemName:["name"],tooltip:Ir}},{name:"Outlier",type:"scatter",symbolSize:5,itemStyle:{color:"#2F8CC0"},emphasis:{scale:2},datasetIndex:1}]}function fd(e){const{outliers:t,min:n,max:r}=e,a=t.filter(u=>u[1]<n).length,o=t.filter(u=>u[1]>r).length,l=(u,c)=>`
61
+ `}function rt(e){return{width:e.width,overflow:e.overflow,ellipsis:e.ellipsis}}const kr={x_axis:{name:"X Axis",data_key:"",axisLabel:{rotate:0,formatter:{...Ue},overflow:Re}},y_axis:{name:"Y Axis",data_key:"value",label_formatter:ze},tooltip:{metrics:[]},color:"#228be6",reference_lines:[],legend:{show:!0,top:"10",right:"0",left:"auto",bottom:"auto",orient:"vertical",type:"scroll"}};function Dt(e,t){return b.useMemo(()=>{const{queryID:n,columnKey:r}=O(t);return x.keyBy(e[n],r)},[e,t])}const Ke=(e,t)=>{const[n,r]=b.useState([]);return b.useEffect(()=>e.watchTriggerSnapshotList(a=>r(a.filter(o=>o.schemaRef===t))),[]),n};class Ot{constructor(t,n){this.root=t,this.path=n}async deleteItem(t){t===null&&await this.root.deleteItem(this.path);const n=await this.root.getItem(this.path)||{};await this.root.setItem(this.path,x.omit(n,t))}async getItem(t){const n=await this.root.getItem(this.path);return t===null?n:x.get(n,t)}async setItem(t,n){if(t===null)await this.root.setItem(this.path,n);else{const r=await this.root.getItem(this.path)||{};await this.root.setItem(this.path,{...r,[t]:n})}return await this.getItem(t)}watchItem(t,n,r){return t===null?this.root.watchItem(this.path,(a,o)=>{n(a,o)},r):this.root.watchItem(this.path,(a,o)=>{const l=x.get(a,t),u=x.get(o,t);l!==u&&n(l,u)},r)}}class Tr{constructor(t,n,r){N(this,"attachmentStorage");this.instance=t,this.attachmentKey=n,this.constructInstance=r,this.attachmentStorage=new Ot(t.instanceData,n)}async getInstance(t){if(await this.attachmentStorage.getItem(t))return this.constructInstance(new Ot(this.attachmentStorage,t))}async create(t,n){return await this.attachmentStorage.setItem(t,n),this.constructInstance(new Ot(this.attachmentStorage,t))}async remove(t){await this.attachmentStorage.deleteItem(t)}async list(){const t=await this.attachmentStorage.getItem(null);return Promise.all(x.values(t).map(n=>this.constructInstance(new Ot(this.attachmentStorage,n.id))))}}function Sc(e,t){const{value:n,set:r}=R(e.operation.operationData,"config"),[a,o]=b.useState(x.defaults({},n,t)),l=async()=>{await r(a)};return b.useEffect(()=>{o(x.defaults({},n,t))},[n]),{config:a,setConfig:o,commit:l}}function _c(e){const{config:t,setConfig:n,commit:r}=Sc(e,{urlTemplate:"",openInNewTab:!0});async function a(){await r()}async function o(u){n({...t,openInNewTab:u}),await r()}const l=u=>n({...t,urlTemplate:u.currentTarget.value});return p(s.Stack,{children:[i(s.TextInput,{label:"Url",value:t.urlTemplate,onChange:l,onBlur:a}),i(s.Switch,{label:"Open in new Tab",checked:t.openInNewTab,onChange:u=>o(u.currentTarget.checked)})]})}async function kc(e,t){const{urlTemplate:n,openInNewTab:r}=await t.operationData.getItem("config");window.dispatchEvent(new CustomEvent("open-link",{detail:{urlTemplate:n,openInNewTab:r,payload:e}}))}class Tc extends ye{constructor(){super(...arguments);N(this,"VERSION",1)}configVersions(){this.version(1,n=>n)}}const Dc={displayName:"Open Link",id:"builtin:op:open-link",configRender:_c,run:kc,migrator:new Tc,createDefaultConfig:()=>({version:1,config:{urlTemplate:"",openInNewTab:!0}})};function Ic(e){const{value:t,set:n}=R(e.operationData,"config"),r=a=>void n({template:a});return[(t==null?void 0:t.template)||"",r]}function Mc(e){const[t,n]=Ic(e.operation);return i(s.TextInput,{defaultValue:t,onBlur:r=>n(r.currentTarget.value),label:"console.log"})}async function Ac(e,t){const n=await t.operationData.getItem("config"),r=x.template(n.template||"");console.log("run with payload",e),console.log(r(e))}const zc={displayName:"console.log (debug)",id:"builtin:op:debug",configRender:Mc,run:Ac},Ec=k.observer(e=>{const t=le(),{value:n,set:r}=R(e.operation.operationData,"config");console.log({value:n,viewID:n==null?void 0:n.viewID});const a=(n==null?void 0:n.viewID)||"",o=l=>void r({viewID:l});return i(s.Select,{defaultValue:a,value:a,onChange:o,label:"View",data:t.views.options,withinPortal:!0,zIndex:340,maxDropdownHeight:500})});async function $c(e,t){const r=(await t.operationData.getItem("config")).viewID;window.dispatchEvent(new CustomEvent("open-view",{detail:{viewID:r}}))}const Lc={displayName:"Open View",id:"builtin:op:open_view",configRender:Ec,run:$c},Oc={"tbody tr":{opacity:.5,transition:"opacity 200ms ease"},"tr[data-affected=true]":{opacity:1}},Pc=({value:e="",onChange:t})=>{const[n,r]=b.useState(e);b.useEffect(()=>{r(e)},[e]);const a=()=>{t(n)};return i(s.TextInput,{size:"xs",label:"",value:n,onChange:o=>r(o.currentTarget.value),sx:{flexGrow:1},rightSection:i(s.ActionIcon,{color:"green",size:"xs",onClick:a,disabled:n===e,children:i($.IconDeviceFloppy,{})})})},Bc={dictionary:{}},Vc=k.observer(e=>{const t=le(),{value:n=Bc,set:r}=R(e.operation.operationData,"config"),{dictionary:a={}}=n;console.log({value:{...n},dictionary:{...a},filters:[...t.filters.keyLabelOptions]});const o=(l,u)=>{if(u===""){const c={...a};delete c[l],r({dictionary:c});return}r({dictionary:{...a,[l]:u}})};return p(s.Table,{sx:Oc,children:[i("thead",{children:p("tr",{children:[i("th",{children:"Set filter"}),i("th",{children:"with"})]})}),i("tbody",{children:[...t.filters.keyLabelOptions].map(l=>{const u=l.value in a;return p("tr",{"data-affected":u,children:[i("td",{children:l.label}),i("td",{children:i(Pc,{value:a[l.value],onChange:c=>o(l.value,c)})})]},l.value)})})]})});async function Nc(e,t){const r=(await t.operationData.getItem("config")).dictionary;window.dispatchEvent(new CustomEvent("set-filter-values",{detail:{dictionary:r,payload:e}}))}const qc={displayName:"Set Filter Values",id:"builtin:op:set_filter_values",configRender:Vc,run:Nc},Fc={filter_keys:[]},Gc=k.observer(e=>{const t=le(),{value:n=Fc,set:r}=R(e.operation.operationData,"config"),{filter_keys:a=[]}=n,o=u=>{r({filter_keys:[...u]})},l=b.useMemo(()=>t.filters.current.map(u=>({label:u.label,value:u.key})),[t.filters.values]);return i(s.Stack,{spacing:10,children:i(s.MultiSelect,{label:"Select Filters to Clear",data:l,value:a,onChange:o})})});async function Wc(e,t){const r=(await t.operationData.getItem("config")).filter_keys;window.dispatchEvent(new CustomEvent("clear-filter-values",{detail:{filter_keys:r,payload:e}}))}const Dn=[zc,Dc,Lc,qc,{displayName:"Clear Filter Values",id:"builtin:op:clear_filter_values",configRender:Gc,run:Wc}];class jc{constructor(t,n=Dn){N(this,"attachments");this.operations=n;const r=async a=>{const{id:o,schemaRef:l}=await a.getItem(null);return{id:o,schemaRef:l,operationData:new Ot(a,"data")}};this.attachments=new Tr(t,"__OPERATIONS",r)}async runOperation(t,n){const r=await this.attachments.getInstance(t);if(!r){console.warn(`Operation '${t}' is not defined`);return}const a=this.tryGetSchema(r.schemaRef);if(!a){console.warn(`Operation schema '${r.schemaRef}' is not defined`);return}await a.run(n,r)}tryGetSchema(t){return this.operations.find(n=>n.id===t)}async needMigration(){const n=(await this.attachments.list()).map(async r=>{const a={configData:r.operationData},o=this.tryGetSchema(r.schemaRef),l=o==null?void 0:o.migrator;return l&&await l.needMigration(a)});return(await Promise.all(n)).some(r=>r)}async runMigration(){const n=(await this.attachments.list()).map(async r=>{const a={configData:r.operationData},o=this.tryGetSchema(r.schemaRef),l=o==null?void 0:o.migrator;l&&await l.needMigration(a)&&await l.migrate(a)});await Promise.all(n)}async createOrGetOperation(t,n){var l;if(!this.getOperationSchemaList().some(u=>u.id===n.id))throw new Error(`Operation schema '${n.id}' is not defined`);const a=await this.attachments.getInstance(t);return!a||a.schemaRef!==n.id?await this.attachments.create(t,{id:t,schemaRef:n.id,data:((l=n.createDefaultConfig)==null?void 0:l.call(n))??{}}):a}getOperationList(){return this.attachments.list()}getOperationSchemaList(){return this.operations}removeOperation(t){return this.attachments.remove(t)}async retrieveTrigger(t){return await this.attachments.getInstance(t)}}const ls="__TRIGGERS";class Rc{constructor(t,n){N(this,"attachments");this.instance=t,this.component=n;const r=async a=>{const{id:o,schemaRef:l}=await a.getItem(null);return{id:o,schemaRef:l,triggerData:new Ot(a,"data")}};this.attachments=new Tr(t,ls,r)}watchTriggerSnapshotList(t){return this.instance.instanceData.watchItem(ls,n=>{const r=x.values(n).map(a=>({id:x.get(a,"id"),schemaRef:x.get(a,"schemaRef"),config:te.toJS(x.get(a,"data.config"))}));t(r)},{fireImmediately:!0})}async createOrGetTrigger(t,n,r={recreate:!1}){var u;if(!this.getTriggerSchemaList().some(c=>c.id===n.id))throw new Error(`Trigger schema '${n.id}' is not defined in component '${this.component.name}'`);const o=await this.attachments.getInstance(t);return!o||r.recreate||o.schemaRef!==n.id?await this.attachments.create(t,{id:t,schemaRef:n.id,data:((u=n==null?void 0:n.createDefaultConfig)==null?void 0:u.call(n))||{}}):o}async getTriggerList(){return await this.attachments.list()}getTriggerSchemaList(){return this.component.triggers||[]}async removeTrigger(t){await this.attachments.remove(t)}async retrieveTrigger(t){return await this.attachments.getInstance(t)}async getMigrationTasks(){const n=(await this.getTriggerList()).map(async r=>{const a=this.getTriggerSchemaList().find(u=>u.id===r.schemaRef),o=a==null?void 0:a.migrator,l={configData:r.triggerData};return o&&await o.needMigration(l)?()=>o.migrate(l):null});return Promise.all(n).then(r=>r.filter(a=>a))}async needMigration(){return(await this.getMigrationTasks()).length>0}async runMigration(){const t=await this.getMigrationTasks();await Promise.all(t.map(n=>n()))}}class Dr{constructor(t,n,r){N(this,"operationManager");N(this,"triggerManager");N(this,"attachments");this.operationManager=new jc(t,r),this.triggerManager=new Rc(t,n);const a=async o=>{const{id:l,triggerRef:u,operationRef:c}=await o.getItem(null);return{id:l,triggerRef:u,operationRef:c}};this.attachments=new Tr(t,"__INTERACTIONS",a)}async addInteraction(t,n){const r=t.id,a=n.id,o=`[${r}]:[${a}]`;await this.attachments.create(o,{id:o,triggerRef:r,operationRef:a})}getInteractionList(){return this.attachments.list()}async removeInteraction(t){const n=await this.attachments.getInstance(t);if(!n)return;const{triggerRef:r,operationRef:a}=n;await this.getTriggerRefCount(r)<=1&&await this.triggerManager.removeTrigger(r),await this.getOperationRefCount(a)<=1&&await this.operationManager.removeOperation(a),await this.attachments.remove(t)}async getOperationRefCount(t){return(await this.getInteractionList()).filter(r=>r.operationRef===t).length}async getTriggerRefCount(t){return(await this.getInteractionList()).filter(r=>r.triggerRef===t).length}async runInteraction(t,n){const a=(await this.getInteractionList()).filter(o=>o.triggerRef===t);await Promise.all(a.map(async o=>{try{return await this.operationManager.runOperation(o.operationRef,n)}catch(l){console.warn(`Failed to run operation '${o.operationRef}'`,l)}}))}}const Xe=({vizManager:e,instance:t})=>K.useCreation(()=>new Dr(t,e.resolveComponent(t.type),Dn),[t,e]),us=e=>{const{title:t="Variables",variables:n}=e,r=Ie.useClipboard(),a=o=>{r.copy(o),vn.showNotification({color:"green",message:"Copied to clipboard"})};return p(s.Paper,{withBorder:!0,p:"sm",children:[i(s.Text,{size:"xs",color:"dimmed",mb:"sm",children:t}),i(s.Stack,{style:{maxHeight:"500px"},children:n.map(o=>p(s.Text,{size:"sm",children:[p(s.Code,{color:"teal",children:["// ",o.description]}),i("br",{}),p(s.Code,{onClick:()=>a(o.name),style:{cursor:"pointer"},children:[o.name," : ",o.valueType]})]},o.name))})]})};class Yc{constructor(t,n){N(this,"operationId");N(this,"operation");N(this,"operationSchema");N(this,"variables",[]);this.operationManager=t,this.instance=n,te.makeAutoObservable(this)}get schemaList(){return this.operationManager.getOperationSchemaList()}async configOperation(t,n){const r=await this.operationManager.retrieveTrigger(t),a=this.operationManager.getOperationSchemaList().find(o=>o.id===(r==null?void 0:r.schemaRef));te.runInAction(()=>{this.operationId=t,this.operation=r,this.operationSchema=a,this.variables=n})}async changeSchema(t){this.operationId&&(await this.operationManager.createOrGetOperation(this.operationId,t),await this.configOperation(this.operationId,this.variables))}}function Qc(e){return!!e.operationId}const Uc=k.observer(({model:e,onClick:t})=>{var r;const n=(r=e.operationSchema)==null?void 0:r.displayName;return i(s.Button,{variant:"outline",onClick:t,children:n})}),Kc=k.observer(({model:e})=>{const t={operation:e.operation,instance:e.instance,variables:[]};return b.createElement(e.operationSchema.configRender,t)}),Xc=k.observer(({model:e})=>{const t=e.schemaList,n=t.map(a=>({label:a.displayName,value:a.id}));async function r(a){await e.changeSchema(t.find(o=>o.id===a))}return i(s.Select,{label:"Operation",data:n,onChange:r,value:e.operationSchema.id,withinPortal:!0,zIndex:340})}),Jc=k.observer(e=>{const[t,{setTrue:n,setFalse:r}]=K.useBoolean(!1),{operationManager:a,operationId:o,instance:l,variables:u}=e,c=K.useCreation(()=>new Yc(a,l),[a,l]);return K.useAsyncEffect(async()=>{await c.configOperation(o,u)},[o,c]),Qc(c)?p(B,{children:[i(Uc,{model:c,onClick:n}),i(s.Modal,{size:600,opened:t,onClose:r,title:"Operation Settings",zIndex:320,children:p(s.Stack,{children:[i(Xc,{model:c}),p(s.Tabs,{defaultValue:"settings",children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"settings",children:"Settings"}),i(s.Tabs.Tab,{value:"variables",children:"Variables"})]}),i(s.Tabs.Panel,{value:"settings",pt:10,children:i(Kc,{model:c})}),i(s.Tabs.Panel,{value:"variables",pt:10,children:i(us,{title:"Variables",variables:c.variables})})]})]})})]}):null});class Zc{constructor(t,n){N(this,"triggerId");N(this,"trigger");N(this,"triggerSchema");N(this,"sampleData");this.triggerManager=t,this.instance=n,te.makeAutoObservable(this)}get schemaList(){return this.triggerManager.getTriggerSchemaList()}async configTrigger(t,n){const r=await this.triggerManager.retrieveTrigger(t),a=this.triggerManager.getTriggerSchemaList().find(o=>o.id===(r==null?void 0:r.schemaRef));te.runInAction(()=>{this.triggerId=t,this.trigger=r,this.triggerSchema=a,this.sampleData=n})}async changeSchema(t){this.triggerId&&(await this.triggerManager.createOrGetTrigger(this.triggerId,t),await this.configTrigger(this.triggerId,this.sampleData))}isReady(){return Hc(this)}}function Hc(e){return!!e.triggerId&&!!e.triggerSchema}function ed(e,t){return K.useCreation(()=>new Zc(e,t),[e,t])}const td=k.observer(({model:e,onClick:t})=>{const n=e.triggerSchema.nameRender,r={trigger:e.trigger,instance:e.instance,sampleData:e.sampleData};return i(s.Button,{variant:"outline",onClick:t,children:b.createElement(n,r)})}),nd=k.observer(({model:e})=>{const t=e.schemaList,n=t.map(a=>({label:a.displayName,value:a.id}));async function r(a){await e.changeSchema(t.find(o=>o.id===a))}return i(s.Select,{label:"Trigger",data:n,value:e.triggerSchema.id,onChange:r})}),rd=k.observer(({model:e})=>{const t={trigger:e.trigger,instance:e.instance,sampleData:e.sampleData};return b.createElement(e.triggerSchema.configRender,t)}),id=k.observer(e=>{const[t,{setTrue:n,setFalse:r}]=K.useBoolean(!1),a=e.model;return p(B,{children:[i(s.Modal,{opened:t,onClose:r,title:"Setup Trigger",zIndex:320,children:p(s.Stack,{children:[i(nd,{model:a}),i(rd,{model:a}),i(us,{title:"Payload",variables:a.triggerSchema.payload})]})}),i(td,{onClick:n,model:a})]})});function ad(e,t){const[n,r]=b.useState([]);return K.useAsyncEffect(async()=>{const a=await e.getInteractionList();r(a)},[t,e]),n}const sd=k.observer(({item:e,manager:t,instance:n,sampleData:r,variables:a,onRemove:o})=>{const{triggerRef:l,operationRef:u}=e,c=ed(t.triggerManager,n);if(K.useAsyncEffect(async()=>{await c.configTrigger(l,r)},[c,l,r]),c.isReady()){const d=[...c.triggerSchema.payload,...a];return p(s.Group,{children:[i(id,{model:c}),i(Jc,{instance:n,operationId:u,variables:d,operationManager:t.operationManager}),i(s.ActionIcon,{"aria-label":"delete-interaction",variant:"filled",color:"red",onClick:()=>o(e),children:i(T.Trash,{size:16})})]})}return null}),od=e=>{const[t,n]=b.useState(0),{interactionManager:r,instance:a,sampleData:o,variables:l}=e,u=ad(r,t),c=async()=>{const g=await r.triggerManager.createOrGetTrigger(Ie.randomId(),r.triggerManager.getTriggerSchemaList()[0]),m=await r.operationManager.createOrGetOperation(Ie.randomId(),r.operationManager.getOperationSchemaList()[0]);await r.addInteraction(g,m),n(C=>C+1)};async function d(g){await r.removeInteraction(g.id),n(m=>m+1)}const{data:f=0,loading:h}=K.useRequest(async()=>{try{return(await r.triggerManager.getTriggerSchemaList()).length}catch{return 0}});return p(s.Stack,{children:[i(s.LoadingOverlay,{visible:h}),f===0&&i(s.Alert,{icon:i(T.AlertCircle,{size:16}),title:"Unavailable",color:"gray",children:"This visualization does not have available interactions to choose from"}),u.map(g=>i(sd,{onRemove:d,instance:a,sampleData:o,variables:l,item:g,manager:e.interactionManager},g.id)),i(s.Button,{style:{width:"fit-content"},onClick:()=>c(),disabled:f===0,children:"Add interaction"})]})},ld=()=>{const{panel:e,data:t}=bt(),n=e.viz,{vizManager:r}=b.useContext(ut),a=e.json,o=K.useCreation(()=>r.getOrCreateInstance(a),[r,a]),l=K.useCreation(()=>new Dr(o,r.resolveComponent(n.type),Dn),[o,n.type]);return b.useEffect(()=>o.instanceData.watchItem(null,x.throttle(u=>{e.viz.setConf(u)},100,{leading:!1,trailing:!0})),[o]),{instance:o,vizManager:r,interactionManager:l,sampleData:t,variables:[]}},ud=()=>{const e=ld();return i(od,{...e})};function Pt({enabled:e,func_content:t}){return(n,r)=>{if(!e)return n;try{return new Function(`return ${t}`)()(n,r)}catch(a){return console.error(`[getEchartsXAxisLabel] failed parsing custom function, error: ${a.message}`),n}}}function cd(e,t){return Object.entries(e).map(([r,a])=>{const o=a.map(_=>_[t]).sort((_,D)=>_-D),l=Xt.quantile(o,.25)??0,u=Xt.quantile(o,.5)??0,c=Xt.quantile(o,.75)??0,d=c-l,f=l-1.5*d,h=c+1.5*d,g=Math.max(o[0],f),m=Math.min(x.last(o)??0,h),C=a.filter(_=>{const D=_[t];return D<g||D>m}).map(_=>[r,_[t],_]);return{name:r,min:g,q1:l,median:u,q3:c,max:m,outliers:C}})}function dd(e,t){const{x_axis:n,y_axis:r}=e;if(!n.data_key||!r.data_key)return[];const a=O(n.data_key),o=O(r.data_key);if(a.queryID!==o.queryID)throw new Error("Please use the same query for X & Y axis");const l=x.groupBy(t[a.queryID],a.columnKey),u=cd(l,o.columnKey),c=u.map(d=>d.outliers).flat();return[{source:u},{source:c}]}function pd({config:e}){return{...e.legend,data:[{name:"Box",icon:"roundRect",itemStyle:{color:e.color}},{name:"Outlier",icon:"circle",itemStyle:{color:"#2F8CC0"}}]}}const Ir=["max","q3","median","q1","min"];function hd(e){const{color:t}=e;return[{name:"Box",type:"boxplot",itemStyle:{color:t,borderColor:"#2F8CC0",borderWidth:2},emphasis:{disabled:!0},boxWidth:[10,40],datasetIndex:0,encode:{y:Ir,x:"name",itemName:["name"],tooltip:Ir}},{name:"Outlier",type:"scatter",symbolSize:5,itemStyle:{color:"#2F8CC0"},emphasis:{scale:2},datasetIndex:1}]}function fd(e){const{outliers:t,min:n,max:r}=e,a=t.filter(u=>u[1]<n).length,o=t.filter(u=>u[1]>r).length,l=(u,c)=>`
62
62
  <tr>
63
63
  <th style="text-align: right; padding: 0 1em;">${u}</th>
64
64
  <td style="text-align: left; padding: 0 1em;">
@@ -97,13 +97,13 @@ Check the top-level render call using <`+V+">.")}return E}}function Su(S,E){{if(
97
97
  ${r.join("")}
98
98
  </tbody>
99
99
  </table>
100
- `}const bd=e=>t=>{const{componentSubType:n,value:r}=t;return n==="scatter"?yd(e,r):gd(e,r)};function vd({config:e}){return{trigger:"item",confine:!0,formatter:bd(e)}}const en=y.forwardRef(function({value:t,onChange:n,...r},a){return i(s.TextInput,{ref:a,value:t,onChange:n,...r})}),Mr={fontSize:"14px",lineHeight:"32px",color:"#3D3E45",ul:{paddingLeft:"2em",margin:"6px 0 0"},p:{margin:0},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 cs(e,t,n){for(let r=0;;r++){if(r==e.childCount||r==t.childCount)return e.childCount==t.childCount?null:n;let a=e.child(r),o=t.child(r);if(a==o){n+=a.nodeSize;continue}if(!a.sameMarkup(o))return n;if(a.isText&&a.text!=o.text){for(let l=0;a.text[l]==o.text[l];l++)n++;return n}if(a.content.size||o.content.size){let l=cs(a.content,o.content,n+1);if(l!=null)return l}n+=a.nodeSize}}function ds(e,t,n,r){for(let a=e.childCount,o=t.childCount;;){if(a==0||o==0)return a==o?null:{a:n,b:r};let l=e.child(--a),u=t.child(--o),c=l.nodeSize;if(l==u){n-=c,r-=c;continue}if(!l.sameMarkup(u))return{a:n,b:r};if(l.isText&&l.text!=u.text){let d=0,f=Math.min(l.text.length,u.text.length);for(;d<f&&l.text[l.text.length-d-1]==u.text[u.text.length-d-1];)d++,n--,r--;return{a:n,b:r}}if(l.content.size||u.content.size){let d=ds(l.content,u.content,n-1,r-1);if(d)return d}n-=c,r-=c}}class ae{constructor(t,n){if(this.content=t,this.size=n||0,n==null)for(let r=0;r<t.length;r++)this.size+=t[r].nodeSize}nodesBetween(t,n,r,a=0,o){for(let l=0,u=0;u<n;l++){let c=this.content[l],d=u+c.nodeSize;if(d>t&&r(c,a+u,o||null,l)!==!1&&c.content.size){let f=u+1;c.nodesBetween(Math.max(0,t-f),Math.min(c.content.size,n-f),r,a+f)}u=d}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,n,r,a){let o="",l=!0;return this.nodesBetween(t,n,(u,c)=>{u.isText?(o+=u.text.slice(Math.max(t,c)-c,n-c),l=!r):u.isLeaf?(a?o+=typeof a=="function"?a(u):a:u.type.spec.leafText&&(o+=u.type.spec.leafText(u)),l=!r):!l&&u.isBlock&&(o+=r,l=!0)},0),o}append(t){if(!t.size)return this;if(!this.size)return t;let n=this.lastChild,r=t.firstChild,a=this.content.slice(),o=0;for(n.isText&&n.sameMarkup(r)&&(a[a.length-1]=n.withText(n.text+r.text),o=1);o<t.content.length;o++)a.push(t.content[o]);return new ae(a,this.size+t.size)}cut(t,n=this.size){if(t==0&&n==this.size)return this;let r=[],a=0;if(n>t)for(let o=0,l=0;l<n;o++){let u=this.content[o],c=l+u.nodeSize;c>t&&((l<t||c>n)&&(u.isText?u=u.cut(Math.max(0,t-l),Math.min(u.text.length,n-l)):u=u.cut(Math.max(0,t-l-1),Math.min(u.content.size,n-l-1))),r.push(u),a+=u.nodeSize),l=c}return new ae(r,a)}cutByIndex(t,n){return t==n?ae.empty:t==0&&n==this.content.length?this:new ae(this.content.slice(t,n))}replaceChild(t,n){let r=this.content[t];if(r==n)return this;let a=this.content.slice(),o=this.size+n.nodeSize-r.nodeSize;return a[t]=n,new ae(a,o)}addToStart(t){return new ae([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new ae(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,r=0;n<this.content.length;n++){let a=this.content[n];t(a,r,n),r+=a.nodeSize}}findDiffStart(t,n=0){return cs(this,t,n)}findDiffEnd(t,n=this.size,r=t.size){return ds(this,t,n,r)}findIndex(t,n=-1){if(t==0)return In(0,t);if(t==this.size)return In(this.content.length,t);if(t>this.size||t<0)throw new RangeError(`Position ${t} outside of fragment (${this})`);for(let r=0,a=0;;r++){let o=this.child(r),l=a+o.nodeSize;if(l>=t)return l==t||n>0?In(r+1,l):In(r,a);a=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 ae.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new ae(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return ae.empty;let n,r=0;for(let a=0;a<t.length;a++){let o=t[a];r+=o.nodeSize,a&&o.isText&&t[a-1].sameMarkup(o)?(n||(n=t.slice(0,a)),n[n.length-1]=o.withText(n[n.length-1].text+o.text)):n&&n.push(o)}return new ae(n||t,r)}static from(t){if(!t)return ae.empty;if(t instanceof ae)return t;if(Array.isArray(t))return this.fromArray(t);if(t.attrs)return new ae([t],t.nodeSize);throw new RangeError("Can not convert "+t+" to a Fragment"+(t.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}}ae.empty=new ae([],0);const Ar={index:0,offset:0};function In(e,t){return Ar.index=e,Ar.offset=t,Ar}function zr(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 r=0;r<e.length;r++)if(!zr(e[r],t[r]))return!1}else{for(let r in e)if(!(r in t)||!zr(e[r],t[r]))return!1;for(let r in t)if(!(r in e))return!1}return!0}class Re{constructor(t,n){this.type=t,this.attrs=n}addToSet(t){let n,r=!1;for(let a=0;a<t.length;a++){let o=t[a];if(this.eq(o))return t;if(this.type.excludes(o.type))n||(n=t.slice(0,a));else{if(o.type.excludes(this.type))return t;!r&&o.type.rank>this.type.rank&&(n||(n=t.slice(0,a)),n.push(this),r=!0),n&&n.push(o)}}return n||(n=t.slice()),r||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&&zr(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 r=t.marks[n.type];if(!r)throw new RangeError(`There is no mark type ${n.type} in this schema`);return r.create(n.attrs)}static sameSet(t,n){if(t==n)return!0;if(t.length!=n.length)return!1;for(let r=0;r<t.length;r++)if(!t[r].eq(n[r]))return!1;return!0}static setFrom(t){if(!t||Array.isArray(t)&&t.length==0)return Re.none;if(t instanceof Re)return[t];let n=t.slice();return n.sort((r,a)=>r.type.rank-a.type.rank),n}}Re.none=[];class xd extends Error{}class ce{constructor(t,n,r){this.content=t,this.openStart=n,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,n){let r=hs(this.content,t+this.openStart,n);return r&&new ce(r,this.openStart,this.openEnd)}removeBetween(t,n){return new ce(ps(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 ce.empty;let r=n.openStart||0,a=n.openEnd||0;if(typeof r!="number"||typeof a!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new ce(ae.fromJSON(t,n.content),r,a)}static maxOpen(t,n=!0){let r=0,a=0;for(let o=t.firstChild;o&&!o.isLeaf&&(n||!o.type.spec.isolating);o=o.firstChild)r++;for(let o=t.lastChild;o&&!o.isLeaf&&(n||!o.type.spec.isolating);o=o.lastChild)a++;return new ce(t,r,a)}}ce.empty=new ce(ae.empty,0,0);function ps(e,t,n){let{index:r,offset:a}=e.findIndex(t),o=e.maybeChild(r),{index:l,offset:u}=e.findIndex(n);if(a==t||o.isText){if(u!=n&&!e.child(l).isText)throw new RangeError("Removing non-flat range");return e.cut(0,t).append(e.cut(n))}if(r!=l)throw new RangeError("Removing non-flat range");return e.replaceChild(r,o.copy(ps(o.content,t-a-1,n-a-1)))}function hs(e,t,n,r){let{index:a,offset:o}=e.findIndex(t),l=e.maybeChild(a);if(o==t||l.isText)return r&&!r.canReplace(a,a,n)?null:e.cut(0,t).append(n).append(e.cut(t));let u=hs(l.content,t-o-1,n);return u&&e.replaceChild(a,l.copy(u))}class Mn{constructor(t,n){this.schema=t,this.rules=n,this.tags=[],this.styles=[],n.forEach(r=>{r.tag?this.tags.push(r):r.style&&this.styles.push(r)}),this.normalizeLists=!this.tags.some(r=>{if(!/^(ul|ol)\b/.test(r.tag)||!r.node)return!1;let a=t.nodes[r.node];return a.contentMatch.matchType(a)})}parse(t,n={}){let r=new ys(this,n,!1);return r.addAll(t,n.from,n.to),r.finish()}parseSlice(t,n={}){let r=new ys(this,n,!0);return r.addAll(t,n.from,n.to),ce.maxOpen(r.finish())}matchTag(t,n,r){for(let a=r?this.tags.indexOf(r)+1:0;a<this.tags.length;a++){let o=this.tags[a];if(Sd(t,o.tag)&&(o.namespace===void 0||t.namespaceURI==o.namespace)&&(!o.context||n.matchesContext(o.context))){if(o.getAttrs){let l=o.getAttrs(t);if(l===!1)continue;o.attrs=l||void 0}return o}}}matchStyle(t,n,r,a){for(let o=a?this.styles.indexOf(a)+1:0;o<this.styles.length;o++){let l=this.styles[o],u=l.style;if(!(u.indexOf(t)!=0||l.context&&!r.matchesContext(l.context)||u.length>t.length&&(u.charCodeAt(t.length)!=61||u.slice(t.length+1)!=n))){if(l.getAttrs){let c=l.getAttrs(n);if(c===!1)continue;l.attrs=c||void 0}return l}}}static schemaRules(t){let n=[];function r(a){let o=a.priority==null?50:a.priority,l=0;for(;l<n.length;l++){let u=n[l];if((u.priority==null?50:u.priority)<o)break}n.splice(l,0,a)}for(let a in t.marks){let o=t.marks[a].spec.parseDOM;o&&o.forEach(l=>{r(l=bs(l)),l.mark||l.ignore||l.clearMark||(l.mark=a)})}for(let a in t.nodes){let o=t.nodes[a].spec.parseDOM;o&&o.forEach(l=>{r(l=bs(l)),l.node||l.ignore||l.mark||(l.node=a)})}return n}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new Mn(t,Mn.schemaRules(t)))}}const fs={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},wd={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},gs={ol:!0,ul:!0},An=1,zn=2,tn=4;function ms(e,t,n){return t!=null?(t?An:0)|(t==="full"?zn:0):e&&e.whitespace=="pre"?An|zn:n&~tn}class En{constructor(t,n,r,a,o,l,u){this.type=t,this.attrs=n,this.marks=r,this.pendingMarks=a,this.solid=o,this.options=u,this.content=[],this.activeMarks=Re.none,this.stashMarks=[],this.match=l||(u&tn?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(ae.from(t));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,a;return(a=r.findWrapping(t.type))?(this.match=r,a):null}}return this.match.findWrapping(t.type)}finish(t){if(!(this.options&An)){let r=this.content[this.content.length-1],a;if(r&&r.isText&&(a=/[ \t\r\n\u000c]+$/.exec(r.text))){let o=r;r.text.length==a[0].length?this.content.pop():this.content[this.content.length-1]=o.withText(o.text.slice(0,o.text.length-a[0].length))}}let n=ae.from(this.content);return!t&&this.match&&(n=n.append(this.match.fillBefore(ae.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,r=this.pendingMarks;n<r.length;n++){let a=r[n];(this.type?this.type.allowsMarkType(a.type):kd(a.type,t))&&!a.isInSet(this.activeMarks)&&(this.activeMarks=a.addToSet(this.activeMarks),this.pendingMarks=a.removeFromSet(this.pendingMarks))}}inlineContext(t){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:t.parentNode&&!fs.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class ys{constructor(t,n,r){this.parser=t,this.options=n,this.isOpen=r,this.open=0;let a=n.topNode,o,l=ms(null,n.preserveWhitespace,0)|(r?tn:0);a?o=new En(a.type,a.attrs,Re.none,Re.none,!0,n.topMatch||a.type.contentMatch,l):r?o=new En(null,null,Re.none,Re.none,!0,null,l):o=new En(t.schema.topNodeType,null,Re.none,Re.none,!0,null,l),this.nodes=[o],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 r=this.readStyles(_d(n));if(!r)return;let[a,o]=r,l=this.top;for(let u=0;u<o.length;u++)this.removePendingMark(o[u],l);for(let u=0;u<a.length;u++)this.addPendingMark(a[u]);this.addElement(t);for(let u=0;u<a.length;u++)this.removePendingMark(a[u],l);for(let u=0;u<o.length;u++)this.addPendingMark(o[u])}}}addTextNode(t){let n=t.nodeValue,r=this.top;if(r.options&zn||r.inlineContext(t)||/[^ \t\r\n\u000c]/.test(n)){if(r.options&An)r.options&zn?n=n.replace(/\r\n?/g,`
100
+ `}const bd=e=>t=>{const{componentSubType:n,value:r}=t;return n==="scatter"?yd(e,r):gd(e,r)};function vd({config:e}){return{trigger:"item",confine:!0,formatter:bd(e)}}const tn=b.forwardRef(function({value:t,onChange:n,...r},a){return i(s.TextInput,{ref:a,value:t,onChange:n,...r})}),Mr={fontSize:"14px",lineHeight:"32px",color:"#3D3E45",ul:{paddingLeft:"2em",margin:"6px 0 0"},p:{margin:0},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 cs(e,t,n){for(let r=0;;r++){if(r==e.childCount||r==t.childCount)return e.childCount==t.childCount?null:n;let a=e.child(r),o=t.child(r);if(a==o){n+=a.nodeSize;continue}if(!a.sameMarkup(o))return n;if(a.isText&&a.text!=o.text){for(let l=0;a.text[l]==o.text[l];l++)n++;return n}if(a.content.size||o.content.size){let l=cs(a.content,o.content,n+1);if(l!=null)return l}n+=a.nodeSize}}function ds(e,t,n,r){for(let a=e.childCount,o=t.childCount;;){if(a==0||o==0)return a==o?null:{a:n,b:r};let l=e.child(--a),u=t.child(--o),c=l.nodeSize;if(l==u){n-=c,r-=c;continue}if(!l.sameMarkup(u))return{a:n,b:r};if(l.isText&&l.text!=u.text){let d=0,f=Math.min(l.text.length,u.text.length);for(;d<f&&l.text[l.text.length-d-1]==u.text[u.text.length-d-1];)d++,n--,r--;return{a:n,b:r}}if(l.content.size||u.content.size){let d=ds(l.content,u.content,n-1,r-1);if(d)return d}n-=c,r-=c}}class ae{constructor(t,n){if(this.content=t,this.size=n||0,n==null)for(let r=0;r<t.length;r++)this.size+=t[r].nodeSize}nodesBetween(t,n,r,a=0,o){for(let l=0,u=0;u<n;l++){let c=this.content[l],d=u+c.nodeSize;if(d>t&&r(c,a+u,o||null,l)!==!1&&c.content.size){let f=u+1;c.nodesBetween(Math.max(0,t-f),Math.min(c.content.size,n-f),r,a+f)}u=d}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,n,r,a){let o="",l=!0;return this.nodesBetween(t,n,(u,c)=>{u.isText?(o+=u.text.slice(Math.max(t,c)-c,n-c),l=!r):u.isLeaf?(a?o+=typeof a=="function"?a(u):a:u.type.spec.leafText&&(o+=u.type.spec.leafText(u)),l=!r):!l&&u.isBlock&&(o+=r,l=!0)},0),o}append(t){if(!t.size)return this;if(!this.size)return t;let n=this.lastChild,r=t.firstChild,a=this.content.slice(),o=0;for(n.isText&&n.sameMarkup(r)&&(a[a.length-1]=n.withText(n.text+r.text),o=1);o<t.content.length;o++)a.push(t.content[o]);return new ae(a,this.size+t.size)}cut(t,n=this.size){if(t==0&&n==this.size)return this;let r=[],a=0;if(n>t)for(let o=0,l=0;l<n;o++){let u=this.content[o],c=l+u.nodeSize;c>t&&((l<t||c>n)&&(u.isText?u=u.cut(Math.max(0,t-l),Math.min(u.text.length,n-l)):u=u.cut(Math.max(0,t-l-1),Math.min(u.content.size,n-l-1))),r.push(u),a+=u.nodeSize),l=c}return new ae(r,a)}cutByIndex(t,n){return t==n?ae.empty:t==0&&n==this.content.length?this:new ae(this.content.slice(t,n))}replaceChild(t,n){let r=this.content[t];if(r==n)return this;let a=this.content.slice(),o=this.size+n.nodeSize-r.nodeSize;return a[t]=n,new ae(a,o)}addToStart(t){return new ae([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new ae(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,r=0;n<this.content.length;n++){let a=this.content[n];t(a,r,n),r+=a.nodeSize}}findDiffStart(t,n=0){return cs(this,t,n)}findDiffEnd(t,n=this.size,r=t.size){return ds(this,t,n,r)}findIndex(t,n=-1){if(t==0)return In(0,t);if(t==this.size)return In(this.content.length,t);if(t>this.size||t<0)throw new RangeError(`Position ${t} outside of fragment (${this})`);for(let r=0,a=0;;r++){let o=this.child(r),l=a+o.nodeSize;if(l>=t)return l==t||n>0?In(r+1,l):In(r,a);a=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 ae.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new ae(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return ae.empty;let n,r=0;for(let a=0;a<t.length;a++){let o=t[a];r+=o.nodeSize,a&&o.isText&&t[a-1].sameMarkup(o)?(n||(n=t.slice(0,a)),n[n.length-1]=o.withText(n[n.length-1].text+o.text)):n&&n.push(o)}return new ae(n||t,r)}static from(t){if(!t)return ae.empty;if(t instanceof ae)return t;if(Array.isArray(t))return this.fromArray(t);if(t.attrs)return new ae([t],t.nodeSize);throw new RangeError("Can not convert "+t+" to a Fragment"+(t.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}}ae.empty=new ae([],0);const Ar={index:0,offset:0};function In(e,t){return Ar.index=e,Ar.offset=t,Ar}function zr(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 r=0;r<e.length;r++)if(!zr(e[r],t[r]))return!1}else{for(let r in e)if(!(r in t)||!zr(e[r],t[r]))return!1;for(let r in t)if(!(r in e))return!1}return!0}class Ye{constructor(t,n){this.type=t,this.attrs=n}addToSet(t){let n,r=!1;for(let a=0;a<t.length;a++){let o=t[a];if(this.eq(o))return t;if(this.type.excludes(o.type))n||(n=t.slice(0,a));else{if(o.type.excludes(this.type))return t;!r&&o.type.rank>this.type.rank&&(n||(n=t.slice(0,a)),n.push(this),r=!0),n&&n.push(o)}}return n||(n=t.slice()),r||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&&zr(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 r=t.marks[n.type];if(!r)throw new RangeError(`There is no mark type ${n.type} in this schema`);return r.create(n.attrs)}static sameSet(t,n){if(t==n)return!0;if(t.length!=n.length)return!1;for(let r=0;r<t.length;r++)if(!t[r].eq(n[r]))return!1;return!0}static setFrom(t){if(!t||Array.isArray(t)&&t.length==0)return Ye.none;if(t instanceof Ye)return[t];let n=t.slice();return n.sort((r,a)=>r.type.rank-a.type.rank),n}}Ye.none=[];class xd extends Error{}class de{constructor(t,n,r){this.content=t,this.openStart=n,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,n){let r=hs(this.content,t+this.openStart,n);return r&&new de(r,this.openStart,this.openEnd)}removeBetween(t,n){return new de(ps(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 de.empty;let r=n.openStart||0,a=n.openEnd||0;if(typeof r!="number"||typeof a!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new de(ae.fromJSON(t,n.content),r,a)}static maxOpen(t,n=!0){let r=0,a=0;for(let o=t.firstChild;o&&!o.isLeaf&&(n||!o.type.spec.isolating);o=o.firstChild)r++;for(let o=t.lastChild;o&&!o.isLeaf&&(n||!o.type.spec.isolating);o=o.lastChild)a++;return new de(t,r,a)}}de.empty=new de(ae.empty,0,0);function ps(e,t,n){let{index:r,offset:a}=e.findIndex(t),o=e.maybeChild(r),{index:l,offset:u}=e.findIndex(n);if(a==t||o.isText){if(u!=n&&!e.child(l).isText)throw new RangeError("Removing non-flat range");return e.cut(0,t).append(e.cut(n))}if(r!=l)throw new RangeError("Removing non-flat range");return e.replaceChild(r,o.copy(ps(o.content,t-a-1,n-a-1)))}function hs(e,t,n,r){let{index:a,offset:o}=e.findIndex(t),l=e.maybeChild(a);if(o==t||l.isText)return r&&!r.canReplace(a,a,n)?null:e.cut(0,t).append(n).append(e.cut(t));let u=hs(l.content,t-o-1,n);return u&&e.replaceChild(a,l.copy(u))}class Mn{constructor(t,n){this.schema=t,this.rules=n,this.tags=[],this.styles=[],n.forEach(r=>{r.tag?this.tags.push(r):r.style&&this.styles.push(r)}),this.normalizeLists=!this.tags.some(r=>{if(!/^(ul|ol)\b/.test(r.tag)||!r.node)return!1;let a=t.nodes[r.node];return a.contentMatch.matchType(a)})}parse(t,n={}){let r=new ys(this,n,!1);return r.addAll(t,n.from,n.to),r.finish()}parseSlice(t,n={}){let r=new ys(this,n,!0);return r.addAll(t,n.from,n.to),de.maxOpen(r.finish())}matchTag(t,n,r){for(let a=r?this.tags.indexOf(r)+1:0;a<this.tags.length;a++){let o=this.tags[a];if(Sd(t,o.tag)&&(o.namespace===void 0||t.namespaceURI==o.namespace)&&(!o.context||n.matchesContext(o.context))){if(o.getAttrs){let l=o.getAttrs(t);if(l===!1)continue;o.attrs=l||void 0}return o}}}matchStyle(t,n,r,a){for(let o=a?this.styles.indexOf(a)+1:0;o<this.styles.length;o++){let l=this.styles[o],u=l.style;if(!(u.indexOf(t)!=0||l.context&&!r.matchesContext(l.context)||u.length>t.length&&(u.charCodeAt(t.length)!=61||u.slice(t.length+1)!=n))){if(l.getAttrs){let c=l.getAttrs(n);if(c===!1)continue;l.attrs=c||void 0}return l}}}static schemaRules(t){let n=[];function r(a){let o=a.priority==null?50:a.priority,l=0;for(;l<n.length;l++){let u=n[l];if((u.priority==null?50:u.priority)<o)break}n.splice(l,0,a)}for(let a in t.marks){let o=t.marks[a].spec.parseDOM;o&&o.forEach(l=>{r(l=bs(l)),l.mark||l.ignore||l.clearMark||(l.mark=a)})}for(let a in t.nodes){let o=t.nodes[a].spec.parseDOM;o&&o.forEach(l=>{r(l=bs(l)),l.node||l.ignore||l.mark||(l.node=a)})}return n}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new Mn(t,Mn.schemaRules(t)))}}const fs={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},wd={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},gs={ol:!0,ul:!0},An=1,zn=2,nn=4;function ms(e,t,n){return t!=null?(t?An:0)|(t==="full"?zn:0):e&&e.whitespace=="pre"?An|zn:n&~nn}class En{constructor(t,n,r,a,o,l,u){this.type=t,this.attrs=n,this.marks=r,this.pendingMarks=a,this.solid=o,this.options=u,this.content=[],this.activeMarks=Ye.none,this.stashMarks=[],this.match=l||(u&nn?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(ae.from(t));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,a;return(a=r.findWrapping(t.type))?(this.match=r,a):null}}return this.match.findWrapping(t.type)}finish(t){if(!(this.options&An)){let r=this.content[this.content.length-1],a;if(r&&r.isText&&(a=/[ \t\r\n\u000c]+$/.exec(r.text))){let o=r;r.text.length==a[0].length?this.content.pop():this.content[this.content.length-1]=o.withText(o.text.slice(0,o.text.length-a[0].length))}}let n=ae.from(this.content);return!t&&this.match&&(n=n.append(this.match.fillBefore(ae.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,r=this.pendingMarks;n<r.length;n++){let a=r[n];(this.type?this.type.allowsMarkType(a.type):kd(a.type,t))&&!a.isInSet(this.activeMarks)&&(this.activeMarks=a.addToSet(this.activeMarks),this.pendingMarks=a.removeFromSet(this.pendingMarks))}}inlineContext(t){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:t.parentNode&&!fs.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class ys{constructor(t,n,r){this.parser=t,this.options=n,this.isOpen=r,this.open=0;let a=n.topNode,o,l=ms(null,n.preserveWhitespace,0)|(r?nn:0);a?o=new En(a.type,a.attrs,Ye.none,Ye.none,!0,n.topMatch||a.type.contentMatch,l):r?o=new En(null,null,Ye.none,Ye.none,!0,null,l):o=new En(t.schema.topNodeType,null,Ye.none,Ye.none,!0,null,l),this.nodes=[o],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 r=this.readStyles(_d(n));if(!r)return;let[a,o]=r,l=this.top;for(let u=0;u<o.length;u++)this.removePendingMark(o[u],l);for(let u=0;u<a.length;u++)this.addPendingMark(a[u]);this.addElement(t);for(let u=0;u<a.length;u++)this.removePendingMark(a[u],l);for(let u=0;u<o.length;u++)this.addPendingMark(o[u])}}}addTextNode(t){let n=t.nodeValue,r=this.top;if(r.options&zn||r.inlineContext(t)||/[^ \t\r\n\u000c]/.test(n)){if(r.options&An)r.options&zn?n=n.replace(/\r\n?/g,`
101
101
  `):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 a=r.content[r.content.length-1],o=t.previousSibling;(!a||o&&o.nodeName=="BR"||a.isText&&/[ \t\r\n\u000c]$/.test(a.text))&&(n=n.slice(1))}n&&this.insertNode(this.parser.schema.text(n)),this.findInText(t)}else this.findInside(t)}addElement(t,n){let r=t.nodeName.toLowerCase(),a;gs.hasOwnProperty(r)&&this.parser.normalizeLists&&Cd(t);let o=this.options.ruleFromNode&&this.options.ruleFromNode(t)||(a=this.parser.matchTag(t,this,n));if(o?o.ignore:wd.hasOwnProperty(r))this.findInside(t),this.ignoreFallback(t);else if(!o||o.skip||o.closeParent){o&&o.closeParent?this.open=Math.max(0,this.open-1):o&&o.skip.nodeType&&(t=o.skip);let l,u=this.top,c=this.needsBlock;if(fs.hasOwnProperty(r))u.content.length&&u.content[0].isInline&&this.open&&(this.open--,u=this.top),l=!0,u.type||(this.needsBlock=!0);else if(!t.firstChild){this.leafFallback(t);return}this.addAll(t),l&&this.sync(u),this.needsBlock=c}else this.addElementByRule(t,o,o.consuming===!1?a:void 0)}leafFallback(t){t.nodeName=="BR"&&this.top.type&&this.top.type.inlineContent&&this.addTextNode(t.ownerDocument.createTextNode(`
102
- `))}ignoreFallback(t){t.nodeName=="BR"&&(!this.top.type||!this.top.type.inlineContent)&&this.findPlace(this.parser.schema.text("-"))}readStyles(t){let n=Re.none,r=Re.none;for(let a=0;a<t.length;a+=2)for(let o=void 0;;){let l=this.parser.matchStyle(t[a],t[a+1],this,o);if(!l)break;if(l.ignore)return null;if(l.clearMark?this.top.pendingMarks.concat(this.top.activeMarks).forEach(u=>{l.clearMark(u)&&(r=u.addToSet(r))}):n=this.parser.schema.marks[l.mark].create(l.attrs).addToSet(n),l.consuming===!1)o=l;else break}return[n,r]}addElementByRule(t,n,r){let a,o,l;n.node?(o=this.parser.schema.nodes[n.node],o.isLeaf?this.insertNode(o.create(n.attrs))||this.leafFallback(t):a=this.enter(o,n.attrs||null,n.preserveWhitespace)):(l=this.parser.schema.marks[n.mark].create(n.attrs),this.addPendingMark(l));let u=this.top;if(o&&o.isLeaf)this.findInside(t);else if(r)this.addElement(t,r);else if(n.getContent)this.findInside(t),n.getContent(t,this.parser.schema).forEach(c=>this.insertNode(c));else{let c=t;typeof n.contentElement=="string"?c=t.querySelector(n.contentElement):typeof n.contentElement=="function"?c=n.contentElement(t):n.contentElement&&(c=n.contentElement),this.findAround(t,c,!0),this.addAll(c)}a&&this.sync(u)&&this.open--,l&&this.removePendingMark(l,u)}addAll(t,n,r){let a=n||0;for(let o=n?t.childNodes[n]:t.firstChild,l=r==null?null:t.childNodes[r];o!=l;o=o.nextSibling,++a)this.findAtPoint(t,a),this.addDOM(o);this.findAtPoint(t,a)}findPlace(t){let n,r;for(let a=this.open;a>=0;a--){let o=this.nodes[a],l=o.findWrapping(t);if(l&&(!n||n.length>l.length)&&(n=l,r=o,!l.length)||o.solid)break}if(!n)return!1;this.sync(r);for(let a=0;a<n.length;a++)this.enterInner(n[a],null,!1);return!0}insertNode(t){if(t.isInline&&this.needsBlock&&!this.top.type){let n=this.textblockFromContext();n&&this.enterInner(n)}if(this.findPlace(t)){this.closeExtra();let n=this.top;n.applyPending(t.type),n.match&&(n.match=n.match.matchType(t.type));let r=n.activeMarks;for(let a=0;a<t.marks.length;a++)(!n.type||n.type.allowsMarkType(t.marks[a].type))&&(r=t.marks[a].addToSet(r));return n.content.push(t.mark(r)),!0}return!1}enter(t,n,r){let a=this.findPlace(t.create(n));return a&&this.enterInner(t,n,!0,r),a}enterInner(t,n=null,r=!1,a){this.closeExtra();let o=this.top;o.applyPending(t),o.match=o.match&&o.match.matchType(t);let l=ms(t,a,o.options);o.options&tn&&o.content.length==0&&(l|=tn),this.nodes.push(new En(t,n,o.activeMarks,o.pendingMarks,r,null,l)),this.open++}closeExtra(t=!1){let n=this.nodes.length-1;if(n>this.open){for(;n>this.open;n--)this.nodes[n-1].content.push(this.nodes[n].finish(t));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(this.isOpen||this.options.topOpen)}sync(t){for(let n=this.open;n>=0;n--)if(this.nodes[n]==t)return this.open=n,!0;return!1}get currentPos(){this.closeExtra();let t=0;for(let n=this.open;n>=0;n--){let r=this.nodes[n].content;for(let a=r.length-1;a>=0;a--)t+=r[a].nodeSize;n&&t++}return t}findAtPoint(t,n){if(this.find)for(let r=0;r<this.find.length;r++)this.find[r].node==t&&this.find[r].offset==n&&(this.find[r].pos=this.currentPos)}findInside(t){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].pos==null&&t.nodeType==1&&t.contains(this.find[n].node)&&(this.find[n].pos=this.currentPos)}findAround(t,n,r){if(t!=n&&this.find)for(let a=0;a<this.find.length;a++)this.find[a].pos==null&&t.nodeType==1&&t.contains(this.find[a].node)&&n.compareDocumentPosition(this.find[a].node)&(r?2:4)&&(this.find[a].pos=this.currentPos)}findInText(t){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].node==t&&(this.find[n].pos=this.currentPos-(t.nodeValue.length-this.find[n].offset))}matchesContext(t){if(t.indexOf("|")>-1)return t.split(/\s*\|\s*/).some(this.matchesContext,this);let n=t.split("/"),r=this.options.context,a=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),o=-(r?r.depth+1:0)+(a?0:1),l=(u,c)=>{for(;u>=0;u--){let d=n[u];if(d==""){if(u==n.length-1||u==0)continue;for(;c>=o;c--)if(l(u-1,c))return!0;return!1}else{let f=c>0||c==0&&a?this.nodes[c].type:r&&c>=o?r.node(c-o).type:null;if(!f||f.name!=d&&f.groups.indexOf(d)==-1)return!1;c--}}return!0};return l(n.length-1,this.open)}textblockFromContext(){let t=this.options.context;if(t)for(let n=t.depth;n>=0;n--){let r=t.node(n).contentMatchAt(t.indexAfter(n)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let n in this.parser.schema.nodes){let r=this.parser.schema.nodes[n];if(r.isTextblock&&r.defaultAttrs)return r}}addPendingMark(t){let n=Td(t,this.top.pendingMarks);n&&this.top.stashMarks.push(n),this.top.pendingMarks=t.addToSet(this.top.pendingMarks)}removePendingMark(t,n){for(let r=this.open;r>=0;r--){let a=this.nodes[r];if(a.pendingMarks.lastIndexOf(t)>-1)a.pendingMarks=t.removeFromSet(a.pendingMarks);else{a.activeMarks=t.removeFromSet(a.activeMarks);let l=a.popFromStashMark(t);l&&a.type&&a.type.allowsMarkType(l.type)&&(a.activeMarks=l.addToSet(a.activeMarks))}if(a==n)break}}}function Cd(e){for(let t=e.firstChild,n=null;t;t=t.nextSibling){let r=t.nodeType==1?t.nodeName.toLowerCase():null;r&&gs.hasOwnProperty(r)&&n?(n.appendChild(t),t=n):r=="li"?n=t:r&&(n=null)}}function Sd(e,t){return(e.matches||e.msMatchesSelector||e.webkitMatchesSelector||e.mozMatchesSelector).call(e,t)}function _d(e){let t=/\s*([\w-]+)\s*:\s*([^;]+)/g,n,r=[];for(;n=t.exec(e);)r.push(n[1],n[2].trim());return r}function bs(e){let t={};for(let n in e)t[n]=e[n];return t}function kd(e,t){let n=t.schema.nodes;for(let r in n){let a=n[r];if(!a.allowsMarkType(e))continue;let o=[],l=u=>{o.push(u);for(let c=0;c<u.edgeCount;c++){let{type:d,next:f}=u.edge(c);if(d==t||o.indexOf(f)<0&&l(f))return!0}};if(l(a.contentMatch))return!0}}function Td(e,t){for(let n=0;n<t.length;n++)if(e.eq(t[n]))return t[n]}const vs=65535,xs=Math.pow(2,16);function Dd(e,t){return e+t*xs}function ws(e){return e&vs}function Id(e){return(e-(e&vs))/xs}const Cs=1,Ss=2,$n=4,_s=8;class ks{constructor(t,n,r){this.pos=t,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&_s)>0}get deletedBefore(){return(this.delInfo&(Cs|$n))>0}get deletedAfter(){return(this.delInfo&(Ss|$n))>0}get deletedAcross(){return(this.delInfo&$n)>0}}class Je{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&Je.empty)return Je.empty}recover(t){let n=0,r=ws(t);if(!this.inverted)for(let a=0;a<r;a++)n+=this.ranges[a*3+2]-this.ranges[a*3+1];return this.ranges[r*3]+n+Id(t)}mapResult(t,n=1){return this._map(t,n,!1)}map(t,n=1){return this._map(t,n,!0)}_map(t,n,r){let a=0,o=this.inverted?2:1,l=this.inverted?1:2;for(let u=0;u<this.ranges.length;u+=3){let c=this.ranges[u]-(this.inverted?a:0);if(c>t)break;let d=this.ranges[u+o],f=this.ranges[u+l],h=c+d;if(t<=h){let g=d?t==c?-1:t==h?1:n:n,m=c+a+(g<0?0:f);if(r)return m;let C=t==(n<0?c:h)?null:Dd(u/3,t-c),w=t==c?Ss:t==h?Cs:$n;return(n<0?t!=c:t!=h)&&(w|=_s),new ks(m,w,C)}a+=f-d}return r?t+a:new ks(t+a,0,null)}touches(t,n){let r=0,a=ws(n),o=this.inverted?2:1,l=this.inverted?1:2;for(let u=0;u<this.ranges.length;u+=3){let c=this.ranges[u]-(this.inverted?r:0);if(c>t)break;let d=this.ranges[u+o],f=c+d;if(t<=f&&u==a*3)return!0;r+=this.ranges[u+l]-d}return!1}forEach(t){let n=this.inverted?2:1,r=this.inverted?1:2;for(let a=0,o=0;a<this.ranges.length;a+=3){let l=this.ranges[a],u=l-(this.inverted?o:0),c=l+(this.inverted?0:o),d=this.ranges[a+n],f=this.ranges[a+r];t(u,u+d,c,c+f),o+=f-d}}invert(){return new Je(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(t){return t==0?Je.empty:new Je(t<0?[0,-t,0]:[0,0,t])}}Je.empty=new Je([]);const Er=Object.create(null);class Ge{getMap(){return Je.empty}merge(t){return null}static fromJSON(t,n){if(!n||!n.stepType)throw new RangeError("Invalid input for Step.fromJSON");let r=Er[n.stepType];if(!r)throw new RangeError(`No step type ${n.stepType} defined`);return r.fromJSON(t,n)}static jsonID(t,n){if(t in Er)throw new RangeError("Duplicate use of step JSON ID "+t);return Er[t]=n,n.prototype.jsonID=t,n}}class Te{constructor(t,n){this.doc=t,this.failed=n}static ok(t){return new Te(t,null)}static fail(t){return new Te(null,t)}static fromReplace(t,n,r,a){try{return Te.ok(t.replace(n,r,a))}catch(o){if(o instanceof xd)return Te.fail(o.message);throw o}}}function $r(e,t,n){let r=[];for(let a=0;a<e.childCount;a++){let o=e.child(a);o.content.size&&(o=o.copy($r(o.content,t,o))),o.isInline&&(o=t(o,n,a)),r.push(o)}return ae.fromArray(r)}class It extends Ge{constructor(t,n,r){super(),this.from=t,this.to=n,this.mark=r}apply(t){let n=t.slice(this.from,this.to),r=t.resolve(this.from),a=r.node(r.sharedDepth(this.to)),o=new ce($r(n.content,(l,u)=>!l.isAtom||!u.type.allowsMarkType(this.mark.type)?l:l.mark(this.mark.addToSet(l.marks)),a),n.openStart,n.openEnd);return Te.fromReplace(t,this.from,this.to,o)}invert(){return new Mt(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new It(n.pos,r.pos,this.mark)}merge(t){return t instanceof It&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new It(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"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 It(n.from,n.to,t.markFromJSON(n.mark))}}Ge.jsonID("addMark",It);class Mt extends Ge{constructor(t,n,r){super(),this.from=t,this.to=n,this.mark=r}apply(t){let n=t.slice(this.from,this.to),r=new ce($r(n.content,a=>a.mark(this.mark.removeFromSet(a.marks)),t),n.openStart,n.openEnd);return Te.fromReplace(t,this.from,this.to,r)}invert(){return new It(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new Mt(n.pos,r.pos,this.mark)}merge(t){return t instanceof Mt&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new Mt(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"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 Mt(n.from,n.to,t.markFromJSON(n.mark))}}Ge.jsonID("removeMark",Mt);class At extends Ge{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return Te.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return Te.fromReplace(t,this.pos,this.pos+1,new ce(ae.from(r),0,n.isLeaf?0:1))}invert(t){let n=t.nodeAt(this.pos);if(n){let r=this.mark.addToSet(n.marks);if(r.length==n.marks.length){for(let a=0;a<n.marks.length;a++)if(!n.marks[a].isInSet(r))return new At(this.pos,n.marks[a]);return new At(this.pos,this.mark)}}return new nn(this.pos,this.mark)}map(t){let n=t.mapResult(this.pos,1);return n.deletedAfter?null:new At(n.pos,this.mark)}toJSON(){return{stepType:"addNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(t,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");return new At(n.pos,t.markFromJSON(n.mark))}}Ge.jsonID("addNodeMark",At);class nn extends Ge{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return Te.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.removeFromSet(n.marks));return Te.fromReplace(t,this.pos,this.pos+1,new ce(ae.from(r),0,n.isLeaf?0:1))}invert(t){let n=t.nodeAt(this.pos);return!n||!this.mark.isInSet(n.marks)?this:new At(this.pos,this.mark)}map(t){let n=t.mapResult(this.pos,1);return n.deletedAfter?null:new nn(n.pos,this.mark)}toJSON(){return{stepType:"removeNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(t,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");return new nn(n.pos,t.markFromJSON(n.mark))}}Ge.jsonID("removeNodeMark",nn);class ot extends Ge{constructor(t,n,r,a=!1){super(),this.from=t,this.to=n,this.slice=r,this.structure=a}apply(t){return this.structure&&Lr(t,this.from,this.to)?Te.fail("Structure replace would overwrite content"):Te.fromReplace(t,this.from,this.to,this.slice)}getMap(){return new Je([this.from,this.to-this.from,this.slice.size])}invert(t){return new ot(this.from,this.from+this.slice.size,t.slice(this.from,this.to))}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1);return n.deletedAcross&&r.deletedAcross?null:new ot(n.pos,Math.max(n.pos,r.pos),this.slice)}merge(t){if(!(t instanceof ot)||t.structure||this.structure)return null;if(this.from+this.slice.size==t.from&&!this.slice.openEnd&&!t.slice.openStart){let n=this.slice.size+t.slice.size==0?ce.empty:new ce(this.slice.content.append(t.slice.content),this.slice.openStart,t.slice.openEnd);return new ot(this.from,this.to+(t.to-t.from),n,this.structure)}else if(t.to==this.from&&!this.slice.openStart&&!t.slice.openEnd){let n=this.slice.size+t.slice.size==0?ce.empty:new ce(t.slice.content.append(this.slice.content),t.slice.openStart,this.slice.openEnd);return new ot(t.from,this.to,n,this.structure)}else return null}toJSON(){let t={stepType:"replace",from:this.from,to:this.to};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for ReplaceStep.fromJSON");return new ot(n.from,n.to,ce.fromJSON(t,n.slice),!!n.structure)}}Ge.jsonID("replace",ot);class zt extends Ge{constructor(t,n,r,a,o,l,u=!1){super(),this.from=t,this.to=n,this.gapFrom=r,this.gapTo=a,this.slice=o,this.insert=l,this.structure=u}apply(t){if(this.structure&&(Lr(t,this.from,this.gapFrom)||Lr(t,this.gapTo,this.to)))return Te.fail("Structure gap-replace would overwrite content");let n=t.slice(this.gapFrom,this.gapTo);if(n.openStart||n.openEnd)return Te.fail("Gap is not a flat range");let r=this.slice.insertAt(this.insert,n.content);return r?Te.fromReplace(t,this.from,this.to,r):Te.fail("Content does not fit in gap")}getMap(){return new Je([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(t){let n=this.gapTo-this.gapFrom;return new zt(this.from,this.from+this.slice.size+n,this.from+this.insert,this.from+this.insert+n,t.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1),a=t.map(this.gapFrom,-1),o=t.map(this.gapTo,1);return n.deletedAcross&&r.deletedAcross||a<n.pos||o>r.pos?null:new zt(n.pos,r.pos,a,o,this.slice,this.insert,this.structure)}toJSON(){let t={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number"||typeof n.gapFrom!="number"||typeof n.gapTo!="number"||typeof n.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new zt(n.from,n.to,n.gapFrom,n.gapTo,ce.fromJSON(t,n.slice),n.insert,!!n.structure)}}Ge.jsonID("replaceAround",zt);function Lr(e,t,n){let r=e.resolve(t),a=n-t,o=r.depth;for(;a>0&&o>0&&r.indexAfter(o)==r.node(o).childCount;)o--,a--;if(a>0){let l=r.node(o).maybeChild(r.indexAfter(o));for(;a>0;){if(!l||l.isLeaf)return!0;l=l.firstChild,a--}}return!1}function Md(e,t,n){return(t==0||e.canReplace(t,e.childCount))&&(n==e.childCount||e.canReplace(0,n))}function Ad(e){let n=e.parent.content.cutByIndex(e.startIndex,e.endIndex);for(let r=e.depth;;--r){let a=e.$from.node(r),o=e.$from.index(r),l=e.$to.indexAfter(r);if(r<e.depth&&a.canReplace(o,l,n))return r;if(r==0||a.type.spec.isolating||!Md(a,o,l))break}return null}function Ln(e,t,n=1,r){let a=e.resolve(t),o=a.depth-n,l=r&&r[r.length-1]||a.parent;if(o<0||a.parent.type.spec.isolating||!a.parent.canReplace(a.index(),a.parent.childCount)||!l.type.validContent(a.parent.content.cutByIndex(a.index(),a.parent.childCount)))return!1;for(let d=a.depth-1,f=n-2;d>o;d--,f--){let h=a.node(d),g=a.index(d);if(h.type.spec.isolating)return!1;let m=h.content.cutByIndex(g,h.childCount),C=r&&r[f+1];C&&(m=m.replaceChild(0,C.type.create(C.attrs)));let w=r&&r[f]||h;if(!h.canReplace(g+1,h.childCount)||!w.type.validContent(m))return!1}let u=a.indexAfter(o),c=r&&r[0];return a.node(o).canReplaceWith(u,u,c?c.type:a.node(o+1).type)}function Ts(e,t){let n=e.resolve(t),r=n.index();return zd(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function zd(e,t){return!!(e&&t&&!e.isLeaf&&e.canAppend(t))}class rn extends Ge{constructor(t,n,r){super(),this.pos=t,this.attr=n,this.value=r}apply(t){let n=t.nodeAt(this.pos);if(!n)return Te.fail("No node at attribute step's position");let r=Object.create(null);for(let o in n.attrs)r[o]=n.attrs[o];r[this.attr]=this.value;let a=n.type.create(r,null,n.marks);return Te.fromReplace(t,this.pos,this.pos+1,new ce(ae.from(a),0,n.isLeaf?0:1))}getMap(){return Je.empty}invert(t){return new rn(this.pos,this.attr,t.nodeAt(this.pos).attrs[this.attr])}map(t){let n=t.mapResult(this.pos,1);return n.deletedAfter?null:new rn(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(t,n){if(typeof n.pos!="number"||typeof n.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new rn(n.pos,n.attr,n.value)}}Ge.jsonID("attr",rn);let an=class extends Error{};an=function e(t){let n=Error.call(this,t);return n.__proto__=e.prototype,n},an.prototype=Object.create(Error.prototype),an.prototype.constructor=an,an.prototype.name="TransformError";const Or=Object.create(null);class fe{constructor(t,n,r){this.$anchor=t,this.$head=n,this.ranges=r||[new Ed(t.min(n),t.max(n))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let t=this.ranges;for(let n=0;n<t.length;n++)if(t[n].$from.pos!=t[n].$to.pos)return!1;return!0}content(){return this.$from.doc.slice(this.from,this.to,!0)}replace(t,n=ce.empty){let r=n.content.lastChild,a=null;for(let u=0;u<n.openEnd;u++)a=r,r=r.lastChild;let o=t.steps.length,l=this.ranges;for(let u=0;u<l.length;u++){let{$from:c,$to:d}=l[u],f=t.mapping.slice(o);t.replaceRange(f.map(c.pos),f.map(d.pos),u?ce.empty:n),u==0&&Ms(t,o,(r?r.isInline:a&&a.isTextblock)?-1:1)}}replaceWith(t,n){let r=t.steps.length,a=this.ranges;for(let o=0;o<a.length;o++){let{$from:l,$to:u}=a[o],c=t.mapping.slice(r),d=c.map(l.pos),f=c.map(u.pos);o?t.deleteRange(d,f):(t.replaceRangeWith(d,f,n),Ms(t,r,n.isInline?-1:1))}}static findFrom(t,n,r=!1){let a=t.parent.inlineContent?new De(t):Bt(t.node(0),t.parent,t.pos,t.index(),n,r);if(a)return a;for(let o=t.depth-1;o>=0;o--){let l=n<0?Bt(t.node(0),t.node(o),t.before(o+1),t.index(o),n,r):Bt(t.node(0),t.node(o),t.after(o+1),t.index(o)+1,n,r);if(l)return l}return null}static near(t,n=1){return this.findFrom(t,n)||this.findFrom(t,-n)||new ht(t.node(0))}static atStart(t){return Bt(t,t,0,0,1)||new ht(t)}static atEnd(t){return Bt(t,t,t.content.size,t.childCount,-1)||new ht(t)}static fromJSON(t,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=Or[n.type];if(!r)throw new RangeError(`No selection type ${n.type} defined`);return r.fromJSON(t,n)}static jsonID(t,n){if(t in Or)throw new RangeError("Duplicate use of selection JSON ID "+t);return Or[t]=n,n.prototype.jsonID=t,n}getBookmark(){return De.between(this.$anchor,this.$head).getBookmark()}}fe.prototype.visible=!0;class Ed{constructor(t,n){this.$from=t,this.$to=n}}let Ds=!1;function Is(e){!Ds&&!e.parent.inlineContent&&(Ds=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+e.parent.type.name+")"))}class De extends fe{constructor(t,n=t){Is(t),Is(n),super(t,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(t,n){let r=t.resolve(n.map(this.head));if(!r.parent.inlineContent)return fe.near(r);let a=t.resolve(n.map(this.anchor));return new De(a.parent.inlineContent?a:r,r)}replace(t,n=ce.empty){if(super.replace(t,n),n==ce.empty){let r=this.$from.marksAcross(this.$to);r&&t.ensureMarks(r)}}eq(t){return t instanceof De&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new On(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(t,n){if(typeof n.anchor!="number"||typeof n.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new De(t.resolve(n.anchor),t.resolve(n.head))}static create(t,n,r=n){let a=t.resolve(n);return new this(a,r==n?a:t.resolve(r))}static between(t,n,r){let a=t.pos-n.pos;if((!r||a)&&(r=a>=0?1:-1),!n.parent.inlineContent){let o=fe.findFrom(n,r,!0)||fe.findFrom(n,-r,!0);if(o)n=o.$head;else return fe.near(n,r)}return t.parent.inlineContent||(a==0?t=n:(t=(fe.findFrom(t,-r,!0)||fe.findFrom(t,r,!0)).$anchor,t.pos<n.pos!=a<0&&(t=n))),new De(t,n)}}fe.jsonID("text",De);class On{constructor(t,n){this.anchor=t,this.head=n}map(t){return new On(t.map(this.anchor),t.map(this.head))}resolve(t){return De.between(t.resolve(this.anchor),t.resolve(this.head))}}class Ye extends fe{constructor(t){let n=t.nodeAfter,r=t.node(0).resolve(t.pos+n.nodeSize);super(t,r),this.node=n}map(t,n){let{deleted:r,pos:a}=n.mapResult(this.anchor),o=t.resolve(a);return r?fe.near(o):new Ye(o)}content(){return new ce(ae.from(this.node),0,0)}eq(t){return t instanceof Ye&&t.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new Pr(this.anchor)}static fromJSON(t,n){if(typeof n.anchor!="number")throw new RangeError("Invalid input for NodeSelection.fromJSON");return new Ye(t.resolve(n.anchor))}static create(t,n){return new Ye(t.resolve(n))}static isSelectable(t){return!t.isText&&t.type.spec.selectable!==!1}}Ye.prototype.visible=!1,fe.jsonID("node",Ye);class Pr{constructor(t){this.anchor=t}map(t){let{deleted:n,pos:r}=t.mapResult(this.anchor);return n?new On(r,r):new Pr(r)}resolve(t){let n=t.resolve(this.anchor),r=n.nodeAfter;return r&&Ye.isSelectable(r)?new Ye(n):fe.near(n)}}class ht extends fe{constructor(t){super(t.resolve(0),t.resolve(t.content.size))}replace(t,n=ce.empty){if(n==ce.empty){t.delete(0,t.doc.content.size);let r=fe.atStart(t.doc);r.eq(t.selection)||t.setSelection(r)}else super.replace(t,n)}toJSON(){return{type:"all"}}static fromJSON(t){return new ht(t)}map(t){return new ht(t)}eq(t){return t instanceof ht}getBookmark(){return $d}}fe.jsonID("all",ht);const $d={map(){return this},resolve(e){return new ht(e)}};function Bt(e,t,n,r,a,o=!1){if(t.inlineContent)return De.create(e,n);for(let l=r-(a>0?0:1);a>0?l<t.childCount:l>=0;l+=a){let u=t.child(l);if(u.isAtom){if(!o&&Ye.isSelectable(u))return Ye.create(e,n-(a<0?u.nodeSize:0))}else{let c=Bt(e,u,n+a,a<0?u.childCount:0,a,o);if(c)return c}n+=u.nodeSize*a}return null}function Ms(e,t,n){let r=e.steps.length-1;if(r<t)return;let a=e.steps[r];if(!(a instanceof ot||a instanceof zt))return;let o=e.mapping.maps[r],l;o.forEach((u,c,d,f)=>{l==null&&(l=f)}),e.setSelection(fe.near(e.doc.resolve(l),n))}function As(e,t){return!t||!e?e:e.bind(t)}class Pn{constructor(t,n,r){this.name=t,this.init=As(n.init,r),this.apply=As(n.apply,r)}}new Pn("doc",{init(e){return e.doc||e.schema.topNodeType.createAndFill()},apply(e){return e.doc}}),new Pn("selection",{init(e,t){return e.selection||fe.atStart(t.doc)},apply(e){return e.selection}}),new Pn("storedMarks",{init(e){return e.storedMarks||null},apply(e,t,n,r){return r.selection.$cursor?e.storedMarks:null}}),new Pn("scrollToSelection",{init(){return 0},apply(e,t){return e.scrolledIntoView?t+1:t}});function zs(e,t,n){for(let r in e){let a=e[r];a instanceof Function?a=a.bind(t):r=="handleDOMEvents"&&(a=zs(a,t,{})),n[r]=a}return n}class sn{constructor(t){this.spec=t,this.props={},t.props&&zs(t.props,this,this.props),this.key=t.key?t.key.key:Es("plugin")}getState(t){return t[this.key]}}const Br=Object.create(null);function Es(e){return e in Br?e+"$"+ ++Br[e]:(Br[e]=0,e+"$")}class on{constructor(t="key"){this.key=Es(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}function $s(e){const{state:t,transaction:n}=e;let{selection:r}=n,{doc:a}=n,{storedMarks:o}=n;return{...t,apply:t.apply.bind(t),applyTransaction:t.applyTransaction.bind(t),filterTransaction:t.filterTransaction,plugins:t.plugins,schema:t.schema,reconfigure:t.reconfigure.bind(t),toJSON:t.toJSON.bind(t),get storedMarks(){return o},get selection(){return r},get doc(){return a},get tr(){return r=n.selection,a=n.doc,o=n.storedMarks,n}}}class Ld{constructor(t){this.editor=t.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=t.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:t,editor:n,state:r}=this,{view:a}=n,{tr:o}=r,l=this.buildProps(o);return Object.fromEntries(Object.entries(t).map(([u,c])=>[u,(...f)=>{const h=c(...f)(l);return!o.getMeta("preventDispatch")&&!this.hasCustomState&&a.dispatch(o),h}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,n=!0){const{rawCommands:r,editor:a,state:o}=this,{view:l}=a,u=[],c=!!t,d=t||o.tr,f=()=>(!c&&n&&!d.getMeta("preventDispatch")&&!this.hasCustomState&&l.dispatch(d),u.every(g=>g===!0)),h={...Object.fromEntries(Object.entries(r).map(([g,m])=>[g,(...w)=>{const _=this.buildProps(d,n),D=m(...w)(_);return u.push(D),h}])),run:f};return h}createCan(t){const{rawCommands:n,state:r}=this,a=!1,o=t||r.tr,l=this.buildProps(o,a);return{...Object.fromEntries(Object.entries(n).map(([c,d])=>[c,(...f)=>d(...f)({...l,dispatch:void 0})])),chain:()=>this.createChain(o,a)}}buildProps(t,n=!0){const{rawCommands:r,editor:a,state:o}=this,{view:l}=a;o.storedMarks&&t.setStoredMarks(o.storedMarks);const u={tr:t,editor:a,view:l,state:$s({state:o,transaction:t}),dispatch:n?()=>{}:void 0,chain:()=>this.createChain(t),can:()=>this.createCan(t),get commands(){return Object.fromEntries(Object.entries(r).map(([c,d])=>[c,(...f)=>d(...f)(u)]))}};return u}}function vt(e,t,n){return e.config[t]===void 0&&e.parent?vt(e.parent,t,n):typeof e.config[t]=="function"?e.config[t].bind({...n,parent:e.parent?vt(e.parent,t,n):null}):e.config[t]}function Od(e){const t=e.filter(a=>a.type==="extension"),n=e.filter(a=>a.type==="node"),r=e.filter(a=>a.type==="mark");return{baseExtensions:t,nodeExtensions:n,markExtensions:r}}function Le(e,t){if(typeof e=="string"){if(!t.nodes[e])throw Error(`There is no node type named '${e}'. Maybe you forgot to add the extension?`);return t.nodes[e]}return e}function Pd(e){return typeof e=="function"}function Vt(e,t=void 0,...n){return Pd(e)?t?e.bind(t)(...n):e(...n):e}function Bd(e){return Object.prototype.toString.call(e)==="[object RegExp]"}function Vd(e){return Object.prototype.toString.call(e).slice(8,-1)}function Vr(e){return Vd(e)!=="Object"?!1:e.constructor===Object&&Object.getPrototypeOf(e)===Object.prototype}function Ls(e,t){const n={...e};return Vr(e)&&Vr(t)&&Object.keys(t).forEach(r=>{Vr(t[r])?r in e?n[r]=Ls(e[r],t[r]):Object.assign(n,{[r]:t[r]}):Object.assign(n,{[r]:t[r]})}),n}class lt{constructor(t={}){this.type="extension",this.name="extension",this.parent=null,this.child=null,this.config={name:this.name,defaultOptions:{}},this.config={...this.config,...t},this.name=this.config.name,t.defaultOptions&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${this.name}".`),this.options=this.config.defaultOptions,this.config.addOptions&&(this.options=Vt(vt(this,"addOptions",{name:this.name}))),this.storage=Vt(vt(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new lt(t)}configure(t={}){const n=this.extend();return n.options=Ls(this.options,t),n.storage=Vt(vt(n,"addStorage",{name:n.name,options:n.options})),n}extend(t={}){const n=new lt(t);return n.parent=this,this.child=n,n.name=t.name?t.name:n.parent.name,t.defaultOptions&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${n.name}".`),n.options=Vt(vt(n,"addOptions",{name:n.name})),n.storage=Vt(vt(n,"addStorage",{name:n.name,options:n.options})),n}}function Nd(e,t,n){const{from:r,to:a}=t,{blockSeparator:o=`
102
+ `))}ignoreFallback(t){t.nodeName=="BR"&&(!this.top.type||!this.top.type.inlineContent)&&this.findPlace(this.parser.schema.text("-"))}readStyles(t){let n=Ye.none,r=Ye.none;for(let a=0;a<t.length;a+=2)for(let o=void 0;;){let l=this.parser.matchStyle(t[a],t[a+1],this,o);if(!l)break;if(l.ignore)return null;if(l.clearMark?this.top.pendingMarks.concat(this.top.activeMarks).forEach(u=>{l.clearMark(u)&&(r=u.addToSet(r))}):n=this.parser.schema.marks[l.mark].create(l.attrs).addToSet(n),l.consuming===!1)o=l;else break}return[n,r]}addElementByRule(t,n,r){let a,o,l;n.node?(o=this.parser.schema.nodes[n.node],o.isLeaf?this.insertNode(o.create(n.attrs))||this.leafFallback(t):a=this.enter(o,n.attrs||null,n.preserveWhitespace)):(l=this.parser.schema.marks[n.mark].create(n.attrs),this.addPendingMark(l));let u=this.top;if(o&&o.isLeaf)this.findInside(t);else if(r)this.addElement(t,r);else if(n.getContent)this.findInside(t),n.getContent(t,this.parser.schema).forEach(c=>this.insertNode(c));else{let c=t;typeof n.contentElement=="string"?c=t.querySelector(n.contentElement):typeof n.contentElement=="function"?c=n.contentElement(t):n.contentElement&&(c=n.contentElement),this.findAround(t,c,!0),this.addAll(c)}a&&this.sync(u)&&this.open--,l&&this.removePendingMark(l,u)}addAll(t,n,r){let a=n||0;for(let o=n?t.childNodes[n]:t.firstChild,l=r==null?null:t.childNodes[r];o!=l;o=o.nextSibling,++a)this.findAtPoint(t,a),this.addDOM(o);this.findAtPoint(t,a)}findPlace(t){let n,r;for(let a=this.open;a>=0;a--){let o=this.nodes[a],l=o.findWrapping(t);if(l&&(!n||n.length>l.length)&&(n=l,r=o,!l.length)||o.solid)break}if(!n)return!1;this.sync(r);for(let a=0;a<n.length;a++)this.enterInner(n[a],null,!1);return!0}insertNode(t){if(t.isInline&&this.needsBlock&&!this.top.type){let n=this.textblockFromContext();n&&this.enterInner(n)}if(this.findPlace(t)){this.closeExtra();let n=this.top;n.applyPending(t.type),n.match&&(n.match=n.match.matchType(t.type));let r=n.activeMarks;for(let a=0;a<t.marks.length;a++)(!n.type||n.type.allowsMarkType(t.marks[a].type))&&(r=t.marks[a].addToSet(r));return n.content.push(t.mark(r)),!0}return!1}enter(t,n,r){let a=this.findPlace(t.create(n));return a&&this.enterInner(t,n,!0,r),a}enterInner(t,n=null,r=!1,a){this.closeExtra();let o=this.top;o.applyPending(t),o.match=o.match&&o.match.matchType(t);let l=ms(t,a,o.options);o.options&nn&&o.content.length==0&&(l|=nn),this.nodes.push(new En(t,n,o.activeMarks,o.pendingMarks,r,null,l)),this.open++}closeExtra(t=!1){let n=this.nodes.length-1;if(n>this.open){for(;n>this.open;n--)this.nodes[n-1].content.push(this.nodes[n].finish(t));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(this.isOpen||this.options.topOpen)}sync(t){for(let n=this.open;n>=0;n--)if(this.nodes[n]==t)return this.open=n,!0;return!1}get currentPos(){this.closeExtra();let t=0;for(let n=this.open;n>=0;n--){let r=this.nodes[n].content;for(let a=r.length-1;a>=0;a--)t+=r[a].nodeSize;n&&t++}return t}findAtPoint(t,n){if(this.find)for(let r=0;r<this.find.length;r++)this.find[r].node==t&&this.find[r].offset==n&&(this.find[r].pos=this.currentPos)}findInside(t){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].pos==null&&t.nodeType==1&&t.contains(this.find[n].node)&&(this.find[n].pos=this.currentPos)}findAround(t,n,r){if(t!=n&&this.find)for(let a=0;a<this.find.length;a++)this.find[a].pos==null&&t.nodeType==1&&t.contains(this.find[a].node)&&n.compareDocumentPosition(this.find[a].node)&(r?2:4)&&(this.find[a].pos=this.currentPos)}findInText(t){if(this.find)for(let n=0;n<this.find.length;n++)this.find[n].node==t&&(this.find[n].pos=this.currentPos-(t.nodeValue.length-this.find[n].offset))}matchesContext(t){if(t.indexOf("|")>-1)return t.split(/\s*\|\s*/).some(this.matchesContext,this);let n=t.split("/"),r=this.options.context,a=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),o=-(r?r.depth+1:0)+(a?0:1),l=(u,c)=>{for(;u>=0;u--){let d=n[u];if(d==""){if(u==n.length-1||u==0)continue;for(;c>=o;c--)if(l(u-1,c))return!0;return!1}else{let f=c>0||c==0&&a?this.nodes[c].type:r&&c>=o?r.node(c-o).type:null;if(!f||f.name!=d&&f.groups.indexOf(d)==-1)return!1;c--}}return!0};return l(n.length-1,this.open)}textblockFromContext(){let t=this.options.context;if(t)for(let n=t.depth;n>=0;n--){let r=t.node(n).contentMatchAt(t.indexAfter(n)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let n in this.parser.schema.nodes){let r=this.parser.schema.nodes[n];if(r.isTextblock&&r.defaultAttrs)return r}}addPendingMark(t){let n=Td(t,this.top.pendingMarks);n&&this.top.stashMarks.push(n),this.top.pendingMarks=t.addToSet(this.top.pendingMarks)}removePendingMark(t,n){for(let r=this.open;r>=0;r--){let a=this.nodes[r];if(a.pendingMarks.lastIndexOf(t)>-1)a.pendingMarks=t.removeFromSet(a.pendingMarks);else{a.activeMarks=t.removeFromSet(a.activeMarks);let l=a.popFromStashMark(t);l&&a.type&&a.type.allowsMarkType(l.type)&&(a.activeMarks=l.addToSet(a.activeMarks))}if(a==n)break}}}function Cd(e){for(let t=e.firstChild,n=null;t;t=t.nextSibling){let r=t.nodeType==1?t.nodeName.toLowerCase():null;r&&gs.hasOwnProperty(r)&&n?(n.appendChild(t),t=n):r=="li"?n=t:r&&(n=null)}}function Sd(e,t){return(e.matches||e.msMatchesSelector||e.webkitMatchesSelector||e.mozMatchesSelector).call(e,t)}function _d(e){let t=/\s*([\w-]+)\s*:\s*([^;]+)/g,n,r=[];for(;n=t.exec(e);)r.push(n[1],n[2].trim());return r}function bs(e){let t={};for(let n in e)t[n]=e[n];return t}function kd(e,t){let n=t.schema.nodes;for(let r in n){let a=n[r];if(!a.allowsMarkType(e))continue;let o=[],l=u=>{o.push(u);for(let c=0;c<u.edgeCount;c++){let{type:d,next:f}=u.edge(c);if(d==t||o.indexOf(f)<0&&l(f))return!0}};if(l(a.contentMatch))return!0}}function Td(e,t){for(let n=0;n<t.length;n++)if(e.eq(t[n]))return t[n]}const vs=65535,xs=Math.pow(2,16);function Dd(e,t){return e+t*xs}function ws(e){return e&vs}function Id(e){return(e-(e&vs))/xs}const Cs=1,Ss=2,$n=4,_s=8;class ks{constructor(t,n,r){this.pos=t,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&_s)>0}get deletedBefore(){return(this.delInfo&(Cs|$n))>0}get deletedAfter(){return(this.delInfo&(Ss|$n))>0}get deletedAcross(){return(this.delInfo&$n)>0}}class Je{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&Je.empty)return Je.empty}recover(t){let n=0,r=ws(t);if(!this.inverted)for(let a=0;a<r;a++)n+=this.ranges[a*3+2]-this.ranges[a*3+1];return this.ranges[r*3]+n+Id(t)}mapResult(t,n=1){return this._map(t,n,!1)}map(t,n=1){return this._map(t,n,!0)}_map(t,n,r){let a=0,o=this.inverted?2:1,l=this.inverted?1:2;for(let u=0;u<this.ranges.length;u+=3){let c=this.ranges[u]-(this.inverted?a:0);if(c>t)break;let d=this.ranges[u+o],f=this.ranges[u+l],h=c+d;if(t<=h){let g=d?t==c?-1:t==h?1:n:n,m=c+a+(g<0?0:f);if(r)return m;let C=t==(n<0?c:h)?null:Dd(u/3,t-c),w=t==c?Ss:t==h?Cs:$n;return(n<0?t!=c:t!=h)&&(w|=_s),new ks(m,w,C)}a+=f-d}return r?t+a:new ks(t+a,0,null)}touches(t,n){let r=0,a=ws(n),o=this.inverted?2:1,l=this.inverted?1:2;for(let u=0;u<this.ranges.length;u+=3){let c=this.ranges[u]-(this.inverted?r:0);if(c>t)break;let d=this.ranges[u+o],f=c+d;if(t<=f&&u==a*3)return!0;r+=this.ranges[u+l]-d}return!1}forEach(t){let n=this.inverted?2:1,r=this.inverted?1:2;for(let a=0,o=0;a<this.ranges.length;a+=3){let l=this.ranges[a],u=l-(this.inverted?o:0),c=l+(this.inverted?0:o),d=this.ranges[a+n],f=this.ranges[a+r];t(u,u+d,c,c+f),o+=f-d}}invert(){return new Je(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(t){return t==0?Je.empty:new Je(t<0?[0,-t,0]:[0,0,t])}}Je.empty=new Je([]);const Er=Object.create(null);class Ge{getMap(){return Je.empty}merge(t){return null}static fromJSON(t,n){if(!n||!n.stepType)throw new RangeError("Invalid input for Step.fromJSON");let r=Er[n.stepType];if(!r)throw new RangeError(`No step type ${n.stepType} defined`);return r.fromJSON(t,n)}static jsonID(t,n){if(t in Er)throw new RangeError("Duplicate use of step JSON ID "+t);return Er[t]=n,n.prototype.jsonID=t,n}}class Te{constructor(t,n){this.doc=t,this.failed=n}static ok(t){return new Te(t,null)}static fail(t){return new Te(null,t)}static fromReplace(t,n,r,a){try{return Te.ok(t.replace(n,r,a))}catch(o){if(o instanceof xd)return Te.fail(o.message);throw o}}}function $r(e,t,n){let r=[];for(let a=0;a<e.childCount;a++){let o=e.child(a);o.content.size&&(o=o.copy($r(o.content,t,o))),o.isInline&&(o=t(o,n,a)),r.push(o)}return ae.fromArray(r)}class It extends Ge{constructor(t,n,r){super(),this.from=t,this.to=n,this.mark=r}apply(t){let n=t.slice(this.from,this.to),r=t.resolve(this.from),a=r.node(r.sharedDepth(this.to)),o=new de($r(n.content,(l,u)=>!l.isAtom||!u.type.allowsMarkType(this.mark.type)?l:l.mark(this.mark.addToSet(l.marks)),a),n.openStart,n.openEnd);return Te.fromReplace(t,this.from,this.to,o)}invert(){return new Mt(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new It(n.pos,r.pos,this.mark)}merge(t){return t instanceof It&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new It(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"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 It(n.from,n.to,t.markFromJSON(n.mark))}}Ge.jsonID("addMark",It);class Mt extends Ge{constructor(t,n,r){super(),this.from=t,this.to=n,this.mark=r}apply(t){let n=t.slice(this.from,this.to),r=new de($r(n.content,a=>a.mark(this.mark.removeFromSet(a.marks)),t),n.openStart,n.openEnd);return Te.fromReplace(t,this.from,this.to,r)}invert(){return new It(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new Mt(n.pos,r.pos,this.mark)}merge(t){return t instanceof Mt&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new Mt(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"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 Mt(n.from,n.to,t.markFromJSON(n.mark))}}Ge.jsonID("removeMark",Mt);class At extends Ge{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return Te.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return Te.fromReplace(t,this.pos,this.pos+1,new de(ae.from(r),0,n.isLeaf?0:1))}invert(t){let n=t.nodeAt(this.pos);if(n){let r=this.mark.addToSet(n.marks);if(r.length==n.marks.length){for(let a=0;a<n.marks.length;a++)if(!n.marks[a].isInSet(r))return new At(this.pos,n.marks[a]);return new At(this.pos,this.mark)}}return new rn(this.pos,this.mark)}map(t){let n=t.mapResult(this.pos,1);return n.deletedAfter?null:new At(n.pos,this.mark)}toJSON(){return{stepType:"addNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(t,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");return new At(n.pos,t.markFromJSON(n.mark))}}Ge.jsonID("addNodeMark",At);class rn extends Ge{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return Te.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.removeFromSet(n.marks));return Te.fromReplace(t,this.pos,this.pos+1,new de(ae.from(r),0,n.isLeaf?0:1))}invert(t){let n=t.nodeAt(this.pos);return!n||!this.mark.isInSet(n.marks)?this:new At(this.pos,this.mark)}map(t){let n=t.mapResult(this.pos,1);return n.deletedAfter?null:new rn(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 rn(n.pos,t.markFromJSON(n.mark))}}Ge.jsonID("removeNodeMark",rn);class ot extends Ge{constructor(t,n,r,a=!1){super(),this.from=t,this.to=n,this.slice=r,this.structure=a}apply(t){return this.structure&&Lr(t,this.from,this.to)?Te.fail("Structure replace would overwrite content"):Te.fromReplace(t,this.from,this.to,this.slice)}getMap(){return new Je([this.from,this.to-this.from,this.slice.size])}invert(t){return new ot(this.from,this.from+this.slice.size,t.slice(this.from,this.to))}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1);return n.deletedAcross&&r.deletedAcross?null:new ot(n.pos,Math.max(n.pos,r.pos),this.slice)}merge(t){if(!(t instanceof ot)||t.structure||this.structure)return null;if(this.from+this.slice.size==t.from&&!this.slice.openEnd&&!t.slice.openStart){let n=this.slice.size+t.slice.size==0?de.empty:new de(this.slice.content.append(t.slice.content),this.slice.openStart,t.slice.openEnd);return new ot(this.from,this.to+(t.to-t.from),n,this.structure)}else if(t.to==this.from&&!this.slice.openStart&&!t.slice.openEnd){let n=this.slice.size+t.slice.size==0?de.empty:new de(t.slice.content.append(this.slice.content),t.slice.openStart,this.slice.openEnd);return new ot(t.from,this.to,n,this.structure)}else return null}toJSON(){let t={stepType:"replace",from:this.from,to:this.to};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for ReplaceStep.fromJSON");return new ot(n.from,n.to,de.fromJSON(t,n.slice),!!n.structure)}}Ge.jsonID("replace",ot);class zt extends Ge{constructor(t,n,r,a,o,l,u=!1){super(),this.from=t,this.to=n,this.gapFrom=r,this.gapTo=a,this.slice=o,this.insert=l,this.structure=u}apply(t){if(this.structure&&(Lr(t,this.from,this.gapFrom)||Lr(t,this.gapTo,this.to)))return Te.fail("Structure gap-replace would overwrite content");let n=t.slice(this.gapFrom,this.gapTo);if(n.openStart||n.openEnd)return Te.fail("Gap is not a flat range");let r=this.slice.insertAt(this.insert,n.content);return r?Te.fromReplace(t,this.from,this.to,r):Te.fail("Content does not fit in gap")}getMap(){return new Je([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(t){let n=this.gapTo-this.gapFrom;return new zt(this.from,this.from+this.slice.size+n,this.from+this.insert,this.from+this.insert+n,t.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1),a=t.map(this.gapFrom,-1),o=t.map(this.gapTo,1);return n.deletedAcross&&r.deletedAcross||a<n.pos||o>r.pos?null:new zt(n.pos,r.pos,a,o,this.slice,this.insert,this.structure)}toJSON(){let t={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number"||typeof n.gapFrom!="number"||typeof n.gapTo!="number"||typeof n.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new zt(n.from,n.to,n.gapFrom,n.gapTo,de.fromJSON(t,n.slice),n.insert,!!n.structure)}}Ge.jsonID("replaceAround",zt);function Lr(e,t,n){let r=e.resolve(t),a=n-t,o=r.depth;for(;a>0&&o>0&&r.indexAfter(o)==r.node(o).childCount;)o--,a--;if(a>0){let l=r.node(o).maybeChild(r.indexAfter(o));for(;a>0;){if(!l||l.isLeaf)return!0;l=l.firstChild,a--}}return!1}function Md(e,t,n){return(t==0||e.canReplace(t,e.childCount))&&(n==e.childCount||e.canReplace(0,n))}function Ad(e){let n=e.parent.content.cutByIndex(e.startIndex,e.endIndex);for(let r=e.depth;;--r){let a=e.$from.node(r),o=e.$from.index(r),l=e.$to.indexAfter(r);if(r<e.depth&&a.canReplace(o,l,n))return r;if(r==0||a.type.spec.isolating||!Md(a,o,l))break}return null}function Ln(e,t,n=1,r){let a=e.resolve(t),o=a.depth-n,l=r&&r[r.length-1]||a.parent;if(o<0||a.parent.type.spec.isolating||!a.parent.canReplace(a.index(),a.parent.childCount)||!l.type.validContent(a.parent.content.cutByIndex(a.index(),a.parent.childCount)))return!1;for(let d=a.depth-1,f=n-2;d>o;d--,f--){let h=a.node(d),g=a.index(d);if(h.type.spec.isolating)return!1;let m=h.content.cutByIndex(g,h.childCount),C=r&&r[f+1];C&&(m=m.replaceChild(0,C.type.create(C.attrs)));let w=r&&r[f]||h;if(!h.canReplace(g+1,h.childCount)||!w.type.validContent(m))return!1}let u=a.indexAfter(o),c=r&&r[0];return a.node(o).canReplaceWith(u,u,c?c.type:a.node(o+1).type)}function Ts(e,t){let n=e.resolve(t),r=n.index();return zd(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function zd(e,t){return!!(e&&t&&!e.isLeaf&&e.canAppend(t))}class an extends Ge{constructor(t,n,r){super(),this.pos=t,this.attr=n,this.value=r}apply(t){let n=t.nodeAt(this.pos);if(!n)return Te.fail("No node at attribute step's position");let r=Object.create(null);for(let o in n.attrs)r[o]=n.attrs[o];r[this.attr]=this.value;let a=n.type.create(r,null,n.marks);return Te.fromReplace(t,this.pos,this.pos+1,new de(ae.from(a),0,n.isLeaf?0:1))}getMap(){return Je.empty}invert(t){return new an(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 an(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 an(n.pos,n.attr,n.value)}}Ge.jsonID("attr",an);let sn=class extends Error{};sn=function e(t){let n=Error.call(this,t);return n.__proto__=e.prototype,n},sn.prototype=Object.create(Error.prototype),sn.prototype.constructor=sn,sn.prototype.name="TransformError";const Or=Object.create(null);class fe{constructor(t,n,r){this.$anchor=t,this.$head=n,this.ranges=r||[new Ed(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=de.empty){let r=n.content.lastChild,a=null;for(let u=0;u<n.openEnd;u++)a=r,r=r.lastChild;let o=t.steps.length,l=this.ranges;for(let u=0;u<l.length;u++){let{$from:c,$to:d}=l[u],f=t.mapping.slice(o);t.replaceRange(f.map(c.pos),f.map(d.pos),u?de.empty:n),u==0&&Ms(t,o,(r?r.isInline:a&&a.isTextblock)?-1:1)}}replaceWith(t,n){let r=t.steps.length,a=this.ranges;for(let o=0;o<a.length;o++){let{$from:l,$to:u}=a[o],c=t.mapping.slice(r),d=c.map(l.pos),f=c.map(u.pos);o?t.deleteRange(d,f):(t.replaceRangeWith(d,f,n),Ms(t,r,n.isInline?-1:1))}}static findFrom(t,n,r=!1){let a=t.parent.inlineContent?new De(t):Bt(t.node(0),t.parent,t.pos,t.index(),n,r);if(a)return a;for(let o=t.depth-1;o>=0;o--){let l=n<0?Bt(t.node(0),t.node(o),t.before(o+1),t.index(o),n,r):Bt(t.node(0),t.node(o),t.after(o+1),t.index(o)+1,n,r);if(l)return l}return null}static near(t,n=1){return this.findFrom(t,n)||this.findFrom(t,-n)||new ht(t.node(0))}static atStart(t){return Bt(t,t,0,0,1)||new ht(t)}static atEnd(t){return Bt(t,t,t.content.size,t.childCount,-1)||new ht(t)}static fromJSON(t,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=Or[n.type];if(!r)throw new RangeError(`No selection type ${n.type} defined`);return r.fromJSON(t,n)}static jsonID(t,n){if(t in Or)throw new RangeError("Duplicate use of selection JSON ID "+t);return Or[t]=n,n.prototype.jsonID=t,n}getBookmark(){return De.between(this.$anchor,this.$head).getBookmark()}}fe.prototype.visible=!0;class Ed{constructor(t,n){this.$from=t,this.$to=n}}let Ds=!1;function Is(e){!Ds&&!e.parent.inlineContent&&(Ds=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+e.parent.type.name+")"))}class De extends fe{constructor(t,n=t){Is(t),Is(n),super(t,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(t,n){let r=t.resolve(n.map(this.head));if(!r.parent.inlineContent)return fe.near(r);let a=t.resolve(n.map(this.anchor));return new De(a.parent.inlineContent?a:r,r)}replace(t,n=de.empty){if(super.replace(t,n),n==de.empty){let r=this.$from.marksAcross(this.$to);r&&t.ensureMarks(r)}}eq(t){return t instanceof De&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new On(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(t,n){if(typeof n.anchor!="number"||typeof n.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new De(t.resolve(n.anchor),t.resolve(n.head))}static create(t,n,r=n){let a=t.resolve(n);return new this(a,r==n?a:t.resolve(r))}static between(t,n,r){let a=t.pos-n.pos;if((!r||a)&&(r=a>=0?1:-1),!n.parent.inlineContent){let o=fe.findFrom(n,r,!0)||fe.findFrom(n,-r,!0);if(o)n=o.$head;else return fe.near(n,r)}return t.parent.inlineContent||(a==0?t=n:(t=(fe.findFrom(t,-r,!0)||fe.findFrom(t,r,!0)).$anchor,t.pos<n.pos!=a<0&&(t=n))),new De(t,n)}}fe.jsonID("text",De);class On{constructor(t,n){this.anchor=t,this.head=n}map(t){return new On(t.map(this.anchor),t.map(this.head))}resolve(t){return De.between(t.resolve(this.anchor),t.resolve(this.head))}}class Qe extends fe{constructor(t){let n=t.nodeAfter,r=t.node(0).resolve(t.pos+n.nodeSize);super(t,r),this.node=n}map(t,n){let{deleted:r,pos:a}=n.mapResult(this.anchor),o=t.resolve(a);return r?fe.near(o):new Qe(o)}content(){return new de(ae.from(this.node),0,0)}eq(t){return t instanceof Qe&&t.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new Pr(this.anchor)}static fromJSON(t,n){if(typeof n.anchor!="number")throw new RangeError("Invalid input for NodeSelection.fromJSON");return new Qe(t.resolve(n.anchor))}static create(t,n){return new Qe(t.resolve(n))}static isSelectable(t){return!t.isText&&t.type.spec.selectable!==!1}}Qe.prototype.visible=!1,fe.jsonID("node",Qe);class Pr{constructor(t){this.anchor=t}map(t){let{deleted:n,pos:r}=t.mapResult(this.anchor);return n?new On(r,r):new Pr(r)}resolve(t){let n=t.resolve(this.anchor),r=n.nodeAfter;return r&&Qe.isSelectable(r)?new Qe(n):fe.near(n)}}class ht extends fe{constructor(t){super(t.resolve(0),t.resolve(t.content.size))}replace(t,n=de.empty){if(n==de.empty){t.delete(0,t.doc.content.size);let r=fe.atStart(t.doc);r.eq(t.selection)||t.setSelection(r)}else super.replace(t,n)}toJSON(){return{type:"all"}}static fromJSON(t){return new ht(t)}map(t){return new ht(t)}eq(t){return t instanceof ht}getBookmark(){return $d}}fe.jsonID("all",ht);const $d={map(){return this},resolve(e){return new ht(e)}};function Bt(e,t,n,r,a,o=!1){if(t.inlineContent)return De.create(e,n);for(let l=r-(a>0?0:1);a>0?l<t.childCount:l>=0;l+=a){let u=t.child(l);if(u.isAtom){if(!o&&Qe.isSelectable(u))return Qe.create(e,n-(a<0?u.nodeSize:0))}else{let c=Bt(e,u,n+a,a<0?u.childCount:0,a,o);if(c)return c}n+=u.nodeSize*a}return null}function Ms(e,t,n){let r=e.steps.length-1;if(r<t)return;let a=e.steps[r];if(!(a instanceof ot||a instanceof zt))return;let o=e.mapping.maps[r],l;o.forEach((u,c,d,f)=>{l==null&&(l=f)}),e.setSelection(fe.near(e.doc.resolve(l),n))}function As(e,t){return!t||!e?e:e.bind(t)}class Pn{constructor(t,n,r){this.name=t,this.init=As(n.init,r),this.apply=As(n.apply,r)}}new Pn("doc",{init(e){return e.doc||e.schema.topNodeType.createAndFill()},apply(e){return e.doc}}),new Pn("selection",{init(e,t){return e.selection||fe.atStart(t.doc)},apply(e){return e.selection}}),new Pn("storedMarks",{init(e){return e.storedMarks||null},apply(e,t,n,r){return r.selection.$cursor?e.storedMarks:null}}),new Pn("scrollToSelection",{init(){return 0},apply(e,t){return e.scrolledIntoView?t+1:t}});function zs(e,t,n){for(let r in e){let a=e[r];a instanceof Function?a=a.bind(t):r=="handleDOMEvents"&&(a=zs(a,t,{})),n[r]=a}return n}class on{constructor(t){this.spec=t,this.props={},t.props&&zs(t.props,this,this.props),this.key=t.key?t.key.key:Es("plugin")}getState(t){return t[this.key]}}const Br=Object.create(null);function Es(e){return e in Br?e+"$"+ ++Br[e]:(Br[e]=0,e+"$")}class ln{constructor(t="key"){this.key=Es(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}function $s(e){const{state:t,transaction:n}=e;let{selection:r}=n,{doc:a}=n,{storedMarks:o}=n;return{...t,apply:t.apply.bind(t),applyTransaction:t.applyTransaction.bind(t),filterTransaction:t.filterTransaction,plugins:t.plugins,schema:t.schema,reconfigure:t.reconfigure.bind(t),toJSON:t.toJSON.bind(t),get storedMarks(){return o},get selection(){return r},get doc(){return a},get tr(){return r=n.selection,a=n.doc,o=n.storedMarks,n}}}class Ld{constructor(t){this.editor=t.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=t.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:t,editor:n,state:r}=this,{view:a}=n,{tr:o}=r,l=this.buildProps(o);return Object.fromEntries(Object.entries(t).map(([u,c])=>[u,(...f)=>{const h=c(...f)(l);return!o.getMeta("preventDispatch")&&!this.hasCustomState&&a.dispatch(o),h}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,n=!0){const{rawCommands:r,editor:a,state:o}=this,{view:l}=a,u=[],c=!!t,d=t||o.tr,f=()=>(!c&&n&&!d.getMeta("preventDispatch")&&!this.hasCustomState&&l.dispatch(d),u.every(g=>g===!0)),h={...Object.fromEntries(Object.entries(r).map(([g,m])=>[g,(...w)=>{const _=this.buildProps(d,n),D=m(...w)(_);return u.push(D),h}])),run:f};return h}createCan(t){const{rawCommands:n,state:r}=this,a=!1,o=t||r.tr,l=this.buildProps(o,a);return{...Object.fromEntries(Object.entries(n).map(([c,d])=>[c,(...f)=>d(...f)({...l,dispatch:void 0})])),chain:()=>this.createChain(o,a)}}buildProps(t,n=!0){const{rawCommands:r,editor:a,state:o}=this,{view:l}=a;o.storedMarks&&t.setStoredMarks(o.storedMarks);const u={tr:t,editor:a,view:l,state:$s({state:o,transaction:t}),dispatch:n?()=>{}:void 0,chain:()=>this.createChain(t),can:()=>this.createCan(t),get commands(){return Object.fromEntries(Object.entries(r).map(([c,d])=>[c,(...f)=>d(...f)(u)]))}};return u}}function vt(e,t,n){return e.config[t]===void 0&&e.parent?vt(e.parent,t,n):typeof e.config[t]=="function"?e.config[t].bind({...n,parent:e.parent?vt(e.parent,t,n):null}):e.config[t]}function Od(e){const t=e.filter(a=>a.type==="extension"),n=e.filter(a=>a.type==="node"),r=e.filter(a=>a.type==="mark");return{baseExtensions:t,nodeExtensions:n,markExtensions:r}}function Le(e,t){if(typeof e=="string"){if(!t.nodes[e])throw Error(`There is no node type named '${e}'. Maybe you forgot to add the extension?`);return t.nodes[e]}return e}function Pd(e){return typeof e=="function"}function Vt(e,t=void 0,...n){return Pd(e)?t?e.bind(t)(...n):e(...n):e}function Bd(e){return Object.prototype.toString.call(e)==="[object RegExp]"}function Vd(e){return Object.prototype.toString.call(e).slice(8,-1)}function Vr(e){return Vd(e)!=="Object"?!1:e.constructor===Object&&Object.getPrototypeOf(e)===Object.prototype}function Ls(e,t){const n={...e};return Vr(e)&&Vr(t)&&Object.keys(t).forEach(r=>{Vr(t[r])?r in e?n[r]=Ls(e[r],t[r]):Object.assign(n,{[r]:t[r]}):Object.assign(n,{[r]:t[r]})}),n}class lt{constructor(t={}){this.type="extension",this.name="extension",this.parent=null,this.child=null,this.config={name:this.name,defaultOptions:{}},this.config={...this.config,...t},this.name=this.config.name,t.defaultOptions&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${this.name}".`),this.options=this.config.defaultOptions,this.config.addOptions&&(this.options=Vt(vt(this,"addOptions",{name:this.name}))),this.storage=Vt(vt(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new lt(t)}configure(t={}){const n=this.extend();return n.options=Ls(this.options,t),n.storage=Vt(vt(n,"addStorage",{name:n.name,options:n.options})),n}extend(t={}){const n=new lt(t);return n.parent=this,this.child=n,n.name=t.name?t.name:n.parent.name,t.defaultOptions&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${n.name}".`),n.options=Vt(vt(n,"addOptions",{name:n.name})),n.storage=Vt(vt(n,"addStorage",{name:n.name,options:n.options})),n}}function Nd(e,t,n){const{from:r,to:a}=t,{blockSeparator:o=`
103
103
 
104
- `,textSerializers:l={}}=n||{};let u="",c=!0;return e.nodesBetween(r,a,(d,f,h,g)=>{var m;const C=l==null?void 0:l[d.type.name];C?(d.isBlock&&!c&&(u+=o,c=!0),h&&(u+=C({node:d,pos:f,parent:h,index:g,range:t}))):d.isText?(u+=(m=d==null?void 0:d.text)===null||m===void 0?void 0:m.slice(Math.max(r,f)-f,a-f),c=!1):d.isBlock&&!c&&(u+=o,c=!0)}),u}function qd(e){return Object.fromEntries(Object.entries(e.nodes).filter(([,t])=>t.spec.toText).map(([t,n])=>[t,n.spec.toText]))}lt.create({name:"clipboardTextSerializer",addProseMirrorPlugins(){return[new sn({key:new on("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:e}=this,{state:t,schema:n}=e,{doc:r,selection:a}=t,{ranges:o}=a,l=Math.min(...o.map(f=>f.$from.pos)),u=Math.max(...o.map(f=>f.$to.pos)),c=qd(n);return Nd(r,{from:l,to:u},{textSerializers:c})}}})]}});const Fd=()=>({editor:e,view:t})=>(requestAnimationFrame(()=>{var n;e.isDestroyed||(t.dom.blur(),(n=window==null?void 0:window.getSelection())===null||n===void 0||n.removeAllRanges())}),!0),Gd=(e=!1)=>({commands:t})=>t.setContent("",e),Wd=()=>({state:e,tr:t,dispatch:n})=>{const{selection:r}=t,{ranges:a}=r;return n&&a.forEach(({$from:o,$to:l})=>{e.doc.nodesBetween(o.pos,l.pos,(u,c)=>{if(u.type.isText)return;const{doc:d,mapping:f}=t,h=d.resolve(f.map(c)),g=d.resolve(f.map(c+u.nodeSize)),m=h.blockRange(g);if(!m)return;const C=Ad(m);if(u.type.isTextblock){const{defaultType:w}=h.parent.contentMatchAt(h.index());t.setNodeMarkup(m.start,w)}(C||C===0)&&t.lift(m,C)})}),!0},jd=e=>t=>e(t),Rd=()=>({state:e,dispatch:t})=>Me.createParagraphNear(e,t),Yd=()=>({tr:e,dispatch:t})=>{const{selection:n}=e,r=n.$anchor.node();if(r.content.size>0)return!1;const a=e.selection.$anchor;for(let o=a.depth;o>0;o-=1)if(a.node(o).type===r.type){if(t){const u=a.before(o),c=a.after(o);e.delete(u,c).scrollIntoView()}return!0}return!1},Qd=e=>({tr:t,state:n,dispatch:r})=>{const a=Le(e,n.schema),o=t.selection.$anchor;for(let l=o.depth;l>0;l-=1)if(o.node(l).type===a){if(r){const c=o.before(l),d=o.after(l);t.delete(c,d).scrollIntoView()}return!0}return!1},Ud=e=>({tr:t,dispatch:n})=>{const{from:r,to:a}=e;return n&&t.delete(r,a),!0},Kd=()=>({state:e,dispatch:t})=>Me.deleteSelection(e,t),Xd=()=>({commands:e})=>e.keyboardShortcut("Enter"),Jd=()=>({state:e,dispatch:t})=>Me.exitCode(e,t);function Bn(e,t,n={strict:!0}){const r=Object.keys(t);return r.length?r.every(a=>n.strict?t[a]===e[a]:Bd(t[a])?t[a].test(e[a]):t[a]===e[a]):!0}function Nr(e,t,n={}){return e.find(r=>r.type===t&&Bn(r.attrs,n))}function Zd(e,t,n={}){return!!Nr(e,t,n)}function Os(e,t,n={}){if(!e||!t)return;let r=e.parent.childAfter(e.parentOffset);if(e.parentOffset===r.offset&&r.offset!==0&&(r=e.parent.childBefore(e.parentOffset)),!r.node)return;const a=Nr([...r.node.marks],t,n);if(!a)return;let o=r.index,l=e.start()+r.offset,u=o+1,c=l+r.node.nodeSize;for(Nr([...r.node.marks],t,n);o>0&&a.isInSet(e.parent.child(o-1).marks);)o-=1,l-=e.parent.child(o).nodeSize;for(;u<e.parent.childCount&&Zd([...e.parent.child(u).marks],t,n);)c+=e.parent.child(u).nodeSize,u+=1;return{from:l,to:c}}function xt(e,t){if(typeof e=="string"){if(!t.marks[e])throw Error(`There is no mark type named '${e}'. Maybe you forgot to add the extension?`);return t.marks[e]}return e}const Hd=(e,t={})=>({tr:n,state:r,dispatch:a})=>{const o=xt(e,r.schema),{doc:l,selection:u}=n,{$from:c,from:d,to:f}=u;if(a){const h=Os(c,o,t);if(h&&h.from<=d&&h.to>=f){const g=De.create(l,h.from,h.to);n.setSelection(g)}}return!0},ep=e=>t=>{const n=typeof e=="function"?e(t):e;for(let r=0;r<n.length;r+=1)if(n[r](t))return!0;return!1};function Ps(e){return e instanceof De}function Et(e=0,t=0,n=0){return Math.min(Math.max(e,t),n)}function tp(e,t=null){if(!t)return null;const n=fe.atStart(e),r=fe.atEnd(e);if(t==="start"||t===!0)return n;if(t==="end")return r;const a=n.from,o=r.to;return t==="all"?De.create(e,Et(0,a,o),Et(e.content.size,a,o)):De.create(e,Et(t,a,o),Et(t,a,o))}function qr(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}const np=(e=null,t={})=>({editor:n,view:r,tr:a,dispatch:o})=>{t={scrollIntoView:!0,...t};const l=()=>{qr()&&r.dom.focus(),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),t!=null&&t.scrollIntoView&&n.commands.scrollIntoView())})};if(r.hasFocus()&&e===null||e===!1)return!0;if(o&&e===null&&!Ps(n.state.selection))return l(),!0;const u=tp(a.doc,e)||n.state.selection,c=n.state.selection.eq(u);return o&&(c||a.setSelection(u),c&&a.storedMarks&&a.setStoredMarks(a.storedMarks),l()),!0},rp=(e,t)=>n=>e.every((r,a)=>t(r,{...n,index:a})),ip=(e,t)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},e,t);function Bs(e){const t=`<body>${e}</body>`;return new window.DOMParser().parseFromString(t,"text/html").body}function Vn(e,t,n){if(n={slice:!0,parseOptions:{},...n},typeof e=="object"&&e!==null)try{return Array.isArray(e)&&e.length>0?ae.fromArray(e.map(r=>t.nodeFromJSON(r))):t.nodeFromJSON(e)}catch(r){return console.warn("[tiptap warn]: Invalid content.","Passed value:",e,"Error:",r),Vn("",t,n)}if(typeof e=="string"){const r=Mn.fromSchema(t);return n.slice?r.parseSlice(Bs(e),n.parseOptions).content:r.parse(Bs(e),n.parseOptions)}return Vn("",t,n)}function ap(e,t,n){const r=e.steps.length-1;if(r<t)return;const a=e.steps[r];if(!(a instanceof ot||a instanceof zt))return;const o=e.mapping.maps[r];let l=0;o.forEach((u,c,d,f)=>{l===0&&(l=f)}),e.setSelection(fe.near(e.doc.resolve(l),n))}const sp=e=>e.toString().startsWith("<"),op=(e,t,n)=>({tr:r,dispatch:a,editor:o})=>{if(a){n={parseOptions:{},updateSelection:!0,...n};const l=Vn(t,o.schema,{parseOptions:{preserveWhitespace:"full",...n.parseOptions}});if(l.toString()==="<>")return!0;let{from:u,to:c}=typeof e=="number"?{from:e,to:e}:e,d=!0,f=!0;if((sp(l)?l:[l]).forEach(g=>{g.check(),d=d?g.isText&&g.marks.length===0:!1,f=f?g.isBlock:!1}),u===c&&f){const{parent:g}=r.doc.resolve(u);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(u-=1,c+=1)}d?Array.isArray(t)?r.insertText(t.map(g=>g.text||"").join(""),u,c):typeof t=="object"&&t&&t.text?r.insertText(t.text,u,c):r.insertText(t,u,c):r.replaceWith(u,c,l),n.updateSelection&&ap(r,r.steps.length-1,-1)}return!0},lp=()=>({state:e,dispatch:t})=>Me.joinUp(e,t),up=()=>({state:e,dispatch:t})=>Me.joinDown(e,t),cp=()=>({state:e,dispatch:t})=>Me.joinBackward(e,t),dp=()=>({state:e,dispatch:t})=>Me.joinForward(e,t);function Vs(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function pp(e){const t=e.split(/-(?!$)/);let n=t[t.length-1];n==="Space"&&(n=" ");let r,a,o,l;for(let u=0;u<t.length-1;u+=1){const c=t[u];if(/^(cmd|meta|m)$/i.test(c))l=!0;else if(/^a(lt)?$/i.test(c))r=!0;else if(/^(c|ctrl|control)$/i.test(c))a=!0;else if(/^s(hift)?$/i.test(c))o=!0;else if(/^mod$/i.test(c))qr()||Vs()?l=!0:a=!0;else throw new Error(`Unrecognized modifier name: ${c}`)}return r&&(n=`Alt-${n}`),a&&(n=`Ctrl-${n}`),l&&(n=`Meta-${n}`),o&&(n=`Shift-${n}`),n}const hp=e=>({editor:t,view:n,tr:r,dispatch:a})=>{const o=pp(e).split(/-(?!$)/),l=o.find(d=>!["Alt","Ctrl","Meta","Shift"].includes(d)),u=new KeyboardEvent("keydown",{key:l==="Space"?" ":l,altKey:o.includes("Alt"),ctrlKey:o.includes("Ctrl"),metaKey:o.includes("Meta"),shiftKey:o.includes("Shift"),bubbles:!0,cancelable:!0}),c=t.captureTransaction(()=>{n.someProp("handleKeyDown",d=>d(n,u))});return c==null||c.steps.forEach(d=>{const f=d.map(r.mapping);f&&a&&r.maybeStep(f)}),!0};function Fr(e,t,n={}){const{from:r,to:a,empty:o}=e.selection,l=t?Le(t,e.schema):null,u=[];e.doc.nodesBetween(r,a,(h,g)=>{if(h.isText)return;const m=Math.max(r,g),C=Math.min(a,g+h.nodeSize);u.push({node:h,from:m,to:C})});const c=a-r,d=u.filter(h=>l?l.name===h.node.type.name:!0).filter(h=>Bn(h.node.attrs,n,{strict:!1}));return o?!!d.length:d.reduce((h,g)=>h+g.to-g.from,0)>=c}const fp=(e,t={})=>({state:n,dispatch:r})=>{const a=Le(e,n.schema);return Fr(n,a,t)?Me.lift(n,r):!1},gp=()=>({state:e,dispatch:t})=>Me.liftEmptyBlock(e,t),mp=e=>({state:t,dispatch:n})=>{const r=Le(e,t.schema);return pr.liftListItem(r)(t,n)},yp=()=>({state:e,dispatch:t})=>Me.newlineInCode(e,t);function Ns(e,t){return t.nodes[e]?"node":t.marks[e]?"mark":null}function qs(e,t){const n=typeof t=="string"?[t]:t;return Object.keys(e).reduce((r,a)=>(n.includes(a)||(r[a]=e[a]),r),{})}const bp=(e,t)=>({tr:n,state:r,dispatch:a})=>{let o=null,l=null;const u=Ns(typeof e=="string"?e:e.name,r.schema);return u?(u==="node"&&(o=Le(e,r.schema)),u==="mark"&&(l=xt(e,r.schema)),a&&n.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(d,f)=>{o&&o===d.type&&n.setNodeMarkup(f,void 0,qs(d.attrs,t)),l&&d.marks.length&&d.marks.forEach(h=>{l===h.type&&n.addMark(f,f+d.nodeSize,l.create(qs(h.attrs,t)))})})}),!0):!1},vp=()=>({tr:e,dispatch:t})=>(t&&e.scrollIntoView(),!0),xp=()=>({tr:e,commands:t})=>t.setTextSelection({from:0,to:e.doc.content.size}),wp=()=>({state:e,dispatch:t})=>Me.selectNodeBackward(e,t),Cp=()=>({state:e,dispatch:t})=>Me.selectNodeForward(e,t),Sp=()=>({state:e,dispatch:t})=>Me.selectParentNode(e,t),_p=()=>({state:e,dispatch:t})=>Me.selectTextblockEnd(e,t),kp=()=>({state:e,dispatch:t})=>Me.selectTextblockStart(e,t);function Tp(e,t,n={}){return Vn(e,t,{slice:!1,parseOptions:n})}const Dp=(e,t=!1,n={})=>({tr:r,editor:a,dispatch:o})=>{const{doc:l}=r,u=Tp(e,a.schema,n);return o&&r.replaceWith(0,l.content.size,u).setMeta("preventUpdate",!t),!0};function Ip(e){for(let t=0;t<e.edgeCount;t+=1){const{type:n}=e.edge(t);if(n.isTextblock&&!n.hasRequiredAttrs())return n}return null}function Mp(e,t){for(let n=e.depth;n>0;n-=1){const r=e.node(n);if(t(r))return{pos:n>0?e.before(n):0,start:e.start(n),depth:n,node:r}}}function Gr(e){return t=>Mp(t.$from,e)}function Ap(e,t){const n=xt(t,e.schema),{from:r,to:a,empty:o}=e.selection,l=[];o?(e.storedMarks&&l.push(...e.storedMarks),l.push(...e.selection.$head.marks())):e.doc.nodesBetween(r,a,c=>{l.push(...c.marks)});const u=l.find(c=>c.type.name===n.name);return u?{...u.attrs}:{}}function Nn(e,t,n){return Object.fromEntries(Object.entries(n).filter(([r])=>{const a=e.find(o=>o.type===t&&o.name===r);return a?a.attribute.keepOnSplit:!1}))}function zp(e,t,n={}){const{empty:r,ranges:a}=e.selection,o=t?xt(t,e.schema):null;if(r)return!!(e.storedMarks||e.selection.$from.marks()).filter(h=>o?o.name===h.type.name:!0).find(h=>Bn(h.attrs,n,{strict:!1}));let l=0;const u=[];if(a.forEach(({$from:h,$to:g})=>{const m=h.pos,C=g.pos;e.doc.nodesBetween(m,C,(w,_)=>{if(!w.isText&&!w.marks.length)return;const D=Math.max(m,_),M=Math.min(C,_+w.nodeSize),P=M-D;l+=P,u.push(...w.marks.map(G=>({mark:G,from:D,to:M})))})}),l===0)return!1;const c=u.filter(h=>o?o.name===h.mark.type.name:!0).filter(h=>Bn(h.mark.attrs,n,{strict:!1})).reduce((h,g)=>h+g.to-g.from,0),d=u.filter(h=>o?h.mark.type!==o&&h.mark.type.excludes(o):!0).reduce((h,g)=>h+g.to-g.from,0);return(c>0?c+d:c)>=l}function Fs(e,t){const{nodeExtensions:n}=Od(t),r=n.find(l=>l.name===e);if(!r)return!1;const a={name:r.name,options:r.options,storage:r.storage},o=Vt(vt(r,"group",a));return typeof o!="string"?!1:o.split(" ").includes("list")}function Ep(e,t,n){var r;const{selection:a}=t;let o=null;if(Ps(a)&&(o=a.$cursor),o){const u=(r=e.storedMarks)!==null&&r!==void 0?r:o.marks();return!!n.isInSet(u)||!u.some(c=>c.type.excludes(n))}const{ranges:l}=a;return l.some(({$from:u,$to:c})=>{let d=u.depth===0?e.doc.inlineContent&&e.doc.type.allowsMarkType(n):!1;return e.doc.nodesBetween(u.pos,c.pos,(f,h,g)=>{if(d)return!1;if(f.isInline){const m=!g||g.type.allowsMarkType(n),C=!!n.isInSet(f.marks)||!f.marks.some(w=>w.type.excludes(n));d=m&&C}return!d}),d})}const $p=(e,t={})=>({tr:n,state:r,dispatch:a})=>{const{selection:o}=n,{empty:l,ranges:u}=o,c=xt(e,r.schema);if(a)if(l){const d=Ap(r,c);n.addStoredMark(c.create({...d,...t}))}else u.forEach(d=>{const f=d.$from.pos,h=d.$to.pos;r.doc.nodesBetween(f,h,(g,m)=>{const C=Math.max(m,f),w=Math.min(m+g.nodeSize,h);g.marks.find(D=>D.type===c)?g.marks.forEach(D=>{c===D.type&&n.addMark(C,w,c.create({...D.attrs,...t}))}):n.addMark(C,w,c.create(t))})});return Ep(r,n,c)},Lp=(e,t)=>({tr:n})=>(n.setMeta(e,t),!0),Op=(e,t={})=>({state:n,dispatch:r,chain:a})=>{const o=Le(e,n.schema);return o.isTextblock?a().command(({commands:l})=>Me.setBlockType(o,t)(n)?!0:l.clearNodes()).command(({state:l})=>Me.setBlockType(o,t)(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},Pp=e=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,a=Et(e,0,r.content.size),o=Ye.create(r,a);t.setSelection(o)}return!0},Bp=e=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,{from:a,to:o}=typeof e=="number"?{from:e,to:e}:e,l=De.atStart(r).from,u=De.atEnd(r).to,c=Et(a,l,u),d=Et(o,l,u),f=De.create(r,c,d);t.setSelection(f)}return!0},Vp=e=>({state:t,dispatch:n})=>{const r=Le(e,t.schema);return pr.sinkListItem(r)(t,n)};function Gs(e,t){const n=e.storedMarks||e.selection.$to.parentOffset&&e.selection.$from.marks();if(n){const r=n.filter(a=>t==null?void 0:t.includes(a.type.name));e.tr.ensureMarks(r)}}const Np=({keepMarks:e=!0}={})=>({tr:t,state:n,dispatch:r,editor:a})=>{const{selection:o,doc:l}=t,{$from:u,$to:c}=o,d=a.extensionManager.attributes,f=Nn(d,u.node().type.name,u.node().attrs);if(o instanceof Ye&&o.node.isBlock)return!u.parentOffset||!Ln(l,u.pos)?!1:(r&&(e&&Gs(n,a.extensionManager.splittableMarks),t.split(u.pos).scrollIntoView()),!0);if(!u.parent.isBlock)return!1;if(r){const h=c.parentOffset===c.parent.content.size;o instanceof De&&t.deleteSelection();const g=u.depth===0?void 0:Ip(u.node(-1).contentMatchAt(u.indexAfter(-1)));let m=h&&g?[{type:g,attrs:f}]:void 0,C=Ln(t.doc,t.mapping.map(u.pos),1,m);if(!m&&!C&&Ln(t.doc,t.mapping.map(u.pos),1,g?[{type:g}]:void 0)&&(C=!0,m=g?[{type:g,attrs:f}]:void 0),C&&(t.split(t.mapping.map(u.pos),1,m),g&&!h&&!u.parentOffset&&u.parent.type!==g)){const w=t.mapping.map(u.before()),_=t.doc.resolve(w);u.node(-1).canReplaceWith(_.index(),_.index()+1,g)&&t.setNodeMarkup(t.mapping.map(u.before()),g)}e&&Gs(n,a.extensionManager.splittableMarks),t.scrollIntoView()}return!0},qp=e=>({tr:t,state:n,dispatch:r,editor:a})=>{var o;const l=Le(e,n.schema),{$from:u,$to:c}=n.selection,d=n.selection.node;if(d&&d.isBlock||u.depth<2||!u.sameParent(c))return!1;const f=u.node(-1);if(f.type!==l)return!1;const h=a.extensionManager.attributes;if(u.parent.content.size===0&&u.node(-1).childCount===u.indexAfter(-1)){if(u.depth===2||u.node(-3).type!==l||u.index(-2)!==u.node(-2).childCount-1)return!1;if(r){let _=ae.empty;const D=u.index(-1)?1:u.index(-2)?2:3;for(let A=u.depth-D;A>=u.depth-3;A-=1)_=ae.from(u.node(A).copy(_));const M=u.indexAfter(-1)<u.node(-2).childCount?1:u.indexAfter(-2)<u.node(-3).childCount?2:3,P=Nn(h,u.node().type.name,u.node().attrs),G=((o=l.contentMatch.defaultType)===null||o===void 0?void 0:o.createAndFill(P))||void 0;_=_.append(ae.from(l.createAndFill(null,G)||void 0));const L=u.before(u.depth-(D-1));t.replace(L,u.after(-M),new ce(_,4-D,0));let z=-1;t.doc.nodesBetween(L,t.doc.content.size,(A,F)=>{if(z>-1)return!1;A.isTextblock&&A.content.size===0&&(z=F+1)}),z>-1&&t.setSelection(De.near(t.doc.resolve(z))),t.scrollIntoView()}return!0}const g=c.pos===u.end()?f.contentMatchAt(0).defaultType:null,m=Nn(h,f.type.name,f.attrs),C=Nn(h,u.node().type.name,u.node().attrs);t.delete(u.pos,c.pos);const w=g?[{type:l,attrs:m},{type:g,attrs:C}]:[{type:l,attrs:m}];if(!Ln(t.doc,u.pos,2))return!1;if(r){const{selection:_,storedMarks:D}=n,{splittableMarks:M}=a.extensionManager,P=D||_.$to.parentOffset&&_.$from.marks();if(t.split(u.pos,2,w).scrollIntoView(),!P||!r)return!0;const G=P.filter(L=>M.includes(L.type.name));t.ensureMarks(G)}return!0},Wr=(e,t)=>{const n=Gr(l=>l.type===t)(e.selection);if(!n)return!0;const r=e.doc.resolve(Math.max(0,n.pos-1)).before(n.depth);if(r===void 0)return!0;const a=e.doc.nodeAt(r);return n.node.type===(a==null?void 0:a.type)&&Ts(e.doc,n.pos)&&e.join(n.pos),!0},jr=(e,t)=>{const n=Gr(l=>l.type===t)(e.selection);if(!n)return!0;const r=e.doc.resolve(n.start).after(n.depth);if(r===void 0)return!0;const a=e.doc.nodeAt(r);return n.node.type===(a==null?void 0:a.type)&&Ts(e.doc,r)&&e.join(r),!0};var Fp=Object.freeze({__proto__:null,blur:Fd,clearContent:Gd,clearNodes:Wd,command:jd,createParagraphNear:Rd,deleteCurrentNode:Yd,deleteNode:Qd,deleteRange:Ud,deleteSelection:Kd,enter:Xd,exitCode:Jd,extendMarkRange:Hd,first:ep,focus:np,forEach:rp,insertContent:ip,insertContentAt:op,joinUp:lp,joinDown:up,joinBackward:cp,joinForward:dp,keyboardShortcut:hp,lift:fp,liftEmptyBlock:gp,liftListItem:mp,newlineInCode:yp,resetAttributes:bp,scrollIntoView:vp,selectAll:xp,selectNodeBackward:wp,selectNodeForward:Cp,selectParentNode:Sp,selectTextblockEnd:_p,selectTextblockStart:kp,setContent:Dp,setMark:$p,setMeta:Lp,setNode:Op,setNodeSelection:Pp,setTextSelection:Bp,sinkListItem:Vp,splitBlock:Np,splitListItem:qp,toggleList:(e,t,n,r={})=>({editor:a,tr:o,state:l,dispatch:u,chain:c,commands:d,can:f})=>{const{extensions:h,splittableMarks:g}=a.extensionManager,m=Le(e,l.schema),C=Le(t,l.schema),{selection:w,storedMarks:_}=l,{$from:D,$to:M}=w,P=D.blockRange(M),G=_||w.$to.parentOffset&&w.$from.marks();if(!P)return!1;const L=Gr(z=>Fs(z.type.name,h))(w);if(P.depth>=1&&L&&P.depth-L.depth<=1){if(L.node.type===m)return d.liftListItem(C);if(Fs(L.node.type.name,h)&&m.validContent(L.node.content)&&u)return c().command(()=>(o.setNodeMarkup(L.pos,m),!0)).command(()=>Wr(o,m)).command(()=>jr(o,m)).run()}return!n||!G||!u?c().command(()=>f().wrapInList(m,r)?!0:d.clearNodes()).wrapInList(m,r).command(()=>Wr(o,m)).command(()=>jr(o,m)).run():c().command(()=>{const z=f().wrapInList(m,r),A=G.filter(F=>g.includes(F.type.name));return o.ensureMarks(A),z?!0:d.clearNodes()}).wrapInList(m,r).command(()=>Wr(o,m)).command(()=>jr(o,m)).run()},toggleMark:(e,t={},n={})=>({state:r,commands:a})=>{const{extendEmptyMarkRange:o=!1}=n,l=xt(e,r.schema);return zp(r,l,t)?a.unsetMark(l,{extendEmptyMarkRange:o}):a.setMark(l,t)},toggleNode:(e,t,n={})=>({state:r,commands:a})=>{const o=Le(e,r.schema),l=Le(t,r.schema);return Fr(r,o,n)?a.setNode(l):a.setNode(o,n)},toggleWrap:(e,t={})=>({state:n,commands:r})=>{const a=Le(e,n.schema);return Fr(n,a,t)?r.lift(a):r.wrapIn(a,t)},undoInputRule:()=>({state:e,dispatch:t})=>{const n=e.plugins;for(let r=0;r<n.length;r+=1){const a=n[r];let o;if(a.spec.isInputRules&&(o=a.getState(e))){if(t){const l=e.tr,u=o.transform;for(let c=u.steps.length-1;c>=0;c-=1)l.step(u.steps[c].invert(u.docs[c]));if(o.text){const c=l.doc.resolve(o.from).marks();l.replaceWith(o.from,o.to,e.schema.text(o.text,c))}else l.delete(o.from,o.to)}return!0}}return!1},unsetAllMarks:()=>({tr:e,dispatch:t})=>{const{selection:n}=e,{empty:r,ranges:a}=n;return r||t&&a.forEach(o=>{e.removeMark(o.$from.pos,o.$to.pos)}),!0},unsetMark:(e,t={})=>({tr:n,state:r,dispatch:a})=>{var o;const{extendEmptyMarkRange:l=!1}=t,{selection:u}=n,c=xt(e,r.schema),{$from:d,empty:f,ranges:h}=u;if(!a)return!0;if(f&&l){let{from:g,to:m}=u;const C=(o=d.marks().find(_=>_.type===c))===null||o===void 0?void 0:o.attrs,w=Os(d,c,C);w&&(g=w.from,m=w.to),n.removeMark(g,m,c)}else h.forEach(g=>{n.removeMark(g.$from.pos,g.$to.pos,c)});return n.removeStoredMark(c),!0},updateAttributes:(e,t={})=>({tr:n,state:r,dispatch:a})=>{let o=null,l=null;const u=Ns(typeof e=="string"?e:e.name,r.schema);return u?(u==="node"&&(o=Le(e,r.schema)),u==="mark"&&(l=xt(e,r.schema)),a&&n.selection.ranges.forEach(c=>{const d=c.$from.pos,f=c.$to.pos;r.doc.nodesBetween(d,f,(h,g)=>{o&&o===h.type&&n.setNodeMarkup(g,void 0,{...h.attrs,...t}),l&&h.marks.length&&h.marks.forEach(m=>{if(l===m.type){const C=Math.max(g,d),w=Math.min(g+h.nodeSize,f);n.addMark(C,w,l.create({...m.attrs,...t}))}})})}),!0):!1},wrapIn:(e,t={})=>({state:n,dispatch:r})=>{const a=Le(e,n.schema);return Me.wrapIn(a,t)(n,r)},wrapInList:(e,t={})=>({state:n,dispatch:r})=>{const a=Le(e,n.schema);return pr.wrapInList(a,t)(n,r)}});lt.create({name:"commands",addCommands(){return{...Fp}}}),lt.create({name:"editable",addProseMirrorPlugins(){return[new sn({key:new on("editable"),props:{editable:()=>this.editor.options.editable}})]}}),lt.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:e}=this;return[new sn({key:new on("focusEvents"),props:{handleDOMEvents:{focus:(t,n)=>{e.isFocused=!0;const r=e.state.tr.setMeta("focus",{event:n}).setMeta("addToHistory",!1);return t.dispatch(r),!1},blur:(t,n)=>{e.isFocused=!1;const r=e.state.tr.setMeta("blur",{event:n}).setMeta("addToHistory",!1);return t.dispatch(r),!1}}}})]}}),lt.create({name:"keymap",addKeyboardShortcuts(){const e=()=>this.editor.commands.first(({commands:l})=>[()=>l.undoInputRule(),()=>l.command(({tr:u})=>{const{selection:c,doc:d}=u,{empty:f,$anchor:h}=c,{pos:g,parent:m}=h,C=fe.atStart(d).from===g;return!f||!C||!m.type.isTextblock||m.textContent.length?!1:l.clearNodes()}),()=>l.deleteSelection(),()=>l.joinBackward(),()=>l.selectNodeBackward()]),t=()=>this.editor.commands.first(({commands:l})=>[()=>l.deleteSelection(),()=>l.deleteCurrentNode(),()=>l.joinForward(),()=>l.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:l})=>[()=>l.newlineInCode(),()=>l.createParagraphNear(),()=>l.liftEmptyBlock(),()=>l.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:e,"Mod-Backspace":e,"Shift-Backspace":e,Delete:t,"Mod-Delete":t,"Mod-a":()=>this.editor.commands.selectAll()},a={...r},o={...r,"Ctrl-h":e,"Alt-Backspace":e,"Ctrl-d":t,"Ctrl-Alt-Backspace":t,"Alt-Delete":t,"Alt-d":t,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return qr()||Vs()?o:a},addProseMirrorPlugins(){return[new sn({key:new on("clearDocument"),appendTransaction:(e,t,n)=>{if(!(e.some(C=>C.docChanged)&&!t.doc.eq(n.doc)))return;const{empty:a,from:o,to:l}=t.selection,u=fe.atStart(t.doc).from,c=fe.atEnd(t.doc).to;if(a||!(o===u&&l===c)||!(n.doc.textBetween(0,n.doc.content.size," "," ").length===0))return;const h=n.tr,g=$s({state:n,transaction:h}),{commands:m}=new Ld({editor:this.editor,state:g});if(m.clearNodes(),!!h.steps.length)return h}})]}}),lt.create({name:"tabindex",addProseMirrorPlugins(){return[new sn({key:new on("tabindex"),props:{attributes:this.editor.isEditable?{tabindex:"0"}:{}}})]}});const Ws=lt.create({name:"fontSize",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{fontSize:{default:null,parseHTML:e=>e.style.fontSize.replace(/['"]+/g,""),renderHTML:e=>e.fontSize?{style:`font-size: ${e.fontSize}`}:{}}}}]},addCommands(){return{setFontSize:e=>({chain:t})=>t().setMark("textStyle",{fontSize:e}).run(),unsetFontSize:()=>({chain:e})=>e().setMark("textStyle",{fontSize:null}).removeEmptyTextStyle().run()}}}),Gp=["8","10","12","14","16","18","20","24","30","36","48","60","72"].map(e=>`${e}px`),Wp=[{label:"auto",value:""}].concat(Gp.map(e=>({label:e,value:e}))),jp={input:{height:"26px",minHeight:"26px",lineHeight:"26px",borderColor:"#ced4da !important"}},Rp=({editor:e})=>{const t=e.getAttributes("textStyle").fontSize;return i(J.RichTextEditor.ControlsGroup,{children:i(s.NativeSelect,{size:"xs",icon:i($.IconTextSize,{stroke:1.5,size:16}),data:Wp,styles:jp,value:t||"",onChange:n=>{const r=n.currentTarget.value;r?e.chain().focus().setFontSize(r).run():e.chain().focus().unsetFontSize().run()}})})},qn=({value:e,styles:t={}})=>{const n=Ga.useEditor({extensions:[Wa,Fa,J.Link,La,$a,za,Ba.configure({resizable:!1,HTMLAttributes:{class:"rich-text-table-render"}}),qa,Na,Va,Oa.configure({types:["heading","paragraph"]}),Ea.configure({placeholder:"This is placeholder"}),Pa,Aa.Color,Ws],content:e,editable:!1});y.useEffect(()=>{n==null||n.commands.setContent(e)},[e,n]);const r=y.useMemo(()=>x.defaultsDeep({},{content:Mr},t),[t]);return i(J.RichTextEditor,{editor:n,styles:r,children:i(J.RichTextEditor.Content,{})})};function Yp(){const[e,{open:t,close:n}]=Ie.useDisclosure(!1);return p(B,{children:[i(s.Modal,{opened:e,onClose:n,title:"About FunctionUtils",zIndex:330,withinPortal:!0,children:i(qn,{value:Gu,styles:{root:{border:"none"},content:{padding:0,table:{marginBottom:0}}}})}),i(s.Button,{variant:"light",color:"violet",size:"xs",onClick:t,leftIcon:i($.IconInfoCircle,{size:16}),children:"About parameter 'utils'"})]})}const Qp=({value:e,onChange:t})=>{const n=r=>{r&&t(r)};return i(s.Box,{sx:{position:"relative",flexGrow:1},children:i(Ae,{className:"function-editor",height:"100%",defaultLanguage:"javascript",value:e,onChange:n,theme:"vs-dark",options:{lineNumbers:"off",folding:!1,lineDecorationsWidth:20,lineNumbersMinChars:0,wordWrap:"on",minimap:{enabled:!1}}})})},ln=y.forwardRef(({value:e,onChange:t,label:n,defaultValue:r},a)=>{const[o,l]=y.useState(e),u=()=>{t(o)},c=()=>{l(e)},d=()=>{l(r)};y.useEffect(()=>{l(e)},[e]);const f=o!==e;return p(s.Stack,{spacing:4,sx:{height:"100%"},children:[p(s.Group,{mb:6,position:"apart",sx:{flexShrink:0,flexGrow:0},children:[i(s.Group,{position:"left",children:i(Yp,{})}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:d,size:"xs",variant:"default",leftIcon:i($.IconPlayerSkipBack,{size:16}),children:"Reset to default"}),i(s.Button,{onClick:c,color:"red",size:"xs",disabled:!f,leftIcon:i($.IconRecycle,{size:16}),children:"Revert Changes"}),i(s.Button,{size:"xs",onClick:u,disabled:!f,leftIcon:i($.IconDeviceFloppy,{size:16}),children:"Confirm Changes"})]})]}),i(s.Text,{size:14,children:n}),i(Qp,{value:o,onChange:l})]})}),Up=y.forwardRef(({value:e,onChange:t,label:n,triggerLabel:r="Edit",triggerButtonProps:a={},defaultValue:o},l)=>{const[u,{open:c,close:d}]=Ie.useDisclosure(!1);return p(B,{children:[i(s.Modal,{opened:u,onClose:d,title:"Authentication",withinPortal:!0,zIndex:320,size:"900px",children:i(s.Box,{h:600,children:i(ln,{value:e,onChange:t,defaultValue:o,label:n})})}),i(s.Button,{onClick:c,...a,children:r})]})}),js=["function aggregation({ queryData }, utils) {",' return "Aggregation Result";',"}"].join(`
105
- `),Nt={type:"none",config:{}};function Kp(e){const t=Array.from(e).sort((r,a)=>r-a),n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function Xp(e){const t=Number(e);return isFinite(t)?t:0}function Jp(e,t){switch(t.type){case"sum":return x.sum(e);case"mean":return x.mean(e);case"median":return Kp(e);case"max":return x.max(e)??0;case"min":return x.min(e)??0;case"quantile":return Kt.quantile(e,t.config.p)??0;case"CV":const n=Cn.std(...e),r=Cn.mean(...e);return r?n/r:"N/A";case"std":return Cn.std(...e);default:return e}}function Rr(e,t){const n=e.map(Xp);return Jp(n,t)}function Zp(e,t,n){try{const r=Ht(e,t);return new Function(`return ${n.config.func}`)()({queryData:r},Tt)}catch(r){return console.error(r),r.message}}function Fn(e,t,n){try{return n.type==="custom"?Zp(e,t,n):Rr(pt(e,t),n)}catch(r){return console.error(r),null}}const Hp=[{label:"None",value:"none"},{label:"Sum",value:"sum"},{label:"Mean",value:"mean"},{label:"Median",value:"median"},{label:"Max",value:"max"},{label:"Min",value:"min"},{label:"Coefficient of Variation",value:"CV"},{label:"Standard Variation",value:"std"},{label:"Quantile(99%, 95%, ...)",value:"quantile"},{label:"Custom",value:"custom"}];function eh({label:e,value:t,onChange:n,pt:r="sm"},a){y.useEffect(()=>{typeof t=="string"&&n({type:t,config:{}})},[t,n]);const o=c=>{n(c==="quantile"?{type:"quantile",config:{p:.99}}:c==="custom"?{type:"custom",config:{func:js}}:{type:c,config:{}})},l=c=>{n({type:"quantile",config:{p:c}})},u=c=>{n({type:"custom",config:{func:c}})};return p(s.Group,{grow:!0,noWrap:!0,pt:r,children:[i(s.Select,{ref:a,label:e,data:Hp,value:t.type,onChange:o}),t.type==="quantile"&&i(s.NumberInput,{label:"p",value:t.config.p,onChange:l,precision:2,min:.05,step:.05,max:1}),t.type==="custom"&&i(Up,{label:"",triggerLabel:"Edit Function",value:t.config.func,onChange:u,defaultValue:js,triggerButtonProps:{size:"xs",sx:{flexGrow:0,alignSelf:"center",marginTop:"22px"},leftIcon:i($.IconMathFunction,{size:16})}})]})}const Gn=y.forwardRef(eh);function th({label:e,value:t,onChange:n},r){const[a,o]=y.useState(Array.isArray(t)?[...t]:[]),l=y.useCallback(()=>{o(g=>[...g,""])},[o]),u=y.useCallback(g=>{o(m=>(m.splice(g,1),[...m]))},[o]),c=y.useMemo(()=>!x.isEqual(a,t),[a,t]),d=()=>{n(a.map(g=>g.toString()))},f=s.useMantineTheme(),h=y.useMemo(()=>Object.entries(f.colors).map(([g,m])=>m[6]),[f]);return p(B,{children:[p(s.Group,{position:"left",ref:r,children:[i(s.Text,{children:e}),i(s.ActionIcon,{mr:5,variant:"filled",color:"blue",disabled:!c,onClick:d,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Group,{children:[a.map((g,m)=>i(s.ColorInput,{value:g,onChange:C=>{o(w=>(w.splice(m,1,C),[...w]))},swatches:h,rightSection:i(s.ActionIcon,{onClick:()=>u(m),color:"red",children:i(T.Trash,{size:14})}),sx:{width:"45%"}})),i(s.ActionIcon,{onClick:l,color:"blue",variant:"outline",children:i(T.PlaylistAdd,{size:20})})]})]})}const nh=y.forwardRef(th);function rh({value:e,onChange:t},n){const{colorManager:r}=y.useContext(ut),a=y.useMemo(()=>r.getStaticColors().map(u=>({label:u.name,group:u.category,value:u.value})),[r]),o=y.useMemo(()=>a.some(l=>l.value===e),[e,a]);return p(s.Group,{position:"apart",spacing:4,ref:n,children:[i(s.TextInput,{placeholder:"Set any color",value:o?"":e,onChange:l=>t(l.currentTarget.value),rightSection:i(s.ColorSwatch,{color:o?"transparent":e,radius:4}),variant:o?"filled":"default",sx:{maxWidth:"46%",flexGrow:1}}),i(s.Text,{sx:{flexGrow:0},children:"or"}),i(s.Select,{data:a,value:e,onChange:t,variant:o?"default":"filled",placeholder:"Pick a theme color",icon:i(s.ColorSwatch,{color:o?e:"transparent",radius:4}),sx:{maxWidth:"46%",flexGrow:1}})]})}const Ve=y.forwardRef(rh),Wn=[{label:"initial",value:0},{label:"500",value:25},{label:"700",value:50},{label:"semibold",value:75},{label:"bold",value:100}];function ih({label:e,value:t,onChange:n},r){var l;const[a,o]=y.useState(((l=Wn.find(u=>u.label===t))==null?void 0:l.value)??Wn[0].value);return y.useEffect(()=>{const u=Wn.find(c=>c.value===a);u&&n(u.label)},[a]),p(s.Stack,{spacing:0,mt:"sm",mb:"lg",children:[i(s.Text,{size:"sm",children:e}),i(s.Slider,{label:null,marks:Wn,value:a,onChange:o,step:25,placeholder:"Pick a font size",px:"1em",ref:r})]})}const Rs=y.forwardRef(ih);function ah({label:e,value:t,onChange:n,type:r},a){const[o,l]=y.useState(Array.isArray(t)?[...t]:[]),u=y.useCallback(()=>{l(h=>[...h,""])},[l]),c=y.useCallback(h=>{l(g=>(g.splice(h,1),[...g]))},[l]),d=y.useMemo(()=>!x.isEqual(o.map(String),t.map(String)),[o,t]),f=()=>{n(o.map(h=>r==="number"?Number(h):h.toString()))};return p(B,{children:[p(s.Group,{position:"left",ref:a,children:[i(s.Text,{children:e}),i(s.ActionIcon,{mr:5,variant:"filled",color:"blue",disabled:!d,onClick:f,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Group,{children:[o.map((h,g)=>i(s.TextInput,{type:r,value:h,onChange:m=>{const C=m.currentTarget.value;l(w=>(w.splice(g,1,C),[...w]))},rightSection:i(s.ActionIcon,{onClick:()=>c(g),color:"red",children:i(T.Trash,{size:14})}),sx:{width:"45%"}})),i(s.ActionIcon,{onClick:u,color:"blue",variant:"outline",children:i(T.PlaylistAdd,{size:20})})]})]})}const sh=y.forwardRef(ah),Ys=y.forwardRef(function({value:t,onChange:n},r){const a=t.color.type,o=(u,c)=>{const d=x.cloneDeep(t);x.set(d,u,c),n(d)},l=u=>{if(u==="static"){n({...t,color:{type:"static",staticColor:"#25262B"}});return}n({...t,color:{type:"continuous",colorRange:[],valueRange:[]}})};return p(B,{children:[i(s.Divider,{my:"xs",label:"Typography",labelPosition:"center"}),i(s.Stack,{children:i(s.TextInput,{label:"Font Size",placeholder:"10px, 1em, 1rem, 100%...",sx:{flex:1},value:t.size,onChange:u=>o("size",u.currentTarget.value)})}),i(s.Group,{position:"apart",grow:!0,sx:{"> *":{flexGrow:1,maxWidth:"100%"}},children:i(Rs,{label:"Font Weight",value:t.weight,onChange:u=>o("weight",u)})}),i(s.Divider,{my:"xs",label:"Style",labelPosition:"center"}),p(s.Stack,{children:[i(s.Select,{label:"Color Type",data:[{label:"Static Color",value:"static"},{label:"Continuous Color",value:"continuous"}],value:t.color.type,onChange:l}),a==="static"&&i(Ve,{value:t.color.staticColor,onChange:u=>o("color.staticColor",u)}),a==="continuous"&&p(B,{children:[i(sh,{label:"Value Range",value:t.color.valueRange,type:"number",onChange:u=>o("color.valueRange",u)}),i(nh,{label:"Color Range",value:t.color.colorRange,onChange:u=>o("color.colorRange",u)})]})]})]})});y.forwardRef(function({value:t,onChange:n,withStyle:r=!0},a){const o=(l,u)=>{const c=x.cloneDeep(t);x.set(c,l,u),n(c)};return p(s.Box,{px:"sm",py:"md",ref:a,children:[i(s.Text,{weight:"bold",pb:0,children:t.name}),i(s.Divider,{my:"xs",label:"Data",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(s.TextInput,{label:"Name",required:!0,value:t.name,onChange:l=>o("name",l.currentTarget.value)}),i(W,{label:"Data Field",required:!0,value:t.data_field,onChange:l=>o("data_field",l)})]}),i(Gn,{label:"Aggregation",value:t.aggregation,onChange:l=>o("aggregation",l)}),i(s.Divider,{my:"xs",label:"Format",labelPosition:"center"}),t.aggregation.type!=="custom"&&i(We,{value:t.formatter,onChange:l=>o("formatter",l)}),r&&i(Ys,{value:t,onChange:n})]})});class oh{constructor({valueRange:t,colorRange:n}){N(this,"mapper");this.mapper=_t.interpolate(t,n)}getColor(t){return this.mapper(t)}}function lh(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?`Array(${e.length})`:e.toString()}function ft({data_field:e,aggregation:t},n){return Fn(n,e,t)}function Ze({formatter:e,aggregation:t},n){if(!["string","number"].includes(typeof n))return lh(n);if(t.type==="custom")return n;try{return Z(n).format(e)}catch(r){return console.error(r),n}}function uh(e,t){if(e.type==="static")return e.staticColor;if(e.type==="continuous")try{if(typeof t!="number")throw new Error(`[getColorByColorConf] Invalid type of aggregated value: ${t}`);return new oh(e).getColor(t)}catch(n){return console.error(n),"black"}return"black"}function Qs(e,t){const{color:n,data_field:r,aggregation:a,size:o,weight:l}=e,u=Fn(t,r,a),c=Ze(e,u);return i(s.Text,{sx:{fontSize:o,display:"inline"},color:uh(n,u),weight:l,children:c})}function ch(e,t){const n={};return e.forEach(r=>{const a=r.name;n[a]=Qs(r,t)}),n}function dh(e){return e.split(" ").map((t,n)=>p(y.Fragment,{children:[t," "]},n))}function ph(e){const n=e.replaceAll("<br />","<br/>").replaceAll(`
106
- `,"<br/>").split("<br/>");return n.map((a,o)=>{const l=[dh(a)];return o!==n.length-1&&l.push(i("br",{},`br-${o}`)),l}).flat().filter(a=>a!==void 0)}function Yr(e){return ph(e)}function un(e,t,n){const r=ch(t,n),a=/^\{(.+)\}(.*)$/;return e.split("$").map((o,l)=>{const u=a.exec(o);if(!u)return Yr(o);const c=r[u[1]];if(!c)return Yr(o);const d=u[2]??"";return p(y.Fragment,{children:[c,Yr(d)]},`${o}-${l}`)})}function hh(e,t){const n={};return e.forEach(r=>{const{name:a,data_field:o,aggregation:l}=r,u=Fn(t,o,l);n[a]=Ze(r,u)}),n}function jn(e,t,n){const r=hh(t,n),a=/^\{(.+)\}(.*)$/;return e.split("$").map(o=>{const l=a.exec(o);if(!l)return o;const u=r[l[1]];if(!u)return o;const c=l[2]??"";return`${u}${c}`}).join("")}function fh(e,t,n){const r=t.reduce((a,o)=>{const l=ft(o,n);return a[o.name]=Ze(o,l),a},{});return e.map(a=>({name:"refs",type:"scatter",data:[],markLine:{data:[{name:a.name,yAxis:Number(r[a.variable_key])}],silent:!0,symbol:["none","none"],label:{formatter:function(){return jn(a.template,t,n)},position:"insideEndTop"}}}))}function gh(e){const t={top:30,left:20,right:15,bottom:25,containLabel:!0};return e.legend.orient==="vertical"&&(t.right=80),t}function mh({config:e,data:t,variables:n}){const{x_axis:r,y_axis:a,reference_lines:o}=e,l=dd(e,t),u=rt(r.axisLabel.overflow.on_axis),c=hd(e);return{grid:gh(e),dataset:l,legend:pd({config:e}),tooltip:vd({config:e}),xAxis:[{type:"category",name:r.name,nameGap:25,nameLocation:"center",nameTextStyle:{fontWeight:"bold",align:"center"},axisTick:{show:!0,alignWithLabel:!0},axisLabel:{...r.axisLabel,...u,formatter:Pt(r.axisLabel.formatter)}}],yAxis:[{name:a.name,minInterval:1,nameTextStyle:{fontWeight:"bold"},axisLine:{show:!0},axisLabel:{formatter:function(d){return Z(d).format(a.label_formatter)}}}],series:[...c,...fh(o,n,t)]}}ie.use([q.DataZoomComponent,he.BoxplotChart,q.MarkLineComponent,q.GridComponent,q.LegendComponent,q.TooltipComponent,Pe.CanvasRenderer]);function yh({context:e,instance:t}){const{value:n}=R(e.instanceData,"config"),{variables:r}=e,a=e.data,{width:o,height:l}=e.viewport,u=x.defaults({},n,kr),c=Xe({vizManager:e.vizManager,instance:t}),d=Ke(c.triggerManager,os.id),f=Dt(a,u.x_axis.data_key),h=y.useCallback(C=>{const w=x.get(f,C.name,{error:"rowData is not found"});d.forEach(_=>{c.runInteraction(_.id,{...C,rowData:w})})},[f,d,c]),g=y.useMemo(()=>({click:h}),[h]),m=y.useMemo(()=>mh({config:u,data:a,variables:r}),[u,a,r]);return!n||!o||!l?null:i(Be,{echarts:ie,option:m,style:{width:o,height:l},onEvents:g,notMerge:!0,theme:"merico-light"})}function bh({control:e,index:t,remove:n,variableOptions:r}){return p(s.Stack,{my:0,p:"md",pr:40,sx:{border:"1px solid #eee",position:"relative"},children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`reference_lines.${t}.name`,control:e,render:({field:a})=>i(s.TextInput,{label:"Name",placeholder:"Average Reference Line",required:!0,sx:{flex:1},...a})}),i(v.Controller,{name:`reference_lines.${t}.variable_key`,control:e,render:({field:a})=>i(s.Select,{label:"Value",required:!0,data:r,sx:{flex:1},...a})})]}),i(v.Controller,{name:`reference_lines.${t}.template`,control:e,render:({field:a})=>i(s.TextInput,{label:"Content Template",placeholder:"Average: ${avg}",required:!0,sx:{flex:1},...a})}),i(s.ActionIcon,{color:"red",variant:"subtle",onClick:()=>n(t),sx:{position:"absolute",top:15,right:5},children:i(T.Trash,{size:16})})]},t)}function vh({control:e,watch:t,variables:n}){const{fields:r,append:a,remove:o}=v.useFieldArray({control:e,name:"reference_lines"}),l=t("reference_lines"),u=r.map((f,h)=>({...f,...l[h]})),c=()=>a({name:"",template:"",variable_key:""}),d=y.useMemo(()=>n.map(f=>({label:f.name,value:f.name})),[n]);return p(s.Stack,{children:[u.map((f,h)=>i(bh,{control:e,index:h,remove:o,variableOptions:d},f.id)),i(s.Group,{position:"center",mt:"xs",children:i(s.Button,{onClick:c,children:"Add a Reference Line"})})]})}const xh=({disabled:e,value:t,onChange:n})=>{const r=a=>{a&&n(a)};return p(s.Box,{sx:{position:"relative"},children:[e&&i(s.Overlay,{opacity:.6,color:"#fff",zIndex:5,blur:2}),i(Ae,{height:"500px",defaultLanguage:"javascript",value:t,onChange:r,theme:"vs-dark",options:{minimap:{enabled:!1},readOnly:e}})]})},Rn=y.forwardRef(({value:e,onChange:t},n)=>{const[r,{setTrue:a,setFalse:o}]=K.useBoolean(),[l,u]=y.useState(e);y.useEffect(()=>{u(e)},[e]);const c=m=>{u({...l,enabled:m})},d=()=>{o();const{enabled:m,func_content:C}=l,w={enabled:m,func_content:C};u(w),t(w)},f=()=>{o(),u(e)},h=m=>{u(C=>({...C,func_content:m}))},g=()=>{h(Ue.func_content)};return p(B,{children:[i(s.Button,{variant:"filled",mt:24,onClick:a,sx:{flexGrow:0},children:"Customize Label"}),i(s.Modal,{size:800,title:"Customize label content",opened:r,onClose:o,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:r&&p(s.Stack,{children:[i(s.Checkbox,{mt:10,label:"Enabled",checked:l.enabled,onChange:m=>c(m.currentTarget.checked)}),i(xh,{value:l.func_content,onChange:h,disabled:!l.enabled}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:g,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:f,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:d,children:"OK"})]})]})]})})]})}),wh=({control:e,watch:t})=>(t(["x_axis"]),p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"X Axis Name",sx:{flex:1},...n})}),i(v.Controller,{name:"x_axis.data_key",control:e,render:({field:n})=>i(W,{label:"X Axis Data Field",required:!0,sx:{flex:1},...n})})]}),i(s.Divider,{mb:-15,label:"Tick Label",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.axisLabel.rotate",control:e,render:({field:n})=>i(s.NumberInput,{label:"Rotate",hideControls:!0,min:-90,max:90,rightSection:i(s.Text,{color:"dimmed",children:"degree"}),sx:{width:"48%"},styles:{rightSection:{width:"4em",justifyContent:"flex-end",paddingRight:"6px"}},...n})}),i(v.Controller,{name:"x_axis.axisLabel.formatter",control:e,render:({field:n})=>i(Rn,{...n})})]}),i(v.Controller,{name:"x_axis.axisLabel.overflow",control:e,render:({field:n})=>i(at,{...n})})]})),Ch=({control:e,watch:t})=>(t(["y_axis"]),p(B,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"y_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Y Axis Name",sx:{flex:1},...n})}),i(v.Controller,{name:"y_axis.data_key",control:e,render:({field:n})=>i(W,{label:"Y Axis Data Field",required:!0,sx:{flex:1},...n})})]}),p(s.Stack,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Label Format",labelPosition:"center"}),i(v.Controller,{name:"y_axis.label_formatter",control:e,render:({field:n})=>i(We,{...n})})]})]})),Sh=({control:e,index:t,remove:n})=>p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`tooltip.metrics.${t}.name`,control:e,render:({field:r})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:`tooltip.metrics.${t}.data_key`,control:e,render:({field:r})=>i(W,{label:"Value Field",required:!0,sx:{flex:1},...r})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed"}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Metric"})]}),_h=({control:e,watch:t})=>{const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"tooltip.metrics"}),o=t("tooltip.metrics"),l=n.map((h,g)=>({...h,...o[g]})),u=()=>r({id:Date.now().toString(),data_key:"",name:""}),c=t("tooltip.metrics.0.id"),[d,f]=y.useState(()=>c??null);return y.useEffect(()=>{c&&f(h=>h!==null?h:c)},[c]),p(B,{children:[p(s.Group,{spacing:2,sx:{cursor:"default",userSelect:"none"},children:[i(T.InfoCircle,{size:14,color:"#888"}),i(s.Text,{size:14,color:"#888",children:"Set additional metrics to show in scatter's tooltip"})]}),p(s.Tabs,{value:d,onTabChange:h=>f(h),styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map((h,g)=>i(s.Tabs.Tab,{value:h.id,children:h.name?h.name:g},h.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((h,g)=>i(s.Tabs.Panel,{value:h.id,children:i(Sh,{control:e,index:g,remove:a},h.id)},h.id))]})]})};function kh({control:e,watch:t}){return i(s.Stack,{children:i(_h,{control:e,watch:t})})}const Th=[{label:"Horizontal",value:"horizontal"},{label:"Vertical",value:"vertical"}],Dh=({control:e,watch:t})=>{const n=t("legend"),r=(a,o)=>{const l={...n,orient:a};a==="horizontal"?(l.top="0",l.left="auto",l.right="10",l.bottom="auto"):(l.top="10",l.left="auto",l.right="0",l.bottom="auto"),o(l)};return p(s.Stack,{children:[i(s.Group,{grow:!0,noWrap:!0,mt:20,children:i(v.Controller,{name:"legend.show",control:e,render:({field:a})=>i(s.Switch,{label:"Show Legend",sx:{flex:1},checked:a.value,onChange:o=>a.onChange(o.currentTarget.checked)})})}),i(s.Group,{children:i(v.Controller,{name:"legend",control:e,render:({field:a})=>i(s.Select,{label:"Orientation",data:Th,sx:{flex:1},value:a.value.orient,onChange:o=>{r(o,a.onChange)},disabled:!n.show})})})]})};function Ih({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),{variables:r}=e,a=y.useMemo(()=>x.defaults({},t,kr),[t]),{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});y.useEffect(()=>{d(a)},[a]),u(["x_axis","y_axis","reference_lines","color"]);const f=c(),h=y.useMemo(()=>!x.isEqual(f,t),[f,t]);return i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:l(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"X Axis",orientation:"vertical",styles:{tab:{paddingLeft:"6px",paddingRight:"6px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"X Axis",children:"X Axis"}),i(s.Tabs.Tab,{value:"Y Axis",children:"Y Axis"}),i(s.Tabs.Tab,{value:"Legend",children:"Legend"}),i(s.Tabs.Tab,{value:"Tooltip",children:"Tooltip"}),i(s.Tabs.Tab,{value:"Style",children:"Style"}),i(s.Tabs.Tab,{value:"Reference Lines",children:"Reference Lines"})]}),i(s.Tabs.Panel,{value:"X Axis",children:i(wh,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Y Axis",children:i(Ch,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Legend",children:i(Dh,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Tooltip",children:i(kh,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Style",children:p(s.Stack,{spacing:4,children:[i(s.Text,{size:"sm",children:"Color"}),i(v.Controller,{name:"color",control:o,render:({field:g})=>i(Ve,{...g})})]})}),i(s.Tabs.Panel,{value:"Reference Lines",children:i(vh,{variables:r,control:o,watch:u})})]})]})})}function Mh(e){return x.omit(e,"variables")}function Ah(e){const{label_formatter:t=ze,...n}=e.y_axis;return{...e,y_axis:{...n,label_formatter:t}}}function zh(e){const t={rotate:0,formatter:{...Ue}},{axisLabel:n=t,...r}=e.x_axis;return{...e,x_axis:{...r,axisLabel:n}}}function Eh(e){const t={x_axis:{axisLabel:{overflow:{x_axis:{width:80,overflow:"truncate",ellipsis:"..."},tooltip:{width:200,overflow:"break",ellipsis:"..."}}}}};return x.defaultsDeep(t,e)}function $h(e){delete e.config;const{x_axis:t,tooltip:n}=e.x_axis.axisLabel.overflow,r={x_axis:{axisLabel:{overflow:{on_axis:t,in_tooltip:n}}}};return x.defaultsDeep(r,e)}function Lh(e){const t={tooltip:{metrics:[]}};return x.defaultsDeep(t,e)}function Oh(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=c=>c&&`${n}.${c}`,{x_axis:a,y_axis:o,tooltip:l,...u}=e;return{...u,x_axis:{...a,data_key:r(a.data_key)},y_axis:{...o,data_key:r(o.data_key)},tooltip:{...l,metrics:l.metrics.map(c=>({...c,data_key:r(c.data_key)}))}}}catch(n){throw console.error("[Migration failed]",n),n}}function Ph(e){const t={legend:{show:!0,top:"0",right:"10",left:"auto",bottom:"auto",orient:"horizontal",type:"scroll"}};return x.defaultsDeep(t,e)}class Bh extends ye{constructor(){super(...arguments);N(this,"VERSION",9)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,(n,{panelModel:r})=>{const{config:a}=n;return(a.variables||[]).forEach(l=>{r.variables.find(u=>u.name===l.name)||r.addVariable(l)}),{...n,version:2,config:Mh(a)}}),this.version(3,n=>{const{config:r}=n;return{...n,version:3,config:Ah(r)}}),this.version(4,n=>{const{config:r}=n;return{...n,version:4,config:zh(r)}}),this.version(5,n=>{const{config:r}=n;return{...n,version:5,config:Eh(r)}}),this.version(6,n=>{const{config:r}=n;return{...n,version:6,config:$h(r)}}),this.version(7,n=>{const{config:r}=n;return{...n,version:7,config:Lh(r)}}),this.version(8,(n,r)=>{const{config:a}=n;return{...n,version:8,config:Oh(a,r)}}),this.version(9,n=>{const{config:r}=n;return{...n,version:9,config:Ph(r)}})}}const Vh={displayName:"Boxplot Chart",displayGroup:"ECharts-based charts",migrator:new Bh,name:"boxplot",viewRender:yh,configRender:Ih,createConfig(){return{version:9,config:x.cloneDeep(kr)}},triggers:[os]},Us={id:"builtin:button:click-button",displayName:"Click Button",nameRender:qh,configRender:Nh,payload:[]};function Nh(e){return i(B,{})}function qh(e){return i(s.Text,{children:"Click this button"})}const Qr={content:"Button",variant:"filled",color:"blue",size:"xs",compact:!1,horizontal_align:"left",vertical_align:"center"},Fh={left:"flex-start",center:"center",right:"flex-end"},Gh={top:"flex-start",center:"center",bottom:"flex-end"},Wh=k.observer(({context:e,instance:t})=>{const n=Xe({vizManager:e.vizManager,instance:t}),r=Ke(n.triggerManager,Us.id),a=we(),{value:o}=R(e.instanceData,"config"),l=y.useMemo(()=>x.defaultsDeep({},o,Qr),[o]),{content:u,horizontal_align:c,vertical_align:d,...f}=l,{width:h,height:g}=e.viewport,m=a.payloadForSQL,C=()=>{r.forEach(w=>{n.runInteraction(w.id,{})})};return i(s.Center,{sx:{width:h,height:g,justifyContent:Fh[c],alignItems:Gh[d]},children:i(s.Button,{...f,onClick:C,children:x.template(u)(m)})})}),jh=({value:e,onChange:t,label:n})=>{const r=s.useMantineTheme(),a=y.useCallback(l=>()=>t(l),[t]),o=l=>e===l;return p(s.Stack,{spacing:2,children:[i(s.Text,{size:14,sx:{fontWeight:500},children:n}),i(s.Group,{position:"left",spacing:"xs",children:Object.keys(r.colors).map(l=>{const u=r.colors[l][6];return i(s.ColorSwatch,{color:u,onClick:a(l),radius:4,size:26,sx:{cursor:"pointer"},children:o(l)&&i(s.CheckIcon,{width:10,color:"white"})},l)})})]})},Rh=s.MANTINE_SIZES.map(e=>({label:e.toUpperCase(),value:e})),Yh=({label:e,value:t,onChange:n})=>i(s.Select,{data:Rh,label:e,value:t,onChange:n}),Qh=[{label:"Filled",value:"filled"},{label:"Outline",value:"outline"},{label:"Light",value:"light"},{label:"White",value:"white"},{label:"Default",value:"default"},{label:"Subtle",value:"subtle"},{label:"Gradient",value:"gradient",disabled:!0}],Uh=[{label:"Left",value:"left"},{label:"Center",value:"center"},{label:"Right",value:"right"}],Kh=[{label:"Top",value:"top"},{label:"Center",value:"center"},{label:"Bottom",value:"bottom"}];function Xh({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=y.useMemo(()=>x.defaultsDeep({},t,Qr),[t]),a=r;y.useEffect(()=>{!x.isEqual(r,a)&&(console.log("config malformed, resetting to defaults",r,a),n(a))},[r,a]);const{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});y.useEffect(()=>{d(a)},[a]);const f=c(),h=y.useMemo(()=>!x.isEqual(f,r),[f,r]);return u(["content","variant","color","size","compact","horizontal_align","vertical_align"]),p("form",{onSubmit:l(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Stack,{children:[i(v.Controller,{control:o,name:"content",render:({field:g})=>i(s.TextInput,{label:"Content Template",description:"Filter values & context entries are supported",...g,required:!0})}),i(s.Divider,{mt:"xs",mb:0,label:"Styles",labelPosition:"center",variant:"dashed"}),p(s.SimpleGrid,{cols:2,children:[i(v.Controller,{control:o,name:"variant",render:({field:g})=>i(s.Select,{label:"Variant",data:Qh,...g})}),i(v.Controller,{control:o,name:"color",render:({field:g})=>i(jh,{label:"Theme",...g})})]}),p(s.SimpleGrid,{cols:2,children:[i(v.Controller,{control:o,name:"size",render:({field:g})=>i(Yh,{label:"Size",...g})}),i(v.Controller,{control:o,name:"compact",render:({field:g})=>i(s.Checkbox,{label:"Compact",checked:g.value,onChange:m=>g.onChange(m.currentTarget.checked),mt:26})})]}),p(s.SimpleGrid,{cols:2,children:[i(v.Controller,{control:o,name:"horizontal_align",render:({field:g})=>i(s.Select,{label:"Horizontal Alignment",data:Uh,...g})}),i(v.Controller,{control:o,name:"vertical_align",render:({field:g})=>i(s.Select,{label:"Vertical Alignment",data:Kh,...g})})]})]})]})}class Jh extends ye{constructor(){super(...arguments);N(this,"VERSION",2)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,n=>{const{horizontal_align:r="left",vertical_align:a="center",...o}=n.config;return{...n,version:2,config:{...o,horizontal_align:r,vertical_align:a}}})}}const Zh={displayName:"Button",displayGroup:"Others",migrator:new Jh,name:"button",viewRender:Wh,configRender:Xh,createConfig(){return{version:2,config:x.cloneDeep(Qr)}},triggers:[Us]},Ur={id:"builtin:echarts:click-echart:series",displayName:"Click Chart Series",nameRender:ef,configRender:Hh,payload:[{name:"seriesType",description:"'line' | 'scatter' | 'bar'",valueType:"string"},{name:"componentType",description:"'series'",valueType:"string"},{name:"name",description:"Name of the series clicked",valueType:"string"},{name:"color",description:"Color",valueType:"string"},{name:"value",description:"String-typed number, or series' actual value",valueType:"string"},{name:"rowData",description:"Data of the row",valueType:"object"}]};function Hh(e){return i(B,{})}function ef(e){return i(s.Text,{children:"Click chart's series"})}const qt={x_axis_scroll:!1,y_axis_scroll:!1,x_axis_slider:!1,y_axis_slider:!1},Kr={regressions:[],series:[],stats:{templates:{bottom:"",top:""}},x_axis:{type:"category",axisLabel:{rotate:0,formatter:{...Ue},overflow:je}},x_axis_data_key:"",x_axis_name:"",y_axes:[{min:"",max:"",name:"Y Axis",show:!0,position:"left",nameAlignment:"center",label_formatter:ze}],reference_lines:[],reference_areas:[],dataZoom:qt};function Xr(e){const t=[];return e.x_axis_scroll&&t.push({type:"inside",xAxisIndex:[0],filterMode:"none",minSpan:1}),e.y_axis_scroll&&t.push({type:"inside",yAxisIndex:[0],filterMode:"none",minSpan:1}),e.x_axis_slider&&t.push({type:"slider",xAxisIndex:[0],filterMode:"none",bottom:"auto",top:0,height:15,moveHandleSize:0,showDataShadow:!1,minSpan:1}),t}function tf(e){const t=e.y_axes.some(a=>!!a.name);let n=15;t&&(n+=20),e.dataZoom.x_axis_slider&&(n+=20);let r=5;return e.x_axis_name&&(r+=15),e.series.some(a=>!a.hide_in_legend)&&(r+=20),{top:n,right:15,bottom:r,left:20,containLabel:!0}}function nf(e){return e!=="line"?{}:{itemStyle:{opacity:0}}}function rf(e){switch(e){case"line":return;case"bar":return"roundRect";case"scatter":return"circle"}}function af(e){const t={show:!0,bottom:0,left:"center",type:"scroll"};return t.data=e.filter(n=>!n.hide_in_legend).map(({name:n,type:r})=>({name:n,icon:rf(r),...nf(r)})),t}function Yn(e,t){switch(e.config.method){case"linear":return[...yt.regressionLinear()(t)];case"exponential":return[...yt.regressionExp()(t)];case"logarithmic":return[...yt.regressionLog()(t)];case"polynomial":return[...yt.regressionPoly().order(e.config.order)(t)];default:return[]}}function sf(e,t,n,r){const{transform:a,plot:o}=e,l={...o,name:t,data:Yn(a,r),showSymbol:!1,tooltip:{show:!1},smooth:!1,custom:{}};return n&&(l.custom={type:"regression-line",targetSeries:n}),l}function of({regressions:e=[],x_axis_data_key:t},n){const r=[];if(Object.keys(n).length===0)return r;function a(o,l,u,c){const d=sf(o,l,u,c);r.push(d)}return e.forEach(o=>{const{name:l,group_by_key:u}=o;if(!u||u===t){const h=pt(n,o.y_axis_data_key).map((g,m)=>[m,Number(g)]);a(o,l,"",h);return}const{columnKey:c}=O(o.y_axis_data_key),d=x.groupBy(Ht(n,o.y_axis_data_key),u);Object.entries(d).forEach(([f,h])=>{const g=h.map((C,w)=>[w,Number(C[c])]);a(o,f,f,g)})}),r}function lf(e,t){return e.map(n=>({name:"",type:"line",hide_in_legend:!0,data:[],markArea:{itemStyle:{color:n.color},data:[[{yAxis:t[n.y_keys.upper]},{yAxis:t[n.y_keys.lower]}]],silent:!0}}))}function uf(e,t,n,r){return e.map(a=>{const o=a.orientation==="horizontal",l=o?"yAxis":"xAxis",u=o?"insideEndTop":"end";return{name:a.name,type:"line",hide_in_legend:!a.show_in_legend,yAxisIndex:a.yAxisIndex,data:[],lineStyle:a.lineStyle,markLine:{data:[{name:a.name,[l]:n[a.variable_key]}],silent:!0,symbol:["none","none"],lineStyle:a.lineStyle,label:{formatter:function(){return a.template?jn(a.template,t,r):""},position:u}}}})}function cf({type:e,...t},n,r,a){if(!e)return 10;if(e==="static"){const{size:d}=t;return d}const{func_content:o}=t,{queryID:l,columnKey:u}=O(r),c=x.keyBy(Ht(n,l),u);return(d,f)=>{let h;f.name?h=c[f.name]:h=n[f.dataIndex];try{return new Function(`return ${o}`)()({rowData:h,params:f,variables:a},{lodash:x,interpolate:_t.interpolate})}catch(g){return console.error(`[getEchartsSymbolSize] failed parsing custom function, error: ${g.message}`),10}}}function Jr(e,t,n){const r=pt(e,t),a=pt(e,n);return x.zip(r,a)}function df(e,t,n,r){const a=Jr(t,n,r);return x.unionBy(a,e,0)}function pf({dataTemplate:e,data:t,x_axis_data_key:n,y_axis_data_key:r,valueTypedXAxis:a}){return a?df(e,t,n,r):pt(t,r)}function hf({dataTemplate:e,data:t,aggregation_on_value:n,x_axis_data_key:r,y_axis_data_key:a,valueTypedXAxis:o}){if(!n||n.type==="none")return pf({dataTemplate:e,data:t,x_axis_data_key:r,y_axis_data_key:a,valueTypedXAxis:o});const l=Jr(t,r,a),u=x.groupBy(l,"0");return e.map(([d])=>{const h=u[d].map(m=>m[1]),g=Rr(h,n);return[d,g]})}function ff({group_by_key:e,data:t,x_axis_data_key:n,y_axis_data_key:r}){const{queryID:a,columnKey:o}=O(e),l=x.groupBy(t[a],o);return Object.entries(l).forEach(([u,c])=>{l[u]=Jr({[a]:c},n,r)}),l}function gf({x_axis_data_key:e,x_axis:t},{y_axis_data_key:n,yAxisIndex:r,label_position:a,name:o,group_by_key:l,aggregation_on_value:u,stack:c,color:d,display_name_on_line:f,symbolSize:h,hide_in_legend:g,...m},C,w,_,D){const M=t.type!=="category",P={label:{show:!!a,position:a,formatter:D[r??"default"]},name:o,xAxisId:"main-x-axis",yAxisIndex:r,stack:c,color:d,symbolSize:cf(h,w,e,_),hide_in_legend:g,labelLayout:{hideOverlap:!0},...m};if(f&&(P.endLabel={show:!0,formatter:o,offset:[-12,12],align:"right"}),!l||l===e)return P.data=hf({dataTemplate:C,data:w,aggregation_on_value:u,x_axis_data_key:e,y_axis_data_key:n,valueTypedXAxis:M}),P;const G=ff({group_by_key:l,data:w,x_axis_data_key:e,y_axis_data_key:n});return Object.entries(G).map(([L,z])=>{const A=x.cloneDeep(P);return A.name=L,A.color=void 0,A.data=z,A})}function mf(e,t,n,r,a,o){const l=t.map(c=>[c,0]);return e.series.map(c=>gf(e,c,l,n,o,r)).flat().concat(uf(e.reference_lines,a,o,n)).concat(lf(e.reference_areas,o))}function yf(e,t){const n=e.find(o=>o.axisDim==="x"&&o.axisId==="main-x-axis");if(!n)return"";const{axisValue:r,axisIndex:a}=n;return Pt(t.x_axis.axisLabel.formatter)(r,a)}function bf(e,t,n){const r=t.reduce((a,{yAxisIndex:o,name:l})=>(a[l]=o,a),{});return{trigger:"axis",confine:!0,formatter:function(a){const o=Array.isArray(a)?a:[a];if(o.length===0)return"";const l=o.map(({seriesName:d,marker:f,value:h})=>{if(Array.isArray(h)&&h.length===2&&(h=h[1]),!d)return h;const g=r[d],m=n[g]??n.default;return`
104
+ `,textSerializers:l={}}=n||{};let u="",c=!0;return e.nodesBetween(r,a,(d,f,h,g)=>{var m;const C=l==null?void 0:l[d.type.name];C?(d.isBlock&&!c&&(u+=o,c=!0),h&&(u+=C({node:d,pos:f,parent:h,index:g,range:t}))):d.isText?(u+=(m=d==null?void 0:d.text)===null||m===void 0?void 0:m.slice(Math.max(r,f)-f,a-f),c=!1):d.isBlock&&!c&&(u+=o,c=!0)}),u}function qd(e){return Object.fromEntries(Object.entries(e.nodes).filter(([,t])=>t.spec.toText).map(([t,n])=>[t,n.spec.toText]))}lt.create({name:"clipboardTextSerializer",addProseMirrorPlugins(){return[new on({key:new ln("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:e}=this,{state:t,schema:n}=e,{doc:r,selection:a}=t,{ranges:o}=a,l=Math.min(...o.map(f=>f.$from.pos)),u=Math.max(...o.map(f=>f.$to.pos)),c=qd(n);return Nd(r,{from:l,to:u},{textSerializers:c})}}})]}});const Fd=()=>({editor:e,view:t})=>(requestAnimationFrame(()=>{var n;e.isDestroyed||(t.dom.blur(),(n=window==null?void 0:window.getSelection())===null||n===void 0||n.removeAllRanges())}),!0),Gd=(e=!1)=>({commands:t})=>t.setContent("",e),Wd=()=>({state:e,tr:t,dispatch:n})=>{const{selection:r}=t,{ranges:a}=r;return n&&a.forEach(({$from:o,$to:l})=>{e.doc.nodesBetween(o.pos,l.pos,(u,c)=>{if(u.type.isText)return;const{doc:d,mapping:f}=t,h=d.resolve(f.map(c)),g=d.resolve(f.map(c+u.nodeSize)),m=h.blockRange(g);if(!m)return;const C=Ad(m);if(u.type.isTextblock){const{defaultType:w}=h.parent.contentMatchAt(h.index());t.setNodeMarkup(m.start,w)}(C||C===0)&&t.lift(m,C)})}),!0},jd=e=>t=>e(t),Rd=()=>({state:e,dispatch:t})=>Me.createParagraphNear(e,t),Yd=()=>({tr:e,dispatch:t})=>{const{selection:n}=e,r=n.$anchor.node();if(r.content.size>0)return!1;const a=e.selection.$anchor;for(let o=a.depth;o>0;o-=1)if(a.node(o).type===r.type){if(t){const u=a.before(o),c=a.after(o);e.delete(u,c).scrollIntoView()}return!0}return!1},Qd=e=>({tr:t,state:n,dispatch:r})=>{const a=Le(e,n.schema),o=t.selection.$anchor;for(let l=o.depth;l>0;l-=1)if(o.node(l).type===a){if(r){const c=o.before(l),d=o.after(l);t.delete(c,d).scrollIntoView()}return!0}return!1},Ud=e=>({tr:t,dispatch:n})=>{const{from:r,to:a}=e;return n&&t.delete(r,a),!0},Kd=()=>({state:e,dispatch:t})=>Me.deleteSelection(e,t),Xd=()=>({commands:e})=>e.keyboardShortcut("Enter"),Jd=()=>({state:e,dispatch:t})=>Me.exitCode(e,t);function Bn(e,t,n={strict:!0}){const r=Object.keys(t);return r.length?r.every(a=>n.strict?t[a]===e[a]:Bd(t[a])?t[a].test(e[a]):t[a]===e[a]):!0}function Nr(e,t,n={}){return e.find(r=>r.type===t&&Bn(r.attrs,n))}function Zd(e,t,n={}){return!!Nr(e,t,n)}function Os(e,t,n={}){if(!e||!t)return;let r=e.parent.childAfter(e.parentOffset);if(e.parentOffset===r.offset&&r.offset!==0&&(r=e.parent.childBefore(e.parentOffset)),!r.node)return;const a=Nr([...r.node.marks],t,n);if(!a)return;let o=r.index,l=e.start()+r.offset,u=o+1,c=l+r.node.nodeSize;for(Nr([...r.node.marks],t,n);o>0&&a.isInSet(e.parent.child(o-1).marks);)o-=1,l-=e.parent.child(o).nodeSize;for(;u<e.parent.childCount&&Zd([...e.parent.child(u).marks],t,n);)c+=e.parent.child(u).nodeSize,u+=1;return{from:l,to:c}}function xt(e,t){if(typeof e=="string"){if(!t.marks[e])throw Error(`There is no mark type named '${e}'. Maybe you forgot to add the extension?`);return t.marks[e]}return e}const Hd=(e,t={})=>({tr:n,state:r,dispatch:a})=>{const o=xt(e,r.schema),{doc:l,selection:u}=n,{$from:c,from:d,to:f}=u;if(a){const h=Os(c,o,t);if(h&&h.from<=d&&h.to>=f){const g=De.create(l,h.from,h.to);n.setSelection(g)}}return!0},ep=e=>t=>{const n=typeof e=="function"?e(t):e;for(let r=0;r<n.length;r+=1)if(n[r](t))return!0;return!1};function Ps(e){return e instanceof De}function Et(e=0,t=0,n=0){return Math.min(Math.max(e,t),n)}function tp(e,t=null){if(!t)return null;const n=fe.atStart(e),r=fe.atEnd(e);if(t==="start"||t===!0)return n;if(t==="end")return r;const a=n.from,o=r.to;return t==="all"?De.create(e,Et(0,a,o),Et(e.content.size,a,o)):De.create(e,Et(t,a,o),Et(t,a,o))}function qr(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}const np=(e=null,t={})=>({editor:n,view:r,tr:a,dispatch:o})=>{t={scrollIntoView:!0,...t};const l=()=>{qr()&&r.dom.focus(),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),t!=null&&t.scrollIntoView&&n.commands.scrollIntoView())})};if(r.hasFocus()&&e===null||e===!1)return!0;if(o&&e===null&&!Ps(n.state.selection))return l(),!0;const u=tp(a.doc,e)||n.state.selection,c=n.state.selection.eq(u);return o&&(c||a.setSelection(u),c&&a.storedMarks&&a.setStoredMarks(a.storedMarks),l()),!0},rp=(e,t)=>n=>e.every((r,a)=>t(r,{...n,index:a})),ip=(e,t)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},e,t);function Bs(e){const t=`<body>${e}</body>`;return new window.DOMParser().parseFromString(t,"text/html").body}function Vn(e,t,n){if(n={slice:!0,parseOptions:{},...n},typeof e=="object"&&e!==null)try{return Array.isArray(e)&&e.length>0?ae.fromArray(e.map(r=>t.nodeFromJSON(r))):t.nodeFromJSON(e)}catch(r){return console.warn("[tiptap warn]: Invalid content.","Passed value:",e,"Error:",r),Vn("",t,n)}if(typeof e=="string"){const r=Mn.fromSchema(t);return n.slice?r.parseSlice(Bs(e),n.parseOptions).content:r.parse(Bs(e),n.parseOptions)}return Vn("",t,n)}function ap(e,t,n){const r=e.steps.length-1;if(r<t)return;const a=e.steps[r];if(!(a instanceof ot||a instanceof zt))return;const o=e.mapping.maps[r];let l=0;o.forEach((u,c,d,f)=>{l===0&&(l=f)}),e.setSelection(fe.near(e.doc.resolve(l),n))}const sp=e=>e.toString().startsWith("<"),op=(e,t,n)=>({tr:r,dispatch:a,editor:o})=>{if(a){n={parseOptions:{},updateSelection:!0,...n};const l=Vn(t,o.schema,{parseOptions:{preserveWhitespace:"full",...n.parseOptions}});if(l.toString()==="<>")return!0;let{from:u,to:c}=typeof e=="number"?{from:e,to:e}:e,d=!0,f=!0;if((sp(l)?l:[l]).forEach(g=>{g.check(),d=d?g.isText&&g.marks.length===0:!1,f=f?g.isBlock:!1}),u===c&&f){const{parent:g}=r.doc.resolve(u);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(u-=1,c+=1)}d?Array.isArray(t)?r.insertText(t.map(g=>g.text||"").join(""),u,c):typeof t=="object"&&t&&t.text?r.insertText(t.text,u,c):r.insertText(t,u,c):r.replaceWith(u,c,l),n.updateSelection&&ap(r,r.steps.length-1,-1)}return!0},lp=()=>({state:e,dispatch:t})=>Me.joinUp(e,t),up=()=>({state:e,dispatch:t})=>Me.joinDown(e,t),cp=()=>({state:e,dispatch:t})=>Me.joinBackward(e,t),dp=()=>({state:e,dispatch:t})=>Me.joinForward(e,t);function Vs(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function pp(e){const t=e.split(/-(?!$)/);let n=t[t.length-1];n==="Space"&&(n=" ");let r,a,o,l;for(let u=0;u<t.length-1;u+=1){const c=t[u];if(/^(cmd|meta|m)$/i.test(c))l=!0;else if(/^a(lt)?$/i.test(c))r=!0;else if(/^(c|ctrl|control)$/i.test(c))a=!0;else if(/^s(hift)?$/i.test(c))o=!0;else if(/^mod$/i.test(c))qr()||Vs()?l=!0:a=!0;else throw new Error(`Unrecognized modifier name: ${c}`)}return r&&(n=`Alt-${n}`),a&&(n=`Ctrl-${n}`),l&&(n=`Meta-${n}`),o&&(n=`Shift-${n}`),n}const hp=e=>({editor:t,view:n,tr:r,dispatch:a})=>{const o=pp(e).split(/-(?!$)/),l=o.find(d=>!["Alt","Ctrl","Meta","Shift"].includes(d)),u=new KeyboardEvent("keydown",{key:l==="Space"?" ":l,altKey:o.includes("Alt"),ctrlKey:o.includes("Ctrl"),metaKey:o.includes("Meta"),shiftKey:o.includes("Shift"),bubbles:!0,cancelable:!0}),c=t.captureTransaction(()=>{n.someProp("handleKeyDown",d=>d(n,u))});return c==null||c.steps.forEach(d=>{const f=d.map(r.mapping);f&&a&&r.maybeStep(f)}),!0};function Fr(e,t,n={}){const{from:r,to:a,empty:o}=e.selection,l=t?Le(t,e.schema):null,u=[];e.doc.nodesBetween(r,a,(h,g)=>{if(h.isText)return;const m=Math.max(r,g),C=Math.min(a,g+h.nodeSize);u.push({node:h,from:m,to:C})});const c=a-r,d=u.filter(h=>l?l.name===h.node.type.name:!0).filter(h=>Bn(h.node.attrs,n,{strict:!1}));return o?!!d.length:d.reduce((h,g)=>h+g.to-g.from,0)>=c}const fp=(e,t={})=>({state:n,dispatch:r})=>{const a=Le(e,n.schema);return Fr(n,a,t)?Me.lift(n,r):!1},gp=()=>({state:e,dispatch:t})=>Me.liftEmptyBlock(e,t),mp=e=>({state:t,dispatch:n})=>{const r=Le(e,t.schema);return pr.liftListItem(r)(t,n)},yp=()=>({state:e,dispatch:t})=>Me.newlineInCode(e,t);function Ns(e,t){return t.nodes[e]?"node":t.marks[e]?"mark":null}function qs(e,t){const n=typeof t=="string"?[t]:t;return Object.keys(e).reduce((r,a)=>(n.includes(a)||(r[a]=e[a]),r),{})}const bp=(e,t)=>({tr:n,state:r,dispatch:a})=>{let o=null,l=null;const u=Ns(typeof e=="string"?e:e.name,r.schema);return u?(u==="node"&&(o=Le(e,r.schema)),u==="mark"&&(l=xt(e,r.schema)),a&&n.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(d,f)=>{o&&o===d.type&&n.setNodeMarkup(f,void 0,qs(d.attrs,t)),l&&d.marks.length&&d.marks.forEach(h=>{l===h.type&&n.addMark(f,f+d.nodeSize,l.create(qs(h.attrs,t)))})})}),!0):!1},vp=()=>({tr:e,dispatch:t})=>(t&&e.scrollIntoView(),!0),xp=()=>({tr:e,commands:t})=>t.setTextSelection({from:0,to:e.doc.content.size}),wp=()=>({state:e,dispatch:t})=>Me.selectNodeBackward(e,t),Cp=()=>({state:e,dispatch:t})=>Me.selectNodeForward(e,t),Sp=()=>({state:e,dispatch:t})=>Me.selectParentNode(e,t),_p=()=>({state:e,dispatch:t})=>Me.selectTextblockEnd(e,t),kp=()=>({state:e,dispatch:t})=>Me.selectTextblockStart(e,t);function Tp(e,t,n={}){return Vn(e,t,{slice:!1,parseOptions:n})}const Dp=(e,t=!1,n={})=>({tr:r,editor:a,dispatch:o})=>{const{doc:l}=r,u=Tp(e,a.schema,n);return o&&r.replaceWith(0,l.content.size,u).setMeta("preventUpdate",!t),!0};function Ip(e){for(let t=0;t<e.edgeCount;t+=1){const{type:n}=e.edge(t);if(n.isTextblock&&!n.hasRequiredAttrs())return n}return null}function Mp(e,t){for(let n=e.depth;n>0;n-=1){const r=e.node(n);if(t(r))return{pos:n>0?e.before(n):0,start:e.start(n),depth:n,node:r}}}function Gr(e){return t=>Mp(t.$from,e)}function Ap(e,t){const n=xt(t,e.schema),{from:r,to:a,empty:o}=e.selection,l=[];o?(e.storedMarks&&l.push(...e.storedMarks),l.push(...e.selection.$head.marks())):e.doc.nodesBetween(r,a,c=>{l.push(...c.marks)});const u=l.find(c=>c.type.name===n.name);return u?{...u.attrs}:{}}function Nn(e,t,n){return Object.fromEntries(Object.entries(n).filter(([r])=>{const a=e.find(o=>o.type===t&&o.name===r);return a?a.attribute.keepOnSplit:!1}))}function zp(e,t,n={}){const{empty:r,ranges:a}=e.selection,o=t?xt(t,e.schema):null;if(r)return!!(e.storedMarks||e.selection.$from.marks()).filter(h=>o?o.name===h.type.name:!0).find(h=>Bn(h.attrs,n,{strict:!1}));let l=0;const u=[];if(a.forEach(({$from:h,$to:g})=>{const m=h.pos,C=g.pos;e.doc.nodesBetween(m,C,(w,_)=>{if(!w.isText&&!w.marks.length)return;const D=Math.max(m,_),M=Math.min(C,_+w.nodeSize),P=M-D;l+=P,u.push(...w.marks.map(G=>({mark:G,from:D,to:M})))})}),l===0)return!1;const c=u.filter(h=>o?o.name===h.mark.type.name:!0).filter(h=>Bn(h.mark.attrs,n,{strict:!1})).reduce((h,g)=>h+g.to-g.from,0),d=u.filter(h=>o?h.mark.type!==o&&h.mark.type.excludes(o):!0).reduce((h,g)=>h+g.to-g.from,0);return(c>0?c+d:c)>=l}function Fs(e,t){const{nodeExtensions:n}=Od(t),r=n.find(l=>l.name===e);if(!r)return!1;const a={name:r.name,options:r.options,storage:r.storage},o=Vt(vt(r,"group",a));return typeof o!="string"?!1:o.split(" ").includes("list")}function Ep(e,t,n){var r;const{selection:a}=t;let o=null;if(Ps(a)&&(o=a.$cursor),o){const u=(r=e.storedMarks)!==null&&r!==void 0?r:o.marks();return!!n.isInSet(u)||!u.some(c=>c.type.excludes(n))}const{ranges:l}=a;return l.some(({$from:u,$to:c})=>{let d=u.depth===0?e.doc.inlineContent&&e.doc.type.allowsMarkType(n):!1;return e.doc.nodesBetween(u.pos,c.pos,(f,h,g)=>{if(d)return!1;if(f.isInline){const m=!g||g.type.allowsMarkType(n),C=!!n.isInSet(f.marks)||!f.marks.some(w=>w.type.excludes(n));d=m&&C}return!d}),d})}const $p=(e,t={})=>({tr:n,state:r,dispatch:a})=>{const{selection:o}=n,{empty:l,ranges:u}=o,c=xt(e,r.schema);if(a)if(l){const d=Ap(r,c);n.addStoredMark(c.create({...d,...t}))}else u.forEach(d=>{const f=d.$from.pos,h=d.$to.pos;r.doc.nodesBetween(f,h,(g,m)=>{const C=Math.max(m,f),w=Math.min(m+g.nodeSize,h);g.marks.find(D=>D.type===c)?g.marks.forEach(D=>{c===D.type&&n.addMark(C,w,c.create({...D.attrs,...t}))}):n.addMark(C,w,c.create(t))})});return Ep(r,n,c)},Lp=(e,t)=>({tr:n})=>(n.setMeta(e,t),!0),Op=(e,t={})=>({state:n,dispatch:r,chain:a})=>{const o=Le(e,n.schema);return o.isTextblock?a().command(({commands:l})=>Me.setBlockType(o,t)(n)?!0:l.clearNodes()).command(({state:l})=>Me.setBlockType(o,t)(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},Pp=e=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,a=Et(e,0,r.content.size),o=Qe.create(r,a);t.setSelection(o)}return!0},Bp=e=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,{from:a,to:o}=typeof e=="number"?{from:e,to:e}:e,l=De.atStart(r).from,u=De.atEnd(r).to,c=Et(a,l,u),d=Et(o,l,u),f=De.create(r,c,d);t.setSelection(f)}return!0},Vp=e=>({state:t,dispatch:n})=>{const r=Le(e,t.schema);return pr.sinkListItem(r)(t,n)};function Gs(e,t){const n=e.storedMarks||e.selection.$to.parentOffset&&e.selection.$from.marks();if(n){const r=n.filter(a=>t==null?void 0:t.includes(a.type.name));e.tr.ensureMarks(r)}}const Np=({keepMarks:e=!0}={})=>({tr:t,state:n,dispatch:r,editor:a})=>{const{selection:o,doc:l}=t,{$from:u,$to:c}=o,d=a.extensionManager.attributes,f=Nn(d,u.node().type.name,u.node().attrs);if(o instanceof Qe&&o.node.isBlock)return!u.parentOffset||!Ln(l,u.pos)?!1:(r&&(e&&Gs(n,a.extensionManager.splittableMarks),t.split(u.pos).scrollIntoView()),!0);if(!u.parent.isBlock)return!1;if(r){const h=c.parentOffset===c.parent.content.size;o instanceof De&&t.deleteSelection();const g=u.depth===0?void 0:Ip(u.node(-1).contentMatchAt(u.indexAfter(-1)));let m=h&&g?[{type:g,attrs:f}]:void 0,C=Ln(t.doc,t.mapping.map(u.pos),1,m);if(!m&&!C&&Ln(t.doc,t.mapping.map(u.pos),1,g?[{type:g}]:void 0)&&(C=!0,m=g?[{type:g,attrs:f}]:void 0),C&&(t.split(t.mapping.map(u.pos),1,m),g&&!h&&!u.parentOffset&&u.parent.type!==g)){const w=t.mapping.map(u.before()),_=t.doc.resolve(w);u.node(-1).canReplaceWith(_.index(),_.index()+1,g)&&t.setNodeMarkup(t.mapping.map(u.before()),g)}e&&Gs(n,a.extensionManager.splittableMarks),t.scrollIntoView()}return!0},qp=e=>({tr:t,state:n,dispatch:r,editor:a})=>{var o;const l=Le(e,n.schema),{$from:u,$to:c}=n.selection,d=n.selection.node;if(d&&d.isBlock||u.depth<2||!u.sameParent(c))return!1;const f=u.node(-1);if(f.type!==l)return!1;const h=a.extensionManager.attributes;if(u.parent.content.size===0&&u.node(-1).childCount===u.indexAfter(-1)){if(u.depth===2||u.node(-3).type!==l||u.index(-2)!==u.node(-2).childCount-1)return!1;if(r){let _=ae.empty;const D=u.index(-1)?1:u.index(-2)?2:3;for(let A=u.depth-D;A>=u.depth-3;A-=1)_=ae.from(u.node(A).copy(_));const M=u.indexAfter(-1)<u.node(-2).childCount?1:u.indexAfter(-2)<u.node(-3).childCount?2:3,P=Nn(h,u.node().type.name,u.node().attrs),G=((o=l.contentMatch.defaultType)===null||o===void 0?void 0:o.createAndFill(P))||void 0;_=_.append(ae.from(l.createAndFill(null,G)||void 0));const L=u.before(u.depth-(D-1));t.replace(L,u.after(-M),new de(_,4-D,0));let z=-1;t.doc.nodesBetween(L,t.doc.content.size,(A,F)=>{if(z>-1)return!1;A.isTextblock&&A.content.size===0&&(z=F+1)}),z>-1&&t.setSelection(De.near(t.doc.resolve(z))),t.scrollIntoView()}return!0}const g=c.pos===u.end()?f.contentMatchAt(0).defaultType:null,m=Nn(h,f.type.name,f.attrs),C=Nn(h,u.node().type.name,u.node().attrs);t.delete(u.pos,c.pos);const w=g?[{type:l,attrs:m},{type:g,attrs:C}]:[{type:l,attrs:m}];if(!Ln(t.doc,u.pos,2))return!1;if(r){const{selection:_,storedMarks:D}=n,{splittableMarks:M}=a.extensionManager,P=D||_.$to.parentOffset&&_.$from.marks();if(t.split(u.pos,2,w).scrollIntoView(),!P||!r)return!0;const G=P.filter(L=>M.includes(L.type.name));t.ensureMarks(G)}return!0},Wr=(e,t)=>{const n=Gr(l=>l.type===t)(e.selection);if(!n)return!0;const r=e.doc.resolve(Math.max(0,n.pos-1)).before(n.depth);if(r===void 0)return!0;const a=e.doc.nodeAt(r);return n.node.type===(a==null?void 0:a.type)&&Ts(e.doc,n.pos)&&e.join(n.pos),!0},jr=(e,t)=>{const n=Gr(l=>l.type===t)(e.selection);if(!n)return!0;const r=e.doc.resolve(n.start).after(n.depth);if(r===void 0)return!0;const a=e.doc.nodeAt(r);return n.node.type===(a==null?void 0:a.type)&&Ts(e.doc,r)&&e.join(r),!0};var Fp=Object.freeze({__proto__:null,blur:Fd,clearContent:Gd,clearNodes:Wd,command:jd,createParagraphNear:Rd,deleteCurrentNode:Yd,deleteNode:Qd,deleteRange:Ud,deleteSelection:Kd,enter:Xd,exitCode:Jd,extendMarkRange:Hd,first:ep,focus:np,forEach:rp,insertContent:ip,insertContentAt:op,joinUp:lp,joinDown:up,joinBackward:cp,joinForward:dp,keyboardShortcut:hp,lift:fp,liftEmptyBlock:gp,liftListItem:mp,newlineInCode:yp,resetAttributes:bp,scrollIntoView:vp,selectAll:xp,selectNodeBackward:wp,selectNodeForward:Cp,selectParentNode:Sp,selectTextblockEnd:_p,selectTextblockStart:kp,setContent:Dp,setMark:$p,setMeta:Lp,setNode:Op,setNodeSelection:Pp,setTextSelection:Bp,sinkListItem:Vp,splitBlock:Np,splitListItem:qp,toggleList:(e,t,n,r={})=>({editor:a,tr:o,state:l,dispatch:u,chain:c,commands:d,can:f})=>{const{extensions:h,splittableMarks:g}=a.extensionManager,m=Le(e,l.schema),C=Le(t,l.schema),{selection:w,storedMarks:_}=l,{$from:D,$to:M}=w,P=D.blockRange(M),G=_||w.$to.parentOffset&&w.$from.marks();if(!P)return!1;const L=Gr(z=>Fs(z.type.name,h))(w);if(P.depth>=1&&L&&P.depth-L.depth<=1){if(L.node.type===m)return d.liftListItem(C);if(Fs(L.node.type.name,h)&&m.validContent(L.node.content)&&u)return c().command(()=>(o.setNodeMarkup(L.pos,m),!0)).command(()=>Wr(o,m)).command(()=>jr(o,m)).run()}return!n||!G||!u?c().command(()=>f().wrapInList(m,r)?!0:d.clearNodes()).wrapInList(m,r).command(()=>Wr(o,m)).command(()=>jr(o,m)).run():c().command(()=>{const z=f().wrapInList(m,r),A=G.filter(F=>g.includes(F.type.name));return o.ensureMarks(A),z?!0:d.clearNodes()}).wrapInList(m,r).command(()=>Wr(o,m)).command(()=>jr(o,m)).run()},toggleMark:(e,t={},n={})=>({state:r,commands:a})=>{const{extendEmptyMarkRange:o=!1}=n,l=xt(e,r.schema);return zp(r,l,t)?a.unsetMark(l,{extendEmptyMarkRange:o}):a.setMark(l,t)},toggleNode:(e,t,n={})=>({state:r,commands:a})=>{const o=Le(e,r.schema),l=Le(t,r.schema);return Fr(r,o,n)?a.setNode(l):a.setNode(o,n)},toggleWrap:(e,t={})=>({state:n,commands:r})=>{const a=Le(e,n.schema);return Fr(n,a,t)?r.lift(a):r.wrapIn(a,t)},undoInputRule:()=>({state:e,dispatch:t})=>{const n=e.plugins;for(let r=0;r<n.length;r+=1){const a=n[r];let o;if(a.spec.isInputRules&&(o=a.getState(e))){if(t){const l=e.tr,u=o.transform;for(let c=u.steps.length-1;c>=0;c-=1)l.step(u.steps[c].invert(u.docs[c]));if(o.text){const c=l.doc.resolve(o.from).marks();l.replaceWith(o.from,o.to,e.schema.text(o.text,c))}else l.delete(o.from,o.to)}return!0}}return!1},unsetAllMarks:()=>({tr:e,dispatch:t})=>{const{selection:n}=e,{empty:r,ranges:a}=n;return r||t&&a.forEach(o=>{e.removeMark(o.$from.pos,o.$to.pos)}),!0},unsetMark:(e,t={})=>({tr:n,state:r,dispatch:a})=>{var o;const{extendEmptyMarkRange:l=!1}=t,{selection:u}=n,c=xt(e,r.schema),{$from:d,empty:f,ranges:h}=u;if(!a)return!0;if(f&&l){let{from:g,to:m}=u;const C=(o=d.marks().find(_=>_.type===c))===null||o===void 0?void 0:o.attrs,w=Os(d,c,C);w&&(g=w.from,m=w.to),n.removeMark(g,m,c)}else h.forEach(g=>{n.removeMark(g.$from.pos,g.$to.pos,c)});return n.removeStoredMark(c),!0},updateAttributes:(e,t={})=>({tr:n,state:r,dispatch:a})=>{let o=null,l=null;const u=Ns(typeof e=="string"?e:e.name,r.schema);return u?(u==="node"&&(o=Le(e,r.schema)),u==="mark"&&(l=xt(e,r.schema)),a&&n.selection.ranges.forEach(c=>{const d=c.$from.pos,f=c.$to.pos;r.doc.nodesBetween(d,f,(h,g)=>{o&&o===h.type&&n.setNodeMarkup(g,void 0,{...h.attrs,...t}),l&&h.marks.length&&h.marks.forEach(m=>{if(l===m.type){const C=Math.max(g,d),w=Math.min(g+h.nodeSize,f);n.addMark(C,w,l.create({...m.attrs,...t}))}})})}),!0):!1},wrapIn:(e,t={})=>({state:n,dispatch:r})=>{const a=Le(e,n.schema);return Me.wrapIn(a,t)(n,r)},wrapInList:(e,t={})=>({state:n,dispatch:r})=>{const a=Le(e,n.schema);return pr.wrapInList(a,t)(n,r)}});lt.create({name:"commands",addCommands(){return{...Fp}}}),lt.create({name:"editable",addProseMirrorPlugins(){return[new on({key:new ln("editable"),props:{editable:()=>this.editor.options.editable}})]}}),lt.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:e}=this;return[new on({key:new ln("focusEvents"),props:{handleDOMEvents:{focus:(t,n)=>{e.isFocused=!0;const r=e.state.tr.setMeta("focus",{event:n}).setMeta("addToHistory",!1);return t.dispatch(r),!1},blur:(t,n)=>{e.isFocused=!1;const r=e.state.tr.setMeta("blur",{event:n}).setMeta("addToHistory",!1);return t.dispatch(r),!1}}}})]}}),lt.create({name:"keymap",addKeyboardShortcuts(){const e=()=>this.editor.commands.first(({commands:l})=>[()=>l.undoInputRule(),()=>l.command(({tr:u})=>{const{selection:c,doc:d}=u,{empty:f,$anchor:h}=c,{pos:g,parent:m}=h,C=fe.atStart(d).from===g;return!f||!C||!m.type.isTextblock||m.textContent.length?!1:l.clearNodes()}),()=>l.deleteSelection(),()=>l.joinBackward(),()=>l.selectNodeBackward()]),t=()=>this.editor.commands.first(({commands:l})=>[()=>l.deleteSelection(),()=>l.deleteCurrentNode(),()=>l.joinForward(),()=>l.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:l})=>[()=>l.newlineInCode(),()=>l.createParagraphNear(),()=>l.liftEmptyBlock(),()=>l.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:e,"Mod-Backspace":e,"Shift-Backspace":e,Delete:t,"Mod-Delete":t,"Mod-a":()=>this.editor.commands.selectAll()},a={...r},o={...r,"Ctrl-h":e,"Alt-Backspace":e,"Ctrl-d":t,"Ctrl-Alt-Backspace":t,"Alt-Delete":t,"Alt-d":t,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return qr()||Vs()?o:a},addProseMirrorPlugins(){return[new on({key:new ln("clearDocument"),appendTransaction:(e,t,n)=>{if(!(e.some(C=>C.docChanged)&&!t.doc.eq(n.doc)))return;const{empty:a,from:o,to:l}=t.selection,u=fe.atStart(t.doc).from,c=fe.atEnd(t.doc).to;if(a||!(o===u&&l===c)||!(n.doc.textBetween(0,n.doc.content.size," "," ").length===0))return;const h=n.tr,g=$s({state:n,transaction:h}),{commands:m}=new Ld({editor:this.editor,state:g});if(m.clearNodes(),!!h.steps.length)return h}})]}}),lt.create({name:"tabindex",addProseMirrorPlugins(){return[new on({key:new ln("tabindex"),props:{attributes:this.editor.isEditable?{tabindex:"0"}:{}}})]}});const Ws=lt.create({name:"fontSize",addOptions(){return{types:["textStyle"]}},addGlobalAttributes(){return[{types:this.options.types,attributes:{fontSize:{default:null,parseHTML:e=>e.style.fontSize.replace(/['"]+/g,""),renderHTML:e=>e.fontSize?{style:`font-size: ${e.fontSize}`}:{}}}}]},addCommands(){return{setFontSize:e=>({chain:t})=>t().setMark("textStyle",{fontSize:e}).run(),unsetFontSize:()=>({chain:e})=>e().setMark("textStyle",{fontSize:null}).removeEmptyTextStyle().run()}}}),Gp=["8","10","12","14","16","18","20","24","30","36","48","60","72"].map(e=>`${e}px`),Wp=[{label:"auto",value:""}].concat(Gp.map(e=>({label:e,value:e}))),jp={input:{height:"26px",minHeight:"26px",lineHeight:"26px",borderColor:"#ced4da !important"}},Rp=({editor:e})=>{const t=e.getAttributes("textStyle").fontSize;return i(J.RichTextEditor.ControlsGroup,{children:i(s.NativeSelect,{size:"xs",icon:i($.IconTextSize,{stroke:1.5,size:16}),data:Wp,styles:jp,value:t||"",onChange:n=>{const r=n.currentTarget.value;r?e.chain().focus().setFontSize(r).run():e.chain().focus().unsetFontSize().run()}})})},qn=({value:e,styles:t={}})=>{const n=Ga.useEditor({extensions:[Wa,Fa,J.Link,La,$a,za,Ba.configure({resizable:!1,HTMLAttributes:{class:"rich-text-table-render"}}),qa,Na,Va,Oa.configure({types:["heading","paragraph"]}),Ea.configure({placeholder:"This is placeholder"}),Pa,Aa.Color,Ws],content:e,editable:!1});b.useEffect(()=>{n==null||n.commands.setContent(e)},[e,n]);const r=b.useMemo(()=>x.defaultsDeep({},{content:Mr},t),[t]);return i(J.RichTextEditor,{editor:n,styles:r,children:i(J.RichTextEditor.Content,{})})};function Yp(){const[e,{open:t,close:n}]=Ie.useDisclosure(!1);return p(B,{children:[i(s.Modal,{opened:e,onClose:n,title:"About FunctionUtils",zIndex:330,withinPortal:!0,children:i(qn,{value:Gu,styles:{root:{border:"none"},content:{padding:0,table:{marginBottom:0}}}})}),i(s.Button,{variant:"light",color:"violet",size:"xs",onClick:t,leftIcon:i($.IconInfoCircle,{size:16}),children:"About parameter 'utils'"})]})}const Qp=({value:e,onChange:t})=>{const n=r=>{r&&t(r)};return i(s.Box,{sx:{position:"relative",flexGrow:1},children:i(Ae,{className:"function-editor",height:"100%",defaultLanguage:"javascript",value:e,onChange:n,theme:"vs-dark",options:{lineNumbers:"off",folding:!1,lineDecorationsWidth:20,lineNumbersMinChars:0,wordWrap:"on",minimap:{enabled:!1}}})})},un=b.forwardRef(({value:e,onChange:t,label:n,defaultValue:r},a)=>{const[o,l]=b.useState(e),u=()=>{t(o)},c=()=>{l(e)},d=()=>{l(r)};b.useEffect(()=>{l(e)},[e]);const f=o!==e;return p(s.Stack,{spacing:4,sx:{height:"100%"},children:[p(s.Group,{mb:6,position:"apart",sx:{flexShrink:0,flexGrow:0},children:[i(s.Group,{position:"left",children:i(Yp,{})}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:d,size:"xs",variant:"default",leftIcon:i($.IconPlayerSkipBack,{size:16}),children:"Reset to default"}),i(s.Button,{onClick:c,color:"red",size:"xs",disabled:!f,leftIcon:i($.IconRecycle,{size:16}),children:"Revert Changes"}),i(s.Button,{size:"xs",onClick:u,disabled:!f,leftIcon:i($.IconDeviceFloppy,{size:16}),children:"Confirm Changes"})]})]}),i(s.Text,{size:14,children:n}),i(Qp,{value:o,onChange:l})]})}),Up=b.forwardRef(({value:e,onChange:t,label:n,triggerLabel:r="Edit",triggerButtonProps:a={},defaultValue:o},l)=>{const[u,{open:c,close:d}]=Ie.useDisclosure(!1);return p(B,{children:[i(s.Modal,{opened:u,onClose:d,title:"Authentication",withinPortal:!0,zIndex:320,size:"900px",children:i(s.Box,{h:600,children:i(un,{value:e,onChange:t,defaultValue:o,label:n})})}),i(s.Button,{onClick:c,...a,children:r})]})}),js=["function aggregation({ queryData }, utils) {",' return "Aggregation Result";',"}"].join(`
105
+ `),Nt={type:"none",config:{}};function Kp(e){const t=Array.from(e).sort((r,a)=>r-a),n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function Xp(e){const t=Number(e);return isFinite(t)?t:0}function Jp(e,t){switch(t.type){case"sum":return x.sum(e);case"mean":return x.mean(e);case"median":return Kp(e);case"max":return x.max(e)??0;case"min":return x.min(e)??0;case"quantile":return Xt.quantile(e,t.config.p)??0;case"CV":const n=Cn.std(...e),r=Cn.mean(...e);return r?n/r:"N/A";case"std":return Cn.std(...e);default:return e}}function Rr(e,t){const n=e.map(Xp);return Jp(n,t)}function Zp(e,t,n){try{const r=en(e,t);return new Function(`return ${n.config.func}`)()({queryData:r},Tt)}catch(r){return console.error(r),r.message}}function Fn(e,t,n){try{return n.type==="custom"?Zp(e,t,n):Rr(pt(e,t),n)}catch(r){return console.error(r),null}}const Hp=[{label:"None",value:"none"},{label:"Sum",value:"sum"},{label:"Mean",value:"mean"},{label:"Median",value:"median"},{label:"Max",value:"max"},{label:"Min",value:"min"},{label:"Coefficient of Variation",value:"CV"},{label:"Standard Variation",value:"std"},{label:"Quantile(99%, 95%, ...)",value:"quantile"},{label:"Custom",value:"custom"}];function eh({label:e,value:t,onChange:n,pt:r="sm"},a){b.useEffect(()=>{typeof t=="string"&&n({type:t,config:{}})},[t,n]);const o=c=>{n(c==="quantile"?{type:"quantile",config:{p:.99}}:c==="custom"?{type:"custom",config:{func:js}}:{type:c,config:{}})},l=c=>{n({type:"quantile",config:{p:c}})},u=c=>{n({type:"custom",config:{func:c}})};return p(s.Group,{grow:!0,noWrap:!0,pt:r,children:[i(s.Select,{ref:a,label:e,data:Hp,value:t.type,onChange:o}),t.type==="quantile"&&i(s.NumberInput,{label:"p",value:t.config.p,onChange:l,precision:2,min:.05,step:.05,max:1}),t.type==="custom"&&i(Up,{label:"",triggerLabel:"Edit Function",value:t.config.func,onChange:u,defaultValue:js,triggerButtonProps:{size:"xs",sx:{flexGrow:0,alignSelf:"center",marginTop:"22px"},leftIcon:i($.IconMathFunction,{size:16})}})]})}const Gn=b.forwardRef(eh);function th({label:e,value:t,onChange:n},r){const[a,o]=b.useState(Array.isArray(t)?[...t]:[]),l=b.useCallback(()=>{o(g=>[...g,""])},[o]),u=b.useCallback(g=>{o(m=>(m.splice(g,1),[...m]))},[o]),c=b.useMemo(()=>!x.isEqual(a,t),[a,t]),d=()=>{n(a.map(g=>g.toString()))},f=s.useMantineTheme(),h=b.useMemo(()=>Object.entries(f.colors).map(([g,m])=>m[6]),[f]);return p(B,{children:[p(s.Group,{position:"left",ref:r,children:[i(s.Text,{children:e}),i(s.ActionIcon,{mr:5,variant:"filled",color:"blue",disabled:!c,onClick:d,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Group,{children:[a.map((g,m)=>i(s.ColorInput,{value:g,onChange:C=>{o(w=>(w.splice(m,1,C),[...w]))},swatches:h,rightSection:i(s.ActionIcon,{onClick:()=>u(m),color:"red",children:i(T.Trash,{size:14})}),sx:{width:"45%"}})),i(s.ActionIcon,{onClick:l,color:"blue",variant:"outline",children:i(T.PlaylistAdd,{size:20})})]})]})}const nh=b.forwardRef(th);function rh({value:e,onChange:t},n){const{colorManager:r}=b.useContext(ut),a=b.useMemo(()=>r.getStaticColors().map(u=>({label:u.name,group:u.category,value:u.value})),[r]),o=b.useMemo(()=>a.some(l=>l.value===e),[e,a]);return p(s.Group,{position:"apart",spacing:4,ref:n,children:[i(s.TextInput,{placeholder:"Set any color",value:o?"":e,onChange:l=>t(l.currentTarget.value),rightSection:i(s.ColorSwatch,{color:o?"transparent":e,radius:4}),variant:o?"filled":"default",sx:{maxWidth:"46%",flexGrow:1}}),i(s.Text,{sx:{flexGrow:0},children:"or"}),i(s.Select,{data:a,value:e,onChange:t,variant:o?"default":"filled",placeholder:"Pick a theme color",icon:i(s.ColorSwatch,{color:o?e:"transparent",radius:4}),sx:{maxWidth:"46%",flexGrow:1}})]})}const Ve=b.forwardRef(rh),Wn=[{label:"initial",value:0},{label:"500",value:25},{label:"700",value:50},{label:"semibold",value:75},{label:"bold",value:100}];function ih({label:e,value:t,onChange:n},r){var l;const[a,o]=b.useState(((l=Wn.find(u=>u.label===t))==null?void 0:l.value)??Wn[0].value);return b.useEffect(()=>{const u=Wn.find(c=>c.value===a);u&&n(u.label)},[a]),p(s.Stack,{spacing:0,mt:"sm",mb:"lg",children:[i(s.Text,{size:"sm",children:e}),i(s.Slider,{label:null,marks:Wn,value:a,onChange:o,step:25,placeholder:"Pick a font size",px:"1em",ref:r})]})}const Rs=b.forwardRef(ih);function ah({label:e,value:t,onChange:n,type:r},a){const[o,l]=b.useState(Array.isArray(t)?[...t]:[]),u=b.useCallback(()=>{l(h=>[...h,""])},[l]),c=b.useCallback(h=>{l(g=>(g.splice(h,1),[...g]))},[l]),d=b.useMemo(()=>!x.isEqual(o.map(String),t.map(String)),[o,t]),f=()=>{n(o.map(h=>r==="number"?Number(h):h.toString()))};return p(B,{children:[p(s.Group,{position:"left",ref:a,children:[i(s.Text,{children:e}),i(s.ActionIcon,{mr:5,variant:"filled",color:"blue",disabled:!d,onClick:f,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Group,{children:[o.map((h,g)=>i(s.TextInput,{type:r,value:h,onChange:m=>{const C=m.currentTarget.value;l(w=>(w.splice(g,1,C),[...w]))},rightSection:i(s.ActionIcon,{onClick:()=>c(g),color:"red",children:i(T.Trash,{size:14})}),sx:{width:"45%"}})),i(s.ActionIcon,{onClick:u,color:"blue",variant:"outline",children:i(T.PlaylistAdd,{size:20})})]})]})}const sh=b.forwardRef(ah),Ys=b.forwardRef(function({value:t,onChange:n},r){const a=t.color.type,o=(u,c)=>{const d=x.cloneDeep(t);x.set(d,u,c),n(d)},l=u=>{if(u==="static"){n({...t,color:{type:"static",staticColor:"#25262B"}});return}n({...t,color:{type:"continuous",colorRange:[],valueRange:[]}})};return p(B,{children:[i(s.Divider,{my:"xs",label:"Typography",labelPosition:"center"}),i(s.Stack,{children:i(s.TextInput,{label:"Font Size",placeholder:"10px, 1em, 1rem, 100%...",sx:{flex:1},value:t.size,onChange:u=>o("size",u.currentTarget.value)})}),i(s.Group,{position:"apart",grow:!0,sx:{"> *":{flexGrow:1,maxWidth:"100%"}},children:i(Rs,{label:"Font Weight",value:t.weight,onChange:u=>o("weight",u)})}),i(s.Divider,{my:"xs",label:"Style",labelPosition:"center"}),p(s.Stack,{children:[i(s.Select,{label:"Color Type",data:[{label:"Static Color",value:"static"},{label:"Continuous Color",value:"continuous"}],value:t.color.type,onChange:l}),a==="static"&&i(Ve,{value:t.color.staticColor,onChange:u=>o("color.staticColor",u)}),a==="continuous"&&p(B,{children:[i(sh,{label:"Value Range",value:t.color.valueRange,type:"number",onChange:u=>o("color.valueRange",u)}),i(nh,{label:"Color Range",value:t.color.colorRange,onChange:u=>o("color.colorRange",u)})]})]})]})});b.forwardRef(function({value:t,onChange:n,withStyle:r=!0},a){const o=(l,u)=>{const c=x.cloneDeep(t);x.set(c,l,u),n(c)};return p(s.Box,{px:"sm",py:"md",ref:a,children:[i(s.Text,{weight:"bold",pb:0,children:t.name}),i(s.Divider,{my:"xs",label:"Data",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(s.TextInput,{label:"Name",required:!0,value:t.name,onChange:l=>o("name",l.currentTarget.value)}),i(W,{label:"Data Field",required:!0,value:t.data_field,onChange:l=>o("data_field",l)})]}),i(Gn,{label:"Aggregation",value:t.aggregation,onChange:l=>o("aggregation",l)}),i(s.Divider,{my:"xs",label:"Format",labelPosition:"center"}),t.aggregation.type!=="custom"&&i(je,{value:t.formatter,onChange:l=>o("formatter",l)}),r&&i(Ys,{value:t,onChange:n})]})});class oh{constructor({valueRange:t,colorRange:n}){N(this,"mapper");this.mapper=_t.interpolate(t,n)}getColor(t){return this.mapper(t)}}function lh(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?`Array(${e.length})`:e.toString()}function ft({data_field:e,aggregation:t},n){return Fn(n,e,t)}function Ze({formatter:e,aggregation:t},n){if(!["string","number"].includes(typeof n))return lh(n);if(t.type==="custom")return n;try{return Z(n).format(e)}catch(r){return console.error(r),n}}function uh(e,t){if(e.type==="static")return e.staticColor;if(e.type==="continuous")try{if(typeof t!="number")throw new Error(`[getColorByColorConf] Invalid type of aggregated value: ${t}`);return new oh(e).getColor(t)}catch(n){return console.error(n),"black"}return"black"}function Qs(e,t){const{color:n,data_field:r,aggregation:a,size:o,weight:l}=e,u=Fn(t,r,a),c=Ze(e,u);return i(s.Text,{sx:{fontSize:o,display:"inline"},color:uh(n,u),weight:l,children:c})}function ch(e,t){const n={};return e.forEach(r=>{const a=r.name;n[a]=Qs(r,t)}),n}function dh(e){return e.split(" ").map((t,n)=>p(b.Fragment,{children:[t," "]},n))}function ph(e){const n=e.replaceAll("<br />","<br/>").replaceAll(`
106
+ `,"<br/>").split("<br/>");return n.map((a,o)=>{const l=[dh(a)];return o!==n.length-1&&l.push(i("br",{},`br-${o}`)),l}).flat().filter(a=>a!==void 0)}function Yr(e){return ph(e)}function cn(e,t,n){const r=ch(t,n),a=/^\{(.+)\}(.*)$/;return e.split("$").map((o,l)=>{const u=a.exec(o);if(!u)return Yr(o);const c=r[u[1]];if(!c)return Yr(o);const d=u[2]??"";return p(b.Fragment,{children:[c,Yr(d)]},`${o}-${l}`)})}function hh(e,t){const n={};return e.forEach(r=>{const{name:a,data_field:o,aggregation:l}=r,u=Fn(t,o,l);n[a]=Ze(r,u)}),n}function jn(e,t,n){const r=hh(t,n),a=/^\{(.+)\}(.*)$/;return e.split("$").map(o=>{const l=a.exec(o);if(!l)return o;const u=r[l[1]];if(!u)return o;const c=l[2]??"";return`${u}${c}`}).join("")}function fh(e,t,n){const r=t.reduce((a,o)=>{const l=ft(o,n);return a[o.name]=Ze(o,l),a},{});return e.map(a=>({name:"refs",type:"scatter",data:[],markLine:{data:[{name:a.name,yAxis:Number(r[a.variable_key])}],silent:!0,symbol:["none","none"],label:{formatter:function(){return jn(a.template,t,n)},position:"insideEndTop"}}}))}function gh(e){const t={top:30,left:20,right:15,bottom:25,containLabel:!0};return e.legend.orient==="vertical"&&(t.right=80),t}function mh({config:e,data:t,variables:n}){const{x_axis:r,y_axis:a,reference_lines:o}=e,l=dd(e,t),u=rt(r.axisLabel.overflow.on_axis),c=hd(e);return{grid:gh(e),dataset:l,legend:pd({config:e}),tooltip:vd({config:e}),xAxis:[{type:"category",name:r.name,nameGap:25,nameLocation:"center",nameTextStyle:{fontWeight:"bold",align:"center"},axisTick:{show:!0,alignWithLabel:!0},axisLabel:{...r.axisLabel,...u,formatter:Pt(r.axisLabel.formatter)}}],yAxis:[{name:a.name,minInterval:1,nameTextStyle:{fontWeight:"bold"},axisLine:{show:!0},axisLabel:{formatter:function(d){return Z(d).format(a.label_formatter)}}}],series:[...c,...fh(o,n,t)]}}ie.use([q.DataZoomComponent,he.BoxplotChart,q.MarkLineComponent,q.GridComponent,q.LegendComponent,q.TooltipComponent,Pe.CanvasRenderer]);function yh({context:e,instance:t}){const{value:n}=R(e.instanceData,"config"),{variables:r}=e,a=e.data,{width:o,height:l}=e.viewport,u=x.defaults({},n,kr),c=Xe({vizManager:e.vizManager,instance:t}),d=Ke(c.triggerManager,os.id),f=Dt(a,u.x_axis.data_key),h=b.useCallback(C=>{const w=x.get(f,C.name,{error:"rowData is not found"});d.forEach(_=>{c.runInteraction(_.id,{...C,rowData:w})})},[f,d,c]),g=b.useMemo(()=>({click:h}),[h]),m=b.useMemo(()=>mh({config:u,data:a,variables:r}),[u,a,r]);return!n||!o||!l?null:i(Be,{echarts:ie,option:m,style:{width:o,height:l},onEvents:g,notMerge:!0,theme:"merico-light"})}function bh({control:e,index:t,remove:n,variableOptions:r}){return p(s.Stack,{my:0,p:"md",pr:40,sx:{border:"1px solid #eee",position:"relative"},children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`reference_lines.${t}.name`,control:e,render:({field:a})=>i(s.TextInput,{label:"Name",placeholder:"Average Reference Line",required:!0,sx:{flex:1},...a})}),i(v.Controller,{name:`reference_lines.${t}.variable_key`,control:e,render:({field:a})=>i(s.Select,{label:"Value",required:!0,data:r,sx:{flex:1},...a})})]}),i(v.Controller,{name:`reference_lines.${t}.template`,control:e,render:({field:a})=>i(s.TextInput,{label:"Content Template",placeholder:"Average: ${avg}",required:!0,sx:{flex:1},...a})}),i(s.ActionIcon,{color:"red",variant:"subtle",onClick:()=>n(t),sx:{position:"absolute",top:15,right:5},children:i(T.Trash,{size:16})})]},t)}function vh({control:e,watch:t,variables:n}){const{fields:r,append:a,remove:o}=v.useFieldArray({control:e,name:"reference_lines"}),l=t("reference_lines"),u=r.map((f,h)=>({...f,...l[h]})),c=()=>a({name:"",template:"",variable_key:""}),d=b.useMemo(()=>n.map(f=>({label:f.name,value:f.name})),[n]);return p(s.Stack,{children:[u.map((f,h)=>i(bh,{control:e,index:h,remove:o,variableOptions:d},f.id)),i(s.Group,{position:"center",mt:"xs",children:i(s.Button,{onClick:c,children:"Add a Reference Line"})})]})}const xh=({disabled:e,value:t,onChange:n})=>{const r=a=>{a&&n(a)};return p(s.Box,{sx:{position:"relative"},children:[e&&i(s.Overlay,{opacity:.6,color:"#fff",zIndex:5,blur:2}),i(Ae,{height:"500px",defaultLanguage:"javascript",value:t,onChange:r,theme:"vs-dark",options:{minimap:{enabled:!1},readOnly:e}})]})},Rn=b.forwardRef(({value:e,onChange:t},n)=>{const[r,{setTrue:a,setFalse:o}]=K.useBoolean(),[l,u]=b.useState(e);b.useEffect(()=>{u(e)},[e]);const c=m=>{u({...l,enabled:m})},d=()=>{o();const{enabled:m,func_content:C}=l,w={enabled:m,func_content:C};u(w),t(w)},f=()=>{o(),u(e)},h=m=>{u(C=>({...C,func_content:m}))},g=()=>{h(Ue.func_content)};return p(B,{children:[i(s.Button,{variant:"filled",mt:24,onClick:a,sx:{flexGrow:0},children:"Customize Label"}),i(s.Modal,{size:800,title:"Customize label content",opened:r,onClose:o,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:r&&p(s.Stack,{children:[i(s.Checkbox,{mt:10,label:"Enabled",checked:l.enabled,onChange:m=>c(m.currentTarget.checked)}),i(xh,{value:l.func_content,onChange:h,disabled:!l.enabled}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:g,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:f,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:d,children:"OK"})]})]})]})})]})}),wh=({control:e,watch:t})=>(t(["x_axis"]),p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"X Axis Name",sx:{flex:1},...n})}),i(v.Controller,{name:"x_axis.data_key",control:e,render:({field:n})=>i(W,{label:"X Axis Data Field",required:!0,sx:{flex:1},...n})})]}),i(s.Divider,{mb:-15,label:"Tick Label",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.axisLabel.rotate",control:e,render:({field:n})=>i(s.NumberInput,{label:"Rotate",hideControls:!0,min:-90,max:90,rightSection:i(s.Text,{color:"dimmed",children:"degree"}),sx:{width:"48%"},styles:{rightSection:{width:"4em",justifyContent:"flex-end",paddingRight:"6px"}},...n})}),i(v.Controller,{name:"x_axis.axisLabel.formatter",control:e,render:({field:n})=>i(Rn,{...n})})]}),i(v.Controller,{name:"x_axis.axisLabel.overflow",control:e,render:({field:n})=>i(at,{...n})})]})),Ch=({control:e,watch:t})=>(t(["y_axis"]),p(B,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"y_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Y Axis Name",sx:{flex:1},...n})}),i(v.Controller,{name:"y_axis.data_key",control:e,render:({field:n})=>i(W,{label:"Y Axis Data Field",required:!0,sx:{flex:1},...n})})]}),p(s.Stack,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Label Format",labelPosition:"center"}),i(v.Controller,{name:"y_axis.label_formatter",control:e,render:({field:n})=>i(je,{...n})})]})]})),Sh=({control:e,index:t,remove:n})=>p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`tooltip.metrics.${t}.name`,control:e,render:({field:r})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:`tooltip.metrics.${t}.data_key`,control:e,render:({field:r})=>i(W,{label:"Value Field",required:!0,sx:{flex:1},...r})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed"}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Metric"})]}),_h=({control:e,watch:t})=>{const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"tooltip.metrics"}),o=t("tooltip.metrics"),l=n.map((h,g)=>({...h,...o[g]})),u=()=>r({id:Date.now().toString(),data_key:"",name:""}),c=t("tooltip.metrics.0.id"),[d,f]=b.useState(()=>c??null);return b.useEffect(()=>{c&&f(h=>h!==null?h:c)},[c]),p(B,{children:[p(s.Group,{spacing:2,sx:{cursor:"default",userSelect:"none"},children:[i(T.InfoCircle,{size:14,color:"#888"}),i(s.Text,{size:14,color:"#888",children:"Set additional metrics to show in scatter's tooltip"})]}),p(s.Tabs,{value:d,onTabChange:h=>f(h),styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map((h,g)=>i(s.Tabs.Tab,{value:h.id,children:h.name?h.name:g},h.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((h,g)=>i(s.Tabs.Panel,{value:h.id,children:i(Sh,{control:e,index:g,remove:a},h.id)},h.id))]})]})};function kh({control:e,watch:t}){return i(s.Stack,{children:i(_h,{control:e,watch:t})})}const Th=[{label:"Horizontal",value:"horizontal"},{label:"Vertical",value:"vertical"}],Dh=({control:e,watch:t})=>{const n=t("legend"),r=(a,o)=>{const l={...n,orient:a};a==="horizontal"?(l.top="0",l.left="auto",l.right="10",l.bottom="auto"):(l.top="10",l.left="auto",l.right="0",l.bottom="auto"),o(l)};return p(s.Stack,{children:[i(s.Group,{grow:!0,noWrap:!0,mt:20,children:i(v.Controller,{name:"legend.show",control:e,render:({field:a})=>i(s.Switch,{label:"Show Legend",sx:{flex:1},checked:a.value,onChange:o=>a.onChange(o.currentTarget.checked)})})}),i(s.Group,{children:i(v.Controller,{name:"legend",control:e,render:({field:a})=>i(s.Select,{label:"Orientation",data:Th,sx:{flex:1},value:a.value.orient,onChange:o=>{r(o,a.onChange)},disabled:!n.show})})})]})};function Ih({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),{variables:r}=e,a=b.useMemo(()=>x.defaults({},t,kr),[t]),{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});b.useEffect(()=>{d(a)},[a]),u(["x_axis","y_axis","reference_lines","color"]);const f=c(),h=b.useMemo(()=>!x.isEqual(f,t),[f,t]);return i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:l(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"X Axis",orientation:"vertical",styles:{tab:{paddingLeft:"6px",paddingRight:"6px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"X Axis",children:"X Axis"}),i(s.Tabs.Tab,{value:"Y Axis",children:"Y Axis"}),i(s.Tabs.Tab,{value:"Legend",children:"Legend"}),i(s.Tabs.Tab,{value:"Tooltip",children:"Tooltip"}),i(s.Tabs.Tab,{value:"Style",children:"Style"}),i(s.Tabs.Tab,{value:"Reference Lines",children:"Reference Lines"})]}),i(s.Tabs.Panel,{value:"X Axis",children:i(wh,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Y Axis",children:i(Ch,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Legend",children:i(Dh,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Tooltip",children:i(kh,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Style",children:p(s.Stack,{spacing:4,children:[i(s.Text,{size:"sm",children:"Color"}),i(v.Controller,{name:"color",control:o,render:({field:g})=>i(Ve,{...g})})]})}),i(s.Tabs.Panel,{value:"Reference Lines",children:i(vh,{variables:r,control:o,watch:u})})]})]})})}function Mh(e){return x.omit(e,"variables")}function Ah(e){const{label_formatter:t=ze,...n}=e.y_axis;return{...e,y_axis:{...n,label_formatter:t}}}function zh(e){const t={rotate:0,formatter:{...Ue}},{axisLabel:n=t,...r}=e.x_axis;return{...e,x_axis:{...r,axisLabel:n}}}function Eh(e){const t={x_axis:{axisLabel:{overflow:{x_axis:{width:80,overflow:"truncate",ellipsis:"..."},tooltip:{width:200,overflow:"break",ellipsis:"..."}}}}};return x.defaultsDeep(t,e)}function $h(e){delete e.config;const{x_axis:t,tooltip:n}=e.x_axis.axisLabel.overflow,r={x_axis:{axisLabel:{overflow:{on_axis:t,in_tooltip:n}}}};return x.defaultsDeep(r,e)}function Lh(e){const t={tooltip:{metrics:[]}};return x.defaultsDeep(t,e)}function Oh(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=c=>c&&`${n}.${c}`,{x_axis:a,y_axis:o,tooltip:l,...u}=e;return{...u,x_axis:{...a,data_key:r(a.data_key)},y_axis:{...o,data_key:r(o.data_key)},tooltip:{...l,metrics:l.metrics.map(c=>({...c,data_key:r(c.data_key)}))}}}catch(n){throw console.error("[Migration failed]",n),n}}function Ph(e){const t={legend:{show:!0,top:"0",right:"10",left:"auto",bottom:"auto",orient:"horizontal",type:"scroll"}};return x.defaultsDeep(t,e)}class Bh extends ye{constructor(){super(...arguments);N(this,"VERSION",9)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,(n,{panelModel:r})=>{const{config:a}=n;return(a.variables||[]).forEach(l=>{r.variables.find(u=>u.name===l.name)||r.addVariable(l)}),{...n,version:2,config:Mh(a)}}),this.version(3,n=>{const{config:r}=n;return{...n,version:3,config:Ah(r)}}),this.version(4,n=>{const{config:r}=n;return{...n,version:4,config:zh(r)}}),this.version(5,n=>{const{config:r}=n;return{...n,version:5,config:Eh(r)}}),this.version(6,n=>{const{config:r}=n;return{...n,version:6,config:$h(r)}}),this.version(7,n=>{const{config:r}=n;return{...n,version:7,config:Lh(r)}}),this.version(8,(n,r)=>{const{config:a}=n;return{...n,version:8,config:Oh(a,r)}}),this.version(9,n=>{const{config:r}=n;return{...n,version:9,config:Ph(r)}})}}const Vh={displayName:"Boxplot Chart",displayGroup:"ECharts-based charts",migrator:new Bh,name:"boxplot",viewRender:yh,configRender:Ih,createConfig(){return{version:9,config:x.cloneDeep(kr)}},triggers:[os]},Us={id:"builtin:button:click-button",displayName:"Click Button",nameRender:qh,configRender:Nh,payload:[]};function Nh(e){return i(B,{})}function qh(e){return i(s.Text,{children:"Click this button"})}const Qr={content:"Button",variant:"filled",color:"blue",size:"xs",compact:!1,horizontal_align:"left",vertical_align:"center"},Fh={left:"flex-start",center:"center",right:"flex-end"},Gh={top:"flex-start",center:"center",bottom:"flex-end"},Wh=k.observer(({context:e,instance:t})=>{const n=Xe({vizManager:e.vizManager,instance:t}),r=Ke(n.triggerManager,Us.id),a=we(),{value:o}=R(e.instanceData,"config"),l=b.useMemo(()=>x.defaultsDeep({},o,Qr),[o]),{content:u,horizontal_align:c,vertical_align:d,...f}=l,{width:h,height:g}=e.viewport,m=a.payloadForSQL,C=()=>{r.forEach(w=>{n.runInteraction(w.id,{})})};return i(s.Center,{sx:{width:h,height:g,justifyContent:Fh[c],alignItems:Gh[d]},children:i(s.Button,{...f,onClick:C,children:x.template(u)(m)})})}),jh=({value:e,onChange:t,label:n})=>{const r=s.useMantineTheme(),a=b.useCallback(l=>()=>t(l),[t]),o=l=>e===l;return p(s.Stack,{spacing:2,children:[i(s.Text,{size:14,sx:{fontWeight:500},children:n}),i(s.Group,{position:"left",spacing:"xs",children:Object.keys(r.colors).map(l=>{const u=r.colors[l][6];return i(s.ColorSwatch,{color:u,onClick:a(l),radius:4,size:26,sx:{cursor:"pointer"},children:o(l)&&i(s.CheckIcon,{width:10,color:"white"})},l)})})]})},Rh=s.MANTINE_SIZES.map(e=>({label:e.toUpperCase(),value:e})),Yh=({label:e,value:t,onChange:n})=>i(s.Select,{data:Rh,label:e,value:t,onChange:n}),Qh=[{label:"Filled",value:"filled"},{label:"Outline",value:"outline"},{label:"Light",value:"light"},{label:"White",value:"white"},{label:"Default",value:"default"},{label:"Subtle",value:"subtle"},{label:"Gradient",value:"gradient",disabled:!0}],Uh=[{label:"Left",value:"left"},{label:"Center",value:"center"},{label:"Right",value:"right"}],Kh=[{label:"Top",value:"top"},{label:"Center",value:"center"},{label:"Bottom",value:"bottom"}];function Xh({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=b.useMemo(()=>x.defaultsDeep({},t,Qr),[t]),a=r;b.useEffect(()=>{!x.isEqual(r,a)&&(console.log("config malformed, resetting to defaults",r,a),n(a))},[r,a]);const{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});b.useEffect(()=>{d(a)},[a]);const f=c(),h=b.useMemo(()=>!x.isEqual(f,r),[f,r]);return u(["content","variant","color","size","compact","horizontal_align","vertical_align"]),p("form",{onSubmit:l(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Stack,{children:[i(v.Controller,{control:o,name:"content",render:({field:g})=>i(s.TextInput,{label:"Content Template",description:"Filter values & context entries are supported",...g,required:!0})}),i(s.Divider,{mt:"xs",mb:0,label:"Styles",labelPosition:"center",variant:"dashed"}),p(s.SimpleGrid,{cols:2,children:[i(v.Controller,{control:o,name:"variant",render:({field:g})=>i(s.Select,{label:"Variant",data:Qh,...g})}),i(v.Controller,{control:o,name:"color",render:({field:g})=>i(jh,{label:"Theme",...g})})]}),p(s.SimpleGrid,{cols:2,children:[i(v.Controller,{control:o,name:"size",render:({field:g})=>i(Yh,{label:"Size",...g})}),i(v.Controller,{control:o,name:"compact",render:({field:g})=>i(s.Checkbox,{label:"Compact",checked:g.value,onChange:m=>g.onChange(m.currentTarget.checked),mt:26})})]}),p(s.SimpleGrid,{cols:2,children:[i(v.Controller,{control:o,name:"horizontal_align",render:({field:g})=>i(s.Select,{label:"Horizontal Alignment",data:Uh,...g})}),i(v.Controller,{control:o,name:"vertical_align",render:({field:g})=>i(s.Select,{label:"Vertical Alignment",data:Kh,...g})})]})]})]})}class Jh extends ye{constructor(){super(...arguments);N(this,"VERSION",2)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,n=>{const{horizontal_align:r="left",vertical_align:a="center",...o}=n.config;return{...n,version:2,config:{...o,horizontal_align:r,vertical_align:a}}})}}const Zh={displayName:"Button",displayGroup:"Others",migrator:new Jh,name:"button",viewRender:Wh,configRender:Xh,createConfig(){return{version:2,config:x.cloneDeep(Qr)}},triggers:[Us]},Ur={id:"builtin:echarts:click-echart:series",displayName:"Click Chart Series",nameRender:ef,configRender:Hh,payload:[{name:"seriesType",description:"'line' | 'scatter' | 'bar'",valueType:"string"},{name:"componentType",description:"'series'",valueType:"string"},{name:"name",description:"Name of the series clicked",valueType:"string"},{name:"color",description:"Color",valueType:"string"},{name:"value",description:"String-typed number, or series' actual value",valueType:"string"},{name:"rowData",description:"Data of the row",valueType:"object"}]};function Hh(e){return i(B,{})}function ef(e){return i(s.Text,{children:"Click chart's series"})}const qt={x_axis_scroll:!1,y_axis_scroll:!1,x_axis_slider:!1,y_axis_slider:!1},Kr={regressions:[],series:[],stats:{templates:{bottom:"",top:""}},x_axis:{type:"category",axisLabel:{rotate:0,formatter:{...Ue},overflow:Re}},x_axis_data_key:"",x_axis_name:"",y_axes:[{min:"",max:"",name:"Y Axis",show:!0,position:"left",nameAlignment:"center",label_formatter:ze}],reference_lines:[],reference_areas:[],dataZoom:qt};function Xr(e){const t=[];return e.x_axis_scroll&&t.push({type:"inside",xAxisIndex:[0],filterMode:"none",minSpan:1}),e.y_axis_scroll&&t.push({type:"inside",yAxisIndex:[0],filterMode:"none",minSpan:1}),e.x_axis_slider&&t.push({type:"slider",xAxisIndex:[0],filterMode:"none",bottom:"auto",top:0,height:15,moveHandleSize:0,showDataShadow:!1,minSpan:1}),t}function tf(e){const t=e.y_axes.some(a=>!!a.name);let n=15;t&&(n+=20),e.dataZoom.x_axis_slider&&(n+=20);let r=5;return e.x_axis_name&&(r+=15),e.series.some(a=>!a.hide_in_legend)&&(r+=20),{top:n,right:15,bottom:r,left:20,containLabel:!0}}function nf(e){return e!=="line"?{}:{itemStyle:{opacity:0}}}function rf(e){switch(e){case"line":return;case"bar":return"roundRect";case"scatter":return"circle"}}function af(e){const t={show:!0,bottom:0,left:"center",type:"scroll"};return t.data=e.filter(n=>!n.hide_in_legend).map(({name:n,type:r})=>({name:n,icon:rf(r),...nf(r)})),t}function Yn(e,t){switch(e.config.method){case"linear":return[...yt.regressionLinear()(t)];case"exponential":return[...yt.regressionExp()(t)];case"logarithmic":return[...yt.regressionLog()(t)];case"polynomial":return[...yt.regressionPoly().order(e.config.order)(t)];default:return[]}}function sf(e,t,n,r){const{transform:a,plot:o}=e,l={...o,name:t,data:Yn(a,r),showSymbol:!1,tooltip:{show:!1},smooth:!1,custom:{}};return n&&(l.custom={type:"regression-line",targetSeries:n}),l}function of({regressions:e=[],x_axis_data_key:t},n){const r=[];if(Object.keys(n).length===0)return r;function a(o,l,u,c){const d=sf(o,l,u,c);r.push(d)}return e.forEach(o=>{const{name:l,group_by_key:u}=o;if(!u||u===t){const h=pt(n,o.y_axis_data_key).map((g,m)=>[m,Number(g)]);a(o,l,"",h);return}const{columnKey:c}=O(o.y_axis_data_key),d=x.groupBy(en(n,o.y_axis_data_key),u);Object.entries(d).forEach(([f,h])=>{const g=h.map((C,w)=>[w,Number(C[c])]);a(o,f,f,g)})}),r}function lf(e,t){return e.map(n=>({name:"",type:"line",hide_in_legend:!0,data:[],markArea:{itemStyle:{color:n.color},data:[[{yAxis:t[n.y_keys.upper]},{yAxis:t[n.y_keys.lower]}]],silent:!0}}))}function uf(e,t,n,r){return e.map(a=>{const o=a.orientation==="horizontal",l=o?"yAxis":"xAxis",u=o?"insideEndTop":"end";return{name:a.name,type:"line",hide_in_legend:!a.show_in_legend,yAxisIndex:a.yAxisIndex,data:[],lineStyle:a.lineStyle,markLine:{data:[{name:a.name,[l]:n[a.variable_key]}],silent:!0,symbol:["none","none"],lineStyle:a.lineStyle,label:{formatter:function(){return a.template?jn(a.template,t,r):""},position:u}}}})}function cf({type:e,...t},n,r,a){if(!e)return 10;if(e==="static"){const{size:d}=t;return d}const{func_content:o}=t,{queryID:l,columnKey:u}=O(r),c=x.keyBy(en(n,l),u);return(d,f)=>{let h;f.name?h=c[f.name]:h=n[f.dataIndex];try{return new Function(`return ${o}`)()({rowData:h,params:f,variables:a},{lodash:x,interpolate:_t.interpolate})}catch(g){return console.error(`[getEchartsSymbolSize] failed parsing custom function, error: ${g.message}`),10}}}function Jr(e,t,n){const r=pt(e,t),a=pt(e,n);return x.zip(r,a)}function df(e,t,n,r){const a=Jr(t,n,r);return x.unionBy(a,e,0)}function pf({dataTemplate:e,data:t,x_axis_data_key:n,y_axis_data_key:r,valueTypedXAxis:a}){return a?df(e,t,n,r):pt(t,r)}function hf({dataTemplate:e,data:t,aggregation_on_value:n,x_axis_data_key:r,y_axis_data_key:a,valueTypedXAxis:o}){if(!n||n.type==="none")return pf({dataTemplate:e,data:t,x_axis_data_key:r,y_axis_data_key:a,valueTypedXAxis:o});const l=Jr(t,r,a),u=x.groupBy(l,"0");return e.map(([d])=>{const h=u[d].map(m=>m[1]),g=Rr(h,n);return[d,g]})}function ff({group_by_key:e,data:t,x_axis_data_key:n,y_axis_data_key:r}){const{queryID:a,columnKey:o}=O(e),l=x.groupBy(t[a],o);return Object.entries(l).forEach(([u,c])=>{l[u]=Jr({[a]:c},n,r)}),l}function gf({x_axis_data_key:e,x_axis:t},{y_axis_data_key:n,yAxisIndex:r,label_position:a,name:o,group_by_key:l,aggregation_on_value:u,stack:c,color:d,display_name_on_line:f,symbolSize:h,hide_in_legend:g,...m},C,w,_,D){const M=t.type!=="category",P={label:{show:!!a,position:a,formatter:D[r??"default"]},name:o,xAxisId:"main-x-axis",yAxisIndex:r,stack:c,color:d,symbolSize:cf(h,w,e,_),hide_in_legend:g,labelLayout:{hideOverlap:!0},...m};if(f&&(P.endLabel={show:!0,formatter:o,offset:[-12,12],align:"right"}),!l||l===e)return P.data=hf({dataTemplate:C,data:w,aggregation_on_value:u,x_axis_data_key:e,y_axis_data_key:n,valueTypedXAxis:M}),P;const G=ff({group_by_key:l,data:w,x_axis_data_key:e,y_axis_data_key:n});return Object.entries(G).map(([L,z])=>{const A=x.cloneDeep(P);return A.name=L,A.color=void 0,A.data=z,A})}function mf(e,t,n,r,a,o){const l=t.map(c=>[c,0]);return e.series.map(c=>gf(e,c,l,n,o,r)).flat().concat(uf(e.reference_lines,a,o,n)).concat(lf(e.reference_areas,o))}function yf(e,t){const n=e.find(o=>o.axisDim==="x"&&o.axisId==="main-x-axis");if(!n)return"";const{axisValue:r,axisIndex:a}=n;return Pt(t.x_axis.axisLabel.formatter)(r,a)}function bf(e,t,n){const r=t.reduce((a,{yAxisIndex:o,name:l})=>(a[l]=o,a),{});return{trigger:"axis",confine:!0,formatter:function(a){const o=Array.isArray(a)?a:[a];if(o.length===0)return"";const l=o.map(({seriesName:d,marker:f,value:h})=>{if(Array.isArray(h)&&h.length===2&&(h=h[1]),!d)return h;const g=r[d],m=n[g]??n.default;return`
107
107
  <tr>
108
108
  <td>${f}</td>
109
109
  <th style="text-align: right; padding: 0 1em;">${d}</th>
@@ -118,8 +118,8 @@ Check the top-level render call using <`+V+">.")}return E}}function Su(S,E){{if(
118
118
  ${l.join("")}
119
119
  </tbody>
120
120
  </table>
121
- `}}}function vf(e){return e.y_axes.reduce((n,{label_formatter:r},a)=>(n[a]=function(l){let u=l;if(typeof l=="object"&&(Array.isArray(l.value)&&l.value.length===2?u=l.value[1]:u=l.value),!r)return u;try{return Z(u).format(r)}catch(c){return console.error(c),u}},n),{default:({value:n})=>n})}function Ks(e,t){const n={};return t.map(r=>{const a=ft(r,e);n[r.name]=Ze(r,a)}),n}function xf(e,t){const{overflow:n,...r}=e.x_axis.axisLabel,a=rt(n.on_axis);return[{data:t,name:e.x_axis_name??"",id:"main-x-axis",axisTick:{show:!0,alignWithLabel:!0},type:e.x_axis.type,axisLabel:{...r,...a,formatter:Pt(r.formatter)}}]}function wf(e,t){return e.y_axes.map(({nameAlignment:n,min:r,max:a,show:o,...l},u)=>{let c=l.position;return c||(c=u>0?"right":"left"),{...l,minInterval:1,show:o,min:r||void 0,max:a||void 0,position:c,axisLabel:{show:o,formatter:t[u]??t.default},axisLine:{show:o},nameTextStyle:{fontWeight:"bold",align:n},nameLocation:"end",nameGap:o?15:0,splitLine:{show:!1}}})}const Cf={xAxis:[{type:"category",nameGap:25,nameLocation:"center",nameTextStyle:{fontWeight:"bold"},splitLine:{show:!1},axisTick:{show:!0,alignWithLabel:!0}}]};function Sf(e,t,n){const r=Ks(t,n),a=vf(e),o=x.uniq(pt(t,e.x_axis_data_key)),l=mf(e,o,t,a,n,r),u=of(e,t),c={xAxis:xf(e,o),yAxis:wf(e,a),series:[...l,...u],tooltip:bf(e,l,a),grid:tf(e),legend:af(l),dataZoom:Xr(e.dataZoom)};return x.defaultsDeep({},c,Cf)}function Xs(e){const t=e.getModel(),n=t.getSeries().map(r=>{if(!r.option.custom)return r.option;const a=t.getColorFromPalette(r.option.custom.targetSeries,null);return r.option.color=a,r.option});e.setOption({...e.getOption(),series:n})}ie.use([q.DataZoomComponent,he.BarChart,he.LineChart,he.ScatterChart,q.GridComponent,q.LegendComponent,q.TooltipComponent,Pe.CanvasRenderer,q.MarkLineComponent,q.MarkAreaComponent]);function Js(e){return e.trim().length>0}function _f({conf:e,data:t,width:n,height:r,interactionManager:a,variables:o}){const l=Dt(t,e.x_axis_data_key),u=Ke(a.triggerManager,Ur.id),c=y.useCallback(m=>{const C=x.get(l,m.name,{error:"rowData is not found"});u.forEach(w=>{a.runInteraction(w.id,{...m,rowData:C})})},[l,u,a]),d=y.useMemo(()=>Sf(e,t,o),[e,t]),f=y.useRef(),h=y.useMemo(()=>({click:c}),[c]),g=m=>{f.current=m,Xs(m)};return y.useEffect(()=>{f.current&&Xs(f.current)},[d]),!n||!r?null:i(Be,{echarts:ie,option:d,style:{width:n,height:r},onEvents:h,onChartReady:g,notMerge:!0,theme:"merico-light"})}function kf({context:e,instance:t}){const n=Xe({vizManager:e.vizManager,instance:t}),{value:r}=R(e.instanceData,"config"),{variables:a}=e,o=y.useMemo(()=>x.defaults({},r,Kr),[r]),l=e.data,{width:u,height:c}=e.viewport,{ref:d,height:f}=Ie.useElementSize(),{ref:h,height:g}=Ie.useElementSize(),m=y.useMemo(()=>{const{stats:{templates:w}}=o;return{top:un(w.top,a,l),bottom:un(w.bottom,a,l)}},[o,l]),C=Math.max(0,c-f-g);return p(B,{children:[i(s.Text,{ref:d,align:"left",size:"xs",pl:"sm",sx:{display:Js(o.stats.templates.top)?"block":"none"},children:Object.values(m.top).map((w,_)=>i(y.Fragment,{children:w},_))}),i(_f,{variables:a,width:u,height:C,data:l,conf:o,interactionManager:n}),i(s.Text,{ref:h,align:"left",size:"xs",pl:"sm",sx:{display:Js(o.stats.templates.bottom)?"block":"none"},children:Object.values(m.bottom).map((w,_)=>i(y.Fragment,{children:w},_))})]})}const Zr=y.forwardRef(({value:e,onChange:t},n)=>{const r=a=>o=>{t({...e,[a]:o})};return p(s.Stack,{children:[i(s.Divider,{variant:"dashed",label:"Scroll to Zoom",labelPosition:"center"}),p(s.Group,{children:[i(s.Box,{sx:{flexGrow:1},children:i(s.Switch,{label:"Enable on X Axis",checked:e.x_axis_scroll,onChange:a=>r("x_axis_scroll")(a.currentTarget.checked)})}),i(s.Box,{sx:{flexGrow:1},children:i(s.Switch,{label:"Enable on Y Axis",checked:e.y_axis_scroll,onChange:a=>r("y_axis_scroll")(a.currentTarget.checked)})})]}),i(s.Divider,{variant:"dashed",label:"Slider for Zooming",labelPosition:"center"}),p(s.Group,{children:[i(s.Box,{sx:{flexGrow:1},children:i(s.Switch,{label:"Slider for X Axis",checked:e.x_axis_slider,onChange:a=>r("x_axis_slider")(a.currentTarget.checked)})}),i(s.Tooltip,{label:"Not available for now, will overlap y-axis's label",children:i(s.Box,{sx:{flexGrow:1},children:i(s.Switch,{label:"Slider for Y Axis",disabled:!e.y_axis_slider,checked:e.y_axis_slider,onChange:a=>r("y_axis_slider")(a.currentTarget.checked)})})})]})]})}),Tf=[{label:"Rectangle",value:"rectangle"}],Df=[{label:"Horizontal",value:"horizontal"}];function If({control:e,index:t,remove:n,variableOptions:r}){return p(s.Stack,{my:0,p:0,sx:{position:"relative"},children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`reference_areas.${t}.name`,control:e,render:({field:a})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...a})}),i(v.Controller,{name:`reference_areas.${t}.color`,control:e,render:({field:a})=>i(s.TextInput,{label:"Color",required:!0,sx:{flex:1},...a})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`reference_areas.${t}.type`,control:e,render:({field:a})=>i(s.Select,{label:"Type",required:!0,data:Tf,sx:{flex:1},...a})}),i(v.Controller,{name:`reference_areas.${t}.direction`,control:e,render:({field:a})=>i(s.Select,{label:"Direction",required:!0,data:Df,sx:{flex:1},...a})})]}),i(s.Divider,{variant:"dashed",label:"Data",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`reference_areas.${t}.y_keys.upper`,control:e,render:({field:a})=>i(s.Select,{label:"Upper Boundary",required:!0,data:r,sx:{flex:1},...a})}),i(v.Controller,{name:`reference_areas.${t}.y_keys.lower`,control:e,render:({field:a})=>i(s.Select,{label:"Lower Boundary",required:!0,data:r,sx:{flex:1},...a})})]}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Reference Area"})]},t)}function Mf({control:e,watch:t,variables:n}){const{fields:r,append:a,remove:o}=v.useFieldArray({control:e,name:"reference_areas"}),l=t("reference_areas"),u=r.map((f,h)=>({...f,...l[h]})),c=()=>a({name:"",color:"rgba(0,0,0,0.1)",type:"rectangle",direction:"horizontal",y_keys:{upper:"",lower:""}}),d=y.useMemo(()=>n.map(f=>({label:f.name,value:f.name})),[n]);return p(s.Tabs,{defaultValue:"0",styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"6px 0px 0px"}},children:[p(s.Tabs.List,{children:[u.map((f,h)=>i(s.Tabs.Tab,{value:h.toString(),children:h+1},h)),i(s.Tabs.Tab,{onClick:c,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),u.map((f,h)=>i(s.Tabs.Panel,{value:h.toString(),children:i(If,{control:e,index:h,remove:o,variableOptions:d})},h))]})}const Af=[{label:"solid",value:"solid"},{label:"dashed",value:"dashed"},{label:"dotted",value:"dotted"}],zf=[{label:"Horizontal",value:"horizontal"},{label:"Vertical",value:"vertical"}];function Ef({control:e,index:t,remove:n,watch:r,variableOptions:a,yAxisOptions:o}){const l=r(`reference_lines.${t}.orientation`);return p(s.Stack,{my:0,p:0,sx:{position:"relative"},children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`reference_lines.${t}.name`,control:e,render:({field:u})=>i(s.TextInput,{label:"Name",placeholder:"Average Reference Line",required:!0,sx:{flex:1},...u})}),i(v.Controller,{name:`reference_lines.${t}.variable_key`,control:e,render:({field:u})=>i(s.Select,{label:"Value",required:!0,data:a,sx:{flex:1},...u})})]}),i(v.Controller,{name:`reference_lines.${t}.template`,control:e,render:({field:u})=>i(s.TextInput,{label:"Content Template",placeholder:"Average: ${avg}",sx:{flex:1},...u})}),p(s.Group,{grow:!0,children:[p(s.Stack,{children:[i(v.Controller,{name:`reference_lines.${t}.orientation`,control:e,render:({field:u})=>i(s.Select,{label:"Orientation",data:zf,required:!0,sx:{flex:1},...u})}),l==="vertical"&&i(s.Text,{mt:-10,color:"dimmed",size:12,children:"Works only when xAxis values are numbers"})]}),l==="horizontal"&&i(v.Controller,{name:`reference_lines.${t}.yAxisIndex`,control:e,render:({field:{value:u,onChange:c,...d}})=>i(s.Select,{label:"Y Axis",data:o,disabled:o.length===0,...d,value:(u==null?void 0:u.toString())??"",onChange:f=>{if(!f){c(0);return}c(Number(f))},sx:{flex:1}})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Style",labelPosition:"center"}),p(s.Group,{grow:!0,children:[i(v.Controller,{name:`reference_lines.${t}.lineStyle.type`,control:e,render:({field:u})=>i(s.Select,{label:"Line Type",data:Af,sx:{flexGrow:1},...u})}),i(v.Controller,{name:`reference_lines.${t}.lineStyle.width`,control:e,render:({field:u})=>i(s.NumberInput,{label:"Line Width",min:1,max:10,sx:{flexGrow:1},...u})})]}),p(s.Stack,{spacing:4,children:[i(s.Text,{size:"sm",children:"Color"}),i(v.Controller,{name:`reference_lines.${t}.lineStyle.color`,control:e,render:({field:u})=>i(Ve,{...u})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Behavior",labelPosition:"center"}),i(v.Controller,{name:`reference_lines.${t}.show_in_legend`,control:e,render:({field:u})=>i(s.Checkbox,{label:"Show in legend",checked:u.value,onChange:c=>u.onChange(c.currentTarget.checked)})}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Reference Line"})]},t)}function $f({control:e,watch:t,variables:n}){const{fields:r,append:a,remove:o}=v.useFieldArray({control:e,name:"reference_lines"}),l=t("reference_lines"),u=r.map((g,m)=>({...g,...l[m]})),c=()=>{a({name:"",template:"",variable_key:"",orientation:"horizontal",lineStyle:{type:"dashed",width:1,color:"#868E96"},show_in_legend:!1,yAxisIndex:0})},d=y.useMemo(()=>n.map(g=>({label:g.name,value:g.name})),[n]),f=t("y_axes"),h=y.useMemo(()=>f.map(({name:g},m)=>({label:g,value:m.toString()})),[f]);return p(s.Tabs,{defaultValue:"0",styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px"}},children:[p(s.Tabs.List,{children:[u.map((g,m)=>i(s.Tabs.Tab,{value:m.toString(),children:m+1},m)),i(s.Tabs.Tab,{onClick:c,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),u.map((g,m)=>i(s.Tabs.Panel,{value:m.toString(),children:i(Ef,{control:e,index:m,remove:o,watch:t,variableOptions:d,yAxisOptions:h})},m))]})}const Lf=[{label:"Linear",value:"linear"},{label:"Exponential",value:"exponential"},{label:"Logarithmic",value:"logarithmic"},{label:"Polynomial",value:"polynomial"}],Of=[{label:"solid",value:"solid"},{label:"dashed",value:"dashed"},{label:"dotted",value:"dotted"}];function Pf({control:e,regressionItem:t,index:n,remove:r,yAxisOptions:a}){const o=t.transform.config.method;return p(s.Stack,{my:0,p:0,sx:{position:"relative"},children:[p(s.Group,{grow:!0,children:[i(v.Controller,{name:`regressions.${n}.name`,control:e,render:({field:l})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...l})}),i(v.Controller,{name:`regressions.${n}.group_by_key`,control:e,render:({field:l})=>i(W,{label:"Split into multiple regression lines by this key...",clearable:!0,sx:{flex:1},...l})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`regressions.${n}.y_axis_data_key`,control:e,render:({field:l})=>i(W,{label:"Value Field",required:!0,sx:{flex:1},...l})}),i(v.Controller,{name:`regressions.${n}.plot.yAxisIndex`,control:e,render:({field:{value:l,onChange:u,...c}})=>i(s.Select,{label:"Y Axis",data:a,disabled:a.length===0,...c,value:(l==null?void 0:l.toString())??"",onChange:d=>{if(!d){u(0);return}u(Number(d))},sx:{flex:1}})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`regressions.${n}.transform.config.method`,control:e,render:({field:l})=>i(s.Select,{label:"Method",data:Lf,sx:{flex:1},...l})}),o==="polynomial"&&i(v.Controller,{name:`regressions.${n}.transform.config.order`,control:e,render:({field:l})=>i(s.NumberInput,{label:"Order",sx:{flex:1},...l})})]}),i(s.Divider,{mb:-15,variant:"dashed",label:"Line Style",labelPosition:"center"}),p(s.Group,{grow:!0,children:[i(v.Controller,{name:`regressions.${n}.plot.lineStyle.type`,control:e,render:({field:l})=>i(s.Select,{label:"Line Type",data:Of,sx:{flexGrow:1},...l})}),i(v.Controller,{name:`regressions.${n}.plot.lineStyle.width`,control:e,render:({field:l})=>i(s.NumberInput,{label:"Line Width",min:1,max:10,sx:{flexGrow:1},...l})})]}),p(s.Stack,{spacing:4,children:[i(s.Text,{size:"sm",children:"Color"}),i(v.Controller,{name:`regressions.${n}.plot.color`,control:e,render:({field:l})=>i(Ve,{...l})})]}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>r(n),sx:{top:15,right:5},children:"Delete this Regression Line"})]},n)}function Bf({control:e,watch:t}){const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"regressions"}),o=t("regressions"),l=n.map((f,h)=>({...f,...o[h]})),u=t("y_axes"),c=y.useMemo(()=>u.map(({name:f},h)=>({label:f,value:h.toString()})),[u]),d=()=>r({transform:{type:"ecStat:regression",config:{method:"linear",order:1,formulaOn:"end"}},group_by_key:"",name:"",y_axis_data_key:"",plot:{type:"line",yAxisIndex:0,color:"#666666",lineStyle:{type:"solid",width:1}}});return p(s.Tabs,{defaultValue:"0",styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map((f,h)=>i(s.Tabs.Tab,{value:h.toString(),children:h+1},h)),i(s.Tabs.Tab,{onClick:d,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((f,h)=>i(s.Tabs.Panel,{value:h.toString(),children:i(Pf,{regressionItem:f,control:e,index:h,remove:a,yAxisOptions:c},h)},h))]})}const Hr={static:{type:"static",size:10},dynamic:{type:"dynamic",func_content:["function getSize({ rowData, params, variables }, { lodash, interpolate }) {"," // your code goes here"," // return 10","}"].join(`
122
- `)}},Vf=[{label:"No gap between bars",value:"0%"},{label:"Bars overlapping on each other",value:"-100%"}];function Nf({control:e,index:t,seriesItem:n}){const r=!!n.barWidth.trim();return p(B,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${t}.stack`,control:e,render:({field:a})=>i(s.TextInput,{label:"Stack",placeholder:"Stack bars by this ID",sx:{flexGrow:1},...a})}),i(v.Controller,{name:`series.${t}.barGap`,control:e,render:({field:a})=>i(s.Select,{label:"Bar Gap",data:Vf,sx:{flexGrow:1},...a})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${t}.barMinWidth`,control:e,render:({field:a})=>i(s.TextInput,{label:"Bar Width(Min)",disabled:r,sx:{flexGrow:1},...a})}),i(v.Controller,{name:`series.${t}.barWidth`,control:e,render:({field:a})=>i(s.TextInput,{label:"Bar Width",sx:{flexGrow:1},...a})}),i(v.Controller,{name:`series.${t}.barMaxWidth`,control:e,render:({field:a})=>i(s.TextInput,{label:"Bar Width(Max)",disabled:r,sx:{flexGrow:1},...a})})]})]})}const qf=({value:e,onChange:t})=>{const n=r=>{r&&t(r)};return i(s.Box,{children:i(Ae,{height:"500px",defaultLanguage:"javascript",value:e,onChange:n,theme:"vs-dark",options:{minimap:{enabled:!1}}})})},Ff=({value:e,onChange:t})=>{const[n,{setTrue:r,setFalse:a}]=K.useBoolean(),[o,l]=y.useState(e),u=()=>{a();const{type:h,func_content:g}=o,m={type:h,func_content:g};l(m),t(m)},c=()=>{a(),l(e)},d=h=>{l(g=>({...g,func_content:h}))},f=()=>{d(Hr.dynamic.func_content)};return p(B,{children:[i(s.Box,{sx:{width:"50%"},children:i(s.Button,{variant:"filled",mt:24,onClick:r,sx:{flexGrow:0},children:"Setup"})}),i(s.Modal,{size:800,title:"Setup dynamic size",opened:n,onClose:a,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:n&&p(s.Stack,{children:[i(s.Divider,{mt:10,mb:-10,label:"Dynamic by a custom function",labelPosition:"center",variant:"dashed"}),i(qf,{value:o.func_content,onChange:d}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:f,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:c,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:u,children:"OK"})]})]})]})})]})},Gf=({value:e,onChange:t})=>e.type!=="dynamic"?null:i(Ff,{value:e,onChange:t}),Wf=({value:e,onChange:t})=>{if(e.type!=="static")return null;const n=r=>{t({...e,size:r})};return i(B,{children:i(s.NumberInput,{defaultValue:18,placeholder:"1 ~ 100",label:" ",hideControls:!0,value:e.size,onChange:n})})},jf=[{label:"Static",value:"static"},{label:"Dynamic",value:"dynamic"}],Zs=y.forwardRef(({label:e="Size",value:t,onChange:n},r)=>{const a=o=>{n({...Hr[o]})};return p(s.SimpleGrid,{cols:2,children:[i(s.Select,{ref:r,label:e,data:jf,value:t.type,onChange:a,sx:{flexGrow:1}}),i(Wf,{value:t,onChange:n}),i(Gf,{value:t,onChange:n})]})}),Rf=[{label:"off",value:"false"},{label:"start",value:"start"},{label:"middle",value:"middle"},{label:"end",value:"end"}],Yf=[{label:"solid",value:"solid"},{label:"dashed",value:"dashed"},{label:"dotted",value:"dotted"}];function Qf({control:e,index:t,seriesItem:n}){const r=n.showSymbol;return p(B,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Line Settings",labelPosition:"center"}),p(s.Group,{grow:!0,children:[i(v.Controller,{name:`series.${t}.lineStyle.type`,control:e,render:({field:a})=>i(s.Select,{label:"Line Type",data:Yf,sx:{flexGrow:1},...a})}),i(v.Controller,{name:`series.${t}.lineStyle.width`,control:e,render:({field:a})=>i(s.NumberInput,{label:"Line Width",min:1,max:10,sx:{flexGrow:1},...a})})]}),p(s.Group,{grow:!0,align:"center",children:[i(v.Controller,{name:`series.${t}.step`,control:e,render:({field:a})=>i(s.Select,{label:"Step",data:Rf,sx:{flexGrow:1,maxWidth:"48%"},...a,value:String(a.value),onChange:o=>{const l=o==="false"?!1:o;a.onChange(l)}})}),p(s.Stack,{children:[i(v.Controller,{name:`series.${t}.smooth`,control:e,render:({field:a})=>i(s.Box,{sx:{flexGrow:1},children:i(s.Switch,{label:"Smooth Line",checked:a.value,onChange:o=>a.onChange(o.currentTarget.checked)})})}),i(v.Controller,{name:`series.${t}.display_name_on_line`,control:e,render:({field:a})=>i(s.Box,{sx:{flexGrow:1},children:i(s.Switch,{label:"Display Name on Line",checked:a.value??!1,onChange:o=>a.onChange(o.currentTarget.checked)})})})]})]}),p(s.Stack,{children:[i(v.Controller,{name:`series.${t}.showSymbol`,control:e,render:({field:a})=>i(s.Box,{mt:10,mb:-10,sx:{flexGrow:1},children:i(s.Switch,{label:"Show Symbol on Line",checked:a.value,onChange:o=>a.onChange(o.currentTarget.checked)})})}),r&&i(v.Controller,{name:`series.${t}.symbolSize`,control:e,render:({field:a})=>i(Zs,{label:"Symbol Size",...a})})]})]})}function Uf({control:e,index:t}){return i(v.Controller,{name:`series.${t}.symbolSize`,control:e,render:({field:n})=>i(Zs,{label:"Size",...n})})}const Kf=[{label:"off",value:""},{label:"top",value:"top"},{label:"left",value:"left"},{label:"right",value:"right"},{label:"bottom",value:"bottom"},{label:"inside",value:"inside"},{label:"insideLeft",value:"insideLeft"},{label:"insideRight",value:"insideRight"},{label:"insideTop",value:"insideTop"},{label:"insideBottom",value:"insideBottom"},{label:"insideTopLeft",value:"insideTopLeft"},{label:"insideBottomLeft",value:"insideBottomLeft"},{label:"insideTopRight",value:"insideTopRight"},{label:"insideBottomRight",value:"insideBottomRight"}];function Xf({control:e,index:t,remove:n,seriesItem:r,yAxisOptions:a}){const o=r.type;return p(s.Stack,{my:0,p:0,sx:{position:"relative"},children:[i(s.Stack,{children:i(v.Controller,{name:`series.${t}.type`,control:e,render:({field:l})=>i(s.SegmentedControl,{data:[{label:"Line",value:"line"},{label:"Bar",value:"bar"},{label:"Scatter",value:"scatter"}],...l})})}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${t}.name`,control:e,render:({field:l})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...l})}),i(v.Controller,{name:`series.${t}.yAxisIndex`,control:e,render:({field:{value:l,onChange:u,...c}})=>i(s.Select,{label:"Y Axis",data:a,disabled:a.length===0,...c,value:(l==null?void 0:l.toString())??"",onChange:d=>{if(!d){u(0);return}u(Number(d))},sx:{flex:1}})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${t}.y_axis_data_key`,control:e,render:({field:l})=>i(W,{label:"Value Field",required:!0,sx:{flex:1},...l})}),i(v.Controller,{name:`series.${t}.aggregation_on_value`,control:e,render:({field:l})=>i(Gn,{label:"Aggregation on Value",value:l.value??Nt,onChange:l.onChange,pt:0})})]}),i(s.Group,{grow:!0,children:i(v.Controller,{name:`series.${t}.group_by_key`,control:e,render:({field:l})=>i(W,{label:"Split into multiple series by this key...",clearable:!0,sx:{flex:1},...l})})}),o==="line"&&i(Qf,{index:t,control:e,seriesItem:r}),o==="bar"&&i(Nf,{index:t,control:e,seriesItem:r}),o==="scatter"&&i(Uf,{index:t,control:e}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Style",labelPosition:"center"}),i(v.Controller,{name:`series.${t}.label_position`,control:e,render:({field:l})=>i(s.Select,{label:"Label Position",data:Kf,...l})}),p(s.Stack,{spacing:4,children:[i(s.Text,{size:"sm",children:"Color"}),i(v.Controller,{name:`series.${t}.color`,control:e,render:({field:l})=>i(Ve,{...l})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Behavior",labelPosition:"center"}),i(v.Controller,{name:`series.${t}.hide_in_legend`,control:e,render:({field:l})=>i(s.Checkbox,{label:"Hide in legend",checked:l.value,onChange:u=>l.onChange(u.currentTarget.checked)})}),i(s.Divider,{mb:-10,mt:10,variant:"dashed"}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Series"})]},t)}function Jf({control:e,watch:t}){const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"series"}),o=t("series"),l=n.map((f,h)=>({...f,...o[h]})),u=()=>{const f={type:"bar",name:Ie.randomId(),showSymbol:!1,symbolSize:Hr.static,y_axis_data_key:"value",yAxisIndex:0,label_position:"top",display_name_on_line:!1,stack:"",color:"#000",step:!1,smooth:!1,barMinWidth:"1",barWidth:"10%",barMaxWidth:"10",barGap:"0%",lineStyle:{type:"solid",width:1},hide_in_legend:!1,group_by_key:""};r(f)},c=t("y_axes"),d=y.useMemo(()=>c.map(({name:f},h)=>({label:f,value:h.toString()})),[c]);return p(s.Tabs,{defaultValue:"0",styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map((f,h)=>i(s.Tabs.Tab,{value:h.toString(),children:h+1},f.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((f,h)=>i(s.Tabs.Panel,{value:h.toString(),children:i(Xf,{control:e,index:h,remove:a,seriesItem:f,yAxisOptions:d},f.id)},f.id))]})}function Zf({control:e,watch:t}){return t("stats"),i(s.Stack,{children:p(s.Stack,{spacing:0,children:[i(v.Controller,{name:"stats.templates.top",control:e,render:({field:n})=>i(en,{label:"Template for stats above the chart",py:"md",sx:{flexGrow:1},...n})}),i(v.Controller,{name:"stats.templates.bottom",control:e,render:({field:n})=>i(en,{label:"Template for stats under the chart",py:"md",sx:{flexGrow:1},...n})})]})})}const Hf=()=>p(s.Group,{sx:{display:"inline-flex"},spacing:6,mr:14,children:[i(s.Text,{children:"X Axis Data Type"}),p(s.HoverCard,{width:340,shadow:"md",position:"top",children:[i(s.HoverCard.Target,{children:i(s.ActionIcon,{size:"xs",sx:{transform:"none !important"},children:i($.IconInfoCircle,{})})}),i(s.HoverCard.Dropdown,{children:p(s.Text,{size:"sm",children:["Click",i(s.Anchor,{href:"https://echarts.apache.org/en/option.html#xAxis.type",target:"_blank",mx:4,children:"here"}),"to learn more about these options"]})})]})]}),eg=[{label:"Value",value:"value"},{label:"Category",value:"category"},{label:"Time",value:"time"},{label:"Log",value:"log"}];function tg({control:e,watch:t}){return t(["x_axis_data_key","x_axis_name","x_axis"]),p(s.Stack,{children:[i(v.Controller,{name:"x_axis_name",control:e,render:({field:n})=>i(s.TextInput,{label:"X Axis Name",sx:{flex:1},...n})}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis_data_key",control:e,render:({field:n})=>i(W,{label:"X Axis Data Field",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"x_axis.type",control:e,render:({field:n})=>i(s.Select,{label:i(Hf,{}),required:!0,data:eg,sx:{flex:1},...n})})]}),i(s.Divider,{mb:-15,label:"Tick Label",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.axisLabel.rotate",control:e,render:({field:n})=>i(s.NumberInput,{label:"Rotate",hideControls:!0,min:-90,max:90,rightSection:i(s.Text,{color:"dimmed",children:"degree"}),sx:{width:"48%"},styles:{rightSection:{width:"4em",justifyContent:"flex-end",paddingRight:"6px"}},...n})}),i(v.Controller,{name:"x_axis.axisLabel.formatter",control:e,render:({field:n})=>i(Rn,{...n})})]}),i(v.Controller,{name:"x_axis.axisLabel.overflow",control:e,render:({field:n})=>i(at,{...n})})]})}const ng=[{label:"left",value:"left"},{label:"center",value:"center"},{label:"right",value:"right"}],rg=[{label:"left",value:"left"},{label:"right",value:"right"}];function ig({control:e,index:t,remove:n}){return p(s.Stack,{my:0,p:"0",sx:{position:"relative"},children:[i(s.Divider,{mb:-15,mt:15,variant:"dashed",label:"Name",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`y_axes.${t}.name`,control:e,render:({field:r})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:`y_axes.${t}.nameAlignment`,control:e,render:({field:r})=>i(s.Select,{label:"Name Anchor",required:!0,data:ng,sx:{flex:1},...r})})]}),i(s.Divider,{mb:-15,variant:"dashed",label:"Layout",labelPosition:"center"}),i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:`y_axes.${t}.position`,control:e,render:({field:r})=>i(s.Select,{label:"Position",required:!0,data:rg,sx:{flex:1},...r})})}),p(s.Stack,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Label Format",labelPosition:"center"}),i(v.Controller,{name:`y_axes.${t}.label_formatter`,control:e,render:({field:r})=>i(We,{...r})})]}),p(s.Stack,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Value Range",labelPosition:"center"}),p(s.Group,{grow:!0,children:[i(v.Controller,{name:`y_axes.${t}.min`,control:e,render:({field:r})=>i(s.TextInput,{label:"Min",...r})}),i(v.Controller,{name:`y_axes.${t}.max`,control:e,render:({field:r})=>i(s.TextInput,{label:"Max",...r})})]})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Behavior",labelPosition:"center"}),i(v.Controller,{name:`y_axes.${t}.show`,control:e,render:({field:r})=>i(s.Checkbox,{label:"Visible",checked:r.value,onChange:a=>r.onChange(a.currentTarget.checked)})}),i(s.Button,{mt:20,leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),disabled:t===0,children:"Delete this YAxis"})]})}function ag({control:e,watch:t}){const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"y_axes"}),o=t("y_axes"),l=n.map((c,d)=>({...c,...o[d]})),u=()=>r({name:"",position:"left",nameAlignment:"left",label_formatter:ze,min:"",max:"",show:!0});return p(s.Tabs,{defaultValue:"0",styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px"}},children:[p(s.Tabs.List,{children:[l.map((c,d)=>i(s.Tabs.Tab,{value:d.toString(),children:d+1},d)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((c,d)=>i(s.Tabs.Panel,{value:d.toString(),children:i(ig,{control:e,index:d,remove:a})},d))]})}function sg({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),{variables:r}=e,a=y.useMemo(()=>x.defaultsDeep({},t,Kr),[t]),{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});y.useEffect(()=>{d(a)},[a]);const f=c(),h=y.useMemo(()=>!x.isEqual(f,a),[f,a]);return u(["dataZoom"]),i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:l(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"Series",orientation:"vertical",styles:{tab:{paddingLeft:"6px",paddingRight:"6px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"X Axis",children:"X Axis"}),i(s.Tabs.Tab,{value:"Y Axes",children:"Y Axes"}),i(s.Tabs.Tab,{value:"Series",children:"Series"}),i(s.Tabs.Tab,{value:"Regression Lines",children:"Regression Lines"}),i(s.Tabs.Tab,{value:"Stats",children:"Stats"}),i(s.Tabs.Tab,{value:"Reference Lines",children:"Reference Lines"}),i(s.Tabs.Tab,{value:"Reference Areas",children:"Reference Areas"}),i(s.Tabs.Tab,{value:"Zooming",children:"Zooming"})]}),i(s.Tabs.Panel,{value:"X Axis",children:i(tg,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Y Axes",children:i(ag,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Series",children:i(Jf,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Regression Lines",children:i(Bf,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Stats",children:i(Zf,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Reference Lines",children:i($f,{variables:r,control:o,watch:u})}),i(s.Tabs.Panel,{value:"Reference Areas",children:i(Mf,{variables:r,control:o,watch:u})}),i(s.Tabs.Panel,{value:"Zooming",children:i(v.Controller,{name:"dataZoom",control:o,render:({field:g})=>i(Zr,{...g})})})]})]})})}function og(e){const t=x.cloneDeep(x.omit(e,"variables"));return t.stats=x.omit(t.stats,"variables"),t}function lg(e){const{rotate:t,formatter:n=Ue}=e.x_axis.axisLabel;return{...e,x_axis:{...e.x_axis,axisLabel:{rotate:t,formatter:n}}}}function ug(e){const{dataZoom:t=qt,...n}=e;return{...n,dataZoom:t}}function cg(e){const t={x_axis:{axisLabel:{overflow:{x_axis:{width:80,overflow:"truncate",ellipsis:"..."},tooltip:{width:200,overflow:"break",ellipsis:"..."}}}}};return x.defaultsDeep(t,e)}function dg(e){const t=e.reference_lines.map(n=>{const{lineStyle:r={type:"dashed",width:1,color:ct.random().css()},show_in_legend:a=!1}=n;return{...n,lineStyle:r,show_in_legend:a}});return{...e,reference_lines:t}}function pg(e){const t=e.reference_lines.map(n=>{const{yAxisIndex:r=0}=n;return{...n,yAxisIndex:r}});return{...e,reference_lines:t}}function hg(e){const t=e.series.map(n=>{const{aggregation_on_group:r=Nt}=n;return{...n,aggregation_on_group:r}});return{...e,series:t}}function fg(e){const t=e.series.map(n=>{const{aggregation_on_value:r=Nt}=n;return{...n,aggregation_on_value:r}});return{...e,series:t}}function gg(e){delete e.config;const{x_axis:t,tooltip:n}=e.x_axis.axisLabel.overflow,r={x_axis:{axisLabel:{overflow:{on_axis:t,in_tooltip:n}}}};return x.defaultsDeep(r,e)}function mg(e){const{series:t,...n}=e;return{...n,series:t.map(r=>{const{barMinWidth:a,barWidth:o,barMaxWidth:l}=r;return a?{...r,barMinWidth:a,barWidth:"",barMaxWidth:l??o}:{...r,barMinWidth:"",barWidth:o,barMaxWidth:""}})}}function yg(e){const{y_axes:t,...n}=e;return{...n,y_axes:t.map(r=>{const{min:a="",max:o=""}=r;return{...r,min:a,max:o}})}}function bg(e){const{y_axes:t,...n}=e;return{...n,y_axes:t.map(r=>{const{nameAlignment:a="left"}=r;return{...r,nameAlignment:a}})}}function vg(e){const{y_axes:t,...n}=e;return{...n,y_axes:t.map(r=>{const{show:a=!0}=r;return{...r,show:a}})}}function xg(e){const{regressions:t,...n}=e;return{...n,regressions:t.map(r=>{const{group_by_key:a=""}=r;return{...r,group_by_key:a}})}}function wg(e){const{series:t,y_axes:n,...r}=e;return{...r,series:t.map(a=>{const{hide_in_legend:o=!1,aggregation_on_value:l=Nt}=a;return{...a,hide_in_legend:o,aggregation_on_value:l}}),y_axes:n.map(a=>{const{min:o="",max:l="",show:u=!0}=a;return{...a,min:o,max:l,show:u}})}}function Cg(e){const{type:t="category",...n}=e.x_axis;return{...e,x_axis:{...n,type:t}}}function Sg(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=c=>c&&`${n}.${c}`,{x_axis_data_key:a,series:o,regressions:l,...u}=e;return{...u,x_axis_data_key:r(a),series:o.map(c=>({...c,y_axis_data_key:r(c.y_axis_data_key),group_by_key:r(c.group_by_key)})),regressions:l.map(c=>({...c,y_axis_data_key:r(c.y_axis_data_key),group_by_key:r(c.group_by_key)}))}}catch(n){throw console.error("[Migration failed]",n),n}}class _g extends ye{constructor(){super(...arguments);N(this,"VERSION",18)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,(n,{panelModel:r})=>{const{config:a}=n;return(a.variables||[]).forEach(u=>{r.variables.find(c=>c.name===u.name)||r.addVariable(u)}),(x.get(a,"stats.variables")||[]).forEach(u=>{r.variables.find(c=>c.name===u.name)||r.addVariable(u)}),{...n,version:2,config:og(a)}}),this.version(3,n=>({...n,version:3,config:lg(n.config)})),this.version(4,n=>({...n,version:4,config:ug(n.config)})),this.version(5,n=>({...n,version:5,config:cg(n.config)})),this.version(6,n=>({...n,version:6,config:dg(n.config)})),this.version(7,n=>({...n,version:7,config:pg(n.config)})),this.version(8,n=>({...n,version:8,config:hg(n.config)})),this.version(9,n=>({...n,version:9,config:fg(n.config)})),this.version(10,n=>({...n,version:10,config:gg(n.config)})),this.version(11,n=>({...n,version:11,config:mg(n.config)})),this.version(12,n=>({...n,version:12,config:yg(n.config)})),this.version(13,n=>({...n,version:13,config:bg(n.config)})),this.version(14,n=>({...n,version:14,config:vg(n.config)})),this.version(15,n=>({...n,version:15,config:xg(n.config)})),this.version(16,n=>({...n,version:16,config:wg(n.config)})),this.version(17,n=>({...n,version:17,config:Cg(n.config)})),this.version(18,(n,r)=>({...n,version:18,config:Sg(n.config,r)}))}}const kg={displayName:"Cartesian Chart",displayGroup:"ECharts-based charts",migrator:new _g,name:"cartesian",viewRender:kf,configRender:sg,createConfig(){return{version:18,config:x.cloneDeep(Kr)}},triggers:[Ur]};function Tg(e){if(e.enable_value)return e.value}function Dg(e){if(e.enable_value)return e.value}function Ig(e){const t=e.axisLabel.overflow.on_axis.width,n=e.axisLabel.position,r={top:5,left:5,right:5,bottom:5};return e.orient==="vertical"&&x.get(r,n)&&n===e.funnelAlign&&x.set(r,n,t),r}function Mg(e,t){return e.series.map(n=>{const{level_name_data_key:r,level_value_data_key:a,axisLabel:o,min:l,max:u,funnelAlign:c,orient:d,...f}=n;if(!r||!a)return{};const h=O(r),g=O(a),m=t[h.queryID].map(w=>({name:w[h.columnKey],value:w[g.columnKey]})),C=rt(o.overflow.on_axis);return{type:"funnel",...Ig(n),min:Tg(l),max:Dg(u),minSize:l.size,maxSize:u.size,...f,label:{show:!0,position:o.position,...C},orient:d,funnelAlign:d==="horizontal"?"center":c,data:m}})}function Ag({conf:e,params:t,max:n}){const{name:r,value:a}=t.data,o=Z(a/n).format({output:"percent",mantissa:2,trimMantissa:!0});return[{label:`${t.marker} ${r}`,value:`${a} (${o})`,style:{label:"",value:""}}]}function zg(e,t){var o;const n=O(e.series[0].level_name_data_key),r=O(e.series[0].level_value_data_key),a=(o=x.maxBy(t[n.queryID],r.columnKey))==null?void 0:o[r.columnKey];return l=>{const c=Ag({conf:e,params:l,max:a}).map(f=>`
121
+ `}}}function vf(e){return e.y_axes.reduce((n,{label_formatter:r},a)=>(n[a]=function(l){let u=l;if(typeof l=="object"&&(Array.isArray(l.value)&&l.value.length===2?u=l.value[1]:u=l.value),!r)return u;try{return Z(u).format(r)}catch(c){return console.error(c),u}},n),{default:({value:n})=>n})}function Ks(e,t){const n={};return t.map(r=>{const a=ft(r,e);n[r.name]=Ze(r,a)}),n}function xf(e,t){const{overflow:n,...r}=e.x_axis.axisLabel,a=rt(n.on_axis);return[{data:t,name:e.x_axis_name??"",id:"main-x-axis",axisTick:{show:!0,alignWithLabel:!0},type:e.x_axis.type,axisLabel:{...r,...a,formatter:Pt(r.formatter)}}]}function wf(e,t){return e.y_axes.map(({nameAlignment:n,min:r,max:a,show:o,...l},u)=>{let c=l.position;return c||(c=u>0?"right":"left"),{...l,minInterval:1,show:o,min:r||void 0,max:a||void 0,position:c,axisLabel:{show:o,formatter:t[u]??t.default},axisLine:{show:o},nameTextStyle:{fontWeight:"bold",align:n},nameLocation:"end",nameGap:o?15:0,splitLine:{show:!1}}})}const Cf={xAxis:[{type:"category",nameGap:25,nameLocation:"center",nameTextStyle:{fontWeight:"bold"},splitLine:{show:!1},axisTick:{show:!0,alignWithLabel:!0}}]};function Sf(e,t,n){const r=Ks(t,n),a=vf(e),o=x.uniq(pt(t,e.x_axis_data_key)),l=mf(e,o,t,a,n,r),u=of(e,t),c={xAxis:xf(e,o),yAxis:wf(e,a),series:[...l,...u],tooltip:bf(e,l,a),grid:tf(e),legend:af(l),dataZoom:Xr(e.dataZoom)};return x.defaultsDeep({},c,Cf)}function Xs(e){const t=e.getModel(),n=t.getSeries().map(r=>{if(!r.option.custom)return r.option;const a=t.getColorFromPalette(r.option.custom.targetSeries,null);return r.option.color=a,r.option});e.setOption({...e.getOption(),series:n})}ie.use([q.DataZoomComponent,he.BarChart,he.LineChart,he.ScatterChart,q.GridComponent,q.LegendComponent,q.TooltipComponent,Pe.CanvasRenderer,q.MarkLineComponent,q.MarkAreaComponent]);function Js(e){return e.trim().length>0}function _f({conf:e,data:t,width:n,height:r,interactionManager:a,variables:o}){const l=Dt(t,e.x_axis_data_key),u=Ke(a.triggerManager,Ur.id),c=b.useCallback(m=>{const C=x.get(l,m.name,{error:"rowData is not found"});u.forEach(w=>{a.runInteraction(w.id,{...m,rowData:C})})},[l,u,a]),d=b.useMemo(()=>Sf(e,t,o),[e,t]),f=b.useRef(),h=b.useMemo(()=>({click:c}),[c]),g=m=>{f.current=m,Xs(m)};return b.useEffect(()=>{f.current&&Xs(f.current)},[d]),!n||!r?null:i(Be,{echarts:ie,option:d,style:{width:n,height:r},onEvents:h,onChartReady:g,notMerge:!0,theme:"merico-light"})}function kf({context:e,instance:t}){const n=Xe({vizManager:e.vizManager,instance:t}),{value:r}=R(e.instanceData,"config"),{variables:a}=e,o=b.useMemo(()=>x.defaults({},r,Kr),[r]),l=e.data,{width:u,height:c}=e.viewport,{ref:d,height:f}=Ie.useElementSize(),{ref:h,height:g}=Ie.useElementSize(),m=b.useMemo(()=>{const{stats:{templates:w}}=o;return{top:cn(w.top,a,l),bottom:cn(w.bottom,a,l)}},[o,l]),C=Math.max(0,c-f-g);return p(B,{children:[i(s.Text,{ref:d,align:"left",size:"xs",pl:"sm",sx:{display:Js(o.stats.templates.top)?"block":"none"},children:Object.values(m.top).map((w,_)=>i(b.Fragment,{children:w},_))}),i(_f,{variables:a,width:u,height:C,data:l,conf:o,interactionManager:n}),i(s.Text,{ref:h,align:"left",size:"xs",pl:"sm",sx:{display:Js(o.stats.templates.bottom)?"block":"none"},children:Object.values(m.bottom).map((w,_)=>i(b.Fragment,{children:w},_))})]})}const Zr=b.forwardRef(({value:e,onChange:t},n)=>{const r=a=>o=>{t({...e,[a]:o})};return p(s.Stack,{children:[i(s.Divider,{variant:"dashed",label:"Scroll to Zoom",labelPosition:"center"}),p(s.Group,{children:[i(s.Box,{sx:{flexGrow:1},children:i(s.Switch,{label:"Enable on X Axis",checked:e.x_axis_scroll,onChange:a=>r("x_axis_scroll")(a.currentTarget.checked)})}),i(s.Box,{sx:{flexGrow:1},children:i(s.Switch,{label:"Enable on Y Axis",checked:e.y_axis_scroll,onChange:a=>r("y_axis_scroll")(a.currentTarget.checked)})})]}),i(s.Divider,{variant:"dashed",label:"Slider for Zooming",labelPosition:"center"}),p(s.Group,{children:[i(s.Box,{sx:{flexGrow:1},children:i(s.Switch,{label:"Slider for X Axis",checked:e.x_axis_slider,onChange:a=>r("x_axis_slider")(a.currentTarget.checked)})}),i(s.Tooltip,{label:"Not available for now, will overlap y-axis's label",children:i(s.Box,{sx:{flexGrow:1},children:i(s.Switch,{label:"Slider for Y Axis",disabled:!e.y_axis_slider,checked:e.y_axis_slider,onChange:a=>r("y_axis_slider")(a.currentTarget.checked)})})})]})]})}),Tf=[{label:"Rectangle",value:"rectangle"}],Df=[{label:"Horizontal",value:"horizontal"}];function If({control:e,index:t,remove:n,variableOptions:r}){return p(s.Stack,{my:0,p:0,sx:{position:"relative"},children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`reference_areas.${t}.name`,control:e,render:({field:a})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...a})}),i(v.Controller,{name:`reference_areas.${t}.color`,control:e,render:({field:a})=>i(s.TextInput,{label:"Color",required:!0,sx:{flex:1},...a})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`reference_areas.${t}.type`,control:e,render:({field:a})=>i(s.Select,{label:"Type",required:!0,data:Tf,sx:{flex:1},...a})}),i(v.Controller,{name:`reference_areas.${t}.direction`,control:e,render:({field:a})=>i(s.Select,{label:"Direction",required:!0,data:Df,sx:{flex:1},...a})})]}),i(s.Divider,{variant:"dashed",label:"Data",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`reference_areas.${t}.y_keys.upper`,control:e,render:({field:a})=>i(s.Select,{label:"Upper Boundary",required:!0,data:r,sx:{flex:1},...a})}),i(v.Controller,{name:`reference_areas.${t}.y_keys.lower`,control:e,render:({field:a})=>i(s.Select,{label:"Lower Boundary",required:!0,data:r,sx:{flex:1},...a})})]}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Reference Area"})]},t)}function Mf({control:e,watch:t,variables:n}){const{fields:r,append:a,remove:o}=v.useFieldArray({control:e,name:"reference_areas"}),l=t("reference_areas"),u=r.map((f,h)=>({...f,...l[h]})),c=()=>a({name:"",color:"rgba(0,0,0,0.1)",type:"rectangle",direction:"horizontal",y_keys:{upper:"",lower:""}}),d=b.useMemo(()=>n.map(f=>({label:f.name,value:f.name})),[n]);return p(s.Tabs,{defaultValue:"0",styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"6px 0px 0px"}},children:[p(s.Tabs.List,{children:[u.map((f,h)=>i(s.Tabs.Tab,{value:h.toString(),children:h+1},h)),i(s.Tabs.Tab,{onClick:c,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),u.map((f,h)=>i(s.Tabs.Panel,{value:h.toString(),children:i(If,{control:e,index:h,remove:o,variableOptions:d})},h))]})}const Af=[{label:"solid",value:"solid"},{label:"dashed",value:"dashed"},{label:"dotted",value:"dotted"}],zf=[{label:"Horizontal",value:"horizontal"},{label:"Vertical",value:"vertical"}];function Ef({control:e,index:t,remove:n,watch:r,variableOptions:a,yAxisOptions:o}){const l=r(`reference_lines.${t}.orientation`);return p(s.Stack,{my:0,p:0,sx:{position:"relative"},children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`reference_lines.${t}.name`,control:e,render:({field:u})=>i(s.TextInput,{label:"Name",placeholder:"Average Reference Line",required:!0,sx:{flex:1},...u})}),i(v.Controller,{name:`reference_lines.${t}.variable_key`,control:e,render:({field:u})=>i(s.Select,{label:"Value",required:!0,data:a,sx:{flex:1},...u})})]}),i(v.Controller,{name:`reference_lines.${t}.template`,control:e,render:({field:u})=>i(s.TextInput,{label:"Content Template",placeholder:"Average: ${avg}",sx:{flex:1},...u})}),p(s.Group,{grow:!0,children:[p(s.Stack,{children:[i(v.Controller,{name:`reference_lines.${t}.orientation`,control:e,render:({field:u})=>i(s.Select,{label:"Orientation",data:zf,required:!0,sx:{flex:1},...u})}),l==="vertical"&&i(s.Text,{mt:-10,color:"dimmed",size:12,children:"Works only when xAxis values are numbers"})]}),l==="horizontal"&&i(v.Controller,{name:`reference_lines.${t}.yAxisIndex`,control:e,render:({field:{value:u,onChange:c,...d}})=>i(s.Select,{label:"Y Axis",data:o,disabled:o.length===0,...d,value:(u==null?void 0:u.toString())??"",onChange:f=>{if(!f){c(0);return}c(Number(f))},sx:{flex:1}})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Style",labelPosition:"center"}),p(s.Group,{grow:!0,children:[i(v.Controller,{name:`reference_lines.${t}.lineStyle.type`,control:e,render:({field:u})=>i(s.Select,{label:"Line Type",data:Af,sx:{flexGrow:1},...u})}),i(v.Controller,{name:`reference_lines.${t}.lineStyle.width`,control:e,render:({field:u})=>i(s.NumberInput,{label:"Line Width",min:1,max:10,sx:{flexGrow:1},...u})})]}),p(s.Stack,{spacing:4,children:[i(s.Text,{size:"sm",children:"Color"}),i(v.Controller,{name:`reference_lines.${t}.lineStyle.color`,control:e,render:({field:u})=>i(Ve,{...u})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Behavior",labelPosition:"center"}),i(v.Controller,{name:`reference_lines.${t}.show_in_legend`,control:e,render:({field:u})=>i(s.Checkbox,{label:"Show in legend",checked:u.value,onChange:c=>u.onChange(c.currentTarget.checked)})}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Reference Line"})]},t)}function $f({control:e,watch:t,variables:n}){const{fields:r,append:a,remove:o}=v.useFieldArray({control:e,name:"reference_lines"}),l=t("reference_lines"),u=r.map((g,m)=>({...g,...l[m]})),c=()=>{a({name:"",template:"",variable_key:"",orientation:"horizontal",lineStyle:{type:"dashed",width:1,color:"#868E96"},show_in_legend:!1,yAxisIndex:0})},d=b.useMemo(()=>n.map(g=>({label:g.name,value:g.name})),[n]),f=t("y_axes"),h=b.useMemo(()=>f.map(({name:g},m)=>({label:g,value:m.toString()})),[f]);return p(s.Tabs,{defaultValue:"0",styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px"}},children:[p(s.Tabs.List,{children:[u.map((g,m)=>i(s.Tabs.Tab,{value:m.toString(),children:m+1},m)),i(s.Tabs.Tab,{onClick:c,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),u.map((g,m)=>i(s.Tabs.Panel,{value:m.toString(),children:i(Ef,{control:e,index:m,remove:o,watch:t,variableOptions:d,yAxisOptions:h})},m))]})}const Lf=[{label:"Linear",value:"linear"},{label:"Exponential",value:"exponential"},{label:"Logarithmic",value:"logarithmic"},{label:"Polynomial",value:"polynomial"}],Of=[{label:"solid",value:"solid"},{label:"dashed",value:"dashed"},{label:"dotted",value:"dotted"}];function Pf({control:e,regressionItem:t,index:n,remove:r,yAxisOptions:a}){const o=t.transform.config.method;return p(s.Stack,{my:0,p:0,sx:{position:"relative"},children:[p(s.Group,{grow:!0,children:[i(v.Controller,{name:`regressions.${n}.name`,control:e,render:({field:l})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...l})}),i(v.Controller,{name:`regressions.${n}.group_by_key`,control:e,render:({field:l})=>i(W,{label:"Split into multiple regression lines by this key...",clearable:!0,sx:{flex:1},...l})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`regressions.${n}.y_axis_data_key`,control:e,render:({field:l})=>i(W,{label:"Value Field",required:!0,sx:{flex:1},...l})}),i(v.Controller,{name:`regressions.${n}.plot.yAxisIndex`,control:e,render:({field:{value:l,onChange:u,...c}})=>i(s.Select,{label:"Y Axis",data:a,disabled:a.length===0,...c,value:(l==null?void 0:l.toString())??"",onChange:d=>{if(!d){u(0);return}u(Number(d))},sx:{flex:1}})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`regressions.${n}.transform.config.method`,control:e,render:({field:l})=>i(s.Select,{label:"Method",data:Lf,sx:{flex:1},...l})}),o==="polynomial"&&i(v.Controller,{name:`regressions.${n}.transform.config.order`,control:e,render:({field:l})=>i(s.NumberInput,{label:"Order",sx:{flex:1},...l})})]}),i(s.Divider,{mb:-15,variant:"dashed",label:"Line Style",labelPosition:"center"}),p(s.Group,{grow:!0,children:[i(v.Controller,{name:`regressions.${n}.plot.lineStyle.type`,control:e,render:({field:l})=>i(s.Select,{label:"Line Type",data:Of,sx:{flexGrow:1},...l})}),i(v.Controller,{name:`regressions.${n}.plot.lineStyle.width`,control:e,render:({field:l})=>i(s.NumberInput,{label:"Line Width",min:1,max:10,sx:{flexGrow:1},...l})})]}),p(s.Stack,{spacing:4,children:[i(s.Text,{size:"sm",children:"Color"}),i(v.Controller,{name:`regressions.${n}.plot.color`,control:e,render:({field:l})=>i(Ve,{...l})})]}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>r(n),sx:{top:15,right:5},children:"Delete this Regression Line"})]},n)}function Bf({control:e,watch:t}){const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"regressions"}),o=t("regressions"),l=n.map((f,h)=>({...f,...o[h]})),u=t("y_axes"),c=b.useMemo(()=>u.map(({name:f},h)=>({label:f,value:h.toString()})),[u]),d=()=>r({transform:{type:"ecStat:regression",config:{method:"linear",order:1,formulaOn:"end"}},group_by_key:"",name:"",y_axis_data_key:"",plot:{type:"line",yAxisIndex:0,color:"#666666",lineStyle:{type:"solid",width:1}}});return p(s.Tabs,{defaultValue:"0",styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map((f,h)=>i(s.Tabs.Tab,{value:h.toString(),children:h+1},h)),i(s.Tabs.Tab,{onClick:d,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((f,h)=>i(s.Tabs.Panel,{value:h.toString(),children:i(Pf,{regressionItem:f,control:e,index:h,remove:a,yAxisOptions:c},h)},h))]})}const Hr={static:{type:"static",size:10},dynamic:{type:"dynamic",func_content:["function getSize({ rowData, params, variables }, { lodash, interpolate }) {"," // your code goes here"," // return 10","}"].join(`
122
+ `)}},Vf=[{label:"No gap between bars",value:"0%"},{label:"Bars overlapping on each other",value:"-100%"}];function Nf({control:e,index:t,seriesItem:n}){const r=!!n.barWidth.trim();return p(B,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${t}.stack`,control:e,render:({field:a})=>i(s.TextInput,{label:"Stack",placeholder:"Stack bars by this ID",sx:{flexGrow:1},...a})}),i(v.Controller,{name:`series.${t}.barGap`,control:e,render:({field:a})=>i(s.Select,{label:"Bar Gap",data:Vf,sx:{flexGrow:1},...a})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${t}.barMinWidth`,control:e,render:({field:a})=>i(s.TextInput,{label:"Bar Width(Min)",disabled:r,sx:{flexGrow:1},...a})}),i(v.Controller,{name:`series.${t}.barWidth`,control:e,render:({field:a})=>i(s.TextInput,{label:"Bar Width",sx:{flexGrow:1},...a})}),i(v.Controller,{name:`series.${t}.barMaxWidth`,control:e,render:({field:a})=>i(s.TextInput,{label:"Bar Width(Max)",disabled:r,sx:{flexGrow:1},...a})})]})]})}const qf=({value:e,onChange:t})=>{const n=r=>{r&&t(r)};return i(s.Box,{children:i(Ae,{height:"500px",defaultLanguage:"javascript",value:e,onChange:n,theme:"vs-dark",options:{minimap:{enabled:!1}}})})},Ff=({value:e,onChange:t})=>{const[n,{setTrue:r,setFalse:a}]=K.useBoolean(),[o,l]=b.useState(e),u=()=>{a();const{type:h,func_content:g}=o,m={type:h,func_content:g};l(m),t(m)},c=()=>{a(),l(e)},d=h=>{l(g=>({...g,func_content:h}))},f=()=>{d(Hr.dynamic.func_content)};return p(B,{children:[i(s.Box,{sx:{width:"50%"},children:i(s.Button,{variant:"filled",mt:24,onClick:r,sx:{flexGrow:0},children:"Setup"})}),i(s.Modal,{size:800,title:"Setup dynamic size",opened:n,onClose:a,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:n&&p(s.Stack,{children:[i(s.Divider,{mt:10,mb:-10,label:"Dynamic by a custom function",labelPosition:"center",variant:"dashed"}),i(qf,{value:o.func_content,onChange:d}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:f,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:c,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:u,children:"OK"})]})]})]})})]})},Gf=({value:e,onChange:t})=>e.type!=="dynamic"?null:i(Ff,{value:e,onChange:t}),Wf=({value:e,onChange:t})=>{if(e.type!=="static")return null;const n=r=>{t({...e,size:r})};return i(B,{children:i(s.NumberInput,{defaultValue:18,placeholder:"1 ~ 100",label:" ",hideControls:!0,value:e.size,onChange:n})})},jf=[{label:"Static",value:"static"},{label:"Dynamic",value:"dynamic"}],Zs=b.forwardRef(({label:e="Size",value:t,onChange:n},r)=>{const a=o=>{n({...Hr[o]})};return p(s.SimpleGrid,{cols:2,children:[i(s.Select,{ref:r,label:e,data:jf,value:t.type,onChange:a,sx:{flexGrow:1}}),i(Wf,{value:t,onChange:n}),i(Gf,{value:t,onChange:n})]})}),Rf=[{label:"off",value:"false"},{label:"start",value:"start"},{label:"middle",value:"middle"},{label:"end",value:"end"}],Yf=[{label:"solid",value:"solid"},{label:"dashed",value:"dashed"},{label:"dotted",value:"dotted"}];function Qf({control:e,index:t,seriesItem:n}){const r=n.showSymbol;return p(B,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Line Settings",labelPosition:"center"}),p(s.Group,{grow:!0,children:[i(v.Controller,{name:`series.${t}.lineStyle.type`,control:e,render:({field:a})=>i(s.Select,{label:"Line Type",data:Yf,sx:{flexGrow:1},...a})}),i(v.Controller,{name:`series.${t}.lineStyle.width`,control:e,render:({field:a})=>i(s.NumberInput,{label:"Line Width",min:1,max:10,sx:{flexGrow:1},...a})})]}),p(s.Group,{grow:!0,align:"center",children:[i(v.Controller,{name:`series.${t}.step`,control:e,render:({field:a})=>i(s.Select,{label:"Step",data:Rf,sx:{flexGrow:1,maxWidth:"48%"},...a,value:String(a.value),onChange:o=>{const l=o==="false"?!1:o;a.onChange(l)}})}),p(s.Stack,{children:[i(v.Controller,{name:`series.${t}.smooth`,control:e,render:({field:a})=>i(s.Box,{sx:{flexGrow:1},children:i(s.Switch,{label:"Smooth Line",checked:a.value,onChange:o=>a.onChange(o.currentTarget.checked)})})}),i(v.Controller,{name:`series.${t}.display_name_on_line`,control:e,render:({field:a})=>i(s.Box,{sx:{flexGrow:1},children:i(s.Switch,{label:"Display Name on Line",checked:a.value??!1,onChange:o=>a.onChange(o.currentTarget.checked)})})})]})]}),p(s.Stack,{children:[i(v.Controller,{name:`series.${t}.showSymbol`,control:e,render:({field:a})=>i(s.Box,{mt:10,mb:-10,sx:{flexGrow:1},children:i(s.Switch,{label:"Show Symbol on Line",checked:a.value,onChange:o=>a.onChange(o.currentTarget.checked)})})}),r&&i(v.Controller,{name:`series.${t}.symbolSize`,control:e,render:({field:a})=>i(Zs,{label:"Symbol Size",...a})})]})]})}function Uf({control:e,index:t}){return i(v.Controller,{name:`series.${t}.symbolSize`,control:e,render:({field:n})=>i(Zs,{label:"Size",...n})})}const Kf=[{label:"off",value:""},{label:"top",value:"top"},{label:"left",value:"left"},{label:"right",value:"right"},{label:"bottom",value:"bottom"},{label:"inside",value:"inside"},{label:"insideLeft",value:"insideLeft"},{label:"insideRight",value:"insideRight"},{label:"insideTop",value:"insideTop"},{label:"insideBottom",value:"insideBottom"},{label:"insideTopLeft",value:"insideTopLeft"},{label:"insideBottomLeft",value:"insideBottomLeft"},{label:"insideTopRight",value:"insideTopRight"},{label:"insideBottomRight",value:"insideBottomRight"}];function Xf({control:e,index:t,remove:n,seriesItem:r,yAxisOptions:a}){const o=r.type;return p(s.Stack,{my:0,p:0,sx:{position:"relative"},children:[i(s.Stack,{children:i(v.Controller,{name:`series.${t}.type`,control:e,render:({field:l})=>i(s.SegmentedControl,{data:[{label:"Line",value:"line"},{label:"Bar",value:"bar"},{label:"Scatter",value:"scatter"}],...l})})}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${t}.name`,control:e,render:({field:l})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...l})}),i(v.Controller,{name:`series.${t}.yAxisIndex`,control:e,render:({field:{value:l,onChange:u,...c}})=>i(s.Select,{label:"Y Axis",data:a,disabled:a.length===0,...c,value:(l==null?void 0:l.toString())??"",onChange:d=>{if(!d){u(0);return}u(Number(d))},sx:{flex:1}})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${t}.y_axis_data_key`,control:e,render:({field:l})=>i(W,{label:"Value Field",required:!0,sx:{flex:1},...l})}),i(v.Controller,{name:`series.${t}.aggregation_on_value`,control:e,render:({field:l})=>i(Gn,{label:"Aggregation on Value",value:l.value??Nt,onChange:l.onChange,pt:0})})]}),i(s.Group,{grow:!0,children:i(v.Controller,{name:`series.${t}.group_by_key`,control:e,render:({field:l})=>i(W,{label:"Split into multiple series by this key...",clearable:!0,sx:{flex:1},...l})})}),o==="line"&&i(Qf,{index:t,control:e,seriesItem:r}),o==="bar"&&i(Nf,{index:t,control:e,seriesItem:r}),o==="scatter"&&i(Uf,{index:t,control:e}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Style",labelPosition:"center"}),i(v.Controller,{name:`series.${t}.label_position`,control:e,render:({field:l})=>i(s.Select,{label:"Label Position",data:Kf,...l})}),p(s.Stack,{spacing:4,children:[i(s.Text,{size:"sm",children:"Color"}),i(v.Controller,{name:`series.${t}.color`,control:e,render:({field:l})=>i(Ve,{...l})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Behavior",labelPosition:"center"}),i(v.Controller,{name:`series.${t}.hide_in_legend`,control:e,render:({field:l})=>i(s.Checkbox,{label:"Hide in legend",checked:l.value,onChange:u=>l.onChange(u.currentTarget.checked)})}),i(s.Divider,{mb:-10,mt:10,variant:"dashed"}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Series"})]},t)}function Jf({control:e,watch:t}){const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"series"}),o=t("series"),l=n.map((f,h)=>({...f,...o[h]})),u=()=>{const f={type:"bar",name:Ie.randomId(),showSymbol:!1,symbolSize:Hr.static,y_axis_data_key:"value",yAxisIndex:0,label_position:"top",display_name_on_line:!1,stack:"",color:"#000",step:!1,smooth:!1,barMinWidth:"1",barWidth:"10%",barMaxWidth:"10",barGap:"0%",lineStyle:{type:"solid",width:1},hide_in_legend:!1,group_by_key:""};r(f)},c=t("y_axes"),d=b.useMemo(()=>c.map(({name:f},h)=>({label:f,value:h.toString()})),[c]);return p(s.Tabs,{defaultValue:"0",styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map((f,h)=>i(s.Tabs.Tab,{value:h.toString(),children:h+1},f.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((f,h)=>i(s.Tabs.Panel,{value:h.toString(),children:i(Xf,{control:e,index:h,remove:a,seriesItem:f,yAxisOptions:d},f.id)},f.id))]})}function Zf({control:e,watch:t}){return t("stats"),i(s.Stack,{children:p(s.Stack,{spacing:0,children:[i(v.Controller,{name:"stats.templates.top",control:e,render:({field:n})=>i(tn,{label:"Template for stats above the chart",py:"md",sx:{flexGrow:1},...n})}),i(v.Controller,{name:"stats.templates.bottom",control:e,render:({field:n})=>i(tn,{label:"Template for stats under the chart",py:"md",sx:{flexGrow:1},...n})})]})})}const Hf=()=>p(s.Group,{sx:{display:"inline-flex"},spacing:6,mr:14,children:[i(s.Text,{children:"X Axis Data Type"}),p(s.HoverCard,{width:340,shadow:"md",position:"top",children:[i(s.HoverCard.Target,{children:i(s.ActionIcon,{size:"xs",sx:{transform:"none !important"},children:i($.IconInfoCircle,{})})}),i(s.HoverCard.Dropdown,{children:p(s.Text,{size:"sm",children:["Click",i(s.Anchor,{href:"https://echarts.apache.org/en/option.html#xAxis.type",target:"_blank",mx:4,children:"here"}),"to learn more about these options"]})})]})]}),eg=[{label:"Value",value:"value"},{label:"Category",value:"category"},{label:"Time",value:"time"},{label:"Log",value:"log"}];function tg({control:e,watch:t}){return t(["x_axis_data_key","x_axis_name","x_axis"]),p(s.Stack,{children:[i(v.Controller,{name:"x_axis_name",control:e,render:({field:n})=>i(s.TextInput,{label:"X Axis Name",sx:{flex:1},...n})}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis_data_key",control:e,render:({field:n})=>i(W,{label:"X Axis Data Field",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"x_axis.type",control:e,render:({field:n})=>i(s.Select,{label:i(Hf,{}),required:!0,data:eg,sx:{flex:1},...n})})]}),i(s.Divider,{mb:-15,label:"Tick Label",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.axisLabel.rotate",control:e,render:({field:n})=>i(s.NumberInput,{label:"Rotate",hideControls:!0,min:-90,max:90,rightSection:i(s.Text,{color:"dimmed",children:"degree"}),sx:{width:"48%"},styles:{rightSection:{width:"4em",justifyContent:"flex-end",paddingRight:"6px"}},...n})}),i(v.Controller,{name:"x_axis.axisLabel.formatter",control:e,render:({field:n})=>i(Rn,{...n})})]}),i(v.Controller,{name:"x_axis.axisLabel.overflow",control:e,render:({field:n})=>i(at,{...n})})]})}const ng=[{label:"left",value:"left"},{label:"center",value:"center"},{label:"right",value:"right"}],rg=[{label:"left",value:"left"},{label:"right",value:"right"}];function ig({control:e,index:t,remove:n}){return p(s.Stack,{my:0,p:"0",sx:{position:"relative"},children:[i(s.Divider,{mb:-15,mt:15,variant:"dashed",label:"Name",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`y_axes.${t}.name`,control:e,render:({field:r})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:`y_axes.${t}.nameAlignment`,control:e,render:({field:r})=>i(s.Select,{label:"Name Anchor",required:!0,data:ng,sx:{flex:1},...r})})]}),i(s.Divider,{mb:-15,variant:"dashed",label:"Layout",labelPosition:"center"}),i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:`y_axes.${t}.position`,control:e,render:({field:r})=>i(s.Select,{label:"Position",required:!0,data:rg,sx:{flex:1},...r})})}),p(s.Stack,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Label Format",labelPosition:"center"}),i(v.Controller,{name:`y_axes.${t}.label_formatter`,control:e,render:({field:r})=>i(je,{...r})})]}),p(s.Stack,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Value Range",labelPosition:"center"}),p(s.Group,{grow:!0,children:[i(v.Controller,{name:`y_axes.${t}.min`,control:e,render:({field:r})=>i(s.TextInput,{label:"Min",...r})}),i(v.Controller,{name:`y_axes.${t}.max`,control:e,render:({field:r})=>i(s.TextInput,{label:"Max",...r})})]})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Behavior",labelPosition:"center"}),i(v.Controller,{name:`y_axes.${t}.show`,control:e,render:({field:r})=>i(s.Checkbox,{label:"Visible",checked:r.value,onChange:a=>r.onChange(a.currentTarget.checked)})}),i(s.Button,{mt:20,leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),disabled:t===0,children:"Delete this YAxis"})]})}function ag({control:e,watch:t}){const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"y_axes"}),o=t("y_axes"),l=n.map((c,d)=>({...c,...o[d]})),u=()=>r({name:"",position:"left",nameAlignment:"left",label_formatter:ze,min:"",max:"",show:!0});return p(s.Tabs,{defaultValue:"0",styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px"}},children:[p(s.Tabs.List,{children:[l.map((c,d)=>i(s.Tabs.Tab,{value:d.toString(),children:d+1},d)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((c,d)=>i(s.Tabs.Panel,{value:d.toString(),children:i(ig,{control:e,index:d,remove:a})},d))]})}function sg({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),{variables:r}=e,a=b.useMemo(()=>x.defaultsDeep({},t,Kr),[t]),{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});b.useEffect(()=>{d(a)},[a]);const f=c(),h=b.useMemo(()=>!x.isEqual(f,a),[f,a]);return u(["dataZoom"]),i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:l(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"Series",orientation:"vertical",styles:{tab:{paddingLeft:"6px",paddingRight:"6px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"X Axis",children:"X Axis"}),i(s.Tabs.Tab,{value:"Y Axes",children:"Y Axes"}),i(s.Tabs.Tab,{value:"Series",children:"Series"}),i(s.Tabs.Tab,{value:"Regression Lines",children:"Regression Lines"}),i(s.Tabs.Tab,{value:"Stats",children:"Stats"}),i(s.Tabs.Tab,{value:"Reference Lines",children:"Reference Lines"}),i(s.Tabs.Tab,{value:"Reference Areas",children:"Reference Areas"}),i(s.Tabs.Tab,{value:"Zooming",children:"Zooming"})]}),i(s.Tabs.Panel,{value:"X Axis",children:i(tg,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Y Axes",children:i(ag,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Series",children:i(Jf,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Regression Lines",children:i(Bf,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Stats",children:i(Zf,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Reference Lines",children:i($f,{variables:r,control:o,watch:u})}),i(s.Tabs.Panel,{value:"Reference Areas",children:i(Mf,{variables:r,control:o,watch:u})}),i(s.Tabs.Panel,{value:"Zooming",children:i(v.Controller,{name:"dataZoom",control:o,render:({field:g})=>i(Zr,{...g})})})]})]})})}function og(e){const t=x.cloneDeep(x.omit(e,"variables"));return t.stats=x.omit(t.stats,"variables"),t}function lg(e){const{rotate:t,formatter:n=Ue}=e.x_axis.axisLabel;return{...e,x_axis:{...e.x_axis,axisLabel:{rotate:t,formatter:n}}}}function ug(e){const{dataZoom:t=qt,...n}=e;return{...n,dataZoom:t}}function cg(e){const t={x_axis:{axisLabel:{overflow:{x_axis:{width:80,overflow:"truncate",ellipsis:"..."},tooltip:{width:200,overflow:"break",ellipsis:"..."}}}}};return x.defaultsDeep(t,e)}function dg(e){const t=e.reference_lines.map(n=>{const{lineStyle:r={type:"dashed",width:1,color:ct.random().css()},show_in_legend:a=!1}=n;return{...n,lineStyle:r,show_in_legend:a}});return{...e,reference_lines:t}}function pg(e){const t=e.reference_lines.map(n=>{const{yAxisIndex:r=0}=n;return{...n,yAxisIndex:r}});return{...e,reference_lines:t}}function hg(e){const t=e.series.map(n=>{const{aggregation_on_group:r=Nt}=n;return{...n,aggregation_on_group:r}});return{...e,series:t}}function fg(e){const t=e.series.map(n=>{const{aggregation_on_value:r=Nt}=n;return{...n,aggregation_on_value:r}});return{...e,series:t}}function gg(e){delete e.config;const{x_axis:t,tooltip:n}=e.x_axis.axisLabel.overflow,r={x_axis:{axisLabel:{overflow:{on_axis:t,in_tooltip:n}}}};return x.defaultsDeep(r,e)}function mg(e){const{series:t,...n}=e;return{...n,series:t.map(r=>{const{barMinWidth:a,barWidth:o,barMaxWidth:l}=r;return a?{...r,barMinWidth:a,barWidth:"",barMaxWidth:l??o}:{...r,barMinWidth:"",barWidth:o,barMaxWidth:""}})}}function yg(e){const{y_axes:t,...n}=e;return{...n,y_axes:t.map(r=>{const{min:a="",max:o=""}=r;return{...r,min:a,max:o}})}}function bg(e){const{y_axes:t,...n}=e;return{...n,y_axes:t.map(r=>{const{nameAlignment:a="left"}=r;return{...r,nameAlignment:a}})}}function vg(e){const{y_axes:t,...n}=e;return{...n,y_axes:t.map(r=>{const{show:a=!0}=r;return{...r,show:a}})}}function xg(e){const{regressions:t,...n}=e;return{...n,regressions:t.map(r=>{const{group_by_key:a=""}=r;return{...r,group_by_key:a}})}}function wg(e){const{series:t,y_axes:n,...r}=e;return{...r,series:t.map(a=>{const{hide_in_legend:o=!1,aggregation_on_value:l=Nt}=a;return{...a,hide_in_legend:o,aggregation_on_value:l}}),y_axes:n.map(a=>{const{min:o="",max:l="",show:u=!0}=a;return{...a,min:o,max:l,show:u}})}}function Cg(e){const{type:t="category",...n}=e.x_axis;return{...e,x_axis:{...n,type:t}}}function Sg(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=c=>c&&`${n}.${c}`,{x_axis_data_key:a,series:o,regressions:l,...u}=e;return{...u,x_axis_data_key:r(a),series:o.map(c=>({...c,y_axis_data_key:r(c.y_axis_data_key),group_by_key:r(c.group_by_key)})),regressions:l.map(c=>({...c,y_axis_data_key:r(c.y_axis_data_key),group_by_key:r(c.group_by_key)}))}}catch(n){throw console.error("[Migration failed]",n),n}}class _g extends ye{constructor(){super(...arguments);N(this,"VERSION",18)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,(n,{panelModel:r})=>{const{config:a}=n;return(a.variables||[]).forEach(u=>{r.variables.find(c=>c.name===u.name)||r.addVariable(u)}),(x.get(a,"stats.variables")||[]).forEach(u=>{r.variables.find(c=>c.name===u.name)||r.addVariable(u)}),{...n,version:2,config:og(a)}}),this.version(3,n=>({...n,version:3,config:lg(n.config)})),this.version(4,n=>({...n,version:4,config:ug(n.config)})),this.version(5,n=>({...n,version:5,config:cg(n.config)})),this.version(6,n=>({...n,version:6,config:dg(n.config)})),this.version(7,n=>({...n,version:7,config:pg(n.config)})),this.version(8,n=>({...n,version:8,config:hg(n.config)})),this.version(9,n=>({...n,version:9,config:fg(n.config)})),this.version(10,n=>({...n,version:10,config:gg(n.config)})),this.version(11,n=>({...n,version:11,config:mg(n.config)})),this.version(12,n=>({...n,version:12,config:yg(n.config)})),this.version(13,n=>({...n,version:13,config:bg(n.config)})),this.version(14,n=>({...n,version:14,config:vg(n.config)})),this.version(15,n=>({...n,version:15,config:xg(n.config)})),this.version(16,n=>({...n,version:16,config:wg(n.config)})),this.version(17,n=>({...n,version:17,config:Cg(n.config)})),this.version(18,(n,r)=>({...n,version:18,config:Sg(n.config,r)}))}}const kg={displayName:"Cartesian Chart",displayGroup:"ECharts-based charts",migrator:new _g,name:"cartesian",viewRender:kf,configRender:sg,createConfig(){return{version:18,config:x.cloneDeep(Kr)}},triggers:[Ur]};function Tg(e){if(e.enable_value)return e.value}function Dg(e){if(e.enable_value)return e.value}function Ig(e){const t=e.axisLabel.overflow.on_axis.width,n=e.axisLabel.position,r={top:5,left:5,right:5,bottom:5};return e.orient==="vertical"&&x.get(r,n)&&n===e.funnelAlign&&x.set(r,n,t),r}function Mg(e,t){return e.series.map(n=>{const{level_name_data_key:r,level_value_data_key:a,axisLabel:o,min:l,max:u,funnelAlign:c,orient:d,...f}=n;if(!r||!a)return{};const h=O(r),g=O(a),m=t[h.queryID].map(w=>({name:w[h.columnKey],value:w[g.columnKey]})),C=rt(o.overflow.on_axis);return{type:"funnel",...Ig(n),min:Tg(l),max:Dg(u),minSize:l.size,maxSize:u.size,...f,label:{show:!0,position:o.position,...C},orient:d,funnelAlign:d==="horizontal"?"center":c,data:m}})}function Ag({conf:e,params:t,max:n}){const{name:r,value:a}=t.data,o=Z(a/n).format({output:"percent",mantissa:2,trimMantissa:!0});return[{label:`${t.marker} ${r}`,value:`${a} (${o})`,style:{label:"",value:""}}]}function zg(e,t){var o;const n=O(e.series[0].level_name_data_key),r=O(e.series[0].level_value_data_key),a=(o=x.maxBy(t[n.queryID],r.columnKey))==null?void 0:o[r.columnKey];return l=>{const c=Ag({conf:e,params:l,max:a}).map(f=>`
123
123
  <tr>
124
124
  <th style="text-align: right;">
125
125
  <div style="${f.style.label}">${f.label}</div>
@@ -135,7 +135,7 @@ Check the top-level render call using <`+V+">.")}return E}}function Su(S,E){{if(
135
135
  <table style="width: auto">
136
136
  <tbody>${c.join("")}</tbody>
137
137
  </table>
138
- `}}function Eg(e,t){return{trigger:"item",confine:!0,formatter:zg(e,t)}}function $g(e,t){return{grid:{top:0,left:0,right:0,bottom:0},tooltip:Eg(e,t),series:Mg(e,t)}}function Lg(e){return e||(e=Date.now().toString()),{id:e,name:e,level_name_data_key:"",level_value_data_key:"",min:{value:0,enable_value:!1,size:"0%"},max:{value:0,enable_value:!1,size:"100%"},gap:2,axisLabel:{show:!0,position:"inside",overflow:je},sort:"descending",orient:"vertical",funnelAlign:"center"}}const ei={series:[Lg("Funnel")]};ie.use([he.FunnelChart,q.DataZoomComponent,q.GridComponent,q.LegendComponent,q.TooltipComponent,Pe.CanvasRenderer]);function Og({conf:e,data:t,width:n,height:r}){const a=y.useMemo(()=>$g(e,t),[e,t]);return!n||!r?null:i(Be,{echarts:ie,option:a,style:{width:n,height:r},notMerge:!0,theme:"merico-light"})}function Pg({context:e}){const{value:t}=R(e.instanceData,"config"),n=y.useMemo(()=>x.defaults({},t,ei),[t]),r=e.data,{width:a,height:o}=e.viewport;return i(Og,{width:a,height:o,data:r,conf:n})}const Bg=[{label:"Top",value:"top"},{label:"Left",value:"left"},{label:"Right",value:"right"},{label:"Bottom",value:"bottom"},{label:"Outside",value:"outside"},{label:"Inside",value:"inside"},{label:"InsideLeft",value:"insideLeft"},{label:"InsideRight",value:"insideRight"},{label:"InsideTop",value:"insideTop"},{label:"InsideBottom",value:"insideBottom"},{label:"InsideTopLeft",value:"insideTopLeft"},{label:"InsideBottomLeft",value:"insideBottomLeft"},{label:"InsideTopRight",value:"insideTopRight"},{label:"InsideBottomRight",value:"insideBottomRight"}],ti=y.forwardRef(({label:e,value:t,onChange:n,options:r=Bg},a)=>i(s.Select,{ref:a,label:e,data:r,value:t,onChange:n})),Vg=[{label:"Ascending",value:"ascending"},{label:"Descending",value:"descending"},{label:"Use original data order",value:"0"}],Ng=[{label:"Left",value:"left"},{label:"Center",value:"center"},{label:"Right",value:"right"}],qg=[{label:"Horizontal",value:"horizontal"},{label:"Vertical",value:"vertical"}],Fg={horizontal:[{label:"Top",value:"top"},{label:"Inside Center",value:"inside"},{label:"Bottom",value:"bottom"}],vertical:[{label:"Left",value:"left"},{label:"Inside Left",value:"insideLeft"},{label:"Inside Center",value:"inside"},{label:"Inside Right",value:"insideRight"},{label:"Right",value:"right"}]},Gg=({item:e,control:t,index:n,remove:r})=>{const a=e.min.enable_value,o=e.max.enable_value,{orient:l}=e;return p(s.Stack,{children:[i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:`series.${n}.name`,control:t,render:({field:u})=>i(s.TextInput,{label:"Series Name",...u})})}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${n}.level_name_data_key`,control:t,render:({field:u})=>i(W,{label:"Level Name Field",...u})}),i(v.Controller,{name:`series.${n}.level_value_data_key`,control:t,render:({field:u})=>i(W,{label:"Level Value Field",...u})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Funnel Style",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${n}.min.value`,control:t,render:({field:u})=>i(s.NumberInput,{disabled:!a,labelProps:{display:"block"},label:p(s.Group,{position:"apart",pr:6,sx:{width:"100%"},children:[i(s.Text,{children:"Min Value"}),i(s.Tooltip,{label:"Check to enable specific min value",children:i(s.Box,{children:i(v.Controller,{name:`series.${n}.min.enable_value`,control:t,render:({field:c})=>i(s.Checkbox,{size:"xs",checked:c.value,onChange:d=>c.onChange(d.currentTarget.checked)})})})})]}),...u})}),i(v.Controller,{name:`series.${n}.min.size`,control:t,render:({field:u})=>i(s.TextInput,{placeholder:"0%",label:"Min Size",...u})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${n}.max.value`,control:t,render:({field:u})=>i(s.NumberInput,{disabled:!o,labelProps:{display:"block"},label:p(s.Group,{position:"apart",pr:6,sx:{width:"100%"},children:[i(s.Text,{children:"Max Value"}),i(s.Tooltip,{label:"Check to enable specific max value",children:i(s.Box,{children:i(v.Controller,{name:`series.${n}.max.enable_value`,control:t,render:({field:c})=>i(s.Checkbox,{size:"xs",checked:c.value,onChange:d=>c.onChange(d.currentTarget.checked)})})})})]}),...u})}),i(v.Controller,{name:`series.${n}.max.size`,control:t,render:({field:u})=>i(s.TextInput,{placeholder:"100%",label:"Max Size",...u})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${n}.orient`,control:t,render:({field:u})=>i(s.Select,{label:"Orientation",data:qg,...u})}),i(v.Controller,{name:`series.${n}.sort`,control:t,render:({field:u})=>i(s.Select,{label:"Sort",data:Vg,...u})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${n}.funnelAlign`,control:t,render:({field:u})=>i(s.Select,{label:"Align",disabled:l==="horizontal",data:Ng,...u})}),i(v.Controller,{name:`series.${n}.gap`,control:t,render:({field:u})=>i(s.NumberInput,{placeholder:"0, 5, 10...",label:"Gap",...u})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Label Style",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${n}.axisLabel.position`,control:t,render:({field:u})=>i(ti,{label:"Position",options:Fg[l],...u})}),i(s.Box,{})]}),i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:`series.${n}.axisLabel.overflow`,control:t,render:({field:u})=>i(at,{...u})})})]})},Wg=({control:e,watch:t})=>{const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"series"}),o=t("series"),l=n.map((f,h)=>({...f,...o[h]})),u=x.get(l,"0.id"),[c,d]=y.useState(u??null);return y.useEffect(()=>{u&&d(f=>f!==null?f:u)},[u]),p(s.Tabs,{value:c,onTabChange:f=>d(f),styles:{panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map((f,h)=>i(s.Tabs.Tab,{value:f.id,children:f.name},f.id)),i(s.Tabs.Tab,{value:"add",disabled:!0,children:i(s.Tooltip,{label:"TODO",children:i(s.Center,{children:i($.IconPlus,{size:18,color:"#228be6"})})})})]}),l.map((f,h)=>i(s.Tabs.Panel,{value:f.id,children:i(Gg,{item:f,control:e,index:h,remove:a})},f.id))]})};function jg({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=y.useMemo(()=>x.defaultsDeep({},t,ei),[t]),{control:a,handleSubmit:o,watch:l,getValues:u,reset:c}=v.useForm({defaultValues:r});y.useEffect(()=>{c(r)},[r]),l([]);const d=u(),f=y.useMemo(()=>!x.isEqual(d,r),[d,r]);return i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:o(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Funnel Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!f,children:i(T.DeviceFloppy,{size:20})})]}),i(Wg,{control:a,watch:l})]})})}function Rg(e){return{series:e.series.map(t=>{const{min:n,minSize:r,max:a,maxSize:o,...l}=t;return{...l,min:{value:n,use_data_min:!1,size:r},max:{value:a,use_data_max:!1,size:o}}})}}function Yg(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=l=>l&&`${n}.${l}`,{series:a,...o}=e;return{...o,series:a.map(l=>({...l,level_name_data_key:r(l.level_name_data_key),level_value_data_key:r(l.level_value_data_key)}))}}catch(n){throw console.error("[Migration failed]",n),n}}class Qg extends ye{constructor(){super(...arguments);N(this,"VERSION",3)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,n=>{const{config:r}=n;return{...n,version:2,config:Rg(r)}}),this.version(3,(n,r)=>{const{config:a}=n;return{...n,version:3,config:Yg(a,r)}})}}const Ug={displayName:"Funnel Chart",displayGroup:"ECharts-based charts",migrator:new Qg,name:"funnel",viewRender:Pg,configRender:jg,createConfig:()=>({version:3,config:ei})};function Hs({enabled:e,func_content:t}){return(n,r)=>{if(!e)return n;try{return new Function(`return ${t}`)()(n,r)}catch(a){return console.error(`[getEchartsXAxisLabel] failed parsing custom function, error: ${a.message}`),n}}}function Kg(e){const t=Hs(e.x_axis.axisLabel.formatter),n=Hs(e.y_axis.axisLabel.formatter);return{x_axis:t,y_axis:n}}function Xg(e){return{heat_block:function(r){if(!e.heat_block.value_formatter)return r;try{return Z(r).format(e.heat_block.value_formatter)}catch(a){return console.error(a),r}}}}function Jg(e){let t=0;return e.x_axis.name&&(t+=20),{top:45,left:5,right:5,bottom:t,containLabel:!0}}function Zg(e,t,n){const{heat_block:r}=e;return{type:"heatmap",name:r.name,xAxisId:"main-x-axis",yAxisIndex:0,datasetIndex:0,itemStyle:{borderColor:"white",borderWidth:n},data:t,label:r.label,labelLayout:{hideOverlap:!0}}}const Hg=e=>{try{return Z(e).format({trimMantissa:!0,mantissa:2})}catch{return e}};function em({conf:e,labelFormatters:t,valueFormatters:n,dataDict:r,params:a}){const{value:o,dataIndex:l}=a,[u,c,d]=o,f={label:e.x_axis.name?e.x_axis.name:"X Axis",value:t.x_axis(u,l),style:{label:"",value:st(e.x_axis.axisLabel.overflow.in_tooltip)}},h={label:e.y_axis.name?e.y_axis.name:"Y Axis",value:t.y_axis(c,l),style:{label:"",value:st(e.y_axis.axisLabel.overflow.in_tooltip)}},g={label:e.heat_block.name,value:n.heat_block(d),style:{label:"",value:""}},m=[f,h,g],C=r[`${u}---${c}`];return C&&e.tooltip.metrics.forEach(w=>{const _=O(w.data_key);m.push({label:w.name,value:Hg(x.get(C,_.columnKey,"")),style:{label:"",value:""}})}),m}function tm(e,t,n,r){const{x_axis:a,y_axis:o,heat_block:l}=e,u=O(a.data_key),c=O(o.data_key);O(l.data_key);const d=x.keyBy(t[u.queryID],f=>`${f[u.columnKey]}---${f[c.columnKey]}`);return{confine:!0,formatter:function(f){const g=em({conf:e,labelFormatters:n,valueFormatters:r,dataDict:d,params:f}).map(C=>`
138
+ `}}function Eg(e,t){return{trigger:"item",confine:!0,formatter:zg(e,t)}}function $g(e,t){return{grid:{top:0,left:0,right:0,bottom:0},tooltip:Eg(e,t),series:Mg(e,t)}}function Lg(e){return e||(e=Date.now().toString()),{id:e,name:e,level_name_data_key:"",level_value_data_key:"",min:{value:0,enable_value:!1,size:"0%"},max:{value:0,enable_value:!1,size:"100%"},gap:2,axisLabel:{show:!0,position:"inside",overflow:Re},sort:"descending",orient:"vertical",funnelAlign:"center"}}const ei={series:[Lg("Funnel")]};ie.use([he.FunnelChart,q.DataZoomComponent,q.GridComponent,q.LegendComponent,q.TooltipComponent,Pe.CanvasRenderer]);function Og({conf:e,data:t,width:n,height:r}){const a=b.useMemo(()=>$g(e,t),[e,t]);return!n||!r?null:i(Be,{echarts:ie,option:a,style:{width:n,height:r},notMerge:!0,theme:"merico-light"})}function Pg({context:e}){const{value:t}=R(e.instanceData,"config"),n=b.useMemo(()=>x.defaults({},t,ei),[t]),r=e.data,{width:a,height:o}=e.viewport;return i(Og,{width:a,height:o,data:r,conf:n})}const Bg=[{label:"Top",value:"top"},{label:"Left",value:"left"},{label:"Right",value:"right"},{label:"Bottom",value:"bottom"},{label:"Outside",value:"outside"},{label:"Inside",value:"inside"},{label:"InsideLeft",value:"insideLeft"},{label:"InsideRight",value:"insideRight"},{label:"InsideTop",value:"insideTop"},{label:"InsideBottom",value:"insideBottom"},{label:"InsideTopLeft",value:"insideTopLeft"},{label:"InsideBottomLeft",value:"insideBottomLeft"},{label:"InsideTopRight",value:"insideTopRight"},{label:"InsideBottomRight",value:"insideBottomRight"}],ti=b.forwardRef(({label:e,value:t,onChange:n,options:r=Bg},a)=>i(s.Select,{ref:a,label:e,data:r,value:t,onChange:n})),Vg=[{label:"Ascending",value:"ascending"},{label:"Descending",value:"descending"},{label:"Use original data order",value:"0"}],Ng=[{label:"Left",value:"left"},{label:"Center",value:"center"},{label:"Right",value:"right"}],qg=[{label:"Horizontal",value:"horizontal"},{label:"Vertical",value:"vertical"}],Fg={horizontal:[{label:"Top",value:"top"},{label:"Inside Center",value:"inside"},{label:"Bottom",value:"bottom"}],vertical:[{label:"Left",value:"left"},{label:"Inside Left",value:"insideLeft"},{label:"Inside Center",value:"inside"},{label:"Inside Right",value:"insideRight"},{label:"Right",value:"right"}]},Gg=({item:e,control:t,index:n,remove:r})=>{const a=e.min.enable_value,o=e.max.enable_value,{orient:l}=e;return p(s.Stack,{children:[i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:`series.${n}.name`,control:t,render:({field:u})=>i(s.TextInput,{label:"Series Name",...u})})}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${n}.level_name_data_key`,control:t,render:({field:u})=>i(W,{label:"Level Name Field",...u})}),i(v.Controller,{name:`series.${n}.level_value_data_key`,control:t,render:({field:u})=>i(W,{label:"Level Value Field",...u})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Funnel Style",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${n}.min.value`,control:t,render:({field:u})=>i(s.NumberInput,{disabled:!a,labelProps:{display:"block"},label:p(s.Group,{position:"apart",pr:6,sx:{width:"100%"},children:[i(s.Text,{children:"Min Value"}),i(s.Tooltip,{label:"Check to enable specific min value",children:i(s.Box,{children:i(v.Controller,{name:`series.${n}.min.enable_value`,control:t,render:({field:c})=>i(s.Checkbox,{size:"xs",checked:c.value,onChange:d=>c.onChange(d.currentTarget.checked)})})})})]}),...u})}),i(v.Controller,{name:`series.${n}.min.size`,control:t,render:({field:u})=>i(s.TextInput,{placeholder:"0%",label:"Min Size",...u})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${n}.max.value`,control:t,render:({field:u})=>i(s.NumberInput,{disabled:!o,labelProps:{display:"block"},label:p(s.Group,{position:"apart",pr:6,sx:{width:"100%"},children:[i(s.Text,{children:"Max Value"}),i(s.Tooltip,{label:"Check to enable specific max value",children:i(s.Box,{children:i(v.Controller,{name:`series.${n}.max.enable_value`,control:t,render:({field:c})=>i(s.Checkbox,{size:"xs",checked:c.value,onChange:d=>c.onChange(d.currentTarget.checked)})})})})]}),...u})}),i(v.Controller,{name:`series.${n}.max.size`,control:t,render:({field:u})=>i(s.TextInput,{placeholder:"100%",label:"Max Size",...u})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${n}.orient`,control:t,render:({field:u})=>i(s.Select,{label:"Orientation",data:qg,...u})}),i(v.Controller,{name:`series.${n}.sort`,control:t,render:({field:u})=>i(s.Select,{label:"Sort",data:Vg,...u})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${n}.funnelAlign`,control:t,render:({field:u})=>i(s.Select,{label:"Align",disabled:l==="horizontal",data:Ng,...u})}),i(v.Controller,{name:`series.${n}.gap`,control:t,render:({field:u})=>i(s.NumberInput,{placeholder:"0, 5, 10...",label:"Gap",...u})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Label Style",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${n}.axisLabel.position`,control:t,render:({field:u})=>i(ti,{label:"Position",options:Fg[l],...u})}),i(s.Box,{})]}),i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:`series.${n}.axisLabel.overflow`,control:t,render:({field:u})=>i(at,{...u})})})]})},Wg=({control:e,watch:t})=>{const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"series"}),o=t("series"),l=n.map((f,h)=>({...f,...o[h]})),u=x.get(l,"0.id"),[c,d]=b.useState(u??null);return b.useEffect(()=>{u&&d(f=>f!==null?f:u)},[u]),p(s.Tabs,{value:c,onTabChange:f=>d(f),styles:{panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map((f,h)=>i(s.Tabs.Tab,{value:f.id,children:f.name},f.id)),i(s.Tabs.Tab,{value:"add",disabled:!0,children:i(s.Tooltip,{label:"TODO",children:i(s.Center,{children:i($.IconPlus,{size:18,color:"#228be6"})})})})]}),l.map((f,h)=>i(s.Tabs.Panel,{value:f.id,children:i(Gg,{item:f,control:e,index:h,remove:a})},f.id))]})};function jg({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=b.useMemo(()=>x.defaultsDeep({},t,ei),[t]),{control:a,handleSubmit:o,watch:l,getValues:u,reset:c}=v.useForm({defaultValues:r});b.useEffect(()=>{c(r)},[r]),l([]);const d=u(),f=b.useMemo(()=>!x.isEqual(d,r),[d,r]);return i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:o(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Funnel Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!f,children:i(T.DeviceFloppy,{size:20})})]}),i(Wg,{control:a,watch:l})]})})}function Rg(e){return{series:e.series.map(t=>{const{min:n,minSize:r,max:a,maxSize:o,...l}=t;return{...l,min:{value:n,use_data_min:!1,size:r},max:{value:a,use_data_max:!1,size:o}}})}}function Yg(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=l=>l&&`${n}.${l}`,{series:a,...o}=e;return{...o,series:a.map(l=>({...l,level_name_data_key:r(l.level_name_data_key),level_value_data_key:r(l.level_value_data_key)}))}}catch(n){throw console.error("[Migration failed]",n),n}}class Qg extends ye{constructor(){super(...arguments);N(this,"VERSION",3)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,n=>{const{config:r}=n;return{...n,version:2,config:Rg(r)}}),this.version(3,(n,r)=>{const{config:a}=n;return{...n,version:3,config:Yg(a,r)}})}}const Ug={displayName:"Funnel Chart",displayGroup:"ECharts-based charts",migrator:new Qg,name:"funnel",viewRender:Pg,configRender:jg,createConfig:()=>({version:3,config:ei})};function Hs({enabled:e,func_content:t}){return(n,r)=>{if(!e)return n;try{return new Function(`return ${t}`)()(n,r)}catch(a){return console.error(`[getEchartsXAxisLabel] failed parsing custom function, error: ${a.message}`),n}}}function Kg(e){const t=Hs(e.x_axis.axisLabel.formatter),n=Hs(e.y_axis.axisLabel.formatter);return{x_axis:t,y_axis:n}}function Xg(e){return{heat_block:function(r){if(!e.heat_block.value_formatter)return r;try{return Z(r).format(e.heat_block.value_formatter)}catch(a){return console.error(a),r}}}}function Jg(e){let t=0;return e.x_axis.name&&(t+=20),{top:45,left:5,right:5,bottom:t,containLabel:!0}}function Zg(e,t,n){const{heat_block:r}=e;return{type:"heatmap",name:r.name,xAxisId:"main-x-axis",yAxisIndex:0,datasetIndex:0,itemStyle:{borderColor:"white",borderWidth:n},data:t,label:r.label,labelLayout:{hideOverlap:!0}}}const Hg=e=>{try{return Z(e).format({trimMantissa:!0,mantissa:2})}catch{return e}};function em({conf:e,labelFormatters:t,valueFormatters:n,dataDict:r,params:a}){const{value:o,dataIndex:l}=a,[u,c,d]=o,f={label:e.x_axis.name?e.x_axis.name:"X Axis",value:t.x_axis(u,l),style:{label:"",value:st(e.x_axis.axisLabel.overflow.in_tooltip)}},h={label:e.y_axis.name?e.y_axis.name:"Y Axis",value:t.y_axis(c,l),style:{label:"",value:st(e.y_axis.axisLabel.overflow.in_tooltip)}},g={label:e.heat_block.name,value:n.heat_block(d),style:{label:"",value:""}},m=[f,h,g],C=r[`${u}---${c}`];return C&&e.tooltip.metrics.forEach(w=>{const _=O(w.data_key);m.push({label:w.name,value:Hg(x.get(C,_.columnKey,"")),style:{label:"",value:""}})}),m}function tm(e,t,n,r){const{x_axis:a,y_axis:o,heat_block:l}=e,u=O(a.data_key),c=O(o.data_key);O(l.data_key);const d=x.keyBy(t[u.queryID],f=>`${f[u.columnKey]}---${f[c.columnKey]}`);return{confine:!0,formatter:function(f){const g=em({conf:e,labelFormatters:n,valueFormatters:r,dataDict:d,params:f}).map(C=>`
139
139
  <tr>
140
140
  <th style="text-align: right;">
141
141
  <div style="${C.style.label}">${C.label}</div>
@@ -157,8 +157,8 @@ Check the top-level render call using <`+V+">.")}return E}}function Su(S,E){{if(
157
157
  <tbody>${g.join("")}</tbody>
158
158
  </table>
159
159
  `}}}const nm=({value:e,onChange:t})=>{const n=r=>{r&&t(r)};return i(s.Box,{children:i(Ae,{height:"500px",defaultLanguage:"javascript",value:e,onChange:n,theme:"vs-dark",options:{minimap:{enabled:!1}}})})},eo={static:{type:"static",value:10},dynamic:{type:"dynamic",value:["function getValue({ variables }, { lodash, interpolate }) {"," // your code goes here"," return 100;","}"].join(`
160
- `)}},rm=({value:e,onChange:t})=>{const[n,{setTrue:r,setFalse:a}]=K.useBoolean(),[o,l]=y.useState(e),u=()=>{a();const{type:h,value:g}=o,m={type:h,value:g};l(m),t(m)},c=()=>{a(),l(e)},d=h=>{l(g=>({...g,value:h}))},f=()=>{d(eo.dynamic.value)};return p(B,{children:[i(s.Box,{sx:{width:"50%"},children:i(s.Button,{variant:"filled",mt:24,onClick:r,sx:{flexGrow:0},children:"Setup"})}),i(s.Modal,{size:800,title:"Setup dynamic value",opened:n,onClose:a,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:n&&p(s.Stack,{children:[i(s.Divider,{mt:10,mb:-10,label:"Dynamic by a custom function",labelPosition:"center",variant:"dashed"}),i(nm,{value:o.value,onChange:d}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:f,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:c,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:u,children:"OK"})]})]})]})})]})},im=({value:e,onChange:t})=>e.type!=="dynamic"?null:i(rm,{value:e,onChange:t}),am=({value:e,onChange:t})=>{if(e.type!=="static")return null;const n=r=>{t({...e,value:r})};return i(s.NumberInput,{defaultValue:18,label:" ",hideControls:!0,value:e.value,onChange:n})},sm=[{label:"Static",value:"static"},{label:"Dynamic",value:"dynamic"}],Ft=y.forwardRef(({label:e="Value",value:t,onChange:n},r)=>{const a=o=>{n({...eo[o]})};return p(s.SimpleGrid,{cols:2,children:[i(s.Select,{ref:r,label:e,data:sm,value:t.type,onChange:a,sx:{flexGrow:1}}),i(am,{value:t,onChange:n}),i(im,{value:t,onChange:n})]})});function Gt(e,t,n){if(!e.type)return n;if(e.type==="static"){const{value:a}=e;return a}const{value:r}=e;try{return new Function(`return ${r}`)()({variables:t},{lodash:x,interpolate:_t.interpolate})}catch(a){return console.error(`[getNumberOrDynamicValue] failed parsing custom function, error: ${a.message}`),10}}function om(e,t){const n=Gt(e.heat_block.min,t),r=Gt(e.heat_block.max,t);return{min:n,max:r,calculable:!0,orient:"horizontal",left:"center",top:0,itemWidth:15}}function lm(e,t,n){const{overflow:r,rotate:a}=e.x_axis.axisLabel,o=rt(r.on_axis);return{id:"main-x-axis",type:"category",data:t,name:e.x_axis.name??"",align:"center",axisTick:{show:!0,alignWithLabel:!0},axisLabel:{rotate:a,...o,formatter:n},splitArea:{show:!0},nameLocation:"center",nameGap:25,nameTextStyle:{fontWeight:"bold",align:"center"},z:2}}function um(e,t,n){const{nameAlignment:r,data_key:a,...o}=e.y_axis,{overflow:l,rotate:u}=e.y_axis.axisLabel,c=rt(l.on_axis);return{...o,type:"category",data:t,axisLabel:{rotate:u,...c,formatter:n},axisLine:{show:!0,color:"blue"},axisTick:{show:!0,alignWithLabel:!0},splitArea:{show:!0},nameTextStyle:{fontWeight:"bold",align:r},nameLocation:"end",nameGap:15,z:2}}const cm={tooltip:{confine:!0}};function dm(e,t,n,r){return n<e*10||r<t*10?0:n<e*20||r<t*20?1:2}function pm(e,t,n,r,a){if(!e.x_axis.data_key||!e.y_axis.data_key||!e.heat_block.data_key)return{};const o=n.reduce((_,D)=>{const M=ft(D,t);return _[D.name]=Ze(D,M),_},{}),l=Kg(e),u=Xg(e),c=O(e.x_axis.data_key),d=O(e.y_axis.data_key),f=O(e.heat_block.data_key),h=x.uniq(t[c.queryID].map(_=>_[c.columnKey])),g=x.uniq(t[c.queryID].map(_=>_[d.columnKey])),m=t[c.queryID].map(_=>[x.get(_,c.columnKey),x.get(_,d.columnKey),x.get(_,f.columnKey)]),C=dm(h.length,g.length,r,a),w={xAxis:lm(e,h,l.x_axis),yAxis:um(e,g,l.y_axis),series:Zg(e,m,C),tooltip:tm(e,t,l,u),grid:Jg(e),visualMap:om(e,o)};return x.defaultsDeep({},w,cm)}function hm(e){return i(B,{})}function fm(e){return i(s.Text,{children:"Click heat block"})}const to={id:"builtin:echarts:click-heatmap:heat-block",displayName:"Click Heat Block",nameRender:fm,configRender:hm,payload:[{name:"seriesType",description:"'heatmap'",valueType:"string"},{name:"componentType",description:"'series'",valueType:"string"},{name:"name",description:"Name of the series clicked",valueType:"string"},{name:"color",description:"Color",valueType:"string"},{name:"value",description:"String-typed number, or series' actual value",valueType:"string"},{name:"rowData",description:"Data of the row",valueType:"object"}]},ni={x_axis:{name:"",data_key:"",axisLabel:{rotate:0,overflow:je,formatter:{...Ue}}},y_axis:{name:"Y Axis",data_key:"",nameAlignment:"center",axisLabel:{rotate:0,overflow:je,formatter:{...Ue}}},heat_block:{min:{type:"static",value:0},max:{type:"static",value:100},name:"Value",data_key:"",value_formatter:ze,label:{show:!1,fontSize:10}},tooltip:{metrics:[]}};ie.use([q.DataZoomComponent,he.HeatmapChart,q.GridComponent,q.LegendComponent,q.TooltipComponent,q.VisualMapComponent,Pe.CanvasRenderer]);function gm({conf:e,data:t,width:n,height:r,interactionManager:a,variables:o}){const l=y.useMemo(()=>{const h=O(e.x_axis.data_key),g=O(e.y_axis.data_key);return x.keyBy(t[h.queryID],m=>`${m[h.columnKey]}---${m[g.columnKey]}`)},[t,e.x_axis.data_key,e.y_axis.data_key]),u=Ke(a.triggerManager,to.id),c=y.useCallback(h=>{const[g,m]=h.value,C=x.get(l,`${g}---${m}`,{error:"rowData is not found"});u.forEach(w=>{a.runInteraction(w.id,{...h,rowData:C})})},[l,u,a]),d=y.useMemo(()=>({click:c}),[c]),f=y.useMemo(()=>pm(e,t,o,n,r),[e,t,n,r]);return!n||!r?null:i(Be,{echarts:ie,option:f,style:{width:n,height:r},onEvents:d,notMerge:!0,theme:"merico-light"})}function mm({context:e,instance:t}){const n=Xe({vizManager:e.vizManager,instance:t}),{value:r}=R(e.instanceData,"config"),{variables:a}=e,o=y.useMemo(()=>x.defaults({},r,ni),[r]),l=e.data,{width:u,height:c}=e.viewport;return i(gm,{variables:a,width:u,height:c,data:l,conf:o,interactionManager:n})}function ym({control:e,watch:t}){t(["heat_block"]);const n=t("heat_block.label.show");return p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"heat_block.data_key",control:e,render:({field:r})=>i(W,{label:"Data Field",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:"heat_block.name",control:e,render:({field:r})=>i(s.TextInput,{label:"Name",sx:{flex:1},...r})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"heat_block.min",control:e,render:({field:r})=>i(Ft,{label:"Min Value",...r})}),i(v.Controller,{name:"heat_block.max",control:e,render:({field:r})=>i(Ft,{label:"Max Value",...r})})]}),i(s.Divider,{mb:-15,variant:"dashed",label:"Value Format",labelPosition:"center"}),i(v.Controller,{name:"heat_block.value_formatter",control:e,render:({field:r})=>i(We,{...r})}),i(s.Divider,{mb:-5,variant:"dashed",label:"Label",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"heat_block.label.show",control:e,render:({field:r})=>i(s.Switch,{label:"Show label",checked:r.value,onChange:a=>r.onChange(a.currentTarget.checked),sx:{flexGrow:1}})}),i(v.Controller,{name:"heat_block.label.fontSize",control:e,render:({field:r})=>i(s.NumberInput,{size:"xs",icon:i($.IconTextSize,{size:16}),disabled:!n,...r})})]})]})}const bm=({control:e,index:t,remove:n})=>p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`tooltip.metrics.${t}.name`,control:e,render:({field:r})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:`tooltip.metrics.${t}.data_key`,control:e,render:({field:r})=>i(W,{label:"Value Field",required:!0,sx:{flex:1},...r})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed"}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Metric"})]}),vm=({control:e,watch:t})=>{const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"tooltip.metrics"}),o=t("tooltip.metrics"),l=n.map((h,g)=>({...h,...o[g]})),u=()=>r({id:Date.now().toString(),data_key:"",name:""}),c=t("tooltip.metrics.0.id"),[d,f]=y.useState(()=>c??null);return y.useEffect(()=>{c&&f(h=>h!==null?h:c)},[c]),p(B,{children:[p(s.Group,{spacing:2,sx:{cursor:"default",userSelect:"none"},children:[i(T.InfoCircle,{size:14,color:"#888"}),i(s.Text,{size:14,color:"#888",children:"Configure additional metrics to show in tooltip"})]}),i(s.Divider,{variant:"dashed",my:10}),p(s.Tabs,{value:d,onTabChange:h=>f(h),styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map((h,g)=>i(s.Tabs.Tab,{value:h.id,children:h.name?h.name:g},h.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((h,g)=>i(s.Tabs.Panel,{value:h.id,children:i(bm,{control:e,index:g,remove:a},h.id)},h.id))]})]})};function xm({control:e,watch:t}){return i(vm,{control:e,watch:t})}const wm=({disabled:e,value:t,onChange:n})=>{const r=a=>{a&&n(a)};return p(s.Box,{sx:{position:"relative"},children:[e&&i(s.Overlay,{opacity:.6,color:"#fff",zIndex:5,blur:2}),i(Ae,{height:"500px",defaultLanguage:"javascript",value:t,onChange:r,theme:"vs-dark",options:{minimap:{enabled:!1},readOnly:e}})]})},Cm={enabled:!1,func_content:["function label(value, index) {"," // your code goes here"," // return value","}"].join(`
161
- `)},no=y.forwardRef(({value:e,onChange:t},n)=>{const[r,{setTrue:a,setFalse:o}]=K.useBoolean(),[l,u]=y.useState(e);y.useEffect(()=>{u(e)},[e]);const c=m=>{u({...l,enabled:m})},d=()=>{o();const{enabled:m,func_content:C}=l,w={enabled:m,func_content:C};u(w),t(w)},f=()=>{o(),u(e)},h=m=>{u(C=>({...C,func_content:m}))},g=()=>{h(Cm.func_content)};return p(B,{children:[i(s.Button,{variant:"filled",mt:24,onClick:a,sx:{flexGrow:0},children:"Customize Label"}),i(s.Modal,{size:800,title:"Customize label content",opened:r,onClose:o,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:r&&p(s.Stack,{children:[i(s.Checkbox,{mt:10,label:"Enabled",checked:l.enabled,onChange:m=>c(m.currentTarget.checked)}),i(wm,{value:l.func_content,onChange:h,disabled:!l.enabled}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:g,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:f,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:d,children:"OK"})]})]})]})})]})});function Sm({control:e,watch:t}){return t(["x_axis"]),p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.data_key",control:e,render:({field:n})=>i(W,{label:"Data Field",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"x_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Name",sx:{flex:1},...n})})]}),i(s.Divider,{mb:-15,variant:"dashed",label:"Tick Label",labelPosition:"center"}),i(v.Controller,{name:"x_axis.axisLabel.overflow",control:e,render:({field:n})=>i(at,{...n})}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.axisLabel.rotate",control:e,render:({field:n})=>i(s.NumberInput,{label:"Rotate",hideControls:!0,min:-90,max:90,rightSection:i(s.Text,{color:"dimmed",children:"degree"}),sx:{width:"48%"},styles:{rightSection:{width:"4em",justifyContent:"flex-end",paddingRight:"6px"}},...n})}),i(v.Controller,{name:"x_axis.axisLabel.formatter",control:e,render:({field:n})=>i(no,{...n})})]})]})}const _m=[{label:"left",value:"left"},{label:"center",value:"center"},{label:"right",value:"right"}];function km({control:e,watch:t}){return t(["y_axis"]),p(s.Stack,{my:0,p:"0",sx:{position:"relative"},children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"y_axis.data_key",control:e,render:({field:n})=>i(W,{label:"Data Field",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"y_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...n})})]}),i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:"y_axis.nameAlignment",control:e,render:({field:n})=>i(s.Select,{label:"Name Alignment",required:!0,data:_m,sx:{flex:1},...n})})}),i(s.Divider,{mb:-15,variant:"dashed",label:"Tick Label",labelPosition:"center"}),i(v.Controller,{name:"y_axis.axisLabel.overflow",control:e,render:({field:n})=>i(at,{...n})}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"y_axis.axisLabel.rotate",control:e,render:({field:n})=>i(s.NumberInput,{label:"Rotate",hideControls:!0,min:-90,max:90,rightSection:i(s.Text,{color:"dimmed",children:"degree"}),sx:{width:"48%"},styles:{rightSection:{width:"4em",justifyContent:"flex-end",paddingRight:"6px"}},...n})}),i(v.Controller,{name:"y_axis.axisLabel.formatter",control:e,render:({field:n})=>i(no,{...n})})]})]})}function Tm({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=y.useMemo(()=>x.defaultsDeep({},t,ni),[t]),a=y.useMemo(()=>x.cloneDeep(r),[r]);y.useEffect(()=>{!x.isEqual(r,a)&&(console.log("config malformed, resetting to defaults",r,a),n(a))},[r,a]);const{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});y.useEffect(()=>{d(a)},[a]);const f=c(),h=y.useMemo(()=>!x.isEqual(f,r),[f,r]);return i("form",{onSubmit:l(n),style:{flexGrow:1},children:p(s.Stack,{spacing:"xs",sx:{height:"100%"},children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"X Axis",orientation:"vertical",styles:{root:{flexGrow:1},tab:{paddingLeft:"6px",paddingRight:"6px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"X Axis",children:"X Axis"}),i(s.Tabs.Tab,{value:"Y Axis",children:"Y Axis"}),i(s.Tabs.Tab,{value:"Heat Block",children:"Heat Block"}),i(s.Tabs.Tab,{value:"Tooltip",children:"Tooltip"})]}),i(s.Tabs.Panel,{value:"X Axis",children:i(Sm,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Y Axis",children:i(km,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Heat Block",children:i(ym,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Tooltip",children:i(xm,{control:o,watch:u})})]})]})})}function Dm(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=d=>d&&`${n}.${d}`,{x_axis:a,y_axis:o,heat_block:l,tooltip:u,...c}=e;return{...c,x_axis:{...a,data_key:r(a.data_key)},y_axis:{...o,data_key:r(o.data_key)},heat_block:{...l,data_key:r(l.data_key)},tooltip:{...u,metrics:u.metrics.map(d=>({...d,data_key:r(d.data_key)}))}}}catch(n){throw console.error("[Migration failed]",n),n}}function Im(e){return x.defaultsDeep({},e,{heat_block:{label:{show:!1,fontSize:10}}})}function Mm(e){const{heat_block:t}=e;let{min:n,max:r}=t;return typeof n!="number"&&(n=0),typeof r!="number"&&(r=100),{...e,heat_block:{...t,min:{type:"static",value:n},max:{type:"static",value:r}}}}class Am extends ye{constructor(){super(...arguments);N(this,"VERSION",4)}configVersions(){this.version(1,n=>(console.log("🟥 unexpected calling"),{version:1,config:n})),this.version(2,(n,r)=>({...n,version:2,config:Dm(n.config,r)})),this.version(3,n=>({...n,version:3,config:Im(n.config)})),this.version(4,n=>({...n,version:4,config:Mm(n.config)}))}}const zm={displayName:"Heatmap",displayGroup:"ECharts-based charts",migrator:new Am,name:"heatmap",viewRender:mm,configRender:Tm,createConfig:()=>({version:4,config:ni}),triggers:[to]},ro={id:"builtin:echarts:click-echart:series",displayName:"Click Chart Series",nameRender:$m,configRender:Em,payload:[{name:"type",description:"Always 'click'",valueType:"string"},{name:"seriesType",description:"'line' | 'bar'",valueType:"string"},{name:"name",description:"Name of the series clicked",valueType:"string"},{name:"color",description:"Color",valueType:"string"},{name:"rowData",description:"Data of the row",valueType:"object"}]};function Em(e){return i(B,{})}function $m(e){return i(s.Text,{children:"Click chart's series"})}const io={label_template:"${percentage.x} of ${x_axis.name} causes ${percentage.y} of ${bar.name}",color:"rgba(0,0,0,0.3)"},ri={x_axis:{name:"X Axis",data_key:"",axisLabel:{rotate:0,formatter:{...Ue},overflow:je}},data_key:"value",bar:{name:"Value",nameAlignment:"left",color:"#228be6",label_formatter:ze},line:{name:"Value",nameAlignment:"right",color:"red"},dataZoom:qt,markLine:io};function Qn(e){return Z(e).format({output:"percent",mantissa:0})}function Lm(e){const t=e.value[1];try{return Qn(t)}catch(n){return console.error(n),t}}function Om(e){function t(n){let r=n;if(typeof n=="object"&&(Array.isArray(n.value)&&n.value.length===2?r=n.value[1]:r=n.value),!e.bar.label_formatter)return r;try{return Z(r).format(e.bar.label_formatter)}catch(a){return console.error(a),r}}return{bar:t,line:Lm,lineValue:Qn}}function Pm(e,t,n){const{label_template:r}=e.markLine;if(!r)return"";const a={...e,percentage:t,count:n},o=Object.keys(a),l=Object.values(a);return new Function(...o,`return \`${r}\`;`)(...l)}function Bm(e,t){if(t.length===0)return{};const n=t.findIndex(u=>u[1]>=.8);if(n===-1)return{};const r=t[n],a={x:Qn((n+1)/t.length),y:Qn(r[1])},o={left:n+1,right:t.length-n-1},l=r[0];return l?{name:"",silent:!0,symbol:"triangle",symbolRotate:180,symbolSize:[10,8],data:[{name:"",symbol:"none",xAxis:l,lineStyle:{color:e.markLine.color},label:{formatter:Pm(e,a,o)}}]}:{}}function Vm(e,t,n){const{x_axis:r,data_key:a}=e;if(!r.data_key||!a)return[];const o=O(r.data_key),l=O(a);if(o.queryID!==l.queryID)throw new Error("Please use the same query for X & Y axis");const u=t[o.queryID].map(h=>[h[o.columnKey],Number(h[l.columnKey])]).sort((h,g)=>g[1]-h[1]),c=u.reduce((h,g)=>h+g[1],0),d=u.reduce((h,g,m)=>{const C=m===0?0:h[m-1][1];return h.push([g[0],C+g[1]]),h},[]).map(h=>[h[0],h[1]/c]),f=Bm(e,d);return[{name:e.bar.name,type:"bar",barMaxWidth:20,itemStyle:{color:e.bar.color},label:{show:!1,position:"top",formatter:n.bar},yAxisIndex:0,data:u},{name:e.line.name,type:"line",itemStyle:{color:e.line.color},symbolSize:2,lineStyle:{width:1},label:{show:!1,position:"top",formatter:n.line},yAxisIndex:1,data:d,markLine:f}]}const Nm=(e,t)=>n=>{const r=Array.isArray(n)?n:[n];if(r.length===0)return"";const a=r.map((u,c)=>{const d=u.seriesName,[f,h]=u.value;if(!d)return h;const g=c===0?t.bar:t.lineValue;return`
160
+ `)}},rm=({value:e,onChange:t})=>{const[n,{setTrue:r,setFalse:a}]=K.useBoolean(),[o,l]=b.useState(e),u=()=>{a();const{type:h,value:g}=o,m={type:h,value:g};l(m),t(m)},c=()=>{a(),l(e)},d=h=>{l(g=>({...g,value:h}))},f=()=>{d(eo.dynamic.value)};return p(B,{children:[i(s.Box,{sx:{width:"50%"},children:i(s.Button,{variant:"filled",mt:24,onClick:r,sx:{flexGrow:0},children:"Setup"})}),i(s.Modal,{size:800,title:"Setup dynamic value",opened:n,onClose:a,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:n&&p(s.Stack,{children:[i(s.Divider,{mt:10,mb:-10,label:"Dynamic by a custom function",labelPosition:"center",variant:"dashed"}),i(nm,{value:o.value,onChange:d}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:f,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:c,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:u,children:"OK"})]})]})]})})]})},im=({value:e,onChange:t})=>e.type!=="dynamic"?null:i(rm,{value:e,onChange:t}),am=({value:e,onChange:t})=>{if(e.type!=="static")return null;const n=r=>{t({...e,value:r})};return i(s.NumberInput,{defaultValue:18,label:" ",hideControls:!0,value:e.value,onChange:n})},sm=[{label:"Static",value:"static"},{label:"Dynamic",value:"dynamic"}],Ft=b.forwardRef(({label:e="Value",value:t,onChange:n},r)=>{const a=o=>{n({...eo[o]})};return p(s.SimpleGrid,{cols:2,children:[i(s.Select,{ref:r,label:e,data:sm,value:t.type,onChange:a,sx:{flexGrow:1}}),i(am,{value:t,onChange:n}),i(im,{value:t,onChange:n})]})});function Gt(e,t,n){if(!e.type)return n;if(e.type==="static"){const{value:a}=e;return a}const{value:r}=e;try{return new Function(`return ${r}`)()({variables:t},{lodash:x,interpolate:_t.interpolate})}catch(a){return console.error(`[getNumberOrDynamicValue] failed parsing custom function, error: ${a.message}`),10}}function om(e,t){const n=Gt(e.heat_block.min,t),r=Gt(e.heat_block.max,t);return{min:n,max:r,calculable:!0,orient:"horizontal",left:"center",top:0,itemWidth:15}}function lm(e,t,n){const{overflow:r,rotate:a}=e.x_axis.axisLabel,o=rt(r.on_axis);return{id:"main-x-axis",type:"category",data:t,name:e.x_axis.name??"",align:"center",axisTick:{show:!0,alignWithLabel:!0},axisLabel:{rotate:a,...o,formatter:n},splitArea:{show:!0},nameLocation:"center",nameGap:25,nameTextStyle:{fontWeight:"bold",align:"center"},z:2}}function um(e,t,n){const{nameAlignment:r,data_key:a,...o}=e.y_axis,{overflow:l,rotate:u}=e.y_axis.axisLabel,c=rt(l.on_axis);return{...o,type:"category",data:t,axisLabel:{rotate:u,...c,formatter:n},axisLine:{show:!0,color:"blue"},axisTick:{show:!0,alignWithLabel:!0},splitArea:{show:!0},nameTextStyle:{fontWeight:"bold",align:r},nameLocation:"end",nameGap:15,z:2}}const cm={tooltip:{confine:!0}};function dm(e,t,n,r){return n<e*10||r<t*10?0:n<e*20||r<t*20?1:2}function pm(e,t,n,r,a){if(!e.x_axis.data_key||!e.y_axis.data_key||!e.heat_block.data_key)return{};const o=n.reduce((_,D)=>{const M=ft(D,t);return _[D.name]=Ze(D,M),_},{}),l=Kg(e),u=Xg(e),c=O(e.x_axis.data_key),d=O(e.y_axis.data_key),f=O(e.heat_block.data_key),h=x.uniq(t[c.queryID].map(_=>_[c.columnKey])),g=x.uniq(t[c.queryID].map(_=>_[d.columnKey])),m=t[c.queryID].map(_=>[x.get(_,c.columnKey),x.get(_,d.columnKey),x.get(_,f.columnKey)]),C=dm(h.length,g.length,r,a),w={xAxis:lm(e,h,l.x_axis),yAxis:um(e,g,l.y_axis),series:Zg(e,m,C),tooltip:tm(e,t,l,u),grid:Jg(e),visualMap:om(e,o)};return x.defaultsDeep({},w,cm)}function hm(e){return i(B,{})}function fm(e){return i(s.Text,{children:"Click heat block"})}const to={id:"builtin:echarts:click-heatmap:heat-block",displayName:"Click Heat Block",nameRender:fm,configRender:hm,payload:[{name:"seriesType",description:"'heatmap'",valueType:"string"},{name:"componentType",description:"'series'",valueType:"string"},{name:"name",description:"Name of the series clicked",valueType:"string"},{name:"color",description:"Color",valueType:"string"},{name:"value",description:"String-typed number, or series' actual value",valueType:"string"},{name:"rowData",description:"Data of the row",valueType:"object"}]},ni={x_axis:{name:"",data_key:"",axisLabel:{rotate:0,overflow:Re,formatter:{...Ue}}},y_axis:{name:"Y Axis",data_key:"",nameAlignment:"center",axisLabel:{rotate:0,overflow:Re,formatter:{...Ue}}},heat_block:{min:{type:"static",value:0},max:{type:"static",value:100},name:"Value",data_key:"",value_formatter:ze,label:{show:!1,fontSize:10}},tooltip:{metrics:[]}};ie.use([q.DataZoomComponent,he.HeatmapChart,q.GridComponent,q.LegendComponent,q.TooltipComponent,q.VisualMapComponent,Pe.CanvasRenderer]);function gm({conf:e,data:t,width:n,height:r,interactionManager:a,variables:o}){const l=b.useMemo(()=>{const h=O(e.x_axis.data_key),g=O(e.y_axis.data_key);return x.keyBy(t[h.queryID],m=>`${m[h.columnKey]}---${m[g.columnKey]}`)},[t,e.x_axis.data_key,e.y_axis.data_key]),u=Ke(a.triggerManager,to.id),c=b.useCallback(h=>{const[g,m]=h.value,C=x.get(l,`${g}---${m}`,{error:"rowData is not found"});u.forEach(w=>{a.runInteraction(w.id,{...h,rowData:C})})},[l,u,a]),d=b.useMemo(()=>({click:c}),[c]),f=b.useMemo(()=>pm(e,t,o,n,r),[e,t,n,r]);return!n||!r?null:i(Be,{echarts:ie,option:f,style:{width:n,height:r},onEvents:d,notMerge:!0,theme:"merico-light"})}function mm({context:e,instance:t}){const n=Xe({vizManager:e.vizManager,instance:t}),{value:r}=R(e.instanceData,"config"),{variables:a}=e,o=b.useMemo(()=>x.defaults({},r,ni),[r]),l=e.data,{width:u,height:c}=e.viewport;return i(gm,{variables:a,width:u,height:c,data:l,conf:o,interactionManager:n})}function ym({control:e,watch:t}){t(["heat_block"]);const n=t("heat_block.label.show");return p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"heat_block.data_key",control:e,render:({field:r})=>i(W,{label:"Data Field",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:"heat_block.name",control:e,render:({field:r})=>i(s.TextInput,{label:"Name",sx:{flex:1},...r})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"heat_block.min",control:e,render:({field:r})=>i(Ft,{label:"Min Value",...r})}),i(v.Controller,{name:"heat_block.max",control:e,render:({field:r})=>i(Ft,{label:"Max Value",...r})})]}),i(s.Divider,{mb:-15,variant:"dashed",label:"Value Format",labelPosition:"center"}),i(v.Controller,{name:"heat_block.value_formatter",control:e,render:({field:r})=>i(je,{...r})}),i(s.Divider,{mb:-5,variant:"dashed",label:"Label",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"heat_block.label.show",control:e,render:({field:r})=>i(s.Switch,{label:"Show label",checked:r.value,onChange:a=>r.onChange(a.currentTarget.checked),sx:{flexGrow:1}})}),i(v.Controller,{name:"heat_block.label.fontSize",control:e,render:({field:r})=>i(s.NumberInput,{size:"xs",icon:i($.IconTextSize,{size:16}),disabled:!n,...r})})]})]})}const bm=({control:e,index:t,remove:n})=>p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`tooltip.metrics.${t}.name`,control:e,render:({field:r})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:`tooltip.metrics.${t}.data_key`,control:e,render:({field:r})=>i(W,{label:"Value Field",required:!0,sx:{flex:1},...r})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed"}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Metric"})]}),vm=({control:e,watch:t})=>{const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"tooltip.metrics"}),o=t("tooltip.metrics"),l=n.map((h,g)=>({...h,...o[g]})),u=()=>r({id:Date.now().toString(),data_key:"",name:""}),c=t("tooltip.metrics.0.id"),[d,f]=b.useState(()=>c??null);return b.useEffect(()=>{c&&f(h=>h!==null?h:c)},[c]),p(B,{children:[p(s.Group,{spacing:2,sx:{cursor:"default",userSelect:"none"},children:[i(T.InfoCircle,{size:14,color:"#888"}),i(s.Text,{size:14,color:"#888",children:"Configure additional metrics to show in tooltip"})]}),i(s.Divider,{variant:"dashed",my:10}),p(s.Tabs,{value:d,onTabChange:h=>f(h),styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map((h,g)=>i(s.Tabs.Tab,{value:h.id,children:h.name?h.name:g},h.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((h,g)=>i(s.Tabs.Panel,{value:h.id,children:i(bm,{control:e,index:g,remove:a},h.id)},h.id))]})]})};function xm({control:e,watch:t}){return i(vm,{control:e,watch:t})}const wm=({disabled:e,value:t,onChange:n})=>{const r=a=>{a&&n(a)};return p(s.Box,{sx:{position:"relative"},children:[e&&i(s.Overlay,{opacity:.6,color:"#fff",zIndex:5,blur:2}),i(Ae,{height:"500px",defaultLanguage:"javascript",value:t,onChange:r,theme:"vs-dark",options:{minimap:{enabled:!1},readOnly:e}})]})},Cm={enabled:!1,func_content:["function label(value, index) {"," // your code goes here"," // return value","}"].join(`
161
+ `)},no=b.forwardRef(({value:e,onChange:t},n)=>{const[r,{setTrue:a,setFalse:o}]=K.useBoolean(),[l,u]=b.useState(e);b.useEffect(()=>{u(e)},[e]);const c=m=>{u({...l,enabled:m})},d=()=>{o();const{enabled:m,func_content:C}=l,w={enabled:m,func_content:C};u(w),t(w)},f=()=>{o(),u(e)},h=m=>{u(C=>({...C,func_content:m}))},g=()=>{h(Cm.func_content)};return p(B,{children:[i(s.Button,{variant:"filled",mt:24,onClick:a,sx:{flexGrow:0},children:"Customize Label"}),i(s.Modal,{size:800,title:"Customize label content",opened:r,onClose:o,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:r&&p(s.Stack,{children:[i(s.Checkbox,{mt:10,label:"Enabled",checked:l.enabled,onChange:m=>c(m.currentTarget.checked)}),i(wm,{value:l.func_content,onChange:h,disabled:!l.enabled}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:g,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:f,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:d,children:"OK"})]})]})]})})]})});function Sm({control:e,watch:t}){return t(["x_axis"]),p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.data_key",control:e,render:({field:n})=>i(W,{label:"Data Field",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"x_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Name",sx:{flex:1},...n})})]}),i(s.Divider,{mb:-15,variant:"dashed",label:"Tick Label",labelPosition:"center"}),i(v.Controller,{name:"x_axis.axisLabel.overflow",control:e,render:({field:n})=>i(at,{...n})}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.axisLabel.rotate",control:e,render:({field:n})=>i(s.NumberInput,{label:"Rotate",hideControls:!0,min:-90,max:90,rightSection:i(s.Text,{color:"dimmed",children:"degree"}),sx:{width:"48%"},styles:{rightSection:{width:"4em",justifyContent:"flex-end",paddingRight:"6px"}},...n})}),i(v.Controller,{name:"x_axis.axisLabel.formatter",control:e,render:({field:n})=>i(no,{...n})})]})]})}const _m=[{label:"left",value:"left"},{label:"center",value:"center"},{label:"right",value:"right"}];function km({control:e,watch:t}){return t(["y_axis"]),p(s.Stack,{my:0,p:"0",sx:{position:"relative"},children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"y_axis.data_key",control:e,render:({field:n})=>i(W,{label:"Data Field",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"y_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...n})})]}),i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:"y_axis.nameAlignment",control:e,render:({field:n})=>i(s.Select,{label:"Name Alignment",required:!0,data:_m,sx:{flex:1},...n})})}),i(s.Divider,{mb:-15,variant:"dashed",label:"Tick Label",labelPosition:"center"}),i(v.Controller,{name:"y_axis.axisLabel.overflow",control:e,render:({field:n})=>i(at,{...n})}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"y_axis.axisLabel.rotate",control:e,render:({field:n})=>i(s.NumberInput,{label:"Rotate",hideControls:!0,min:-90,max:90,rightSection:i(s.Text,{color:"dimmed",children:"degree"}),sx:{width:"48%"},styles:{rightSection:{width:"4em",justifyContent:"flex-end",paddingRight:"6px"}},...n})}),i(v.Controller,{name:"y_axis.axisLabel.formatter",control:e,render:({field:n})=>i(no,{...n})})]})]})}function Tm({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=b.useMemo(()=>x.defaultsDeep({},t,ni),[t]),a=b.useMemo(()=>x.cloneDeep(r),[r]);b.useEffect(()=>{!x.isEqual(r,a)&&(console.log("config malformed, resetting to defaults",r,a),n(a))},[r,a]);const{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});b.useEffect(()=>{d(a)},[a]);const f=c(),h=b.useMemo(()=>!x.isEqual(f,r),[f,r]);return i("form",{onSubmit:l(n),style:{flexGrow:1},children:p(s.Stack,{spacing:"xs",sx:{height:"100%"},children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"X Axis",orientation:"vertical",styles:{root:{flexGrow:1},tab:{paddingLeft:"6px",paddingRight:"6px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"X Axis",children:"X Axis"}),i(s.Tabs.Tab,{value:"Y Axis",children:"Y Axis"}),i(s.Tabs.Tab,{value:"Heat Block",children:"Heat Block"}),i(s.Tabs.Tab,{value:"Tooltip",children:"Tooltip"})]}),i(s.Tabs.Panel,{value:"X Axis",children:i(Sm,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Y Axis",children:i(km,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Heat Block",children:i(ym,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Tooltip",children:i(xm,{control:o,watch:u})})]})]})})}function Dm(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=d=>d&&`${n}.${d}`,{x_axis:a,y_axis:o,heat_block:l,tooltip:u,...c}=e;return{...c,x_axis:{...a,data_key:r(a.data_key)},y_axis:{...o,data_key:r(o.data_key)},heat_block:{...l,data_key:r(l.data_key)},tooltip:{...u,metrics:u.metrics.map(d=>({...d,data_key:r(d.data_key)}))}}}catch(n){throw console.error("[Migration failed]",n),n}}function Im(e){return x.defaultsDeep({},e,{heat_block:{label:{show:!1,fontSize:10}}})}function Mm(e){const{heat_block:t}=e;let{min:n,max:r}=t;return typeof n!="number"&&(n=0),typeof r!="number"&&(r=100),{...e,heat_block:{...t,min:{type:"static",value:n},max:{type:"static",value:r}}}}class Am extends ye{constructor(){super(...arguments);N(this,"VERSION",4)}configVersions(){this.version(1,n=>(console.log("🟥 unexpected calling"),{version:1,config:n})),this.version(2,(n,r)=>({...n,version:2,config:Dm(n.config,r)})),this.version(3,n=>({...n,version:3,config:Im(n.config)})),this.version(4,n=>({...n,version:4,config:Mm(n.config)}))}}const zm={displayName:"Heatmap",displayGroup:"ECharts-based charts",migrator:new Am,name:"heatmap",viewRender:mm,configRender:Tm,createConfig:()=>({version:4,config:ni}),triggers:[to]},ro={id:"builtin:echarts:click-echart:series",displayName:"Click Chart Series",nameRender:$m,configRender:Em,payload:[{name:"type",description:"Always 'click'",valueType:"string"},{name:"seriesType",description:"'line' | 'bar'",valueType:"string"},{name:"name",description:"Name of the series clicked",valueType:"string"},{name:"color",description:"Color",valueType:"string"},{name:"rowData",description:"Data of the row",valueType:"object"}]};function Em(e){return i(B,{})}function $m(e){return i(s.Text,{children:"Click chart's series"})}const io={label_template:"${percentage.x} of ${x_axis.name} causes ${percentage.y} of ${bar.name}",color:"rgba(0,0,0,0.3)"},ri={x_axis:{name:"X Axis",data_key:"",axisLabel:{rotate:0,formatter:{...Ue},overflow:Re}},data_key:"value",bar:{name:"Value",nameAlignment:"left",color:"#228be6",label_formatter:ze},line:{name:"Value",nameAlignment:"right",color:"red"},dataZoom:qt,markLine:io};function Qn(e){return Z(e).format({output:"percent",mantissa:0})}function Lm(e){const t=e.value[1];try{return Qn(t)}catch(n){return console.error(n),t}}function Om(e){function t(n){let r=n;if(typeof n=="object"&&(Array.isArray(n.value)&&n.value.length===2?r=n.value[1]:r=n.value),!e.bar.label_formatter)return r;try{return Z(r).format(e.bar.label_formatter)}catch(a){return console.error(a),r}}return{bar:t,line:Lm,lineValue:Qn}}function Pm(e,t,n){const{label_template:r}=e.markLine;if(!r)return"";const a={...e,percentage:t,count:n},o=Object.keys(a),l=Object.values(a);return new Function(...o,`return \`${r}\`;`)(...l)}function Bm(e,t){if(t.length===0)return{};const n=t.findIndex(u=>u[1]>=.8);if(n===-1)return{};const r=t[n],a={x:Qn((n+1)/t.length),y:Qn(r[1])},o={left:n+1,right:t.length-n-1},l=r[0];return l?{name:"",silent:!0,symbol:"triangle",symbolRotate:180,symbolSize:[10,8],data:[{name:"",symbol:"none",xAxis:l,lineStyle:{color:e.markLine.color},label:{formatter:Pm(e,a,o)}}]}:{}}function Vm(e,t,n){const{x_axis:r,data_key:a}=e;if(!r.data_key||!a)return[];const o=O(r.data_key),l=O(a);if(o.queryID!==l.queryID)throw new Error("Please use the same query for X & Y axis");const u=t[o.queryID].map(h=>[h[o.columnKey],Number(h[l.columnKey])]).sort((h,g)=>g[1]-h[1]),c=u.reduce((h,g)=>h+g[1],0),d=u.reduce((h,g,m)=>{const C=m===0?0:h[m-1][1];return h.push([g[0],C+g[1]]),h},[]).map(h=>[h[0],h[1]/c]),f=Bm(e,d);return[{name:e.bar.name,type:"bar",barMaxWidth:20,itemStyle:{color:e.bar.color},label:{show:!1,position:"top",formatter:n.bar},yAxisIndex:0,data:u},{name:e.line.name,type:"line",itemStyle:{color:e.line.color},symbolSize:2,lineStyle:{width:1},label:{show:!1,position:"top",formatter:n.line},yAxisIndex:1,data:d,markLine:f}]}const Nm=(e,t)=>n=>{const r=Array.isArray(n)?n:[n];if(r.length===0)return"";const a=r.map((u,c)=>{const d=u.seriesName,[f,h]=u.value;if(!d)return h;const g=c===0?t.bar:t.lineValue;return`
162
162
  <tr>
163
163
  <th style="text-align: right; padding: 0 1em;">${d}</th>
164
164
  <td style="text-align: left; padding: 0 1em;">${g(h)}</td>
@@ -172,7 +172,7 @@ Check the top-level render call using <`+V+">.")}return E}}function Su(S,E){{if(
172
172
  ${a.join("")}
173
173
  </tbody>
174
174
  </table>
175
- `};function qm(e,t){return{trigger:"axis",formatter:Nm(e,t)}}function Fm(e){const{name:t,axisLabel:n}=e.x_axis,r=rt(n.overflow.on_axis);return[{type:"category",name:t,nameLocation:"middle",nameGap:30,nameTextStyle:{fontWeight:"bold",align:"right"},splitLine:{show:!1},axisTick:{show:!0,alignWithLabel:!0},axisLabel:{...n,...r,formatter:Pt(n.formatter)}}]}function Gm(e,t){return[{name:e.bar.name,nameGap:20,minInterval:1,nameTextStyle:{fontWeight:"bold",align:e.bar.nameAlignment},position:"left",axisLine:{show:!0},axisLabel:{show:!0,formatter:t.bar},splitLine:{show:!1}},{name:e.line.name,nameGap:20,nameTextStyle:{fontWeight:"bold",align:e.line.nameAlignment},position:"right",axisLine:{show:!0},axisLabel:{show:!0,formatter:t.lineValue},splitLine:{show:!1}}]}function Wm(e,t,n){const r=Om(e);return{dataZoom:Xr(e.dataZoom),tooltip:qm(e,r),xAxis:Fm(e),yAxis:Gm(e,r),series:Vm(e,t,r),grid:{top:50,left:30,right:15,bottom:5,containLabel:!0}}}ie.use([he.BarChart,he.LineChart,q.DataZoomComponent,q.GridComponent,q.LegendComponent,q.TooltipComponent,Pe.CanvasRenderer]);function jm({context:e,instance:t}){const{value:n}=R(e.instanceData,"config"),r=e.data,{width:a,height:o}=e.viewport,l=x.defaults({},n,ri),u=Wm(l,r),c=Xe({vizManager:e.vizManager,instance:t}),d=Ke(c.triggerManager,ro.id),f=Dt(r,l.x_axis.data_key),h=y.useCallback(m=>{const C=x.get(f,m.name,{error:"rowData is not found"});d.forEach(w=>{c.runInteraction(w.id,{...m,rowData:C})})},[f,d,c]),g=y.useMemo(()=>({click:h}),[h]);return!l||!a||!o?null:i(Be,{echarts:ie,option:u,style:{width:a,height:o},onEvents:g,notMerge:!0,theme:"merico-light"})}const Rm=[{label:"left",value:"left"},{label:"center",value:"center"},{label:"right",value:"right"}];function Ym({control:e,watch:t}){return t(["bar"]),p(s.Stack,{children:[p(s.Group,{grow:!0,children:[i(v.Controller,{name:"bar.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Bar Name",sx:{flex:1},...n})}),i(v.Controller,{name:"bar.nameAlignment",control:e,render:({field:n})=>i(s.Select,{label:"Align",required:!0,data:Rm,sx:{flex:1},...n})})]}),p(s.Stack,{spacing:2,children:[i(s.Text,{size:"sm",children:"Color"}),i(v.Controller,{name:"bar.color",control:e,render:({field:n})=>i(Ve,{...n})})]}),p(s.Stack,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Label Format",labelPosition:"center"}),i(v.Controller,{name:"bar.label_formatter",control:e,render:({field:n})=>i(We,{...n})})]})]})}const Qm=[{label:"left",value:"left"},{label:"center",value:"center"},{label:"right",value:"right"}];function Um({control:e,watch:t}){return t(["line"]),p(s.Stack,{children:[p(s.Group,{grow:!0,children:[i(v.Controller,{name:"line.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Line Name",sx:{flex:1},...n})}),i(v.Controller,{name:"line.nameAlignment",control:e,render:({field:n})=>i(s.Select,{label:"Align",required:!0,data:Qm,sx:{flex:1},...n})})]}),p(s.Stack,{spacing:2,children:[i(s.Text,{size:"sm",children:"Color"}),i(v.Controller,{name:"line.color",control:e,render:({field:n})=>i(Ve,{...n})})]})]})}const Km=`
175
+ `};function qm(e,t){return{trigger:"axis",formatter:Nm(e,t)}}function Fm(e){const{name:t,axisLabel:n}=e.x_axis,r=rt(n.overflow.on_axis);return[{type:"category",name:t,nameLocation:"middle",nameGap:30,nameTextStyle:{fontWeight:"bold",align:"right"},splitLine:{show:!1},axisTick:{show:!0,alignWithLabel:!0},axisLabel:{...n,...r,formatter:Pt(n.formatter)}}]}function Gm(e,t){return[{name:e.bar.name,nameGap:20,minInterval:1,nameTextStyle:{fontWeight:"bold",align:e.bar.nameAlignment},position:"left",axisLine:{show:!0},axisLabel:{show:!0,formatter:t.bar},splitLine:{show:!1}},{name:e.line.name,nameGap:20,nameTextStyle:{fontWeight:"bold",align:e.line.nameAlignment},position:"right",axisLine:{show:!0},axisLabel:{show:!0,formatter:t.lineValue},splitLine:{show:!1}}]}function Wm(e,t,n){const r=Om(e);return{dataZoom:Xr(e.dataZoom),tooltip:qm(e,r),xAxis:Fm(e),yAxis:Gm(e,r),series:Vm(e,t,r),grid:{top:50,left:30,right:15,bottom:5,containLabel:!0}}}ie.use([he.BarChart,he.LineChart,q.DataZoomComponent,q.GridComponent,q.LegendComponent,q.TooltipComponent,Pe.CanvasRenderer]);function jm({context:e,instance:t}){const{value:n}=R(e.instanceData,"config"),r=e.data,{width:a,height:o}=e.viewport,l=x.defaults({},n,ri),u=Wm(l,r),c=Xe({vizManager:e.vizManager,instance:t}),d=Ke(c.triggerManager,ro.id),f=Dt(r,l.x_axis.data_key),h=b.useCallback(m=>{const C=x.get(f,m.name,{error:"rowData is not found"});d.forEach(w=>{c.runInteraction(w.id,{...m,rowData:C})})},[f,d,c]),g=b.useMemo(()=>({click:h}),[h]);return!l||!a||!o?null:i(Be,{echarts:ie,option:u,style:{width:a,height:o},onEvents:g,notMerge:!0,theme:"merico-light"})}const Rm=[{label:"left",value:"left"},{label:"center",value:"center"},{label:"right",value:"right"}];function Ym({control:e,watch:t}){return t(["bar"]),p(s.Stack,{children:[p(s.Group,{grow:!0,children:[i(v.Controller,{name:"bar.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Bar Name",sx:{flex:1},...n})}),i(v.Controller,{name:"bar.nameAlignment",control:e,render:({field:n})=>i(s.Select,{label:"Align",required:!0,data:Rm,sx:{flex:1},...n})})]}),p(s.Stack,{spacing:2,children:[i(s.Text,{size:"sm",children:"Color"}),i(v.Controller,{name:"bar.color",control:e,render:({field:n})=>i(Ve,{...n})})]}),p(s.Stack,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Label Format",labelPosition:"center"}),i(v.Controller,{name:"bar.label_formatter",control:e,render:({field:n})=>i(je,{...n})})]})]})}const Qm=[{label:"left",value:"left"},{label:"center",value:"center"},{label:"right",value:"right"}];function Um({control:e,watch:t}){return t(["line"]),p(s.Stack,{children:[p(s.Group,{grow:!0,children:[i(v.Controller,{name:"line.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Line Name",sx:{flex:1},...n})}),i(v.Controller,{name:"line.nameAlignment",control:e,render:({field:n})=>i(s.Select,{label:"Align",required:!0,data:Qm,sx:{flex:1},...n})})]}),p(s.Stack,{spacing:2,children:[i(s.Text,{size:"sm",children:"Color"}),i(v.Controller,{name:"line.color",control:e,render:({field:n})=>i(Ve,{...n})})]})]})}const Km=`
176
176
  {
177
177
  // 80-20 line stuff
178
178
  percentage: {
@@ -195,8 +195,8 @@ Check the top-level render call using <`+V+">.")}return E}}function Su(S,E){{if(
195
195
  name: string;
196
196
  };
197
197
  }
198
- `,Xm=()=>{const[e,t]=y.useState(!1);return p(B,{children:[i(s.Button,{variant:"subtle",compact:!0,onClick:()=>t(n=>!n),children:e?"Close":"Click to see params for Label Template"}),i(s.Collapse,{in:e,children:i(kt.Prism,{language:"typescript",noCopy:!0,colorScheme:"dark",children:Km})})]})};function Jm({control:e,watch:t}){return t(["markLine"]),p(s.Stack,{children:[p(s.Stack,{spacing:2,children:[i(s.Text,{size:"sm",children:"Color"}),i(v.Controller,{name:"markLine.color",control:e,render:({field:n})=>i(Ve,{...n})})]}),p(s.Stack,{spacing:4,children:[i(v.Controller,{name:"markLine.label_template",control:e,render:({field:n})=>i(s.Textarea,{autosize:!0,minRows:2,maxRows:4,label:"Label Template",sx:{flex:1},...n})}),i(Xm,{})]})]})}function Zm({control:e,watch:t}){return t(["x_axis"]),p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.data_key",control:e,render:({field:n})=>i(W,{label:"Data Field",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"x_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Name",sx:{flex:1},...n})})]}),i(s.Divider,{mb:-15,label:"Tick Label",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.axisLabel.rotate",control:e,render:({field:n})=>i(s.NumberInput,{label:"Rotate",hideControls:!0,min:-90,max:90,rightSection:i(s.Text,{color:"dimmed",children:"degree"}),sx:{width:"48%"},styles:{rightSection:{width:"4em",justifyContent:"flex-end",paddingRight:"6px"}},...n})}),i(v.Controller,{name:"x_axis.axisLabel.formatter",control:e,render:({field:n})=>i(Rn,{...n})})]}),i(v.Controller,{name:"x_axis.axisLabel.overflow",control:e,render:({field:n})=>i(at,{...n})})]})}function Hm({control:e,watch:t}){return t(["data_key"]),i(s.Stack,{children:i(v.Controller,{name:"data_key",control:e,render:({field:n})=>i(W,{label:"Y Axis Data Field",required:!0,sx:{flex:1},...n})})})}function ey({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=y.useMemo(()=>x.defaults({},t,ri),[t]),{control:a,handleSubmit:o,watch:l,getValues:u,reset:c}=v.useForm({defaultValues:r});y.useEffect(()=>{c(r)},[r]),l(["x_axis","data_key","bar","line","dataZoom"]);const d=u(),f=y.useMemo(()=>!x.isEqual(d,t),[d,t]);return p("form",{onSubmit:o(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!f,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"X Axis",orientation:"vertical",styles:{tab:{paddingLeft:"6px",paddingRight:"6px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"X Axis",children:"X Axis"}),i(s.Tabs.Tab,{value:"Y Axis",children:"Y Axis"}),i(s.Tabs.Tab,{value:"Bar",children:"Bar"}),i(s.Tabs.Tab,{value:"Line",children:"Line"}),i(s.Tabs.Tab,{value:"80-20 Line",children:"80-20 Line"}),i(s.Tabs.Tab,{value:"Zooming",children:"Zooming"})]}),i(s.Tabs.Panel,{value:"X Axis",children:i(Zm,{control:a,watch:l})}),i(s.Tabs.Panel,{value:"Y Axis",children:i(Hm,{control:a,watch:l})}),i(s.Tabs.Panel,{value:"Bar",children:i(Ym,{control:a,watch:l})}),i(s.Tabs.Panel,{value:"Line",children:i(Um,{control:a,watch:l})}),i(s.Tabs.Panel,{value:"80-20 Line",children:i(Jm,{control:a,watch:l})}),i(s.Tabs.Panel,{value:"Zooming",children:i(v.Controller,{name:"dataZoom",control:a,render:({field:h})=>i(Zr,{...h})})})]})]})}function ty(e){const{dataZoom:t=qt,...n}=e;return{...n,dataZoom:t}}function ny(e){const{markLine:t=io,...n}=e;return{...n,markLine:t}}function ry(e){const t=x.defaultsDeep({},e.x_axis.axisLabel,{rotate:0,formatter:{...Ue}});return{...e,x_axis:{...e.x_axis,axisLabel:t}}}function iy(e){const{label_formatter:t=ze}=e.bar;return{...e,bar:{...e.bar,label_formatter:t}}}function ay(e){const t={x_axis:{axisLabel:{overflow:{x_axis:{width:80,overflow:"truncate",ellipsis:"..."},tooltip:{width:200,overflow:"break",ellipsis:"..."}}}}};return x.defaultsDeep(t,e)}function sy(e){const t={bar:{nameAlignment:"left"},line:{nameAlignment:"right"}};return x.defaultsDeep(t,e)}function oy(e){console.log(e);const{x_axis:t,tooltip:n}=e.x_axis.axisLabel.overflow,r={x_axis:{axisLabel:{overflow:{on_axis:t,in_tooltip:n}}}};return x.defaultsDeep(r,e)}function ly(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=u=>u&&`${n}.${u}`,{x_axis:a,data_key:o,...l}=e;return{...l,x_axis:{...a,data_key:r(a.data_key)},data_key:r(o)}}catch(n){throw console.error("[Migration failed]",n),n}}class uy extends ye{constructor(){super(...arguments);N(this,"VERSION",9)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,n=>({...n,version:2,config:ty(n.config)})),this.version(3,n=>({...n,version:3,config:ny(n.config)})),this.version(4,n=>({...n,version:4,config:ry(n.config)})),this.version(5,n=>({...n,version:5,config:iy(n.config)})),this.version(6,n=>({...n,version:6,config:ay(n.config)})),this.version(7,n=>({...n,version:7,config:sy(n.config)})),this.version(8,n=>({...n,version:8,config:oy(n.config)})),this.version(9,(n,r)=>({...n,version:9,config:ly(n.config,r)}))}}const cy={displayName:"Pareto Chart",displayGroup:"ECharts-based charts",migrator:new uy,name:"paretoChart",viewRender:jm,configRender:ey,createConfig(){return{version:9,config:x.cloneDeep(ri)}},triggers:[ro]},ii={grid:{axis:"#97999D",scope:"rgba(47,140,192,0.1)",boundary:"#789AB4",reference:"#CFCFD8"},graphics:{compared:{blueDark:"#3E7CAB",blue:"#6398C7",blueLight:"#7CB0DF",blue10:"#6398C71a",redDark:"#AF5F6B",red:"#CD7C88",redLight:"#E794A0",red10:"#CD7C881a"},gradient:{distributed:"linear-gradient(90deg, #1babe6 0%, #2fc8c8 28.63%, #98d44b 48.86%, #ffd057 67.53%, #f5ae53 80.6%, #e76441 91.18%, #b90000 100%)",protrude:"linear-gradient(180deg, #ec73734d 0%, #ec737300 100%)"},level:{lv0:"#6398C7",lv1:"#61B5BF",lv2:"#54D4BB",lv3:"#F5D277",lv4:"#E8BB7F",lv5:"#DB9E84",lv6:"#CB8089"},depth:{dp0:"#FFF7F8",dp1:"#FFE1E1",dp2:"#FDBCBC",dp3:"#F39494",dp4:"#FA4242",dp5:"#E21212"},multiple:{c1:"#66B4DB",c2:"#E46464",c3:"#EEBA00",c4:"#33A678",c5:"#9D88CB",c6:"#939943",c7:"#E49792",c8:"#09A2B8",c9:"#AF5F6B",c10:"#6CA157",c11:"#3E7CAB",c12:"#6398C7",c13:"#E692BA",c14:"#97B566",c15:"#8CACE2",c16:"#CA79AC",c17:"#6DBC80",c18:"#B08F4B",c19:"#39BFA2",c20:"#826BAF"}}};function dy(){ie.registerTheme("merico-light",{color:Object.values(ii.graphics.multiple),visualMap:{color:Object.values(ii.graphics.depth).reverse()}})}function ao(){dy()}function*py(e){const t=ii.graphics[e];if(!t)throw new Error("Invalid palette key provided");const n=Object.values(t);let r=0;for(;;)yield n[r%n.length],r++}function hy(e,t,n){const{label_field:r,value_field:a,color_field:o}=e;if(!r||!a)return{};const l=O(r),u=O(a),c=O(o),d=t[l.queryID].map(h=>({name:h[l.columnKey],value:Number(h[u.columnKey]),color:c.columnKey?h[c.columnKey]:void 0})),f=py("multiple");return{type:"pie",name:"pie",radius:["50%","80%"],itemStyle:{color:({data:h})=>h.color?h.color:f.next().value},label:{position:"outer",alignTo:"edge",formatter:`{name|{b}}
199
- {percentage|{d}%}`,minMargin:5,edgeDistance:10,lineHeight:15,rich:{percentage:{color:"#999"}},margin:20},labelLine:{length:15,length2:0,maxSurfaceAngle:80,showAbove:!0},labelLayout:function(h){const g=h.labelRect.x<n/2,m=h.labelLinePoints;return x.set(m,[2,0],g?h.labelRect.x:h.labelRect.x+h.labelRect.width),{labelLinePoints:m}},data:d,top:10,bottom:10,left:10,right:10}}function fy(e,t,n){return{tooltip:{show:!0,confine:!0},series:hy(e,t,n)}}const so={id:"builtin:echarts:click-pie-chart:series",displayName:"Click Pie Series",nameRender:my,configRender:gy,payload:[{name:"seriesType",description:"'line' | 'scatter' | 'bar'",valueType:"string"},{name:"componentType",description:"'series'",valueType:"string"},{name:"name",description:"Name of the series clicked",valueType:"string"},{name:"color",description:"Color",valueType:"string"},{name:"value",description:"Value of the series clicked",valueType:"number"},{name:"rowData",description:"Data of the row",valueType:"object"}]};function gy(e){return i(B,{})}function my(e){return i(s.Text,{children:"Click chart's series"})}const ai={label_field:"",value_field:"",color_field:""};ie.use([he.PieChart,Pe.CanvasRenderer]);function yy({conf:e,data:t,width:n,height:r,interactionManager:a}){const o=Dt(t,e.label_field),l=Ke(a.triggerManager,so.id),u=y.useCallback(f=>{const h=x.get(o,f.name,{error:"rowData is not found"});l.forEach(g=>{a.runInteraction(g.id,{...f,rowData:h})})},[o,l,a]),c=y.useMemo(()=>fy(e,t,n),[e,t,n]),d=y.useMemo(()=>({click:u}),[u]);return!n||!r||!c.series.name?null:i(Be,{echarts:ie,option:c,style:{width:n,height:r},onEvents:d,notMerge:!0,theme:"merico-light"})}function by({context:e,instance:t}){const n=Xe({vizManager:e.vizManager,instance:t}),{value:r}=R(e.instanceData,"config"),a=y.useMemo(()=>x.defaults({},r,ai),[r]),o=e.data,{width:l,height:u}=e.viewport;return!l||!u?null:i(yy,{conf:a,width:l,height:u,data:o,interactionManager:n})}function vy({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=y.useMemo(()=>x.defaultsDeep({},t,ai),[t]),a=y.useMemo(()=>x.clone(r),[r]),{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});y.useEffect(()=>{d(a)},[a]);const f=c(),h=y.useMemo(()=>!x.isEqual(f,r),[f,r]);return u(["label_field","value_field","color_field"]),i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:l(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Pie Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Stack,{mt:"md",spacing:"xs",p:"md",mb:"sm",sx:{border:"1px solid #eee",borderRadius:"5px"},children:[i(v.Controller,{control:o,name:"label_field",render:({field:g})=>i(W,{label:"Label Key",required:!0,...g})}),i(v.Controller,{control:o,name:"value_field",render:({field:g})=>i(W,{label:"Value Key",required:!0,...g})}),i(v.Controller,{control:o,name:"color_field",render:({field:g})=>i(W,{label:"Color Key",clearable:!0,...g})})]})]})})}function xy(e){const{color_field:t="",...n}=e;return{...n,color_field:t}}function wy(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=u=>u&&`${n}.${u}`,{label_field:a,value_field:o,color_field:l}=e;return{label_field:r(a),value_field:r(o),color_field:r(l)}}catch(n){throw console.error("[Migration failed]",n),n}}class Cy extends ye{constructor(){super(...arguments);N(this,"VERSION",3)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,n=>({...n,version:2,config:xy(n.config)})),this.version(3,(n,r)=>({...n,version:3,config:wy(n.config,r)}))}}const Sy={displayName:"Pie Chart",displayGroup:"ECharts-based charts",migrator:new Cy,name:"pie",viewRender:by,configRender:vy,createConfig(){return{version:3,config:x.cloneDeep(ai)}},triggers:[so]};function _y(e){return i(B,{})}function ky(e){return i(s.Text,{children:"Click heat block"})}const oo={id:"builtin:echarts:click-radar-chart:series",displayName:"Click radar chart series",nameRender:ky,configRender:_y,payload:[{name:"seriesType",description:"'radar'",valueType:"string"},{name:"componentType",description:"'series'",valueType:"string"},{name:"name",description:"Name of the series clicked",valueType:"string"},{name:"color",description:"Color",valueType:"string"},{name:"value",description:"String-typed number, or series' actual value",valueType:"string"},{name:"rowData",description:"Data of the row",valueType:"object"}]},Un={series_name_key:"",additional_series:[],background:{enabled:!0},label:{enabled:!0},dimensions:[]};function lo(e){return e?t=>{try{return Z(t).format(e)}catch(n){return console.error(n),t}}:t=>t}function uo(e){return{show:e.label.enabled,formatter:({dimensionIndex:t,value:n})=>lo(e.dimensions[t].formatter)(n)}}function co(e,t){return t.map(({data_key:n})=>{const r=O(n);return e[r.columnKey]})}function Ty(e,t,n){const r=O(t);return e[r.queryID].map(a=>({value:co(a,n),name:a[r.columnKey]}))}function Dy(e,t){const{series_name_key:n,dimensions:r}=t;return[{type:"radar",name:"main-radar",data:Ty(e,n,r),symbolSize:4,lineStyle:{width:1},emphasis:{lineStyle:{width:4}},areaStyle:t.background.enabled?{opacity:.4}:void 0,label:uo(t)}]}function Iy(e,t){const{additional_series:n,dimensions:r}=t;return n.map(o=>{const l=O(o.name_key),u=O(o.color_key);return{type:"radar",colorBy:"data",data:e[l.queryID].map(f=>{const h=f[l.columnKey],g=f[u.columnKey];return{name:h,value:co(f,r),itemStyle:{color:g}}}),symbolSize:4,lineStyle:{width:1},emphasis:{lineStyle:{width:4}},areaStyle:t.background.enabled?{opacity:.4}:void 0,label:uo(t)}}).flat()}function My(e,t){const n=[...Dy(e,t),...Iy(e,t)];return console.log(n),n}function Ay(e){return({name:t,marker:n,value:r})=>{if(r.length===0)return"";const a=r.map((o,l)=>{const u=e.dimensions[l],c=lo(u.formatter);return`
198
+ `,Xm=()=>{const[e,t]=b.useState(!1);return p(B,{children:[i(s.Button,{variant:"subtle",compact:!0,onClick:()=>t(n=>!n),children:e?"Close":"Click to see params for Label Template"}),i(s.Collapse,{in:e,children:i(kt.Prism,{language:"typescript",noCopy:!0,colorScheme:"dark",children:Km})})]})};function Jm({control:e,watch:t}){return t(["markLine"]),p(s.Stack,{children:[p(s.Stack,{spacing:2,children:[i(s.Text,{size:"sm",children:"Color"}),i(v.Controller,{name:"markLine.color",control:e,render:({field:n})=>i(Ve,{...n})})]}),p(s.Stack,{spacing:4,children:[i(v.Controller,{name:"markLine.label_template",control:e,render:({field:n})=>i(s.Textarea,{autosize:!0,minRows:2,maxRows:4,label:"Label Template",sx:{flex:1},...n})}),i(Xm,{})]})]})}function Zm({control:e,watch:t}){return t(["x_axis"]),p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.data_key",control:e,render:({field:n})=>i(W,{label:"Data Field",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"x_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Name",sx:{flex:1},...n})})]}),i(s.Divider,{mb:-15,label:"Tick Label",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.axisLabel.rotate",control:e,render:({field:n})=>i(s.NumberInput,{label:"Rotate",hideControls:!0,min:-90,max:90,rightSection:i(s.Text,{color:"dimmed",children:"degree"}),sx:{width:"48%"},styles:{rightSection:{width:"4em",justifyContent:"flex-end",paddingRight:"6px"}},...n})}),i(v.Controller,{name:"x_axis.axisLabel.formatter",control:e,render:({field:n})=>i(Rn,{...n})})]}),i(v.Controller,{name:"x_axis.axisLabel.overflow",control:e,render:({field:n})=>i(at,{...n})})]})}function Hm({control:e,watch:t}){return t(["data_key"]),i(s.Stack,{children:i(v.Controller,{name:"data_key",control:e,render:({field:n})=>i(W,{label:"Y Axis Data Field",required:!0,sx:{flex:1},...n})})})}function ey({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=b.useMemo(()=>x.defaults({},t,ri),[t]),{control:a,handleSubmit:o,watch:l,getValues:u,reset:c}=v.useForm({defaultValues:r});b.useEffect(()=>{c(r)},[r]),l(["x_axis","data_key","bar","line","dataZoom"]);const d=u(),f=b.useMemo(()=>!x.isEqual(d,t),[d,t]);return p("form",{onSubmit:o(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!f,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"X Axis",orientation:"vertical",styles:{tab:{paddingLeft:"6px",paddingRight:"6px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"X Axis",children:"X Axis"}),i(s.Tabs.Tab,{value:"Y Axis",children:"Y Axis"}),i(s.Tabs.Tab,{value:"Bar",children:"Bar"}),i(s.Tabs.Tab,{value:"Line",children:"Line"}),i(s.Tabs.Tab,{value:"80-20 Line",children:"80-20 Line"}),i(s.Tabs.Tab,{value:"Zooming",children:"Zooming"})]}),i(s.Tabs.Panel,{value:"X Axis",children:i(Zm,{control:a,watch:l})}),i(s.Tabs.Panel,{value:"Y Axis",children:i(Hm,{control:a,watch:l})}),i(s.Tabs.Panel,{value:"Bar",children:i(Ym,{control:a,watch:l})}),i(s.Tabs.Panel,{value:"Line",children:i(Um,{control:a,watch:l})}),i(s.Tabs.Panel,{value:"80-20 Line",children:i(Jm,{control:a,watch:l})}),i(s.Tabs.Panel,{value:"Zooming",children:i(v.Controller,{name:"dataZoom",control:a,render:({field:h})=>i(Zr,{...h})})})]})]})}function ty(e){const{dataZoom:t=qt,...n}=e;return{...n,dataZoom:t}}function ny(e){const{markLine:t=io,...n}=e;return{...n,markLine:t}}function ry(e){const t=x.defaultsDeep({},e.x_axis.axisLabel,{rotate:0,formatter:{...Ue}});return{...e,x_axis:{...e.x_axis,axisLabel:t}}}function iy(e){const{label_formatter:t=ze}=e.bar;return{...e,bar:{...e.bar,label_formatter:t}}}function ay(e){const t={x_axis:{axisLabel:{overflow:{x_axis:{width:80,overflow:"truncate",ellipsis:"..."},tooltip:{width:200,overflow:"break",ellipsis:"..."}}}}};return x.defaultsDeep(t,e)}function sy(e){const t={bar:{nameAlignment:"left"},line:{nameAlignment:"right"}};return x.defaultsDeep(t,e)}function oy(e){console.log(e);const{x_axis:t,tooltip:n}=e.x_axis.axisLabel.overflow,r={x_axis:{axisLabel:{overflow:{on_axis:t,in_tooltip:n}}}};return x.defaultsDeep(r,e)}function ly(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=u=>u&&`${n}.${u}`,{x_axis:a,data_key:o,...l}=e;return{...l,x_axis:{...a,data_key:r(a.data_key)},data_key:r(o)}}catch(n){throw console.error("[Migration failed]",n),n}}class uy extends ye{constructor(){super(...arguments);N(this,"VERSION",9)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,n=>({...n,version:2,config:ty(n.config)})),this.version(3,n=>({...n,version:3,config:ny(n.config)})),this.version(4,n=>({...n,version:4,config:ry(n.config)})),this.version(5,n=>({...n,version:5,config:iy(n.config)})),this.version(6,n=>({...n,version:6,config:ay(n.config)})),this.version(7,n=>({...n,version:7,config:sy(n.config)})),this.version(8,n=>({...n,version:8,config:oy(n.config)})),this.version(9,(n,r)=>({...n,version:9,config:ly(n.config,r)}))}}const cy={displayName:"Pareto Chart",displayGroup:"ECharts-based charts",migrator:new uy,name:"paretoChart",viewRender:jm,configRender:ey,createConfig(){return{version:9,config:x.cloneDeep(ri)}},triggers:[ro]},ii={grid:{axis:"#97999D",scope:"rgba(47,140,192,0.1)",boundary:"#789AB4",reference:"#CFCFD8"},graphics:{compared:{blueDark:"#3E7CAB",blue:"#6398C7",blueLight:"#7CB0DF",blue10:"#6398C71a",redDark:"#AF5F6B",red:"#CD7C88",redLight:"#E794A0",red10:"#CD7C881a"},gradient:{distributed:"linear-gradient(90deg, #1babe6 0%, #2fc8c8 28.63%, #98d44b 48.86%, #ffd057 67.53%, #f5ae53 80.6%, #e76441 91.18%, #b90000 100%)",protrude:"linear-gradient(180deg, #ec73734d 0%, #ec737300 100%)"},level:{lv0:"#6398C7",lv1:"#61B5BF",lv2:"#54D4BB",lv3:"#F5D277",lv4:"#E8BB7F",lv5:"#DB9E84",lv6:"#CB8089"},depth:{dp0:"#FFF7F8",dp1:"#FFE1E1",dp2:"#FDBCBC",dp3:"#F39494",dp4:"#FA4242",dp5:"#E21212"},multiple:{c1:"#66B4DB",c2:"#E46464",c3:"#EEBA00",c4:"#33A678",c5:"#9D88CB",c6:"#939943",c7:"#E49792",c8:"#09A2B8",c9:"#AF5F6B",c10:"#6CA157",c11:"#3E7CAB",c12:"#6398C7",c13:"#E692BA",c14:"#97B566",c15:"#8CACE2",c16:"#CA79AC",c17:"#6DBC80",c18:"#B08F4B",c19:"#39BFA2",c20:"#826BAF"}}};function dy(){ie.registerTheme("merico-light",{color:Object.values(ii.graphics.multiple),visualMap:{color:Object.values(ii.graphics.depth).reverse()}})}function ao(){dy()}function*py(e){const t=ii.graphics[e];if(!t)throw new Error("Invalid palette key provided");const n=Object.values(t);let r=0;for(;;)yield n[r%n.length],r++}function hy(e,t,n){const{label_field:r,value_field:a,color_field:o}=e;if(!r||!a)return{};const l=O(r),u=O(a),c=O(o),d=t[l.queryID].map(h=>({name:h[l.columnKey],value:Number(h[u.columnKey]),color:c.columnKey?h[c.columnKey]:void 0})),f=py("multiple");return{type:"pie",name:"pie",radius:["50%","80%"],itemStyle:{color:({data:h})=>h.color?h.color:f.next().value},label:{position:"outer",alignTo:"edge",formatter:`{name|{b}}
199
+ {percentage|{d}%}`,minMargin:5,edgeDistance:10,lineHeight:15,rich:{percentage:{color:"#999"}},margin:20},labelLine:{length:15,length2:0,maxSurfaceAngle:80,showAbove:!0},labelLayout:function(h){const g=h.labelRect.x<n/2,m=h.labelLinePoints;return x.set(m,[2,0],g?h.labelRect.x:h.labelRect.x+h.labelRect.width),{labelLinePoints:m}},data:d,top:10,bottom:10,left:10,right:10}}function fy(e,t,n){return{tooltip:{show:!0,confine:!0},series:hy(e,t,n)}}const so={id:"builtin:echarts:click-pie-chart:series",displayName:"Click Pie Series",nameRender:my,configRender:gy,payload:[{name:"seriesType",description:"'line' | 'scatter' | 'bar'",valueType:"string"},{name:"componentType",description:"'series'",valueType:"string"},{name:"name",description:"Name of the series clicked",valueType:"string"},{name:"color",description:"Color",valueType:"string"},{name:"value",description:"Value of the series clicked",valueType:"number"},{name:"rowData",description:"Data of the row",valueType:"object"}]};function gy(e){return i(B,{})}function my(e){return i(s.Text,{children:"Click chart's series"})}const ai={label_field:"",value_field:"",color_field:""};ie.use([he.PieChart,Pe.CanvasRenderer]);function yy({conf:e,data:t,width:n,height:r,interactionManager:a}){const o=Dt(t,e.label_field),l=Ke(a.triggerManager,so.id),u=b.useCallback(f=>{const h=x.get(o,f.name,{error:"rowData is not found"});l.forEach(g=>{a.runInteraction(g.id,{...f,rowData:h})})},[o,l,a]),c=b.useMemo(()=>fy(e,t,n),[e,t,n]),d=b.useMemo(()=>({click:u}),[u]);return!n||!r||!c.series.name?null:i(Be,{echarts:ie,option:c,style:{width:n,height:r},onEvents:d,notMerge:!0,theme:"merico-light"})}function by({context:e,instance:t}){const n=Xe({vizManager:e.vizManager,instance:t}),{value:r}=R(e.instanceData,"config"),a=b.useMemo(()=>x.defaults({},r,ai),[r]),o=e.data,{width:l,height:u}=e.viewport;return!l||!u?null:i(yy,{conf:a,width:l,height:u,data:o,interactionManager:n})}function vy({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=b.useMemo(()=>x.defaultsDeep({},t,ai),[t]),a=b.useMemo(()=>x.clone(r),[r]),{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});b.useEffect(()=>{d(a)},[a]);const f=c(),h=b.useMemo(()=>!x.isEqual(f,r),[f,r]);return u(["label_field","value_field","color_field"]),i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:l(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Pie Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Stack,{mt:"md",spacing:"xs",p:"md",mb:"sm",sx:{border:"1px solid #eee",borderRadius:"5px"},children:[i(v.Controller,{control:o,name:"label_field",render:({field:g})=>i(W,{label:"Label Key",required:!0,...g})}),i(v.Controller,{control:o,name:"value_field",render:({field:g})=>i(W,{label:"Value Key",required:!0,...g})}),i(v.Controller,{control:o,name:"color_field",render:({field:g})=>i(W,{label:"Color Key",clearable:!0,...g})})]})]})})}function xy(e){const{color_field:t="",...n}=e;return{...n,color_field:t}}function wy(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=u=>u&&`${n}.${u}`,{label_field:a,value_field:o,color_field:l}=e;return{label_field:r(a),value_field:r(o),color_field:r(l)}}catch(n){throw console.error("[Migration failed]",n),n}}class Cy extends ye{constructor(){super(...arguments);N(this,"VERSION",3)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,n=>({...n,version:2,config:xy(n.config)})),this.version(3,(n,r)=>({...n,version:3,config:wy(n.config,r)}))}}const Sy={displayName:"Pie Chart",displayGroup:"ECharts-based charts",migrator:new Cy,name:"pie",viewRender:by,configRender:vy,createConfig(){return{version:3,config:x.cloneDeep(ai)}},triggers:[so]};function _y(e){return i(B,{})}function ky(e){return i(s.Text,{children:"Click heat block"})}const oo={id:"builtin:echarts:click-radar-chart:series",displayName:"Click radar chart series",nameRender:ky,configRender:_y,payload:[{name:"seriesType",description:"'radar'",valueType:"string"},{name:"componentType",description:"'series'",valueType:"string"},{name:"name",description:"Name of the series clicked",valueType:"string"},{name:"color",description:"Color",valueType:"string"},{name:"value",description:"String-typed number, or series' actual value",valueType:"string"},{name:"rowData",description:"Data of the row",valueType:"object"}]},Un={series_name_key:"",additional_series:[],background:{enabled:!0},label:{enabled:!0},dimensions:[]};function lo(e){return e?t=>{try{return Z(t).format(e)}catch(n){return console.error(n),t}}:t=>t}function uo(e){return{show:e.label.enabled,formatter:({dimensionIndex:t,value:n})=>lo(e.dimensions[t].formatter)(n)}}function co(e,t){return t.map(({data_key:n})=>{const r=O(n);return e[r.columnKey]})}function Ty(e,t,n){const r=O(t);return e[r.queryID].map(a=>({value:co(a,n),name:a[r.columnKey]}))}function Dy(e,t){const{series_name_key:n,dimensions:r}=t;return[{type:"radar",name:"main-radar",data:Ty(e,n,r),symbolSize:4,lineStyle:{width:1},emphasis:{lineStyle:{width:4}},areaStyle:t.background.enabled?{opacity:.4}:void 0,label:uo(t)}]}function Iy(e,t){const{additional_series:n,dimensions:r}=t;return n.map(o=>{const l=O(o.name_key),u=O(o.color_key);return{type:"radar",colorBy:"data",data:e[l.queryID].map(f=>{const h=f[l.columnKey],g=f[u.columnKey];return{name:h,value:co(f,r),itemStyle:{color:g}}}),symbolSize:4,lineStyle:{width:1},emphasis:{lineStyle:{width:4}},areaStyle:t.background.enabled?{opacity:.4}:void 0,label:uo(t)}}).flat()}function My(e,t){const n=[...Dy(e,t),...Iy(e,t)];return console.log(n),n}function Ay(e){return({name:t,marker:n,value:r})=>{if(r.length===0)return"";const a=r.map((o,l)=>{const u=e.dimensions[l],c=lo(u.formatter);return`
200
200
  <tr>
201
201
  <td style="padding-left: 18px;">${u.name}</td>
202
202
  <td style="text-align: right; "><strong>${c(o)}</strong></td>
@@ -224,7 +224,7 @@ Check the top-level render call using <`+V+">.")}return E}}function Su(S,E){{if(
224
224
  ${a.join("")}
225
225
  </tbody>
226
226
  </table>
227
- `}}const zy={legend:{show:!0,bottom:0,left:0},tooltip:{trigger:"item"}},Ey=["#66B4DB","#39BFA2","#E46464","#33A678","#EEBA00","#9D88CB","#939943","#E49792","#09A2B8","#AF5F6B","#6CA157","#09A2B8","#6398C7","#E692BA","#97B566","#8CACE2","#CA79AC","#6DBC80","#B08F4B","#826BAF"];function $y(e,t){const{series_name_key:n,dimensions:r,additional_series:a}=e;if(!n||r.length===0)return{};const l={radar:{indicator:r.map(({name:u,max:c})=>({name:u,max:c})),splitArea:{show:!1}},tooltip:{confine:!0,backgroundColor:"rgba(255,255,255,0.6)",formatter:Ay(e)},legend:{show:!0,bottom:0,left:"center",type:"scroll"},series:My(t,e),color:Ey};return x.merge({},zy,l)}ie.use([he.RadarChart,q.GridComponent,q.LegendComponent,q.TooltipComponent,Pe.CanvasRenderer]);function Ly({conf:e,data:t,width:n,height:r,interactionManager:a,variables:o}){const l=y.useMemo(()=>{const{queryID:h,columnKey:g}=O(e.series_name_key),m=x.keyBy(t[h],g),C=e.additional_series.reduce((w,_)=>{const D=O(_.name_key),M=x.keyBy(t[D.queryID],D.columnKey);return{...w,...M}},m);return{...m,...C}},[t,e.series_name_key,e.additional_series]),u=Ke(a.triggerManager,oo.id),c=y.useCallback(h=>{const g=x.get(l,h.name,{error:"rowData is not found"});u.forEach(m=>{a.runInteraction(m.id,{...h,rowData:g})})},[l,u,a]),d=y.useMemo(()=>({click:c}),[c]),f=y.useMemo(()=>$y(x.defaultsDeep({},e,Un),t),[e,t]);return!n||!r?null:i(Be,{echarts:ie,option:f,style:{width:n,height:r},onEvents:d,notMerge:!0,theme:"merico-light"})}function Oy({context:e,instance:t}){const n=Xe({vizManager:e.vizManager,instance:t}),{value:r}=R(e.instanceData,"config"),{variables:a}=e,o=y.useMemo(()=>x.defaults({},r,Un),[r]),l=e.data,{width:u,height:c}=e.viewport;return!u||!c||!o||x.isEmpty(o==null?void 0:o.dimensions)?null:i(Ly,{variables:a,width:u,height:c,data:l,conf:o,interactionManager:n})}function Py({control:e,index:t,remove:n}){return p(s.Stack,{my:0,p:"md",pr:40,sx:{border:"1px solid #eee",position:"relative"},children:[i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:`additional_series.${t}.name_key`,control:e,render:({field:r})=>i(W,{label:"Series Name Key",required:!0,sx:{flex:1},...r})})}),i(s.Stack,{children:i(v.Controller,{name:`additional_series.${t}.color_key`,control:e,render:({field:r})=>i(W,{label:"Color Key",required:!0,clearable:!0,sx:{flex:1},...r})})}),i(s.Button,{mt:20,leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),disabled:t===0,children:"Delete"})]},t)}function By({control:e,watch:t}){const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"additional_series"}),o=t("additional_series"),l=n.map((g,m)=>({...g,...o[m]})),u=()=>{const g=new Date().getTime().toString();r({id:g,name_key:"",color_key:""})},c=x.get(l,"0.id",null),[d,f]=y.useState(c);y.useEffect(()=>{f(g=>g||c)},[c]);const h=g=>{a(g);const m=x.get(l,"0.id",null);f(m)};return p(B,{children:[p(s.Alert,{icon:i($.IconInfoCircle,{size:16}),title:"Additional Series",children:["By setting ",i(s.Mark,{children:"Series Name Key"}),", you may add series from more queries to the chart."]}),p(s.Tabs,{value:d,onTabChange:f,styles:{tab:{paddingBottom:"0px"},panel:{padding:"0px"}},children:[p(s.Tabs.List,{children:[l.map((g,m)=>i(s.Tabs.Tab,{value:g.id,children:m+1},g.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i($.IconPlus,{size:18,color:"#228be6"})})]}),l.map((g,m)=>i(s.Tabs.Panel,{value:g.id,children:i(Py,{control:e,index:m,remove:h})},m))]})]})}function Vy({control:e,index:t,remove:n}){return p(s.Stack,{my:0,p:"md",pr:40,sx:{border:"1px solid #eee",position:"relative"},children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`dimensions.${t}.name`,control:e,render:({field:r})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:`dimensions.${t}.data_key`,control:e,render:({field:r})=>i(W,{label:"Data Key",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:`dimensions.${t}.max`,control:e,render:({field:r})=>i(s.NumberInput,{label:"Max",hideControls:!0,required:!0,sx:{flex:1},...r})})]}),p(s.Stack,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Value Formatter",labelPosition:"center"}),i(v.Controller,{name:`dimensions.${t}.formatter`,control:e,render:({field:r})=>i(We,{...r})})]}),i(s.Button,{mt:20,leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),disabled:t===0,children:"Delete this Metric"})]},t)}function Ny({control:e,watch:t}){const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"dimensions"}),o=t("dimensions"),l=n.map((g,m)=>({...g,...o[m]})),u=()=>{const g=new Date().getTime().toString();r({id:g,name:g,data_key:"",max:100,formatter:ze})},c=x.get(l,"0.id",null),[d,f]=y.useState(c);y.useEffect(()=>{f(g=>g||c)},[c]);const h=g=>{a(g);const m=x.get(l,"0.id",null);f(m)};return i(B,{children:p(s.Tabs,{value:d,onTabChange:f,styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px"}},children:[p(s.Tabs.List,{children:[l.map((g,m)=>i(s.Tabs.Tab,{value:g.id,children:g.name?g.name:m+1},m)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i($.IconPlus,{size:18,color:"#228be6"})})]}),l.map((g,m)=>i(s.Tabs.Panel,{value:g.id,children:i(Vy,{control:e,index:m,remove:h})},m))]})})}function qy({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=y.useMemo(()=>x.defaultsDeep({},t,Un),[t]),{control:a,handleSubmit:o,watch:l,getValues:u,reset:c}=v.useForm({defaultValues:r});y.useEffect(()=>{c(r)},[r]),l(["series_name_key","background","label"]);const d=u(),f=y.useMemo(()=>!x.isEqual(d,r),[d,r]);return i("form",{onSubmit:o(n),children:p(s.Stack,{spacing:"xs",children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Radar Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!f,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"series",children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"series",children:"Series"}),i(s.Tabs.Tab,{value:"metrics",children:"Metrics"}),i(s.Tabs.Tab,{value:"style",children:"Style"}),i(s.Tabs.Tab,{value:"additional_series",ml:"auto",children:"Additional Series"})]}),i(s.Tabs.Panel,{value:"series",p:"md",children:i(v.Controller,{name:"series_name_key",control:a,render:({field:h})=>i(W,{label:"Series Name Field",required:!0,sx:{flex:1},...h})})}),i(s.Tabs.Panel,{value:"metrics",p:"md",children:i(Ny,{control:a,watch:l})}),i(s.Tabs.Panel,{value:"style",p:"md",children:p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"background.enabled",control:a,render:({field:h})=>i(s.Checkbox,{label:"Show background",checked:h.value,onChange:g=>h.onChange(g.currentTarget.checked)})}),i(v.Controller,{name:"label.enabled",control:a,render:({field:h})=>i(s.Checkbox,{label:"Show value label",checked:h.value,onChange:g=>h.onChange(g.currentTarget.checked)})})]})}),i(s.Tabs.Panel,{value:"additional_series",p:"md",children:i(By,{control:a,watch:l})})]})]})})}function Fy(e){const{dimensions:t=[],...n}=e;function r({name:a="",data_key:o="",max:l=10,formatter:u=ze}){return{name:a,data_key:o,max:l,formatter:u}}return{...n,dimensions:t.map(r)}}function Gy(e){const{dimensions:t=[],...n}=e;return{...n,dimensions:t.map(r=>({...r,id:r.id??r.name}))}}function Wy(e){const t={background:{enabled:!0},label:{enabled:!0}};return x.defaultsDeep(t,e)}function jy(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=u=>u&&`${n}.${u}`,{series_name_key:a,dimensions:o,...l}=e;return{...l,series_name_key:r(a),dimensions:o.map(u=>({...u,data_key:r(u.data_key)}))}}catch(n){throw console.error("[Migration failed]",n),n}}function Ry(e){const t={additionalSeries:[]};return x.defaultsDeep(t,e)}class Yy extends ye{constructor(){super(...arguments);N(this,"VERSION",6)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,n=>{const{config:r}=n;return{...n,version:2,config:Fy(r)}}),this.version(3,n=>{const{config:r}=n;return{...n,version:3,config:Gy(r)}}),this.version(4,n=>{const{config:r}=n;return{...n,version:4,config:Wy(r)}}),this.version(5,(n,r)=>{const{config:a}=n;return{...n,version:5,config:jy(a,r)}}),this.version(6,n=>{const{config:r}=n;return{...n,version:6,config:Ry(r)}})}}const Qy={displayName:"Radar Chart",displayGroup:"ECharts-based charts",migrator:new Yy,name:"radar",viewRender:Oy,configRender:qy,createConfig:()=>({version:6,config:Un}),triggers:[oo]};function Uy(e,t){const{plot:n,transform:r}=e.regression;return t.map(a=>({...n,id:`reg-for-${a.name}`,name:a.name,data:Yn(r,a.data),color:a.color,showSymbol:!1,smooth:!0,tooltip:{show:!1},custom:{type:"regression-line",targetSeries:a.name}}))}function po(e,t){const n=O(e.x_axis.data_key),r=O(e.regression.y_axis_data_key);return x.uniqBy(t.map(a=>[a[n.columnKey],a[r.columnKey]]),0)}function Ky(e,t){const{plot:n,transform:r}=e.regression,a=po(e,t);return[{type:"scatter",name:e.y_axis.name,data:a,symbolSize:4,color:"red",markLine:{...n,data:[Yn(r,a)],color:"blue",smooth:!0,silent:!0,symbol:["none","none"]}}]}function Xy(e,t){const{plot:n,transform:r,group_by_key:a}=e.regression,o=O(a),l=x.groupBy(t,o.columnKey);return Object.entries(l).map(([u,c])=>{const d=po(e,c);return{type:"scatter",name:u,data:d,symbolSize:4,markLine:{...n,data:[Yn(r,d)],smooth:!0,silent:!0,symbol:["none","none"]}}})}function Jy(e,t){if(t.length===0)return[];const{group_by_key:n}=e.regression;return n?Xy(e,t):Ky(e,t)}function Zy(e){return Array.isArray(e)||(e=[e]),e.map(t=>({marker:t.marker,label:t.seriesName,x:t.value[0],y:t.value[1]}))}function Hy(e){return{confine:!0,trigger:"axis",formatter:t=>{const n=Zy(t);return n.length===0?"":`
227
+ `}}const zy={legend:{show:!0,bottom:0,left:0},tooltip:{trigger:"item"}},Ey=["#66B4DB","#39BFA2","#E46464","#33A678","#EEBA00","#9D88CB","#939943","#E49792","#09A2B8","#AF5F6B","#6CA157","#09A2B8","#6398C7","#E692BA","#97B566","#8CACE2","#CA79AC","#6DBC80","#B08F4B","#826BAF"];function $y(e,t){const{series_name_key:n,dimensions:r,additional_series:a}=e;if(!n||r.length===0)return{};const l={radar:{indicator:r.map(({name:u,max:c})=>({name:u,max:c})),splitArea:{show:!1}},tooltip:{confine:!0,backgroundColor:"rgba(255,255,255,0.6)",formatter:Ay(e)},legend:{show:!0,bottom:0,left:"center",type:"scroll"},series:My(t,e),color:Ey};return x.merge({},zy,l)}ie.use([he.RadarChart,q.GridComponent,q.LegendComponent,q.TooltipComponent,Pe.CanvasRenderer]);function Ly({conf:e,data:t,width:n,height:r,interactionManager:a,variables:o}){const l=b.useMemo(()=>{const{queryID:h,columnKey:g}=O(e.series_name_key),m=x.keyBy(t[h],g),C=e.additional_series.reduce((w,_)=>{const D=O(_.name_key),M=x.keyBy(t[D.queryID],D.columnKey);return{...w,...M}},m);return{...m,...C}},[t,e.series_name_key,e.additional_series]),u=Ke(a.triggerManager,oo.id),c=b.useCallback(h=>{const g=x.get(l,h.name,{error:"rowData is not found"});u.forEach(m=>{a.runInteraction(m.id,{...h,rowData:g})})},[l,u,a]),d=b.useMemo(()=>({click:c}),[c]),f=b.useMemo(()=>$y(x.defaultsDeep({},e,Un),t),[e,t]);return!n||!r?null:i(Be,{echarts:ie,option:f,style:{width:n,height:r},onEvents:d,notMerge:!0,theme:"merico-light"})}function Oy({context:e,instance:t}){const n=Xe({vizManager:e.vizManager,instance:t}),{value:r}=R(e.instanceData,"config"),{variables:a}=e,o=b.useMemo(()=>x.defaults({},r,Un),[r]),l=e.data,{width:u,height:c}=e.viewport;return!u||!c||!o||x.isEmpty(o==null?void 0:o.dimensions)?null:i(Ly,{variables:a,width:u,height:c,data:l,conf:o,interactionManager:n})}function Py({control:e,index:t,remove:n}){return p(s.Stack,{my:0,p:"md",pr:40,sx:{border:"1px solid #eee",position:"relative"},children:[i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:`additional_series.${t}.name_key`,control:e,render:({field:r})=>i(W,{label:"Series Name Key",required:!0,sx:{flex:1},...r})})}),i(s.Stack,{children:i(v.Controller,{name:`additional_series.${t}.color_key`,control:e,render:({field:r})=>i(W,{label:"Color Key",required:!0,clearable:!0,sx:{flex:1},...r})})}),i(s.Button,{mt:20,leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),disabled:t===0,children:"Delete"})]},t)}function By({control:e,watch:t}){const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"additional_series"}),o=t("additional_series"),l=n.map((g,m)=>({...g,...o[m]})),u=()=>{const g=new Date().getTime().toString();r({id:g,name_key:"",color_key:""})},c=x.get(l,"0.id",null),[d,f]=b.useState(c);b.useEffect(()=>{f(g=>g||c)},[c]);const h=g=>{a(g);const m=x.get(l,"0.id",null);f(m)};return p(B,{children:[p(s.Alert,{icon:i($.IconInfoCircle,{size:16}),title:"Additional Series",children:["By setting ",i(s.Mark,{children:"Series Name Key"}),", you may add series from more queries to the chart."]}),p(s.Tabs,{value:d,onTabChange:f,styles:{tab:{paddingBottom:"0px"},panel:{padding:"0px"}},children:[p(s.Tabs.List,{children:[l.map((g,m)=>i(s.Tabs.Tab,{value:g.id,children:m+1},g.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i($.IconPlus,{size:18,color:"#228be6"})})]}),l.map((g,m)=>i(s.Tabs.Panel,{value:g.id,children:i(Py,{control:e,index:m,remove:h})},m))]})]})}function Vy({control:e,index:t,remove:n}){return p(s.Stack,{my:0,p:"md",pr:40,sx:{border:"1px solid #eee",position:"relative"},children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`dimensions.${t}.name`,control:e,render:({field:r})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:`dimensions.${t}.data_key`,control:e,render:({field:r})=>i(W,{label:"Data Key",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:`dimensions.${t}.max`,control:e,render:({field:r})=>i(s.NumberInput,{label:"Max",hideControls:!0,required:!0,sx:{flex:1},...r})})]}),p(s.Stack,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Value Formatter",labelPosition:"center"}),i(v.Controller,{name:`dimensions.${t}.formatter`,control:e,render:({field:r})=>i(je,{...r})})]}),i(s.Button,{mt:20,leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),disabled:t===0,children:"Delete this Metric"})]},t)}function Ny({control:e,watch:t}){const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"dimensions"}),o=t("dimensions"),l=n.map((g,m)=>({...g,...o[m]})),u=()=>{const g=new Date().getTime().toString();r({id:g,name:g,data_key:"",max:100,formatter:ze})},c=x.get(l,"0.id",null),[d,f]=b.useState(c);b.useEffect(()=>{f(g=>g||c)},[c]);const h=g=>{a(g);const m=x.get(l,"0.id",null);f(m)};return i(B,{children:p(s.Tabs,{value:d,onTabChange:f,styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px"}},children:[p(s.Tabs.List,{children:[l.map((g,m)=>i(s.Tabs.Tab,{value:g.id,children:g.name?g.name:m+1},m)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i($.IconPlus,{size:18,color:"#228be6"})})]}),l.map((g,m)=>i(s.Tabs.Panel,{value:g.id,children:i(Vy,{control:e,index:m,remove:h})},m))]})})}function qy({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=b.useMemo(()=>x.defaultsDeep({},t,Un),[t]),{control:a,handleSubmit:o,watch:l,getValues:u,reset:c}=v.useForm({defaultValues:r});b.useEffect(()=>{c(r)},[r]),l(["series_name_key","background","label"]);const d=u(),f=b.useMemo(()=>!x.isEqual(d,r),[d,r]);return i("form",{onSubmit:o(n),children:p(s.Stack,{spacing:"xs",children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Radar Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!f,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"series",children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"series",children:"Series"}),i(s.Tabs.Tab,{value:"metrics",children:"Metrics"}),i(s.Tabs.Tab,{value:"style",children:"Style"}),i(s.Tabs.Tab,{value:"additional_series",ml:"auto",children:"Additional Series"})]}),i(s.Tabs.Panel,{value:"series",p:"md",children:i(v.Controller,{name:"series_name_key",control:a,render:({field:h})=>i(W,{label:"Series Name Field",required:!0,sx:{flex:1},...h})})}),i(s.Tabs.Panel,{value:"metrics",p:"md",children:i(Ny,{control:a,watch:l})}),i(s.Tabs.Panel,{value:"style",p:"md",children:p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"background.enabled",control:a,render:({field:h})=>i(s.Checkbox,{label:"Show background",checked:h.value,onChange:g=>h.onChange(g.currentTarget.checked)})}),i(v.Controller,{name:"label.enabled",control:a,render:({field:h})=>i(s.Checkbox,{label:"Show value label",checked:h.value,onChange:g=>h.onChange(g.currentTarget.checked)})})]})}),i(s.Tabs.Panel,{value:"additional_series",p:"md",children:i(By,{control:a,watch:l})})]})]})})}function Fy(e){const{dimensions:t=[],...n}=e;function r({name:a="",data_key:o="",max:l=10,formatter:u=ze}){return{name:a,data_key:o,max:l,formatter:u}}return{...n,dimensions:t.map(r)}}function Gy(e){const{dimensions:t=[],...n}=e;return{...n,dimensions:t.map(r=>({...r,id:r.id??r.name}))}}function Wy(e){const t={background:{enabled:!0},label:{enabled:!0}};return x.defaultsDeep(t,e)}function jy(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=u=>u&&`${n}.${u}`,{series_name_key:a,dimensions:o,...l}=e;return{...l,series_name_key:r(a),dimensions:o.map(u=>({...u,data_key:r(u.data_key)}))}}catch(n){throw console.error("[Migration failed]",n),n}}function Ry(e){const t={additionalSeries:[]};return x.defaultsDeep(t,e)}class Yy extends ye{constructor(){super(...arguments);N(this,"VERSION",6)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,n=>{const{config:r}=n;return{...n,version:2,config:Fy(r)}}),this.version(3,n=>{const{config:r}=n;return{...n,version:3,config:Gy(r)}}),this.version(4,n=>{const{config:r}=n;return{...n,version:4,config:Wy(r)}}),this.version(5,(n,r)=>{const{config:a}=n;return{...n,version:5,config:jy(a,r)}}),this.version(6,n=>{const{config:r}=n;return{...n,version:6,config:Ry(r)}})}}const Qy={displayName:"Radar Chart",displayGroup:"ECharts-based charts",migrator:new Yy,name:"radar",viewRender:Oy,configRender:qy,createConfig:()=>({version:6,config:Un}),triggers:[oo]};function Uy(e,t){const{plot:n,transform:r}=e.regression;return t.map(a=>({...n,id:`reg-for-${a.name}`,name:a.name,data:Yn(r,a.data),color:a.color,showSymbol:!1,smooth:!0,tooltip:{show:!1},custom:{type:"regression-line",targetSeries:a.name}}))}function po(e,t){const n=O(e.x_axis.data_key),r=O(e.regression.y_axis_data_key);return x.uniqBy(t.map(a=>[a[n.columnKey],a[r.columnKey]]),0)}function Ky(e,t){const{plot:n,transform:r}=e.regression,a=po(e,t);return[{type:"scatter",name:e.y_axis.name,data:a,symbolSize:4,color:"red",markLine:{...n,data:[Yn(r,a)],color:"blue",smooth:!0,silent:!0,symbol:["none","none"]}}]}function Xy(e,t){const{plot:n,transform:r,group_by_key:a}=e.regression,o=O(a),l=x.groupBy(t,o.columnKey);return Object.entries(l).map(([u,c])=>{const d=po(e,c);return{type:"scatter",name:u,data:d,symbolSize:4,markLine:{...n,data:[Yn(r,d)],smooth:!0,silent:!0,symbol:["none","none"]}}})}function Jy(e,t){if(t.length===0)return[];const{group_by_key:n}=e.regression;return n?Xy(e,t):Ky(e,t)}function Zy(e){return Array.isArray(e)||(e=[e]),e.map(t=>({marker:t.marker,label:t.seriesName,x:t.value[0],y:t.value[1]}))}function Hy(e){return{confine:!0,trigger:"axis",formatter:t=>{const n=Zy(t);return n.length===0?"":`
228
228
  <table style="width: auto">
229
229
  <thead>
230
230
  <tr>
@@ -243,16 +243,16 @@ Check the top-level render call using <`+V+">.")}return E}}function Su(S,E){{if(
243
243
  </tr>
244
244
  </tbody>
245
245
  </table>
246
- `}}}function ho({enabled:e,func_content:t}){return(n,r)=>{if(!e)return n;try{return new Function(`return ${t}`)()(n,r)}catch(a){return console.error(`[getEchartsXAxisLabel] failed parsing custom function, error: ${a.message}`),n}}}function eb(e){const{overflow:t,format:n,formatter:r,...a}=e.x_axis.axisLabel,o=rt(t.on_axis);return{type:"value",name:e.x_axis.name??"",nameLocation:"middle",nameGap:25,axisTick:{show:!0,alignWithLabel:!0},axisLabel:{...a,...o,formatter:(l,u)=>{let c=l;try{c=Z(l).format(n)}catch{}return ho(r)(c,u)}}}}const tb={tooltip:{trigger:"axis"},grid:{top:50,left:5,right:10,bottom:20,containLabel:!0},dataZoom:[{type:"inside",xAxisIndex:[0]},{type:"inside",yAxisIndex:[0]}]};function nb(e,t){const n=Jy(e,t),r=Uy(e,n),a={xAxis:eb(e),yAxis:{name:e.y_axis.name??"",nameLocation:"end",nameTextStyle:{align:"left"},nameGap:5,axisLine:{show:!0}},series:[...n,...r],tooltip:Hy(e),legend:{show:!0,type:"scroll",orient:"horizontal",align:"left",right:0,top:0,left:"auto",itemGap:20,padding:[4,8,0,140],data:n.map(o=>o.name)}};return x.defaultsDeep({},a,tb)}function Kn(e,t,n){return 1-(1-e)*(t-1)/(t-n-1)}function rb(e,t,n,r){const{x_axis:a,y_axis:o}=r,l=yt.regressionLinear()(n),{a:u,b:c,rSquared:d}=l;return{name:e,expression:p(s.Group,{position:"center",noWrap:!0,spacing:10,children:[i(s.Text,{children:o.name}),i(s.Text,{children:"="}),i(s.Text,{weight:"bold",color:"red",children:Z(c).format({mantissa:2,trimMantissa:!0})}),i(s.Text,{children:"+"}),i(s.Text,{weight:"bold",color:"red",children:Z(u).format({mantissa:2,trimMantissa:!0})}),i(s.Text,{children:"×"}),i(s.Text,{children:a.name})]}),rSquared:d,adjustedRSquared:Kn(d,t.length,1)}}function ib(e,t,n,r){const{x_axis:a,y_axis:o}=r,{a:l,b:u,rSquared:c}=yt.regressionExp()(n);return{name:e,expression:p(s.Group,{position:"center",noWrap:!0,spacing:10,children:[i(s.Text,{children:o.name}),i(s.Text,{children:"="}),i(s.Text,{weight:"bold",color:"gray",children:l}),i(s.Text,{children:"×"}),p(s.Group,{position:"left",noWrap:!0,spacing:2,children:[i(s.Text,{children:"Math.exp("}),i(s.Text,{weight:"bold",color:"gray",children:u}),i(s.Text,{children:"×"}),i(s.Text,{children:a.name}),i(s.Text,{children:")"})]})]}),rSquared:c,adjustedRSquared:Kn(c,t.length,1)}}function ab(e,t,n,r){const{x_axis:a,y_axis:o}=r,{a:l,b:u,rSquared:c}=yt.regressionLog()(n);return{name:e,expression:p(s.Group,{position:"center",noWrap:!0,spacing:10,children:[i(s.Text,{children:o.name}),i(s.Text,{children:"="}),i(s.Text,{weight:"bold",color:"gray",children:l}),i(s.Text,{children:"×"}),p(s.Group,{position:"left",noWrap:!0,spacing:2,children:[i(s.Text,{children:"Math.log("}),i(s.Text,{children:a.name}),i(s.Text,{children:")"}),i(s.Text,{children:"+"}),i(s.Text,{weight:"bold",color:"gray",children:u})]})]}),rSquared:c,adjustedRSquared:Kn(c,t.length,1)}}function sb(e,t,n,r){const{x_axis:a,y_axis:o,regression:l}=r,u=yt.regressionPoly().order(l.transform.config.order)(n),{rSquared:c}=u;return console.log(u),{name:e,expression:"",rSquared:c,adjustedRSquared:Kn(c,t.length,1)}}function fo(e,t,n){const{regression:r,x_axis:a}=n,o=O(a.data_key),l=O(r.y_axis_data_key),u=t.map(c=>[c[o.columnKey],c[l.columnKey]]);return r.transform.config.method==="linear"?rb(e,t,u,n):r.transform.config.method==="exponential"?ib(e,t,u,n):r.transform.config.method==="logarithmic"?ab(e,t,u,n):r.transform.config.method==="polynomial"?sb(e,t,u,n):{name:e,expression:"",rSquared:0,adjustedRSquared:0}}function ob(e,t){if(!t)return[{name:"",expression:"",rSquared:0,adjustedRSquared:0}];if(!t.regression.group_by_key)return[fo("",e,t)];const n=O(t.regression.group_by_key),r=x.groupBy(e,n.columnKey);return Object.entries(r).map(([a,o])=>fo(a,o,t))}const lb={marginTop:"10px","tbody th, tbody td":{padding:"7px 10px"},"tbody tr:not(:first-of-type) th":{borderTop:"1px solid #dee2e6"}};function go({desc:e}){const{expression:t,rSquared:n,adjustedRSquared:r}=e;return t?i(s.Table,{fontSize:14,sx:lb,children:p("tbody",{children:[i("tr",{children:i("td",{colSpan:2,children:i(s.Text,{align:"center",children:t})})}),p("tr",{children:[i("td",{children:"R-Sq"}),i("td",{style:{textAlign:"right"},children:Z(n).format({output:"percent",mantissa:1})})]}),p("tr",{children:[i("td",{children:"R-Sq(Adjusted)"}),i("td",{style:{textAlign:"right"},children:Z(r).format({output:"percent",mantissa:1})})]})]})}):i(s.Text,{children:"Unavailable for this regression method"})}function ub({conf:e,queryData:t}){var r;const n=y.useMemo(()=>ob(t,e),[e,t]);return e.regression.group_by_key?(console.log(n),p(s.Tabs,{defaultValue:(r=n[0])==null?void 0:r.name,color:"gray",children:[i(s.Tabs.List,{grow:!0,children:n.map(a=>i(s.Tabs.Tab,{value:a.name,children:a.name},a.name))}),n.map(a=>i(s.Tabs.Panel,{value:a.name,children:i(go,{desc:a})},a.name))]})):i(go,{desc:n[0]})}function cb({conf:e,queryData:t}){return p(s.HoverCard,{shadow:"md",withinPortal:!0,zIndex:320,children:[i(s.HoverCard.Target,{children:i(s.Button,{size:"xs",variant:"subtle",compact:!0,leftIcon:i($.IconInfoCircle,{size:14}),children:"Regression Info"})}),i(s.HoverCard.Dropdown,{children:i(Fe,{children:i(ub,{conf:e,queryData:t})})})]})}function db(e){return i(s.Group,{position:"apart",sx:{position:"absolute",top:0,left:0,height:"22px",zIndex:1},children:i(cb,{...e})})}const Xn={enabled:!1,func_content:["function label(value, index) {"," // your code goes here"," // return value","}"].join(`
247
- `)},si={x_axis:{name:"X Axis",data_key:"",axisLabel:{rotate:0,format:ze,overflow:je,formatter:{...Xn}}},y_axis:{name:"Y Axis"},regression:{transform:{type:"ecStat:regression",config:{method:"linear",order:1,formulaOn:"end"}},plot:{type:"line",yAxisIndex:0,color:"#228be6",lineStyle:{type:"solid",width:1}},name:"regression",group_by_key:"",y_axis_data_key:"value"}};ie.use([q.DataZoomComponent,he.ScatterChart,q.GridComponent,q.LegendComponent,q.TooltipComponent,Pe.CanvasRenderer]);function pb({context:e}){const{value:t}=R(e.instanceData,"config"),{width:n,height:r}=e.viewport,a=y.useMemo(()=>{var m;const c=e.data,d=t==null?void 0:t.x_axis.data_key,f=(m=t==null?void 0:t.regression)==null?void 0:m.y_axis_data_key;if(!d||!f)return[];const h=O(d),g=O(f);return c[h.queryID].map(C=>typeof C[g.columnKey]=="number"?C:{...C,[g.columnKey]:Number(C[g.columnKey])})},[e.data,t==null?void 0:t.regression.y_axis_data_key]),o=y.useMemo(()=>nb(x.defaultsDeep({},t,si),a),[t,a]),l=y.useRef(null),u=c=>{l.current=c};return!n||!r||!t?null:p(s.Box,{sx:{position:"relative"},children:[i(db,{conf:t,queryData:a}),i(Be,{echarts:ie,onChartReady:u,option:o,style:{width:n,height:r},notMerge:!0,theme:"merico-light"})]})}const hb=[{label:"Linear",value:"linear"},{label:"Exponential",value:"exponential"},{label:"Logarithmic",value:"logarithmic"},{label:"Polynomial",value:"polynomial"}];function fb({control:e,watch:t}){t("regression");const n=t("regression.transform.config.method"),r=t("regression.group_by_key");return p(s.Stack,{children:[i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:"regression.name",control:e,render:({field:a})=>i(s.TextInput,{label:"回归线名称",sx:{flex:1},...a})})}),i(v.Controller,{name:"regression.group_by_key",control:e,render:({field:a})=>i(W,{label:"按此字段将数据分为多个系列",clearable:!0,sx:{flex:1},...a})}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"regression.transform.config.method",control:e,render:({field:a})=>i(s.Select,{label:"回归方法",data:hb,sx:{flex:1},...a})}),n==="polynomial"&&i(v.Controller,{name:"regression.transform.config.order",control:e,render:({field:a})=>i(s.NumberInput,{label:"次",sx:{flex:1},...a})})]}),!r&&p(s.Stack,{spacing:4,children:[i(s.Text,{size:"sm",children:"颜色"}),i(v.Controller,{name:"regression.plot.color",control:e,render:({field:a})=>i(Ve,{...a})})]})]})}const gb=({disabled:e,value:t,onChange:n})=>{const r=a=>{a&&n(a)};return p(s.Box,{sx:{position:"relative"},children:[e&&i(s.Overlay,{opacity:.6,color:"#fff",zIndex:5,blur:2}),i(Ae,{height:"500px",defaultLanguage:"javascript",value:t,onChange:r,theme:"vs-dark",options:{minimap:{enabled:!1},readOnly:e}})]})},mo=y.forwardRef(({value:e,onChange:t,triggerButtonText:n="Customize Label"},r)=>{const[a,{setTrue:o,setFalse:l}]=K.useBoolean(),[u,c]=y.useState(e);y.useEffect(()=>{c(e)},[e]);const d=C=>{c({...u,enabled:C})},f=()=>{l();const{enabled:C,func_content:w}=u,_={enabled:C,func_content:w};c(_),t(_)},h=()=>{l(),c(e)},g=C=>{c(w=>({...w,func_content:C}))},m=()=>{g(Xn.func_content)};return p(B,{children:[i(s.Button,{variant:"filled",mt:24,onClick:o,sx:{flexGrow:0},children:n}),i(s.Modal,{size:800,title:"Customize label content",opened:a,onClose:l,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:a&&p(s.Stack,{children:[i(s.Checkbox,{mt:10,label:"Enabled",checked:u.enabled,onChange:C=>d(C.currentTarget.checked)}),i(gb,{value:u.func_content,onChange:g,disabled:!u.enabled}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:m,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:h,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:f,children:"OK"})]})]})]})})]})});function mb({control:e,watch:t}){return t(["x_axis"]),p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"X轴名称",sx:{flex:1},...n})}),i(v.Controller,{name:"x_axis.data_key",control:e,render:({field:n})=>i(W,{label:"X轴数据字段",required:!0,sx:{flex:1},...n})})]}),i(s.Divider,{variant:"dashed",labelPosition:"center",label:"格式化数据"}),i(s.Stack,{children:i(v.Controller,{name:"x_axis.axisLabel.format",control:e,render:({field:n})=>i(We,{...n})})}),i(s.Divider,{variant:"dashed",labelPosition:"center",label:"标签文案样式"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.axisLabel.rotate",control:e,render:({field:n})=>i(s.NumberInput,{label:"旋转",hideControls:!0,min:-90,max:90,rightSection:i(s.Text,{color:"dimmed",children:"度"}),sx:{width:"48%"},styles:{rightSection:{width:"4em",justifyContent:"flex-end",paddingRight:"6px"}},...n})}),i(v.Controller,{name:"x_axis.axisLabel.formatter",control:e,render:({field:n})=>i(mo,{triggerButtonText:"自定义标签文案内容",...n})})]}),i(v.Controller,{name:"x_axis.axisLabel.overflow",control:e,render:({field:n})=>i(at,{...n})})]})}function yb({control:e,watch:t}){return t(["y_axis","regression.y_axis_data_key"]),i(s.Stack,{children:p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"y_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Y轴名称",sx:{flex:1},...n})}),i(v.Controller,{name:"regression.y_axis_data_key",control:e,render:({field:n})=>i(W,{label:"Y轴数据字段",required:!0,sx:{flex:1},...n})})]})})}function bb({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=y.useMemo(()=>x.defaults({},t,si),[t]),{control:a,handleSubmit:o,watch:l,getValues:u,reset:c}=v.useForm({defaultValues:r});y.useEffect(()=>{c(r)},[r]),l(["x_axis","y_axis","regression"]);const d=u(),f=y.useMemo(()=>!x.isEqual(d,t),[d,t]);return i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:o(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!f,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"X轴",orientation:"vertical",styles:{panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"X轴",children:"X轴"}),i(s.Tabs.Tab,{value:"Y轴",children:"Y轴"}),i(s.Tabs.Tab,{value:"回归",children:"回归"})]}),i(s.Tabs.Panel,{value:"X轴",children:i(mb,{watch:l,control:a})}),i(s.Tabs.Panel,{value:"Y轴",children:i(yb,{watch:l,control:a})}),i(s.Tabs.Panel,{value:"回归",children:i(fb,{control:a,watch:l})})]})]})})}function vb(e){const t={x_axis:{axisLabel:{rotate:0,format:ze,overflow:je,formatter:Xn}},regression:{group_by_key:""}};return x.defaultsDeep(t,e)}function xb(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=u=>u&&`${n}.${u}`,{x_axis:a,regression:o,...l}=e;return{...l,x_axis:{...a,data_key:r(a.data_key)},regression:{...o,group_by_key:r(o.group_by_key),y_axis_data_key:r(o.y_axis_data_key)}}}catch(n){throw console.error("[Migration failed]",n),n}}class wb extends ye{constructor(){super(...arguments);N(this,"VERSION",3)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,n=>({...n,version:2,config:vb(n.config)})),this.version(3,(n,r)=>{const{config:a}=n;return{...n,version:3,config:xb(a,r)}})}}const Cb={displayName:"Regression Chart",displayGroup:"Merico suite",migrator:new wb,name:"regressionChart",viewRender:pb,configRender:bb,createConfig(){return{version:3,config:x.cloneDeep(si)}}},Jn={content:""};function Sb(e,t){const n={};return e.forEach(r=>{const{name:a,data_field:o,aggregation:l}=r,u=Fn(t,o,l);n[a]=Ze(r,u)}),n}function _b(e){const t=document.createElement("span");return t.innerHTML=e,t.innerText}function kb(e,t,n){try{return new Function("payload",`
246
+ `}}}function ho({enabled:e,func_content:t}){return(n,r)=>{if(!e)return n;try{return new Function(`return ${t}`)()(n,r)}catch(a){return console.error(`[getEchartsXAxisLabel] failed parsing custom function, error: ${a.message}`),n}}}function eb(e){const{overflow:t,format:n,formatter:r,...a}=e.x_axis.axisLabel,o=rt(t.on_axis);return{type:"value",name:e.x_axis.name??"",nameLocation:"middle",nameGap:25,axisTick:{show:!0,alignWithLabel:!0},axisLabel:{...a,...o,formatter:(l,u)=>{let c=l;try{c=Z(l).format(n)}catch{}return ho(r)(c,u)}}}}const tb={tooltip:{trigger:"axis"},grid:{top:50,left:5,right:10,bottom:20,containLabel:!0},dataZoom:[{type:"inside",xAxisIndex:[0]},{type:"inside",yAxisIndex:[0]}]};function nb(e,t){const n=Jy(e,t),r=Uy(e,n),a={xAxis:eb(e),yAxis:{name:e.y_axis.name??"",nameLocation:"end",nameTextStyle:{align:"left"},nameGap:5,axisLine:{show:!0}},series:[...n,...r],tooltip:Hy(e),legend:{show:!0,type:"scroll",orient:"horizontal",align:"left",right:0,top:0,left:"auto",itemGap:20,padding:[4,8,0,140],data:n.map(o=>o.name)}};return x.defaultsDeep({},a,tb)}function Kn(e,t,n){return 1-(1-e)*(t-1)/(t-n-1)}function rb(e,t,n,r){const{x_axis:a,y_axis:o}=r,l=yt.regressionLinear()(n),{a:u,b:c,rSquared:d}=l;return{name:e,expression:p(s.Group,{position:"center",noWrap:!0,spacing:10,children:[i(s.Text,{children:o.name}),i(s.Text,{children:"="}),i(s.Text,{weight:"bold",color:"red",children:Z(c).format({mantissa:2,trimMantissa:!0})}),i(s.Text,{children:"+"}),i(s.Text,{weight:"bold",color:"red",children:Z(u).format({mantissa:2,trimMantissa:!0})}),i(s.Text,{children:"×"}),i(s.Text,{children:a.name})]}),rSquared:d,adjustedRSquared:Kn(d,t.length,1)}}function ib(e,t,n,r){const{x_axis:a,y_axis:o}=r,{a:l,b:u,rSquared:c}=yt.regressionExp()(n);return{name:e,expression:p(s.Group,{position:"center",noWrap:!0,spacing:10,children:[i(s.Text,{children:o.name}),i(s.Text,{children:"="}),i(s.Text,{weight:"bold",color:"gray",children:l}),i(s.Text,{children:"×"}),p(s.Group,{position:"left",noWrap:!0,spacing:2,children:[i(s.Text,{children:"Math.exp("}),i(s.Text,{weight:"bold",color:"gray",children:u}),i(s.Text,{children:"×"}),i(s.Text,{children:a.name}),i(s.Text,{children:")"})]})]}),rSquared:c,adjustedRSquared:Kn(c,t.length,1)}}function ab(e,t,n,r){const{x_axis:a,y_axis:o}=r,{a:l,b:u,rSquared:c}=yt.regressionLog()(n);return{name:e,expression:p(s.Group,{position:"center",noWrap:!0,spacing:10,children:[i(s.Text,{children:o.name}),i(s.Text,{children:"="}),i(s.Text,{weight:"bold",color:"gray",children:l}),i(s.Text,{children:"×"}),p(s.Group,{position:"left",noWrap:!0,spacing:2,children:[i(s.Text,{children:"Math.log("}),i(s.Text,{children:a.name}),i(s.Text,{children:")"}),i(s.Text,{children:"+"}),i(s.Text,{weight:"bold",color:"gray",children:u})]})]}),rSquared:c,adjustedRSquared:Kn(c,t.length,1)}}function sb(e,t,n,r){const{x_axis:a,y_axis:o,regression:l}=r,u=yt.regressionPoly().order(l.transform.config.order)(n),{rSquared:c}=u;return console.log(u),{name:e,expression:"",rSquared:c,adjustedRSquared:Kn(c,t.length,1)}}function fo(e,t,n){const{regression:r,x_axis:a}=n,o=O(a.data_key),l=O(r.y_axis_data_key),u=t.map(c=>[c[o.columnKey],c[l.columnKey]]);return r.transform.config.method==="linear"?rb(e,t,u,n):r.transform.config.method==="exponential"?ib(e,t,u,n):r.transform.config.method==="logarithmic"?ab(e,t,u,n):r.transform.config.method==="polynomial"?sb(e,t,u,n):{name:e,expression:"",rSquared:0,adjustedRSquared:0}}function ob(e,t){if(!t)return[{name:"",expression:"",rSquared:0,adjustedRSquared:0}];if(!t.regression.group_by_key)return[fo("",e,t)];const n=O(t.regression.group_by_key),r=x.groupBy(e,n.columnKey);return Object.entries(r).map(([a,o])=>fo(a,o,t))}const lb={marginTop:"10px","tbody th, tbody td":{padding:"7px 10px"},"tbody tr:not(:first-of-type) th":{borderTop:"1px solid #dee2e6"}};function go({desc:e}){const{expression:t,rSquared:n,adjustedRSquared:r}=e;return t?i(s.Table,{fontSize:14,sx:lb,children:p("tbody",{children:[i("tr",{children:i("td",{colSpan:2,children:i(s.Text,{align:"center",children:t})})}),p("tr",{children:[i("td",{children:"R-Sq"}),i("td",{style:{textAlign:"right"},children:Z(n).format({output:"percent",mantissa:1})})]}),p("tr",{children:[i("td",{children:"R-Sq(Adjusted)"}),i("td",{style:{textAlign:"right"},children:Z(r).format({output:"percent",mantissa:1})})]})]})}):i(s.Text,{children:"Unavailable for this regression method"})}function ub({conf:e,queryData:t}){var r;const n=b.useMemo(()=>ob(t,e),[e,t]);return e.regression.group_by_key?(console.log(n),p(s.Tabs,{defaultValue:(r=n[0])==null?void 0:r.name,color:"gray",children:[i(s.Tabs.List,{grow:!0,children:n.map(a=>i(s.Tabs.Tab,{value:a.name,children:a.name},a.name))}),n.map(a=>i(s.Tabs.Panel,{value:a.name,children:i(go,{desc:a})},a.name))]})):i(go,{desc:n[0]})}function cb({conf:e,queryData:t}){return p(s.HoverCard,{shadow:"md",withinPortal:!0,zIndex:320,children:[i(s.HoverCard.Target,{children:i(s.Button,{size:"xs",variant:"subtle",compact:!0,leftIcon:i($.IconInfoCircle,{size:14}),children:"Regression Info"})}),i(s.HoverCard.Dropdown,{children:i(Fe,{children:i(ub,{conf:e,queryData:t})})})]})}function db(e){return i(s.Group,{position:"apart",sx:{position:"absolute",top:0,left:0,height:"22px",zIndex:1},children:i(cb,{...e})})}const Xn={enabled:!1,func_content:["function label(value, index) {"," // your code goes here"," // return value","}"].join(`
247
+ `)},si={x_axis:{name:"X Axis",data_key:"",axisLabel:{rotate:0,format:ze,overflow:Re,formatter:{...Xn}}},y_axis:{name:"Y Axis"},regression:{transform:{type:"ecStat:regression",config:{method:"linear",order:1,formulaOn:"end"}},plot:{type:"line",yAxisIndex:0,color:"#228be6",lineStyle:{type:"solid",width:1}},name:"regression",group_by_key:"",y_axis_data_key:"value"}};ie.use([q.DataZoomComponent,he.ScatterChart,q.GridComponent,q.LegendComponent,q.TooltipComponent,Pe.CanvasRenderer]);function pb({context:e}){const{value:t}=R(e.instanceData,"config"),{width:n,height:r}=e.viewport,a=b.useMemo(()=>{var m;const c=e.data,d=t==null?void 0:t.x_axis.data_key,f=(m=t==null?void 0:t.regression)==null?void 0:m.y_axis_data_key;if(!d||!f)return[];const h=O(d),g=O(f);return c[h.queryID].map(C=>typeof C[g.columnKey]=="number"?C:{...C,[g.columnKey]:Number(C[g.columnKey])})},[e.data,t==null?void 0:t.regression.y_axis_data_key]),o=b.useMemo(()=>nb(x.defaultsDeep({},t,si),a),[t,a]),l=b.useRef(null),u=c=>{l.current=c};return!n||!r||!t?null:p(s.Box,{sx:{position:"relative"},children:[i(db,{conf:t,queryData:a}),i(Be,{echarts:ie,onChartReady:u,option:o,style:{width:n,height:r},notMerge:!0,theme:"merico-light"})]})}const hb=[{label:"Linear",value:"linear"},{label:"Exponential",value:"exponential"},{label:"Logarithmic",value:"logarithmic"},{label:"Polynomial",value:"polynomial"}];function fb({control:e,watch:t}){t("regression");const n=t("regression.transform.config.method"),r=t("regression.group_by_key");return p(s.Stack,{children:[i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:"regression.name",control:e,render:({field:a})=>i(s.TextInput,{label:"回归线名称",sx:{flex:1},...a})})}),i(v.Controller,{name:"regression.group_by_key",control:e,render:({field:a})=>i(W,{label:"按此字段将数据分为多个系列",clearable:!0,sx:{flex:1},...a})}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"regression.transform.config.method",control:e,render:({field:a})=>i(s.Select,{label:"回归方法",data:hb,sx:{flex:1},...a})}),n==="polynomial"&&i(v.Controller,{name:"regression.transform.config.order",control:e,render:({field:a})=>i(s.NumberInput,{label:"次",sx:{flex:1},...a})})]}),!r&&p(s.Stack,{spacing:4,children:[i(s.Text,{size:"sm",children:"颜色"}),i(v.Controller,{name:"regression.plot.color",control:e,render:({field:a})=>i(Ve,{...a})})]})]})}const gb=({disabled:e,value:t,onChange:n})=>{const r=a=>{a&&n(a)};return p(s.Box,{sx:{position:"relative"},children:[e&&i(s.Overlay,{opacity:.6,color:"#fff",zIndex:5,blur:2}),i(Ae,{height:"500px",defaultLanguage:"javascript",value:t,onChange:r,theme:"vs-dark",options:{minimap:{enabled:!1},readOnly:e}})]})},mo=b.forwardRef(({value:e,onChange:t,triggerButtonText:n="Customize Label"},r)=>{const[a,{setTrue:o,setFalse:l}]=K.useBoolean(),[u,c]=b.useState(e);b.useEffect(()=>{c(e)},[e]);const d=C=>{c({...u,enabled:C})},f=()=>{l();const{enabled:C,func_content:w}=u,_={enabled:C,func_content:w};c(_),t(_)},h=()=>{l(),c(e)},g=C=>{c(w=>({...w,func_content:C}))},m=()=>{g(Xn.func_content)};return p(B,{children:[i(s.Button,{variant:"filled",mt:24,onClick:o,sx:{flexGrow:0},children:n}),i(s.Modal,{size:800,title:"Customize label content",opened:a,onClose:l,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:a&&p(s.Stack,{children:[i(s.Checkbox,{mt:10,label:"Enabled",checked:u.enabled,onChange:C=>d(C.currentTarget.checked)}),i(gb,{value:u.func_content,onChange:g,disabled:!u.enabled}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:m,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:h,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:f,children:"OK"})]})]})]})})]})});function mb({control:e,watch:t}){return t(["x_axis"]),p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"X轴名称",sx:{flex:1},...n})}),i(v.Controller,{name:"x_axis.data_key",control:e,render:({field:n})=>i(W,{label:"X轴数据字段",required:!0,sx:{flex:1},...n})})]}),i(s.Divider,{variant:"dashed",labelPosition:"center",label:"格式化数据"}),i(s.Stack,{children:i(v.Controller,{name:"x_axis.axisLabel.format",control:e,render:({field:n})=>i(je,{...n})})}),i(s.Divider,{variant:"dashed",labelPosition:"center",label:"标签文案样式"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.axisLabel.rotate",control:e,render:({field:n})=>i(s.NumberInput,{label:"旋转",hideControls:!0,min:-90,max:90,rightSection:i(s.Text,{color:"dimmed",children:"度"}),sx:{width:"48%"},styles:{rightSection:{width:"4em",justifyContent:"flex-end",paddingRight:"6px"}},...n})}),i(v.Controller,{name:"x_axis.axisLabel.formatter",control:e,render:({field:n})=>i(mo,{triggerButtonText:"自定义标签文案内容",...n})})]}),i(v.Controller,{name:"x_axis.axisLabel.overflow",control:e,render:({field:n})=>i(at,{...n})})]})}function yb({control:e,watch:t}){return t(["y_axis","regression.y_axis_data_key"]),i(s.Stack,{children:p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"y_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Y轴名称",sx:{flex:1},...n})}),i(v.Controller,{name:"regression.y_axis_data_key",control:e,render:({field:n})=>i(W,{label:"Y轴数据字段",required:!0,sx:{flex:1},...n})})]})})}function bb({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=b.useMemo(()=>x.defaults({},t,si),[t]),{control:a,handleSubmit:o,watch:l,getValues:u,reset:c}=v.useForm({defaultValues:r});b.useEffect(()=>{c(r)},[r]),l(["x_axis","y_axis","regression"]);const d=u(),f=b.useMemo(()=>!x.isEqual(d,t),[d,t]);return i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:o(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!f,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"X轴",orientation:"vertical",styles:{panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"X轴",children:"X轴"}),i(s.Tabs.Tab,{value:"Y轴",children:"Y轴"}),i(s.Tabs.Tab,{value:"回归",children:"回归"})]}),i(s.Tabs.Panel,{value:"X轴",children:i(mb,{watch:l,control:a})}),i(s.Tabs.Panel,{value:"Y轴",children:i(yb,{watch:l,control:a})}),i(s.Tabs.Panel,{value:"回归",children:i(fb,{control:a,watch:l})})]})]})})}function vb(e){const t={x_axis:{axisLabel:{rotate:0,format:ze,overflow:Re,formatter:Xn}},regression:{group_by_key:""}};return x.defaultsDeep(t,e)}function xb(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=u=>u&&`${n}.${u}`,{x_axis:a,regression:o,...l}=e;return{...l,x_axis:{...a,data_key:r(a.data_key)},regression:{...o,group_by_key:r(o.group_by_key),y_axis_data_key:r(o.y_axis_data_key)}}}catch(n){throw console.error("[Migration failed]",n),n}}class wb extends ye{constructor(){super(...arguments);N(this,"VERSION",3)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,n=>({...n,version:2,config:vb(n.config)})),this.version(3,(n,r)=>{const{config:a}=n;return{...n,version:3,config:xb(a,r)}})}}const Cb={displayName:"Regression Chart",displayGroup:"Merico suite",migrator:new wb,name:"regressionChart",viewRender:pb,configRender:bb,createConfig(){return{version:3,config:x.cloneDeep(si)}}},Jn={content:""};function Sb(e,t){const n={};return e.forEach(r=>{const{name:a,data_field:o,aggregation:l}=r,u=Fn(t,o,l);n[a]=Ze(r,u)}),n}function _b(e){const t=document.createElement("span");return t.innerHTML=e,t.innerText}function kb(e,t,n){try{return new Function("payload",`
248
248
  const filters = payload.filters;
249
249
  const context = payload.context;
250
250
  ${Object.entries(t).map(([r,a])=>`const ${r} = '${a}';`).join(`
251
251
  `)}
252
252
  return ${e};
253
- `)(n)}catch(r){return console.error(r),console.log(e),e}}function Tb(e,t,n,r){const a=Sb(t,r),o=/^(.+)\}\}(.*)$/;return e.split("{{").map(l=>{const u=o.exec(l);if(!u)return l;const c=a[u[1]];if(c){const f=u[2]??"";return`${c}${f}`}const d=_b(u[1]);return`${kb(d,a,n)}${u[2]}`}).join("")}const Db=k.observer(({context:e})=>{const t=we(),{value:n}=R(e.instanceData,"config"),{variables:r,data:a}=e,o=y.useMemo(()=>{const l=x.defaults({},n,Jn);return l.content?Tb(l.content,r,t.payloadForViz,a):""},[n,r,t.payloadForViz]);return o?i(qn,{value:o,styles:{root:{border:"none",height:"100%"},content:{padding:0}}}):null});function Ib(){const{editor:e}=J.useRichTextEditorContext();return i(J.RichTextEditor.Control,{onClick:()=>e==null?void 0:e.commands.insertTable({rows:3,cols:3,withHeaderRow:!0}),"aria-label":"Insert table",title:"Insert table",children:i($.IconBorderAll,{stroke:1.5,size:16})})}const oi=y.forwardRef(({value:e,onChange:t,styles:n={},label:r,onSubmit:a},o)=>{const[l,u]=y.useState(e),c=Ga.useEditor({extensions:[Wa,Fa,J.Link,La,$a,za,Ba.configure({resizable:!1,HTMLAttributes:{class:"rich-text-table-render"}}),qa,Na,Va,Oa.configure({types:["heading","paragraph"]}),Ea.configure({placeholder:"This is placeholder"}),Pa,Aa.Color,Ws],content:l,onUpdate:({editor:g})=>{u(g.getHTML())}});y.useEffect(()=>{u(e),c==null||c.commands.setContent(e)},[e]);const d=()=>{t(l),a==null||a()},f=e!==l,h=y.useMemo(()=>x.defaultsDeep({},{content:Mr},n),[n]);return c?p(s.Stack,{spacing:4,sx:{flexGrow:1,position:"relative"},children:[p(s.Group,{align:"center",children:[i(s.Text,{size:14,fw:500,children:r}),i(s.ActionIcon,{color:"blue",disabled:!f,onClick:d,children:i($.IconDeviceFloppy,{size:18})})]}),p(J.RichTextEditor,{editor:c,styles:h,children:[p(J.RichTextEditor.Toolbar,{sticky:!0,stickyOffset:0,children:[i(J.RichTextEditor.ControlsGroup,{children:i(J.RichTextEditor.ColorPicker,{colors:["#25262b","#868e96","#fa5252","#e64980","#be4bdb","#7950f2","#4c6ef5","#228be6","#15aabf","#12b886","#40c057","#82c91e","#fab005","#fd7e14"],popoverProps:{zIndex:320}})}),p(J.RichTextEditor.ControlsGroup,{children:[i(J.RichTextEditor.Bold,{}),i(J.RichTextEditor.Italic,{}),i(J.RichTextEditor.Underline,{}),i(J.RichTextEditor.ClearFormatting,{}),i(J.RichTextEditor.Highlight,{}),i(J.RichTextEditor.Code,{})]}),p(J.RichTextEditor.ControlsGroup,{children:[i(J.RichTextEditor.H1,{}),i(J.RichTextEditor.H2,{}),i(J.RichTextEditor.H3,{}),i(J.RichTextEditor.H4,{})]}),p(J.RichTextEditor.ControlsGroup,{children:[i(J.RichTextEditor.Blockquote,{}),i(J.RichTextEditor.Hr,{}),i(J.RichTextEditor.BulletList,{}),i(J.RichTextEditor.OrderedList,{}),i(J.RichTextEditor.Subscript,{}),i(J.RichTextEditor.Superscript,{})]}),p(J.RichTextEditor.ControlsGroup,{children:[i(J.RichTextEditor.Link,{}),i(J.RichTextEditor.Unlink,{})]}),p(J.RichTextEditor.ControlsGroup,{children:[i(J.RichTextEditor.AlignLeft,{}),i(J.RichTextEditor.AlignCenter,{}),i(J.RichTextEditor.AlignJustify,{}),i(J.RichTextEditor.AlignRight,{})]}),i(J.RichTextEditor.ControlsGroup,{children:i(Ib,{})}),i(Rp,{editor:c})]}),i(J.RichTextEditor.Content,{})]})]}):null});function Mb({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=y.useMemo(()=>x.defaults({},t,Jn),[t]),{control:a,handleSubmit:o,watch:l,reset:u}=v.useForm({defaultValues:r});l("content"),y.useEffect(()=>{u(r)},[r]);const c=y.useRef(null),d=()=>{var f;return(f=c.current)==null?void 0:f.click()};return i("form",{onSubmit:o(n),style:{flexGrow:1,display:"flex",flexDirection:"column"},children:p(s.Stack,{spacing:"xs",sx:{flexGrow:1},children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef",display:"none"},children:[i(s.Text,{children:"Content"}),i(s.ActionIcon,{ref:c,type:"submit",mr:5,variant:"filled",color:"blue",children:i(T.DeviceFloppy,{size:20})})]}),i(v.Controller,{name:"content",control:a,render:({field:f})=>i(oi,{...f,styles:{root:{flexGrow:1}},label:"Content",onSubmit:d})})]})})}class Ab extends ye{constructor(){super(...arguments);N(this,"VERSION",1)}fixMalformedConfig(n){return x.defaults({},n,Jn)}configVersions(){this.version(1,n=>({version:1,config:this.fixMalformedConfig(n)}))}}const zb={displayName:"Rich Text",displayGroup:"Others",migrator:new Ab,name:"richText",viewRender:Db,configRender:Mb,createConfig(){return{version:1,config:x.cloneDeep(Jn)}}},cn={static:{type:"static",color:ct.random().css()},dynamic:{type:"dynamic",func_content:["function getColor({ rowData, params, variables }, { lodash, interpolate }) {"," // your code goes here",' // return "blue"',"}"].join(`
253
+ `)(n)}catch(r){return console.error(r),console.log(e),e}}function Tb(e,t,n,r){const a=Sb(t,r),o=/^(.+)\}\}(.*)$/;return e.split("{{").map(l=>{const u=o.exec(l);if(!u)return l;const c=a[u[1]];if(c){const f=u[2]??"";return`${c}${f}`}const d=_b(u[1]);return`${kb(d,a,n)}${u[2]}`}).join("")}const Db=k.observer(({context:e})=>{const t=we(),{value:n}=R(e.instanceData,"config"),{variables:r,data:a}=e,o=b.useMemo(()=>{const l=x.defaults({},n,Jn);return l.content?Tb(l.content,r,t.payloadForViz,a):""},[n,r,t.payloadForViz]);return o?i(qn,{value:o,styles:{root:{border:"none",height:"100%"},content:{padding:0}}}):null});function Ib(){const{editor:e}=J.useRichTextEditorContext();return i(J.RichTextEditor.Control,{onClick:()=>e==null?void 0:e.commands.insertTable({rows:3,cols:3,withHeaderRow:!0}),"aria-label":"Insert table",title:"Insert table",children:i($.IconBorderAll,{stroke:1.5,size:16})})}const oi=b.forwardRef(({value:e,onChange:t,styles:n={},label:r,onSubmit:a},o)=>{const[l,u]=b.useState(e),c=Ga.useEditor({extensions:[Wa,Fa,J.Link,La,$a,za,Ba.configure({resizable:!1,HTMLAttributes:{class:"rich-text-table-render"}}),qa,Na,Va,Oa.configure({types:["heading","paragraph"]}),Ea.configure({placeholder:"This is placeholder"}),Pa,Aa.Color,Ws],content:l,onUpdate:({editor:g})=>{u(g.getHTML())}});b.useEffect(()=>{u(e),c==null||c.commands.setContent(e)},[e]);const d=()=>{t(l),a==null||a()},f=e!==l,h=b.useMemo(()=>x.defaultsDeep({},{content:Mr},n),[n]);return c?p(s.Stack,{spacing:4,sx:{flexGrow:1,position:"relative"},children:[p(s.Group,{align:"center",children:[i(s.Text,{size:14,fw:500,children:r}),i(s.ActionIcon,{color:"blue",disabled:!f,onClick:d,children:i($.IconDeviceFloppy,{size:18})})]}),p(J.RichTextEditor,{editor:c,styles:h,children:[p(J.RichTextEditor.Toolbar,{sticky:!0,stickyOffset:0,children:[i(J.RichTextEditor.ControlsGroup,{children:i(J.RichTextEditor.ColorPicker,{colors:["#25262b","#868e96","#fa5252","#e64980","#be4bdb","#7950f2","#4c6ef5","#228be6","#15aabf","#12b886","#40c057","#82c91e","#fab005","#fd7e14"],popoverProps:{zIndex:320}})}),p(J.RichTextEditor.ControlsGroup,{children:[i(J.RichTextEditor.Bold,{}),i(J.RichTextEditor.Italic,{}),i(J.RichTextEditor.Underline,{}),i(J.RichTextEditor.ClearFormatting,{}),i(J.RichTextEditor.Highlight,{}),i(J.RichTextEditor.Code,{})]}),p(J.RichTextEditor.ControlsGroup,{children:[i(J.RichTextEditor.H1,{}),i(J.RichTextEditor.H2,{}),i(J.RichTextEditor.H3,{}),i(J.RichTextEditor.H4,{})]}),p(J.RichTextEditor.ControlsGroup,{children:[i(J.RichTextEditor.Blockquote,{}),i(J.RichTextEditor.Hr,{}),i(J.RichTextEditor.BulletList,{}),i(J.RichTextEditor.OrderedList,{}),i(J.RichTextEditor.Subscript,{}),i(J.RichTextEditor.Superscript,{})]}),p(J.RichTextEditor.ControlsGroup,{children:[i(J.RichTextEditor.Link,{}),i(J.RichTextEditor.Unlink,{})]}),p(J.RichTextEditor.ControlsGroup,{children:[i(J.RichTextEditor.AlignLeft,{}),i(J.RichTextEditor.AlignCenter,{}),i(J.RichTextEditor.AlignJustify,{}),i(J.RichTextEditor.AlignRight,{})]}),i(J.RichTextEditor.ControlsGroup,{children:i(Ib,{})}),i(Rp,{editor:c})]}),i(J.RichTextEditor.Content,{})]})]}):null});function Mb({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=b.useMemo(()=>x.defaults({},t,Jn),[t]),{control:a,handleSubmit:o,watch:l,reset:u}=v.useForm({defaultValues:r});l("content"),b.useEffect(()=>{u(r)},[r]);const c=b.useRef(null),d=()=>{var f;return(f=c.current)==null?void 0:f.click()};return i("form",{onSubmit:o(n),style:{flexGrow:1,display:"flex",flexDirection:"column"},children:p(s.Stack,{spacing:"xs",sx:{flexGrow:1},children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef",display:"none"},children:[i(s.Text,{children:"Content"}),i(s.ActionIcon,{ref:c,type:"submit",mr:5,variant:"filled",color:"blue",children:i(T.DeviceFloppy,{size:20})})]}),i(v.Controller,{name:"content",control:a,render:({field:f})=>i(oi,{...f,styles:{root:{flexGrow:1}},label:"Content",onSubmit:d})})]})})}class Ab extends ye{constructor(){super(...arguments);N(this,"VERSION",1)}fixMalformedConfig(n){return x.defaults({},n,Jn)}configVersions(){this.version(1,n=>({version:1,config:this.fixMalformedConfig(n)}))}}const zb={displayName:"Rich Text",displayGroup:"Others",migrator:new Ab,name:"richText",viewRender:Db,configRender:Mb,createConfig(){return{version:1,config:x.cloneDeep(Jn)}}},dn={static:{type:"static",color:ct.random().css()},dynamic:{type:"dynamic",func_content:["function getColor({ rowData, params, variables }, { lodash, interpolate }) {"," // your code goes here",' // return "blue"',"}"].join(`
254
254
  `)}},yo={id:"builtin:echarts:click-scatter-chart:series",displayName:"Click Scatter",nameRender:$b,configRender:Eb,payload:[{name:"seriesType",description:"'scatter'",valueType:"string"},{name:"componentType",description:"'series'",valueType:"string"},{name:"name",description:"Name of the series clicked",valueType:"string"},{name:"color",description:"Color",valueType:"string"},{name:"value",description:"String-typed number, or series' actual value",valueType:"string"},{name:"rowData",description:"Data of the row",valueType:"object"}]};function Eb(e){return i(B,{})}function $b(e){return i(s.Text,{children:"Click scatter"})}const bo={enabled:!1,func_content:["function label(value, index) {"," // your code goes here"," // return value","}"].join(`
255
- `)},vo={label:je.on_axis,tooltip:je.in_tooltip},li={scatter:{y_data_key:"",name_data_key:"",symbolSize:{type:"static",size:10},color:cn.static,label_position:"right",label_overflow:vo},stats:{templates:{top:"",bottom:""}},x_axis:{name:"",data_key:"",axisLabel:{rotate:0,formatter:{...bo}}},y_axes:[{name:"Y Axis",position:"left",nameAlignment:"center",label_formatter:ze,min:"",max:"",show:!0}],tooltip:{trigger:"item",metrics:[]},reference_lines:[],reference_areas:[],dataZoom:qt};function Lb(e,t){if(!e.x_axis.data_key)return[];const n=O(e.x_axis.data_key);return[{source:t[n.queryID]}]}function Ob(e){const t=e.y_axes.some(a=>!!a.name);let n=15;t&&(n+=20),e.dataZoom.x_axis_slider&&(n+=20);let r=5;return e.x_axis.name&&(r+=15),{top:n,bottom:r}}function Pb(){return{show:!1,bottom:0,left:"center",type:"scroll"}}function Zn(e,t){if(e)return t[e]??void 0}function Bb({reference_areas:e,variableValueMap:t}){const n=e.map(r=>[{name:r.content.text,value:r.content.text,itemStyle:r.itemStyle,label:r.label,xAxis:Zn(r.leftBottomPoint.x_data_key,t),yAxis:Zn(r.leftBottomPoint.y_data_key,t)},{xAxis:Zn(r.rightTopPoint.x_data_key,t),yAxis:Zn(r.rightTopPoint.y_data_key,t)}]);return{type:"scatter",name:"ref_areas",silent:!0,data:[],markArea:{data:n}}}function Vb({type:e,...t},n){if(!e)return 10;if(e==="static"){const{size:a}=t;return a}const{func_content:r}=t;return(a,o)=>{const l=o.data;try{return new Function(`return ${r}`)()({rowData:l,params:o,variables:n},{lodash:x,interpolate:_t.interpolate})}catch(u){return console.error(`[getEchartsSymbolSize] failed parsing custom function, error: ${u.message}`),10}}}function Nb({type:e,...t},n){if(!e)return cn.static.color;if(e==="static"){const{color:a}=t;return a}const{func_content:r}=t;return({value:a})=>{try{return new Function(`return ${r}`)()({rowData:a,variables:n},{lodash:x,interpolate:_t.interpolate})}catch(o){return console.error(`[getSeriesColor] failed parsing custom function, error: ${o.message}`),10}}}function qb(e,t,n,r){return e.map(a=>{const o=a.orientation==="horizontal",l=o?"yAxis":"xAxis",u=o?"insideEndTop":"end";return{name:a.name,type:"line",hide_in_legend:!a.show_in_legend,yAxisIndex:a.yAxisIndex,data:[],lineStyle:a.lineStyle,markLine:{data:[{name:a.name,[l]:Number(n[a.variable_key])}],silent:!0,symbol:["none","none"],lineStyle:a.lineStyle,label:{formatter:function(){return a.template?jn(a.template,t,r):""},position:u}}}})}function Fb({x_axis:e,scatter:t},n){const r=O(e.data_key),a=O(t.y_data_key),o=O(t.name_data_key);return{label:{show:!!t.label_position,position:t.label_position,...rt(t.label_overflow.label),formatter:({value:l})=>l[o.columnKey]},type:"scatter",name:"",xAxisId:"main-x-axis",yAxisIndex:0,datasetIndex:0,itemStyle:{color:Nb(t.color,n)},symbolSize:Vb(t.symbolSize,n),encode:{x:r.columnKey,y:a.columnKey}}}function Gb(e,t,n,r){return[Fb(e,r)].concat(qb(e.reference_lines,n,r,t)).concat(Bb({reference_areas:e.reference_areas,variableValueMap:r}))}function xo({enabled:e,func_content:t}){return(n,r)=>{if(!e)return n;try{return new Function(`return ${t}`)()(n,r)}catch(a){return console.error(`[getEchartsXAxisLabel] failed parsing custom function, error: ${a.message}`),n}}}function wo(e,t,n){const{x_axis:r}=n;return r.axisLabel.formatter.enabled?xo(r.axisLabel.formatter)(e,t):e}function Wb(e,t){const{x_axis:n,tooltip:r}=t;if(r.trigger==="item"){const u=_n(e[0].data,n.data_key);return wo(u,0,t)}const a=e.find(u=>u.axisDim==="x"&&u.axisId==="main-x-axis");if(!a)return"";const{axisValue:o,axisIndex:l}=a;return wo(o,l,t)}const jb=e=>{try{return Z(e).format({trimMantissa:!0,mantissa:2})}catch{return e}};function Rb(e,t){const{scatter:n,tooltip:r}=e;return{confine:!0,trigger:r.trigger,formatter:function(a){const o=t[0]??t.default,l=Array.isArray(a)?a:[a];if(l.length===0)return"";const u=Wb(l,e),c=st(e.scatter.label_overflow.tooltip),d=l.map(({value:m})=>`
255
+ `)},vo={label:Re.on_axis,tooltip:Re.in_tooltip},li={scatter:{y_data_key:"",name_data_key:"",symbolSize:{type:"static",size:10},color:dn.static,label_position:"right",label_overflow:vo},stats:{templates:{top:"",bottom:""}},x_axis:{name:"",data_key:"",axisLabel:{rotate:0,formatter:{...bo}}},y_axes:[{name:"Y Axis",position:"left",nameAlignment:"center",label_formatter:ze,min:"",max:"",show:!0}],tooltip:{trigger:"item",metrics:[]},reference_lines:[],reference_areas:[],dataZoom:qt};function Lb(e,t){if(!e.x_axis.data_key)return[];const n=O(e.x_axis.data_key);return[{source:t[n.queryID]}]}function Ob(e){const t=e.y_axes.some(a=>!!a.name);let n=15;t&&(n+=20),e.dataZoom.x_axis_slider&&(n+=20);let r=5;return e.x_axis.name&&(r+=15),{top:n,bottom:r}}function Pb(){return{show:!1,bottom:0,left:"center",type:"scroll"}}function Zn(e,t){if(e)return t[e]??void 0}function Bb({reference_areas:e,variableValueMap:t}){const n=e.map(r=>[{name:r.content.text,value:r.content.text,itemStyle:r.itemStyle,label:r.label,xAxis:Zn(r.leftBottomPoint.x_data_key,t),yAxis:Zn(r.leftBottomPoint.y_data_key,t)},{xAxis:Zn(r.rightTopPoint.x_data_key,t),yAxis:Zn(r.rightTopPoint.y_data_key,t)}]);return{type:"scatter",name:"ref_areas",silent:!0,data:[],markArea:{data:n}}}function Vb({type:e,...t},n){if(!e)return 10;if(e==="static"){const{size:a}=t;return a}const{func_content:r}=t;return(a,o)=>{const l=o.data;try{return new Function(`return ${r}`)()({rowData:l,params:o,variables:n},{lodash:x,interpolate:_t.interpolate})}catch(u){return console.error(`[getEchartsSymbolSize] failed parsing custom function, error: ${u.message}`),10}}}function Nb({type:e,...t},n){if(!e)return dn.static.color;if(e==="static"){const{color:a}=t;return a}const{func_content:r}=t;return({value:a})=>{try{return new Function(`return ${r}`)()({rowData:a,variables:n},{lodash:x,interpolate:_t.interpolate})}catch(o){return console.error(`[getSeriesColor] failed parsing custom function, error: ${o.message}`),10}}}function qb(e,t,n,r){return e.map(a=>{const o=a.orientation==="horizontal",l=o?"yAxis":"xAxis",u=o?"insideEndTop":"end";return{name:a.name,type:"line",hide_in_legend:!a.show_in_legend,yAxisIndex:a.yAxisIndex,data:[],lineStyle:a.lineStyle,markLine:{data:[{name:a.name,[l]:Number(n[a.variable_key])}],silent:!0,symbol:["none","none"],lineStyle:a.lineStyle,label:{formatter:function(){return a.template?jn(a.template,t,r):""},position:u}}}})}function Fb({x_axis:e,scatter:t},n){const r=O(e.data_key),a=O(t.y_data_key),o=O(t.name_data_key);return{label:{show:!!t.label_position,position:t.label_position,...rt(t.label_overflow.label),formatter:({value:l})=>l[o.columnKey]},type:"scatter",name:"",xAxisId:"main-x-axis",yAxisIndex:0,datasetIndex:0,itemStyle:{color:Nb(t.color,n)},symbolSize:Vb(t.symbolSize,n),encode:{x:r.columnKey,y:a.columnKey}}}function Gb(e,t,n,r){return[Fb(e,r)].concat(qb(e.reference_lines,n,r,t)).concat(Bb({reference_areas:e.reference_areas,variableValueMap:r}))}function xo({enabled:e,func_content:t}){return(n,r)=>{if(!e)return n;try{return new Function(`return ${t}`)()(n,r)}catch(a){return console.error(`[getEchartsXAxisLabel] failed parsing custom function, error: ${a.message}`),n}}}function wo(e,t,n){const{x_axis:r}=n;return r.axisLabel.formatter.enabled?xo(r.axisLabel.formatter)(e,t):e}function Wb(e,t){const{x_axis:n,tooltip:r}=t;if(r.trigger==="item"){const u=_n(e[0].data,n.data_key);return wo(u,0,t)}const a=e.find(u=>u.axisDim==="x"&&u.axisId==="main-x-axis");if(!a)return"";const{axisValue:o,axisIndex:l}=a;return wo(o,l,t)}const jb=e=>{try{return Z(e).format({trimMantissa:!0,mantissa:2})}catch{return e}};function Rb(e,t){const{scatter:n,tooltip:r}=e;return{confine:!0,trigger:r.trigger,formatter:function(a){const o=t[0]??t.default,l=Array.isArray(a)?a:[a];if(l.length===0)return"";const u=Wb(l,e),c=st(e.scatter.label_overflow.tooltip),d=l.map(({value:m})=>`
256
256
  <th style="text-align: right; padding-right: 1em">
257
257
  <div style="${c}">${_n(m,n.name_data_key)}</div>
258
258
  </th>
@@ -273,8 +273,8 @@ Check the top-level render call using <`+V+">.")}return E}}function Su(S,E){{if(
273
273
  <thead><tr>${d.join("")}</tr></thead>
274
274
  <tbody>${f.join("")}</tbody>
275
275
  </table>
276
- `}}}function Yb(e,t){const n=t.every(a=>!Number.isNaN(Number(a))),{axisLabel:r}=e.x_axis;return[{data:t,name:e.x_axis.name??"",id:"main-x-axis",axisTick:{show:!0,alignWithLabel:!0},type:n?"value":"category",axisLabel:{...r,formatter:xo(r.formatter)}}]}function Qb(e,t){return e.y_axes.map(({nameAlignment:n,min:r,max:a,...o},l)=>{let u=o.position;return u||(u=l>0?"right":"left"),{...o,minInterval:1,min:r||void 0,max:a||void 0,position:u,axisLabel:{show:!0,formatter:t[l]??t.default},axisLine:{show:!0},nameTextStyle:{fontWeight:"bold",align:n},nameLocation:"end",nameGap:15,splitLine:{show:!1}}})}const Ub={xAxis:[{type:"category",nameGap:25,nameLocation:"center",nameTextStyle:{fontWeight:"bold"},splitLine:{show:!1},axisTick:{show:!0,alignWithLabel:!0}}],grid:{top:10,left:20,right:15,bottom:25,containLabel:!0}};function Kb(e,t,n){const r=n.reduce((c,d)=>{const f=ft(d,t);return c[d.name]=Ze(d,f),c},{}),a=e.y_axes.reduce((c,{label_formatter:d},f)=>(c[f]=function(g){let m=g;if(typeof g=="object"&&(Array.isArray(g.value)&&g.value.length===2?m=g.value[1]:m=g.value),!d)return m;try{return Z(m).format(d)}catch(C){return console.error(C),m}},c),{default:({value:c})=>c}),o=x.uniq(pt(t,e.x_axis.data_key)),l=Gb(e,t,n,r),u={xAxis:Yb(e,o),yAxis:Qb(e,a),series:l,dataset:Lb(e,t),tooltip:Rb(e,a),grid:Ob(e),legend:Pb(),dataZoom:Xr(e.dataZoom)};return x.defaultsDeep({},u,Ub)}ie.use([q.DataZoomComponent,he.BarChart,he.LineChart,he.ScatterChart,q.GridComponent,q.LegendComponent,q.TooltipComponent,Pe.CanvasRenderer,q.MarkLineComponent,q.MarkAreaComponent]);function Co(e){return e.trim().length>0}function Xb({conf:e,data:t,width:n,height:r,interactionManager:a,variables:o}){const l=Dt(t,e.x_axis.data_key),u=Ke(a.triggerManager,yo.id),c=y.useCallback(h=>{const g=h.data;u.forEach(m=>{a.runInteraction(m.id,{...h,rowData:g})})},[l,u,a]),d=y.useMemo(()=>({click:c}),[c]),f=y.useMemo(()=>Kb(e,t,o),[e,t]);return i(Be,{echarts:ie,option:f,style:{width:n,height:r},onEvents:d,notMerge:!0,theme:"merico-light"})}function Jb({context:e,instance:t}){const n=Xe({vizManager:e.vizManager,instance:t}),{value:r}=R(e.instanceData,"config"),{variables:a}=e,o=y.useMemo(()=>x.defaults({},r,li),[r]),l=e.data,{width:u,height:c}=e.viewport,{ref:d,height:f}=Ie.useElementSize(),{ref:h,height:g}=Ie.useElementSize(),m=y.useMemo(()=>{const{stats:{templates:w}}=o;return{top:un(w.top,a,l),bottom:un(w.bottom,a,l)}},[o,l]),C=Math.max(0,c-f-g);return!u||!c?null:p(B,{children:[i(s.Text,{ref:d,align:"left",size:"xs",pl:"sm",sx:{display:Co(o.stats.templates.top)?"block":"none"},children:Object.values(m.top).map(w=>w)}),i(Xb,{variables:a,width:u,height:C,data:l,conf:o,interactionManager:n}),i(s.Text,{ref:h,align:"left",size:"xs",pl:"sm",sx:{display:Co(o.stats.templates.bottom)?"block":"none"},children:Object.values(m.bottom).map(w=>w)})]})}const Zb=y.forwardRef(({value:e,onChange:t,xAxisOptions:n,yAxisOptions:r,variableOptions:a},o)=>{const l=(u,c)=>{const d=x.cloneDeep(e);x.set(d,u,c),t(d)};return p(s.Stack,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Content",labelPosition:"right"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(s.TextInput,{label:"Content Text",value:e.content.text,onChange:u=>l("content.text",u.currentTarget.value)}),i(ti,{label:"Text Position",value:e.label.position,onChange:u=>l("label.position",u)})]}),i(s.Divider,{mb:-15,variant:"dashed",label:"Endpoints",labelPosition:"right"}),p(s.Group,{grow:!0,noWrap:!0,children:[n&&i(s.Select,{label:"X Axis",data:n,value:e.xAxisIndex,onChange:u=>l("xAxisIndex",u)}),r&&i(s.Select,{label:"Y Axis",data:r,value:e.yAxisIndex,onChange:u=>l("xAxisIndex",u)})]}),p(s.Stack,{spacing:0,children:[i(s.Text,{size:14,color:"#212529",fw:500,children:"Left-Bottom Point"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(s.Select,{icon:i(s.Text,{children:"x"}),data:a,value:e.leftBottomPoint.x_data_key,onChange:u=>l("leftBottomPoint.x_data_key",u??""),clearable:!0}),i(s.Select,{icon:i(s.Text,{children:"y"}),data:a,value:e.leftBottomPoint.y_data_key,onChange:u=>l("leftBottomPoint.y_data_key",u??""),clearable:!0})]})]}),p(s.Stack,{spacing:0,children:[i(s.Text,{size:14,color:"#212529",fw:500,children:"Right-Top Point"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(s.Select,{icon:i(s.Text,{children:"x"}),data:a,value:e.rightTopPoint.x_data_key,onChange:u=>l("rightTopPoint.x_data_key",u??""),clearable:!0}),i(s.Select,{icon:i(s.Text,{children:"y"}),data:a,value:e.rightTopPoint.y_data_key,onChange:u=>l("rightTopPoint.y_data_key",u??""),clearable:!0})]})]}),i(s.Divider,{mb:-15,variant:"dashed",label:"Style",labelPosition:"right"}),p(s.Stack,{spacing:4,children:[i(s.Text,{size:14,children:"Background Color"}),i(Ve,{value:e.itemStyle.color,onChange:u=>l("itemStyle.color",u)})]}),p(s.Stack,{spacing:4,children:[i(s.Text,{size:14,children:"Text Color"}),i(Ve,{value:e.label.color,onChange:u=>l("label.color",u)})]})]})});function Hb(){const e=new Date().getTime().toString();return{id:e,content:{text:e},itemStyle:{color:"rgba(0,0,0,0.05)"},label:{position:"inside",color:"rgba(0,0,0,0.5)"},leftBottomPoint:{x_data_key:"",y_data_key:""},rightTopPoint:{x_data_key:"",y_data_key:""},xAxisIndex:"0",yAxisIndex:"0"}}function ev({control:e,watch:t,variables:n}){const{fields:r,append:a,remove:o}=v.useFieldArray({control:e,name:"reference_areas"}),l=t("reference_areas"),u=r.map((g,m)=>({...g,...l[m]})),c=()=>{const g=Hb();a(g)},d=y.useMemo(()=>n.map(g=>({label:g.name,value:g.name})),[n]),f=t("y_axes"),h=y.useMemo(()=>f.map(({name:g},m)=>({label:g,value:m.toString()})),[f]);return p(s.Tabs,{defaultValue:"0",styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px"}},children:[p(s.Tabs.List,{children:[u.map((g,m)=>i(s.Tabs.Tab,{value:m.toString(),children:m+1},m)),i(s.Tabs.Tab,{onClick:c,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),u.map((g,m)=>i(s.Tabs.Panel,{value:m.toString(),children:i(v.Controller,{name:`reference_areas.${m}`,control:e,render:({field:C})=>p(s.Stack,{children:[i(Zb,{variableOptions:d,yAxisOptions:h,...C}),i(s.Divider,{mb:-10,mt:10,variant:"dashed"}),i(s.Button,{leftIcon:i($.IconTrash,{size:16}),color:"red",variant:"light",onClick:()=>o(m),children:"Delete this Reference Area"})]})})},m))]})}const tv=[{label:"solid",value:"solid"},{label:"dashed",value:"dashed"},{label:"dotted",value:"dotted"}],nv=[{label:"Horizontal",value:"horizontal"},{label:"Vertical",value:"vertical"}];function rv({control:e,index:t,remove:n,watch:r,variableOptions:a,yAxisOptions:o}){const l=r(`reference_lines.${t}.orientation`);return p(s.Stack,{my:0,p:0,sx:{position:"relative"},children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`reference_lines.${t}.name`,control:e,render:({field:u})=>i(s.TextInput,{label:"Name",placeholder:"Average Reference Line",required:!0,sx:{flex:1},...u})}),i(v.Controller,{name:`reference_lines.${t}.variable_key`,control:e,render:({field:u})=>i(s.Select,{label:"Value",required:!0,data:a,sx:{flex:1},...u})})]}),i(v.Controller,{name:`reference_lines.${t}.template`,control:e,render:({field:u})=>i(s.TextInput,{label:"Content Template",placeholder:"Average: ${avg}",sx:{flex:1},...u})}),p(s.Group,{grow:!0,children:[p(s.Stack,{children:[i(v.Controller,{name:`reference_lines.${t}.orientation`,control:e,render:({field:u})=>i(s.Select,{label:"Orientation",data:nv,required:!0,sx:{flex:1},...u})}),l==="vertical"&&i(s.Text,{mt:-10,color:"dimmed",size:12,children:"Works only when xAxis values are numbers"})]}),l==="horizontal"&&i(v.Controller,{name:`reference_lines.${t}.yAxisIndex`,control:e,render:({field:{value:u,onChange:c,...d}})=>i(s.Select,{label:"Y Axis",data:o,disabled:o.length===0,...d,value:(u==null?void 0:u.toString())??"",onChange:f=>{if(!f){c(0);return}c(Number(f))},sx:{flex:1}})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Style",labelPosition:"center"}),p(s.Group,{grow:!0,children:[i(v.Controller,{name:`reference_lines.${t}.lineStyle.type`,control:e,render:({field:u})=>i(s.Select,{label:"Line Type",data:tv,sx:{flexGrow:1},...u})}),i(v.Controller,{name:`reference_lines.${t}.lineStyle.width`,control:e,render:({field:u})=>i(s.NumberInput,{label:"Line Width",min:1,max:10,sx:{flexGrow:1},...u})})]}),p(s.Stack,{spacing:4,children:[i(s.Text,{size:"sm",children:"Color"}),i(v.Controller,{name:`reference_lines.${t}.lineStyle.color`,control:e,render:({field:u})=>i(Ve,{...u})})]}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Reference Line"})]},t)}function iv({control:e,watch:t,variables:n}){const{fields:r,append:a,remove:o}=v.useFieldArray({control:e,name:"reference_lines"}),l=t("reference_lines"),u=r.map((g,m)=>({...g,...l[m]})),c=()=>{const g={name:"",template:"",variable_key:"",orientation:"horizontal",lineStyle:{type:"dashed",width:1,color:ct.random().css()},show_in_legend:!1,yAxisIndex:0};a(g)},d=y.useMemo(()=>n.map(g=>({label:g.name,value:g.name})),[n]),f=t("y_axes"),h=y.useMemo(()=>f.map(({name:g},m)=>({label:g,value:m.toString()})),[f]);return p(s.Tabs,{defaultValue:"0",styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px"}},children:[p(s.Tabs.List,{children:[u.map((g,m)=>i(s.Tabs.Tab,{value:m.toString(),children:m+1},m)),i(s.Tabs.Tab,{onClick:c,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),u.map((g,m)=>i(s.Tabs.Panel,{value:m.toString(),children:i(rv,{control:e,index:m,remove:o,watch:t,variableOptions:d,yAxisOptions:h})},m))]})}const av=({value:e,onChange:t})=>{const n=r=>{r&&t(r)};return i(s.Box,{children:i(Ae,{height:"500px",defaultLanguage:"javascript",value:e,onChange:n,theme:"vs-dark",options:{minimap:{enabled:!1}}})})},sv=({value:e,onChange:t})=>{const[n,{setTrue:r,setFalse:a}]=K.useBoolean(),[o,l]=y.useState(e),u=()=>{a();const{type:h,func_content:g}=o,m={type:h,func_content:g};l(m),t(m)},c=()=>{a(),l(e)},d=h=>{l(g=>({...g,func_content:h}))},f=()=>{d(cn.dynamic.func_content)};return p(B,{children:[i(s.Box,{sx:{width:"50%"},children:i(s.Button,{variant:"filled",mt:24,onClick:r,sx:{flexGrow:0},children:"Setup"})}),i(s.Modal,{size:800,title:"Setup dynamic color",opened:n,onClose:a,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:n&&p(s.Stack,{children:[i(s.Divider,{mt:10,mb:-10,label:"Dynamic by a custom function",labelPosition:"center",variant:"dashed"}),i(av,{value:o.func_content,onChange:d}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:f,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:c,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:u,children:"OK"})]})]})]})})]})},ov=({value:e,onChange:t})=>e.type!=="dynamic"?null:i(sv,{value:e,onChange:t}),lv=({value:e,onChange:t})=>{if(e.type!=="static")return null;const n=r=>{t({...e,color:r})};return i(s.ColorInput,{label:" ",format:"rgb",value:e.color,onChange:n})},uv=[{label:"Static",value:"static"},{label:"Dynamic",value:"dynamic"}],cv=y.forwardRef(({label:e="Color",value:t,onChange:n},r)=>{const a=o=>{n({...cn[o]})};return p(s.SimpleGrid,{cols:2,children:[i(s.Select,{ref:r,label:e,data:uv,value:t.type,onChange:a,sx:{flexGrow:1}}),i(lv,{value:t,onChange:n}),i(ov,{value:t,onChange:n})]})}),dv=y.forwardRef(({value:e,onChange:t},n)=>{const r=o=>{t({...e,label:o})},a=o=>{t({...e,tooltip:o})};return p(s.Stack,{ref:n,spacing:0,children:[i(Tn,{sectionTitle:"Overflow on Chart",value:e.label,onChange:r}),i(Tn,{sectionTitle:"Overflow in Tooltip",value:e.tooltip,onChange:a})]})}),pv=({value:e,onChange:t})=>{const n=r=>{r&&t(r)};return i(s.Box,{children:i(Ae,{height:"500px",defaultLanguage:"javascript",value:e,onChange:n,theme:"vs-dark",options:{minimap:{enabled:!1}}})})},So={static:{type:"static",size:10},dynamic:{type:"dynamic",func_content:["function getSize({ rowData, params, variables }, { lodash, interpolate }) {"," // your code goes here"," // return 10","}"].join(`
277
- `)}},hv=({value:e,onChange:t})=>{const[n,{setTrue:r,setFalse:a}]=K.useBoolean(),[o,l]=y.useState(e),u=()=>{a();const{type:h,func_content:g}=o,m={type:h,func_content:g};l(m),t(m)},c=()=>{a(),l(e)},d=h=>{l(g=>({...g,func_content:h}))},f=()=>{d(So.dynamic.func_content)};return p(B,{children:[i(s.Box,{sx:{width:"50%"},children:i(s.Button,{variant:"filled",mt:24,onClick:r,sx:{flexGrow:0},children:"Setup"})}),i(s.Modal,{size:800,title:"Setup dynamic size",opened:n,onClose:a,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:n&&p(s.Stack,{children:[i(s.Divider,{mt:10,mb:-10,label:"Dynamic by a custom function",labelPosition:"center",variant:"dashed"}),i(pv,{value:o.func_content,onChange:d}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:f,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:c,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:u,children:"OK"})]})]})]})})]})},fv=({value:e,onChange:t})=>e.type!=="dynamic"?null:i(hv,{value:e,onChange:t}),gv=({value:e,onChange:t})=>{if(e.type!=="static")return null;const n=r=>{t({...e,size:r})};return i(B,{children:i(s.NumberInput,{defaultValue:18,placeholder:"1 ~ 100",label:" ",hideControls:!0,value:e.size,onChange:n})})},mv=[{label:"Static",value:"static"},{label:"Dynamic",value:"dynamic"}],yv=y.forwardRef(({label:e="Size",value:t,onChange:n},r)=>{const a=o=>{n({...So[o]})};return p(s.SimpleGrid,{cols:2,children:[i(s.Select,{ref:r,label:e,data:mv,value:t.type,onChange:a,sx:{flexGrow:1}}),i(gv,{value:t,onChange:n}),i(fv,{value:t,onChange:n})]})}),bv=[{label:"off",value:""},{label:"top",value:"top"},{label:"left",value:"left"},{label:"right",value:"right"},{label:"bottom",value:"bottom"},{label:"inside",value:"inside"},{label:"insideLeft",value:"insideLeft"},{label:"insideRight",value:"insideRight"},{label:"insideTop",value:"insideTop"},{label:"insideBottom",value:"insideBottom"},{label:"insideTopLeft",value:"insideTopLeft"},{label:"insideBottomLeft",value:"insideBottomLeft"},{label:"insideTopRight",value:"insideTopRight"},{label:"insideBottomRight",value:"insideBottomRight"}];function vv({control:e,watch:t}){return t(["scatter"]),p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"scatter.name_data_key",control:e,render:({field:n})=>i(W,{label:"Name Data Field",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"scatter.y_data_key",control:e,render:({field:n})=>i(W,{label:"Value Data Field",required:!0,sx:{flex:1},...n})})]}),i(s.Divider,{mb:-15,label:"Style",labelPosition:"center"}),i(v.Controller,{name:"scatter.symbolSize",control:e,render:({field:n})=>i(yv,{label:"Size",...n})}),i(v.Controller,{name:"scatter.color",control:e,render:({field:n})=>i(cv,{...n})}),i(s.Divider,{mb:-15,label:"Label",labelPosition:"center"}),i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:"scatter.label_position",control:e,render:({field:n})=>i(s.Select,{label:"Label Position",data:bv,...n})})}),i(v.Controller,{name:"scatter.label_overflow",control:e,render:({field:n})=>i(dv,{...n})})]})}function xv({control:e,watch:t}){return t("stats"),i(s.Stack,{children:p(s.Stack,{spacing:0,children:[i(v.Controller,{name:"stats.templates.top",control:e,render:({field:n})=>i(en,{label:"Template for stats above the chart",py:"md",sx:{flexGrow:1},...n})}),i(v.Controller,{name:"stats.templates.bottom",control:e,render:({field:n})=>i(en,{label:"Template for stats under the chart",py:"md",sx:{flexGrow:1},...n})})]})})}const wv=({control:e,index:t,remove:n})=>p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`tooltip.metrics.${t}.name`,control:e,render:({field:r})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:`tooltip.metrics.${t}.data_key`,control:e,render:({field:r})=>i(W,{label:"Value Field",required:!0,sx:{flex:1},...r})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed"}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Metric"})]}),Cv=({control:e,watch:t})=>{const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"tooltip.metrics"}),o=t("tooltip.metrics"),l=n.map((h,g)=>({...h,...o[g]})),u=()=>r({id:Date.now().toString(),data_key:"",name:""}),c=t("tooltip.metrics.0.id"),[d,f]=y.useState(()=>c??null);return y.useEffect(()=>{c&&f(h=>h!==null?h:c)},[c]),p(B,{children:[p(s.Group,{spacing:2,sx:{cursor:"default",userSelect:"none"},children:[i(T.InfoCircle,{size:14,color:"#888"}),i(s.Text,{size:14,color:"#888",children:"Configure additional metrics to show in tooltip"})]}),p(s.Tabs,{value:d,onTabChange:h=>f(h),styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map((h,g)=>i(s.Tabs.Tab,{value:h.id,children:h.name?h.name:g},h.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((h,g)=>i(s.Tabs.Panel,{value:h.id,children:i(wv,{control:e,index:g,remove:a},h.id)},h.id))]})]})},Sv=[{label:"Scatter Point",value:"item"},{label:"X Axis",value:"axis"}];function _v({control:e,watch:t}){return t("tooltip.trigger"),p(s.Stack,{children:[i(v.Controller,{name:"tooltip.trigger",control:e,render:({field:n})=>i(s.Select,{label:"Trigger",data:Sv,sx:{flexGrow:1},...n})}),i(s.Divider,{variant:"dashed"}),i(Cv,{control:e,watch:t})]})}const kv=({disabled:e,value:t,onChange:n})=>{const r=a=>{a&&n(a)};return p(s.Box,{sx:{position:"relative"},children:[e&&i(s.Overlay,{opacity:.6,color:"#fff",zIndex:5,blur:2}),i(Ae,{height:"500px",defaultLanguage:"javascript",value:t,onChange:r,theme:"vs-dark",options:{minimap:{enabled:!1},readOnly:e}})]})},Tv=y.forwardRef(({value:e,onChange:t},n)=>{const[r,{setTrue:a,setFalse:o}]=K.useBoolean(),[l,u]=y.useState(e);y.useEffect(()=>{u(e)},[e]);const c=m=>{u({...l,enabled:m})},d=()=>{o();const{enabled:m,func_content:C}=l,w={enabled:m,func_content:C};u(w),t(w)},f=()=>{o(),u(e)},h=m=>{u(C=>({...C,func_content:m}))},g=()=>{h(bo.func_content)};return p(B,{children:[i(s.Button,{variant:"filled",mt:24,onClick:a,sx:{flexGrow:0},children:"Customize Label"}),i(s.Modal,{size:800,title:"Customize label content",opened:r,onClose:o,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:r&&p(s.Stack,{children:[i(s.Checkbox,{mt:10,label:"Enabled",checked:l.enabled,onChange:m=>c(m.currentTarget.checked)}),i(kv,{value:l.func_content,onChange:h,disabled:!l.enabled}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:g,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:f,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:d,children:"OK"})]})]})]})})]})});function Dv({control:e,watch:t}){return t(["x_axis"]),p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.data_key",control:e,render:({field:n})=>i(W,{label:"Data Field",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"x_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Name",sx:{flex:1},...n})})]}),i(s.Divider,{mb:-15,label:"Tick Label",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.axisLabel.rotate",control:e,render:({field:n})=>i(s.NumberInput,{label:"Rotate",hideControls:!0,min:-90,max:90,rightSection:i(s.Text,{color:"dimmed",children:"degree"}),sx:{width:"48%"},styles:{rightSection:{width:"4em",justifyContent:"flex-end",paddingRight:"6px"}},...n})}),i(v.Controller,{name:"x_axis.axisLabel.formatter",control:e,render:({field:n})=>i(Tv,{...n})})]})]})}const Iv=[{label:"left",value:"left"},{label:"center",value:"center"},{label:"right",value:"right"}],Mv=[{label:"left",value:"left"},{label:"right",value:"right"}];function Av({control:e,index:t,remove:n}){return p(s.Stack,{my:0,p:"0",sx:{position:"relative"},children:[i(s.Divider,{mb:-15,mt:15,variant:"dashed",label:"Name",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`y_axes.${t}.name`,control:e,render:({field:r})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:`y_axes.${t}.nameAlignment`,control:e,render:({field:r})=>i(s.Select,{label:"Align",required:!0,data:Iv,sx:{flex:1},...r})})]}),i(s.Divider,{mb:-15,variant:"dashed",label:"Layout",labelPosition:"center"}),i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:`y_axes.${t}.position`,control:e,render:({field:r})=>i(s.Select,{label:"Position",required:!0,data:Mv,sx:{flex:1},...r})})}),p(s.Stack,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Label Format",labelPosition:"center"}),i(v.Controller,{name:`y_axes.${t}.label_formatter`,control:e,render:({field:r})=>i(We,{...r})})]}),p(s.Stack,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Value Range",labelPosition:"center"}),p(s.Group,{grow:!0,children:[i(v.Controller,{name:`y_axes.${t}.min`,control:e,render:({field:r})=>i(s.TextInput,{label:"Min",...r})}),i(v.Controller,{name:`y_axes.${t}.max`,control:e,render:({field:r})=>i(s.TextInput,{label:"Max",...r})})]})]}),i(s.Button,{mt:20,leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),disabled:t===0,children:"Delete this YAxis"})]})}function zv({control:e,watch:t}){const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"y_axes"}),o=t("y_axes"),l=n.map((c,d)=>({...c,...o[d]})),u=()=>r({name:"",label_formatter:ze,min:"",max:"",show:!0,position:"right",nameAlignment:"right"});return p(s.Tabs,{defaultValue:"0",styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px"}},children:[p(s.Tabs.List,{children:[l.map((c,d)=>i(s.Tabs.Tab,{value:d.toString(),children:d+1},d)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((c,d)=>i(s.Tabs.Panel,{value:d.toString(),children:i(Av,{control:e,index:d,remove:a})},d))]})}function Ev(e){return e||{templates:{top:"",bottom:""}}}function $v({reference_lines:e=[],stats:t,...n}){return{reference_lines:e,stats:Ev(t),...n}}function Lv({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),{variables:r}=e,a=y.useMemo(()=>x.defaultsDeep({},t,li),[t]),o=y.useMemo(()=>$v(a),[a]);y.useEffect(()=>{!x.isEqual(a,o)&&(console.log("config malformed, resetting to defaults",a,o),n(o))},[a,o]);const{control:l,handleSubmit:u,watch:c,getValues:d,reset:f}=v.useForm({defaultValues:o});y.useEffect(()=>{f(o)},[o]);const h=d(),g=y.useMemo(()=>!x.isEqual(h,a),[h,a]);return c(["dataZoom"]),i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:u(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!g,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"X Axis",orientation:"vertical",styles:{tab:{paddingLeft:"6px",paddingRight:"6px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"X Axis",children:"X Axis"}),i(s.Tabs.Tab,{value:"Y Axes",children:"Y Axes"}),i(s.Tabs.Tab,{value:"Scatter",children:"Scatter"}),i(s.Tabs.Tab,{value:"Tooltip",children:"Tooltip"}),i(s.Tabs.Tab,{value:"Stats",children:"Stats"}),i(s.Tabs.Tab,{value:"Reference Lines",children:"Reference Lines"}),i(s.Tabs.Tab,{value:"Reference Areas",children:"Reference Areas"}),i(s.Tabs.Tab,{value:"Zooming",children:"Zooming"})]}),i(s.Tabs.Panel,{value:"X Axis",children:i(Dv,{control:l,watch:c})}),i(s.Tabs.Panel,{value:"Y Axes",children:i(zv,{control:l,watch:c})}),i(s.Tabs.Panel,{value:"Scatter",children:i(vv,{control:l,watch:c})}),i(s.Tabs.Panel,{value:"Tooltip",children:i(_v,{control:l,watch:c})}),i(s.Tabs.Panel,{value:"Stats",children:i(xv,{control:l,watch:c})}),i(s.Tabs.Panel,{value:"Reference Lines",children:i(iv,{variables:r,control:l,watch:c})}),i(s.Tabs.Panel,{value:"Reference Areas",children:i(ev,{variables:r,control:l,watch:c})}),i(s.Tabs.Panel,{value:"Zooming",children:i(v.Controller,{name:"dataZoom",control:l,render:({field:m})=>i(Zr,{...m})})})]})]})})}function Ov(e){const{dataZoom:t=qt,...n}=e;return{...n,dataZoom:t}}function Pv(e){const t={scatter:{label_overflow:vo}};return x.defaultsDeep(t,e)}function Bv(e){const{color:t}=e.scatter;return typeof t=="string"?{...e,scatter:{...e.scatter,color:{...cn.static,color:t}}}:e}function Vv(e){const t=e.reference_lines.map(n=>{const{lineStyle:r={type:"dashed",width:1,color:ct.random().css()},show_in_legend:a=!1,yAxisIndex:o=0}=n;return{...n,lineStyle:r,show_in_legend:a,yAxisIndex:o}});return{...e,reference_lines:t}}function Nv(e){const t={tooltip:{trigger:"item"}};return x.defaultsDeep({},e,t)}function qv(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=c=>c&&`${n}.${c}`,{x_axis:a,scatter:o,tooltip:l,...u}=e;return{...u,x_axis:{...a,data_key:r(a.data_key)},scatter:{...o,y_data_key:r(o.y_data_key),name_data_key:r(o.name_data_key)},tooltip:{...l,metrics:l.metrics.map(c=>({...c,data_key:r(c.data_key)}))}}}catch(n){throw console.error("[Migration failed]",n),n}}class Fv extends ye{constructor(){super(...arguments);N(this,"VERSION",9)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,n=>{const{tooltip:r={metrics:[]},...a}=n.config;return{...n,version:2,config:{...a,tooltip:r}}}),this.version(3,n=>({...n,version:3,config:Ov(n.config)})),this.version(4,n=>{const{config:r}=n;return{...n,version:5,config:Pv(r)}}),this.version(6,n=>{const{config:r}=n;return{...n,version:6,config:Bv(r)}}),this.version(7,n=>{const{config:r}=n;return{...n,version:7,config:Vv(r)}}),this.version(8,n=>{const{config:r}=n;return{...n,version:8,config:Nv(r)}}),this.version(9,(n,r)=>{const{config:a}=n;return{...n,version:9,config:qv(a,r)}})}}const Gv={displayName:"Scatter Chart",displayGroup:"ECharts-based charts",migrator:new Fv,name:"scatterChart",viewRender:Jb,configRender:Lv,createConfig(){return{version:9,config:x.cloneDeep(li)}},triggers:[yo]},ui={template:"The variable ${value} is defined in Variables section",vertical_align:"center",horizontal_align:"left"};function Wv(e){if("variables"in e)return e;const{align:t,size:n,weight:r,color:a,content:{prefix:o="",data_field:l="value",formatter:u={output:"number",mantissa:0},postfix:c=""}={}}=e;return{align:t,template:`${o} \${value} ${c}`,variables:[{name:"value",data_field:l,aggregation:{type:"none",config:{}},formatter:u,color:a,weight:r,size:n}]}}function jv(e){return x.omit(e,["variables"])}function Rv(e){const{align:t,...n}=e;return{horizontal_align:t,vertical_align:"center",...n}}function Yv(e){const t=x.cloneDeep(e),n=x.get(t,"color.valueRange");return n!==void 0&&x.set(t,"color.valueRange",n.map(r=>Number(r))),t}class Qv extends ye{constructor(){super(...arguments);N(this,"VERSION",2)}configVersions(){this.version(1,n=>({version:1,config:Wv(n)})),this.version(2,(n,{panelModel:r})=>{const{config:a}=n;return(a.variables||[]).forEach(l=>{r.variables.find(u=>u.name===l.name)||r.addVariable(Yv(l))}),{...n,version:2,config:jv(a)}}),this.version(3,n=>{const{config:r}=n;return{...n,version:3,config:Rv(r)}})}}const Uv={left:"flex-start",center:"center",right:"flex-end"},Kv={top:"flex-start",center:"center",bottom:"flex-end"},Xv=k.observer(({context:e})=>{const t=we(),{value:n=ui}=R(e.instanceData,"config"),{variables:r}=e,{template:a,horizontal_align:o,vertical_align:l}=n,{width:u,height:c}=e.viewport,d=y.useMemo(()=>{try{return x.template(a)(t.payloadForSQL)}catch{return a}},[t.payloadForSQL,a]),f=y.useMemo(()=>un(d,r,e.data),[d,r,e.data,e]);return i(s.Center,{sx:{width:u,height:c,justifyContent:Uv[o],alignItems:Kv[l]},children:i(s.Box,{children:Object.values(f).map((h,g)=>i(y.Fragment,{children:h},g))})})}),Jv=[{label:"Left",value:"left"},{label:"Center",value:"center"},{label:"Right",value:"right"}],Zv=[{label:"Top",value:"top"},{label:"Center",value:"center"},{label:"Bottom",value:"bottom"}];function Hv({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=y.useMemo(()=>x.defaultsDeep({},t,ui),[t]),{control:a,handleSubmit:o,watch:l,getValues:u,reset:c}=v.useForm({defaultValues:r});y.useEffect(()=>{c(r)},[r]),l(["template","horizontal_align","vertical_align"]);const d=u(),f=y.useMemo(()=>!x.isEqual(d,t),[d,t]);return i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:o(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{weight:500,children:"Stats Configurations"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!f,children:i(T.DeviceFloppy,{size:20})})]}),i(v.Controller,{name:"template",control:a,render:({field:h})=>i(en,{label:"Template",py:"md",sx:{flexGrow:1},...h})}),p(s.SimpleGrid,{cols:2,children:[i(v.Controller,{name:"horizontal_align",control:a,render:({field:h})=>i(s.Select,{label:"Horizontal Alignment",data:Jv,...h})}),i(v.Controller,{control:a,name:"vertical_align",render:({field:h})=>i(s.Select,{label:"Vertical Alignment",data:Zv,...h})})]})]})})}const ex={createConfig(){return{version:3,config:ui}},displayName:"Stats",displayGroup:"Others",migrator:new Qv,name:"stats",viewRender:Xv,configRender:Hv},ci={label_key:"",value_key:"",group_key:"",levels:[]};function tx(e){const t=new Set(e.map(r=>r.parent_id)),n=new Set(e.map(r=>r.id));return t.forEach(r=>{r===null||n.has(r)||e.push({id:r,name:r,parent_id:null})}),e}function nx(e){const t=tx(e).map(a=>({...a,children:[]})),n=x.keyBy(t,a=>a.id),r=[];return t.forEach(a=>{if(!a.parent_id||!n[a.parent_id]){r.push(a);return}n[a.parent_id].children.push(a)}),r}function rx(e,t){const{label_key:n,value_key:r,group_key:a}=e;if(!n||!r)return[];const o=O(n),l=O(r),u=O(a),c=t[o.queryID].map(d=>({...d,id:d[o.columnKey],parent_id:d[u.columnKey],name:d[o.columnKey],value:d[l.columnKey]?Number(d[l.columnKey]):d[l.columnKey]}));return a?nx(c):c}const ix=e=>({treePathInfo:t,name:n,value:r})=>{if(t.length===1||!e)return n;try{const a=t[t.length-2].value;if(r/a<e)return" "}catch{return n}};function ax(e){const{levels:t}=e;return t.map(n=>{const{show_label_tolerance:r,...a}=n.label;return{...n,label:{...a,formatter:ix(r)}}})}function sx(){return({treePathInfo:e,name:t,value:n,color:r,marker:a,...o})=>{const l=e.slice(0,e.length-1),u=[`<tr>
276
+ `}}}function Yb(e,t){const n=t.every(a=>!Number.isNaN(Number(a))),{axisLabel:r}=e.x_axis;return[{data:t,name:e.x_axis.name??"",id:"main-x-axis",axisTick:{show:!0,alignWithLabel:!0},type:n?"value":"category",axisLabel:{...r,formatter:xo(r.formatter)}}]}function Qb(e,t){return e.y_axes.map(({nameAlignment:n,min:r,max:a,...o},l)=>{let u=o.position;return u||(u=l>0?"right":"left"),{...o,minInterval:1,min:r||void 0,max:a||void 0,position:u,axisLabel:{show:!0,formatter:t[l]??t.default},axisLine:{show:!0},nameTextStyle:{fontWeight:"bold",align:n},nameLocation:"end",nameGap:15,splitLine:{show:!1}}})}const Ub={xAxis:[{type:"category",nameGap:25,nameLocation:"center",nameTextStyle:{fontWeight:"bold"},splitLine:{show:!1},axisTick:{show:!0,alignWithLabel:!0}}],grid:{top:10,left:20,right:15,bottom:25,containLabel:!0}};function Kb(e,t,n){const r=n.reduce((c,d)=>{const f=ft(d,t);return c[d.name]=Ze(d,f),c},{}),a=e.y_axes.reduce((c,{label_formatter:d},f)=>(c[f]=function(g){let m=g;if(typeof g=="object"&&(Array.isArray(g.value)&&g.value.length===2?m=g.value[1]:m=g.value),!d)return m;try{return Z(m).format(d)}catch(C){return console.error(C),m}},c),{default:({value:c})=>c}),o=x.uniq(pt(t,e.x_axis.data_key)),l=Gb(e,t,n,r),u={xAxis:Yb(e,o),yAxis:Qb(e,a),series:l,dataset:Lb(e,t),tooltip:Rb(e,a),grid:Ob(e),legend:Pb(),dataZoom:Xr(e.dataZoom)};return x.defaultsDeep({},u,Ub)}ie.use([q.DataZoomComponent,he.BarChart,he.LineChart,he.ScatterChart,q.GridComponent,q.LegendComponent,q.TooltipComponent,Pe.CanvasRenderer,q.MarkLineComponent,q.MarkAreaComponent]);function Co(e){return e.trim().length>0}function Xb({conf:e,data:t,width:n,height:r,interactionManager:a,variables:o}){const l=Dt(t,e.x_axis.data_key),u=Ke(a.triggerManager,yo.id),c=b.useCallback(h=>{const g=h.data;u.forEach(m=>{a.runInteraction(m.id,{...h,rowData:g})})},[l,u,a]),d=b.useMemo(()=>({click:c}),[c]),f=b.useMemo(()=>Kb(e,t,o),[e,t]);return i(Be,{echarts:ie,option:f,style:{width:n,height:r},onEvents:d,notMerge:!0,theme:"merico-light"})}function Jb({context:e,instance:t}){const n=Xe({vizManager:e.vizManager,instance:t}),{value:r}=R(e.instanceData,"config"),{variables:a}=e,o=b.useMemo(()=>x.defaults({},r,li),[r]),l=e.data,{width:u,height:c}=e.viewport,{ref:d,height:f}=Ie.useElementSize(),{ref:h,height:g}=Ie.useElementSize(),m=b.useMemo(()=>{const{stats:{templates:w}}=o;return{top:cn(w.top,a,l),bottom:cn(w.bottom,a,l)}},[o,l]),C=Math.max(0,c-f-g);return!u||!c?null:p(B,{children:[i(s.Text,{ref:d,align:"left",size:"xs",pl:"sm",sx:{display:Co(o.stats.templates.top)?"block":"none"},children:Object.values(m.top).map(w=>w)}),i(Xb,{variables:a,width:u,height:C,data:l,conf:o,interactionManager:n}),i(s.Text,{ref:h,align:"left",size:"xs",pl:"sm",sx:{display:Co(o.stats.templates.bottom)?"block":"none"},children:Object.values(m.bottom).map(w=>w)})]})}const Zb=b.forwardRef(({value:e,onChange:t,xAxisOptions:n,yAxisOptions:r,variableOptions:a},o)=>{const l=(u,c)=>{const d=x.cloneDeep(e);x.set(d,u,c),t(d)};return p(s.Stack,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Content",labelPosition:"right"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(s.TextInput,{label:"Content Text",value:e.content.text,onChange:u=>l("content.text",u.currentTarget.value)}),i(ti,{label:"Text Position",value:e.label.position,onChange:u=>l("label.position",u)})]}),i(s.Divider,{mb:-15,variant:"dashed",label:"Endpoints",labelPosition:"right"}),p(s.Group,{grow:!0,noWrap:!0,children:[n&&i(s.Select,{label:"X Axis",data:n,value:e.xAxisIndex,onChange:u=>l("xAxisIndex",u)}),r&&i(s.Select,{label:"Y Axis",data:r,value:e.yAxisIndex,onChange:u=>l("xAxisIndex",u)})]}),p(s.Stack,{spacing:0,children:[i(s.Text,{size:14,color:"#212529",fw:500,children:"Left-Bottom Point"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(s.Select,{icon:i(s.Text,{children:"x"}),data:a,value:e.leftBottomPoint.x_data_key,onChange:u=>l("leftBottomPoint.x_data_key",u??""),clearable:!0}),i(s.Select,{icon:i(s.Text,{children:"y"}),data:a,value:e.leftBottomPoint.y_data_key,onChange:u=>l("leftBottomPoint.y_data_key",u??""),clearable:!0})]})]}),p(s.Stack,{spacing:0,children:[i(s.Text,{size:14,color:"#212529",fw:500,children:"Right-Top Point"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(s.Select,{icon:i(s.Text,{children:"x"}),data:a,value:e.rightTopPoint.x_data_key,onChange:u=>l("rightTopPoint.x_data_key",u??""),clearable:!0}),i(s.Select,{icon:i(s.Text,{children:"y"}),data:a,value:e.rightTopPoint.y_data_key,onChange:u=>l("rightTopPoint.y_data_key",u??""),clearable:!0})]})]}),i(s.Divider,{mb:-15,variant:"dashed",label:"Style",labelPosition:"right"}),p(s.Stack,{spacing:4,children:[i(s.Text,{size:14,children:"Background Color"}),i(Ve,{value:e.itemStyle.color,onChange:u=>l("itemStyle.color",u)})]}),p(s.Stack,{spacing:4,children:[i(s.Text,{size:14,children:"Text Color"}),i(Ve,{value:e.label.color,onChange:u=>l("label.color",u)})]})]})});function Hb(){const e=new Date().getTime().toString();return{id:e,content:{text:e},itemStyle:{color:"rgba(0,0,0,0.05)"},label:{position:"inside",color:"rgba(0,0,0,0.5)"},leftBottomPoint:{x_data_key:"",y_data_key:""},rightTopPoint:{x_data_key:"",y_data_key:""},xAxisIndex:"0",yAxisIndex:"0"}}function ev({control:e,watch:t,variables:n}){const{fields:r,append:a,remove:o}=v.useFieldArray({control:e,name:"reference_areas"}),l=t("reference_areas"),u=r.map((g,m)=>({...g,...l[m]})),c=()=>{const g=Hb();a(g)},d=b.useMemo(()=>n.map(g=>({label:g.name,value:g.name})),[n]),f=t("y_axes"),h=b.useMemo(()=>f.map(({name:g},m)=>({label:g,value:m.toString()})),[f]);return p(s.Tabs,{defaultValue:"0",styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px"}},children:[p(s.Tabs.List,{children:[u.map((g,m)=>i(s.Tabs.Tab,{value:m.toString(),children:m+1},m)),i(s.Tabs.Tab,{onClick:c,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),u.map((g,m)=>i(s.Tabs.Panel,{value:m.toString(),children:i(v.Controller,{name:`reference_areas.${m}`,control:e,render:({field:C})=>p(s.Stack,{children:[i(Zb,{variableOptions:d,yAxisOptions:h,...C}),i(s.Divider,{mb:-10,mt:10,variant:"dashed"}),i(s.Button,{leftIcon:i($.IconTrash,{size:16}),color:"red",variant:"light",onClick:()=>o(m),children:"Delete this Reference Area"})]})})},m))]})}const tv=[{label:"solid",value:"solid"},{label:"dashed",value:"dashed"},{label:"dotted",value:"dotted"}],nv=[{label:"Horizontal",value:"horizontal"},{label:"Vertical",value:"vertical"}];function rv({control:e,index:t,remove:n,watch:r,variableOptions:a,yAxisOptions:o}){const l=r(`reference_lines.${t}.orientation`);return p(s.Stack,{my:0,p:0,sx:{position:"relative"},children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`reference_lines.${t}.name`,control:e,render:({field:u})=>i(s.TextInput,{label:"Name",placeholder:"Average Reference Line",required:!0,sx:{flex:1},...u})}),i(v.Controller,{name:`reference_lines.${t}.variable_key`,control:e,render:({field:u})=>i(s.Select,{label:"Value",required:!0,data:a,sx:{flex:1},...u})})]}),i(v.Controller,{name:`reference_lines.${t}.template`,control:e,render:({field:u})=>i(s.TextInput,{label:"Content Template",placeholder:"Average: ${avg}",sx:{flex:1},...u})}),p(s.Group,{grow:!0,children:[p(s.Stack,{children:[i(v.Controller,{name:`reference_lines.${t}.orientation`,control:e,render:({field:u})=>i(s.Select,{label:"Orientation",data:nv,required:!0,sx:{flex:1},...u})}),l==="vertical"&&i(s.Text,{mt:-10,color:"dimmed",size:12,children:"Works only when xAxis values are numbers"})]}),l==="horizontal"&&i(v.Controller,{name:`reference_lines.${t}.yAxisIndex`,control:e,render:({field:{value:u,onChange:c,...d}})=>i(s.Select,{label:"Y Axis",data:o,disabled:o.length===0,...d,value:(u==null?void 0:u.toString())??"",onChange:f=>{if(!f){c(0);return}c(Number(f))},sx:{flex:1}})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Style",labelPosition:"center"}),p(s.Group,{grow:!0,children:[i(v.Controller,{name:`reference_lines.${t}.lineStyle.type`,control:e,render:({field:u})=>i(s.Select,{label:"Line Type",data:tv,sx:{flexGrow:1},...u})}),i(v.Controller,{name:`reference_lines.${t}.lineStyle.width`,control:e,render:({field:u})=>i(s.NumberInput,{label:"Line Width",min:1,max:10,sx:{flexGrow:1},...u})})]}),p(s.Stack,{spacing:4,children:[i(s.Text,{size:"sm",children:"Color"}),i(v.Controller,{name:`reference_lines.${t}.lineStyle.color`,control:e,render:({field:u})=>i(Ve,{...u})})]}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Reference Line"})]},t)}function iv({control:e,watch:t,variables:n}){const{fields:r,append:a,remove:o}=v.useFieldArray({control:e,name:"reference_lines"}),l=t("reference_lines"),u=r.map((g,m)=>({...g,...l[m]})),c=()=>{const g={name:"",template:"",variable_key:"",orientation:"horizontal",lineStyle:{type:"dashed",width:1,color:ct.random().css()},show_in_legend:!1,yAxisIndex:0};a(g)},d=b.useMemo(()=>n.map(g=>({label:g.name,value:g.name})),[n]),f=t("y_axes"),h=b.useMemo(()=>f.map(({name:g},m)=>({label:g,value:m.toString()})),[f]);return p(s.Tabs,{defaultValue:"0",styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px"}},children:[p(s.Tabs.List,{children:[u.map((g,m)=>i(s.Tabs.Tab,{value:m.toString(),children:m+1},m)),i(s.Tabs.Tab,{onClick:c,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),u.map((g,m)=>i(s.Tabs.Panel,{value:m.toString(),children:i(rv,{control:e,index:m,remove:o,watch:t,variableOptions:d,yAxisOptions:h})},m))]})}const av=({value:e,onChange:t})=>{const n=r=>{r&&t(r)};return i(s.Box,{children:i(Ae,{height:"500px",defaultLanguage:"javascript",value:e,onChange:n,theme:"vs-dark",options:{minimap:{enabled:!1}}})})},sv=({value:e,onChange:t})=>{const[n,{setTrue:r,setFalse:a}]=K.useBoolean(),[o,l]=b.useState(e),u=()=>{a();const{type:h,func_content:g}=o,m={type:h,func_content:g};l(m),t(m)},c=()=>{a(),l(e)},d=h=>{l(g=>({...g,func_content:h}))},f=()=>{d(dn.dynamic.func_content)};return p(B,{children:[i(s.Box,{sx:{width:"50%"},children:i(s.Button,{variant:"filled",mt:24,onClick:r,sx:{flexGrow:0},children:"Setup"})}),i(s.Modal,{size:800,title:"Setup dynamic color",opened:n,onClose:a,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:n&&p(s.Stack,{children:[i(s.Divider,{mt:10,mb:-10,label:"Dynamic by a custom function",labelPosition:"center",variant:"dashed"}),i(av,{value:o.func_content,onChange:d}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:f,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:c,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:u,children:"OK"})]})]})]})})]})},ov=({value:e,onChange:t})=>e.type!=="dynamic"?null:i(sv,{value:e,onChange:t}),lv=({value:e,onChange:t})=>{if(e.type!=="static")return null;const n=r=>{t({...e,color:r})};return i(s.ColorInput,{label:" ",format:"rgb",value:e.color,onChange:n})},uv=[{label:"Static",value:"static"},{label:"Dynamic",value:"dynamic"}],cv=b.forwardRef(({label:e="Color",value:t,onChange:n},r)=>{const a=o=>{n({...dn[o]})};return p(s.SimpleGrid,{cols:2,children:[i(s.Select,{ref:r,label:e,data:uv,value:t.type,onChange:a,sx:{flexGrow:1}}),i(lv,{value:t,onChange:n}),i(ov,{value:t,onChange:n})]})}),dv=b.forwardRef(({value:e,onChange:t},n)=>{const r=o=>{t({...e,label:o})},a=o=>{t({...e,tooltip:o})};return p(s.Stack,{ref:n,spacing:0,children:[i(Tn,{sectionTitle:"Overflow on Chart",value:e.label,onChange:r}),i(Tn,{sectionTitle:"Overflow in Tooltip",value:e.tooltip,onChange:a})]})}),pv=({value:e,onChange:t})=>{const n=r=>{r&&t(r)};return i(s.Box,{children:i(Ae,{height:"500px",defaultLanguage:"javascript",value:e,onChange:n,theme:"vs-dark",options:{minimap:{enabled:!1}}})})},So={static:{type:"static",size:10},dynamic:{type:"dynamic",func_content:["function getSize({ rowData, params, variables }, { lodash, interpolate }) {"," // your code goes here"," // return 10","}"].join(`
277
+ `)}},hv=({value:e,onChange:t})=>{const[n,{setTrue:r,setFalse:a}]=K.useBoolean(),[o,l]=b.useState(e),u=()=>{a();const{type:h,func_content:g}=o,m={type:h,func_content:g};l(m),t(m)},c=()=>{a(),l(e)},d=h=>{l(g=>({...g,func_content:h}))},f=()=>{d(So.dynamic.func_content)};return p(B,{children:[i(s.Box,{sx:{width:"50%"},children:i(s.Button,{variant:"filled",mt:24,onClick:r,sx:{flexGrow:0},children:"Setup"})}),i(s.Modal,{size:800,title:"Setup dynamic size",opened:n,onClose:a,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:n&&p(s.Stack,{children:[i(s.Divider,{mt:10,mb:-10,label:"Dynamic by a custom function",labelPosition:"center",variant:"dashed"}),i(pv,{value:o.func_content,onChange:d}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:f,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:c,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:u,children:"OK"})]})]})]})})]})},fv=({value:e,onChange:t})=>e.type!=="dynamic"?null:i(hv,{value:e,onChange:t}),gv=({value:e,onChange:t})=>{if(e.type!=="static")return null;const n=r=>{t({...e,size:r})};return i(B,{children:i(s.NumberInput,{defaultValue:18,placeholder:"1 ~ 100",label:" ",hideControls:!0,value:e.size,onChange:n})})},mv=[{label:"Static",value:"static"},{label:"Dynamic",value:"dynamic"}],yv=b.forwardRef(({label:e="Size",value:t,onChange:n},r)=>{const a=o=>{n({...So[o]})};return p(s.SimpleGrid,{cols:2,children:[i(s.Select,{ref:r,label:e,data:mv,value:t.type,onChange:a,sx:{flexGrow:1}}),i(gv,{value:t,onChange:n}),i(fv,{value:t,onChange:n})]})}),bv=[{label:"off",value:""},{label:"top",value:"top"},{label:"left",value:"left"},{label:"right",value:"right"},{label:"bottom",value:"bottom"},{label:"inside",value:"inside"},{label:"insideLeft",value:"insideLeft"},{label:"insideRight",value:"insideRight"},{label:"insideTop",value:"insideTop"},{label:"insideBottom",value:"insideBottom"},{label:"insideTopLeft",value:"insideTopLeft"},{label:"insideBottomLeft",value:"insideBottomLeft"},{label:"insideTopRight",value:"insideTopRight"},{label:"insideBottomRight",value:"insideBottomRight"}];function vv({control:e,watch:t}){return t(["scatter"]),p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"scatter.name_data_key",control:e,render:({field:n})=>i(W,{label:"Name Data Field",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"scatter.y_data_key",control:e,render:({field:n})=>i(W,{label:"Value Data Field",required:!0,sx:{flex:1},...n})})]}),i(s.Divider,{mb:-15,label:"Style",labelPosition:"center"}),i(v.Controller,{name:"scatter.symbolSize",control:e,render:({field:n})=>i(yv,{label:"Size",...n})}),i(v.Controller,{name:"scatter.color",control:e,render:({field:n})=>i(cv,{...n})}),i(s.Divider,{mb:-15,label:"Label",labelPosition:"center"}),i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:"scatter.label_position",control:e,render:({field:n})=>i(s.Select,{label:"Label Position",data:bv,...n})})}),i(v.Controller,{name:"scatter.label_overflow",control:e,render:({field:n})=>i(dv,{...n})})]})}function xv({control:e,watch:t}){return t("stats"),i(s.Stack,{children:p(s.Stack,{spacing:0,children:[i(v.Controller,{name:"stats.templates.top",control:e,render:({field:n})=>i(tn,{label:"Template for stats above the chart",py:"md",sx:{flexGrow:1},...n})}),i(v.Controller,{name:"stats.templates.bottom",control:e,render:({field:n})=>i(tn,{label:"Template for stats under the chart",py:"md",sx:{flexGrow:1},...n})})]})})}const wv=({control:e,index:t,remove:n})=>p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`tooltip.metrics.${t}.name`,control:e,render:({field:r})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:`tooltip.metrics.${t}.data_key`,control:e,render:({field:r})=>i(W,{label:"Value Field",required:!0,sx:{flex:1},...r})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed"}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Metric"})]}),Cv=({control:e,watch:t})=>{const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"tooltip.metrics"}),o=t("tooltip.metrics"),l=n.map((h,g)=>({...h,...o[g]})),u=()=>r({id:Date.now().toString(),data_key:"",name:""}),c=t("tooltip.metrics.0.id"),[d,f]=b.useState(()=>c??null);return b.useEffect(()=>{c&&f(h=>h!==null?h:c)},[c]),p(B,{children:[p(s.Group,{spacing:2,sx:{cursor:"default",userSelect:"none"},children:[i(T.InfoCircle,{size:14,color:"#888"}),i(s.Text,{size:14,color:"#888",children:"Configure additional metrics to show in tooltip"})]}),p(s.Tabs,{value:d,onTabChange:h=>f(h),styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map((h,g)=>i(s.Tabs.Tab,{value:h.id,children:h.name?h.name:g},h.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((h,g)=>i(s.Tabs.Panel,{value:h.id,children:i(wv,{control:e,index:g,remove:a},h.id)},h.id))]})]})},Sv=[{label:"Scatter Point",value:"item"},{label:"X Axis",value:"axis"}];function _v({control:e,watch:t}){return t("tooltip.trigger"),p(s.Stack,{children:[i(v.Controller,{name:"tooltip.trigger",control:e,render:({field:n})=>i(s.Select,{label:"Trigger",data:Sv,sx:{flexGrow:1},...n})}),i(s.Divider,{variant:"dashed"}),i(Cv,{control:e,watch:t})]})}const kv=({disabled:e,value:t,onChange:n})=>{const r=a=>{a&&n(a)};return p(s.Box,{sx:{position:"relative"},children:[e&&i(s.Overlay,{opacity:.6,color:"#fff",zIndex:5,blur:2}),i(Ae,{height:"500px",defaultLanguage:"javascript",value:t,onChange:r,theme:"vs-dark",options:{minimap:{enabled:!1},readOnly:e}})]})},Tv=b.forwardRef(({value:e,onChange:t},n)=>{const[r,{setTrue:a,setFalse:o}]=K.useBoolean(),[l,u]=b.useState(e);b.useEffect(()=>{u(e)},[e]);const c=m=>{u({...l,enabled:m})},d=()=>{o();const{enabled:m,func_content:C}=l,w={enabled:m,func_content:C};u(w),t(w)},f=()=>{o(),u(e)},h=m=>{u(C=>({...C,func_content:m}))},g=()=>{h(bo.func_content)};return p(B,{children:[i(s.Button,{variant:"filled",mt:24,onClick:a,sx:{flexGrow:0},children:"Customize Label"}),i(s.Modal,{size:800,title:"Customize label content",opened:r,onClose:o,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:r&&p(s.Stack,{children:[i(s.Checkbox,{mt:10,label:"Enabled",checked:l.enabled,onChange:m=>c(m.currentTarget.checked)}),i(kv,{value:l.func_content,onChange:h,disabled:!l.enabled}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:g,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:f,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:d,children:"OK"})]})]})]})})]})});function Dv({control:e,watch:t}){return t(["x_axis"]),p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.data_key",control:e,render:({field:n})=>i(W,{label:"Data Field",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"x_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Name",sx:{flex:1},...n})})]}),i(s.Divider,{mb:-15,label:"Tick Label",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.axisLabel.rotate",control:e,render:({field:n})=>i(s.NumberInput,{label:"Rotate",hideControls:!0,min:-90,max:90,rightSection:i(s.Text,{color:"dimmed",children:"degree"}),sx:{width:"48%"},styles:{rightSection:{width:"4em",justifyContent:"flex-end",paddingRight:"6px"}},...n})}),i(v.Controller,{name:"x_axis.axisLabel.formatter",control:e,render:({field:n})=>i(Tv,{...n})})]})]})}const Iv=[{label:"left",value:"left"},{label:"center",value:"center"},{label:"right",value:"right"}],Mv=[{label:"left",value:"left"},{label:"right",value:"right"}];function Av({control:e,index:t,remove:n}){return p(s.Stack,{my:0,p:"0",sx:{position:"relative"},children:[i(s.Divider,{mb:-15,mt:15,variant:"dashed",label:"Name",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`y_axes.${t}.name`,control:e,render:({field:r})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:`y_axes.${t}.nameAlignment`,control:e,render:({field:r})=>i(s.Select,{label:"Align",required:!0,data:Iv,sx:{flex:1},...r})})]}),i(s.Divider,{mb:-15,variant:"dashed",label:"Layout",labelPosition:"center"}),i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:`y_axes.${t}.position`,control:e,render:({field:r})=>i(s.Select,{label:"Position",required:!0,data:Mv,sx:{flex:1},...r})})}),p(s.Stack,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Label Format",labelPosition:"center"}),i(v.Controller,{name:`y_axes.${t}.label_formatter`,control:e,render:({field:r})=>i(je,{...r})})]}),p(s.Stack,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Value Range",labelPosition:"center"}),p(s.Group,{grow:!0,children:[i(v.Controller,{name:`y_axes.${t}.min`,control:e,render:({field:r})=>i(s.TextInput,{label:"Min",...r})}),i(v.Controller,{name:`y_axes.${t}.max`,control:e,render:({field:r})=>i(s.TextInput,{label:"Max",...r})})]})]}),i(s.Button,{mt:20,leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),disabled:t===0,children:"Delete this YAxis"})]})}function zv({control:e,watch:t}){const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"y_axes"}),o=t("y_axes"),l=n.map((c,d)=>({...c,...o[d]})),u=()=>r({name:"",label_formatter:ze,min:"",max:"",show:!0,position:"right",nameAlignment:"right"});return p(s.Tabs,{defaultValue:"0",styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px"}},children:[p(s.Tabs.List,{children:[l.map((c,d)=>i(s.Tabs.Tab,{value:d.toString(),children:d+1},d)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((c,d)=>i(s.Tabs.Panel,{value:d.toString(),children:i(Av,{control:e,index:d,remove:a})},d))]})}function Ev(e){return e||{templates:{top:"",bottom:""}}}function $v({reference_lines:e=[],stats:t,...n}){return{reference_lines:e,stats:Ev(t),...n}}function Lv({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),{variables:r}=e,a=b.useMemo(()=>x.defaultsDeep({},t,li),[t]),o=b.useMemo(()=>$v(a),[a]);b.useEffect(()=>{!x.isEqual(a,o)&&(console.log("config malformed, resetting to defaults",a,o),n(o))},[a,o]);const{control:l,handleSubmit:u,watch:c,getValues:d,reset:f}=v.useForm({defaultValues:o});b.useEffect(()=>{f(o)},[o]);const h=d(),g=b.useMemo(()=>!x.isEqual(h,a),[h,a]);return c(["dataZoom"]),i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:u(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!g,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"X Axis",orientation:"vertical",styles:{tab:{paddingLeft:"6px",paddingRight:"6px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"X Axis",children:"X Axis"}),i(s.Tabs.Tab,{value:"Y Axes",children:"Y Axes"}),i(s.Tabs.Tab,{value:"Scatter",children:"Scatter"}),i(s.Tabs.Tab,{value:"Tooltip",children:"Tooltip"}),i(s.Tabs.Tab,{value:"Stats",children:"Stats"}),i(s.Tabs.Tab,{value:"Reference Lines",children:"Reference Lines"}),i(s.Tabs.Tab,{value:"Reference Areas",children:"Reference Areas"}),i(s.Tabs.Tab,{value:"Zooming",children:"Zooming"})]}),i(s.Tabs.Panel,{value:"X Axis",children:i(Dv,{control:l,watch:c})}),i(s.Tabs.Panel,{value:"Y Axes",children:i(zv,{control:l,watch:c})}),i(s.Tabs.Panel,{value:"Scatter",children:i(vv,{control:l,watch:c})}),i(s.Tabs.Panel,{value:"Tooltip",children:i(_v,{control:l,watch:c})}),i(s.Tabs.Panel,{value:"Stats",children:i(xv,{control:l,watch:c})}),i(s.Tabs.Panel,{value:"Reference Lines",children:i(iv,{variables:r,control:l,watch:c})}),i(s.Tabs.Panel,{value:"Reference Areas",children:i(ev,{variables:r,control:l,watch:c})}),i(s.Tabs.Panel,{value:"Zooming",children:i(v.Controller,{name:"dataZoom",control:l,render:({field:m})=>i(Zr,{...m})})})]})]})})}function Ov(e){const{dataZoom:t=qt,...n}=e;return{...n,dataZoom:t}}function Pv(e){const t={scatter:{label_overflow:vo}};return x.defaultsDeep(t,e)}function Bv(e){const{color:t}=e.scatter;return typeof t=="string"?{...e,scatter:{...e.scatter,color:{...dn.static,color:t}}}:e}function Vv(e){const t=e.reference_lines.map(n=>{const{lineStyle:r={type:"dashed",width:1,color:ct.random().css()},show_in_legend:a=!1,yAxisIndex:o=0}=n;return{...n,lineStyle:r,show_in_legend:a,yAxisIndex:o}});return{...e,reference_lines:t}}function Nv(e){const t={tooltip:{trigger:"item"}};return x.defaultsDeep({},e,t)}function qv(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=c=>c&&`${n}.${c}`,{x_axis:a,scatter:o,tooltip:l,...u}=e;return{...u,x_axis:{...a,data_key:r(a.data_key)},scatter:{...o,y_data_key:r(o.y_data_key),name_data_key:r(o.name_data_key)},tooltip:{...l,metrics:l.metrics.map(c=>({...c,data_key:r(c.data_key)}))}}}catch(n){throw console.error("[Migration failed]",n),n}}class Fv extends ye{constructor(){super(...arguments);N(this,"VERSION",9)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,n=>{const{tooltip:r={metrics:[]},...a}=n.config;return{...n,version:2,config:{...a,tooltip:r}}}),this.version(3,n=>({...n,version:3,config:Ov(n.config)})),this.version(4,n=>{const{config:r}=n;return{...n,version:5,config:Pv(r)}}),this.version(6,n=>{const{config:r}=n;return{...n,version:6,config:Bv(r)}}),this.version(7,n=>{const{config:r}=n;return{...n,version:7,config:Vv(r)}}),this.version(8,n=>{const{config:r}=n;return{...n,version:8,config:Nv(r)}}),this.version(9,(n,r)=>{const{config:a}=n;return{...n,version:9,config:qv(a,r)}})}}const Gv={displayName:"Scatter Chart",displayGroup:"ECharts-based charts",migrator:new Fv,name:"scatterChart",viewRender:Jb,configRender:Lv,createConfig(){return{version:9,config:x.cloneDeep(li)}},triggers:[yo]},ui={template:"The variable ${value} is defined in Variables section",vertical_align:"center",horizontal_align:"left"};function Wv(e){if("variables"in e)return e;const{align:t,size:n,weight:r,color:a,content:{prefix:o="",data_field:l="value",formatter:u={output:"number",mantissa:0},postfix:c=""}={}}=e;return{align:t,template:`${o} \${value} ${c}`,variables:[{name:"value",data_field:l,aggregation:{type:"none",config:{}},formatter:u,color:a,weight:r,size:n}]}}function jv(e){return x.omit(e,["variables"])}function Rv(e){const{align:t,...n}=e;return{horizontal_align:t,vertical_align:"center",...n}}function Yv(e){const t=x.cloneDeep(e),n=x.get(t,"color.valueRange");return n!==void 0&&x.set(t,"color.valueRange",n.map(r=>Number(r))),t}class Qv extends ye{constructor(){super(...arguments);N(this,"VERSION",2)}configVersions(){this.version(1,n=>({version:1,config:Wv(n)})),this.version(2,(n,{panelModel:r})=>{const{config:a}=n;return(a.variables||[]).forEach(l=>{r.variables.find(u=>u.name===l.name)||r.addVariable(Yv(l))}),{...n,version:2,config:jv(a)}}),this.version(3,n=>{const{config:r}=n;return{...n,version:3,config:Rv(r)}})}}const Uv={left:"flex-start",center:"center",right:"flex-end"},Kv={top:"flex-start",center:"center",bottom:"flex-end"},Xv=k.observer(({context:e})=>{const t=we(),{value:n=ui}=R(e.instanceData,"config"),{variables:r}=e,{template:a,horizontal_align:o,vertical_align:l}=n,{width:u,height:c}=e.viewport,d=b.useMemo(()=>{try{return x.template(a)(t.payloadForSQL)}catch{return a}},[t.payloadForSQL,a]),f=b.useMemo(()=>cn(d,r,e.data),[d,r,e.data,e]);return i(s.Center,{sx:{width:u,height:c,justifyContent:Uv[o],alignItems:Kv[l]},children:i(s.Box,{children:Object.values(f).map((h,g)=>i(b.Fragment,{children:h},g))})})}),Jv=[{label:"Left",value:"left"},{label:"Center",value:"center"},{label:"Right",value:"right"}],Zv=[{label:"Top",value:"top"},{label:"Center",value:"center"},{label:"Bottom",value:"bottom"}];function Hv({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=b.useMemo(()=>x.defaultsDeep({},t,ui),[t]),{control:a,handleSubmit:o,watch:l,getValues:u,reset:c}=v.useForm({defaultValues:r});b.useEffect(()=>{c(r)},[r]),l(["template","horizontal_align","vertical_align"]);const d=u(),f=b.useMemo(()=>!x.isEqual(d,t),[d,t]);return i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:o(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{weight:500,children:"Stats Configurations"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!f,children:i(T.DeviceFloppy,{size:20})})]}),i(v.Controller,{name:"template",control:a,render:({field:h})=>i(tn,{label:"Template",py:"md",sx:{flexGrow:1},...h})}),p(s.SimpleGrid,{cols:2,children:[i(v.Controller,{name:"horizontal_align",control:a,render:({field:h})=>i(s.Select,{label:"Horizontal Alignment",data:Jv,...h})}),i(v.Controller,{control:a,name:"vertical_align",render:({field:h})=>i(s.Select,{label:"Vertical Alignment",data:Zv,...h})})]})]})})}const ex={createConfig(){return{version:3,config:ui}},displayName:"Stats",displayGroup:"Others",migrator:new Qv,name:"stats",viewRender:Xv,configRender:Hv},ci={label_key:"",value_key:"",group_key:"",levels:[]};function tx(e){const t=new Set(e.map(r=>r.parent_id)),n=new Set(e.map(r=>r.id));return t.forEach(r=>{r===null||n.has(r)||e.push({id:r,name:r,parent_id:null})}),e}function nx(e){const t=tx(e).map(a=>({...a,children:[]})),n=x.keyBy(t,a=>a.id),r=[];return t.forEach(a=>{if(!a.parent_id||!n[a.parent_id]){r.push(a);return}n[a.parent_id].children.push(a)}),r}function rx(e,t){const{label_key:n,value_key:r,group_key:a}=e;if(!n||!r)return[];const o=O(n),l=O(r),u=O(a),c=t[o.queryID].map(d=>({...d,id:d[o.columnKey],parent_id:d[u.columnKey],name:d[o.columnKey],value:d[l.columnKey]?Number(d[l.columnKey]):d[l.columnKey]}));return a?nx(c):c}const ix=e=>({treePathInfo:t,name:n,value:r})=>{if(t.length===1||!e)return n;try{const a=t[t.length-2].value;if(r/a<e)return" "}catch{return n}};function ax(e){const{levels:t}=e;return t.map(n=>{const{show_label_tolerance:r,...a}=n.label;return{...n,label:{...a,formatter:ix(r)}}})}function sx(){return({treePathInfo:e,name:t,value:n,color:r,marker:a,...o})=>{const l=e.slice(0,e.length-1),u=[`<tr>
278
278
  <th style="text-align: right; padding: 0 1em;">Value</th>
279
279
  <td style="text-align: left; padding: 0 1em;">${n}</td>
280
280
  </tr>
@@ -292,9 +292,9 @@ Check the top-level render call using <`+V+">.")}return E}}function Su(S,E){{if(
292
292
  <table style="width: auto">
293
293
  <tbody>${u.join("")}</tbody>
294
294
  </table>
295
- `}}function ox(){return{show:!0,trigger:"item",confine:!0,formatter:sx()}}const lx={tooltip:{show:!0},series:{type:"sunburst",radius:[0,"90%"],emphasis:{focus:"ancestor"}}};function ux(e,t,n){n.reduce((o,l)=>{const u=ft(l,t);return o[l.name]=Ze(l,u),o},{});const a={series:{data:rx(e,t),levels:ax(e)},tooltip:ox()};return x.defaultsDeep({},a,lx)}ie.use([he.SunburstChart,Pe.CanvasRenderer]);function cx({context:e}){const{variables:t}=e,{value:n}=R(e.instanceData,"config"),r=y.useMemo(()=>x.defaults({},n,ci),[n]),a=e.data,{width:o,height:l}=e.viewport,u=y.useMemo(()=>ux(r,a,t),[r,a,t]);return!o||!l?null:i(Be,{echarts:ie,option:u,style:{width:o,height:l},notMerge:!0,theme:"merico-light"})}function dx({control:e,watch:t}){return t(["label_key","value_key","group_key"]),p(s.Stack,{children:[i(v.Controller,{name:"label_key",control:e,render:({field:n})=>i(W,{label:"Label Key",required:!0,...n})}),i(v.Controller,{name:"value_key",control:e,render:({field:n})=>i(W,{label:"Value Key",required:!0,...n})}),i(v.Controller,{name:"group_key",control:e,render:({field:n})=>i(W,{label:"Group Key",clearable:!0,...n})})]})}const px=[{label:"Radial",value:"radial"},{label:"Tangential",value:"tangential"},{label:"None",value:"0"}],hx=[{label:"Left",value:"left"},{label:"Center",value:"center"},{label:"Right",value:"right"}],fx=({control:e,index:t,remove:n})=>p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`levels.${t}.r0`,control:e,render:({field:r})=>i(s.TextInput,{label:"Inside Radius",placeholder:"0%",...r})}),i(v.Controller,{name:`levels.${t}.r`,control:e,render:({field:r})=>i(s.TextInput,{label:"Outside Radius",placeholder:"50%",...r})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Label Style",labelPosition:"center"}),i(v.Controller,{name:`levels.${t}.label.show_label_tolerance`,control:e,render:({field:r})=>i(s.NumberInput,{label:"Hide label when its percentage is less than...",precision:4,step:5e-4,min:0,max:1,...r})}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`levels.${t}.label.rotate`,control:e,render:({field:r})=>i(s.Select,{label:"Rotate",data:px,...r})}),i(v.Controller,{name:`levels.${t}.label.align`,control:e,render:({field:r})=>i(s.Select,{label:"Align",data:hx,...r})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`levels.${t}.label.position`,control:e,render:({field:r})=>i(ti,{label:"Position",...r})}),i(v.Controller,{name:`levels.${t}.label.padding`,control:e,render:({field:r})=>i(s.NumberInput,{label:"Padding",min:0,hideControls:!0,...r})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed"}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Level"})]}),gx=({control:e,watch:t})=>{const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"levels"}),o=t("levels"),l=n.map((h,g)=>({...h,...o[g]})),u=()=>r({id:Date.now().toString(),r0:"",r:"",label:{show_label_tolerance:.001,rotate:"0",align:"center",position:"inside",padding:0}}),c=t("levels.0.id"),[d,f]=y.useState(()=>c??null);return y.useEffect(()=>{c&&f(h=>h!==null?h:c)},[c]),p(B,{children:[p(s.Group,{spacing:2,sx:{cursor:"default",userSelect:"none"},children:[i(T.InfoCircle,{size:14,color:"#888"}),i(s.Text,{size:14,color:"#888",children:"Configure ring style on each level"})]}),i(s.Divider,{variant:"dashed",my:10}),p(s.Tabs,{value:d,onTabChange:h=>f(h),styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map((h,g)=>i(s.Tabs.Tab,{value:h.id,children:g},h.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((h,g)=>i(s.Tabs.Panel,{value:h.id,children:i(fx,{control:e,index:g,remove:a},h.id)},h.id))]})]})};function mx({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=y.useMemo(()=>x.defaultsDeep({},t,ci),[t]),a=y.useMemo(()=>x.clone(r),[r]),{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});y.useEffect(()=>{d(a)},[a]);const f=c(),h=y.useMemo(()=>!x.isEqual(f,r),[f,r]);u(["label_key","value_key","group_key","levels"]);const[g,m]=y.useState("Data");return i("form",{onSubmit:l(n),children:p(s.Stack,{spacing:"xs",children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Sunburst Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{value:g,onTabChange:m,orientation:"vertical",styles:{tab:{paddingLeft:"6px",paddingRight:"6px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"Data",children:"Data"}),i(s.Tabs.Tab,{value:"Levels",children:"Levels"})]}),i(s.Tabs.Panel,{value:"Data",children:i(dx,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Levels",children:i(gx,{control:o,watch:u})})]})]})})}function yx(e){const{label_field:t,value_field:n,...r}=e;return{...r,label_key:t,value_key:n}}function bx(e){const{group_key:t="",...n}=e;return{...n,group_key:t}}function vx(e){const{levels:t=[],...n}=e;return{...n,levels:t}}function xx(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=c=>c&&`${n}.${c}`,{label_key:a,value_key:o,group_key:l,...u}=e;return{...u,label_key:r(a),value_key:r(o),group_key:r(l)}}catch(n){throw console.error("[Migration failed]",n),n}}class wx extends ye{constructor(){super(...arguments);N(this,"VERSION",5)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,n=>({...n,version:2,config:yx(n.config)})),this.version(3,n=>({...n,version:3,config:bx(n.config)})),this.version(4,n=>({...n,version:4,config:vx(n.config)})),this.version(5,(n,r)=>({...n,version:5,config:xx(n.config,r)}))}}const Cx={displayName:"Sunburst Chart",displayGroup:"ECharts-based charts",migrator:new wx,name:"sunburst",viewRender:cx,configRender:mx,createConfig(){return{version:5,config:x.cloneDeep(ci)}}};var it=(e=>(e.string="string",e.number="number",e.eloc="eloc",e.percentage="percentage",e.custom="custom",e))(it||{});const _o=["function text({ value }) {"," // your code goes here"," return value","}"].join(`
296
- `),ko={columns:[],fontSize:"14px",highlightOnHover:!0,horizontalSpacing:"14px",id_field:"",striped:!0,use_raw_columns:!0,verticalSpacing:"14px"},To={left:"flex-start",center:"center",right:"flex-end"},Sx=({header:e,cx:t})=>{const n=x.get(e.column.columnDef.meta,"align","left");return p(s.Text,{className:t("table-head-cell",{"table-head-cell--sortable":e.column.getCanSort()}),onClick:e.column.getToggleSortingHandler(),align:n,sx:{justifyContent:To[n]},children:[e.isPlaceholder?null:tt.flexRender(e.column.columnDef.header,e.getContext()),i(_x,{direction:e.column.getIsSorted()})]})},_x=({direction:e})=>{switch(e){case"asc":return i($.IconArrowUp,{size:16});case"desc":return i($.IconArrowDown,{size:"1em"});default:return null}},di={id:"builtin:table:click-cell-content",displayName:"Click Cell Content",nameRender:Ix,configRender:Tx,payload:[{name:"row_index",description:"Index of the row that the cell belongs to",valueType:"number"},{name:"col_index",description:"Index of the column that the cell belongs to",valueType:"number"},{name:"row_data",description:"Data of the row that the cell belongs to",valueType:"object"}]},kx={column:""};function Do(e,t){const{value:n}=R(e.instanceData,"config"),r={columnsFromConfig:[],columnsFromData:[]};if(n&&(r.columnsFromConfig=n.columns.map((a,o)=>({label:a.label,value:o.toString()}))),!t)return r;if(n!=null&&n.id_field){const a=Ht(t,n.id_field);(a==null?void 0:a.length)>0&&(r.columnsFromData=Object.keys(a[0]).map(o=>({label:o,value:o})))}return r}function Tx(e){const{columnsFromConfig:t,columnsFromData:n}=Do(e.instance,e.sampleData),r=t.length>0?t:n,{value:a,set:o}=R(e.trigger.triggerData,"config"),{column:l}=x.defaults({},a,kx),u=c=>{isNaN(+c)?o({column:c}):o({column:+c})};return i(s.Select,{clearable:!1,data:r,label:"Choose a column",value:l.toString(),onChange:u})}function Dx(e,t){return e?x.isNumber(e.column)?`Click cell of ${t[e.column].label}`:`Click cell of ${e.column}`:"Click cell content (click to config)"}function Ix(e){const{columnsFromConfig:t}=Do(e.instance),{value:n}=R(e.trigger.triggerData,"config");return i(s.Text,{children:Dx(n,t)})}const Mx=s.createStyles(e=>({root:{overflow:"auto",position:"relative","& .table-head-cell":{display:"flex",flexFlow:"row nowrap",alignItems:"center",whiteSpace:"nowrap","&.table-head-cell--sortable":{cursor:"pointer",userSelect:"none"}},"&.table-highlight-on-hover tr":{transition:"background-color 0.2s","&:hover":{backgroundColor:e.colorScheme==="dark"?e.colors.dark[5]:e.colors.gray[0]}}},thead:{background:e.colorScheme==="dark"?e.colors.dark[7]:e.white,position:"sticky",top:24,transform:"translateY(-1px)",zIndex:10},info_bar:{position:"sticky",top:0,left:0,right:0,zIndex:10,background:"white"}})),Ax={tableLayout:"fixed","thead, tbody":{tr:{"th, td":{padding:"2px 10px",div:{overflow:"hidden",textOverflow:"ellipsis"},"&:first-of-type":{paddingLeft:2,paddingRight:2}}}}};function Io(e,t,n){return Math.min(Math.max(e,t),n)}class zx{constructor(t){this.steps=t;const n=[],r=new Set;for(const a of t)r.has(a.to)||(n.push(a),r.add(a.to));if(n.sort((a,o)=>a.from-o.from),n.length<2)throw new Error("MultiStepValueMapper requires at least 2 steps");this.steps=n}getLinearFunction(t,n){const r=(n.to-t.to)/(n.from-t.from),a=t.to-r*t.from;return o=>r*o+a}getStepFunctionForValue(t){let n=x.findLastIndex(this.steps,r=>r.from<=t);return n=Io(n,0,this.steps.length-2),this.getLinearFunction(this.steps[n],this.steps[n+1])}mapValue(t){return Io(this.getStepFunctionForValue(t)(t),0,100)}}class Ex{constructor(t,n,r,a,o){this.getColIndex=t,this.cell=n,this.triggers=r,this.interactionManager=a,this.colorManager=o}getClickHandler(){const t=this.getRelatedTrigger();if(t.length!==0)return()=>{const n={row_data:this.cell.row.original,row_index:this.cell.row.index,col_index:this.getColIndex(this.cell)};for(const r of t)this.interactionManager.runInteraction(r.id,n)}}getRelatedTrigger(){return this.triggers.filter(n=>n.schemaRef===di.id).filter(n=>{const r=this.getColIndex(this.cell),a=x.get(this.cell.column.columnDef.meta,"value_field"),o=x.get(n.config,"column");return o==r||o==a})}isClickable(){return this.getRelatedTrigger().length>0}get columnConf(){return this.cell.column.columnDef.meta}get bgColor(){const t=this.columnConf.cellBackgroundColor;if(!t||t==="none")return;if(x.isString(t))return t;const n=+this.cell.getValue();if(isFinite(n)){const r=this.colorManager.decodeInterpolation(t.interpolation),o=new zx(t.steps).mapValue(n);return r==null?void 0:r.getColor(o)}}}const $x=s.createStyles((e,t)=>({content:{display:"flex",alignItems:"center",justifyContent:To[t.align],".table-cell-text":{whiteSpace:"nowrap",cursor:t.clickable?"pointer":"default",textDecoration:t.clickable?"underline":"none"}}}));function Lx(e){return e?ct(e).oklch()[0]>.7?"black":"white":"inherit"}function Ox(e){const t=e.tableCellContext.bgColor;return{backgroundColor:t,color:Lx(t)}}function Wt(e){const t=e.tableCellContext.isClickable(),n=$x({clickable:t,align:e.align});return i("div",{className:n.classes.content,style:{...Ox(e)},children:i(s.Text,{className:"table-cell-text",onClick:e.tableCellContext.getClickHandler(),children:i("span",{title:e.children,children:e.children})})})}function Px(e){return i(Wt,{...e,children:e.value})}function Bx(e){const t=Z(e.value).format({average:!0,mantissa:2,trimMantissa:!0});return i(Wt,{...e,children:t})}function Vx(e){const t=Z(e.value).format({thousandSeparated:!0});return i(Wt,{...e,children:t})}function Nx(e){const t=Z(e.value).format({output:"percent",mantissa:3});return i(Wt,{...e,children:t})}function qx(e){const t=e.value,n=e.func_content;if(!n)return i(Wt,{...e,children:t});const r=new Function(`return ${n}`)()({value:t});return i(Wt,{...e,children:r})}function Fx(e){switch(e.type){case it.string:return i(Px,{...e});case it.eloc:return i(Bx,{...e});case it.number:return i(Vx,{...e});case it.percentage:return i(Nx,{...e});case it.custom:return i(qx,{...e})}}const Gx=e=>{const t=Xe(e),n=Ke(t.triggerManager,di.id),{colorManager:r}=y.useContext(ut);return y.useCallback(a=>new Ex(e.getColIndex,a,n,t,r),[n,t,e.getColIndex])};function Wx({data:e,width:t,height:n,conf:r,context:a,instance:o}){var be,Ee;const{id_field:l,use_raw_columns:u,columns:c,...d}=r,{classes:f,cx:h}=Mx(),g=y.useMemo(()=>{if(!l)return[];const ge=O(l);return e[ge.queryID]},[e,l]),m=y.useMemo(()=>u?!Array.isArray(g)||g.length===0?[]:Object.keys(g[0]).map(ge=>({id:ge,label:ge,value_field:ge,value_type:it.string,align:"left",width:"",cellBackgroundColor:""})):c,[u,c,g]),C=Gx({getColIndex:y.useCallback(ge=>m.indexOf(ge.column.columnDef.meta),[m]),vizManager:a.vizManager,instance:o}),w=y.useMemo(()=>{const ge=tt.createColumnHelper();return m.map(me=>{const Oe=cc(me.value_field);return ge.accessor(Oe.columnKey,{cell:He=>i(Fx,{tableCellContext:C(He.cell),value:He.getValue(),type:me.value_type,...me}),header:me.label,enableSorting:!0,meta:me,size:typeof me.width=="number"?me.width:void 0,minSize:typeof me.width=="number"?me.width:void 0})})},[m,C]),[_,D]=y.useState([]),M=tt.useReactTable({data:g,state:{sorting:_},onSortingChange:D,columns:w,getCoreRowModel:tt.getCoreRowModel(),getSortedRowModel:tt.getSortedRowModel()}),{rows:P}=M.getRowModel(),G=y.useRef(null),L=zu.useVirtual({parentRef:G,size:P.length,estimateSize:y.useCallback(()=>28,[]),overscan:20}),{virtualItems:z,totalSize:A}=L,F=z.length>0&&((be=z==null?void 0:z[0])==null?void 0:be.start)||0,X=z.length>0?A-(((Ee=z==null?void 0:z[z.length-1])==null?void 0:Ee.end)||0):0,Q=P.length,H=Q>0,oe=H?n-22:n,ue=H?22:0;return!Array.isArray(g)||g.length===0?i(s.Text,{color:"gray",align:"center",children:"Empty Data"}):p("div",{ref:G,style:{height:n,width:t,padding:"0 5px"},"data-enable-scrollbar":!0,className:h(f.root,{"table-highlight-on-hover":r.highlightOnHover}),children:[Q>0&&i(s.Box,{className:f.info_bar,sx:{height:22},children:p(s.Text,{align:"right",pr:6,size:14,color:"dimmed",fw:"normal",children:["Total: ",Q]})}),p(s.Table,{sx:{...Ax,maxHeight:oe},...d,striped:r.striped,children:[i("thead",{className:f.thead,style:{top:ue},children:M.getHeaderGroups().map(ge=>i("tr",{children:ge.headers.map(ve=>i("th",{style:{width:ve.getSize()},children:i(Sx,{header:ve,cx:h})},ve.id))},ge.id))}),p("tbody",{children:[F>0&&i("tr",{children:i("td",{style:{height:`${F}px`}})}),z.map(ge=>{const ve=P[ge.index];return i("tr",{children:ve.getVisibleCells().map(me=>i("td",{children:tt.flexRender(me.column.columnDef.cell,me.getContext())},me.id))},ve.id)}),X>0&&i("tr",{children:i("td",{style:{height:`${X}px`}})})]})]})]})}function jx({context:e,instance:t}){const n=e.data,{height:r,width:a}=e.viewport,{value:o}=R(e.instanceData,"config");return o?o.id_field?i(Wx,{data:n,width:a,height:r,conf:o,context:e,instance:t}):i(s.Text,{color:"red",align:"center",children:"ID Field is not set, can't render a table without it"}):null}const Mo=s.createStyles(()=>({palette:{display:"flex",flexFlow:"row nowrap"},paletteItem:{".palette-value":{height:24,overflow:"visible",width:36},".palette-item":{width:"36px",height:36*.618,cursor:"pointer",transition:"transform 100ms ease-in-out","&:hover":{boxShadow:"0 0 0 2px var(--shadow-color)",borderRadius:2,transform:"scale(1.2)"}}}})),Rx=[{from:0,to:0},{from:100,to:100}];class Yx{constructor(){N(this,"steps",new Map);N(this,"interpolation");N(this,"onChange");te.makeAutoObservable(this,{steps:te.observable},{deep:!1}),te.reaction(()=>te.toJS(this.steps),()=>{this.notifyStepChange()})}setSteps(t){for(const n of t)this.steps.set(n.to,n.from)}notifyStepChange(){var t;(t=this.onChange)==null||t.call(this,Array.from(this.steps.entries()).map(([n,r])=>({to:n,from:r})).sort((n,r)=>n.to-r.to||n.from-r.from))}fromProps(t){t.steps.length<2?this.setSteps(Rx):this.setSteps(t.steps),this.interpolation=t.interpolation,this.onChange=t.onChange}changeStep(t,n){t==null?this.steps.delete(n):this.steps.set(n,t)}getStepFromValue(t){return this.steps.get(t)}}function Qx(e){const{onChange:t,color:n,index:r,value:a}=e,{classes:o}=Mo(),[l,u]=y.useState(a),[c,{setTrue:d,setFalse:f}]=K.useBoolean(!1),h=r%2===1,g=h&&a!=null,m=!h&&a!=null,C=`map ${a} to color ${r}`,w=()=>{u(a),f()},_=()=>{f(),t==null||t(l)},D=Z(a).format({average:!0});return p("div",{"data-testid":`palette-item-${r}`,className:o.paletteItem,children:[i(s.Text,{title:C,style:{opacity:g?1:0},color:"dimmed",size:"sm",className:"palette-value--up palette-value",children:D}),p(s.Popover,{width:200,trapFocus:!0,opened:c,onClose:f,children:[i(s.Popover.Target,{children:i("div",{"data-testid":"palette-item-target",className:"palette-item",onClick:d,style:{"--shadow-color":ct(n).alpha(.5).hex(),backgroundColor:n}})}),i(s.Popover.Dropdown,{children:p(s.Stack,{children:[i(s.NumberInput,{size:"xs",label:"Map a value to this color",value:l,onChange:u}),p(s.Group,{position:"right",children:[i(s.Button,{variant:"subtle",size:"xs",onClick:w,children:"Cancel"}),i(s.Button,{"data-testid":"palette-item-ok",size:"xs",onClick:_,children:"OK"})]})]})})]}),i(s.Text,{title:C,style:{opacity:m?1:0},color:"dimmed",size:"sm",className:"palette-value--bottom palette-value",children:D})]})}const Ux=k.observer(({model:e})=>{const{classes:t}=Mo(),n=x.range(0,13,1).map(r=>100/12*r).map(r=>[e.interpolation.getColor(r),r]);return i("div",{className:t.palette,children:n.map(([r,a],o)=>i(Qx,{index:o,color:r,value:e.getStepFromValue(a),onChange:l=>e.changeStep(l,a)},r))})}),Kx=k.observer(function(t){const n=K.useCreation(()=>new Yx,[]);return y.useEffect(()=>{n.fromProps(t)}),n.interpolation==null?null:i(Ux,{model:n})}),Xx=e=>{const{value:t,onChange:n,colorManager:r}=e,a=r.getColorInterpolations(),[o,l]=y.useState(t),u=r.decodeInterpolation(o.interpolation)||a[0],[c,{setTrue:d,setFalse:f}]=K.useBoolean(),h=a.map(_=>({label:_.displayName,value:r.encodeColor(_),group:_.category}));function g(_){_&&l(D=>({...D,interpolation:_}))}const m=()=>{f(),n==null||n(te.toJS(o))};function C(_){l(D=>({...D,steps:_}))}const w=()=>{f(),l(t)};return p(B,{children:[i(s.Button,{variant:"outline",onClick:d,children:u==null?void 0:u.displayName}),i(s.Modal,{size:508,title:"Setup color interpolation",opened:c,onClose:f,zIndex:320,children:c&&p(s.Stack,{"data-testid":"color-interpolation-modal",children:[i(s.Select,{label:"Color style",value:o.interpolation,data:h,onChange:g}),i(Kx,{steps:o.steps,interpolation:u,onChange:C}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:w,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:m,children:"OK"})]})]})})]})},Jx=["static","interpolation","none"].map(e=>({label:x.capitalize(e),value:e})),Zx=[{from:0,to:0},{from:100,to:100}];function Ao(e){return e?x.isString(e)?e==="none"?"none":"static":"interpolation":"none"}function Hx(e,t){var n;return Ao(t)==="static"?t:(n=e.getStaticColors()[0])==null?void 0:n.value}function e0(e,t){return x.isObject(t)?t:{steps:Zx,interpolation:e.encodeColor(e.getColorInterpolations()[0])}}const t0=y.forwardRef((e,t)=>{const{colorManager:n}=y.useContext(ut),[r,a]=y.useState(Ao(e.value)),[o,l]=y.useState(Hx(n,e.value)),u=K.useLatest(o),[c,d]=y.useState(e0(n,e.value)),f=K.useLatest(c),h=C=>{var w,_,D;a(C||"none"),C==="static"?(w=e.onChange)==null||w.call(e,u.current):C==="none"||!C?(_=e.onChange)==null||_.call(e,"none"):(D=e.onChange)==null||D.call(e,f.current)},g=C=>{var w;l(C),(w=e.onChange)==null||w.call(e,C)},m=C=>{var w;d(C),(w=e.onChange)==null||w.call(e,C)};return p(s.Stack,{align:"stretch",children:[i(s.Select,{label:"Cell background",value:r||"none",onChange:h,data:Jx}),r==="static"&&i(Ve,{value:o,onChange:g}),r==="interpolation"&&i(Xx,{colorManager:n,value:c,onChange:m})]})}),n0={[it.eloc]:"ELOC"},r0=Object.values(it).map(e=>({label:x.get(n0,e,x.capitalize(e)),value:e})),i0=y.forwardRef(({label:e,value:t,onChange:n,sx:r},a)=>i(s.Select,{ref:a,label:e,data:r0,value:t,onChange:n,sx:r})),a0=y.forwardRef(({value:e,onChange:t},n)=>{const[r,{setTrue:a,setFalse:o}]=K.useBoolean(),[l,u]=y.useState(e),c=()=>{o(),t(l)},d=()=>{o(),u(e)},f=()=>{u(_o)};return y.useEffect(()=>{u(e)},[e]),p(B,{children:[i(s.Button,{variant:"filled",mt:24,onClick:a,sx:{flexGrow:0},children:"Custom Cell Content"}),i(s.Modal,{size:800,title:"Custom cell content",opened:r,onClose:o,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:r&&p(s.Stack,{children:[i(s.Box,{sx:{position:"relative"},children:i(Ae,{height:"500px",defaultLanguage:"javascript",value:l,onChange:h=>u(h??""),theme:"vs-dark",options:{minimap:{enabled:!1}}})}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:f,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:d,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:c,children:"OK"})]})]})]})})]})}),s0=[{label:"Left",value:"left"},{label:"Center",value:"center"},{label:"Right",value:"right"}],pi=()=>i(s.Text,{color:"dimmed",size:12,children:"px"}),o0=({control:e,index:t,watch:n,remove:r,column:a})=>{const o=n(`columns.${t}.value_type`);return p(s.Stack,{my:0,sx:{position:"relative"},children:[p(s.Group,{grow:!0,children:[i(v.Controller,{name:`columns.${t}.label`,control:e,render:({field:l})=>i(s.TextInput,{label:"Label",required:!0,id:`col-label-${t}`,sx:{flex:1},...l})}),i(v.Controller,{name:`columns.${t}.value_field`,control:e,render:({field:l})=>i(W,{label:"Value Field",required:!0,...l})})]}),p(s.Group,{grow:!0,children:[i(v.Controller,{name:`columns.${t}.value_type`,control:e,render:({field:l})=>i(i0,{label:"Value Type",sx:{flex:1},...l})}),o===it.custom&&i(v.Controller,{name:`columns.${t}.func_content`,control:e,render:({field:l})=>i(a0,{value:l.value??_o,onChange:u=>l.onChange(u??"")})})]}),i(s.Divider,{mb:-10,variant:"dashed",label:"Style",labelPosition:"center"}),p(s.Group,{grow:!0,children:[i(s.NumberInput,{hideControls:!0,label:"Min Width",rightSection:i(pi,{}),disabled:!0}),i(v.Controller,{name:`columns.${t}.width`,control:e,render:({field:l})=>i(s.NumberInput,{hideControls:!0,label:"Width",rightSection:i(pi,{}),...l})}),i(s.NumberInput,{hideControls:!0,label:"Max Width",rightSection:i(pi,{}),disabled:!0})]}),i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:`columns.${t}.align`,control:e,render:({field:l})=>i(s.Select,{label:"Alignment",data:s0,...l})})}),i(v.Controller,{name:`columns.${t}.cellBackgroundColor`,control:e,render:({field:l})=>i(t0,{...l})}),i(s.Divider,{mb:4,mt:12,variant:"dashed"}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>r(t),children:"Delete this column"})]})},l0=({control:e,watch:t})=>{const{fields:n,append:r,remove:a,update:o}=v.useFieldArray({control:e,name:"columns"}),l=()=>{const c=Ie.randomId();r({id:c,label:c,align:"center",value_field:"",value_type:it.string,width:""})};t("columns");const u=t("use_raw_columns");return p(B,{children:[i(v.Controller,{name:"use_raw_columns",control:e,render:({field:c})=>i(s.Switch,{mt:20,mb:20,label:"Use Original Data Columns",checked:c.value,onChange:d=>c.onChange(d.currentTarget.checked)})}),!u&&i(s.Stack,{children:p(s.Tabs,{defaultValue:"0",styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[n.map((c,d)=>i(s.Tabs.Tab,{value:d.toString(),children:d+1},c.id)),i(s.Tabs.Tab,{onClick:l,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),n.map((c,d)=>i(s.Tabs.Panel,{value:d.toString(),children:i(o0,{control:e,watch:t,index:d,column:c,remove:a},d)},c.id))]})})]})};function u0({control:e,watch:t}){return t(["horizontalSpacing","verticalSpacing","fontSize","striped","highlightOnHover"]),p(s.Stack,{spacing:"xs",children:[p(s.Group,{position:"apart",mb:"lg",grow:!0,sx:{"> *":{flexGrow:1}},children:[i(v.Controller,{name:"horizontalSpacing",control:e,render:({field:n})=>i(s.TextInput,{label:"Horizontal Spacing",placeholder:"10px, 1em, 1rem, 100%...",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"verticalSpacing",control:e,render:({field:n})=>i(s.TextInput,{label:"Vertical Spacing",placeholder:"10px, 1em, 1rem, 100%...",required:!0,sx:{flex:1},...n})})]}),i(s.Group,{position:"apart",mb:"lg",grow:!0,sx:{"> *":{flexGrow:1}},children:i(v.Controller,{name:"fontSize",control:e,render:({field:n})=>i(s.TextInput,{label:"Font Size",placeholder:"10px, 1em, 1rem, 100%...",required:!0,sx:{flex:1},...n})})}),p(s.Group,{position:"apart",grow:!0,children:[i(v.Controller,{name:"striped",control:e,render:({field:n})=>i(s.Switch,{label:"Striped",checked:n.value,onChange:r=>n.onChange(r.currentTarget.checked)})}),i(v.Controller,{name:"highlightOnHover",control:e,render:({field:n})=>i(s.Switch,{label:"Highlight on hover",checked:n.value,onChange:r=>n.onChange(r.currentTarget.checked)})})]})]})}function c0({columns:e,...t}){return{...t,columns:e.map(({id:n,...r})=>({id:n??Ie.randomId(),...r}))}}function d0({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=y.useMemo(()=>x.defaultsDeep({},t,ko),[t]),a=y.useMemo(()=>c0(r),[r]);y.useEffect(()=>{!x.isEqual(r,a)&&(console.log("config malformed, resetting to defaults",r,a),n(a))},[r,a]);const{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});y.useEffect(()=>{d(a)},[a]);const f=c(),h=y.useMemo(()=>!x.isEqual(f,r),[f,r]);return u(["id_field"]),p("form",{onSubmit:l(n),children:[p(s.Group,{position:"apart",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Table Config"}),i(s.ActionIcon,{type:"submit","aria-label":"save config",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"Columns",orientation:"vertical",styles:{tab:{paddingLeft:"6px",paddingRight:"6px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"Columns",children:"Columns"}),i(s.Tabs.Tab,{value:"Style",children:"Style"})]}),p(s.Tabs.Panel,{value:"Columns",children:[i(v.Controller,{name:"id_field",control:o,render:({field:g})=>i(W,{label:"ID Field",required:!0,...g})}),i(s.Divider,{mt:20,mb:10,variant:"dashed"}),i(l0,{control:o,watch:u})]}),i(s.Tabs.Panel,{value:"Style",children:i(u0,{control:o,watch:u})})]})]})}function p0(e){const{columns:t,...n}=e;return{...e,columns:t.map(r=>({...r,align:r.align??"left"}))}}function h0(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=u=>u&&`${n}.${u}`,{id_field:a,columns:o,...l}=e;return{...l,id_field:r(a),columns:o.map(u=>({...u,value_field:r(u.value_field)}))}}catch(n){throw console.error("[Migration failed]",n),n}}function f0(e){const{columns:t,...n}=e;return{...n,columns:t.map(r=>({...r,align:r.align??"left",cellBackgroundColor:r.cellBackgroundColor??"",width:r.width??""}))}}class g0 extends ye{constructor(){super(...arguments);N(this,"VERSION",5)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,n=>{const{columns:r,...a}=n.config;return{...n,version:2,config:{...a,columns:r.map(({id:o,...l})=>({id:o??Ie.randomId(),...l}))}}}),this.version(3,n=>({...n,version:3,config:p0(n.config)})),this.version(4,(n,r)=>({...n,version:4,config:h0(n.config,r)})),this.version(5,n=>({...n,version:5,config:f0(n.config)}))}}const hi={createConfig(){return{version:5,config:x.cloneDeep(ko)}},displayName:"Table",displayGroup:"Others",migrator:new g0,name:"table",viewRender:jx,configRender:d0,triggers:[di]},zo=["function text({ data, variables, filters, context}) {"," // your code goes here",' return "text"',"}"].join(`
297
- `),fi={func_content:zo,horizontal_align:"left",font_size:"14px",font_weight:"normal"},m0=k.observer(({context:e})=>{const t=we(),{value:n=fi}=R(e.instanceData,"config"),{variables:r}=e,a=e.data,{func_content:o,horizontal_align:l,font_size:u,font_weight:c}=n,d=y.useMemo(()=>r.reduce((h,g)=>{const m=ft(g,a);return h[g.name]=Ze(g,m),h},{}),[r,a]),f=y.useMemo(()=>new Function(`return ${o}`)()({data:a,variables:d,filters:t.payloadForSQL.filters,context:t.payloadForSQL.context}),[o,a,d,t.payloadForSQL]);return i(s.Text,{align:l,weight:c,sx:{fontSize:u},children:f})}),y0=({value:e,onChange:t})=>{const n=r=>{r&&t(r)};return i(s.Box,{sx:{position:"relative"},children:i(Ae,{height:"500px",defaultLanguage:"javascript",value:e,onChange:n,theme:"vs-dark",options:{minimap:{enabled:!1}}})})},b0=y.forwardRef(({value:e,onChange:t},n)=>{const[r,{setTrue:a,setFalse:o}]=K.useBoolean(),[l,u]=y.useState(e),c=()=>{o(),t(l)},d=()=>{o(),u(e)},f=()=>{u(zo)};return y.useEffect(()=>{u(e)},[e]),p(B,{children:[i(s.Button,{variant:"filled",mt:24,onClick:a,sx:{flexGrow:0},children:"Edit Content"}),i(s.Modal,{size:800,title:"Text content",opened:r,onClose:o,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:r&&p(s.Stack,{children:[i(y0,{value:l,onChange:u}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:f,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:d,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:c,children:"OK"})]})]})]})})]})}),v0=[{label:"Left",value:"left"},{label:"Center",value:"center"},{label:"Right",value:"right"}];function x0({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=y.useMemo(()=>x.defaultsDeep({},t,fi),[t]),a=y.useMemo(()=>{const{func_content:g,horizontal_align:m,font_size:C,font_weight:w}=r;return{func_content:g,horizontal_align:m,font_size:C,font_weight:w}},[r]);y.useEffect(()=>{!x.isEqual(r,a)&&(console.log("config malformed, resetting to defaults",r,a),n(a))},[r,a]);const{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});y.useEffect(()=>{d(a)},[a]),u(["func_content","horizontal_align","font_size","font_weight"]);const f=c(),h=y.useMemo(()=>!x.isEqual(f,r),[f,r]);return i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:l(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{weight:500,children:"Configurations"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Stack,{spacing:10,children:[i(v.Controller,{name:"func_content",control:o,render:({field:g})=>i(b0,{...g})}),i(s.Divider,{mt:10,mb:-10,variant:"dashed",label:"Style",labelPosition:"center"}),i(v.Controller,{name:"horizontal_align",control:o,render:({field:g})=>i(s.Select,{label:"Horizontal Alignment",data:v0,...g})}),i(v.Controller,{name:"font_size",control:o,render:({field:g})=>i(s.TextInput,{label:"Font Size",placeholder:"10px, 1em, 1rem, 100%...",sx:{flex:1},...g})}),i(s.Group,{position:"apart",grow:!0,sx:{"> *":{flexGrow:1,maxWidth:"100%"}},children:i(v.Controller,{name:"font_weight",control:o,render:({field:g})=>i(Rs,{label:"Font Weight",...g})})})]})]})})}class w0 extends ye{constructor(){super(...arguments);N(this,"VERSION",1)}configVersions(){this.version(1,n=>({version:1,config:n}))}}const C0={displayName:"Text",displayGroup:"Others",migrator:new w0,name:"text",viewRender:m0,configRender:x0,createConfig(){return{version:1,config:x.cloneDeep(fi)}}},S0=()=>p("svg",{width:"64",height:"64",viewBox:"0 0 64 64",fill:"none",children:[i("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M22.49 27.79H14.47C13.55 27.79 12.81 28.53 12.81 29.45C12.81 30.37 13.55 31.11 14.47 31.11H22.49C23.41 31.11 24.15 30.37 24.15 29.45C24.15 28.54 23.41 27.79 22.49 27.79ZM34.32 31.28C35.22 31.32 35.7 31.82 35.74 32.76C35.78 33.54 35.37 34.3 34.51 35.04C33.52 35.9 33.03 36.95 33.03 38.19V38.81H34.82V38.25C34.78 37.59 35.07 37.02 35.68 36.52C37.12 35.41 37.82 34.15 37.78 32.75C37.66 30.53 36.5 29.35 34.32 29.23C32.3 29.23 31.05 30.46 30.55 32.93L32.53 33.55C32.82 32.04 33.42 31.28 34.32 31.28ZM35 39.93H32.84V42.21H35V39.93ZM14.83 36.42H18.54C19.46 36.42 20.2 37.17 20.2 38.08C20.2 39 19.46 39.74 18.54 39.74H10.52C9.6 39.74 8.86 39 8.86 38.08C8.86 37.61 9.06 37.19 9.37 36.89H5.66C4.74 36.89 4 36.15 4 35.23C4 34.31 4.74 33.57 5.66 33.57H13.68C14.6 33.57 15.34 34.31 15.34 35.23C15.34 35.7 15.14 36.12 14.83 36.42ZM50.94 36.85H58.74C59.66 36.85 60.4 37.59 60.41 38.51C60.41 39.43 59.67 40.17 58.75 40.17H54.26C54.56 40.47 54.74 40.88 54.74 41.34C54.74 42.26 54 43 53.08 43H50.94V36.85Z",fill:"#B8C0CC"}),i("path",{d:"M18.39 32.28H16.51V35.02H18.39V32.28Z",fill:"#9399A5"}),i("path",{d:"M46.87 15H20.69C18.38 15 16.5 16.88 16.5 19.19V26.22H18.38V23.45H49.18V47.68H18.38V41.07H16.5V49.55H51.05V19.19C51.06 16.88 49.18 15 46.87 15ZM39.46 20.73C38.81 20.73 38.29 20.2 38.29 19.56C38.29 18.92 38.82 18.39 39.46 18.39C40.11 18.39 40.63 18.92 40.63 19.56C40.63 20.2 40.11 20.73 39.46 20.73ZM43.22 20.73C42.57 20.73 42.05 20.2 42.05 19.56C42.05 18.92 42.58 18.39 43.22 18.39C43.87 18.39 44.39 18.92 44.39 19.56C44.39 20.2 43.87 20.73 43.22 20.73ZM46.97 20.73C46.32 20.73 45.8 20.2 45.8 19.56C45.8 18.92 46.33 18.39 46.97 18.39C47.62 18.39 48.14 18.92 48.14 19.56C48.14 20.2 47.62 20.73 46.97 20.73Z",fill:"#9399A5"})]});function Eo(e,t){const n=x.get(e,t,"");if(n)throw new Error(n)}async function _0(e,t,n,r={}){const a={"X-Requested-With":"XMLHttpRequest","Content-Type":r.string?"application/x-www-form-urlencoded":"application/json",...r.headers},o={baseURL:e,method:"POST",url:t,params:r.params,headers:a};return o.data=r.string?JSON.stringify(n):n,mt(o).then(l=>l.data).catch(l=>Promise.reject(l))}const k0=({conf:e,panelData:t})=>async()=>{const{expertSystemURL:n,path:r,goal:a,question:o}=e;if(!r||!a||!o)return;const l=dc(t);if(!l)return;const u={dashboard:a,panel:o,data:l};try{const c=n.startsWith("http")?n:window.location.origin;return await _0(c,`/expert/v3/devtable/${r}`,u,{})}catch(c){throw Eo(c,"response.data.detail"),Eo(c,"response.data.error"),console.error(c),c}},gi={expertSystemURL:"",path:"",goal:"",question:""},mi={height:"100%",overflowY:"auto",...Mr},$o=({message:e})=>i(s.Box,{sx:mi,children:i("div",{dangerouslySetInnerHTML:{__html:e},style:{fontSize:"14px",lineHeight:"32px",color:"#3D3E45"}})}),T0=({error:e,width:t,height:n})=>{const r=e.message;if(r.startsWith("<"))return i($o,{message:r});const o=n-25-20-30;return i(s.Center,{sx:{width:"100%",height:o},children:p(s.Stack,{align:"center",spacing:20,children:[i(S0,{}),i($o,{message:r})]})})};function D0({context:e}){const{value:t}=R(e.instanceData,"config"),n=y.useMemo(()=>x.defaultsDeep({},t,gi),[t]),{width:r,height:a}=e.viewport,o=e.data,{data:l,error:u,loading:c}=K.useRequest(k0({conf:n,panelData:o}),{refreshDeps:[o,n]});return!r||!a||!n?null:c?i(s.Box,{sx:{position:"relative",height:a},children:i(s.LoadingOverlay,{visible:!0})}):u?i(s.Box,{sx:mi,"data-enable-scrollbar":!0,children:i(T0,{error:u,width:r,height:a})}):!l||!Array.isArray(l.replies)||l.replies.length===0?null:i(s.Box,{sx:mi,"data-enable-scrollbar":!0,children:l.replies.map((d,f)=>i("div",{dangerouslySetInnerHTML:{__html:d.interpretation.html}},f))})}function I0({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=y.useMemo(()=>x.defaultsDeep({},t,gi),[t]),{control:a,handleSubmit:o,watch:l,getValues:u,reset:c}=v.useForm({defaultValues:r});y.useEffect(()=>{c(r)},[r]),l(["expertSystemURL","goal","path","question"]);const d=u(),f=y.useMemo(()=>!x.isEqual(d,r),[d,r]);return i("form",{onSubmit:o(n),children:p(s.Stack,{children:[p(s.Group,{grow:!0,children:[i(v.Controller,{name:"expertSystemURL",control:a,render:({field:h})=>i(s.TextInput,{label:"Expert System URL",...h})}),i(v.Controller,{name:"path",control:a,render:({field:h})=>i(s.TextInput,{label:"Path",required:!0,...h})})]}),p(s.Group,{grow:!0,children:[i(v.Controller,{name:"goal",control:a,render:({field:h})=>i(s.TextInput,{label:"Goal",required:!0,...h})}),i(v.Controller,{name:"question",control:a,render:({field:h})=>i(s.TextInput,{label:"Question",required:!0,...h})})]}),i(s.Divider,{variant:"dashed",mt:16,mb:8}),i(s.Button,{type:"submit",variant:"filled",color:"blue",leftIcon:i(T.DeviceFloppy,{size:20}),disabled:!f,sx:{alignSelf:"flex-end"},children:"Submit Changes"})]})})}class M0 extends ye{constructor(){super(...arguments);N(this,"VERSION",1)}configVersions(){this.version(1,n=>({version:1,config:n}))}}const A0={displayName:"Merico GQM",displayGroup:"Merico suite",migrator:new M0,name:"mericoGQM",viewRender:D0,configRender:I0,createConfig(){return{version:1,config:x.cloneDeep(gi)}}};function z0(e,t,n){if(!e)return n[0];try{return[t,Y(t).add(1,"year").subtract(1,"day").valueOf()]}catch(r){return console.error(r),n[0]}}function E0(e,t,n){const r=z0(e,t,n);return{top:50,left:25,right:5,cellSize:["auto",13],range:r,itemStyle:{borderColor:"#eee"},splitLine:{show:!0},dayLabel:{firstDay:1},monthLabel:{position:"end"},yearLabel:{show:!0}}}function $0(e){return{heat_block:function(r){if(!e.heat_block.value_formatter)return r;try{return Z(r).format(e.heat_block.value_formatter)}catch(a){return console.error(a),r}}}}function L0(e,t){return{show:!e,selectedMode:"single",top:5,right:5,data:t.map(n=>({name:n,icon:"circle"}))}}function O0(e,t,n,r){const{calendar:a,heat_block:o}=e,l=O(a.data_key),u=O(o.data_key);return t?{type:"heatmap",name:"heatmap",coordinateSystem:"calendar",calendarIndex:0,data:r[l.queryID].map(c=>[x.get(c,l.columnKey),x.get(c,u.columnKey)])}:Object.entries(n).map(([c,d])=>({type:"heatmap",name:c,coordinateSystem:"calendar",calendarIndex:0,data:d.map(f=>[x.get(f,l.columnKey),x.get(f,u.columnKey)])}))}const P0=e=>{try{return Z(e).format({trimMantissa:!0,mantissa:2})}catch{return e}};function B0({conf:e,valueFormatters:t,dataDict:n,params:r}){const{value:a}=r,[o,l]=a,c=[{label:e.heat_block.name,value:t.heat_block(l),style:{label:"",value:""}}],d=n[o];return d&&e.tooltip.metrics.forEach(f=>{const h=O(f.data_key);c.push({label:f.name,value:P0(x.get(d,h.columnKey,"")),style:{label:"",value:""}})}),c}function V0(e,t,n){const r=O(e.calendar.data_key),a=x.keyBy(t[r.queryID],r.columnKey);return{confine:!0,formatter:function(o){const u=B0({conf:e,valueFormatters:n,dataDict:a,params:o}).map(f=>`
295
+ `}}function ox(){return{show:!0,trigger:"item",confine:!0,formatter:sx()}}const lx={tooltip:{show:!0},series:{type:"sunburst",radius:[0,"90%"],emphasis:{focus:"ancestor"}}};function ux(e,t,n){n.reduce((o,l)=>{const u=ft(l,t);return o[l.name]=Ze(l,u),o},{});const a={series:{data:rx(e,t),levels:ax(e)},tooltip:ox()};return x.defaultsDeep({},a,lx)}ie.use([he.SunburstChart,Pe.CanvasRenderer]);function cx({context:e}){const{variables:t}=e,{value:n}=R(e.instanceData,"config"),r=b.useMemo(()=>x.defaults({},n,ci),[n]),a=e.data,{width:o,height:l}=e.viewport,u=b.useMemo(()=>ux(r,a,t),[r,a,t]);return!o||!l?null:i(Be,{echarts:ie,option:u,style:{width:o,height:l},notMerge:!0,theme:"merico-light"})}function dx({control:e,watch:t}){return t(["label_key","value_key","group_key"]),p(s.Stack,{children:[i(v.Controller,{name:"label_key",control:e,render:({field:n})=>i(W,{label:"Label Key",required:!0,...n})}),i(v.Controller,{name:"value_key",control:e,render:({field:n})=>i(W,{label:"Value Key",required:!0,...n})}),i(v.Controller,{name:"group_key",control:e,render:({field:n})=>i(W,{label:"Group Key",clearable:!0,...n})})]})}const px=[{label:"Radial",value:"radial"},{label:"Tangential",value:"tangential"},{label:"None",value:"0"}],hx=[{label:"Left",value:"left"},{label:"Center",value:"center"},{label:"Right",value:"right"}],fx=({control:e,index:t,remove:n})=>p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`levels.${t}.r0`,control:e,render:({field:r})=>i(s.TextInput,{label:"Inside Radius",placeholder:"0%",...r})}),i(v.Controller,{name:`levels.${t}.r`,control:e,render:({field:r})=>i(s.TextInput,{label:"Outside Radius",placeholder:"50%",...r})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Label Style",labelPosition:"center"}),i(v.Controller,{name:`levels.${t}.label.show_label_tolerance`,control:e,render:({field:r})=>i(s.NumberInput,{label:"Hide label when its percentage is less than...",precision:4,step:5e-4,min:0,max:1,...r})}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`levels.${t}.label.rotate`,control:e,render:({field:r})=>i(s.Select,{label:"Rotate",data:px,...r})}),i(v.Controller,{name:`levels.${t}.label.align`,control:e,render:({field:r})=>i(s.Select,{label:"Align",data:hx,...r})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`levels.${t}.label.position`,control:e,render:({field:r})=>i(ti,{label:"Position",...r})}),i(v.Controller,{name:`levels.${t}.label.padding`,control:e,render:({field:r})=>i(s.NumberInput,{label:"Padding",min:0,hideControls:!0,...r})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed"}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Level"})]}),gx=({control:e,watch:t})=>{const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"levels"}),o=t("levels"),l=n.map((h,g)=>({...h,...o[g]})),u=()=>r({id:Date.now().toString(),r0:"",r:"",label:{show_label_tolerance:.001,rotate:"0",align:"center",position:"inside",padding:0}}),c=t("levels.0.id"),[d,f]=b.useState(()=>c??null);return b.useEffect(()=>{c&&f(h=>h!==null?h:c)},[c]),p(B,{children:[p(s.Group,{spacing:2,sx:{cursor:"default",userSelect:"none"},children:[i(T.InfoCircle,{size:14,color:"#888"}),i(s.Text,{size:14,color:"#888",children:"Configure ring style on each level"})]}),i(s.Divider,{variant:"dashed",my:10}),p(s.Tabs,{value:d,onTabChange:h=>f(h),styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map((h,g)=>i(s.Tabs.Tab,{value:h.id,children:g},h.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((h,g)=>i(s.Tabs.Panel,{value:h.id,children:i(fx,{control:e,index:g,remove:a},h.id)},h.id))]})]})};function mx({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=b.useMemo(()=>x.defaultsDeep({},t,ci),[t]),a=b.useMemo(()=>x.clone(r),[r]),{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});b.useEffect(()=>{d(a)},[a]);const f=c(),h=b.useMemo(()=>!x.isEqual(f,r),[f,r]);u(["label_key","value_key","group_key","levels"]);const[g,m]=b.useState("Data");return i("form",{onSubmit:l(n),children:p(s.Stack,{spacing:"xs",children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Sunburst Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{value:g,onTabChange:m,orientation:"vertical",styles:{tab:{paddingLeft:"6px",paddingRight:"6px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"Data",children:"Data"}),i(s.Tabs.Tab,{value:"Levels",children:"Levels"})]}),i(s.Tabs.Panel,{value:"Data",children:i(dx,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Levels",children:i(gx,{control:o,watch:u})})]})]})})}function yx(e){const{label_field:t,value_field:n,...r}=e;return{...r,label_key:t,value_key:n}}function bx(e){const{group_key:t="",...n}=e;return{...n,group_key:t}}function vx(e){const{levels:t=[],...n}=e;return{...n,levels:t}}function xx(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=c=>c&&`${n}.${c}`,{label_key:a,value_key:o,group_key:l,...u}=e;return{...u,label_key:r(a),value_key:r(o),group_key:r(l)}}catch(n){throw console.error("[Migration failed]",n),n}}class wx extends ye{constructor(){super(...arguments);N(this,"VERSION",5)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,n=>({...n,version:2,config:yx(n.config)})),this.version(3,n=>({...n,version:3,config:bx(n.config)})),this.version(4,n=>({...n,version:4,config:vx(n.config)})),this.version(5,(n,r)=>({...n,version:5,config:xx(n.config,r)}))}}const Cx={displayName:"Sunburst Chart",displayGroup:"ECharts-based charts",migrator:new wx,name:"sunburst",viewRender:cx,configRender:mx,createConfig(){return{version:5,config:x.cloneDeep(ci)}}};var it=(e=>(e.string="string",e.number="number",e.eloc="eloc",e.percentage="percentage",e.custom="custom",e))(it||{});const _o=["function text({ value }) {"," // your code goes here"," return value","}"].join(`
296
+ `),ko={columns:[],fontSize:"14px",highlightOnHover:!0,horizontalSpacing:"14px",id_field:"",striped:!0,use_raw_columns:!0,verticalSpacing:"14px"},To={left:"flex-start",center:"center",right:"flex-end"},Sx=({header:e,cx:t})=>{const n=x.get(e.column.columnDef.meta,"align","left");return p(s.Text,{className:t("table-head-cell",{"table-head-cell--sortable":e.column.getCanSort()}),onClick:e.column.getToggleSortingHandler(),align:n,sx:{justifyContent:To[n]},children:[e.isPlaceholder?null:tt.flexRender(e.column.columnDef.header,e.getContext()),i(_x,{direction:e.column.getIsSorted()})]})},_x=({direction:e})=>{switch(e){case"asc":return i($.IconArrowUp,{size:16});case"desc":return i($.IconArrowDown,{size:"1em"});default:return null}},di={id:"builtin:table:click-cell-content",displayName:"Click Cell Content",nameRender:Ix,configRender:Tx,payload:[{name:"row_index",description:"Index of the row that the cell belongs to",valueType:"number"},{name:"col_index",description:"Index of the column that the cell belongs to",valueType:"number"},{name:"row_data",description:"Data of the row that the cell belongs to",valueType:"object"}]},kx={column:""};function Do(e,t){const{value:n}=R(e.instanceData,"config"),r={columnsFromConfig:[],columnsFromData:[]};if(n&&(r.columnsFromConfig=n.columns.map((a,o)=>({label:a.label,value:o.toString()}))),!t)return r;if(n!=null&&n.id_field){const a=en(t,n.id_field);(a==null?void 0:a.length)>0&&(r.columnsFromData=Object.keys(a[0]).map(o=>({label:o,value:o})))}return r}function Tx(e){const{columnsFromConfig:t,columnsFromData:n}=Do(e.instance,e.sampleData),r=t.length>0?t:n,{value:a,set:o}=R(e.trigger.triggerData,"config"),{column:l}=x.defaults({},a,kx),u=c=>{isNaN(+c)?o({column:c}):o({column:+c})};return i(s.Select,{clearable:!1,data:r,label:"Choose a column",value:l.toString(),onChange:u})}function Dx(e,t){return e?x.isNumber(e.column)?`Click cell of ${t[e.column].label}`:`Click cell of ${e.column}`:"Click cell content (click to config)"}function Ix(e){const{columnsFromConfig:t}=Do(e.instance),{value:n}=R(e.trigger.triggerData,"config");return i(s.Text,{children:Dx(n,t)})}const Mx=s.createStyles(e=>({root:{overflow:"auto",position:"relative","& .table-head-cell":{display:"flex",flexFlow:"row nowrap",alignItems:"center",whiteSpace:"nowrap","&.table-head-cell--sortable":{cursor:"pointer",userSelect:"none"}},"&.table-highlight-on-hover tr":{transition:"background-color 0.2s","&:hover":{backgroundColor:e.colorScheme==="dark"?e.colors.dark[5]:e.colors.gray[0]}}},thead:{background:e.colorScheme==="dark"?e.colors.dark[7]:e.white,position:"sticky",top:24,transform:"translateY(-1px)",zIndex:10},info_bar:{position:"sticky",top:0,left:0,right:0,zIndex:10,background:"white"}})),Ax={tableLayout:"fixed","thead, tbody":{tr:{"th, td":{padding:"2px 10px",div:{overflow:"hidden",textOverflow:"ellipsis"},"&:first-of-type":{paddingLeft:2,paddingRight:2}}}}};function Io(e,t,n){return Math.min(Math.max(e,t),n)}class zx{constructor(t){this.steps=t;const n=[],r=new Set;for(const a of t)r.has(a.to)||(n.push(a),r.add(a.to));if(n.sort((a,o)=>a.from-o.from),n.length<2)throw new Error("MultiStepValueMapper requires at least 2 steps");this.steps=n}getLinearFunction(t,n){const r=(n.to-t.to)/(n.from-t.from),a=t.to-r*t.from;return o=>r*o+a}getStepFunctionForValue(t){let n=x.findLastIndex(this.steps,r=>r.from<=t);return n=Io(n,0,this.steps.length-2),this.getLinearFunction(this.steps[n],this.steps[n+1])}mapValue(t){return Io(this.getStepFunctionForValue(t)(t),0,100)}}class Ex{constructor(t,n,r,a,o){this.getColIndex=t,this.cell=n,this.triggers=r,this.interactionManager=a,this.colorManager=o}getClickHandler(){const t=this.getRelatedTrigger();if(t.length!==0)return()=>{const n={row_data:this.cell.row.original,row_index:this.cell.row.index,col_index:this.getColIndex(this.cell)};for(const r of t)this.interactionManager.runInteraction(r.id,n)}}getRelatedTrigger(){return this.triggers.filter(n=>n.schemaRef===di.id).filter(n=>{const r=this.getColIndex(this.cell),a=x.get(this.cell.column.columnDef.meta,"value_field"),o=x.get(n.config,"column");return o==r||o==a})}isClickable(){return this.getRelatedTrigger().length>0}get columnConf(){return this.cell.column.columnDef.meta}get bgColor(){const t=this.columnConf.cellBackgroundColor;if(!t||t==="none")return;if(x.isString(t))return t;const n=+this.cell.getValue();if(isFinite(n)){const r=this.colorManager.decodeInterpolation(t.interpolation),o=new zx(t.steps).mapValue(n);return r==null?void 0:r.getColor(o)}}}const $x=s.createStyles((e,t)=>({content:{display:"flex",alignItems:"center",justifyContent:To[t.align],".table-cell-text":{whiteSpace:"nowrap",cursor:t.clickable?"pointer":"default",textDecoration:t.clickable?"underline":"none"}}}));function Lx(e){return e?ct(e).oklch()[0]>.7?"black":"white":"inherit"}function Ox(e){const t=e.tableCellContext.bgColor;return{backgroundColor:t,color:Lx(t)}}function Wt(e){const t=e.tableCellContext.isClickable(),n=$x({clickable:t,align:e.align});return i("div",{className:n.classes.content,style:{...Ox(e)},children:i(s.Text,{className:"table-cell-text",onClick:e.tableCellContext.getClickHandler(),children:i("span",{title:e.children,children:e.children})})})}function Px(e){return i(Wt,{...e,children:e.value})}function Bx(e){const t=Z(e.value).format({average:!0,mantissa:2,trimMantissa:!0});return i(Wt,{...e,children:t})}function Vx(e){const t=Z(e.value).format({thousandSeparated:!0});return i(Wt,{...e,children:t})}function Nx(e){const t=Z(e.value).format({output:"percent",mantissa:3});return i(Wt,{...e,children:t})}function qx(e){const t=e.value,n=e.func_content;if(!n)return i(Wt,{...e,children:t});const r=new Function(`return ${n}`)()({value:t});return i(Wt,{...e,children:r})}function Fx(e){switch(e.type){case it.string:return i(Px,{...e});case it.eloc:return i(Bx,{...e});case it.number:return i(Vx,{...e});case it.percentage:return i(Nx,{...e});case it.custom:return i(qx,{...e})}}const Gx=e=>{const t=Xe(e),n=Ke(t.triggerManager,di.id),{colorManager:r}=b.useContext(ut);return b.useCallback(a=>new Ex(e.getColIndex,a,n,t,r),[n,t,e.getColIndex])};function Wx({data:e,width:t,height:n,conf:r,context:a,instance:o}){var be,Ee;const{id_field:l,use_raw_columns:u,columns:c,...d}=r,{classes:f,cx:h}=Mx(),g=b.useMemo(()=>{if(!l)return[];const ge=O(l);return e[ge.queryID]},[e,l]),m=b.useMemo(()=>u?!Array.isArray(g)||g.length===0?[]:Object.keys(g[0]).map(ge=>({id:ge,label:ge,value_field:ge,value_type:it.string,align:"left",width:"",cellBackgroundColor:""})):c,[u,c,g]),C=Gx({getColIndex:b.useCallback(ge=>m.indexOf(ge.column.columnDef.meta),[m]),vizManager:a.vizManager,instance:o}),w=b.useMemo(()=>{const ge=tt.createColumnHelper();return m.map(me=>{const Oe=cc(me.value_field);return ge.accessor(Oe.columnKey,{cell:He=>i(Fx,{tableCellContext:C(He.cell),value:He.getValue(),type:me.value_type,...me}),header:me.label,enableSorting:!0,meta:me,size:typeof me.width=="number"?me.width:void 0,minSize:typeof me.width=="number"?me.width:void 0})})},[m,C]),[_,D]=b.useState([]),M=tt.useReactTable({data:g,state:{sorting:_},onSortingChange:D,columns:w,getCoreRowModel:tt.getCoreRowModel(),getSortedRowModel:tt.getSortedRowModel()}),{rows:P}=M.getRowModel(),G=b.useRef(null),L=zu.useVirtual({parentRef:G,size:P.length,estimateSize:b.useCallback(()=>28,[]),overscan:20}),{virtualItems:z,totalSize:A}=L,F=z.length>0&&((be=z==null?void 0:z[0])==null?void 0:be.start)||0,X=z.length>0?A-(((Ee=z==null?void 0:z[z.length-1])==null?void 0:Ee.end)||0):0,Q=P.length,H=Q>0,oe=H?n-22:n,ue=H?22:0;return!Array.isArray(g)||g.length===0?i(s.Text,{color:"gray",align:"center",children:"Empty Data"}):p("div",{ref:G,style:{height:n,width:t,padding:"0 5px"},"data-enable-scrollbar":!0,className:h(f.root,{"table-highlight-on-hover":r.highlightOnHover}),children:[Q>0&&i(s.Box,{className:f.info_bar,sx:{height:22},children:p(s.Text,{align:"right",pr:6,size:14,color:"dimmed",fw:"normal",children:["Total: ",Q]})}),p(s.Table,{sx:{...Ax,maxHeight:oe},...d,striped:r.striped,children:[i("thead",{className:f.thead,style:{top:ue},children:M.getHeaderGroups().map(ge=>i("tr",{children:ge.headers.map(ve=>i("th",{style:{width:ve.getSize()},children:i(Sx,{header:ve,cx:h})},ve.id))},ge.id))}),p("tbody",{children:[F>0&&i("tr",{children:i("td",{style:{height:`${F}px`}})}),z.map(ge=>{const ve=P[ge.index];return i("tr",{children:ve.getVisibleCells().map(me=>i("td",{children:tt.flexRender(me.column.columnDef.cell,me.getContext())},me.id))},ve.id)}),X>0&&i("tr",{children:i("td",{style:{height:`${X}px`}})})]})]})]})}function jx({context:e,instance:t}){const n=e.data,{height:r,width:a}=e.viewport,{value:o}=R(e.instanceData,"config");return o?o.id_field?i(Wx,{data:n,width:a,height:r,conf:o,context:e,instance:t}):i(s.Text,{color:"red",align:"center",children:"ID Field is not set, can't render a table without it"}):null}const Mo=s.createStyles(()=>({palette:{display:"flex",flexFlow:"row nowrap"},paletteItem:{".palette-value":{height:24,overflow:"visible",width:36},".palette-item":{width:"36px",height:36*.618,cursor:"pointer",transition:"transform 100ms ease-in-out","&:hover":{boxShadow:"0 0 0 2px var(--shadow-color)",borderRadius:2,transform:"scale(1.2)"}}}})),Rx=[{from:0,to:0},{from:100,to:100}];class Yx{constructor(){N(this,"steps",new Map);N(this,"interpolation");N(this,"onChange");te.makeAutoObservable(this,{steps:te.observable},{deep:!1}),te.reaction(()=>te.toJS(this.steps),()=>{this.notifyStepChange()})}setSteps(t){for(const n of t)this.steps.set(n.to,n.from)}notifyStepChange(){var t;(t=this.onChange)==null||t.call(this,Array.from(this.steps.entries()).map(([n,r])=>({to:n,from:r})).sort((n,r)=>n.to-r.to||n.from-r.from))}fromProps(t){t.steps.length<2?this.setSteps(Rx):this.setSteps(t.steps),this.interpolation=t.interpolation,this.onChange=t.onChange}changeStep(t,n){t==null?this.steps.delete(n):this.steps.set(n,t)}getStepFromValue(t){return this.steps.get(t)}}function Qx(e){const{onChange:t,color:n,index:r,value:a}=e,{classes:o}=Mo(),[l,u]=b.useState(a),[c,{setTrue:d,setFalse:f}]=K.useBoolean(!1),h=r%2===1,g=h&&a!=null,m=!h&&a!=null,C=`map ${a} to color ${r}`,w=()=>{u(a),f()},_=()=>{f(),t==null||t(l)},D=Z(a).format({average:!0});return p("div",{"data-testid":`palette-item-${r}`,className:o.paletteItem,children:[i(s.Text,{title:C,style:{opacity:g?1:0},color:"dimmed",size:"sm",className:"palette-value--up palette-value",children:D}),p(s.Popover,{width:200,trapFocus:!0,opened:c,onClose:f,children:[i(s.Popover.Target,{children:i("div",{"data-testid":"palette-item-target",className:"palette-item",onClick:d,style:{"--shadow-color":ct(n).alpha(.5).hex(),backgroundColor:n}})}),i(s.Popover.Dropdown,{children:p(s.Stack,{children:[i(s.NumberInput,{size:"xs",label:"Map a value to this color",value:l,onChange:u}),p(s.Group,{position:"right",children:[i(s.Button,{variant:"subtle",size:"xs",onClick:w,children:"Cancel"}),i(s.Button,{"data-testid":"palette-item-ok",size:"xs",onClick:_,children:"OK"})]})]})})]}),i(s.Text,{title:C,style:{opacity:m?1:0},color:"dimmed",size:"sm",className:"palette-value--bottom palette-value",children:D})]})}const Ux=k.observer(({model:e})=>{const{classes:t}=Mo(),n=x.range(0,13,1).map(r=>100/12*r).map(r=>[e.interpolation.getColor(r),r]);return i("div",{className:t.palette,children:n.map(([r,a],o)=>i(Qx,{index:o,color:r,value:e.getStepFromValue(a),onChange:l=>e.changeStep(l,a)},r))})}),Kx=k.observer(function(t){const n=K.useCreation(()=>new Yx,[]);return b.useEffect(()=>{n.fromProps(t)}),n.interpolation==null?null:i(Ux,{model:n})}),Xx=e=>{const{value:t,onChange:n,colorManager:r}=e,a=r.getColorInterpolations(),[o,l]=b.useState(t),u=r.decodeInterpolation(o.interpolation)||a[0],[c,{setTrue:d,setFalse:f}]=K.useBoolean(),h=a.map(_=>({label:_.displayName,value:r.encodeColor(_),group:_.category}));function g(_){_&&l(D=>({...D,interpolation:_}))}const m=()=>{f(),n==null||n(te.toJS(o))};function C(_){l(D=>({...D,steps:_}))}const w=()=>{f(),l(t)};return p(B,{children:[i(s.Button,{variant:"outline",onClick:d,children:u==null?void 0:u.displayName}),i(s.Modal,{size:508,title:"Setup color interpolation",opened:c,onClose:f,zIndex:320,children:c&&p(s.Stack,{"data-testid":"color-interpolation-modal",children:[i(s.Select,{label:"Color style",value:o.interpolation,data:h,onChange:g}),i(Kx,{steps:o.steps,interpolation:u,onChange:C}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:w,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:m,children:"OK"})]})]})})]})},Jx=["static","interpolation","none"].map(e=>({label:x.capitalize(e),value:e})),Zx=[{from:0,to:0},{from:100,to:100}];function Ao(e){return e?x.isString(e)?e==="none"?"none":"static":"interpolation":"none"}function Hx(e,t){var n;return Ao(t)==="static"?t:(n=e.getStaticColors()[0])==null?void 0:n.value}function e0(e,t){return x.isObject(t)?t:{steps:Zx,interpolation:e.encodeColor(e.getColorInterpolations()[0])}}const t0=b.forwardRef((e,t)=>{const{colorManager:n}=b.useContext(ut),[r,a]=b.useState(Ao(e.value)),[o,l]=b.useState(Hx(n,e.value)),u=K.useLatest(o),[c,d]=b.useState(e0(n,e.value)),f=K.useLatest(c),h=C=>{var w,_,D;a(C||"none"),C==="static"?(w=e.onChange)==null||w.call(e,u.current):C==="none"||!C?(_=e.onChange)==null||_.call(e,"none"):(D=e.onChange)==null||D.call(e,f.current)},g=C=>{var w;l(C),(w=e.onChange)==null||w.call(e,C)},m=C=>{var w;d(C),(w=e.onChange)==null||w.call(e,C)};return p(s.Stack,{align:"stretch",children:[i(s.Select,{label:"Cell background",value:r||"none",onChange:h,data:Jx}),r==="static"&&i(Ve,{value:o,onChange:g}),r==="interpolation"&&i(Xx,{colorManager:n,value:c,onChange:m})]})}),n0={[it.eloc]:"ELOC"},r0=Object.values(it).map(e=>({label:x.get(n0,e,x.capitalize(e)),value:e})),i0=b.forwardRef(({label:e,value:t,onChange:n,sx:r},a)=>i(s.Select,{ref:a,label:e,data:r0,value:t,onChange:n,sx:r})),a0=b.forwardRef(({value:e,onChange:t},n)=>{const[r,{setTrue:a,setFalse:o}]=K.useBoolean(),[l,u]=b.useState(e),c=()=>{o(),t(l)},d=()=>{o(),u(e)},f=()=>{u(_o)};return b.useEffect(()=>{u(e)},[e]),p(B,{children:[i(s.Button,{variant:"filled",mt:24,onClick:a,sx:{flexGrow:0},children:"Custom Cell Content"}),i(s.Modal,{size:800,title:"Custom cell content",opened:r,onClose:o,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:r&&p(s.Stack,{children:[i(s.Box,{sx:{position:"relative"},children:i(Ae,{height:"500px",defaultLanguage:"javascript",value:l,onChange:h=>u(h??""),theme:"vs-dark",options:{minimap:{enabled:!1}}})}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:f,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:d,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:c,children:"OK"})]})]})]})})]})}),s0=[{label:"Left",value:"left"},{label:"Center",value:"center"},{label:"Right",value:"right"}],pi=()=>i(s.Text,{color:"dimmed",size:12,children:"px"}),o0=({control:e,index:t,watch:n,remove:r,column:a})=>{const o=n(`columns.${t}.value_type`);return p(s.Stack,{my:0,sx:{position:"relative"},children:[p(s.Group,{grow:!0,children:[i(v.Controller,{name:`columns.${t}.label`,control:e,render:({field:l})=>i(s.TextInput,{label:"Label",required:!0,id:`col-label-${t}`,sx:{flex:1},...l})}),i(v.Controller,{name:`columns.${t}.value_field`,control:e,render:({field:l})=>i(W,{label:"Value Field",required:!0,...l})})]}),p(s.Group,{grow:!0,children:[i(v.Controller,{name:`columns.${t}.value_type`,control:e,render:({field:l})=>i(i0,{label:"Value Type",sx:{flex:1},...l})}),o===it.custom&&i(v.Controller,{name:`columns.${t}.func_content`,control:e,render:({field:l})=>i(a0,{value:l.value??_o,onChange:u=>l.onChange(u??"")})})]}),i(s.Divider,{mb:-10,variant:"dashed",label:"Style",labelPosition:"center"}),p(s.Group,{grow:!0,children:[i(s.NumberInput,{hideControls:!0,label:"Min Width",rightSection:i(pi,{}),disabled:!0}),i(v.Controller,{name:`columns.${t}.width`,control:e,render:({field:l})=>i(s.NumberInput,{hideControls:!0,label:"Width",rightSection:i(pi,{}),...l})}),i(s.NumberInput,{hideControls:!0,label:"Max Width",rightSection:i(pi,{}),disabled:!0})]}),i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:`columns.${t}.align`,control:e,render:({field:l})=>i(s.Select,{label:"Alignment",data:s0,...l})})}),i(v.Controller,{name:`columns.${t}.cellBackgroundColor`,control:e,render:({field:l})=>i(t0,{...l})}),i(s.Divider,{mb:4,mt:12,variant:"dashed"}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>r(t),children:"Delete this column"})]})},l0=({control:e,watch:t})=>{const{fields:n,append:r,remove:a,update:o}=v.useFieldArray({control:e,name:"columns"}),l=()=>{const c=Ie.randomId();r({id:c,label:c,align:"center",value_field:"",value_type:it.string,width:""})};t("columns");const u=t("use_raw_columns");return p(B,{children:[i(v.Controller,{name:"use_raw_columns",control:e,render:({field:c})=>i(s.Switch,{mt:20,mb:20,label:"Use Original Data Columns",checked:c.value,onChange:d=>c.onChange(d.currentTarget.checked)})}),!u&&i(s.Stack,{children:p(s.Tabs,{defaultValue:"0",styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[n.map((c,d)=>i(s.Tabs.Tab,{value:d.toString(),children:d+1},c.id)),i(s.Tabs.Tab,{onClick:l,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),n.map((c,d)=>i(s.Tabs.Panel,{value:d.toString(),children:i(o0,{control:e,watch:t,index:d,column:c,remove:a},d)},c.id))]})})]})};function u0({control:e,watch:t}){return t(["horizontalSpacing","verticalSpacing","fontSize","striped","highlightOnHover"]),p(s.Stack,{spacing:"xs",children:[p(s.Group,{position:"apart",mb:"lg",grow:!0,sx:{"> *":{flexGrow:1}},children:[i(v.Controller,{name:"horizontalSpacing",control:e,render:({field:n})=>i(s.TextInput,{label:"Horizontal Spacing",placeholder:"10px, 1em, 1rem, 100%...",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"verticalSpacing",control:e,render:({field:n})=>i(s.TextInput,{label:"Vertical Spacing",placeholder:"10px, 1em, 1rem, 100%...",required:!0,sx:{flex:1},...n})})]}),i(s.Group,{position:"apart",mb:"lg",grow:!0,sx:{"> *":{flexGrow:1}},children:i(v.Controller,{name:"fontSize",control:e,render:({field:n})=>i(s.TextInput,{label:"Font Size",placeholder:"10px, 1em, 1rem, 100%...",required:!0,sx:{flex:1},...n})})}),p(s.Group,{position:"apart",grow:!0,children:[i(v.Controller,{name:"striped",control:e,render:({field:n})=>i(s.Switch,{label:"Striped",checked:n.value,onChange:r=>n.onChange(r.currentTarget.checked)})}),i(v.Controller,{name:"highlightOnHover",control:e,render:({field:n})=>i(s.Switch,{label:"Highlight on hover",checked:n.value,onChange:r=>n.onChange(r.currentTarget.checked)})})]})]})}function c0({columns:e,...t}){return{...t,columns:e.map(({id:n,...r})=>({id:n??Ie.randomId(),...r}))}}function d0({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=b.useMemo(()=>x.defaultsDeep({},t,ko),[t]),a=b.useMemo(()=>c0(r),[r]);b.useEffect(()=>{!x.isEqual(r,a)&&(console.log("config malformed, resetting to defaults",r,a),n(a))},[r,a]);const{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});b.useEffect(()=>{d(a)},[a]);const f=c(),h=b.useMemo(()=>!x.isEqual(f,r),[f,r]);return u(["id_field"]),p("form",{onSubmit:l(n),children:[p(s.Group,{position:"apart",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Table Config"}),i(s.ActionIcon,{type:"submit","aria-label":"save config",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"Columns",orientation:"vertical",styles:{tab:{paddingLeft:"6px",paddingRight:"6px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"Columns",children:"Columns"}),i(s.Tabs.Tab,{value:"Style",children:"Style"})]}),p(s.Tabs.Panel,{value:"Columns",children:[i(v.Controller,{name:"id_field",control:o,render:({field:g})=>i(W,{label:"ID Field",required:!0,...g})}),i(s.Divider,{mt:20,mb:10,variant:"dashed"}),i(l0,{control:o,watch:u})]}),i(s.Tabs.Panel,{value:"Style",children:i(u0,{control:o,watch:u})})]})]})}function p0(e){const{columns:t,...n}=e;return{...e,columns:t.map(r=>({...r,align:r.align??"left"}))}}function h0(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=u=>u&&`${n}.${u}`,{id_field:a,columns:o,...l}=e;return{...l,id_field:r(a),columns:o.map(u=>({...u,value_field:r(u.value_field)}))}}catch(n){throw console.error("[Migration failed]",n),n}}function f0(e){const{columns:t,...n}=e;return{...n,columns:t.map(r=>({...r,align:r.align??"left",cellBackgroundColor:r.cellBackgroundColor??"",width:r.width??""}))}}class g0 extends ye{constructor(){super(...arguments);N(this,"VERSION",5)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,n=>{const{columns:r,...a}=n.config;return{...n,version:2,config:{...a,columns:r.map(({id:o,...l})=>({id:o??Ie.randomId(),...l}))}}}),this.version(3,n=>({...n,version:3,config:p0(n.config)})),this.version(4,(n,r)=>({...n,version:4,config:h0(n.config,r)})),this.version(5,n=>({...n,version:5,config:f0(n.config)}))}}const hi={createConfig(){return{version:5,config:x.cloneDeep(ko)}},displayName:"Table",displayGroup:"Others",migrator:new g0,name:"table",viewRender:jx,configRender:d0,triggers:[di]},zo=["function text({ data, variables, filters, context}) {"," // your code goes here",' return "text"',"}"].join(`
297
+ `),fi={func_content:zo,horizontal_align:"left",font_size:"14px",font_weight:"normal"},m0=k.observer(({context:e})=>{const t=we(),{value:n=fi}=R(e.instanceData,"config"),{variables:r}=e,a=e.data,{func_content:o,horizontal_align:l,font_size:u,font_weight:c}=n,d=b.useMemo(()=>r.reduce((h,g)=>{const m=ft(g,a);return h[g.name]=Ze(g,m),h},{}),[r,a]),f=b.useMemo(()=>new Function(`return ${o}`)()({data:a,variables:d,filters:t.payloadForSQL.filters,context:t.payloadForSQL.context}),[o,a,d,t.payloadForSQL]);return i(s.Text,{align:l,weight:c,sx:{fontSize:u},children:f})}),y0=({value:e,onChange:t})=>{const n=r=>{r&&t(r)};return i(s.Box,{sx:{position:"relative"},children:i(Ae,{height:"500px",defaultLanguage:"javascript",value:e,onChange:n,theme:"vs-dark",options:{minimap:{enabled:!1}}})})},b0=b.forwardRef(({value:e,onChange:t},n)=>{const[r,{setTrue:a,setFalse:o}]=K.useBoolean(),[l,u]=b.useState(e),c=()=>{o(),t(l)},d=()=>{o(),u(e)},f=()=>{u(zo)};return b.useEffect(()=>{u(e)},[e]),p(B,{children:[i(s.Button,{variant:"filled",mt:24,onClick:a,sx:{flexGrow:0},children:"Edit Content"}),i(s.Modal,{size:800,title:"Text content",opened:r,onClose:o,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:r&&p(s.Stack,{children:[i(y0,{value:l,onChange:u}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:f,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:d,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:c,children:"OK"})]})]})]})})]})}),v0=[{label:"Left",value:"left"},{label:"Center",value:"center"},{label:"Right",value:"right"}];function x0({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=b.useMemo(()=>x.defaultsDeep({},t,fi),[t]),a=b.useMemo(()=>{const{func_content:g,horizontal_align:m,font_size:C,font_weight:w}=r;return{func_content:g,horizontal_align:m,font_size:C,font_weight:w}},[r]);b.useEffect(()=>{!x.isEqual(r,a)&&(console.log("config malformed, resetting to defaults",r,a),n(a))},[r,a]);const{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});b.useEffect(()=>{d(a)},[a]),u(["func_content","horizontal_align","font_size","font_weight"]);const f=c(),h=b.useMemo(()=>!x.isEqual(f,r),[f,r]);return i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:l(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{weight:500,children:"Configurations"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Stack,{spacing:10,children:[i(v.Controller,{name:"func_content",control:o,render:({field:g})=>i(b0,{...g})}),i(s.Divider,{mt:10,mb:-10,variant:"dashed",label:"Style",labelPosition:"center"}),i(v.Controller,{name:"horizontal_align",control:o,render:({field:g})=>i(s.Select,{label:"Horizontal Alignment",data:v0,...g})}),i(v.Controller,{name:"font_size",control:o,render:({field:g})=>i(s.TextInput,{label:"Font Size",placeholder:"10px, 1em, 1rem, 100%...",sx:{flex:1},...g})}),i(s.Group,{position:"apart",grow:!0,sx:{"> *":{flexGrow:1,maxWidth:"100%"}},children:i(v.Controller,{name:"font_weight",control:o,render:({field:g})=>i(Rs,{label:"Font Weight",...g})})})]})]})})}class w0 extends ye{constructor(){super(...arguments);N(this,"VERSION",1)}configVersions(){this.version(1,n=>({version:1,config:n}))}}const C0={displayName:"Text",displayGroup:"Others",migrator:new w0,name:"text",viewRender:m0,configRender:x0,createConfig(){return{version:1,config:x.cloneDeep(fi)}}},S0=()=>p("svg",{width:"64",height:"64",viewBox:"0 0 64 64",fill:"none",children:[i("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M22.49 27.79H14.47C13.55 27.79 12.81 28.53 12.81 29.45C12.81 30.37 13.55 31.11 14.47 31.11H22.49C23.41 31.11 24.15 30.37 24.15 29.45C24.15 28.54 23.41 27.79 22.49 27.79ZM34.32 31.28C35.22 31.32 35.7 31.82 35.74 32.76C35.78 33.54 35.37 34.3 34.51 35.04C33.52 35.9 33.03 36.95 33.03 38.19V38.81H34.82V38.25C34.78 37.59 35.07 37.02 35.68 36.52C37.12 35.41 37.82 34.15 37.78 32.75C37.66 30.53 36.5 29.35 34.32 29.23C32.3 29.23 31.05 30.46 30.55 32.93L32.53 33.55C32.82 32.04 33.42 31.28 34.32 31.28ZM35 39.93H32.84V42.21H35V39.93ZM14.83 36.42H18.54C19.46 36.42 20.2 37.17 20.2 38.08C20.2 39 19.46 39.74 18.54 39.74H10.52C9.6 39.74 8.86 39 8.86 38.08C8.86 37.61 9.06 37.19 9.37 36.89H5.66C4.74 36.89 4 36.15 4 35.23C4 34.31 4.74 33.57 5.66 33.57H13.68C14.6 33.57 15.34 34.31 15.34 35.23C15.34 35.7 15.14 36.12 14.83 36.42ZM50.94 36.85H58.74C59.66 36.85 60.4 37.59 60.41 38.51C60.41 39.43 59.67 40.17 58.75 40.17H54.26C54.56 40.47 54.74 40.88 54.74 41.34C54.74 42.26 54 43 53.08 43H50.94V36.85Z",fill:"#B8C0CC"}),i("path",{d:"M18.39 32.28H16.51V35.02H18.39V32.28Z",fill:"#9399A5"}),i("path",{d:"M46.87 15H20.69C18.38 15 16.5 16.88 16.5 19.19V26.22H18.38V23.45H49.18V47.68H18.38V41.07H16.5V49.55H51.05V19.19C51.06 16.88 49.18 15 46.87 15ZM39.46 20.73C38.81 20.73 38.29 20.2 38.29 19.56C38.29 18.92 38.82 18.39 39.46 18.39C40.11 18.39 40.63 18.92 40.63 19.56C40.63 20.2 40.11 20.73 39.46 20.73ZM43.22 20.73C42.57 20.73 42.05 20.2 42.05 19.56C42.05 18.92 42.58 18.39 43.22 18.39C43.87 18.39 44.39 18.92 44.39 19.56C44.39 20.2 43.87 20.73 43.22 20.73ZM46.97 20.73C46.32 20.73 45.8 20.2 45.8 19.56C45.8 18.92 46.33 18.39 46.97 18.39C47.62 18.39 48.14 18.92 48.14 19.56C48.14 20.2 47.62 20.73 46.97 20.73Z",fill:"#9399A5"})]});function Eo(e,t){const n=x.get(e,t,"");if(n)throw new Error(n)}async function _0(e,t,n,r={}){const a={"X-Requested-With":"XMLHttpRequest","Content-Type":r.string?"application/x-www-form-urlencoded":"application/json",...r.headers},o={baseURL:e,method:"POST",url:t,params:r.params,headers:a};return o.data=r.string?JSON.stringify(n):n,mt(o).then(l=>l.data).catch(l=>Promise.reject(l))}const k0=({conf:e,panelData:t})=>async()=>{const{expertSystemURL:n,path:r,goal:a,question:o}=e;if(!r||!a||!o)return;const l=dc(t);if(!l)return;const u={dashboard:a,panel:o,data:l};try{const c=n.startsWith("http")?n:window.location.origin;return await _0(c,`/expert/v3/devtable/${r}`,u,{})}catch(c){throw Eo(c,"response.data.detail"),Eo(c,"response.data.error"),console.error(c),c}},gi={expertSystemURL:"",path:"",goal:"",question:""},mi={height:"100%",overflowY:"auto",...Mr},$o=({message:e})=>i(s.Box,{sx:mi,children:i("div",{dangerouslySetInnerHTML:{__html:e},style:{fontSize:"14px",lineHeight:"32px",color:"#3D3E45"}})}),T0=({error:e,width:t,height:n})=>{const r=e.message;if(r.startsWith("<"))return i($o,{message:r});const o=n-25-20-30;return i(s.Center,{sx:{width:"100%",height:o},children:p(s.Stack,{align:"center",spacing:20,children:[i(S0,{}),i($o,{message:r})]})})};function D0({context:e}){const{value:t}=R(e.instanceData,"config"),n=b.useMemo(()=>x.defaultsDeep({},t,gi),[t]),{width:r,height:a}=e.viewport,o=e.data,{data:l,error:u,loading:c}=K.useRequest(k0({conf:n,panelData:o}),{refreshDeps:[o,n]});return!r||!a||!n?null:c?i(s.Box,{sx:{position:"relative",height:a},children:i(s.LoadingOverlay,{visible:!0})}):u?i(s.Box,{sx:mi,"data-enable-scrollbar":!0,children:i(T0,{error:u,width:r,height:a})}):!l||!Array.isArray(l.replies)||l.replies.length===0?null:i(s.Box,{sx:mi,"data-enable-scrollbar":!0,children:l.replies.map((d,f)=>i("div",{dangerouslySetInnerHTML:{__html:d.interpretation.html}},f))})}function I0({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=b.useMemo(()=>x.defaultsDeep({},t,gi),[t]),{control:a,handleSubmit:o,watch:l,getValues:u,reset:c}=v.useForm({defaultValues:r});b.useEffect(()=>{c(r)},[r]),l(["expertSystemURL","goal","path","question"]);const d=u(),f=b.useMemo(()=>!x.isEqual(d,r),[d,r]);return i("form",{onSubmit:o(n),children:p(s.Stack,{children:[p(s.Group,{grow:!0,children:[i(v.Controller,{name:"expertSystemURL",control:a,render:({field:h})=>i(s.TextInput,{label:"Expert System URL",...h})}),i(v.Controller,{name:"path",control:a,render:({field:h})=>i(s.TextInput,{label:"Path",required:!0,...h})})]}),p(s.Group,{grow:!0,children:[i(v.Controller,{name:"goal",control:a,render:({field:h})=>i(s.TextInput,{label:"Goal",required:!0,...h})}),i(v.Controller,{name:"question",control:a,render:({field:h})=>i(s.TextInput,{label:"Question",required:!0,...h})})]}),i(s.Divider,{variant:"dashed",mt:16,mb:8}),i(s.Button,{type:"submit",variant:"filled",color:"blue",leftIcon:i(T.DeviceFloppy,{size:20}),disabled:!f,sx:{alignSelf:"flex-end"},children:"Submit Changes"})]})})}class M0 extends ye{constructor(){super(...arguments);N(this,"VERSION",1)}configVersions(){this.version(1,n=>({version:1,config:n}))}}const A0={displayName:"Merico GQM",displayGroup:"Merico suite",migrator:new M0,name:"mericoGQM",viewRender:D0,configRender:I0,createConfig(){return{version:1,config:x.cloneDeep(gi)}}};function z0(e,t,n){if(!e)return n[0];try{return[t,Y(t).add(1,"year").subtract(1,"day").valueOf()]}catch(r){return console.error(r),n[0]}}function E0(e,t,n){const r=z0(e,t,n);return{top:50,left:25,right:5,cellSize:["auto",13],range:r,itemStyle:{borderColor:"#eee"},splitLine:{show:!0},dayLabel:{firstDay:1},monthLabel:{position:"end"},yearLabel:{show:!0}}}function $0(e){return{heat_block:function(r){if(!e.heat_block.value_formatter)return r;try{return Z(r).format(e.heat_block.value_formatter)}catch(a){return console.error(a),r}}}}function L0(e,t){return{show:!e,selectedMode:"single",top:5,right:5,data:t.map(n=>({name:n,icon:"circle"}))}}function O0(e,t,n,r){const{calendar:a,heat_block:o}=e,l=O(a.data_key),u=O(o.data_key);return t?{type:"heatmap",name:"heatmap",coordinateSystem:"calendar",calendarIndex:0,data:r[l.queryID].map(c=>[x.get(c,l.columnKey),x.get(c,u.columnKey)])}:Object.entries(n).map(([c,d])=>({type:"heatmap",name:c,coordinateSystem:"calendar",calendarIndex:0,data:d.map(f=>[x.get(f,l.columnKey),x.get(f,u.columnKey)])}))}const P0=e=>{try{return Z(e).format({trimMantissa:!0,mantissa:2})}catch{return e}};function B0({conf:e,valueFormatters:t,dataDict:n,params:r}){const{value:a}=r,[o,l]=a,c=[{label:e.heat_block.name,value:t.heat_block(l),style:{label:"",value:""}}],d=n[o];return d&&e.tooltip.metrics.forEach(f=>{const h=O(f.data_key);c.push({label:f.name,value:P0(x.get(d,h.columnKey,"")),style:{label:"",value:""}})}),c}function V0(e,t,n){const r=O(e.calendar.data_key),a=x.keyBy(t[r.queryID],r.columnKey);return{confine:!0,formatter:function(o){const u=B0({conf:e,valueFormatters:n,dataDict:a,params:o}).map(f=>`
298
298
  <tr>
299
299
  <th style="text-align: right;">
300
300
  <div style="${f.style.label}">${f.label}</div>
@@ -320,7 +320,7 @@ Check the top-level render call using <`+V+">.")}return E}}function Su(S,E){{if(
320
320
  </thead>
321
321
  <tbody>${u.join("")}</tbody>
322
322
  </table>
323
- `}}}function N0(e,t,n){const r=Gt(e.heat_block.min,n),a=Gt(e.heat_block.max,n);return{min:r,max:a,calculable:!0,orient:"horizontal",left:t?"center":5,top:0,itemWidth:15}}const q0={tooltip:{confine:!0},grid:{containLabel:!0}},F0=e=>Y(e).get("year");function G0(e,t){const n=O(e.calendar.data_key),r=t[n.queryID],a=x.groupBy(r,d=>F0(d[n.columnKey])),o=Object.keys(a),l=r.map(d=>Y(d[n.columnKey]).valueOf()),u=x.min(l),c=x.max(l);return{minDate:u??0,maxDate:c??0,dateSpan:Y(c).diff(u,"day"),dataByYear:a,years:o}}function W0(e,t,n){const r=n.reduce((h,g)=>{const m=ft(g,t);return h[g.name]=Ze(g,m),h},{}),a=$0(e),{dateSpan:o,minDate:l,dataByYear:u,years:c}=G0(e,t),d=o<=366,f={calendar:E0(d,l,c),series:O0(e,d,u,t),tooltip:V0(e,t,a),visualMap:N0(e,d,r),legend:L0(d,c)};return x.defaultsDeep({},f,q0)}function j0(e){return i(B,{})}function R0(e){return i(s.Text,{children:"Click heat block"})}const Lo={id:"builtin:echarts:click-heatmap:heat-block",displayName:"Click Heat Block",nameRender:R0,configRender:j0,payload:[{name:"seriesType",description:"'heatmap'",valueType:"string"},{name:"componentType",description:"'series'",valueType:"string"},{name:"name",description:"Name of the series clicked",valueType:"string"},{name:"color",description:"Color",valueType:"string"},{name:"value",description:"String-typed number, or series' actual value",valueType:"string"},{name:"rowData",description:"Data of the row",valueType:"object"}]},yi={calendar:{data_key:"",locale:"EN"},heat_block:{min:{type:"static",value:0},max:{type:"static",value:100},name:"Value",data_key:"",value_formatter:ze},tooltip:{metrics:[]}};ie.use([q.DataZoomComponent,he.BarChart,he.LineChart,he.HeatmapChart,q.CalendarComponent,q.GridComponent,q.LegendComponent,q.TooltipComponent,q.VisualMapComponent,Pe.CanvasRenderer]);function Y0({name:e},t){const n=t.getOption();n.calendar.forEach(r=>{r.range=e}),t.setOption(n)}function Q0({conf:e,data:t,width:n,height:r,interactionManager:a,variables:o}){const l=Dt(t,e.calendar.data_key),u=Ke(a.triggerManager,Lo.id),c=y.useCallback(h=>{const[g,m]=h.value,C=x.get(l,g,{error:"rowData is not found"});u.forEach(w=>{a.runInteraction(w.id,{...h,rowData:C})})},[l,u,a]),d=y.useMemo(()=>({click:c,legendselectchanged:Y0}),[c]),f=y.useMemo(()=>W0(e,t,o),[e,t]);return!n||!r?null:i(Be,{echarts:ie,option:f,style:{width:n,height:r},onEvents:d,notMerge:!0,opts:{locale:e.calendar.locale},theme:"merico-light"})}function U0({context:e,instance:t}){const n=Xe({vizManager:e.vizManager,instance:t}),{value:r}=R(e.instanceData,"config"),{variables:a}=e,o=y.useMemo(()=>x.defaults({},r,yi),[r]),l=e.data,{width:u,height:c}=e.viewport;return!o.calendar.data_key||!o.heat_block.data_key?null:i(Q0,{variables:a,width:u,height:c,data:l,conf:o,interactionManager:n})}function K0({control:e,watch:t}){return t(["heat_block"]),p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"heat_block.data_key",control:e,render:({field:n})=>i(W,{label:"Data Field",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"heat_block.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Name",sx:{flex:1},...n})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"heat_block.min",control:e,render:({field:n})=>i(Ft,{label:"Min Value",...n})}),i(v.Controller,{name:"heat_block.max",control:e,render:({field:n})=>i(Ft,{label:"Max Value",...n})})]}),i(s.Divider,{mb:-15,variant:"dashed",label:"Value Format",labelPosition:"center"}),i(v.Controller,{name:"heat_block.value_formatter",control:e,render:({field:n})=>i(We,{...n})})]})}const X0=({control:e,index:t,remove:n})=>p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`tooltip.metrics.${t}.name`,control:e,render:({field:r})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:`tooltip.metrics.${t}.data_key`,control:e,render:({field:r})=>i(W,{label:"Value Field",required:!0,sx:{flex:1},...r})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed"}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Metric"})]}),J0=({control:e,watch:t})=>{const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"tooltip.metrics"}),o=t("tooltip.metrics"),l=n.map((h,g)=>({...h,...o[g]})),u=()=>r({id:Date.now().toString(),data_key:"",name:""}),c=t("tooltip.metrics.0.id"),[d,f]=y.useState(()=>c??null);return y.useEffect(()=>{c&&f(h=>h!==null?h:c)},[c]),p(B,{children:[p(s.Group,{spacing:2,sx:{cursor:"default",userSelect:"none"},children:[i(T.InfoCircle,{size:14,color:"#888"}),i(s.Text,{size:14,color:"#888",children:"Configure additional metrics to show in tooltip"})]}),i(s.Divider,{variant:"dashed",my:10}),p(s.Tabs,{value:d,onTabChange:h=>f(h),styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map((h,g)=>i(s.Tabs.Tab,{value:h.id,children:h.name?h.name:g},h.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((h,g)=>i(s.Tabs.Panel,{value:h.id,children:i(X0,{control:e,index:g,remove:a},h.id)},h.id))]})]})};function Z0({control:e,watch:t}){return i(J0,{control:e,watch:t})}const H0=[{label:"Chinese",value:"ZH"},{label:"English",value:"EN"}];function ew({control:e,watch:t}){return t(["calendar"]),p(s.Stack,{children:[i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:"calendar.data_key",control:e,render:({field:n})=>i(W,{label:"Data Field",required:!0,sx:{flex:1},...n})})}),i(v.Controller,{name:"calendar.locale",control:e,render:({field:n})=>i(s.Select,{label:"Language",required:!0,data:H0,sx:{flex:1},...n})})]})}function tw({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=y.useMemo(()=>x.defaultsDeep({},t,yi),[t]),a=y.useMemo(()=>x.cloneDeep(r),[r]);y.useEffect(()=>{!x.isEqual(r,a)&&(console.log("config malformed, resetting to defaults",r,a),n(a))},[r,a]);const{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});y.useEffect(()=>{d(a)},[a]);const f=c(),h=y.useMemo(()=>!x.isEqual(f,r),[f,r]);return i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:l(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Calendar Heatmap Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"Calendar",orientation:"vertical",styles:{tab:{paddingLeft:"6px",paddingRight:"6px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"Calendar",children:"Calendar"}),i(s.Tabs.Tab,{value:"Heat Block",children:"Heat Block"}),i(s.Tabs.Tab,{value:"Tooltip",children:"Tooltip"})]}),i(s.Tabs.Panel,{value:"Calendar",children:i(ew,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Heat Block",children:i(K0,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Tooltip",children:i(Z0,{control:o,watch:u})})]})]})})}function nw(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=c=>c&&`${n}.${c}`,{calendar:a,heat_block:o,tooltip:l,...u}=e;return{...u,calendar:{...a,data_key:r(a.data_key)},heat_block:{...o,data_key:r(o.data_key)},tooltip:{...l,metrics:l.metrics.map(c=>({...c,data_key:r(c.data_key)}))}}}catch(n){throw console.error("[Migration failed]",n),n}}function rw(e){const{heat_block:t}=e;let{min:n,max:r}=t;return typeof n!="number"&&(n=0),typeof r!="number"&&(r=100),{...e,heat_block:{...t,min:{type:"static",value:n},max:{type:"static",value:r}}}}class iw extends ye{constructor(){super(...arguments);N(this,"VERSION",3)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,(n,r)=>({...n,version:2,config:nw(n.config,r)})),this.version(3,n=>({...n,version:3,config:rw(n.config)}))}}const aw={displayName:"Heatmap(Calendar)",displayGroup:"ECharts-based charts",migrator:new iw,name:"calendarHeatmap",viewRender:U0,configRender:tw,createConfig:()=>({version:3,config:yi}),triggers:[Lo]},bi={x_axes:[{id:"initial-x",min:"",max:"",name:"X Axis",data_key:"",position:"bottom",label_formatter:ze,show:!0}],y_axis:{name:"Y Axis",data_key:"",axisLabel:{formatter:{...Ue},overflow:je},nameAlignment:"center"},series:[],tooltip:{metrics:[]},reference_lines:[]};function sw(){const e=new Date().getTime().toString();return{id:e,min:"",max:"",name:e,data_key:"",position:"bottom",label_formatter:ze,show:!0}}function ow(){const e=new Date().getTime().toString();return{id:e,type:"bar",name:e,stack:"",color:"",barGap:"0%",data_key:"",barWidth:"",barMinWidth:"1",barMaxWidth:"10",group_by_key:"",hide_in_legend:!1,invisible:!1,label_position:"right",aggregation_on_value:Nt,xAxisIndex:"0"}}function lw(){const e=new Date().getTime().toString();return{id:e,name:e,template:"",variable_key:"",orientation:"horizontal",lineStyle:{type:"dashed",width:1,color:"#868E96"},show_in_legend:!1,xAxisIndex:"0"}}function uw(e){const t=e.x_axes.some(o=>o.position==="top"&&!!o.name&&o.show);let n=0;t&&(n+=15);const r=e.x_axes.some(o=>o.position==="bottom"&&!!o.name&&o.show);let a=0;return r&&(a+=15),e.series.some(o=>!o.hide_in_legend)&&(a+=20),{top:n,right:5,bottom:a,left:5,containLabel:!0}}function cw(e){switch(e){case"bar":return"roundRect";case"scatter":return"circle"}}function dw(e){const t={show:!0,bottom:0,left:"center",type:"scroll"};return t.data=e.filter(n=>!n.hide_in_legend).map(({name:n,type:r})=>({name:n,icon:cw(r)})),t}function pw(e,t,n,r){return e.map(a=>{const o=a.orientation==="horizontal",l=o?"yAxis":"xAxis",u=o?"insideEndTop":"end";return{name:a.name,type:"line",hide_in_legend:!a.show_in_legend,xAxisIndex:a.xAxisIndex,data:[],lineStyle:a.lineStyle,markLine:{data:[{name:a.name,[l]:Number(n[a.variable_key])}],silent:!0,symbol:["none","none"],lineStyle:a.lineStyle,label:{formatter:function(){return a.template?jn(a.template,t,r):""},position:u}}}})}function Hn(e,t,n){const r=pt(e,t),a=pt(e,n);return x.zip(a,r)}function hw(e,t,n,r){const a=Hn(t,n,r);return x.unionBy(a,e,0)}function fw({dataTemplate:e,data:t,name_data_key:n,value_data_key:r,valueTypedXAxis:a}){return a?hw(e,t,n,r):Hn(t,n,r)}function gw({dataTemplate:e,data:t,aggregation_on_value:n,name_data_key:r,value_data_key:a,valueTypedXAxis:o}){if(!n||n.type==="none")return fw({dataTemplate:e,data:t,name_data_key:r,value_data_key:a,valueTypedXAxis:o});const l=Hn(t,r,a),u=x.groupBy(l,"0");return e.map(([d])=>{const h=u[d].map(m=>m[1]),g=Rr(h,n);return[d,g]})}function mw({group_by_key:e,data:t,value_data_key:n,name_data_key:r}){const{queryID:a,columnKey:o}=O(e),l=x.groupBy(t[a],o);return Object.entries(l).forEach(([u,c])=>{l[u]=Hn({[a]:c},r,n)}),l}function yw({y_axis:e},{data_key:t,xAxisIndex:n,label_position:r,name:a,group_by_key:o,aggregation_on_value:l,stack:u,color:c,hide_in_legend:d,invisible:f,id:h,...g},m,C,w,_,D){const M={label:{show:!!r,position:r,formatter:D[n??"default"]},name:a,yAxisId:"main-y-axis",xAxisIndex:n,stack:u,color:f?"transparent":c,hide_in_legend:d,labelLayout:{hideOverlap:!0},emphasis:{disabled:!0},...g};if(!o||o===e.data_key)return M.data=gw({dataTemplate:m,data:w,aggregation_on_value:l,name_data_key:e.data_key,value_data_key:t,valueTypedXAxis:C}),M;const P=mw({group_by_key:o,data:w,name_data_key:e.data_key,value_data_key:t});return Object.entries(P).map(([G,L])=>{const z=x.cloneDeep(M);return z.name=G,z.color=void 0,z.data=L,z})}function bw(e,t,n,r,a,o,l){const u=t.map(d=>[d,0]);return e.series.map(d=>yw(e,d,u,n,r,l,a)).flat().concat(pw(e.reference_lines,o,l,r))}function vw(e,t){const n=e.find(u=>u.axisDim==="y"&&u.axisId==="main-y-axis");if(!n)return"";const{name:r,axisType:a,axisValue:o,axisIndex:l}=n;return a==="yAxis.category"?r:Pt(t.y_axis.axisLabel.formatter)(o,l)}function xw(e,t,n){const r=t.reduce((a,{xAxisIndex:o,name:l})=>(a[l]=o,a),{});return{trigger:"axis",axisPointer:{type:"shadow"},formatter:function(a){const o=Array.isArray(a)?a:[a];if(o.length===0)return"";const l=o.map(({seriesName:d,marker:f,value:h})=>{if(Array.isArray(h)&&h.length===2&&(h=h[0]),!d)return h;const g=r[d],m=n[g]??n.default;return`
323
+ `}}}function N0(e,t,n){const r=Gt(e.heat_block.min,n),a=Gt(e.heat_block.max,n);return{min:r,max:a,calculable:!0,orient:"horizontal",left:t?"center":5,top:0,itemWidth:15}}const q0={tooltip:{confine:!0},grid:{containLabel:!0}},F0=e=>Y(e).get("year");function G0(e,t){const n=O(e.calendar.data_key),r=t[n.queryID],a=x.groupBy(r,d=>F0(d[n.columnKey])),o=Object.keys(a),l=r.map(d=>Y(d[n.columnKey]).valueOf()),u=x.min(l),c=x.max(l);return{minDate:u??0,maxDate:c??0,dateSpan:Y(c).diff(u,"day"),dataByYear:a,years:o}}function W0(e,t,n){const r=n.reduce((h,g)=>{const m=ft(g,t);return h[g.name]=Ze(g,m),h},{}),a=$0(e),{dateSpan:o,minDate:l,dataByYear:u,years:c}=G0(e,t),d=o<=366,f={calendar:E0(d,l,c),series:O0(e,d,u,t),tooltip:V0(e,t,a),visualMap:N0(e,d,r),legend:L0(d,c)};return x.defaultsDeep({},f,q0)}function j0(e){return i(B,{})}function R0(e){return i(s.Text,{children:"Click heat block"})}const Lo={id:"builtin:echarts:click-heatmap:heat-block",displayName:"Click Heat Block",nameRender:R0,configRender:j0,payload:[{name:"seriesType",description:"'heatmap'",valueType:"string"},{name:"componentType",description:"'series'",valueType:"string"},{name:"name",description:"Name of the series clicked",valueType:"string"},{name:"color",description:"Color",valueType:"string"},{name:"value",description:"String-typed number, or series' actual value",valueType:"string"},{name:"rowData",description:"Data of the row",valueType:"object"}]},yi={calendar:{data_key:"",locale:"EN"},heat_block:{min:{type:"static",value:0},max:{type:"static",value:100},name:"Value",data_key:"",value_formatter:ze},tooltip:{metrics:[]}};ie.use([q.DataZoomComponent,he.BarChart,he.LineChart,he.HeatmapChart,q.CalendarComponent,q.GridComponent,q.LegendComponent,q.TooltipComponent,q.VisualMapComponent,Pe.CanvasRenderer]);function Y0({name:e},t){const n=t.getOption();n.calendar.forEach(r=>{r.range=e}),t.setOption(n)}function Q0({conf:e,data:t,width:n,height:r,interactionManager:a,variables:o}){const l=Dt(t,e.calendar.data_key),u=Ke(a.triggerManager,Lo.id),c=b.useCallback(h=>{const[g,m]=h.value,C=x.get(l,g,{error:"rowData is not found"});u.forEach(w=>{a.runInteraction(w.id,{...h,rowData:C})})},[l,u,a]),d=b.useMemo(()=>({click:c,legendselectchanged:Y0}),[c]),f=b.useMemo(()=>W0(e,t,o),[e,t]);return!n||!r?null:i(Be,{echarts:ie,option:f,style:{width:n,height:r},onEvents:d,notMerge:!0,opts:{locale:e.calendar.locale},theme:"merico-light"})}function U0({context:e,instance:t}){const n=Xe({vizManager:e.vizManager,instance:t}),{value:r}=R(e.instanceData,"config"),{variables:a}=e,o=b.useMemo(()=>x.defaults({},r,yi),[r]),l=e.data,{width:u,height:c}=e.viewport;return!o.calendar.data_key||!o.heat_block.data_key?null:i(Q0,{variables:a,width:u,height:c,data:l,conf:o,interactionManager:n})}function K0({control:e,watch:t}){return t(["heat_block"]),p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"heat_block.data_key",control:e,render:({field:n})=>i(W,{label:"Data Field",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"heat_block.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Name",sx:{flex:1},...n})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"heat_block.min",control:e,render:({field:n})=>i(Ft,{label:"Min Value",...n})}),i(v.Controller,{name:"heat_block.max",control:e,render:({field:n})=>i(Ft,{label:"Max Value",...n})})]}),i(s.Divider,{mb:-15,variant:"dashed",label:"Value Format",labelPosition:"center"}),i(v.Controller,{name:"heat_block.value_formatter",control:e,render:({field:n})=>i(je,{...n})})]})}const X0=({control:e,index:t,remove:n})=>p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`tooltip.metrics.${t}.name`,control:e,render:({field:r})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:`tooltip.metrics.${t}.data_key`,control:e,render:({field:r})=>i(W,{label:"Value Field",required:!0,sx:{flex:1},...r})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed"}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Metric"})]}),J0=({control:e,watch:t})=>{const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"tooltip.metrics"}),o=t("tooltip.metrics"),l=n.map((h,g)=>({...h,...o[g]})),u=()=>r({id:Date.now().toString(),data_key:"",name:""}),c=t("tooltip.metrics.0.id"),[d,f]=b.useState(()=>c??null);return b.useEffect(()=>{c&&f(h=>h!==null?h:c)},[c]),p(B,{children:[p(s.Group,{spacing:2,sx:{cursor:"default",userSelect:"none"},children:[i(T.InfoCircle,{size:14,color:"#888"}),i(s.Text,{size:14,color:"#888",children:"Configure additional metrics to show in tooltip"})]}),i(s.Divider,{variant:"dashed",my:10}),p(s.Tabs,{value:d,onTabChange:h=>f(h),styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map((h,g)=>i(s.Tabs.Tab,{value:h.id,children:h.name?h.name:g},h.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((h,g)=>i(s.Tabs.Panel,{value:h.id,children:i(X0,{control:e,index:g,remove:a},h.id)},h.id))]})]})};function Z0({control:e,watch:t}){return i(J0,{control:e,watch:t})}const H0=[{label:"Chinese",value:"ZH"},{label:"English",value:"EN"}];function ew({control:e,watch:t}){return t(["calendar"]),p(s.Stack,{children:[i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:"calendar.data_key",control:e,render:({field:n})=>i(W,{label:"Data Field",required:!0,sx:{flex:1},...n})})}),i(v.Controller,{name:"calendar.locale",control:e,render:({field:n})=>i(s.Select,{label:"Language",required:!0,data:H0,sx:{flex:1},...n})})]})}function tw({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=b.useMemo(()=>x.defaultsDeep({},t,yi),[t]),a=b.useMemo(()=>x.cloneDeep(r),[r]);b.useEffect(()=>{!x.isEqual(r,a)&&(console.log("config malformed, resetting to defaults",r,a),n(a))},[r,a]);const{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});b.useEffect(()=>{d(a)},[a]);const f=c(),h=b.useMemo(()=>!x.isEqual(f,r),[f,r]);return i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:l(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Calendar Heatmap Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"Calendar",orientation:"vertical",styles:{tab:{paddingLeft:"6px",paddingRight:"6px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"Calendar",children:"Calendar"}),i(s.Tabs.Tab,{value:"Heat Block",children:"Heat Block"}),i(s.Tabs.Tab,{value:"Tooltip",children:"Tooltip"})]}),i(s.Tabs.Panel,{value:"Calendar",children:i(ew,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Heat Block",children:i(K0,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Tooltip",children:i(Z0,{control:o,watch:u})})]})]})})}function nw(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=c=>c&&`${n}.${c}`,{calendar:a,heat_block:o,tooltip:l,...u}=e;return{...u,calendar:{...a,data_key:r(a.data_key)},heat_block:{...o,data_key:r(o.data_key)},tooltip:{...l,metrics:l.metrics.map(c=>({...c,data_key:r(c.data_key)}))}}}catch(n){throw console.error("[Migration failed]",n),n}}function rw(e){const{heat_block:t}=e;let{min:n,max:r}=t;return typeof n!="number"&&(n=0),typeof r!="number"&&(r=100),{...e,heat_block:{...t,min:{type:"static",value:n},max:{type:"static",value:r}}}}class iw extends ye{constructor(){super(...arguments);N(this,"VERSION",3)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,(n,r)=>({...n,version:2,config:nw(n.config,r)})),this.version(3,n=>({...n,version:3,config:rw(n.config)}))}}const aw={displayName:"Heatmap(Calendar)",displayGroup:"ECharts-based charts",migrator:new iw,name:"calendarHeatmap",viewRender:U0,configRender:tw,createConfig:()=>({version:3,config:yi}),triggers:[Lo]},bi={x_axes:[{id:"initial-x",min:"",max:"",name:"X Axis",data_key:"",position:"bottom",label_formatter:ze,show:!0}],y_axis:{name:"Y Axis",data_key:"",axisLabel:{formatter:{...Ue},overflow:Re},nameAlignment:"center"},series:[],tooltip:{metrics:[]},reference_lines:[]};function sw(){const e=new Date().getTime().toString();return{id:e,min:"",max:"",name:e,data_key:"",position:"bottom",label_formatter:ze,show:!0}}function ow(){const e=new Date().getTime().toString();return{id:e,type:"bar",name:e,stack:"",color:"",barGap:"0%",data_key:"",barWidth:"",barMinWidth:"1",barMaxWidth:"10",group_by_key:"",hide_in_legend:!1,invisible:!1,label_position:"right",aggregation_on_value:Nt,xAxisIndex:"0"}}function lw(){const e=new Date().getTime().toString();return{id:e,name:e,template:"",variable_key:"",orientation:"horizontal",lineStyle:{type:"dashed",width:1,color:"#868E96"},show_in_legend:!1,xAxisIndex:"0"}}function uw(e){const t=e.x_axes.some(o=>o.position==="top"&&!!o.name&&o.show);let n=0;t&&(n+=15);const r=e.x_axes.some(o=>o.position==="bottom"&&!!o.name&&o.show);let a=0;return r&&(a+=15),e.series.some(o=>!o.hide_in_legend)&&(a+=20),{top:n,right:5,bottom:a,left:5,containLabel:!0}}function cw(e){switch(e){case"bar":return"roundRect";case"scatter":return"circle"}}function dw(e){const t={show:!0,bottom:0,left:"center",type:"scroll"};return t.data=e.filter(n=>!n.hide_in_legend).map(({name:n,type:r})=>({name:n,icon:cw(r)})),t}function pw(e,t,n,r){return e.map(a=>{const o=a.orientation==="horizontal",l=o?"yAxis":"xAxis",u=o?"insideEndTop":"end";return{name:a.name,type:"line",hide_in_legend:!a.show_in_legend,xAxisIndex:a.xAxisIndex,data:[],lineStyle:a.lineStyle,markLine:{data:[{name:a.name,[l]:Number(n[a.variable_key])}],silent:!0,symbol:["none","none"],lineStyle:a.lineStyle,label:{formatter:function(){return a.template?jn(a.template,t,r):""},position:u}}}})}function Hn(e,t,n){const r=pt(e,t),a=pt(e,n);return x.zip(a,r)}function hw(e,t,n,r){const a=Hn(t,n,r);return x.unionBy(a,e,0)}function fw({dataTemplate:e,data:t,name_data_key:n,value_data_key:r,valueTypedXAxis:a}){return a?hw(e,t,n,r):Hn(t,n,r)}function gw({dataTemplate:e,data:t,aggregation_on_value:n,name_data_key:r,value_data_key:a,valueTypedXAxis:o}){if(!n||n.type==="none")return fw({dataTemplate:e,data:t,name_data_key:r,value_data_key:a,valueTypedXAxis:o});const l=Hn(t,r,a),u=x.groupBy(l,"0");return e.map(([d])=>{const h=u[d].map(m=>m[1]),g=Rr(h,n);return[d,g]})}function mw({group_by_key:e,data:t,value_data_key:n,name_data_key:r}){const{queryID:a,columnKey:o}=O(e),l=x.groupBy(t[a],o);return Object.entries(l).forEach(([u,c])=>{l[u]=Hn({[a]:c},r,n)}),l}function yw({y_axis:e},{data_key:t,xAxisIndex:n,label_position:r,name:a,group_by_key:o,aggregation_on_value:l,stack:u,color:c,hide_in_legend:d,invisible:f,id:h,...g},m,C,w,_,D){const M={label:{show:!!r,position:r,formatter:D[n??"default"]},name:a,yAxisId:"main-y-axis",xAxisIndex:n,stack:u,color:f?"transparent":c,hide_in_legend:d,labelLayout:{hideOverlap:!0},emphasis:{disabled:!0},...g};if(!o||o===e.data_key)return M.data=gw({dataTemplate:m,data:w,aggregation_on_value:l,name_data_key:e.data_key,value_data_key:t,valueTypedXAxis:C}),M;const P=mw({group_by_key:o,data:w,name_data_key:e.data_key,value_data_key:t});return Object.entries(P).map(([G,L])=>{const z=x.cloneDeep(M);return z.name=G,z.color=void 0,z.data=L,z})}function bw(e,t,n,r,a,o,l){const u=t.map(d=>[d,0]);return e.series.map(d=>yw(e,d,u,n,r,l,a)).flat().concat(pw(e.reference_lines,o,l,r))}function vw(e,t){const n=e.find(u=>u.axisDim==="y"&&u.axisId==="main-y-axis");if(!n)return"";const{name:r,axisType:a,axisValue:o,axisIndex:l}=n;return a==="yAxis.category"?r:Pt(t.y_axis.axisLabel.formatter)(o,l)}function xw(e,t,n){const r=t.reduce((a,{xAxisIndex:o,name:l})=>(a[l]=o,a),{});return{trigger:"axis",axisPointer:{type:"shadow"},formatter:function(a){const o=Array.isArray(a)?a:[a];if(o.length===0)return"";const l=o.map(({seriesName:d,marker:f,value:h})=>{if(Array.isArray(h)&&h.length===2&&(h=h[0]),!d)return h;const g=r[d],m=n[g]??n.default;return`
324
324
  <tr>
325
325
  <td>${f}</td>
326
326
  <th style="text-align: right; padding: 0 1em;">${d}</th>
@@ -335,7 +335,7 @@ Check the top-level render call using <`+V+">.")}return E}}function Su(S,E){{if(
335
335
  ${l.join("")}
336
336
  </tbody>
337
337
  </table>
338
- `}}}function ww(e){return e.x_axes.reduce((n,{label_formatter:r},a)=>(n[a]=function(l){let u=l;if(typeof l=="object"&&(Array.isArray(l.value)&&l.value.length===2?u=l.value[0]:u=l.value),!r)return u;try{return Z(u).format(r)}catch(c){return console.error(c),u}},n),{default:({value:n})=>n})}function Cw(e,t){const n={};return t.map(r=>{const a=ft(r,e);n[r.name]=Ze(r,a)}),n}function Sw(e,t){return e.x_axes.map(({min:n,max:r,...a},o)=>{let l=a.position;return l||(l=o>0?"bottom":"top"),{...a,type:"value",min:n||void 0,max:r||void 0,position:l,axisLabel:{show:!0,margin:2,formatter:t[o]??t.default},axisLine:{show:!0},axisTick:{show:!1},splitLine:{show:!0},nameTextStyle:{fontWeight:"bold"},nameLocation:"center",nameGap:15}})}function _w(e,t){const n=t.every(l=>!Number.isNaN(Number(l))),{overflow:r,...a}=e.y_axis.axisLabel,o=rt(r.on_axis);return[{data:t,name:e.y_axis.name??"",nameLocation:"end",nameTextStyle:{align:"center",fontWeight:"bold"},id:"main-y-axis",axisTick:{show:!0,alignWithLabel:!0},type:n?"value":"category",axisLabel:{...a,...o,formatter:Pt(a.formatter)},z:5}]}function kw(e,t,n){if(!e.y_axis.data_key)return{};const r=Cw(t,n),a=ww(e),o=O(e.y_axis.data_key),l=x.uniq(t[o.queryID].map(f=>f[o.columnKey])),u=l.every(f=>!Number.isNaN(Number(f))),c=bw(e,l,u,t,a,n,r);return{xAxis:Sw(e,a),yAxis:_w(e,l),series:c,tooltip:xw(e,c,a),grid:uw(e),legend:dw(c)}}ie.use([q.DataZoomComponent,he.BarChart,he.LineChart,he.ScatterChart,q.GridComponent,q.LegendComponent,q.TooltipComponent,Pe.CanvasRenderer,q.MarkLineComponent,q.MarkAreaComponent]);function Tw({conf:e,data:t,width:n,height:r,interactionManager:a,variables:o}){const l=Dt(t,e.y_axis.data_key),u=Ke(a.triggerManager,Ur.id),c=y.useCallback(h=>{const g=x.get(l,h.name,{error:"rowData is not found"});u.forEach(m=>{a.runInteraction(m.id,{...h,rowData:g})})},[l,u,a]),d=y.useMemo(()=>({click:c}),[c]),f=y.useMemo(()=>kw(e,t,o),[e,t]);return!n||!r?null:i(Be,{echarts:ie,option:f,style:{width:n,height:r},onEvents:d,notMerge:!0,theme:"merico-light"})}function Dw({context:e,instance:t}){const n=Xe({vizManager:e.vizManager,instance:t}),{value:r}=R(e.instanceData,"config"),{variables:a}=e,o=y.useMemo(()=>x.defaults({},r,bi),[r]),l=e.data,{width:u,height:c}=e.viewport;return i(Tw,{variables:a,width:u,height:c,data:l,conf:o,interactionManager:n})}const Iw=[{label:"solid",value:"solid"},{label:"dashed",value:"dashed"},{label:"dotted",value:"dotted"}],Mw=[{label:"Horizontal",value:"horizontal"},{label:"Vertical",value:"vertical"}];function Aw({control:e,index:t,remove:n,watch:r,variableOptions:a,xAxisOptions:o}){const l=r(`reference_lines.${t}.orientation`);return p(s.Stack,{my:0,p:0,sx:{position:"relative"},children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`reference_lines.${t}.name`,control:e,render:({field:u})=>i(s.TextInput,{label:"Name",placeholder:"Average Reference Line",required:!0,sx:{flex:1},...u})}),i(v.Controller,{name:`reference_lines.${t}.variable_key`,control:e,render:({field:u})=>i(s.Select,{label:"Value",required:!0,data:a,sx:{flex:1},...u})})]}),i(v.Controller,{name:`reference_lines.${t}.template`,control:e,render:({field:u})=>i(s.TextInput,{label:"Content Template",placeholder:"Average: ${avg}",sx:{flex:1},...u})}),p(s.Group,{grow:!0,children:[p(s.Stack,{children:[i(v.Controller,{name:`reference_lines.${t}.orientation`,control:e,render:({field:u})=>i(s.Select,{label:"Orientation",data:Mw,required:!0,sx:{flex:1},...u})}),l==="vertical"&&i(s.Text,{mt:-10,color:"dimmed",size:12,children:"Works only when xAxis values are numbers"})]}),l==="horizontal"&&i(v.Controller,{name:`reference_lines.${t}.xAxisIndex`,control:e,render:({field:u})=>i(s.Select,{label:"X Axis",data:o,disabled:o.length===0,sx:{flex:1},...u})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Style",labelPosition:"center"}),p(s.Group,{grow:!0,children:[i(v.Controller,{name:`reference_lines.${t}.lineStyle.type`,control:e,render:({field:u})=>i(s.Select,{label:"Line Type",data:Iw,sx:{flexGrow:1},...u})}),i(v.Controller,{name:`reference_lines.${t}.lineStyle.width`,control:e,render:({field:u})=>i(s.NumberInput,{label:"Line Width",min:1,max:10,sx:{flexGrow:1},...u})})]}),p(s.Stack,{spacing:4,children:[i(s.Text,{size:"sm",children:"Color"}),i(v.Controller,{name:`reference_lines.${t}.lineStyle.color`,control:e,render:({field:u})=>i(Ve,{...u})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Behavior",labelPosition:"center"}),i(v.Controller,{name:`reference_lines.${t}.show_in_legend`,control:e,render:({field:u})=>i(s.Checkbox,{label:"Show in legend",checked:u.value,onChange:c=>u.onChange(c.currentTarget.checked)})}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Reference Line"})]},t)}function zw({control:e,watch:t,variables:n}){const{fields:r,append:a,remove:o}=v.useFieldArray({control:e,name:"reference_lines"}),l=t("reference_lines"),u=r.map((m,C)=>({...m,...l[C]})),c=()=>{const m=lw();a(m)},d=y.useMemo(()=>n.map(m=>({label:m.name,value:m.name})),[n]),f=t("x_axes"),h=y.useMemo(()=>f.map(({name:m},C)=>({label:m,value:C.toString()})),[f]),g=u.length>0?u[0].id:"0";return p(s.Tabs,{defaultValue:g,styles:{tab:{paddingTop:"4px",paddingBottom:"4px"},panel:{padding:"0px"}},children:[p(s.Tabs.List,{children:[u.map((m,C)=>i(s.Tabs.Tab,{value:m.id,children:m.name},C)),i(s.Tabs.Tab,{onClick:c,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),u.map((m,C)=>i(s.Tabs.Panel,{value:m.id,children:i(Aw,{control:e,index:C,remove:o,watch:t,variableOptions:d,xAxisOptions:h})},C))]})}function Ew(e){const[t,n]=y.useState(e);return y.useEffect(()=>{n(e)},[e]),{tab:t,setTab:n}}const $w=[{label:"No gap between bars",value:"0%"},{label:"Bars overlapping on each other",value:"-100%"}];function Lw({control:e,index:t,seriesItem:n}){const r=!!n.barWidth.trim();return p(B,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${t}.stack`,control:e,render:({field:a})=>i(s.TextInput,{label:"Stack",placeholder:"Stack bars by this ID",sx:{flexGrow:1},...a})}),i(v.Controller,{name:`series.${t}.barGap`,control:e,render:({field:a})=>i(s.Select,{label:"Bar Gap",data:$w,sx:{flexGrow:1},...a})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${t}.barMinWidth`,control:e,render:({field:a})=>i(s.TextInput,{label:"Bar Width(Min)",disabled:r,sx:{flexGrow:1},...a})}),i(v.Controller,{name:`series.${t}.barWidth`,control:e,render:({field:a})=>i(s.TextInput,{label:"Bar Width",sx:{flexGrow:1},...a})}),i(v.Controller,{name:`series.${t}.barMaxWidth`,control:e,render:({field:a})=>i(s.TextInput,{label:"Bar Width(Max)",disabled:r,sx:{flexGrow:1},...a})})]})]})}const Ow=[{label:"off",value:""},{label:"top",value:"top"},{label:"left",value:"left"},{label:"right",value:"right"},{label:"bottom",value:"bottom"},{label:"inside",value:"inside"},{label:"insideLeft",value:"insideLeft"},{label:"insideRight",value:"insideRight"},{label:"insideTop",value:"insideTop"},{label:"insideBottom",value:"insideBottom"},{label:"insideTopLeft",value:"insideTopLeft"},{label:"insideBottomLeft",value:"insideBottomLeft"},{label:"insideTopRight",value:"insideTopRight"},{label:"insideBottomRight",value:"insideBottomRight"}];function Pw({control:e,index:t,remove:n,seriesItem:r,xAxisOptions:a}){return p(s.Stack,{my:0,p:0,sx:{position:"relative"},children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${t}.name`,control:e,render:({field:o})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...o})}),i(v.Controller,{name:`series.${t}.xAxisIndex`,control:e,render:({field:o})=>i(s.Select,{label:"X Axis",data:a,disabled:a.length===0,sx:{flex:1},...o})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${t}.data_key`,control:e,render:({field:o})=>i(W,{label:"Value Field",required:!0,sx:{flex:1},...o})}),i(v.Controller,{name:`series.${t}.aggregation_on_value`,control:e,render:({field:o})=>i(Gn,{label:"Aggregation on Value",value:o.value??Nt,onChange:o.onChange,pt:0})})]}),i(s.Group,{grow:!0,children:i(v.Controller,{name:`series.${t}.group_by_key`,control:e,render:({field:o})=>i(W,{label:"Split into multiple series by this key...",clearable:!0,sx:{flex:1},...o})})}),i(Lw,{index:t,control:e,seriesItem:r}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Style",labelPosition:"center"}),i(v.Controller,{name:`series.${t}.label_position`,control:e,render:({field:o})=>i(s.Select,{label:"Label Position",data:Ow,...o})}),p(s.Stack,{spacing:4,children:[i(s.Text,{size:"sm",children:"Color"}),i(v.Controller,{name:`series.${t}.color`,control:e,render:({field:o})=>i(Ve,{...o})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Behavior",labelPosition:"center"}),i(v.Controller,{name:`series.${t}.hide_in_legend`,control:e,render:({field:o})=>i(s.Checkbox,{label:"Hide in legend",checked:o.value,onChange:l=>o.onChange(l.currentTarget.checked)})}),i(v.Controller,{name:`series.${t}.invisible`,control:e,render:({field:o})=>i(s.Checkbox,{label:"Invisible",checked:o.value,onChange:l=>o.onChange(l.currentTarget.checked)})}),i(s.Divider,{mb:-10,mt:10,variant:"dashed"}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Series"})]},t)}function Bw({control:e,watch:t}){var g;const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"series"}),o=t("series"),l=n.map((m,C)=>({...m,...o[C]})),u=()=>{const m=ow();r(m)},c=t("x_axes"),d=y.useMemo(()=>c.map(({name:m},C)=>({label:m,value:C.toString()})),[c]),{tab:f,setTab:h}=Ew((g=l[0])==null?void 0:g.id);return p(s.Tabs,{value:f,onTabChange:h,styles:{tab:{paddingTop:"4px",paddingBottom:"4px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map(m=>i(s.Tabs.Tab,{value:m.id,children:m.name},m.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((m,C)=>i(s.Tabs.Panel,{value:m.id,children:i(Pw,{control:e,index:C,remove:a,seriesItem:m,xAxisOptions:d},m.id)},m.id))]})}const Vw=[{label:"Top",value:"top"},{label:"Bottom",value:"bottom"}];function Nw({control:e,index:t,remove:n}){return p(s.Stack,{my:0,p:"0",sx:{position:"relative"},children:[i(s.Divider,{mb:-15,mt:15,variant:"dashed",label:"Name",labelPosition:"center"}),i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:`x_axes.${t}.name`,control:e,render:({field:r})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...r})})}),i(s.Divider,{mb:-15,variant:"dashed",label:"Layout",labelPosition:"center"}),i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:`x_axes.${t}.position`,control:e,render:({field:r})=>i(s.Select,{label:"Position",required:!0,data:Vw,sx:{flex:1},...r})})}),p(s.Stack,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Label Format",labelPosition:"center"}),i(v.Controller,{name:`x_axes.${t}.label_formatter`,control:e,render:({field:r})=>i(We,{...r})})]}),p(s.Stack,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Value Range",labelPosition:"center"}),p(s.Group,{grow:!0,children:[i(v.Controller,{name:`x_axes.${t}.min`,control:e,render:({field:r})=>i(s.TextInput,{label:"Min",...r})}),i(v.Controller,{name:`x_axes.${t}.max`,control:e,render:({field:r})=>i(s.TextInput,{label:"Max",...r})})]})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Behavior",labelPosition:"center"}),i(v.Controller,{name:`x_axes.${t}.show`,control:e,render:({field:r})=>i(s.Checkbox,{label:"Visible",checked:r.value,onChange:a=>r.onChange(a.currentTarget.checked)})}),i(s.Button,{mt:20,leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),disabled:t===0,children:"Delete this X Axis"})]})}function qw({control:e,watch:t}){const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"x_axes"}),o=t("x_axes"),l=n.map((d,f)=>({...d,...o[f]})),u=()=>{const d=sw();r(d)},c=l.length>0?l[0].id:"0";return p(s.Tabs,{defaultValue:c,styles:{tab:{paddingTop:"4px",paddingBottom:"4px"},panel:{padding:"0px"}},children:[p(s.Tabs.List,{children:[l.map(d=>i(s.Tabs.Tab,{value:d.id,children:d.name},d.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((d,f)=>i(s.Tabs.Panel,{value:d.id,children:i(Nw,{control:e,index:f,remove:a})},d.id))]})}function Fw({control:e,watch:t}){return t(["y_axis"]),p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"y_axis.data_key",control:e,render:({field:n})=>i(W,{label:"Y Axis Data Field",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"y_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"X Axis Name",sx:{flex:1},...n})})]}),i(s.Divider,{mb:-15,label:"Tick Label",labelPosition:"center"}),i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:"y_axis.axisLabel.formatter",control:e,render:({field:n})=>i(Rn,{...n})})}),i(v.Controller,{name:"y_axis.axisLabel.overflow",control:e,render:({field:n})=>i(at,{...n})})]})}function Gw({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),{variables:r}=e,a=y.useMemo(()=>x.defaultsDeep({},t,bi),[t]),{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});y.useEffect(()=>{d(a)},[a]),u([]);const f=c(),h=y.useMemo(()=>!x.isEqual(f,a),[f,a]);return i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:l(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Horizontal Bar Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"Series",orientation:"vertical",styles:{tab:{paddingLeft:"6px",paddingRight:"6px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"X Axes",children:"X Axes"}),i(s.Tabs.Tab,{value:"Y Axis",children:"Y Axis"}),i(s.Tabs.Tab,{value:"Series",children:"Series"}),i(s.Tabs.Tab,{value:"Reference Lines",children:"Reference Lines"})]}),i(s.Tabs.Panel,{value:"X Axes",children:i(qw,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Y Axis",children:i(Fw,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Series",children:i(Bw,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Reference Lines",children:i(zw,{variables:r,control:o,watch:u})})]})]})})}function Ww(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=c=>c&&`${n}.${c}`,{x_axis:a,y_axis:o,series:l,...u}=e;return{...u,x_axis:{...a,data_key:r(a.data_key)},y_axis:{...o,data_key:r(o.data_key)},series:l.map(c=>({...c,data_key:r(c.data_key),group_by_key:r(c.group_by_key)}))}}catch(n){throw console.error("[Migration failed]",n),n}}class jw extends ye{constructor(){super(...arguments);N(this,"VERSION",2)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,(n,r)=>{const{config:a}=n;return{...n,version:2,config:Ww(a,r)}})}}const Rw={displayName:"Horizontal Bar Chart",displayGroup:"ECharts-based charts",migrator:new jw,name:"horizontalBarChart",viewRender:Dw,configRender:Gw,createConfig:()=>({version:2,config:bi})},vi={x_axis:{name:"",data_key:"",axisLabel:{rotate:0,formatter:{...Xn}}},deviation:{name:"",data_keys:{estimated_value:"",actual_value:""}},metrics:[]};function Yw(){return[{top:20,left:30,right:60,height:40,containLabel:!0,backgroundColor:"rgba(235, 235, 255, 0.5)",borderWidth:0,show:!0},{top:70,left:30,right:60,height:100,containLabel:!0,backgroundColor:"rgba(235, 235, 255, 0.5)",borderWidth:0,show:!0},{top:180,left:30,right:60,bottom:130,containLabel:!0,backgroundColor:"rgba(235, 235, 255, 0.5)",borderWidth:0,show:!0},{left:30,right:60,bottom:20,height:100,containLabel:!1,backgroundColor:"rgba(235, 235, 255, 0.5)",borderWidth:0,show:!0}]}const Oo=({value:e})=>{try{return Z(e[2]).format({output:"percent",mantissa:0})}catch(t){return console.error(t),e}};function Qw(e,t,n){return{type:"heatmap",name:"准确估算比例",xAxisIndex:0,yAxisIndex:0,data:t.map(a=>{const o=n[a].length,c=(x.countBy(n[a],d=>d.level.diff===0).true??0)/o;return[a,"_y",c]}),label:{show:!0,formatter:Oo},labelLayout:{hideOverlap:!0},visualMapIndex:0,tooltip:{trigger:"item",formatter:({color:a,value:o})=>`
338
+ `}}}function ww(e){return e.x_axes.reduce((n,{label_formatter:r},a)=>(n[a]=function(l){let u=l;if(typeof l=="object"&&(Array.isArray(l.value)&&l.value.length===2?u=l.value[0]:u=l.value),!r)return u;try{return Z(u).format(r)}catch(c){return console.error(c),u}},n),{default:({value:n})=>n})}function Cw(e,t){const n={};return t.map(r=>{const a=ft(r,e);n[r.name]=Ze(r,a)}),n}function Sw(e,t){return e.x_axes.map(({min:n,max:r,...a},o)=>{let l=a.position;return l||(l=o>0?"bottom":"top"),{...a,type:"value",min:n||void 0,max:r||void 0,position:l,axisLabel:{show:!0,margin:2,formatter:t[o]??t.default},axisLine:{show:!0},axisTick:{show:!1},splitLine:{show:!0},nameTextStyle:{fontWeight:"bold"},nameLocation:"center",nameGap:15}})}function _w(e,t){const n=t.every(l=>!Number.isNaN(Number(l))),{overflow:r,...a}=e.y_axis.axisLabel,o=rt(r.on_axis);return[{data:t,name:e.y_axis.name??"",nameLocation:"end",nameTextStyle:{align:"center",fontWeight:"bold"},id:"main-y-axis",axisTick:{show:!0,alignWithLabel:!0},type:n?"value":"category",axisLabel:{...a,...o,formatter:Pt(a.formatter)},z:5}]}function kw(e,t,n){if(!e.y_axis.data_key)return{};const r=Cw(t,n),a=ww(e),o=O(e.y_axis.data_key),l=x.uniq(t[o.queryID].map(f=>f[o.columnKey])),u=l.every(f=>!Number.isNaN(Number(f))),c=bw(e,l,u,t,a,n,r);return{xAxis:Sw(e,a),yAxis:_w(e,l),series:c,tooltip:xw(e,c,a),grid:uw(e),legend:dw(c)}}ie.use([q.DataZoomComponent,he.BarChart,he.LineChart,he.ScatterChart,q.GridComponent,q.LegendComponent,q.TooltipComponent,Pe.CanvasRenderer,q.MarkLineComponent,q.MarkAreaComponent]);function Tw({conf:e,data:t,width:n,height:r,interactionManager:a,variables:o}){const l=Dt(t,e.y_axis.data_key),u=Ke(a.triggerManager,Ur.id),c=b.useCallback(h=>{const g=x.get(l,h.name,{error:"rowData is not found"});u.forEach(m=>{a.runInteraction(m.id,{...h,rowData:g})})},[l,u,a]),d=b.useMemo(()=>({click:c}),[c]),f=b.useMemo(()=>kw(e,t,o),[e,t]);return!n||!r?null:i(Be,{echarts:ie,option:f,style:{width:n,height:r},onEvents:d,notMerge:!0,theme:"merico-light"})}function Dw({context:e,instance:t}){const n=Xe({vizManager:e.vizManager,instance:t}),{value:r}=R(e.instanceData,"config"),{variables:a}=e,o=b.useMemo(()=>x.defaults({},r,bi),[r]),l=e.data,{width:u,height:c}=e.viewport;return i(Tw,{variables:a,width:u,height:c,data:l,conf:o,interactionManager:n})}const Iw=[{label:"solid",value:"solid"},{label:"dashed",value:"dashed"},{label:"dotted",value:"dotted"}],Mw=[{label:"Horizontal",value:"horizontal"},{label:"Vertical",value:"vertical"}];function Aw({control:e,index:t,remove:n,watch:r,variableOptions:a,xAxisOptions:o}){const l=r(`reference_lines.${t}.orientation`);return p(s.Stack,{my:0,p:0,sx:{position:"relative"},children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`reference_lines.${t}.name`,control:e,render:({field:u})=>i(s.TextInput,{label:"Name",placeholder:"Average Reference Line",required:!0,sx:{flex:1},...u})}),i(v.Controller,{name:`reference_lines.${t}.variable_key`,control:e,render:({field:u})=>i(s.Select,{label:"Value",required:!0,data:a,sx:{flex:1},...u})})]}),i(v.Controller,{name:`reference_lines.${t}.template`,control:e,render:({field:u})=>i(s.TextInput,{label:"Content Template",placeholder:"Average: ${avg}",sx:{flex:1},...u})}),p(s.Group,{grow:!0,children:[p(s.Stack,{children:[i(v.Controller,{name:`reference_lines.${t}.orientation`,control:e,render:({field:u})=>i(s.Select,{label:"Orientation",data:Mw,required:!0,sx:{flex:1},...u})}),l==="vertical"&&i(s.Text,{mt:-10,color:"dimmed",size:12,children:"Works only when xAxis values are numbers"})]}),l==="horizontal"&&i(v.Controller,{name:`reference_lines.${t}.xAxisIndex`,control:e,render:({field:u})=>i(s.Select,{label:"X Axis",data:o,disabled:o.length===0,sx:{flex:1},...u})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Style",labelPosition:"center"}),p(s.Group,{grow:!0,children:[i(v.Controller,{name:`reference_lines.${t}.lineStyle.type`,control:e,render:({field:u})=>i(s.Select,{label:"Line Type",data:Iw,sx:{flexGrow:1},...u})}),i(v.Controller,{name:`reference_lines.${t}.lineStyle.width`,control:e,render:({field:u})=>i(s.NumberInput,{label:"Line Width",min:1,max:10,sx:{flexGrow:1},...u})})]}),p(s.Stack,{spacing:4,children:[i(s.Text,{size:"sm",children:"Color"}),i(v.Controller,{name:`reference_lines.${t}.lineStyle.color`,control:e,render:({field:u})=>i(Ve,{...u})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Behavior",labelPosition:"center"}),i(v.Controller,{name:`reference_lines.${t}.show_in_legend`,control:e,render:({field:u})=>i(s.Checkbox,{label:"Show in legend",checked:u.value,onChange:c=>u.onChange(c.currentTarget.checked)})}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Reference Line"})]},t)}function zw({control:e,watch:t,variables:n}){const{fields:r,append:a,remove:o}=v.useFieldArray({control:e,name:"reference_lines"}),l=t("reference_lines"),u=r.map((m,C)=>({...m,...l[C]})),c=()=>{const m=lw();a(m)},d=b.useMemo(()=>n.map(m=>({label:m.name,value:m.name})),[n]),f=t("x_axes"),h=b.useMemo(()=>f.map(({name:m},C)=>({label:m,value:C.toString()})),[f]),g=u.length>0?u[0].id:"0";return p(s.Tabs,{defaultValue:g,styles:{tab:{paddingTop:"4px",paddingBottom:"4px"},panel:{padding:"0px"}},children:[p(s.Tabs.List,{children:[u.map((m,C)=>i(s.Tabs.Tab,{value:m.id,children:m.name},C)),i(s.Tabs.Tab,{onClick:c,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),u.map((m,C)=>i(s.Tabs.Panel,{value:m.id,children:i(Aw,{control:e,index:C,remove:o,watch:t,variableOptions:d,xAxisOptions:h})},C))]})}function Ew(e){const[t,n]=b.useState(e);return b.useEffect(()=>{n(e)},[e]),{tab:t,setTab:n}}const $w=[{label:"No gap between bars",value:"0%"},{label:"Bars overlapping on each other",value:"-100%"}];function Lw({control:e,index:t,seriesItem:n}){const r=!!n.barWidth.trim();return p(B,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${t}.stack`,control:e,render:({field:a})=>i(s.TextInput,{label:"Stack",placeholder:"Stack bars by this ID",sx:{flexGrow:1},...a})}),i(v.Controller,{name:`series.${t}.barGap`,control:e,render:({field:a})=>i(s.Select,{label:"Bar Gap",data:$w,sx:{flexGrow:1},...a})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${t}.barMinWidth`,control:e,render:({field:a})=>i(s.TextInput,{label:"Bar Width(Min)",disabled:r,sx:{flexGrow:1},...a})}),i(v.Controller,{name:`series.${t}.barWidth`,control:e,render:({field:a})=>i(s.TextInput,{label:"Bar Width",sx:{flexGrow:1},...a})}),i(v.Controller,{name:`series.${t}.barMaxWidth`,control:e,render:({field:a})=>i(s.TextInput,{label:"Bar Width(Max)",disabled:r,sx:{flexGrow:1},...a})})]})]})}const Ow=[{label:"off",value:""},{label:"top",value:"top"},{label:"left",value:"left"},{label:"right",value:"right"},{label:"bottom",value:"bottom"},{label:"inside",value:"inside"},{label:"insideLeft",value:"insideLeft"},{label:"insideRight",value:"insideRight"},{label:"insideTop",value:"insideTop"},{label:"insideBottom",value:"insideBottom"},{label:"insideTopLeft",value:"insideTopLeft"},{label:"insideBottomLeft",value:"insideBottomLeft"},{label:"insideTopRight",value:"insideTopRight"},{label:"insideBottomRight",value:"insideBottomRight"}];function Pw({control:e,index:t,remove:n,seriesItem:r,xAxisOptions:a}){return p(s.Stack,{my:0,p:0,sx:{position:"relative"},children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${t}.name`,control:e,render:({field:o})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...o})}),i(v.Controller,{name:`series.${t}.xAxisIndex`,control:e,render:({field:o})=>i(s.Select,{label:"X Axis",data:a,disabled:a.length===0,sx:{flex:1},...o})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`series.${t}.data_key`,control:e,render:({field:o})=>i(W,{label:"Value Field",required:!0,sx:{flex:1},...o})}),i(v.Controller,{name:`series.${t}.aggregation_on_value`,control:e,render:({field:o})=>i(Gn,{label:"Aggregation on Value",value:o.value??Nt,onChange:o.onChange,pt:0})})]}),i(s.Group,{grow:!0,children:i(v.Controller,{name:`series.${t}.group_by_key`,control:e,render:({field:o})=>i(W,{label:"Split into multiple series by this key...",clearable:!0,sx:{flex:1},...o})})}),i(Lw,{index:t,control:e,seriesItem:r}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Style",labelPosition:"center"}),i(v.Controller,{name:`series.${t}.label_position`,control:e,render:({field:o})=>i(s.Select,{label:"Label Position",data:Ow,...o})}),p(s.Stack,{spacing:4,children:[i(s.Text,{size:"sm",children:"Color"}),i(v.Controller,{name:`series.${t}.color`,control:e,render:({field:o})=>i(Ve,{...o})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Behavior",labelPosition:"center"}),i(v.Controller,{name:`series.${t}.hide_in_legend`,control:e,render:({field:o})=>i(s.Checkbox,{label:"Hide in legend",checked:o.value,onChange:l=>o.onChange(l.currentTarget.checked)})}),i(v.Controller,{name:`series.${t}.invisible`,control:e,render:({field:o})=>i(s.Checkbox,{label:"Invisible",checked:o.value,onChange:l=>o.onChange(l.currentTarget.checked)})}),i(s.Divider,{mb:-10,mt:10,variant:"dashed"}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Series"})]},t)}function Bw({control:e,watch:t}){var g;const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"series"}),o=t("series"),l=n.map((m,C)=>({...m,...o[C]})),u=()=>{const m=ow();r(m)},c=t("x_axes"),d=b.useMemo(()=>c.map(({name:m},C)=>({label:m,value:C.toString()})),[c]),{tab:f,setTab:h}=Ew((g=l[0])==null?void 0:g.id);return p(s.Tabs,{value:f,onTabChange:h,styles:{tab:{paddingTop:"4px",paddingBottom:"4px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map(m=>i(s.Tabs.Tab,{value:m.id,children:m.name},m.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((m,C)=>i(s.Tabs.Panel,{value:m.id,children:i(Pw,{control:e,index:C,remove:a,seriesItem:m,xAxisOptions:d},m.id)},m.id))]})}const Vw=[{label:"Top",value:"top"},{label:"Bottom",value:"bottom"}];function Nw({control:e,index:t,remove:n}){return p(s.Stack,{my:0,p:"0",sx:{position:"relative"},children:[i(s.Divider,{mb:-15,mt:15,variant:"dashed",label:"Name",labelPosition:"center"}),i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:`x_axes.${t}.name`,control:e,render:({field:r})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...r})})}),i(s.Divider,{mb:-15,variant:"dashed",label:"Layout",labelPosition:"center"}),i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:`x_axes.${t}.position`,control:e,render:({field:r})=>i(s.Select,{label:"Position",required:!0,data:Vw,sx:{flex:1},...r})})}),p(s.Stack,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Label Format",labelPosition:"center"}),i(v.Controller,{name:`x_axes.${t}.label_formatter`,control:e,render:({field:r})=>i(je,{...r})})]}),p(s.Stack,{children:[i(s.Divider,{mb:-15,variant:"dashed",label:"Value Range",labelPosition:"center"}),p(s.Group,{grow:!0,children:[i(v.Controller,{name:`x_axes.${t}.min`,control:e,render:({field:r})=>i(s.TextInput,{label:"Min",...r})}),i(v.Controller,{name:`x_axes.${t}.max`,control:e,render:({field:r})=>i(s.TextInput,{label:"Max",...r})})]})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed",label:"Behavior",labelPosition:"center"}),i(v.Controller,{name:`x_axes.${t}.show`,control:e,render:({field:r})=>i(s.Checkbox,{label:"Visible",checked:r.value,onChange:a=>r.onChange(a.currentTarget.checked)})}),i(s.Button,{mt:20,leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),disabled:t===0,children:"Delete this X Axis"})]})}function qw({control:e,watch:t}){const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"x_axes"}),o=t("x_axes"),l=n.map((d,f)=>({...d,...o[f]})),u=()=>{const d=sw();r(d)},c=l.length>0?l[0].id:"0";return p(s.Tabs,{defaultValue:c,styles:{tab:{paddingTop:"4px",paddingBottom:"4px"},panel:{padding:"0px"}},children:[p(s.Tabs.List,{children:[l.map(d=>i(s.Tabs.Tab,{value:d.id,children:d.name},d.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((d,f)=>i(s.Tabs.Panel,{value:d.id,children:i(Nw,{control:e,index:f,remove:a})},d.id))]})}function Fw({control:e,watch:t}){return t(["y_axis"]),p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"y_axis.data_key",control:e,render:({field:n})=>i(W,{label:"Y Axis Data Field",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"y_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"X Axis Name",sx:{flex:1},...n})})]}),i(s.Divider,{mb:-15,label:"Tick Label",labelPosition:"center"}),i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:"y_axis.axisLabel.formatter",control:e,render:({field:n})=>i(Rn,{...n})})}),i(v.Controller,{name:"y_axis.axisLabel.overflow",control:e,render:({field:n})=>i(at,{...n})})]})}function Gw({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),{variables:r}=e,a=b.useMemo(()=>x.defaultsDeep({},t,bi),[t]),{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});b.useEffect(()=>{d(a)},[a]),u([]);const f=c(),h=b.useMemo(()=>!x.isEqual(f,a),[f,a]);return i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:l(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Horizontal Bar Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"Series",orientation:"vertical",styles:{tab:{paddingLeft:"6px",paddingRight:"6px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"X Axes",children:"X Axes"}),i(s.Tabs.Tab,{value:"Y Axis",children:"Y Axis"}),i(s.Tabs.Tab,{value:"Series",children:"Series"}),i(s.Tabs.Tab,{value:"Reference Lines",children:"Reference Lines"})]}),i(s.Tabs.Panel,{value:"X Axes",children:i(qw,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Y Axis",children:i(Fw,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Series",children:i(Bw,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Reference Lines",children:i(zw,{variables:r,control:o,watch:u})})]})]})})}function Ww(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=c=>c&&`${n}.${c}`,{x_axis:a,y_axis:o,series:l,...u}=e;return{...u,x_axis:{...a,data_key:r(a.data_key)},y_axis:{...o,data_key:r(o.data_key)},series:l.map(c=>({...c,data_key:r(c.data_key),group_by_key:r(c.group_by_key)}))}}catch(n){throw console.error("[Migration failed]",n),n}}class jw extends ye{constructor(){super(...arguments);N(this,"VERSION",2)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,(n,r)=>{const{config:a}=n;return{...n,version:2,config:Ww(a,r)}})}}const Rw={displayName:"Horizontal Bar Chart",displayGroup:"ECharts-based charts",migrator:new jw,name:"horizontalBarChart",viewRender:Dw,configRender:Gw,createConfig:()=>({version:2,config:bi})},vi={x_axis:{name:"",data_key:"",axisLabel:{rotate:0,formatter:{...Xn}}},deviation:{name:"",data_keys:{estimated_value:"",actual_value:""}},metrics:[]};function Yw(){return[{top:20,left:30,right:60,height:40,containLabel:!0,backgroundColor:"rgba(235, 235, 255, 0.5)",borderWidth:0,show:!0},{top:70,left:30,right:60,height:100,containLabel:!0,backgroundColor:"rgba(235, 235, 255, 0.5)",borderWidth:0,show:!0},{top:180,left:30,right:60,bottom:130,containLabel:!0,backgroundColor:"rgba(235, 235, 255, 0.5)",borderWidth:0,show:!0},{left:30,right:60,bottom:20,height:100,containLabel:!1,backgroundColor:"rgba(235, 235, 255, 0.5)",borderWidth:0,show:!0}]}const Oo=({value:e})=>{try{return Z(e[2]).format({output:"percent",mantissa:0})}catch(t){return console.error(t),e}};function Qw(e,t,n){return{type:"heatmap",name:"准确估算比例",xAxisIndex:0,yAxisIndex:0,data:t.map(a=>{const o=n[a].length,c=(x.countBy(n[a],d=>d.level.diff===0).true??0)/o;return[a,"_y",c]}),label:{show:!0,formatter:Oo},labelLayout:{hideOverlap:!0},visualMapIndex:0,tooltip:{trigger:"item",formatter:({color:a,value:o})=>`
339
339
  <table style="width: auto">
340
340
  <thead>
341
341
  <tr colspan="2">
@@ -414,8 +414,8 @@ Check the top-level render call using <`+V+">.")}return E}}function Su(S,E){{if(
414
414
  </tr>
415
415
  </tbody>
416
416
  </table>
417
- `}},show_in_legend:!0}))}function Zw(e,t,n,r){const a=O(t.data_key),o=t.name,l=n.map(u=>{const c=x.sumBy(r[u],a.columnKey);return[u,c]});return{type:"line",name:o,xAxisIndex:3,yAxisIndex:3,color:"#b41529",data:l,show_in_legend:!1}}function Hw(e,t,n,r){const l={barMinWidth:5,barMaxWidth:20};return[Qw(e,n,r),Kw(e,n,r,l),...Jw(e,n,r,l),Zw(e,t,n,r)]}function eC(e,t){const{axisLabel:n}=e.x_axis;return[{data:t,id:"准确估算比例",gridIndex:0,axisTick:{show:!1},axisLabel:{show:!1},axisLine:{show:!1},type:"category"},{data:t,id:"平均偏差",gridIndex:1,axisTick:{show:!1},axisLabel:{show:!1},axisLine:{show:!0,lineStyle:{color:"#FFFFFF",width:2}},type:"category"},{data:t,id:"数量占比",gridIndex:2,axisTick:{show:!1},axisLabel:{show:!1},axisLine:{show:!1},type:"category"},{data:t,id:"代码当量",gridIndex:3,axisTick:{show:!1},type:"category",axisLabel:{...n,formatter:ho(n.formatter)},axisLine:{show:!1}}]}function tC(e){return[{type:"category",name:"准确估算比例",nameRotate:0,nameGap:5,nameLocation:"end",nameTextStyle:{align:"left"},gridIndex:0,axisLabel:{show:!1},axisTick:{show:!1},axisLine:{show:!1},splitLine:{show:!1}},{type:"value",name:"平均偏差",nameGap:5,nameRotate:90,nameLocation:"middle",gridIndex:1,boundaryGap:[1,1],axisLabel:{show:!1},axisTick:{show:!1},axisLine:{show:!1},splitLine:{show:!1}},{type:"value",name:"数量占比",nameGap:5,nameRotate:90,nameLocation:"middle",gridIndex:2,axisLabel:{show:!1},axisTick:{show:!1},axisLine:{show:!1},splitLine:{show:!1},min:0,max:1},{type:"value",gridIndex:3,position:"right",splitNumber:3,axisLabel:{show:!0,verticalAlign:"top",showMinLabel:!1,lineHeight:14},axisTick:{show:!1},axisLine:{show:!1},splitLine:{show:!1}},{type:"value",name:e.name,nameGap:5,nameRotate:90,nameLocation:"middle",gridIndex:3,position:"left",axisLabel:{show:!1},axisTick:{show:!1},axisLine:{show:!1},splitLine:{show:!1}}]}function xi(e){return e==1||e==2?1:xi(e-2)+xi(e-1)}const nC=Array.from(new Array(20),(e,t)=>xi(t+1));function Bo(e){return e<=1?e:nC.findIndex(t=>e<=t)-1}function rC(e,t){const{x_axis:n,deviation:r}=e,a=O(n.data_key),o=O(r.data_keys.estimated_value),l=O(r.data_keys.actual_value);return t[a.queryID].map(u=>{const c=Bo(u[o.columnKey]),d=Bo(u[l.columnKey]),f=c-d;return{...u,level:{estimated:c,actual:d,diff:f}}})}function iC(e){return e==="rgba(255, 255, 255, 1)"?{borderColor:"rgba(0,0,0,.1)",borderWidth:1}:{}}function aC(e){return{show:!0,orient:"vertical",top:"middle",right:0,data:e.filter(n=>n.show_in_legend).reverse().map(n=>({name:`${n.name}`,color:n.color,itemStyle:iC(n.color)})),tooltip:{show:!0,formatter:"档位偏差:{a}"}}}const sC={tooltip:{trigger:"axis"}};function oC(e,t){const{deviation:n,metrics:r}=e,a=r.find(l=>l.data_key===t);if(a)return a;const o=n.data_keys.actual_value;return{id:o,name:n.name,data_key:o}}function lC(e,t,n){const r=rC(e,n),a=O(e.x_axis.data_key),o=x.uniqBy(n[a.queryID],a.columnKey).map(f=>f[a.columnKey]),l=x.groupBy(r,a.columnKey),u=oC(e,t),c=Hw(e,u,o,l),d={xAxis:eC(e,o),yAxis:tC(u),series:c,grid:Yw(),visualMap:[{min:0,max:1,calculable:!0,show:!1,seriesIndex:0,color:["#F0F0F0","#418AAF"]}],legend:aC(c)};return x.defaultsDeep({},d,sC)}const uC={input:{border:"none !important",paddingLeft:0,lineHeight:"1.55 !important"}},cC=({conf:e,metricKey:t,setMetricKey:n})=>{const{deviation:r,metrics:a}=e,o=y.useMemo(()=>{const l=a.map(u=>({label:u.name,value:u.data_key}));return l.push({label:r.name?r.name:r.data_keys.actual_value,value:r.data_keys.actual_value}),l},[r,a]);return p(s.Group,{spacing:1,children:[i(s.Text,{size:12,color:"dimmed",sx:{cursor:"default",userSelect:"none"},children:"基线指标"}),i(s.NativeSelect,{size:"xs",data:o,value:t,onChange:l=>n(l.currentTarget.value),styles:uC})]})},dC={"tbody th, tbody td":{padding:"7px 10px"},"tbody tr:not(:first-of-type) th":{borderTop:"1px solid #dee2e6"}};function pC(){return p(s.HoverCard,{width:400,shadow:"md",children:[i(s.HoverCard.Target,{children:i(s.Button,{size:"xs",variant:"subtle",compact:!0,leftIcon:i($.IconInfoCircle,{size:14}),children:"指标说明"})}),i(s.HoverCard.Dropdown,{children:i(s.Table,{fontSize:14,sx:dC,children:p("tbody",{children:[p("tr",{children:[i("th",{children:"估算偏差"}),i("td",{children:"使用斐波那契数列(1,2,3,5,8,13)估算故事点,每个数位为一个档位,计算issue实际故事点与估算故事点的档位偏差,即为估算偏差。如估算故事点为5,实际故事点为8,则估算偏差为-1。"})]}),p("tr",{children:[i("th",{children:"准确估算比例"}),i("td",{children:"偏差在 ± 1 档位内的 issue 均为准确估算,以此计算准确估算的比例。"})]})]})})})]})}function hC(e){return p(s.Group,{position:"apart",children:[i(pC,{}),i(cC,{...e})]})}ie.use([he.BarChart,he.LineChart,he.HeatmapChart,q.GridComponent,q.LegendComponent,q.TooltipComponent,Pe.CanvasRenderer,q.VisualMapComponent]);function fC({conf:e,data:t,width:n,height:r,metricKey:a}){const o=y.useMemo(()=>lC(e,a,t),[e,t,a]);return i(Be,{echarts:ie,option:o,style:{width:n,height:r},notMerge:!0,theme:"merico-light"})}function gC({context:e}){const{value:t}=R(e.instanceData,"config"),n=y.useMemo(()=>x.defaults({},t,vi),[t]),r=e.data,{width:a,height:o}=e.viewport,{x_axis:l,deviation:u}=n,{estimated_value:c,actual_value:d}=u.data_keys,[f,h]=y.useState(d);if(y.useEffect(()=>{h(C=>C||d)},[d]),!l.data_key||!c||!d||!a||!o)return null;const g=Math.max(a,300),m=Math.max(o,370);return p(s.Box,{sx:{overflow:"hidden",height:m,width:g},children:[i(hC,{conf:n,metricKey:f,setMetricKey:h}),i(fC,{width:g,height:m-30,data:r,conf:n,metricKey:f})]})}function mC({control:e,watch:t}){return t(["deviation"]),p(s.Stack,{children:[i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:"deviation.name",control:e,render:({field:n})=>i(s.TextInput,{label:"指标名称",sx:{flex:1},...n})})}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"deviation.data_keys.estimated_value",control:e,render:({field:n})=>i(W,{label:"估算值字段",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"deviation.data_keys.actual_value",control:e,render:({field:n})=>i(W,{label:"实际值字段",required:!0,sx:{flex:1},...n})})]})]})}const yC=({control:e,index:t,remove:n})=>p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`metrics.${t}.name`,control:e,render:({field:r})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:`metrics.${t}.data_key`,control:e,render:({field:r})=>i(W,{label:"Value Field",required:!0,sx:{flex:1},...r})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed"}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Metric"})]}),bC=({control:e,watch:t})=>{const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"metrics"}),o=t("metrics"),l=n.map((h,g)=>({...h,...o[g]})),u=()=>r({id:Date.now().toString(),data_key:"",name:""}),c=t("metrics.0.id"),[d,f]=y.useState(()=>c??null);return y.useEffect(()=>{c&&f(h=>h!==null?h:c)},[c]),p(B,{children:[p(s.Group,{spacing:2,sx:{cursor:"default",userSelect:"none"},children:[i(T.InfoCircle,{size:14,color:"#888"}),i(s.Text,{size:14,color:"#888",children:"设置可以展示在基线图的指标,例如代码当量"})]}),i(s.Divider,{variant:"dashed",my:10}),p(s.Tabs,{value:d,onTabChange:h=>f(h),styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map((h,g)=>i(s.Tabs.Tab,{value:h.id,children:h.name?h.name:g},h.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((h,g)=>i(s.Tabs.Panel,{value:h.id,children:i(yC,{control:e,index:g,remove:a},h.id)},h.id))]})]})};function vC({control:e,watch:t}){return t(["x_axis"]),p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.data_key",control:e,render:({field:n})=>i(W,{label:"数据字段",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"x_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"X轴名称",sx:{flex:1},...n})})]}),i(s.Divider,{mb:-15,label:"点位文案",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.axisLabel.rotate",control:e,render:({field:n})=>i(s.NumberInput,{label:"旋转",hideControls:!0,min:-90,max:90,rightSection:i(s.Text,{color:"dimmed",children:"度"}),sx:{width:"48%"},styles:{rightSection:{width:"4em",justifyContent:"flex-end",paddingRight:"6px"}},...n})}),i(v.Controller,{name:"x_axis.axisLabel.formatter",control:e,render:({field:n})=>i(mo,{...n})})]})]})}function xC({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=y.useMemo(()=>x.defaultsDeep({},t,vi),[t]),{control:a,handleSubmit:o,watch:l,getValues:u,reset:c}=v.useForm({defaultValues:r});y.useEffect(()=>{c(r)},[r]),l([]);const d=u(),f=y.useMemo(()=>!x.isEqual(d,r),[d,r]);return i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:o(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Merico Estimation Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!f,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"X Axis",orientation:"vertical",styles:{tab:{paddingLeft:"6px",paddingRight:"12px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"X Axis",children:"X 轴"}),i(s.Tabs.Tab,{value:"Deviation",children:"偏差"}),i(s.Tabs.Tab,{value:"Additional Metrics",children:"指标"})]}),i(s.Tabs.Panel,{value:"X Axis",children:i(vC,{control:a,watch:l})}),i(s.Tabs.Panel,{value:"Deviation",children:i(mC,{control:a,watch:l})}),i(s.Tabs.Panel,{value:"Additional Metrics",children:i(bC,{control:a,watch:l})})]})]})})}function wC(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=c=>c&&`${n}.${c}`,{x_axis:a,deviation:o,metrics:l,...u}=e;return{...u,x_axis:{...a,data_key:r(a.data_key)},deviation:{...o,data_keys:{estimated_value:r(o.data_keys.estimated_value),actual_value:r(o.data_keys.actual_value)}},metrics:l.map(c=>({...c,data_key:r(c.data_key)}))}}catch(n){throw console.error("[Migration failed]",n),n}}class CC extends ye{constructor(){super(...arguments);N(this,"VERSION",2)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,(n,r)=>{const{config:a}=n;return{...n,version:2,config:wC(a,r)}})}}const SC={displayName:"Merico Estimation Chart",displayGroup:"Merico suite",migrator:new CC,name:"mericoEstimationChart",viewRender:gC,configRender:xC,createConfig:()=>({version:2,config:vi})},wi={styles:{justify:"space-around",align:"start"},metrics:[]};function _C(){return{id:new Date().getTime().toString(),names:{value:"Value",basis:"Basis"},data_keys:{value:"",basis:""},formatter:ze,postfix:{type:"text",value:""}}}const Vo=({postfix:e})=>e?p(B,{children:[i(s.Text,{size:"12px",color:"#818388",sx:{lineHeight:1},children:"/"}),i(s.Text,{size:"12px",color:"#818388",sx:{lineHeight:1},children:e})]}):null,kC=k.observer(({metric:e,variableValueMap:t})=>{const{names:n,data_keys:r,formatter:a,postfix:o}=e,l=we(),u=y.useMemo(()=>{if(o.type==="text"&&o.value)return o.value;if(o.type==="filter-option-label"&&o.value){const c=l.filters.getSelectOption(o.value);return c?c.label:null}return null},[o,l]);return p(s.Stack,{spacing:18,children:[p(s.Stack,{spacing:12,children:[i(s.Text,{size:"14px",color:"#818388",children:n.value}),p(s.Group,{spacing:"2px",align:"baseline",children:[i(s.Text,{size:"24px",fw:"bold",color:"#3D3E45",sx:{lineHeight:1},children:Z(t[r.value]).format(a)}),i(Vo,{postfix:u})]})]}),p(s.Stack,{spacing:12,children:[i(s.Text,{size:"14px",color:"#818388",children:n.basis}),p(s.Group,{spacing:"2px",align:"baseline",children:[i(s.Text,{size:"12px",color:"#3D3E45",sx:{lineHeight:1},children:Z(t[r.basis]).format(a)}),i(Vo,{postfix:u})]})]})]})}),TC=k.observer(({context:e,instance:t})=>{const{value:n}=R(e.instanceData,"config"),{variables:r}=e,a=y.useMemo(()=>x.defaults({},n,wi),[n]),o=e.data,l=y.useMemo(()=>Ks(o,r),[r,o]),{width:u,height:c}=e.viewport;return!u||!c||!a?null:i(s.Flex,{w:`${u}px`,h:`${c}px`,justify:a.styles.justify,align:a.styles.align,direction:"row",wrap:"nowrap",sx:{overflow:"hidden"},children:a.metrics.map(d=>i(kC,{metric:d,variableValueMap:l},d.id))})}),DC=[{label:"Text",value:"text"},{label:"Filter Option Label",value:"filter-option-label"}],IC=k.observer(y.forwardRef(({value:e,onChange:t},n)=>{const a=le().filters.selects,o=u=>{t({type:u,value:e.value})},l=u=>{t({type:e.type,value:u})};return p(s.Group,{grow:!0,noWrap:!0,children:[i(s.Select,{label:"Postfix Type",data:DC,value:e.type,onChange:o}),e.type==="text"&&i(s.TextInput,{label:"Postfix Content",value:e.value,onChange:u=>{l(u.currentTarget.value)}}),e.type==="filter-option-label"&&i(s.Select,{label:"Filter",value:e.value,onChange:l,data:a})]})}));function MC({control:e,index:t,remove:n,watch:r,variableOptions:a}){return r(`metrics.${t}.postfix`),p(s.Stack,{my:0,p:"md",pr:40,sx:{border:"1px solid #eee",position:"relative"},children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`metrics.${t}.names.value`,control:e,render:({field:o})=>i(s.TextInput,{label:"Metric Name",required:!0,sx:{flex:1},...o})}),i(v.Controller,{name:`metrics.${t}.data_keys.value`,control:e,render:({field:o})=>i(s.Select,{label:"Metric Data",required:!0,data:a,sx:{flex:1},...o})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`metrics.${t}.names.basis`,control:e,render:({field:o})=>i(s.TextInput,{label:"Basis Name",required:!0,sx:{flex:1},...o})}),i(v.Controller,{name:`metrics.${t}.data_keys.basis`,control:e,render:({field:o})=>i(s.Select,{label:"Basis Data",required:!0,data:a,sx:{flex:1},...o})})]}),i(s.Divider,{mb:-15,variant:"dashed",label:"Format",labelPosition:"center"}),i(v.Controller,{name:`metrics.${t}.formatter`,control:e,render:({field:o})=>i(We,{...o})}),i(s.Divider,{mb:-15,variant:"dashed",label:"Others",labelPosition:"center"}),i(v.Controller,{name:`metrics.${t}.postfix`,control:e,render:({field:o})=>i(IC,{...o})}),i(s.ActionIcon,{color:"red",variant:"subtle",onClick:()=>n(t),sx:{position:"absolute",top:15,right:5},disabled:t===0,children:i(T.Trash,{size:16})})]},t)}const AC=({control:e,watch:t,variables:n})=>{const{fields:r,append:a,remove:o}=v.useFieldArray({control:e,name:"metrics"}),l=t("metrics"),u=r.map((C,w)=>({...C,...l[w]})),c=()=>{a(_C())},d=y.useMemo(()=>n.map(C=>({label:C.name,value:C.name})),[n]),f=x.get(u,"0.id",null),[h,g]=y.useState(f);y.useEffect(()=>{g(C=>C||f)},[f]);const m=C=>{o(C);const w=x.get(u,"0.id",null);g(w)};return p(B,{children:[i(s.Divider,{mt:15,variant:"dashed",label:"Metrics",labelPosition:"center"}),p(s.Tabs,{value:h,onTabChange:g,styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px"}},children:[p(s.Tabs.List,{children:[u.map((C,w)=>i(s.Tabs.Tab,{value:C.id,children:C.names.value?C.names.value:w+1},w)),i(s.Tabs.Tab,{onClick:c,value:"add",children:i($.IconPlus,{size:18,color:"#228be6"})})]}),u.map((C,w)=>i(s.Tabs.Panel,{value:C.id,children:i(MC,{control:e,index:w,remove:m,variableOptions:d,watch:t})},w))]})]})},zC=[{label:"Left",value:"left"},{label:"Center",value:"center"},{label:"Right",value:"right"},{label:"Space Between",value:"space-between"},{label:"Space Around",value:"space-around"},{label:"Space Evenly",value:"space-evenly"}],EC=[{label:"Start",value:"start"},{label:"Center",value:"center"},{label:"End",value:"end"},{label:"Stretch",value:"stretch"}];function $C({control:e,watch:t}){return t("styles"),p(B,{children:[i(s.Divider,{mt:15,variant:"dashed",label:"Styles",labelPosition:"center"}),p(s.Group,{children:[i(v.Controller,{name:"styles.justify",control:e,render:({field:n})=>i(s.Select,{label:"Justify Content",required:!0,data:zC,sx:{flex:1},...n})}),i(v.Controller,{name:"styles.align",control:e,render:({field:n})=>i(s.Select,{label:"Align",required:!0,data:EC,sx:{flex:1},...n})})]})]})}function LC({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),{variables:r}=e,a=y.useMemo(()=>x.defaultsDeep({},t,wi),[t]),{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});y.useEffect(()=>{d(a)},[a]);const f=c(),h=y.useMemo(()=>!x.isEqual(f,a),[f,a]);return i("form",{onSubmit:l(n),children:p(s.Stack,{spacing:"xs",children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Merico Stats Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),i($C,{control:o,watch:u}),i(AC,{control:o,watch:u,variables:r})]})})}function OC(e){const{metrics:t,...n}=e;return{...n,metrics:t.map(r=>({...r,postfix:r.postfix??{type:"text",value:""}}))}}class PC extends ye{constructor(){super(...arguments);N(this,"VERSION",2)}configVersions(){this.version(1,n=>({...n,version:1,config:n.config})),this.version(2,n=>({...n,version:2,config:OC(n.config)}))}}const BC={displayName:"Merico Stats",displayGroup:"Merico suite",migrator:new PC,name:"merico-stats",viewRender:TC,configRender:LC,createConfig:()=>({version:2,config:wi})};function VC({control:e,watch:t}){t(["heat_block"]);const n=t("heat_block.label.show");return p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"heat_block.data_key",control:e,render:({field:r})=>i(W,{label:"Data Field",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:"heat_block.name",control:e,render:({field:r})=>i(s.TextInput,{label:"Name",sx:{flex:1},...r})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"heat_block.min",control:e,render:({field:r})=>i(Ft,{label:"Min Value",...r})}),i(v.Controller,{name:"heat_block.max",control:e,render:({field:r})=>i(Ft,{label:"Max Value",...r})})]}),i(s.Divider,{mb:-15,variant:"dashed",label:"Value Format",labelPosition:"center"}),i(v.Controller,{name:"heat_block.value_formatter",control:e,render:({field:r})=>i(We,{...r})}),i(s.Divider,{mb:-5,variant:"dashed",label:"Label",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"heat_block.label.show",control:e,render:({field:r})=>i(s.Switch,{label:"Show label",checked:r.value,onChange:a=>r.onChange(a.currentTarget.checked),sx:{flexGrow:1}})}),i(v.Controller,{name:"heat_block.label.fontSize",control:e,render:({field:r})=>i(s.NumberInput,{size:"xs",icon:i($.IconTextSize,{size:16}),disabled:!n,...r})})]})]})}const NC=({control:e,index:t,remove:n})=>p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`tooltip.metrics.${t}.name`,control:e,render:({field:r})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:`tooltip.metrics.${t}.data_key`,control:e,render:({field:r})=>i(W,{label:"Value Field",required:!0,sx:{flex:1},...r})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed"}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Metric"})]}),qC=({control:e,watch:t})=>{const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"tooltip.metrics"}),o=t("tooltip.metrics"),l=n.map((h,g)=>({...h,...o[g]})),u=()=>r({id:Date.now().toString(),data_key:"",name:""}),c=t("tooltip.metrics.0.id"),[d,f]=y.useState(()=>c??null);return y.useEffect(()=>{c&&f(h=>h!==null?h:c)},[c]),p(B,{children:[p(s.Group,{spacing:2,sx:{cursor:"default",userSelect:"none"},children:[i(T.InfoCircle,{size:14,color:"#888"}),i(s.Text,{size:14,color:"#888",children:"Configure additional metrics to show in tooltip"})]}),i(s.Divider,{variant:"dashed",my:10}),p(s.Tabs,{value:d,onTabChange:h=>f(h),styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map((h,g)=>i(s.Tabs.Tab,{value:h.id,children:h.name?h.name:g},h.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((h,g)=>i(s.Tabs.Panel,{value:h.id,children:i(NC,{control:e,index:g,remove:a},h.id)},h.id))]})]})};function FC({control:e,watch:t}){return i(qC,{control:e,watch:t})}const GC=({disabled:e,value:t,onChange:n})=>{const r=a=>{a&&n(a)};return p(s.Box,{sx:{position:"relative"},children:[e&&i(s.Overlay,{opacity:.6,color:"#fff",zIndex:5,blur:2}),i(Ae,{height:"500px",defaultLanguage:"javascript",value:t,onChange:r,theme:"vs-dark",options:{minimap:{enabled:!1},readOnly:e}})]})},WC={enabled:!1,func_content:["function label(value, index) {"," // your code goes here"," // return value","}"].join(`
418
- `)},No=y.forwardRef(({value:e,onChange:t},n)=>{const[r,{setTrue:a,setFalse:o}]=K.useBoolean(),[l,u]=y.useState(e);y.useEffect(()=>{u(e)},[e]);const c=m=>{u({...l,enabled:m})},d=()=>{o();const{enabled:m,func_content:C}=l,w={enabled:m,func_content:C};u(w),t(w)},f=()=>{o(),u(e)},h=m=>{u(C=>({...C,func_content:m}))},g=()=>{h(WC.func_content)};return p(B,{children:[i(s.Button,{variant:"filled",mt:24,onClick:a,sx:{flexGrow:0},children:"Customize Label"}),i(s.Modal,{size:800,title:"Customize label content",opened:r,onClose:o,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:r&&p(s.Stack,{children:[i(s.Checkbox,{mt:10,label:"Enabled",checked:l.enabled,onChange:m=>c(m.currentTarget.checked)}),i(GC,{value:l.func_content,onChange:h,disabled:!l.enabled}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:g,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:f,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:d,children:"OK"})]})]})]})})]})});function jC({control:e,watch:t}){return t(["x_axis"]),p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.data_key",control:e,render:({field:n})=>i(W,{label:"Data Field",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"x_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Name",sx:{flex:1},...n})})]}),i(s.Divider,{mb:-15,variant:"dashed",label:"Tick Label",labelPosition:"center"}),i(v.Controller,{name:"x_axis.axisLabel.overflow",control:e,render:({field:n})=>i(at,{...n})}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.axisLabel.rotate",control:e,render:({field:n})=>i(s.NumberInput,{label:"Rotate",hideControls:!0,min:-90,max:90,rightSection:i(s.Text,{color:"dimmed",children:"degree"}),sx:{width:"48%"},styles:{rightSection:{width:"4em",justifyContent:"flex-end",paddingRight:"6px"}},...n})}),i(v.Controller,{name:"x_axis.axisLabel.formatter",control:e,render:({field:n})=>i(No,{...n})})]})]})}const RC=[{label:"left",value:"left"},{label:"center",value:"center"},{label:"right",value:"right"}];function YC({control:e,watch:t}){return t(["y_axis"]),p(s.Stack,{my:0,p:"0",sx:{position:"relative"},children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"y_axis.data_key",control:e,render:({field:n})=>i(W,{label:"Data Field",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"y_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...n})})]}),i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:"y_axis.nameAlignment",control:e,render:({field:n})=>i(s.Select,{label:"Name Alignment",required:!0,data:RC,sx:{flex:1},...n})})}),i(s.Divider,{mb:-15,variant:"dashed",label:"Tick Label",labelPosition:"center"}),i(v.Controller,{name:"y_axis.axisLabel.overflow",control:e,render:({field:n})=>i(at,{...n})}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"y_axis.axisLabel.rotate",control:e,render:({field:n})=>i(s.NumberInput,{label:"Rotate",hideControls:!0,min:-90,max:90,rightSection:i(s.Text,{color:"dimmed",children:"degree"}),sx:{width:"48%"},styles:{rightSection:{width:"4em",justifyContent:"flex-end",paddingRight:"6px"}},...n})}),i(v.Controller,{name:"y_axis.axisLabel.formatter",control:e,render:({field:n})=>i(No,{...n})})]})]})}const Ci={x_axis:{name:"",data_key:"",axisLabel:{rotate:0,overflow:je,formatter:{...Ue}}},y_axis:{name:"Y Axis",data_key:"",nameAlignment:"center",axisLabel:{rotate:0,overflow:je,formatter:{...Ue}}},heat_block:{min:{type:"static",value:0},max:{type:"static",value:100},name:"Value",data_key:"",value_formatter:ze,label:{show:!1,fontSize:10}},tooltip:{metrics:[]}};function QC({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=y.useMemo(()=>x.defaultsDeep({},t,Ci),[t]),a=y.useMemo(()=>x.cloneDeep(r),[r]);y.useEffect(()=>{!x.isEqual(r,a)&&(console.log("config malformed, resetting to defaults",r,a),n(a))},[r,a]);const{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});y.useEffect(()=>{d(a)},[a]);const f=c(),h=y.useMemo(()=>!x.isEqual(f,r),[f,r]);return i("form",{onSubmit:l(n),style:{flexGrow:1},children:p(s.Stack,{spacing:"xs",sx:{height:"100%"},children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"X Axis",orientation:"vertical",styles:{root:{flexGrow:1},tab:{paddingLeft:"6px",paddingRight:"6px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"X Axis",children:"X Axis"}),i(s.Tabs.Tab,{value:"Y Axis",children:"Y Axis"}),i(s.Tabs.Tab,{value:"Heat Block",children:"Heat Block"}),i(s.Tabs.Tab,{value:"Tooltip",children:"Tooltip"})]}),i(s.Tabs.Panel,{value:"X Axis",children:i(jC,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Y Axis",children:i(YC,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Heat Block",children:i(VC,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Tooltip",children:i(FC,{control:o,watch:u})})]})]})})}function qo({enabled:e,func_content:t}){return(n,r)=>{if(!e)return n;try{return new Function(`return ${t}`)()(n,r)}catch(a){return console.error(`[getEchartsXAxisLabel] failed parsing custom function, error: ${a.message}`),n}}}function UC(e){const t=qo(e.x_axis.axisLabel.formatter),n=qo(e.y_axis.axisLabel.formatter);return{x_axis:t,y_axis:n}}function KC(e){return{heat_block:function(r){if(!e.heat_block.value_formatter)return r;try{return Z(r).format(e.heat_block.value_formatter)}catch(a){return console.error(a),r}}}}function XC(e){let t=0;return e.x_axis.name&&(t+=20),{top:45,left:5,right:5,bottom:t,containLabel:!0}}function JC(e,t){const{x_axis:n,y_axis:r,heat_block:a}=e,o=O(n.data_key),l=O(r.data_key),u=O(a.data_key),c=t[o.queryID].map(d=>[x.get(d,o.columnKey),x.get(d,l.columnKey),x.get(d,u.columnKey)]);return{type:"heatmap",name:a.name,xAxisId:"main-x-axis",yAxisIndex:0,datasetIndex:0,itemStyle:{borderWidth:0},data:c,label:a.label,labelLayout:{hideOverlap:!0}}}const ZC=e=>{try{return Z(e).format({trimMantissa:!0,mantissa:2})}catch{return e}};function HC({conf:e,labelFormatters:t,valueFormatters:n,dataDict:r,params:a}){const{value:o,dataIndex:l}=a,[u,c,d]=o,f={label:e.x_axis.name?e.x_axis.name:"X Axis",value:t.x_axis(u,l),style:{label:"",value:st(e.x_axis.axisLabel.overflow.in_tooltip)}},h={label:e.y_axis.name?e.y_axis.name:"Y Axis",value:t.y_axis(c,l),style:{label:"",value:st(e.y_axis.axisLabel.overflow.in_tooltip)}},g={label:e.heat_block.name,value:n.heat_block(d),style:{label:"",value:""}},m=[f,h,g],C=r[`${u}---${c}`];return C&&e.tooltip.metrics.forEach(w=>{const _=O(w.data_key);m.push({label:w.name,value:ZC(x.get(C,_.columnKey,"")),style:{label:"",value:""}})}),m}function e1(e,t,n,r){const{x_axis:a,y_axis:o,heat_block:l}=e,u=O(a.data_key),c=O(o.data_key);O(l.data_key);const d=x.keyBy(t[u.queryID],f=>`${f[u.columnKey]}---${f[c.columnKey]}`);return{confine:!0,formatter:function(f){const g=HC({conf:e,labelFormatters:n,valueFormatters:r,dataDict:d,params:f}).map(C=>`
417
+ `}},show_in_legend:!0}))}function Zw(e,t,n,r){const a=O(t.data_key),o=t.name,l=n.map(u=>{const c=x.sumBy(r[u],a.columnKey);return[u,c]});return{type:"line",name:o,xAxisIndex:3,yAxisIndex:3,color:"#b41529",data:l,show_in_legend:!1}}function Hw(e,t,n,r){const l={barMinWidth:5,barMaxWidth:20};return[Qw(e,n,r),Kw(e,n,r,l),...Jw(e,n,r,l),Zw(e,t,n,r)]}function eC(e,t){const{axisLabel:n}=e.x_axis;return[{data:t,id:"准确估算比例",gridIndex:0,axisTick:{show:!1},axisLabel:{show:!1},axisLine:{show:!1},type:"category"},{data:t,id:"平均偏差",gridIndex:1,axisTick:{show:!1},axisLabel:{show:!1},axisLine:{show:!0,lineStyle:{color:"#FFFFFF",width:2}},type:"category"},{data:t,id:"数量占比",gridIndex:2,axisTick:{show:!1},axisLabel:{show:!1},axisLine:{show:!1},type:"category"},{data:t,id:"代码当量",gridIndex:3,axisTick:{show:!1},type:"category",axisLabel:{...n,formatter:ho(n.formatter)},axisLine:{show:!1}}]}function tC(e){return[{type:"category",name:"准确估算比例",nameRotate:0,nameGap:5,nameLocation:"end",nameTextStyle:{align:"left"},gridIndex:0,axisLabel:{show:!1},axisTick:{show:!1},axisLine:{show:!1},splitLine:{show:!1}},{type:"value",name:"平均偏差",nameGap:5,nameRotate:90,nameLocation:"middle",gridIndex:1,boundaryGap:[1,1],axisLabel:{show:!1},axisTick:{show:!1},axisLine:{show:!1},splitLine:{show:!1}},{type:"value",name:"数量占比",nameGap:5,nameRotate:90,nameLocation:"middle",gridIndex:2,axisLabel:{show:!1},axisTick:{show:!1},axisLine:{show:!1},splitLine:{show:!1},min:0,max:1},{type:"value",gridIndex:3,position:"right",splitNumber:3,axisLabel:{show:!0,verticalAlign:"top",showMinLabel:!1,lineHeight:14},axisTick:{show:!1},axisLine:{show:!1},splitLine:{show:!1}},{type:"value",name:e.name,nameGap:5,nameRotate:90,nameLocation:"middle",gridIndex:3,position:"left",axisLabel:{show:!1},axisTick:{show:!1},axisLine:{show:!1},splitLine:{show:!1}}]}function xi(e){return e==1||e==2?1:xi(e-2)+xi(e-1)}const nC=Array.from(new Array(20),(e,t)=>xi(t+1));function Bo(e){return e<=1?e:nC.findIndex(t=>e<=t)-1}function rC(e,t){const{x_axis:n,deviation:r}=e,a=O(n.data_key),o=O(r.data_keys.estimated_value),l=O(r.data_keys.actual_value);return t[a.queryID].map(u=>{const c=Bo(u[o.columnKey]),d=Bo(u[l.columnKey]),f=c-d;return{...u,level:{estimated:c,actual:d,diff:f}}})}function iC(e){return e==="rgba(255, 255, 255, 1)"?{borderColor:"rgba(0,0,0,.1)",borderWidth:1}:{}}function aC(e){return{show:!0,orient:"vertical",top:"middle",right:0,data:e.filter(n=>n.show_in_legend).reverse().map(n=>({name:`${n.name}`,color:n.color,itemStyle:iC(n.color)})),tooltip:{show:!0,formatter:"档位偏差:{a}"}}}const sC={tooltip:{trigger:"axis"}};function oC(e,t){const{deviation:n,metrics:r}=e,a=r.find(l=>l.data_key===t);if(a)return a;const o=n.data_keys.actual_value;return{id:o,name:n.name,data_key:o}}function lC(e,t,n){const r=rC(e,n),a=O(e.x_axis.data_key),o=x.uniqBy(n[a.queryID],a.columnKey).map(f=>f[a.columnKey]),l=x.groupBy(r,a.columnKey),u=oC(e,t),c=Hw(e,u,o,l),d={xAxis:eC(e,o),yAxis:tC(u),series:c,grid:Yw(),visualMap:[{min:0,max:1,calculable:!0,show:!1,seriesIndex:0,color:["#F0F0F0","#418AAF"]}],legend:aC(c)};return x.defaultsDeep({},d,sC)}const uC={input:{border:"none !important",paddingLeft:0,lineHeight:"1.55 !important"}},cC=({conf:e,metricKey:t,setMetricKey:n})=>{const{deviation:r,metrics:a}=e,o=b.useMemo(()=>{const l=a.map(u=>({label:u.name,value:u.data_key}));return l.push({label:r.name?r.name:r.data_keys.actual_value,value:r.data_keys.actual_value}),l},[r,a]);return p(s.Group,{spacing:1,children:[i(s.Text,{size:12,color:"dimmed",sx:{cursor:"default",userSelect:"none"},children:"基线指标"}),i(s.NativeSelect,{size:"xs",data:o,value:t,onChange:l=>n(l.currentTarget.value),styles:uC})]})},dC={"tbody th, tbody td":{padding:"7px 10px"},"tbody tr:not(:first-of-type) th":{borderTop:"1px solid #dee2e6"}};function pC(){return p(s.HoverCard,{width:400,shadow:"md",children:[i(s.HoverCard.Target,{children:i(s.Button,{size:"xs",variant:"subtle",compact:!0,leftIcon:i($.IconInfoCircle,{size:14}),children:"指标说明"})}),i(s.HoverCard.Dropdown,{children:i(s.Table,{fontSize:14,sx:dC,children:p("tbody",{children:[p("tr",{children:[i("th",{children:"估算偏差"}),i("td",{children:"使用斐波那契数列(1,2,3,5,8,13)估算故事点,每个数位为一个档位,计算issue实际故事点与估算故事点的档位偏差,即为估算偏差。如估算故事点为5,实际故事点为8,则估算偏差为-1。"})]}),p("tr",{children:[i("th",{children:"准确估算比例"}),i("td",{children:"偏差在 ± 1 档位内的 issue 均为准确估算,以此计算准确估算的比例。"})]})]})})})]})}function hC(e){return p(s.Group,{position:"apart",children:[i(pC,{}),i(cC,{...e})]})}ie.use([he.BarChart,he.LineChart,he.HeatmapChart,q.GridComponent,q.LegendComponent,q.TooltipComponent,Pe.CanvasRenderer,q.VisualMapComponent]);function fC({conf:e,data:t,width:n,height:r,metricKey:a}){const o=b.useMemo(()=>lC(e,a,t),[e,t,a]);return i(Be,{echarts:ie,option:o,style:{width:n,height:r},notMerge:!0,theme:"merico-light"})}function gC({context:e}){const{value:t}=R(e.instanceData,"config"),n=b.useMemo(()=>x.defaults({},t,vi),[t]),r=e.data,{width:a,height:o}=e.viewport,{x_axis:l,deviation:u}=n,{estimated_value:c,actual_value:d}=u.data_keys,[f,h]=b.useState(d);if(b.useEffect(()=>{h(C=>C||d)},[d]),!l.data_key||!c||!d||!a||!o)return null;const g=Math.max(a,300),m=Math.max(o,370);return p(s.Box,{sx:{overflow:"hidden",height:m,width:g},children:[i(hC,{conf:n,metricKey:f,setMetricKey:h}),i(fC,{width:g,height:m-30,data:r,conf:n,metricKey:f})]})}function mC({control:e,watch:t}){return t(["deviation"]),p(s.Stack,{children:[i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:"deviation.name",control:e,render:({field:n})=>i(s.TextInput,{label:"指标名称",sx:{flex:1},...n})})}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"deviation.data_keys.estimated_value",control:e,render:({field:n})=>i(W,{label:"估算值字段",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"deviation.data_keys.actual_value",control:e,render:({field:n})=>i(W,{label:"实际值字段",required:!0,sx:{flex:1},...n})})]})]})}const yC=({control:e,index:t,remove:n})=>p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`metrics.${t}.name`,control:e,render:({field:r})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:`metrics.${t}.data_key`,control:e,render:({field:r})=>i(W,{label:"Value Field",required:!0,sx:{flex:1},...r})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed"}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Metric"})]}),bC=({control:e,watch:t})=>{const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"metrics"}),o=t("metrics"),l=n.map((h,g)=>({...h,...o[g]})),u=()=>r({id:Date.now().toString(),data_key:"",name:""}),c=t("metrics.0.id"),[d,f]=b.useState(()=>c??null);return b.useEffect(()=>{c&&f(h=>h!==null?h:c)},[c]),p(B,{children:[p(s.Group,{spacing:2,sx:{cursor:"default",userSelect:"none"},children:[i(T.InfoCircle,{size:14,color:"#888"}),i(s.Text,{size:14,color:"#888",children:"设置可以展示在基线图的指标,例如代码当量"})]}),i(s.Divider,{variant:"dashed",my:10}),p(s.Tabs,{value:d,onTabChange:h=>f(h),styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map((h,g)=>i(s.Tabs.Tab,{value:h.id,children:h.name?h.name:g},h.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((h,g)=>i(s.Tabs.Panel,{value:h.id,children:i(yC,{control:e,index:g,remove:a},h.id)},h.id))]})]})};function vC({control:e,watch:t}){return t(["x_axis"]),p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.data_key",control:e,render:({field:n})=>i(W,{label:"数据字段",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"x_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"X轴名称",sx:{flex:1},...n})})]}),i(s.Divider,{mb:-15,label:"点位文案",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.axisLabel.rotate",control:e,render:({field:n})=>i(s.NumberInput,{label:"旋转",hideControls:!0,min:-90,max:90,rightSection:i(s.Text,{color:"dimmed",children:"度"}),sx:{width:"48%"},styles:{rightSection:{width:"4em",justifyContent:"flex-end",paddingRight:"6px"}},...n})}),i(v.Controller,{name:"x_axis.axisLabel.formatter",control:e,render:({field:n})=>i(mo,{...n})})]})]})}function xC({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=b.useMemo(()=>x.defaultsDeep({},t,vi),[t]),{control:a,handleSubmit:o,watch:l,getValues:u,reset:c}=v.useForm({defaultValues:r});b.useEffect(()=>{c(r)},[r]),l([]);const d=u(),f=b.useMemo(()=>!x.isEqual(d,r),[d,r]);return i(s.Stack,{spacing:"xs",children:p("form",{onSubmit:o(n),children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Merico Estimation Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!f,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"X Axis",orientation:"vertical",styles:{tab:{paddingLeft:"6px",paddingRight:"12px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"X Axis",children:"X 轴"}),i(s.Tabs.Tab,{value:"Deviation",children:"偏差"}),i(s.Tabs.Tab,{value:"Additional Metrics",children:"指标"})]}),i(s.Tabs.Panel,{value:"X Axis",children:i(vC,{control:a,watch:l})}),i(s.Tabs.Panel,{value:"Deviation",children:i(mC,{control:a,watch:l})}),i(s.Tabs.Panel,{value:"Additional Metrics",children:i(bC,{control:a,watch:l})})]})]})})}function wC(e,{panelModel:t}){try{const n=t.queryIDs[0];if(!n)throw new Error("cannot migrate when queryID is empty");const r=c=>c&&`${n}.${c}`,{x_axis:a,deviation:o,metrics:l,...u}=e;return{...u,x_axis:{...a,data_key:r(a.data_key)},deviation:{...o,data_keys:{estimated_value:r(o.data_keys.estimated_value),actual_value:r(o.data_keys.actual_value)}},metrics:l.map(c=>({...c,data_key:r(c.data_key)}))}}catch(n){throw console.error("[Migration failed]",n),n}}class CC extends ye{constructor(){super(...arguments);N(this,"VERSION",2)}configVersions(){this.version(1,n=>({version:1,config:n})),this.version(2,(n,r)=>{const{config:a}=n;return{...n,version:2,config:wC(a,r)}})}}const SC={displayName:"Merico Estimation Chart",displayGroup:"Merico suite",migrator:new CC,name:"mericoEstimationChart",viewRender:gC,configRender:xC,createConfig:()=>({version:2,config:vi})},wi={styles:{justify:"space-around",align:"start"},metrics:[]};function _C(){return{id:new Date().getTime().toString(),names:{value:"Value",basis:"Basis"},data_keys:{value:"",basis:""},formatter:ze,postfix:{type:"text",value:""}}}const Vo=({postfix:e})=>e?p(B,{children:[i(s.Text,{size:"12px",color:"#818388",sx:{lineHeight:1},children:"/"}),i(s.Text,{size:"12px",color:"#818388",sx:{lineHeight:1},children:e})]}):null,kC=k.observer(({metric:e,variableValueMap:t})=>{const{names:n,data_keys:r,formatter:a,postfix:o}=e,l=we(),u=b.useMemo(()=>{if(o.type==="text"&&o.value)return o.value;if(o.type==="filter-option-label"&&o.value){const c=l.filters.getSelectOption(o.value);return c?c.label:null}return null},[o,l]);return p(s.Stack,{spacing:18,children:[p(s.Stack,{spacing:12,children:[i(s.Text,{size:"14px",color:"#818388",children:n.value}),p(s.Group,{spacing:"2px",align:"baseline",children:[i(s.Text,{size:"24px",fw:"bold",color:"#3D3E45",sx:{lineHeight:1},children:Z(t[r.value]).format(a)}),i(Vo,{postfix:u})]})]}),p(s.Stack,{spacing:12,children:[i(s.Text,{size:"14px",color:"#818388",children:n.basis}),p(s.Group,{spacing:"2px",align:"baseline",children:[i(s.Text,{size:"12px",color:"#3D3E45",sx:{lineHeight:1},children:Z(t[r.basis]).format(a)}),i(Vo,{postfix:u})]})]})]})}),TC=k.observer(({context:e,instance:t})=>{const{value:n}=R(e.instanceData,"config"),{variables:r}=e,a=b.useMemo(()=>x.defaults({},n,wi),[n]),o=e.data,l=b.useMemo(()=>Ks(o,r),[r,o]),{width:u,height:c}=e.viewport;return!u||!c||!a?null:i(s.Flex,{w:`${u}px`,h:`${c}px`,justify:a.styles.justify,align:a.styles.align,direction:"row",wrap:"nowrap",sx:{overflow:"hidden"},children:a.metrics.map(d=>i(kC,{metric:d,variableValueMap:l},d.id))})}),DC=[{label:"Text",value:"text"},{label:"Filter Option Label",value:"filter-option-label"}],IC=k.observer(b.forwardRef(({value:e,onChange:t},n)=>{const a=le().filters.selects,o=u=>{t({type:u,value:e.value})},l=u=>{t({type:e.type,value:u})};return p(s.Group,{grow:!0,noWrap:!0,children:[i(s.Select,{label:"Postfix Type",data:DC,value:e.type,onChange:o}),e.type==="text"&&i(s.TextInput,{label:"Postfix Content",value:e.value,onChange:u=>{l(u.currentTarget.value)}}),e.type==="filter-option-label"&&i(s.Select,{label:"Filter",value:e.value,onChange:l,data:a})]})}));function MC({control:e,index:t,remove:n,watch:r,variableOptions:a}){return r(`metrics.${t}.postfix`),p(s.Stack,{my:0,p:"md",pr:40,sx:{border:"1px solid #eee",position:"relative"},children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`metrics.${t}.names.value`,control:e,render:({field:o})=>i(s.TextInput,{label:"Metric Name",required:!0,sx:{flex:1},...o})}),i(v.Controller,{name:`metrics.${t}.data_keys.value`,control:e,render:({field:o})=>i(s.Select,{label:"Metric Data",required:!0,data:a,sx:{flex:1},...o})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`metrics.${t}.names.basis`,control:e,render:({field:o})=>i(s.TextInput,{label:"Basis Name",required:!0,sx:{flex:1},...o})}),i(v.Controller,{name:`metrics.${t}.data_keys.basis`,control:e,render:({field:o})=>i(s.Select,{label:"Basis Data",required:!0,data:a,sx:{flex:1},...o})})]}),i(s.Divider,{mb:-15,variant:"dashed",label:"Format",labelPosition:"center"}),i(v.Controller,{name:`metrics.${t}.formatter`,control:e,render:({field:o})=>i(je,{...o})}),i(s.Divider,{mb:-15,variant:"dashed",label:"Others",labelPosition:"center"}),i(v.Controller,{name:`metrics.${t}.postfix`,control:e,render:({field:o})=>i(IC,{...o})}),i(s.ActionIcon,{color:"red",variant:"subtle",onClick:()=>n(t),sx:{position:"absolute",top:15,right:5},disabled:t===0,children:i(T.Trash,{size:16})})]},t)}const AC=({control:e,watch:t,variables:n})=>{const{fields:r,append:a,remove:o}=v.useFieldArray({control:e,name:"metrics"}),l=t("metrics"),u=r.map((C,w)=>({...C,...l[w]})),c=()=>{a(_C())},d=b.useMemo(()=>n.map(C=>({label:C.name,value:C.name})),[n]),f=x.get(u,"0.id",null),[h,g]=b.useState(f);b.useEffect(()=>{g(C=>C||f)},[f]);const m=C=>{o(C);const w=x.get(u,"0.id",null);g(w)};return p(B,{children:[i(s.Divider,{mt:15,variant:"dashed",label:"Metrics",labelPosition:"center"}),p(s.Tabs,{value:h,onTabChange:g,styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px"}},children:[p(s.Tabs.List,{children:[u.map((C,w)=>i(s.Tabs.Tab,{value:C.id,children:C.names.value?C.names.value:w+1},w)),i(s.Tabs.Tab,{onClick:c,value:"add",children:i($.IconPlus,{size:18,color:"#228be6"})})]}),u.map((C,w)=>i(s.Tabs.Panel,{value:C.id,children:i(MC,{control:e,index:w,remove:m,variableOptions:d,watch:t})},w))]})]})},zC=[{label:"Left",value:"left"},{label:"Center",value:"center"},{label:"Right",value:"right"},{label:"Space Between",value:"space-between"},{label:"Space Around",value:"space-around"},{label:"Space Evenly",value:"space-evenly"}],EC=[{label:"Start",value:"start"},{label:"Center",value:"center"},{label:"End",value:"end"},{label:"Stretch",value:"stretch"}];function $C({control:e,watch:t}){return t("styles"),p(B,{children:[i(s.Divider,{mt:15,variant:"dashed",label:"Styles",labelPosition:"center"}),p(s.Group,{children:[i(v.Controller,{name:"styles.justify",control:e,render:({field:n})=>i(s.Select,{label:"Justify Content",required:!0,data:zC,sx:{flex:1},...n})}),i(v.Controller,{name:"styles.align",control:e,render:({field:n})=>i(s.Select,{label:"Align",required:!0,data:EC,sx:{flex:1},...n})})]})]})}function LC({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),{variables:r}=e,a=b.useMemo(()=>x.defaultsDeep({},t,wi),[t]),{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});b.useEffect(()=>{d(a)},[a]);const f=c(),h=b.useMemo(()=>!x.isEqual(f,a),[f,a]);return i("form",{onSubmit:l(n),children:p(s.Stack,{spacing:"xs",children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Merico Stats Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),i($C,{control:o,watch:u}),i(AC,{control:o,watch:u,variables:r})]})})}function OC(e){const{metrics:t,...n}=e;return{...n,metrics:t.map(r=>({...r,postfix:r.postfix??{type:"text",value:""}}))}}class PC extends ye{constructor(){super(...arguments);N(this,"VERSION",2)}configVersions(){this.version(1,n=>({...n,version:1,config:n.config})),this.version(2,n=>({...n,version:2,config:OC(n.config)}))}}const BC={displayName:"Merico Stats",displayGroup:"Merico suite",migrator:new PC,name:"merico-stats",viewRender:TC,configRender:LC,createConfig:()=>({version:2,config:wi})};function VC({control:e,watch:t}){t(["heat_block"]);const n=t("heat_block.label.show");return p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"heat_block.data_key",control:e,render:({field:r})=>i(W,{label:"Data Field",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:"heat_block.name",control:e,render:({field:r})=>i(s.TextInput,{label:"Name",sx:{flex:1},...r})})]}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"heat_block.min",control:e,render:({field:r})=>i(Ft,{label:"Min Value",...r})}),i(v.Controller,{name:"heat_block.max",control:e,render:({field:r})=>i(Ft,{label:"Max Value",...r})})]}),i(s.Divider,{mb:-15,variant:"dashed",label:"Value Format",labelPosition:"center"}),i(v.Controller,{name:"heat_block.value_formatter",control:e,render:({field:r})=>i(je,{...r})}),i(s.Divider,{mb:-5,variant:"dashed",label:"Label",labelPosition:"center"}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"heat_block.label.show",control:e,render:({field:r})=>i(s.Switch,{label:"Show label",checked:r.value,onChange:a=>r.onChange(a.currentTarget.checked),sx:{flexGrow:1}})}),i(v.Controller,{name:"heat_block.label.fontSize",control:e,render:({field:r})=>i(s.NumberInput,{size:"xs",icon:i($.IconTextSize,{size:16}),disabled:!n,...r})})]})]})}const NC=({control:e,index:t,remove:n})=>p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:`tooltip.metrics.${t}.name`,control:e,render:({field:r})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...r})}),i(v.Controller,{name:`tooltip.metrics.${t}.data_key`,control:e,render:({field:r})=>i(W,{label:"Value Field",required:!0,sx:{flex:1},...r})})]}),i(s.Divider,{mb:-10,mt:10,variant:"dashed"}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:()=>n(t),sx:{top:15,right:5},children:"Delete this Metric"})]}),qC=({control:e,watch:t})=>{const{fields:n,append:r,remove:a}=v.useFieldArray({control:e,name:"tooltip.metrics"}),o=t("tooltip.metrics"),l=n.map((h,g)=>({...h,...o[g]})),u=()=>r({id:Date.now().toString(),data_key:"",name:""}),c=t("tooltip.metrics.0.id"),[d,f]=b.useState(()=>c??null);return b.useEffect(()=>{c&&f(h=>h!==null?h:c)},[c]),p(B,{children:[p(s.Group,{spacing:2,sx:{cursor:"default",userSelect:"none"},children:[i(T.InfoCircle,{size:14,color:"#888"}),i(s.Text,{size:14,color:"#888",children:"Configure additional metrics to show in tooltip"})]}),i(s.Divider,{variant:"dashed",my:10}),p(s.Tabs,{value:d,onTabChange:h=>f(h),styles:{tab:{paddingTop:"0px",paddingBottom:"0px"},panel:{padding:"0px",paddingTop:"6px"}},children:[p(s.Tabs.List,{children:[l.map((h,g)=>i(s.Tabs.Tab,{value:h.id,children:h.name?h.name:g},h.id)),i(s.Tabs.Tab,{onClick:u,value:"add",children:i(T.Plus,{size:18,color:"#228be6"})})]}),l.map((h,g)=>i(s.Tabs.Panel,{value:h.id,children:i(NC,{control:e,index:g,remove:a},h.id)},h.id))]})]})};function FC({control:e,watch:t}){return i(qC,{control:e,watch:t})}const GC=({disabled:e,value:t,onChange:n})=>{const r=a=>{a&&n(a)};return p(s.Box,{sx:{position:"relative"},children:[e&&i(s.Overlay,{opacity:.6,color:"#fff",zIndex:5,blur:2}),i(Ae,{height:"500px",defaultLanguage:"javascript",value:t,onChange:r,theme:"vs-dark",options:{minimap:{enabled:!1},readOnly:e}})]})},WC={enabled:!1,func_content:["function label(value, index) {"," // your code goes here"," // return value","}"].join(`
418
+ `)},No=b.forwardRef(({value:e,onChange:t},n)=>{const[r,{setTrue:a,setFalse:o}]=K.useBoolean(),[l,u]=b.useState(e);b.useEffect(()=>{u(e)},[e]);const c=m=>{u({...l,enabled:m})},d=()=>{o();const{enabled:m,func_content:C}=l,w={enabled:m,func_content:C};u(w),t(w)},f=()=>{o(),u(e)},h=m=>{u(C=>({...C,func_content:m}))},g=()=>{h(WC.func_content)};return p(B,{children:[i(s.Button,{variant:"filled",mt:24,onClick:a,sx:{flexGrow:0},children:"Customize Label"}),i(s.Modal,{size:800,title:"Customize label content",opened:r,onClose:o,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:r&&p(s.Stack,{children:[i(s.Checkbox,{mt:10,label:"Enabled",checked:l.enabled,onChange:m=>c(m.currentTarget.checked)}),i(GC,{value:l.func_content,onChange:h,disabled:!l.enabled}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:g,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:f,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:d,children:"OK"})]})]})]})})]})});function jC({control:e,watch:t}){return t(["x_axis"]),p(s.Stack,{children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.data_key",control:e,render:({field:n})=>i(W,{label:"Data Field",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"x_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Name",sx:{flex:1},...n})})]}),i(s.Divider,{mb:-15,variant:"dashed",label:"Tick Label",labelPosition:"center"}),i(v.Controller,{name:"x_axis.axisLabel.overflow",control:e,render:({field:n})=>i(at,{...n})}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"x_axis.axisLabel.rotate",control:e,render:({field:n})=>i(s.NumberInput,{label:"Rotate",hideControls:!0,min:-90,max:90,rightSection:i(s.Text,{color:"dimmed",children:"degree"}),sx:{width:"48%"},styles:{rightSection:{width:"4em",justifyContent:"flex-end",paddingRight:"6px"}},...n})}),i(v.Controller,{name:"x_axis.axisLabel.formatter",control:e,render:({field:n})=>i(No,{...n})})]})]})}const RC=[{label:"left",value:"left"},{label:"center",value:"center"},{label:"right",value:"right"}];function YC({control:e,watch:t}){return t(["y_axis"]),p(s.Stack,{my:0,p:"0",sx:{position:"relative"},children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"y_axis.data_key",control:e,render:({field:n})=>i(W,{label:"Data Field",required:!0,sx:{flex:1},...n})}),i(v.Controller,{name:"y_axis.name",control:e,render:({field:n})=>i(s.TextInput,{label:"Name",required:!0,sx:{flex:1},...n})})]}),i(s.Group,{grow:!0,noWrap:!0,children:i(v.Controller,{name:"y_axis.nameAlignment",control:e,render:({field:n})=>i(s.Select,{label:"Name Alignment",required:!0,data:RC,sx:{flex:1},...n})})}),i(s.Divider,{mb:-15,variant:"dashed",label:"Tick Label",labelPosition:"center"}),i(v.Controller,{name:"y_axis.axisLabel.overflow",control:e,render:({field:n})=>i(at,{...n})}),p(s.Group,{grow:!0,noWrap:!0,children:[i(v.Controller,{name:"y_axis.axisLabel.rotate",control:e,render:({field:n})=>i(s.NumberInput,{label:"Rotate",hideControls:!0,min:-90,max:90,rightSection:i(s.Text,{color:"dimmed",children:"degree"}),sx:{width:"48%"},styles:{rightSection:{width:"4em",justifyContent:"flex-end",paddingRight:"6px"}},...n})}),i(v.Controller,{name:"y_axis.axisLabel.formatter",control:e,render:({field:n})=>i(No,{...n})})]})]})}const Ci={x_axis:{name:"",data_key:"",axisLabel:{rotate:0,overflow:Re,formatter:{...Ue}}},y_axis:{name:"Y Axis",data_key:"",nameAlignment:"center",axisLabel:{rotate:0,overflow:Re,formatter:{...Ue}}},heat_block:{min:{type:"static",value:0},max:{type:"static",value:100},name:"Value",data_key:"",value_formatter:ze,label:{show:!1,fontSize:10}},tooltip:{metrics:[]}};function QC({context:e}){const{value:t,set:n}=R(e.instanceData,"config"),r=b.useMemo(()=>x.defaultsDeep({},t,Ci),[t]),a=b.useMemo(()=>x.cloneDeep(r),[r]);b.useEffect(()=>{!x.isEqual(r,a)&&(console.log("config malformed, resetting to defaults",r,a),n(a))},[r,a]);const{control:o,handleSubmit:l,watch:u,getValues:c,reset:d}=v.useForm({defaultValues:a});b.useEffect(()=>{d(a)},[a]);const f=c(),h=b.useMemo(()=>!x.isEqual(f,r),[f,r]);return i("form",{onSubmit:l(n),style:{flexGrow:1},children:p(s.Stack,{spacing:"xs",sx:{height:"100%"},children:[p(s.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[i(s.Text,{children:"Chart Config"}),i(s.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!h,children:i(T.DeviceFloppy,{size:20})})]}),p(s.Tabs,{defaultValue:"X Axis",orientation:"vertical",styles:{root:{flexGrow:1},tab:{paddingLeft:"6px",paddingRight:"6px"},panel:{paddingTop:"6px",paddingLeft:"12px"}},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"X Axis",children:"X Axis"}),i(s.Tabs.Tab,{value:"Y Axis",children:"Y Axis"}),i(s.Tabs.Tab,{value:"Heat Block",children:"Heat Block"}),i(s.Tabs.Tab,{value:"Tooltip",children:"Tooltip"})]}),i(s.Tabs.Panel,{value:"X Axis",children:i(jC,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Y Axis",children:i(YC,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Heat Block",children:i(VC,{control:o,watch:u})}),i(s.Tabs.Panel,{value:"Tooltip",children:i(FC,{control:o,watch:u})})]})]})})}function qo({enabled:e,func_content:t}){return(n,r)=>{if(!e)return n;try{return new Function(`return ${t}`)()(n,r)}catch(a){return console.error(`[getEchartsXAxisLabel] failed parsing custom function, error: ${a.message}`),n}}}function UC(e){const t=qo(e.x_axis.axisLabel.formatter),n=qo(e.y_axis.axisLabel.formatter);return{x_axis:t,y_axis:n}}function KC(e){return{heat_block:function(r){if(!e.heat_block.value_formatter)return r;try{return Z(r).format(e.heat_block.value_formatter)}catch(a){return console.error(a),r}}}}function XC(e){let t=0;return e.x_axis.name&&(t+=20),{top:45,left:5,right:5,bottom:t,containLabel:!0}}function JC(e,t){const{x_axis:n,y_axis:r,heat_block:a}=e,o=O(n.data_key),l=O(r.data_key),u=O(a.data_key),c=t[o.queryID].map(d=>[x.get(d,o.columnKey),x.get(d,l.columnKey),x.get(d,u.columnKey)]);return{type:"heatmap",name:a.name,xAxisId:"main-x-axis",yAxisIndex:0,datasetIndex:0,itemStyle:{borderWidth:0},data:c,label:a.label,labelLayout:{hideOverlap:!0}}}const ZC=e=>{try{return Z(e).format({trimMantissa:!0,mantissa:2})}catch{return e}};function HC({conf:e,labelFormatters:t,valueFormatters:n,dataDict:r,params:a}){const{value:o,dataIndex:l}=a,[u,c,d]=o,f={label:e.x_axis.name?e.x_axis.name:"X Axis",value:t.x_axis(u,l),style:{label:"",value:st(e.x_axis.axisLabel.overflow.in_tooltip)}},h={label:e.y_axis.name?e.y_axis.name:"Y Axis",value:t.y_axis(c,l),style:{label:"",value:st(e.y_axis.axisLabel.overflow.in_tooltip)}},g={label:e.heat_block.name,value:n.heat_block(d),style:{label:"",value:""}},m=[f,h,g],C=r[`${u}---${c}`];return C&&e.tooltip.metrics.forEach(w=>{const _=O(w.data_key);m.push({label:w.name,value:ZC(x.get(C,_.columnKey,"")),style:{label:"",value:""}})}),m}function e1(e,t,n,r){const{x_axis:a,y_axis:o,heat_block:l}=e,u=O(a.data_key),c=O(o.data_key);O(l.data_key);const d=x.keyBy(t[u.queryID],f=>`${f[u.columnKey]}---${f[c.columnKey]}`);return{confine:!0,formatter:function(f){const g=HC({conf:e,labelFormatters:n,valueFormatters:r,dataDict:d,params:f}).map(C=>`
419
419
  <tr>
420
420
  <th style="text-align: right;">
421
421
  <div style="${C.style.label}">${C.label}</div>
@@ -436,9 +436,9 @@ Check the top-level render call using <`+V+">.")}return E}}function Su(S,E){{if(
436
436
  </thead>
437
437
  <tbody>${g.join("")}</tbody>
438
438
  </table>
439
- `}}}function t1(e,t){const n=Gt(e.heat_block.min,t),r=Gt(e.heat_block.max,t);return{min:n,max:r,calculable:!0,orient:"horizontal",left:"center",top:0,itemWidth:15}}function n1(e,t,n){const r=O(e.x_axis.data_key),a=x.uniq(t[r.queryID].map(c=>c[r.columnKey])),{overflow:o,rotate:l}=e.x_axis.axisLabel,u=rt(o.on_axis);return{id:"main-x-axis",type:"category",data:a,name:e.x_axis.name??"",align:"center",axisTick:{show:!0,alignWithLabel:!0},axisLabel:{rotate:l,...u,formatter:n},splitArea:{show:!0},nameLocation:"center",nameGap:25,nameTextStyle:{fontWeight:"bold",align:"center"},z:2}}function r1(e,t,n){const r=O(e.x_axis.data_key),a=O(e.y_axis.data_key),{nameAlignment:o,data_key:l,...u}=e.y_axis,c=x.uniq(t[r.queryID].map(g=>g[a.columnKey])),{overflow:d,rotate:f}=e.y_axis.axisLabel,h=rt(d.on_axis);return{...u,type:"category",data:c,axisLabel:{rotate:f,...h,formatter:n},axisLine:{show:!0,color:"blue"},axisTick:{show:!0,alignWithLabel:!0},splitArea:{show:!0},nameTextStyle:{fontWeight:"bold",align:o},nameLocation:"end",nameGap:15,z:2}}const i1={tooltip:{confine:!0}};function a1(e,t,n){if(!e.x_axis.data_key||!e.y_axis.data_key||!e.heat_block.data_key)return{};const r=n.reduce((u,c)=>{const d=ft(c,t);return u[c.name]=Ze(c,d),u},{}),a=UC(e),o=KC(e),l={xAxis:n1(e,t,a.x_axis),yAxis:r1(e,t,a.y_axis),series:JC(e,t),tooltip:e1(e,t,a,o),grid:XC(e),visualMap:t1(e,r)};return x.defaultsDeep({},l,i1)}function s1(e){return i(B,{})}function o1(e){return i(s.Text,{children:"Click heat block"})}const Fo={id:"builtin:echarts:click-heatmap:heat-block",displayName:"Click Heat Block",nameRender:o1,configRender:s1,payload:[{name:"seriesType",description:"'heatmap'",valueType:"string"},{name:"componentType",description:"'series'",valueType:"string"},{name:"name",description:"Name of the series clicked",valueType:"string"},{name:"color",description:"Color",valueType:"string"},{name:"value",description:"String-typed number, or series' actual value",valueType:"string"},{name:"rowData",description:"Data of the row",valueType:"object"}]};ie.use([q.DataZoomComponent,he.HeatmapChart,q.GridComponent,q.LegendComponent,q.TooltipComponent,q.VisualMapComponent,Pe.CanvasRenderer]);function l1({conf:e,data:t,width:n,height:r,interactionManager:a,variables:o}){const l=y.useMemo(()=>{const h=O(e.x_axis.data_key),g=O(e.y_axis.data_key);return x.keyBy(t[h.queryID],m=>`${m[h.columnKey]}---${m[g.columnKey]}`)},[t,e.x_axis.data_key,e.y_axis.data_key]),u=Ke(a.triggerManager,Fo.id),c=y.useCallback(h=>{const[g,m]=h.value,C=x.get(l,`${g}---${m}`,{error:"rowData is not found"});u.forEach(w=>{a.runInteraction(w.id,{...h,rowData:C})})},[l,u,a]),d=y.useMemo(()=>({click:c}),[c]),f=y.useMemo(()=>a1(e,t,o),[e,t]);return!n||!r?null:i(Be,{echarts:ie,option:f,style:{width:n,height:r},onEvents:d,notMerge:!0,theme:"merico-light"})}function u1({context:e,instance:t}){const n=Xe({vizManager:e.vizManager,instance:t}),{value:r}=R(e.instanceData,"config"),{variables:a}=e,o=y.useMemo(()=>x.defaults({},r,Ci),[r]),l=e.data,{width:u,height:c}=e.viewport;return i(l1,{variables:a,width:u,height:c,data:l,conf:o,interactionManager:n})}class c1 extends ye{constructor(){super(...arguments);N(this,"VERSION",1)}configVersions(){this.version(1,n=>({version:1,config:n}))}}const d1={displayName:"Merico Heatmap",displayGroup:"Merico suite",migrator:new c1,name:"merico-heatmap",viewRender:u1,configRender:QC,createConfig:()=>({version:1,config:Ci}),triggers:[Fo]},p1=[{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"})),h1=[Hu,ec,rc,nc,tc,ic],Go=()=>({id:"dashboard",version:es,manifest:{viz:[hi,ex,C0,zb,Cx,Sy,Rw,bc,Vh,Ug,zm,aw,cy,kg,Gv,Qy,Cb,A0,SC,d1,BC,Zh],color:[...p1,...h1]}}),dn=new lc,Ce={pluginManager:dt("pluginManager"),vizManager:dt("vizManager"),colorManager:dt("colorManager"),instanceScope:{panelModel:dt("panelModel"),vizInstance:dt("vizInstance"),interactionManager:dt("interactionManager"),migrator:dt("migrator"),operationManager:dt("operationManager"),triggerManager:dt("triggerManager")}},Si=()=>{try{dn.install(Go())}catch{}const e=new Xu(dn),t=new oc(dn);return{pluginManager:dn,vizManager:e,colorManager:t}},ut=y.createContext(Si());try{dn.install(Go())}catch{}const _i=y.createContext(null);function er(e){const t=y.useContext(_i),n=K.useCreation(()=>e.configure(t||new yr),[e.configure]),r=K.usePrevious(n);return r&&r!==n&&r.dispose(),i(_i.Provider,{value:n,children:e.children})}function Wo(){return y.useContext(_i)}const f1=({description:e,isDescriptionEmpty:t})=>t?null:i(s.Tooltip,{color:"white",label:i(qn,{value:e,styles:{root:{border:"none"},content:{padding:0}}}),styles:{tooltip:{border:"0.0625rem solid rgb(233, 236, 239)",boxShadow:"rgb(0 0 0 / 5%) 0px 0.0625rem 0.1875rem, rgb(0 0 0 / 5%) 0px 1.25rem 1.5625rem -0.3125rem, rgb(0 0 0 / 4%) 0px 0.625rem 0.625rem -0.3125rem"}},withArrow:!0,children:i(s.Box,{sx:{height:"16px",alignSelf:"center"},children:i($.IconInfoCircle,{size:16,color:"gray"})})}),g1=k.observer(({label:e,config:{default_value:t,description:n,isDescriptionEmpty:r,...a},value:o,onChange:l})=>p(s.Box,{children:[i(s.Text,{children:" "}),i(s.Checkbox,{label:p(s.Group,{noWrap:!0,position:"apart",align:"middle",spacing:6,children:[i(s.Box,{sx:{flexGrow:1},children:e}),i(f1,{description:n,isDescriptionEmpty:r})]}),checked:o||!1,onChange:u=>l(u.currentTarget.checked),...a,pt:".4em",styles:{input:{borderColor:"#e9ecef"}}})]})),jo=k.observer(({label:e,config:t,value:n=[null,null],onChange:r})=>{const{inputFormat:a,...o}=t,l=Array.isArray(n)?n.map(f=>f?Y(f).toDate():null):[null,null],u=f=>{r(f.map(h=>h&&Y(h).format(a)))},c=t.getMinDate(l[0]),d=t.getMaxDate(l[0]);return i(Eu.DatePickerInput,{type:"range",label:e,value:l,onChange:u,icon:i(T.Calendar,{size:16}),sx:{minWidth:"16em"},minDate:c,maxDate:d,valueFormat:a,styles:{input:{borderColor:"#e9ecef"}},...o})}),m1=s.createStyles((e,{radius:t=4})=>({root:{borderRadius:e.fn.radius(t),display:"flex",flexWrap:"nowrap",border:"1px solid #ced4da",paddingLeft:"0px",paddingRight:"30px",backgroundColor:"#fff",transition:"border-color 100ms ease",borderColor:"#e9ecef","&.rc-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"}}})),Ro=({errorMessage:e})=>e?i(s.Text,{color:"red",size:12,children:e}):i(s.Text,{color:"dimmed",size:12,children:"Not found"}),y1=({disabled:e,classNames:t,styles:n,unstyled:r,radius:a,style:o,label:l,value:u,onChange:c,options:d,errorMessage:f,required:h})=>{const{classes:g,cx:m}=m1({radius:a},{name:"MultiSelectWidget",classNames:t,styles:n,unstyled:r}),[C,w]=y.useState(!1),_=L=>{w(L)},D=C&&(u==null?void 0:u.length)>0,[M,P]=y.useState(""),G=y.useMemo(()=>{if(!M)return d;const L=M.toLowerCase(),z=A=>{var F;return((F=A.description)==null?void 0:F.toLowerCase().includes(L))||A.label.toLowerCase().includes(L)};return d.filter(z)},[M,d]);return p(s.Stack,{spacing:3,children:[p(s.Group,{position:"apart",children:[p(s.Text,{className:g.label,children:[l,h&&i("span",{className:g.required,"aria-hidden":"true",children:"*"})]}),D&&i(s.Tooltip,{label:`${u.length} selected`,children:i(s.Badge,{children:u.length})})]}),i(ja,{disabled:e,allowClear:!0,className:m(g.root,"check-select"),dropdownClassName:m(g.dropdown,""),onDropdownVisibleChange:_,transitionName:"rc-select-dropdown-slide-up",choiceTransitionName:"rc-select-selection__choice-zoom",style:o,clearIcon:()=>i(s.CloseButton,{}),value:u,onChange:c,onSelect:console.log,mode:"multiple",maxTagCount:0,notFoundContent:i(Ro,{errorMessage:f}),maxTagTextLength:10,maxTagPlaceholder:L=>`${L.length} selected`,searchValue:M,onSearch:P,filterOption:!1,children:G.map(L=>p(ja.Option,{title:L.label,children:[i(s.Text,{size:"sm","data-role":"label",children:L.label}),L.description&&i(s.Text,{size:"xs",color:"dimmed","data-role":"description",children:L.description})]},L.value))})]})},b1=k.observer(({label:e,config:t,value:n,onChange:r})=>{const a=we(),o=!!t.options_query_id,{state:l,error:u}=a.getDataStuffByID(t.options_query_id),c=l==="loading",d=t.min_width?t.min_width:"200px",f=o?c:!1,h=g=>r(g,!1);return i(y1,{label:e,options:t.options,style:{minWidth:"160px",width:d,maxWidth:f?d:"unset",borderColor:"#e9ecef"},disabled:f,value:n,onChange:h,errorMessage:u,required:t.required})}),v1=y.forwardRef(({label:e,description:t,...n},r)=>i("div",{ref:r,...n,children:i(s.Group,{noWrap:!0,children:p("div",{children:[i(s.Text,{size:"sm","data-role":"label",children:e}),i(s.Text,{size:"xs",color:"dimmed","data-role":"description",children:t})]})})})),x1=k.observer(({label:e,config:t,value:n,onChange:r})=>{const a=we(),o=!!t.options_query_id,{state:l,error:u}=a.getDataStuffByID(t.options_query_id),c=l==="loading";return i(s.Select,{label:e,data:t.options,disabled:o?c:!1,value:n,onChange:r,error:!!u,placeholder:u,maxDropdownHeight:500,styles:{root:{width:t.width?t.width:"200px"},input:{borderColor:"#e9ecef"}},sx:{".mantine-Select-item[data-selected] .mantine-Text-root[data-role=description]":{color:"rgba(255,255,255,.7)"}},itemComponent:v1})});function w1({label:e,config:t,value:n,onChange:r}){return i(s.TextInput,{label:e,value:n||"",onChange:a=>r(a.currentTarget.value),...t,styles:{input:{borderColor:"#e9ecef"}}})}const C1=({rotate:e,onClick:t})=>i("svg",{onClick:t,className:"caret-icon",viewBox:"0 0 1024 1024",focusable:"false","data-icon":"caret-down",width:"14px",height:"14px",fill:"currentColor","aria-hidden":"true",transform:`rotate(${e})`,children:i("path",{d:"M840.4 300H183.6c-19.7 0-30.7 20.8-18.5 35l328.4 380.8c9.4 10.9 27.5 10.9 37 0L858.9 335c12.2-14.2 1.2-35-18.5-35z"})}),S1=({expanded:e,isLeaf:t,value:n,onClick:r,...a})=>(n==="0-0-value"&&console.log(a),t?i("span",{style:{width:"14px",display:"inline-block"}}):i(C1,{rotate:e?"0":"-90",onClick:r,...a})),_1=({onClick:e})=>p("svg",{onClick:e,className:"checkbox-icon",width:"16",height:"16",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:"2",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",children:[i("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),i("rect",{className:"border",x:"4",y:"4",width:"16",height:"16",rx:"2"}),i("rect",{className:"checkmark-indeterminate",x:"8",y:"8",width:"8",height:"8",rx:"2",stroke:"none"}),i("path",{className:"checkmark-checked",d:"M9 12l2 2l4 -4"})]}),k1=({onClick:e,...t})=>i(_1,{onClick:e,...t}),T1=s.createStyles((e,{radius:t=4})=>({root:{borderRadius:e.fn.radius(t),display:"flex",flexWrap:"nowrap",border:"1px solid #ced4da",paddingLeft:"0px",paddingRight:"30px",backgroundColor:"#fff",transition:"border-color 100ms ease",borderColor:"#e9ecef","&.rc-tree-select.rc-tree-select-open":{borderColor:"#228be6 !important",".rc-tree-select-selection-overflow-item-rest":{display:"none"},".rc-tree-select-selection-overflow-item-suffix":{display:"block"}},".rc-tree-select-selector":{height:"auto",lineHeight:1.55,paddingLeft:"12px",resize:"none",boxSizing:"border-box",fontSize:"14px",width:"100%",color:"#000",display:"block",textAlign:"left",minHeight:"36px",cursor:"pointer",flexGrow:1},".rc-tree-select-selection-search-mirror":{display:"none"},".rc-tree-select-selection-search":{flexGrow:1,width:"auto !important"},".rc-tree-select-selection-overflow":{display:"flex",minHeight:"34px",alignItems:"center",flexWrap:"nowrap",marginLeft:"calc(-10px / 2)",boxSizing:"border-box"},".rc-tree-select-selection-overflow-item":{display:"flex",alignItems:"center",backgroundColor:"#f1f3f5",color:"#495057",height:"24px",paddingLeft:"12px",paddingRight:"12px",fontWeight:500,fontSize:"12px",borderRadius:"4px",cursor:"default",userSelect:"none",maxWidth:"calc(100% - 20px)",margin:"calc(10px / 2 - 2px) calc(10px / 2)"},".rc-tree-select-selection-overflow-item-rest":{cursor:"pointer"},".rc-tree-select-selection-overflow-item-suffix":{display:"none",backgroundColor:"transparent",width:"100%",maxWidth:"100%",height:"28px",margin:0,paddingLeft:0,paddingRight:0},input:{flex:1,minWidth:"60px",backgroundColor:"transparent",border:0,outline:0,fontSize:"14px",padding:0,marginLeft:0,color:"inherit",height:"28px",lineHeight:"32px",cursor:"pointer",width:"100%","&::-webkit-search-decoration, &::-webkit-search-cancel-button, &::-webkit-search-results-button, &::-webkit-search-results-decoration":{display:"none"}},".rc-tree-select-clear":{marginRight:"-24px",alignSelf:"center",cursor:"pointer"},"&.rc-tree-select-disabled":{backgroundColor:"rgb(241, 243, 245)",color:"rgb(144, 146, 150)",opacity:.6,"&, .rc-tree-select-selector, input":{cursor:"not-allowed"}}},label:{fontSize:e.fontSizes.sm,fontWeight:500,color:"#212529"},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"}}}})),D1=({disabled:e,classNames:t,styles:n,unstyled:r,radius:a,style:o,label:l,value:u,onChange:c,treeData:d,errorMessage:f,required:h,treeCheckStrictly:g})=>{const{classes:m,cx:C}=T1({radius:a},{name:"FilterTreeSelectWidget",classNames:t,styles:n,unstyled:r}),[w,_]=y.useState(!1),D=P=>{_(P)},M=w&&(u==null?void 0:u.length)>0;return p(s.Stack,{spacing:3,children:[p(s.Group,{position:"apart",children:[p(s.Text,{className:m.label,children:[l,h&&i("span",{className:m.required,"aria-hidden":"true",children:"*"})]}),M&&i(s.Tooltip,{label:`${u.length} selected`,children:i(s.Badge,{children:u.length})})]}),i(Ra,{disabled:e,allowClear:!0,treeCheckStrictly:g,className:C(m.root,"check-select"),dropdownClassName:C(m.dropdown,""),onDropdownVisibleChange:D,transitionName:"rc-tree-select-dropdown-slide-up",choiceTransitionName:"rc-tree-select-selection__choice-zoom",style:o,treeLine:!0,clearIcon:()=>i(s.CloseButton,{}),switcherIcon:S1,treeIcon:k1,maxTagTextLength:10,value:u,treeData:d,notFoundContent:i(Ro,{errorMessage:f}),treeNodeFilterProp:"filterBasis",treeCheckable:!0,showCheckedStrategy:Ra.SHOW_PARENT,onChange:c,onSelect:console.log,maxTagCount:0,maxTagPlaceholder:P=>`${P.length} selected`})]})},I1=k.observer(({label:e,config:t,value:n,onChange:r})=>{const{treeData:a,treeDataLoading:o,errorMessage:l}=t,u=t.min_width?t.min_width:"200px",d=!!t.options_query_id?o:!1;return i(D1,{disabled:d,style:{minWidth:"160px",width:u,maxWidth:d?u:"unset",borderColor:"#e9ecef"},value:n,onChange:f=>r(f,!1),treeData:a,errorMessage:l,label:e,required:t.required,treeCheckStrictly:t.treeCheckStrictly})}),M1=k.observer(({filter:{type:e,config:t,key:n,...r},formFieldProps:a})=>{switch(e){case"select":return i(x1,{...r,...a,config:t});case"multi-select":return i(b1,{...r,...a,config:t});case"tree-select":return i(I1,{...r,...a,config:t});case"text-input":return i(w1,{...r,...a,config:t});case"date-range":return i(jo,{...r,...a,config:t});case"checkbox":return i(g1,{...r,...a,config:t});default:return null}}),A1=k.observer(y.forwardRef(({filter:e,...t},n)=>i("div",{className:"filter-root",ref:n,children:i(Fe,{children:i(M1,{filter:e,formFieldProps:t})})})));function z1(e){const t=le();y.useEffect(()=>{var n,r;(r=(n=t.filters).updatePreviewValues)==null||r.call(n,e)},[e])}const Yo=k.observer(function({view:t}){const n=we(),{control:r,handleSubmit:a,reset:o}=v.useForm({defaultValues:n.filters.values,reValidateMode:"onBlur"}),l=v.useWatch({control:r});y.useEffect(()=>{o(n.filters.values)},[n.filters.values,o]),z1(l);const u=n.filters.visibleInView(t.id),c=y.useMemo(()=>u.every(g=>g.should_auto_submit),[u]),d=y.useMemo(()=>u.filter(g=>x.get(g,"config.required",!1)),[u]),f=y.useMemo(()=>d.length===0?!1:d.some(g=>!g.requiredAndPass(l[g.key])),[l,d]);if(u.length===0)return null;const h=(g,m)=>(C,w)=>{m(C),(g.should_auto_submit||w)&&n.filters.setValueByKey(g.key,C)};return i("form",{onSubmit:a(n.filters.setValues),children:p(s.Group,{className:"dashboard-filters",position:"apart",noWrap:!0,sx:c?{}:{border:"1px solid #e9ecef",borderRadius:"4px",padding:"16px"},children:[i(s.Group,{align:"flex-start",children:u.map(g=>i(v.Controller,{name:g.key,control:r,render:({field:m})=>i(A1,{filter:g,value:m.value,onChange:h(g,m.onChange)})},g.id))}),!c&&i(s.Group,{sx:{alignSelf:"flex-end"},children:i(s.Button,{color:"blue",size:"sm",type:"submit",disabled:f,children:"Search"})})]})})}),E1={viewPanelInFullScreen:x.noop,inFullScreen:!1},tr=y.createContext(E1),Qo=b.types.model("MockContextMeta",{current:b.types.optional(b.types.frozen(),{})}).views(e=>({get keys(){return Object.keys(e.current)},get entries(){return Object.entries(e.current)}})).actions(e=>({replace(t){e.current=t},get(t){return e.current[t]},set(t,n){e.current[t]=n}}));function Uo(e){return{current:e}}const $1=b.types.model("PanelLayoutMeta",{x:b.types.number,y:b.types.maybeNull(b.types.number),w:b.types.number,h:b.types.number,moved:b.types.optional(b.types.boolean,!1),static:b.types.optional(b.types.boolean,!1)}).views(e=>({get json(){const{x:t,y:n,w:r,h:a,moved:o}=e;return{h:a,w:r,x:t,y:n===null?0:n,moved:o,static:e.static}}})).actions(e=>({set(t){const{x:n,y:r,w:a,h:o,moved:l}=t;e.x=n,e.y=r,e.w=a,e.h=o,e.moved=!!l,e.static=!!t.static},setWidth(t){e.w=t},setHeight(t){e.h=t}})),L1=b.types.model("PanelStyleBorderMeta",{enabled:b.types.boolean}).views(e=>({get json(){const{enabled:t}=e;return{enabled:t}}})).actions(e=>({setEnabled(t){e.enabled=t}})),O1=b.types.model("PanelStyleMeta",{border:L1}).views(e=>({get json(){const{border:t}=e;return{border:t.json}}})).actions(e=>({})),P1=b.types.model("VariableMeta",{name:b.types.string,size:b.types.string,weight:b.types.string,color:b.types.union(b.types.model({type:b.types.literal("static"),staticColor:b.types.string}),b.types.model({type:b.types.literal("continuous"),valueRange:b.types.array(b.types.number),colorRange:b.types.array(b.types.string)}),b.types.model({type:b.types.literal("piecewise")})),formatter:b.types.model({output:b.types.enumeration("Output",["number","percent"]),average:b.types.optional(b.types.boolean,!1),mantissa:b.types.number,trimMantissa:b.types.optional(b.types.boolean,!1)}),data_field:b.types.string,aggregation:b.types.union(b.types.model({type:b.types.enumeration(["none","sum","mean","median","min","max","CV","std"]),config:b.types.frozen()}),b.types.model({type:b.types.literal("quantile"),config:b.types.model({p:b.types.number})}),b.types.model({type:b.types.literal("custom"),config:b.types.model({func:b.types.string})}))}).views(e=>({get json(){const{name:t,size:n,weight:r,color:a,formatter:o,data_field:l,aggregation:u}=e;return x.cloneDeep({name:t,size:n,color:a,weight:r,formatter:o,data_field:l,aggregation:u})}})),B1=b.types.model("PanelVizMeta",{type:b.types.string,conf:b.types.frozen()}).views(e=>({get json(){return{conf:e.conf,type:e.type}}})).actions(e=>({setType(t){e.type=t},setConf(t){e.conf=t}})),V1=b.types.model({id:b.types.string,title:b.types.string,description:b.types.string,layout:$1,queryIDs:b.types.array(b.types.string),viz:B1,style:O1,variables:b.types.optional(b.types.array(P1),[])}).views(e=>({get json(){const{id:t,title:n,description:r,queryIDs:a}=e;return{id:t,viz:e.viz.json,style:e.style.json,title:n,layout:e.layout.json,queryIDs:[...a],variables:e.variables.map(o=>o.json),description:r}},get queryIDSet(){return new Set(e.queryIDs)}})).actions(e=>({setID(t){e.id=t},setTitle(t){e.title=t},setDescription(t){e.description=t},addQueryID(t){e.queryIDSet.has(t)||e.queryIDs.push(t)},removeQueryID(t){if(!e.queryIDSet.has(t))return;const n=new Set(e.queryIDSet);n.delete(t),e.queryIDs=b.cast(Array.from(n))},setQueryIDs(t){e.queryIDs=b.cast(t)},addVariable(t){e.variables.push(t)},removeVariable(t){e.variables.remove(t)}})),nr=e=>x.cloneDeepWith(e,(t,n)=>{if(n!==void 0&&t)return te.toJS(t)});var Se=(e=>(e.Postgresql="postgresql",e.MySQL="mysql",e.HTTP="http",e))(Se||{});const N1=b.types.model("QueryMeta",{id:b.types.string,name:b.types.string,type:b.types.enumeration("DataSourceType",[Se.Postgresql,Se.MySQL,Se.HTTP]),key:b.types.string,sql:b.types.string,pre_process:b.types.optional(b.types.string,""),post_process:b.types.optional(b.types.string,""),run_by:b.types.optional(b.types.array(b.types.string),[]),react_to:b.types.optional(b.types.array(b.types.string),[])}).views(e=>({get valid(){return e.id&&e.type&&e.key&&e.name?e.type===Se.HTTP?!!e.pre_process:!!e.sql:!1},get json(){const{id:t,name:n,type:r,key:a,sql:o,run_by:l,react_to:u,pre_process:c,post_process:d}=e;return nr({id:t,key:a,sql:o,name:n,type:r,run_by:l,react_to:u,pre_process:c,post_process:d})}})).actions(e=>({setName(t){e.name=t},setKey(t){e.key=t},setType(t){e.type=t},setSQL(t){e.sql=t},setRunBy(t){e.run_by.length=0,e.run_by.push(...t)},setReactTo(t){e.react_to.length=0,e.react_to.push(...t)},setPreProcess(t){e.pre_process=t},setPostProcess(t){e.post_process=t}})),q1=b.types.model("SQLSnippetMeta",{key:b.types.string,value:b.types.string}).views(e=>({get json(){const{key:t,value:n}=e;return{key:t,value:n}}})).actions(e=>({setKey(t){e.key=t},setValue(t){e.value=t}}));var _e=(e=>(e.Select="select",e.MultiSelect="multi-select",e.TreeSelect="tree-select",e.TextInput="text-input",e.Checkbox="checkbox",e.DateRange="date-range",e))(_e||{});const Ko=b.types.model("FilterCheckboxConfigMeta",{_name:b.types.literal("checkbox"),description:b.types.optional(b.types.string,""),default_value:b.types.boolean}).views(e=>({get json(){const{_name:t,description:n,default_value:r}=e;return{_name:t,description:n,default_value:r}},get isDescriptionEmpty(){const{description:t}=e;return t===""||t==="<p></p>"}})).actions(e=>({setDefaultValue(t){e.default_value=t},setDescription(t){e.description=t}})),F1=()=>Ko.create({_name:"checkbox",description:"",default_value:!1});function Xo(e,t){return e.map(n=>{try{return n?Y.tz(n,"UTC").format(t):null}catch{return console.log(`[date-range] failed parsing ${n}`),null}})}const G1=b.types.model("FilterDateRangeConfigMeta",{_name:b.types.literal("date-range"),required:b.types.boolean,inputFormat:b.types.enumeration("DateRangeInputFormat",["YYYY","YYYYMM","YYYYMMDD","YYYY-MM","YYYY-MM-DD"]),default_value:b.types.optional(b.types.array(b.types.union(b.types.string,b.types.null)),[null,null]),clearable:b.types.boolean,max_days:b.types.optional(b.types.number,0),allowSingleDateInRange:b.types.optional(b.types.boolean,!1)}).views(e=>({get json(){const{_name:t,max_days:n,required:r,clearable:a,inputFormat:o,default_value:l,allowSingleDateInRange:u}=e;return{_name:t,max_days:n,required:r,clearable:a,inputFormat:o,default_value:Xo(l,o),allowSingleDateInRange:u}},truthy(t){return Array.isArray(t)&&t.length===2&&t.every(n=>!!n)}})).views(e=>({getMaxDate(t){const{max_days:n}=e;if(!(!n||!t))return Y(t).startOf("day").add(n,"days").toDate()},getMinDate(t){const{max_days:n}=e;if(!(!n||!t))return Y(t).startOf("day").subtract(n,"days").toDate()}})).actions(e=>({setFilterValue(t){try{const n=b.getParent(e);b.getRoot(e).filters.setValueByKey(n.key,t)}catch(n){console.error(n)}}})).actions(e=>({setRequired(t){e.required=t},setClearable(t){e.clearable=t},setInputFormat(t){e.inputFormat=t},setDefaultValue(t){e.default_value.length=0,e.default_value.push(...t),e.setFilterValue(t)},setMaxDays(t){e.max_days=t,t>0&&(e.clearable=!0)},setAllowSingleDateInRange(t){e.allowSingleDateInRange=t}})),Jo=b.types.snapshotProcessor(G1,{preProcessor({default_value:e,...t}){return{...t,default_value:e.map(n=>n===null?null:Y.tz(n,"UTC").toISOString())}},postProcessor(e){const{default_value:t,...n}=e;return{...n,default_value:Xo(t,n.inputFormat)}}}),W1=()=>Jo.create({_name:"date-range",required:!1,inputFormat:"YYYY-MM-DD",clearable:!1,default_value:[null,null]}),j1=b.types.model({label:b.types.string,value:b.types.string}).actions(e=>({setLabel(t){e.label=t},setValue(t){e.value=t}})),ki=b.types.model("FilterConfigModel_BaseSelect",{static_options:b.types.optional(b.types.array(j1),[]),options_query_id:b.types.optional(b.types.string,""),default_selection_count:b.types.optional(b.types.number,0),required:b.types.optional(b.types.boolean,!1)}).views(e=>({get usingQuery(){return!!e.options_query_id}})).views(e=>({get options(){if(!e.usingQuery)return e.static_options;const{data:t,state:n,error:r}=b.getRoot(e).content.getDataStuffByID(e.options_query_id);return n==="idle"?t:[]}})).actions(e=>({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??""}})),Zo=b.types.compose("FilterMultiSelectConfigMeta",b.types.model({_name:b.types.literal("multi-select"),min_width:b.types.optional(b.types.string,""),default_value:b.types.optional(b.types.array(b.types.string),[])}),ki).views(e=>({get json(){const{_name:t,default_value:n,required:r,min_width:a,static_options:o,options_query_id:l,default_selection_count:u}=e;return nr({_name:t,required:!!r,min_width:a,default_value:n,static_options:o,options_query_id:l,default_selection_count:u})},get default_selection(){return e.usingQuery?e.options.slice(0,e.default_selection_count).map(t=>t.value):e.default_value},truthy(t){return Array.isArray(t)&&t.length>0}})).actions(e=>({setDefaultValue(t){e.default_value=b.cast(t)},setMinWidth(t){e.min_width=t},setDefaultSelection(){const t=b.getRoot(e).content.filters,n=b.getParent(e).key;t.setValueByKey(n,e.default_selection)}})).actions(e=>({afterCreate(){b.addDisposer(e,te.reaction(()=>te.toJS(e.default_selection),e.setDefaultSelection,{fireImmediately:!0,delay:0}))}})),R1=()=>Zo.create({_name:"multi-select",default_value:[],static_options:[],options_query_id:"",default_selection_count:0}),Ho=b.types.compose("FilterConfigModel_Select",b.types.model({_name:b.types.literal("select"),default_value:b.types.string,width:b.types.optional(b.types.string,"")}),ki).views(e=>({get json(){const{_name:t,default_value:n,required:r,width:a,static_options:o,options_query_id:l,default_selection_count:u}=e;return nr({_name:t,width:a,required:r,default_value:n,static_options:o,options_query_id:l,default_selection_count:u})},truthy(t){return!!t},getSelectOption(t){return e.options.find(n=>n.value===t)},get default_selection(){return e.usingQuery?e.default_selection_count>0&&e.options.length>0?e.options[0].value:"":e.default_value}})).actions(e=>({setDefaultValue(t){e.default_value=t},setWidth(t){e.width=t},setDefaultSelection(){const t=b.getRoot(e).content.filters,n=b.getParent(e).key;t.setValueByKey(n,e.default_selection)}})).actions(e=>({afterCreate(){b.addDisposer(e,te.reaction(()=>te.toJS(e.default_selection),e.setDefaultSelection,{fireImmediately:!0,delay:0}))}})),Y1=()=>Ho.create({_name:"select",required:!1,default_value:"",static_options:[],options_query_id:"",default_selection_count:0}),el=b.types.model("FilterTextInputConfigMeta",{_name:b.types.literal("text-input"),required:b.types.boolean,default_value:b.types.string}).views(e=>({get json(){const{_name:t,required:n,default_value:r}=e;return{_name:t,required:n,default_value:r}},truthy(t){return typeof t!="string"?!1:!!t.trim()}})).actions(e=>({setRequired(t){e.required=t},setDefaultValue(t){e.default_value=t}})),tl=()=>el.create({_name:"text-input",required:!1,default_value:""});function Q1(e){return $u.arrayToTree(e,{id:"value",parentId:"parent_value",childrenField:"children",dataField:null})}function U1(e){return e.map(t=>{const{label:n,description:r,...a}=t,o={...a,filterBasis:`${n}___${r??""}`,description:r,label:n};return r&&(o.label=y.createElement("div",{},[y.createElement(s.Text,{key:0,title:t.label},t.label),y.createElement(s.Text,{key:1,className:"rc-tree-select-tree-title-desc",color:"dimmed",title:t.description},t.description)])),o})}const nl=b.types.compose("FilterTreeSelectConfigMeta",b.types.model({_name:b.types.literal("tree-select"),min_width:b.types.optional(b.types.string,""),default_value:b.types.optional(b.types.array(b.types.string),[]),treeCheckStrictly:b.types.optional(b.types.boolean,!1)}),ki).views(e=>({get json(){const{_name:t,default_value:n,required:r,min_width:a,static_options:o,options_query_id:l,default_selection_count:u}=e;return{_name:t,required:!!r,min_width:a,default_value:n,static_options:o,options_query_id:l,default_selection_count:u}},get treeData(){const{data:t}=b.getRoot(e).content.getDataStuffByID(e.options_query_id),n=U1(t);return Q1(n)},get errorMessage(){const{error:t}=b.getRoot(e).content.getDataStuffByID(e.options_query_id);return t},get treeDataLoading(){const{state:t}=b.getRoot(e).content.getDataStuffByID(e.options_query_id);return t==="loading"},get defaultSelection(){const{default_selection_count:t}=e;return t?this.treeData.slice(0,t).map(r=>r.value):[]},truthy(t){return Array.isArray(t)&&t.length>0}})).actions(e=>({setDefaultValue(t){e.default_value=b.cast(t)},setMinWidth(t){e.min_width=t},setTreeCheckStrictly(t){e.treeCheckStrictly=t},applyDefaultSelection(){const t=b.getParent(e,1).key;b.getRoot(e).content.filters.setValueByKey(t,e.defaultSelection)},afterCreate(){b.addDisposer(e,te.reaction(()=>JSON.stringify(e.defaultSelection),this.applyDefaultSelection,{fireImmediately:!0,delay:0}))}})),K1=()=>nl.create({_name:"tree-select",default_value:[],static_options:[],options_query_id:"",default_selection_count:0}),rl=b.types.model("FilterMeta",{id:b.types.identifier,key:b.types.string,label:b.types.string,order:b.types.number,visibleInViewsIDs:b.types.array(b.types.string),auto_submit:b.types.optional(b.types.boolean,!1),type:b.types.enumeration("DashboardFilterType",[_e.Select,_e.MultiSelect,_e.TreeSelect,_e.TextInput,_e.Checkbox,_e.DateRange]),config:b.types.union(Ho,Zo,nl,el,Ko,Jo)}).views(e=>({get plainDefaultValue(){const t=e.config.default_value;return Array.isArray(t)?[...t]:t},get usingDefaultValue(){return e.type!==_e.TreeSelect},get auto_submit_supported(){return[_e.Select,_e.Checkbox,_e.DateRange].includes(e.type)}})).views(e=>({get json(){const{id:t,key:n,label:r,order:a,visibleInViewsIDs:o,auto_submit:l,type:u,config:c}=e;return{id:t,key:n,type:u,label:r,order:a,config:c.json,auto_submit:l,visibleInViewsIDs:te.toJS(o)}},get visibleInViewsIDSet(){return new Set(e.visibleInViewsIDs)},get should_auto_submit(){return e.auto_submit_supported&&e.auto_submit},requiredAndPass(t){return x.get(e.config,"required",!1)?x.get(e.config,"truthy",()=>!0)(t):!1}})).actions(e=>({setKey(t){e.key=t},setLabel(t){e.label=t},setOrder(t){e.order=t},setType(t){switch(t){case _e.Select:e.config=Y1();break;case _e.MultiSelect:e.config=R1();break;case _e.TreeSelect:e.config=K1();break;case _e.TextInput:e.config=tl();break;case _e.Checkbox:e.config=F1();break;case _e.DateRange:e.config=W1();break}e.type=t},setVisibleInViewsIDs(t){e.visibleInViewsIDs.length=0,e.visibleInViewsIDs.push(...t)},setAutoSubmit(t){e.auto_submit=e.auto_submit_supported&&t}}));var j=(e=>(e.Division="div",e.Modal="modal",e.Tabs="tabs",e))(j||{});const il=b.types.model("ViewDivisionConfig",{_name:b.types.literal(j.Division)}).views(e=>({get json(){const{_name:t}=e;return{_name:t}}})),X1=()=>il.create({_name:j.Division}),J1=b.types.model("CustomModalTitleModel",{enabled:b.types.optional(b.types.boolean,!1),func_content:b.types.optional(b.types.string,"")}).views(e=>({get json(){const{enabled:t,func_content:n}=e;return{enabled:t,func_content:n}},get value(){const{enabled:t,func_content:n}=e,r=b.getParent(e,2),a=b.getRoot(e);if(!t)return r.name;try{const o={filters:a.content.filters.values,context:a.context.current};return new Function(`return ${n}`)()(o)}catch(o){return console.error(o),r.name}}})).actions(e=>({setEnabled(t){e.enabled=t},setFuncContent(t){e.func_content=t},replace({enabled:t,func_content:n}){e.enabled=t,e.func_content=n}})),Ti={enabled:!1,func_content:["function text({ filters, context}) {"," // your code goes here",' return "text"',"}"].join(`
440
- `)},al=b.types.model("ViewModalConfig",{_name:b.types.literal(j.Modal),width:b.types.string,height:b.types.string,custom_modal_title:b.types.optional(J1,Ti)}).views(e=>({get json(){const{_name:t,width:n,height:r,custom_modal_title:a}=e;return{_name:t,width:n,height:r,custom_modal_title:a.json}}})).actions(e=>({setWidth(t){e.width=t},setHeight(t){e.height=t}})),Z1=()=>al.create({_name:j.Modal,width:"90vw",height:"90vh"}),H1=b.types.model("ViewTabsTabModel",{id:b.types.identifier,name:b.types.string,view_id:b.types.string,color:b.types.optional(b.types.string,"")}).views(e=>({get json(){const{id:t,name:n,view_id:r,color:a}=e;return{id:t,name:n,color:a,view_id:r}}})).actions(e=>({setName(t){e.name=t},setViewID(t){e.view_id=t},setColor(t){e.color=t}})),sl=b.types.model("ViewTabsConfig",{_name:b.types.literal(j.Modal),tabs:b.types.optional(b.types.array(H1),[]),variant:b.types.optional(b.types.enumeration("variant",["default","outline","pills"]),"default"),orientation:b.types.optional(b.types.enumeration("orientation",["horizontal","vertical"]),"horizontal"),grow:b.types.optional(b.types.boolean,!1)}).views(e=>({get json(){const{_name:t,variant:n,orientation:r,tabs:a,grow:o}=e;return{grow:o,tabs:a.map(l=>l.json),_name:t,variant:n,orientation:r}}})).actions(e=>({setVariant(t){e.variant=t},setOrientation(t){e.orientation=t},setGrow(t){e.grow=t},setTabs(t){e.tabs.length=0,e.tabs=b.cast(t)},addTab(){const t=Ie.randomId(),n={id:t,name:t,view_id:""};e.tabs.push(n)},removeTab(t){e.tabs.splice(t,1)}})),eS=()=>sl.create({_name:j.Modal,tabs:[]}),tS=b.types.model({id:b.types.identifier,name:b.types.string,type:b.types.enumeration("EViewComponentType",[j.Division,j.Modal,j.Tabs]),config:b.types.union(il,al,sl),panelIDs:b.types.optional(b.types.array(b.types.string),[])}).views(e=>({get json(){const{id:t,name:n,type:r,config:a}=e;return{id:t,name:n,type:r,config:a.json,panelIDs:e.panelIDs}}})).actions(e=>({setName(t){e.name=t},setType(t){if(e.type!==t){switch(t){case j.Division:e.config=X1();break;case j.Modal:e.config=Z1();break;case j.Tabs:e.config=eS();break}e.type=t}},appendPanelID(t){e.panelIDs.push(t)},removePanelID(t){const n=e.panelIDs.filter(r=>r!==t);e.panelIDs.length=0,e.panelIDs.push(...n)}})),ol=b.types.model("DataSourceMetaModel",{id:b.types.string,type:b.types.enumeration("DataSourceType",[Se.HTTP,Se.MySQL,Se.Postgresql]),key:b.types.string,config:b.types.frozen()}),nS=b.types.model("DataSourcesMetaModel",{list:b.types.optional(b.types.array(ol),[])}).views(e=>({find({type:t,key:n}){return e.list.find(r=>r.key===n&&r.type===t)},get options(){return e.list.map(t=>({value:t.key,label:t.key}))}})).actions(e=>({replace(t){e.list.length=0,e.list.push(...t)}})),rS=b.types.model({id:b.types.string,content:b.types.string,create_time:b.types.string,update_time:b.types.string,is_preset:b.types.boolean}),ll=b.types.model("GlobalSQLSnippetsMeta",{list:b.types.optional(b.types.array(rS),[])}).views(e=>({find(t){return e.list.find(n=>n.id===t)},get options(){return e.list.map(t=>({value:t.id,label:t.id}))}})).actions(e=>({replace(t){e.list.length=0,e.list.push(...t)}})),Di=b.types.model("ContextMeta",{current:b.types.optional(b.types.frozen(),{})}).views(e=>({get keys(){return Object.keys(e.current)},get entries(){return Object.entries(e.current)}})).actions(e=>({replace(t){e.current=t},get(t){return e.current[t]},set(t,n){e.current[t]=n}}));function ul(e){return Di.create({current:e})}const iS=b.types.compose("ViewRenderModel",tS,b.types.model({tab:b.types.optional(b.types.string,"")})).views(e=>({get defaultTab(){if(e.type!==j.Tabs)return"";const t=e.config;return t.tabs.length>0?t.tabs[0].id:""},get tabViewID(){var n;return e.type!==j.Tabs?"":((n=e.config.tabs.find(r=>r.id===e.tab))==null?void 0:n.view_id)??""},get contentModel(){return b.getParent(e,3)},get panels(){if(e.type!==j.Tabs)return this.contentModel.panels.panelsByIDs(e.panelIDs).panels;const t=this.tabViewID;return this.contentModel.views.findByID(t).panels},get renderViewIDs(){const t=[e.id];return e.type===j.Tabs&&t.push(this.tabViewID),t}})).actions(e=>({setTab(t){e.tab=t??""},afterCreate(){b.addDisposer(e,te.reaction(()=>e.defaultTab,t=>this.setTab(t),{fireImmediately:!0,delay:0}))}})),cl=b.types.model("ViewsRenderModel",{current:b.types.optional(b.types.array(iS),[]),visibleViewIDs:b.types.array(b.types.string)}).views(e=>({get json(){return e.current.map(t=>nr(t.json))},get idMap(){const t=new Map;return e.current.forEach(n=>{t.set(n.id,n)}),t},findByID(t){return e.current.find(n=>n.id===t)},get firstVisibleView(){const[t]=e.visibleViewIDs;return e.current.find(({id:n})=>n===t)},get visibleViews(){const t=new Set(e.visibleViewIDs);return e.current.filter(({id:n})=>t.has(n))}})).actions(e=>({appendToVisibles(t){new Set(e.visibleViewIDs.map(r=>r)).has(t)||e.visibleViewIDs.push(t)},rmVisibleViewID(t){const n=e.visibleViewIDs.findIndex(r=>r===t);n!==-1&&e.visibleViewIDs.splice(n,1)}}));function aS(e){const t=e.length>0?[e[0].id]:[];return{current:e.map(r=>{const{_name:a=r.type}=r.config;return{...r,config:{...r.config,_name:a},panelIDs:r.panelIDs}}),visibleViewIDs:t}}const dl=V1.views(e=>({get contentModel(){return b.getRoot(e).content}})).views(e=>({get queries(){return e.contentModel.queries.findByIDSet(e.queryIDSet)},get data(){return this.queries.reduce((t,n)=>(t[n.id]=n.data,t),{})},get dataLoading(){return this.queries.some(t=>t.state==="loading")},get queryStateMessages(){const t=this.queries.filter(o=>!o.runByConditionsMet);if(t.length===0)return"";const n=new Set,r=new Set;t.forEach(o=>{const l=o.conditionNames;l.context.forEach(u=>n.add(u)),l.filters.forEach(u=>r.add(u))});const a=[];return n.size>0&&(console.log(n),a.push(`context: ${Array.from(n).join(", ")}`)),r.size>0&&a.push(`filter${r.size>1?"s":""}: ${Array.from(r).join(", ")}`),a.length===2&&a.splice(1,0,"and"),a.unshift("Waiting for"),a.join(" ")},get queryErrors(){return this.queries.map(t=>t.error).filter(t=>!!t)},get canRenderViz(){return this.queryErrors.length===0&&this.queryStateMessages===""&&!this.dataLoading}})).actions(e=>({refreshData(){e.queries.forEach(t=>t.fetchData())},downloadData(){b.getRoot(e).content.queries.downloadDataByQueryIDs(e.queryIDs)}}));function sS(e){return{id:e,layout:{x:0,y:1/0,w:18,h:300},title:e,description:"<p></p>",queryIDs:[],viz:{type:hi.name,conf:hi.createConfig()},style:{border:{enabled:!0}}}}const pl=b.types.model("PanelsRenderModel",{list:b.types.optional(b.types.array(dl),[])}).views(e=>({get json(){return e.list.map(t=>t.json)},findByID(t){return e.list.find(n=>n.id===t)},get idMap(){const t=new Map;return e.list.forEach(n=>{t.set(n.id,n)}),t}})).views(e=>({panelsByIDs(t){const n=[];t.forEach(a=>{const o=e.idMap.get(a);o?n.push(o):console.warn(`Panel is not found, id:${a}`)});const r=n.map(a=>({...a.layout.json,i:a.id}));return{panels:n,layouts:r}}}));function hl(e,t){if(e===void 0)return e;if(t._name==="date-range")try{const[...n]=e;return n.map(r=>r===null?r:Y.tz(r,"UTC").format(t.inputFormat)??r)}catch(n){return console.error(n),e}return e}function oS(e){return e.reduce((t,n)=>(t[n.key]=hl(n.config.default_value,n.config),t),{})}const fl=b.types.model("FiltersRenderModel",{current:b.types.optional(b.types.array(rl),[]),values:b.types.optional(b.types.frozen(),{})}).views(e=>({get json(){return e.current.map(t=>t.json)},get firstID(){if(e.current.length!==0)return e.current[0].id},findByID(t){return e.current.find(n=>n.id===t)},get inOrder(){return x.sortBy(e.current,"order")},get empty(){return e.current.length===0},visibleInView(t){return x.sortBy(e.current.filter(n=>n.visibleInViewsIDSet.has(t)),"order")},get firstFilterValueKey(){return Object.keys(e.values)[0]??""},get keyLabelMap(){return e.current.reduce((t,n)=>(t[n.key]=n.label,t),{})},getSelectOption(t){const n=this.findByID(t);if(!n||!("getSelectOption"in n.config))return null;const r=e.values[n.key];return n.config.getSelectOption(r)}})).actions(e=>({setValues(t){e.values=t},setValueByKey(t,n){e.values={...e.values,[t]:n}},getValueByKey(t){return e.values[t]}}));function gl(e){return{current:e,values:oS(e)}}const lS=N1.views(e=>({get conditionOptions(){if(!b.isAlive(e))return[];const t=b.getRoot(e).content,{context:n}=t.payloadForSQL,r=Object.keys(n).map(o=>({group:"Context",label:o,value:`context.${o}`,description:void 0})),a=t.filters.keyLabelOptions.map(o=>({group:"Filters",label:o.label,value:`filters.${o.value}`,description:o.value}));return[...r,...a]},get unmetRunByConditions(){if(!b.isAlive(e))return[];const{run_by:t}=e;if(t.length===0)return[];const n=b.getRoot(e).content.payloadForSQL;return t.filter(r=>{const a=x.get(n,r);return Array.isArray(a)?a.length===0:typeof a=="number"?Number.isNaN(a):!a})}})).views(e=>({get reQueryKey(){const{react_to:t=[]}=e;if(t.length===0)return"";const n=b.getRoot(e).content.payloadForSQL,r=[...t].reduce((a,o)=>(a[o]=x.get(n,o),a),{});return JSON.stringify(r)},get runByConditionsMet(){return e.unmetRunByConditions.length===0},get conditionNames(){if(e.unmetRunByConditions.length===0)return{context:[],filters:[]};const{keyLabelMap:t}=b.getRoot(e).content.filters,n=e.unmetRunByConditions.filter(a=>a.startsWith("context.")).map(a=>a.split("context.")[0]),r=e.unmetRunByConditions.filter(a=>a.startsWith("filters.")).map(a=>x.get({filters:t},a)).filter(a=>!!a);return{context:n,filters:r}},get queries(){return b.getParent(e,2)},get inUse(){return this.queries.isQueryInUse(e.id)}}));function uS(e,t){return new Function(`return ${e}`)()(t,Tt)}function cS(e,t,n){return uS(e,{context:t,filters:n})}function dS(e,t){try{return new Function(`return ${e.config.processing.pre}`)()(t,Tt)}catch(n){return console.error(n),t}}function pS(e,t){return new Function(`return ${e.config.processing.post}`)()(t,Tt)}function hS(e,t){return e?new Function(`return ${e}`)()(t,Tt):t}const fS=b.types.compose("QueryRenderModel",lS,b.types.model({state:b.types.optional(b.types.enumeration(["idle","loading","error"]),"idle"),data:b.types.optional(b.types.frozen([]),[]),error:b.types.frozen()})).views(e=>({get formattedSQL(){const t=b.getRoot(e).content.payloadForSQL;return gr(e.sql,t)},get typedAsSQL(){return[Se.Postgresql,Se.MySQL].includes(e.type)},get typedAsHTTP(){return[Se.HTTP].includes(e.type)},get datasource(){const{key:t,type:n}=e;return b.getRoot(e).datasources.find({type:n,key:t})},get httpConfigString(){const{context:t,filters:n}=b.getRoot(e).content.payloadForSQL,{name:r,pre_process:a}=e.json,o=cS(a,t,n);return console.groupCollapsed(`Request config for: ${r}`),console.log(o),console.groupEnd(),JSON.stringify(o)}})).views(e=>({get stateMessage(){if(e.state!=="idle")return"";if(!e.runByConditionsMet){const{context:t,filters:n}=e.conditionNames;if(t.length===0&&n.length===0)return"Waiting";const r=[];return t.length>0&&r.push(`context: ${t.join(", ")}`),n.length>0&&r.push(`filter${n.length>1?"s":""}: ${n.join(", ")}`),r.length===2&&r.splice(1,0,"and"),r.unshift("Waiting for"),r.join(" ")}return e.data.length>0?"":"Empty Data"}})).volatile(()=>({controller:new AbortController})).actions(e=>({runSQL:b.flow(function*(){var t;if(!e.inUse){console.debug(`Skipping query[${e.name}]`);return}if(e.valid&&((t=e.controller)==null||t.abort(),!!e.runByConditionsMet)){e.controller=new AbortController,e.state="loading";try{const n=b.getRoot(e).content.payloadForSQL;e.data=yield*b.toGenerator(Qu({payload:n,name:e.name,query:e.json},e.controller.signal)),e.state="idle",e.error=null}catch(n){if(!mt.isCancel(n)){e.data=[];const r=x.get(n,"message","unkown error");e.error=x.get(n,"response.data.detail.message",r),e.state="error"}}}}),runHTTP:b.flow(function*(){var t;if(!e.inUse){console.debug(`Skipping query[${e.name}]`);return}if(!(!e.valid||!e.datasource)&&((t=e.controller)==null||t.abort(),!!e.runByConditionsMet)){e.controller=new AbortController,e.state="loading";try{const{type:n,key:r,post_process:a}=e.json;let o=JSON.parse(e.httpConfigString);o=dS(e.datasource,o);const l=yield*b.toGenerator(Uu({type:n,key:r,configString:JSON.stringify(o),name:e.name},e.controller.signal));let u=pS(e.datasource,l);u=hS(a,u),e.data=u,e.state="idle",e.error=null}catch(n){if(console.error(n),!mt.isCancel(n)){e.data=[];const r=x.get(n,"message","unkown error");e.error=x.get(n,"response.data.detail.message",r),e.state="error"}}}})})).actions(e=>({fetchData:()=>e.typedAsHTTP?e.runHTTP():e.runSQL(),beforeDestroy(){var t;(t=e.controller)==null||t.abort()}})).actions(e=>({afterCreate(){b.addDisposer(e,te.reaction(()=>{var t,n;return e.typedAsHTTP?`${e.inUse}--${e.id}--${e.key}--${e.reQueryKey}--${(t=e.datasource)==null?void 0:t.id}`:`${e.inUse}--${e.id}--${e.key}--${e.formattedSQL}--${e.pre_process}--${e.post_process}--${(n=e.datasource)==null?void 0:n.id}`},e.fetchData,{fireImmediately:!0,delay:0}))}})),ml="\uFEFF";function gS(e,t){const n=new Blob([ml+t],{type:"text/csv"});hr.saveAs(n,`${e}.csv`)}function yl(e,t){const n=new Blob([t],{type:"application/json"});hr.saveAs(n,`${e}.json`)}function bl(e){const t=new Lu;e.forEach(({id:n,data:r})=>{t.file(`${n}.csv`,xl(r))}),t.generateAsync({type:"blob"}).then(n=>{hr.saveAs(n,"dashboard_data.zip")})}function vl(e){return typeof e=="string"&&e.includes(",")?`"${e}"`:e}function xl(e){if(!Array.isArray(e)||e.length===0)return"";const t=[],n=Object.keys(e[0]).map(vl);return t.push(n.join(",")),e.forEach(r=>{const a=Object.values(r).map(vl).join(",");t.push(a)}),ml+t.join(`
441
- `)}const wl=b.types.model("QueriesRenderModel",{current:b.types.optional(b.types.array(fS),[])}).views(e=>({get firstID(){if(e.current.length!==0)return e.current[0].id},findByID(t){return e.current.find(n=>n.id===t)},findByIDSet(t){return e.current.filter(n=>t.has(n.id))},get json(){return e.current.filter(t=>t.id&&t.key).map(t=>t.json)},get contentModel(){return b.getParent(e,1)},get visibleQueryIDSet(){const{views:t,filters:n}=this.contentModel,r=[];t.visibleViews.forEach(l=>{l.panels.forEach(u=>{r.push(...u.queryIDs)})});const a=x.uniq(t.visibleViews.map(l=>l.renderViewIDs).flat());n.current.forEach(l=>{const u=x.get(l,"config.options_query_id");if(!u)return;a.some(d=>l.visibleInViewsIDSet.has(d))&&r.push(u)});const o=new Set(r);return console.debug("QueryIDs:",o),o},isQueryInUse(t){return this.visibleQueryIDSet.has(t)}})).actions(e=>({downloadAllData(){const t=e.current.map(({name:n,data:r})=>({id:n,data:r}));bl(t)},downloadDataByQueryIDs(t){const n=new Set(t),r=e.current.filter(a=>n.has(a.id)).map(({name:a,data:o})=>({id:a,data:o}));bl(r)},downloadDataByQueryID(t){const n=e.findByID(t);if(!n){console.log("[downloadDataByQueryID] query not found");return}const{name:r,data:a}=n,o=xl(a);gS(r,o)},refetchDataByQueryID(t){const n=e.findByID(t);if(!n){console.error(new Error(`[downloadDataByQueryID] query by ID[${t}] not found`));return}return n.fetchData()}}));function mS(e){return{current:e}}const yS=q1.views(e=>({isADuplicatedKey(t){return!t||t===e.key?!1:!!b.getParent(e,2).findByKey(t)}})),Cl=b.types.model("SQLSnippetsRenderModel",{current:b.types.optional(b.types.array(yS),[])}).views(e=>({get json(){return e.current.map(t=>t.json)},get record(){return e.current.reduce((t,n)=>(t[n.key]=n.value,t),{})},get firstKey(){if(e.current.length!==0)return e.current[0].key},findByKey(t){return e.current.find(n=>n.key===t)}}));function bS(e){return{current:e}}function rr(e,t,n,r){return e.reduce((a,o)=>{try{a[o[t]]=fr(o[n],r)}catch(l){a[o[t]]=l.message}return a},{})}class vS{constructor(t){N(this,"origin");N(this,"copy");this.origin=t,this.copy=b.clone(t),te.makeAutoObservable(this,{},{autoBind:!0,deep:!1})}get changed(){return!x.isEqual(b.getSnapshot(this.origin),b.getSnapshot(this.copy))}commit(){b.applySnapshot(this.origin,b.getSnapshot(this.copy))}update(t){b.applySnapshot(this.copy,t)}}const xS=e=>new vS(e),wS=k.observer(({view:e})=>{const t=pe(),n=le(),r=Qe.useModals(),{panel:a,downloadPanelScreenshot:o}=nt(),{id:l}=a,{viewPanelInFullScreen:u,inFullScreen:c}=y.useContext(tr),d=()=>{n.duplicatePanelByID(l,e.id)},f=()=>{t.editor.open(["_VIEWS_",e.id,"_PANELS_",l])},h=()=>r.openConfirmModal({title:"Delete this panel?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>n.removePanelByID(l,e.id),confirmProps:{color:"red"},zIndex:320}),g=y.useCallback(()=>{u(l)},[l,u]),m=!c&&e.type!==j.Modal;return i(B,{children:i(s.Box,{sx:{position:"absolute",top:0,left:0,right:0,zIndex:300},children:p(s.Menu,{withinPortal:!0,children:[i(s.Menu.Target,{children:i(s.Box,{className:"panel-dropdown-target",sx:{width:"100%",height:"25px"}})}),p(s.Menu.Dropdown,{children:[i(s.Menu.Item,{onClick:a.refreshData,icon:i(T.Refresh,{size:14}),children:"Refresh"}),i(s.Menu.Item,{onClick:a.downloadData,icon:i(T.Download,{size:14}),children:"Download Data"}),i(s.Menu.Item,{onClick:o,icon:i($.IconCamera,{size:14}),children:"Screenshot"}),m&&i(s.Menu.Item,{onClick:g,icon:i(T.ArrowsMaximize,{size:14}),disabled:!0,children:"Full Screen"}),i(s.Divider,{label:"Edit",labelPosition:"center"}),i(s.Menu.Item,{onClick:f,icon:i(T.Settings,{size:14}),children:"Settings"}),i(s.Menu.Item,{onClick:d,icon:i(T.Copy,{size:14}),children:"Duplicate"}),i(s.Menu.Item,{color:"red",onClick:h,icon:i(T.Trash,{size:14}),children:"Delete"})]})]})})})});function CS(e){return e?["<p><br></p>","<p></p>"].includes(e):!0}const Ii=k.observer(()=>{const[e,t]=y.useState(!1),{panel:n}=bt();return CS(n.description)?null:p(B,{children:[i(s.Modal,{opened:e,onClose:()=>t(!1),title:n.title,withCloseButton:!1,withinPortal:!0,zIndex:310,children:i(qn,{value:n.description,styles:{root:{border:"none"},content:{padding:0}}})}),i(s.Tooltip,{label:"Click to see description",position:"top-start",withinPortal:!0,children:i(s.ActionIcon,{variant:"subtle",color:"blue",onClick:()=>t(r=>!r),sx:{verticalAlign:"baseline",cursor:"pointer"},children:i(T.InfoCircle,{size:20})})})]})}),tM="",nM="",SS=k.observer(function(){const{panel:t}=bt(),{title:n}=t;return n?i(s.Group,{grow:!0,position:"center",px:20,className:"panel-title-wrapper",sx:{flexGrow:1},children:i(s.Text,{align:"center",lineClamp:1,weight:"bold",children:n})}):null});function _S(e){const t=y.useRef(null);return{ref:t,downloadPanelScreenshot:()=>{const r=t.current;if(!r)return;const a=r.offsetWidth*2,o=r.offsetHeight*2;Ya.toBlob(t.current,{bgcolor:"white",width:a,height:o,style:{border:"none",borderRadius:0,transformOrigin:"0 0",transform:"scale(2)"}}).then(l=>{window.saveAs(l,`${e.title?e.title:e.viz.type}.png`)})}}}var Sl=(e=>(e.migrated="migrated",e.nothingToMigrate="nothingToMigrate",e.checkFailed="checkFailed",e.migrationFailed="migrationFailed",e))(Sl||{}),ir=(e=>(e.notStarted="notStarted",e.inProgress="inProgress",e.done="done",e))(ir||{});class kS{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(Ce.instanceScope.panelModel),this.vizInstance=t.getRequired(Ce.instanceScope.vizInstance),this.operationManager=t.getRequired(Ce.instanceScope.operationManager),this.triggerManager=t.getRequired(Ce.instanceScope.triggerManager),this.vizManager=t.getRequired(Ce.vizManager)}async createMigrationTask(){const t=[];try{await this.instanceNeedMigration()&&t.push(()=>this.runInstanceMigration()),await this.interactionNeedMigration()&&t.push(()=>this.runInteractionMigration())}catch(n){return console.warn("check migration failed",n),"checkFailed"}if(t.length===0)return"nothingToMigrate";try{return await Promise.all(t.map(n=>n())),"migrated"}catch(n){return console.warn("migration failed",n),"migrationFailed"}}async runMigration(){return this.runningMigration||(this.status="inProgress",this.runningMigration=this.createMigrationTask().then(t=>(this.status="done",t))),this.runningMigration}async runInteractionMigration(){await this.operationManager.runMigration(),await this.triggerManager.runMigration()}async runInstanceMigration(){const t=this.vizManager.resolveComponent(this.vizInstance.type),n={configData:this.vizInstance.instanceData,panelModel:this.panelModel};await t.migrator.migrate(n)}async instanceNeedMigration(){const t=this.vizManager.resolveComponent(this.vizInstance.type),n={configData:this.vizInstance.instanceData};return t.migrator.needMigration(n)}async interactionNeedMigration(){return await this.operationManager.needMigration()||await this.triggerManager.needMigration()}}function _l(e){const{panel:t}=bt();return y.useCallback(n=>{const r=n.getRequired(Ce.vizManager),a=r.resolveComponent(e.viz.type);return n.createScoped().provideFactory(Ce.instanceScope.vizInstance,()=>r.getOrCreateInstance(e)).provideFactory(Ce.instanceScope.interactionManager,o=>{const l=o.getRequired(Ce.instanceScope.vizInstance);return new Dr(l,a,Dn)}).provideFactory(Ce.instanceScope.operationManager,o=>o.getRequired(Ce.instanceScope.interactionManager).operationManager).provideFactory(Ce.instanceScope.triggerManager,o=>o.getRequired(Ce.instanceScope.interactionManager).triggerManager).provideValue(Ce.instanceScope.panelModel,t).provideFactory(Ce.instanceScope.migrator,o=>new kS(o))},[e.viz.type,e.viz.conf])}function kl(e){const[t,n]=y.useState(!1),r=Wo().getRequired(Ce.instanceScope.migrator);return K.useAsyncEffect(async()=>{const a=r.status===ir.notStarted;n(r.status===ir.done),r.status===ir.notStarted&&r.runMigration().then(o=>{o===Sl.migrated&&a&&(e==null||e())}).finally(()=>{n(!0)})},[r]),t}function Tl(e,t){const n=Wo().getRequired(Ce.instanceScope.vizInstance);return y.useEffect(()=>(n.instanceData.setItem(null,t.viz.conf),n.instanceData.watchItem(null,r=>{e(r)})),[e,t.viz.type]),n}function TS({setVizConf:e,...t}){const{panel:n}=t,r=Tl(e,n),a=kl(()=>{vn.showNotification({title:`${n.title} - Updated`,message:"Your plugin configuration has been migrated to the latest version"})});return K.useAsyncEffect(async()=>{await r.instanceData.setItem(null,n.viz.conf)},[r,n.viz.type]),a?i(Zu,{...t}):i(s.Text,{children:"Checking update..."})}function DS(e){const{panel:t,setVizConf:n}=e;Tl(n,t);const{inEditMode:r}=y.useContext(kn);return kl(()=>{r&&vn.showNotification({title:`${t.title} - Updated`,message:"Your plugin configuration has been migrated to the latest version"})})?i(Ju,{...e}):i(s.Text,{children:"Checking update"})}const rM="";function IS(e,t){const{vizManager:n}=y.useContext(ut),{panel:{viz:r,title:a,id:o,description:l,queryIDs:u,variables:c}}=bt(),d={title:a,id:o,description:l,queryIDs:u,viz:r,layout:t},f=_l(d);try{return n.resolveComponent(r.type),i(er,{configure:f,children:i(DS,{setVizConf:r.setConf,panel:d,data:e,variables:c,vizManager:n})})}catch(h){return console.info(x.get(h,"message")),null}}const Dl=k.observer(function({data:t}){const{ref:n,width:r,height:a}=Ie.useElementSize(),o=IS(t,{w:r,h:a}),l=r>0&&a>0;return i("div",{className:"viz-root",ref:n,children:i(s.Box,{sx:{width:r,height:a,overflow:"hidden"},children:l&&i(Fe,{children:o})})})}),Il=k.observer(({panel:e})=>p(s.Stack,{children:[e.queryErrors.map((t,n)=>i(s.Text,{color:"red",size:"sm",align:"center",sx:{fontFamily:"monospace"},children:t},`${n}-${t}`)),i(s.Text,{color:"gray",align:"center",size:"sm",children:e.queryStateMessages})]})),Mi=k.observer(({panel:e,height:t})=>p(s.Flex,{direction:"column",sx:{height:t,position:"relative",width:"100%"},children:[i(s.LoadingOverlay,{visible:e.dataLoading,exitTransitionDuration:0}),!e.canRenderViz&&i(Il,{panel:e}),e.canRenderViz&&i(Dl,{data:e.data})]})),MS={border:"1px solid #e9ecef"},Ml=k.observer(({panel:e,panelStyle:t,dropdownContent:n})=>{const{ref:r,downloadPanelScreenshot:a}=_S(e),o=e.title?"calc(100% - 25px)":"100%";return i(Sr,{value:{panel:e,data:e.data,loading:e.dataLoading,errors:e.queryErrors,downloadPanelScreenshot:a},children:p(s.Box,{className:"panel-root",ref:r,p:0,sx:{...MS,...t},children:[i(s.Box,{sx:{position:"absolute",left:0,top:0,height:28,zIndex:310},children:i(Ii,{})}),n,i(SS,{}),i(Mi,{panel:e,height:o})]})})}),AS={border:"1px dashed transparent",transition:"border-color 300ms ease","&:hover":{borderColor:"#e9ecef"}};function zS(e){return e.style.border.enabled?{}:AS}const Al=k.observer(function({panel:t,view:n}){const r=zS(t);return i(Ml,{panel:t,panelStyle:r,dropdownContent:i(wS,{view:n})})});function ES(e){return!["richText","button"].includes(e)}const $S=k.observer(({view:e})=>{const{panel:t,downloadPanelScreenshot:n}=bt(),{id:r}=t,{viewPanelInFullScreen:a,inFullScreen:o}=y.useContext(tr),l=y.useCallback(()=>{a(r)},[r,a]),u=!o&&e.type!==j.Modal;return ES(t.viz.type)?i(s.Box,{sx:{position:"absolute",top:0,left:0,right:0,zIndex:300},children:p(s.Menu,{withinPortal:!0,children:[i(s.Menu.Target,{children:i(s.Box,{className:"panel-dropdown-target",sx:{width:"100%",height:"25px"}})}),p(s.Menu.Dropdown,{children:[i(s.Menu.Item,{onClick:t.refreshData,icon:i(T.Refresh,{size:14}),children:"Refresh"}),i(s.Menu.Item,{onClick:t.downloadData,icon:i(T.Download,{size:14}),children:"Download Data"}),i(s.Menu.Item,{onClick:n,icon:i($.IconCamera,{size:14}),children:"Screenshot"}),u&&i(s.Menu.Item,{onClick:l,icon:i(T.ArrowsMaximize,{size:14}),children:"Full Screen"})]})]})}):null});function LS(e){return e.style.border.enabled?{}:{border:"1px dashed transparent"}}const Ai=k.observer(({panel:e,view:t})=>{const n=LS(e);return i(Ml,{panel:e,panelStyle:n,dropdownContent:i($S,{view:t})})}),OS={modal:{display:"flex",flexDirection:"column",flexWrap:"nowrap"},body:{display:"flex",height:"calc(100vh - 88px)"}},zl=k.observer(function({view:t,panel:n,exitFullScreen:r}){return i(s.Modal,{opened:!0,fullScreen:!0,onClose:r,title:i(s.Button,{color:"blue",size:"xs",onClick:r,leftIcon:i(T.ArrowLeft,{size:20}),children:"Exit fullscreen"}),styles:OS,children:i(s.Group,{grow:!0,sx:{flexGrow:1,flexShrink:0},children:i(Ai,{view:t,panel:n})})})});function El(e,t,n){const{panels:r}=we(),a=e.id==="Main",[o,l]=y.useState(()=>a&&r.findByID(t)?t:null),u=y.useCallback(h=>{l(h),a&&n(h)},[a,n]),c=y.useCallback(()=>{l(null),a&&n("")},[a,n]),d=o?r.findByID(o):null;return{viewPanelInFullScreen:u,exitFullScreen:c,inFullScreen:!!d,fullScreenPanel:d}}const iM="",PS=y.forwardRef(({h:e},t)=>i(s.ActionIcon,{ref:t,className:"react-grid-customDragHandle",sx:{userSelect:"none",cursor:"grab",position:"absolute",top:5,right:e>38?5:20,zIndex:400,"&:hover":{color:"#228be6"}},variant:"transparent",children:i(T.ArrowsMove,{size:16})})),BS=y.forwardRef(({handleAxis:e,...t},n)=>i(s.ActionIcon,{ref:n,className:"react-grid-customResizeHandle",sx:{userSelect:"none",cursor:"nwse-resize",position:"absolute",bottom:0,right:0,zIndex:400,"&:hover":{color:"#228be6"}},variant:"transparent",...t,children:i(T.ChevronDownRight,{size:16})})),VS=xn.WidthProvider(xn),NS=k.observer(({view:e,className:t="layout"})=>{const n=we(),{panels:r,layouts:a}=n.panels.panelsByIDs(e.panelIDs),o=y.useCallback(u=>{u.forEach(({i:c,...d})=>{const f=n.panels.findByID(c);f&&f.layout.set(d)})},[n]),l=(u,c,d,f)=>{d.h<30&&(d.h=30,f.h=30),d.w<4&&(d.w=4,f.w=4)};return i(VS,{onLayoutChange:o,className:`dashboard-layout ${t}`,rowHeight:1,cols:36,margin:[0,0],isBounded:!0,isDraggable:!0,isResizable:!0,layout:a,draggableHandle:".react-grid-customDragHandle",resizeHandle:i(BS,{}),onResize:l,children:r.map((u,c)=>p("div",{"data-grid":{...u.layout},className:"panel-grid-item",children:[i(PS,{h:u.layout.h}),i(Al,{view:e,panel:u})]},u.id))})}),qS=xn.WidthProvider(xn),FS=k.observer(function({view:t,className:n="layout"}){const{panels:r,layouts:a}=we().panels.panelsByIDs(t.panelIDs);return i(qS,{className:`dashboard-layout ${n}`,cols:36,rowHeight:1,margin:[0,0],isDraggable:!1,isResizable:!1,layout:a,children:r.map(o=>i("div",{"data-grid":{...o.layout},className:"panel-grid-item",children:i(Ai,{view:t,panel:o})},o.id))})});function zi(e){const t=y.useRef(null);return{ref:t,downloadScreenshot:()=>{var l;const r=(l=t.current)==null?void 0:l.querySelector(".react-grid-layout");if(!r)return;const a=r.offsetWidth*2+10,o=r.offsetHeight*2+10;Ya.toBlob(r,{bgcolor:"white",width:a,height:o,style:{transformOrigin:"0 0",transform:"scale(2)"}}).then(u=>{window.saveAs(u,`${e.name}.png`)})}}}const GS=k.observer(({downloadScreenShot:e})=>{const[t,{setTrue:n,setFalse:r}]=K.useBoolean(!1),a=wr(),o=we(),l=()=>{const u=JSON.stringify(o.json,null,2),c=`${a.name}__${o.name}`;yl(c,u)};return p(s.Menu,{shadow:"md",width:200,trigger:"hover",openDelay:200,closeDelay:400,withinPortal:!0,position:"bottom-end",children:[i(s.Menu.Target,{children:i(s.Affix,{position:{bottom:"20px",right:"10px"},zIndex:1,children:i(s.ActionIcon,{size:"md",variant:"gradient",gradient:{from:"indigo",to:"cyan"},onMouseEnter:n,onMouseLeave:r,sx:{opacity:t?1:.6,transform:`translateX(${t?0:"2px"})`,transition:"all ease 300ms",borderRadius:"50%"},children:i($.IconShare3,{size:"1rem"})})})}),p(s.Menu.Dropdown,{children:[i(s.Menu.Item,{icon:i($.IconCamera,{size:14}),onClick:e,children:"Screenshot"}),i(s.Menu.Divider,{}),i(s.Menu.Item,{icon:i($.IconDownload,{size:14}),onClick:o.queries.downloadAllData,children:"Download Data"}),i(s.Menu.Item,{icon:i($.IconCode,{size:14}),onClick:l,children:"Download Schema"})]})]})}),$l=k.observer(({children:e,view:t,sx:n={}})=>{const{ref:r,downloadScreenshot:a}=zi(t);return p(B,{children:[i(s.Box,{ref:r,sx:n,children:e}),i(GS,{downloadScreenShot:a})]})}),Ll=k.observer(({downloadScreenshot:e})=>i(s.ActionIcon,{className:"download-screenshot-button",color:"blue",onClick:e,children:i($.IconCamera,{size:14})})),WS=k.observer(({children:e,view:t})=>{const n=we(),r=t.config,a=n.views.visibleViewIDs.includes(t.id),o=()=>n.views.rmVisibleViewID(t.id),{ref:l,downloadScreenshot:u}=zi(t);return i(s.Modal,{size:r.width,centered:!0,opened:a,onClose:o,withCloseButton:!1,title:p(s.Group,{position:"apart",px:"1rem",h:"48px",children:[i(s.Box,{children:r.custom_modal_title.value}),i(Ll,{downloadScreenshot:u})]}),trapFocus:!0,onDragStart:c=>{c.stopPropagation()},styles:{root:{position:"fixed",zIndex:200,inset:0},overlay:{zIndex:"unset"},inner:{zIndex:"unset",padding:"0 !important"},content:{border:"1px solid #efefef",maxHeight:"unset !important",overflow:"hidden"},body:{maxHeight:r.height,overflow:"auto",position:"relative"},header:{padding:0},title:{flexGrow:1}},transitionProps:{duration:0},children:i(s.Box,{ref:l,children:e})})}),jS=e=>e.color?{"&[data-active], &[data-active]:hover":{borderColor:e.color?e.color:"..."}}:{},RS=k.observer(({view:e})=>{const t=we(),n=e.config;return p(s.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"?"8px 0px 8px":"0",height:"100%",overflow:"auto"}},keepMounted:!1,children:[i(s.Tabs.List,{grow:n.grow,children:n.tabs.map(r=>i(s.Tabs.Tab,{value:r.id,sx:jS(r),disabled:!r.view_id,children:r.name??r.id},r.id))}),n.tabs.map(r=>{const a=t.views.findByID(r.view_id);return a?i(s.Tabs.Panel,{value:r.id,children:i(ar,{view:a})},r.id):null})]})}),YS=k.observer(({view:e,children:t})=>{switch(e.type){case j.Modal:return i(WS,{view:e,children:t});case j.Tabs:return i(RS,{view:e});case j.Division:default:return i($l,{view:e,children:t})}}),QS=k.observer(({children:e,view:t})=>i($l,{sx:{paddingTop:"10px",paddingBottom:"100px"},view:t,children:e}));function Ol(e){return e.replace(/(vw|vh)/,"%")}const US=k.observer(({children:e,view:t})=>{const n=t.config,{width:r,height:a}=y.useMemo(()=>({width:Ol(n.width),height:Ol(n.height)}),[n.width,n.height]),{ref:o,downloadScreenshot:l}=zi(t);return i(s.Box,{sx:{height:"100%","> div:not(.mantine-Modal-root)":{height:"100%"}},children:i(s.Modal,{size:n.width,opened:!0,onClose:x.noop,withCloseButton:!1,title:p(s.Group,{position:"apart",px:"1rem",h:"48px",children:[i(s.Box,{children:n.custom_modal_title.value}),i(Ll,{downloadScreenshot:l})]}),trapFocus:!0,onDragStart:u=>{u.stopPropagation()},styles:{root:{position:"relative",height:"100%"},overlay:{position:"absolute !important"},inner:{position:"relative",top:"50%",left:"50%",right:"unset",bottom:"unset",transform:"translate(-50%, -50%)",padding:"0 !important",width:r,height:a,maxHeight:a},content:{border:"1px solid #efefef",height:"100%"},body:{maxHeight:"calc(100% - 48px)",overflow:"auto"},header:{padding:0},title:{flexGrow:1}},withinPortal:!1,transitionProps:{duration:0},children:i(s.Box,{ref:o,children:e})})})}),KS=({variant:e,orientation:t})=>{const n={root:{height:"100%",overflow:"hidden"},tab:{},panel:{padding:"16px"}};return e==="pills"&&t==="horizontal"&&(n.tab.paddingTop="6px",n.tab.paddingBottom="6px"),t==="vertical"&&(n.tab["&.add-a-tab"]={paddingTop:"1px",paddingBottom:"1px"},n.tab["&.add-a-tab .mantine-Tabs-tabLabel"]={marginLeft:"auto",marginRight:"auto"}),n},XS=e=>e.color?{"&[data-active], &[data-active]:hover":{borderColor:e.color?e.color:"..."}}:{},JS=k.observer(({view:e})=>{const t=Qe.useModals(),n=le(),r=y.useMemo(()=>n.views.options.filter(u=>u.type===j.Division),[e.id,n.views.options]),a=e.config,o=u=>t.openConfirmModal({title:"Delete this tab?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>{a.removeTab(u)},confirmProps:{color:"red"},zIndex:320}),l=a.tabs.length===0;return p(s.Tabs,{className:"preview-view-tabs",variant:a.variant,orientation:a.orientation,value:e.tab,onTabChange:e.setTab,styles:KS(a),children:[p(s.Tabs.List,{grow:a.grow,children:[a.tabs.map(u=>i(s.Tabs.Tab,{value:u.id,sx:XS(u),children:u.name??u.id},u.id)),i(s.Tabs.Tab,{onClick:a.addTab,value:"add",className:"add-a-tab",children:i(T.Plus,{size:18,color:"#228be6"})})]}),a.tabs.map((u,c)=>{const d=n.views.findByID(u.view_id);return p(s.Tabs.Panel,{value:u.id,sx:{position:"relative"},children:[p(s.Box,{sx:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:200},children:[i(s.Overlay,{opacity:.8,color:"#FFF",blur:10,zIndex:100}),p(s.Stack,{mx:"auto",mt:100,sx:{width:"300px",position:"relative",zIndex:200},children:[i(s.TextInput,{label:"Tab Name",value:u.name,onChange:f=>u.setName(f.currentTarget.value)}),i(s.Select,{label:"View",value:u.view_id,onChange:u.setViewID,data:r}),i(s.ColorInput,{label:"Color",value:u.color,onChange:u.setColor,disabled:a.variant!=="default"}),d&&p(s.Button,{mt:20,variant:"gradient",leftIcon:i($.IconArrowsLeftRight,{size:18}),gradient:{from:"cyan",to:"indigo"},onClick:()=>n.views.setIDOfVIE(d.id),children:["Swith to View: ",d.name]}),i(s.Button,{mt:20,variant:"subtle",color:"red",onClick:()=>o(c),disabled:l,leftIcon:i($.IconTrash,{size:14}),children:"Delete This Tab"})]})]}),d&&i(ar,{view:d})]},u.id)})]})}),ZS=k.observer(({view:e,children:t})=>{switch(e.type){case j.Modal:return i(US,{view:e,children:t});case j.Tabs:return i(JS,{view:e});case j.Division:default:return i(QS,{view:e,children:t})}}),Pl=k.observer(function({view:t}){return i(tr.Provider,{value:{viewPanelInFullScreen:x.noop,inFullScreen:!1},children:i(s.Box,{className:"dashboard-view","data-enable-scrollbar":!0,children:i(ZS,{view:t,children:p(s.Box,{sx:{position:"relative"},children:[i(s.Box,{className:"dashboard-sticky-area",sx:{position:"sticky",top:"0px"},children:i(Yo,{view:t})}),i(NS,{view:t})]})})})})}),ar=k.observer(function({view:t}){const{fullScreenPanelID:n,setFullScreenPanelID:r}=ss(),{viewPanelInFullScreen:a,exitFullScreen:o,inFullScreen:l,fullScreenPanel:u}=El(t,n,r);return i(tr.Provider,{value:{viewPanelInFullScreen:a,inFullScreen:l},children:p(s.Box,{className:"dashboard-view","data-enable-scrollbar":!0,sx:{height:t.type===j.Modal?"0 !important":"100%"},children:[l&&i(zl,{view:t,panel:u,exitFullScreen:o}),i(YS,{view:t,children:p(s.Box,{sx:{position:"relative"},children:[!l&&i(s.Box,{className:"dashboard-sticky-area",sx:{position:"sticky",top:"0px"},children:i(Yo,{view:t})}),!l&&i(FS,{view:t})]})})]})})});var Bl=(e=>(e.Use="use",e.Edit="edit",e))(Bl||{});const HS={[j.Division]:"Division",[j.Tabs]:"Tabs",[j.Modal]:"Modal"},Vl={[j.Division]:"rgba(255, 0, 0, 0.2)",[j.Modal]:"rgba(0, 0, 0, 0.2)",[j.Tabs]:"rgba(255, 200, 100, 0.4)"},e_={[j.Division]:"#ff4000",[j.Modal]:"#000",[j.Tabs]:"#ffad18"},t_={definition:{sqlSnippets:[],queries:[],mock_context:{}},views:[{id:"Main",name:"Main",type:j.Division,config:{},panelIDs:[]}],panels:[],filters:[],version:"9.19.0"};function n_(e,t,n){b.addDisposer(e,b.addMiddleware(e,(r,a)=>{a(r,()=>{b.getType(r.context)===t&&r.type==="action"&&n(r.name,r.context)})}))}const Nl=b.types.compose("FiltersModel",fl,b.types.model("FiltersModel",{previewValues:b.types.optional(b.types.frozen(),{})})).views(e=>({get options(){return e.current.map(t=>({label:t.label??t.id,value:t.id,_type:"filter"}))},get selects(){return e.current.filter(t=>t.type===_e.Select).map(t=>({label:t.label??t.id,value:t.id}))},get keyLabelOptions(){return e.current.map(t=>({label:t.label??t.key,value:t.key}))}})).actions(e=>({replace(t){e.current=b.cast(t)},append(t){e.current.push(t)},remove(t){e.current.splice(t,1)},removeByID(t){const n=e.current.findIndex(r=>r.id===t);n>=0&&e.current.splice(n,1)},updatePreviewValues(t){e.previewValues=t}})).actions(e=>{function t(){n_(e.current,rl,(n,r)=>{if(n==="setType"){const a=hl(r.config.default_value,r.config);e.setValueByKey(r.key,a),e.updatePreviewValues({...e.previewValues,[r.key]:a})}})}return{afterCreate(){t()}}}),ql=wl.views(e=>({get options(){const t=e.current.map(n=>({value:n.id,label:n.name,_type:"query"}));return x.sortBy(t,n=>n.label.toLowerCase())},get sortedList(){return x.sortBy(e.current,t=>t.name.toLowerCase())}})).actions(e=>({replace(t){e.current=b.cast(t)},append(t){e.current.push(t)},remove(t){e.current.splice(t,1)},replaceByIndex(t,n){e.current.splice(t,1,n)},removeQuery(t){const n=e.current.find(r=>r.id===t);n&&(b.detach(n),e.current.remove(n))},removeQueries(t){const n=new Set(t);e.current.forEach(a=>{n.has(a.id)&&b.detach(a)});const r=[...e.current];x.remove(r,a=>n.has(a.id)),e.current=b.cast(r)}})),Fl=Cl.views(e=>({get options(){const t=e.current.map(n=>({label:n.key,value:n.key,_type:"sql_snippet"}));return x.sortBy(t,n=>n.label.toLowerCase())}})).actions(e=>({replace(t){e.current=b.cast(t)},append(t){e.current.push(t)},remove(t){e.current.splice(t,1)},removeByKey(t){const n=e.current.findIndex(r=>r.key===t);n>=0&&e.current.splice(n,1)},replaceByIndex(t,n){e.current.splice(t,1,n)}})),r_=b.types.model({data:b.types.optional(b.types.frozen(),[]),state:b.types.optional(b.types.enumeration(["idle","loading","error"]),"idle"),error:b.types.frozen()}).views(e=>({get loading(){return e.state==="loading"},get empty(){return e.data.length===0},get sql(){const t=b.getParent(e,1),{type:n,table_name:r,table_schema:a}=t;if(n===Se.MySQL)return`
439
+ `}}}function t1(e,t){const n=Gt(e.heat_block.min,t),r=Gt(e.heat_block.max,t);return{min:n,max:r,calculable:!0,orient:"horizontal",left:"center",top:0,itemWidth:15}}function n1(e,t,n){const r=O(e.x_axis.data_key),a=x.uniq(t[r.queryID].map(c=>c[r.columnKey])),{overflow:o,rotate:l}=e.x_axis.axisLabel,u=rt(o.on_axis);return{id:"main-x-axis",type:"category",data:a,name:e.x_axis.name??"",align:"center",axisTick:{show:!0,alignWithLabel:!0},axisLabel:{rotate:l,...u,formatter:n},splitArea:{show:!0},nameLocation:"center",nameGap:25,nameTextStyle:{fontWeight:"bold",align:"center"},z:2}}function r1(e,t,n){const r=O(e.x_axis.data_key),a=O(e.y_axis.data_key),{nameAlignment:o,data_key:l,...u}=e.y_axis,c=x.uniq(t[r.queryID].map(g=>g[a.columnKey])),{overflow:d,rotate:f}=e.y_axis.axisLabel,h=rt(d.on_axis);return{...u,type:"category",data:c,axisLabel:{rotate:f,...h,formatter:n},axisLine:{show:!0,color:"blue"},axisTick:{show:!0,alignWithLabel:!0},splitArea:{show:!0},nameTextStyle:{fontWeight:"bold",align:o},nameLocation:"end",nameGap:15,z:2}}const i1={tooltip:{confine:!0}};function a1(e,t,n){if(!e.x_axis.data_key||!e.y_axis.data_key||!e.heat_block.data_key)return{};const r=n.reduce((u,c)=>{const d=ft(c,t);return u[c.name]=Ze(c,d),u},{}),a=UC(e),o=KC(e),l={xAxis:n1(e,t,a.x_axis),yAxis:r1(e,t,a.y_axis),series:JC(e,t),tooltip:e1(e,t,a,o),grid:XC(e),visualMap:t1(e,r)};return x.defaultsDeep({},l,i1)}function s1(e){return i(B,{})}function o1(e){return i(s.Text,{children:"Click heat block"})}const Fo={id:"builtin:echarts:click-heatmap:heat-block",displayName:"Click Heat Block",nameRender:o1,configRender:s1,payload:[{name:"seriesType",description:"'heatmap'",valueType:"string"},{name:"componentType",description:"'series'",valueType:"string"},{name:"name",description:"Name of the series clicked",valueType:"string"},{name:"color",description:"Color",valueType:"string"},{name:"value",description:"String-typed number, or series' actual value",valueType:"string"},{name:"rowData",description:"Data of the row",valueType:"object"}]};ie.use([q.DataZoomComponent,he.HeatmapChart,q.GridComponent,q.LegendComponent,q.TooltipComponent,q.VisualMapComponent,Pe.CanvasRenderer]);function l1({conf:e,data:t,width:n,height:r,interactionManager:a,variables:o}){const l=b.useMemo(()=>{const h=O(e.x_axis.data_key),g=O(e.y_axis.data_key);return x.keyBy(t[h.queryID],m=>`${m[h.columnKey]}---${m[g.columnKey]}`)},[t,e.x_axis.data_key,e.y_axis.data_key]),u=Ke(a.triggerManager,Fo.id),c=b.useCallback(h=>{const[g,m]=h.value,C=x.get(l,`${g}---${m}`,{error:"rowData is not found"});u.forEach(w=>{a.runInteraction(w.id,{...h,rowData:C})})},[l,u,a]),d=b.useMemo(()=>({click:c}),[c]),f=b.useMemo(()=>a1(e,t,o),[e,t]);return!n||!r?null:i(Be,{echarts:ie,option:f,style:{width:n,height:r},onEvents:d,notMerge:!0,theme:"merico-light"})}function u1({context:e,instance:t}){const n=Xe({vizManager:e.vizManager,instance:t}),{value:r}=R(e.instanceData,"config"),{variables:a}=e,o=b.useMemo(()=>x.defaults({},r,Ci),[r]),l=e.data,{width:u,height:c}=e.viewport;return i(l1,{variables:a,width:u,height:c,data:l,conf:o,interactionManager:n})}class c1 extends ye{constructor(){super(...arguments);N(this,"VERSION",1)}configVersions(){this.version(1,n=>({version:1,config:n}))}}const d1={displayName:"Merico Heatmap",displayGroup:"Merico suite",migrator:new c1,name:"merico-heatmap",viewRender:u1,configRender:QC,createConfig:()=>({version:1,config:Ci}),triggers:[Fo]},p1=[{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"})),h1=[Hu,ec,rc,nc,tc,ic],Go=()=>({id:"dashboard",version:es,manifest:{viz:[hi,ex,C0,zb,Cx,Sy,Rw,bc,Vh,Ug,zm,aw,cy,kg,Gv,Qy,Cb,A0,SC,d1,BC,Zh],color:[...p1,...h1]}}),pn=new lc,Ce={pluginManager:dt("pluginManager"),vizManager:dt("vizManager"),colorManager:dt("colorManager"),instanceScope:{panelModel:dt("panelModel"),vizInstance:dt("vizInstance"),interactionManager:dt("interactionManager"),migrator:dt("migrator"),operationManager:dt("operationManager"),triggerManager:dt("triggerManager")}},Si=()=>{try{pn.install(Go())}catch{}const e=new Xu(pn),t=new oc(pn);return{pluginManager:pn,vizManager:e,colorManager:t}},ut=b.createContext(Si());try{pn.install(Go())}catch{}const _i=b.createContext(null);function er(e){const t=b.useContext(_i),n=K.useCreation(()=>e.configure(t||new yr),[e.configure]),r=K.usePrevious(n);return r&&r!==n&&r.dispose(),i(_i.Provider,{value:n,children:e.children})}function Wo(){return b.useContext(_i)}const f1=({description:e,isDescriptionEmpty:t})=>t?null:i(s.Tooltip,{color:"white",label:i(qn,{value:e,styles:{root:{border:"none"},content:{padding:0}}}),styles:{tooltip:{border:"0.0625rem solid rgb(233, 236, 239)",boxShadow:"rgb(0 0 0 / 5%) 0px 0.0625rem 0.1875rem, rgb(0 0 0 / 5%) 0px 1.25rem 1.5625rem -0.3125rem, rgb(0 0 0 / 4%) 0px 0.625rem 0.625rem -0.3125rem"}},withArrow:!0,children:i(s.Box,{sx:{height:"16px",alignSelf:"center"},children:i($.IconInfoCircle,{size:16,color:"gray"})})}),g1=k.observer(({label:e,config:{default_value:t,description:n,isDescriptionEmpty:r,...a},value:o,onChange:l})=>p(s.Box,{children:[i(s.Text,{children:" "}),i(s.Checkbox,{label:p(s.Group,{noWrap:!0,position:"apart",align:"middle",spacing:6,children:[i(s.Box,{sx:{flexGrow:1},children:e}),i(f1,{description:n,isDescriptionEmpty:r})]}),checked:o||!1,onChange:u=>l(u.currentTarget.checked),...a,pt:".4em",styles:{input:{borderColor:"#e9ecef"}}})]})),jo=k.observer(({label:e,config:t,value:n=[null,null],onChange:r})=>{const{inputFormat:a,...o}=t,l=Array.isArray(n)?n.map(f=>f?Y(f).toDate():null):[null,null],u=f=>{r(f.map(h=>h&&Y(h).format(a)))},c=t.getMinDate(l[0]),d=t.getMaxDate(l[0]);return i(Eu.DatePickerInput,{type:"range",label:e,value:l,onChange:u,icon:i(T.Calendar,{size:16}),sx:{minWidth:"16em"},minDate:c,maxDate:d,valueFormat:a,styles:{input:{borderColor:"#e9ecef"}},...o})}),m1=s.createStyles((e,{radius:t=4})=>({root:{borderRadius:e.fn.radius(t),display:"flex",flexWrap:"nowrap",border:"1px solid #ced4da",paddingLeft:"0px",paddingRight:"30px",backgroundColor:"#fff",transition:"border-color 100ms ease",borderColor:"#e9ecef","&.rc-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"}}})),Ro=({errorMessage:e})=>e?i(s.Text,{color:"red",size:12,children:e}):i(s.Text,{color:"dimmed",size:12,children:"Not found"}),y1=({disabled:e,classNames:t,styles:n,unstyled:r,radius:a,style:o,label:l,value:u,onChange:c,options:d,errorMessage:f,required:h})=>{const{classes:g,cx:m}=m1({radius:a},{name:"MultiSelectWidget",classNames:t,styles:n,unstyled:r}),[C,w]=b.useState(!1),_=L=>{w(L)},D=C&&(u==null?void 0:u.length)>0,[M,P]=b.useState(""),G=b.useMemo(()=>{if(!M)return d;const L=M.toLowerCase(),z=A=>{var F;return((F=A.description)==null?void 0:F.toLowerCase().includes(L))||A.label.toLowerCase().includes(L)};return d.filter(z)},[M,d]);return p(s.Stack,{spacing:3,children:[p(s.Group,{position:"apart",children:[p(s.Text,{className:g.label,children:[l,h&&i("span",{className:g.required,"aria-hidden":"true",children:"*"})]}),D&&i(s.Tooltip,{label:`${u.length} selected`,children:i(s.Badge,{children:u.length})})]}),i(ja,{disabled:e,allowClear:!0,className:m(g.root,"check-select"),dropdownClassName:m(g.dropdown,""),onDropdownVisibleChange:_,transitionName:"rc-select-dropdown-slide-up",choiceTransitionName:"rc-select-selection__choice-zoom",style:o,clearIcon:()=>i(s.CloseButton,{}),value:u,onChange:c,onSelect:console.log,mode:"multiple",maxTagCount:0,notFoundContent:i(Ro,{errorMessage:f}),maxTagTextLength:10,maxTagPlaceholder:L=>`${L.length} selected`,searchValue:M,onSearch:P,filterOption:!1,children:G.map(L=>p(ja.Option,{title:L.label,children:[i(s.Text,{size:"sm","data-role":"label",children:L.label}),L.description&&i(s.Text,{size:"xs",color:"dimmed","data-role":"description",children:L.description})]},L.value))})]})},b1=k.observer(({label:e,config:t,value:n,onChange:r})=>{const a=we(),o=!!t.options_query_id,{state:l,error:u}=a.getDataStuffByID(t.options_query_id),c=l==="loading",d=t.min_width?t.min_width:"200px",f=o?c:!1,h=g=>r(g,!1);return i(y1,{label:e,options:t.options,style:{minWidth:"160px",width:d,maxWidth:f?d:"unset",borderColor:"#e9ecef"},disabled:f,value:n,onChange:h,errorMessage:u,required:t.required})}),v1=b.forwardRef(({label:e,description:t,...n},r)=>i("div",{ref:r,...n,children:i(s.Group,{noWrap:!0,children:p("div",{children:[i(s.Text,{size:"sm","data-role":"label",children:e}),i(s.Text,{size:"xs",color:"dimmed","data-role":"description",children:t})]})})})),x1=k.observer(({label:e,config:t,value:n,onChange:r})=>{const a=we(),o=!!t.options_query_id,{state:l,error:u}=a.getDataStuffByID(t.options_query_id),c=l==="loading";return i(s.Select,{label:e,data:t.options,disabled:o?c:!1,value:n,onChange:r,error:!!u,placeholder:u,maxDropdownHeight:500,styles:{root:{width:t.width?t.width:"200px"},input:{borderColor:"#e9ecef"}},sx:{".mantine-Select-item[data-selected] .mantine-Text-root[data-role=description]":{color:"rgba(255,255,255,.7)"}},itemComponent:v1})});function w1({label:e,config:t,value:n,onChange:r}){return i(s.TextInput,{label:e,value:n||"",onChange:a=>r(a.currentTarget.value),...t,styles:{input:{borderColor:"#e9ecef"}}})}const C1=({rotate:e,onClick:t})=>i("svg",{onClick:t,className:"caret-icon",viewBox:"0 0 1024 1024",focusable:"false","data-icon":"caret-down",width:"14px",height:"14px",fill:"currentColor","aria-hidden":"true",transform:`rotate(${e})`,children:i("path",{d:"M840.4 300H183.6c-19.7 0-30.7 20.8-18.5 35l328.4 380.8c9.4 10.9 27.5 10.9 37 0L858.9 335c12.2-14.2 1.2-35-18.5-35z"})}),S1=({expanded:e,isLeaf:t,value:n,onClick:r,...a})=>(n==="0-0-value"&&console.log(a),t?i("span",{style:{width:"14px",display:"inline-block"}}):i(C1,{rotate:e?"0":"-90",onClick:r,...a})),_1=({onClick:e})=>p("svg",{onClick:e,className:"checkbox-icon",width:"16",height:"16",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:"2",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",children:[i("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),i("rect",{className:"border",x:"4",y:"4",width:"16",height:"16",rx:"2"}),i("rect",{className:"checkmark-indeterminate",x:"8",y:"8",width:"8",height:"8",rx:"2",stroke:"none"}),i("path",{className:"checkmark-checked",d:"M9 12l2 2l4 -4"})]}),k1=({onClick:e,...t})=>i(_1,{onClick:e,...t}),T1=s.createStyles((e,{radius:t=4})=>({root:{borderRadius:e.fn.radius(t),display:"flex",flexWrap:"nowrap",border:"1px solid #ced4da",paddingLeft:"0px",paddingRight:"30px",backgroundColor:"#fff",transition:"border-color 100ms ease",borderColor:"#e9ecef","&.rc-tree-select.rc-tree-select-open":{borderColor:"#228be6 !important",".rc-tree-select-selection-overflow-item-rest":{display:"none"},".rc-tree-select-selection-overflow-item-suffix":{display:"block"}},".rc-tree-select-selector":{height:"auto",lineHeight:1.55,paddingLeft:"12px",resize:"none",boxSizing:"border-box",fontSize:"14px",width:"100%",color:"#000",display:"block",textAlign:"left",minHeight:"36px",cursor:"pointer",flexGrow:1},".rc-tree-select-selection-search-mirror":{display:"none"},".rc-tree-select-selection-search":{flexGrow:1,width:"auto !important"},".rc-tree-select-selection-overflow":{display:"flex",minHeight:"34px",alignItems:"center",flexWrap:"nowrap",marginLeft:"calc(-10px / 2)",boxSizing:"border-box"},".rc-tree-select-selection-overflow-item":{display:"flex",alignItems:"center",backgroundColor:"#f1f3f5",color:"#495057",height:"24px",paddingLeft:"12px",paddingRight:"12px",fontWeight:500,fontSize:"12px",borderRadius:"4px",cursor:"default",userSelect:"none",maxWidth:"calc(100% - 20px)",margin:"calc(10px / 2 - 2px) calc(10px / 2)"},".rc-tree-select-selection-overflow-item-rest":{cursor:"pointer"},".rc-tree-select-selection-overflow-item-suffix":{display:"none",backgroundColor:"transparent",width:"100%",maxWidth:"100%",height:"28px",margin:0,paddingLeft:0,paddingRight:0},input:{flex:1,minWidth:"60px",backgroundColor:"transparent",border:0,outline:0,fontSize:"14px",padding:0,marginLeft:0,color:"inherit",height:"28px",lineHeight:"32px",cursor:"pointer",width:"100%","&::-webkit-search-decoration, &::-webkit-search-cancel-button, &::-webkit-search-results-button, &::-webkit-search-results-decoration":{display:"none"}},".rc-tree-select-clear":{marginRight:"-24px",alignSelf:"center",cursor:"pointer"},"&.rc-tree-select-disabled":{backgroundColor:"rgb(241, 243, 245)",color:"rgb(144, 146, 150)",opacity:.6,"&, .rc-tree-select-selector, input":{cursor:"not-allowed"}}},label:{fontSize:e.fontSizes.sm,fontWeight:500,color:"#212529"},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"}}}})),D1=({disabled:e,classNames:t,styles:n,unstyled:r,radius:a,style:o,label:l,value:u,onChange:c,treeData:d,errorMessage:f,required:h,treeCheckStrictly:g})=>{const{classes:m,cx:C}=T1({radius:a},{name:"FilterTreeSelectWidget",classNames:t,styles:n,unstyled:r}),[w,_]=b.useState(!1),D=P=>{_(P)},M=w&&(u==null?void 0:u.length)>0;return p(s.Stack,{spacing:3,children:[p(s.Group,{position:"apart",children:[p(s.Text,{className:m.label,children:[l,h&&i("span",{className:m.required,"aria-hidden":"true",children:"*"})]}),M&&i(s.Tooltip,{label:`${u.length} selected`,children:i(s.Badge,{children:u.length})})]}),i(Ra,{disabled:e,allowClear:!0,treeCheckStrictly:g,className:C(m.root,"check-select"),dropdownClassName:C(m.dropdown,""),onDropdownVisibleChange:D,transitionName:"rc-tree-select-dropdown-slide-up",choiceTransitionName:"rc-tree-select-selection__choice-zoom",style:o,treeLine:!0,clearIcon:()=>i(s.CloseButton,{}),switcherIcon:S1,treeIcon:k1,maxTagTextLength:10,value:u,treeData:d,notFoundContent:i(Ro,{errorMessage:f}),treeNodeFilterProp:"filterBasis",treeCheckable:!0,showCheckedStrategy:Ra.SHOW_PARENT,onChange:c,onSelect:console.log,maxTagCount:0,maxTagPlaceholder:P=>`${P.length} selected`})]})},I1=k.observer(({label:e,config:t,value:n,onChange:r})=>{const{treeData:a,treeDataLoading:o,errorMessage:l}=t,u=t.min_width?t.min_width:"200px",d=!!t.options_query_id?o:!1;return i(D1,{disabled:d,style:{minWidth:"160px",width:u,maxWidth:d?u:"unset",borderColor:"#e9ecef"},value:n,onChange:f=>r(f,!1),treeData:a,errorMessage:l,label:e,required:t.required,treeCheckStrictly:t.treeCheckStrictly})}),M1=k.observer(({filter:{type:e,config:t,key:n,...r},formFieldProps:a})=>{switch(e){case"select":return i(x1,{...r,...a,config:t});case"multi-select":return i(b1,{...r,...a,config:t});case"tree-select":return i(I1,{...r,...a,config:t});case"text-input":return i(w1,{...r,...a,config:t});case"date-range":return i(jo,{...r,...a,config:t});case"checkbox":return i(g1,{...r,...a,config:t});default:return null}}),A1=k.observer(b.forwardRef(({filter:e,...t},n)=>i("div",{className:"filter-root",ref:n,children:i(Fe,{children:i(M1,{filter:e,formFieldProps:t})})})));function z1(e){const t=le();b.useEffect(()=>{var n,r;(r=(n=t.filters).updatePreviewValues)==null||r.call(n,e)},[e])}const Yo=k.observer(function({view:t}){const n=we(),{control:r,handleSubmit:a,reset:o}=v.useForm({defaultValues:n.filters.values,reValidateMode:"onBlur"}),l=v.useWatch({control:r});b.useEffect(()=>{o(n.filters.values)},[n.filters.values,o]),z1(l);const u=n.filters.visibleInView(t.id),c=b.useMemo(()=>u.every(g=>g.should_auto_submit),[u]),d=b.useMemo(()=>u.filter(g=>x.get(g,"config.required",!1)),[u]),f=b.useMemo(()=>d.length===0?!1:d.some(g=>!g.requiredAndPass(l[g.key])),[l,d]);if(u.length===0)return null;const h=(g,m)=>(C,w)=>{m(C),(g.should_auto_submit||w)&&n.filters.setValueByKey(g.key,C)};return i("form",{onSubmit:a(n.filters.setValues),children:p(s.Group,{className:"dashboard-filters",position:"apart",noWrap:!0,sx:c?{}:{border:"1px solid #e9ecef",borderRadius:"4px",padding:"16px"},children:[i(s.Group,{align:"flex-start",children:u.map(g=>i(v.Controller,{name:g.key,control:r,render:({field:m})=>i(A1,{filter:g,value:m.value,onChange:h(g,m.onChange)})},g.id))}),!c&&i(s.Group,{sx:{alignSelf:"flex-end"},children:i(s.Button,{color:"blue",size:"sm",type:"submit",disabled:f,children:"Search"})})]})})}),E1={viewPanelInFullScreen:x.noop,inFullScreen:!1},tr=b.createContext(E1),Qo=y.types.model("MockContextMeta",{current:y.types.optional(y.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 Uo(e){return{current:e}}const $1=y.types.model("PanelLayoutMeta",{x:y.types.number,y:y.types.maybeNull(y.types.number),w:y.types.number,h:y.types.number,moved:y.types.optional(y.types.boolean,!1),static:y.types.optional(y.types.boolean,!1)}).views(e=>({get json(){const{x:t,y:n,w:r,h:a,moved:o}=e;return{h:a,w:r,x:t,y:n===null?0:n,moved:o,static:e.static}}})).actions(e=>({set(t){const{x:n,y:r,w:a,h:o,moved:l}=t;e.x=n,e.y=r,e.w=a,e.h=o,e.moved=!!l,e.static=!!t.static},setWidth(t){e.w=t},setHeight(t){e.h=t}})),L1=y.types.model("PanelStyleBorderMeta",{enabled:y.types.boolean}).views(e=>({get json(){const{enabled:t}=e;return{enabled:t}}})).actions(e=>({setEnabled(t){e.enabled=t}})),O1=y.types.model("PanelStyleMeta",{border:L1}).views(e=>({get json(){const{border:t}=e;return{border:t.json}}})).actions(e=>({})),P1=y.types.model("VariableMeta",{name:y.types.string,size:y.types.string,weight:y.types.string,color:y.types.union(y.types.model({type:y.types.literal("static"),staticColor:y.types.string}),y.types.model({type:y.types.literal("continuous"),valueRange:y.types.array(y.types.number),colorRange:y.types.array(y.types.string)}),y.types.model({type:y.types.literal("piecewise")})),formatter:y.types.model({output:y.types.enumeration("Output",["number","percent"]),average:y.types.optional(y.types.boolean,!1),mantissa:y.types.number,trimMantissa:y.types.optional(y.types.boolean,!1)}),data_field:y.types.string,aggregation:y.types.union(y.types.model({type:y.types.enumeration(["none","sum","mean","median","min","max","CV","std"]),config:y.types.frozen()}),y.types.model({type:y.types.literal("quantile"),config:y.types.model({p:y.types.number})}),y.types.model({type:y.types.literal("custom"),config:y.types.model({func:y.types.string})}))}).views(e=>({get json(){const{name:t,size:n,weight:r,color:a,formatter:o,data_field:l,aggregation:u}=e;return x.cloneDeep({name:t,size:n,color:a,weight:r,formatter:o,data_field:l,aggregation:u})}})),B1=y.types.model("PanelVizMeta",{type:y.types.string,conf:y.types.frozen()}).views(e=>({get json(){return{conf:e.conf,type:e.type}}})).actions(e=>({setType(t){e.type=t},setConf(t){e.conf=t}})),V1=y.types.model({id:y.types.string,title:y.types.string,description:y.types.string,layout:$1,queryIDs:y.types.array(y.types.string),viz:B1,style:O1,variables:y.types.optional(y.types.array(P1),[])}).views(e=>({get json(){const{id:t,title:n,description:r,queryIDs:a}=e;return{id:t,viz:e.viz.json,style:e.style.json,title:n,layout:e.layout.json,queryIDs:[...a],variables:e.variables.map(o=>o.json),description:r}},get queryIDSet(){return new Set(e.queryIDs)}})).actions(e=>({setID(t){e.id=t},setTitle(t){e.title=t},setDescription(t){e.description=t},addQueryID(t){e.queryIDSet.has(t)||e.queryIDs.push(t)},removeQueryID(t){if(!e.queryIDSet.has(t))return;const n=new Set(e.queryIDSet);n.delete(t),e.queryIDs=y.cast(Array.from(n))},setQueryIDs(t){e.queryIDs=y.cast(t)},addVariable(t){e.variables.push(t)},removeVariable(t){e.variables.remove(t)}})),nr=e=>x.cloneDeepWith(e,(t,n)=>{if(n!==void 0&&t)return te.toJS(t)});var Se=(e=>(e.Postgresql="postgresql",e.MySQL="mysql",e.HTTP="http",e))(Se||{});const N1=y.types.model("QueryMeta",{id:y.types.string,name:y.types.string,type:y.types.enumeration("DataSourceType",[Se.Postgresql,Se.MySQL,Se.HTTP]),key:y.types.string,sql:y.types.string,pre_process:y.types.optional(y.types.string,""),post_process:y.types.optional(y.types.string,""),run_by:y.types.optional(y.types.array(y.types.string),[]),react_to:y.types.optional(y.types.array(y.types.string),[])}).views(e=>({get valid(){return e.id&&e.type&&e.key&&e.name?e.type===Se.HTTP?!!e.pre_process:!!e.sql:!1},get json(){const{id:t,name:n,type:r,key:a,sql:o,run_by:l,react_to:u,pre_process:c,post_process:d}=e;return nr({id:t,key:a,sql:o,name:n,type:r,run_by:l,react_to:u,pre_process:c,post_process:d})}})).actions(e=>({setName(t){e.name=t},setKey(t){e.key=t},setType(t){e.type=t},setSQL(t){e.sql=t},setRunBy(t){e.run_by.length=0,e.run_by.push(...t)},setReactTo(t){e.react_to.length=0,e.react_to.push(...t)},setPreProcess(t){e.pre_process=t},setPostProcess(t){e.post_process=t}})),q1=y.types.model("SQLSnippetMeta",{key:y.types.string,value:y.types.string}).views(e=>({get json(){const{key:t,value:n}=e;return{key:t,value:n}}})).actions(e=>({setKey(t){e.key=t},setValue(t){e.value=t}}));var _e=(e=>(e.Select="select",e.MultiSelect="multi-select",e.TreeSelect="tree-select",e.TextInput="text-input",e.Checkbox="checkbox",e.DateRange="date-range",e))(_e||{});const Ko=y.types.model("FilterCheckboxConfigMeta",{_name:y.types.literal("checkbox"),description:y.types.optional(y.types.string,""),default_value:y.types.boolean}).views(e=>({get json(){const{_name:t,description:n,default_value:r}=e;return{_name:t,description:n,default_value:r}},get isDescriptionEmpty(){const{description:t}=e;return t===""||t==="<p></p>"}})).actions(e=>({setDefaultValue(t){e.default_value=t},setDescription(t){e.description=t}})),F1=()=>Ko.create({_name:"checkbox",description:"",default_value:!1});function Xo(e,t){return e.map(n=>{try{return n?Y.tz(n,"UTC").format(t):null}catch{return console.log(`[date-range] failed parsing ${n}`),null}})}const G1=y.types.model("FilterDateRangeConfigMeta",{_name:y.types.literal("date-range"),required:y.types.boolean,inputFormat:y.types.enumeration("DateRangeInputFormat",["YYYY","YYYYMM","YYYYMMDD","YYYY-MM","YYYY-MM-DD"]),default_value:y.types.optional(y.types.array(y.types.union(y.types.string,y.types.null)),[null,null]),clearable:y.types.boolean,max_days:y.types.optional(y.types.number,0),allowSingleDateInRange:y.types.optional(y.types.boolean,!1)}).views(e=>({get json(){const{_name:t,max_days:n,required:r,clearable:a,inputFormat:o,default_value:l,allowSingleDateInRange:u}=e;return{_name:t,max_days:n,required:r,clearable:a,inputFormat:o,default_value:Xo(l,o),allowSingleDateInRange:u}},truthy(t){return Array.isArray(t)&&t.length===2&&t.every(n=>!!n)}})).views(e=>({getMaxDate(t){const{max_days:n}=e;if(!(!n||!t))return Y(t).startOf("day").add(n,"days").toDate()},getMinDate(t){const{max_days:n}=e;if(!(!n||!t))return Y(t).startOf("day").subtract(n,"days").toDate()}})).actions(e=>({setFilterValue(t){try{const n=y.getParent(e);y.getRoot(e).filters.setValueByKey(n.key,t)}catch(n){console.error(n)}}})).actions(e=>({setRequired(t){e.required=t},setClearable(t){e.clearable=t},setInputFormat(t){e.inputFormat=t},setDefaultValue(t){e.default_value.length=0,e.default_value.push(...t),e.setFilterValue(t)},setMaxDays(t){e.max_days=t,t>0&&(e.clearable=!0)},setAllowSingleDateInRange(t){e.allowSingleDateInRange=t}})),Jo=y.types.snapshotProcessor(G1,{preProcessor({default_value:e,...t}){return{...t,default_value:e.map(n=>n===null?null:Y.tz(n,"UTC").toISOString())}},postProcessor(e){const{default_value:t,...n}=e;return{...n,default_value:Xo(t,n.inputFormat)}}}),W1=()=>Jo.create({_name:"date-range",required:!1,inputFormat:"YYYY-MM-DD",clearable:!1,default_value:[null,null]}),j1=y.types.model({label:y.types.string,value:y.types.string}).actions(e=>({setLabel(t){e.label=t},setValue(t){e.value=t}})),ki=y.types.model("FilterConfigModel_BaseSelect",{static_options:y.types.optional(y.types.array(j1),[]),options_query_id:y.types.optional(y.types.string,""),default_selection_count:y.types.optional(y.types.number,0),required:y.types.optional(y.types.boolean,!1)}).views(e=>({get usingQuery(){return!!e.options_query_id}})).views(e=>({get options(){if(!e.usingQuery)return e.static_options;const{data:t,state:n,error:r}=y.getRoot(e).content.getDataStuffByID(e.options_query_id);return n==="idle"?t:[]}})).actions(e=>({setRequired(t){e.required=t},addStaticOption(t){e.static_options.push(t)},removeStaticOption(t){e.static_options.splice(t,1)},setDefaultSelectionCount(t){e.default_selection_count=t},setOptionsQueryID(t){e.options_query_id=t??""}})),Zo=y.types.compose("FilterMultiSelectConfigMeta",y.types.model({_name:y.types.literal("multi-select"),min_width:y.types.optional(y.types.string,""),default_value:y.types.optional(y.types.array(y.types.string),[])}),ki).views(e=>({get json(){const{_name:t,default_value:n,required:r,min_width:a,static_options:o,options_query_id:l,default_selection_count:u}=e;return nr({_name:t,required:!!r,min_width:a,default_value:n,static_options:o,options_query_id:l,default_selection_count:u})},get default_selection(){return e.usingQuery?e.options.slice(0,e.default_selection_count).map(t=>t.value):e.default_value},truthy(t){return Array.isArray(t)&&t.length>0}})).actions(e=>({setDefaultValue(t){e.default_value=y.cast(t)},setMinWidth(t){e.min_width=t},setDefaultSelection(){const t=y.getRoot(e).content.filters,n=y.getParent(e).key;t.setValueByKey(n,e.default_selection)}})).actions(e=>({afterCreate(){y.addDisposer(e,te.reaction(()=>te.toJS(e.default_selection),e.setDefaultSelection,{fireImmediately:!0,delay:0}))}})),R1=()=>Zo.create({_name:"multi-select",default_value:[],static_options:[],options_query_id:"",default_selection_count:0}),Ho=y.types.compose("FilterConfigModel_Select",y.types.model({_name:y.types.literal("select"),default_value:y.types.string,width:y.types.optional(y.types.string,"")}),ki).views(e=>({get json(){const{_name:t,default_value:n,required:r,width:a,static_options:o,options_query_id:l,default_selection_count:u}=e;return nr({_name:t,width:a,required:r,default_value:n,static_options:o,options_query_id:l,default_selection_count:u})},truthy(t){return!!t},getSelectOption(t){return e.options.find(n=>n.value===t)},get default_selection(){return e.usingQuery?e.default_selection_count>0&&e.options.length>0?e.options[0].value:"":e.default_value}})).actions(e=>({setDefaultValue(t){e.default_value=t},setWidth(t){e.width=t},setDefaultSelection(){const t=y.getRoot(e).content.filters,n=y.getParent(e).key;t.setValueByKey(n,e.default_selection)}})).actions(e=>({afterCreate(){y.addDisposer(e,te.reaction(()=>te.toJS(e.default_selection),e.setDefaultSelection,{fireImmediately:!0,delay:0}))}})),Y1=()=>Ho.create({_name:"select",required:!1,default_value:"",static_options:[],options_query_id:"",default_selection_count:0}),el=y.types.model("FilterTextInputConfigMeta",{_name:y.types.literal("text-input"),required:y.types.boolean,default_value:y.types.string}).views(e=>({get json(){const{_name:t,required:n,default_value:r}=e;return{_name:t,required:n,default_value:r}},truthy(t){return typeof t!="string"?!1:!!t.trim()}})).actions(e=>({setRequired(t){e.required=t},setDefaultValue(t){e.default_value=t}})),tl=()=>el.create({_name:"text-input",required:!1,default_value:""});function Q1(e){return $u.arrayToTree(e,{id:"value",parentId:"parent_value",childrenField:"children",dataField:null})}function U1(e){return e.map(t=>{const{label:n,description:r,...a}=t,o={...a,filterBasis:`${n}___${r??""}`,description:r,label:n};return r&&(o.label=b.createElement("div",{},[b.createElement(s.Text,{key:0,title:t.label},t.label),b.createElement(s.Text,{key:1,className:"rc-tree-select-tree-title-desc",color:"dimmed",title:t.description},t.description)])),o})}const nl=y.types.compose("FilterTreeSelectConfigMeta",y.types.model({_name:y.types.literal("tree-select"),min_width:y.types.optional(y.types.string,""),default_value:y.types.optional(y.types.array(y.types.string),[]),treeCheckStrictly:y.types.optional(y.types.boolean,!1)}),ki).views(e=>({get json(){const{_name:t,default_value:n,required:r,min_width:a,static_options:o,options_query_id:l,default_selection_count:u,treeCheckStrictly:c}=e;return{_name:t,required:!!r,min_width:a,default_value:n,static_options:o,options_query_id:l,treeCheckStrictly:c,default_selection_count:u}},get treeData(){const{data:t}=y.getRoot(e).content.getDataStuffByID(e.options_query_id),n=U1(t);return Q1(n)},get errorMessage(){const{error:t}=y.getRoot(e).content.getDataStuffByID(e.options_query_id);return t},get treeDataLoading(){const{state:t}=y.getRoot(e).content.getDataStuffByID(e.options_query_id);return t==="loading"},get defaultSelection(){const{default_selection_count:t}=e;return t?this.treeData.slice(0,t).map(r=>r.value):[]},truthy(t){return Array.isArray(t)&&t.length>0}})).actions(e=>({setDefaultValue(t){e.default_value=y.cast(t)},setMinWidth(t){e.min_width=t},setTreeCheckStrictly(t){e.treeCheckStrictly=t},applyDefaultSelection(){const t=y.getParent(e,1).key;y.getRoot(e).content.filters.setValueByKey(t,e.defaultSelection)},afterCreate(){y.addDisposer(e,te.reaction(()=>JSON.stringify(e.defaultSelection),this.applyDefaultSelection,{fireImmediately:!0,delay:0}))}})),K1=()=>nl.create({_name:"tree-select",default_value:[],static_options:[],options_query_id:"",default_selection_count:0}),rl=y.types.model("FilterMeta",{id:y.types.identifier,key:y.types.string,label:y.types.string,order:y.types.number,visibleInViewsIDs:y.types.array(y.types.string),auto_submit:y.types.optional(y.types.boolean,!1),type:y.types.enumeration("DashboardFilterType",[_e.Select,_e.MultiSelect,_e.TreeSelect,_e.TextInput,_e.Checkbox,_e.DateRange]),config:y.types.union(Ho,Zo,nl,el,Ko,Jo)}).views(e=>({get plainDefaultValue(){const t=e.config.default_value;return Array.isArray(t)?[...t]:t},get usingDefaultValue(){return e.type!==_e.TreeSelect},get auto_submit_supported(){return[_e.Select,_e.Checkbox,_e.DateRange].includes(e.type)}})).views(e=>({get json(){const{id:t,key:n,label:r,order:a,visibleInViewsIDs:o,auto_submit:l,type:u,config:c}=e;return{id:t,key:n,type:u,label:r,order:a,config:c.json,auto_submit:l,visibleInViewsIDs:te.toJS(o)}},get visibleInViewsIDSet(){return new Set(e.visibleInViewsIDs)},get should_auto_submit(){return e.auto_submit_supported&&e.auto_submit},requiredAndPass(t){return x.get(e.config,"required",!1)?x.get(e.config,"truthy",()=>!0)(t):!1}})).actions(e=>({setKey(t){e.key=t},setLabel(t){e.label=t},setOrder(t){e.order=t},setType(t){switch(t){case _e.Select:e.config=Y1();break;case _e.MultiSelect:e.config=R1();break;case _e.TreeSelect:e.config=K1();break;case _e.TextInput:e.config=tl();break;case _e.Checkbox:e.config=F1();break;case _e.DateRange:e.config=W1();break}e.type=t},setVisibleInViewsIDs(t){e.visibleInViewsIDs.length=0,e.visibleInViewsIDs.push(...t)},setAutoSubmit(t){e.auto_submit=e.auto_submit_supported&&t}}));var j=(e=>(e.Division="div",e.Modal="modal",e.Tabs="tabs",e))(j||{});const il=y.types.model("ViewDivisionConfig",{_name:y.types.literal(j.Division)}).views(e=>({get json(){const{_name:t}=e;return{_name:t}}})),X1=()=>il.create({_name:j.Division}),J1=y.types.model("CustomModalTitleModel",{enabled:y.types.optional(y.types.boolean,!1),func_content:y.types.optional(y.types.string,"")}).views(e=>({get json(){const{enabled:t,func_content:n}=e;return{enabled:t,func_content:n}},get value(){const{enabled:t,func_content:n}=e,r=y.getParent(e,2),a=y.getRoot(e);if(!t)return r.name;try{const o={filters:a.content.filters.values,context:a.context.current};return new Function(`return ${n}`)()(o)}catch(o){return console.error(o),r.name}}})).actions(e=>({setEnabled(t){e.enabled=t},setFuncContent(t){e.func_content=t},replace({enabled:t,func_content:n}){e.enabled=t,e.func_content=n}})),Ti={enabled:!1,func_content:["function text({ filters, context}) {"," // your code goes here",' return "text"',"}"].join(`
440
+ `)},al=y.types.model("ViewModalConfig",{_name:y.types.literal(j.Modal),width:y.types.string,height:y.types.string,custom_modal_title:y.types.optional(J1,Ti)}).views(e=>({get json(){const{_name:t,width:n,height:r,custom_modal_title:a}=e;return{_name:t,width:n,height:r,custom_modal_title:a.json}}})).actions(e=>({setWidth(t){e.width=t},setHeight(t){e.height=t}})),Z1=()=>al.create({_name:j.Modal,width:"90vw",height:"90vh"}),H1=y.types.model("ViewTabsTabModel",{id:y.types.identifier,name:y.types.string,view_id:y.types.string,color:y.types.optional(y.types.string,"")}).views(e=>({get json(){const{id:t,name:n,view_id:r,color:a}=e;return{id:t,name:n,color:a,view_id:r}}})).actions(e=>({setName(t){e.name=t},setViewID(t){e.view_id=t},setColor(t){e.color=t}})),sl=y.types.model("ViewTabsConfig",{_name:y.types.literal(j.Modal),tabs:y.types.optional(y.types.array(H1),[]),variant:y.types.optional(y.types.enumeration("variant",["default","outline","pills"]),"default"),orientation:y.types.optional(y.types.enumeration("orientation",["horizontal","vertical"]),"horizontal"),grow:y.types.optional(y.types.boolean,!1)}).views(e=>({get json(){const{_name:t,variant:n,orientation:r,tabs:a,grow:o}=e;return{grow:o,tabs:a.map(l=>l.json),_name:t,variant:n,orientation:r}}})).actions(e=>({setVariant(t){e.variant=t},setOrientation(t){e.orientation=t},setGrow(t){e.grow=t},setTabs(t){e.tabs.length=0,e.tabs=y.cast(t)},addTab(){const t=Ie.randomId(),n={id:t,name:t,view_id:""};e.tabs.push(n)},removeTab(t){e.tabs.splice(t,1)}})),eS=()=>sl.create({_name:j.Modal,tabs:[]}),tS=y.types.model({id:y.types.identifier,name:y.types.string,type:y.types.enumeration("EViewComponentType",[j.Division,j.Modal,j.Tabs]),config:y.types.union(il,al,sl),panelIDs:y.types.optional(y.types.array(y.types.string),[])}).views(e=>({get json(){const{id:t,name:n,type:r,config:a}=e;return{id:t,name:n,type:r,config:a.json,panelIDs:e.panelIDs}}})).actions(e=>({setName(t){e.name=t},setType(t){if(e.type!==t){switch(t){case j.Division:e.config=X1();break;case j.Modal:e.config=Z1();break;case j.Tabs:e.config=eS();break}e.type=t}},appendPanelID(t){e.panelIDs.push(t)},removePanelID(t){const n=e.panelIDs.filter(r=>r!==t);e.panelIDs.length=0,e.panelIDs.push(...n)}})),ol=y.types.model("DataSourceMetaModel",{id:y.types.string,type:y.types.enumeration("DataSourceType",[Se.HTTP,Se.MySQL,Se.Postgresql]),key:y.types.string,config:y.types.frozen()}),nS=y.types.model("DataSourcesMetaModel",{list:y.types.optional(y.types.array(ol),[])}).views(e=>({find({type:t,key:n}){return e.list.find(r=>r.key===n&&r.type===t)},get options(){return e.list.map(t=>({value:t.key,label:t.key}))}})).actions(e=>({replace(t){e.list.length=0,e.list.push(...t)}})),rS=y.types.model({id:y.types.string,content:y.types.string,create_time:y.types.string,update_time:y.types.string,is_preset:y.types.boolean}),ll=y.types.model("GlobalSQLSnippetsMeta",{list:y.types.optional(y.types.array(rS),[])}).views(e=>({find(t){return e.list.find(n=>n.id===t)},get options(){return e.list.map(t=>({value:t.id,label:t.id}))}})).actions(e=>({replace(t){e.list.length=0,e.list.push(...t)}})),Di=y.types.model("ContextMeta",{current:y.types.optional(y.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 ul(e){return Di.create({current:e})}const iS=y.types.compose("ViewRenderModel",tS,y.types.model({tab:y.types.optional(y.types.string,"")})).views(e=>({get defaultTab(){if(e.type!==j.Tabs)return"";const t=e.config;return t.tabs.length>0?t.tabs[0].id:""},get tabViewID(){var n;return e.type!==j.Tabs?"":((n=e.config.tabs.find(r=>r.id===e.tab))==null?void 0:n.view_id)??""},get contentModel(){return y.getParent(e,3)},get panels(){if(e.type!==j.Tabs)return this.contentModel.panels.panelsByIDs(e.panelIDs).panels;const t=this.tabViewID;return this.contentModel.views.findByID(t).panels},get renderViewIDs(){const t=[e.id];return e.type===j.Tabs&&t.push(this.tabViewID),t}})).actions(e=>({setTab(t){e.tab=t??""},afterCreate(){y.addDisposer(e,te.reaction(()=>e.defaultTab,t=>this.setTab(t),{fireImmediately:!0,delay:0}))}})),cl=y.types.model("ViewsRenderModel",{current:y.types.optional(y.types.array(iS),[]),visibleViewIDs:y.types.array(y.types.string)}).views(e=>({get json(){return e.current.map(t=>nr(t.json))},get idMap(){const t=new Map;return e.current.forEach(n=>{t.set(n.id,n)}),t},findByID(t){return e.current.find(n=>n.id===t)},get firstVisibleView(){const[t]=e.visibleViewIDs;return e.current.find(({id:n})=>n===t)},get visibleViews(){const t=new Set(e.visibleViewIDs);return e.current.filter(({id:n})=>t.has(n))}})).actions(e=>({appendToVisibles(t){new Set(e.visibleViewIDs.map(r=>r)).has(t)||e.visibleViewIDs.push(t)},rmVisibleViewID(t){const n=e.visibleViewIDs.findIndex(r=>r===t);n!==-1&&e.visibleViewIDs.splice(n,1)}}));function aS(e){const t=e.length>0?[e[0].id]:[];return{current:e.map(r=>{const{_name:a=r.type}=r.config;return{...r,config:{...r.config,_name:a},panelIDs:r.panelIDs}}),visibleViewIDs:t}}const dl=V1.views(e=>({get contentModel(){return y.getRoot(e).content}})).views(e=>({get queries(){return e.contentModel.queries.findByIDSet(e.queryIDSet)},get data(){return this.queries.reduce((t,n)=>(t[n.id]=n.data,t),{})},get dataLoading(){return this.queries.some(t=>t.state==="loading")},get queryStateMessages(){const t=this.queries.filter(o=>!o.runByConditionsMet);if(t.length===0)return"";const n=new Set,r=new Set;t.forEach(o=>{const l=o.conditionNames;l.context.forEach(u=>n.add(u)),l.filters.forEach(u=>r.add(u))});const a=[];return n.size>0&&(console.log(n),a.push(`context: ${Array.from(n).join(", ")}`)),r.size>0&&a.push(`filter${r.size>1?"s":""}: ${Array.from(r).join(", ")}`),a.length===2&&a.splice(1,0,"and"),a.unshift("Waiting for"),a.join(" ")},get queryErrors(){return this.queries.map(t=>t.error).filter(t=>!!t)},get canRenderViz(){return this.queryErrors.length===0&&this.queryStateMessages===""&&!this.dataLoading}})).actions(e=>({refreshData(){e.queries.forEach(t=>t.fetchData())},downloadData(){y.getRoot(e).content.queries.downloadDataByQueryIDs(e.queryIDs)}}));function sS(e){return{id:e,layout:{x:0,y:1/0,w:18,h:300},title:e,description:"<p></p>",queryIDs:[],viz:{type:hi.name,conf:hi.createConfig()},style:{border:{enabled:!0}}}}const pl=y.types.model("PanelsRenderModel",{list:y.types.optional(y.types.array(dl),[])}).views(e=>({get json(){return e.list.map(t=>t.json)},findByID(t){return e.list.find(n=>n.id===t)},get idMap(){const t=new Map;return e.list.forEach(n=>{t.set(n.id,n)}),t}})).views(e=>({panelsByIDs(t){const n=[];t.forEach(a=>{const o=e.idMap.get(a);o?n.push(o):console.warn(`Panel is not found, id:${a}`)});const r=n.map(a=>({...a.layout.json,i:a.id}));return{panels:n,layouts:r}}}));function hl(e,t){if(e===void 0)return e;if(t._name==="date-range")try{const[...n]=e;return n.map(r=>r===null?r:Y.tz(r,"UTC").format(t.inputFormat)??r)}catch(n){return console.error(n),e}return e}function oS(e){return e.reduce((t,n)=>(t[n.key]=hl(n.config.default_value,n.config),t),{})}const fl=y.types.model("FiltersRenderModel",{current:y.types.optional(y.types.array(rl),[]),values:y.types.optional(y.types.frozen(),{})}).views(e=>({get json(){return e.current.map(t=>t.json)},get firstID(){if(e.current.length!==0)return e.current[0].id},findByID(t){return e.current.find(n=>n.id===t)},get inOrder(){return x.sortBy(e.current,"order")},get empty(){return e.current.length===0},visibleInView(t){return x.sortBy(e.current.filter(n=>n.visibleInViewsIDSet.has(t)),"order")},get firstFilterValueKey(){return Object.keys(e.values)[0]??""},get keyLabelMap(){return e.current.reduce((t,n)=>(t[n.key]=n.label,t),{})},getSelectOption(t){const n=this.findByID(t);if(!n||!("getSelectOption"in n.config))return null;const r=e.values[n.key];return n.config.getSelectOption(r)}})).actions(e=>({setValues(t){e.values=t},setValueByKey(t,n){e.values={...e.values,[t]:n}},getValueByKey(t){return e.values[t]}}));function gl(e){return{current:e,values:oS(e)}}const lS=N1.views(e=>({get conditionOptions(){if(!y.isAlive(e))return[];const t=y.getRoot(e).content,{context:n}=t.payloadForSQL,r=Object.keys(n).map(o=>({group:"Context",label:o,value:`context.${o}`,description:void 0})),a=t.filters.keyLabelOptions.map(o=>({group:"Filters",label:o.label,value:`filters.${o.value}`,description:o.value}));return[...r,...a]},get unmetRunByConditions(){if(!y.isAlive(e))return[];const{run_by:t}=e;if(t.length===0)return[];const n=y.getRoot(e).content.payloadForSQL;return t.filter(r=>{const a=x.get(n,r);return Array.isArray(a)?a.length===0:typeof a=="number"?Number.isNaN(a):!a})}})).views(e=>({get reQueryKey(){const{react_to:t=[]}=e;if(t.length===0)return"";const n=y.getRoot(e).content.payloadForSQL,r=[...t].reduce((a,o)=>(a[o]=x.get(n,o),a),{});return JSON.stringify(r)},get runByConditionsMet(){return e.unmetRunByConditions.length===0},get conditionNames(){if(e.unmetRunByConditions.length===0)return{context:[],filters:[]};const{keyLabelMap:t}=y.getRoot(e).content.filters,n=e.unmetRunByConditions.filter(a=>a.startsWith("context.")).map(a=>a.split("context.")[0]),r=e.unmetRunByConditions.filter(a=>a.startsWith("filters.")).map(a=>x.get({filters:t},a)).filter(a=>!!a);return{context:n,filters:r}},get queries(){return y.getParent(e,2)},get inUse(){return this.queries.isQueryInUse(e.id)}}));function uS(e,t){return new Function(`return ${e}`)()(t,Tt)}function cS(e,t,n){return uS(e,{context:t,filters:n})}function dS(e,t){try{return new Function(`return ${e.config.processing.pre}`)()(t,Tt)}catch(n){return console.error(n),t}}function pS(e,t){return new Function(`return ${e.config.processing.post}`)()(t,Tt)}function hS(e,t){return e?new Function(`return ${e}`)()(t,Tt):t}const fS=y.types.compose("QueryRenderModel",lS,y.types.model({state:y.types.optional(y.types.enumeration(["idle","loading","error"]),"idle"),data:y.types.optional(y.types.frozen([]),[]),error:y.types.frozen()})).views(e=>({get formattedSQL(){const t=y.getRoot(e).content.payloadForSQL;return gr(e.sql,t)},get typedAsSQL(){return[Se.Postgresql,Se.MySQL].includes(e.type)},get typedAsHTTP(){return[Se.HTTP].includes(e.type)},get datasource(){const{key:t,type:n}=e;return y.getRoot(e).datasources.find({type:n,key:t})},get httpConfigString(){const{context:t,filters:n}=y.getRoot(e).content.payloadForSQL,{name:r,pre_process:a}=e.json,o=cS(a,t,n);return console.groupCollapsed(`Request config for: ${r}`),console.log(o),console.groupEnd(),JSON.stringify(o)}})).views(e=>({get stateMessage(){if(e.state!=="idle")return"";if(!e.runByConditionsMet){const{context:t,filters:n}=e.conditionNames;if(t.length===0&&n.length===0)return"Waiting";const r=[];return t.length>0&&r.push(`context: ${t.join(", ")}`),n.length>0&&r.push(`filter${n.length>1?"s":""}: ${n.join(", ")}`),r.length===2&&r.splice(1,0,"and"),r.unshift("Waiting for"),r.join(" ")}return e.data.length>0?"":"Empty Data"}})).volatile(()=>({controller:new AbortController})).actions(e=>({runSQL:y.flow(function*(){var t;if(!e.inUse){console.debug(`Skipping query[${e.name}]`);return}if(e.valid&&((t=e.controller)==null||t.abort(),!!e.runByConditionsMet)){e.controller=new AbortController,e.state="loading";try{const n=y.getRoot(e).content.payloadForSQL;e.data=yield*y.toGenerator(Qu({payload:n,name:e.name,query:e.json},e.controller.signal)),e.state="idle",e.error=null}catch(n){if(!mt.isCancel(n)){e.data=[];const r=x.get(n,"message","unkown error");e.error=x.get(n,"response.data.detail.message",r),e.state="error"}}}}),runHTTP:y.flow(function*(){var t;if(!e.inUse){console.debug(`Skipping query[${e.name}]`);return}if(!(!e.valid||!e.datasource)&&((t=e.controller)==null||t.abort(),!!e.runByConditionsMet)){e.controller=new AbortController,e.state="loading";try{const{type:n,key:r,post_process:a}=e.json;let o=JSON.parse(e.httpConfigString);o=dS(e.datasource,o);const l=yield*y.toGenerator(Uu({type:n,key:r,configString:JSON.stringify(o),name:e.name},e.controller.signal));let u=pS(e.datasource,l);u=hS(a,u),e.data=u,e.state="idle",e.error=null}catch(n){if(console.error(n),!mt.isCancel(n)){e.data=[];const r=x.get(n,"message","unkown error");e.error=x.get(n,"response.data.detail.message",r),e.state="error"}}}})})).actions(e=>({fetchData:()=>e.typedAsHTTP?e.runHTTP():e.runSQL(),beforeDestroy(){var t;(t=e.controller)==null||t.abort()}})).actions(e=>({afterCreate(){y.addDisposer(e,te.reaction(()=>{var t,n;return e.typedAsHTTP?`${e.inUse}--${e.id}--${e.key}--${e.reQueryKey}--${(t=e.datasource)==null?void 0:t.id}`:`${e.inUse}--${e.id}--${e.key}--${e.formattedSQL}--${e.pre_process}--${e.post_process}--${(n=e.datasource)==null?void 0:n.id}`},e.fetchData,{fireImmediately:!0,delay:0}))}})),ml="\uFEFF";function gS(e,t){const n=new Blob([ml+t],{type:"text/csv"});hr.saveAs(n,`${e}.csv`)}function yl(e,t){const n=new Blob([t],{type:"application/json"});hr.saveAs(n,`${e}.json`)}function bl(e){const t=new Lu;e.forEach(({id:n,data:r})=>{t.file(`${n}.csv`,xl(r))}),t.generateAsync({type:"blob"}).then(n=>{hr.saveAs(n,"dashboard_data.zip")})}function vl(e){return typeof e=="string"&&e.includes(",")?`"${e}"`:e}function xl(e){if(!Array.isArray(e)||e.length===0)return"";const t=[],n=Object.keys(e[0]).map(vl);return t.push(n.join(",")),e.forEach(r=>{const a=Object.values(r).map(vl).join(",");t.push(a)}),ml+t.join(`
441
+ `)}const wl=y.types.model("QueriesRenderModel",{current:y.types.optional(y.types.array(fS),[])}).views(e=>({get firstID(){if(e.current.length!==0)return e.current[0].id},findByID(t){return e.current.find(n=>n.id===t)},findByIDSet(t){return e.current.filter(n=>t.has(n.id))},get json(){return e.current.filter(t=>t.id&&t.key).map(t=>t.json)},get contentModel(){return y.getParent(e,1)},get visibleQueryIDSet(){const{views:t,filters:n}=this.contentModel,r=[];t.visibleViews.forEach(l=>{l.panels.forEach(u=>{r.push(...u.queryIDs)})});const a=x.uniq(t.visibleViews.map(l=>l.renderViewIDs).flat());n.current.forEach(l=>{const u=x.get(l,"config.options_query_id");if(!u)return;a.some(d=>l.visibleInViewsIDSet.has(d))&&r.push(u)});const o=new Set(r);return console.debug("QueryIDs:",o),o},isQueryInUse(t){return this.visibleQueryIDSet.has(t)}})).actions(e=>({downloadAllData(){const t=e.current.map(({name:n,data:r})=>({id:n,data:r}));bl(t)},downloadDataByQueryIDs(t){const n=new Set(t),r=e.current.filter(a=>n.has(a.id)).map(({name:a,data:o})=>({id:a,data:o}));bl(r)},downloadDataByQueryID(t){const n=e.findByID(t);if(!n){console.log("[downloadDataByQueryID] query not found");return}const{name:r,data:a}=n,o=xl(a);gS(r,o)},refetchDataByQueryID(t){const n=e.findByID(t);if(!n){console.error(new Error(`[downloadDataByQueryID] query by ID[${t}] not found`));return}return n.fetchData()}}));function mS(e){return{current:e}}const yS=q1.views(e=>({isADuplicatedKey(t){return!t||t===e.key?!1:!!y.getParent(e,2).findByKey(t)}})),Cl=y.types.model("SQLSnippetsRenderModel",{current:y.types.optional(y.types.array(yS),[])}).views(e=>({get json(){return e.current.map(t=>t.json)},get record(){return e.current.reduce((t,n)=>(t[n.key]=n.value,t),{})},get firstKey(){if(e.current.length!==0)return e.current[0].key},findByKey(t){return e.current.find(n=>n.key===t)}}));function bS(e){return{current:e}}function rr(e,t,n,r){return e.reduce((a,o)=>{try{a[o[t]]=fr(o[n],r)}catch(l){a[o[t]]=l.message}return a},{})}class vS{constructor(t){N(this,"origin");N(this,"copy");this.origin=t,this.copy=y.clone(t),te.makeAutoObservable(this,{},{autoBind:!0,deep:!1})}get changed(){return!x.isEqual(y.getSnapshot(this.origin),y.getSnapshot(this.copy))}commit(){y.applySnapshot(this.origin,y.getSnapshot(this.copy))}update(t){y.applySnapshot(this.copy,t)}}const xS=e=>new vS(e),wS=k.observer(({view:e})=>{const t=ce(),n=le(),r=We.useModals(),{panel:a,downloadPanelScreenshot:o}=nt(),{id:l}=a,{viewPanelInFullScreen:u,inFullScreen:c}=b.useContext(tr),d=()=>{n.duplicatePanelByID(l,e.id)},f=()=>{t.editor.open(["_VIEWS_",e.id,"_PANELS_",l])},h=()=>r.openConfirmModal({title:"Delete this panel?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>n.removePanelByID(l,e.id),confirmProps:{color:"red"},zIndex:320}),g=b.useCallback(()=>{u(l)},[l,u]),m=!c&&e.type!==j.Modal;return i(B,{children:i(s.Box,{sx:{position:"absolute",top:0,left:0,right:0,zIndex:300},children:p(s.Menu,{withinPortal:!0,children:[i(s.Menu.Target,{children:i(s.Box,{className:"panel-dropdown-target",sx:{width:"100%",height:"25px"}})}),p(s.Menu.Dropdown,{children:[i(s.Menu.Item,{onClick:a.refreshData,icon:i(T.Refresh,{size:14}),children:"Refresh"}),i(s.Menu.Item,{onClick:a.downloadData,icon:i(T.Download,{size:14}),children:"Download Data"}),i(s.Menu.Item,{onClick:o,icon:i($.IconCamera,{size:14}),children:"Screenshot"}),m&&i(s.Menu.Item,{onClick:g,icon:i(T.ArrowsMaximize,{size:14}),disabled:!0,children:"Full Screen"}),i(s.Divider,{label:"Edit",labelPosition:"center"}),i(s.Menu.Item,{onClick:f,icon:i(T.Settings,{size:14}),children:"Settings"}),i(s.Menu.Item,{onClick:d,icon:i(T.Copy,{size:14}),children:"Duplicate"}),i(s.Menu.Item,{color:"red",onClick:h,icon:i(T.Trash,{size:14}),children:"Delete"})]})]})})})});function CS(e){return e?["<p><br></p>","<p></p>"].includes(e):!0}const Ii=k.observer(()=>{const[e,t]=b.useState(!1),{panel:n}=bt();return CS(n.description)?null:p(B,{children:[i(s.Modal,{opened:e,onClose:()=>t(!1),title:n.title,withCloseButton:!1,withinPortal:!0,zIndex:310,children:i(qn,{value:n.description,styles:{root:{border:"none"},content:{padding:0}}})}),i(s.Tooltip,{label:"Click to see description",position:"top-start",withinPortal:!0,children:i(s.ActionIcon,{variant:"subtle",color:"blue",onClick:()=>t(r=>!r),sx:{verticalAlign:"baseline",cursor:"pointer"},children:i(T.InfoCircle,{size:20})})})]})}),iM="",aM="",SS=k.observer(function(){const{panel:t}=bt(),{title:n}=t;return n?i(s.Group,{grow:!0,position:"center",px:20,className:"panel-title-wrapper",sx:{flexGrow:1},children:i(s.Text,{align:"center",lineClamp:1,weight:"bold",children:n})}):null});function _S(e){const t=b.useRef(null);return{ref:t,downloadPanelScreenshot:()=>{const r=t.current;if(!r)return;const a=r.offsetWidth*2,o=r.offsetHeight*2;Ya.toBlob(t.current,{bgcolor:"white",width:a,height:o,style:{border:"none",borderRadius:0,transformOrigin:"0 0",transform:"scale(2)"}}).then(l=>{window.saveAs(l,`${e.title?e.title:e.viz.type}.png`)})}}}var Sl=(e=>(e.migrated="migrated",e.nothingToMigrate="nothingToMigrate",e.checkFailed="checkFailed",e.migrationFailed="migrationFailed",e))(Sl||{}),ir=(e=>(e.notStarted="notStarted",e.inProgress="inProgress",e.done="done",e))(ir||{});class kS{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(Ce.instanceScope.panelModel),this.vizInstance=t.getRequired(Ce.instanceScope.vizInstance),this.operationManager=t.getRequired(Ce.instanceScope.operationManager),this.triggerManager=t.getRequired(Ce.instanceScope.triggerManager),this.vizManager=t.getRequired(Ce.vizManager)}async createMigrationTask(){const t=[];try{await this.instanceNeedMigration()&&t.push(()=>this.runInstanceMigration()),await this.interactionNeedMigration()&&t.push(()=>this.runInteractionMigration())}catch(n){return console.warn("check migration failed",n),"checkFailed"}if(t.length===0)return"nothingToMigrate";try{return await Promise.all(t.map(n=>n())),"migrated"}catch(n){return console.warn("migration failed",n),"migrationFailed"}}async runMigration(){return this.runningMigration||(this.status="inProgress",this.runningMigration=this.createMigrationTask().then(t=>(this.status="done",t))),this.runningMigration}async runInteractionMigration(){await this.operationManager.runMigration(),await this.triggerManager.runMigration()}async runInstanceMigration(){const t=this.vizManager.resolveComponent(this.vizInstance.type),n={configData:this.vizInstance.instanceData,panelModel:this.panelModel};await t.migrator.migrate(n)}async instanceNeedMigration(){const t=this.vizManager.resolveComponent(this.vizInstance.type),n={configData:this.vizInstance.instanceData};return t.migrator.needMigration(n)}async interactionNeedMigration(){return await this.operationManager.needMigration()||await this.triggerManager.needMigration()}}function _l(e){const{panel:t}=bt();return b.useCallback(n=>{const r=n.getRequired(Ce.vizManager),a=r.resolveComponent(e.viz.type);return n.createScoped().provideFactory(Ce.instanceScope.vizInstance,()=>r.getOrCreateInstance(e)).provideFactory(Ce.instanceScope.interactionManager,o=>{const l=o.getRequired(Ce.instanceScope.vizInstance);return new Dr(l,a,Dn)}).provideFactory(Ce.instanceScope.operationManager,o=>o.getRequired(Ce.instanceScope.interactionManager).operationManager).provideFactory(Ce.instanceScope.triggerManager,o=>o.getRequired(Ce.instanceScope.interactionManager).triggerManager).provideValue(Ce.instanceScope.panelModel,t).provideFactory(Ce.instanceScope.migrator,o=>new kS(o))},[e.viz.type,e.viz.conf])}function kl(e){const[t,n]=b.useState(!1),r=Wo().getRequired(Ce.instanceScope.migrator);return K.useAsyncEffect(async()=>{const a=r.status===ir.notStarted;n(r.status===ir.done),r.status===ir.notStarted&&r.runMigration().then(o=>{o===Sl.migrated&&a&&(e==null||e())}).finally(()=>{n(!0)})},[r]),t}function Tl(e,t){const n=Wo().getRequired(Ce.instanceScope.vizInstance);return b.useEffect(()=>(n.instanceData.setItem(null,t.viz.conf),n.instanceData.watchItem(null,r=>{e(r)})),[e,t.viz.type]),n}function TS({setVizConf:e,...t}){const{panel:n}=t,r=Tl(e,n),a=kl(()=>{vn.showNotification({title:`${n.title} - Updated`,message:"Your plugin configuration has been migrated to the latest version"})});return K.useAsyncEffect(async()=>{await r.instanceData.setItem(null,n.viz.conf)},[r,n.viz.type]),a?i(Zu,{...t}):i(s.Text,{children:"Checking update..."})}function DS(e){const{panel:t,setVizConf:n}=e;Tl(n,t);const{inEditMode:r}=b.useContext(kn);return kl(()=>{r&&vn.showNotification({title:`${t.title} - Updated`,message:"Your plugin configuration has been migrated to the latest version"})})?i(Ju,{...e}):i(s.Text,{children:"Checking update"})}const sM="";function IS(e,t){const{vizManager:n}=b.useContext(ut),{panel:{viz:r,title:a,id:o,description:l,queryIDs:u,variables:c}}=bt(),d={title:a,id:o,description:l,queryIDs:u,viz:r,layout:t},f=_l(d);try{return n.resolveComponent(r.type),i(er,{configure:f,children:i(DS,{setVizConf:r.setConf,panel:d,data:e,variables:c,vizManager:n})})}catch(h){return console.info(x.get(h,"message")),null}}const Dl=k.observer(function({data:t}){const{ref:n,width:r,height:a}=Ie.useElementSize(),o=IS(t,{w:r,h:a}),l=r>0&&a>0;return i("div",{className:"viz-root",ref:n,children:i(s.Box,{sx:{width:r,height:a,overflow:"hidden"},children:l&&i(Fe,{children:o})})})}),Il=k.observer(({panel:e})=>p(s.Stack,{children:[e.queryErrors.map((t,n)=>i(s.Text,{color:"red",size:"sm",align:"center",sx:{fontFamily:"monospace"},children:t},`${n}-${t}`)),i(s.Text,{color:"gray",align:"center",size:"sm",children:e.queryStateMessages})]})),Mi=k.observer(({panel:e,height:t})=>p(s.Flex,{direction:"column",sx:{height:t,position:"relative",width:"100%"},children:[i(s.LoadingOverlay,{visible:e.dataLoading,exitTransitionDuration:0}),!e.canRenderViz&&i(Il,{panel:e}),e.canRenderViz&&i(Dl,{data:e.data})]})),MS={border:"1px solid #e9ecef"},Ml=k.observer(({panel:e,panelStyle:t,dropdownContent:n})=>{const{ref:r,downloadPanelScreenshot:a}=_S(e),o=e.title?"calc(100% - 25px)":"100%";return i(Sr,{value:{panel:e,data:e.data,loading:e.dataLoading,errors:e.queryErrors,downloadPanelScreenshot:a},children:p(s.Box,{className:"panel-root",ref:r,p:0,sx:{...MS,...t},children:[i(s.Box,{sx:{position:"absolute",left:0,top:0,height:28,zIndex:310},children:i(Ii,{})}),n,i(SS,{}),i(Mi,{panel:e,height:o})]})})}),AS={border:"1px dashed transparent",transition:"border-color 300ms ease","&:hover":{borderColor:"#e9ecef"}};function zS(e){return e.style.border.enabled?{}:AS}const Al=k.observer(function({panel:t,view:n}){const r=zS(t);return i(Ml,{panel:t,panelStyle:r,dropdownContent:i(wS,{view:n})})});function ES(e){return!["richText","button"].includes(e)}const $S=k.observer(({view:e})=>{const{panel:t,downloadPanelScreenshot:n}=bt(),{id:r}=t,{viewPanelInFullScreen:a,inFullScreen:o}=b.useContext(tr),l=b.useCallback(()=>{a(r)},[r,a]),u=!o&&e.type!==j.Modal;return ES(t.viz.type)?i(s.Box,{sx:{position:"absolute",top:0,left:0,right:0,zIndex:300},children:p(s.Menu,{withinPortal:!0,children:[i(s.Menu.Target,{children:i(s.Box,{className:"panel-dropdown-target",sx:{width:"100%",height:"25px"}})}),p(s.Menu.Dropdown,{children:[i(s.Menu.Item,{onClick:t.refreshData,icon:i(T.Refresh,{size:14}),children:"Refresh"}),i(s.Menu.Item,{onClick:t.downloadData,icon:i(T.Download,{size:14}),children:"Download Data"}),i(s.Menu.Item,{onClick:n,icon:i($.IconCamera,{size:14}),children:"Screenshot"}),u&&i(s.Menu.Item,{onClick:l,icon:i(T.ArrowsMaximize,{size:14}),children:"Full Screen"})]})]})}):null});function LS(e){return e.style.border.enabled?{}:{border:"1px dashed transparent"}}const Ai=k.observer(({panel:e,view:t})=>{const n=LS(e);return i(Ml,{panel:e,panelStyle:n,dropdownContent:i($S,{view:t})})}),OS={modal:{display:"flex",flexDirection:"column",flexWrap:"nowrap"},body:{display:"flex",height:"calc(100vh - 88px)"}},zl=k.observer(function({view:t,panel:n,exitFullScreen:r}){return i(s.Modal,{opened:!0,fullScreen:!0,onClose:r,title:i(s.Button,{color:"blue",size:"xs",onClick:r,leftIcon:i(T.ArrowLeft,{size:20}),children:"Exit fullscreen"}),styles:OS,children:i(s.Group,{grow:!0,sx:{flexGrow:1,flexShrink:0},children:i(Ai,{view:t,panel:n})})})});function El(e,t,n){const{panels:r}=we(),a=e.id==="Main",[o,l]=b.useState(()=>a&&r.findByID(t)?t:null),u=b.useCallback(h=>{l(h),a&&n(h)},[a,n]),c=b.useCallback(()=>{l(null),a&&n("")},[a,n]),d=o?r.findByID(o):null;return{viewPanelInFullScreen:u,exitFullScreen:c,inFullScreen:!!d,fullScreenPanel:d}}const oM="",PS=b.forwardRef(({h:e},t)=>i(s.ActionIcon,{ref:t,className:"react-grid-customDragHandle",sx:{userSelect:"none",cursor:"grab",position:"absolute",top:5,right:e>38?5:20,zIndex:400,"&:hover":{color:"#228be6"}},variant:"transparent",children:i(T.ArrowsMove,{size:16})})),BS=b.forwardRef(({handleAxis:e,...t},n)=>i(s.ActionIcon,{ref:n,className:"react-grid-customResizeHandle",sx:{userSelect:"none",cursor:"nwse-resize",position:"absolute",bottom:0,right:0,zIndex:400,"&:hover":{color:"#228be6"}},variant:"transparent",...t,children:i(T.ChevronDownRight,{size:16})})),VS=xn.WidthProvider(xn),NS=k.observer(({view:e,className:t="layout"})=>{const n=we(),{panels:r,layouts:a}=n.panels.panelsByIDs(e.panelIDs),o=b.useCallback(u=>{u.forEach(({i:c,...d})=>{const f=n.panels.findByID(c);f&&f.layout.set(d)})},[n]),l=(u,c,d,f)=>{d.h<30&&(d.h=30,f.h=30),d.w<4&&(d.w=4,f.w=4)};return i(VS,{onLayoutChange:o,className:`dashboard-layout ${t}`,rowHeight:1,cols:36,margin:[0,0],isBounded:!0,isDraggable:!0,isResizable:!0,layout:a,draggableHandle:".react-grid-customDragHandle",resizeHandle:i(BS,{}),onResize:l,children:r.map((u,c)=>p("div",{"data-grid":{...u.layout},className:"panel-grid-item",children:[i(PS,{h:u.layout.h}),i(Al,{view:e,panel:u})]},u.id))})}),qS=xn.WidthProvider(xn),FS=k.observer(function({view:t,className:n="layout"}){const{panels:r,layouts:a}=we().panels.panelsByIDs(t.panelIDs);return i(qS,{className:`dashboard-layout ${n}`,cols:36,rowHeight:1,margin:[0,0],isDraggable:!1,isResizable:!1,layout:a,children:r.map(o=>i("div",{"data-grid":{...o.layout},className:"panel-grid-item",children:i(Ai,{view:t,panel:o})},o.id))})});function zi(e){const t=b.useRef(null);return{ref:t,downloadScreenshot:()=>{var l;const r=(l=t.current)==null?void 0:l.querySelector(".react-grid-layout");if(!r)return;const a=r.offsetWidth*2+10,o=r.offsetHeight*2+10;Ya.toBlob(r,{bgcolor:"white",width:a,height:o,style:{transformOrigin:"0 0",transform:"scale(2)"}}).then(u=>{window.saveAs(u,`${e.name}.png`)})}}}const GS=k.observer(({downloadScreenShot:e})=>{const[t,{setTrue:n,setFalse:r}]=K.useBoolean(!1),a=wr(),o=we(),l=()=>{const u=JSON.stringify(o.json,null,2),c=`${a.name}__${o.name}`;yl(c,u)};return p(s.Menu,{shadow:"md",width:200,trigger:"hover",openDelay:200,closeDelay:400,withinPortal:!0,position:"bottom-end",children:[i(s.Menu.Target,{children:i(s.Affix,{position:{bottom:"20px",right:"10px"},zIndex:1,children:i(s.ActionIcon,{size:"md",variant:"gradient",gradient:{from:"indigo",to:"cyan"},onMouseEnter:n,onMouseLeave:r,sx:{opacity:t?1:.6,transform:`translateX(${t?0:"2px"})`,transition:"all ease 300ms",borderRadius:"50%"},children:i($.IconShare3,{size:"1rem"})})})}),p(s.Menu.Dropdown,{children:[i(s.Menu.Item,{icon:i($.IconCamera,{size:14}),onClick:e,children:"Screenshot"}),i(s.Menu.Divider,{}),i(s.Menu.Item,{icon:i($.IconDownload,{size:14}),onClick:o.queries.downloadAllData,children:"Download Data"}),i(s.Menu.Item,{icon:i($.IconCode,{size:14}),onClick:l,children:"Download Schema"})]})]})}),$l=k.observer(({children:e,view:t,sx:n={}})=>{const{ref:r,downloadScreenshot:a}=zi(t);return p(B,{children:[i(s.Box,{ref:r,sx:n,children:e}),i(GS,{downloadScreenShot:a})]})}),Ll=k.observer(({downloadScreenshot:e})=>i(s.ActionIcon,{className:"download-screenshot-button",color:"blue",onClick:e,children:i($.IconCamera,{size:14})})),WS=k.observer(({children:e,view:t})=>{const n=we(),r=t.config,a=n.views.visibleViewIDs.includes(t.id),o=()=>n.views.rmVisibleViewID(t.id),{ref:l,downloadScreenshot:u}=zi(t);return i(s.Modal,{size:r.width,centered:!0,opened:a,onClose:o,withCloseButton:!1,title:p(s.Group,{position:"apart",px:"1rem",h:"48px",children:[i(s.Box,{children:r.custom_modal_title.value}),i(Ll,{downloadScreenshot:u})]}),trapFocus:!0,onDragStart:c=>{c.stopPropagation()},styles:{root:{position:"fixed",zIndex:200,inset:0},overlay:{zIndex:"unset"},inner:{zIndex:"unset",padding:"0 !important"},content:{border:"1px solid #efefef",maxHeight:"unset !important",overflow:"hidden"},body:{maxHeight:r.height,overflow:"auto",position:"relative"},header:{padding:0},title:{flexGrow:1}},transitionProps:{duration:0},children:i(s.Box,{ref:l,children:e})})}),jS=e=>e.color?{"&[data-active], &[data-active]:hover":{borderColor:e.color?e.color:"..."}}:{},RS=k.observer(({view:e})=>{const t=we(),n=e.config;return p(s.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"?"8px 0px 8px":"0",height:"100%",overflow:"auto"}},keepMounted:!1,children:[i(s.Tabs.List,{grow:n.grow,children:n.tabs.map(r=>i(s.Tabs.Tab,{value:r.id,sx:jS(r),disabled:!r.view_id,children:r.name??r.id},r.id))}),n.tabs.map(r=>{const a=t.views.findByID(r.view_id);return a?i(s.Tabs.Panel,{value:r.id,children:i(ar,{view:a})},r.id):null})]})}),YS=k.observer(({view:e,children:t})=>{switch(e.type){case j.Modal:return i(WS,{view:e,children:t});case j.Tabs:return i(RS,{view:e});case j.Division:default:return i($l,{view:e,children:t})}}),QS=k.observer(({children:e,view:t})=>i($l,{sx:{paddingTop:"10px",paddingBottom:"100px"},view:t,children:e}));function Ol(e){return e.replace(/(vw|vh)/,"%")}const US=k.observer(({children:e,view:t})=>{const n=t.config,{width:r,height:a}=b.useMemo(()=>({width:Ol(n.width),height:Ol(n.height)}),[n.width,n.height]),{ref:o,downloadScreenshot:l}=zi(t);return i(s.Box,{sx:{height:"100%","> div:not(.mantine-Modal-root)":{height:"100%"}},children:i(s.Modal,{size:n.width,opened:!0,onClose:x.noop,withCloseButton:!1,title:p(s.Group,{position:"apart",px:"1rem",h:"48px",children:[i(s.Box,{children:n.custom_modal_title.value}),i(Ll,{downloadScreenshot:l})]}),trapFocus:!0,onDragStart:u=>{u.stopPropagation()},styles:{root:{position:"relative",height:"100%"},overlay:{position:"absolute !important"},inner:{position:"relative",top:"50%",left:"50%",right:"unset",bottom:"unset",transform:"translate(-50%, -50%)",padding:"0 !important",width:r,height:a,maxHeight:a},content:{border:"1px solid #efefef",height:"100%"},body:{maxHeight:"calc(100% - 48px)",overflow:"auto"},header:{padding:0},title:{flexGrow:1}},withinPortal:!1,transitionProps:{duration:0},children:i(s.Box,{ref:o,children:e})})})}),KS=({variant:e,orientation:t})=>{const n={root:{height:"100%",overflow:"hidden"},tab:{},panel:{padding:"16px"}};return e==="pills"&&t==="horizontal"&&(n.tab.paddingTop="6px",n.tab.paddingBottom="6px"),t==="vertical"&&(n.tab["&.add-a-tab"]={paddingTop:"1px",paddingBottom:"1px"},n.tab["&.add-a-tab .mantine-Tabs-tabLabel"]={marginLeft:"auto",marginRight:"auto"}),n},XS=e=>e.color?{"&[data-active], &[data-active]:hover":{borderColor:e.color?e.color:"..."}}:{},JS=k.observer(({view:e})=>{const t=We.useModals(),n=le(),r=b.useMemo(()=>n.views.options.filter(u=>u.type===j.Division),[e.id,n.views.options]),a=e.config,o=u=>t.openConfirmModal({title:"Delete this tab?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>{a.removeTab(u)},confirmProps:{color:"red"},zIndex:320}),l=a.tabs.length===0;return p(s.Tabs,{className:"preview-view-tabs",variant:a.variant,orientation:a.orientation,value:e.tab,onTabChange:e.setTab,styles:KS(a),children:[p(s.Tabs.List,{grow:a.grow,children:[a.tabs.map(u=>i(s.Tabs.Tab,{value:u.id,sx:XS(u),children:u.name??u.id},u.id)),i(s.Tabs.Tab,{onClick:a.addTab,value:"add",className:"add-a-tab",children:i(T.Plus,{size:18,color:"#228be6"})})]}),a.tabs.map((u,c)=>{const d=n.views.findByID(u.view_id);return p(s.Tabs.Panel,{value:u.id,sx:{position:"relative"},children:[p(s.Box,{sx:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:200},children:[i(s.Overlay,{opacity:.8,color:"#FFF",blur:10,zIndex:100}),p(s.Stack,{mx:"auto",mt:100,sx:{width:"300px",position:"relative",zIndex:200},children:[i(s.TextInput,{label:"Tab Name",value:u.name,onChange:f=>u.setName(f.currentTarget.value)}),i(s.Select,{label:"View",value:u.view_id,onChange:u.setViewID,data:r}),i(s.ColorInput,{label:"Color",value:u.color,onChange:u.setColor,disabled:a.variant!=="default"}),d&&p(s.Button,{mt:20,variant:"gradient",leftIcon:i($.IconArrowsLeftRight,{size:18}),gradient:{from:"cyan",to:"indigo"},onClick:()=>n.views.setIDOfVIE(d.id),children:["Swith to View: ",d.name]}),i(s.Button,{mt:20,variant:"subtle",color:"red",onClick:()=>o(c),disabled:l,leftIcon:i($.IconTrash,{size:14}),children:"Delete This Tab"})]})]}),d&&i(ar,{view:d})]},u.id)})]})}),ZS=k.observer(({view:e,children:t})=>{switch(e.type){case j.Modal:return i(US,{view:e,children:t});case j.Tabs:return i(JS,{view:e});case j.Division:default:return i(QS,{view:e,children:t})}}),Pl=k.observer(function({view:t}){return i(tr.Provider,{value:{viewPanelInFullScreen:x.noop,inFullScreen:!1},children:i(s.Box,{className:"dashboard-view","data-enable-scrollbar":!0,children:i(ZS,{view:t,children:p(s.Box,{sx:{position:"relative"},children:[i(s.Box,{className:"dashboard-sticky-area",sx:{position:"sticky",top:"0px"},children:i(Yo,{view:t})}),i(NS,{view:t})]})})})})}),ar=k.observer(function({view:t}){const{fullScreenPanelID:n,setFullScreenPanelID:r}=ss(),{viewPanelInFullScreen:a,exitFullScreen:o,inFullScreen:l,fullScreenPanel:u}=El(t,n,r);return i(tr.Provider,{value:{viewPanelInFullScreen:a,inFullScreen:l},children:p(s.Box,{className:"dashboard-view","data-enable-scrollbar":!0,sx:{height:t.type===j.Modal?"0 !important":"100%"},children:[l&&i(zl,{view:t,panel:u,exitFullScreen:o}),i(YS,{view:t,children:p(s.Box,{sx:{position:"relative"},children:[!l&&i(s.Box,{className:"dashboard-sticky-area",sx:{position:"sticky",top:"0px"},children:i(Yo,{view:t})}),!l&&i(FS,{view:t})]})})]})})});var Bl=(e=>(e.Use="use",e.Edit="edit",e))(Bl||{});const HS={[j.Division]:"Division",[j.Tabs]:"Tabs",[j.Modal]:"Modal"},Vl={[j.Division]:"rgba(255, 0, 0, 0.2)",[j.Modal]:"rgba(0, 0, 0, 0.2)",[j.Tabs]:"rgba(255, 200, 100, 0.4)"},e_={[j.Division]:"#ff4000",[j.Modal]:"#000",[j.Tabs]:"#ffad18"},t_={definition:{sqlSnippets:[],queries:[],mock_context:{}},views:[{id:"Main",name:"Main",type:j.Division,config:{},panelIDs:[]}],panels:[],filters:[],version:"9.19.0"};function n_(e,t,n){y.addDisposer(e,y.addMiddleware(e,(r,a)=>{a(r,()=>{y.getType(r.context)===t&&r.type==="action"&&n(r.name,r.context)})}))}const Nl=y.types.compose("FiltersModel",fl,y.types.model("FiltersModel",{previewValues:y.types.optional(y.types.frozen(),{})})).views(e=>({get options(){return e.current.map(t=>({label:t.label??t.id,value:t.id,_type:"filter"}))},get selects(){return e.current.filter(t=>t.type===_e.Select).map(t=>({label:t.label??t.id,value:t.id}))},get keyLabelOptions(){return e.current.map(t=>({label:t.label??t.key,value:t.key}))}})).actions(e=>({replace(t){e.current=y.cast(t)},append(t){e.current.push(t)},remove(t){e.current.splice(t,1)},removeByID(t){const n=e.current.findIndex(r=>r.id===t);n>=0&&e.current.splice(n,1)},updatePreviewValues(t){e.previewValues=t}})).actions(e=>{function t(){n_(e.current,rl,(n,r)=>{if(n==="setType"){const a=hl(r.config.default_value,r.config);e.setValueByKey(r.key,a),e.updatePreviewValues({...e.previewValues,[r.key]:a})}})}return{afterCreate(){t()}}}),ql=wl.views(e=>({get options(){const t=e.current.map(n=>({value:n.id,label:n.name,_type:"query"}));return x.sortBy(t,n=>n.label.toLowerCase())},get sortedList(){return x.sortBy(e.current,t=>t.name.toLowerCase())}})).actions(e=>({replace(t){e.current=y.cast(t)},append(t){e.current.push(t)},remove(t){e.current.splice(t,1)},replaceByIndex(t,n){e.current.splice(t,1,n)},removeQuery(t){const n=e.current.find(r=>r.id===t);n&&(y.detach(n),e.current.remove(n))},removeQueries(t){const n=new Set(t);e.current.forEach(a=>{n.has(a.id)&&y.detach(a)});const r=[...e.current];x.remove(r,a=>n.has(a.id)),e.current=y.cast(r)}})),Fl=Cl.views(e=>({get sortedList(){return x.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 x.sortBy(t,n=>n.label.toLowerCase())}})).actions(e=>({replace(t){e.current=y.cast(t)},append(t){e.current.push(t)},remove(t){e.current.splice(t,1)},removeByKey(t){const n=e.current.findIndex(r=>r.key===t);n>=0&&e.current.splice(n,1)},removeByKeys(t){const n=new Set(t);e.current.forEach(a=>{n.has(a.key)&&y.detach(a)});const r=[...e.current];x.remove(r,a=>n.has(a.key)),e.current=y.cast(r)},replaceByIndex(t,n){e.current.splice(t,1,n)}})),r_=y.types.model({data:y.types.optional(y.types.frozen(),[]),state:y.types.optional(y.types.enumeration(["idle","loading","error"]),"idle"),error:y.types.frozen()}).views(e=>({get loading(){return e.state==="loading"},get empty(){return e.data.length===0},get sql(){const t=y.getParent(e,1),{type:n,table_name:r,table_schema:a}=t;if(n===Se.MySQL)return`
442
442
  SELECT ordinal_position, column_key, column_name, column_type, is_nullable, column_default, column_comment
443
443
  FROM information_schema.columns
444
444
  WHERE table_name = '${r}' AND table_schema = '${a}'
@@ -459,7 +459,7 @@ Check the top-level render call using <`+V+">.")}return E}}function Su(S,E){{if(
459
459
  LEFT JOIN pg_constraint pc ON pc.conrelid = ${o} AND ordinal_position = any(pc.conkey)
460
460
  WHERE
461
461
  table_name = '${r}' AND table_schema = '${a}';
462
- `}return""}})),i_=b.types.model({data:b.types.optional(b.types.frozen(),[]),state:b.types.optional(b.types.enumeration(["idle","loading","error"]),"idle"),error:b.types.frozen()}).views(e=>({get loading(){return e.state==="loading"},get empty(){return e.data.length===0},get sql(){const t=b.getParent(e,1),{type:n,table_name:r,table_schema:a}=t;return n===Se.MySQL?`
462
+ `}return""}})),i_=y.types.model({data:y.types.optional(y.types.frozen(),[]),state:y.types.optional(y.types.enumeration(["idle","loading","error"]),"idle"),error:y.types.frozen()}).views(e=>({get loading(){return e.state==="loading"},get empty(){return e.data.length===0},get sql(){const t=y.getParent(e,1),{type:n,table_name:r,table_schema:a}=t;return n===Se.MySQL?`
463
463
  SELECT
464
464
  sub_part AS index_length,
465
465
  index_name AS index_name,
@@ -494,21 +494,21 @@ Check the top-level render call using <`+V+">.")}return E}}function Su(S,E){{if(
494
494
  JOIN pg_am AS am ON ix.relam = am.oid
495
495
  WHERE
496
496
  t.relname = '${r}' AND n.nspname = '${a}';
497
- `:""}})),a_=b.types.model({page:b.types.optional(b.types.number,1),limit:b.types.optional(b.types.number,20),data:b.types.optional(b.types.frozen(),[]),total:b.types.optional(b.types.number,0),state:b.types.optional(b.types.enumeration(["idle","loading","error"]),"idle"),error:b.types.frozen()}).views(e=>({get keywords(){return b.getParent(e,1)},get keywordString(){const{table_name:t,table_schema:n}=b.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 sql(){const t=b.getParent(e,1),{table_name:n,table_schema:r}=t;return`
497
+ `:""}})),a_=y.types.model({page:y.types.optional(y.types.number,1),limit:y.types.optional(y.types.number,20),data:y.types.optional(y.types.frozen(),[]),total:y.types.optional(y.types.number,0),state:y.types.optional(y.types.enumeration(["idle","loading","error"]),"idle"),error:y.types.frozen()}).views(e=>({get keywords(){return y.getParent(e,1)},get keywordString(){const{table_name:t,table_schema:n}=y.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 sql(){const t=y.getParent(e,1),{table_name:n,table_schema:r}=t;return`
498
498
  SELECT *
499
499
  FROM ${r}.${n}
500
500
  LIMIT ${e.limit} OFFSET ${(e.page-1)*e.limit}
501
501
  `},get countSql(){const{table_name:t,table_schema:n}=e.keywords;return`
502
502
  SELECT count(*) AS total
503
503
  FROM ${n}.${t}
504
- `}})).actions(e=>({setPage(t){e.page=t},resetPage(){e.page=1},setLimit(t){e.limit=t}})).actions(e=>({afterCreate(){b.addDisposer(e,te.reaction(()=>e.keywordString,e.resetPage,{fireImmediately:!1,delay:0})),b.addDisposer(e,te.reaction(()=>e.limit,e.resetPage,{fireImmediately:!1,delay:0}))}})),s_=b.types.model({data:b.types.optional(b.types.frozen(),{}),state:b.types.optional(b.types.enumeration(["idle","loading","error"]),"idle"),error:b.types.frozen()}).views(e=>({get loading(){return e.state==="loading"},get empty(){return Object.keys(e.data).length===0},get sql(){const t=b.getParent(e,1).type;return t===Se.MySQL||t===Se.Postgresql?"SELECT table_schema, table_name, table_type FROM information_schema.tables ORDER BY table_schema, table_name":""}})),o_=b.types.compose("DataSourceModel",ol,b.types.model({tables:b.types.optional(s_,{}),columns:b.types.optional(r_,{}),tableData:b.types.optional(a_,{}),indexes:b.types.optional(i_,{}),table_schema:b.types.optional(b.types.string,""),table_name:b.types.optional(b.types.string,"")})).volatile(()=>({controllers:{tables:new AbortController,columns:new AbortController,indexes:new AbortController,tableData:new AbortController}})).actions(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=b.flow(function*(){var n;(n=e.controllers.tables)==null||n.abort(),e.controllers.tables=new AbortController,e.tables.state="loading";try{const r=yield*b.toGenerator(qe.query(e.controllers.tables.signal)({type:e.type,key:e.key,query:e.tables.sql},{}));e.tables.data=x.groupBy(r,"table_schema"),e.tables.state="idle",e.tables.error=null,e.initKeywords()}catch(r){if(!mt.isCancel(r)){e.tables.data={};const a=x.get(r,"message","unkown error");e.tables.error=x.get(r,"response.data.detail.message",a),e.tables.state="error"}}});return{loadTables:t,loadTablesIfEmpty(){e.tables.empty&&t()},loadColumns:b.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*b.toGenerator(qe.query(e.controllers.columns.signal)({type:e.type,key:e.key,query:e.columns.sql},{})),e.columns.state="idle",e.columns.error=null}catch(r){if(mt.isCancel(r))e.columns.state="idle",e.columns.error=null;else{e.columns.data=[];const a=x.get(r,"message","unkown error");e.columns.error=x.get(r,"response.data.detail.message",a),e.columns.state="error"}}}),loadIndexes:b.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*b.toGenerator(qe.query(e.controllers.indexes.signal)({type:e.type,key:e.key,query:e.indexes.sql},{})),e.indexes.state="idle",e.indexes.error=null}catch(r){if(mt.isCancel(r))e.indexes.state="idle",e.indexes.error=null;else{e.indexes.data=[];const a=x.get(r,"message","unkown error");e.indexes.error=x.get(r,"response.data.detail.message",a),e.indexes.state="error"}}}),loadTableData:b.flow(function*(){var r;(r=e.controllers.tableData)==null||r.abort(),e.controllers.tableData=new AbortController;const n=e.tableData;n.state="loading";try{n.data=yield*b.toGenerator(qe.query(e.controllers.tableData.signal)({type:e.type,key:e.key,query:n.sql},{}));const[{total:a}]=yield*b.toGenerator(qe.query(e.controllers.tableData.signal)({type:e.type,key:e.key,query:n.countSql},{}));n.total=Number(a),n.state="idle",n.error=null}catch(a){if(mt.isCancel(a))n.state="idle",n.error=null;else{n.data=[];const o=x.get(a,"message","unkown error");n.error=x.get(a,"response.data.detail.message",o),n.state="error"}}})}}).actions(e=>({afterCreate(){b.addDisposer(e,te.reaction(()=>e.columns.sql,e.loadColumns,{fireImmediately:!1,delay:500}))}})).actions(e=>({afterCreate(){b.addDisposer(e,te.reaction(()=>e.indexes.sql,e.loadIndexes,{fireImmediately:!1,delay:500})),b.addDisposer(e,te.reaction(()=>e.tableData.sql,e.loadTableData,{fireImmediately:!1,delay:0}))}})),l_=b.types.model("DataSourcesModel",{list:b.types.optional(b.types.array(o_),[])}).views(e=>({find({type:t,key:n}){return e.list.find(r=>r.key===n&&r.type===t)},get options(){return e.list.map(t=>({value:t.key,label:t.key}))}})).actions(e=>({replace(t){e.list.length=0,e.list.push(...t)}}));function pn(e){return{label:e,value:e,_type:"ACTION",_action_type:e,Icon:null,children:null}}function u_(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 c_=b.types.model("EditorModel",{path:b.types.optional(b.types.frozen(),[]),settings_open:b.types.optional(b.types.boolean,!1)}).views(e=>({get navOptions(){const{content:t}=b.getRoot(e),{filters:n,views:r,sqlSnippets:a,queries:o}=t;return[{label:"Query Variables",value:"_QUERY_VARS_",_type:"query_variables",Icon:$.IconVariable},{label:"Mock Context",value:"_MOCK_CONTEXT_",Icon:$.IconCodeDots,_type:"mock_context"},{label:"Filters",value:"_FILTERS_",Icon:$.IconFilter,children:[...n.options,pn("_Add_A_Filter_")],_type:"GROUP"},{label:"SQL Snippets",value:"_SQL_SNIPPETS_",Icon:$.IconCopy,children:[...a.options,pn("_Add_A_SQL_SNIPPET_")],_type:"GROUP"},{label:"Queries",value:"_QUERIES_",Icon:$.IconDatabase,children:[pn("_QUERIES_SETTINGS_"),...o.options,pn("_Add_A_QUERY_")],_type:"GROUP"},{label:"Views",value:"_VIEWS_",Icon:$.IconBoxMultiple,children:[...r.editorOptions,pn("_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=u_(t);n&&e.setPath(n)}})),Gl=dl.views(e=>({get dataFieldOptions(){return e.queryIDs.length===0?[]:e.queries.map(t=>{const n=t.data;return n.length===0?[]:Object.keys(n[0]).map(a=>({label:a,value:`${t.id}.${a}`,group:t.name}))}).flat()}})).actions(e=>({removeSelf(){b.getParent(e,2).removeByID(e.id)}})).actions(e=>({moveToView(t,n){b.getRoot(e).content.views.findByID(t).removePanelID(e.id),b.getRoot(e).content.views.findByID(n).appendPanelID(e.id),b.getRoot(e).editor.setPath(["_VIEWS_",n,"_PANELS_",e.id])}})),Wl=b.types.compose("PanelsModel",pl,b.types.model({list:b.types.optional(b.types.array(Gl),[])})).views(e=>({editorOptions(t,n){const{panels:r}=e.panelsByIDs(n);r.length!==n.length&&console.warn(`Unfulfilled panels for View[${t}]`);const a=r.map(l=>({label:l.title?l.title:x.capitalize(l.viz.type),value:l.id,_type:"panel",parentID:t})),o="_Add_A_PANEL_";return a.push({label:o,value:o,_type:"ACTION",_action_type:o,parentID:t,Icon:null,children:null}),a}})).actions(e=>({replace(t){e.list=b.castToSnapshot(t)},append(t){e.list.push(t)},remove(t){e.list.splice(t,1)},removeByID(t){const n=e.list.findIndex(r=>r.id===t);n!==-1&&e.list.splice(n,1)},removeByIDs(t){t.forEach(n=>{this.removeByID(n)})},duplicateByID(t){const n=e.list.find(a=>a.id===t);if(!n){console.error(new Error(`[duplicate panel] Can't find a panel by id[${t}]`));return}const r=new Date().getTime().toString();return e.list.push({...n.json,id:r,layout:{...n.layout,y:1/0,moved:!1}}),r},replaceByIndex(t,n){e.list.splice(t,1,n)}})),jl=b.types.compose("ViewsModel",cl,b.types.model({idOfVIE:b.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=b.getRoot(e).content.panels;return e.current.map(n=>({label:n.name,value:n.id,_type:"view",children:t.editorOptions(n.id,n.panelIDs)}))}})).actions(e=>({setIDOfVIE(t){e.idOfVIE=t,e.visibleViewIDs.length=0,e.visibleViewIDs.push(t)},replace(t){e.current.replace(t)},addANewView(t,n,r,a){e.current.push({id:t,name:n,type:r,config:a,panelIDs:[]})},append(t){e.current.push(t)},remove(t){e.current.splice(t,1)},removeByID(t){const n=e.current.findIndex(o=>o.id===t);if(n===-1)return;const r=e.current[n];b.getRoot(e).content.panels.removeByIDs(r.panelIDs),e.current.splice(n,1)},replaceByIndex(t,n){e.current.splice(t,1,n)},addARandomNewView(){const t=new Date().getTime().toString();this.addANewView(t,j.Division,j.Division,{_name:j.Division}),this.setIDOfVIE(t)},removeVIE(){e.current.length!==1&&(this.removeByID(e.idOfVIE),this.setIDOfVIE(e.current[0].id))}}));function Ei(e){const t=e.length>0?[e[0].id]:[],n=e.length>0?e[0].id:"";return{current:e.map(a=>{const{_name:o=a.type}=a.config;return{...a,config:{...a.config,_name:o},panelIDs:a.panelIDs}}),visibleViewIDs:t,idOfVIE:n}}const d_=b.types.model({id:b.types.string,name:b.types.string,dashboard_id:b.types.string,create_time:b.types.string,update_time:b.types.string,version:b.types.string,filters:Nl,queries:ql,sqlSnippets:Fl,views:jl,panels:Wl,mock_context:Qo,origin:b.types.maybe(b.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,definition:{queries:e.queries.json,sqlSnippets:e.sqlSnippets.json,mock_context:e.mock_context.current}}}},get filtersChanged(){const t="filters.current";return!x.isEqual(b.getSnapshot(x.get(e,t)),x.get(e.origin,t))},get queriesChanged(){const t="queries.current",n=b.getSnapshot(x.get(e,t)).map(r=>x.pick(r,["id","name","key","type","sql","run_by","react_to","pre_process","post_process"]));return!x.isEqual(n,x.get(e.origin,t))},get sqlSnippetsChanged(){const t="sqlSnippets.current";return!x.isEqual(b.getSnapshot(x.get(e,t)),x.get(e.origin,t))},get viewsChanged(){const t="views.current";return!x.isEqual(e.views.json,x.get(e.origin,t))},get panelsChanged(){const t="panels.list";return!x.isEqual(b.getSnapshot(x.get(e,t)),x.get(e.origin,t))},get mockContextChanged(){const t="mock_context.current";return!x.isEqual(x.get(e,t),x.get(e.origin,t))},get payloadForSQL(){const t=b.getParent(e).context.current,n=b.getParent(e).globalSQLSnippets,r={context:{...e.mock_context.current,...t},filters:e.filters.values};return{...r,sql_snippets:rr(e.sqlSnippets.current,"key","value",r),global_sql_snippets:rr(n.list,"id","content",r)}},get payloadForViz(){const t=b.getParent(e).context.current;return{context:{...e.mock_context.current,...t},filters:e.filters.values}},get changed(){return this.filtersChanged||this.queriesChanged||this.sqlSnippetsChanged||this.viewsChanged||this.panelsChanged||this.mockContextChanged},get data(){return e.queries.current.map(({id:n,data:r})=>({id:n,data:r})).reduce((n,r)=>(n[r.id]=r.data,n),{})},getDataStuffByID(t){const n=e.queries.findByID(t);return n?{data:n.data,len:n.data.length,state:n.state,error:n.error}:{data:[],len:0,state:"idle",error:void 0}}})).views(e=>({get queriesUsage(){const t=e.panels.idMap,n=[];e.views.current.forEach(a=>{a.panelIDs.forEach(o=>{const l=t.get(o);if(!l)return;const u="panel",c=l.title?l.title:l.viz.type,d=[{id:a.id,label:a.name}];l.queryIDs.forEach(f=>{n.push({id:o,queryID:f,type:u,label:c,views:d})})})});const r=e.views.idMap;return e.filters.current.filter(a=>!!x.get(a,"config.options_query_id")).map(a=>({type:"filter",id:a.id,queryID:x.get(a,"config.options_query_id"),label:a.label,views:a.visibleInViewsIDs.map(o=>{var l;return{id:o,label:((l=r.get(o))==null?void 0:l.name)??o}})})),x.groupBy(n,"queryID")},get hasUnusedQueries(){return e.queries.current.length>Object.keys(this.queriesUsage).length},findQueryUsage(t){return this.queriesUsage[t]??[]}})).actions(e=>({removeUnusedQueries(){const t=new Set(Object.keys(e.queriesUsage)),n=e.queries.current.filter(r=>!t.has(r.id)).map(r=>r.id);e.queries.removeQueries(n)},duplicatePanelByID(t,n){var a;const r=e.panels.duplicateByID(t);r&&((a=e.views.findByID(n))==null||a.appendPanelID(r))},removePanelByID(t,n){var r;e.panels.removeByID(t),(r=e.views.findByID(n))==null||r.removePanelID(t)},addANewPanel(t){var r;const n=new Date().getTime().toString();e.panels.append(sS(n)),(r=e.views.findByID(t))==null||r.appendPanelID(n)}})).actions(e=>({reset(){b.applySnapshot(e.filters.current,e.origin.filters.current),b.applySnapshot(e.queries.current,e.origin.queries.current),b.applySnapshot(e.sqlSnippets.current,e.origin.sqlSnippets.current),b.applySnapshot(e.views.current,e.origin.views.current),b.applySnapshot(e.panels.list,e.origin.panels.list),e.mock_context.current=e.origin.mock_context.current},resetFilters(){b.applySnapshot(e.filters.current,e.origin.filters.current)},updateCurrent(t){const{id:n,name:r,content:a}=t;if(!a)throw new Error("unexpected null content when updating a content model");const{version:o,filters:l,views:u,panels:c,definition:{queries:d,sqlSnippets:f,mock_context:h={}}}=a;e.id=n,e.name=r,e.version=o,b.applySnapshot(e.filters.current,l),b.applySnapshot(e.views.current,Ei(u).current),b.applySnapshot(e.panels.list,c),b.applySnapshot(e.queries.current,d),b.applySnapshot(e.sqlSnippets.current,f),e.mock_context.current=h}})),$i=b.types.snapshotProcessor(d_,{preProcessor(e){return{...e,origin:e}},postProcessor(e){delete e.origin;const t=b.castToSnapshot(e.queries.current.map(n=>x.pick(n,["id","key","type","sql"])));return x.defaults({},{queries:{current:t}},e)}});function p_(e,t){t.filters&&b.applySnapshot(e.filters.current,t.filters)}function Rl({id:e,name:t,dashboard_id:n,create_time:r,update_time:a,content:o}){if(!o)throw new Error("unexpected null content when creating a content model");const{version:l,filters:u,views:c,panels:d,definition:{queries:f,sqlSnippets:h,mock_context:g={}}}=o;return $i.create({id:e,name:t,dashboard_id:n,create_time:r,update_time:a,version:l,filters:gl(u),queries:{current:f},sqlSnippets:{current:h},mock_context:Uo(g),views:Ei(c),panels:{list:d}})}const Yl=b.types.model({id:b.types.identifier,name:b.types.string,group:b.types.string,content:$i,content_id:b.types.string,datasources:l_,globalSQLSnippets:ll,context:Di,editor:c_}).views(e=>({get json(){return{id:e.id,name:e.name,group:e.group,content_id:e.content_id}}})).actions(e=>({updateCurrentContent(t){e.content.updateCurrent(t)},updateCurrent(t,n){const{id:r,name:a,group:o,content_id:l}=t;e.id=r,e.name=a,e.group=o,e.content_id=l,this.updateCurrentContent(n)}}));function Ql({id:e,name:t,group:n,content_id:r},a,o,l,u){return Yl.create({id:e,name:t,group:n,content_id:r,content:Rl(a),datasources:{list:o},globalSQLSnippets:{list:l},context:ul(u),editor:{}})}function Ul(e,t){y.useEffect(()=>{const n=r=>{console.log(r);const{viewID:a}=r.detail;if(!a){console.error(new Error("[Open View] Needs to pick a view first"));return}e.views.appendToVisibles(a),t&&e.views.setIDOfVIE(a)};return window.addEventListener("open-view",n),()=>{window.removeEventListener("open-view",n)}},[e,t]),y.useEffect(()=>{const n=r=>{console.log(r);const{dictionary:a,payload:o}=r.detail;if(!o||Object.keys(o).length===0){console.error(new Error("[Set Filter Values] payload is empty"));return}Object.entries(a).forEach(([l,u])=>{e.filters.setValueByKey(l,x.get(o,u))})};return window.addEventListener("set-filter-values",n),()=>{window.removeEventListener("set-filter-values",n)}},[e]),y.useEffect(()=>{function n(a){return Array.isArray(a)?[]:typeof a=="object"?{}:typeof a=="boolean"?!1:typeof a=="string"?"":typeof a=="number"?0:a}const r=a=>{console.log(a);const{filter_keys:o}=a.detail;o.forEach(l=>{const u=x.get(e.filters.values,l),c=n(u);console.log(`${l}: ${c}`),e.filters.setValueByKey(l,c)})};return window.addEventListener("clear-filter-values",r),()=>{window.removeEventListener("clear-filter-values",r)}},[e]),y.useEffect(()=>{const n=r=>{console.log(r);const{urlTemplate:a,openInNewTab:o,enableEncoding:l=!1,payload:u}=r.detail;if(!a){console.error(new Error("[Open Link] URL is empty"));return}function c(h){return x.cloneDeepWith(h,m=>{if(l&&typeof m=="string")return encodeURIComponent(m)})}const f=x.template(a||"")(c({...u,filters:e.payloadForSQL.filters,context:e.payloadForSQL.context}));window.open(f,o?"_blank":"_self","noopener")};return window.addEventListener("open-link",n),()=>{window.removeEventListener("open-link",n)}},[e])}function Kl(e){return y.useCallback(t=>t.provideValue(Ce.pluginManager,e.pluginManager).provideValue(Ce.vizManager,e.vizManager).provideValue(Ce.colorManager,e.colorManager),[])}const aM="",h_=k.observer(()=>{const e=wr(),t=le(),n=()=>{const r=JSON.stringify(t.json,null,2),a=`${e.name}__${t.name}`;yl(a,r)};return p(s.Menu,{shadow:"md",width:200,trigger:"hover",openDelay:100,closeDelay:400,withinPortal:!0,zIndex:310,children:[i(s.Menu.Target,{children:i(s.ActionIcon,{variant:"light",color:"blue",children:i($.IconMenu2,{size:14})})}),p(s.Menu.Dropdown,{children:[i(s.Menu.Item,{icon:i($.IconDownload,{size:14}),onClick:t.queries.downloadAllData,children:"Download Data"}),i(s.Menu.Item,{icon:i($.IconCode,{size:14}),onClick:n,children:"Download Schema"})]})]})}),f_=k.observer(({saveDashboardChanges:e})=>{const t=Qe.useModals(),n=le(),r=()=>{t.openConfirmModal({title:p(s.Group,{position:"left",children:[i($.IconAlertTriangle,{size:18,color:"red"}),i(s.Text,{children:"You are reverting changes"})]}),labels:{confirm:"Confirm",cancel:"Cancel"},confirmProps:{color:"red"},onCancel:()=>console.log("Cancel"),onConfirm:()=>n.reset(),zIndex:320,withCloseButton:!1})},a=n.changed;return p(s.Group,{spacing:0,children:[i(s.Button,{color:"green",variant:"filled",size:"xs",leftIcon:i($.IconDeviceFloppy,{size:18}),onClick:e,disabled:!a,sx:{borderTopRightRadius:0,borderBottomRightRadius:0},children:"Save Changes"}),p(s.Menu,{width:200,trigger:"hover",openDelay:100,closeDelay:400,withinPortal:!0,zIndex:320,disabled:!a,children:[i(s.Menu.Target,{children:i(s.ActionIcon,{variant:"default",disabled:!a,sx:{height:"30px",borderTopLeftRadius:0,borderBottomLeftRadius:0,svg:{fill:"rgb(173, 181, 189)",stroke:"none"}},children:i($.IconCaretDown,{size:18})})}),i(s.Menu.Dropdown,{children:i(s.Menu.Item,{icon:i($.IconRecycle,{size:14,color:"red"}),disabled:!a,onClick:r,children:"Revert Changes"})})]})]})}),g_=k.observer(({saveDashboardChanges:e,headerSlot:t=null})=>{const n=Ou.useNavigate(),r=pe(),a=()=>{n(`/dashboard/${r.id}`)},o=Qe.useModals(),l=()=>{o.openConfirmModal({title:p(s.Group,{position:"left",children:[i($.IconAlertTriangle,{size:18,color:"red"}),i(s.Text,{children:"There are unsaved changes"})]}),labels:{confirm:"Discard",cancel:"Cancel"},confirmProps:{color:"red"},onCancel:()=>console.log("Cancel"),onConfirm:a,zIndex:320,withCloseButton:!1})},u=r.content.changed;return i(s.Header,{height:60,px:"md",py:0,sx:{zIndex:299},children:p(s.Group,{position:"apart",sx:{height:60,minWidth:"1000px",position:"relative"},children:[p(s.Group,{children:[i(s.Button,{size:"xs",color:u?"red":"green",leftIcon:i($.IconArrowLeft,{size:20}),onClick:u?l:a,children:p(s.Group,{spacing:4,children:["End Editing",i(s.Text,{td:"underline",children:r.name})]})}),i(f_,{saveDashboardChanges:e})]}),p(s.Group,{position:"right",sx:{flexGrow:1},children:[t,i(h_,{})]})]})})}),m_={position:"fixed",top:60,left:0,right:0,height:30,zIndex:299,borderBottom:"1px solid #e9ecef",background:"rgba(233,236,239, 0.15)"},y_=k.observer(()=>{var n;const e=le(),t=((n=e.views.VIE)==null?void 0:n.type)===j.Tabs;return i(s.Box,{sx:m_,pl:{base:200,xs:200,sm:200,md:220,lg:240,xl:260},children:p(s.Group,{position:"apart",align:"center",sx:{height:"30px"},pr:16,children:[i(s.Button,{variant:"outline",color:"blue",radius:0,size:"xs",disabled:!e.views.VIE||t,onClick:()=>e.addANewPanel(e.views.idOfVIE),leftIcon:i($.IconPlaylistAdd,{size:20}),sx:{height:"30px",borderLeft:"none",borderTop:"none",borderRight:"1px solid #e9ecef",borderBottom:"1px solid #e9ecef",background:"rgb(231, 245, 255)"},children:"Add a Panel"}),i(s.Box,{}),i(s.Box,{})]})})}),b_=k.observer(e=>p(B,{children:[i(g_,{...e}),i(y_,{})]})),sM="";function v_(e,t,n){const r=[];return e.filter(a=>"__INTERACTIONS"in a.viz.conf).forEach((a,o)=>{const l=t[a.id];l.data.interactions=x.get(l,"data.interactions",[]);const{__INTERACTIONS:u,__OPERATIONS:c,__TRIGGERS:d}=a.viz.conf;Object.entries(c).forEach(([f,h])=>{const{schemaRef:g,data:m}=h,{config:C}=m;switch(g){case"builtin:op:open-link":let w=C.urlTemplate.substring(0,100);C.urlTemplate.length>=20&&(w+="..."),l.type="interaction",l.data.interactions.push({schemaRef:g,urlTemplate:C.urlTemplate,shortURLTemplate:w});return;case"builtin:op:open_view":r.push({id:`OPERATION--${f}`,source:a.id,target:C.viewID,label:"Open View",style:{stroke:"rgba(0,0,0,0.8)"},type:"default"});return;case"builtin:op:set_filter_values":l.type="interaction",l.data.interactions.push({schemaRef:g,filters:Object.keys(C.dictionary).map(_=>({key:_,label:n[_]}))});return;case"builtin:op:clear_filter_values":l.type="interaction",l.data.interactions.push({schemaRef:g,filters:C.filter_keys.map(_=>({key:_,label:n[_]}))});return;default:return}})}),r}function x_(e,t){const n=e.filters.keyLabelMap;return{edges:v_(e.panels.list,t,n),edgeNodes:[]}}function Xl(e,t,n){return e*t+e*n}function w_(e,t,n){return e*t+(e-1)*n}const sr=25,Li=40,Jl=25,Oi=350,C_=150,S_=150,Zl=150,Hl=300,or=40,eu=25,__=300;function k_(e,t){const n=x.keyBy(t,a=>a.id),r=[];return e.current.forEach((a,o)=>{a.panelIDs.forEach((l,u)=>{const c=Xl(u,or,eu)+Li,d=n[l];if(!d){r.push({id:l,_node_type:"panel",parentNode:a.id,data:{label:`!: ${l}`},position:{x:sr,y:c},sourcePosition:$e.Position.Right,targetPosition:$e.Position.Left,style:{width:Hl,height:or}});return}const f=d.title.trim()?`${d.title}`:d.viz.type;r.push({id:d.id,_node_type:"panel",parentNode:a.id,data:{label:f},position:{x:sr,y:c},sourcePosition:$e.Position.Right,targetPosition:$e.Position.Left,style:{width:Hl,height:or}})})}),r}const T_={[j.Division]:"Div",[j.Modal]:"Modal",[j.Tabs]:"Tabs"},D_=Vl;function I_(e){return e.current.map((n,r)=>{const a=w_(n.panelIDs.length,or,eu)+Li+Jl;let o=[];return n.type===j.Tabs&&(o=n.config.tabs.map(u=>u.view_id)),{id:n.id,_node_type:"view-root",_view_type:n.type,_view_level:0,_sub_view_ids:[],_tab_view_ids:o,data:{label:`${T_[n.type]}:${n.name}`},position:{x:0,y:0},sourcePosition:$e.Position.Right,targetPosition:$e.Position.Left,className:"light",style:{backgroundColor:D_[n.type],width:Oi,height:a}}})}function M_(e){const t=x.keyBy(e,n=>n.id);e.forEach(n=>{n._node_type!=="view-root"||n._view_type!==j.Tabs||n._tab_view_ids.forEach(r=>{t[r].parentNode=n.id})})}function A_(e){const t=I_(e.views);M_(t);const n=k_(e.views,e.panels.list);return[...t,...n]}function z_({nodeMap:e,nodes:t,edges:n}){t.forEach(r=>{r._node_type!=="view-root"||r._view_type!==j.Tabs||(r.sourcePosition=$e.Position.Bottom,r.style.width=Oi+sr*2,r.style.height=Jl+r._tab_view_ids.reduce((a,o)=>{const l=e[o];l.position.y=a,l.position.x=sr;const u=l.style.height;return a+u+20},Li))})}function E_({nodeMap:e,nodes:t,edges:n}){n.filter(r=>r.label==="Open View").forEach(r=>{const a=e[r.source],o=e[r.target];if(!a||!o||!a.parentNode)return;const l=e[a.parentNode];l._node_type!=="view-root"||o._node_type!=="view-root"||(o._view_level+=1+l._view_level,l._sub_view_ids.push(o.id))}),t.sort((r,a)=>r._node_type==="view-root"&&a._node_type==="view-root"?r._view_level-a._view_level:r._node_type!=="view-root"&&a._node_type!=="view-root"?0:r._node_type==="view-root"?-1:1)}function $_({nodeMap:e,nodes:t,edges:n}){const r={};n.forEach(a=>{if(a.label!=="Open View")return;const o=e[a.source],l=e[a.target];if(o&&l&&o.parentNode){const u=e[o.parentNode],c=u.position.x,d=Number(x.get(l,"style.height",0)),f=Number(u.style.width);l.position.x=c+f+__,u._view_level===0&&l._sub_view_ids.length===0&&(o.sourcePosition=$e.Position.Left,l.targetPosition=$e.Position.Right,l.position.x*=-1);const g=l.position.x,m=x.get(r,g,0);l.position.y=m,r[g]=m+d+Zl}})}function L_({nodeMap:e,nodes:t,edges:n}){const r=new Set,a=new Set;n.forEach(l=>{r.add(l.source),a.add(l.target)}),t.filter(l=>l._node_type!=="view-root"||l.id==="Main"||l.parentNode?!1:!r.has(l.id)&&!a.has(l.id)).forEach((l,u)=>{l.position.x=Xl(u,Oi,S_),l.position.y=0-C_-Zl})}function O_({nodeMap:e,nodes:t,edges:n}){const r={nodeMap:e,nodes:t,edges:n};return L_(r),E_(r),z_(r),$_(r),{nodes:t,edges:n}}function P_(e){const t=A_(e),n=x.keyBy(t,c=>c.id),{edges:r,edgeNodes:a}=x_(e,n),o=[...t,...a],l=x.keyBy(o,c=>c.id),u={edges:x.uniqBy(r,c=>c.id),nodes:o,nodeMap:l};return O_(u)}const oM="",Pi={"builtin:op:open-link":i(s.ThemeIcon,{color:"blue",size:20,radius:"xl",children:i($.IconCircleDashed,{size:14})}),"builtin:op:set_filter_values":i(s.ThemeIcon,{color:"orange",size:20,radius:"xl",children:i($.IconCircleDot,{size:14})}),"builtin:op:clear_filter_values":i(s.ThemeIcon,{color:"orange",size:20,radius:"xl",children:i($.IconCircleOff,{size:14})})};function B_(e){const t=[];return e.forEach(n=>{switch(n.schemaRef){case"builtin:op:open-link":t.push({key:n.urlTemplate,icon:Pi[n.schemaRef],text:p(s.Group,{spacing:4,children:[i(s.Text,{children:"Open: "}),i(s.Text,{color:"dimmed",children:n.shortURLTemplate})]})});return;case"builtin:op:set_filter_values":n.filters.forEach(({key:r,label:a})=>{t.push({key:n.schemaRef+r,icon:Pi[n.schemaRef],text:i(s.Group,{spacing:4,children:p(s.Text,{children:["Set Filter: ",a]})})})});return;case"builtin:op:clear_filter_values":n.filters.forEach(({key:r,label:a})=>{t.push({key:n.schemaRef+r,icon:Pi[n.schemaRef],text:i(s.Group,{spacing:4,children:p(s.Text,{children:["Clear Filter: ",a]})})})});return}}),t}const V_=y.memo(({data:e,isConnectable:t,sourcePosition:n=$e.Position.Right,targetPosition:r=$e.Position.Left,...a})=>{const o=y.useMemo(()=>B_(e.interactions),[e.interactions]);return p(B,{children:[i($e.Handle,{type:"target",position:r,isConnectable:t}),i(s.Box,{sx:{position:"absolute",top:0,right:0},children:i(T.ChevronsUpRight,{size:12})}),p(s.HoverCard,{shadow:"xl",withinPortal:!0,children:[i(s.HoverCard.Target,{children:i(s.Text,{children:e.label})}),i(s.HoverCard.Dropdown,{children:i(s.List,{spacing:"xs",size:"sm",center:!0,children:o.map(l=>i(s.List.Item,{icon:l.icon,children:l.text},l.key))})})]}),i($e.Handle,{type:"source",position:n,isConnectable:t})]})}),lM="",N_={interaction:V_},q_=k.observer(()=>{const e=we(),{edges:t,nodes:n}=P_(e);return p($e,{nodes:n,edges:t,onNodesChange:x.noop,onEdgesChange:x.noop,onConnect:x.noop,className:"interactions-viewer",fitView:!0,nodeTypes:N_,children:[i($e.MiniMap,{}),i($e.Controls,{}),i($e.Background,{})]})}),F_=k.observer(({opened:e,close:t})=>i(s.Modal,{size:"96vw",opened:e,onClose:t,title:"Interactions",trapFocus:!0,onDragStart:n=>{n.stopPropagation()},styles:{body:{height:"90vh"},content:{transform:"none !important"}},zIndex:300,children:i(q_,{})})),G_={"> 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 W_({onClick:e,name:t,active:n,openSettings:r}){return p(s.Box,{sx:{position:"relative"},children:[i(s.UnstyledButton,{sx:a=>({display:"block",width:"100%",padding:a.spacing.xs,borderRadius:0,position:"relative",color:a.black,"&:hover":{backgroundColor:a.colors.gray[0]},backgroundColor:n?a.colors.gray[2]:"transparent"}),children:i(s.Group,{sx:{width:"calc(100% - 28px)"},onClick:e,children:i(s.Text,{size:"sm",children:t})})}),n&&i(s.Tooltip,{label:"Edit",position:"right",withinPortal:!0,children:i(s.ActionIcon,{onClick:r,variant:"light",color:"blue",sx:{position:"absolute",top:0,bottom:0,height:"100%",right:0,zIndex:0,borderRadius:0},children:i($.IconAdjustments,{size:16})})})]})}const j_=k.observer(()=>{const e=pe(),t=le(),n=y.useCallback(a=>()=>t.views.setIDOfVIE(a),[t]),r=a=>{e.editor.open(["_VIEWS_",a])};return p(s.Box,{sx:{position:"relative"},children:[t.views.options.map(a=>i(W_,{active:t.views.idOfVIE===a.value,name:a.label,onClick:n(a.value),openSettings:()=>r(a.value)},a.value)),i(s.Divider,{variant:"dashed"}),i(s.Button,{variant:"subtle",rightIcon:i($.IconPlus,{size:14}),size:"sm",px:"xs",color:"blue",onClick:t.views.addARandomNewView,sx:{width:"100%",borderRadius:0},styles:{inner:{justifyContent:"space-between"}},children:"Add a View"})]})}),R_=k.observer(()=>{const e=pe(),t=le(),n=()=>{if(!t.queries.firstID){e.editor.open(["_QUERIES_",""]);return}e.editor.open(["_QUERIES_",t.queries.firstID])},r=()=>{if(!t.filters.firstID){e.editor.open(["_FILTERS_",""]);return}e.editor.open(["_FILTERS_",t.filters.firstID])},[a,o]=y.useState(!1),l=()=>o(!0),u=()=>o(!1);return p(s.Navbar,{p:0,width:{base:200,xs:200,sm:200,md:220,lg:240,xl:260},zIndex:299,children:[p(s.Navbar.Section,{children:[p(s.Group,{grow:!0,spacing:0,sx:{...G_,button:{borderWidth:0,borderBottomWidth:1,borderColor:"#e9ecef"}},children:[i(s.Tooltip,{label:"Filters",withinPortal:!0,children:i(s.ActionIcon,{variant:"default",radius:0,size:"md",sx:{height:"30px"},onClick:r,children:i($.IconFilter,{size:18})})}),i(s.Tooltip,{label:"Queries",withinPortal:!0,children:i(s.ActionIcon,{variant:"default",radius:0,size:"md",sx:{height:"30px"},onClick:n,children:i($.IconDatabase,{size:18})})}),i(s.Tooltip,{label:"Interactions Viewer",withinPortal:!0,children:i(s.ActionIcon,{variant:"default",radius:0,size:"md",sx:{height:"30px"},onClick:l,children:i($.IconLink,{size:18})})})]}),i(F_,{opened:a,close:u})]}),i(s.Navbar.Section,{py:5,sx:{borderBottom:"1px solid #eee"},children:i(s.Text,{align:"center",sx:{userSelect:"none",cursor:"default"},children:"Views"})}),i(s.Navbar.Section,{grow:!0,sx:{overflow:"auto"},children:i(j_,{})}),i(s.Navbar.Section,{children:i(s.Group,{grow:!0,p:"md",pt:"sm",sx:{borderTop:"1px solid #eee"},children:i(s.Button,{size:"xs",leftIcon:i($.IconSettings,{size:20}),onClick:()=>e.editor.open([]),children:"Settings"})})})]})}),Y_=k.observer(function({config:t}){return p(B,{children:[i(s.Checkbox,{checked:t.default_value,onChange:n=>t.setDefaultValue(n.currentTarget.checked),label:"Default Checked"}),i(oi,{label:"Description",value:t.description,onChange:t.setDescription,styles:{root:{flexGrow:1,minHeight:"400px"}}})]})}),Q_=[{label:"2022",value:"YYYY"},{label:"202201",value:"YYYYMM"},{label:"20220101",value:"YYYYMMDD"},{label:"2022-01",value:"YYYY-MM"},{label:"2022-01-01",value:"YYYY-MM-DD"}],U_=k.observer(function({config:t}){return p(B,{children:[p(s.Group,{children:[i(s.Checkbox,{checked:t.required,onChange:n=>t.setRequired(n.currentTarget.checked),label:"Required"}),i(s.Checkbox,{checked:t.clearable,onChange:n=>t.setClearable(n.currentTarget.checked),disabled:t.max_days>0,label:"Clearable"}),i(s.Checkbox,{checked:t.allowSingleDateInRange,onChange:n=>t.setAllowSingleDateInRange(n.currentTarget.checked),label:"Allow choosing 1 day"})]}),i(s.Select,{data:Q_,label:"Display Format",value:t.inputFormat,onChange:t.setInputFormat}),i(jo,{label:"Default Value",config:t,value:t.default_value,onChange:t.setDefaultValue}),i(s.NumberInput,{label:"Max Days",description:p(s.Group,{position:"apart",children:[i(s.Text,{children:"Set 0 to disable."}),p(s.Group,{spacing:4,children:[i(s.Text,{children:"This feature requires"}),i(s.Text,{color:"blue",children:"Clearable"}),i(s.Text,{children:"to be checked"})]})]}),min:0,value:t.max_days,onChange:t.setMaxDays,hideControls:!0})]})}),Bi=k.observer(({value:e,onChange:t})=>{const n=pe(),r=le(),a=y.useMemo(()=>r.queries.options,[r.queries.current]),o=a.length===0,l=u=>{n.editor.setPath(["_QUERIES_",u])};return i(s.Select,{label:p(s.Group,{position:"apart",children:[i(s.Text,{children:"Use query data as options"}),e&&i(s.Button,{size:"xs",leftIcon:i($.IconArrowCurveRight,{size:16}),variant:"subtle",color:"blue",onClick:()=>l(e),children:"Open this query"})]}),data:a,value:e,onChange:t,allowDeselect:!1,clearable:!0,sx:{flexGrow:1},disabled:o,error:o?"You need to add a query in Data Settings":void 0,styles:{label:{display:"block"}}})}),K_=`
504
+ `}})).actions(e=>({setPage(t){e.page=t},resetPage(){e.page=1},setLimit(t){e.limit=t}})).actions(e=>({afterCreate(){y.addDisposer(e,te.reaction(()=>e.keywordString,e.resetPage,{fireImmediately:!1,delay:0})),y.addDisposer(e,te.reaction(()=>e.limit,e.resetPage,{fireImmediately:!1,delay:0}))}})),s_=y.types.model({data:y.types.optional(y.types.frozen(),{}),state:y.types.optional(y.types.enumeration(["idle","loading","error"]),"idle"),error:y.types.frozen()}).views(e=>({get loading(){return e.state==="loading"},get empty(){return Object.keys(e.data).length===0},get sql(){const t=y.getParent(e,1).type;return t===Se.MySQL||t===Se.Postgresql?"SELECT table_schema, table_name, table_type FROM information_schema.tables ORDER BY table_schema, table_name":""}})),o_=y.types.compose("DataSourceModel",ol,y.types.model({tables:y.types.optional(s_,{}),columns:y.types.optional(r_,{}),tableData:y.types.optional(a_,{}),indexes:y.types.optional(i_,{}),table_schema:y.types.optional(y.types.string,""),table_name:y.types.optional(y.types.string,"")})).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=y.flow(function*(){var n;(n=e.controllers.tables)==null||n.abort(),e.controllers.tables=new AbortController,e.tables.state="loading";try{const r=yield*y.toGenerator(qe.query(e.controllers.tables.signal)({type:e.type,key:e.key,query:e.tables.sql},{}));e.tables.data=x.groupBy(r,"table_schema"),e.tables.state="idle",e.tables.error=null,e.initKeywords()}catch(r){if(!mt.isCancel(r)){e.tables.data={};const a=x.get(r,"message","unkown error");e.tables.error=x.get(r,"response.data.detail.message",a),e.tables.state="error"}}});return{loadTables:t,loadTablesIfEmpty(){e.tables.empty&&t()},loadColumns:y.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*y.toGenerator(qe.query(e.controllers.columns.signal)({type:e.type,key:e.key,query:e.columns.sql},{})),e.columns.state="idle",e.columns.error=null}catch(r){if(mt.isCancel(r))e.columns.state="idle",e.columns.error=null;else{e.columns.data=[];const a=x.get(r,"message","unkown error");e.columns.error=x.get(r,"response.data.detail.message",a),e.columns.state="error"}}}),loadIndexes:y.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*y.toGenerator(qe.query(e.controllers.indexes.signal)({type:e.type,key:e.key,query:e.indexes.sql},{})),e.indexes.state="idle",e.indexes.error=null}catch(r){if(mt.isCancel(r))e.indexes.state="idle",e.indexes.error=null;else{e.indexes.data=[];const a=x.get(r,"message","unkown error");e.indexes.error=x.get(r,"response.data.detail.message",a),e.indexes.state="error"}}}),loadTableData:y.flow(function*(){var r;(r=e.controllers.tableData)==null||r.abort(),e.controllers.tableData=new AbortController;const n=e.tableData;n.state="loading";try{n.data=yield*y.toGenerator(qe.query(e.controllers.tableData.signal)({type:e.type,key:e.key,query:n.sql},{}));const[{total:a}]=yield*y.toGenerator(qe.query(e.controllers.tableData.signal)({type:e.type,key:e.key,query:n.countSql},{}));n.total=Number(a),n.state="idle",n.error=null}catch(a){if(mt.isCancel(a))n.state="idle",n.error=null;else{n.data=[];const o=x.get(a,"message","unkown error");n.error=x.get(a,"response.data.detail.message",o),n.state="error"}}})}}).actions(e=>({afterCreate(){y.addDisposer(e,te.reaction(()=>e.columns.sql,e.loadColumns,{fireImmediately:!1,delay:500}))}})).actions(e=>({afterCreate(){y.addDisposer(e,te.reaction(()=>e.indexes.sql,e.loadIndexes,{fireImmediately:!1,delay:500})),y.addDisposer(e,te.reaction(()=>e.tableData.sql,e.loadTableData,{fireImmediately:!1,delay:0}))}})),l_=y.types.model("DataSourcesModel",{list:y.types.optional(y.types.array(o_),[])}).views(e=>({find({type:t,key:n}){return e.list.find(r=>r.key===n&&r.type===t)},get options(){return e.list.map(t=>({value:t.key,label:t.key}))}})).actions(e=>({replace(t){e.list.length=0,e.list.push(...t)}}));function jt(e){return{label:e,value:e,_type:"ACTION",_action_type:e,Icon:null,children:null}}function u_(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 c_=y.types.model("EditorModel",{path:y.types.optional(y.types.frozen(),[]),settings_open:y.types.optional(y.types.boolean,!1)}).views(e=>({get navOptions(){const{content:t}=y.getRoot(e),{filters:n,views:r,sqlSnippets:a,queries:o}=t;return[{label:"Query Variables",value:"_QUERY_VARS_",_type:"query_variables",Icon:$.IconVariable},{label:"Mock Context",value:"_MOCK_CONTEXT_",Icon:$.IconCodeDots,_type:"mock_context"},{label:"Filters",value:"_FILTERS_",Icon:$.IconFilter,children:[...n.options,jt("_Add_A_Filter_")],_type:"GROUP"},{label:"SQL Snippets",value:"_SQL_SNIPPETS_",Icon:$.IconCopy,children:[jt("_SQL_SNIPPETS_SETTINGS_"),...a.options,jt("_Add_A_SQL_SNIPPET_")],_type:"GROUP"},{label:"Queries",value:"_QUERIES_",Icon:$.IconDatabase,children:[jt("_QUERIES_SETTINGS_"),...o.options,jt("_Add_A_QUERY_")],_type:"GROUP"},{label:"Views",value:"_VIEWS_",Icon:$.IconBoxMultiple,children:[...r.editorOptions,jt("_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=u_(t);n&&e.setPath(n)}})),Gl=dl.views(e=>({get dataFieldOptions(){return e.queryIDs.length===0?[]:e.queries.map(t=>{const n=t.data;return n.length===0?[]:Object.keys(n[0]).map(a=>({label:a,value:`${t.id}.${a}`,group:t.name}))}).flat()}})).actions(e=>({removeSelf(){y.getParent(e,2).removeByID(e.id)}})).actions(e=>({moveToView(t,n){y.getRoot(e).content.views.findByID(t).removePanelID(e.id),y.getRoot(e).content.views.findByID(n).appendPanelID(e.id),y.getRoot(e).editor.setPath(["_VIEWS_",n,"_PANELS_",e.id])}})),Wl=y.types.compose("PanelsModel",pl,y.types.model({list:y.types.optional(y.types.array(Gl),[])})).views(e=>({editorOptions(t,n){const{panels:r}=e.panelsByIDs(n);r.length!==n.length&&console.warn(`Unfulfilled panels for View[${t}]`);const a=r.map(l=>({label:l.title?l.title:x.capitalize(l.viz.type),value:l.id,_type:"panel",parentID:t})),o="_Add_A_PANEL_";return a.push({label:o,value:o,_type:"ACTION",_action_type:o,parentID:t,Icon:null,children:null}),a}})).actions(e=>({replace(t){e.list=y.castToSnapshot(t)},append(t){e.list.push(t)},remove(t){e.list.splice(t,1)},removeByID(t){const n=e.list.findIndex(r=>r.id===t);n!==-1&&e.list.splice(n,1)},removeByIDs(t){t.forEach(n=>{this.removeByID(n)})},duplicateByID(t){const n=e.list.find(a=>a.id===t);if(!n){console.error(new Error(`[duplicate panel] Can't find a panel by id[${t}]`));return}const r=new Date().getTime().toString();return e.list.push({...n.json,id:r,layout:{...n.layout,y:1/0,moved:!1}}),r},replaceByIndex(t,n){e.list.splice(t,1,n)}})),jl=y.types.compose("ViewsModel",cl,y.types.model({idOfVIE:y.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=y.getRoot(e).content.panels;return e.current.map(n=>({label:n.name,value:n.id,_type:"view",children:t.editorOptions(n.id,n.panelIDs)}))}})).actions(e=>({setIDOfVIE(t){e.idOfVIE=t,e.visibleViewIDs.length=0,e.visibleViewIDs.push(t)},replace(t){e.current.replace(t)},addANewView(t,n,r,a){e.current.push({id:t,name:n,type:r,config:a,panelIDs:[]})},append(t){e.current.push(t)},remove(t){e.current.splice(t,1)},removeByID(t){const n=e.current.findIndex(o=>o.id===t);if(n===-1)return;const r=e.current[n];y.getRoot(e).content.panels.removeByIDs(r.panelIDs),e.current.splice(n,1)},replaceByIndex(t,n){e.current.splice(t,1,n)},addARandomNewView(){const t=new Date().getTime().toString();this.addANewView(t,j.Division,j.Division,{_name:j.Division}),this.setIDOfVIE(t)},removeVIE(){e.current.length!==1&&(this.removeByID(e.idOfVIE),this.setIDOfVIE(e.current[0].id))}}));function Ei(e){const t=e.length>0?[e[0].id]:[],n=e.length>0?e[0].id:"";return{current:e.map(a=>{const{_name:o=a.type}=a.config;return{...a,config:{...a.config,_name:o},panelIDs:a.panelIDs}}),visibleViewIDs:t,idOfVIE:n}}const d_=y.types.model({id:y.types.string,name:y.types.string,dashboard_id:y.types.string,create_time:y.types.string,update_time:y.types.string,version:y.types.string,filters:Nl,queries:ql,sqlSnippets:Fl,views:jl,panels:Wl,mock_context:Qo,origin:y.types.maybe(y.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,definition:{queries:e.queries.json,sqlSnippets:e.sqlSnippets.json,mock_context:e.mock_context.current}}}},get filtersChanged(){const t="filters.current";return!x.isEqual(y.getSnapshot(x.get(e,t)),x.get(e.origin,t))},get queriesChanged(){const t="queries.current",n=y.getSnapshot(x.get(e,t)).map(r=>x.pick(r,["id","name","key","type","sql","run_by","react_to","pre_process","post_process"]));return!x.isEqual(n,x.get(e.origin,t))},get sqlSnippetsChanged(){const t="sqlSnippets.current";return!x.isEqual(y.getSnapshot(x.get(e,t)),x.get(e.origin,t))},get viewsChanged(){const t="views.current";return!x.isEqual(e.views.json,x.get(e.origin,t))},get panelsChanged(){const t="panels.list";return!x.isEqual(y.getSnapshot(x.get(e,t)),x.get(e.origin,t))},get mockContextChanged(){const t="mock_context.current";return!x.isEqual(x.get(e,t),x.get(e.origin,t))},get payloadForSQL(){const t=y.getParent(e).context.current,n=y.getParent(e).globalSQLSnippets,r={context:{...e.mock_context.current,...t},filters:e.filters.values};return{...r,sql_snippets:rr(e.sqlSnippets.current,"key","value",r),global_sql_snippets:rr(n.list,"id","content",r)}},get payloadForViz(){const t=y.getParent(e).context.current;return{context:{...e.mock_context.current,...t},filters:e.filters.values}},get changed(){return this.filtersChanged||this.queriesChanged||this.sqlSnippetsChanged||this.viewsChanged||this.panelsChanged||this.mockContextChanged},get data(){return e.queries.current.map(({id:n,data:r})=>({id:n,data:r})).reduce((n,r)=>(n[r.id]=r.data,n),{})},getDataStuffByID(t){const n=e.queries.findByID(t);return n?{data:n.data,len:n.data.length,state:n.state,error:n.error}:{data:[],len:0,state:"idle",error:void 0}}})).views(e=>({get queriesUsage(){const t=e.panels.idMap,n=[];e.views.current.forEach(a=>{a.panelIDs.forEach(o=>{const l=t.get(o);if(!l)return;const u="panel",c=l.title?l.title:l.viz.type,d=[{id:a.id,label:a.name}];l.queryIDs.forEach(f=>{n.push({id:o,queryID:f,type:u,label:c,views:d})})})});const r=e.views.idMap;return e.filters.current.filter(a=>!!x.get(a,"config.options_query_id")).map(a=>({type:"filter",id:a.id,queryID:x.get(a,"config.options_query_id"),label:a.label,views:a.visibleInViewsIDs.map(o=>{var l;return{id:o,label:((l=r.get(o))==null?void 0:l.name)??o}})})),x.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=[],n=new RegExp("(?<=sql_snippets\\.)([^}.]+)","gm");return e.queries.current.forEach(r=>{if(!r.typedAsSQL)return;x.uniq(r.sql.match(n)).forEach(o=>{t.push({queryID:r.id,sqlSnippetKey:o,queryName:r.name})})}),x.groupBy(t,"sqlSnippetKey")},get hasUnusedSQLSnippets(){return e.sqlSnippets.current.length>Object.keys(this.sqlSnippetsUsage).length},findSQLSnippetUsage(t){return this.sqlSnippetsUsage[t]??[]}})).actions(e=>({removeUnusedQueries(){const t=new Set(Object.keys(e.queriesUsage)),n=e.queries.current.filter(r=>!t.has(r.id)).map(r=>r.id);e.queries.removeQueries(n)},removeUnusedSQLSnippets(){const t=new Set(Object.keys(e.sqlSnippetsUsage)),n=e.sqlSnippets.current.filter(r=>!t.has(r.key)).map(r=>r.key);e.sqlSnippets.removeByKeys(n)},duplicatePanelByID(t,n){var a;const r=e.panels.duplicateByID(t);r&&((a=e.views.findByID(n))==null||a.appendPanelID(r))},removePanelByID(t,n){var r;e.panels.removeByID(t),(r=e.views.findByID(n))==null||r.removePanelID(t)},addANewPanel(t){var r;const n=new Date().getTime().toString();e.panels.append(sS(n)),(r=e.views.findByID(t))==null||r.appendPanelID(n)}})).actions(e=>({reset(){y.applySnapshot(e.filters.current,e.origin.filters.current),y.applySnapshot(e.queries.current,e.origin.queries.current),y.applySnapshot(e.sqlSnippets.current,e.origin.sqlSnippets.current),y.applySnapshot(e.views.current,e.origin.views.current),y.applySnapshot(e.panels.list,e.origin.panels.list),e.mock_context.current=e.origin.mock_context.current},resetFilters(){y.applySnapshot(e.filters.current,e.origin.filters.current)},updateCurrent(t){const{id:n,name:r,content:a}=t;if(!a)throw new Error("unexpected null content when updating a content model");const{version:o,filters:l,views:u,panels:c,definition:{queries:d,sqlSnippets:f,mock_context:h={}}}=a;e.id=n,e.name=r,e.version=o,y.applySnapshot(e.filters.current,l),y.applySnapshot(e.views.current,Ei(u).current),y.applySnapshot(e.panels.list,c),y.applySnapshot(e.queries.current,d),y.applySnapshot(e.sqlSnippets.current,f),e.mock_context.current=h}})),$i=y.types.snapshotProcessor(d_,{preProcessor(e){return{...e,origin:e}},postProcessor(e){delete e.origin;const t=y.castToSnapshot(e.queries.current.map(n=>x.pick(n,["id","key","type","sql"])));return x.defaults({},{queries:{current:t}},e)}});function p_(e,t){t.filters&&y.applySnapshot(e.filters.current,t.filters)}function Rl({id:e,name:t,dashboard_id:n,create_time:r,update_time:a,content:o}){if(!o)throw new Error("unexpected null content when creating a content model");const{version:l,filters:u,views:c,panels:d,definition:{queries:f,sqlSnippets:h,mock_context:g={}}}=o;return $i.create({id:e,name:t,dashboard_id:n,create_time:r,update_time:a,version:l,filters:gl(u),queries:{current:f},sqlSnippets:{current:h},mock_context:Uo(g),views:Ei(c),panels:{list:d}})}const Yl=y.types.model({id:y.types.identifier,name:y.types.string,group:y.types.string,content:$i,content_id:y.types.string,datasources:l_,globalSQLSnippets:ll,context:Di,editor:c_}).views(e=>({get json(){return{id:e.id,name:e.name,group:e.group,content_id:e.content_id}}})).actions(e=>({updateCurrentContent(t){e.content.updateCurrent(t)},updateCurrent(t,n){const{id:r,name:a,group:o,content_id:l}=t;e.id=r,e.name=a,e.group=o,e.content_id=l,this.updateCurrentContent(n)}}));function Ql({id:e,name:t,group:n,content_id:r},a,o,l,u){return Yl.create({id:e,name:t,group:n,content_id:r,content:Rl(a),datasources:{list:o},globalSQLSnippets:{list:l},context:ul(u),editor:{}})}function Ul(e,t){b.useEffect(()=>{const n=r=>{console.log(r);const{viewID:a}=r.detail;if(!a){console.error(new Error("[Open View] Needs to pick a view first"));return}e.views.appendToVisibles(a),t&&e.views.setIDOfVIE(a)};return window.addEventListener("open-view",n),()=>{window.removeEventListener("open-view",n)}},[e,t]),b.useEffect(()=>{const n=r=>{console.log(r);const{dictionary:a,payload:o}=r.detail;if(!o||Object.keys(o).length===0){console.error(new Error("[Set Filter Values] payload is empty"));return}Object.entries(a).forEach(([l,u])=>{e.filters.setValueByKey(l,x.get(o,u))})};return window.addEventListener("set-filter-values",n),()=>{window.removeEventListener("set-filter-values",n)}},[e]),b.useEffect(()=>{function n(a){return Array.isArray(a)?[]:typeof a=="object"?{}:typeof a=="boolean"?!1:typeof a=="string"?"":typeof a=="number"?0:a}const r=a=>{console.log(a);const{filter_keys:o}=a.detail;o.forEach(l=>{const u=x.get(e.filters.values,l),c=n(u);console.log(`${l}: ${c}`),e.filters.setValueByKey(l,c)})};return window.addEventListener("clear-filter-values",r),()=>{window.removeEventListener("clear-filter-values",r)}},[e]),b.useEffect(()=>{const n=r=>{console.log(r);const{urlTemplate:a,openInNewTab:o,enableEncoding:l=!1,payload:u}=r.detail;if(!a){console.error(new Error("[Open Link] URL is empty"));return}function c(h){return x.cloneDeepWith(h,m=>{if(l&&typeof m=="string")return encodeURIComponent(m)})}const f=x.template(a||"")(c({...u,filters:e.payloadForSQL.filters,context:e.payloadForSQL.context}));window.open(f,o?"_blank":"_self","noopener")};return window.addEventListener("open-link",n),()=>{window.removeEventListener("open-link",n)}},[e])}function Kl(e){return b.useCallback(t=>t.provideValue(Ce.pluginManager,e.pluginManager).provideValue(Ce.vizManager,e.vizManager).provideValue(Ce.colorManager,e.colorManager),[])}const lM="",h_=k.observer(()=>{const e=wr(),t=le(),n=()=>{const r=JSON.stringify(t.json,null,2),a=`${e.name}__${t.name}`;yl(a,r)};return p(s.Menu,{shadow:"md",width:200,trigger:"hover",openDelay:100,closeDelay:400,withinPortal:!0,zIndex:310,children:[i(s.Menu.Target,{children:i(s.ActionIcon,{variant:"light",color:"blue",children:i($.IconMenu2,{size:14})})}),p(s.Menu.Dropdown,{children:[i(s.Menu.Item,{icon:i($.IconDownload,{size:14}),onClick:t.queries.downloadAllData,children:"Download Data"}),i(s.Menu.Item,{icon:i($.IconCode,{size:14}),onClick:n,children:"Download Schema"})]})]})}),f_=k.observer(({saveDashboardChanges:e})=>{const t=We.useModals(),n=le(),r=()=>{t.openConfirmModal({title:p(s.Group,{position:"left",children:[i($.IconAlertTriangle,{size:18,color:"red"}),i(s.Text,{children:"You are reverting changes"})]}),labels:{confirm:"Confirm",cancel:"Cancel"},confirmProps:{color:"red"},onCancel:()=>console.log("Cancel"),onConfirm:()=>n.reset(),zIndex:320,withCloseButton:!1})},a=n.changed;return p(s.Group,{spacing:0,children:[i(s.Button,{color:"green",variant:"filled",size:"xs",leftIcon:i($.IconDeviceFloppy,{size:18}),onClick:e,disabled:!a,sx:{borderTopRightRadius:0,borderBottomRightRadius:0},children:"Save Changes"}),p(s.Menu,{width:200,trigger:"hover",openDelay:100,closeDelay:400,withinPortal:!0,zIndex:320,disabled:!a,children:[i(s.Menu.Target,{children:i(s.ActionIcon,{variant:"default",disabled:!a,sx:{height:"30px",borderTopLeftRadius:0,borderBottomLeftRadius:0,svg:{fill:"rgb(173, 181, 189)",stroke:"none"}},children:i($.IconCaretDown,{size:18})})}),i(s.Menu.Dropdown,{children:i(s.Menu.Item,{icon:i($.IconRecycle,{size:14,color:"red"}),disabled:!a,onClick:r,children:"Revert Changes"})})]})]})}),g_=k.observer(({saveDashboardChanges:e,headerSlot:t=null})=>{const n=Ou.useNavigate(),r=ce(),a=()=>{n(`/dashboard/${r.id}`)},o=We.useModals(),l=()=>{o.openConfirmModal({title:p(s.Group,{position:"left",children:[i($.IconAlertTriangle,{size:18,color:"red"}),i(s.Text,{children:"There are unsaved changes"})]}),labels:{confirm:"Discard",cancel:"Cancel"},confirmProps:{color:"red"},onCancel:()=>console.log("Cancel"),onConfirm:a,zIndex:320,withCloseButton:!1})},u=r.content.changed;return i(s.Header,{height:60,px:"md",py:0,sx:{zIndex:299},children:p(s.Group,{position:"apart",sx:{height:60,minWidth:"1000px",position:"relative"},children:[p(s.Group,{children:[i(s.Button,{size:"xs",color:u?"red":"green",leftIcon:i($.IconArrowLeft,{size:20}),onClick:u?l:a,children:p(s.Group,{spacing:4,children:["End Editing",i(s.Text,{td:"underline",children:r.name})]})}),i(f_,{saveDashboardChanges:e})]}),p(s.Group,{position:"right",sx:{flexGrow:1},children:[t,i(h_,{})]})]})})}),m_={position:"fixed",top:60,left:0,right:0,height:30,zIndex:299,borderBottom:"1px solid #e9ecef",background:"rgba(233,236,239, 0.15)"},y_=k.observer(()=>{var n;const e=le(),t=((n=e.views.VIE)==null?void 0:n.type)===j.Tabs;return i(s.Box,{sx:m_,pl:{base:200,xs:200,sm:200,md:220,lg:240,xl:260},children:p(s.Group,{position:"apart",align:"center",sx:{height:"30px"},pr:16,children:[i(s.Button,{variant:"outline",color:"blue",radius:0,size:"xs",disabled:!e.views.VIE||t,onClick:()=>e.addANewPanel(e.views.idOfVIE),leftIcon:i($.IconPlaylistAdd,{size:20}),sx:{height:"30px",borderLeft:"none",borderTop:"none",borderRight:"1px solid #e9ecef",borderBottom:"1px solid #e9ecef",background:"rgb(231, 245, 255)"},children:"Add a Panel"}),i(s.Box,{}),i(s.Box,{})]})})}),b_=k.observer(e=>p(B,{children:[i(g_,{...e}),i(y_,{})]})),uM="";function v_(e,t,n){const r=[];return e.filter(a=>"__INTERACTIONS"in a.viz.conf).forEach((a,o)=>{const l=t[a.id];l.data.interactions=x.get(l,"data.interactions",[]);const{__INTERACTIONS:u,__OPERATIONS:c,__TRIGGERS:d}=a.viz.conf;Object.entries(c).forEach(([f,h])=>{const{schemaRef:g,data:m}=h,{config:C}=m;switch(g){case"builtin:op:open-link":let w=C.urlTemplate.substring(0,100);C.urlTemplate.length>=20&&(w+="..."),l.type="interaction",l.data.interactions.push({schemaRef:g,urlTemplate:C.urlTemplate,shortURLTemplate:w});return;case"builtin:op:open_view":r.push({id:`OPERATION--${f}`,source:a.id,target:C.viewID,label:"Open View",style:{stroke:"rgba(0,0,0,0.8)"},type:"default"});return;case"builtin:op:set_filter_values":l.type="interaction",l.data.interactions.push({schemaRef:g,filters:Object.keys(C.dictionary).map(_=>({key:_,label:n[_]}))});return;case"builtin:op:clear_filter_values":l.type="interaction",l.data.interactions.push({schemaRef:g,filters:C.filter_keys.map(_=>({key:_,label:n[_]}))});return;default:return}})}),r}function x_(e,t){const n=e.filters.keyLabelMap;return{edges:v_(e.panels.list,t,n),edgeNodes:[]}}function Xl(e,t,n){return e*t+e*n}function w_(e,t,n){return e*t+(e-1)*n}const sr=25,Li=40,Jl=25,Oi=350,C_=150,S_=150,Zl=150,Hl=300,or=40,eu=25,__=300;function k_(e,t){const n=x.keyBy(t,a=>a.id),r=[];return e.current.forEach((a,o)=>{a.panelIDs.forEach((l,u)=>{const c=Xl(u,or,eu)+Li,d=n[l];if(!d){r.push({id:l,_node_type:"panel",parentNode:a.id,data:{label:`!: ${l}`},position:{x:sr,y:c},sourcePosition:$e.Position.Right,targetPosition:$e.Position.Left,style:{width:Hl,height:or}});return}const f=d.title.trim()?`${d.title}`:d.viz.type;r.push({id:d.id,_node_type:"panel",parentNode:a.id,data:{label:f},position:{x:sr,y:c},sourcePosition:$e.Position.Right,targetPosition:$e.Position.Left,style:{width:Hl,height:or}})})}),r}const T_={[j.Division]:"Div",[j.Modal]:"Modal",[j.Tabs]:"Tabs"},D_=Vl;function I_(e){return e.current.map((n,r)=>{const a=w_(n.panelIDs.length,or,eu)+Li+Jl;let o=[];return n.type===j.Tabs&&(o=n.config.tabs.map(u=>u.view_id)),{id:n.id,_node_type:"view-root",_view_type:n.type,_view_level:0,_sub_view_ids:[],_tab_view_ids:o,data:{label:`${T_[n.type]}:${n.name}`},position:{x:0,y:0},sourcePosition:$e.Position.Right,targetPosition:$e.Position.Left,className:"light",style:{backgroundColor:D_[n.type],width:Oi,height:a}}})}function M_(e){const t=x.keyBy(e,n=>n.id);e.forEach(n=>{n._node_type!=="view-root"||n._view_type!==j.Tabs||n._tab_view_ids.forEach(r=>{t[r].parentNode=n.id})})}function A_(e){const t=I_(e.views);M_(t);const n=k_(e.views,e.panels.list);return[...t,...n]}function z_({nodeMap:e,nodes:t,edges:n}){t.forEach(r=>{r._node_type!=="view-root"||r._view_type!==j.Tabs||(r.sourcePosition=$e.Position.Bottom,r.style.width=Oi+sr*2,r.style.height=Jl+r._tab_view_ids.reduce((a,o)=>{const l=e[o];l.position.y=a,l.position.x=sr;const u=l.style.height;return a+u+20},Li))})}function E_({nodeMap:e,nodes:t,edges:n}){n.filter(r=>r.label==="Open View").forEach(r=>{const a=e[r.source],o=e[r.target];if(!a||!o||!a.parentNode)return;const l=e[a.parentNode];l._node_type!=="view-root"||o._node_type!=="view-root"||(o._view_level+=1+l._view_level,l._sub_view_ids.push(o.id))}),t.sort((r,a)=>r._node_type==="view-root"&&a._node_type==="view-root"?r._view_level-a._view_level:r._node_type!=="view-root"&&a._node_type!=="view-root"?0:r._node_type==="view-root"?-1:1)}function $_({nodeMap:e,nodes:t,edges:n}){const r={};n.forEach(a=>{if(a.label!=="Open View")return;const o=e[a.source],l=e[a.target];if(o&&l&&o.parentNode){const u=e[o.parentNode],c=u.position.x,d=Number(x.get(l,"style.height",0)),f=Number(u.style.width);l.position.x=c+f+__,u._view_level===0&&l._sub_view_ids.length===0&&(o.sourcePosition=$e.Position.Left,l.targetPosition=$e.Position.Right,l.position.x*=-1);const g=l.position.x,m=x.get(r,g,0);l.position.y=m,r[g]=m+d+Zl}})}function L_({nodeMap:e,nodes:t,edges:n}){const r=new Set,a=new Set;n.forEach(l=>{r.add(l.source),a.add(l.target)}),t.filter(l=>l._node_type!=="view-root"||l.id==="Main"||l.parentNode?!1:!r.has(l.id)&&!a.has(l.id)).forEach((l,u)=>{l.position.x=Xl(u,Oi,S_),l.position.y=0-C_-Zl})}function O_({nodeMap:e,nodes:t,edges:n}){const r={nodeMap:e,nodes:t,edges:n};return L_(r),E_(r),z_(r),$_(r),{nodes:t,edges:n}}function P_(e){const t=A_(e),n=x.keyBy(t,c=>c.id),{edges:r,edgeNodes:a}=x_(e,n),o=[...t,...a],l=x.keyBy(o,c=>c.id),u={edges:x.uniqBy(r,c=>c.id),nodes:o,nodeMap:l};return O_(u)}const cM="",Pi={"builtin:op:open-link":i(s.ThemeIcon,{color:"blue",size:20,radius:"xl",children:i($.IconCircleDashed,{size:14})}),"builtin:op:set_filter_values":i(s.ThemeIcon,{color:"orange",size:20,radius:"xl",children:i($.IconCircleDot,{size:14})}),"builtin:op:clear_filter_values":i(s.ThemeIcon,{color:"orange",size:20,radius:"xl",children:i($.IconCircleOff,{size:14})})};function B_(e){const t=[];return e.forEach(n=>{switch(n.schemaRef){case"builtin:op:open-link":t.push({key:n.urlTemplate,icon:Pi[n.schemaRef],text:p(s.Group,{spacing:4,children:[i(s.Text,{children:"Open: "}),i(s.Text,{color:"dimmed",children:n.shortURLTemplate})]})});return;case"builtin:op:set_filter_values":n.filters.forEach(({key:r,label:a})=>{t.push({key:n.schemaRef+r,icon:Pi[n.schemaRef],text:i(s.Group,{spacing:4,children:p(s.Text,{children:["Set Filter: ",a]})})})});return;case"builtin:op:clear_filter_values":n.filters.forEach(({key:r,label:a})=>{t.push({key:n.schemaRef+r,icon:Pi[n.schemaRef],text:i(s.Group,{spacing:4,children:p(s.Text,{children:["Clear Filter: ",a]})})})});return}}),t}const V_=b.memo(({data:e,isConnectable:t,sourcePosition:n=$e.Position.Right,targetPosition:r=$e.Position.Left,...a})=>{const o=b.useMemo(()=>B_(e.interactions),[e.interactions]);return p(B,{children:[i($e.Handle,{type:"target",position:r,isConnectable:t}),i(s.Box,{sx:{position:"absolute",top:0,right:0},children:i(T.ChevronsUpRight,{size:12})}),p(s.HoverCard,{shadow:"xl",withinPortal:!0,children:[i(s.HoverCard.Target,{children:i(s.Text,{children:e.label})}),i(s.HoverCard.Dropdown,{children:i(s.List,{spacing:"xs",size:"sm",center:!0,children:o.map(l=>i(s.List.Item,{icon:l.icon,children:l.text},l.key))})})]}),i($e.Handle,{type:"source",position:n,isConnectable:t})]})}),dM="",N_={interaction:V_},q_=k.observer(()=>{const e=we(),{edges:t,nodes:n}=P_(e);return p($e,{nodes:n,edges:t,onNodesChange:x.noop,onEdgesChange:x.noop,onConnect:x.noop,className:"interactions-viewer",fitView:!0,nodeTypes:N_,children:[i($e.MiniMap,{}),i($e.Controls,{}),i($e.Background,{})]})}),F_=k.observer(({opened:e,close:t})=>i(s.Modal,{size:"96vw",opened:e,onClose:t,title:"Interactions",trapFocus:!0,onDragStart:n=>{n.stopPropagation()},styles:{body:{height:"90vh"},content:{transform:"none !important"}},zIndex:300,children:i(q_,{})})),G_={"> 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 W_({onClick:e,name:t,active:n,openSettings:r}){return p(s.Box,{sx:{position:"relative"},children:[i(s.UnstyledButton,{sx:a=>({display:"block",width:"100%",padding:a.spacing.xs,borderRadius:0,position:"relative",color:a.black,"&:hover":{backgroundColor:a.colors.gray[0]},backgroundColor:n?a.colors.gray[2]:"transparent"}),children:i(s.Group,{sx:{width:"calc(100% - 28px)"},onClick:e,children:i(s.Text,{size:"sm",children:t})})}),n&&i(s.Tooltip,{label:"Edit",position:"right",withinPortal:!0,children:i(s.ActionIcon,{onClick:r,variant:"light",color:"blue",sx:{position:"absolute",top:0,bottom:0,height:"100%",right:0,zIndex:0,borderRadius:0},children:i($.IconAdjustments,{size:16})})})]})}const j_=k.observer(()=>{const e=ce(),t=le(),n=b.useCallback(a=>()=>t.views.setIDOfVIE(a),[t]),r=a=>{e.editor.open(["_VIEWS_",a])};return p(s.Box,{sx:{position:"relative"},children:[t.views.options.map(a=>i(W_,{active:t.views.idOfVIE===a.value,name:a.label,onClick:n(a.value),openSettings:()=>r(a.value)},a.value)),i(s.Divider,{variant:"dashed"}),i(s.Button,{variant:"subtle",rightIcon:i($.IconPlus,{size:14}),size:"sm",px:"xs",color:"blue",onClick:t.views.addARandomNewView,sx:{width:"100%",borderRadius:0},styles:{inner:{justifyContent:"space-between"}},children:"Add a View"})]})}),R_=k.observer(()=>{const e=ce(),t=le(),n=()=>{if(!t.queries.firstID){e.editor.open(["_QUERIES_",""]);return}e.editor.open(["_QUERIES_",t.queries.firstID])},r=()=>{if(!t.filters.firstID){e.editor.open(["_FILTERS_",""]);return}e.editor.open(["_FILTERS_",t.filters.firstID])},[a,o]=b.useState(!1),l=()=>o(!0),u=()=>o(!1);return p(s.Navbar,{p:0,width:{base:200,xs:200,sm:200,md:220,lg:240,xl:260},zIndex:299,children:[p(s.Navbar.Section,{children:[p(s.Group,{grow:!0,spacing:0,sx:{...G_,button:{borderWidth:0,borderBottomWidth:1,borderColor:"#e9ecef"}},children:[i(s.Tooltip,{label:"Filters",withinPortal:!0,children:i(s.ActionIcon,{variant:"default",radius:0,size:"md",sx:{height:"30px"},onClick:r,children:i($.IconFilter,{size:18})})}),i(s.Tooltip,{label:"Queries",withinPortal:!0,children:i(s.ActionIcon,{variant:"default",radius:0,size:"md",sx:{height:"30px"},onClick:n,children:i($.IconDatabase,{size:18})})}),i(s.Tooltip,{label:"Interactions Viewer",withinPortal:!0,children:i(s.ActionIcon,{variant:"default",radius:0,size:"md",sx:{height:"30px"},onClick:l,children:i($.IconLink,{size:18})})})]}),i(F_,{opened:a,close:u})]}),i(s.Navbar.Section,{py:5,sx:{borderBottom:"1px solid #eee"},children:i(s.Text,{align:"center",sx:{userSelect:"none",cursor:"default"},children:"Views"})}),i(s.Navbar.Section,{grow:!0,sx:{overflow:"auto"},children:i(j_,{})}),i(s.Navbar.Section,{children:i(s.Group,{grow:!0,p:"md",pt:"sm",sx:{borderTop:"1px solid #eee"},children:i(s.Button,{size:"xs",leftIcon:i($.IconSettings,{size:20}),onClick:()=>e.editor.open([]),children:"Settings"})})})]})}),Y_=k.observer(function({config:t}){return p(B,{children:[i(s.Checkbox,{checked:t.default_value,onChange:n=>t.setDefaultValue(n.currentTarget.checked),label:"Default Checked"}),i(oi,{label:"Description",value:t.description,onChange:t.setDescription,styles:{root:{flexGrow:1,minHeight:"400px"}}})]})}),Q_=[{label:"2022",value:"YYYY"},{label:"202201",value:"YYYYMM"},{label:"20220101",value:"YYYYMMDD"},{label:"2022-01",value:"YYYY-MM"},{label:"2022-01-01",value:"YYYY-MM-DD"}],U_=k.observer(function({config:t}){return p(B,{children:[p(s.Group,{children:[i(s.Checkbox,{checked:t.required,onChange:n=>t.setRequired(n.currentTarget.checked),label:"Required"}),i(s.Checkbox,{checked:t.clearable,onChange:n=>t.setClearable(n.currentTarget.checked),disabled:t.max_days>0,label:"Clearable"}),i(s.Checkbox,{checked:t.allowSingleDateInRange,onChange:n=>t.setAllowSingleDateInRange(n.currentTarget.checked),label:"Allow choosing 1 day"})]}),i(s.Select,{data:Q_,label:"Display Format",value:t.inputFormat,onChange:t.setInputFormat}),i(jo,{label:"Default Value",config:t,value:t.default_value,onChange:t.setDefaultValue}),i(s.NumberInput,{label:"Max Days",description:p(s.Group,{position:"apart",children:[i(s.Text,{children:"Set 0 to disable."}),p(s.Group,{spacing:4,children:[i(s.Text,{children:"This feature requires"}),i(s.Text,{color:"blue",children:"Clearable"}),i(s.Text,{children:"to be checked"})]})]}),min:0,value:t.max_days,onChange:t.setMaxDays,hideControls:!0})]})}),Bi=k.observer(({value:e,onChange:t})=>{const n=ce(),r=le(),a=b.useMemo(()=>r.queries.options,[r.queries.current]),o=a.length===0,l=u=>{n.editor.setPath(["_QUERIES_",u])};return i(s.Select,{label:p(s.Group,{position:"apart",children:[i(s.Text,{children:"Use query data as options"}),e&&i(s.Button,{size:"xs",leftIcon:i($.IconArrowCurveRight,{size:16}),variant:"subtle",color:"blue",onClick:()=>l(e),children:"Open this query"})]}),data:a,value:e,onChange:t,allowDeselect:!1,clearable:!0,sx:{flexGrow:1},disabled:o,error:o?"You need to add a query in Data Settings":void 0,styles:{label:{display:"block"}}})}),K_=`
505
505
  // row
506
506
  {
507
507
  label: string;
508
508
  value: string;
509
509
  description?: string; // optional
510
510
  }
511
- `,tu=()=>{const[e,t]=y.useState(!1);return p(B,{children:[i(s.Button,{variant:"subtle",compact:!0,onClick:()=>t(n=>!n),children:e?"Close":"Click to see expected data structure"}),i(s.Collapse,{in:e,children:i(kt.Prism,{language:"typescript",noCopy:!0,colorScheme:"dark",children:K_})})]})},X_=k.observer(function({config:t}){const n=()=>{t.addStaticOption({label:"",value:""})},r=t.static_options,a=[...r];return p(B,{children:[i(s.Checkbox,{checked:t.required,onChange:o=>t.setRequired(o.currentTarget.checked),label:"Required"}),i(s.TextInput,{label:"Width",description:"At least 160px",value:t.min_width,onChange:o=>t.setMinWidth(o.currentTarget.value),placeholder:"default: 200px"}),i(s.Divider,{label:"Configure options",labelPosition:"center"}),p(s.Stack,{spacing:10,sx:{position:"relative",minHeight:"50px"},children:[t.usingQuery&&p(B,{children:[i(s.Overlay,{opacity:.8,color:"#000",sx:{left:"-5px",right:"-5px",top:"-5px",bottom:"-5px"}}),i(s.Center,{sx:{position:"absolute",top:0,left:0,zIndex:200,height:"100%",width:"100%"},children:i(s.Text,{color:"white",size:16,children:"Using query"})})]}),r.length>0&&i(s.MultiSelect,{label:"Default Selection",data:a,value:[...t.default_value],onChange:t.setDefaultValue}),r.map((o,l)=>p(s.Flex,{gap:10,sx:{position:"relative"},pr:"40px",children:[i(s.TextInput,{label:"Label",required:!0,value:t.static_options[l].label,onChange:u=>{t.static_options[l].setLabel(u.currentTarget.value)},sx:{flexGrow:1}}),i(s.TextInput,{label:"Value",required:!0,value:t.static_options[l].value,onChange:u=>{t.static_options[l].setValue(u.currentTarget.value)},sx:{flexGrow:1}}),i(s.ActionIcon,{color:"red",variant:"subtle",onClick:()=>t.removeStaticOption(l),sx:{position:"absolute",top:28,right:5},children:i(T.Trash,{size:16})})]},l)),i(s.Button,{mt:10,size:"xs",color:"blue",leftIcon:i(T.PlaylistAdd,{size:20}),onClick:n,sx:{width:"50%"},mx:"auto",children:"Add an Option"})]}),i(s.Divider,{label:"Or fetch options from database",labelPosition:"center"}),i(s.NumberInput,{value:t.default_selection_count,onChange:t.setDefaultSelectionCount,label:"Select first N options by default"}),i(Bi,{value:t.options_query_id,onChange:t.setOptionsQueryID}),i(tu,{})]})}),J_=k.observer(function({config:t}){const n=()=>{t.addStaticOption({label:"",value:""})},r=t.static_options,a=[{label:"No default selection",value:""},...r];return p(B,{children:[i(s.Checkbox,{checked:t.required,onChange:o=>t.setRequired(o.currentTarget.checked),label:"Required"}),i(s.TextInput,{label:"Width",value:t.width,onChange:o=>t.setWidth(o.currentTarget.value),placeholder:"200px"}),i(s.Divider,{label:"Configure options",labelPosition:"center"}),p(s.Stack,{spacing:10,sx:{position:"relative",minHeight:"50px"},children:[t.usingQuery&&p(B,{children:[i(s.Overlay,{opacity:.8,color:"#000",sx:{left:"-5px",right:"-5px",top:"-5px",bottom:"-5px"}}),i(s.Center,{sx:{position:"absolute",top:0,left:0,zIndex:200,height:"100%",width:"100%"},children:i(s.Text,{color:"white",size:16,children:"Using query"})})]}),r.length>0&&i(s.Select,{label:"Default Selection",data:a,value:t.default_value,onChange:t.setDefaultValue}),r.map((o,l)=>p(s.Flex,{gap:10,sx:{position:"relative"},pr:"40px",children:[i(s.TextInput,{label:"Label",required:!0,value:t.static_options[l].label,onChange:u=>{t.static_options[l].setLabel(u.currentTarget.value)},sx:{flexGrow:1}}),i(s.TextInput,{label:"Value",required:!0,value:t.static_options[l].value,onChange:u=>{t.static_options[l].setValue(u.currentTarget.value)},sx:{flexGrow:1}}),i(s.ActionIcon,{color:"red",variant:"subtle",onClick:()=>t.removeStaticOption(l),sx:{position:"absolute",top:28,right:5},children:i(T.Trash,{size:16})})]},l)),i(s.Button,{size:"xs",color:"blue",leftIcon:i(T.PlaylistAdd,{size:20}),onClick:n,sx:{width:"50%"},mx:"auto",children:"Add an Option"})]}),i(s.Divider,{label:"Or fetch options from database",labelPosition:"center"}),i(s.Checkbox,{checked:t.default_selection_count===1,onChange:o=>t.setDefaultSelectionCount(o.currentTarget.checked?1:0),label:"Select the first option by default"}),i(Bi,{value:t.options_query_id,onChange:t.setOptionsQueryID}),i(tu,{})]})}),Z_=k.observer(function({config:t}){return p(B,{children:[i(s.TextInput,{label:"Default Value",value:t.default_value,onChange:n=>{t.setDefaultValue(n.currentTarget.value)}}),i(s.Checkbox,{checked:t.required,onChange:n=>t.setRequired(n.currentTarget.checked),label:"Required"})]})}),H_=`
511
+ `,tu=()=>{const[e,t]=b.useState(!1);return p(B,{children:[i(s.Button,{variant:"subtle",compact:!0,onClick:()=>t(n=>!n),children:e?"Close":"Click to see expected data structure"}),i(s.Collapse,{in:e,children:i(kt.Prism,{language:"typescript",noCopy:!0,colorScheme:"dark",children:K_})})]})},X_=k.observer(function({config:t}){const n=()=>{t.addStaticOption({label:"",value:""})},r=t.static_options,a=[...r];return p(B,{children:[i(s.Checkbox,{checked:t.required,onChange:o=>t.setRequired(o.currentTarget.checked),label:"Required"}),i(s.TextInput,{label:"Width",description:"At least 160px",value:t.min_width,onChange:o=>t.setMinWidth(o.currentTarget.value),placeholder:"default: 200px"}),i(s.Divider,{label:"Configure options",labelPosition:"center"}),p(s.Stack,{spacing:10,sx:{position:"relative",minHeight:"50px"},children:[t.usingQuery&&p(B,{children:[i(s.Overlay,{opacity:.8,color:"#000",sx:{left:"-5px",right:"-5px",top:"-5px",bottom:"-5px"}}),i(s.Center,{sx:{position:"absolute",top:0,left:0,zIndex:200,height:"100%",width:"100%"},children:i(s.Text,{color:"white",size:16,children:"Using query"})})]}),r.length>0&&i(s.MultiSelect,{label:"Default Selection",data:a,value:[...t.default_value],onChange:t.setDefaultValue}),r.map((o,l)=>p(s.Flex,{gap:10,sx:{position:"relative"},pr:"40px",children:[i(s.TextInput,{label:"Label",required:!0,value:t.static_options[l].label,onChange:u=>{t.static_options[l].setLabel(u.currentTarget.value)},sx:{flexGrow:1}}),i(s.TextInput,{label:"Value",required:!0,value:t.static_options[l].value,onChange:u=>{t.static_options[l].setValue(u.currentTarget.value)},sx:{flexGrow:1}}),i(s.ActionIcon,{color:"red",variant:"subtle",onClick:()=>t.removeStaticOption(l),sx:{position:"absolute",top:28,right:5},children:i(T.Trash,{size:16})})]},l)),i(s.Button,{mt:10,size:"xs",color:"blue",leftIcon:i(T.PlaylistAdd,{size:20}),onClick:n,sx:{width:"50%"},mx:"auto",children:"Add an Option"})]}),i(s.Divider,{label:"Or fetch options from database",labelPosition:"center"}),i(s.NumberInput,{value:t.default_selection_count,onChange:t.setDefaultSelectionCount,label:"Select first N options by default"}),i(Bi,{value:t.options_query_id,onChange:t.setOptionsQueryID}),i(tu,{})]})}),J_=k.observer(function({config:t}){const n=()=>{t.addStaticOption({label:"",value:""})},r=t.static_options,a=[{label:"No default selection",value:""},...r];return p(B,{children:[i(s.Checkbox,{checked:t.required,onChange:o=>t.setRequired(o.currentTarget.checked),label:"Required"}),i(s.TextInput,{label:"Width",value:t.width,onChange:o=>t.setWidth(o.currentTarget.value),placeholder:"200px"}),i(s.Divider,{label:"Configure options",labelPosition:"center"}),p(s.Stack,{spacing:10,sx:{position:"relative",minHeight:"50px"},children:[t.usingQuery&&p(B,{children:[i(s.Overlay,{opacity:.8,color:"#000",sx:{left:"-5px",right:"-5px",top:"-5px",bottom:"-5px"}}),i(s.Center,{sx:{position:"absolute",top:0,left:0,zIndex:200,height:"100%",width:"100%"},children:i(s.Text,{color:"white",size:16,children:"Using query"})})]}),r.length>0&&i(s.Select,{label:"Default Selection",data:a,value:t.default_value,onChange:t.setDefaultValue}),r.map((o,l)=>p(s.Flex,{gap:10,sx:{position:"relative"},pr:"40px",children:[i(s.TextInput,{label:"Label",required:!0,value:t.static_options[l].label,onChange:u=>{t.static_options[l].setLabel(u.currentTarget.value)},sx:{flexGrow:1}}),i(s.TextInput,{label:"Value",required:!0,value:t.static_options[l].value,onChange:u=>{t.static_options[l].setValue(u.currentTarget.value)},sx:{flexGrow:1}}),i(s.ActionIcon,{color:"red",variant:"subtle",onClick:()=>t.removeStaticOption(l),sx:{position:"absolute",top:28,right:5},children:i(T.Trash,{size:16})})]},l)),i(s.Button,{size:"xs",color:"blue",leftIcon:i(T.PlaylistAdd,{size:20}),onClick:n,sx:{width:"50%"},mx:"auto",children:"Add an Option"})]}),i(s.Divider,{label:"Or fetch options from database",labelPosition:"center"}),i(s.Checkbox,{checked:t.default_selection_count===1,onChange:o=>t.setDefaultSelectionCount(o.currentTarget.checked?1:0),label:"Select the first option by default"}),i(Bi,{value:t.options_query_id,onChange:t.setOptionsQueryID}),i(tu,{})]})}),Z_=k.observer(function({config:t}){return p(B,{children:[i(s.TextInput,{label:"Default Value",value:t.default_value,onChange:n=>{t.setDefaultValue(n.currentTarget.value)}}),i(s.Checkbox,{checked:t.required,onChange:n=>t.setRequired(n.currentTarget.checked),label:"Required"})]})}),H_=`
512
512
  // row
513
513
  {
514
514
  label: string;
@@ -516,7 +516,7 @@ Check the top-level render call using <`+V+">.")}return E}}function Su(S,E){{if(
516
516
  parent_value: string;
517
517
  description?: string;
518
518
  }
519
- `,ek=()=>{const[e,t]=y.useState(!1);return p(B,{children:[i(s.Button,{variant:"subtle",compact:!0,onClick:()=>t(n=>!n),children:e?"Close":"Click to see expected data structure"}),i(s.Collapse,{in:e,children:i(kt.Prism,{language:"typescript",noCopy:!0,colorScheme:"dark",children:H_})})]})},tk=k.observer(function({config:t}){return p(B,{children:[i(s.Checkbox,{checked:t.required,onChange:n=>t.setRequired(n.currentTarget.checked),label:"Required"}),i(s.TextInput,{label:"Min-width",value:t.min_width,onChange:n=>t.setMinWidth(n.currentTarget.value),placeholder:"200px"}),i(s.Divider,{label:"Fetch options from database",labelPosition:"center"}),i(s.Checkbox,{checked:t.treeCheckStrictly,onChange:n=>t.setTreeCheckStrictly(n.currentTarget.checked),label:"Parent and children nodes are not associated"}),i(s.NumberInput,{value:t.default_selection_count,onChange:t.setDefaultSelectionCount,label:"Select first N options by default"}),i(Bi,{value:t.options_query_id,onChange:t.setOptionsQueryID}),i(ek,{})]})}),nk=k.observer(function({filter:t}){return p(s.Box,{sx:{maxWidth:"480px"},children:[i(s.Text,{pt:"0",pb:"md",color:"gray",children:"Config"}),i(kt.Prism,{mt:22,language:"json",colorScheme:"dark",noCopy:!0,children:JSON.stringify(t,null,4)})]})}),rk={select:J_,"multi-select":X_,"tree-select":tk,"text-input":Z_,checkbox:Y_,"date-range":U_},ik=[{label:"Select",value:"select"},{label:"Multi Select",value:"multi-select"},{label:"Tree Select",value:"tree-select"},{label:"Text Input",value:"text-input"},{label:"Checkbox",value:"checkbox"},{label:"Date Range",value:"date-range"}],ak=k.observer(function({filter:t}){const n=le(),r=y.useMemo(()=>rk[t.type],[t.type]);return p(s.Group,{grow:!0,spacing:20,align:"top",children:[p(s.Box,{sx:{maxWidth:"600px"},children:[i(s.Text,{pb:"md",color:"gray",children:"Edit"}),p(s.Stack,{children:[p(s.Group,{noWrap:!0,children:[i(s.NumberInput,{label:"Placement Order",required:!0,value:t.order,onChange:t.setOrder,hideControls:!0,sx:{flexGrow:"1 !important"}}),t.auto_submit_supported&&i(s.Checkbox,{label:"Submit automatically",checked:t.auto_submit,onChange:a=>t.setAutoSubmit(a.currentTarget.checked),mt:22})]}),i(s.MultiSelect,{label:"Visible in...",data:n.views.options,value:[...t.visibleInViewsIDs],onChange:t.setVisibleInViewsIDs}),i(s.TextInput,{label:"Key",placeholder:"A unique key to refer",required:!0,value:t.key,onChange:a=>{t.setKey(a.currentTarget.value)}}),i(s.TextInput,{label:"Label",placeholder:"Label for this field",required:!0,value:t.label,onChange:a=>{t.setLabel(a.currentTarget.value)}}),i(s.Select,{label:"Widget",data:ik,required:!0,value:t.type,onChange:t.setType}),i(r,{config:t.config})]})]}),i(nk,{filter:t})]})}),sk=k.observer(({id:e})=>{const t=Qe.useModals(),n=pe(),r=le();if(e==="")return null;const a=r.filters.findByID(e);if(!a)return p(s.Text,{size:14,children:["Filter by ID[",e,"] is not found"]});const o=()=>{n.editor.setPath(["_FILTERS_",""])},l=()=>{t.openConfirmModal({title:"Delete this filter?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>{r.filters.removeByID(e),o()},confirmProps:{color:"red"},zIndex:320})};return p(s.Stack,{sx:{maxWidth:"1100px",height:"100vh"},spacing:"sm",pb:30,children:[i(s.Group,{position:"right",pt:10,children:i(s.Button,{size:"xs",color:"red",leftIcon:i(T.Trash,{size:16}),onClick:l,children:"Delete this filter"})}),i(s.Box,{sx:{flexGrow:1,maxHeight:"calc(100% - 52px)",overflow:"auto"},children:i(ak,{filter:a})})]})}),ok=k.observer(()=>{const e=le(),[t,n]=y.useState(()=>JSON.stringify(e.mock_context.current,null,4)),r=()=>{try{e.mock_context.replace(JSON.parse(t))}catch(o){vn.showNotification({title:"Failed",message:o.message,color:"red"})}},a=y.useMemo(()=>{try{return JSON.stringify(JSON.parse(t))!==JSON.stringify(e.mock_context.current)}catch{return!1}},[t,e.mock_context.current]);return p(s.Stack,{sx:{border:"1px solid #eee",borderLeft:"none",borderRight:"none",flexGrow:1,maxWidth:"unset"},children:[i(s.Group,{position:"left",pl:"md",py:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef",flexGrow:0},children:i(s.Text,{weight:500,children:"Mock Context"})}),p(s.Group,{grow:!0,px:"md",pb:"md",pt:0,sx:{flexGrow:1,position:"relative",alignItems:"flex-start"},children:[p(s.Stack,{spacing:10,sx:{maxWidth:"unset !important"},children:[i(s.Text,{children:"A valid json string is required"}),i(s.JsonInput,{validationError:"Invalid json",formatOnBlur:!0,autosize:!0,minRows:30,value:t,onChange:n,sx:{flexGrow:1}})]}),i(s.ActionIcon,{mr:5,variant:"filled",color:"blue",sx:{position:"absolute",right:12,top:0},disabled:!a,onClick:r,children:i(T.DeviceFloppy,{size:20})})]})]})}),lk=k.observer(()=>{const{panel:e}=nt();return i(oi,{label:"Description",value:e.description,onChange:e.setDescription,styles:{root:{flexGrow:1}}})}),uk=k.observer(()=>{const{panel:e}=nt(),{style:t}=e;return p(B,{children:[i(s.Divider,{mb:-10,label:"Style",labelPosition:"center",variant:"dashed"}),p(s.Stack,{spacing:20,children:[p(s.Group,{grow:!0,align:"top",children:[i(s.NumberInput,{label:"Width",min:1,max:36,step:1,precision:0,rightSection:i(s.Text,{size:12,children:"of 36 columns"}),styles:{rightSection:{width:"110px"}},value:e.layout.w,onChange:n=>{n&&e.layout.setWidth(n)}}),i(s.NumberInput,{label:"Height",rightSection:i(s.Text,{size:12,children:"px"}),styles:{rightSection:{width:"40px"}},value:e.layout.h,onChange:n=>{n&&e.layout.setHeight(n)}})]}),i(s.Switch,{label:"Border",checked:t.border.enabled,onChange:n=>t.border.setEnabled(n.currentTarget.checked)})]})]})}),ck=k.observer(()=>{const{panel:e}=nt(),{title:t,setTitle:n}=e,[r,a]=Ie.useInputState(t),o=t!==r,l=y.useCallback(()=>{o&&n(r)},[o,r]);return y.useEffect(()=>{a(t)},[t]),i(s.TextInput,{value:r,onChange:a,label:p(s.Group,{children:[i(s.Text,{children:"Panel Title"}),i(s.ActionIcon,{variant:"subtle",color:"blue",disabled:!o,onClick:l,children:i(T.DeviceFloppy,{size:20})})]}),styles:{label:{display:"block",paddingBottom:"4px"}}})});function dk(){return p(s.Stack,{sx:{height:"100%"},children:[i(uk,{}),i(s.Divider,{label:"Info",labelPosition:"center",variant:"dashed"}),i(ck,{}),i(lk,{})]})}const pk={width:"fit-content",minWidth:"100%",tableLayout:"fixed",tr:{width:"fit-content"},th:{position:"relative"},"th, td":{wordBreak:"break-word"},".resizer":{position:"absolute",right:0,top:"50%",transform:"translateY(-50%)",cursor:"col-resize",userSelect:"none",touchAction:"none"},".resizer.isResizing":{color:"#228be6",opacity:"1"},"@media (hover: hover)":{".resizer":{opacity:"0"},"*:hover > .resizer":{color:"#228be6",opacity:"1"}}};function nu({data:e}){const t=y.useMemo(()=>{if(!Array.isArray(e)||e.length===0)return[];const r=tt.createColumnHelper();return Object.keys(e[0]).map(a=>r.accessor(a,{cell:o=>o.getValue()}))},[e]),n=tt.useReactTable({data:e,columns:t,columnResizeMode:"onChange",getCoreRowModel:tt.getCoreRowModel()});return e.length===0?i(s.Box,{sx:{height:"5em"}}):i(Fe,{children:p(s.Table,{sx:pk,children:[i("thead",{children:n.getHeaderGroups().map(r=>i("tr",{children:r.headers.map(a=>p("th",{style:{width:a.getSize()},children:[a.isPlaceholder?null:tt.flexRender(a.column.columnDef.header,a.getContext()),i(s.ActionIcon,{onMouseDown:a.getResizeHandler(),onTouchStart:a.getResizeHandler(),className:`resizer ${a.column.getIsResizing()?"isResizing":""}`,children:i(T.ArrowBarToRight,{})})]},a.id))},r.id))}),i("tbody",{children:n.getRowModel().rows.map(r=>i("tr",{children:r.getVisibleCells().map(a=>i("td",{children:i(Fe,{children:tt.flexRender(a.column.columnDef.cell,a.getContext())})},a.id))},r.id))})]})})}const hk=({queryID:e})=>{const t=we(),{state:n,error:r}=t.getDataStuffByID(e),a=y.useMemo(()=>t.queries.findByID(e),[t,e]);return n==="loading"?null:r?i(s.Text,{color:"red",size:"md",align:"center",sx:{fontFamily:"monospace"},children:r}):a!=null&&a.stateMessage?i(s.Text,{color:"gray",align:"center",children:a.stateMessage}):null},Vi=k.observer(function({id:t,moreActions:n=null}){const r=we(),{data:a,state:o}=r.getDataStuffByID(t),l=o==="loading",u=()=>{r.queries.refetchDataByQueryID(t)},c=()=>{r.queries.downloadDataByQueryID(t)},d=y.useMemo(()=>Array.isArray(a)?a.slice(0,10):[],[a]),f=!Array.isArray(a)||a.length===0;return p(s.Stack,{sx:{border:"1px solid #eee"},children:[p(s.Group,{position:"apart",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[p(s.Group,{position:"left",children:[i(s.Text,{weight:500,children:"Preview Data"}),a.length>10&&p(s.Text,{size:"sm",color:"gray",children:["Showing 10 rows of ",a.length]})]}),p(s.Group,{pr:15,children:[n,i(s.ActionIcon,{variant:"subtle",color:"blue",disabled:l,onClick:u,children:i(T.Refresh,{size:16})}),i(s.ActionIcon,{variant:"subtle",color:"blue",disabled:l||f,onClick:c,children:i(T.Download,{size:16})})]})]}),p(s.Box,{sx:{position:"relative",overflow:"auto"},children:[i(s.LoadingOverlay,{visible:l}),i(hk,{queryID:t}),i(nu,{data:d})]})]})}),fk=k.observer(function(){const t=pe(),n=le(),{panel:r}=nt(),[a,o]=y.useState(!1),l=u=>{t.editor.setPath(["_QUERIES_",u])};return p(B,{children:[i(s.Drawer,{opened:a,onClose:()=>o(!1),title:"Choose queries",padding:"xl",size:500,zIndex:320,children:i(s.Checkbox.Group,{value:[...r.queryIDs],onChange:r.setQueryIDs,children:i(s.Stack,{spacing:"lg",children:n.queries.options.map(u=>i(s.Checkbox,{label:u.label,value:u.value},u.value))})})}),p(s.Stack,{spacing:6,children:[i(s.Group,{position:"right",children:i(s.Button,{variant:"light",size:"sm",leftIcon:i($.IconLine,{size:16}),onClick:()=>o(!0),children:"Click me to choose queries for this panel"})}),r.queryIDs.length===1&&i(Vi,{id:r.queryIDs[0],moreActions:i(s.Tooltip,{label:"Open this query",children:i(s.ActionIcon,{variant:"subtle",color:"blue",onClick:()=>l(r.queryIDs[0]),children:i($.IconArrowCurveRight,{size:16})})})}),r.queryIDs.length>1&&p(s.Tabs,{defaultValue:r.queryIDs[0],children:[i(s.Tabs.List,{children:r.queries.map(u=>i(s.Tabs.Tab,{value:u.id,children:u.name},u.id))}),r.queries.map(u=>i(s.Tabs.Panel,{value:u.id,children:i(Vi,{id:u.id,moreActions:i(s.Tooltip,{label:"Open this query",children:i(s.ActionIcon,{variant:"subtle",color:"blue",onClick:()=>l(u.id),children:i($.IconArrowCurveRight,{size:16})})})})},u.id))]})]})]})}),gk=k.observer(()=>{const{panel:e}=bt();return i(Fe,{children:i(s.Box,{sx:{height:"100%",flexGrow:0,flexShrink:0,width:"600px"},children:p(s.Stack,{mt:24,spacing:5,sx:{width:"600px",height:"450px",background:"transparent",borderRadius:"5px",border:"1px solid #e9ecef",borderWidth:e.style.border.enabled?"1px":"0px"},children:[p(s.Group,{position:"apart",noWrap:!0,sx:{flexGrow:0,flexShrink:0},children:[i(s.Group,{children:i(Ii,{})}),i(s.Group,{grow:!0,position:"center",children:i(s.Text,{lineClamp:1,weight:"bold",children:e.title})}),i(s.Group,{position:"right",spacing:0,sx:{height:"28px"}})]}),i(s.Group,{px:5,pb:5,sx:{flexGrow:1},children:i(Mi,{panel:e,height:"410px"})})]})})})}),Ni={name:"new_var",size:"1rem",weight:"initial",color:{type:"static",staticColor:"Red"},data_field:"",aggregation:{type:"sum",config:{}},formatter:{output:"number",mantissa:0,trimMantissa:!1,average:!1}};class mk{constructor(t){N(this,"panel");N(this,"selected");this.panel=t,te.makeAutoObservable(this,{},{deep:!1,autoBind:!0})}get variables(){return this.panel.variables}addNew(){const t=this.panel.variables.filter(n=>n.name.startsWith(Ni.name)).length;this.panel.addVariable(x.cloneDeep({...Ni,name:`${Ni.name}${t||""}`})),this.selected=x.last(this.panel.variables)}select(t){this.selected=t}remove(t){this.selected===t&&(this.selected=void 0);const n=this.panel.variables.indexOf(t);if(this.panel.removeVariable(t),!this.selected&&!x.isEmpty(this.panel.variables)){const r=Math.min(this.panel.variables.length-1,n);this.selected=this.panel.variables[r]}}}function yk(){const{panel:e}=nt();return K.useCreation(()=>new mk(e),[e])}const ru=s.createStyles(e=>({root:{height:"100%",overflow:"hidden",".var-list-container":{"& > *":{height:"100%"},width:250,height:"100%"},".var-list-actions":{height:"fit-content",flexShrink:0,width:"100%"},".var-list":{flex:"1 1 auto",overflow:"auto",minHeight:0,"& > *":{flex:"0 0 auto"}}},config:{height:"100%",overflow:"auto",paddingRight:10}})),bk=y.forwardRef(function({value:t,onChange:n,data:r,withStyle:a=!0},o){const l=(u,c)=>{const d=x.cloneDeep(t);x.set(d,u,c),n(d)};return p(s.Box,{px:"sm",py:"md",ref:o,children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(s.TextInput,{label:"Name",required:!0,value:t.name,onChange:u=>l("name",u.currentTarget.value)}),i(W,{label:"Data Field",required:!0,value:t.data_field,onChange:u=>l("data_field",u)})]}),i(Gn,{label:"Aggregation",value:t.aggregation,onChange:u=>l("aggregation",u)}),t.aggregation.type!=="custom"&&p(B,{children:[i(s.Divider,{my:"xs",label:"Format",labelPosition:"center"}),i(We,{value:t.formatter,onChange:u=>l("formatter",u)})]}),a&&i(Ys,{value:t,onChange:n})]})}),vk=e=>{const{uiModel:t}=e;return i(s.Stack,{className:"var-list",children:t.variables.map(n=>i(s.Button,{variant:t.selected===n?"filled":"subtle",color:"gray",onClick:()=>t.select(n),children:n.name},n.name))})},xk=k.observer(vk),wk=({variable:e,data:t})=>i(s.Group,{style:{minHeight:0,height:"calc(100% - 68px)"},children:i(s.Paper,{withBorder:!0,p:"md",children:Qs(e,t)})}),Ck=k.observer(wk),Sk=e=>{const t=K.useCreation(()=>xS(e.variable),[e.variable]),{classes:n}=ru(),{data:r}=nt();return p(s.Group,{style:{height:"100%"},align:"start",children:[p(s.Stack,{"data-testid":"variable-editor",align:"stretch",className:n.config,children:[p(s.Group,{position:"right",children:[i(s.ActionIcon,{variant:"filled",disabled:!t.changed,color:"primary",onClick:t.commit,children:i($.IconDeviceFloppy,{size:18})}),i(s.ActionIcon,{color:"red",onClick:()=>e.uiModel.remove(e.variable),children:i($.IconTrash,{size:18})})]}),i(bk,{value:b.getSnapshot(t.copy),onChange:t.update,data:r})]}),i(Ck,{variable:b.getSnapshot(t.copy),data:r})]})},_k=k.observer(Sk),kk=()=>{const e=yk(),{classes:t}=ru();return p(s.Group,{className:t.root,noWrap:!0,align:"start",children:[i(s.Paper,{withBorder:!0,p:"md",className:"var-list-container",children:p(s.Stack,{justify:"space-between",children:[i(s.Box,{className:"var-list-actions",children:i(s.Button,{variant:"light",size:"sm",onClick:e.addNew,fullWidth:!0,children:"Add Variable"})}),i(xk,{uiModel:e})]})}),e.selected?i(B,{children:i(_k,{uiModel:e,variable:e.selected})}):i("span",{children:"Select or create a new variable on right side"})]})},Tk=k.observer(kk);function Dk(){const{vizManager:e}=y.useContext(ut);return y.useMemo(()=>{const t=e.availableVizList.map(n=>({value:n.name,label:n.displayName??n.name,group:n.displayGroup??""}));return x.orderBy(t,[n=>n.group,n=>n.label],["asc","asc"])},[e])}const Ik=k.observer(({value:e,submit:t})=>{const[n,r]=Ie.useInputState(e);y.useEffect(()=>{r(e)},[e]);const a=Dk(),o=e!==n;return i(s.Select,{label:"Visualization",value:n,searchable:!0,onChange:r,data:a,rightSection:i(s.ActionIcon,{disabled:!o,onClick:()=>t(n),children:i(T.DeviceFloppy,{size:20})}),maxDropdownHeight:600})}),iu=[];function Mk(e,t){try{return e.resolveComponent(t).createConfig()}catch{return null}}function Ak(){const{data:e,panel:{variables:t,viz:n,title:r,queryIDs:a,description:o,setDescription:l,setTitle:u,addQueryID:c,removeQueryID:d,id:f}}=nt(),{vizManager:h}=y.useContext(ut),g={title:r,description:o,viz:n,queryIDs:a,id:f},m={setDescription:l,addQueryID:c,removeQueryID:d,setTitle:u},C=_l(g);try{return h.resolveComponent(g.viz.type),i(er,{configure:C,children:i(TS,{variables:t,setVizConf:n.setConf,panel:g,panelInfoEditor:m,vizManager:h,data:e})})}catch(w){return console.info(x.get(w,"message")),null}}const zk=k.observer(()=>{const{data:e,panel:{viz:t}}=nt(),{vizManager:n}=y.useContext(ut),r=y.useCallback(d=>{if(d===t.type)return;const f=Mk(n,d);t.setType(d),t.setConf(f||{})},[t.type]),a=d=>{try{t.setConf(JSON.parse(d))}catch(f){console.error(f)}},o=y.useMemo(()=>{var d;return(d=iu.find(f=>f.value===t.type))==null?void 0:d.Panel},[t.type,iu]),l=Ak(),u=o?y.createElement(o,{data:e,conf:t.conf,setConf:t.setConf}):null,c=l||u;return p(s.Stack,{align:"stretch",sx:{height:"100%",overflow:"hidden"},children:[i(Ik,{submit:r,value:t.type}),p(Fe,{children:[i(s.Stack,{pb:10,sx:{flexGrow:1,maxHeight:"100%",overflow:"auto"},children:c}),!c&&i(s.JsonInput,{minRows:20,label:"Config",value:JSON.stringify(t.conf,null,2),onChange:a})]})]})}),Ek=k.observer(({panel:e,sourceViewID:t})=>{const n=le(),[r,a]=y.useState(t);y.useEffect(()=>{a(t)},[t]);const[o,{open:l,close:u}]=Ie.useDisclosure(!1),c=()=>{e.moveToView(t,r),u()};return p(B,{children:[i(s.Button,{size:"xs",variant:"subtle",color:"blue",onClick:l,leftIcon:i($.IconBoxMultiple,{size:14}),children:"Move into Another View"}),i(s.Modal,{opened:o,onClose:u,title:"Move panel into another view",zIndex:320,children:p(s.Stack,{sx:{maxHeight:"calc(100vh - 185px)",overflow:"hidden"},children:[i(s.Radio.Group,{value:r,onChange:a,pb:10,sx:{flexGrow:1,maxHeight:"calc(100vh - 185px - 30px)",overflow:"auto"},children:i(s.Stack,{spacing:"xs",children:n.views.options.map(d=>i(s.Radio,{value:d.value,label:d.label},d.value))})}),p(s.Group,{noWrap:!0,position:"apart",sx:{flexGrow:0,flexShrink:0},children:[i(s.Button,{size:"xs",color:"red",leftIcon:i($.IconX,{size:14}),onClick:u,children:"Cancel"}),i(s.Button,{size:"xs",color:"blue",leftIcon:i($.IconDeviceFloppy,{size:14}),onClick:c,disabled:r===t,children:"Confirm"})]})]})})]})}),$k={root:{flexGrow:1,width:"100%",overflow:"hidden"},panel:{width:"100%",height:"calc(100% - 44px)",padding:10,overflow:"scroll"}},au=({children:e})=>p(s.Group,{noWrap:!0,grow:!0,position:"left",spacing:20,sx:{width:"100%",height:"100%"},children:[i(s.Box,{sx:{maxWidth:"calc(100% - 610px - 10px)",height:"100%",overflow:"auto"},children:e}),i(gk,{})]});function Lk(e){return!["richText","button"].includes(e)}const Ok=k.observer(({panel:e})=>{const t=Qe.useModals(),n=pe(),r=le(),[a,o]=y.useState("Data"),l=e.queries,c=Lk(e.viz.type)&&e.dataLoading,d=c||e.queryErrors.length>0||e.queryStateMessages!==""||l.length===0,f=n.editor.path[1];y.useEffect(()=>{o(m=>d&&m==="Visualization"?"Data":m)},[e.id,d]);const h=()=>{n.editor.setPath(["_VIEWS_",f])},g=()=>t.openConfirmModal({title:"Delete this panel?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>{r.removePanelByID(e.id,f),h()},confirmProps:{color:"red"},zIndex:320});return p(Sr,{value:{panel:e,data:e.data,loading:c,errors:e.queryErrors,downloadPanelScreenshot:()=>{}},children:[p(s.Group,{px:16,position:"apart",sx:{borderBottom:"1px solid #eee"},children:[p(s.Text,{pt:9,pb:8,children:[e.title?e.title:e.viz.type," "]}),p(s.Group,{position:"right",noWrap:!0,children:[i(Ek,{panel:e,sourceViewID:f}),i(s.Button,{size:"xs",variant:"subtle",color:"red",onClick:g,leftIcon:i($.IconTrash,{size:14}),children:"Delete This Panel"})]})]}),p(s.Tabs,{value:a,onTabChange:o,keepMounted:!1,styles:$k,children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"Data",disabled:c,children:"Data"}),i(s.Tabs.Tab,{value:"Panel",children:"Panel"}),i(s.Tabs.Tab,{value:"Variables",disabled:d,children:i(s.Tooltip,{label:"Requires data",disabled:!d,withinPortal:!0,zIndex:310,children:i(s.Text,{children:"Variables"})})}),i(s.Tabs.Tab,{value:"Visualization",disabled:d,children:i(s.Tooltip,{label:"Requires data",disabled:!d,withinPortal:!0,zIndex:310,children:i(s.Text,{children:"Visualization"})})}),i(s.Tabs.Tab,{value:"Interactions",children:"Interactions"})]}),p(s.Tabs.Panel,{value:"Data",children:[i(s.LoadingOverlay,{visible:c,exitTransitionDuration:0}),i(fk,{})]}),i(s.Tabs.Panel,{value:"Panel",children:i(au,{children:i(dk,{})})}),i(s.Tabs.Panel,{value:"Variables",children:i(Tk,{})}),i(s.Tabs.Panel,{value:"Visualization",children:i(Fe,{children:i(au,{children:i(zk,{})})})}),i(s.Tabs.Panel,{value:"Interactions",children:i(Fe,{children:i(ud,{})})})]})]})}),Pk=k.observer(({viewID:e,panelID:t})=>{const n=le();if(!n.views.findByID(e))return p(s.Text,{size:14,children:["View by ID[",e,"] is not found"]});const a=n.panels.findByID(t);return a?i(Ok,{panel:a}):p(s.Text,{size:14,children:["Panel by ID[",t,"] is not found"]})}),Bk=e=>{const{queryModel:t}=e,n=pe(),r=le(),o=r.findQueryUsage(t.id).length>0,l=Qe.useModals(),u=()=>{l.openConfirmModal({title:"Delete this query?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>{r.queries.removeQuery(t.id),n.editor.setPath(["_QUERIES_",""])},confirmProps:{color:"red"},zIndex:320})};return o?i(s.Tooltip,{label:"Can't delete this query for it's being used, check out Usage tab for details",withArrow:!0,events:{hover:!0,focus:!1,touch:!1},withinPortal:!0,children:i(s.Button,{color:"gray",size:"xs",leftIcon:i($.IconTrash,{size:16}),sx:{alignSelf:"flex-end"},children:"Delete this Query"})}):i(s.Button,{color:"red",size:"xs",onClick:u,leftIcon:i($.IconTrash,{size:16}),sx:{alignSelf:"flex-end"},children:"Delete this Query"})},Vk=k.observer(Bk),su=({width:e="calc(100% - 32px)",lastWidth:t="50%",height:n,count:r,spacing:a=16,pl:o=0})=>p(s.Stack,{spacing:a,mt:6,pl:o,children:[Array.from(new Array(r-1),(l,u)=>i(s.Skeleton,{width:e,height:n,radius:"xs"},u)),i(s.Skeleton,{width:t,height:n,radius:"xs"})]}),hn=({value:e})=>e===null||e===""?null:i(s.Tooltip,{label:e,disabled:!e,multiline:!0,children:i(s.ActionIcon,{children:i($.IconInfoCircle,{size:14})})}),Nk=({column:e})=>{const{column_key:t,column_key_text:n}=e;return t?i(s.Tooltip,{label:n,disabled:!n,children:i(s.Badge,{children:t})}):null},qk=k.observer(({dataSource:e})=>{const{columns:t}=e;return t.loading?i(su,{height:"24px",width:"100%",lastWidth:"100%",count:20,pl:6}):t.empty?null:p(s.Table,{highlightOnHover:!0,fontSize:14,sx:{width:"auto",minWidth:"1000px",alignSelf:"flex-start",flexGrow:0,tableLayout:"fixed",tbody:{fontFamily:"monospace"}},children:[p("colgroup",{children:[i("col",{style:{width:50}}),i("col",{style:{minWidth:300}}),i("col",{style:{width:30}}),i("col",{style:{width:70}}),i("col",{style:{minWidth:300}}),i("col",{style:{minWidth:80,width:80}}),i("col",{style:{minWidth:120,width:120}})]}),i("thead",{children:p("tr",{children:[i("th",{children:"#"}),i("th",{children:"Column Name"}),i("th",{}),i("th",{}),i("th",{children:"Type"}),i("th",{children:"Nullable"}),i("th",{children:"Default Value"})]})}),i("tbody",{children:t.data.map(n=>p("tr",{children:[i("td",{children:n.ordinal_position}),i("td",{children:n.column_name}),i("td",{children:i(hn,{value:n.column_comment})}),i("td",{children:i(Nk,{column:n})}),i("td",{children:n.column_type}),i("td",{children:n.is_nullable}),i("td",{children:i(hn,{value:n.column_default})})]},n.column_name))})]})}),Fk=k.observer(({dataSource:e})=>{const{indexes:t}=e,n=t.data;return p(s.Table,{highlightOnHover:!0,fontSize:14,sx:{width:"auto",minWidth:"950px",alignSelf:"flex-start",flexGrow:0,tableLayout:"fixed",tbody:{fontFamily:"monospace"}},children:[p("colgroup",{children:[i("col",{style:{width:100}}),i("col",{style:{minWidth:300}}),i("col",{style:{width:150}}),i("col",{style:{width:150}}),i("col",{style:{width:250}})]}),i("thead",{children:p("tr",{children:[i("th",{children:"Index Length"}),i("th",{children:"Index Name"}),i("th",{children:"Index Algorithm"}),i("th",{children:"Unique"}),i("th",{children:"Column Name"})]})}),i("tbody",{children:n.map(r=>p("tr",{children:[i("td",{children:r.index_length}),i("td",{children:r.index_name}),i("td",{children:r.index_algorithm}),i("td",{children:r.is_unique?"YES":"NO"}),i("td",{children:r.column_name})]},r.index_name))})]})}),Gk=k.observer(({dataSource:e})=>{const{indexes:t}=e,n=t.data;return p(s.Table,{highlightOnHover:!0,fontSize:14,sx:{width:"auto",minWidth:"850px",alignSelf:"flex-start",flexGrow:0,tableLayout:"fixed",tbody:{fontFamily:"monospace"}},children:[p("colgroup",{children:[i("col",{style:{minWidth:300}}),i("col",{style:{width:150}}),i("col",{style:{width:100}}),i("col",{style:{width:100}}),i("col",{style:{width:100}}),i("col",{style:{width:100}})]}),i("thead",{children:p("tr",{children:[i("th",{children:"Index Name"}),i("th",{children:"Index Algorithm"}),i("th",{children:"Unique"}),i("th",{children:"Definition"}),i("th",{children:"Condition"}),i("th",{children:"Comment"})]})}),i("tbody",{children:n.map(r=>p("tr",{children:[i("td",{children:r.index_name}),i("td",{children:r.index_algorithm}),i("td",{children:r.is_unique?"YES":"NO"}),i("td",{children:i(hn,{value:r.index_definition})}),i("td",{children:i(hn,{value:r.condition})}),i("td",{children:i(hn,{value:r.comment})})]},r.index_name))})]})}),Wk=k.observer(({dataSource:e})=>{const{indexes:t}=e;return t.loading||t.empty?null:e.type===Se.MySQL?i(Fk,{dataSource:e}):e.type===Se.Postgresql?i(Gk,{dataSource:e}):null}),jk=k.observer(({dataSource:e})=>p(s.Stack,{spacing:40,pt:10,sx:{flexGrow:1,overflow:"auto",position:"relative"},children:[i(Fe,{children:i(qk,{dataSource:e})}),i(Fe,{children:i(Wk,{dataSource:e})})]}));function Rk({table_type:e}){return e==="VIEW"?i($.IconEye,{size:14}):e==="BASE TABLE"?i($.IconTable,{size:14}):null}const Yk=k.observer(({dataSource:e})=>{const{tables:t}=e;return t.loading?i(su,{height:"24px",lastWidth:"50%",count:15}):i(s.Box,{h:"100%",sx:{overflow:"auto",".mantine-NavLink-label":{fontFamily:"monospace"}},children:Object.entries(t.data).map(([n,r])=>i(s.NavLink,{label:n,icon:i($.IconDatabase,{size:14}),defaultOpened:e.table_schema===n,pl:0,childrenOffset:14,children:r.map(a=>i(s.NavLink,{label:a.table_name,icon:i(Rk,{table_type:a.table_type}),onClick:()=>{e.setKeywords(n,a.table_name)},active:e.table_name===a.table_name},a.table_name))},n))})}),Qk=({visible:e})=>i(s.Box,{py:10,sx:{width:"100%",height:"100%",overflow:"hidden",position:"relative"},children:i(s.LoadingOverlay,{visible:e})}),Uk=[{label:"10",value:"10"},{label:"20",value:"20"},{label:"50",value:"50"},{label:"100",value:"100"}],Kk={icon:{width:"50px",textAlign:"center"},input:{"&[data-with-icon]":{paddingLeft:"50px"}}},Xk=k.observer(({dataSource:e})=>{const{tableData:t}=e;return p(s.Group,{pt:10,px:10,position:"apart",children:[p(s.Group,{position:"left",children:[t.maxPage>1&&i(s.Pagination,{size:"sm",value:t.page,onChange:t.setPage,total:t.maxPage,withEdges:t.maxPage>7,styles:{control:{height:"30px"}}}),i(s.Select,{icon:i(s.Text,{ta:"center",color:"dimmed",size:14,children:"Limit"}),size:"xs",styles:Kk,data:Uk,value:String(t.limit),onChange:n=>t.setLimit(Number(n))})]}),i(s.Group,{position:"right",children:p(s.Text,{color:"dimmed",my:0,size:14,children:["Total ",t.total," rows"]})})]})}),Jk=k.observer(({dataSource:e})=>{const t=e.tableData;return t.maxPage===0?i(s.Text,{mt:20,color:"red",size:"md",align:"center",sx:{fontFamily:"monospace"},children:"This table is empty"}):t.error?i(s.Text,{mt:20,color:"red",size:"md",align:"center",sx:{fontFamily:"monospace"},children:t.error}):t.page===1&&t.loading?i(Qk,{visible:!0}):p(Fe,{children:[i(Xk,{dataSource:e}),p(s.Box,{py:10,sx:{width:"100%",height:"calc(100% - 42px)",overflow:"auto",position:"relative"},children:[i(s.LoadingOverlay,{visible:t.loading,overlayBlur:2}),i(nu,{data:t.data})]})]})}),Zk={root:{flexGrow:1,overflow:"auto",borderLeft:"1px solid #efefef"},tabsList:{borderBottom:"1px solid #efefef"},tab:{minWidth:120}},Hk=k.observer(({dataSource:e})=>(y.useEffect(()=>{e.loadTablesIfEmpty()},[e]),e.tables.error?i(s.Text,{color:"red",size:"md",align:"center",sx:{fontFamily:"monospace"},children:e.tables.error}):p(s.Flex,{sx:{height:"100%"},children:[i(s.Box,{w:300,sx:{flexGrow:0,flexShrink:0,position:"relative"},children:i(Fe,{children:i(Yk,{dataSource:e})})}),p(s.Tabs,{defaultValue:"structure",styles:Zk,children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"structure",icon:i($.IconColumns,{size:14}),children:"Structure"}),i(s.Tabs.Tab,{value:"data",icon:i($.IconDatabase,{size:14}),children:"Data"})]}),i(s.Tabs.Panel,{value:"structure",children:i(jk,{dataSource:e})}),i(s.Tabs.Panel,{value:"data",sx:{width:"100%",height:"calc(100% - 36px)",overflow:"hidden"},children:i(Jk,{dataSource:e})})]})]}))),eT={modal:{paddingLeft:"0px !important",paddingRight:"0px !important"},header:{marginBottom:0,padding:"20px 20px 10px",borderBottom:"1px solid #efefef",gap:"20px"},title:{flexGrow:1},body:{padding:"0 0 0 20px"}},ou=k.observer(({dataSource:e,triggerButtonProps:t={}})=>{const[n,r]=y.useState(!1);return e.type==="http"?null:p(B,{children:[i(s.Modal,{opened:n,onClose:()=>r(!1),title:p(s.Group,{position:"apart",sx:{flexGrow:1},children:[i(s.Text,{fw:500,children:"Explorer Data Source"}),p(s.Group,{spacing:7,children:[i(s.Badge,{variant:"gradient",gradient:{from:"indigo",to:"cyan"},children:e.key}),i(s.Badge,{variant:"gradient",gradient:{from:"orange",to:"red"},children:e.type})]})]}),zIndex:320,size:"96vw",styles:eT,children:i(s.Box,{sx:{height:"calc(100vh - 220px)"},children:i(Hk,{dataSource:e})})}),i(s.Button,{variant:"subtle",onClick:()=>r(!0),px:16,styles:{inner:{justifyContent:"flex-start"}},...t,children:"See Table Structure"})]})}),tT=y.forwardRef(({label:e,type:t,...n},r)=>p(s.Group,{position:"apart",ref:r,...n,children:[i(s.Text,{children:e}),i(s.Text,{children:t})]})),nT=k.observer(({value:e,onChange:t})=>{const n=pe(),{data:r=[],loading:a}=K.useRequest(mr,{refreshDeps:[]},[]),o=y.useMemo(()=>r.map(d=>({label:d.key,value:d.key,type:d.type})),[r]),l=y.useMemo(()=>o.reduce((d,f)=>(d[f.value]=f.type,d),{}),[o]),u=d=>{d!==null&&t({key:d,type:l[d]})},c=y.useMemo(()=>n.datasources.find(e),[n,e]);return i(s.Select,{data:o,label:p(s.Group,{position:"apart",children:[i(s.Box,{children:"Data Source"}),c&&i(ou,{dataSource:c,triggerButtonProps:{compact:!0,size:"xs",px:10}})]}),itemComponent:tT,rightSection:c?i(s.Text,{size:"xs",color:"dimmed",children:c.type}):void 0,rightSectionWidth:85,maxDropdownHeight:280,styles:{root:{flex:1},label:{display:"block"},rightSection:{pointerEvents:"none",justifyContent:"flex-end",paddingRight:"10px",".mantine-Text-root":{userSelect:"none"}}},disabled:a,value:e.key,onChange:u})}),lu=y.forwardRef((e,t)=>{const{label:n,description:r,...a}=e;return i("div",{ref:t,...a,children:p(s.Group,{position:"apart",noWrap:!0,children:[i(s.Text,{children:n}),i(s.Text,{size:"xs",color:"dimmed",children:r})]})})}),rT=k.observer(({queryModel:e})=>{const[t,n]=y.useState(e.name);return y.useEffect(()=>{n(e.name)},[e.name]),i(s.Center,{ml:20,mt:20,sx:{maxWidth:"600px"},children:p(s.Stack,{spacing:10,sx:{width:"100%"},children:[i(s.Divider,{mb:-10,variant:"dashed",label:"Basics",labelPosition:"center"}),i(s.TextInput,{placeholder:"A unique name",label:"Name",required:!0,sx:{flex:1},value:t,onChange:r=>{n(r.currentTarget.value)},rightSection:i(s.ActionIcon,{variant:"filled",color:"blue",size:"sm",onClick:()=>e.setName(t),disabled:t===e.name,children:i($.IconDeviceFloppy,{size:16})}),onBlur:()=>{e.setName(t)}}),i(nT,{value:{type:e.type,key:e.key},onChange:({type:r,key:a})=>{e.setKey(a),e.setType(r)}}),i(s.Divider,{mt:10,mb:-10,variant:"dashed",label:"Conditions",labelPosition:"center"}),i(s.MultiSelect,{label:"Run query when these are truthy",placeholder:"Always run this query on load",data:e.conditionOptions,value:[...e.run_by],onChange:e.setRunBy,itemComponent:lu,maxDropdownHeight:500}),e.typedAsHTTP&&i(s.MultiSelect,{label:"Re-run query when these changed",placeholder:"Leave it empty to never re-run this query",data:e.conditionOptions,value:[...e.react_to],onChange:e.setReactTo,itemComponent:lu,maxDropdownHeight:500}),i(s.Divider,{mt:20,mb:10,variant:"dashed"}),i(Vk,{queryModel:e})]})})});function iT({content:e}){return p(s.HoverCard,{width:"60vw",shadow:"md",children:[i(s.HoverCard.Target,{children:i(s.ActionIcon,{size:16,color:"blue",children:i($.IconEye,{})})}),i(s.HoverCard.Dropdown,{children:i(kt.Prism,{language:"sql",noCopy:!0,withLineNumbers:!0,children:e})})]})}const aT=k.observer(()=>{const t=[...pe().globalSQLSnippets.list];return t.length===0?null:p(s.Table,{horizontalSpacing:"xs",verticalSpacing:"xs",fontSize:"sm",highlightOnHover:!0,children:[i("thead",{children:p("tr",{children:[i("th",{children:"Key"}),i("th",{children:"Value"})]})}),i("tbody",{children:t.map(n=>{const{id:r,content:a}=n;return p("tr",{children:[i("td",{children:r}),i("td",{width:200,children:i(iT,{content:a})})]},r)})})]})}),sT=`
519
+ `,ek=()=>{const[e,t]=b.useState(!1);return p(B,{children:[i(s.Button,{variant:"subtle",compact:!0,onClick:()=>t(n=>!n),children:e?"Close":"Click to see expected data structure"}),i(s.Collapse,{in:e,children:i(kt.Prism,{language:"typescript",noCopy:!0,colorScheme:"dark",children:H_})})]})},tk=k.observer(function({config:t}){return p(B,{children:[i(s.Checkbox,{checked:t.required,onChange:n=>t.setRequired(n.currentTarget.checked),label:"Required"}),i(s.TextInput,{label:"Min-width",value:t.min_width,onChange:n=>t.setMinWidth(n.currentTarget.value),placeholder:"200px"}),i(s.Divider,{label:"Fetch options from database",labelPosition:"center"}),i(s.Checkbox,{checked:t.treeCheckStrictly,onChange:n=>t.setTreeCheckStrictly(n.currentTarget.checked),label:"Parent and children nodes are not associated"}),i(s.NumberInput,{value:t.default_selection_count,onChange:t.setDefaultSelectionCount,label:"Select first N options by default"}),i(Bi,{value:t.options_query_id,onChange:t.setOptionsQueryID}),i(ek,{})]})}),nk=k.observer(function({filter:t}){return p(s.Box,{sx:{maxWidth:"480px"},children:[i(s.Text,{pt:"0",pb:"md",color:"gray",children:"Config"}),i(kt.Prism,{mt:22,language:"json",colorScheme:"dark",noCopy:!0,children:JSON.stringify(t,null,4)})]})}),rk={select:J_,"multi-select":X_,"tree-select":tk,"text-input":Z_,checkbox:Y_,"date-range":U_},ik=[{label:"Select",value:"select"},{label:"Multi Select",value:"multi-select"},{label:"Tree Select",value:"tree-select"},{label:"Text Input",value:"text-input"},{label:"Checkbox",value:"checkbox"},{label:"Date Range",value:"date-range"}],ak=k.observer(function({filter:t}){const n=le(),r=b.useMemo(()=>rk[t.type],[t.type]);return p(s.Group,{grow:!0,spacing:20,align:"top",children:[p(s.Box,{sx:{maxWidth:"600px"},children:[i(s.Text,{pb:"md",color:"gray",children:"Edit"}),p(s.Stack,{children:[p(s.Group,{noWrap:!0,children:[i(s.NumberInput,{label:"Placement Order",required:!0,value:t.order,onChange:t.setOrder,hideControls:!0,sx:{flexGrow:"1 !important"}}),t.auto_submit_supported&&i(s.Checkbox,{label:"Submit automatically",checked:t.auto_submit,onChange:a=>t.setAutoSubmit(a.currentTarget.checked),mt:22})]}),i(s.MultiSelect,{label:"Visible in...",data:n.views.options,value:[...t.visibleInViewsIDs],onChange:t.setVisibleInViewsIDs}),i(s.TextInput,{label:"Key",placeholder:"A unique key to refer",required:!0,value:t.key,onChange:a=>{t.setKey(a.currentTarget.value)}}),i(s.TextInput,{label:"Label",placeholder:"Label for this field",required:!0,value:t.label,onChange:a=>{t.setLabel(a.currentTarget.value)}}),i(s.Select,{label:"Widget",data:ik,required:!0,value:t.type,onChange:t.setType}),i(r,{config:t.config})]})]}),i(nk,{filter:t})]})}),sk=k.observer(({id:e})=>{const t=We.useModals(),n=ce(),r=le();if(e==="")return null;const a=r.filters.findByID(e);if(!a)return p(s.Text,{size:14,children:["Filter by ID[",e,"] is not found"]});const o=()=>{n.editor.setPath(["_FILTERS_",""])},l=()=>{t.openConfirmModal({title:"Delete this filter?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>{r.filters.removeByID(e),o()},confirmProps:{color:"red"},zIndex:320})};return p(s.Stack,{sx:{maxWidth:"1100px",height:"100vh"},spacing:"sm",pb:30,children:[i(s.Group,{position:"right",pt:10,children:i(s.Button,{size:"xs",color:"red",leftIcon:i(T.Trash,{size:16}),onClick:l,children:"Delete this filter"})}),i(s.Box,{sx:{flexGrow:1,maxHeight:"calc(100% - 52px)",overflow:"auto"},children:i(ak,{filter:a})})]})}),ok=k.observer(()=>{const e=le(),[t,n]=b.useState(()=>JSON.stringify(e.mock_context.current,null,4)),r=()=>{try{e.mock_context.replace(JSON.parse(t))}catch(o){vn.showNotification({title:"Failed",message:o.message,color:"red"})}},a=b.useMemo(()=>{try{return JSON.stringify(JSON.parse(t))!==JSON.stringify(e.mock_context.current)}catch{return!1}},[t,e.mock_context.current]);return p(s.Stack,{sx:{border:"1px solid #eee",borderLeft:"none",borderRight:"none",flexGrow:1,maxWidth:"unset"},children:[i(s.Group,{position:"left",pl:"md",py:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef",flexGrow:0},children:i(s.Text,{weight:500,children:"Mock Context"})}),p(s.Group,{grow:!0,px:"md",pb:"md",pt:0,sx:{flexGrow:1,position:"relative",alignItems:"flex-start"},children:[p(s.Stack,{spacing:10,sx:{maxWidth:"unset !important"},children:[i(s.Text,{children:"A valid json string is required"}),i(s.JsonInput,{validationError:"Invalid json",formatOnBlur:!0,autosize:!0,minRows:30,value:t,onChange:n,sx:{flexGrow:1}})]}),i(s.ActionIcon,{mr:5,variant:"filled",color:"blue",sx:{position:"absolute",right:12,top:0},disabled:!a,onClick:r,children:i(T.DeviceFloppy,{size:20})})]})]})}),lk=k.observer(()=>{const{panel:e}=nt();return i(oi,{label:"Description",value:e.description,onChange:e.setDescription,styles:{root:{flexGrow:1}}})}),uk=k.observer(()=>{const{panel:e}=nt(),{style:t}=e;return p(B,{children:[i(s.Divider,{mb:-10,label:"Style",labelPosition:"center",variant:"dashed"}),p(s.Stack,{spacing:20,children:[p(s.Group,{grow:!0,align:"top",children:[i(s.NumberInput,{label:"Width",min:1,max:36,step:1,precision:0,rightSection:i(s.Text,{size:12,children:"of 36 columns"}),styles:{rightSection:{width:"110px"}},value:e.layout.w,onChange:n=>{n&&e.layout.setWidth(n)}}),i(s.NumberInput,{label:"Height",rightSection:i(s.Text,{size:12,children:"px"}),styles:{rightSection:{width:"40px"}},value:e.layout.h,onChange:n=>{n&&e.layout.setHeight(n)}})]}),i(s.Switch,{label:"Border",checked:t.border.enabled,onChange:n=>t.border.setEnabled(n.currentTarget.checked)})]})]})}),ck=k.observer(()=>{const{panel:e}=nt(),{title:t,setTitle:n}=e,[r,a]=Ie.useInputState(t),o=t!==r,l=b.useCallback(()=>{o&&n(r)},[o,r]);return b.useEffect(()=>{a(t)},[t]),i(s.TextInput,{value:r,onChange:a,label:p(s.Group,{children:[i(s.Text,{children:"Panel Title"}),i(s.ActionIcon,{variant:"subtle",color:"blue",disabled:!o,onClick:l,children:i(T.DeviceFloppy,{size:20})})]}),styles:{label:{display:"block",paddingBottom:"4px"}}})});function dk(){return p(s.Stack,{sx:{height:"100%"},children:[i(uk,{}),i(s.Divider,{label:"Info",labelPosition:"center",variant:"dashed"}),i(ck,{}),i(lk,{})]})}const pk={width:"fit-content",minWidth:"100%",tableLayout:"fixed",tr:{width:"fit-content"},th:{position:"relative"},"th, td":{wordBreak:"break-word"},".resizer":{position:"absolute",right:0,top:"50%",transform:"translateY(-50%)",cursor:"col-resize",userSelect:"none",touchAction:"none"},".resizer.isResizing":{color:"#228be6",opacity:"1"},"@media (hover: hover)":{".resizer":{opacity:"0"},"*:hover > .resizer":{color:"#228be6",opacity:"1"}}};function nu({data:e}){const t=b.useMemo(()=>{if(!Array.isArray(e)||e.length===0)return[];const r=tt.createColumnHelper();return Object.keys(e[0]).map(a=>r.accessor(a,{cell:o=>o.getValue()}))},[e]),n=tt.useReactTable({data:e,columns:t,columnResizeMode:"onChange",getCoreRowModel:tt.getCoreRowModel()});return e.length===0?i(s.Box,{sx:{height:"5em"}}):i(Fe,{children:p(s.Table,{sx:pk,children:[i("thead",{children:n.getHeaderGroups().map(r=>i("tr",{children:r.headers.map(a=>p("th",{style:{width:a.getSize()},children:[a.isPlaceholder?null:tt.flexRender(a.column.columnDef.header,a.getContext()),i(s.ActionIcon,{onMouseDown:a.getResizeHandler(),onTouchStart:a.getResizeHandler(),className:`resizer ${a.column.getIsResizing()?"isResizing":""}`,children:i(T.ArrowBarToRight,{})})]},a.id))},r.id))}),i("tbody",{children:n.getRowModel().rows.map(r=>i("tr",{children:r.getVisibleCells().map(a=>i("td",{children:i(Fe,{children:tt.flexRender(a.column.columnDef.cell,a.getContext())})},a.id))},r.id))})]})})}const hk=({queryID:e})=>{const t=we(),{state:n,error:r}=t.getDataStuffByID(e),a=b.useMemo(()=>t.queries.findByID(e),[t,e]);return n==="loading"?null:r?i(s.Text,{color:"red",size:"md",align:"center",sx:{fontFamily:"monospace"},children:r}):a!=null&&a.stateMessage?i(s.Text,{color:"gray",align:"center",children:a.stateMessage}):null},Vi=k.observer(function({id:t,moreActions:n=null}){const r=we(),{data:a,state:o}=r.getDataStuffByID(t),l=o==="loading",u=()=>{r.queries.refetchDataByQueryID(t)},c=()=>{r.queries.downloadDataByQueryID(t)},d=b.useMemo(()=>Array.isArray(a)?a.slice(0,10):[],[a]),f=!Array.isArray(a)||a.length===0;return p(s.Stack,{sx:{border:"1px solid #eee"},children:[p(s.Group,{position:"apart",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[p(s.Group,{position:"left",children:[i(s.Text,{weight:500,children:"Preview Data"}),a.length>10&&p(s.Text,{size:"sm",color:"gray",children:["Showing 10 rows of ",a.length]})]}),p(s.Group,{pr:15,children:[n,i(s.ActionIcon,{variant:"subtle",color:"blue",disabled:l,onClick:u,children:i(T.Refresh,{size:16})}),i(s.ActionIcon,{variant:"subtle",color:"blue",disabled:l||f,onClick:c,children:i(T.Download,{size:16})})]})]}),p(s.Box,{sx:{position:"relative",overflow:"auto"},children:[i(s.LoadingOverlay,{visible:l}),i(hk,{queryID:t}),i(nu,{data:d})]})]})}),fk=k.observer(function(){const t=ce(),n=le(),{panel:r}=nt(),[a,o]=b.useState(!1),l=u=>{t.editor.setPath(["_QUERIES_",u])};return p(B,{children:[i(s.Drawer,{opened:a,onClose:()=>o(!1),title:"Choose queries",padding:"xl",size:500,zIndex:320,children:i(s.Checkbox.Group,{value:[...r.queryIDs],onChange:r.setQueryIDs,children:i(s.Stack,{spacing:"lg",children:n.queries.options.map(u=>i(s.Checkbox,{label:u.label,value:u.value},u.value))})})}),p(s.Stack,{spacing:6,children:[i(s.Group,{position:"right",children:i(s.Button,{variant:"light",size:"sm",leftIcon:i($.IconLine,{size:16}),onClick:()=>o(!0),children:"Click me to choose queries for this panel"})}),r.queryIDs.length===1&&i(Vi,{id:r.queryIDs[0],moreActions:i(s.Tooltip,{label:"Open this query",children:i(s.ActionIcon,{variant:"subtle",color:"blue",onClick:()=>l(r.queryIDs[0]),children:i($.IconArrowCurveRight,{size:16})})})}),r.queryIDs.length>1&&p(s.Tabs,{defaultValue:r.queryIDs[0],children:[i(s.Tabs.List,{children:r.queries.map(u=>i(s.Tabs.Tab,{value:u.id,children:u.name},u.id))}),r.queries.map(u=>i(s.Tabs.Panel,{value:u.id,children:i(Vi,{id:u.id,moreActions:i(s.Tooltip,{label:"Open this query",children:i(s.ActionIcon,{variant:"subtle",color:"blue",onClick:()=>l(u.id),children:i($.IconArrowCurveRight,{size:16})})})})},u.id))]})]})]})}),gk=k.observer(()=>{const{panel:e}=bt();return i(Fe,{children:i(s.Box,{sx:{height:"100%",flexGrow:0,flexShrink:0,width:"600px"},children:p(s.Stack,{mt:24,spacing:5,sx:{width:"600px",height:"450px",background:"transparent",borderRadius:"5px",border:"1px solid #e9ecef",borderWidth:e.style.border.enabled?"1px":"0px"},children:[p(s.Group,{position:"apart",noWrap:!0,sx:{flexGrow:0,flexShrink:0},children:[i(s.Group,{children:i(Ii,{})}),i(s.Group,{grow:!0,position:"center",children:i(s.Text,{lineClamp:1,weight:"bold",children:e.title})}),i(s.Group,{position:"right",spacing:0,sx:{height:"28px"}})]}),i(s.Group,{px:5,pb:5,sx:{flexGrow:1},children:i(Mi,{panel:e,height:"410px"})})]})})})}),Ni={name:"new_var",size:"1rem",weight:"initial",color:{type:"static",staticColor:"Red"},data_field:"",aggregation:{type:"sum",config:{}},formatter:{output:"number",mantissa:0,trimMantissa:!1,average:!1}};class mk{constructor(t){N(this,"panel");N(this,"selected");this.panel=t,te.makeAutoObservable(this,{},{deep:!1,autoBind:!0})}get variables(){return this.panel.variables}addNew(){const t=this.panel.variables.filter(n=>n.name.startsWith(Ni.name)).length;this.panel.addVariable(x.cloneDeep({...Ni,name:`${Ni.name}${t||""}`})),this.selected=x.last(this.panel.variables)}select(t){this.selected=t}remove(t){this.selected===t&&(this.selected=void 0);const n=this.panel.variables.indexOf(t);if(this.panel.removeVariable(t),!this.selected&&!x.isEmpty(this.panel.variables)){const r=Math.min(this.panel.variables.length-1,n);this.selected=this.panel.variables[r]}}}function yk(){const{panel:e}=nt();return K.useCreation(()=>new mk(e),[e])}const ru=s.createStyles(e=>({root:{height:"100%",overflow:"hidden",".var-list-container":{"& > *":{height:"100%"},width:250,height:"100%"},".var-list-actions":{height:"fit-content",flexShrink:0,width:"100%"},".var-list":{flex:"1 1 auto",overflow:"auto",minHeight:0,"& > *":{flex:"0 0 auto"}}},config:{height:"100%",overflow:"auto",paddingRight:10}})),bk=b.forwardRef(function({value:t,onChange:n,data:r,withStyle:a=!0},o){const l=(u,c)=>{const d=x.cloneDeep(t);x.set(d,u,c),n(d)};return p(s.Box,{px:"sm",py:"md",ref:o,children:[p(s.Group,{grow:!0,noWrap:!0,children:[i(s.TextInput,{label:"Name",required:!0,value:t.name,onChange:u=>l("name",u.currentTarget.value)}),i(W,{label:"Data Field",required:!0,value:t.data_field,onChange:u=>l("data_field",u)})]}),i(Gn,{label:"Aggregation",value:t.aggregation,onChange:u=>l("aggregation",u)}),t.aggregation.type!=="custom"&&p(B,{children:[i(s.Divider,{my:"xs",label:"Format",labelPosition:"center"}),i(je,{value:t.formatter,onChange:u=>l("formatter",u)})]}),a&&i(Ys,{value:t,onChange:n})]})}),vk=e=>{const{uiModel:t}=e;return i(s.Stack,{className:"var-list",children:t.variables.map(n=>i(s.Button,{variant:t.selected===n?"filled":"subtle",color:"gray",onClick:()=>t.select(n),children:n.name},n.name))})},xk=k.observer(vk),wk=({variable:e,data:t})=>i(s.Group,{style:{minHeight:0,height:"calc(100% - 68px)"},children:i(s.Paper,{withBorder:!0,p:"md",children:Qs(e,t)})}),Ck=k.observer(wk),Sk=e=>{const t=K.useCreation(()=>xS(e.variable),[e.variable]),{classes:n}=ru(),{data:r}=nt();return p(s.Group,{style:{height:"100%"},align:"start",children:[p(s.Stack,{"data-testid":"variable-editor",align:"stretch",className:n.config,children:[p(s.Group,{position:"right",children:[i(s.ActionIcon,{variant:"filled",disabled:!t.changed,color:"primary",onClick:t.commit,children:i($.IconDeviceFloppy,{size:18})}),i(s.ActionIcon,{color:"red",onClick:()=>e.uiModel.remove(e.variable),children:i($.IconTrash,{size:18})})]}),i(bk,{value:y.getSnapshot(t.copy),onChange:t.update,data:r})]}),i(Ck,{variable:y.getSnapshot(t.copy),data:r})]})},_k=k.observer(Sk),kk=()=>{const e=yk(),{classes:t}=ru();return p(s.Group,{className:t.root,noWrap:!0,align:"start",children:[i(s.Paper,{withBorder:!0,p:"md",className:"var-list-container",children:p(s.Stack,{justify:"space-between",children:[i(s.Box,{className:"var-list-actions",children:i(s.Button,{variant:"light",size:"sm",onClick:e.addNew,fullWidth:!0,children:"Add Variable"})}),i(xk,{uiModel:e})]})}),e.selected?i(B,{children:i(_k,{uiModel:e,variable:e.selected})}):i("span",{children:"Select or create a new variable on right side"})]})},Tk=k.observer(kk);function Dk(){const{vizManager:e}=b.useContext(ut);return b.useMemo(()=>{const t=e.availableVizList.map(n=>({value:n.name,label:n.displayName??n.name,group:n.displayGroup??""}));return x.orderBy(t,[n=>n.group,n=>n.label],["asc","asc"])},[e])}const Ik=k.observer(({value:e,submit:t})=>{const[n,r]=Ie.useInputState(e);b.useEffect(()=>{r(e)},[e]);const a=Dk(),o=e!==n;return i(s.Select,{label:"Visualization",value:n,searchable:!0,onChange:r,data:a,rightSection:i(s.ActionIcon,{disabled:!o,onClick:()=>t(n),children:i(T.DeviceFloppy,{size:20})}),maxDropdownHeight:600})}),iu=[];function Mk(e,t){try{return e.resolveComponent(t).createConfig()}catch{return null}}function Ak(){const{data:e,panel:{variables:t,viz:n,title:r,queryIDs:a,description:o,setDescription:l,setTitle:u,addQueryID:c,removeQueryID:d,id:f}}=nt(),{vizManager:h}=b.useContext(ut),g={title:r,description:o,viz:n,queryIDs:a,id:f},m={setDescription:l,addQueryID:c,removeQueryID:d,setTitle:u},C=_l(g);try{return h.resolveComponent(g.viz.type),i(er,{configure:C,children:i(TS,{variables:t,setVizConf:n.setConf,panel:g,panelInfoEditor:m,vizManager:h,data:e})})}catch(w){return console.info(x.get(w,"message")),null}}const zk=k.observer(()=>{const{data:e,panel:{viz:t}}=nt(),{vizManager:n}=b.useContext(ut),r=b.useCallback(d=>{if(d===t.type)return;const f=Mk(n,d);t.setType(d),t.setConf(f||{})},[t.type]),a=d=>{try{t.setConf(JSON.parse(d))}catch(f){console.error(f)}},o=b.useMemo(()=>{var d;return(d=iu.find(f=>f.value===t.type))==null?void 0:d.Panel},[t.type,iu]),l=Ak(),u=o?b.createElement(o,{data:e,conf:t.conf,setConf:t.setConf}):null,c=l||u;return p(s.Stack,{align:"stretch",sx:{height:"100%",overflow:"hidden"},children:[i(Ik,{submit:r,value:t.type}),p(Fe,{children:[i(s.Stack,{pb:10,sx:{flexGrow:1,maxHeight:"100%",overflow:"auto"},children:c}),!c&&i(s.JsonInput,{minRows:20,label:"Config",value:JSON.stringify(t.conf,null,2),onChange:a})]})]})}),Ek=k.observer(({panel:e,sourceViewID:t})=>{const n=le(),[r,a]=b.useState(t);b.useEffect(()=>{a(t)},[t]);const[o,{open:l,close:u}]=Ie.useDisclosure(!1),c=()=>{e.moveToView(t,r),u()};return p(B,{children:[i(s.Button,{size:"xs",variant:"subtle",color:"blue",onClick:l,leftIcon:i($.IconBoxMultiple,{size:14}),children:"Move into Another View"}),i(s.Modal,{opened:o,onClose:u,title:"Move panel into another view",zIndex:320,children:p(s.Stack,{sx:{maxHeight:"calc(100vh - 185px)",overflow:"hidden"},children:[i(s.Radio.Group,{value:r,onChange:a,pb:10,sx:{flexGrow:1,maxHeight:"calc(100vh - 185px - 30px)",overflow:"auto"},children:i(s.Stack,{spacing:"xs",children:n.views.options.map(d=>i(s.Radio,{value:d.value,label:d.label},d.value))})}),p(s.Group,{noWrap:!0,position:"apart",sx:{flexGrow:0,flexShrink:0},children:[i(s.Button,{size:"xs",color:"red",leftIcon:i($.IconX,{size:14}),onClick:u,children:"Cancel"}),i(s.Button,{size:"xs",color:"blue",leftIcon:i($.IconDeviceFloppy,{size:14}),onClick:c,disabled:r===t,children:"Confirm"})]})]})})]})}),$k={root:{flexGrow:1,width:"100%",overflow:"hidden"},panel:{width:"100%",height:"calc(100% - 44px)",padding:10,overflow:"scroll"}},au=({children:e})=>p(s.Group,{noWrap:!0,grow:!0,position:"left",spacing:20,sx:{width:"100%",height:"100%"},children:[i(s.Box,{sx:{maxWidth:"calc(100% - 610px - 10px)",height:"100%",overflow:"auto"},children:e}),i(gk,{})]});function Lk(e){return!["richText","button"].includes(e)}const Ok=k.observer(({panel:e})=>{const t=We.useModals(),n=ce(),r=le(),[a,o]=b.useState("Data"),l=e.queries,c=Lk(e.viz.type)&&e.dataLoading,d=c||e.queryErrors.length>0||e.queryStateMessages!==""||l.length===0,f=n.editor.path[1];b.useEffect(()=>{o(m=>d&&m==="Visualization"?"Data":m)},[e.id,d]);const h=()=>{n.editor.setPath(["_VIEWS_",f])},g=()=>t.openConfirmModal({title:"Delete this panel?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>{r.removePanelByID(e.id,f),h()},confirmProps:{color:"red"},zIndex:320});return p(Sr,{value:{panel:e,data:e.data,loading:c,errors:e.queryErrors,downloadPanelScreenshot:()=>{}},children:[p(s.Group,{px:16,position:"apart",sx:{borderBottom:"1px solid #eee"},children:[p(s.Text,{pt:9,pb:8,children:[e.title?e.title:e.viz.type," "]}),p(s.Group,{position:"right",noWrap:!0,children:[i(Ek,{panel:e,sourceViewID:f}),i(s.Button,{size:"xs",variant:"subtle",color:"red",onClick:g,leftIcon:i($.IconTrash,{size:14}),children:"Delete This Panel"})]})]}),p(s.Tabs,{value:a,onTabChange:o,keepMounted:!1,styles:$k,children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"Data",disabled:c,children:"Data"}),i(s.Tabs.Tab,{value:"Panel",children:"Panel"}),i(s.Tabs.Tab,{value:"Variables",disabled:d,children:i(s.Tooltip,{label:"Requires data",disabled:!d,withinPortal:!0,zIndex:310,children:i(s.Text,{children:"Variables"})})}),i(s.Tabs.Tab,{value:"Visualization",disabled:d,children:i(s.Tooltip,{label:"Requires data",disabled:!d,withinPortal:!0,zIndex:310,children:i(s.Text,{children:"Visualization"})})}),i(s.Tabs.Tab,{value:"Interactions",children:"Interactions"})]}),p(s.Tabs.Panel,{value:"Data",children:[i(s.LoadingOverlay,{visible:c,exitTransitionDuration:0}),i(fk,{})]}),i(s.Tabs.Panel,{value:"Panel",children:i(au,{children:i(dk,{})})}),i(s.Tabs.Panel,{value:"Variables",children:i(Tk,{})}),i(s.Tabs.Panel,{value:"Visualization",children:i(Fe,{children:i(au,{children:i(zk,{})})})}),i(s.Tabs.Panel,{value:"Interactions",children:i(Fe,{children:i(ud,{})})})]})]})}),Pk=k.observer(({viewID:e,panelID:t})=>{const n=le();if(!n.views.findByID(e))return p(s.Text,{size:14,children:["View by ID[",e,"] is not found"]});const a=n.panels.findByID(t);return a?i(Ok,{panel:a}):p(s.Text,{size:14,children:["Panel by ID[",t,"] is not found"]})}),Bk=e=>{const{queryModel:t}=e,n=ce(),r=le(),o=r.findQueryUsage(t.id).length>0,l=We.useModals(),u=()=>{l.openConfirmModal({title:"Delete this query?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>{r.queries.removeQuery(t.id),n.editor.setPath(["_QUERIES_",""])},confirmProps:{color:"red"},zIndex:320})};return o?i(s.Tooltip,{label:"Can't delete this query for it's being used, check out Usage tab for details",withArrow:!0,events:{hover:!0,focus:!1,touch:!1},withinPortal:!0,children:i(s.Button,{color:"gray",size:"xs",leftIcon:i($.IconTrash,{size:16}),sx:{alignSelf:"flex-end"},children:"Delete this Query"})}):i(s.Button,{color:"red",size:"xs",onClick:u,leftIcon:i($.IconTrash,{size:16}),sx:{alignSelf:"flex-end"},children:"Delete this Query"})},Vk=k.observer(Bk),su=({width:e="calc(100% - 32px)",lastWidth:t="50%",height:n,count:r,spacing:a=16,pl:o=0})=>p(s.Stack,{spacing:a,mt:6,pl:o,children:[Array.from(new Array(r-1),(l,u)=>i(s.Skeleton,{width:e,height:n,radius:"xs"},u)),i(s.Skeleton,{width:t,height:n,radius:"xs"})]}),hn=({value:e})=>e===null||e===""?null:i(s.Tooltip,{label:e,disabled:!e,multiline:!0,children:i(s.ActionIcon,{children:i($.IconInfoCircle,{size:14})})}),Nk=({column:e})=>{const{column_key:t,column_key_text:n}=e;return t?i(s.Tooltip,{label:n,disabled:!n,children:i(s.Badge,{children:t})}):null},qk=k.observer(({dataSource:e})=>{const{columns:t}=e;return t.loading?i(su,{height:"24px",width:"100%",lastWidth:"100%",count:20,pl:6}):t.empty?null:p(s.Table,{highlightOnHover:!0,fontSize:14,sx:{width:"auto",minWidth:"1000px",alignSelf:"flex-start",flexGrow:0,tableLayout:"fixed",tbody:{fontFamily:"monospace"}},children:[p("colgroup",{children:[i("col",{style:{width:50}}),i("col",{style:{minWidth:300}}),i("col",{style:{width:30}}),i("col",{style:{width:70}}),i("col",{style:{minWidth:300}}),i("col",{style:{minWidth:80,width:80}}),i("col",{style:{minWidth:120,width:120}})]}),i("thead",{children:p("tr",{children:[i("th",{children:"#"}),i("th",{children:"Column Name"}),i("th",{}),i("th",{}),i("th",{children:"Type"}),i("th",{children:"Nullable"}),i("th",{children:"Default Value"})]})}),i("tbody",{children:t.data.map(n=>p("tr",{children:[i("td",{children:n.ordinal_position}),i("td",{children:n.column_name}),i("td",{children:i(hn,{value:n.column_comment})}),i("td",{children:i(Nk,{column:n})}),i("td",{children:n.column_type}),i("td",{children:n.is_nullable}),i("td",{children:i(hn,{value:n.column_default})})]},n.column_name))})]})}),Fk=k.observer(({dataSource:e})=>{const{indexes:t}=e,n=t.data;return p(s.Table,{highlightOnHover:!0,fontSize:14,sx:{width:"auto",minWidth:"950px",alignSelf:"flex-start",flexGrow:0,tableLayout:"fixed",tbody:{fontFamily:"monospace"}},children:[p("colgroup",{children:[i("col",{style:{width:100}}),i("col",{style:{minWidth:300}}),i("col",{style:{width:150}}),i("col",{style:{width:150}}),i("col",{style:{width:250}})]}),i("thead",{children:p("tr",{children:[i("th",{children:"Index Length"}),i("th",{children:"Index Name"}),i("th",{children:"Index Algorithm"}),i("th",{children:"Unique"}),i("th",{children:"Column Name"})]})}),i("tbody",{children:n.map(r=>p("tr",{children:[i("td",{children:r.index_length}),i("td",{children:r.index_name}),i("td",{children:r.index_algorithm}),i("td",{children:r.is_unique?"YES":"NO"}),i("td",{children:r.column_name})]},r.index_name))})]})}),Gk=k.observer(({dataSource:e})=>{const{indexes:t}=e,n=t.data;return p(s.Table,{highlightOnHover:!0,fontSize:14,sx:{width:"auto",minWidth:"850px",alignSelf:"flex-start",flexGrow:0,tableLayout:"fixed",tbody:{fontFamily:"monospace"}},children:[p("colgroup",{children:[i("col",{style:{minWidth:300}}),i("col",{style:{width:150}}),i("col",{style:{width:100}}),i("col",{style:{width:100}}),i("col",{style:{width:100}}),i("col",{style:{width:100}})]}),i("thead",{children:p("tr",{children:[i("th",{children:"Index Name"}),i("th",{children:"Index Algorithm"}),i("th",{children:"Unique"}),i("th",{children:"Definition"}),i("th",{children:"Condition"}),i("th",{children:"Comment"})]})}),i("tbody",{children:n.map(r=>p("tr",{children:[i("td",{children:r.index_name}),i("td",{children:r.index_algorithm}),i("td",{children:r.is_unique?"YES":"NO"}),i("td",{children:i(hn,{value:r.index_definition})}),i("td",{children:i(hn,{value:r.condition})}),i("td",{children:i(hn,{value:r.comment})})]},r.index_name))})]})}),Wk=k.observer(({dataSource:e})=>{const{indexes:t}=e;return t.loading||t.empty?null:e.type===Se.MySQL?i(Fk,{dataSource:e}):e.type===Se.Postgresql?i(Gk,{dataSource:e}):null}),jk=k.observer(({dataSource:e})=>p(s.Stack,{spacing:40,pt:10,sx:{flexGrow:1,overflow:"auto",position:"relative"},children:[i(Fe,{children:i(qk,{dataSource:e})}),i(Fe,{children:i(Wk,{dataSource:e})})]}));function Rk({table_type:e}){return e==="VIEW"?i($.IconEye,{size:14}):e==="BASE TABLE"?i($.IconTable,{size:14}):null}const Yk=k.observer(({dataSource:e})=>{const{tables:t}=e;return t.loading?i(su,{height:"24px",lastWidth:"50%",count:15}):i(s.Box,{h:"100%",sx:{overflow:"auto",".mantine-NavLink-label":{fontFamily:"monospace"}},children:Object.entries(t.data).map(([n,r])=>i(s.NavLink,{label:n,icon:i($.IconDatabase,{size:14}),defaultOpened:e.table_schema===n,pl:0,childrenOffset:14,children:r.map(a=>i(s.NavLink,{label:a.table_name,icon:i(Rk,{table_type:a.table_type}),onClick:()=>{e.setKeywords(n,a.table_name)},active:e.table_name===a.table_name},a.table_name))},n))})}),Qk=({visible:e})=>i(s.Box,{py:10,sx:{width:"100%",height:"100%",overflow:"hidden",position:"relative"},children:i(s.LoadingOverlay,{visible:e})}),Uk=[{label:"10",value:"10"},{label:"20",value:"20"},{label:"50",value:"50"},{label:"100",value:"100"}],Kk={icon:{width:"50px",textAlign:"center"},input:{"&[data-with-icon]":{paddingLeft:"50px"}}},Xk=k.observer(({dataSource:e})=>{const{tableData:t}=e;return p(s.Group,{pt:10,px:10,position:"apart",children:[p(s.Group,{position:"left",children:[t.maxPage>1&&i(s.Pagination,{size:"sm",value:t.page,onChange:t.setPage,total:t.maxPage,withEdges:t.maxPage>7,styles:{control:{height:"30px"}}}),i(s.Select,{icon:i(s.Text,{ta:"center",color:"dimmed",size:14,children:"Limit"}),size:"xs",styles:Kk,data:Uk,value:String(t.limit),onChange:n=>t.setLimit(Number(n))})]}),i(s.Group,{position:"right",children:p(s.Text,{color:"dimmed",my:0,size:14,children:["Total ",t.total," rows"]})})]})}),Jk=k.observer(({dataSource:e})=>{const t=e.tableData;return t.maxPage===0?i(s.Text,{mt:20,color:"red",size:"md",align:"center",sx:{fontFamily:"monospace"},children:"This table is empty"}):t.error?i(s.Text,{mt:20,color:"red",size:"md",align:"center",sx:{fontFamily:"monospace"},children:t.error}):t.page===1&&t.loading?i(Qk,{visible:!0}):p(Fe,{children:[i(Xk,{dataSource:e}),p(s.Box,{py:10,sx:{width:"100%",height:"calc(100% - 42px)",overflow:"auto",position:"relative"},children:[i(s.LoadingOverlay,{visible:t.loading,overlayBlur:2}),i(nu,{data:t.data})]})]})}),Zk={root:{flexGrow:1,overflow:"auto",borderLeft:"1px solid #efefef"},tabsList:{borderBottom:"1px solid #efefef"},tab:{minWidth:120}},Hk=k.observer(({dataSource:e})=>(b.useEffect(()=>{e.loadTablesIfEmpty()},[e]),e.tables.error?i(s.Text,{color:"red",size:"md",align:"center",sx:{fontFamily:"monospace"},children:e.tables.error}):p(s.Flex,{sx:{height:"100%"},children:[i(s.Box,{w:300,sx:{flexGrow:0,flexShrink:0,position:"relative"},children:i(Fe,{children:i(Yk,{dataSource:e})})}),p(s.Tabs,{defaultValue:"structure",styles:Zk,children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"structure",icon:i($.IconColumns,{size:14}),children:"Structure"}),i(s.Tabs.Tab,{value:"data",icon:i($.IconDatabase,{size:14}),children:"Data"})]}),i(s.Tabs.Panel,{value:"structure",children:i(jk,{dataSource:e})}),i(s.Tabs.Panel,{value:"data",sx:{width:"100%",height:"calc(100% - 36px)",overflow:"hidden"},children:i(Jk,{dataSource:e})})]})]}))),eT={modal:{paddingLeft:"0px !important",paddingRight:"0px !important"},header:{marginBottom:0,padding:"20px 20px 10px",borderBottom:"1px solid #efefef",gap:"20px"},title:{flexGrow:1},body:{padding:"0 0 0 20px"}},ou=k.observer(({dataSource:e,triggerButtonProps:t={}})=>{const[n,r]=b.useState(!1);return e.type==="http"?null:p(B,{children:[i(s.Modal,{opened:n,onClose:()=>r(!1),title:p(s.Group,{position:"apart",sx:{flexGrow:1},children:[i(s.Text,{fw:500,children:"Explorer Data Source"}),p(s.Group,{spacing:7,children:[i(s.Badge,{variant:"gradient",gradient:{from:"indigo",to:"cyan"},children:e.key}),i(s.Badge,{variant:"gradient",gradient:{from:"orange",to:"red"},children:e.type})]})]}),zIndex:320,size:"96vw",styles:eT,children:i(s.Box,{sx:{height:"calc(100vh - 220px)"},children:i(Hk,{dataSource:e})})}),i(s.Button,{variant:"subtle",onClick:()=>r(!0),px:16,styles:{inner:{justifyContent:"flex-start"}},...t,children:"See Table Structure"})]})}),tT=b.forwardRef(({label:e,type:t,...n},r)=>p(s.Group,{position:"apart",ref:r,...n,children:[i(s.Text,{children:e}),i(s.Text,{children:t})]})),nT=k.observer(({value:e,onChange:t})=>{const n=ce(),{data:r=[],loading:a}=K.useRequest(mr,{refreshDeps:[]},[]),o=b.useMemo(()=>r.map(d=>({label:d.key,value:d.key,type:d.type})),[r]),l=b.useMemo(()=>o.reduce((d,f)=>(d[f.value]=f.type,d),{}),[o]),u=d=>{d!==null&&t({key:d,type:l[d]})},c=b.useMemo(()=>n.datasources.find(e),[n,e]);return i(s.Select,{data:o,label:p(s.Group,{position:"apart",children:[i(s.Box,{children:"Data Source"}),c&&i(ou,{dataSource:c,triggerButtonProps:{compact:!0,size:"xs",px:10}})]}),itemComponent:tT,rightSection:c?i(s.Text,{size:"xs",color:"dimmed",children:c.type}):void 0,rightSectionWidth:85,maxDropdownHeight:280,styles:{root:{flex:1},label:{display:"block"},rightSection:{pointerEvents:"none",justifyContent:"flex-end",paddingRight:"10px",".mantine-Text-root":{userSelect:"none"}}},disabled:a,value:e.key,onChange:u})}),lu=b.forwardRef((e,t)=>{const{label:n,description:r,...a}=e;return i("div",{ref:t,...a,children:p(s.Group,{position:"apart",noWrap:!0,children:[i(s.Text,{children:n}),i(s.Text,{size:"xs",color:"dimmed",children:r})]})})}),rT=k.observer(({queryModel:e})=>{const[t,n]=b.useState(e.name);return b.useEffect(()=>{n(e.name)},[e.name]),i(s.Center,{ml:20,mt:20,sx:{maxWidth:"600px"},children:p(s.Stack,{spacing:10,sx:{width:"100%"},children:[i(s.Divider,{mb:-10,variant:"dashed",label:"Basics",labelPosition:"center"}),i(s.TextInput,{placeholder:"A unique name",label:"Name",required:!0,sx:{flex:1},value:t,onChange:r=>{n(r.currentTarget.value)},rightSection:i(s.ActionIcon,{variant:"filled",color:"blue",size:"sm",onClick:()=>e.setName(t),disabled:t===e.name,children:i($.IconDeviceFloppy,{size:16})}),onBlur:()=>{e.setName(t)}}),i(nT,{value:{type:e.type,key:e.key},onChange:({type:r,key:a})=>{e.setKey(a),e.setType(r)}}),i(s.Divider,{mt:10,mb:-10,variant:"dashed",label:"Conditions",labelPosition:"center"}),i(s.MultiSelect,{label:"Run query when these are truthy",placeholder:"Always run this query on load",data:e.conditionOptions,value:[...e.run_by],onChange:e.setRunBy,itemComponent:lu,maxDropdownHeight:500}),e.typedAsHTTP&&i(s.MultiSelect,{label:"Re-run query when these changed",placeholder:"Leave it empty to never re-run this query",data:e.conditionOptions,value:[...e.react_to],onChange:e.setReactTo,itemComponent:lu,maxDropdownHeight:500}),i(s.Divider,{mt:20,mb:10,variant:"dashed"}),i(Vk,{queryModel:e})]})})});function iT({content:e}){return p(s.HoverCard,{width:"60vw",shadow:"md",children:[i(s.HoverCard.Target,{children:i(s.ActionIcon,{size:16,color:"blue",children:i($.IconEye,{})})}),i(s.HoverCard.Dropdown,{children:i(kt.Prism,{language:"sql",noCopy:!0,withLineNumbers:!0,children:e})})]})}const aT=k.observer(()=>{const t=[...ce().globalSQLSnippets.list];return t.length===0?null:p(s.Table,{horizontalSpacing:"xs",verticalSpacing:"xs",fontSize:"sm",highlightOnHover:!0,children:[i("thead",{children:p("tr",{children:[i("th",{children:"Key"}),i("th",{children:"Value"})]})}),i("tbody",{children:t.map(n=>{const{id:r,content:a}=n;return p("tr",{children:[i("td",{children:r}),i("td",{width:200,children:i(iT,{content:a})})]},r)})})]})}),sT=`
520
520
  -- You may reference query variables in SQL or VizConfig.
521
521
  SELECT *
522
522
  FROM commit
@@ -529,8 +529,8 @@ WHERE
529
529
  AND \${sql_snippets.author_email_condition}
530
530
  -- Global SQL snippets (shared between dashboards)
531
531
  AND \${global_sql_snippets.account_condition}
532
- `,uu=k.observer(function({showSQLSnippets:t=!0,sx:n={}}){const r=pe(),a=le(),o=r.context.current,l=(()=>{const u={context:{...a.mock_context.current,...o},filters:a.filters.previewValues};return t&&(u.sql_snippets=a.sqlSnippets.record),JSON.stringify(u,null,2)})();return i(s.Stack,{sx:{overflow:"hidden",...n},children:p(s.Tabs,{defaultValue:"guide",keepMounted:!1,children:[p(s.Tabs.List,{grow:!0,children:[i(s.Tabs.Tab,{value:"guide",icon:i($.IconAlertCircle,{size:14}),children:"Guide"}),i(s.Tabs.Tab,{value:"local_query_vars",icon:i($.IconVariable,{size:14}),children:"Variables in this dashboard"}),i(s.Tabs.Tab,{value:"global_sql_snippets",icon:i($.IconVariablePlus,{size:14}),children:"Global SQL Snippets"})]}),i(s.Tabs.Panel,{value:"guide",pt:"xs",children:i(kt.Prism,{language:"sql",sx:{width:"100%"},noCopy:!0,colorScheme:"dark",children:sT})}),i(s.Tabs.Panel,{value:"local_query_vars",pt:"xs",children:i(kt.Prism,{language:"json",sx:{width:"100%"},noCopy:!0,colorScheme:"dark",children:l})}),i(s.Tabs.Panel,{value:"global_sql_snippets",pt:"xs",children:p(s.Stack,{spacing:10,children:[i(s.Alert,{icon:i($.IconAlertCircle,{size:16}),title:"Global SQL Snippets",children:"SQL snippets worth sharing between dashboards are managed in System Settings by admins."}),i(aT,{})]})})]})})}),qi=k.observer(()=>{const[e,t]=y.useState(!1);return p(B,{children:[i(s.Modal,{opened:e,onClose:()=>t(!1),title:"Query Variables",zIndex:320,size:"800px",children:i(uu,{})}),i(s.Button,{variant:"subtle",onClick:()=>t(!0),px:16,styles:{inner:{justifyContent:"flex-start"}},children:"See Query Variables"})]})}),cu={pre:["function build_request({ context, filters }, utils) {"," // build the quest"," return { method: 'POST', url: '/', params: {}, headers: {}, data: {} }","}"].join(`
532
+ `,uu=k.observer(function({showSQLSnippets:t=!0,sx:n={}}){const r=ce(),a=le(),o=r.context.current,l=(()=>{const u={context:{...a.mock_context.current,...o},filters:a.filters.previewValues};return t&&(u.sql_snippets=a.sqlSnippets.record),JSON.stringify(u,null,2)})();return i(s.Stack,{sx:{overflow:"hidden",...n},children:p(s.Tabs,{defaultValue:"guide",keepMounted:!1,children:[p(s.Tabs.List,{grow:!0,children:[i(s.Tabs.Tab,{value:"guide",icon:i($.IconAlertCircle,{size:14}),children:"Guide"}),i(s.Tabs.Tab,{value:"local_query_vars",icon:i($.IconVariable,{size:14}),children:"Variables in this dashboard"}),i(s.Tabs.Tab,{value:"global_sql_snippets",icon:i($.IconVariablePlus,{size:14}),children:"Global SQL Snippets"})]}),i(s.Tabs.Panel,{value:"guide",pt:"xs",children:i(kt.Prism,{language:"sql",sx:{width:"100%"},noCopy:!0,colorScheme:"dark",children:sT})}),i(s.Tabs.Panel,{value:"local_query_vars",pt:"xs",children:i(kt.Prism,{language:"json",sx:{width:"100%"},noCopy:!0,colorScheme:"dark",children:l})}),i(s.Tabs.Panel,{value:"global_sql_snippets",pt:"xs",children:p(s.Stack,{spacing:10,children:[i(s.Alert,{icon:i($.IconAlertCircle,{size:16}),title:"Global SQL Snippets",children:"SQL snippets worth sharing between dashboards are managed in System Settings by admins."}),i(aT,{})]})})]})})}),qi=k.observer(()=>{const[e,t]=b.useState(!1);return p(B,{children:[i(s.Modal,{opened:e,onClose:()=>t(!1),title:"Query Variables",zIndex:320,size:"800px",children:i(uu,{})}),i(s.Button,{variant:"subtle",onClick:()=>t(!0),px:16,styles:{inner:{justifyContent:"flex-start"}},children:"See Query Variables"})]})}),cu={pre:["function build_request({ context, filters }, utils) {"," // build the quest"," return { method: 'POST', url: '/', params: {}, headers: {}, data: {} }","}"].join(`
533
533
  `),post:["function process_result(res, utils) {"," // your code goes here"," return data","}"].join(`
534
- `)},oT=k.observer(({queryModel:e})=>e.typedAsHTTP?p(s.Tabs,{defaultValue:"pre_process",orientation:"vertical",sx:{flexGrow:1},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"pre_process",children:"Build Request"}),i(s.Tabs.Tab,{value:"post_process",children:"Process Result"}),i(qi,{})]}),i(s.Tabs.Panel,{value:"pre_process",sx:{position:"relative"},p:"sm",children:i(ln,{label:"",value:e.pre_process,onChange:e.setPreProcess,defaultValue:cu.pre})}),i(s.Tabs.Panel,{value:"post_process",p:"sm",children:i(ln,{label:"",value:e.post_process,onChange:e.setPostProcess,defaultValue:cu.post})})]}):null),lT=k.observer(({queryID:e,usage:t})=>{const n=pe().editor,r=o=>{if(o.type==="filter"){n.setPath(["_FILTERS_",o.id]);return}if(o.type==="panel"){const l=o.views[0].id;n.setPath(["_VIEWS_",l,"_PANELS_",o.id]);return}},a=o=>{n.setPath(["_VIEWS_",o])};return i(s.Stack,{py:"sm",px:"md",children:p(s.Table,{highlightOnHover:!0,sx:{tableLayout:"fixed"},children:[i("thead",{children:p("tr",{children:[i("th",{style:{width:100},children:"Type"}),i("th",{style:{width:"calc(50% - 50px)"},children:"Name"}),i("th",{children:"In View(s)"})]})}),i("tbody",{children:t.map(o=>p("tr",{children:[i("td",{children:x.capitalize(o.type)}),i("td",{children:i(s.Anchor,{component:"button",type:"button",onClick:()=>r(o),children:o.label})}),i("td",{children:p(s.Stack,{align:"flex-start",justify:"flex-start",spacing:2,children:[o.views.map(l=>i(s.Anchor,{component:"button",type:"button",onClick:()=>a(l.id),children:i(s.Box,{children:l.label})})),o.views.length===0&&i(s.Box,{children:"--"})]})})]},o.id))})]})})}),Fi=({value:e,onChange:t,height:n="200px",defaultLanguage:r="sql",theme:a="vs-dark"})=>{const o=u=>{t==null||t(u??"")},l=!t;return i(Ae,{className:"minimal-monaco-editor",height:n,defaultLanguage:r,value:e,onChange:l?void 0:o,theme:a,options:{lineNumbers:"off",folding:!1,lineDecorationsWidth:20,lineNumbersMinChars:0,wordWrap:"on",minimap:{enabled:!1},readOnly:l||!t,"semanticHighlighting.enabled":!0}})},uT=({value:e,onChange:t,defaultValue:n})=>{const[r,a]=y.useState(e),o=()=>{t(r)},l=()=>{a(e)},u=()=>{a(n)};y.useEffect(()=>{a(e)},[e]);const c=r!==e;return p(s.Stack,{spacing:4,sx:{height:"100%"},children:[p(s.Group,{mb:6,position:"apart",sx:{flexShrink:0,flexGrow:0},children:[i(s.Group,{position:"left",children:i(s.Button,{onClick:u,size:"xs",variant:"default",leftIcon:i($.IconPlayerSkipBack,{size:16}),children:"Reset to default"})}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:l,color:"red",size:"xs",disabled:!c,leftIcon:i($.IconRecycle,{size:16}),children:"Revert Changes"}),i(s.Button,{size:"xs",onClick:o,disabled:!c,leftIcon:i($.IconDeviceFloppy,{size:16}),children:"Confirm Changes"})]})]}),i(Fi,{height:"100%",value:r,onChange:a,theme:"sql-dark",defaultLanguage:"sql"})]})},cT=({value:e,height:t="200px",defaultLanguage:n="sql"})=>i(Ae,{className:"preview-sql-in-monaco-editor",height:t,defaultLanguage:n,value:e,onChange:void 0,theme:"vs-light",options:{lineNumbers:"on",folding:!0,lineDecorationsWidth:20,wordWrap:"on",minimap:{enabled:!1},readOnly:!0}}),dT=k.observer(({value:e})=>{const n=we().payloadForSQL,r=y.useMemo(()=>gr(e,n),[e,n]);return i(cT,{height:"100%",value:r})}),du={pre:["function process_request({ context, filters, sql }, utils) {"," // modify and return sql"," return sql","}"].join(`
534
+ `)},oT=k.observer(({queryModel:e})=>e.typedAsHTTP?p(s.Tabs,{defaultValue:"pre_process",orientation:"vertical",sx:{flexGrow:1},children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"pre_process",children:"Build Request"}),i(s.Tabs.Tab,{value:"post_process",children:"Process Result"}),i(qi,{})]}),i(s.Tabs.Panel,{value:"pre_process",sx:{position:"relative"},p:"sm",children:i(un,{label:"",value:e.pre_process,onChange:e.setPreProcess,defaultValue:cu.pre})}),i(s.Tabs.Panel,{value:"post_process",p:"sm",children:i(un,{label:"",value:e.post_process,onChange:e.setPostProcess,defaultValue:cu.post})})]}):null),lT=k.observer(({queryID:e,usage:t})=>{const n=ce().editor,r=o=>{if(o.type==="filter"){n.setPath(["_FILTERS_",o.id]);return}if(o.type==="panel"){const l=o.views[0].id;n.setPath(["_VIEWS_",l,"_PANELS_",o.id]);return}},a=o=>{n.setPath(["_VIEWS_",o])};return i(s.Stack,{py:"sm",px:"md",children:p(s.Table,{highlightOnHover:!0,sx:{tableLayout:"fixed"},children:[i("thead",{children:p("tr",{children:[i("th",{style:{width:100},children:"Type"}),i("th",{style:{width:"calc(50% - 50px)"},children:"Name"}),i("th",{children:"In View(s)"})]})}),i("tbody",{children:t.map(o=>p("tr",{children:[i("td",{children:x.capitalize(o.type)}),i("td",{children:i(s.Anchor,{component:"button",type:"button",onClick:()=>r(o),children:o.label})}),i("td",{children:p(s.Stack,{align:"flex-start",justify:"flex-start",spacing:2,children:[o.views.map(l=>i(s.Anchor,{component:"button",type:"button",onClick:()=>a(l.id),children:i(s.Box,{children:l.label})})),o.views.length===0&&i(s.Box,{children:"--"})]})})]},o.id))})]})})}),Fi=({value:e,onChange:t,height:n="200px",defaultLanguage:r="sql",theme:a="vs-dark"})=>{const o=u=>{t==null||t(u??"")},l=!t;return i(Ae,{className:"minimal-monaco-editor",height:n,defaultLanguage:r,value:e,onChange:l?void 0:o,theme:a,options:{lineNumbers:"off",folding:!1,lineDecorationsWidth:20,lineNumbersMinChars:0,wordWrap:"on",minimap:{enabled:!1},readOnly:l||!t,"semanticHighlighting.enabled":!0}})},uT=({value:e,onChange:t,defaultValue:n})=>{const[r,a]=b.useState(e),o=()=>{t(r)},l=()=>{a(e)},u=()=>{a(n)};b.useEffect(()=>{a(e)},[e]);const c=r!==e;return p(s.Stack,{spacing:4,sx:{height:"100%"},children:[p(s.Group,{mb:6,position:"apart",sx:{flexShrink:0,flexGrow:0},children:[i(s.Group,{position:"left",children:i(s.Button,{onClick:u,size:"xs",variant:"default",leftIcon:i($.IconPlayerSkipBack,{size:16}),children:"Reset to default"})}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:l,color:"red",size:"xs",disabled:!c,leftIcon:i($.IconRecycle,{size:16}),children:"Revert Changes"}),i(s.Button,{size:"xs",onClick:o,disabled:!c,leftIcon:i($.IconDeviceFloppy,{size:16}),children:"Confirm Changes"})]})]}),i(Fi,{height:"100%",value:r,onChange:a,theme:"sql-dark",defaultLanguage:"sql"})]})},cT=({value:e,height:t="200px",defaultLanguage:n="sql"})=>i(Ae,{className:"preview-sql-in-monaco-editor",height:t,defaultLanguage:n,value:e,onChange:void 0,theme:"vs-light",options:{lineNumbers:"on",folding:!0,lineDecorationsWidth:20,wordWrap:"on",minimap:{enabled:!1},readOnly:!0}}),dT=k.observer(({value:e})=>{const n=we().payloadForSQL,r=b.useMemo(()=>gr(e,n),[e,n]);return i(cT,{height:"100%",value:r})}),du={pre:["function process_request({ context, filters, sql }, utils) {"," // modify and return sql"," return sql","}"].join(`
535
535
  `),post:["function process_result(data, utils) {"," // process data and return the result"," return data","}"].join(`
536
- `)},pT=k.observer(({queryModel:e})=>e.typedAsSQL?p(s.Tabs,{defaultValue:"Edit",orientation:"vertical",sx:{flexGrow:1},styles:{tabLabel:{width:"100%",height:"28px",lineHeight:"28px"}},keepMounted:!1,children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"Edit",children:i(s.Group,{spacing:14,position:"apart",children:"Edit SQL"})}),i(s.Tabs.Tab,{value:"Preview",children:"Preview SQL"}),i(s.Tabs.Tab,{value:"pre_process",children:"Process Request"}),i(s.Tabs.Tab,{value:"post_process",children:"Process Result"}),i(qi,{}),e.datasource&&i(ou,{dataSource:e.datasource})]}),i(s.Tabs.Panel,{value:"Edit",sx:{position:"relative"},p:"sm",children:i(uT,{value:e.sql,onChange:e.setSQL,defaultValue:"SELECT 1"})}),i(s.Tabs.Panel,{value:"Preview",p:0,pl:4,children:i(dT,{value:e.sql})}),i(s.Tabs.Panel,{value:"pre_process",sx:{position:"relative"},p:"sm",children:i(ln,{label:"",value:e.pre_process,onChange:e.setPreProcess,defaultValue:du.pre})}),i(s.Tabs.Panel,{value:"post_process",p:"sm",children:i(ln,{label:"",value:e.post_process,onChange:e.setPostProcess,defaultValue:du.post})})]}):null),lr={height:"calc(100% - 44px)",padding:0},hT=k.observer(({queryModel:e})=>{const t=le(),n=y.useMemo(()=>e.datasource?e.typedAsHTTP?"HTTP":"SQL":"Configurations",[e.datasource,e.typedAsHTTP]),[r,a]=y.useState(n);y.useEffect(()=>{a(u=>u!=="Configurations"&&n==="Configurations"?"Configurations":u)},[n]);const o=t.findQueryUsage(e.id),l=o.length===0;return i(s.Stack,{sx:{flexGrow:1},my:0,p:0,children:p(s.Tabs,{value:r,onTabChange:a,defaultValue:n,orientation:"horizontal",keepMounted:!1,sx:{flexGrow:1},children:[p(s.Tabs.List,{grow:!0,children:[i(s.Tabs.Tab,{value:"Configurations",children:"Configurations"}),e.typedAsSQL&&i(s.Tabs.Tab,{value:"SQL",children:"Request"}),e.typedAsHTTP&&i(s.Tabs.Tab,{value:"HTTP",children:"Request"}),i(s.Tabs.Tab,{value:"Data",disabled:!e.datasource,children:i(s.Tooltip,{label:"Need to pick a Data Source first",disabled:e.datasource,withinPortal:!0,children:i(s.Text,{children:"Data"})})}),i(s.Tabs.Tab,{value:"Usage",disabled:l,children:i(s.Tooltip,{label:"This query is not used for any filter or panel",disabled:!l,withinPortal:!0,children:i(s.Text,{children:"Usage"})})})]}),i(s.Tabs.Panel,{value:"Configurations",pt:0,p:0,children:i(rT,{queryModel:e})}),e.typedAsSQL&&i(s.Tabs.Panel,{value:"SQL",sx:lr,children:i(s.Stack,{sx:{height:"100%"},children:i(pT,{queryModel:e})})}),e.typedAsHTTP&&i(s.Tabs.Panel,{value:"HTTP",sx:lr,children:i(s.Stack,{sx:{height:"100%"},children:i(oT,{queryModel:e})})}),i(s.Tabs.Panel,{value:"Data",sx:{...lr,overflow:"hidden"},children:i(Vi,{id:e.id})}),i(s.Tabs.Panel,{value:"Usage",sx:{...lr,overflow:"hidden"},children:i(lT,{queryID:e.id,usage:o})})]})})}),fT=k.observer(({id:e})=>{const n=le().queries.findByID(e);return e===""?null:n?i(s.Stack,{sx:{height:"100%"},spacing:"sm",children:i(hT,{queryModel:n})}):i(s.Text,{size:14,color:"red",children:"Invalid Query ID"})}),gT=k.observer(({value:e})=>{const n=we().payloadForSQL,r=y.useMemo(()=>gr(e,n),[e,n]);return i(Fi,{height:"100%",value:r})}),mT=k.observer(({item:e,remove:t,onKeyChanged:n})=>{const[r,a]=y.useState("SQL"),[o,l]=y.useState(e.key),u=()=>{e.setKey(o),n(o)},c=o!==e.key,d=e.isADuplicatedKey(o),[f,h]=y.useState(e.value),g=()=>{e.setValue(f)};y.useEffect(()=>{l(e.key),h(e.value)},[e]);const m=f!==e.value,C=Qe.useModals(),w=()=>{C.openConfirmModal({title:"Delete this SQL snippet?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:t,confirmProps:{color:"red"},zIndex:320})};return p(s.Stack,{p:20,sx:{maxWidth:"1100px",height:"100vh"},spacing:"sm",children:[p(s.Group,{sx:{alignItems:"end"},spacing:40,children:[i(s.TextInput,{label:d?"This key is occupied by another snippet":"Key",value:o,onChange:_=>{l(_.currentTarget.value)},sx:{flexGrow:"1 !important"},rightSection:i(s.ActionIcon,{color:"blue",variant:"subtle",onClick:u,disabled:!c||d,children:i(T.DeviceFloppy,{size:16})}),error:d}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:w,children:"Delete this SQL Snippet"})]}),p(s.Tabs,{value:r,onTabChange:a,sx:{flexGrow:1},styles:{panel:{height:"calc(100% - 50px)"}},children:[p(s.Tabs.List,{sx:{position:"relative"},children:[i(s.Tabs.Tab,{value:"SQL",children:"SQL"}),i(s.Tabs.Tab,{value:"Preview",children:"Preview"}),i(qi,{}),i(s.ActionIcon,{color:"blue",variant:"filled",onClick:g,disabled:!m,sx:{position:"absolute",top:0,right:10},children:i(T.DeviceFloppy,{size:18})})]}),i(s.Tabs.Panel,{value:"SQL",pt:"sm",children:i(Fi,{height:"100%",value:f,onChange:h,defaultLanguage:"sql",theme:"sql-dark"})}),i(s.Tabs.Panel,{value:"Preview",pt:"sm",children:i(gT,{value:f})})]})]})}),yT=k.observer(({id:e})=>{const t=pe(),n=le(),r=y.useMemo(()=>n.sqlSnippets.findByKey(e),[e]);if(!e)return null;if(!r)return p(s.Text,{size:14,children:["SQL Snippet by key[",e,"] is not found"]});const a=()=>{t.editor.setPath(["_SQL_SNIPPETS_",""])};return i(mT,{item:r,remove:()=>{n.sqlSnippets.removeByKey(e),a()},onKeyChanged:u=>{t.editor.setPath(["_SQL_SNIPPETS_",u])}})}),bT=k.observer(({view:e})=>!e||e.type!==j.Division?null:p(s.Stack,{children:[i(s.Divider,{mt:8,mb:0,label:"Division settings",labelPosition:"center"}),i(s.Text,{align:"center",size:"xs",color:"dimmed",children:"Under construction"})]})),vT=[{value:"default",label:"Default"},{value:"outline",label:"Outline"},{value:"pills",label:"Pills"}],xT=[{value:"horizontal",label:"Horizontal"},{value:"vertical",label:"Vertical"}],wT=k.observer(({view:e})=>{if(!e||e.type!==j.Tabs)return null;const t=e.config;return p(s.Stack,{children:[i(s.Divider,{mt:8,mb:0,label:"Tabs settings",labelPosition:"center"}),i(s.Select,{label:"Variant",value:t.variant,onChange:t.setVariant,data:vT}),i(s.Select,{label:"Orientation",value:t.orientation,onChange:t.setOrientation,data:xT}),i(s.Switch,{label:"Grow Tabs",checked:t.grow,onChange:n=>t.setGrow(n.currentTarget.checked)})]})}),CT=({disabled:e,value:t,onChange:n})=>{const r=a=>{a&&n(a)};return p(s.Box,{sx:{position:"relative"},children:[e&&i(s.Overlay,{opacity:.6,color:"#fff",zIndex:5,blur:2}),i(Ae,{height:"500px",defaultLanguage:"javascript",value:t,onChange:r,theme:"vs-dark",options:{minimap:{enabled:!1},readOnly:e}})]})},ST=({value:e,onChange:t})=>{const[n,{setTrue:r,setFalse:a}]=K.useBoolean(),[o,l]=y.useState(e??Ti),u=g=>{l({...o,enabled:g})},c=()=>{a();const{enabled:g,func_content:m}=o,C={enabled:g,func_content:m};l(C),t(C)},d=()=>{a(),l(e)},f=g=>{l(m=>({...m,func_content:g}))},h=()=>{f(Ti.func_content)};return p(B,{children:[i(s.ActionIcon,{size:"lg",color:"blue",variant:"filled",mt:26,onClick:r,sx:{flexGrow:0},children:i(T.Settings,{size:14})}),i(s.Modal,{size:800,title:"Customize modal title",opened:n,onClose:a,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:n&&p(s.Stack,{children:[i(s.Checkbox,{mt:10,label:"Enabled",checked:o.enabled,onChange:g=>u(g.currentTarget.checked)}),i(CT,{value:o.func_content,onChange:f,disabled:!o.enabled}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:h,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:d,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:c,children:"OK"})]})]})]})})]})},_T=k.observer(({view:e})=>{if(!e||e.type!==j.Modal)return null;const t=e.config,n=t.custom_modal_title.value;return p(s.Stack,{children:[i(s.Divider,{mt:8,label:"Modal settings",labelPosition:"center"}),p(s.Flex,{gap:10,children:[i(s.TextInput,{label:"Modal Title",value:n,onChange:x.noop,disabled:!0,sx:{flexGrow:1}}),i(ST,{value:t.custom_modal_title,onChange:t.custom_modal_title.replace})]}),p(s.Group,{grow:!0,children:[i(s.TextInput,{label:"Width",value:t.width,onChange:r=>t.setWidth(r.currentTarget.value),placeholder:"600px / 50vw"}),i(s.TextInput,{label:"Height",value:t.height,onChange:r=>t.setHeight(r.currentTarget.value),placeholder:"600px / 50vw"})]})]})}),kT=k.observer(({view:e})=>p(B,{children:[i(bT,{view:e}),i(_T,{view:e}),i(wT,{view:e})]})),TT=[{label:"Division",value:j.Division},{label:"Modal",value:j.Modal},{label:"Tabs",value:j.Tabs}],DT=k.observer(({view:e})=>e?p(s.Stack,{sx:{position:"relative"},children:[i(s.TextInput,{label:"Name",value:e.name,onChange:t=>{e.setName(t.currentTarget.value)}}),i(s.Select,{label:"Type",withinPortal:!0,zIndex:320,value:e.type,onChange:e.setType,data:TT}),i(kT,{view:e})]}):null),IT=k.observer(({id:e})=>{const t=Qe.useModals(),n=pe(),r=le();if(e==="")return null;const a=r.views.findByID(e);if(!a)return p(s.Text,{size:14,children:["View by ID[",e,"] is not found"]});const o=()=>{n.editor.setPath(["_VIEWS_",""])},l=()=>{t.openConfirmModal({title:"Delete this view?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>{r.views.removeByID(e),o()},zIndex:320})};return p(s.Stack,{sx:{maxWidth:"600px",height:"100%"},spacing:"sm",children:[i(s.Group,{position:"right",pt:10,children:i(s.Button,{size:"xs",color:"red",leftIcon:i(T.Trash,{size:16}),onClick:l,children:"Delete this view"})}),i(s.Box,{sx:{flexGrow:1,maxHeight:"calc(100% - 52px)",overflow:"auto"},children:i(DT,{view:a})})]})});function MT(e){return e.length===1&&e[0]==="_QUERY_VARS_"}function AT(e){return e.length===1&&e[0]==="_MOCK_CONTEXT_"}function zT(e){return e.length===2&&e[0]==="_FILTERS_"}function ET(e){return e.length===2&&e[0]==="_SQL_SNIPPETS_"}function $T(e){return e.length===2&&e[0]==="_QUERIES_"}function LT(e){return e.length===1&&e[0]==="_QUERIES_"}function OT(e){return e.length===2&&e[0]==="_VIEWS_"}function PT(e){return e.length===4&&e[0]==="_VIEWS_"&&e[2]==="_PANELS_"}const BT=k.observer(()=>i(s.Stack,{sx:{height:"100%"},p:"sm",children:i(uu,{})})),VT=k.observer(()=>{const e=Qe.useModals(),t=pe(),n=o=>{t.editor.setPath(["_QUERIES_",o])},r=()=>{e.openConfirmModal({title:"Delete ununsed queries?",children:i(s.Text,{size:"sm",children:"This action cannot be undone."}),labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>t.content.removeUnusedQueries(),confirmProps:{color:"red"},zIndex:320})},a=t.content.queriesUsage;return p(s.Stack,{sx:{height:"100%"},spacing:"sm",pb:"59px",children:[i(s.Box,{pt:9,pb:8,sx:{borderBottom:"1px solid #eee"},children:i(s.Text,{px:"md",align:"left",sx:{userSelect:"none",cursor:"default"},children:"Manage Queries"})}),i(s.Flex,{justify:"flex-end",align:"center",px:12,children:i(s.Button,{variant:"subtle",size:"xs",color:"red",leftIcon:i($.IconTrash,{size:14}),disabled:!t.content.hasUnusedQueries,onClick:r,children:"Delete unused queries"})}),i(s.Box,{sx:{flexGrow:1,overflow:"auto"},children:p(s.Table,{fontSize:"sm",highlightOnHover:!0,sx:{tableLayout:"fixed"},children:[i("thead",{children:p("tr",{children:[i("th",{children:"Name"}),i("th",{style:{width:"200px"},children:"Data Source"}),i("th",{style:{width:"100px",textAlign:"right"},children:"Type"}),i("th",{style:{width:"100px",textAlign:"center"},children:"Usage"}),i("th",{style:{width:"300px",paddingLeft:"24px"},children:"Action"})]})}),i("tbody",{children:t.content.queries.sortedList.map(o=>{var u;const l=((u=a[o.id])==null?void 0:u.length)??0;return p("tr",{children:[i("td",{children:o.name}),i("td",{children:o.key}),i("td",{style:{textAlign:"right"},children:o.type}),i("td",{style:{color:l===0?"#ff0000":"#000",fontWeight:l===0?"bold":"normal",textAlign:"center"},children:l}),i("td",{children:i(s.Button,{variant:"subtle",size:"xs",onClick:()=>n(o.id),children:"Open"})})]},o.id)})})]})})]})}),NT=k.observer(()=>{const e=pe().editor,t=e.path;return MT(t)?i(BT,{}):AT(t)?i(ok,{}):zT(t)?i(s.Box,{p:"xs",pl:20,children:i(sk,{id:t[1]})}):ET(t)?i(yT,{id:t[1]}):LT(t)?i(VT,{}):$T(t)?i(fT,{id:t[1]}):OT(t)?i(s.Box,{p:"xs",pl:20,children:i(IT,{id:t[1]})}):PT(t)?i(Pk,{viewID:t[1],panelID:t[3]}):i(s.Box,{children:e.path})}),qT=k.observer(()=>i(NT,{})),FT=k.observer(()=>{const e=pe(),t=()=>{const n=new Date().getTime().toString(),r={id:n,key:n,label:n,order:e.content.filters.current.length+1,type:_e.TextInput,config:tl(),visibleInViewsIDs:["Main"],auto_submit:!1};e.content.filters.append(r),e.editor.setPath(["_FILTERS_",n])};return i(s.Button,{variant:"subtle",leftIcon:i($.IconPlus,{size:14}),size:"sm",px:"xs",mb:10,color:"blue",onClick:t,sx:{width:"100%",borderRadius:0},styles:{inner:{justifyContent:"flex-start"}},children:"Add a Filter"})}),GT=k.observer(({parentID:e})=>{const t=le();if(!e)return null;const n=t.views.findByID(e);return!n||n.type===j.Tabs?null:i(s.Button,{variant:"subtle",leftIcon:i($.IconPlus,{size:14}),size:"sm",px:"xs",mb:10,color:"blue",onClick:()=>t.addANewPanel(n.id),sx:{width:"100%",borderRadius:0},styles:{inner:{justifyContent:"flex-start"}},children:"Add a Panel"})}),WT=k.observer(()=>{const e=pe(),t=()=>{const n=new Date().getTime().toString(),r={id:n,name:n,type:Se.Postgresql,key:"",sql:""};e.content.queries.append(r),e.editor.setPath(["_QUERIES_",n])};return i(s.Button,{variant:"subtle",leftIcon:i($.IconPlus,{size:14}),size:"sm",px:"xs",mb:10,color:"blue",onClick:t,sx:{width:"100%",borderRadius:0},styles:{inner:{justifyContent:"flex-start"}},children:"Add a Query"})}),jT=k.observer(()=>{const e=pe(),t=()=>{const n=new Date().getTime().toString(),r={key:n,value:""};e.content.sqlSnippets.append(r),e.editor.setPath(["_SQL_SNIPPETS_",n])};return i(s.Button,{variant:"subtle",leftIcon:i($.IconPlus,{size:14}),size:"sm",px:"xs",mb:10,color:"blue",onClick:t,sx:{width:"100%",borderRadius:0},styles:{inner:{justifyContent:"flex-start"}},children:"Add a SQL Snippet"})}),RT=k.observer(()=>{const e=le();return i(s.Button,{variant:"subtle",leftIcon:i($.IconPlus,{size:14}),size:"sm",px:"xs",mb:10,color:"blue",onClick:e.views.addARandomNewView,sx:{width:"100%",borderRadius:0},styles:{inner:{justifyContent:"flex-start"}},children:"Add a View"})}),YT=k.observer(()=>{const e=pe();return i(s.Button,{variant:"subtle",rightIcon:i($.IconSettings,{size:14}),size:"sm",px:12,mb:0,color:"blue",onClick:()=>e.editor.setPath(["_QUERIES_"]),sx:{width:"100%",borderRadius:0,fontWeight:"normal"},styles:{inner:{justifyContent:"space-between"}},children:"Manage Queries"})}),QT=k.observer(({action_type:e,parentID:t})=>e==="_Add_A_Filter_"?i(FT,{}):e==="_Add_A_SQL_SNIPPET_"?i(jT,{}):e==="_Add_A_QUERY_"?i(WT,{}):e==="_Add_A_VIEW_"?i(RT,{}):e==="_Add_A_PANEL_"?i(GT,{parentID:t}):e==="_QUERIES_SETTINGS_"?i(YT,{}):null),pu=k.observer(({option:e})=>{var d;const t=pe().editor,n=t.isOptionActive,r=n(t.path,e),a=t.isOptionOpened,o=t.navigate,l=a(e),[u,c]=y.useState(l);return y.useEffect(()=>{c(l)},[l]),i(s.NavLink,{active:r,defaultOpened:l,opened:u,onChange:c,label:e.label,onClick:()=>o(e),icon:e.Icon?i(e.Icon,{size:18}):null,children:(d=e.children)==null?void 0:d.map(f=>f._type==="ACTION"?i(QT,{action_type:f._action_type,parentID:f.parentID},`_ADD_${f.value}_`):i(pu,{option:f},f.value))},e.label)}),UT=k.observer(()=>{const e=pe();return i(s.Box,{sx:{position:"relative"},children:e.editor.navOptions.map(t=>i(pu,{option:t},t.value))})}),KT=k.observer(()=>{const e=pe();return p(s.Navbar,{p:0,width:{base:200,xs:200,sm:220,md:240,lg:280,xl:300},sx:{height:"100vh - 60px - 60px"},children:[i(s.Navbar.Section,{pt:9,pb:8,sx:{borderBottom:"1px solid #eee"},children:i(s.Text,{align:"center",sx:{userSelect:"none",cursor:"default"},children:"Settings"})}),i(s.Navbar.Section,{grow:!0,sx:{overflow:"auto"},children:i(UT,{})}),i(s.Navbar.Section,{children:i(s.Group,{grow:!0,p:"md",pt:"sm",sx:{borderTop:"1px solid #eee"},children:i(s.Button,{size:"xs",color:"red",leftIcon:i($.IconX,{size:18}),onClick:()=>e.editor.close(),children:"Close"})})})]})}),XT={root:{height:"100vh",display:"flex",flexDirection:"column",overflow:"hidden"},body:{flexGrow:1,nav:{top:0,height:"100vh"}},main:{flexGrow:1,display:"flex",flexDirection:"column",paddingTop:0,height:"100vh"}},JT=k.observer(()=>{const e=pe().editor;return i(s.Modal,{onClose:()=>e.setSettingsOpen(!1),closeOnEscape:!1,closeOnClickOutside:!1,opened:e.settings_open,fullScreen:!0,title:null,transitionProps:{duration:0},withCloseButton:!1,withinPortal:!0,zIndex:300,styles:{body:{padding:"0 !important"}},children:i(s.AppShell,{padding:0,navbar:i(KT,{}),styles:XT,children:i(qT,{})})})}),ZT=e=>e.replace(/([^:])(\/\/+)/g,"$1/");function HT(e){y.useEffect(()=>{if(Ae.loader.__getMonacoInstance())return;console.log("loading monaco for @devtable/dashboard");const n=ZT(e);Ae.loader.config({paths:{vs:n}}),Ae.loader.init().then(r=>console.log("monaco instance:",r))},[])}ao();const eD={root:{height:"100vh",display:"flex",flexDirection:"column",overflow:"hidden"},body:{flexGrow:1},main:{flexGrow:1,display:"flex",flexDirection:"column",paddingTop:60+30,height:"100vh"}},tD=({context:e,dashboard:t,content:n,update:r,className:a="dashboard",config:o,onChange:l,headerSlot:u},c)=>{HT(o.monacoPath),Ka(o);const{data:d=[]}=K.useRequest(mr),{data:f=[]}=K.useRequest(Xa),h=y.useMemo(()=>Ql(t,n,d,f,e),[t,n]);y.useImperativeHandle(c,()=>h,[h]),Ul(h.content,!0),y.useEffect(()=>{h.context.replace(e)},[e]),y.useEffect(()=>{h.datasources.replace(d)},[d]),y.useEffect(()=>{h.globalSQLSnippets.replace(f)},[f]),y.useEffect(()=>te.reaction(()=>te.toJS(h.json),w=>{l==null||l(w)}),[h]);const g=async()=>{await r(h.json,h.content.json)},m=K.useCreation(Si,[]),C=Kl(m);return i(Qe.ModalsProvider,{children:i(vr,{value:h,children:i(Cr,{value:h.content,children:i(kn.Provider,{value:{inEditMode:!0},children:i(ut.Provider,{value:m,children:p(er,{configure:C,children:[i(s.AppShell,{padding:0,header:i(b_,{saveDashboardChanges:g,headerSlot:u}),navbar:i(R_,{}),styles:eD,children:i(s.Box,{className:`${a} dashboard-root`,sx:{position:"relative"},children:h.content.views.visibleViews.map(w=>i(Pl,{view:w},w.id))})}),i(JT,{})]})})})})})})},nD=k.observer(y.forwardRef(tD)),uM="",hu=b.types.model({id:b.types.string,name:b.types.string,dashboard_id:b.types.string,create_time:b.types.string,update_time:b.types.string,version:b.types.string,filters:fl,queries:wl,sqlSnippets:Cl,views:cl,panels:pl,mock_context:Qo}).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,definition:{queries:e.queries.json,sqlSnippets:e.sqlSnippets.json,mock_context:e.mock_context.current}}}},get payloadForSQL(){const t=b.getParent(e).context.current,n=b.getParent(e).globalSQLSnippets,r={context:{...e.mock_context.current,...t},filters:e.filters.values};return{...r,sql_snippets:rr(e.sqlSnippets.current,"key","value",r),global_sql_snippets:rr(n.list,"id","content",r)}},get payloadForViz(){const t=b.getParent(e).context.current;return{context:{...e.mock_context.current,...t},filters:e.filters.values}},get data(){return e.queries.current.map(({id:n,data:r})=>({id:n,data:r})).reduce((n,r)=>(n[r.id]=r.data,n),{})},getDataStuffByID(t){const n=e.queries.findByID(t);return n?{data:n.data,len:n.data.length,state:n.state,error:n.error}:{data:[],len:0,state:"idle",error:void 0}}})).actions(e=>({}));function rD({id:e,name:t,dashboard_id:n,create_time:r,update_time:a,content:o}){if(!o)throw new Error("unexpected null content when creating a content model");const{version:l,filters:u,views:c,panels:d,definition:{queries:f,sqlSnippets:h,mock_context:g={}}}=o;return hu.create({id:e,name:t,dashboard_id:n,create_time:r,update_time:a,version:l,filters:gl(u),queries:mS(f),sqlSnippets:bS(h),mock_context:Uo(g),views:aS(c),panels:{list:d}})}const iD=b.types.model({id:b.types.identifier,name:b.types.string,group:b.types.string,content:hu,content_id:b.types.string,datasources:nS,globalSQLSnippets:ll,context:Di});function aD({id:e,name:t,group:n,content_id:r},a,o,l,u){return iD.create({id:e,name:t,group:n,content_id:r,content:rD(a),datasources:{list:o},globalSQLSnippets:{list:l},context:ul(u)})}ao();const sD=k.observer(({context:e,dashboard:t,content:n,className:r="dashboard",config:a,fullScreenPanelID:o,setFullScreenPanelID:l})=>{Ka(a);const{data:u=[]}=K.useRequest(mr),{data:c=[]}=K.useRequest(Xa),d=y.useMemo(()=>aD(t,n,u,c,e),[t,n]);Ul(d.content,!1),y.useEffect(()=>{d.context.replace(e)},[e]),y.useEffect(()=>{d.datasources.replace(u)},[u]),y.useEffect(()=>{d.globalSQLSnippets.replace(c)},[c]);const f=K.useCreation(Si,[]),h=Kl(f);return i(Qe.ModalsProvider,{children:i(vr,{value:d,children:i(Cr,{value:d.content,children:i(_r.Provider,{value:{fullScreenPanelID:o,setFullScreenPanelID:l},children:i(kn.Provider,{value:{inEditMode:!1},children:i(s.Box,{className:`${r} dashboard-root`,children:i(ut.Provider,{value:f,children:i(er,{configure:h,children:d.content.views.visibleViews.map(g=>i(ar,{view:g},g.id))})})})})})})})})});var Gi={},oD={get exports(){return Gi},set exports(e){Gi=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){var a=r.prototype,o=a.format;a.format=function(l){var u=this,c=this.$locale();if(!this.isValid())return o.bind(this)(l);var d=this.$utils(),f=(l||"YYYY-MM-DDTHH:mm:ssZ").replace(/\[([^\]]+)]|Q|wo|ww|w|WW|W|zzz|z|gggg|GGGG|Do|X|x|k{1,2}|S/g,function(h){switch(h){case"Q":return Math.ceil((u.$M+1)/3);case"Do":return c.ordinal(u.$D);case"gggg":return u.weekYear();case"GGGG":return u.isoWeekYear();case"wo":return c.ordinal(u.week(),"W");case"w":case"ww":return d.s(u.week(),h==="w"?1:2,"0");case"W":case"WW":return d.s(u.isoWeek(),h==="W"?1:2,"0");case"k":case"kk":return d.s(String(u.$H===0?24:u.$H),h==="k"?1:2,"0");case"X":return Math.floor(u.$d.getTime()/1e3);case"x":return u.$d.getTime();case"z":return"["+u.offsetName()+"]";case"zzz":return"["+u.offsetName("long")+"]";default:return h}});return o.bind(this)(f)}}})})(oD);const lD=Gi;var Wi={},uD={get exports(){return Wi},set exports(e){Wi=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){var o=r.prototype,l=function(c){var d=c.date,f=c.utc;return Array.isArray(d)?f?d.length?new Date(Date.UTC.apply(null,d)):new Date:d.length===1?a(String(d[0])).toDate():new(Function.prototype.bind.apply(Date,[null].concat(d))):d},u=o.parse;o.parse=function(c){c.date=l.bind(this)(c),u.bind(this)(c)}}})})(uD);const cD=Wi;var ji={},dD={get exports(){return ji},set exports(e){ji=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){var a=r.prototype,o=a.format;a.format=function(l){var u=this,c=(l||"YYYY-MM-DDTHH:mm:ssZ").replace(/(\[[^\]]+])|BBBB|BB/g,function(d,f){var h,g=String(u.$y+543),m=d==="BB"?[g.slice(-2),2]:[g,4];return f||(h=u.$utils()).s.apply(h,m.concat(["0"]))});return o.bind(this)(c)}}})})(dD);const pD=ji;var Ri={},hD={get exports(){return Ri},set exports(e){Ri=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){var o="h:mm A",l={lastDay:"[Yesterday at] "+o,sameDay:"[Today at] "+o,nextDay:"[Tomorrow at] "+o,nextWeek:"dddd [at] "+o,lastWeek:"[Last] dddd [at] "+o,sameElse:"MM/DD/YYYY"};r.prototype.calendar=function(u,c){var d=c||this.$locale().calendar||l,f=a(u||void 0).startOf("d"),h=this.diff(f,"d",!0),g="sameElse",m=h<-6?g:h<-1?"lastWeek":h<0?"lastDay":h<1?"sameDay":h<2?"nextDay":h<7?"nextWeek":g,C=d[m]||l[m];return typeof C=="function"?C.call(this,a()):this.format(C)}}})})(hD);const fD=Ri;var Yi={},gD={get exports(){return Yi},set exports(e){Yi=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){var n={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},r=/(\[[^[]*\])|([-_:/.,()\s]+)|(A|a|YYYY|YY?|MM?M?M?|Do|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g,a=/\d\d/,o=/\d\d?/,l=/\d*[^-_:/,()\s\d]+/,u={},c=function(w){return(w=+w)+(w>68?1900:2e3)},d=function(w){return function(_){this[w]=+_}},f=[/[+-]\d\d:?(\d\d)?|Z/,function(w){(this.zone||(this.zone={})).offset=function(_){if(!_||_==="Z")return 0;var D=_.match(/([+-]|\d\d)/g),M=60*D[1]+(+D[2]||0);return M===0?0:D[0]==="+"?-M:M}(w)}],h=function(w){var _=u[w];return _&&(_.indexOf?_:_.s.concat(_.f))},g=function(w,_){var D,M=u.meridiem;if(M){for(var P=1;P<=24;P+=1)if(w.indexOf(M(P,0,_))>-1){D=P>12;break}}else D=w===(_?"pm":"PM");return D},m={A:[l,function(w){this.afternoon=g(w,!1)}],a:[l,function(w){this.afternoon=g(w,!0)}],S:[/\d/,function(w){this.milliseconds=100*+w}],SS:[a,function(w){this.milliseconds=10*+w}],SSS:[/\d{3}/,function(w){this.milliseconds=+w}],s:[o,d("seconds")],ss:[o,d("seconds")],m:[o,d("minutes")],mm:[o,d("minutes")],H:[o,d("hours")],h:[o,d("hours")],HH:[o,d("hours")],hh:[o,d("hours")],D:[o,d("day")],DD:[a,d("day")],Do:[l,function(w){var _=u.ordinal,D=w.match(/\d+/);if(this.day=D[0],_)for(var M=1;M<=31;M+=1)_(M).replace(/\[|\]/g,"")===w&&(this.day=M)}],M:[o,d("month")],MM:[a,d("month")],MMM:[l,function(w){var _=h("months"),D=(h("monthsShort")||_.map(function(M){return M.slice(0,3)})).indexOf(w)+1;if(D<1)throw new Error;this.month=D%12||D}],MMMM:[l,function(w){var _=h("months").indexOf(w)+1;if(_<1)throw new Error;this.month=_%12||_}],Y:[/[+-]?\d+/,d("year")],YY:[a,function(w){this.year=c(w)}],YYYY:[/\d{4}/,d("year")],Z:f,ZZ:f};function C(w){var _,D;_=w,D=u&&u.formats;for(var M=(w=_.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,function(X,Q,H){var oe=H&&H.toUpperCase();return Q||D[H]||n[H]||D[oe].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(ue,be,Ee){return be||Ee.slice(1)})})).match(r),P=M.length,G=0;G<P;G+=1){var L=M[G],z=m[L],A=z&&z[0],F=z&&z[1];M[G]=F?{regex:A,parser:F}:L.replace(/^\[|\]$/g,"")}return function(X){for(var Q={},H=0,oe=0;H<P;H+=1){var ue=M[H];if(typeof ue=="string")oe+=ue.length;else{var be=ue.regex,Ee=ue.parser,ge=X.slice(oe),ve=be.exec(ge)[0];Ee.call(Q,ve),X=X.replace(ve,"")}}return function(me){var Oe=me.afternoon;if(Oe!==void 0){var He=me.hours;Oe?He<12&&(me.hours+=12):He===12&&(me.hours=0),delete me.afternoon}}(Q),Q}}return function(w,_,D){D.p.customParseFormat=!0,w&&w.parseTwoDigitYear&&(c=w.parseTwoDigitYear);var M=_.prototype,P=M.parse;M.parse=function(G){var L=G.date,z=G.utc,A=G.args;this.$u=z;var F=A[1];if(typeof F=="string"){var X=A[2]===!0,Q=A[3]===!0,H=X||Q,oe=A[2];Q&&(oe=A[2]),u=this.$locale(),!X&&oe&&(u=D.Ls[oe]),this.$d=function(ge,ve,me){try{if(["x","X"].indexOf(ve)>-1)return new Date((ve==="X"?1e3:1)*ge);var Oe=C(ve)(ge),He=Oe.year,$t=Oe.month,ur=Oe.day,cr=Oe.hours,wa=Oe.minutes,Ca=Oe.seconds,fn=Oe.milliseconds,jt=Oe.zone,wt=new Date,Lt=ur||(He||$t?1:wt.getDate()),Ct=He||wt.getFullYear(),Rt=0;He&&!$t||(Rt=$t>0?$t-1:wt.getMonth());var Yt=cr||0,gn=wa||0,mn=Ca||0,St=fn||0;return jt?new Date(Date.UTC(Ct,Rt,Lt,Yt,gn,mn,St+60*jt.offset*1e3)):me?new Date(Date.UTC(Ct,Rt,Lt,Yt,gn,mn,St)):new Date(Ct,Rt,Lt,Yt,gn,mn,St)}catch{return new Date("")}}(L,F,z),this.init(),oe&&oe!==!0&&(this.$L=this.locale(oe).$L),H&&L!=this.format(F)&&(this.$d=new Date("")),u={}}else if(F instanceof Array)for(var ue=F.length,be=1;be<=ue;be+=1){A[1]=F[be-1];var Ee=D.apply(this,A);if(Ee.isValid()){this.$d=Ee.$d,this.$L=Ee.$L,this.init();break}be===ue&&(this.$d=new Date(""))}else P.call(this,G)}}})})(gD);const mD=Yi;var Qi={},yD={get exports(){return Qi},set exports(e){Qi=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){r.prototype.dayOfYear=function(o){var l=Math.round((a(this).startOf("day")-a(this).startOf("year"))/864e5)+1;return o==null?l:this.add(o-l,"day")}}})})(yD);const bD=Qi;var Ui={},vD={get exports(){return Ui},set exports(e){Ui=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){var n,r,a=1e3,o=6e4,l=36e5,u=864e5,c=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,d=31536e6,f=2592e6,h=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/,g={years:d,months:f,days:u,hours:l,minutes:o,seconds:a,milliseconds:1,weeks:6048e5},m=function(L){return L instanceof G},C=function(L,z,A){return new G(L,A,z.$l)},w=function(L){return r.p(L)+"s"},_=function(L){return L<0},D=function(L){return _(L)?Math.ceil(L):Math.floor(L)},M=function(L){return Math.abs(L)},P=function(L,z){return L?_(L)?{negative:!0,format:""+M(L)+z}:{negative:!1,format:""+L+z}:{negative:!1,format:""}},G=function(){function L(A,F,X){var Q=this;if(this.$d={},this.$l=X,A===void 0&&(this.$ms=0,this.parseFromMilliseconds()),F)return C(A*g[w(F)],this);if(typeof A=="number")return this.$ms=A,this.parseFromMilliseconds(),this;if(typeof A=="object")return Object.keys(A).forEach(function(ue){Q.$d[w(ue)]=A[ue]}),this.calMilliseconds(),this;if(typeof A=="string"){var H=A.match(h);if(H){var oe=H.slice(2).map(function(ue){return ue!=null?Number(ue):0});return this.$d.years=oe[0],this.$d.months=oe[1],this.$d.weeks=oe[2],this.$d.days=oe[3],this.$d.hours=oe[4],this.$d.minutes=oe[5],this.$d.seconds=oe[6],this.calMilliseconds(),this}}return this}var z=L.prototype;return z.calMilliseconds=function(){var A=this;this.$ms=Object.keys(this.$d).reduce(function(F,X){return F+(A.$d[X]||0)*g[X]},0)},z.parseFromMilliseconds=function(){var A=this.$ms;this.$d.years=D(A/d),A%=d,this.$d.months=D(A/f),A%=f,this.$d.days=D(A/u),A%=u,this.$d.hours=D(A/l),A%=l,this.$d.minutes=D(A/o),A%=o,this.$d.seconds=D(A/a),A%=a,this.$d.milliseconds=A},z.toISOString=function(){var A=P(this.$d.years,"Y"),F=P(this.$d.months,"M"),X=+this.$d.days||0;this.$d.weeks&&(X+=7*this.$d.weeks);var Q=P(X,"D"),H=P(this.$d.hours,"H"),oe=P(this.$d.minutes,"M"),ue=this.$d.seconds||0;this.$d.milliseconds&&(ue+=this.$d.milliseconds/1e3);var be=P(ue,"S"),Ee=A.negative||F.negative||Q.negative||H.negative||oe.negative||be.negative,ge=H.format||oe.format||be.format?"T":"",ve=(Ee?"-":"")+"P"+A.format+F.format+Q.format+ge+H.format+oe.format+be.format;return ve==="P"||ve==="-P"?"P0D":ve},z.toJSON=function(){return this.toISOString()},z.format=function(A){var F=A||"YYYY-MM-DDTHH:mm:ss",X={Y:this.$d.years,YY:r.s(this.$d.years,2,"0"),YYYY:r.s(this.$d.years,4,"0"),M:this.$d.months,MM:r.s(this.$d.months,2,"0"),D:this.$d.days,DD:r.s(this.$d.days,2,"0"),H:this.$d.hours,HH:r.s(this.$d.hours,2,"0"),m:this.$d.minutes,mm:r.s(this.$d.minutes,2,"0"),s:this.$d.seconds,ss:r.s(this.$d.seconds,2,"0"),SSS:r.s(this.$d.milliseconds,3,"0")};return F.replace(c,function(Q,H){return H||String(X[Q])})},z.as=function(A){return this.$ms/g[w(A)]},z.get=function(A){var F=this.$ms,X=w(A);return X==="milliseconds"?F%=1e3:F=X==="weeks"?D(F/g[X]):this.$d[X],F===0?0:F},z.add=function(A,F,X){var Q;return Q=F?A*g[w(F)]:m(A)?A.$ms:C(A,this).$ms,C(this.$ms+Q*(X?-1:1),this)},z.subtract=function(A,F){return this.add(A,F,!0)},z.locale=function(A){var F=this.clone();return F.$l=A,F},z.clone=function(){return C(this.$ms,this)},z.humanize=function(A){return n().add(this.$ms,"ms").locale(this.$l).fromNow(!A)},z.milliseconds=function(){return this.get("milliseconds")},z.asMilliseconds=function(){return this.as("milliseconds")},z.seconds=function(){return this.get("seconds")},z.asSeconds=function(){return this.as("seconds")},z.minutes=function(){return this.get("minutes")},z.asMinutes=function(){return this.as("minutes")},z.hours=function(){return this.get("hours")},z.asHours=function(){return this.as("hours")},z.days=function(){return this.get("days")},z.asDays=function(){return this.as("days")},z.weeks=function(){return this.get("weeks")},z.asWeeks=function(){return this.as("weeks")},z.months=function(){return this.get("months")},z.asMonths=function(){return this.as("months")},z.years=function(){return this.get("years")},z.asYears=function(){return this.as("years")},L}();return function(L,z,A){n=A,r=A().$utils(),A.duration=function(Q,H){var oe=A.locale();return C(Q,{$l:oe},H)},A.isDuration=m;var F=z.prototype.add,X=z.prototype.subtract;z.prototype.add=function(Q,H){return m(Q)&&(Q=Q.asMilliseconds()),F.bind(this)(Q,H)},z.prototype.subtract=function(Q,H){return m(Q)&&(Q=Q.asMilliseconds()),X.bind(this)(Q,H)}}})})(vD);const xD=Ui;var Ki={},wD={get exports(){return Ki},set exports(e){Ki=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){r.prototype.isBetween=function(o,l,u,c){var d=a(o),f=a(l),h=(c=c||"()")[0]==="(",g=c[1]===")";return(h?this.isAfter(d,u):!this.isBefore(d,u))&&(g?this.isBefore(f,u):!this.isAfter(f,u))||(h?this.isBefore(d,u):!this.isAfter(d,u))&&(g?this.isAfter(f,u):!this.isBefore(f,u))}}})})(wD);const CD=Ki;var Xi={},SD={get exports(){return Xi},set exports(e){Xi=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){r.prototype.isLeapYear=function(){return this.$y%4==0&&this.$y%100!=0||this.$y%400==0}}})})(SD);const _D=Xi;var Ji={},kD={get exports(){return Ji},set exports(e){Ji=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){a.isMoment=function(o){return a.isDayjs(o)}}})})(kD);const TD=Ji;var Zi={},DD={get exports(){return Zi},set exports(e){Zi=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){var n="day";return function(r,a,o){var l=function(d){return d.add(4-d.isoWeekday(),n)},u=a.prototype;u.isoWeekYear=function(){return l(this).year()},u.isoWeek=function(d){if(!this.$utils().u(d))return this.add(7*(d-this.isoWeek()),n);var f,h,g,m,C=l(this),w=(f=this.isoWeekYear(),h=this.$u,g=(h?o.utc:o)().year(f).startOf("year"),m=4-g.isoWeekday(),g.isoWeekday()>4&&(m+=7),g.add(m,n));return C.diff(w,"week")+1},u.isoWeekday=function(d){return this.$utils().u(d)?this.day()||7:this.day(this.day()%7?d:d-7)};var c=u.startOf;u.startOf=function(d,f){var h=this.$utils(),g=!!h.u(f)||f;return h.p(d)==="isoweek"?g?this.date(this.date()-(this.isoWeekday()-1)).startOf("day"):this.date(this.date()-1-(this.isoWeekday()-1)+7).endOf("day"):c.bind(this)(d,f)}}})})(DD);const ID=Zi;var Hi={},MD={get exports(){return Hi},set exports(e){Hi=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){r.prototype.isoWeeksInYear=function(){var a=this.isLeapYear(),o=this.endOf("y").day();return o===4||a&&o===5?53:52}}})})(MD);const AD=Hi;var ea={},zD={get exports(){return ea},set exports(e){ea=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){r.prototype.isSameOrAfter=function(a,o){return this.isSame(a,o)||this.isAfter(a,o)}}})})(zD);const ED=ea;var ta={},$D={get exports(){return ta},set exports(e){ta=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){r.prototype.isSameOrBefore=function(a,o){return this.isSame(a,o)||this.isBefore(a,o)}}})})($D);const LD=ta;var na={},OD={get exports(){return na},set exports(e){na=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){r.prototype.isToday=function(){var o="YYYY-MM-DD",l=a();return this.format(o)===l.format(o)}}})})(OD);const PD=na;var ra={},BD={get exports(){return ra},set exports(e){ra=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){r.prototype.isTomorrow=function(){var o="YYYY-MM-DD",l=a().add(1,"day");return this.format(o)===l.format(o)}}})})(BD);const VD=ra;var ia={},ND={get exports(){return ia},set exports(e){ia=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){r.prototype.isYesterday=function(){var o="YYYY-MM-DD",l=a().subtract(1,"day");return this.format(o)===l.format(o)}}})})(ND);const qD=ia;var aa={},FD={get exports(){return aa},set exports(e){aa=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){var o=r.prototype,l=function(h){return h&&(h.indexOf?h:h.s)},u=function(h,g,m,C,w){var _=h.name?h:h.$locale(),D=l(_[g]),M=l(_[m]),P=D||M.map(function(L){return L.slice(0,C)});if(!w)return P;var G=_.weekStart;return P.map(function(L,z){return P[(z+(G||0))%7]})},c=function(){return a.Ls[a.locale()]},d=function(h,g){return h.formats[g]||function(m){return m.replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(C,w,_){return w||_.slice(1)})}(h.formats[g.toUpperCase()])},f=function(){var h=this;return{months:function(g){return g?g.format("MMMM"):u(h,"months")},monthsShort:function(g){return g?g.format("MMM"):u(h,"monthsShort","months",3)},firstDayOfWeek:function(){return h.$locale().weekStart||0},weekdays:function(g){return g?g.format("dddd"):u(h,"weekdays")},weekdaysMin:function(g){return g?g.format("dd"):u(h,"weekdaysMin","weekdays",2)},weekdaysShort:function(g){return g?g.format("ddd"):u(h,"weekdaysShort","weekdays",3)},longDateFormat:function(g){return d(h.$locale(),g)},meridiem:this.$locale().meridiem,ordinal:this.$locale().ordinal}};o.localeData=function(){return f.bind(this)()},a.localeData=function(){var h=c();return{firstDayOfWeek:function(){return h.weekStart||0},weekdays:function(){return a.weekdays()},weekdaysShort:function(){return a.weekdaysShort()},weekdaysMin:function(){return a.weekdaysMin()},months:function(){return a.months()},monthsShort:function(){return a.monthsShort()},longDateFormat:function(g){return d(h,g)},meridiem:h.meridiem,ordinal:h.ordinal}},a.months=function(){return u(c(),"months")},a.monthsShort=function(){return u(c(),"monthsShort","months",3)},a.weekdays=function(h){return u(c(),"weekdays",null,null,h)},a.weekdaysShort=function(h){return u(c(),"weekdaysShort","weekdays",3,h)},a.weekdaysMin=function(h){return u(c(),"weekdaysMin","weekdays",2,h)}}})})(FD);const GD=aa;var sa={},WD={get exports(){return sa},set exports(e){sa=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){var n={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"};return function(r,a,o){var l=a.prototype,u=l.format;o.en.formats=n,l.format=function(c){c===void 0&&(c="YYYY-MM-DDTHH:mm:ssZ");var d=this.$locale().formats,f=function(h,g){return h.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,function(m,C,w){var _=w&&w.toUpperCase();return C||g[w]||n[w]||g[_].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(D,M,P){return M||P.slice(1)})})}(c,d===void 0?{}:d);return u.call(this,f)}}})})(WD);const jD=sa;var oa={},RD={get exports(){return oa},set exports(e){oa=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){var o=function(l,u){if(!u||!u.length||!u[0]||u.length===1&&!u[0].length)return null;var c;u.length===1&&u[0].length>0&&(u=u[0]),c=u[0];for(var d=1;d<u.length;d+=1)u[d].isValid()&&!u[d][l](c)||(c=u[d]);return c};a.max=function(){var l=[].slice.call(arguments,0);return o("isAfter",l)},a.min=function(){var l=[].slice.call(arguments,0);return o("isBefore",l)}}})})(RD);const YD=oa;var la={},QD={get exports(){return la},set exports(e){la=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){var o=r.prototype,l=function(g){var m,C=g.date,w=g.utc,_={};if(!((m=C)instanceof Date||m instanceof Array||o.$utils().u(m)||m.constructor.name!=="Object")){if(!Object.keys(C).length)return new Date;var D=w?a.utc():a();Object.keys(C).forEach(function(X){var Q,H;_[Q=X,H=o.$utils().p(Q),H==="date"?"day":H]=C[X]});var M=_.day||(_.year||_.month>=0?1:D.date()),P=_.year||D.year(),G=_.month>=0?_.month:_.year||_.day?0:D.month(),L=_.hour||0,z=_.minute||0,A=_.second||0,F=_.millisecond||0;return w?new Date(Date.UTC(P,G,M,L,z,A,F)):new Date(P,G,M,L,z,A,F)}return C},u=o.parse;o.parse=function(g){g.date=l.bind(this)(g),u.bind(this)(g)};var c=o.set,d=o.add,f=o.subtract,h=function(g,m,C,w){w===void 0&&(w=1);var _=Object.keys(m),D=this;return _.forEach(function(M){D=g.bind(D)(m[M]*w,M)}),D};o.set=function(g,m){return m=m===void 0?g:m,g.constructor.name==="Object"?h.bind(this)(function(C,w){return c.bind(this)(w,C)},m,g):c.bind(this)(g,m)},o.add=function(g,m){return g.constructor.name==="Object"?h.bind(this)(d,g,m):d.bind(this)(g,m)},o.subtract=function(g,m){return g.constructor.name==="Object"?h.bind(this)(d,g,m,-1):f.bind(this)(g,m)}}})})(QD);const UD=la;var ua={},KD={get exports(){return ua},set exports(e){ua=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){var a=r.prototype;["milliseconds","seconds","minutes","hours","days","weeks","isoWeeks","months","quarters","years","dates"].forEach(function(o){a[o]=a[o.replace(/s$/,"")]})}})})(KD);const XD=ua;var ca={},JD={get exports(){return ca},set exports(e){ca=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){var a=r.prototype.parse;r.prototype.parse=function(u){if(typeof u.date=="string"){var c=this.$locale();u.date=c&&c.preparse?c.preparse(u.date):u.date}return a.bind(this)(u)};var o=r.prototype.format;r.prototype.format=function(){for(var u=arguments.length,c=new Array(u),d=0;d<u;d++)c[d]=arguments[d];var f=o.call.apply(o,[this].concat(c)),h=this.$locale();return h&&h.postformat?h.postformat(f):f};var l=r.prototype.fromToBase;l&&(r.prototype.fromToBase=function(u,c,d,f){var h=this.$locale()||d.$locale();return l.call(this,u,c,d,f,h&&h.postformat)})}})})(JD);const ZD=ca;var da={},HD={get exports(){return da},set exports(e){da=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){var n="month",r="quarter";return function(a,o){var l=o.prototype;l.quarter=function(d){return this.$utils().u(d)?Math.ceil((this.month()+1)/3):this.month(this.month()%3+3*(d-1))};var u=l.add;l.add=function(d,f){return d=Number(d),this.$utils().p(f)===r?this.add(3*d,n):u.bind(this)(d,f)};var c=l.startOf;l.startOf=function(d,f){var h=this.$utils(),g=!!h.u(f)||f;if(h.p(d)===r){var m=this.quarter()-1;return g?this.month(3*m).startOf(n).startOf("day"):this.month(3*m+2).endOf(n).endOf("day")}return c.bind(this)(d,f)}}})})(HD);const eI=da;var pa={},tI={get exports(){return pa},set exports(e){pa=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){n=n||{};var o=r.prototype,l={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function u(d,f,h,g){return o.fromToBase(d,f,h,g)}a.en.relativeTime=l,o.fromToBase=function(d,f,h,g,m){for(var C,w,_,D=h.$locale().relativeTime||l,M=n.thresholds||[{l:"s",r:44,d:"second"},{l:"m",r:89},{l:"mm",r:44,d:"minute"},{l:"h",r:89},{l:"hh",r:21,d:"hour"},{l:"d",r:35},{l:"dd",r:25,d:"day"},{l:"M",r:45},{l:"MM",r:10,d:"month"},{l:"y",r:17},{l:"yy",d:"year"}],P=M.length,G=0;G<P;G+=1){var L=M[G];L.d&&(C=g?a(d).diff(h,L.d,!0):h.diff(d,L.d,!0));var z=(n.rounding||Math.round)(Math.abs(C));if(_=C>0,z<=L.r||!L.r){z<=1&&G>0&&(L=M[G-1]);var A=D[L.l];m&&(z=m(""+z)),w=typeof A=="string"?A.replace("%d",z):A(z,f,L.l,_);break}}if(f)return w;var F=_?D.future:D.past;return typeof F=="function"?F(w):F.replace("%s",w)},o.to=function(d,f){return u(d,f,this,!0)},o.from=function(d,f){return u(d,f,this)};var c=function(d){return d.$u?a.utc():a()};o.toNow=function(d){return this.to(c(this),d)},o.fromNow=function(d){return this.from(c(this),d)}}})})(tI);const nI=pa;var ha={},rI={get exports(){return ha},set exports(e){ha=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){var n={year:0,month:1,day:2,hour:3,minute:4,second:5},r={};return function(a,o,l){var u,c=function(g,m,C){C===void 0&&(C={});var w=new Date(g),_=function(D,M){M===void 0&&(M={});var P=M.timeZoneName||"short",G=D+"|"+P,L=r[G];return L||(L=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:D,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:P}),r[G]=L),L}(m,C);return _.formatToParts(w)},d=function(g,m){for(var C=c(g,m),w=[],_=0;_<C.length;_+=1){var D=C[_],M=D.type,P=D.value,G=n[M];G>=0&&(w[G]=parseInt(P,10))}var L=w[3],z=L===24?0:L,A=w[0]+"-"+w[1]+"-"+w[2]+" "+z+":"+w[4]+":"+w[5]+":000",F=+g;return(l.utc(A).valueOf()-(F-=F%1e3))/6e4},f=o.prototype;f.tz=function(g,m){g===void 0&&(g=u);var C=this.utcOffset(),w=this.toDate(),_=w.toLocaleString("en-US",{timeZone:g}),D=Math.round((w-new Date(_))/1e3/60),M=l(_).$set("millisecond",this.$ms).utcOffset(15*-Math.round(w.getTimezoneOffset()/15)-D,!0);if(m){var P=M.utcOffset();M=M.add(C-P,"minute")}return M.$x.$timezone=g,M},f.offsetName=function(g){var m=this.$x.$timezone||l.tz.guess(),C=c(this.valueOf(),m,{timeZoneName:g}).find(function(w){return w.type.toLowerCase()==="timezonename"});return C&&C.value};var h=f.startOf;f.startOf=function(g,m){if(!this.$x||!this.$x.$timezone)return h.call(this,g,m);var C=l(this.format("YYYY-MM-DD HH:mm:ss:SSS"));return h.call(C,g,m).tz(this.$x.$timezone,!0)},l.tz=function(g,m,C){var w=C&&m,_=C||m||u,D=d(+l(),_);if(typeof g!="string")return l(g).tz(_);var M=function(z,A,F){var X=z-60*A*1e3,Q=d(X,F);if(A===Q)return[X,A];var H=d(X-=60*(Q-A)*1e3,F);return Q===H?[X,Q]:[z-60*Math.min(Q,H)*1e3,Math.max(Q,H)]}(l.utc(g,w).valueOf(),D,_),P=M[0],G=M[1],L=l(P).utcOffset(G);return L.$x.$timezone=_,L},l.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},l.tz.setDefault=function(g){u=g}}})})(rI);const iI=ha;var fa={},aI={get exports(){return fa},set exports(e){fa=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){r.prototype.toArray=function(){return[this.$y,this.$M,this.$D,this.$H,this.$m,this.$s,this.$ms]}}})})(aI);const sI=fa;var ga={},oI={get exports(){return ga},set exports(e){ga=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){r.prototype.toObject=function(){return{years:this.$y,months:this.$M,date:this.$D,hours:this.$H,minutes:this.$m,seconds:this.$s,milliseconds:this.$ms}}}})})(oI);const lI=ga;var ma={},uI={get exports(){return ma},set exports(e){ma=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){a.updateLocale=function(o,l){var u=a.Ls[o];if(u)return(l?Object.keys(l):[]).forEach(function(c){u[c]=l[c]}),u}}})})(uI);const cI=ma;var ya={},dI={get exports(){return ya},set exports(e){ya=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){var n="minute",r=/[+-]\d\d(?::?\d\d)?/g,a=/([+-]|\d\d)/g;return function(o,l,u){var c=l.prototype;u.utc=function(w){var _={date:w,utc:!0,args:arguments};return new l(_)},c.utc=function(w){var _=u(this.toDate(),{locale:this.$L,utc:!0});return w?_.add(this.utcOffset(),n):_},c.local=function(){return u(this.toDate(),{locale:this.$L,utc:!1})};var d=c.parse;c.parse=function(w){w.utc&&(this.$u=!0),this.$utils().u(w.$offset)||(this.$offset=w.$offset),d.call(this,w)};var f=c.init;c.init=function(){if(this.$u){var w=this.$d;this.$y=w.getUTCFullYear(),this.$M=w.getUTCMonth(),this.$D=w.getUTCDate(),this.$W=w.getUTCDay(),this.$H=w.getUTCHours(),this.$m=w.getUTCMinutes(),this.$s=w.getUTCSeconds(),this.$ms=w.getUTCMilliseconds()}else f.call(this)};var h=c.utcOffset;c.utcOffset=function(w,_){var D=this.$utils().u;if(D(w))return this.$u?0:D(this.$offset)?h.call(this):this.$offset;if(typeof w=="string"&&(w=function(L){L===void 0&&(L="");var z=L.match(r);if(!z)return null;var A=(""+z[0]).match(a)||["-",0,0],F=A[0],X=60*+A[1]+ +A[2];return X===0?0:F==="+"?X:-X}(w),w===null))return this;var M=Math.abs(w)<=16?60*w:w,P=this;if(_)return P.$offset=M,P.$u=w===0,P;if(w!==0){var G=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(P=this.local().add(M+G,n)).$offset=M,P.$x.$localOffset=G}else P=this.utc();return P};var g=c.format;c.format=function(w){var _=w||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return g.call(this,_)},c.valueOf=function(){var w=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*w},c.isUTC=function(){return!!this.$u},c.toISOString=function(){return this.toDate().toISOString()},c.toString=function(){return this.toDate().toUTCString()};var m=c.toDate;c.toDate=function(w){return w==="s"&&this.$offset?u(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():m.call(this)};var C=c.diff;c.diff=function(w,_,D){if(w&&this.$u===w.$u)return C.call(this,w,_,D);var M=this.local(),P=u(w).local();return C.call(M,P,_,D)}}})})(dI);const pI=ya;var ba={},hI={get exports(){return ba},set exports(e){ba=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){r.prototype.weekday=function(a){var o=this.$locale().weekStart||0,l=this.$W,u=(l<o?l+7:l)-o;return this.$utils().u(a)?u:this.subtract(u,"day").add(a,"day")}}})})(hI);const fI=ba;var va={},gI={get exports(){return va},set exports(e){va=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){var n="week",r="year";return function(a,o,l){var u=o.prototype;u.week=function(c){if(c===void 0&&(c=null),c!==null)return this.add(7*(c-this.week()),"day");var d=this.$locale().yearStart||1;if(this.month()===11&&this.date()>25){var f=l(this).startOf(r).add(1,r).date(d),h=l(this).endOf(n);if(f.isBefore(h))return 1}var g=l(this).startOf(r).date(d).startOf(n).subtract(1,"millisecond"),m=this.diff(g,n,!0);return m<0?l(this).startOf("week").week():Math.ceil(m)},u.weeks=function(c){return c===void 0&&(c=null),this.week(c)}}})})(gI);const mI=va;var xa={},yI={get exports(){return xa},set exports(e){xa=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){r.prototype.weekYear=function(){var a=this.month(),o=this.week(),l=this.year();return o===1&&a===11?l+1:a===0&&o>=52?l-1:l}}})})(yI);const bI=xa;Y.extend(lD),Y.extend(cD),Y.extend(pD),Y.extend(fD),Y.extend(mD),Y.extend(bD),Y.extend(xD),Y.extend(CD),Y.extend(_D),Y.extend(TD),Y.extend(ED),Y.extend(LD),Y.extend(PD),Y.extend(VD),Y.extend(qD),Y.extend(ID),Y.extend(AD),Y.extend(GD),Y.extend(jD),Y.extend(YD),Y.extend(UD),Y.extend(XD),Y.extend(ZD),Y.extend(eI),Y.extend(nI),Y.extend(iI),Y.extend(sI),Y.extend(lI),Y.extend(cI),Y.extend(pI),Y.extend(mI),Y.extend(bI),Y.extend(fI),Y.tz.setDefault("UTC");const vI=()=>Promise.resolve().then(()=>sc).then(({version:e})=>(console.log(`[@devtable/dashboard] version: ${e}`),e));I.ContentModel=$i,I.ContentModelContextProvider=Cr,I.DashboardEditor=nD,I.DashboardFilterType=_e,I.DashboardMode=Bl,I.DashboardModel=Yl,I.DashboardModelContextProvider=vr,I.DashboardViewEditor=Pl,I.DashboardViewRender=ar,I.DescriptionPopover=Ii,I.FiltersModel=Nl,I.FullScreenPanel=zl,I.FullScreenPanelContext=_r,I.LayoutStateContext=kn,I.Panel=Al,I.PanelContextProvider=Sr,I.PanelErrorOrStateMessage=Il,I.PanelModel=Gl,I.PanelRender=Ai,I.PanelVizSection=Mi,I.PanelsModel=Wl,I.QueriesModel=ql,I.ReadOnlyDashboard=sD,I.SQLSnippetsModel=Fl,I.ViewComponentTypeBackground=Vl,I.ViewComponentTypeColor=e_,I.ViewComponentTypeName=HS,I.ViewsModel=jl,I.Viz=Dl,I.applyPartialDashboard=p_,I.createContentModel=Rl,I.createDashboardModel=Ql,I.getInitialDashboardViewsModel=Ei,I.getVersion=vI,I.initialDashboardContent=t_,I.useDashboardContext=xr,I.useEditContentModelContext=le,I.useEditDashboardContext=pe,I.useEditPanelContext=nt,I.useFullScreenPanelContext=ss,I.usePanelFullScreen=El,I.useRenderContentModelContext=we,I.useRenderDashboardContext=wr,I.useRenderPanelContext=bt,Object.defineProperty(I,Symbol.toStringTag,{value:"Module"})});
536
+ `)},pT=k.observer(({queryModel:e})=>e.typedAsSQL?p(s.Tabs,{defaultValue:"Edit",orientation:"vertical",sx:{flexGrow:1},styles:{tabLabel:{width:"100%",height:"28px",lineHeight:"28px"}},keepMounted:!1,children:[p(s.Tabs.List,{children:[i(s.Tabs.Tab,{value:"Edit",children:i(s.Group,{spacing:14,position:"apart",children:"Edit SQL"})}),i(s.Tabs.Tab,{value:"Preview",children:"Preview SQL"}),i(s.Tabs.Tab,{value:"pre_process",children:"Process Request"}),i(s.Tabs.Tab,{value:"post_process",children:"Process Result"}),i(qi,{}),e.datasource&&i(ou,{dataSource:e.datasource})]}),i(s.Tabs.Panel,{value:"Edit",sx:{position:"relative"},p:"sm",children:i(uT,{value:e.sql,onChange:e.setSQL,defaultValue:"SELECT 1"})}),i(s.Tabs.Panel,{value:"Preview",p:0,pl:4,children:i(dT,{value:e.sql})}),i(s.Tabs.Panel,{value:"pre_process",sx:{position:"relative"},p:"sm",children:i(un,{label:"",value:e.pre_process,onChange:e.setPreProcess,defaultValue:du.pre})}),i(s.Tabs.Panel,{value:"post_process",p:"sm",children:i(un,{label:"",value:e.post_process,onChange:e.setPostProcess,defaultValue:du.post})})]}):null),lr={height:"calc(100% - 44px)",padding:0},hT=k.observer(({queryModel:e})=>{const t=le(),n=b.useMemo(()=>e.datasource?e.typedAsHTTP?"HTTP":"SQL":"Configurations",[e.datasource,e.typedAsHTTP]),[r,a]=b.useState(n);b.useEffect(()=>{a(u=>u!=="Configurations"&&n==="Configurations"?"Configurations":u)},[n]);const o=t.findQueryUsage(e.id),l=o.length===0;return i(s.Stack,{sx:{flexGrow:1},my:0,p:0,children:p(s.Tabs,{value:r,onTabChange:a,defaultValue:n,orientation:"horizontal",keepMounted:!1,sx:{flexGrow:1},children:[p(s.Tabs.List,{grow:!0,children:[i(s.Tabs.Tab,{value:"Configurations",children:"Configurations"}),e.typedAsSQL&&i(s.Tabs.Tab,{value:"SQL",children:"Request"}),e.typedAsHTTP&&i(s.Tabs.Tab,{value:"HTTP",children:"Request"}),i(s.Tabs.Tab,{value:"Data",disabled:!e.datasource,children:i(s.Tooltip,{label:"Need to pick a Data Source first",disabled:e.datasource,withinPortal:!0,children:i(s.Text,{children:"Data"})})}),i(s.Tabs.Tab,{value:"Usage",disabled:l,children:i(s.Tooltip,{label:"This query is not used for any filter or panel",disabled:!l,withinPortal:!0,children:i(s.Text,{children:"Usage"})})})]}),i(s.Tabs.Panel,{value:"Configurations",pt:0,p:0,children:i(rT,{queryModel:e})}),e.typedAsSQL&&i(s.Tabs.Panel,{value:"SQL",sx:lr,children:i(s.Stack,{sx:{height:"100%"},children:i(pT,{queryModel:e})})}),e.typedAsHTTP&&i(s.Tabs.Panel,{value:"HTTP",sx:lr,children:i(s.Stack,{sx:{height:"100%"},children:i(oT,{queryModel:e})})}),i(s.Tabs.Panel,{value:"Data",sx:{...lr,overflow:"hidden"},children:i(Vi,{id:e.id})}),i(s.Tabs.Panel,{value:"Usage",sx:{...lr,overflow:"hidden"},children:i(lT,{queryID:e.id,usage:o})})]})})}),fT=k.observer(({id:e})=>{const n=le().queries.findByID(e);return e===""?null:n?i(s.Stack,{sx:{height:"100%"},spacing:"sm",children:i(hT,{queryModel:n})}):i(s.Text,{size:14,color:"red",children:"Invalid Query ID"})}),gT=k.observer(({value:e})=>{const n=we().payloadForSQL,r=b.useMemo(()=>gr(e,n),[e,n]);return i(Fi,{height:"100%",value:r})}),mT=k.observer(({item:e,remove:t,onKeyChanged:n})=>{const[r,a]=b.useState("SQL"),[o,l]=b.useState(e.key),u=()=>{e.setKey(o),n(o)},c=o!==e.key,d=e.isADuplicatedKey(o),[f,h]=b.useState(e.value),g=()=>{e.setValue(f)};b.useEffect(()=>{l(e.key),h(e.value)},[e]);const m=f!==e.value,C=We.useModals(),w=()=>{C.openConfirmModal({title:"Delete this SQL snippet?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:t,confirmProps:{color:"red"},zIndex:320})};return p(s.Stack,{p:20,sx:{maxWidth:"1100px",height:"100vh"},spacing:"sm",children:[p(s.Group,{sx:{alignItems:"end"},spacing:40,children:[i(s.TextInput,{label:d?"This key is occupied by another snippet":"Key",value:o,onChange:_=>{l(_.currentTarget.value)},sx:{flexGrow:"1 !important"},rightSection:i(s.ActionIcon,{color:"blue",variant:"subtle",onClick:u,disabled:!c||d,children:i(T.DeviceFloppy,{size:16})}),error:d}),i(s.Button,{leftIcon:i(T.Trash,{size:16}),color:"red",variant:"light",onClick:w,children:"Delete this SQL Snippet"})]}),p(s.Tabs,{value:r,onTabChange:a,sx:{flexGrow:1},styles:{panel:{height:"calc(100% - 50px)"}},children:[p(s.Tabs.List,{sx:{position:"relative"},children:[i(s.Tabs.Tab,{value:"SQL",children:"SQL"}),i(s.Tabs.Tab,{value:"Preview",children:"Preview"}),i(qi,{}),i(s.ActionIcon,{color:"blue",variant:"filled",onClick:g,disabled:!m,sx:{position:"absolute",top:0,right:10},children:i(T.DeviceFloppy,{size:18})})]}),i(s.Tabs.Panel,{value:"SQL",pt:"sm",children:i(Fi,{height:"100%",value:f,onChange:h,defaultLanguage:"sql",theme:"sql-dark"})}),i(s.Tabs.Panel,{value:"Preview",pt:"sm",children:i(gT,{value:f})})]})]})}),yT=k.observer(({id:e})=>{const t=ce(),n=le(),r=b.useMemo(()=>n.sqlSnippets.findByKey(e),[e]);if(!e)return null;if(!r)return p(s.Text,{size:14,children:["SQL Snippet by key[",e,"] is not found"]});const a=()=>{t.editor.setPath(["_SQL_SNIPPETS_",""])};return i(mT,{item:r,remove:()=>{n.sqlSnippets.removeByKey(e),a()},onKeyChanged:u=>{t.editor.setPath(["_SQL_SNIPPETS_",u])}})}),bT=k.observer(({view:e})=>!e||e.type!==j.Division?null:p(s.Stack,{children:[i(s.Divider,{mt:8,mb:0,label:"Division settings",labelPosition:"center"}),i(s.Text,{align:"center",size:"xs",color:"dimmed",children:"Under construction"})]})),vT=[{value:"default",label:"Default"},{value:"outline",label:"Outline"},{value:"pills",label:"Pills"}],xT=[{value:"horizontal",label:"Horizontal"},{value:"vertical",label:"Vertical"}],wT=k.observer(({view:e})=>{if(!e||e.type!==j.Tabs)return null;const t=e.config;return p(s.Stack,{children:[i(s.Divider,{mt:8,mb:0,label:"Tabs settings",labelPosition:"center"}),i(s.Select,{label:"Variant",value:t.variant,onChange:t.setVariant,data:vT}),i(s.Select,{label:"Orientation",value:t.orientation,onChange:t.setOrientation,data:xT}),i(s.Switch,{label:"Grow Tabs",checked:t.grow,onChange:n=>t.setGrow(n.currentTarget.checked)})]})}),CT=({disabled:e,value:t,onChange:n})=>{const r=a=>{a&&n(a)};return p(s.Box,{sx:{position:"relative"},children:[e&&i(s.Overlay,{opacity:.6,color:"#fff",zIndex:5,blur:2}),i(Ae,{height:"500px",defaultLanguage:"javascript",value:t,onChange:r,theme:"vs-dark",options:{minimap:{enabled:!1},readOnly:e}})]})},ST=({value:e,onChange:t})=>{const[n,{setTrue:r,setFalse:a}]=K.useBoolean(),[o,l]=b.useState(e??Ti),u=g=>{l({...o,enabled:g})},c=()=>{a();const{enabled:g,func_content:m}=o,C={enabled:g,func_content:m};l(C),t(C)},d=()=>{a(),l(e)},f=g=>{l(m=>({...m,func_content:g}))},h=()=>{f(Ti.func_content)};return p(B,{children:[i(s.ActionIcon,{size:"lg",color:"blue",variant:"filled",mt:26,onClick:r,sx:{flexGrow:0},children:i(T.Settings,{size:14})}),i(s.Modal,{size:800,title:"Customize modal title",opened:n,onClose:a,closeOnClickOutside:!1,withCloseButton:!1,zIndex:320,children:n&&p(s.Stack,{children:[i(s.Checkbox,{mt:10,label:"Enabled",checked:o.enabled,onChange:g=>u(g.currentTarget.checked)}),i(CT,{value:o.func_content,onChange:f,disabled:!o.enabled}),p(s.Group,{position:"apart",children:[i(s.Button,{onClick:h,color:"red",leftIcon:i(T.Recycle,{size:20}),children:"Reset"}),p(s.Group,{position:"right",children:[i(s.Button,{onClick:d,variant:"subtle",children:"Cancel"}),i(s.Button,{onClick:c,children:"OK"})]})]})]})})]})},_T=k.observer(({view:e})=>{if(!e||e.type!==j.Modal)return null;const t=e.config,n=t.custom_modal_title.value;return p(s.Stack,{children:[i(s.Divider,{mt:8,label:"Modal settings",labelPosition:"center"}),p(s.Flex,{gap:10,children:[i(s.TextInput,{label:"Modal Title",value:n,onChange:x.noop,disabled:!0,sx:{flexGrow:1}}),i(ST,{value:t.custom_modal_title,onChange:t.custom_modal_title.replace})]}),p(s.Group,{grow:!0,children:[i(s.TextInput,{label:"Width",value:t.width,onChange:r=>t.setWidth(r.currentTarget.value),placeholder:"600px / 50vw"}),i(s.TextInput,{label:"Height",value:t.height,onChange:r=>t.setHeight(r.currentTarget.value),placeholder:"600px / 50vw"})]})]})}),kT=k.observer(({view:e})=>p(B,{children:[i(bT,{view:e}),i(_T,{view:e}),i(wT,{view:e})]})),TT=[{label:"Division",value:j.Division},{label:"Modal",value:j.Modal},{label:"Tabs",value:j.Tabs}],DT=k.observer(({view:e})=>e?p(s.Stack,{sx:{position:"relative"},children:[i(s.TextInput,{label:"Name",value:e.name,onChange:t=>{e.setName(t.currentTarget.value)}}),i(s.Select,{label:"Type",withinPortal:!0,zIndex:320,value:e.type,onChange:e.setType,data:TT}),i(kT,{view:e})]}):null),IT=k.observer(({id:e})=>{const t=We.useModals(),n=ce(),r=le();if(e==="")return null;const a=r.views.findByID(e);if(!a)return p(s.Text,{size:14,children:["View by ID[",e,"] is not found"]});const o=()=>{n.editor.setPath(["_VIEWS_",""])},l=()=>{t.openConfirmModal({title:"Delete this view?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>{r.views.removeByID(e),o()},zIndex:320})};return p(s.Stack,{sx:{maxWidth:"600px",height:"100%"},spacing:"sm",children:[i(s.Group,{position:"right",pt:10,children:i(s.Button,{size:"xs",color:"red",leftIcon:i(T.Trash,{size:16}),onClick:l,children:"Delete this view"})}),i(s.Box,{sx:{flexGrow:1,maxHeight:"calc(100% - 52px)",overflow:"auto"},children:i(DT,{view:a})})]})});function MT(e){return e.length===1&&e[0]==="_QUERY_VARS_"}function AT(e){return e.length===1&&e[0]==="_MOCK_CONTEXT_"}function zT(e){return e.length===2&&e[0]==="_FILTERS_"}function ET(e){return e.length===1&&e[0]==="_SQL_SNIPPETS_"}function $T(e){return e.length===2&&e[0]==="_SQL_SNIPPETS_"}function LT(e){return e.length===2&&e[0]==="_QUERIES_"}function OT(e){return e.length===1&&e[0]==="_QUERIES_"}function PT(e){return e.length===2&&e[0]==="_VIEWS_"}function BT(e){return e.length===4&&e[0]==="_VIEWS_"&&e[2]==="_PANELS_"}const VT=k.observer(()=>i(s.Stack,{sx:{height:"100%"},p:"sm",children:i(uu,{})})),NT=k.observer(()=>{const e=We.useModals(),t=ce(),n=o=>{t.editor.setPath(["_QUERIES_",o])},r=()=>{e.openConfirmModal({title:"Delete ununsed queries?",children:i(s.Text,{size:"sm",children:"This action cannot be undone."}),labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>t.content.removeUnusedQueries(),confirmProps:{color:"red"},zIndex:320})},a=t.content.queriesUsage;return p(s.Stack,{sx:{height:"100%"},spacing:"sm",pb:"59px",children:[i(s.Box,{pt:9,pb:8,sx:{borderBottom:"1px solid #eee"},children:i(s.Text,{px:"md",align:"left",sx:{userSelect:"none",cursor:"default"},children:"Manage Queries"})}),i(s.Flex,{justify:"flex-end",align:"center",px:12,children:i(s.Button,{variant:"subtle",size:"xs",color:"red",leftIcon:i($.IconTrash,{size:14}),disabled:!t.content.hasUnusedQueries,onClick:r,children:"Delete unused queries"})}),i(s.Box,{sx:{flexGrow:1,overflow:"auto"},children:p(s.Table,{fontSize:"sm",highlightOnHover:!0,sx:{tableLayout:"fixed"},children:[i("thead",{children:p("tr",{children:[i("th",{children:"Name"}),i("th",{style:{width:"200px"},children:"Data Source"}),i("th",{style:{width:"100px",textAlign:"right"},children:"Type"}),i("th",{style:{width:"100px",textAlign:"center"},children:"Usage"}),i("th",{style:{width:"300px",paddingLeft:"24px"},children:"Action"})]})}),i("tbody",{children:t.content.queries.sortedList.map(o=>{var u;const l=((u=a[o.id])==null?void 0:u.length)??0;return p("tr",{children:[i("td",{children:o.name}),i("td",{children:o.key}),i("td",{style:{textAlign:"right"},children:o.type}),i("td",{style:{color:l===0?"#ff0000":"#000",fontWeight:l===0?"bold":"normal",textAlign:"center"},children:l}),i("td",{children:i(s.Button,{variant:"subtle",size:"xs",onClick:()=>n(o.id),children:"Open"})})]},o.id)})})]})})]})}),qT=k.observer(()=>{const e=We.useModals(),t=ce(),n=o=>{t.editor.setPath(["_SQL_SNIPPETS_",o])},r=()=>{e.openConfirmModal({title:"Delete ununsed SQL snippets?",children:i(s.Text,{size:"sm",children:"This action cannot be undone."}),labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>t.content.removeUnusedSQLSnippets(),confirmProps:{color:"red"},zIndex:320})},a=t.content.sqlSnippetsUsage;return p(s.Stack,{sx:{height:"100%"},spacing:"sm",pb:"59px",children:[i(s.Box,{pt:9,pb:8,sx:{borderBottom:"1px solid #eee"},children:i(s.Text,{px:"md",align:"left",sx:{userSelect:"none",cursor:"default"},children:"Manage SQL Snippets"})}),i(s.Flex,{justify:"flex-end",align:"center",px:12,children:i(s.Button,{variant:"subtle",size:"xs",color:"red",leftIcon:i($.IconTrash,{size:14}),disabled:!t.content.hasUnusedSQLSnippets,onClick:r,children:"Delete unused SQL snippets"})}),i(s.Box,{sx:{flexGrow:1,overflow:"auto"},children:p(s.Table,{fontSize:"sm",highlightOnHover:!0,sx:{tableLayout:"fixed"},children:[i("thead",{children:p("tr",{children:[i("th",{children:"Key"}),i("th",{style:{width:"100px",textAlign:"center"},children:"Usage"}),i("th",{style:{width:"300px",paddingLeft:"24px"},children:"Action"})]})}),i("tbody",{children:t.content.sqlSnippets.sortedList.map(o=>{var u;const l=((u=a[o.key])==null?void 0:u.length)??0;return p("tr",{children:[i("td",{children:o.key}),i("td",{style:{color:l===0?"#ff0000":"#000",fontWeight:l===0?"bold":"normal",textAlign:"center"},children:l}),i("td",{children:i(s.Button,{variant:"subtle",size:"xs",onClick:()=>n(o.key),children:"Open"})})]},o.key)})})]})})]})}),FT=k.observer(()=>{const e=ce().editor,t=e.path;return MT(t)?i(VT,{}):AT(t)?i(ok,{}):zT(t)?i(s.Box,{p:"xs",pl:20,children:i(sk,{id:t[1]})}):ET(t)?i(qT,{}):$T(t)?i(yT,{id:t[1]}):OT(t)?i(NT,{}):LT(t)?i(fT,{id:t[1]}):PT(t)?i(s.Box,{p:"xs",pl:20,children:i(IT,{id:t[1]})}):BT(t)?i(Pk,{viewID:t[1],panelID:t[3]}):i(s.Box,{children:e.path})}),GT=k.observer(()=>i(FT,{})),WT=k.observer(()=>{const e=ce(),t=()=>{const n=new Date().getTime().toString(),r={id:n,key:n,label:n,order:e.content.filters.current.length+1,type:_e.TextInput,config:tl(),visibleInViewsIDs:["Main"],auto_submit:!1};e.content.filters.append(r),e.editor.setPath(["_FILTERS_",n])};return i(s.Button,{variant:"subtle",leftIcon:i($.IconPlus,{size:14}),size:"sm",px:"xs",mb:10,color:"blue",onClick:t,sx:{width:"100%",borderRadius:0},styles:{inner:{justifyContent:"flex-start"}},children:"Add a Filter"})}),jT=k.observer(({parentID:e})=>{const t=le();if(!e)return null;const n=t.views.findByID(e);return!n||n.type===j.Tabs?null:i(s.Button,{variant:"subtle",leftIcon:i($.IconPlus,{size:14}),size:"sm",px:"xs",mb:10,color:"blue",onClick:()=>t.addANewPanel(n.id),sx:{width:"100%",borderRadius:0},styles:{inner:{justifyContent:"flex-start"}},children:"Add a Panel"})}),RT=k.observer(()=>{const e=ce(),t=()=>{const n=new Date().getTime().toString(),r={id:n,name:n,type:Se.Postgresql,key:"",sql:""};e.content.queries.append(r),e.editor.setPath(["_QUERIES_",n])};return i(s.Button,{variant:"subtle",leftIcon:i($.IconPlus,{size:14}),size:"sm",px:"xs",mb:10,color:"blue",onClick:t,sx:{width:"100%",borderRadius:0},styles:{inner:{justifyContent:"flex-start"}},children:"Add a Query"})}),YT=k.observer(()=>{const e=ce(),t=()=>{const n=new Date().getTime().toString(),r={key:n,value:""};e.content.sqlSnippets.append(r),e.editor.setPath(["_SQL_SNIPPETS_",n])};return i(s.Button,{variant:"subtle",leftIcon:i($.IconPlus,{size:14}),size:"sm",px:"xs",mb:10,color:"blue",onClick:t,sx:{width:"100%",borderRadius:0},styles:{inner:{justifyContent:"flex-start"}},children:"Add a SQL Snippet"})}),QT=k.observer(()=>{const e=le();return i(s.Button,{variant:"subtle",leftIcon:i($.IconPlus,{size:14}),size:"sm",px:"xs",mb:10,color:"blue",onClick:e.views.addARandomNewView,sx:{width:"100%",borderRadius:0},styles:{inner:{justifyContent:"flex-start"}},children:"Add a View"})}),UT=k.observer(()=>{const e=ce();return i(s.Button,{variant:"subtle",rightIcon:i($.IconSettings,{size:14}),size:"sm",px:12,mb:0,color:"blue",onClick:()=>e.editor.setPath(["_QUERIES_"]),sx:{width:"100%",borderRadius:0,fontWeight:"normal"},styles:{inner:{justifyContent:"space-between"}},children:"Manage Queries"})}),KT=k.observer(()=>{const e=ce();return i(s.Button,{variant:"subtle",rightIcon:i($.IconSettings,{size:14}),size:"sm",px:12,mb:0,color:"blue",onClick:()=>e.editor.setPath(["_SQL_SNIPPETS_"]),sx:{width:"100%",borderRadius:0,fontWeight:"normal"},styles:{inner:{justifyContent:"space-between"}},children:"Manage SQL Snippets"})}),XT=k.observer(({action_type:e,parentID:t})=>e==="_Add_A_Filter_"?i(WT,{}):e==="_Add_A_SQL_SNIPPET_"?i(YT,{}):e==="_Add_A_QUERY_"?i(RT,{}):e==="_Add_A_VIEW_"?i(QT,{}):e==="_Add_A_PANEL_"?i(jT,{parentID:t}):e==="_QUERIES_SETTINGS_"?i(UT,{}):e==="_SQL_SNIPPETS_SETTINGS_"?i(KT,{}):null),pu=k.observer(({option:e})=>{var d;const t=ce().editor,n=t.isOptionActive,r=n(t.path,e),a=t.isOptionOpened,o=t.navigate,l=a(e),[u,c]=b.useState(l);return b.useEffect(()=>{c(l)},[l]),i(s.NavLink,{active:r,defaultOpened:l,opened:u,onChange:c,label:e.label,onClick:()=>o(e),icon:e.Icon?i(e.Icon,{size:18}):null,children:(d=e.children)==null?void 0:d.map(f=>f._type==="ACTION"?i(XT,{action_type:f._action_type,parentID:f.parentID},`_ADD_${f.value}_`):i(pu,{option:f},f.value))},e.label)}),JT=k.observer(()=>{const e=ce();return i(s.Box,{sx:{position:"relative"},children:e.editor.navOptions.map(t=>i(pu,{option:t},t.value))})}),ZT=k.observer(()=>{const e=ce();return p(s.Navbar,{p:0,width:{base:220,xs:220,sm:240,md:260,lg:300,xl:320},sx:{height:"100vh - 60px - 60px"},children:[i(s.Navbar.Section,{pt:9,pb:8,sx:{borderBottom:"1px solid #eee"},children:i(s.Text,{align:"center",sx:{userSelect:"none",cursor:"default"},children:"Settings"})}),i(s.Navbar.Section,{grow:!0,sx:{overflow:"auto"},children:i(JT,{})}),i(s.Navbar.Section,{children:i(s.Group,{grow:!0,p:"md",pt:"sm",sx:{borderTop:"1px solid #eee"},children:i(s.Button,{size:"xs",color:"red",leftIcon:i($.IconX,{size:18}),onClick:()=>e.editor.close(),children:"Close"})})})]})}),HT={root:{height:"100vh",display:"flex",flexDirection:"column",overflow:"hidden"},body:{flexGrow:1,nav:{top:0,height:"100vh"}},main:{flexGrow:1,display:"flex",flexDirection:"column",paddingTop:0,height:"100vh"}},eD=k.observer(()=>{const e=ce().editor;return i(s.Modal,{onClose:()=>e.setSettingsOpen(!1),closeOnEscape:!1,closeOnClickOutside:!1,opened:e.settings_open,fullScreen:!0,title:null,transitionProps:{duration:0},withCloseButton:!1,withinPortal:!0,zIndex:300,styles:{body:{padding:"0 !important"}},children:i(s.AppShell,{padding:0,navbar:i(ZT,{}),styles:HT,children:i(GT,{})})})}),tD=e=>e.replace(/([^:])(\/\/+)/g,"$1/");function nD(e){b.useEffect(()=>{if(Ae.loader.__getMonacoInstance())return;console.log("loading monaco for @devtable/dashboard");const n=tD(e);Ae.loader.config({paths:{vs:n}}),Ae.loader.init().then(r=>console.log("monaco instance:",r))},[])}ao();const rD={root:{height:"100vh",display:"flex",flexDirection:"column",overflow:"hidden"},body:{flexGrow:1},main:{flexGrow:1,display:"flex",flexDirection:"column",paddingTop:60+30,height:"100vh"}},iD=({context:e,dashboard:t,content:n,update:r,className:a="dashboard",config:o,onChange:l,headerSlot:u},c)=>{nD(o.monacoPath),Ka(o);const{data:d=[]}=K.useRequest(mr),{data:f=[]}=K.useRequest(Xa),h=b.useMemo(()=>Ql(t,n,d,f,e),[t,n]);b.useImperativeHandle(c,()=>h,[h]),Ul(h.content,!0),b.useEffect(()=>{h.context.replace(e)},[e]),b.useEffect(()=>{h.datasources.replace(d)},[d]),b.useEffect(()=>{h.globalSQLSnippets.replace(f)},[f]),b.useEffect(()=>te.reaction(()=>te.toJS(h.json),w=>{l==null||l(w)}),[h]);const g=async()=>{await r(h.json,h.content.json)},m=K.useCreation(Si,[]),C=Kl(m);return i(We.ModalsProvider,{children:i(vr,{value:h,children:i(Cr,{value:h.content,children:i(kn.Provider,{value:{inEditMode:!0},children:i(ut.Provider,{value:m,children:p(er,{configure:C,children:[i(s.AppShell,{padding:0,header:i(b_,{saveDashboardChanges:g,headerSlot:u}),navbar:i(R_,{}),styles:rD,children:i(s.Box,{className:`${a} dashboard-root`,sx:{position:"relative"},children:h.content.views.visibleViews.map(w=>i(Pl,{view:w},w.id))})}),i(eD,{})]})})})})})})},aD=k.observer(b.forwardRef(iD)),pM="",hu=y.types.model({id:y.types.string,name:y.types.string,dashboard_id:y.types.string,create_time:y.types.string,update_time:y.types.string,version:y.types.string,filters:fl,queries:wl,sqlSnippets:Cl,views:cl,panels:pl,mock_context:Qo}).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,definition:{queries:e.queries.json,sqlSnippets:e.sqlSnippets.json,mock_context:e.mock_context.current}}}},get payloadForSQL(){const t=y.getParent(e).context.current,n=y.getParent(e).globalSQLSnippets,r={context:{...e.mock_context.current,...t},filters:e.filters.values};return{...r,sql_snippets:rr(e.sqlSnippets.current,"key","value",r),global_sql_snippets:rr(n.list,"id","content",r)}},get payloadForViz(){const t=y.getParent(e).context.current;return{context:{...e.mock_context.current,...t},filters:e.filters.values}},get data(){return e.queries.current.map(({id:n,data:r})=>({id:n,data:r})).reduce((n,r)=>(n[r.id]=r.data,n),{})},getDataStuffByID(t){const n=e.queries.findByID(t);return n?{data:n.data,len:n.data.length,state:n.state,error:n.error}:{data:[],len:0,state:"idle",error:void 0}}})).actions(e=>({}));function sD({id:e,name:t,dashboard_id:n,create_time:r,update_time:a,content:o}){if(!o)throw new Error("unexpected null content when creating a content model");const{version:l,filters:u,views:c,panels:d,definition:{queries:f,sqlSnippets:h,mock_context:g={}}}=o;return hu.create({id:e,name:t,dashboard_id:n,create_time:r,update_time:a,version:l,filters:gl(u),queries:mS(f),sqlSnippets:bS(h),mock_context:Uo(g),views:aS(c),panels:{list:d}})}const oD=y.types.model({id:y.types.identifier,name:y.types.string,group:y.types.string,content:hu,content_id:y.types.string,datasources:nS,globalSQLSnippets:ll,context:Di});function lD({id:e,name:t,group:n,content_id:r},a,o,l,u){return oD.create({id:e,name:t,group:n,content_id:r,content:sD(a),datasources:{list:o},globalSQLSnippets:{list:l},context:ul(u)})}ao();const uD=k.observer(({context:e,dashboard:t,content:n,className:r="dashboard",config:a,fullScreenPanelID:o,setFullScreenPanelID:l})=>{Ka(a);const{data:u=[]}=K.useRequest(mr),{data:c=[]}=K.useRequest(Xa),d=b.useMemo(()=>lD(t,n,u,c,e),[t,n]);Ul(d.content,!1),b.useEffect(()=>{d.context.replace(e)},[e]),b.useEffect(()=>{d.datasources.replace(u)},[u]),b.useEffect(()=>{d.globalSQLSnippets.replace(c)},[c]);const f=K.useCreation(Si,[]),h=Kl(f);return i(We.ModalsProvider,{children:i(vr,{value:d,children:i(Cr,{value:d.content,children:i(_r.Provider,{value:{fullScreenPanelID:o,setFullScreenPanelID:l},children:i(kn.Provider,{value:{inEditMode:!1},children:i(s.Box,{className:`${r} dashboard-root`,children:i(ut.Provider,{value:f,children:i(er,{configure:h,children:d.content.views.visibleViews.map(g=>i(ar,{view:g},g.id))})})})})})})})})});var Gi={},cD={get exports(){return Gi},set exports(e){Gi=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){var a=r.prototype,o=a.format;a.format=function(l){var u=this,c=this.$locale();if(!this.isValid())return o.bind(this)(l);var d=this.$utils(),f=(l||"YYYY-MM-DDTHH:mm:ssZ").replace(/\[([^\]]+)]|Q|wo|ww|w|WW|W|zzz|z|gggg|GGGG|Do|X|x|k{1,2}|S/g,function(h){switch(h){case"Q":return Math.ceil((u.$M+1)/3);case"Do":return c.ordinal(u.$D);case"gggg":return u.weekYear();case"GGGG":return u.isoWeekYear();case"wo":return c.ordinal(u.week(),"W");case"w":case"ww":return d.s(u.week(),h==="w"?1:2,"0");case"W":case"WW":return d.s(u.isoWeek(),h==="W"?1:2,"0");case"k":case"kk":return d.s(String(u.$H===0?24:u.$H),h==="k"?1:2,"0");case"X":return Math.floor(u.$d.getTime()/1e3);case"x":return u.$d.getTime();case"z":return"["+u.offsetName()+"]";case"zzz":return"["+u.offsetName("long")+"]";default:return h}});return o.bind(this)(f)}}})})(cD);const dD=Gi;var Wi={},pD={get exports(){return Wi},set exports(e){Wi=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){var o=r.prototype,l=function(c){var d=c.date,f=c.utc;return Array.isArray(d)?f?d.length?new Date(Date.UTC.apply(null,d)):new Date:d.length===1?a(String(d[0])).toDate():new(Function.prototype.bind.apply(Date,[null].concat(d))):d},u=o.parse;o.parse=function(c){c.date=l.bind(this)(c),u.bind(this)(c)}}})})(pD);const hD=Wi;var ji={},fD={get exports(){return ji},set exports(e){ji=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){var a=r.prototype,o=a.format;a.format=function(l){var u=this,c=(l||"YYYY-MM-DDTHH:mm:ssZ").replace(/(\[[^\]]+])|BBBB|BB/g,function(d,f){var h,g=String(u.$y+543),m=d==="BB"?[g.slice(-2),2]:[g,4];return f||(h=u.$utils()).s.apply(h,m.concat(["0"]))});return o.bind(this)(c)}}})})(fD);const gD=ji;var Ri={},mD={get exports(){return Ri},set exports(e){Ri=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){var o="h:mm A",l={lastDay:"[Yesterday at] "+o,sameDay:"[Today at] "+o,nextDay:"[Tomorrow at] "+o,nextWeek:"dddd [at] "+o,lastWeek:"[Last] dddd [at] "+o,sameElse:"MM/DD/YYYY"};r.prototype.calendar=function(u,c){var d=c||this.$locale().calendar||l,f=a(u||void 0).startOf("d"),h=this.diff(f,"d",!0),g="sameElse",m=h<-6?g:h<-1?"lastWeek":h<0?"lastDay":h<1?"sameDay":h<2?"nextDay":h<7?"nextWeek":g,C=d[m]||l[m];return typeof C=="function"?C.call(this,a()):this.format(C)}}})})(mD);const yD=Ri;var Yi={},bD={get exports(){return Yi},set exports(e){Yi=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){var n={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},r=/(\[[^[]*\])|([-_:/.,()\s]+)|(A|a|YYYY|YY?|MM?M?M?|Do|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g,a=/\d\d/,o=/\d\d?/,l=/\d*[^-_:/,()\s\d]+/,u={},c=function(w){return(w=+w)+(w>68?1900:2e3)},d=function(w){return function(_){this[w]=+_}},f=[/[+-]\d\d:?(\d\d)?|Z/,function(w){(this.zone||(this.zone={})).offset=function(_){if(!_||_==="Z")return 0;var D=_.match(/([+-]|\d\d)/g),M=60*D[1]+(+D[2]||0);return M===0?0:D[0]==="+"?-M:M}(w)}],h=function(w){var _=u[w];return _&&(_.indexOf?_:_.s.concat(_.f))},g=function(w,_){var D,M=u.meridiem;if(M){for(var P=1;P<=24;P+=1)if(w.indexOf(M(P,0,_))>-1){D=P>12;break}}else D=w===(_?"pm":"PM");return D},m={A:[l,function(w){this.afternoon=g(w,!1)}],a:[l,function(w){this.afternoon=g(w,!0)}],S:[/\d/,function(w){this.milliseconds=100*+w}],SS:[a,function(w){this.milliseconds=10*+w}],SSS:[/\d{3}/,function(w){this.milliseconds=+w}],s:[o,d("seconds")],ss:[o,d("seconds")],m:[o,d("minutes")],mm:[o,d("minutes")],H:[o,d("hours")],h:[o,d("hours")],HH:[o,d("hours")],hh:[o,d("hours")],D:[o,d("day")],DD:[a,d("day")],Do:[l,function(w){var _=u.ordinal,D=w.match(/\d+/);if(this.day=D[0],_)for(var M=1;M<=31;M+=1)_(M).replace(/\[|\]/g,"")===w&&(this.day=M)}],M:[o,d("month")],MM:[a,d("month")],MMM:[l,function(w){var _=h("months"),D=(h("monthsShort")||_.map(function(M){return M.slice(0,3)})).indexOf(w)+1;if(D<1)throw new Error;this.month=D%12||D}],MMMM:[l,function(w){var _=h("months").indexOf(w)+1;if(_<1)throw new Error;this.month=_%12||_}],Y:[/[+-]?\d+/,d("year")],YY:[a,function(w){this.year=c(w)}],YYYY:[/\d{4}/,d("year")],Z:f,ZZ:f};function C(w){var _,D;_=w,D=u&&u.formats;for(var M=(w=_.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,function(X,Q,H){var oe=H&&H.toUpperCase();return Q||D[H]||n[H]||D[oe].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(ue,be,Ee){return be||Ee.slice(1)})})).match(r),P=M.length,G=0;G<P;G+=1){var L=M[G],z=m[L],A=z&&z[0],F=z&&z[1];M[G]=F?{regex:A,parser:F}:L.replace(/^\[|\]$/g,"")}return function(X){for(var Q={},H=0,oe=0;H<P;H+=1){var ue=M[H];if(typeof ue=="string")oe+=ue.length;else{var be=ue.regex,Ee=ue.parser,ge=X.slice(oe),ve=be.exec(ge)[0];Ee.call(Q,ve),X=X.replace(ve,"")}}return function(me){var Oe=me.afternoon;if(Oe!==void 0){var He=me.hours;Oe?He<12&&(me.hours+=12):He===12&&(me.hours=0),delete me.afternoon}}(Q),Q}}return function(w,_,D){D.p.customParseFormat=!0,w&&w.parseTwoDigitYear&&(c=w.parseTwoDigitYear);var M=_.prototype,P=M.parse;M.parse=function(G){var L=G.date,z=G.utc,A=G.args;this.$u=z;var F=A[1];if(typeof F=="string"){var X=A[2]===!0,Q=A[3]===!0,H=X||Q,oe=A[2];Q&&(oe=A[2]),u=this.$locale(),!X&&oe&&(u=D.Ls[oe]),this.$d=function(ge,ve,me){try{if(["x","X"].indexOf(ve)>-1)return new Date((ve==="X"?1e3:1)*ge);var Oe=C(ve)(ge),He=Oe.year,$t=Oe.month,ur=Oe.day,cr=Oe.hours,wa=Oe.minutes,Ca=Oe.seconds,fn=Oe.milliseconds,Rt=Oe.zone,wt=new Date,Lt=ur||(He||$t?1:wt.getDate()),Ct=He||wt.getFullYear(),Yt=0;He&&!$t||(Yt=$t>0?$t-1:wt.getMonth());var Qt=cr||0,gn=wa||0,mn=Ca||0,St=fn||0;return Rt?new Date(Date.UTC(Ct,Yt,Lt,Qt,gn,mn,St+60*Rt.offset*1e3)):me?new Date(Date.UTC(Ct,Yt,Lt,Qt,gn,mn,St)):new Date(Ct,Yt,Lt,Qt,gn,mn,St)}catch{return new Date("")}}(L,F,z),this.init(),oe&&oe!==!0&&(this.$L=this.locale(oe).$L),H&&L!=this.format(F)&&(this.$d=new Date("")),u={}}else if(F instanceof Array)for(var ue=F.length,be=1;be<=ue;be+=1){A[1]=F[be-1];var Ee=D.apply(this,A);if(Ee.isValid()){this.$d=Ee.$d,this.$L=Ee.$L,this.init();break}be===ue&&(this.$d=new Date(""))}else P.call(this,G)}}})})(bD);const vD=Yi;var Qi={},xD={get exports(){return Qi},set exports(e){Qi=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){r.prototype.dayOfYear=function(o){var l=Math.round((a(this).startOf("day")-a(this).startOf("year"))/864e5)+1;return o==null?l:this.add(o-l,"day")}}})})(xD);const wD=Qi;var Ui={},CD={get exports(){return Ui},set exports(e){Ui=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){var n,r,a=1e3,o=6e4,l=36e5,u=864e5,c=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,d=31536e6,f=2592e6,h=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/,g={years:d,months:f,days:u,hours:l,minutes:o,seconds:a,milliseconds:1,weeks:6048e5},m=function(L){return L instanceof G},C=function(L,z,A){return new G(L,A,z.$l)},w=function(L){return r.p(L)+"s"},_=function(L){return L<0},D=function(L){return _(L)?Math.ceil(L):Math.floor(L)},M=function(L){return Math.abs(L)},P=function(L,z){return L?_(L)?{negative:!0,format:""+M(L)+z}:{negative:!1,format:""+L+z}:{negative:!1,format:""}},G=function(){function L(A,F,X){var Q=this;if(this.$d={},this.$l=X,A===void 0&&(this.$ms=0,this.parseFromMilliseconds()),F)return C(A*g[w(F)],this);if(typeof A=="number")return this.$ms=A,this.parseFromMilliseconds(),this;if(typeof A=="object")return Object.keys(A).forEach(function(ue){Q.$d[w(ue)]=A[ue]}),this.calMilliseconds(),this;if(typeof A=="string"){var H=A.match(h);if(H){var oe=H.slice(2).map(function(ue){return ue!=null?Number(ue):0});return this.$d.years=oe[0],this.$d.months=oe[1],this.$d.weeks=oe[2],this.$d.days=oe[3],this.$d.hours=oe[4],this.$d.minutes=oe[5],this.$d.seconds=oe[6],this.calMilliseconds(),this}}return this}var z=L.prototype;return z.calMilliseconds=function(){var A=this;this.$ms=Object.keys(this.$d).reduce(function(F,X){return F+(A.$d[X]||0)*g[X]},0)},z.parseFromMilliseconds=function(){var A=this.$ms;this.$d.years=D(A/d),A%=d,this.$d.months=D(A/f),A%=f,this.$d.days=D(A/u),A%=u,this.$d.hours=D(A/l),A%=l,this.$d.minutes=D(A/o),A%=o,this.$d.seconds=D(A/a),A%=a,this.$d.milliseconds=A},z.toISOString=function(){var A=P(this.$d.years,"Y"),F=P(this.$d.months,"M"),X=+this.$d.days||0;this.$d.weeks&&(X+=7*this.$d.weeks);var Q=P(X,"D"),H=P(this.$d.hours,"H"),oe=P(this.$d.minutes,"M"),ue=this.$d.seconds||0;this.$d.milliseconds&&(ue+=this.$d.milliseconds/1e3);var be=P(ue,"S"),Ee=A.negative||F.negative||Q.negative||H.negative||oe.negative||be.negative,ge=H.format||oe.format||be.format?"T":"",ve=(Ee?"-":"")+"P"+A.format+F.format+Q.format+ge+H.format+oe.format+be.format;return ve==="P"||ve==="-P"?"P0D":ve},z.toJSON=function(){return this.toISOString()},z.format=function(A){var F=A||"YYYY-MM-DDTHH:mm:ss",X={Y:this.$d.years,YY:r.s(this.$d.years,2,"0"),YYYY:r.s(this.$d.years,4,"0"),M:this.$d.months,MM:r.s(this.$d.months,2,"0"),D:this.$d.days,DD:r.s(this.$d.days,2,"0"),H:this.$d.hours,HH:r.s(this.$d.hours,2,"0"),m:this.$d.minutes,mm:r.s(this.$d.minutes,2,"0"),s:this.$d.seconds,ss:r.s(this.$d.seconds,2,"0"),SSS:r.s(this.$d.milliseconds,3,"0")};return F.replace(c,function(Q,H){return H||String(X[Q])})},z.as=function(A){return this.$ms/g[w(A)]},z.get=function(A){var F=this.$ms,X=w(A);return X==="milliseconds"?F%=1e3:F=X==="weeks"?D(F/g[X]):this.$d[X],F===0?0:F},z.add=function(A,F,X){var Q;return Q=F?A*g[w(F)]:m(A)?A.$ms:C(A,this).$ms,C(this.$ms+Q*(X?-1:1),this)},z.subtract=function(A,F){return this.add(A,F,!0)},z.locale=function(A){var F=this.clone();return F.$l=A,F},z.clone=function(){return C(this.$ms,this)},z.humanize=function(A){return n().add(this.$ms,"ms").locale(this.$l).fromNow(!A)},z.milliseconds=function(){return this.get("milliseconds")},z.asMilliseconds=function(){return this.as("milliseconds")},z.seconds=function(){return this.get("seconds")},z.asSeconds=function(){return this.as("seconds")},z.minutes=function(){return this.get("minutes")},z.asMinutes=function(){return this.as("minutes")},z.hours=function(){return this.get("hours")},z.asHours=function(){return this.as("hours")},z.days=function(){return this.get("days")},z.asDays=function(){return this.as("days")},z.weeks=function(){return this.get("weeks")},z.asWeeks=function(){return this.as("weeks")},z.months=function(){return this.get("months")},z.asMonths=function(){return this.as("months")},z.years=function(){return this.get("years")},z.asYears=function(){return this.as("years")},L}();return function(L,z,A){n=A,r=A().$utils(),A.duration=function(Q,H){var oe=A.locale();return C(Q,{$l:oe},H)},A.isDuration=m;var F=z.prototype.add,X=z.prototype.subtract;z.prototype.add=function(Q,H){return m(Q)&&(Q=Q.asMilliseconds()),F.bind(this)(Q,H)},z.prototype.subtract=function(Q,H){return m(Q)&&(Q=Q.asMilliseconds()),X.bind(this)(Q,H)}}})})(CD);const SD=Ui;var Ki={},_D={get exports(){return Ki},set exports(e){Ki=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){r.prototype.isBetween=function(o,l,u,c){var d=a(o),f=a(l),h=(c=c||"()")[0]==="(",g=c[1]===")";return(h?this.isAfter(d,u):!this.isBefore(d,u))&&(g?this.isBefore(f,u):!this.isAfter(f,u))||(h?this.isBefore(d,u):!this.isAfter(d,u))&&(g?this.isAfter(f,u):!this.isBefore(f,u))}}})})(_D);const kD=Ki;var Xi={},TD={get exports(){return Xi},set exports(e){Xi=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){r.prototype.isLeapYear=function(){return this.$y%4==0&&this.$y%100!=0||this.$y%400==0}}})})(TD);const DD=Xi;var Ji={},ID={get exports(){return Ji},set exports(e){Ji=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){a.isMoment=function(o){return a.isDayjs(o)}}})})(ID);const MD=Ji;var Zi={},AD={get exports(){return Zi},set exports(e){Zi=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){var n="day";return function(r,a,o){var l=function(d){return d.add(4-d.isoWeekday(),n)},u=a.prototype;u.isoWeekYear=function(){return l(this).year()},u.isoWeek=function(d){if(!this.$utils().u(d))return this.add(7*(d-this.isoWeek()),n);var f,h,g,m,C=l(this),w=(f=this.isoWeekYear(),h=this.$u,g=(h?o.utc:o)().year(f).startOf("year"),m=4-g.isoWeekday(),g.isoWeekday()>4&&(m+=7),g.add(m,n));return C.diff(w,"week")+1},u.isoWeekday=function(d){return this.$utils().u(d)?this.day()||7:this.day(this.day()%7?d:d-7)};var c=u.startOf;u.startOf=function(d,f){var h=this.$utils(),g=!!h.u(f)||f;return h.p(d)==="isoweek"?g?this.date(this.date()-(this.isoWeekday()-1)).startOf("day"):this.date(this.date()-1-(this.isoWeekday()-1)+7).endOf("day"):c.bind(this)(d,f)}}})})(AD);const zD=Zi;var Hi={},ED={get exports(){return Hi},set exports(e){Hi=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){r.prototype.isoWeeksInYear=function(){var a=this.isLeapYear(),o=this.endOf("y").day();return o===4||a&&o===5?53:52}}})})(ED);const $D=Hi;var ea={},LD={get exports(){return ea},set exports(e){ea=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){r.prototype.isSameOrAfter=function(a,o){return this.isSame(a,o)||this.isAfter(a,o)}}})})(LD);const OD=ea;var ta={},PD={get exports(){return ta},set exports(e){ta=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){r.prototype.isSameOrBefore=function(a,o){return this.isSame(a,o)||this.isBefore(a,o)}}})})(PD);const BD=ta;var na={},VD={get exports(){return na},set exports(e){na=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){r.prototype.isToday=function(){var o="YYYY-MM-DD",l=a();return this.format(o)===l.format(o)}}})})(VD);const ND=na;var ra={},qD={get exports(){return ra},set exports(e){ra=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){r.prototype.isTomorrow=function(){var o="YYYY-MM-DD",l=a().add(1,"day");return this.format(o)===l.format(o)}}})})(qD);const FD=ra;var ia={},GD={get exports(){return ia},set exports(e){ia=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){r.prototype.isYesterday=function(){var o="YYYY-MM-DD",l=a().subtract(1,"day");return this.format(o)===l.format(o)}}})})(GD);const WD=ia;var aa={},jD={get exports(){return aa},set exports(e){aa=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){var o=r.prototype,l=function(h){return h&&(h.indexOf?h:h.s)},u=function(h,g,m,C,w){var _=h.name?h:h.$locale(),D=l(_[g]),M=l(_[m]),P=D||M.map(function(L){return L.slice(0,C)});if(!w)return P;var G=_.weekStart;return P.map(function(L,z){return P[(z+(G||0))%7]})},c=function(){return a.Ls[a.locale()]},d=function(h,g){return h.formats[g]||function(m){return m.replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(C,w,_){return w||_.slice(1)})}(h.formats[g.toUpperCase()])},f=function(){var h=this;return{months:function(g){return g?g.format("MMMM"):u(h,"months")},monthsShort:function(g){return g?g.format("MMM"):u(h,"monthsShort","months",3)},firstDayOfWeek:function(){return h.$locale().weekStart||0},weekdays:function(g){return g?g.format("dddd"):u(h,"weekdays")},weekdaysMin:function(g){return g?g.format("dd"):u(h,"weekdaysMin","weekdays",2)},weekdaysShort:function(g){return g?g.format("ddd"):u(h,"weekdaysShort","weekdays",3)},longDateFormat:function(g){return d(h.$locale(),g)},meridiem:this.$locale().meridiem,ordinal:this.$locale().ordinal}};o.localeData=function(){return f.bind(this)()},a.localeData=function(){var h=c();return{firstDayOfWeek:function(){return h.weekStart||0},weekdays:function(){return a.weekdays()},weekdaysShort:function(){return a.weekdaysShort()},weekdaysMin:function(){return a.weekdaysMin()},months:function(){return a.months()},monthsShort:function(){return a.monthsShort()},longDateFormat:function(g){return d(h,g)},meridiem:h.meridiem,ordinal:h.ordinal}},a.months=function(){return u(c(),"months")},a.monthsShort=function(){return u(c(),"monthsShort","months",3)},a.weekdays=function(h){return u(c(),"weekdays",null,null,h)},a.weekdaysShort=function(h){return u(c(),"weekdaysShort","weekdays",3,h)},a.weekdaysMin=function(h){return u(c(),"weekdaysMin","weekdays",2,h)}}})})(jD);const RD=aa;var sa={},YD={get exports(){return sa},set exports(e){sa=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){var n={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"};return function(r,a,o){var l=a.prototype,u=l.format;o.en.formats=n,l.format=function(c){c===void 0&&(c="YYYY-MM-DDTHH:mm:ssZ");var d=this.$locale().formats,f=function(h,g){return h.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,function(m,C,w){var _=w&&w.toUpperCase();return C||g[w]||n[w]||g[_].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(D,M,P){return M||P.slice(1)})})}(c,d===void 0?{}:d);return u.call(this,f)}}})})(YD);const QD=sa;var oa={},UD={get exports(){return oa},set exports(e){oa=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){var o=function(l,u){if(!u||!u.length||!u[0]||u.length===1&&!u[0].length)return null;var c;u.length===1&&u[0].length>0&&(u=u[0]),c=u[0];for(var d=1;d<u.length;d+=1)u[d].isValid()&&!u[d][l](c)||(c=u[d]);return c};a.max=function(){var l=[].slice.call(arguments,0);return o("isAfter",l)},a.min=function(){var l=[].slice.call(arguments,0);return o("isBefore",l)}}})})(UD);const KD=oa;var la={},XD={get exports(){return la},set exports(e){la=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){var o=r.prototype,l=function(g){var m,C=g.date,w=g.utc,_={};if(!((m=C)instanceof Date||m instanceof Array||o.$utils().u(m)||m.constructor.name!=="Object")){if(!Object.keys(C).length)return new Date;var D=w?a.utc():a();Object.keys(C).forEach(function(X){var Q,H;_[Q=X,H=o.$utils().p(Q),H==="date"?"day":H]=C[X]});var M=_.day||(_.year||_.month>=0?1:D.date()),P=_.year||D.year(),G=_.month>=0?_.month:_.year||_.day?0:D.month(),L=_.hour||0,z=_.minute||0,A=_.second||0,F=_.millisecond||0;return w?new Date(Date.UTC(P,G,M,L,z,A,F)):new Date(P,G,M,L,z,A,F)}return C},u=o.parse;o.parse=function(g){g.date=l.bind(this)(g),u.bind(this)(g)};var c=o.set,d=o.add,f=o.subtract,h=function(g,m,C,w){w===void 0&&(w=1);var _=Object.keys(m),D=this;return _.forEach(function(M){D=g.bind(D)(m[M]*w,M)}),D};o.set=function(g,m){return m=m===void 0?g:m,g.constructor.name==="Object"?h.bind(this)(function(C,w){return c.bind(this)(w,C)},m,g):c.bind(this)(g,m)},o.add=function(g,m){return g.constructor.name==="Object"?h.bind(this)(d,g,m):d.bind(this)(g,m)},o.subtract=function(g,m){return g.constructor.name==="Object"?h.bind(this)(d,g,m,-1):f.bind(this)(g,m)}}})})(XD);const JD=la;var ua={},ZD={get exports(){return ua},set exports(e){ua=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){var a=r.prototype;["milliseconds","seconds","minutes","hours","days","weeks","isoWeeks","months","quarters","years","dates"].forEach(function(o){a[o]=a[o.replace(/s$/,"")]})}})})(ZD);const HD=ua;var ca={},eI={get exports(){return ca},set exports(e){ca=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){var a=r.prototype.parse;r.prototype.parse=function(u){if(typeof u.date=="string"){var c=this.$locale();u.date=c&&c.preparse?c.preparse(u.date):u.date}return a.bind(this)(u)};var o=r.prototype.format;r.prototype.format=function(){for(var u=arguments.length,c=new Array(u),d=0;d<u;d++)c[d]=arguments[d];var f=o.call.apply(o,[this].concat(c)),h=this.$locale();return h&&h.postformat?h.postformat(f):f};var l=r.prototype.fromToBase;l&&(r.prototype.fromToBase=function(u,c,d,f){var h=this.$locale()||d.$locale();return l.call(this,u,c,d,f,h&&h.postformat)})}})})(eI);const tI=ca;var da={},nI={get exports(){return da},set exports(e){da=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){var n="month",r="quarter";return function(a,o){var l=o.prototype;l.quarter=function(d){return this.$utils().u(d)?Math.ceil((this.month()+1)/3):this.month(this.month()%3+3*(d-1))};var u=l.add;l.add=function(d,f){return d=Number(d),this.$utils().p(f)===r?this.add(3*d,n):u.bind(this)(d,f)};var c=l.startOf;l.startOf=function(d,f){var h=this.$utils(),g=!!h.u(f)||f;if(h.p(d)===r){var m=this.quarter()-1;return g?this.month(3*m).startOf(n).startOf("day"):this.month(3*m+2).endOf(n).endOf("day")}return c.bind(this)(d,f)}}})})(nI);const rI=da;var pa={},iI={get exports(){return pa},set exports(e){pa=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){n=n||{};var o=r.prototype,l={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function u(d,f,h,g){return o.fromToBase(d,f,h,g)}a.en.relativeTime=l,o.fromToBase=function(d,f,h,g,m){for(var C,w,_,D=h.$locale().relativeTime||l,M=n.thresholds||[{l:"s",r:44,d:"second"},{l:"m",r:89},{l:"mm",r:44,d:"minute"},{l:"h",r:89},{l:"hh",r:21,d:"hour"},{l:"d",r:35},{l:"dd",r:25,d:"day"},{l:"M",r:45},{l:"MM",r:10,d:"month"},{l:"y",r:17},{l:"yy",d:"year"}],P=M.length,G=0;G<P;G+=1){var L=M[G];L.d&&(C=g?a(d).diff(h,L.d,!0):h.diff(d,L.d,!0));var z=(n.rounding||Math.round)(Math.abs(C));if(_=C>0,z<=L.r||!L.r){z<=1&&G>0&&(L=M[G-1]);var A=D[L.l];m&&(z=m(""+z)),w=typeof A=="string"?A.replace("%d",z):A(z,f,L.l,_);break}}if(f)return w;var F=_?D.future:D.past;return typeof F=="function"?F(w):F.replace("%s",w)},o.to=function(d,f){return u(d,f,this,!0)},o.from=function(d,f){return u(d,f,this)};var c=function(d){return d.$u?a.utc():a()};o.toNow=function(d){return this.to(c(this),d)},o.fromNow=function(d){return this.from(c(this),d)}}})})(iI);const aI=pa;var ha={},sI={get exports(){return ha},set exports(e){ha=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){var n={year:0,month:1,day:2,hour:3,minute:4,second:5},r={};return function(a,o,l){var u,c=function(g,m,C){C===void 0&&(C={});var w=new Date(g),_=function(D,M){M===void 0&&(M={});var P=M.timeZoneName||"short",G=D+"|"+P,L=r[G];return L||(L=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:D,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:P}),r[G]=L),L}(m,C);return _.formatToParts(w)},d=function(g,m){for(var C=c(g,m),w=[],_=0;_<C.length;_+=1){var D=C[_],M=D.type,P=D.value,G=n[M];G>=0&&(w[G]=parseInt(P,10))}var L=w[3],z=L===24?0:L,A=w[0]+"-"+w[1]+"-"+w[2]+" "+z+":"+w[4]+":"+w[5]+":000",F=+g;return(l.utc(A).valueOf()-(F-=F%1e3))/6e4},f=o.prototype;f.tz=function(g,m){g===void 0&&(g=u);var C=this.utcOffset(),w=this.toDate(),_=w.toLocaleString("en-US",{timeZone:g}),D=Math.round((w-new Date(_))/1e3/60),M=l(_).$set("millisecond",this.$ms).utcOffset(15*-Math.round(w.getTimezoneOffset()/15)-D,!0);if(m){var P=M.utcOffset();M=M.add(C-P,"minute")}return M.$x.$timezone=g,M},f.offsetName=function(g){var m=this.$x.$timezone||l.tz.guess(),C=c(this.valueOf(),m,{timeZoneName:g}).find(function(w){return w.type.toLowerCase()==="timezonename"});return C&&C.value};var h=f.startOf;f.startOf=function(g,m){if(!this.$x||!this.$x.$timezone)return h.call(this,g,m);var C=l(this.format("YYYY-MM-DD HH:mm:ss:SSS"));return h.call(C,g,m).tz(this.$x.$timezone,!0)},l.tz=function(g,m,C){var w=C&&m,_=C||m||u,D=d(+l(),_);if(typeof g!="string")return l(g).tz(_);var M=function(z,A,F){var X=z-60*A*1e3,Q=d(X,F);if(A===Q)return[X,A];var H=d(X-=60*(Q-A)*1e3,F);return Q===H?[X,Q]:[z-60*Math.min(Q,H)*1e3,Math.max(Q,H)]}(l.utc(g,w).valueOf(),D,_),P=M[0],G=M[1],L=l(P).utcOffset(G);return L.$x.$timezone=_,L},l.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},l.tz.setDefault=function(g){u=g}}})})(sI);const oI=ha;var fa={},lI={get exports(){return fa},set exports(e){fa=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){r.prototype.toArray=function(){return[this.$y,this.$M,this.$D,this.$H,this.$m,this.$s,this.$ms]}}})})(lI);const uI=fa;var ga={},cI={get exports(){return ga},set exports(e){ga=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){r.prototype.toObject=function(){return{years:this.$y,months:this.$M,date:this.$D,hours:this.$H,minutes:this.$m,seconds:this.$s,milliseconds:this.$ms}}}})})(cI);const dI=ga;var ma={},pI={get exports(){return ma},set exports(e){ma=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r,a){a.updateLocale=function(o,l){var u=a.Ls[o];if(u)return(l?Object.keys(l):[]).forEach(function(c){u[c]=l[c]}),u}}})})(pI);const hI=ma;var ya={},fI={get exports(){return ya},set exports(e){ya=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){var n="minute",r=/[+-]\d\d(?::?\d\d)?/g,a=/([+-]|\d\d)/g;return function(o,l,u){var c=l.prototype;u.utc=function(w){var _={date:w,utc:!0,args:arguments};return new l(_)},c.utc=function(w){var _=u(this.toDate(),{locale:this.$L,utc:!0});return w?_.add(this.utcOffset(),n):_},c.local=function(){return u(this.toDate(),{locale:this.$L,utc:!1})};var d=c.parse;c.parse=function(w){w.utc&&(this.$u=!0),this.$utils().u(w.$offset)||(this.$offset=w.$offset),d.call(this,w)};var f=c.init;c.init=function(){if(this.$u){var w=this.$d;this.$y=w.getUTCFullYear(),this.$M=w.getUTCMonth(),this.$D=w.getUTCDate(),this.$W=w.getUTCDay(),this.$H=w.getUTCHours(),this.$m=w.getUTCMinutes(),this.$s=w.getUTCSeconds(),this.$ms=w.getUTCMilliseconds()}else f.call(this)};var h=c.utcOffset;c.utcOffset=function(w,_){var D=this.$utils().u;if(D(w))return this.$u?0:D(this.$offset)?h.call(this):this.$offset;if(typeof w=="string"&&(w=function(L){L===void 0&&(L="");var z=L.match(r);if(!z)return null;var A=(""+z[0]).match(a)||["-",0,0],F=A[0],X=60*+A[1]+ +A[2];return X===0?0:F==="+"?X:-X}(w),w===null))return this;var M=Math.abs(w)<=16?60*w:w,P=this;if(_)return P.$offset=M,P.$u=w===0,P;if(w!==0){var G=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(P=this.local().add(M+G,n)).$offset=M,P.$x.$localOffset=G}else P=this.utc();return P};var g=c.format;c.format=function(w){var _=w||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return g.call(this,_)},c.valueOf=function(){var w=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*w},c.isUTC=function(){return!!this.$u},c.toISOString=function(){return this.toDate().toISOString()},c.toString=function(){return this.toDate().toUTCString()};var m=c.toDate;c.toDate=function(w){return w==="s"&&this.$offset?u(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():m.call(this)};var C=c.diff;c.diff=function(w,_,D){if(w&&this.$u===w.$u)return C.call(this,w,_,D);var M=this.local(),P=u(w).local();return C.call(M,P,_,D)}}})})(fI);const gI=ya;var ba={},mI={get exports(){return ba},set exports(e){ba=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){r.prototype.weekday=function(a){var o=this.$locale().weekStart||0,l=this.$W,u=(l<o?l+7:l)-o;return this.$utils().u(a)?u:this.subtract(u,"day").add(a,"day")}}})})(mI);const yI=ba;var va={},bI={get exports(){return va},set exports(e){va=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){var n="week",r="year";return function(a,o,l){var u=o.prototype;u.week=function(c){if(c===void 0&&(c=null),c!==null)return this.add(7*(c-this.week()),"day");var d=this.$locale().yearStart||1;if(this.month()===11&&this.date()>25){var f=l(this).startOf(r).add(1,r).date(d),h=l(this).endOf(n);if(f.isBefore(h))return 1}var g=l(this).startOf(r).date(d).startOf(n).subtract(1,"millisecond"),m=this.diff(g,n,!0);return m<0?l(this).startOf("week").week():Math.ceil(m)},u.weeks=function(c){return c===void 0&&(c=null),this.week(c)}}})})(bI);const vI=va;var xa={},xI={get exports(){return xa},set exports(e){xa=e}};(function(e,t){(function(n,r){e.exports=r()})(re,function(){return function(n,r){r.prototype.weekYear=function(){var a=this.month(),o=this.week(),l=this.year();return o===1&&a===11?l+1:a===0&&o>=52?l-1:l}}})})(xI);const wI=xa;Y.extend(dD),Y.extend(hD),Y.extend(gD),Y.extend(yD),Y.extend(vD),Y.extend(wD),Y.extend(SD),Y.extend(kD),Y.extend(DD),Y.extend(MD),Y.extend(OD),Y.extend(BD),Y.extend(ND),Y.extend(FD),Y.extend(WD),Y.extend(zD),Y.extend($D),Y.extend(RD),Y.extend(QD),Y.extend(KD),Y.extend(JD),Y.extend(HD),Y.extend(tI),Y.extend(rI),Y.extend(aI),Y.extend(oI),Y.extend(uI),Y.extend(dI),Y.extend(hI),Y.extend(gI),Y.extend(vI),Y.extend(wI),Y.extend(yI),Y.tz.setDefault("UTC");const CI=()=>Promise.resolve().then(()=>sc).then(({version:e})=>(console.log(`[@devtable/dashboard] version: ${e}`),e));I.ContentModel=$i,I.ContentModelContextProvider=Cr,I.DashboardEditor=aD,I.DashboardFilterType=_e,I.DashboardMode=Bl,I.DashboardModel=Yl,I.DashboardModelContextProvider=vr,I.DashboardViewEditor=Pl,I.DashboardViewRender=ar,I.DescriptionPopover=Ii,I.FiltersModel=Nl,I.FullScreenPanel=zl,I.FullScreenPanelContext=_r,I.LayoutStateContext=kn,I.Panel=Al,I.PanelContextProvider=Sr,I.PanelErrorOrStateMessage=Il,I.PanelModel=Gl,I.PanelRender=Ai,I.PanelVizSection=Mi,I.PanelsModel=Wl,I.QueriesModel=ql,I.ReadOnlyDashboard=uD,I.SQLSnippetsModel=Fl,I.ViewComponentTypeBackground=Vl,I.ViewComponentTypeColor=e_,I.ViewComponentTypeName=HS,I.ViewsModel=jl,I.Viz=Dl,I.applyPartialDashboard=p_,I.createContentModel=Rl,I.createDashboardModel=Ql,I.getInitialDashboardViewsModel=Ei,I.getVersion=CI,I.initialDashboardContent=t_,I.useDashboardContext=xr,I.useEditContentModelContext=le,I.useEditDashboardContext=ce,I.useEditPanelContext=nt,I.useFullScreenPanelContext=ss,I.usePanelFullScreen=El,I.useRenderContentModelContext=we,I.useRenderDashboardContext=wr,I.useRenderPanelContext=bt,Object.defineProperty(I,Symbol.toStringTag,{value:"Module"})});