@devtable/dashboard 4.16.8 → 4.17.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.
@@ -2578,7 +2578,7 @@ const Qo = V(function({
2578
2578
  size: 20
2579
2579
  }),
2580
2580
  children: "Revert Changes"
2581
- }), /* @__PURE__ */ d(fe, {
2581
+ }), !s && /* @__PURE__ */ d(fe, {
2582
2582
  width: 180,
2583
2583
  children: [/* @__PURE__ */ i(fe.Target, {
2584
2584
  children: /* @__PURE__ */ i(O, {
@@ -3126,7 +3126,7 @@ const Fs = (e) => {
3126
3126
  getColor: Xt(["#fff7f1", "darkorange", "#b60000"]),
3127
3127
  name: "orange",
3128
3128
  category: "sequential"
3129
- }, zs = "4.16.8";
3129
+ }, zs = "4.17.0";
3130
3130
  class Ts {
3131
3131
  constructor(t) {
3132
3132
  P(this, "staticColors", /* @__PURE__ */ new Map());
@@ -12972,6 +12972,7 @@ const Lp = C.forwardRef(({
12972
12972
  },
12973
12973
  children: /* @__PURE__ */ d(B, {
12974
12974
  className: "dashboard-view",
12975
+ mx: -10,
12975
12976
  sx: {
12976
12977
  position: "relative",
12977
12978
  height: "100%"
@@ -36,7 +36,7 @@ WHERE
36
36
  -- SQL snippets
37
37
  AND \${sql_snippets.author_email_condition}
38
38
  \${sql_snippets.order_by_clause}
39
- `,Hn=E.observer(function({showSQLSnippets:t=!0,sx:n={}}){const r=Y(),i=r.context.current,l=C.default.useMemo(()=>{const s={context:i,filters:r.filters.values};if(t){const u=r.sqlSnippets.current.reduce((d,p)=>(d[p.key]=p.value,d),{});s.sql_snippets=u}return JSON.stringify(s,null,2)},[i,r.sqlSnippets.current,r.filters.values,t]);return g(a.Stack,{sx:{border:"1px solid #eee",maxWidth:"40%",overflow:"hidden",...n},children:[o(a.Group,{position:"left",pl:"md",py:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef",flexGrow:0},children:o(a.Text,{weight:500,children:"Global Variables"})}),g(a.Stack,{px:"md",pb:"md",sx:{width:"100%"},children:[o(Fe.Prism,{language:"sql",sx:{width:"100%"},noCopy:!0,colorScheme:"dark",children:wo}),o(a.Text,{weight:500,sx:{flexGrow:0},children:"Current Values"}),o(Fe.Prism,{language:"json",sx:{width:"100%"},noCopy:!0,colorScheme:"dark",children:l})]})]})});function _o({data:e}){return e.length===0?o(a.Box,{sx:{height:"5em"}}):g(a.Table,{children:[o("thead",{children:o("tr",{children:Object.keys(e==null?void 0:e[0]).map(t=>o("th",{children:o(a.Text,{weight:700,color:"#000",children:t})},t))})}),o("tbody",{children:e.slice(0,10).map((t,n)=>o("tr",{children:Object.values(t).map((r,i)=>o("td",{children:o(a.Group,{sx:{"&, .mantine-Text-root":{fontFamily:"monospace"}},children:o(a.Text,{children:r})})},`${r}--${i}`))},`row-${n}`))})]})}const Yn=E.observer(function({id:t}){const n=Y(),{data:r,state:i}=n.getDataStuffByID(t),l=i==="loading",s=()=>{n.queries.refetchDataByQueryID(t)};return g(a.Stack,{my:"xl",sx:{border:"1px solid #eee"},children:[g(a.Group,{position:"apart",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[g(a.Group,{position:"left",children:[o(a.Text,{weight:500,children:"Preview Data"}),r.length>10&&g(a.Text,{size:"sm",color:"gray",children:["Showing 10 rows of ",r.length]})]}),o(a.ActionIcon,{mr:15,variant:"subtle",color:"blue",disabled:l,onClick:s,children:o(V.Refresh,{size:15})})]}),g(a.Box,{sx:{position:"relative"},children:[o(a.LoadingOverlay,{visible:l}),o(_o,{data:r})]})]})}),Io=w.forwardRef(({label:e,type:t,...n},r)=>g(a.Group,{position:"apart",ref:r,...n,children:[o(a.Text,{children:e}),o(a.Text,{children:t})]})),Xn=E.observer(function({value:t,onChange:n}){const{data:r=[],loading:i}=j.useRequest(vo,{refreshDeps:[]},[]),l=w.useMemo(()=>r.map(u=>({label:u.key,value:u.key,type:u.type})),[r]),s=w.useMemo(()=>l.reduce((u,d)=>(u[d.value]=d.type,u),{}),[l]);return o(a.Select,{label:"Data Source",data:l,itemComponent:Io,sx:{flex:1},disabled:i,value:t.key,onChange:u=>{u!==null&&n({key:u,type:s[u]})}})});function Jn({value:e}){const t=Y(),n=t.context.current,r=C.default.useMemo(()=>Bn(e,n,t.sqlSnippets.current,t.filters.values),[e,n,t.sqlSnippets.current,t.filters.values]);return o(Fe.Prism,{language:"sql",colorScheme:"light",children:r})}const Do=E.observer(function({queryModel:t,setCurrentID:n}){const r=C.default.useRef(t.id),[i,l]=C.default.useState(r.current);C.default.useEffect(()=>{r.current!==t.id&&(l(t.id),r.current=t.id)},[r,t.id]);const[s,u]=C.default.useState(t.sql);C.default.useEffect(()=>{u(f=>f!==t.sql?t.sql:f)},[t.sql]);const d=s!==t.sql,p=()=>{t.setSQL(s)},c=()=>{n(i),t.setID(i)};return g(a.Stack,{sx:{border:"1px solid #eee",flexGrow:1},children:[o(a.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:o(a.Text,{weight:500,children:"Edit Query"})}),g(a.Stack,{my:0,p:"md",pr:40,children:[g(a.Group,{grow:!0,children:[o(a.TextInput,{placeholder:"An ID unique in this dashboard",label:"ID",required:!0,sx:{flex:1},value:i,onChange:f=>{l(f.currentTarget.value)},rightSection:o(a.ActionIcon,{mr:5,variant:"filled",color:"blue",disabled:i===t.id,onClick:c,children:o(V.DeviceFloppy,{size:18})})}),o(Xn,{value:{type:t.type,key:t.key},onChange:({type:f,key:m})=>{t.setKey(m),t.setType(f)}})]}),g(a.Tabs,{defaultValue:"SQL",children:[g(a.Tabs.List,{children:[o(a.Tabs.Tab,{value:"SQL",children:"SQL"}),o(a.Tabs.Tab,{value:"Preview",children:"Preview"})]}),o(a.Tabs.Panel,{value:"SQL",pt:"sm",children:g(a.Box,{sx:{position:"relative"},children:[o(a.Textarea,{autosize:!0,minRows:12,maxRows:24,className:"code-textarea",value:s,onChange:f=>{u(f.currentTarget.value)}}),o(a.ActionIcon,{mr:5,variant:"filled",color:"blue",sx:{position:"absolute",right:10,top:10},disabled:!d,onClick:p,children:o(V.DeviceFloppy,{size:20})})]})}),o(a.Tabs.Panel,{value:"Preview",pt:"sm",children:o(Jn,{value:t.sql})})]})]})]})}),Ao=E.observer(function({id:t,setID:n}){const r=Y(),i=C.default.useMemo(()=>r.queries.findByID(t),[r.queries,t]);return t?i?o(Do,{queryModel:i,setCurrentID:n}):o("span",{children:"Invalid Query ID"}):null});var me=(e=>(e.Postgresql="postgresql",e.MySQL="mysql",e.HTTP="http",e))(me||{});const Mo=E.observer(function({id:t,setID:n}){const r=Y(),i=()=>{var s;n((s=r.queries.firstID)!=null?s:"")};C.default.useEffect(()=>{if(!t){i();return}r.queries.current.findIndex(u=>u.id===t)===-1&&i()},[t,r.queries.current,i]);const l=()=>{const s=J.randomId();r.queries.append(y.cast({id:s,type:me.Postgresql,key:"",sql:""})),n(s)};return o(a.Group,{pb:"xl",children:g(a.Group,{position:"left",sx:{maxWidth:"600px",alignItems:"baseline"},children:[o(a.Text,{children:"Select a Query"}),o(a.Select,{data:r.queries.options,value:t,onChange:n,allowDeselect:!1,clearable:!1,sx:{flexGrow:1}}),o(a.Text,{children:"or"}),o(a.Group,{position:"center",mt:"md",children:o(a.Button,{onClick:l,children:"Add a Query"})})]})})}),Vo=E.observer(function(){const[t,n]=C.default.useState("");return g(a.AppShell,{sx:{height:"90vh",maxHeight:"calc(100vh - 225px)",".mantine-AppShell-body":{height:"100%"},main:{height:"100%",width:"100%",padding:0,margin:0}},padding:"md",children:[g(a.Group,{position:"apart",grow:!0,align:"stretch",noWrap:!0,children:[g(a.Stack,{sx:{flexGrow:1,maxWidth:"calc(60% - 16px)"},children:[o(Mo,{id:t,setID:n}),o(Ao,{id:t,setID:n})]}),o(Hn,{})]}),o(Yn,{id:t})]})}),Eo=E.observer(({value:e})=>{const t=Y(),n=t.context.current,r=C.default.useMemo(()=>ho(e,n,t.filters.values),[e,n]);return g(a.Stack,{children:[o(a.Text,{children:"Preview"}),o(Fe.Prism,{language:"sql",noCopy:!0,colorScheme:"dark",children:r})]})}),Ro=E.observer(function(){const t=Y(),n=()=>t.sqlSnippets.append(y.cast({key:J.randomId(),value:""}));return g(a.Stack,{sx:{border:"1px solid #eee",flexGrow:1},children:[o(a.Group,{position:"left",pl:"md",py:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef",flexGrow:0},children:o(a.Text,{weight:500,children:"SQL Snippets"})}),o(a.Group,{px:"md",pb:"md",pt:"md",children:g(a.Stack,{sx:{width:"100%",position:"relative"},children:[t.sqlSnippets.current.map((r,i)=>g(a.Stack,{my:0,p:"md",pr:40,sx:{border:"1px solid #eee",position:"relative"},children:[o(a.TextInput,{label:"Key",required:!0,value:r.key,onChange:l=>{r.setKey(l.currentTarget.value)}}),o(a.Textarea,{minRows:3,label:"Value",required:!0,value:r.value,onChange:l=>{r.setValue(l.currentTarget.value)},className:"code-textarea"}),o(Eo,{value:r.value}),o(a.ActionIcon,{color:"red",variant:"subtle",onClick:()=>t.sqlSnippets.remove(i),sx:{position:"absolute",top:15,right:5},children:o(V.Trash,{size:16})})]},i)),o(a.Group,{position:"center",mt:"xl",grow:!0,sx:{width:"40%"},mx:"auto",children:o(a.Button,{variant:"default",onClick:n,children:"Add a snippet"})})]})})]})});function To(){return o(a.AppShell,{sx:{height:"90vh",maxHeight:"calc(100vh - 225px)",".mantine-AppShell-body":{height:"100%"},main:{height:"100%",width:"100%",padding:0,margin:0}},padding:"md",children:g(a.Group,{position:"apart",grow:!0,align:"stretch",noWrap:!0,children:[o(Ro,{}),o(Hn,{showSQLSnippets:!1})]})})}const Fo=E.observer(function({opened:t,close:n}){const{freezeLayout:r}=C.default.useContext(ce);return C.default.useEffect(()=>{r(t)},[t]),o(a.Modal,{size:"96vw",overflow:"inside",opened:t,onClose:n,title:"Data Settings",trapFocus:!0,onDragStart:i=>{i.stopPropagation()},children:g(a.Tabs,{defaultValue:"Queries",children:[g(a.Tabs.List,{children:[o(a.Tabs.Tab,{value:"SQL Snippet",children:"SQL Snippet"}),o(a.Tabs.Tab,{value:"Queries",children:"Queries"})]}),o(a.Tabs.Panel,{value:"SQL Snippet",pt:"sm",children:o(To,{})}),o(a.Tabs.Panel,{value:"Queries",pt:"sm",children:o(Vo,{})})]})})});var le=(e=>(e.Select="select",e.MultiSelect="multi-select",e.TextInput="text-input",e.Checkbox="checkbox",e.DateRange="date-range",e))(le||{});const Kn=y.types.model({type:y.types.enumeration("DataSourceType",[me.Postgresql,me.MySQL,me.HTTP]),key:y.types.string,sql:y.types.string}),Zn=y.types.model("FilterConfigModel_TextInput",{required:y.types.boolean,default_value:y.types.string}).actions(e=>({setRequired(t){e.required=t},setDefaultValue(t){e.default_value=t}})),er=()=>Zn.create({required:!1,default_value:""}),$o=E.observer(function({config:t}){return o(U,{children:o(a.Checkbox,{checked:t.default_value,onChange:n=>t.setDefaultValue(n.currentTarget.checked),label:"Default Checked"})})}),Po=[{label:"2022",value:"YYYY"},{label:"2022-01",value:"YYYY-MM"},{label:"2022-01-01",value:"YYYY-MM-DD"}],ko=E.observer(function({config:t}){return g(U,{children:[g(a.Group,{children:[o(a.Checkbox,{checked:t.required,onChange:n=>t.setRequired(n.currentTarget.checked),label:"Required"}),o(a.Checkbox,{checked:t.clearable,onChange:n=>t.setClearable(n.currentTarget.checked),label:"Clearable"})]}),o(a.Select,{data:Po,label:"Display Format",value:t.inputFormat,onChange:t.setInputFormat}),o(qn,{label:"Default Value",config:t,value:t.default_value,onChange:t.setDefaultValue})]})});function Oo({data:e}){return e.length===0?o(a.Box,{sx:{height:"5em"}}):g(a.Table,{children:[o("thead",{children:o("tr",{children:Object.keys(e==null?void 0:e[0]).map(t=>o("th",{children:o(a.Text,{weight:700,color:"#000",children:t})},t))})}),o("tbody",{children:e.slice(0,3).map((t,n)=>o("tr",{children:Object.values(t).map((r,i)=>o("td",{children:o(a.Group,{sx:{"&, .mantine-Text-root":{fontFamily:"monospace"}},children:o(a.Text,{children:r})})},`${r}--${i}`))},`row-${n}`))}),e.length>3&&o("tfoot",{children:o("tr",{children:o("td",{colSpan:Object.keys(e==null?void 0:e[0]).length,children:g(a.Text,{color:"gray",size:"sm",children:[e.length-3," more row(s) hidden"]})})})})]})}const zo=E.observer(function({query:t}){const{data:n=[],loading:r,refresh:i}=j.useRequest(Tt(t),{refreshDeps:[t]});return g(a.Stack,{my:0,children:[g(a.Group,{position:"apart",children:[o(a.Text,{size:"md",pl:"sm",children:"Fetched Data"}),o(a.Button,{size:"xs",onClick:i,disabled:!t.sql||!t.key,children:"Retry"})]}),g(a.Box,{sx:{position:"relative"},children:[o(a.LoadingOverlay,{visible:r,exitTransitionDuration:0}),o(Oo,{data:n})]})]})}),tr=E.observer(function({value:t,onChange:n}){return g(a.Stack,{my:0,children:[o(Xn,{value:t,onChange:({type:r,key:i})=>{n({...t,type:r,key:i})}}),g(a.Tabs,{defaultValue:"SQL",children:[g(a.Tabs.List,{children:[o(a.Tabs.Tab,{value:"SQL",children:"SQL"}),o(a.Tabs.Tab,{value:"Preview",children:"Preview"}),o(a.Tabs.Tab,{value:"Data",children:"Data"})]}),o(a.Tabs.Panel,{value:"SQL",pt:"sm",children:o(a.Textarea,{autosize:!0,minRows:12,maxRows:24,className:"code-textarea",value:t.sql,onChange:r=>{n({...t,sql:r.currentTarget.value})},placeholder:"SELECT name AS label, id AS value"})}),o(a.Tabs.Panel,{value:"Preview",pt:"sm",children:o(Jn,{value:t.sql})}),o(a.Tabs.Panel,{value:"Data",pt:"sm",children:o(zo,{query:t})})]})]})}),Go=E.observer(function({config:t}){const n=()=>{t.addStaticOption({label:"",value:""})},r=t.static_options,i=[...r];return g(U,{children:[o(a.Divider,{label:"Configure options",labelPosition:"center"}),r.length>0&&o(a.MultiSelect,{label:"Default Selection",data:i,value:t.default_value,onChange:t.setDefaultValue}),r.map((l,s)=>g(a.Group,{sx:{position:"relative"},pr:"40px",children:[o(a.TextInput,{label:"Label",required:!0,value:t.static_options[s].label,onChange:u=>{t.static_options[s].setLabel(u.currentTarget.value)},sx:{flexGrow:1}}),o(a.TextInput,{label:"Value",required:!0,value:t.static_options[s].value,onChange:u=>{t.static_options[s].setValue(u.currentTarget.value)},sx:{flexGrow:1}}),o(a.ActionIcon,{color:"red",variant:"subtle",onClick:()=>t.removeStaticOption(s),sx:{position:"absolute",top:28,right:5},children:o(V.Trash,{size:16})})]})),o(a.Button,{size:"xs",color:"blue",leftIcon:o(V.PlaylistAdd,{size:20}),onClick:n,sx:{width:"50%"},mx:"auto",children:"Add an Option"}),o(a.Divider,{label:"Or fetch options from database",labelPosition:"center"}),o(tr,{value:t.options_query,onChange:t.setOptionsQuery})]})}),Lo=E.observer(function({config:t}){const n=()=>{t.addStaticOption({label:"",value:""})},r=t.static_options,i=[{label:"No default selection",value:""},...r];return g(U,{children:[o(a.Checkbox,{checked:t.required,onChange:l=>t.setRequired(l.currentTarget.checked),label:"Required"}),o(a.Divider,{label:"Configure options",labelPosition:"center"}),r.length>0&&o(a.Select,{label:"Default Selection",data:i,value:t.default_value,onChange:t.setDefaultValue}),r.map((l,s)=>g(a.Group,{sx:{position:"relative"},pr:"40px",children:[o(a.TextInput,{label:"Label",required:!0,value:t.static_options[s].label,onChange:u=>{t.static_options[s].setLabel(u.currentTarget.value)},sx:{flexGrow:1}}),o(a.TextInput,{label:"Value",required:!0,value:t.static_options[s].value,onChange:u=>{t.static_options[s].setValue(u.currentTarget.value)},sx:{flexGrow:1}}),o(a.ActionIcon,{color:"red",variant:"subtle",onClick:()=>t.removeStaticOption(s),sx:{position:"absolute",top:28,right:5},children:o(V.Trash,{size:16})})]},s)),o(a.Button,{size:"xs",color:"blue",leftIcon:o(V.PlaylistAdd,{size:20}),onClick:n,sx:{width:"50%"},mx:"auto",children:"Add an Option"}),o(a.Divider,{label:"Or fetch options from database",labelPosition:"center"}),o(tr,{value:t.options_query,onChange:t.setOptionsQuery})]})}),No=E.observer(function({config:t}){return g(U,{children:[o(a.TextInput,{label:"Default Value",value:t.default_value,onChange:n=>{t.setDefaultValue(n.currentTarget.value)}}),o(a.Checkbox,{checked:t.required,onChange:n=>t.setRequired(n.currentTarget.checked),label:"Required"})]})}),qo=E.observer(function({filter:t}){const n=t.plainDefaultValue,[r,i]=C.default.useState(n);return C.default.useEffect(()=>{i(n)},[n]),g(a.Box,{sx:{maxWidth:"30em"},children:[o(a.Text,{pb:"md",color:"gray",children:"Preview"}),o(jn,{filter:t,value:r,onChange:i}),o(a.Text,{pt:"lg",pb:"md",color:"gray",children:"Config"}),o(Fe.Prism,{language:"json",colorScheme:"dark",noCopy:!0,children:JSON.stringify(t,null,4)})]})}),Bo={select:Lo,"multi-select":Go,"text-input":No,checkbox:$o,"date-range":ko},jo=[{label:"Select",value:"select"},{label:"Multi Select",value:"multi-select"},{label:"Text Input",value:"text-input"},{label:"Checkbox",value:"checkbox"},{label:"Date Range",value:"date-range"}],Wo=E.observer(function({filter:t,index:n}){const r=Y(),i=C.default.useMemo(()=>Bo[t.type],[t.type]);return g(a.SimpleGrid,{cols:2,children:[g(a.Box,{pl:"md",children:[o(a.Text,{pb:"md",color:"gray",children:"Edit"}),g(a.Stack,{sx:{maxWidth:"30em"},children:[o(a.NumberInput,{label:"Placement Order",required:!0,value:t.order,onChange:t.setOrder,hideControls:!0}),o(a.MultiSelect,{label:"Visible in...",data:r.views.options,value:t.visibleInViewsIDs,onChange:t.setVisibleInViewsIDs}),o(a.TextInput,{label:"Key",placeholder:"A unique key to refer",required:!0,value:t.key,onChange:l=>{t.setKey(l.currentTarget.value)}}),o(a.TextInput,{label:"Label",placeholder:"Label for this field",required:!0,value:t.label,onChange:l=>{t.setLabel(l.currentTarget.value)}}),o(a.Select,{label:"Widget",data:jo,required:!0,value:t.type,onChange:t.setType}),o(i,{config:t.config,index:n})]})]}),o(qo,{filter:t})]})}),mg="",Uo=E.observer(function(){const t=Y(),n=t.filters.current,r=()=>{const i=J.randomId(),l={id:i,key:i,label:i,order:n.length+1,type:le.TextInput,config:er(),visibleInViewsIDs:["Main"]};t.filters.append(l)};return g(a.Box,{sx:{height:"90vh",maxHeight:"calc(100vh - 185px)"},p:0,children:[o(a.Group,{sx:{position:"absolute",top:"16px",right:"16px"},children:o(a.Button,{size:"xs",color:"red",leftIcon:o(V.Recycle,{size:20}),disabled:!t.filters.changed,onClick:t.filters.reset,children:"Revert Changes"})}),o(a.Tabs,{className:"filter-settings-tabs",orientation:"vertical",defaultValue:t.filters.firstID,styles:{root:{display:"block"}},children:g(a.Group,{sx:{height:"100%"},children:[g(a.Stack,{sx:{height:"100%"},children:[o(a.Tabs.List,{position:"left",sx:{flexGrow:1,width:"200px"},children:t.filters.current.map(i=>o(a.Tabs.Tab,{value:i.id,children:i.label},i.id))}),o(a.Button,{size:"xs",color:"blue",leftIcon:o(V.PlaylistAdd,{size:20}),onClick:r,children:"Add a Filter"})]}),o(a.Box,{sx:{flexGrow:1,height:"100%"},children:t.filters.current.map((i,l)=>o(a.Tabs.Panel,{value:i.id,sx:{height:"100%"},children:g(a.Stack,{sx:{height:"100%"},spacing:"sm",children:[o(a.Box,{sx:{flexGrow:1,maxHeight:"calc(100% - 52px)",overflow:"scroll"},children:o(Wo,{filter:i,index:l})}),o(a.Group,{position:"right",pt:10,children:o(a.Button,{size:"xs",color:"red",leftIcon:o(V.Trash,{size:20}),onClick:()=>t.filters.remove(l),children:"Delete this filter"})})]})},i.id))})]})})]})}),Qo=E.observer(function({opened:t,close:n}){const{freezeLayout:r}=C.default.useContext(ce);return C.default.useEffect(()=>{r(t)},[t]),o(a.Modal,{size:"96vw",overflow:"inside",opened:t,onClose:n,title:"Filters",trapFocus:!0,onDragStart:i=>{i.stopPropagation()},withCloseButton:!1,children:o(Uo,{})})});var nr=(e=>(e.Use="use",e.Edit="edit",e))(nr||{}),ve=(e=>(e.Division="div",e.Modal="modal",e))(ve||{}),rr=(e=>(e.Select="select",e.MultiSelect="multi-select",e.TextInput="text-input",e.Checkbox="checkbox",e.DateRange="date-range",e))(rr||{});const Ho=E.observer(()=>{const t=Y().views.VIE;return!t||t.type!==ve.Division?null:g(a.Stack,{children:[o(a.Divider,{mt:8,mb:0,label:"Division settings",labelPosition:"center"}),o(a.Text,{align:"center",size:"xs",color:"dimmed",children:"Under construction"})]})}),Yo=E.observer(()=>{const t=Y().views.VIE;return!t||t.type!==ve.Modal?null:g(a.Stack,{children:[o(a.Divider,{mt:8,label:"Modal settings",labelPosition:"center"}),g(a.Group,{grow:!0,children:[o(a.TextInput,{label:"Width",value:t.config.width,onChange:n=>t.updateConfig("width",n.currentTarget.value),placeholder:"600px / 50vw"}),o(a.TextInput,{label:"Height",value:t.config.height,onChange:n=>t.updateConfig("height",n.currentTarget.value),placeholder:"600px / 50vw"})]})]})}),Xo=E.observer(()=>g(U,{children:[o(Ho,{}),o(Yo,{})]})),Jo=[{label:"Division",value:ve.Division},{label:"Modal",value:ve.Modal}],Ko=E.observer(()=>{const t=Y().views.VIE;return t?g(a.Stack,{sx:{position:"relative"},children:[o(a.TextInput,{label:"Name",value:t.name,onChange:n=>{t.setName(n.currentTarget.value)}}),o(a.Select,{label:"Type",value:t.type,onChange:t.setType,data:Jo}),o(Xo,{})]}):null}),Zo=E.observer(({opened:e,close:t})=>{var i;const n=Y(),{freezeLayout:r}=C.default.useContext(ce);return C.default.useEffect(()=>{r(e)},[e]),o(a.Modal,{size:"500px",overflow:"inside",opened:e,onClose:t,withCloseButton:!1,styles:{header:{width:"100%"},title:{width:"100%"}},title:g(a.Group,{position:"apart",children:[g(a.Text,{sx:{flexGrow:1},children:["Editing ",(i=n.views.VIE)==null?void 0:i.name]}),o(a.ActionIcon,{size:18,color:"red",onClick:n.views.removeVIE,disabled:n.views.isVIETheFirstView,children:o(V.Trash,{size:18})})]}),trapFocus:!0,onDragStart:l=>{l.stopPropagation()},children:o(Ko,{})})}),ea=w.forwardRef(({label:e,type:t,...n},r)=>t!=="TRIGGER_TO_ADD"?o("div",{ref:r,...n,children:g(a.Group,{noWrap:!0,position:"apart",children:[o(a.Text,{size:"sm",children:e}),o(a.Text,{size:"xs",color:"dimmed",children:t})]})}):o("div",{ref:r,...n,children:o(a.Group,{noWrap:!0,grow:!0,children:o(a.Text,{size:"sm",align:"center",color:"#228be6",children:e})})})),ir="TRIGGER_TO_ADD",ta=E.observer(({value:e,onChange:t,triggerAdd:n,triggerEdit:r,options:i})=>{const l=w.useMemo(()=>[...i,{label:"Add a View",value:ir,type:"TRIGGER_TO_ADD"}],[i,n]),s=u=>{u!==ir?t(u):n()};return g(a.Group,{position:"left",spacing:0,sx:{minWidth:"260px"},children:[o(a.Select,{value:e,onChange:s,placeholder:"Pick a View",itemComponent:ea,data:l,nothingFound:"Empty",sx:{flexGrow:1},styles:{input:{borderTopRightRadius:0,borderBottomRightRadius:0}}}),o(a.ActionIcon,{onClick:r,variant:"default",size:36,sx:{borderLeft:0,borderTopLeftRadius:0,borderBottomLeftRadius:0,"&:active":{transform:"none",svg:{transform:"translateY(1px)"}}},children:o(V.Settings,{size:20})})]})}),na=E.observer(()=>{const e=Y(),[t,n]=w.useState(!1),r=()=>{n(!0)},i=()=>{n(!1)};return g(U,{children:[o(ta,{value:e.views.idOfVIE,onChange:e.views.setIDOfVIE,triggerAdd:e.views.addARandomNewView,triggerEdit:r,options:e.views.options}),o(Zo,{opened:t,close:i})]})});function ra({opened:e,close:t,getCurrentSchema:n}){const{freezeLayout:r}=C.default.useContext(ce);C.default.useEffect(()=>{r(e)},[e]);const i=C.default.useMemo(()=>JSON.stringify(n(),null,2),[e]);return o(a.Modal,{size:"96vw",overflow:"inside",opened:e,onClose:t,title:"This dashboard is described by this schema",trapFocus:!0,onDragStart:l=>{l.stopPropagation()},children:e&&o(Fe.Prism,{language:"json",sx:{width:"100%"},colorScheme:"dark",children:i})})}const or=E.observer(function({saveChanges:t}){const n=Y(),r=C.default.useCallback(()=>{const N=n.queries.current,te=n.views.current,ye=n.sqlSnippets.current;return{filters:n.filters.current,views:te,definition:{sqlSnippets:ye,queries:N}}},[n]),i=()=>{n.filters.reset(),n.views.reset(),n.sqlSnippets.reset(),n.queries.reset()},l=n.views.changed||n.sqlSnippets.changed||n.queries.changed||n.filters.changed,{inEditMode:s,inUseMode:u}=C.default.useContext(ce),[d,p]=C.default.useState(!1),c=()=>p(!0),f=()=>p(!1),[m,v]=C.default.useState(!1),b=()=>v(!0),I=()=>v(!1),[A,T]=C.default.useState(!1),k=()=>T(!0),B=()=>T(!1);return g(a.Group,{position:"apart",pt:0,px:10,pb:"xs",children:[o(a.Group,{position:"left",children:s&&o(na,{})}),g(a.Group,{position:"right",children:[!u&&o(a.Button,{variant:"default",size:"xs",disabled:!n.views.VIE,onClick:n.views.addAPanelToVIE,leftIcon:o(V.PlaylistAdd,{size:20}),children:"Add a Panel"}),s&&o(a.Button,{variant:"default",size:"xs",onClick:b,leftIcon:o(V.Filter,{size:20}),children:"Filters"}),s&&o(a.Button,{variant:"default",size:"xs",onClick:c,leftIcon:o(V.Database,{size:20}),children:"Data Settings"}),!u&&o(a.Button,{variant:"default",size:"xs",onClick:t,disabled:!l,leftIcon:o(V.DeviceFloppy,{size:20}),children:"Save Changes"}),!u&&o(a.Button,{color:"red",size:"xs",disabled:!l,onClick:i,leftIcon:o(V.Recycle,{size:20}),children:"Revert Changes"}),g(a.Menu,{width:180,children:[o(a.Menu.Target,{children:o(a.Button,{variant:"default",size:"xs",leftIcon:o(V.Share,{size:20}),children:"Export"})}),g(a.Menu.Dropdown,{children:[o(a.Menu.Item,{icon:o(V.Download,{size:14}),onClick:n.queries.downloadAllData,children:"Download Data"}),o(a.Menu.Item,{icon:o(V.Code,{size:14}),onClick:k,children:"View Schema"})]})]})]}),o(Qo,{opened:m,close:I}),o(Fo,{opened:d,close:f}),o(ra,{opened:A,close:B,getCurrentSchema:r})]})}),vg="",ar=E.observer(()=>{const{freezeLayout:e}=C.default.useContext(ce),[t,n]=C.default.useState(!1),{panel:r}=ee();return C.default.useEffect(()=>{e(t)},[t]),!r.description||r.description==="<p><br></p>"?null:g(U,{children:[o(a.Modal,{opened:t,onClose:()=>n(!1),title:r.title,withCloseButton:!1,children:o(kn.default,{readOnly:!0,value:r.description,onChange:z.default.noop,sx:{border:"none"}})}),o(a.Tooltip,{label:"Click to see description",position:"top-start",withinPortal:!0,children:o(a.ActionIcon,{variant:"subtle",color:"blue",onClick:()=>n(i=>!i),sx:{verticalAlign:"baseline",cursor:"pointer"},children:o(V.InfoCircle,{size:20})})})]})}),lr=e=>{const{title:t="Variables",variables:n}=e,r=J.useClipboard(),i=l=>{r.copy(l),_t.showNotification({color:"green",message:"Copied to clipboard"})};return g(a.Paper,{withBorder:!0,p:"sm",children:[o(a.Text,{size:"xs",color:"dimmed",mb:"sm",children:t}),o(a.Stack,{style:{maxHeight:"300px"},children:n.map(l=>g(a.Text,{size:"sm",children:[g(a.Code,{color:"teal",children:["// ",l.description]}),o("br",{}),g(a.Code,{onClick:()=>i(l.name),style:{cursor:"pointer"},children:[l.name," : ",l.valueType]})]},l.name))})]})};class ia{constructor(t,n){$(this,"operationId");$(this,"operation");$(this,"operationSchema");$(this,"variables",[]);this.operationManager=t,this.instance=n,K.makeAutoObservable(this)}get schemaList(){return this.operationManager.getOperationSchemaList()}async configOperation(t,n){const r=await this.operationManager.retrieveTrigger(t),i=this.operationManager.getOperationSchemaList().find(l=>l.id===(r==null?void 0:r.schemaRef));K.runInAction(()=>{this.operationId=t,this.operation=r,this.operationSchema=i,this.variables=n})}async changeSchema(t){this.operationId&&(await this.operationManager.createOrGetOperation(this.operationId,t),await this.configOperation(this.operationId,this.variables))}}function oa(e){return!!e.operationId}const aa=E.observer(({model:e,onClick:t})=>{var r;const n=(r=e.operationSchema)==null?void 0:r.displayName;return o(a.Button,{variant:"outline",onClick:t,children:n})}),la=E.observer(({model:e})=>{const t={operation:e.operation,instance:e.instance,variables:[]};return w.createElement(e.operationSchema.configRender,t)});function sa({model:e}){const t=e.schemaList,n=t.map(i=>({label:i.displayName,value:i.id}));async function r(i){await e.changeSchema(t.find(l=>l.id===i))}return o(a.Select,{label:"Operation",data:n,onChange:r,value:e.operationSchema.id})}const ua=E.observer(e=>{const[t,{setTrue:n,setFalse:r}]=j.useBoolean(!1),{operationManager:i,operationId:l,instance:s,variables:u}=e,d=j.useCreation(()=>new ia(i,s),[i,s]);return j.useAsyncEffect(async()=>{await d.configOperation(l,u)},[l,d]),oa(d)?g(U,{children:[o(aa,{model:d,onClick:n}),o(a.Modal,{opened:t,onClose:r,title:"Operation Settings",closeButtonLabel:"close",children:g(a.Stack,{children:[o(sa,{model:d}),o(la,{model:d}),o(lr,{title:"Variables",variables:d.variables})]})})]}):null});class da{constructor(t,n){$(this,"triggerId");$(this,"trigger");$(this,"triggerSchema");$(this,"sampleData");this.triggerManager=t,this.instance=n,K.makeAutoObservable(this)}get schemaList(){return this.triggerManager.getTriggerSchemaList()}async configTrigger(t,n){const r=await this.triggerManager.retrieveTrigger(t),i=this.triggerManager.getTriggerSchemaList().find(l=>l.id===(r==null?void 0:r.schemaRef));K.runInAction(()=>{this.triggerId=t,this.trigger=r,this.triggerSchema=i,this.sampleData=n})}async changeSchema(t){this.triggerId&&(await this.triggerManager.createOrGetTrigger(this.triggerId,t),await this.configTrigger(this.triggerId,this.sampleData))}isReady(){return ca(this)}}function ca(e){return!!e.triggerId&&!!e.triggerSchema}function ga(e,t){return j.useCreation(()=>new da(e,t),[e,t])}const pa=E.observer(({model:e,onClick:t})=>{const n=e.triggerSchema.nameRender,r={trigger:e.trigger,instance:e.instance,sampleData:e.sampleData};return o(a.Button,{variant:"outline",onClick:t,children:w.createElement(n,r)})}),fa=E.observer(({model:e})=>{const t=e.schemaList,n=t.map(i=>({label:i.displayName,value:i.id}));async function r(i){await e.changeSchema(t.find(l=>l.id===i))}return o(a.Select,{label:"Trigger",data:n,value:e.triggerSchema.id,onChange:r})}),ha=E.observer(({model:e})=>{const t={trigger:e.trigger,instance:e.instance,sampleData:e.sampleData};return w.createElement(e.triggerSchema.configRender,t)}),ma=E.observer(e=>{const[t,{setTrue:n,setFalse:r}]=j.useBoolean(!1),i=e.model;return g(U,{children:[o(a.Modal,{opened:t,onClose:r,title:"Setup Trigger",closeButtonLabel:"close setup",children:g(a.Stack,{children:[o(fa,{model:i}),o(ha,{model:i}),o(lr,{title:"Payload",variables:i.triggerSchema.payload})]})}),o(pa,{onClick:n,model:i})]})});class Oe{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,_.omit(n,t))}async getItem(t){const n=await this.root.getItem(this.path);return t===null?n:_.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,(i,l)=>{n(i,l)},r):this.root.watchItem(this.path,(i,l)=>{const s=_.get(i,t),u=_.get(l,t);s!==u&&n(s,u)},r)}}class Ft{constructor(t,n,r){$(this,"attachmentStorage");this.instance=t,this.attachmentKey=n,this.constructInstance=r,this.attachmentStorage=new Oe(t.instanceData,n)}async getInstance(t){if(await this.attachmentStorage.getItem(t))return this.constructInstance(new Oe(this.attachmentStorage,t))}async create(t,n){return await this.attachmentStorage.setItem(t,n),this.constructInstance(new Oe(this.attachmentStorage,t))}async remove(t){await this.attachmentStorage.deleteItem(t)}async list(){const t=await this.attachmentStorage.getItem(null);return Promise.all(_.values(t).map(n=>this.constructInstance(new Oe(this.attachmentStorage,n.id))))}}class sr{constructor(t){$(this,"rootRef");this.rootRef=K.observable({current:t})}async deleteItem(t){K.runInAction(()=>{_.unset(this.rootRef.current,[t])})}getItem(t){const n=this.getValueFromRoot(t);return Promise.resolve(n)}getValueFromRoot(t){return t===null?K.toJS(this.rootRef.current):_.get(this.rootRef.current,[t])}setItem(t,n){if(t===null)if(_.isObject(n))K.runInAction(()=>{this.rootRef.current=n});else throw new Error("Cannot set root value to non-object");else K.runInAction(()=>{_.set(this.rootRef.current,[t],n)});return Promise.resolve(this.getItem(t))}watchItem(t,n,r){return K.reaction(()=>this.getValueFromRoot(t),(i,l)=>{n(i,l)},{requiresObservable:!0,fireImmediately:_.get(r,"fireImmediately",!1)})}}class va{constructor(){$(this,"channels",new Map);$(this,"globalChannel",new On.default)}getChannel(t){const n=this.channels.get(t);if(n)return n;const r=new On.default;return this.channels.set(t,r),r}}class ya{constructor(t){$(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 va,instanceData:new sr(t.viz.conf)};return this.instances.set(t.id,r),r}}function ur(e,t,n){return{vizManager:n,locale:"zh",msgChannels:e.messageChannels,instanceData:e.instanceData,pluginData:new sr({}),colorPalette:{getColor(){return()=>""}},data:t}}const ba=e=>{const{panel:t,vizManager:n,data:r}=e,i=n.resolveComponent(t.viz.type),l=n.getOrCreateInstance(t),s={...ur(l,r,n),viewport:{width:t.layout.w,height:t.layout.h}},u=i.viewRender;return o(u,{context:s,instance:l,..._.omit(e,["panel","vizManager","data"])})},Ca=e=>{const{vizManager:t,panel:n,panelInfoEditor:r,data:i}=e,l=t.resolveComponent(n.viz.type),s=t.getOrCreateInstance(n),u={...ur(s,i,t),panelInfoEditor:r},d=l.configRender;return o(d,{context:u,instance:s,..._.omit(e,["panel","vizManager","data","panelInfoEditor"])})},dr=(e,t)=>{const n=Le.default.bezier(e),r=Le.default.bezier(t);return function(i){return i<50?n(i*2/100).hex():r((i-50)*2/100).hex()}},et=e=>{const t=Le.default.bezier(e);return function(n){return t(n/100).hex()}},xa={type:"interpolation",displayName:"Red / Green",getColor:dr(["darkred","deeppink","lightyellow"],["lightyellow","lightgreen","teal"]),name:"red-green",category:"diverging"},Sa={type:"interpolation",displayName:"Yellow / Blue",getColor:dr(["#8f531d","#ffd347","#e3efe3"],["#eefaee","#4ecbbf","#003f94"]),name:"yellow-blue",category:"diverging"},wa={type:"interpolation",displayName:"Red",getColor:et(["#fff7f1","darkred"]),name:"red",category:"sequential"},_a={type:"interpolation",displayName:"Green",getColor:et(["#f0ffed","darkgreen"]),name:"green",category:"sequential"},Ia={type:"interpolation",displayName:"Blue",getColor:et(["#f9fcff","#48b3e9","darkblue"]),name:"blue",category:"sequential"},Da={type:"interpolation",displayName:"Orange",getColor:et(["#fff7f1","darkorange","#b60000"]),name:"orange",category:"sequential"},Aa="4.16.8";class Ma{constructor(t){$(this,"staticColors",new Map);$(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 Va{constructor(){$(this,"plugins",new Map);$(this,"vizComponents",new Map);$(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 Ea{constructor(){$(this,"migrations",[])}version(t,n){return this.migrations.push({version:t,handler:n}),this}run(t,n){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 r=this.migrations.filter(s=>s.version>t.from&&s.version<=t.to),i=_.orderBy(r,"version","asc");if(((l=_.last(i))==null?void 0:l.version)!==t.to)throw new Error(`Migration to version ${t.to} not found`);return i.reduce((s,u)=>u.handler(s),n)}}class ge extends Ea{constructor(){super(),this.configVersions()}version(t,n){return super.version(t,r=>({version:t,...n(r)}))}async migrate({instanceData:t}){const n=await t.getItem(null),r=_.get(n,"version",0),i=this.run({from:r,to:this.VERSION},n);await t.setItem(null,i)}async needMigration({instanceData:t}){const n=await t.getItem(null);return _.get(n,"version",0)<this.VERSION}}const $t={content:""},L=(e,t)=>{const[n,{setFalse:r}]=j.useBoolean(!0),[i,l]=w.useState();w.useEffect(()=>(e.getItem(t).then(u=>{l(u),r()}),e.watchItem(t,u=>{l(u)})));const s=w.useCallback(async u=>{await e.setItem(t,u),l(u)},[e,t]);return{loading:n,value:i,set:s}};function cr(e){const t=w.useRef(null);return w.useEffect(()=>{var n,r,i;e&&((i=(r=(n=t.current)==null?void 0:n.editor)==null?void 0:r.clipboard)==null||i.dangerouslyPasteHTML(e))},[e]),t}function Ra({context:e}){const{panel:t}=ee(),{value:n}=L(e.instanceData,"config"),r=n==null?void 0:n.content,i=cr(r);return n!=null&&n.content?o(wt.RichTextEditor,{id:t.id,ref:i,readOnly:!0,value:n.content,onChange:_.noop,sx:{border:"none",".ql-editor":{padding:0,"h1, h2, h3, h4, h5, p, ul, ol":{"&:last-child":{marginBottom:0}}}}}):null}function Ta({context:e}){const{value:t,set:n}=L(e.instanceData,"config"),r=w.useMemo(()=>_.defaults({},t,$t),[t]),{control:i,handleSubmit:l,watch:s,getValues:u}=S.useForm({defaultValues:r});s("content");const d=u(),p=w.useMemo(()=>!_.isEqual(d,t),[d,t]),c=cr(t==null?void 0:t.content);return o(a.Stack,{mt:"md",spacing:"xs",children:g("form",{onSubmit:l(n),children:[g(a.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[o(a.Text,{children:"Content"}),o(a.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!p,children:o(V.DeviceFloppy,{size:20})})]}),o(S.Controller,{name:"content",control:i,render:({field:f})=>o(kn.default,{ref:c,sx:{flex:1},..._.omit(f,"ref")})})]})})}class Fa extends ge{constructor(){super(...arguments);$(this,"VERSION",1)}fixMalformedConfig(n){return _.defaults({},n,$t)}configVersions(){this.version(1,n=>({version:1,config:this.fixMalformedConfig(n)}))}}const $a={displayName:"RichText",migrator:new Fa,name:"richText",viewRender:Ra,configRender:Ta,createConfig:()=>$t},Pt={align:"center",template:"The variable ${value} is defined in Variables section",variables:[{name:"value",size:"20px",weight:"bold",color:{type:"static",staticColor:"blue"},data_field:"",aggregation:{type:"none",config:{}},formatter:{output:"number",mantissa:0}}]};function Pa(e){if("variables"in e)return e;const{align:t,size:n,weight:r,color:i,content:{prefix:l="",data_field:s="value",formatter:u={output:"number",mantissa:0},postfix:d=""}={}}=e;return{align:t,template:`${l} \${value} ${d}`,variables:[{name:"value",data_field:s,aggregation:{type:"none",config:{}},formatter:u,color:i,weight:r,size:n}]}}class ka extends ge{constructor(){super(...arguments);$(this,"VERSION",1)}configVersions(){this.version(1,n=>({config:Pa(n)}))}}const kt=w.forwardRef(function({value:t,onChange:n,...r},i){return o(a.TextInput,{ref:i,value:t,onChange:n,...r})}),je={mantissa:0,output:"number",trimMantissa:!1,average:!1};function Oa({value:e,onChange:t},n){const r=u=>{t({...e,output:u})},i=u=>{const d=u===0?!1:e.trimMantissa;t({...e,mantissa:u,trimMantissa:d})},l=u=>{t({...e,trimMantissa:u.currentTarget.checked})},s=u=>{t({...e,average:u.currentTarget.checked})};return g(a.Stack,{ref:n,children:[g(a.Group,{grow:!0,children:[o(a.Select,{label:"Format",data:[{label:"1234",value:"number"},{label:"99%",value:"percent"}],value:e.output,onChange:r,sx:{flexGrow:1}}),o(a.Switch,{label:g(a.Stack,{spacing:0,children:[o(a.Text,{children:"Average"}),o(a.Text,{size:12,color:"gray",children:"like 1.234k, 1.234m"})]}),checked:e.average,onChange:s,disabled:e.output!=="number",sx:{flexGrow:1},styles:{root:{alignSelf:"flex-end"},body:{alignItems:"center"},label:{display:"block"}}})]}),g(a.Group,{grow:!0,children:[o(a.NumberInput,{label:"Mantissa",defaultValue:0,min:0,step:1,max:4,value:e.mantissa,onChange:i}),o(a.Switch,{label:"Trim mantissa",checked:e.trimMantissa,onChange:l,disabled:e.mantissa===0,styles:{root:{alignSelf:"flex-end"},body:{alignItems:"center"}}})]}),g(a.Stack,{spacing:0,children:[o(a.Text,{weight:"bold",children:"Preview"}),o(ke,{children:g(a.Group,{position:"apart",children:[g(a.Text,{size:12,color:"gray",children:["123456789 ",o(V.ArrowRight,{size:9})," ",ae.default(123456789).format(e)]}),g(a.Text,{size:12,color:"gray",children:["1234 ",o(V.ArrowRight,{size:9})," ",ae.default(1234).format(e)]}),g(a.Text,{size:12,color:"gray",children:["0.1234 ",o(V.ArrowRight,{size:9})," ",ae.default(.1234).format(e)]})]})})]})]})}const Ot=C.default.forwardRef(Oa);function tt(){return{name:J.randomId(),size:"20px",weight:"bold",color:{type:"static",staticColor:"blue"},data_field:"",aggregation:{type:"none",config:{}},formatter:je}}const za=[{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:"Quantile(99%, 95%, ...)",value:"quantile"}];function Ga({label:e,value:t,onChange:n},r){w.useEffect(()=>{typeof t=="string"&&(console.log(t),n({type:t,config:{}}))},[t,n]);const i=s=>{n(s==="quantile"?{type:"quantile",config:{p:.99}}:{type:s,config:{}})},l=s=>{n({type:"quantile",config:{p:s}})};return g(a.Group,{grow:!0,noWrap:!0,pt:"sm",children:[o(a.Select,{ref:r,label:e,data:za,value:t.type,onChange:i}),t.type==="quantile"&&o(a.NumberInput,{label:"p",value:t.config.p,onChange:l,precision:2,min:.05,step:.05,max:1})]})}const La=C.default.forwardRef(Ga);function Na({label:e,required:t,value:n,onChange:r,data:i,clearable:l=!1,sx:s,...u},d){const p=C.default.useMemo(()=>{if(!Array.isArray(i)||i.length===0)return[];const f=Object.keys(i[0]).map(m=>({label:m,value:m}));return l?f.concat([{label:"unset",value:""}]):f},[i]);return o(a.Select,{ref:d,label:e,data:p,value:n,onChange:r,required:t,sx:s,...u})}const Q=C.default.forwardRef(Na);function qa({label:e,value:t,onChange:n},r){const[i,l]=C.default.useState(Array.isArray(t)?[...t]:[]),s=C.default.useCallback(()=>{l(m=>[...m,""])},[l]),u=C.default.useCallback(m=>{l(v=>(v.splice(m,1),[...v]))},[l]),d=C.default.useMemo(()=>!z.default.isEqual(i,t),[i,t]),p=()=>{n(i.map(m=>m.toString()))},c=a.useMantineTheme(),f=C.default.useMemo(()=>Object.entries(c.colors).map(([m,v])=>v[6]),[c]);return g(U,{children:[g(a.Group,{position:"left",ref:r,children:[o(a.Text,{children:e}),o(a.ActionIcon,{mr:5,variant:"filled",color:"blue",disabled:!d,onClick:p,children:o(V.DeviceFloppy,{size:20})})]}),g(a.Group,{children:[i.map((m,v)=>o(a.ColorInput,{value:m,onChange:b=>{l(I=>(I.splice(v,1,b),[...I]))},swatches:f,rightSection:o(a.ActionIcon,{onClick:()=>u(v),color:"red",children:o(V.Trash,{size:14})}),sx:{width:"45%"}})),o(a.ActionIcon,{onClick:s,color:"blue",variant:"outline",children:o(V.PlaylistAdd,{size:20})})]})]})}const Ba=C.default.forwardRef(qa);function ja({value:e,onChange:t},n){const{colorManager:r}=w.useContext(xe),i=C.default.useMemo(()=>r.getStaticColors().map(u=>({label:u.name,group:u.category,value:u.value})),[r]),l=C.default.useMemo(()=>i.some(s=>s.value===e),[e,i]);return g(a.Group,{position:"apart",spacing:4,ref:n,children:[o(a.TextInput,{placeholder:"Set any color",value:l?"":e,onChange:s=>t(s.currentTarget.value),rightSection:o(a.ColorSwatch,{color:l?"transparent":e,radius:4}),variant:l?"filled":"default",sx:{maxWidth:"46%",flexGrow:1}}),o(a.Text,{sx:{flexGrow:0},children:"or"}),o(a.Select,{data:i,value:e,onChange:t,variant:l?"default":"filled",placeholder:"Pick a theme color",icon:o(a.ColorSwatch,{color:l?e:"transparent",radius:4}),sx:{maxWidth:"46%",flexGrow:1}})]})}const De=C.default.forwardRef(ja),nt=[{label:"initial",value:0},{label:"500",value:25},{label:"700",value:50},{label:"semibold",value:75},{label:"bold",value:100}];function Wa({label:e,value:t,onChange:n},r){var s,u;const[i,l]=C.default.useState((u=(s=nt.find(d=>d.label===t))==null?void 0:s.value)!=null?u:nt[0].value);return C.default.useEffect(()=>{const d=nt.find(p=>p.value===i);d&&n(d.label)},[i]),g(a.Stack,{spacing:0,mt:"sm",mb:"lg",children:[o(a.Text,{size:"sm",children:e}),o(a.Slider,{label:null,marks:nt,value:i,onChange:l,step:25,placeholder:"Pick a font size",ref:r})]})}const Ua=C.default.forwardRef(Wa);function Qa({label:e,value:t,onChange:n},r){const[i,l]=C.default.useState(Array.isArray(t)?[...t]:[]),s=C.default.useCallback(()=>{l(c=>[...c,""])},[l]),u=C.default.useCallback(c=>{l(f=>(f.splice(c,1),[...f]))},[l]),d=C.default.useMemo(()=>!z.default.isEqual(i,t),[i,t]),p=()=>{n(i.map(c=>c.toString()))};return g(U,{children:[g(a.Group,{position:"left",ref:r,children:[o(a.Text,{children:e}),o(a.ActionIcon,{mr:5,variant:"filled",color:"blue",disabled:!d,onClick:p,children:o(V.DeviceFloppy,{size:20})})]}),g(a.Group,{children:[i.map((c,f)=>o(a.TextInput,{value:c,onChange:m=>{const v=m.currentTarget.value;l(b=>(b.splice(f,1,v),[...b]))},rightSection:o(a.ActionIcon,{onClick:()=>u(f),color:"red",children:o(V.Trash,{size:14})}),sx:{width:"45%"}})),o(a.ActionIcon,{onClick:s,color:"blue",variant:"outline",children:o(V.PlaylistAdd,{size:20})})]})]})}const Ha=C.default.forwardRef(Qa),Ya=C.default.forwardRef(function({value:t,onChange:n},r){const i=t.color.type,l=(s,u)=>{const d=z.default.cloneDeep(t);z.default.set(d,s,u),n(d)};return g(U,{children:[o(a.Divider,{my:"xs",label:"Typography",labelPosition:"center"}),o(a.Stack,{children:o(a.TextInput,{label:"Font Size",placeholder:"10px, 1em, 1rem, 100%...",sx:{flex:1},value:t.size,onChange:s=>l("size",s.currentTarget.value)})}),o(a.Group,{position:"apart",grow:!0,sx:{"> *":{flexGrow:1,maxWidth:"100%"}},children:o(Ua,{label:"Font Weight",value:t.weight,onChange:s=>l("weight",s)})}),o(a.Divider,{my:"xs",label:"Style",labelPosition:"center"}),g(a.Stack,{children:[o(a.Select,{label:"Color Type",data:[{label:"Static Color",value:"static"},{label:"Continuous Color",value:"continuous"}],value:t.color.type,onChange:s=>l("color.type",s)}),i==="static"&&o(De,{value:t.color.staticColor,onChange:s=>l("color.staticColor",s)}),i==="continuous"&&g(U,{children:[o(Ha,{label:"Value Range",value:t.color.valueRange,onChange:s=>l("color.valueRange",s)}),o(Ba,{label:"Color Range",value:t.color.colorRange,onChange:s=>l("color.colorRange",s)})]})]})]})}),rt=C.default.forwardRef(function({value:t,onChange:n,data:r,withStyle:i=!0},l){const s=(u,d)=>{const p=z.default.cloneDeep(t);z.default.set(p,u,d),n(p)};return g(a.Box,{px:"sm",py:"md",ref:l,children:[o(a.Text,{weight:"bold",pb:0,children:t.name}),o(a.Divider,{my:"xs",label:"Data",labelPosition:"center"}),g(a.Group,{grow:!0,noWrap:!0,children:[o(a.TextInput,{label:"Name",required:!0,value:t.name,onChange:u=>s("name",u.currentTarget.value)}),o(Q,{label:"Data Field",required:!0,data:r,value:t.data_field,onChange:u=>s("data_field",u)})]}),o(La,{label:"Aggregation",value:t.aggregation,onChange:u=>s("aggregation",u)}),o(a.Divider,{my:"xs",label:"Format",labelPosition:"center"}),o(Ot,{value:t.formatter,onChange:u=>s("formatter",u)}),i&&o(Ya,{value:t,onChange:n})]})});function Xa(e){const t=Array.from(e).sort((r,i)=>r-i),n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function zt(e,t,n){var i,l,s,u;const r=e.map(d=>d[t]);switch(n.type){case"sum":return z.default.sum(r);case"mean":return z.default.mean(r);case"median":return Xa(r);case"max":return(i=z.default.max(r))!=null?i:0;case"min":return(l=z.default.min(r))!=null?l:0;case"quantile":return(s=eo.quantile(r,n.config.p))!=null?s:0;default:return(u=e[0])==null?void 0:u[t]}}var gr=function(){},We=function(){};process.env.NODE_ENV!=="production"&&(gr=function(e,t){!e&&typeof console<"u"&&console.warn(t)},We=function(e,t){if(!e)throw new Error(t)});const Ja=(e,t,n)=>Math.min(Math.max(n,e),t),pr=(e,t,n)=>{const r=t-e;return r===0?1:(n-e)/r},Gt=(e,t,n)=>-n*e+n*t+e,fr=(e,t)=>n=>Math.max(Math.min(n,t),e),Ue=e=>e%1?Number(e.toFixed(5)):e,it=/(-)?([\d]*\.?[\d])+/g,Lt=/(#[0-9a-f]{6}|#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2,3}\s*\/*\s*[\d\.]+%?\))/gi,Ka=/^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2,3}\s*\/*\s*[\d\.]+%?\))$/i;function Qe(e){return typeof e=="string"}const ot={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},hr=Object.assign(Object.assign({},ot),{transform:fr(0,1)});Object.assign(Object.assign({},ot),{default:1});const He=(e=>({test:t=>Qe(t)&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}))("%");Object.assign(Object.assign({},He),{parse:e=>He.parse(e)/100,transform:e=>He.transform(e*100)});const Nt=(e,t)=>n=>Boolean(Qe(n)&&Ka.test(n)&&n.startsWith(e)||t&&Object.prototype.hasOwnProperty.call(n,t)),mr=(e,t,n)=>r=>{if(!Qe(r))return r;const[i,l,s,u]=r.match(it);return{[e]:parseFloat(i),[t]:parseFloat(l),[n]:parseFloat(s),alpha:u!==void 0?parseFloat(u):1}},Pe={test:Nt("hsl","hue"),parse:mr("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:r=1})=>"hsla("+Math.round(e)+", "+He.transform(Ue(t))+", "+He.transform(Ue(n))+", "+Ue(hr.transform(r))+")"},Za=fr(0,255),qt=Object.assign(Object.assign({},ot),{transform:e=>Math.round(Za(e))}),Ae={test:Nt("rgb","red"),parse:mr("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:r=1})=>"rgba("+qt.transform(e)+", "+qt.transform(t)+", "+qt.transform(n)+", "+Ue(hr.transform(r))+")"};function el(e){let t="",n="",r="",i="";return e.length>5?(t=e.substr(1,2),n=e.substr(3,2),r=e.substr(5,2),i=e.substr(7,2)):(t=e.substr(1,1),n=e.substr(2,1),r=e.substr(3,1),i=e.substr(4,1),t+=t,n+=n,r+=r,i+=i),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(r,16),alpha:i?parseInt(i,16)/255:1}}const Bt={test:Nt("#"),parse:el,transform:Ae.transform},at={test:e=>Ae.test(e)||Bt.test(e)||Pe.test(e),parse:e=>Ae.test(e)?Ae.parse(e):Pe.test(e)?Pe.parse(e):Bt.parse(e),transform:e=>Qe(e)?e:e.hasOwnProperty("red")?Ae.transform(e):Pe.transform(e)},vr="${c}",yr="${n}";function tl(e){var t,n,r,i;return isNaN(e)&&Qe(e)&&((n=(t=e.match(it))===null||t===void 0?void 0:t.length)!==null&&n!==void 0?n:0)+((i=(r=e.match(Lt))===null||r===void 0?void 0:r.length)!==null&&i!==void 0?i:0)>0}function br(e){typeof e=="number"&&(e=`${e}`);const t=[];let n=0;const r=e.match(Lt);r&&(n=r.length,e=e.replace(Lt,vr),t.push(...r.map(at.parse)));const i=e.match(it);return i&&(e=e.replace(it,yr),t.push(...i.map(ot.parse))),{values:t,numColors:n,tokenised:e}}function Cr(e){return br(e).values}function xr(e){const{values:t,numColors:n,tokenised:r}=br(e),i=t.length;return l=>{let s=r;for(let u=0;u<i;u++)s=s.replace(u<n?vr:yr,u<n?at.transform(l[u]):Ue(l[u]));return s}}const nl=e=>typeof e=="number"?0:e;function rl(e){const t=Cr(e);return xr(e)(t.map(nl))}const Sr={test:tl,parse:Cr,createTransformer:xr,getAnimatableNone:rl};function jt(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function wr({hue:e,saturation:t,lightness:n,alpha:r}){e/=360,t/=100,n/=100;let i=0,l=0,s=0;if(!t)i=l=s=n;else{const u=n<.5?n*(1+t):n+t-n*t,d=2*n-u;i=jt(d,u,e+1/3),l=jt(d,u,e),s=jt(d,u,e-1/3)}return{red:Math.round(i*255),green:Math.round(l*255),blue:Math.round(s*255),alpha:r}}const il=(e,t,n)=>{const r=e*e,i=t*t;return Math.sqrt(Math.max(0,n*(i-r)+r))},ol=[Bt,Ae,Pe],_r=e=>ol.find(t=>t.test(e)),Ir=e=>`'${e}' is not an animatable color. Use the equivalent color code instead.`,Dr=(e,t)=>{let n=_r(e),r=_r(t);We(!!n,Ir(e)),We(!!r,Ir(t));let i=n.parse(e),l=r.parse(t);n===Pe&&(i=wr(i),n=Ae),r===Pe&&(l=wr(l),r=Ae);const s=Object.assign({},i);return u=>{for(const d in s)d!=="alpha"&&(s[d]=il(i[d],l[d],u));return s.alpha=Gt(i.alpha,l.alpha,u),n.transform(s)}},al=e=>typeof e=="number",ll=(e,t)=>n=>t(e(n)),Ar=(...e)=>e.reduce(ll);function Mr(e,t){return al(e)?n=>Gt(e,t,n):at.test(e)?Dr(e,t):Rr(e,t)}const Vr=(e,t)=>{const n=[...e],r=n.length,i=e.map((l,s)=>Mr(l,t[s]));return l=>{for(let s=0;s<r;s++)n[s]=i[s](l);return n}},sl=(e,t)=>{const n=Object.assign(Object.assign({},e),t),r={};for(const i in n)e[i]!==void 0&&t[i]!==void 0&&(r[i]=Mr(e[i],t[i]));return i=>{for(const l in r)n[l]=r[l](i);return n}};function Er(e){const t=Sr.parse(e),n=t.length;let r=0,i=0,l=0;for(let s=0;s<n;s++)r||typeof t[s]=="number"?r++:t[s].hue!==void 0?l++:i++;return{parsed:t,numNumbers:r,numRGB:i,numHSL:l}}const Rr=(e,t)=>{const n=Sr.createTransformer(t),r=Er(e),i=Er(t);return r.numHSL===i.numHSL&&r.numRGB===i.numRGB&&r.numNumbers>=i.numNumbers?Ar(Vr(r.parsed,i.parsed),n):(gr(!0,`Complex values '${e}' and '${t}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`),s=>`${s>0?t:e}`)},ul=(e,t)=>n=>Gt(e,t,n);function dl(e){if(typeof e=="number")return ul;if(typeof e=="string")return at.test(e)?Dr:Rr;if(Array.isArray(e))return Vr;if(typeof e=="object")return sl}function cl(e,t,n){const r=[],i=n||dl(e[0]),l=e.length-1;for(let s=0;s<l;s++){let u=i(e[s],e[s+1]);if(t){const d=Array.isArray(t)?t[s]:t;u=Ar(d,u)}r.push(u)}return r}function gl([e,t],[n]){return r=>n(pr(e,t,r))}function pl(e,t){const n=e.length,r=n-1;return i=>{let l=0,s=!1;if(i<=e[0]?s=!0:i>=e[r]&&(l=r-1,s=!0),!s){let d=1;for(;d<n&&!(e[d]>i||d===r);d++);l=d-1}const u=pr(e[l],e[l+1],i);return t[l](u)}}function fl(e,t,{clamp:n=!0,ease:r,mixer:i}={}){const l=e.length;We(l===t.length,"Both input and output ranges must be the same length"),We(!r||!Array.isArray(r)||r.length===l-1,"Array of easing functions must be of length `input.length - 1`, as it applies to the transitions **between** the defined values."),e[0]>e[l-1]&&(e=[].concat(e),t=[].concat(t),e.reverse(),t.reverse());const s=cl(t,r,i),u=l===2?gl(e,s):pl(e,s);return n?d=>u(Ja(e[0],e[l-1],d)):u}class hl{constructor({valueRange:t,colorRange:n}){$(this,"mapper");this.mapper=fl(t,n)}getColor(t){return this.mapper(t)}}function ml(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?`Array(${e.length})`:e.toString()}function Tr({data_field:e,aggregation:t},n){return zt(n,e,t)}function lt({formatter:e},t){return["string","number"].includes(typeof t)?ae.default(t).format(e):ml(t)}function vl(e,t){return e.type==="static"?e.staticColor:e.type==="continuous"?new hl(e).getColor(t):"black"}function yl(e,t){const n={};return e.forEach(r=>{const{name:i,color:l,data_field:s,aggregation:u,size:d,weight:p}=r,c=zt(t,s,u),f=lt(r,c);n[i]=o(a.Text,{sx:{fontSize:d,display:"inline"},color:vl(l,c),weight:p,children:f})}),n}function bl(e){return e.split(" ").map(t=>g(U,{children:[t,"\xA0"]}))}function Cl(e){const n=e.replaceAll("<br />","<br/>").replaceAll(`
39
+ `,Hn=E.observer(function({showSQLSnippets:t=!0,sx:n={}}){const r=Y(),i=r.context.current,l=C.default.useMemo(()=>{const s={context:i,filters:r.filters.values};if(t){const u=r.sqlSnippets.current.reduce((d,p)=>(d[p.key]=p.value,d),{});s.sql_snippets=u}return JSON.stringify(s,null,2)},[i,r.sqlSnippets.current,r.filters.values,t]);return g(a.Stack,{sx:{border:"1px solid #eee",maxWidth:"40%",overflow:"hidden",...n},children:[o(a.Group,{position:"left",pl:"md",py:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef",flexGrow:0},children:o(a.Text,{weight:500,children:"Global Variables"})}),g(a.Stack,{px:"md",pb:"md",sx:{width:"100%"},children:[o(Fe.Prism,{language:"sql",sx:{width:"100%"},noCopy:!0,colorScheme:"dark",children:wo}),o(a.Text,{weight:500,sx:{flexGrow:0},children:"Current Values"}),o(Fe.Prism,{language:"json",sx:{width:"100%"},noCopy:!0,colorScheme:"dark",children:l})]})]})});function _o({data:e}){return e.length===0?o(a.Box,{sx:{height:"5em"}}):g(a.Table,{children:[o("thead",{children:o("tr",{children:Object.keys(e==null?void 0:e[0]).map(t=>o("th",{children:o(a.Text,{weight:700,color:"#000",children:t})},t))})}),o("tbody",{children:e.slice(0,10).map((t,n)=>o("tr",{children:Object.values(t).map((r,i)=>o("td",{children:o(a.Group,{sx:{"&, .mantine-Text-root":{fontFamily:"monospace"}},children:o(a.Text,{children:r})})},`${r}--${i}`))},`row-${n}`))})]})}const Yn=E.observer(function({id:t}){const n=Y(),{data:r,state:i}=n.getDataStuffByID(t),l=i==="loading",s=()=>{n.queries.refetchDataByQueryID(t)};return g(a.Stack,{my:"xl",sx:{border:"1px solid #eee"},children:[g(a.Group,{position:"apart",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[g(a.Group,{position:"left",children:[o(a.Text,{weight:500,children:"Preview Data"}),r.length>10&&g(a.Text,{size:"sm",color:"gray",children:["Showing 10 rows of ",r.length]})]}),o(a.ActionIcon,{mr:15,variant:"subtle",color:"blue",disabled:l,onClick:s,children:o(V.Refresh,{size:15})})]}),g(a.Box,{sx:{position:"relative"},children:[o(a.LoadingOverlay,{visible:l}),o(_o,{data:r})]})]})}),Io=w.forwardRef(({label:e,type:t,...n},r)=>g(a.Group,{position:"apart",ref:r,...n,children:[o(a.Text,{children:e}),o(a.Text,{children:t})]})),Xn=E.observer(function({value:t,onChange:n}){const{data:r=[],loading:i}=j.useRequest(vo,{refreshDeps:[]},[]),l=w.useMemo(()=>r.map(u=>({label:u.key,value:u.key,type:u.type})),[r]),s=w.useMemo(()=>l.reduce((u,d)=>(u[d.value]=d.type,u),{}),[l]);return o(a.Select,{label:"Data Source",data:l,itemComponent:Io,sx:{flex:1},disabled:i,value:t.key,onChange:u=>{u!==null&&n({key:u,type:s[u]})}})});function Jn({value:e}){const t=Y(),n=t.context.current,r=C.default.useMemo(()=>Bn(e,n,t.sqlSnippets.current,t.filters.values),[e,n,t.sqlSnippets.current,t.filters.values]);return o(Fe.Prism,{language:"sql",colorScheme:"light",children:r})}const Do=E.observer(function({queryModel:t,setCurrentID:n}){const r=C.default.useRef(t.id),[i,l]=C.default.useState(r.current);C.default.useEffect(()=>{r.current!==t.id&&(l(t.id),r.current=t.id)},[r,t.id]);const[s,u]=C.default.useState(t.sql);C.default.useEffect(()=>{u(f=>f!==t.sql?t.sql:f)},[t.sql]);const d=s!==t.sql,p=()=>{t.setSQL(s)},c=()=>{n(i),t.setID(i)};return g(a.Stack,{sx:{border:"1px solid #eee",flexGrow:1},children:[o(a.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:o(a.Text,{weight:500,children:"Edit Query"})}),g(a.Stack,{my:0,p:"md",pr:40,children:[g(a.Group,{grow:!0,children:[o(a.TextInput,{placeholder:"An ID unique in this dashboard",label:"ID",required:!0,sx:{flex:1},value:i,onChange:f=>{l(f.currentTarget.value)},rightSection:o(a.ActionIcon,{mr:5,variant:"filled",color:"blue",disabled:i===t.id,onClick:c,children:o(V.DeviceFloppy,{size:18})})}),o(Xn,{value:{type:t.type,key:t.key},onChange:({type:f,key:m})=>{t.setKey(m),t.setType(f)}})]}),g(a.Tabs,{defaultValue:"SQL",children:[g(a.Tabs.List,{children:[o(a.Tabs.Tab,{value:"SQL",children:"SQL"}),o(a.Tabs.Tab,{value:"Preview",children:"Preview"})]}),o(a.Tabs.Panel,{value:"SQL",pt:"sm",children:g(a.Box,{sx:{position:"relative"},children:[o(a.Textarea,{autosize:!0,minRows:12,maxRows:24,className:"code-textarea",value:s,onChange:f=>{u(f.currentTarget.value)}}),o(a.ActionIcon,{mr:5,variant:"filled",color:"blue",sx:{position:"absolute",right:10,top:10},disabled:!d,onClick:p,children:o(V.DeviceFloppy,{size:20})})]})}),o(a.Tabs.Panel,{value:"Preview",pt:"sm",children:o(Jn,{value:t.sql})})]})]})]})}),Ao=E.observer(function({id:t,setID:n}){const r=Y(),i=C.default.useMemo(()=>r.queries.findByID(t),[r.queries,t]);return t?i?o(Do,{queryModel:i,setCurrentID:n}):o("span",{children:"Invalid Query ID"}):null});var me=(e=>(e.Postgresql="postgresql",e.MySQL="mysql",e.HTTP="http",e))(me||{});const Mo=E.observer(function({id:t,setID:n}){const r=Y(),i=()=>{var s;n((s=r.queries.firstID)!=null?s:"")};C.default.useEffect(()=>{if(!t){i();return}r.queries.current.findIndex(u=>u.id===t)===-1&&i()},[t,r.queries.current,i]);const l=()=>{const s=J.randomId();r.queries.append(y.cast({id:s,type:me.Postgresql,key:"",sql:""})),n(s)};return o(a.Group,{pb:"xl",children:g(a.Group,{position:"left",sx:{maxWidth:"600px",alignItems:"baseline"},children:[o(a.Text,{children:"Select a Query"}),o(a.Select,{data:r.queries.options,value:t,onChange:n,allowDeselect:!1,clearable:!1,sx:{flexGrow:1}}),o(a.Text,{children:"or"}),o(a.Group,{position:"center",mt:"md",children:o(a.Button,{onClick:l,children:"Add a Query"})})]})})}),Vo=E.observer(function(){const[t,n]=C.default.useState("");return g(a.AppShell,{sx:{height:"90vh",maxHeight:"calc(100vh - 225px)",".mantine-AppShell-body":{height:"100%"},main:{height:"100%",width:"100%",padding:0,margin:0}},padding:"md",children:[g(a.Group,{position:"apart",grow:!0,align:"stretch",noWrap:!0,children:[g(a.Stack,{sx:{flexGrow:1,maxWidth:"calc(60% - 16px)"},children:[o(Mo,{id:t,setID:n}),o(Ao,{id:t,setID:n})]}),o(Hn,{})]}),o(Yn,{id:t})]})}),Eo=E.observer(({value:e})=>{const t=Y(),n=t.context.current,r=C.default.useMemo(()=>ho(e,n,t.filters.values),[e,n]);return g(a.Stack,{children:[o(a.Text,{children:"Preview"}),o(Fe.Prism,{language:"sql",noCopy:!0,colorScheme:"dark",children:r})]})}),Ro=E.observer(function(){const t=Y(),n=()=>t.sqlSnippets.append(y.cast({key:J.randomId(),value:""}));return g(a.Stack,{sx:{border:"1px solid #eee",flexGrow:1},children:[o(a.Group,{position:"left",pl:"md",py:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef",flexGrow:0},children:o(a.Text,{weight:500,children:"SQL Snippets"})}),o(a.Group,{px:"md",pb:"md",pt:"md",children:g(a.Stack,{sx:{width:"100%",position:"relative"},children:[t.sqlSnippets.current.map((r,i)=>g(a.Stack,{my:0,p:"md",pr:40,sx:{border:"1px solid #eee",position:"relative"},children:[o(a.TextInput,{label:"Key",required:!0,value:r.key,onChange:l=>{r.setKey(l.currentTarget.value)}}),o(a.Textarea,{minRows:3,label:"Value",required:!0,value:r.value,onChange:l=>{r.setValue(l.currentTarget.value)},className:"code-textarea"}),o(Eo,{value:r.value}),o(a.ActionIcon,{color:"red",variant:"subtle",onClick:()=>t.sqlSnippets.remove(i),sx:{position:"absolute",top:15,right:5},children:o(V.Trash,{size:16})})]},i)),o(a.Group,{position:"center",mt:"xl",grow:!0,sx:{width:"40%"},mx:"auto",children:o(a.Button,{variant:"default",onClick:n,children:"Add a snippet"})})]})})]})});function To(){return o(a.AppShell,{sx:{height:"90vh",maxHeight:"calc(100vh - 225px)",".mantine-AppShell-body":{height:"100%"},main:{height:"100%",width:"100%",padding:0,margin:0}},padding:"md",children:g(a.Group,{position:"apart",grow:!0,align:"stretch",noWrap:!0,children:[o(Ro,{}),o(Hn,{showSQLSnippets:!1})]})})}const Fo=E.observer(function({opened:t,close:n}){const{freezeLayout:r}=C.default.useContext(ce);return C.default.useEffect(()=>{r(t)},[t]),o(a.Modal,{size:"96vw",overflow:"inside",opened:t,onClose:n,title:"Data Settings",trapFocus:!0,onDragStart:i=>{i.stopPropagation()},children:g(a.Tabs,{defaultValue:"Queries",children:[g(a.Tabs.List,{children:[o(a.Tabs.Tab,{value:"SQL Snippet",children:"SQL Snippet"}),o(a.Tabs.Tab,{value:"Queries",children:"Queries"})]}),o(a.Tabs.Panel,{value:"SQL Snippet",pt:"sm",children:o(To,{})}),o(a.Tabs.Panel,{value:"Queries",pt:"sm",children:o(Vo,{})})]})})});var le=(e=>(e.Select="select",e.MultiSelect="multi-select",e.TextInput="text-input",e.Checkbox="checkbox",e.DateRange="date-range",e))(le||{});const Kn=y.types.model({type:y.types.enumeration("DataSourceType",[me.Postgresql,me.MySQL,me.HTTP]),key:y.types.string,sql:y.types.string}),Zn=y.types.model("FilterConfigModel_TextInput",{required:y.types.boolean,default_value:y.types.string}).actions(e=>({setRequired(t){e.required=t},setDefaultValue(t){e.default_value=t}})),er=()=>Zn.create({required:!1,default_value:""}),$o=E.observer(function({config:t}){return o(U,{children:o(a.Checkbox,{checked:t.default_value,onChange:n=>t.setDefaultValue(n.currentTarget.checked),label:"Default Checked"})})}),Po=[{label:"2022",value:"YYYY"},{label:"2022-01",value:"YYYY-MM"},{label:"2022-01-01",value:"YYYY-MM-DD"}],ko=E.observer(function({config:t}){return g(U,{children:[g(a.Group,{children:[o(a.Checkbox,{checked:t.required,onChange:n=>t.setRequired(n.currentTarget.checked),label:"Required"}),o(a.Checkbox,{checked:t.clearable,onChange:n=>t.setClearable(n.currentTarget.checked),label:"Clearable"})]}),o(a.Select,{data:Po,label:"Display Format",value:t.inputFormat,onChange:t.setInputFormat}),o(qn,{label:"Default Value",config:t,value:t.default_value,onChange:t.setDefaultValue})]})});function Oo({data:e}){return e.length===0?o(a.Box,{sx:{height:"5em"}}):g(a.Table,{children:[o("thead",{children:o("tr",{children:Object.keys(e==null?void 0:e[0]).map(t=>o("th",{children:o(a.Text,{weight:700,color:"#000",children:t})},t))})}),o("tbody",{children:e.slice(0,3).map((t,n)=>o("tr",{children:Object.values(t).map((r,i)=>o("td",{children:o(a.Group,{sx:{"&, .mantine-Text-root":{fontFamily:"monospace"}},children:o(a.Text,{children:r})})},`${r}--${i}`))},`row-${n}`))}),e.length>3&&o("tfoot",{children:o("tr",{children:o("td",{colSpan:Object.keys(e==null?void 0:e[0]).length,children:g(a.Text,{color:"gray",size:"sm",children:[e.length-3," more row(s) hidden"]})})})})]})}const zo=E.observer(function({query:t}){const{data:n=[],loading:r,refresh:i}=j.useRequest(Tt(t),{refreshDeps:[t]});return g(a.Stack,{my:0,children:[g(a.Group,{position:"apart",children:[o(a.Text,{size:"md",pl:"sm",children:"Fetched Data"}),o(a.Button,{size:"xs",onClick:i,disabled:!t.sql||!t.key,children:"Retry"})]}),g(a.Box,{sx:{position:"relative"},children:[o(a.LoadingOverlay,{visible:r,exitTransitionDuration:0}),o(Oo,{data:n})]})]})}),tr=E.observer(function({value:t,onChange:n}){return g(a.Stack,{my:0,children:[o(Xn,{value:t,onChange:({type:r,key:i})=>{n({...t,type:r,key:i})}}),g(a.Tabs,{defaultValue:"SQL",children:[g(a.Tabs.List,{children:[o(a.Tabs.Tab,{value:"SQL",children:"SQL"}),o(a.Tabs.Tab,{value:"Preview",children:"Preview"}),o(a.Tabs.Tab,{value:"Data",children:"Data"})]}),o(a.Tabs.Panel,{value:"SQL",pt:"sm",children:o(a.Textarea,{autosize:!0,minRows:12,maxRows:24,className:"code-textarea",value:t.sql,onChange:r=>{n({...t,sql:r.currentTarget.value})},placeholder:"SELECT name AS label, id AS value"})}),o(a.Tabs.Panel,{value:"Preview",pt:"sm",children:o(Jn,{value:t.sql})}),o(a.Tabs.Panel,{value:"Data",pt:"sm",children:o(zo,{query:t})})]})]})}),Go=E.observer(function({config:t}){const n=()=>{t.addStaticOption({label:"",value:""})},r=t.static_options,i=[...r];return g(U,{children:[o(a.Divider,{label:"Configure options",labelPosition:"center"}),r.length>0&&o(a.MultiSelect,{label:"Default Selection",data:i,value:t.default_value,onChange:t.setDefaultValue}),r.map((l,s)=>g(a.Group,{sx:{position:"relative"},pr:"40px",children:[o(a.TextInput,{label:"Label",required:!0,value:t.static_options[s].label,onChange:u=>{t.static_options[s].setLabel(u.currentTarget.value)},sx:{flexGrow:1}}),o(a.TextInput,{label:"Value",required:!0,value:t.static_options[s].value,onChange:u=>{t.static_options[s].setValue(u.currentTarget.value)},sx:{flexGrow:1}}),o(a.ActionIcon,{color:"red",variant:"subtle",onClick:()=>t.removeStaticOption(s),sx:{position:"absolute",top:28,right:5},children:o(V.Trash,{size:16})})]})),o(a.Button,{size:"xs",color:"blue",leftIcon:o(V.PlaylistAdd,{size:20}),onClick:n,sx:{width:"50%"},mx:"auto",children:"Add an Option"}),o(a.Divider,{label:"Or fetch options from database",labelPosition:"center"}),o(tr,{value:t.options_query,onChange:t.setOptionsQuery})]})}),Lo=E.observer(function({config:t}){const n=()=>{t.addStaticOption({label:"",value:""})},r=t.static_options,i=[{label:"No default selection",value:""},...r];return g(U,{children:[o(a.Checkbox,{checked:t.required,onChange:l=>t.setRequired(l.currentTarget.checked),label:"Required"}),o(a.Divider,{label:"Configure options",labelPosition:"center"}),r.length>0&&o(a.Select,{label:"Default Selection",data:i,value:t.default_value,onChange:t.setDefaultValue}),r.map((l,s)=>g(a.Group,{sx:{position:"relative"},pr:"40px",children:[o(a.TextInput,{label:"Label",required:!0,value:t.static_options[s].label,onChange:u=>{t.static_options[s].setLabel(u.currentTarget.value)},sx:{flexGrow:1}}),o(a.TextInput,{label:"Value",required:!0,value:t.static_options[s].value,onChange:u=>{t.static_options[s].setValue(u.currentTarget.value)},sx:{flexGrow:1}}),o(a.ActionIcon,{color:"red",variant:"subtle",onClick:()=>t.removeStaticOption(s),sx:{position:"absolute",top:28,right:5},children:o(V.Trash,{size:16})})]},s)),o(a.Button,{size:"xs",color:"blue",leftIcon:o(V.PlaylistAdd,{size:20}),onClick:n,sx:{width:"50%"},mx:"auto",children:"Add an Option"}),o(a.Divider,{label:"Or fetch options from database",labelPosition:"center"}),o(tr,{value:t.options_query,onChange:t.setOptionsQuery})]})}),No=E.observer(function({config:t}){return g(U,{children:[o(a.TextInput,{label:"Default Value",value:t.default_value,onChange:n=>{t.setDefaultValue(n.currentTarget.value)}}),o(a.Checkbox,{checked:t.required,onChange:n=>t.setRequired(n.currentTarget.checked),label:"Required"})]})}),qo=E.observer(function({filter:t}){const n=t.plainDefaultValue,[r,i]=C.default.useState(n);return C.default.useEffect(()=>{i(n)},[n]),g(a.Box,{sx:{maxWidth:"30em"},children:[o(a.Text,{pb:"md",color:"gray",children:"Preview"}),o(jn,{filter:t,value:r,onChange:i}),o(a.Text,{pt:"lg",pb:"md",color:"gray",children:"Config"}),o(Fe.Prism,{language:"json",colorScheme:"dark",noCopy:!0,children:JSON.stringify(t,null,4)})]})}),Bo={select:Lo,"multi-select":Go,"text-input":No,checkbox:$o,"date-range":ko},jo=[{label:"Select",value:"select"},{label:"Multi Select",value:"multi-select"},{label:"Text Input",value:"text-input"},{label:"Checkbox",value:"checkbox"},{label:"Date Range",value:"date-range"}],Wo=E.observer(function({filter:t,index:n}){const r=Y(),i=C.default.useMemo(()=>Bo[t.type],[t.type]);return g(a.SimpleGrid,{cols:2,children:[g(a.Box,{pl:"md",children:[o(a.Text,{pb:"md",color:"gray",children:"Edit"}),g(a.Stack,{sx:{maxWidth:"30em"},children:[o(a.NumberInput,{label:"Placement Order",required:!0,value:t.order,onChange:t.setOrder,hideControls:!0}),o(a.MultiSelect,{label:"Visible in...",data:r.views.options,value:t.visibleInViewsIDs,onChange:t.setVisibleInViewsIDs}),o(a.TextInput,{label:"Key",placeholder:"A unique key to refer",required:!0,value:t.key,onChange:l=>{t.setKey(l.currentTarget.value)}}),o(a.TextInput,{label:"Label",placeholder:"Label for this field",required:!0,value:t.label,onChange:l=>{t.setLabel(l.currentTarget.value)}}),o(a.Select,{label:"Widget",data:jo,required:!0,value:t.type,onChange:t.setType}),o(i,{config:t.config,index:n})]})]}),o(qo,{filter:t})]})}),mg="",Uo=E.observer(function(){const t=Y(),n=t.filters.current,r=()=>{const i=J.randomId(),l={id:i,key:i,label:i,order:n.length+1,type:le.TextInput,config:er(),visibleInViewsIDs:["Main"]};t.filters.append(l)};return g(a.Box,{sx:{height:"90vh",maxHeight:"calc(100vh - 185px)"},p:0,children:[o(a.Group,{sx:{position:"absolute",top:"16px",right:"16px"},children:o(a.Button,{size:"xs",color:"red",leftIcon:o(V.Recycle,{size:20}),disabled:!t.filters.changed,onClick:t.filters.reset,children:"Revert Changes"})}),o(a.Tabs,{className:"filter-settings-tabs",orientation:"vertical",defaultValue:t.filters.firstID,styles:{root:{display:"block"}},children:g(a.Group,{sx:{height:"100%"},children:[g(a.Stack,{sx:{height:"100%"},children:[o(a.Tabs.List,{position:"left",sx:{flexGrow:1,width:"200px"},children:t.filters.current.map(i=>o(a.Tabs.Tab,{value:i.id,children:i.label},i.id))}),o(a.Button,{size:"xs",color:"blue",leftIcon:o(V.PlaylistAdd,{size:20}),onClick:r,children:"Add a Filter"})]}),o(a.Box,{sx:{flexGrow:1,height:"100%"},children:t.filters.current.map((i,l)=>o(a.Tabs.Panel,{value:i.id,sx:{height:"100%"},children:g(a.Stack,{sx:{height:"100%"},spacing:"sm",children:[o(a.Box,{sx:{flexGrow:1,maxHeight:"calc(100% - 52px)",overflow:"scroll"},children:o(Wo,{filter:i,index:l})}),o(a.Group,{position:"right",pt:10,children:o(a.Button,{size:"xs",color:"red",leftIcon:o(V.Trash,{size:20}),onClick:()=>t.filters.remove(l),children:"Delete this filter"})})]})},i.id))})]})})]})}),Qo=E.observer(function({opened:t,close:n}){const{freezeLayout:r}=C.default.useContext(ce);return C.default.useEffect(()=>{r(t)},[t]),o(a.Modal,{size:"96vw",overflow:"inside",opened:t,onClose:n,title:"Filters",trapFocus:!0,onDragStart:i=>{i.stopPropagation()},withCloseButton:!1,children:o(Uo,{})})});var nr=(e=>(e.Use="use",e.Edit="edit",e))(nr||{}),ve=(e=>(e.Division="div",e.Modal="modal",e))(ve||{}),rr=(e=>(e.Select="select",e.MultiSelect="multi-select",e.TextInput="text-input",e.Checkbox="checkbox",e.DateRange="date-range",e))(rr||{});const Ho=E.observer(()=>{const t=Y().views.VIE;return!t||t.type!==ve.Division?null:g(a.Stack,{children:[o(a.Divider,{mt:8,mb:0,label:"Division settings",labelPosition:"center"}),o(a.Text,{align:"center",size:"xs",color:"dimmed",children:"Under construction"})]})}),Yo=E.observer(()=>{const t=Y().views.VIE;return!t||t.type!==ve.Modal?null:g(a.Stack,{children:[o(a.Divider,{mt:8,label:"Modal settings",labelPosition:"center"}),g(a.Group,{grow:!0,children:[o(a.TextInput,{label:"Width",value:t.config.width,onChange:n=>t.updateConfig("width",n.currentTarget.value),placeholder:"600px / 50vw"}),o(a.TextInput,{label:"Height",value:t.config.height,onChange:n=>t.updateConfig("height",n.currentTarget.value),placeholder:"600px / 50vw"})]})]})}),Xo=E.observer(()=>g(U,{children:[o(Ho,{}),o(Yo,{})]})),Jo=[{label:"Division",value:ve.Division},{label:"Modal",value:ve.Modal}],Ko=E.observer(()=>{const t=Y().views.VIE;return t?g(a.Stack,{sx:{position:"relative"},children:[o(a.TextInput,{label:"Name",value:t.name,onChange:n=>{t.setName(n.currentTarget.value)}}),o(a.Select,{label:"Type",value:t.type,onChange:t.setType,data:Jo}),o(Xo,{})]}):null}),Zo=E.observer(({opened:e,close:t})=>{var i;const n=Y(),{freezeLayout:r}=C.default.useContext(ce);return C.default.useEffect(()=>{r(e)},[e]),o(a.Modal,{size:"500px",overflow:"inside",opened:e,onClose:t,withCloseButton:!1,styles:{header:{width:"100%"},title:{width:"100%"}},title:g(a.Group,{position:"apart",children:[g(a.Text,{sx:{flexGrow:1},children:["Editing ",(i=n.views.VIE)==null?void 0:i.name]}),o(a.ActionIcon,{size:18,color:"red",onClick:n.views.removeVIE,disabled:n.views.isVIETheFirstView,children:o(V.Trash,{size:18})})]}),trapFocus:!0,onDragStart:l=>{l.stopPropagation()},children:o(Ko,{})})}),ea=w.forwardRef(({label:e,type:t,...n},r)=>t!=="TRIGGER_TO_ADD"?o("div",{ref:r,...n,children:g(a.Group,{noWrap:!0,position:"apart",children:[o(a.Text,{size:"sm",children:e}),o(a.Text,{size:"xs",color:"dimmed",children:t})]})}):o("div",{ref:r,...n,children:o(a.Group,{noWrap:!0,grow:!0,children:o(a.Text,{size:"sm",align:"center",color:"#228be6",children:e})})})),ir="TRIGGER_TO_ADD",ta=E.observer(({value:e,onChange:t,triggerAdd:n,triggerEdit:r,options:i})=>{const l=w.useMemo(()=>[...i,{label:"Add a View",value:ir,type:"TRIGGER_TO_ADD"}],[i,n]),s=u=>{u!==ir?t(u):n()};return g(a.Group,{position:"left",spacing:0,sx:{minWidth:"260px"},children:[o(a.Select,{value:e,onChange:s,placeholder:"Pick a View",itemComponent:ea,data:l,nothingFound:"Empty",sx:{flexGrow:1},styles:{input:{borderTopRightRadius:0,borderBottomRightRadius:0}}}),o(a.ActionIcon,{onClick:r,variant:"default",size:36,sx:{borderLeft:0,borderTopLeftRadius:0,borderBottomLeftRadius:0,"&:active":{transform:"none",svg:{transform:"translateY(1px)"}}},children:o(V.Settings,{size:20})})]})}),na=E.observer(()=>{const e=Y(),[t,n]=w.useState(!1),r=()=>{n(!0)},i=()=>{n(!1)};return g(U,{children:[o(ta,{value:e.views.idOfVIE,onChange:e.views.setIDOfVIE,triggerAdd:e.views.addARandomNewView,triggerEdit:r,options:e.views.options}),o(Zo,{opened:t,close:i})]})});function ra({opened:e,close:t,getCurrentSchema:n}){const{freezeLayout:r}=C.default.useContext(ce);C.default.useEffect(()=>{r(e)},[e]);const i=C.default.useMemo(()=>JSON.stringify(n(),null,2),[e]);return o(a.Modal,{size:"96vw",overflow:"inside",opened:e,onClose:t,title:"This dashboard is described by this schema",trapFocus:!0,onDragStart:l=>{l.stopPropagation()},children:e&&o(Fe.Prism,{language:"json",sx:{width:"100%"},colorScheme:"dark",children:i})})}const or=E.observer(function({saveChanges:t}){const n=Y(),r=C.default.useCallback(()=>{const N=n.queries.current,te=n.views.current,ye=n.sqlSnippets.current;return{filters:n.filters.current,views:te,definition:{sqlSnippets:ye,queries:N}}},[n]),i=()=>{n.filters.reset(),n.views.reset(),n.sqlSnippets.reset(),n.queries.reset()},l=n.views.changed||n.sqlSnippets.changed||n.queries.changed||n.filters.changed,{inEditMode:s,inUseMode:u}=C.default.useContext(ce),[d,p]=C.default.useState(!1),c=()=>p(!0),f=()=>p(!1),[m,v]=C.default.useState(!1),b=()=>v(!0),I=()=>v(!1),[A,T]=C.default.useState(!1),k=()=>T(!0),B=()=>T(!1);return g(a.Group,{position:"apart",pt:0,px:10,pb:"xs",children:[o(a.Group,{position:"left",children:s&&o(na,{})}),g(a.Group,{position:"right",children:[!u&&o(a.Button,{variant:"default",size:"xs",disabled:!n.views.VIE,onClick:n.views.addAPanelToVIE,leftIcon:o(V.PlaylistAdd,{size:20}),children:"Add a Panel"}),s&&o(a.Button,{variant:"default",size:"xs",onClick:b,leftIcon:o(V.Filter,{size:20}),children:"Filters"}),s&&o(a.Button,{variant:"default",size:"xs",onClick:c,leftIcon:o(V.Database,{size:20}),children:"Data Settings"}),!u&&o(a.Button,{variant:"default",size:"xs",onClick:t,disabled:!l,leftIcon:o(V.DeviceFloppy,{size:20}),children:"Save Changes"}),!u&&o(a.Button,{color:"red",size:"xs",disabled:!l,onClick:i,leftIcon:o(V.Recycle,{size:20}),children:"Revert Changes"}),!u&&g(a.Menu,{width:180,children:[o(a.Menu.Target,{children:o(a.Button,{variant:"default",size:"xs",leftIcon:o(V.Share,{size:20}),children:"Export"})}),g(a.Menu.Dropdown,{children:[o(a.Menu.Item,{icon:o(V.Download,{size:14}),onClick:n.queries.downloadAllData,children:"Download Data"}),o(a.Menu.Item,{icon:o(V.Code,{size:14}),onClick:k,children:"View Schema"})]})]})]}),o(Qo,{opened:m,close:I}),o(Fo,{opened:d,close:f}),o(ra,{opened:A,close:B,getCurrentSchema:r})]})}),vg="",ar=E.observer(()=>{const{freezeLayout:e}=C.default.useContext(ce),[t,n]=C.default.useState(!1),{panel:r}=ee();return C.default.useEffect(()=>{e(t)},[t]),!r.description||r.description==="<p><br></p>"?null:g(U,{children:[o(a.Modal,{opened:t,onClose:()=>n(!1),title:r.title,withCloseButton:!1,children:o(kn.default,{readOnly:!0,value:r.description,onChange:z.default.noop,sx:{border:"none"}})}),o(a.Tooltip,{label:"Click to see description",position:"top-start",withinPortal:!0,children:o(a.ActionIcon,{variant:"subtle",color:"blue",onClick:()=>n(i=>!i),sx:{verticalAlign:"baseline",cursor:"pointer"},children:o(V.InfoCircle,{size:20})})})]})}),lr=e=>{const{title:t="Variables",variables:n}=e,r=J.useClipboard(),i=l=>{r.copy(l),_t.showNotification({color:"green",message:"Copied to clipboard"})};return g(a.Paper,{withBorder:!0,p:"sm",children:[o(a.Text,{size:"xs",color:"dimmed",mb:"sm",children:t}),o(a.Stack,{style:{maxHeight:"300px"},children:n.map(l=>g(a.Text,{size:"sm",children:[g(a.Code,{color:"teal",children:["// ",l.description]}),o("br",{}),g(a.Code,{onClick:()=>i(l.name),style:{cursor:"pointer"},children:[l.name," : ",l.valueType]})]},l.name))})]})};class ia{constructor(t,n){$(this,"operationId");$(this,"operation");$(this,"operationSchema");$(this,"variables",[]);this.operationManager=t,this.instance=n,K.makeAutoObservable(this)}get schemaList(){return this.operationManager.getOperationSchemaList()}async configOperation(t,n){const r=await this.operationManager.retrieveTrigger(t),i=this.operationManager.getOperationSchemaList().find(l=>l.id===(r==null?void 0:r.schemaRef));K.runInAction(()=>{this.operationId=t,this.operation=r,this.operationSchema=i,this.variables=n})}async changeSchema(t){this.operationId&&(await this.operationManager.createOrGetOperation(this.operationId,t),await this.configOperation(this.operationId,this.variables))}}function oa(e){return!!e.operationId}const aa=E.observer(({model:e,onClick:t})=>{var r;const n=(r=e.operationSchema)==null?void 0:r.displayName;return o(a.Button,{variant:"outline",onClick:t,children:n})}),la=E.observer(({model:e})=>{const t={operation:e.operation,instance:e.instance,variables:[]};return w.createElement(e.operationSchema.configRender,t)});function sa({model:e}){const t=e.schemaList,n=t.map(i=>({label:i.displayName,value:i.id}));async function r(i){await e.changeSchema(t.find(l=>l.id===i))}return o(a.Select,{label:"Operation",data:n,onChange:r,value:e.operationSchema.id})}const ua=E.observer(e=>{const[t,{setTrue:n,setFalse:r}]=j.useBoolean(!1),{operationManager:i,operationId:l,instance:s,variables:u}=e,d=j.useCreation(()=>new ia(i,s),[i,s]);return j.useAsyncEffect(async()=>{await d.configOperation(l,u)},[l,d]),oa(d)?g(U,{children:[o(aa,{model:d,onClick:n}),o(a.Modal,{opened:t,onClose:r,title:"Operation Settings",closeButtonLabel:"close",children:g(a.Stack,{children:[o(sa,{model:d}),o(la,{model:d}),o(lr,{title:"Variables",variables:d.variables})]})})]}):null});class da{constructor(t,n){$(this,"triggerId");$(this,"trigger");$(this,"triggerSchema");$(this,"sampleData");this.triggerManager=t,this.instance=n,K.makeAutoObservable(this)}get schemaList(){return this.triggerManager.getTriggerSchemaList()}async configTrigger(t,n){const r=await this.triggerManager.retrieveTrigger(t),i=this.triggerManager.getTriggerSchemaList().find(l=>l.id===(r==null?void 0:r.schemaRef));K.runInAction(()=>{this.triggerId=t,this.trigger=r,this.triggerSchema=i,this.sampleData=n})}async changeSchema(t){this.triggerId&&(await this.triggerManager.createOrGetTrigger(this.triggerId,t),await this.configTrigger(this.triggerId,this.sampleData))}isReady(){return ca(this)}}function ca(e){return!!e.triggerId&&!!e.triggerSchema}function ga(e,t){return j.useCreation(()=>new da(e,t),[e,t])}const pa=E.observer(({model:e,onClick:t})=>{const n=e.triggerSchema.nameRender,r={trigger:e.trigger,instance:e.instance,sampleData:e.sampleData};return o(a.Button,{variant:"outline",onClick:t,children:w.createElement(n,r)})}),fa=E.observer(({model:e})=>{const t=e.schemaList,n=t.map(i=>({label:i.displayName,value:i.id}));async function r(i){await e.changeSchema(t.find(l=>l.id===i))}return o(a.Select,{label:"Trigger",data:n,value:e.triggerSchema.id,onChange:r})}),ha=E.observer(({model:e})=>{const t={trigger:e.trigger,instance:e.instance,sampleData:e.sampleData};return w.createElement(e.triggerSchema.configRender,t)}),ma=E.observer(e=>{const[t,{setTrue:n,setFalse:r}]=j.useBoolean(!1),i=e.model;return g(U,{children:[o(a.Modal,{opened:t,onClose:r,title:"Setup Trigger",closeButtonLabel:"close setup",children:g(a.Stack,{children:[o(fa,{model:i}),o(ha,{model:i}),o(lr,{title:"Payload",variables:i.triggerSchema.payload})]})}),o(pa,{onClick:n,model:i})]})});class Oe{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,_.omit(n,t))}async getItem(t){const n=await this.root.getItem(this.path);return t===null?n:_.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,(i,l)=>{n(i,l)},r):this.root.watchItem(this.path,(i,l)=>{const s=_.get(i,t),u=_.get(l,t);s!==u&&n(s,u)},r)}}class Ft{constructor(t,n,r){$(this,"attachmentStorage");this.instance=t,this.attachmentKey=n,this.constructInstance=r,this.attachmentStorage=new Oe(t.instanceData,n)}async getInstance(t){if(await this.attachmentStorage.getItem(t))return this.constructInstance(new Oe(this.attachmentStorage,t))}async create(t,n){return await this.attachmentStorage.setItem(t,n),this.constructInstance(new Oe(this.attachmentStorage,t))}async remove(t){await this.attachmentStorage.deleteItem(t)}async list(){const t=await this.attachmentStorage.getItem(null);return Promise.all(_.values(t).map(n=>this.constructInstance(new Oe(this.attachmentStorage,n.id))))}}class sr{constructor(t){$(this,"rootRef");this.rootRef=K.observable({current:t})}async deleteItem(t){K.runInAction(()=>{_.unset(this.rootRef.current,[t])})}getItem(t){const n=this.getValueFromRoot(t);return Promise.resolve(n)}getValueFromRoot(t){return t===null?K.toJS(this.rootRef.current):_.get(this.rootRef.current,[t])}setItem(t,n){if(t===null)if(_.isObject(n))K.runInAction(()=>{this.rootRef.current=n});else throw new Error("Cannot set root value to non-object");else K.runInAction(()=>{_.set(this.rootRef.current,[t],n)});return Promise.resolve(this.getItem(t))}watchItem(t,n,r){return K.reaction(()=>this.getValueFromRoot(t),(i,l)=>{n(i,l)},{requiresObservable:!0,fireImmediately:_.get(r,"fireImmediately",!1)})}}class va{constructor(){$(this,"channels",new Map);$(this,"globalChannel",new On.default)}getChannel(t){const n=this.channels.get(t);if(n)return n;const r=new On.default;return this.channels.set(t,r),r}}class ya{constructor(t){$(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 va,instanceData:new sr(t.viz.conf)};return this.instances.set(t.id,r),r}}function ur(e,t,n){return{vizManager:n,locale:"zh",msgChannels:e.messageChannels,instanceData:e.instanceData,pluginData:new sr({}),colorPalette:{getColor(){return()=>""}},data:t}}const ba=e=>{const{panel:t,vizManager:n,data:r}=e,i=n.resolveComponent(t.viz.type),l=n.getOrCreateInstance(t),s={...ur(l,r,n),viewport:{width:t.layout.w,height:t.layout.h}},u=i.viewRender;return o(u,{context:s,instance:l,..._.omit(e,["panel","vizManager","data"])})},Ca=e=>{const{vizManager:t,panel:n,panelInfoEditor:r,data:i}=e,l=t.resolveComponent(n.viz.type),s=t.getOrCreateInstance(n),u={...ur(s,i,t),panelInfoEditor:r},d=l.configRender;return o(d,{context:u,instance:s,..._.omit(e,["panel","vizManager","data","panelInfoEditor"])})},dr=(e,t)=>{const n=Le.default.bezier(e),r=Le.default.bezier(t);return function(i){return i<50?n(i*2/100).hex():r((i-50)*2/100).hex()}},et=e=>{const t=Le.default.bezier(e);return function(n){return t(n/100).hex()}},xa={type:"interpolation",displayName:"Red / Green",getColor:dr(["darkred","deeppink","lightyellow"],["lightyellow","lightgreen","teal"]),name:"red-green",category:"diverging"},Sa={type:"interpolation",displayName:"Yellow / Blue",getColor:dr(["#8f531d","#ffd347","#e3efe3"],["#eefaee","#4ecbbf","#003f94"]),name:"yellow-blue",category:"diverging"},wa={type:"interpolation",displayName:"Red",getColor:et(["#fff7f1","darkred"]),name:"red",category:"sequential"},_a={type:"interpolation",displayName:"Green",getColor:et(["#f0ffed","darkgreen"]),name:"green",category:"sequential"},Ia={type:"interpolation",displayName:"Blue",getColor:et(["#f9fcff","#48b3e9","darkblue"]),name:"blue",category:"sequential"},Da={type:"interpolation",displayName:"Orange",getColor:et(["#fff7f1","darkorange","#b60000"]),name:"orange",category:"sequential"},Aa="4.17.0";class Ma{constructor(t){$(this,"staticColors",new Map);$(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 Va{constructor(){$(this,"plugins",new Map);$(this,"vizComponents",new Map);$(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 Ea{constructor(){$(this,"migrations",[])}version(t,n){return this.migrations.push({version:t,handler:n}),this}run(t,n){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 r=this.migrations.filter(s=>s.version>t.from&&s.version<=t.to),i=_.orderBy(r,"version","asc");if(((l=_.last(i))==null?void 0:l.version)!==t.to)throw new Error(`Migration to version ${t.to} not found`);return i.reduce((s,u)=>u.handler(s),n)}}class ge extends Ea{constructor(){super(),this.configVersions()}version(t,n){return super.version(t,r=>({version:t,...n(r)}))}async migrate({instanceData:t}){const n=await t.getItem(null),r=_.get(n,"version",0),i=this.run({from:r,to:this.VERSION},n);await t.setItem(null,i)}async needMigration({instanceData:t}){const n=await t.getItem(null);return _.get(n,"version",0)<this.VERSION}}const $t={content:""},L=(e,t)=>{const[n,{setFalse:r}]=j.useBoolean(!0),[i,l]=w.useState();w.useEffect(()=>(e.getItem(t).then(u=>{l(u),r()}),e.watchItem(t,u=>{l(u)})));const s=w.useCallback(async u=>{await e.setItem(t,u),l(u)},[e,t]);return{loading:n,value:i,set:s}};function cr(e){const t=w.useRef(null);return w.useEffect(()=>{var n,r,i;e&&((i=(r=(n=t.current)==null?void 0:n.editor)==null?void 0:r.clipboard)==null||i.dangerouslyPasteHTML(e))},[e]),t}function Ra({context:e}){const{panel:t}=ee(),{value:n}=L(e.instanceData,"config"),r=n==null?void 0:n.content,i=cr(r);return n!=null&&n.content?o(wt.RichTextEditor,{id:t.id,ref:i,readOnly:!0,value:n.content,onChange:_.noop,sx:{border:"none",".ql-editor":{padding:0,"h1, h2, h3, h4, h5, p, ul, ol":{"&:last-child":{marginBottom:0}}}}}):null}function Ta({context:e}){const{value:t,set:n}=L(e.instanceData,"config"),r=w.useMemo(()=>_.defaults({},t,$t),[t]),{control:i,handleSubmit:l,watch:s,getValues:u}=S.useForm({defaultValues:r});s("content");const d=u(),p=w.useMemo(()=>!_.isEqual(d,t),[d,t]),c=cr(t==null?void 0:t.content);return o(a.Stack,{mt:"md",spacing:"xs",children:g("form",{onSubmit:l(n),children:[g(a.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[o(a.Text,{children:"Content"}),o(a.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!p,children:o(V.DeviceFloppy,{size:20})})]}),o(S.Controller,{name:"content",control:i,render:({field:f})=>o(kn.default,{ref:c,sx:{flex:1},..._.omit(f,"ref")})})]})})}class Fa extends ge{constructor(){super(...arguments);$(this,"VERSION",1)}fixMalformedConfig(n){return _.defaults({},n,$t)}configVersions(){this.version(1,n=>({version:1,config:this.fixMalformedConfig(n)}))}}const $a={displayName:"RichText",migrator:new Fa,name:"richText",viewRender:Ra,configRender:Ta,createConfig:()=>$t},Pt={align:"center",template:"The variable ${value} is defined in Variables section",variables:[{name:"value",size:"20px",weight:"bold",color:{type:"static",staticColor:"blue"},data_field:"",aggregation:{type:"none",config:{}},formatter:{output:"number",mantissa:0}}]};function Pa(e){if("variables"in e)return e;const{align:t,size:n,weight:r,color:i,content:{prefix:l="",data_field:s="value",formatter:u={output:"number",mantissa:0},postfix:d=""}={}}=e;return{align:t,template:`${l} \${value} ${d}`,variables:[{name:"value",data_field:s,aggregation:{type:"none",config:{}},formatter:u,color:i,weight:r,size:n}]}}class ka extends ge{constructor(){super(...arguments);$(this,"VERSION",1)}configVersions(){this.version(1,n=>({config:Pa(n)}))}}const kt=w.forwardRef(function({value:t,onChange:n,...r},i){return o(a.TextInput,{ref:i,value:t,onChange:n,...r})}),je={mantissa:0,output:"number",trimMantissa:!1,average:!1};function Oa({value:e,onChange:t},n){const r=u=>{t({...e,output:u})},i=u=>{const d=u===0?!1:e.trimMantissa;t({...e,mantissa:u,trimMantissa:d})},l=u=>{t({...e,trimMantissa:u.currentTarget.checked})},s=u=>{t({...e,average:u.currentTarget.checked})};return g(a.Stack,{ref:n,children:[g(a.Group,{grow:!0,children:[o(a.Select,{label:"Format",data:[{label:"1234",value:"number"},{label:"99%",value:"percent"}],value:e.output,onChange:r,sx:{flexGrow:1}}),o(a.Switch,{label:g(a.Stack,{spacing:0,children:[o(a.Text,{children:"Average"}),o(a.Text,{size:12,color:"gray",children:"like 1.234k, 1.234m"})]}),checked:e.average,onChange:s,disabled:e.output!=="number",sx:{flexGrow:1},styles:{root:{alignSelf:"flex-end"},body:{alignItems:"center"},label:{display:"block"}}})]}),g(a.Group,{grow:!0,children:[o(a.NumberInput,{label:"Mantissa",defaultValue:0,min:0,step:1,max:4,value:e.mantissa,onChange:i}),o(a.Switch,{label:"Trim mantissa",checked:e.trimMantissa,onChange:l,disabled:e.mantissa===0,styles:{root:{alignSelf:"flex-end"},body:{alignItems:"center"}}})]}),g(a.Stack,{spacing:0,children:[o(a.Text,{weight:"bold",children:"Preview"}),o(ke,{children:g(a.Group,{position:"apart",children:[g(a.Text,{size:12,color:"gray",children:["123456789 ",o(V.ArrowRight,{size:9})," ",ae.default(123456789).format(e)]}),g(a.Text,{size:12,color:"gray",children:["1234 ",o(V.ArrowRight,{size:9})," ",ae.default(1234).format(e)]}),g(a.Text,{size:12,color:"gray",children:["0.1234 ",o(V.ArrowRight,{size:9})," ",ae.default(.1234).format(e)]})]})})]})]})}const Ot=C.default.forwardRef(Oa);function tt(){return{name:J.randomId(),size:"20px",weight:"bold",color:{type:"static",staticColor:"blue"},data_field:"",aggregation:{type:"none",config:{}},formatter:je}}const za=[{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:"Quantile(99%, 95%, ...)",value:"quantile"}];function Ga({label:e,value:t,onChange:n},r){w.useEffect(()=>{typeof t=="string"&&(console.log(t),n({type:t,config:{}}))},[t,n]);const i=s=>{n(s==="quantile"?{type:"quantile",config:{p:.99}}:{type:s,config:{}})},l=s=>{n({type:"quantile",config:{p:s}})};return g(a.Group,{grow:!0,noWrap:!0,pt:"sm",children:[o(a.Select,{ref:r,label:e,data:za,value:t.type,onChange:i}),t.type==="quantile"&&o(a.NumberInput,{label:"p",value:t.config.p,onChange:l,precision:2,min:.05,step:.05,max:1})]})}const La=C.default.forwardRef(Ga);function Na({label:e,required:t,value:n,onChange:r,data:i,clearable:l=!1,sx:s,...u},d){const p=C.default.useMemo(()=>{if(!Array.isArray(i)||i.length===0)return[];const f=Object.keys(i[0]).map(m=>({label:m,value:m}));return l?f.concat([{label:"unset",value:""}]):f},[i]);return o(a.Select,{ref:d,label:e,data:p,value:n,onChange:r,required:t,sx:s,...u})}const Q=C.default.forwardRef(Na);function qa({label:e,value:t,onChange:n},r){const[i,l]=C.default.useState(Array.isArray(t)?[...t]:[]),s=C.default.useCallback(()=>{l(m=>[...m,""])},[l]),u=C.default.useCallback(m=>{l(v=>(v.splice(m,1),[...v]))},[l]),d=C.default.useMemo(()=>!z.default.isEqual(i,t),[i,t]),p=()=>{n(i.map(m=>m.toString()))},c=a.useMantineTheme(),f=C.default.useMemo(()=>Object.entries(c.colors).map(([m,v])=>v[6]),[c]);return g(U,{children:[g(a.Group,{position:"left",ref:r,children:[o(a.Text,{children:e}),o(a.ActionIcon,{mr:5,variant:"filled",color:"blue",disabled:!d,onClick:p,children:o(V.DeviceFloppy,{size:20})})]}),g(a.Group,{children:[i.map((m,v)=>o(a.ColorInput,{value:m,onChange:b=>{l(I=>(I.splice(v,1,b),[...I]))},swatches:f,rightSection:o(a.ActionIcon,{onClick:()=>u(v),color:"red",children:o(V.Trash,{size:14})}),sx:{width:"45%"}})),o(a.ActionIcon,{onClick:s,color:"blue",variant:"outline",children:o(V.PlaylistAdd,{size:20})})]})]})}const Ba=C.default.forwardRef(qa);function ja({value:e,onChange:t},n){const{colorManager:r}=w.useContext(xe),i=C.default.useMemo(()=>r.getStaticColors().map(u=>({label:u.name,group:u.category,value:u.value})),[r]),l=C.default.useMemo(()=>i.some(s=>s.value===e),[e,i]);return g(a.Group,{position:"apart",spacing:4,ref:n,children:[o(a.TextInput,{placeholder:"Set any color",value:l?"":e,onChange:s=>t(s.currentTarget.value),rightSection:o(a.ColorSwatch,{color:l?"transparent":e,radius:4}),variant:l?"filled":"default",sx:{maxWidth:"46%",flexGrow:1}}),o(a.Text,{sx:{flexGrow:0},children:"or"}),o(a.Select,{data:i,value:e,onChange:t,variant:l?"default":"filled",placeholder:"Pick a theme color",icon:o(a.ColorSwatch,{color:l?e:"transparent",radius:4}),sx:{maxWidth:"46%",flexGrow:1}})]})}const De=C.default.forwardRef(ja),nt=[{label:"initial",value:0},{label:"500",value:25},{label:"700",value:50},{label:"semibold",value:75},{label:"bold",value:100}];function Wa({label:e,value:t,onChange:n},r){var s,u;const[i,l]=C.default.useState((u=(s=nt.find(d=>d.label===t))==null?void 0:s.value)!=null?u:nt[0].value);return C.default.useEffect(()=>{const d=nt.find(p=>p.value===i);d&&n(d.label)},[i]),g(a.Stack,{spacing:0,mt:"sm",mb:"lg",children:[o(a.Text,{size:"sm",children:e}),o(a.Slider,{label:null,marks:nt,value:i,onChange:l,step:25,placeholder:"Pick a font size",ref:r})]})}const Ua=C.default.forwardRef(Wa);function Qa({label:e,value:t,onChange:n},r){const[i,l]=C.default.useState(Array.isArray(t)?[...t]:[]),s=C.default.useCallback(()=>{l(c=>[...c,""])},[l]),u=C.default.useCallback(c=>{l(f=>(f.splice(c,1),[...f]))},[l]),d=C.default.useMemo(()=>!z.default.isEqual(i,t),[i,t]),p=()=>{n(i.map(c=>c.toString()))};return g(U,{children:[g(a.Group,{position:"left",ref:r,children:[o(a.Text,{children:e}),o(a.ActionIcon,{mr:5,variant:"filled",color:"blue",disabled:!d,onClick:p,children:o(V.DeviceFloppy,{size:20})})]}),g(a.Group,{children:[i.map((c,f)=>o(a.TextInput,{value:c,onChange:m=>{const v=m.currentTarget.value;l(b=>(b.splice(f,1,v),[...b]))},rightSection:o(a.ActionIcon,{onClick:()=>u(f),color:"red",children:o(V.Trash,{size:14})}),sx:{width:"45%"}})),o(a.ActionIcon,{onClick:s,color:"blue",variant:"outline",children:o(V.PlaylistAdd,{size:20})})]})]})}const Ha=C.default.forwardRef(Qa),Ya=C.default.forwardRef(function({value:t,onChange:n},r){const i=t.color.type,l=(s,u)=>{const d=z.default.cloneDeep(t);z.default.set(d,s,u),n(d)};return g(U,{children:[o(a.Divider,{my:"xs",label:"Typography",labelPosition:"center"}),o(a.Stack,{children:o(a.TextInput,{label:"Font Size",placeholder:"10px, 1em, 1rem, 100%...",sx:{flex:1},value:t.size,onChange:s=>l("size",s.currentTarget.value)})}),o(a.Group,{position:"apart",grow:!0,sx:{"> *":{flexGrow:1,maxWidth:"100%"}},children:o(Ua,{label:"Font Weight",value:t.weight,onChange:s=>l("weight",s)})}),o(a.Divider,{my:"xs",label:"Style",labelPosition:"center"}),g(a.Stack,{children:[o(a.Select,{label:"Color Type",data:[{label:"Static Color",value:"static"},{label:"Continuous Color",value:"continuous"}],value:t.color.type,onChange:s=>l("color.type",s)}),i==="static"&&o(De,{value:t.color.staticColor,onChange:s=>l("color.staticColor",s)}),i==="continuous"&&g(U,{children:[o(Ha,{label:"Value Range",value:t.color.valueRange,onChange:s=>l("color.valueRange",s)}),o(Ba,{label:"Color Range",value:t.color.colorRange,onChange:s=>l("color.colorRange",s)})]})]})]})}),rt=C.default.forwardRef(function({value:t,onChange:n,data:r,withStyle:i=!0},l){const s=(u,d)=>{const p=z.default.cloneDeep(t);z.default.set(p,u,d),n(p)};return g(a.Box,{px:"sm",py:"md",ref:l,children:[o(a.Text,{weight:"bold",pb:0,children:t.name}),o(a.Divider,{my:"xs",label:"Data",labelPosition:"center"}),g(a.Group,{grow:!0,noWrap:!0,children:[o(a.TextInput,{label:"Name",required:!0,value:t.name,onChange:u=>s("name",u.currentTarget.value)}),o(Q,{label:"Data Field",required:!0,data:r,value:t.data_field,onChange:u=>s("data_field",u)})]}),o(La,{label:"Aggregation",value:t.aggregation,onChange:u=>s("aggregation",u)}),o(a.Divider,{my:"xs",label:"Format",labelPosition:"center"}),o(Ot,{value:t.formatter,onChange:u=>s("formatter",u)}),i&&o(Ya,{value:t,onChange:n})]})});function Xa(e){const t=Array.from(e).sort((r,i)=>r-i),n=Math.floor(t.length/2);return t.length%2===0?(t[n-1]+t[n])/2:t[n]}function zt(e,t,n){var i,l,s,u;const r=e.map(d=>d[t]);switch(n.type){case"sum":return z.default.sum(r);case"mean":return z.default.mean(r);case"median":return Xa(r);case"max":return(i=z.default.max(r))!=null?i:0;case"min":return(l=z.default.min(r))!=null?l:0;case"quantile":return(s=eo.quantile(r,n.config.p))!=null?s:0;default:return(u=e[0])==null?void 0:u[t]}}var gr=function(){},We=function(){};process.env.NODE_ENV!=="production"&&(gr=function(e,t){!e&&typeof console<"u"&&console.warn(t)},We=function(e,t){if(!e)throw new Error(t)});const Ja=(e,t,n)=>Math.min(Math.max(n,e),t),pr=(e,t,n)=>{const r=t-e;return r===0?1:(n-e)/r},Gt=(e,t,n)=>-n*e+n*t+e,fr=(e,t)=>n=>Math.max(Math.min(n,t),e),Ue=e=>e%1?Number(e.toFixed(5)):e,it=/(-)?([\d]*\.?[\d])+/g,Lt=/(#[0-9a-f]{6}|#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2,3}\s*\/*\s*[\d\.]+%?\))/gi,Ka=/^(#[0-9a-f]{3}|#(?:[0-9a-f]{2}){2,4}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2,3}\s*\/*\s*[\d\.]+%?\))$/i;function Qe(e){return typeof e=="string"}const ot={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},hr=Object.assign(Object.assign({},ot),{transform:fr(0,1)});Object.assign(Object.assign({},ot),{default:1});const He=(e=>({test:t=>Qe(t)&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}))("%");Object.assign(Object.assign({},He),{parse:e=>He.parse(e)/100,transform:e=>He.transform(e*100)});const Nt=(e,t)=>n=>Boolean(Qe(n)&&Ka.test(n)&&n.startsWith(e)||t&&Object.prototype.hasOwnProperty.call(n,t)),mr=(e,t,n)=>r=>{if(!Qe(r))return r;const[i,l,s,u]=r.match(it);return{[e]:parseFloat(i),[t]:parseFloat(l),[n]:parseFloat(s),alpha:u!==void 0?parseFloat(u):1}},Pe={test:Nt("hsl","hue"),parse:mr("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:r=1})=>"hsla("+Math.round(e)+", "+He.transform(Ue(t))+", "+He.transform(Ue(n))+", "+Ue(hr.transform(r))+")"},Za=fr(0,255),qt=Object.assign(Object.assign({},ot),{transform:e=>Math.round(Za(e))}),Ae={test:Nt("rgb","red"),parse:mr("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:r=1})=>"rgba("+qt.transform(e)+", "+qt.transform(t)+", "+qt.transform(n)+", "+Ue(hr.transform(r))+")"};function el(e){let t="",n="",r="",i="";return e.length>5?(t=e.substr(1,2),n=e.substr(3,2),r=e.substr(5,2),i=e.substr(7,2)):(t=e.substr(1,1),n=e.substr(2,1),r=e.substr(3,1),i=e.substr(4,1),t+=t,n+=n,r+=r,i+=i),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(r,16),alpha:i?parseInt(i,16)/255:1}}const Bt={test:Nt("#"),parse:el,transform:Ae.transform},at={test:e=>Ae.test(e)||Bt.test(e)||Pe.test(e),parse:e=>Ae.test(e)?Ae.parse(e):Pe.test(e)?Pe.parse(e):Bt.parse(e),transform:e=>Qe(e)?e:e.hasOwnProperty("red")?Ae.transform(e):Pe.transform(e)},vr="${c}",yr="${n}";function tl(e){var t,n,r,i;return isNaN(e)&&Qe(e)&&((n=(t=e.match(it))===null||t===void 0?void 0:t.length)!==null&&n!==void 0?n:0)+((i=(r=e.match(Lt))===null||r===void 0?void 0:r.length)!==null&&i!==void 0?i:0)>0}function br(e){typeof e=="number"&&(e=`${e}`);const t=[];let n=0;const r=e.match(Lt);r&&(n=r.length,e=e.replace(Lt,vr),t.push(...r.map(at.parse)));const i=e.match(it);return i&&(e=e.replace(it,yr),t.push(...i.map(ot.parse))),{values:t,numColors:n,tokenised:e}}function Cr(e){return br(e).values}function xr(e){const{values:t,numColors:n,tokenised:r}=br(e),i=t.length;return l=>{let s=r;for(let u=0;u<i;u++)s=s.replace(u<n?vr:yr,u<n?at.transform(l[u]):Ue(l[u]));return s}}const nl=e=>typeof e=="number"?0:e;function rl(e){const t=Cr(e);return xr(e)(t.map(nl))}const Sr={test:tl,parse:Cr,createTransformer:xr,getAnimatableNone:rl};function jt(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function wr({hue:e,saturation:t,lightness:n,alpha:r}){e/=360,t/=100,n/=100;let i=0,l=0,s=0;if(!t)i=l=s=n;else{const u=n<.5?n*(1+t):n+t-n*t,d=2*n-u;i=jt(d,u,e+1/3),l=jt(d,u,e),s=jt(d,u,e-1/3)}return{red:Math.round(i*255),green:Math.round(l*255),blue:Math.round(s*255),alpha:r}}const il=(e,t,n)=>{const r=e*e,i=t*t;return Math.sqrt(Math.max(0,n*(i-r)+r))},ol=[Bt,Ae,Pe],_r=e=>ol.find(t=>t.test(e)),Ir=e=>`'${e}' is not an animatable color. Use the equivalent color code instead.`,Dr=(e,t)=>{let n=_r(e),r=_r(t);We(!!n,Ir(e)),We(!!r,Ir(t));let i=n.parse(e),l=r.parse(t);n===Pe&&(i=wr(i),n=Ae),r===Pe&&(l=wr(l),r=Ae);const s=Object.assign({},i);return u=>{for(const d in s)d!=="alpha"&&(s[d]=il(i[d],l[d],u));return s.alpha=Gt(i.alpha,l.alpha,u),n.transform(s)}},al=e=>typeof e=="number",ll=(e,t)=>n=>t(e(n)),Ar=(...e)=>e.reduce(ll);function Mr(e,t){return al(e)?n=>Gt(e,t,n):at.test(e)?Dr(e,t):Rr(e,t)}const Vr=(e,t)=>{const n=[...e],r=n.length,i=e.map((l,s)=>Mr(l,t[s]));return l=>{for(let s=0;s<r;s++)n[s]=i[s](l);return n}},sl=(e,t)=>{const n=Object.assign(Object.assign({},e),t),r={};for(const i in n)e[i]!==void 0&&t[i]!==void 0&&(r[i]=Mr(e[i],t[i]));return i=>{for(const l in r)n[l]=r[l](i);return n}};function Er(e){const t=Sr.parse(e),n=t.length;let r=0,i=0,l=0;for(let s=0;s<n;s++)r||typeof t[s]=="number"?r++:t[s].hue!==void 0?l++:i++;return{parsed:t,numNumbers:r,numRGB:i,numHSL:l}}const Rr=(e,t)=>{const n=Sr.createTransformer(t),r=Er(e),i=Er(t);return r.numHSL===i.numHSL&&r.numRGB===i.numRGB&&r.numNumbers>=i.numNumbers?Ar(Vr(r.parsed,i.parsed),n):(gr(!0,`Complex values '${e}' and '${t}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`),s=>`${s>0?t:e}`)},ul=(e,t)=>n=>Gt(e,t,n);function dl(e){if(typeof e=="number")return ul;if(typeof e=="string")return at.test(e)?Dr:Rr;if(Array.isArray(e))return Vr;if(typeof e=="object")return sl}function cl(e,t,n){const r=[],i=n||dl(e[0]),l=e.length-1;for(let s=0;s<l;s++){let u=i(e[s],e[s+1]);if(t){const d=Array.isArray(t)?t[s]:t;u=Ar(d,u)}r.push(u)}return r}function gl([e,t],[n]){return r=>n(pr(e,t,r))}function pl(e,t){const n=e.length,r=n-1;return i=>{let l=0,s=!1;if(i<=e[0]?s=!0:i>=e[r]&&(l=r-1,s=!0),!s){let d=1;for(;d<n&&!(e[d]>i||d===r);d++);l=d-1}const u=pr(e[l],e[l+1],i);return t[l](u)}}function fl(e,t,{clamp:n=!0,ease:r,mixer:i}={}){const l=e.length;We(l===t.length,"Both input and output ranges must be the same length"),We(!r||!Array.isArray(r)||r.length===l-1,"Array of easing functions must be of length `input.length - 1`, as it applies to the transitions **between** the defined values."),e[0]>e[l-1]&&(e=[].concat(e),t=[].concat(t),e.reverse(),t.reverse());const s=cl(t,r,i),u=l===2?gl(e,s):pl(e,s);return n?d=>u(Ja(e[0],e[l-1],d)):u}class hl{constructor({valueRange:t,colorRange:n}){$(this,"mapper");this.mapper=fl(t,n)}getColor(t){return this.mapper(t)}}function ml(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?`Array(${e.length})`:e.toString()}function Tr({data_field:e,aggregation:t},n){return zt(n,e,t)}function lt({formatter:e},t){return["string","number"].includes(typeof t)?ae.default(t).format(e):ml(t)}function vl(e,t){return e.type==="static"?e.staticColor:e.type==="continuous"?new hl(e).getColor(t):"black"}function yl(e,t){const n={};return e.forEach(r=>{const{name:i,color:l,data_field:s,aggregation:u,size:d,weight:p}=r,c=zt(t,s,u),f=lt(r,c);n[i]=o(a.Text,{sx:{fontSize:d,display:"inline"},color:vl(l,c),weight:p,children:f})}),n}function bl(e){return e.split(" ").map(t=>g(U,{children:[t,"\xA0"]}))}function Cl(e){const n=e.replaceAll("<br />","<br/>").replaceAll(`
40
40
  `,"<br/>").split("<br/>");return n.map((i,l)=>{const s=[bl(i)];return l!==n.length-1&&s.push(o("br",{})),s}).flat().filter(i=>i!==void 0)}function Wt(e){return Cl(e)}function Ut(e,t,n){const r=yl(t,n),i=/^\{(.+)\}(.*)$/;return e.split("$").map(l=>{var p;const s=i.exec(l);if(!s)return Wt(l);const u=r[s[1]];if(!u)return Wt(l);const d=(p=s[2])!=null?p:"";return g(U,{children:[u,Wt(d)]})})}function xl(e,t){const n={};return e.forEach(r=>{const{name:i,data_field:l,aggregation:s}=r,u=zt(t,l,s);n[i]=lt(r,u)}),n}function Fr(e,t,n){const r=xl(t,n),i=/^\{(.+)\}(.*)$/;return e.split("$").map(l=>{var p;const s=i.exec(l);if(!s)return l;const u=r[s[1]];if(!u)return l;const d=(p=s[2])!=null?p:"";return`${u}${d}`}).join("")}function Sl({context:e}){const{value:t=Pt}=L(e.instanceData,"config"),{template:n,variables:r,align:i}=t,l=w.useMemo(()=>Ut(n,r,e.data),[n,r,e.data]);return o(a.Text,{align:i,children:Object.values(l).map(s=>s)})}function wl({control:e,index:t,remove:n,data:r}){return g(a.Stack,{my:"sm",p:0,sx:{border:"1px solid #eee",borderTopColor:"#333",borderTopWidth:2,position:"relative"},children:[o(S.Controller,{name:`variables.${t}`,control:e,render:({field:i})=>o(rt,{data:r,...i})}),o(a.ActionIcon,{color:"red",variant:"subtle",onClick:()=>n(t),sx:{position:"absolute",top:15,right:5},children:o(V.Trash,{size:16})})]},t)}function _l({control:e,watch:t,data:n}){const{fields:r,append:i,remove:l}=S.useFieldArray({control:e,name:"variables"}),s=t("variables"),u=r.map((p,c)=>({...p,...s[c]})),d=()=>i(tt());return g(a.Stack,{children:[u.map((p,c)=>o(wl,{control:e,index:c,remove:l,data:n},p.name)),o(a.Group,{position:"center",mt:"xs",children:o(a.Button,{onClick:d,children:"Add a Variable"})})]})}function Il({context:e}){const t=e.data||[],{value:n,set:r}=L(e.instanceData,"config"),i=C.default.useMemo(()=>{const{align:m,template:v="",variables:b=[]}=_.defaultsDeep({},n,Pt);return{variables:b,template:v,align:m}},[n]),{control:l,handleSubmit:s,watch:u,getValues:d,reset:p}=S.useForm({defaultValues:i});C.default.useEffect(()=>{p(i)},[i]),u(["variables","template"]);const c=d(),f=C.default.useMemo(()=>!z.default.isEqual(c,n),[c,n]);return o(a.Stack,{mt:"md",spacing:"xs",children:g("form",{onSubmit:s(r),children:[g(a.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[o(a.Text,{weight:500,children:"Stats Configurations"}),o(a.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!f,children:o(V.DeviceFloppy,{size:20})})]}),o(S.Controller,{name:"template",control:l,render:({field:m})=>o(kt,{label:"Template",py:"md",sx:{flexGrow:1},...m})}),o(a.Text,{pb:"sm",pt:"md",size:"sm",children:"Variables"}),o(_l,{control:l,watch:u,data:t})]})})}const Dl={createConfig(){return{version:1,config:Pt}},displayName:"Stats",migrator:new ka,name:"stats",viewRender:Sl,configRender:Il};var Me=(e=>(e.string="string",e.number="number",e.eloc="eloc",e.percentage="percentage",e))(Me||{});const st={columns:[],fontSize:"1rem",highlightOnHover:!1,horizontalSpacing:"1em",id_field:"",striped:!1,use_raw_columns:!1,verticalSpacing:"1em"};/**
41
41
  * react-table
42
42
  *
@@ -78,5 +78,5 @@ WHERE
78
78
  ${i.join("")}
79
79
  </tbody>
80
80
  </table>
81
- `}}const od={legend:{show:!0,bottom:0,left:0},tooltip:{trigger:"item"}};function ad(e,t){const n=["#66B4DB","#39BFA2","#E46464","#33A678","#EEBA00","#9D88CB","#939943","#E49792","#09A2B8","#AF5F6B","#6CA157","#09A2B8","#6398C7","#E692BA","#97B566","#8CACE2","#CA79AC","#6DBC80","#B08F4B","#826BAF"],r=e.dimensions.map(({name:s,max:u})=>({name:s,max:u})),i=t.map(s=>({value:e.dimensions.map(({data_key:u})=>s[u]),name:s[e.series_name_key]})),l={radar:{indicator:r,splitArea:{show:!1}},tooltip:{formatter:id(e)},legend:{show:!0,left:"center"},series:{type:"radar",data:i,symbolSize:4,lineStyle:{width:1},areaStyle:{opacity:.4},label:rd(e)},color:n};return z.default.merge({},od,l)}const fn={series_name_key:"name",dimensions:[]};Z.use([he.RadarChart,W.GridComponent,W.LegendComponent,W.TooltipComponent,we.CanvasRenderer]);function ld({context:e}){const{value:t}=L(e.instanceData,"config"),{width:n,height:r}=e.viewport,i=e.data,l=w.useMemo(()=>ad(_.defaultsDeep({},t,fn),i),[t,i]);return!n||!r||!t||_.isEmpty(t==null?void 0:t.dimensions)?null:o(a.Box,{children:o(_e.default,{echarts:Z,option:l,style:{width:n,height:r}})})}function sd({control:e,index:t,remove:n,data:r}){return g(a.Stack,{my:0,p:"md",pr:40,sx:{border:"1px solid #eee",position:"relative"},children:[g(a.Group,{grow:!0,noWrap:!0,children:[o(S.Controller,{name:`dimensions.${t}.name`,control:e,render:({field:i})=>o(a.TextInput,{label:"Name",required:!0,sx:{flex:1},...i})}),o(S.Controller,{name:`dimensions.${t}.data_key`,control:e,render:({field:i})=>o(Q,{label:"Data Key",required:!0,data:r,sx:{flex:1},...i})}),o(S.Controller,{name:`dimensions.${t}.max`,control:e,render:({field:i})=>o(a.NumberInput,{label:"Max",hideControls:!0,required:!0,sx:{flex:1},...i})})]}),g(a.Stack,{children:[o(a.Divider,{mb:-15,variant:"dashed",label:"Value Formatter",labelPosition:"center"}),o(S.Controller,{name:`dimensions.${t}.formatter`,control:e,render:({field:i})=>o(Ot,{...i})})]}),o(a.ActionIcon,{color:"red",variant:"subtle",onClick:()=>n(t),sx:{position:"absolute",top:15,right:5},disabled:t===0,children:o(V.Trash,{size:16})})]},t)}function ud({control:e,watch:t,data:n}){const{fields:r,append:i,remove:l}=S.useFieldArray({control:e,name:"dimensions"}),s=t("dimensions"),u=r.map((p,c)=>({...p,...s[c]})),d=()=>i({name:J.randomId(),data_key:"",max:100,formatter:je});return g(a.Stack,{children:[u.map((p,c)=>o(sd,{data:n,control:e,index:c,remove:l})),o(a.Group,{position:"center",mt:"xs",children:o(a.Button,{onClick:d,children:"Add a Dimension"})})]})}function dd(e){function t({name:n="",data_key:r="",max:i=10,formatter:l=je}){return{name:n,data_key:r,max:i,formatter:l}}return e.map(t)}function cd({context:e}){const t=e.data,{value:n,set:r}=L(e.instanceData,"config"),i=w.useMemo(()=>_.defaultsDeep({},n,fn),[n]),{dimensions:l,series_name_key:s}=i,u=w.useMemo(()=>({dimensions:dd(l!=null?l:[]),series_name_key:s}),[l,s]);w.useEffect(()=>{!_.isEqual(i,u)&&r(u)},[i,u]);const{control:d,handleSubmit:p,watch:c,getValues:f,reset:m}=S.useForm({defaultValues:u});w.useEffect(()=>{_.isEqual(f(),u)||m(u)},[i]),c(["series_name_key"]);const v=f(),b=w.useMemo(()=>!_.isEqual(v,i),[v,i]);return o(a.Stack,{mt:"md",spacing:"xs",children:g("form",{onSubmit:p(r),children:[g(a.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[o(a.Text,{children:"Chart Config"}),o(a.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!b,children:o(V.DeviceFloppy,{size:20})})]}),o(a.Box,{py:"sm",children:o(S.Controller,{name:"series_name_key",control:d,render:({field:I})=>o(Q,{label:"Series Name Field",required:!0,data:t,sx:{flex:1},...I})})}),o(ud,{control:d,watch:c,data:t})]})})}class gd extends ge{constructor(){super(...arguments);$(this,"VERSION",1)}configVersions(){this.version(1,n=>({version:1,config:n}))}}const pd={displayName:"Radar Chart",migrator:new gd,name:"radar",viewRender:ld,configRender:cd,createConfig:()=>fn};function fd(e,t){switch(e.config.method){case"linear":return[...Ie.regressionLinear()(t)];case"exponential":return[...Ie.regressionExp()(t)];case"logarithmic":return[...Ie.regressionLog()(t)];case"polynomial":return[...Ie.regressionPoly().order(e.config.order)(t)];default:return[]}}function hd({regression:e},t){const n=[],r=[];if(t.length===0)return{regressionSeries:n,regressionXAxes:r};const{transform:i,plot:l,name:s}=e,u=fd(i,t);return n.push({...l,name:s,data:u,showSymbol:!1,smooth:!0,tooltip:{show:!1}}),{regressionSeries:n,regressionXAxes:r}}const md={tooltip:{trigger:"axis"},grid:{top:10,left:30,right:15,bottom:30,containLabel:!0},dataZoom:[{type:"inside",xAxisIndex:[0]},{type:"inside",yAxisIndex:[0]}]};function vd(e,t){var l,s;const n=z.default.uniqBy(t.map(u=>[u[e.x_axis.data_key],u[e.regression.y_axis_data_key]]),0),{regressionSeries:r}=hd(e,n),i={xAxis:{type:"category",name:(l=e.x_axis.name)!=null?l:""},yAxis:{name:(s=e.y_axis.name)!=null?s:""},series:[{data:n,name:e.y_axis.name,type:"scatter",symbolSize:4,color:"red"},...r]};return _.defaultsDeep({},i,md)}function ft(e,t,n){return 1-(1-e)*(t-1)/(t-n-1)}function yd(e,t){if(!t)return{expression:"",rSquared:0,adjustedRSquared:0};const{regression:n,x_axis:r,y_axis:i}=t,l=e.map(s=>[s[r.data_key],s[n.y_axis_data_key]]);if(n.transform.config.method==="linear"){const s=Ie.regressionLinear()(l),{a:u,b:d,rSquared:p}=s;return{expression:g(a.Group,{position:"center",noWrap:!0,spacing:10,children:[o(a.Text,{children:i.name}),o(a.Text,{children:"="}),o(a.Text,{weight:"bold",color:"gray",children:d}),o(a.Text,{children:"+"}),o(a.Text,{weight:"bold",color:"gray",children:u}),o(a.Text,{children:"\xD7"}),o(a.Text,{children:r.name})]}),rSquared:p,adjustedRSquared:ft(p,e.length,1)}}if(n.transform.config.method==="exponential"){const{a:s,b:u,rSquared:d}=Ie.regressionExp()(l);return{expression:g(a.Group,{position:"center",noWrap:!0,spacing:10,children:[o(a.Text,{children:i.name}),o(a.Text,{children:"="}),o(a.Text,{weight:"bold",color:"gray",children:s}),o(a.Text,{children:"\xD7"}),g(a.Group,{position:"left",noWrap:!0,spacing:2,children:[o(a.Text,{children:"Math.exp("}),o(a.Text,{weight:"bold",color:"gray",children:u}),o(a.Text,{children:"\xD7"}),o(a.Text,{children:r.name}),o(a.Text,{children:")"})]})]}),rSquared:d,adjustedRSquared:ft(d,e.length,1)}}if(n.transform.config.method==="logarithmic"){const{a:s,b:u,rSquared:d}=Ie.regressionLog()(l);return{expression:g(a.Group,{position:"center",noWrap:!0,spacing:10,children:[o(a.Text,{children:i.name}),o(a.Text,{children:"="}),o(a.Text,{weight:"bold",color:"gray",children:s}),o(a.Text,{children:"\xD7"}),g(a.Group,{position:"left",noWrap:!0,spacing:2,children:[o(a.Text,{children:"Math.log("}),o(a.Text,{children:r.name}),o(a.Text,{children:")"}),o(a.Text,{children:"+"}),o(a.Text,{weight:"bold",color:"gray",children:u})]})]}),rSquared:d,adjustedRSquared:ft(d,e.length,1)}}if(n.transform.config.method==="polynomial"){const s=Ie.regressionPoly().order(n.transform.config.order)(l),{rSquared:u}=s;return console.log(s),{expression:"",rSquared:u,adjustedRSquared:ft(u,e.length,1)}}return{expression:"",rSquared:0}}const hn={x_axis:{name:"X Axis",data_key:""},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",y_axis_data_key:"value"}};Z.use([W.DataZoomComponent,he.ScatterChart,W.GridComponent,W.LegendComponent,W.TooltipComponent,we.CanvasRenderer]),Z.registerTransform($n.transform.regression);function bd({context:e}){const{value:t}=L(e.instanceData,"config"),{width:n,height:r}=e.viewport,i=w.useMemo(()=>{var m;const c=e.data,f=(m=t==null?void 0:t.regression)==null?void 0:m.y_axis_data_key;return f?c.map(v=>typeof v[f]=="number"?v:{...v,[f]:Number(v[f])}):c},[e.data,t==null?void 0:t.regression.y_axis_data_key]),l=w.useMemo(()=>vd(_.defaultsDeep({},t,hn),i),[t,i]),{expression:s,rSquared:u,adjustedRSquared:d}=w.useMemo(()=>yd(i,t),[t,i]);if(!n||!r||!t)return null;let p=r;return s&&(p-=20),g(a.Box,{children:[s&&o(a.Text,{align:"center",size:12,children:s}),g(a.Group,{spacing:0,noWrap:!0,align:"start",sx:{"> *":{flexGrow:0,flexShrink:0}},children:[o(_e.default,{echarts:Z,option:l,style:{width:n-190,height:p}}),u&&o(a.Table,{mt:20,fontSize:12,sx:{width:180,border:"1px solid #999",td:{padding:"3px 8px"}},children:g("tbody",{children:[g("tr",{children:[o("td",{children:"R-Sq"}),o("td",{style:{textAlign:"right"},children:ae.default(u).format({output:"percent",mantissa:1})})]}),g("tr",{children:[o("td",{children:"R-Sq(Adjusted)"}),o("td",{style:{textAlign:"right"},children:ae.default(d).format({output:"percent",mantissa:1})})]})]})})]})]})}const Cd=[{label:"Linear",value:"linear"},{label:"Exponential",value:"exponential"},{label:"Logarithmic",value:"logarithmic"},{label:"Polynomial",value:"polynomial"}];function xd({control:e,watch:t,data:n}){const r=t("regression.transform.config.method");return g(a.Stack,{children:[g(a.Group,{grow:!0,noWrap:!0,children:[o(S.Controller,{name:"regression.name",control:e,render:({field:i})=>o(a.TextInput,{label:"Name",required:!0,sx:{flex:1},...i})}),o(S.Controller,{name:"regression.y_axis_data_key",control:e,render:({field:i})=>o(Q,{label:"Value Field",required:!0,data:n,sx:{flex:1},...i})})]}),g(a.Group,{grow:!0,noWrap:!0,children:[o(S.Controller,{name:"regression.transform.config.method",control:e,render:({field:i})=>o(a.Select,{label:"Method",data:Cd,sx:{flex:1},...i})}),r==="polynomial"&&o(S.Controller,{name:"regression.transform.config.order",control:e,render:({field:i})=>o(a.NumberInput,{label:"Order",sx:{flex:1},...i})})]}),g(a.Stack,{spacing:4,children:[o(a.Text,{size:"sm",children:"Color"}),o(S.Controller,{name:"regression.plot.color",control:e,render:({field:i})=>o(De,{...i})})]})]})}function Sd({context:e}){const{value:t,set:n}=L(e.instanceData,"config"),r=e.data,i=w.useMemo(()=>_.defaults({},t,hn),[t]),{control:l,handleSubmit:s,watch:u,getValues:d,reset:p}=S.useForm({defaultValues:i});w.useEffect(()=>{p(i)},[i]),u(["x_axis","y_axis","regression"]);const c=d(),f=w.useMemo(()=>!_.isEqual(c,t),[c,t]);return o(a.Stack,{mt:"md",spacing:"xs",children:g("form",{onSubmit:s(n),children:[g(a.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[o(a.Text,{children:"Chart Config"}),o(a.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!f,children:o(V.DeviceFloppy,{size:20})})]}),g(a.Accordion,{multiple:!0,defaultValue:["Axis","Regression"],children:[g(a.Accordion.Item,{value:"Axis",children:[o(a.Accordion.Control,{children:"Axis"}),g(a.Accordion.Panel,{children:[g(a.Group,{grow:!0,noWrap:!0,children:[o(S.Controller,{name:"x_axis.name",control:l,render:({field:m})=>o(a.TextInput,{label:"X Axis Name",sx:{flex:1},...m})}),o(S.Controller,{name:"x_axis.data_key",control:l,render:({field:m})=>o(Q,{label:"X Axis Data Field",required:!0,data:r,sx:{flex:1},...m})})]}),o(a.Group,{grow:!0,noWrap:!0,children:o(S.Controller,{name:"y_axis.name",control:l,render:({field:m})=>o(a.TextInput,{label:"Y Axis Name",sx:{flex:1},...m})})})]})]}),g(a.Accordion.Item,{value:"Regression",children:[o(a.Accordion.Control,{children:"Regression Line"}),o(a.Accordion.Panel,{children:o(xd,{control:l,watch:u,data:r})})]})]})]})})}class wd extends ge{constructor(){super(...arguments);$(this,"VERSION",1)}configVersions(){this.version(1,n=>({version:1,config:n}))}}const _d={displayName:"Regression Chart",migrator:new wd,name:"regressionChart",viewRender:bd,configRender:Sd,createConfig:()=>hn},mn={x_axis:{name:"X Axis",data_key:""},data_key:"value",bar:{name:"Value",color:"#228be6"},line:{name:"Value",color:"red"}};function vn(e){return ae.default(e).format({output:"percent",mantissa:0})}function Id(e){const t=e.value[1];try{return vn(t)}catch(n){return console.error(n),t}}function Dd(e){const t=Array.isArray(e)?e:[e];if(t.length===0)return"";const n=t.map((r,i)=>{const l=r.seriesName,[s,u]=r.value;return l?`${l}: <strong>${(i===0?p=>p:vn)(u)}</strong>`:u});return n.unshift(`<strong>${t[0].name}</strong>`),n.join("<br />")}Z.use([he.BarChart,he.LineChart,W.DataZoomComponent,W.GridComponent,W.LegendComponent,W.TooltipComponent,we.CanvasRenderer]);function Ad({context:e}){const{value:t}=L(e.instanceData,"config"),n=e.data,{width:r,height:i}=e.viewport,{x_axis:l,data_key:s,bar:u,line:d}=_.defaults({},t,mn),{barData:p,lineData:c}=w.useMemo(()=>{const m=n.map(I=>[I[l.data_key],Number(I[s])]).sort((I,A)=>A[1]-I[1]),v=m.reduce((I,A)=>I+A[1],0),b=m.reduce((I,A,T)=>{const k=T===0?0:I[T-1][1];return I.push([A[0],k+A[1]]),I},[]).map(I=>[I[0],I[1]/v]);return{barData:m,lineData:b}},[l.data_key,s,n]),f={dataZoom:[{type:"inside",xAxisIndex:[0]},{type:"inside",yAxisIndex:[0]}],tooltip:{trigger:"axis",formatter:Dd},xAxis:[{type:"category",name:l.name,nameLocation:"middle",nameGap:30,nameTextStyle:{fontWeight:"bold",align:"right"}}],yAxis:[{name:u.name,nameGap:30,nameTextStyle:{fontWeight:"bold",align:"right"}},{name:d.name,nameGap:30,nameTextStyle:{fontWeight:"bold",align:"center"},axisLabel:{show:!0,formatter:vn}}],series:[{name:u.name,type:"bar",itemStyle:{color:u.color},yAxisIndex:0,data:p},{name:d.name,type:"line",itemStyle:{color:d.color},symbolSize:2,lineStyle:{width:1},label:{show:!0,position:"top",formatter:Id},yAxisIndex:1,data:c}]};return!t||!r||!i?null:o(_e.default,{echarts:Z,option:f,style:{width:r,height:i}})}function Md({context:e}){const{value:t,set:n}=L(e.instanceData,"config"),r=e.data,i=w.useMemo(()=>_.defaults({},t,mn),[t]),{control:l,handleSubmit:s,watch:u,getValues:d,reset:p}=S.useForm({defaultValues:i});w.useEffect(()=>{p(i)},[i]),u(["x_axis","data_key","bar","line"]);const c=d(),f=w.useMemo(()=>!_.isEqual(c,t),[c,t]);return o(a.Stack,{mt:"md",spacing:"xs",children:g("form",{onSubmit:s(n),children:[g(a.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[o(a.Text,{children:"Chart Config"}),o(a.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!f,children:o(V.DeviceFloppy,{size:20})})]}),g(a.Group,{grow:!0,noWrap:!0,children:[o(S.Controller,{name:"x_axis.name",control:l,render:({field:m})=>o(a.TextInput,{label:"X Axis Name",sx:{flex:1},...m})}),o(S.Controller,{name:"x_axis.data_key",control:l,render:({field:m})=>o(Q,{label:"X Axis Data Field",required:!0,data:r,sx:{flex:1},...m})})]}),o(S.Controller,{name:"data_key",control:l,render:({field:m})=>o(Q,{label:"Y Axis Data Field",required:!0,data:r,sx:{flex:1},...m})}),o(a.Divider,{my:"md",label:"Bar",labelPosition:"center"}),g(a.Group,{grow:!0,noWrap:!0,children:[o(S.Controller,{name:"bar.name",control:l,render:({field:m})=>o(a.TextInput,{label:"Bar Name",sx:{flex:1},...m})}),g(a.Stack,{spacing:4,children:[o(a.Text,{size:"sm",children:"Bar's Color"}),o(S.Controller,{name:"bar.color",control:l,render:({field:m})=>o(De,{...m})})]})]}),o(a.Divider,{my:"md",label:"Line",labelPosition:"center"}),g(a.Group,{grow:!0,noWrap:!0,children:[o(S.Controller,{name:"line.name",control:l,render:({field:m})=>o(a.TextInput,{label:"Line Name",sx:{flex:1},...m})}),g(a.Stack,{spacing:4,children:[o(a.Text,{size:"sm",children:"Line's Color"}),o(S.Controller,{name:"line.color",control:l,render:({field:m})=>o(De,{...m})})]})]})]})})}class Vd extends ge{constructor(){super(...arguments);$(this,"VERSION",1)}configVersions(){this.version(1,n=>({version:1,config:n}))}}const Ed={displayName:"Pareto Chart",migrator:new Vd,name:"paretoChart",viewRender:Ad,configRender:Md,createConfig:()=>mn},Rd=[{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"})),Td=[xa,Sa,Ia,_a,wa,Da],ti={id:"dashboard",version:Aa,manifest:{viz:[sn,Dl,$a,Hs,Zs,ru,gu,Ed,nd,pd,_d],color:[...Rd,...Td]}},Xe=new Va,ni=()=>{try{Xe.install(ti)}catch{}const e=new ya(Xe),t=new Ma(Xe);return{pluginManager:Xe,vizManager:e,colorManager:t}},xe=w.createContext(ni());try{Xe.install(ti)}catch{}function Fd(e,t){const{value:n,set:r}=L(e.operation.operationData,"config"),[i,l]=w.useState(_.defaults({},n,t)),s=async()=>{await r(i)};return w.useEffect(()=>{l(_.defaults({},n,t))},[n]),{config:i,setConfig:l,commit:s}}function $d(e){const{config:t,setConfig:n,commit:r}=Fd(e,{urlTemplate:"",openInNewTab:!0});async function i(){await r()}async function l(u){n({...t,openInNewTab:u}),await r()}const s=u=>n({...t,urlTemplate:u.currentTarget.value});return g(a.Stack,{children:[o(a.TextInput,{label:"Url",value:t.urlTemplate,onChange:s,onBlur:i}),o(a.Switch,{label:"Open in new Tab",checked:t.openInNewTab,onChange:u=>l(u.currentTarget.checked)})]})}function Pd(e){return _.cloneDeepWith(e,n=>{if(typeof n=="string")return encodeURIComponent(n)})}async function kd(e,t){const{urlTemplate:n,openInNewTab:r}=await t.operationData.getItem("config"),l=_.template(n||"")(Pd(e));window.open(l,r?"_blank":"_self","noopener")}const Od={displayName:"Open Link",id:"builtin:op:open-link",configRender:$d,run:kd};function zd(e){const{value:t,set:n}=L(e.operationData,"config"),r=i=>void n({template:i});return[(t==null?void 0:t.template)||"",r]}function Gd(e){const[t,n]=zd(e.operation);return o(a.TextInput,{defaultValue:t,onBlur:r=>n(r.currentTarget.value),label:"console.log"})}async function Ld(e,t){const n=await t.operationData.getItem("config"),r=_.template(n.template||"");console.log("run with payload",e),console.log(r(e))}const yn=[{displayName:"console.log (debug)",id:"builtin:op:debug",configRender:Gd,run:Ld},Od];class Nd{constructor(t,n=yn){$(this,"attachments");this.operations=n;const r=async i=>{const{id:l,schemaRef:s}=await i.getItem(null);return{id:l,schemaRef:s,operationData:new Oe(i,"data")}};this.attachments=new Ft(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 i=this.operations.find(l=>l.id===r.schemaRef);if(!i){console.warn(`Operation schema '${r.schemaRef}' is not defined`);return}await i.run(n,r)}async createOrGetOperation(t,n){if(!this.getOperationSchemaList().some(s=>s.id===n.id))throw new Error(`Operation schema '${n.id}' is not defined`);const i=await this.attachments.getInstance(t);return!i||i.schemaRef!==n.id?await this.attachments.create(t,{id:t,schemaRef:n.id,data:{}}):i}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 ri="__TRIGGERS";class qd{constructor(t,n){$(this,"attachments");this.instance=t,this.component=n;const r=async i=>{const{id:l,schemaRef:s}=await i.getItem(null);return{id:l,schemaRef:s,triggerData:new Oe(i,"data")}};this.attachments=new Ft(t,ri,r)}watchTriggerSnapshotList(t){return this.instance.instanceData.watchItem(ri,n=>{const r=_.values(n).map(i=>({id:_.get(i,"id"),schemaRef:_.get(i,"schemaRef"),config:K.toJS(_.get(i,"data.config"))}));t(r)},{fireImmediately:!0})}async createOrGetTrigger(t,n,r={recreate:!1}){if(!this.getTriggerSchemaList().some(u=>u.id===n.id))throw new Error(`Trigger schema '${n.id}' is not defined in component '${this.component.name}'`);const l=await this.attachments.getInstance(t);return!l||r.recreate||l.schemaRef!==n.id?await this.attachments.create(t,{id:t,schemaRef:n.id,data:{}}):l}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)}}class ii{constructor(t,n,r){$(this,"operationManager");$(this,"triggerManager");$(this,"attachments");this.operationManager=new Nd(t,r),this.triggerManager=new qd(t,n);const i=async l=>{const{id:s,triggerRef:u,operationRef:d}=await l.getItem(null);return{id:s,triggerRef:u,operationRef:d}};this.attachments=new Ft(t,"__INTERACTIONS",i)}async addInteraction(t,n){const r=t.id,i=n.id,l=`[${r}]:[${i}]`;await this.attachments.create(l,{id:l,triggerRef:r,operationRef:i})}getInteractionList(){return this.attachments.list()}async removeInteraction(t){const n=await this.attachments.getInstance(t);if(!n)return;const{triggerRef:r,operationRef:i}=n;await this.getTriggerRefCount(r)<=1&&await this.triggerManager.removeTrigger(r),await this.getOperationRefCount(i)<=1&&await this.operationManager.removeOperation(i),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 i=(await this.getInteractionList()).filter(l=>l.triggerRef===t);await Promise.all(i.map(async l=>{try{return await this.operationManager.runOperation(l.operationRef,n)}catch(s){console.warn(`Failed to run operation '${l.operationRef}'`,s)}}))}}function Bd(e,t){const[n,r]=w.useState([]);return j.useAsyncEffect(async()=>{const i=await e.getInteractionList();r(i)},[t]),n}const jd=E.observer(({item:e,manager:t,instance:n,sampleData:r,variables:i,onRemove:l})=>{const{triggerRef:s,operationRef:u}=e,d=ga(t.triggerManager,n);if(j.useAsyncEffect(async()=>{await d.configTrigger(s,r)},[d,s,r]),d.isReady()){const p=[...d.triggerSchema.payload,...i];return g(a.Group,{children:[o(ma,{model:d}),o(ua,{instance:n,operationId:u,variables:p,operationManager:t.operationManager}),o(a.Button,{"aria-label":"delete-interaction",variant:"outline",color:"red",onClick:()=>l(e),children:o(V.Trash,{})})]})}return null}),Wd=e=>{const[t,n]=w.useState(0),{interactionManager:r,instance:i,sampleData:l,variables:s}=e,u=Bd(r,t),d=async()=>{const c=await r.triggerManager.createOrGetTrigger(J.randomId(),r.triggerManager.getTriggerSchemaList()[0]),f=await r.operationManager.createOrGetOperation(J.randomId(),r.operationManager.getOperationSchemaList()[0]);await r.addInteraction(c,f),n(m=>m+1)};async function p(c){await r.removeInteraction(c.id),n(f=>f+1)}return g(a.Stack,{children:[u.map(c=>o(jd,{onRemove:p,instance:i,sampleData:l,variables:s,item:c,manager:e.interactionManager},c.id)),o(a.Button,{style:{width:"fit-content"},onClick:()=>d(),children:"Add interaction"})]})},Ud=()=>{const{panel:e,data:t}=ee(),n=e.viz,{vizManager:r}=w.useContext(xe),i=e.json,l=j.useCreation(()=>r.getOrCreateInstance(i),[r,n.type]),s=j.useCreation(()=>new ii(l,r.resolveComponent(n.type),yn),[l,n.type]);return w.useEffect(()=>l.instanceData.watchItem(null,_.throttle(u=>{e.viz.setConf(u)},100,{leading:!1,trailing:!0})),[l]),{instance:l,vizManager:r,interactionManager:s,sampleData:t,variables:[]}},Qd=()=>{const e=Ud();return o(Wd,{...e})},Hd=E.observer(()=>{const{panel:e}=ee(),[t,n]=C.default.useState(e.description),r=e.description!==t,i=C.default.useCallback(()=>{!r||e.setDescription(t)},[r,t]);return g(a.Stack,{spacing:4,sx:{flexGrow:1},children:[g(a.Group,{align:"end",children:[o(a.Text,{sx:{flexGrow:1},children:"Description"}),o(a.ActionIcon,{variant:"subtle",color:"blue",disabled:!r,onClick:i,children:o(V.DeviceFloppy,{size:20})})]}),o(wt.RichTextEditor,{value:t,onChange:n,sx:{flexGrow:1},sticky:!0,p:"0"})]})}),Yd=E.observer(()=>{const{panel:e}=ee(),{style:t}=e;return o(U,{children:o(a.Switch,{label:"Border",checked:t.border.enabled,onChange:n=>t.border.setEnabled(n.currentTarget.checked)})})}),Xd=E.observer(()=>{const{panel:{title:e,style:{border:t}}}=ee();return o(ke,{children:g(a.Stack,{mx:"auto",mt:"xl",p:"5px",spacing:5,sx:{width:"600px",height:"450px",background:"transparent",borderRadius:"5px",border:"1px solid #ced4da",borderWidth:t.enabled?"1px":"0px"},children:[g(a.Group,{position:"apart",noWrap:!0,sx:{flexGrow:0,flexShrink:0},children:[o(a.Group,{children:o(ar,{})}),o(a.Group,{grow:!0,position:"center",children:o(a.Text,{lineClamp:1,weight:"bold",children:e})}),o(a.Group,{position:"right",spacing:0,sx:{height:"28px"}})]}),o(a.Group,{sx:{background:"#eee",flexGrow:1}})]})})}),Jd=E.observer(()=>{const{panel:e}=ee(),{title:t,setTitle:n}=e,[r,i]=J.useInputState(t),l=t!==r,s=C.default.useCallback(()=>{!l||n(r)},[l,r]);return o(a.TextInput,{value:r,onChange:i,label:g(a.Group,{align:"apart",children:[o(a.Text,{sx:{flexGrow:1},children:"Panel Title"}),o(a.ActionIcon,{variant:"subtle",color:"blue",disabled:!l,onClick:s,children:o(V.DeviceFloppy,{size:20})})]}),styles:{label:{display:"block",paddingBottom:"4px"}}})});function Kd(){return g(a.Group,{grow:!0,noWrap:!0,align:"stretch",sx:{height:"100%"},children:[g(a.Stack,{sx:{width:"40%",flexShrink:0,flexGrow:0,height:"100%"},children:[o(a.Divider,{label:"Style",labelPosition:"center",variant:"dashed"}),o(Yd,{}),o(a.Divider,{label:"Info",labelPosition:"center",variant:"dashed"}),o(Jd,{}),o(Hd,{})]}),o(a.Box,{sx:{height:"100%",flexGrow:1,maxWidth:"60%"},children:o(Xd,{})})]})}const Zd=E.observer(function(){const t=Y(),{panel:{queryID:n,setQueryID:r}}=ee(),i=C.default.useMemo(()=>t.queries.current.map(l=>({value:l.id,label:l.id})),[t.queries.current]);return g(a.Stack,{children:[g(a.Group,{position:"left",sx:{maxWidth:"600px",alignItems:"baseline"},children:[o(a.Text,{children:"Select a Query"}),o(a.Select,{data:i,value:n,onChange:r,allowDeselect:!1,clearable:!1,sx:{flexGrow:1}})]}),o(Yn,{id:n})]})});function oi(e,t,n){const r=j.useCreation(()=>new Set,[]),i=e.resolveComponent(t.type),[l,s]=w.useState(!1);return j.useAsyncEffect(async()=>{if(await i.migrator.needMigration(t)&&!r.has(t.id))try{r.add(t.id),await i.migrator.migrate(t),n==null||n()}finally{r.delete(t.id),s(!0)}else s(!0)},[t]),l}function ec({setVizConf:e,...t}){const{vizManager:n,panel:r}=t,i=n.getOrCreateInstance(r),l=oi(n,i,()=>{_t.showNotification({title:`${r.title} - Updated`,message:"Your plugin configuration has been migrated to the latest version"})});return j.useAsyncEffect(async()=>{await i.instanceData.setItem(null,r.viz.conf)},[i,r.viz.type]),w.useEffect(()=>i.instanceData.watchItem(null,s=>{e(s)}),[e,r.viz.type]),l?o(Ca,{...t}):o(a.Text,{children:"Checking update..."})}function tc(e){const{vizManager:t,panel:n}=e,r=t.getOrCreateInstance(n);return oi(t,r,()=>{_t.showNotification({title:`${n.title} - Updated`,message:"Your plugin configuration has been migrated to the latest version"})})?o(ba,{...e}):o(a.Text,{children:"Checking update"})}const Rg="";function nc(e,t){const{vizManager:n}=w.useContext(xe),{panel:{viz:r,title:i,id:l,description:s,queryID:u,style:d}}=ee(),p={title:i,id:l,description:s,queryID:u,viz:r,layout:t,style:d.json};try{return n.resolveComponent(r.type),o(tc,{panel:p,data:e,vizManager:n})}catch(c){return console.info(_.get(c,"message")),null}}const rc=["richText"],ai=E.observer(function({height:t,viz:n,data:r,loading:i}){const{ref:l,width:s,height:u}=J.useElementSize(),d=C.default.useMemo(()=>!Array.isArray(r)||r.length===0,[r]),p=nc(r,{w:s,h:u});return rc.includes(n.type)?o("div",{className:"viz-root",style:{height:t},ref:l,children:o(ke,{children:p})}):i?o("div",{className:"viz-root",style:{height:t},ref:l,children:o(a.LoadingOverlay,{visible:i,exitTransitionDuration:0})}):g("div",{className:"viz-root",style:{height:t},ref:l,children:[d&&o(a.Text,{color:"gray",align:"center",children:"Empty Data"}),!d&&o(ke,{children:p})]})}),ic=E.observer(()=>{const{data:e,loading:t,panel:{viz:n}}=ee();return o(ai,{viz:n,data:e,loading:t,height:"100%"})}),bn=[];function oc(){const{vizManager:e}=w.useContext(xe);return w.useMemo(()=>e.availableVizList.map(t=>({value:t.name,label:t.displayName})).concat(bn),[e])}function ac(e,t){try{return e.resolveComponent(t).createConfig()}catch{return null}}function lc(){const{data:e,panel:{viz:t,title:n,queryID:r,description:i,setDescription:l,setTitle:s,setQueryID:u,id:d,style:p}}=ee(),{vizManager:c}=w.useContext(xe),f={title:n,description:i,viz:t,queryID:r,id:d,style:p.json},m={setDescription:l,setQueryID:u,setTitle:s};try{return c.resolveComponent(f.viz.type),o(ec,{setVizConf:t.setConf,panel:f,panelInfoEditor:m,vizManager:c,data:e})}catch(v){return console.info(_.get(v,"message")),null}}const sc=E.observer(()=>{const{data:e,panel:{viz:t}}=ee(),[n,r]=J.useInputState(t.type),i=t.type!==n,{vizManager:l}=w.useContext(xe),s=C.default.useCallback(()=>{if(!i)return;const v=ac(l,n);t.setType(n),t.setConf(v||{})},[t,i,n]),u=v=>{try{t.setConf(JSON.parse(v))}catch(b){console.error(b)}},d=C.default.useMemo(()=>{var v;return(v=bn.find(b=>b.value===n))==null?void 0:v.Panel},[n,bn]),p=lc(),c=d?w.createElement(d,{data:e,conf:t.conf,setConf:t.setConf}):null,f=p||c,m=oc();return g(U,{children:[o(a.Select,{label:"Visualization",value:n,onChange:r,data:m,rightSection:o(a.ActionIcon,{disabled:!i,onClick:s,children:o(V.DeviceFloppy,{size:20})})}),f,!f&&o(a.JsonInput,{minRows:20,label:"Config",value:JSON.stringify(t.conf,null,2),onChange:u})]})});function uc(){return g(a.Group,{grow:!0,noWrap:!0,align:"stretch",sx:{height:"100%",overflow:"hidden"},children:[o(a.Stack,{sx:{width:"40%",flexShrink:0,flexGrow:0,overflow:"scroll",height:"100%"},children:o(sc,{})}),o(a.Box,{sx:{height:"100%",flexGrow:1,maxWidth:"60%"},children:o(ic,{})})]})}const dc=E.observer(function({opened:t,close:n}){const{freezeLayout:r}=C.default.useContext(ce),[i,l]=w.useState("Visualization"),{panel:s,loading:u}=ee(),{id:d,title:p}=s;return C.default.useEffect(()=>{r(t)},[t]),o(a.Modal,{size:"96vw",overflow:"inside",opened:t,onClose:n,title:`Editing Panel - ${p.trim()?p:d}`,trapFocus:!0,onDragStart:c=>{c.stopPropagation()},children:o(a.AppShell,{sx:{height:"90vh",maxHeight:"calc(100vh - 185px)",".mantine-AppShell-body":{height:"100%"},main:{height:"100%",minHeight:"unset",maxHeight:"100%",width:"100%",padding:"16px"}},padding:"md",children:g(a.Tabs,{value:i,onTabChange:l,className:"panel-settings-tabs",children:[g(a.Tabs.List,{children:[o(a.Tabs.Tab,{value:"Data",children:"Data"}),o(a.Tabs.Tab,{value:"Panel",children:"Panel"}),o(a.Tabs.Tab,{value:"Visualization",children:"Visualization"}),o(a.Tabs.Tab,{value:"Interactions",children:"Interactions"})]}),g(a.Tabs.Panel,{value:"Data",pt:"sm",children:[o(a.LoadingOverlay,{visible:u,exitTransitionDuration:0}),o(Zd,{})]}),o(a.Tabs.Panel,{value:"Panel",pt:"sm",children:i==="Panel"&&o(Kd,{})}),o(a.Tabs.Panel,{value:"Visualization",pt:"sm",children:i==="Visualization"&&o(uc,{})}),o(a.Tabs.Panel,{value:"Interactions",pt:"sm",children:o(ke,{children:o(Qd,{})})})]})})})}),cc=E.observer(({view:e})=>{const t=Y(),n=be.useModals(),[r,i]=C.default.useState(!1),l=()=>i(!0),s=()=>i(!1),{panel:u}=ee(),{id:d,queryID:p}=u,{inEditMode:c}=C.default.useContext(ce),f=()=>t.queries.refetchDataByQueryID(p),{viewPanelInFullScreen:m,inFullScreen:v}=C.default.useContext(Mt),b=()=>{e.panels.duplicateByID(d)},I=()=>n.openConfirmModal({title:"Delete this panel?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>e.panels.removeByID(d)}),A=C.default.useCallback(()=>{m(d)},[d,m]);return g(U,{children:[o(a.Box,{sx:{position:"absolute",top:0,left:0,right:0,zIndex:300},children:g(a.Menu,{withinPortal:!0,children:[o(a.Menu.Target,{children:o(a.Box,{className:"panel-dropdown-target",sx:{width:"100%",height:"25px"}})}),g(a.Menu.Dropdown,{children:[o(a.Menu.Item,{onClick:f,icon:o(V.Refresh,{size:14}),children:"Refresh"}),o(a.Menu.Item,{onClick:()=>t.queries.downloadDataByQueryID(p),icon:o(V.Download,{size:14}),children:"Download Data"}),!v&&o(a.Menu.Item,{onClick:A,icon:o(V.ArrowsMaximize,{size:14}),children:"Full Screen"}),c&&g(U,{children:[o(a.Divider,{label:"Edit",labelPosition:"center"}),o(a.Menu.Item,{onClick:l,icon:o(V.Settings,{size:14}),children:"Settings"}),o(a.Menu.Item,{onClick:b,icon:o(V.Copy,{size:14}),children:"Duplicate"}),o(a.Menu.Item,{color:"red",onClick:I,icon:o(V.Trash,{size:14}),children:"Delete"})]})]})]})}),c&&o(dc,{opened:r,close:s})]})}),Tg="",gc=E.observer(function(){const{panel:t}=ee(),{title:n}=t;return n?o(a.Group,{grow:!0,position:"center",px:20,className:"panel-title-wrapper",sx:{flexGrow:1},children:o(a.Text,{align:"center",lineClamp:1,weight:"bold",children:n})}):null});function pc(e){return!["richText"].includes(e)}const fc={border:"1px solid #ced4da"},hc={border:"1px dashed transparent",transition:"border-color 300ms ease","&:hover":{borderColor:"#ced4da"}},ht=E.observer(function({panel:t,view:n}){const r=Y(),{data:i,state:l}=r.getDataStuffByID(t.queryID),s=pc(t.viz.type)&&l==="loading",u=t.title?"calc(100% - 25px - 5px)":"100%",d=t.style.border.enabled?fc:hc;return o(Qn,{value:{panel:t,data:i,loading:s},children:g(a.Box,{className:"panel-root",p:5,pt:0,sx:{...d},children:[o(a.Box,{sx:{position:"absolute",left:0,top:0,height:28,zIndex:310},children:o(ar,{})}),o(cc,{view:n}),o(gc,{}),o(ai,{viz:t.viz,data:i,loading:s,height:u})]})})}),li=E.observer(function({view:t,panel:n,exitFullScreen:r}){return g(a.Stack,{px:"10px",pb:"5px",sx:{height:"100%",flexGrow:1,justifyContent:"flex-start"},children:[o(a.Group,{mx:"-5px",sx:{flexGrow:0},children:o(a.Button,{variant:"default",size:"sm",onClick:r,leftIcon:o(V.ArrowLeft,{size:20}),children:"Exit fullscreen"})}),o(a.Group,{mx:"-5px",grow:!0,sx:{flexGrow:1,flexShrink:0},children:o(ht,{view:t,panel:n})})]})});function si(e){const[t,n]=C.default.useState(null),r=C.default.useCallback(u=>{n(u)},[]),i=C.default.useCallback(()=>{n(null)},[]),l=t?e.panels.findByID(t):null;return{viewPanelInFullScreen:r,exitFullScreen:i,inFullScreen:!!l,fullScreenPanel:l}}function ui(){C.default.useEffect(()=>{const e=so.default(".dashboard-sticky-area",{useStickyClasses:!0,parentClass:"dashboard-sticky-parent"});return()=>{e==null||e.cleanup()}},[])}const Fg="",mc=C.default.forwardRef(({handleAxis:e},t)=>o(a.ActionIcon,{ref:t,className:"react-grid-customDragHandle",sx:{userSelect:"none",cursor:"grab",position:"absolute",top:0,right:0,zIndex:400,"&:hover":{color:"#228be6"}},variant:"transparent",children:o(V.ArrowsMove,{size:16})})),vc=C.default.forwardRef(({handleAxis:e,...t},n)=>o(a.ActionIcon,{ref:n,className:"react-grid-customResizeHandle",sx:{userSelect:"none",cursor:"nwse-resize",position:"absolute",bottom:-5,right:-5,zIndex:400,"&:hover":{color:"#228be6"}},variant:"transparent",...t,children:o(V.ChevronDownRight,{size:16})})),yc=Dt.WidthProvider(zn.default),bc=E.observer(function({view:t,className:n="layout",rowHeight:r=10,isDraggable:i,isResizable:l}){const s=C.default.useCallback(u=>{u.forEach(({i:d,...p})=>{const c=t.panels.findByID(d);!c||c.layout.set(p)})},[t]);return o(yc,{onLayoutChange:s,className:`dashboard-layout ${n}`,rowHeight:r,layout:t.panels.layouts,isDraggable:i,isResizable:l,draggableHandle:".react-grid-customDragHandle",resizeHandle:o(vc,{}),children:t.panels.list.map((u,d)=>g("div",{"data-grid":{...u.layout},style:{position:"relative"},children:[i&&o(mc,{}),o(ht,{view:t,panel:u})]},u.id))})}),Cc=Dt.WidthProvider(zn.default),xc=E.observer(function({view:t,className:n="layout",rowHeight:r=10}){return o(Cc,{className:`dashboard-layout ${n}`,rowHeight:r,isDraggable:!1,isResizable:!1,layout:t.panels.layouts,children:t.panels.list.map(i=>o("div",{"data-grid":i.layout,children:o(ht,{view:t,panel:i})},i.id))})}),Sc=E.observer(({children:e})=>o(a.Box,{children:e})),wc=E.observer(({children:e,view:t})=>o(a.Modal,{size:t.config.width,overflow:"inside",opened:!0,onClose:z.default.noop,withCloseButton:!1,title:t.name,trapFocus:!0,onDragStart:n=>{n.stopPropagation()},styles:{root:{position:"relative",height:"calc(100% - 46px)"},overlay:{position:"absolute !important"},modal:{border:"1px solid #efefef"},body:{"> div":{maxHeight:t.config.height,overflow:"scroll"}}},withinPortal:!1,transitionDuration:0,children:e})),_c=E.observer(({view:e,children:t})=>{switch(e.type){case ve.Modal:return o(wc,{view:e,children:t});case ve.Division:default:return o(Sc,{children:t})}}),di=E.observer(function({view:t,saveDashboardChanges:n}){const{viewPanelInFullScreen:r,exitFullScreen:i,inFullScreen:l,fullScreenPanel:s}=si(t);return ui(),o(Mt.Provider,{value:{viewPanelInFullScreen:r,inFullScreen:l},children:g(a.Box,{className:"dashboard-view",mx:-10,sx:{position:"relative",height:"100%"},children:[l&&o(li,{view:t,panel:s,exitFullScreen:i}),!l&&o(or,{saveChanges:n}),o(_c,{view:t,children:g(a.Box,{className:"dashboard-sticky-parent",children:[o(a.Box,{className:"dashboard-sticky-area",children:o(Wn,{view:t})}),o(a.Box,{sx:{display:l?"none":"block"},children:o(bc,{view:t,isDraggable:!0,isResizable:!0})})]})})]})})}),ci=E.observer(function({view:t}){const{viewPanelInFullScreen:n,exitFullScreen:r,inFullScreen:i,fullScreenPanel:l}=si(t);return ui(),o(Mt.Provider,{value:{viewPanelInFullScreen:n,inFullScreen:i},children:g(a.Box,{className:"dashboard-view",sx:{position:"relative",height:"100%"},children:[i&&o(li,{view:t,panel:l,exitFullScreen:r}),!i&&g(a.Box,{className:"dashboard-sticky-area",children:[o(or,{saveChanges:z.default.noop}),o(Wn,{view:t})]}),o(xc,{view:t})]})})}),gi=y.types.model({label:y.types.string,value:y.types.string}).actions(e=>({setLabel(t){e.label=t},setValue(t){e.value=t}})),pi=y.types.model("FilterConfigModel_Select",{required:y.types.boolean,default_value:y.types.string,static_options:y.types.optional(y.types.array(gi),[]),options_query:Kn}).actions(e=>({addStaticOption(t){e.static_options.push(t)},removeStaticOption(t){e.static_options.splice(t,1)},setRequired(t){e.required=t},setDefaultValue(t){e.default_value=t},setOptionsQuery(t){e.options_query=t}})),Ic=()=>pi.create({required:!1,default_value:"",static_options:[],options_query:{type:me.Postgresql,key:"",sql:""}}),fi=y.types.model("FilterConfigModel_MultiSelect",{default_value:y.types.optional(y.types.array(y.types.string),[]),static_options:y.types.optional(y.types.array(gi),[]),options_query:Kn}).actions(e=>({addStaticOption(t){e.static_options.push(t)},removeStaticOption(t){e.static_options.splice(t,1)},setDefaultValue(t){e.default_value=y.cast(t)},setOptionsQuery(t){e.options_query=t}})),Dc=()=>fi.create({default_value:[],static_options:[],options_query:{type:me.Postgresql,key:"",sql:""}}),hi=y.types.model("FilterConfigModel_Checkbox",{default_value:y.types.boolean}).actions(e=>({setDefaultValue(t){e.default_value=t}})),Ac=()=>hi.create({default_value:!1}),Mc=y.types.model("FilterConfigModel_DateRange",{required:y.types.boolean,inputFormat:y.types.enumeration("DateRangeInputFormat",["YYYY","YYYY-MM","YYYY-MM-DD"]),default_value:y.types.optional(y.types.array(y.types.union(y.types.Date,y.types.null)),[null,null]),clearable:y.types.boolean}).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)}})),mi=y.types.snapshotProcessor(Mc,{preProcessor({default_value:e,...t}){return{...t,default_value:e.map(n=>n===null?null:new Date(n))}},postProcessor({default_value:e,...t}){return{...t,default_value:e.map(n=>{try{return typeof n=="number"?new Date(n).toISOString():null}catch{return console.log(`[date-range] failed parsing ${n}`),null}})}}}),Vc=()=>mi.create({required:!1,inputFormat:"YYYY-MM-DD",clearable:!1,default_value:[null,null]}),Cn=y.types.model("FilterModel",{id:y.types.identifier,key:y.types.string,label:y.types.string,order:y.types.number,visibleInViewsIDs:y.types.array(y.types.string),type:y.types.enumeration("DashboardFilterType",[le.Select,le.MultiSelect,le.TextInput,le.Checkbox,le.DateRange]),config:y.types.union(pi,fi,Zn,hi,mi)}).views(e=>({get plainDefaultValue(){const t=e.config.default_value;return Array.isArray(t)?[...t]:t}})).actions(e=>({setKey(t){e.key=t},setLabel(t){e.label=t},setOrder(t){e.order=t},setType(t){switch(t){case le.Select:e.config=Ic();break;case le.MultiSelect:e.config=Dc();break;case le.TextInput:e.config=er();break;case le.Checkbox:e.config=Ac();break;case le.DateRange:e.config=Vc();break}e.type=t},setVisibleInViewsIDs(t){e.visibleInViewsIDs.length=0,e.visibleInViewsIDs.push(...t)}}));function Ec(e){return e===void 0?e:Array.isArray(e)?e.map(t=>{const n=new Date(t);return n!=null?n:t}):e}function vi(e){return e.reduce((t,n)=>(t[n.key]=Ec(n.config.default_value),t),{})}const yi=y.types.model("FiltersModel",{original:y.types.optional(y.types.array(Cn),[]),current:y.types.optional(y.types.array(Cn),[]),values:y.types.optional(y.types.frozen(),{})}).views(e=>({get changed(){return!z.default.isEqual(e.original,e.current)},get firstID(){if(e.current.length!==0)return e.current[0].id},get inOrder(){return z.default.sortBy(e.current,"order")},get empty(){return e.current.length===0},visibleInView(t){return z.default.sortBy(e.current.filter(n=>n.visibleInViewsIDs.includes(t)),"order")},get triggerForRefreshValues(){return e.current.map(n=>{var r;return(r=n.config.default_value)==null?void 0:r.toString()}).join("__")}})).actions(e=>({reset(){e.current=z.default.cloneDeep(e.original)},replace(t){e.current=y.cast(t)},append(t){e.current.push(t)},remove(t){e.current.splice(t,1)},setValues(t){e.values=t},setValueByKey(t,n){e.values[t]=n},getValueByKey(t){return e.values[t]},refreshValues(){console.log("refreshing values");const t=vi(e.current);e.values=t}})).actions(e=>({afterCreate(){y.addDisposer(e,K.reaction(()=>e.triggerForRefreshValues,e.refreshValues,{fireImmediately:!0,delay:0}))}}));function bi(e){return{original:e,current:e,values:vi(e)}}var xn={exports:{}};(function(e,t){(function(n,r){r()})(Ne,function(){function n(p,c){return typeof c>"u"?c={autoBom:!1}:typeof c!="object"&&(console.warn("Deprecated: Expected third argument to be a object"),c={autoBom:!c}),c.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(p.type)?new Blob(["\uFEFF",p],{type:p.type}):p}function r(p,c,f){var m=new XMLHttpRequest;m.open("GET",p),m.responseType="blob",m.onload=function(){d(m.response,c,f)},m.onerror=function(){console.error("could not download file")},m.send()}function i(p){var c=new XMLHttpRequest;c.open("HEAD",p,!1);try{c.send()}catch{}return 200<=c.status&&299>=c.status}function l(p){try{p.dispatchEvent(new MouseEvent("click"))}catch{var c=document.createEvent("MouseEvents");c.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),p.dispatchEvent(c)}}var s=typeof window=="object"&&window.window===window?window:typeof self=="object"&&self.self===self?self:typeof Ne=="object"&&Ne.global===Ne?Ne:void 0,u=s.navigator&&/Macintosh/.test(navigator.userAgent)&&/AppleWebKit/.test(navigator.userAgent)&&!/Safari/.test(navigator.userAgent),d=s.saveAs||(typeof window!="object"||window!==s?function(){}:"download"in HTMLAnchorElement.prototype&&!u?function(p,c,f){var m=s.URL||s.webkitURL,v=document.createElement("a");c=c||p.name||"download",v.download=c,v.rel="noopener",typeof p=="string"?(v.href=p,v.origin===location.origin?l(v):i(v.href)?r(p,c,f):l(v,v.target="_blank")):(v.href=m.createObjectURL(p),setTimeout(function(){m.revokeObjectURL(v.href)},4e4),setTimeout(function(){l(v)},0))}:"msSaveOrOpenBlob"in navigator?function(p,c,f){if(c=c||p.name||"download",typeof p!="string")navigator.msSaveOrOpenBlob(n(p,f),c);else if(i(p))r(p,c,f);else{var m=document.createElement("a");m.href=p,m.target="_blank",setTimeout(function(){l(m)})}}:function(p,c,f,m){if(m=m||open("","_blank"),m&&(m.document.title=m.document.body.innerText="downloading..."),typeof p=="string")return r(p,c,f);var v=p.type==="application/octet-stream",b=/constructor/i.test(s.HTMLElement)||s.safari,I=/CriOS\/[\d]+/.test(navigator.userAgent);if((I||v&&b||u)&&typeof FileReader<"u"){var A=new FileReader;A.onloadend=function(){var B=A.result;B=I?B:B.replace(/^data:[^;]*;/,"data:attachment/file;"),m?m.location.href=B:location=B,m=null},A.readAsDataURL(p)}else{var T=s.URL||s.webkitURL,k=T.createObjectURL(p);m?m.location=k:location.href=k,m=null,setTimeout(function(){T.revokeObjectURL(k)},4e4)}});s.saveAs=d.saveAs=d,e.exports=d})})(xn);function Rc(e,t){const n=new Blob([t],{type:"text/csv"});xn.exports.saveAs(n,`${e}.csv`)}function Tc(e){const t=new uo.default;e.forEach(({id:n,data:r})=>{t.file(`${n}.csv`,Ci(r))}),t.generateAsync({type:"blob"}).then(n=>{xn.exports.saveAs(n,"dashboard_data.zip")})}function Ci(e){if(!Array.isArray(e)||e.length===0)return"";const t=[],n=Object.keys(e[0]);return t.push(n.join(",")),e.forEach(r=>{const i=Object.values(r).join(",");t.push(i)}),t.join(`
81
+ `}}const od={legend:{show:!0,bottom:0,left:0},tooltip:{trigger:"item"}};function ad(e,t){const n=["#66B4DB","#39BFA2","#E46464","#33A678","#EEBA00","#9D88CB","#939943","#E49792","#09A2B8","#AF5F6B","#6CA157","#09A2B8","#6398C7","#E692BA","#97B566","#8CACE2","#CA79AC","#6DBC80","#B08F4B","#826BAF"],r=e.dimensions.map(({name:s,max:u})=>({name:s,max:u})),i=t.map(s=>({value:e.dimensions.map(({data_key:u})=>s[u]),name:s[e.series_name_key]})),l={radar:{indicator:r,splitArea:{show:!1}},tooltip:{formatter:id(e)},legend:{show:!0,left:"center"},series:{type:"radar",data:i,symbolSize:4,lineStyle:{width:1},areaStyle:{opacity:.4},label:rd(e)},color:n};return z.default.merge({},od,l)}const fn={series_name_key:"name",dimensions:[]};Z.use([he.RadarChart,W.GridComponent,W.LegendComponent,W.TooltipComponent,we.CanvasRenderer]);function ld({context:e}){const{value:t}=L(e.instanceData,"config"),{width:n,height:r}=e.viewport,i=e.data,l=w.useMemo(()=>ad(_.defaultsDeep({},t,fn),i),[t,i]);return!n||!r||!t||_.isEmpty(t==null?void 0:t.dimensions)?null:o(a.Box,{children:o(_e.default,{echarts:Z,option:l,style:{width:n,height:r}})})}function sd({control:e,index:t,remove:n,data:r}){return g(a.Stack,{my:0,p:"md",pr:40,sx:{border:"1px solid #eee",position:"relative"},children:[g(a.Group,{grow:!0,noWrap:!0,children:[o(S.Controller,{name:`dimensions.${t}.name`,control:e,render:({field:i})=>o(a.TextInput,{label:"Name",required:!0,sx:{flex:1},...i})}),o(S.Controller,{name:`dimensions.${t}.data_key`,control:e,render:({field:i})=>o(Q,{label:"Data Key",required:!0,data:r,sx:{flex:1},...i})}),o(S.Controller,{name:`dimensions.${t}.max`,control:e,render:({field:i})=>o(a.NumberInput,{label:"Max",hideControls:!0,required:!0,sx:{flex:1},...i})})]}),g(a.Stack,{children:[o(a.Divider,{mb:-15,variant:"dashed",label:"Value Formatter",labelPosition:"center"}),o(S.Controller,{name:`dimensions.${t}.formatter`,control:e,render:({field:i})=>o(Ot,{...i})})]}),o(a.ActionIcon,{color:"red",variant:"subtle",onClick:()=>n(t),sx:{position:"absolute",top:15,right:5},disabled:t===0,children:o(V.Trash,{size:16})})]},t)}function ud({control:e,watch:t,data:n}){const{fields:r,append:i,remove:l}=S.useFieldArray({control:e,name:"dimensions"}),s=t("dimensions"),u=r.map((p,c)=>({...p,...s[c]})),d=()=>i({name:J.randomId(),data_key:"",max:100,formatter:je});return g(a.Stack,{children:[u.map((p,c)=>o(sd,{data:n,control:e,index:c,remove:l})),o(a.Group,{position:"center",mt:"xs",children:o(a.Button,{onClick:d,children:"Add a Dimension"})})]})}function dd(e){function t({name:n="",data_key:r="",max:i=10,formatter:l=je}){return{name:n,data_key:r,max:i,formatter:l}}return e.map(t)}function cd({context:e}){const t=e.data,{value:n,set:r}=L(e.instanceData,"config"),i=w.useMemo(()=>_.defaultsDeep({},n,fn),[n]),{dimensions:l,series_name_key:s}=i,u=w.useMemo(()=>({dimensions:dd(l!=null?l:[]),series_name_key:s}),[l,s]);w.useEffect(()=>{!_.isEqual(i,u)&&r(u)},[i,u]);const{control:d,handleSubmit:p,watch:c,getValues:f,reset:m}=S.useForm({defaultValues:u});w.useEffect(()=>{_.isEqual(f(),u)||m(u)},[i]),c(["series_name_key"]);const v=f(),b=w.useMemo(()=>!_.isEqual(v,i),[v,i]);return o(a.Stack,{mt:"md",spacing:"xs",children:g("form",{onSubmit:p(r),children:[g(a.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[o(a.Text,{children:"Chart Config"}),o(a.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!b,children:o(V.DeviceFloppy,{size:20})})]}),o(a.Box,{py:"sm",children:o(S.Controller,{name:"series_name_key",control:d,render:({field:I})=>o(Q,{label:"Series Name Field",required:!0,data:t,sx:{flex:1},...I})})}),o(ud,{control:d,watch:c,data:t})]})})}class gd extends ge{constructor(){super(...arguments);$(this,"VERSION",1)}configVersions(){this.version(1,n=>({version:1,config:n}))}}const pd={displayName:"Radar Chart",migrator:new gd,name:"radar",viewRender:ld,configRender:cd,createConfig:()=>fn};function fd(e,t){switch(e.config.method){case"linear":return[...Ie.regressionLinear()(t)];case"exponential":return[...Ie.regressionExp()(t)];case"logarithmic":return[...Ie.regressionLog()(t)];case"polynomial":return[...Ie.regressionPoly().order(e.config.order)(t)];default:return[]}}function hd({regression:e},t){const n=[],r=[];if(t.length===0)return{regressionSeries:n,regressionXAxes:r};const{transform:i,plot:l,name:s}=e,u=fd(i,t);return n.push({...l,name:s,data:u,showSymbol:!1,smooth:!0,tooltip:{show:!1}}),{regressionSeries:n,regressionXAxes:r}}const md={tooltip:{trigger:"axis"},grid:{top:10,left:30,right:15,bottom:30,containLabel:!0},dataZoom:[{type:"inside",xAxisIndex:[0]},{type:"inside",yAxisIndex:[0]}]};function vd(e,t){var l,s;const n=z.default.uniqBy(t.map(u=>[u[e.x_axis.data_key],u[e.regression.y_axis_data_key]]),0),{regressionSeries:r}=hd(e,n),i={xAxis:{type:"category",name:(l=e.x_axis.name)!=null?l:""},yAxis:{name:(s=e.y_axis.name)!=null?s:""},series:[{data:n,name:e.y_axis.name,type:"scatter",symbolSize:4,color:"red"},...r]};return _.defaultsDeep({},i,md)}function ft(e,t,n){return 1-(1-e)*(t-1)/(t-n-1)}function yd(e,t){if(!t)return{expression:"",rSquared:0,adjustedRSquared:0};const{regression:n,x_axis:r,y_axis:i}=t,l=e.map(s=>[s[r.data_key],s[n.y_axis_data_key]]);if(n.transform.config.method==="linear"){const s=Ie.regressionLinear()(l),{a:u,b:d,rSquared:p}=s;return{expression:g(a.Group,{position:"center",noWrap:!0,spacing:10,children:[o(a.Text,{children:i.name}),o(a.Text,{children:"="}),o(a.Text,{weight:"bold",color:"gray",children:d}),o(a.Text,{children:"+"}),o(a.Text,{weight:"bold",color:"gray",children:u}),o(a.Text,{children:"\xD7"}),o(a.Text,{children:r.name})]}),rSquared:p,adjustedRSquared:ft(p,e.length,1)}}if(n.transform.config.method==="exponential"){const{a:s,b:u,rSquared:d}=Ie.regressionExp()(l);return{expression:g(a.Group,{position:"center",noWrap:!0,spacing:10,children:[o(a.Text,{children:i.name}),o(a.Text,{children:"="}),o(a.Text,{weight:"bold",color:"gray",children:s}),o(a.Text,{children:"\xD7"}),g(a.Group,{position:"left",noWrap:!0,spacing:2,children:[o(a.Text,{children:"Math.exp("}),o(a.Text,{weight:"bold",color:"gray",children:u}),o(a.Text,{children:"\xD7"}),o(a.Text,{children:r.name}),o(a.Text,{children:")"})]})]}),rSquared:d,adjustedRSquared:ft(d,e.length,1)}}if(n.transform.config.method==="logarithmic"){const{a:s,b:u,rSquared:d}=Ie.regressionLog()(l);return{expression:g(a.Group,{position:"center",noWrap:!0,spacing:10,children:[o(a.Text,{children:i.name}),o(a.Text,{children:"="}),o(a.Text,{weight:"bold",color:"gray",children:s}),o(a.Text,{children:"\xD7"}),g(a.Group,{position:"left",noWrap:!0,spacing:2,children:[o(a.Text,{children:"Math.log("}),o(a.Text,{children:r.name}),o(a.Text,{children:")"}),o(a.Text,{children:"+"}),o(a.Text,{weight:"bold",color:"gray",children:u})]})]}),rSquared:d,adjustedRSquared:ft(d,e.length,1)}}if(n.transform.config.method==="polynomial"){const s=Ie.regressionPoly().order(n.transform.config.order)(l),{rSquared:u}=s;return console.log(s),{expression:"",rSquared:u,adjustedRSquared:ft(u,e.length,1)}}return{expression:"",rSquared:0}}const hn={x_axis:{name:"X Axis",data_key:""},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",y_axis_data_key:"value"}};Z.use([W.DataZoomComponent,he.ScatterChart,W.GridComponent,W.LegendComponent,W.TooltipComponent,we.CanvasRenderer]),Z.registerTransform($n.transform.regression);function bd({context:e}){const{value:t}=L(e.instanceData,"config"),{width:n,height:r}=e.viewport,i=w.useMemo(()=>{var m;const c=e.data,f=(m=t==null?void 0:t.regression)==null?void 0:m.y_axis_data_key;return f?c.map(v=>typeof v[f]=="number"?v:{...v,[f]:Number(v[f])}):c},[e.data,t==null?void 0:t.regression.y_axis_data_key]),l=w.useMemo(()=>vd(_.defaultsDeep({},t,hn),i),[t,i]),{expression:s,rSquared:u,adjustedRSquared:d}=w.useMemo(()=>yd(i,t),[t,i]);if(!n||!r||!t)return null;let p=r;return s&&(p-=20),g(a.Box,{children:[s&&o(a.Text,{align:"center",size:12,children:s}),g(a.Group,{spacing:0,noWrap:!0,align:"start",sx:{"> *":{flexGrow:0,flexShrink:0}},children:[o(_e.default,{echarts:Z,option:l,style:{width:n-190,height:p}}),u&&o(a.Table,{mt:20,fontSize:12,sx:{width:180,border:"1px solid #999",td:{padding:"3px 8px"}},children:g("tbody",{children:[g("tr",{children:[o("td",{children:"R-Sq"}),o("td",{style:{textAlign:"right"},children:ae.default(u).format({output:"percent",mantissa:1})})]}),g("tr",{children:[o("td",{children:"R-Sq(Adjusted)"}),o("td",{style:{textAlign:"right"},children:ae.default(d).format({output:"percent",mantissa:1})})]})]})})]})]})}const Cd=[{label:"Linear",value:"linear"},{label:"Exponential",value:"exponential"},{label:"Logarithmic",value:"logarithmic"},{label:"Polynomial",value:"polynomial"}];function xd({control:e,watch:t,data:n}){const r=t("regression.transform.config.method");return g(a.Stack,{children:[g(a.Group,{grow:!0,noWrap:!0,children:[o(S.Controller,{name:"regression.name",control:e,render:({field:i})=>o(a.TextInput,{label:"Name",required:!0,sx:{flex:1},...i})}),o(S.Controller,{name:"regression.y_axis_data_key",control:e,render:({field:i})=>o(Q,{label:"Value Field",required:!0,data:n,sx:{flex:1},...i})})]}),g(a.Group,{grow:!0,noWrap:!0,children:[o(S.Controller,{name:"regression.transform.config.method",control:e,render:({field:i})=>o(a.Select,{label:"Method",data:Cd,sx:{flex:1},...i})}),r==="polynomial"&&o(S.Controller,{name:"regression.transform.config.order",control:e,render:({field:i})=>o(a.NumberInput,{label:"Order",sx:{flex:1},...i})})]}),g(a.Stack,{spacing:4,children:[o(a.Text,{size:"sm",children:"Color"}),o(S.Controller,{name:"regression.plot.color",control:e,render:({field:i})=>o(De,{...i})})]})]})}function Sd({context:e}){const{value:t,set:n}=L(e.instanceData,"config"),r=e.data,i=w.useMemo(()=>_.defaults({},t,hn),[t]),{control:l,handleSubmit:s,watch:u,getValues:d,reset:p}=S.useForm({defaultValues:i});w.useEffect(()=>{p(i)},[i]),u(["x_axis","y_axis","regression"]);const c=d(),f=w.useMemo(()=>!_.isEqual(c,t),[c,t]);return o(a.Stack,{mt:"md",spacing:"xs",children:g("form",{onSubmit:s(n),children:[g(a.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[o(a.Text,{children:"Chart Config"}),o(a.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!f,children:o(V.DeviceFloppy,{size:20})})]}),g(a.Accordion,{multiple:!0,defaultValue:["Axis","Regression"],children:[g(a.Accordion.Item,{value:"Axis",children:[o(a.Accordion.Control,{children:"Axis"}),g(a.Accordion.Panel,{children:[g(a.Group,{grow:!0,noWrap:!0,children:[o(S.Controller,{name:"x_axis.name",control:l,render:({field:m})=>o(a.TextInput,{label:"X Axis Name",sx:{flex:1},...m})}),o(S.Controller,{name:"x_axis.data_key",control:l,render:({field:m})=>o(Q,{label:"X Axis Data Field",required:!0,data:r,sx:{flex:1},...m})})]}),o(a.Group,{grow:!0,noWrap:!0,children:o(S.Controller,{name:"y_axis.name",control:l,render:({field:m})=>o(a.TextInput,{label:"Y Axis Name",sx:{flex:1},...m})})})]})]}),g(a.Accordion.Item,{value:"Regression",children:[o(a.Accordion.Control,{children:"Regression Line"}),o(a.Accordion.Panel,{children:o(xd,{control:l,watch:u,data:r})})]})]})]})})}class wd extends ge{constructor(){super(...arguments);$(this,"VERSION",1)}configVersions(){this.version(1,n=>({version:1,config:n}))}}const _d={displayName:"Regression Chart",migrator:new wd,name:"regressionChart",viewRender:bd,configRender:Sd,createConfig:()=>hn},mn={x_axis:{name:"X Axis",data_key:""},data_key:"value",bar:{name:"Value",color:"#228be6"},line:{name:"Value",color:"red"}};function vn(e){return ae.default(e).format({output:"percent",mantissa:0})}function Id(e){const t=e.value[1];try{return vn(t)}catch(n){return console.error(n),t}}function Dd(e){const t=Array.isArray(e)?e:[e];if(t.length===0)return"";const n=t.map((r,i)=>{const l=r.seriesName,[s,u]=r.value;return l?`${l}: <strong>${(i===0?p=>p:vn)(u)}</strong>`:u});return n.unshift(`<strong>${t[0].name}</strong>`),n.join("<br />")}Z.use([he.BarChart,he.LineChart,W.DataZoomComponent,W.GridComponent,W.LegendComponent,W.TooltipComponent,we.CanvasRenderer]);function Ad({context:e}){const{value:t}=L(e.instanceData,"config"),n=e.data,{width:r,height:i}=e.viewport,{x_axis:l,data_key:s,bar:u,line:d}=_.defaults({},t,mn),{barData:p,lineData:c}=w.useMemo(()=>{const m=n.map(I=>[I[l.data_key],Number(I[s])]).sort((I,A)=>A[1]-I[1]),v=m.reduce((I,A)=>I+A[1],0),b=m.reduce((I,A,T)=>{const k=T===0?0:I[T-1][1];return I.push([A[0],k+A[1]]),I},[]).map(I=>[I[0],I[1]/v]);return{barData:m,lineData:b}},[l.data_key,s,n]),f={dataZoom:[{type:"inside",xAxisIndex:[0]},{type:"inside",yAxisIndex:[0]}],tooltip:{trigger:"axis",formatter:Dd},xAxis:[{type:"category",name:l.name,nameLocation:"middle",nameGap:30,nameTextStyle:{fontWeight:"bold",align:"right"}}],yAxis:[{name:u.name,nameGap:30,nameTextStyle:{fontWeight:"bold",align:"right"}},{name:d.name,nameGap:30,nameTextStyle:{fontWeight:"bold",align:"center"},axisLabel:{show:!0,formatter:vn}}],series:[{name:u.name,type:"bar",itemStyle:{color:u.color},yAxisIndex:0,data:p},{name:d.name,type:"line",itemStyle:{color:d.color},symbolSize:2,lineStyle:{width:1},label:{show:!0,position:"top",formatter:Id},yAxisIndex:1,data:c}]};return!t||!r||!i?null:o(_e.default,{echarts:Z,option:f,style:{width:r,height:i}})}function Md({context:e}){const{value:t,set:n}=L(e.instanceData,"config"),r=e.data,i=w.useMemo(()=>_.defaults({},t,mn),[t]),{control:l,handleSubmit:s,watch:u,getValues:d,reset:p}=S.useForm({defaultValues:i});w.useEffect(()=>{p(i)},[i]),u(["x_axis","data_key","bar","line"]);const c=d(),f=w.useMemo(()=>!_.isEqual(c,t),[c,t]);return o(a.Stack,{mt:"md",spacing:"xs",children:g("form",{onSubmit:s(n),children:[g(a.Group,{position:"left",py:"md",pl:"md",sx:{borderBottom:"1px solid #eee",background:"#efefef"},children:[o(a.Text,{children:"Chart Config"}),o(a.ActionIcon,{type:"submit",mr:5,variant:"filled",color:"blue",disabled:!f,children:o(V.DeviceFloppy,{size:20})})]}),g(a.Group,{grow:!0,noWrap:!0,children:[o(S.Controller,{name:"x_axis.name",control:l,render:({field:m})=>o(a.TextInput,{label:"X Axis Name",sx:{flex:1},...m})}),o(S.Controller,{name:"x_axis.data_key",control:l,render:({field:m})=>o(Q,{label:"X Axis Data Field",required:!0,data:r,sx:{flex:1},...m})})]}),o(S.Controller,{name:"data_key",control:l,render:({field:m})=>o(Q,{label:"Y Axis Data Field",required:!0,data:r,sx:{flex:1},...m})}),o(a.Divider,{my:"md",label:"Bar",labelPosition:"center"}),g(a.Group,{grow:!0,noWrap:!0,children:[o(S.Controller,{name:"bar.name",control:l,render:({field:m})=>o(a.TextInput,{label:"Bar Name",sx:{flex:1},...m})}),g(a.Stack,{spacing:4,children:[o(a.Text,{size:"sm",children:"Bar's Color"}),o(S.Controller,{name:"bar.color",control:l,render:({field:m})=>o(De,{...m})})]})]}),o(a.Divider,{my:"md",label:"Line",labelPosition:"center"}),g(a.Group,{grow:!0,noWrap:!0,children:[o(S.Controller,{name:"line.name",control:l,render:({field:m})=>o(a.TextInput,{label:"Line Name",sx:{flex:1},...m})}),g(a.Stack,{spacing:4,children:[o(a.Text,{size:"sm",children:"Line's Color"}),o(S.Controller,{name:"line.color",control:l,render:({field:m})=>o(De,{...m})})]})]})]})})}class Vd extends ge{constructor(){super(...arguments);$(this,"VERSION",1)}configVersions(){this.version(1,n=>({version:1,config:n}))}}const Ed={displayName:"Pareto Chart",migrator:new Vd,name:"paretoChart",viewRender:Ad,configRender:Md,createConfig:()=>mn},Rd=[{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"})),Td=[xa,Sa,Ia,_a,wa,Da],ti={id:"dashboard",version:Aa,manifest:{viz:[sn,Dl,$a,Hs,Zs,ru,gu,Ed,nd,pd,_d],color:[...Rd,...Td]}},Xe=new Va,ni=()=>{try{Xe.install(ti)}catch{}const e=new ya(Xe),t=new Ma(Xe);return{pluginManager:Xe,vizManager:e,colorManager:t}},xe=w.createContext(ni());try{Xe.install(ti)}catch{}function Fd(e,t){const{value:n,set:r}=L(e.operation.operationData,"config"),[i,l]=w.useState(_.defaults({},n,t)),s=async()=>{await r(i)};return w.useEffect(()=>{l(_.defaults({},n,t))},[n]),{config:i,setConfig:l,commit:s}}function $d(e){const{config:t,setConfig:n,commit:r}=Fd(e,{urlTemplate:"",openInNewTab:!0});async function i(){await r()}async function l(u){n({...t,openInNewTab:u}),await r()}const s=u=>n({...t,urlTemplate:u.currentTarget.value});return g(a.Stack,{children:[o(a.TextInput,{label:"Url",value:t.urlTemplate,onChange:s,onBlur:i}),o(a.Switch,{label:"Open in new Tab",checked:t.openInNewTab,onChange:u=>l(u.currentTarget.checked)})]})}function Pd(e){return _.cloneDeepWith(e,n=>{if(typeof n=="string")return encodeURIComponent(n)})}async function kd(e,t){const{urlTemplate:n,openInNewTab:r}=await t.operationData.getItem("config"),l=_.template(n||"")(Pd(e));window.open(l,r?"_blank":"_self","noopener")}const Od={displayName:"Open Link",id:"builtin:op:open-link",configRender:$d,run:kd};function zd(e){const{value:t,set:n}=L(e.operationData,"config"),r=i=>void n({template:i});return[(t==null?void 0:t.template)||"",r]}function Gd(e){const[t,n]=zd(e.operation);return o(a.TextInput,{defaultValue:t,onBlur:r=>n(r.currentTarget.value),label:"console.log"})}async function Ld(e,t){const n=await t.operationData.getItem("config"),r=_.template(n.template||"");console.log("run with payload",e),console.log(r(e))}const yn=[{displayName:"console.log (debug)",id:"builtin:op:debug",configRender:Gd,run:Ld},Od];class Nd{constructor(t,n=yn){$(this,"attachments");this.operations=n;const r=async i=>{const{id:l,schemaRef:s}=await i.getItem(null);return{id:l,schemaRef:s,operationData:new Oe(i,"data")}};this.attachments=new Ft(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 i=this.operations.find(l=>l.id===r.schemaRef);if(!i){console.warn(`Operation schema '${r.schemaRef}' is not defined`);return}await i.run(n,r)}async createOrGetOperation(t,n){if(!this.getOperationSchemaList().some(s=>s.id===n.id))throw new Error(`Operation schema '${n.id}' is not defined`);const i=await this.attachments.getInstance(t);return!i||i.schemaRef!==n.id?await this.attachments.create(t,{id:t,schemaRef:n.id,data:{}}):i}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 ri="__TRIGGERS";class qd{constructor(t,n){$(this,"attachments");this.instance=t,this.component=n;const r=async i=>{const{id:l,schemaRef:s}=await i.getItem(null);return{id:l,schemaRef:s,triggerData:new Oe(i,"data")}};this.attachments=new Ft(t,ri,r)}watchTriggerSnapshotList(t){return this.instance.instanceData.watchItem(ri,n=>{const r=_.values(n).map(i=>({id:_.get(i,"id"),schemaRef:_.get(i,"schemaRef"),config:K.toJS(_.get(i,"data.config"))}));t(r)},{fireImmediately:!0})}async createOrGetTrigger(t,n,r={recreate:!1}){if(!this.getTriggerSchemaList().some(u=>u.id===n.id))throw new Error(`Trigger schema '${n.id}' is not defined in component '${this.component.name}'`);const l=await this.attachments.getInstance(t);return!l||r.recreate||l.schemaRef!==n.id?await this.attachments.create(t,{id:t,schemaRef:n.id,data:{}}):l}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)}}class ii{constructor(t,n,r){$(this,"operationManager");$(this,"triggerManager");$(this,"attachments");this.operationManager=new Nd(t,r),this.triggerManager=new qd(t,n);const i=async l=>{const{id:s,triggerRef:u,operationRef:d}=await l.getItem(null);return{id:s,triggerRef:u,operationRef:d}};this.attachments=new Ft(t,"__INTERACTIONS",i)}async addInteraction(t,n){const r=t.id,i=n.id,l=`[${r}]:[${i}]`;await this.attachments.create(l,{id:l,triggerRef:r,operationRef:i})}getInteractionList(){return this.attachments.list()}async removeInteraction(t){const n=await this.attachments.getInstance(t);if(!n)return;const{triggerRef:r,operationRef:i}=n;await this.getTriggerRefCount(r)<=1&&await this.triggerManager.removeTrigger(r),await this.getOperationRefCount(i)<=1&&await this.operationManager.removeOperation(i),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 i=(await this.getInteractionList()).filter(l=>l.triggerRef===t);await Promise.all(i.map(async l=>{try{return await this.operationManager.runOperation(l.operationRef,n)}catch(s){console.warn(`Failed to run operation '${l.operationRef}'`,s)}}))}}function Bd(e,t){const[n,r]=w.useState([]);return j.useAsyncEffect(async()=>{const i=await e.getInteractionList();r(i)},[t]),n}const jd=E.observer(({item:e,manager:t,instance:n,sampleData:r,variables:i,onRemove:l})=>{const{triggerRef:s,operationRef:u}=e,d=ga(t.triggerManager,n);if(j.useAsyncEffect(async()=>{await d.configTrigger(s,r)},[d,s,r]),d.isReady()){const p=[...d.triggerSchema.payload,...i];return g(a.Group,{children:[o(ma,{model:d}),o(ua,{instance:n,operationId:u,variables:p,operationManager:t.operationManager}),o(a.Button,{"aria-label":"delete-interaction",variant:"outline",color:"red",onClick:()=>l(e),children:o(V.Trash,{})})]})}return null}),Wd=e=>{const[t,n]=w.useState(0),{interactionManager:r,instance:i,sampleData:l,variables:s}=e,u=Bd(r,t),d=async()=>{const c=await r.triggerManager.createOrGetTrigger(J.randomId(),r.triggerManager.getTriggerSchemaList()[0]),f=await r.operationManager.createOrGetOperation(J.randomId(),r.operationManager.getOperationSchemaList()[0]);await r.addInteraction(c,f),n(m=>m+1)};async function p(c){await r.removeInteraction(c.id),n(f=>f+1)}return g(a.Stack,{children:[u.map(c=>o(jd,{onRemove:p,instance:i,sampleData:l,variables:s,item:c,manager:e.interactionManager},c.id)),o(a.Button,{style:{width:"fit-content"},onClick:()=>d(),children:"Add interaction"})]})},Ud=()=>{const{panel:e,data:t}=ee(),n=e.viz,{vizManager:r}=w.useContext(xe),i=e.json,l=j.useCreation(()=>r.getOrCreateInstance(i),[r,n.type]),s=j.useCreation(()=>new ii(l,r.resolveComponent(n.type),yn),[l,n.type]);return w.useEffect(()=>l.instanceData.watchItem(null,_.throttle(u=>{e.viz.setConf(u)},100,{leading:!1,trailing:!0})),[l]),{instance:l,vizManager:r,interactionManager:s,sampleData:t,variables:[]}},Qd=()=>{const e=Ud();return o(Wd,{...e})},Hd=E.observer(()=>{const{panel:e}=ee(),[t,n]=C.default.useState(e.description),r=e.description!==t,i=C.default.useCallback(()=>{!r||e.setDescription(t)},[r,t]);return g(a.Stack,{spacing:4,sx:{flexGrow:1},children:[g(a.Group,{align:"end",children:[o(a.Text,{sx:{flexGrow:1},children:"Description"}),o(a.ActionIcon,{variant:"subtle",color:"blue",disabled:!r,onClick:i,children:o(V.DeviceFloppy,{size:20})})]}),o(wt.RichTextEditor,{value:t,onChange:n,sx:{flexGrow:1},sticky:!0,p:"0"})]})}),Yd=E.observer(()=>{const{panel:e}=ee(),{style:t}=e;return o(U,{children:o(a.Switch,{label:"Border",checked:t.border.enabled,onChange:n=>t.border.setEnabled(n.currentTarget.checked)})})}),Xd=E.observer(()=>{const{panel:{title:e,style:{border:t}}}=ee();return o(ke,{children:g(a.Stack,{mx:"auto",mt:"xl",p:"5px",spacing:5,sx:{width:"600px",height:"450px",background:"transparent",borderRadius:"5px",border:"1px solid #ced4da",borderWidth:t.enabled?"1px":"0px"},children:[g(a.Group,{position:"apart",noWrap:!0,sx:{flexGrow:0,flexShrink:0},children:[o(a.Group,{children:o(ar,{})}),o(a.Group,{grow:!0,position:"center",children:o(a.Text,{lineClamp:1,weight:"bold",children:e})}),o(a.Group,{position:"right",spacing:0,sx:{height:"28px"}})]}),o(a.Group,{sx:{background:"#eee",flexGrow:1}})]})})}),Jd=E.observer(()=>{const{panel:e}=ee(),{title:t,setTitle:n}=e,[r,i]=J.useInputState(t),l=t!==r,s=C.default.useCallback(()=>{!l||n(r)},[l,r]);return o(a.TextInput,{value:r,onChange:i,label:g(a.Group,{align:"apart",children:[o(a.Text,{sx:{flexGrow:1},children:"Panel Title"}),o(a.ActionIcon,{variant:"subtle",color:"blue",disabled:!l,onClick:s,children:o(V.DeviceFloppy,{size:20})})]}),styles:{label:{display:"block",paddingBottom:"4px"}}})});function Kd(){return g(a.Group,{grow:!0,noWrap:!0,align:"stretch",sx:{height:"100%"},children:[g(a.Stack,{sx:{width:"40%",flexShrink:0,flexGrow:0,height:"100%"},children:[o(a.Divider,{label:"Style",labelPosition:"center",variant:"dashed"}),o(Yd,{}),o(a.Divider,{label:"Info",labelPosition:"center",variant:"dashed"}),o(Jd,{}),o(Hd,{})]}),o(a.Box,{sx:{height:"100%",flexGrow:1,maxWidth:"60%"},children:o(Xd,{})})]})}const Zd=E.observer(function(){const t=Y(),{panel:{queryID:n,setQueryID:r}}=ee(),i=C.default.useMemo(()=>t.queries.current.map(l=>({value:l.id,label:l.id})),[t.queries.current]);return g(a.Stack,{children:[g(a.Group,{position:"left",sx:{maxWidth:"600px",alignItems:"baseline"},children:[o(a.Text,{children:"Select a Query"}),o(a.Select,{data:i,value:n,onChange:r,allowDeselect:!1,clearable:!1,sx:{flexGrow:1}})]}),o(Yn,{id:n})]})});function oi(e,t,n){const r=j.useCreation(()=>new Set,[]),i=e.resolveComponent(t.type),[l,s]=w.useState(!1);return j.useAsyncEffect(async()=>{if(await i.migrator.needMigration(t)&&!r.has(t.id))try{r.add(t.id),await i.migrator.migrate(t),n==null||n()}finally{r.delete(t.id),s(!0)}else s(!0)},[t]),l}function ec({setVizConf:e,...t}){const{vizManager:n,panel:r}=t,i=n.getOrCreateInstance(r),l=oi(n,i,()=>{_t.showNotification({title:`${r.title} - Updated`,message:"Your plugin configuration has been migrated to the latest version"})});return j.useAsyncEffect(async()=>{await i.instanceData.setItem(null,r.viz.conf)},[i,r.viz.type]),w.useEffect(()=>i.instanceData.watchItem(null,s=>{e(s)}),[e,r.viz.type]),l?o(Ca,{...t}):o(a.Text,{children:"Checking update..."})}function tc(e){const{vizManager:t,panel:n}=e,r=t.getOrCreateInstance(n);return oi(t,r,()=>{_t.showNotification({title:`${n.title} - Updated`,message:"Your plugin configuration has been migrated to the latest version"})})?o(ba,{...e}):o(a.Text,{children:"Checking update"})}const Rg="";function nc(e,t){const{vizManager:n}=w.useContext(xe),{panel:{viz:r,title:i,id:l,description:s,queryID:u,style:d}}=ee(),p={title:i,id:l,description:s,queryID:u,viz:r,layout:t,style:d.json};try{return n.resolveComponent(r.type),o(tc,{panel:p,data:e,vizManager:n})}catch(c){return console.info(_.get(c,"message")),null}}const rc=["richText"],ai=E.observer(function({height:t,viz:n,data:r,loading:i}){const{ref:l,width:s,height:u}=J.useElementSize(),d=C.default.useMemo(()=>!Array.isArray(r)||r.length===0,[r]),p=nc(r,{w:s,h:u});return rc.includes(n.type)?o("div",{className:"viz-root",style:{height:t},ref:l,children:o(ke,{children:p})}):i?o("div",{className:"viz-root",style:{height:t},ref:l,children:o(a.LoadingOverlay,{visible:i,exitTransitionDuration:0})}):g("div",{className:"viz-root",style:{height:t},ref:l,children:[d&&o(a.Text,{color:"gray",align:"center",children:"Empty Data"}),!d&&o(ke,{children:p})]})}),ic=E.observer(()=>{const{data:e,loading:t,panel:{viz:n}}=ee();return o(ai,{viz:n,data:e,loading:t,height:"100%"})}),bn=[];function oc(){const{vizManager:e}=w.useContext(xe);return w.useMemo(()=>e.availableVizList.map(t=>({value:t.name,label:t.displayName})).concat(bn),[e])}function ac(e,t){try{return e.resolveComponent(t).createConfig()}catch{return null}}function lc(){const{data:e,panel:{viz:t,title:n,queryID:r,description:i,setDescription:l,setTitle:s,setQueryID:u,id:d,style:p}}=ee(),{vizManager:c}=w.useContext(xe),f={title:n,description:i,viz:t,queryID:r,id:d,style:p.json},m={setDescription:l,setQueryID:u,setTitle:s};try{return c.resolveComponent(f.viz.type),o(ec,{setVizConf:t.setConf,panel:f,panelInfoEditor:m,vizManager:c,data:e})}catch(v){return console.info(_.get(v,"message")),null}}const sc=E.observer(()=>{const{data:e,panel:{viz:t}}=ee(),[n,r]=J.useInputState(t.type),i=t.type!==n,{vizManager:l}=w.useContext(xe),s=C.default.useCallback(()=>{if(!i)return;const v=ac(l,n);t.setType(n),t.setConf(v||{})},[t,i,n]),u=v=>{try{t.setConf(JSON.parse(v))}catch(b){console.error(b)}},d=C.default.useMemo(()=>{var v;return(v=bn.find(b=>b.value===n))==null?void 0:v.Panel},[n,bn]),p=lc(),c=d?w.createElement(d,{data:e,conf:t.conf,setConf:t.setConf}):null,f=p||c,m=oc();return g(U,{children:[o(a.Select,{label:"Visualization",value:n,onChange:r,data:m,rightSection:o(a.ActionIcon,{disabled:!i,onClick:s,children:o(V.DeviceFloppy,{size:20})})}),f,!f&&o(a.JsonInput,{minRows:20,label:"Config",value:JSON.stringify(t.conf,null,2),onChange:u})]})});function uc(){return g(a.Group,{grow:!0,noWrap:!0,align:"stretch",sx:{height:"100%",overflow:"hidden"},children:[o(a.Stack,{sx:{width:"40%",flexShrink:0,flexGrow:0,overflow:"scroll",height:"100%"},children:o(sc,{})}),o(a.Box,{sx:{height:"100%",flexGrow:1,maxWidth:"60%"},children:o(ic,{})})]})}const dc=E.observer(function({opened:t,close:n}){const{freezeLayout:r}=C.default.useContext(ce),[i,l]=w.useState("Visualization"),{panel:s,loading:u}=ee(),{id:d,title:p}=s;return C.default.useEffect(()=>{r(t)},[t]),o(a.Modal,{size:"96vw",overflow:"inside",opened:t,onClose:n,title:`Editing Panel - ${p.trim()?p:d}`,trapFocus:!0,onDragStart:c=>{c.stopPropagation()},children:o(a.AppShell,{sx:{height:"90vh",maxHeight:"calc(100vh - 185px)",".mantine-AppShell-body":{height:"100%"},main:{height:"100%",minHeight:"unset",maxHeight:"100%",width:"100%",padding:"16px"}},padding:"md",children:g(a.Tabs,{value:i,onTabChange:l,className:"panel-settings-tabs",children:[g(a.Tabs.List,{children:[o(a.Tabs.Tab,{value:"Data",children:"Data"}),o(a.Tabs.Tab,{value:"Panel",children:"Panel"}),o(a.Tabs.Tab,{value:"Visualization",children:"Visualization"}),o(a.Tabs.Tab,{value:"Interactions",children:"Interactions"})]}),g(a.Tabs.Panel,{value:"Data",pt:"sm",children:[o(a.LoadingOverlay,{visible:u,exitTransitionDuration:0}),o(Zd,{})]}),o(a.Tabs.Panel,{value:"Panel",pt:"sm",children:i==="Panel"&&o(Kd,{})}),o(a.Tabs.Panel,{value:"Visualization",pt:"sm",children:i==="Visualization"&&o(uc,{})}),o(a.Tabs.Panel,{value:"Interactions",pt:"sm",children:o(ke,{children:o(Qd,{})})})]})})})}),cc=E.observer(({view:e})=>{const t=Y(),n=be.useModals(),[r,i]=C.default.useState(!1),l=()=>i(!0),s=()=>i(!1),{panel:u}=ee(),{id:d,queryID:p}=u,{inEditMode:c}=C.default.useContext(ce),f=()=>t.queries.refetchDataByQueryID(p),{viewPanelInFullScreen:m,inFullScreen:v}=C.default.useContext(Mt),b=()=>{e.panels.duplicateByID(d)},I=()=>n.openConfirmModal({title:"Delete this panel?",labels:{confirm:"Confirm",cancel:"Cancel"},onCancel:()=>console.log("Cancel"),onConfirm:()=>e.panels.removeByID(d)}),A=C.default.useCallback(()=>{m(d)},[d,m]);return g(U,{children:[o(a.Box,{sx:{position:"absolute",top:0,left:0,right:0,zIndex:300},children:g(a.Menu,{withinPortal:!0,children:[o(a.Menu.Target,{children:o(a.Box,{className:"panel-dropdown-target",sx:{width:"100%",height:"25px"}})}),g(a.Menu.Dropdown,{children:[o(a.Menu.Item,{onClick:f,icon:o(V.Refresh,{size:14}),children:"Refresh"}),o(a.Menu.Item,{onClick:()=>t.queries.downloadDataByQueryID(p),icon:o(V.Download,{size:14}),children:"Download Data"}),!v&&o(a.Menu.Item,{onClick:A,icon:o(V.ArrowsMaximize,{size:14}),children:"Full Screen"}),c&&g(U,{children:[o(a.Divider,{label:"Edit",labelPosition:"center"}),o(a.Menu.Item,{onClick:l,icon:o(V.Settings,{size:14}),children:"Settings"}),o(a.Menu.Item,{onClick:b,icon:o(V.Copy,{size:14}),children:"Duplicate"}),o(a.Menu.Item,{color:"red",onClick:I,icon:o(V.Trash,{size:14}),children:"Delete"})]})]})]})}),c&&o(dc,{opened:r,close:s})]})}),Tg="",gc=E.observer(function(){const{panel:t}=ee(),{title:n}=t;return n?o(a.Group,{grow:!0,position:"center",px:20,className:"panel-title-wrapper",sx:{flexGrow:1},children:o(a.Text,{align:"center",lineClamp:1,weight:"bold",children:n})}):null});function pc(e){return!["richText"].includes(e)}const fc={border:"1px solid #ced4da"},hc={border:"1px dashed transparent",transition:"border-color 300ms ease","&:hover":{borderColor:"#ced4da"}},ht=E.observer(function({panel:t,view:n}){const r=Y(),{data:i,state:l}=r.getDataStuffByID(t.queryID),s=pc(t.viz.type)&&l==="loading",u=t.title?"calc(100% - 25px - 5px)":"100%",d=t.style.border.enabled?fc:hc;return o(Qn,{value:{panel:t,data:i,loading:s},children:g(a.Box,{className:"panel-root",p:5,pt:0,sx:{...d},children:[o(a.Box,{sx:{position:"absolute",left:0,top:0,height:28,zIndex:310},children:o(ar,{})}),o(cc,{view:n}),o(gc,{}),o(ai,{viz:t.viz,data:i,loading:s,height:u})]})})}),li=E.observer(function({view:t,panel:n,exitFullScreen:r}){return g(a.Stack,{px:"10px",pb:"5px",sx:{height:"100%",flexGrow:1,justifyContent:"flex-start"},children:[o(a.Group,{mx:"-5px",sx:{flexGrow:0},children:o(a.Button,{variant:"default",size:"sm",onClick:r,leftIcon:o(V.ArrowLeft,{size:20}),children:"Exit fullscreen"})}),o(a.Group,{mx:"-5px",grow:!0,sx:{flexGrow:1,flexShrink:0},children:o(ht,{view:t,panel:n})})]})});function si(e){const[t,n]=C.default.useState(null),r=C.default.useCallback(u=>{n(u)},[]),i=C.default.useCallback(()=>{n(null)},[]),l=t?e.panels.findByID(t):null;return{viewPanelInFullScreen:r,exitFullScreen:i,inFullScreen:!!l,fullScreenPanel:l}}function ui(){C.default.useEffect(()=>{const e=so.default(".dashboard-sticky-area",{useStickyClasses:!0,parentClass:"dashboard-sticky-parent"});return()=>{e==null||e.cleanup()}},[])}const Fg="",mc=C.default.forwardRef(({handleAxis:e},t)=>o(a.ActionIcon,{ref:t,className:"react-grid-customDragHandle",sx:{userSelect:"none",cursor:"grab",position:"absolute",top:0,right:0,zIndex:400,"&:hover":{color:"#228be6"}},variant:"transparent",children:o(V.ArrowsMove,{size:16})})),vc=C.default.forwardRef(({handleAxis:e,...t},n)=>o(a.ActionIcon,{ref:n,className:"react-grid-customResizeHandle",sx:{userSelect:"none",cursor:"nwse-resize",position:"absolute",bottom:-5,right:-5,zIndex:400,"&:hover":{color:"#228be6"}},variant:"transparent",...t,children:o(V.ChevronDownRight,{size:16})})),yc=Dt.WidthProvider(zn.default),bc=E.observer(function({view:t,className:n="layout",rowHeight:r=10,isDraggable:i,isResizable:l}){const s=C.default.useCallback(u=>{u.forEach(({i:d,...p})=>{const c=t.panels.findByID(d);!c||c.layout.set(p)})},[t]);return o(yc,{onLayoutChange:s,className:`dashboard-layout ${n}`,rowHeight:r,layout:t.panels.layouts,isDraggable:i,isResizable:l,draggableHandle:".react-grid-customDragHandle",resizeHandle:o(vc,{}),children:t.panels.list.map((u,d)=>g("div",{"data-grid":{...u.layout},style:{position:"relative"},children:[i&&o(mc,{}),o(ht,{view:t,panel:u})]},u.id))})}),Cc=Dt.WidthProvider(zn.default),xc=E.observer(function({view:t,className:n="layout",rowHeight:r=10}){return o(Cc,{className:`dashboard-layout ${n}`,rowHeight:r,isDraggable:!1,isResizable:!1,layout:t.panels.layouts,children:t.panels.list.map(i=>o("div",{"data-grid":i.layout,children:o(ht,{view:t,panel:i})},i.id))})}),Sc=E.observer(({children:e})=>o(a.Box,{children:e})),wc=E.observer(({children:e,view:t})=>o(a.Modal,{size:t.config.width,overflow:"inside",opened:!0,onClose:z.default.noop,withCloseButton:!1,title:t.name,trapFocus:!0,onDragStart:n=>{n.stopPropagation()},styles:{root:{position:"relative",height:"calc(100% - 46px)"},overlay:{position:"absolute !important"},modal:{border:"1px solid #efefef"},body:{"> div":{maxHeight:t.config.height,overflow:"scroll"}}},withinPortal:!1,transitionDuration:0,children:e})),_c=E.observer(({view:e,children:t})=>{switch(e.type){case ve.Modal:return o(wc,{view:e,children:t});case ve.Division:default:return o(Sc,{children:t})}}),di=E.observer(function({view:t,saveDashboardChanges:n}){const{viewPanelInFullScreen:r,exitFullScreen:i,inFullScreen:l,fullScreenPanel:s}=si(t);return ui(),o(Mt.Provider,{value:{viewPanelInFullScreen:r,inFullScreen:l},children:g(a.Box,{className:"dashboard-view",mx:-10,sx:{position:"relative",height:"100%"},children:[l&&o(li,{view:t,panel:s,exitFullScreen:i}),!l&&o(or,{saveChanges:n}),o(_c,{view:t,children:g(a.Box,{className:"dashboard-sticky-parent",children:[o(a.Box,{className:"dashboard-sticky-area",children:o(Wn,{view:t})}),o(a.Box,{sx:{display:l?"none":"block"},children:o(bc,{view:t,isDraggable:!0,isResizable:!0})})]})})]})})}),ci=E.observer(function({view:t}){const{viewPanelInFullScreen:n,exitFullScreen:r,inFullScreen:i,fullScreenPanel:l}=si(t);return ui(),o(Mt.Provider,{value:{viewPanelInFullScreen:n,inFullScreen:i},children:g(a.Box,{className:"dashboard-view",mx:-10,sx:{position:"relative",height:"100%"},children:[i&&o(li,{view:t,panel:l,exitFullScreen:r}),!i&&g(a.Box,{className:"dashboard-sticky-area",children:[o(or,{saveChanges:z.default.noop}),o(Wn,{view:t})]}),o(xc,{view:t})]})})}),gi=y.types.model({label:y.types.string,value:y.types.string}).actions(e=>({setLabel(t){e.label=t},setValue(t){e.value=t}})),pi=y.types.model("FilterConfigModel_Select",{required:y.types.boolean,default_value:y.types.string,static_options:y.types.optional(y.types.array(gi),[]),options_query:Kn}).actions(e=>({addStaticOption(t){e.static_options.push(t)},removeStaticOption(t){e.static_options.splice(t,1)},setRequired(t){e.required=t},setDefaultValue(t){e.default_value=t},setOptionsQuery(t){e.options_query=t}})),Ic=()=>pi.create({required:!1,default_value:"",static_options:[],options_query:{type:me.Postgresql,key:"",sql:""}}),fi=y.types.model("FilterConfigModel_MultiSelect",{default_value:y.types.optional(y.types.array(y.types.string),[]),static_options:y.types.optional(y.types.array(gi),[]),options_query:Kn}).actions(e=>({addStaticOption(t){e.static_options.push(t)},removeStaticOption(t){e.static_options.splice(t,1)},setDefaultValue(t){e.default_value=y.cast(t)},setOptionsQuery(t){e.options_query=t}})),Dc=()=>fi.create({default_value:[],static_options:[],options_query:{type:me.Postgresql,key:"",sql:""}}),hi=y.types.model("FilterConfigModel_Checkbox",{default_value:y.types.boolean}).actions(e=>({setDefaultValue(t){e.default_value=t}})),Ac=()=>hi.create({default_value:!1}),Mc=y.types.model("FilterConfigModel_DateRange",{required:y.types.boolean,inputFormat:y.types.enumeration("DateRangeInputFormat",["YYYY","YYYY-MM","YYYY-MM-DD"]),default_value:y.types.optional(y.types.array(y.types.union(y.types.Date,y.types.null)),[null,null]),clearable:y.types.boolean}).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)}})),mi=y.types.snapshotProcessor(Mc,{preProcessor({default_value:e,...t}){return{...t,default_value:e.map(n=>n===null?null:new Date(n))}},postProcessor({default_value:e,...t}){return{...t,default_value:e.map(n=>{try{return typeof n=="number"?new Date(n).toISOString():null}catch{return console.log(`[date-range] failed parsing ${n}`),null}})}}}),Vc=()=>mi.create({required:!1,inputFormat:"YYYY-MM-DD",clearable:!1,default_value:[null,null]}),Cn=y.types.model("FilterModel",{id:y.types.identifier,key:y.types.string,label:y.types.string,order:y.types.number,visibleInViewsIDs:y.types.array(y.types.string),type:y.types.enumeration("DashboardFilterType",[le.Select,le.MultiSelect,le.TextInput,le.Checkbox,le.DateRange]),config:y.types.union(pi,fi,Zn,hi,mi)}).views(e=>({get plainDefaultValue(){const t=e.config.default_value;return Array.isArray(t)?[...t]:t}})).actions(e=>({setKey(t){e.key=t},setLabel(t){e.label=t},setOrder(t){e.order=t},setType(t){switch(t){case le.Select:e.config=Ic();break;case le.MultiSelect:e.config=Dc();break;case le.TextInput:e.config=er();break;case le.Checkbox:e.config=Ac();break;case le.DateRange:e.config=Vc();break}e.type=t},setVisibleInViewsIDs(t){e.visibleInViewsIDs.length=0,e.visibleInViewsIDs.push(...t)}}));function Ec(e){return e===void 0?e:Array.isArray(e)?e.map(t=>{const n=new Date(t);return n!=null?n:t}):e}function vi(e){return e.reduce((t,n)=>(t[n.key]=Ec(n.config.default_value),t),{})}const yi=y.types.model("FiltersModel",{original:y.types.optional(y.types.array(Cn),[]),current:y.types.optional(y.types.array(Cn),[]),values:y.types.optional(y.types.frozen(),{})}).views(e=>({get changed(){return!z.default.isEqual(e.original,e.current)},get firstID(){if(e.current.length!==0)return e.current[0].id},get inOrder(){return z.default.sortBy(e.current,"order")},get empty(){return e.current.length===0},visibleInView(t){return z.default.sortBy(e.current.filter(n=>n.visibleInViewsIDs.includes(t)),"order")},get triggerForRefreshValues(){return e.current.map(n=>{var r;return(r=n.config.default_value)==null?void 0:r.toString()}).join("__")}})).actions(e=>({reset(){e.current=z.default.cloneDeep(e.original)},replace(t){e.current=y.cast(t)},append(t){e.current.push(t)},remove(t){e.current.splice(t,1)},setValues(t){e.values=t},setValueByKey(t,n){e.values[t]=n},getValueByKey(t){return e.values[t]},refreshValues(){console.log("refreshing values");const t=vi(e.current);e.values=t}})).actions(e=>({afterCreate(){y.addDisposer(e,K.reaction(()=>e.triggerForRefreshValues,e.refreshValues,{fireImmediately:!0,delay:0}))}}));function bi(e){return{original:e,current:e,values:vi(e)}}var xn={exports:{}};(function(e,t){(function(n,r){r()})(Ne,function(){function n(p,c){return typeof c>"u"?c={autoBom:!1}:typeof c!="object"&&(console.warn("Deprecated: Expected third argument to be a object"),c={autoBom:!c}),c.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(p.type)?new Blob(["\uFEFF",p],{type:p.type}):p}function r(p,c,f){var m=new XMLHttpRequest;m.open("GET",p),m.responseType="blob",m.onload=function(){d(m.response,c,f)},m.onerror=function(){console.error("could not download file")},m.send()}function i(p){var c=new XMLHttpRequest;c.open("HEAD",p,!1);try{c.send()}catch{}return 200<=c.status&&299>=c.status}function l(p){try{p.dispatchEvent(new MouseEvent("click"))}catch{var c=document.createEvent("MouseEvents");c.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),p.dispatchEvent(c)}}var s=typeof window=="object"&&window.window===window?window:typeof self=="object"&&self.self===self?self:typeof Ne=="object"&&Ne.global===Ne?Ne:void 0,u=s.navigator&&/Macintosh/.test(navigator.userAgent)&&/AppleWebKit/.test(navigator.userAgent)&&!/Safari/.test(navigator.userAgent),d=s.saveAs||(typeof window!="object"||window!==s?function(){}:"download"in HTMLAnchorElement.prototype&&!u?function(p,c,f){var m=s.URL||s.webkitURL,v=document.createElement("a");c=c||p.name||"download",v.download=c,v.rel="noopener",typeof p=="string"?(v.href=p,v.origin===location.origin?l(v):i(v.href)?r(p,c,f):l(v,v.target="_blank")):(v.href=m.createObjectURL(p),setTimeout(function(){m.revokeObjectURL(v.href)},4e4),setTimeout(function(){l(v)},0))}:"msSaveOrOpenBlob"in navigator?function(p,c,f){if(c=c||p.name||"download",typeof p!="string")navigator.msSaveOrOpenBlob(n(p,f),c);else if(i(p))r(p,c,f);else{var m=document.createElement("a");m.href=p,m.target="_blank",setTimeout(function(){l(m)})}}:function(p,c,f,m){if(m=m||open("","_blank"),m&&(m.document.title=m.document.body.innerText="downloading..."),typeof p=="string")return r(p,c,f);var v=p.type==="application/octet-stream",b=/constructor/i.test(s.HTMLElement)||s.safari,I=/CriOS\/[\d]+/.test(navigator.userAgent);if((I||v&&b||u)&&typeof FileReader<"u"){var A=new FileReader;A.onloadend=function(){var B=A.result;B=I?B:B.replace(/^data:[^;]*;/,"data:attachment/file;"),m?m.location.href=B:location=B,m=null},A.readAsDataURL(p)}else{var T=s.URL||s.webkitURL,k=T.createObjectURL(p);m?m.location=k:location.href=k,m=null,setTimeout(function(){T.revokeObjectURL(k)},4e4)}});s.saveAs=d.saveAs=d,e.exports=d})})(xn);function Rc(e,t){const n=new Blob([t],{type:"text/csv"});xn.exports.saveAs(n,`${e}.csv`)}function Tc(e){const t=new uo.default;e.forEach(({id:n,data:r})=>{t.file(`${n}.csv`,Ci(r))}),t.generateAsync({type:"blob"}).then(n=>{xn.exports.saveAs(n,"dashboard_data.zip")})}function Ci(e){if(!Array.isArray(e)||e.length===0)return"";const t=[],n=Object.keys(e[0]);return t.push(n.join(",")),e.forEach(r=>{const i=Object.values(r).join(",");t.push(i)}),t.join(`
82
82
  `)}const xi=y.types.model("QueryModel",{id:y.types.string,type:y.types.enumeration("DataSourceType",[me.Postgresql,me.MySQL,me.HTTP]),key:y.types.string,sql:y.types.string}).views(e=>({get valid(){return e.id&&e.type&&e.key&&e.sql},get configurations(){const{id:t,type:n,key:r,sql:i}=e;return{id:t,type:n,key:r,sql:i}}})),Si=y.types.compose("QueryModel",xi,y.types.model({state:y.types.optional(y.types.enumeration(["idle","loading","error"]),"idle"),data:y.types.optional(y.types.array(y.types.frozen()),[]),error:y.types.frozen()})).views(e=>({get formattedSQL(){const{context:t,sqlSnippets:n,filterValues:r}=y.getRoot(e).payloadForSQL;return Bn(e.sql,t,n,r)}})).views(e=>({get json(){const{id:t,type:n,key:r,sql:i}=e;return{id:t,type:n,key:r,sql:i}}})).actions(e=>({setID(t){e.id=t},setKey(t){e.key=t},setType(t){e.type=t},setSQL(t){e.sql=t},fetchData:y.flow(function*(){if(!!e.valid){e.state="loading";try{const t=e.id,{context:n,sqlSnippets:r,filterValues:i}=y.getRoot(e).payloadForSQL;e.data=yield*y.toGenerator(mo({context:n,sqlSnippets:r,title:t,query:{type:e.type,key:e.key,sql:e.sql},filterValues:i})),e.state="idle"}catch(t){console.error(t),e.error=t,e.state="error"}}})})).actions(e=>({afterCreate(){y.addDisposer(e,K.reaction(()=>`${e.id}--${e.key}--${e.type}--${e.formattedSQL}`,e.fetchData,{fireImmediately:!0,delay:500}))}})),wi=y.types.model("QueriesModel",{original:y.types.optional(y.types.array(xi),[]),current:y.types.optional(y.types.array(Si),[])}).views(e=>({get changed(){return e.original.length!==e.current.length?!0:e.original.some((t,n)=>!z.default.isEqual(t.configurations,e.current[n].configurations))},get firstID(){if(e.current.length!==0)return e.current[0].id},findByID(t){return e.current.find(n=>n.id===t)},get options(){return e.current.map(t=>({value:t.id,label:t.id}))}})).views(e=>({get json(){return e.current.map(t=>t.json)}})).actions(e=>({reset(){const t=e.original.map(n=>({...n,state:"idle",data:[],error:null}));e.current.length=0,e.current.unshift(...t)},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)},downloadAllData(){const t=e.current.map(({id:n,data:r})=>({id:n,data:r.toJSON()}));Tc(t)},downloadDataByQueryID(t){const n=e.findByID(t);if(!n){console.log(`[downloadDataByQueryID] query by ID[${t}] not found`);return}const{id:r,data:i}=n,l=Ci(i);Rc(r,l)},refetchDataByQueryID(t){const n=e.findByID(t);if(!n){console.error(new Error(`[downloadDataByQueryID] query by ID[${t}] not found`));return}return n.fetchData()}})),Sn=y.types.model("SQLSnippetModel",{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}})),_i=y.types.model("SQLSnippetsModel",{original:y.types.optional(y.types.array(Sn),[]),current:y.types.optional(y.types.array(Sn),[])}).views(e=>({get changed(){return!z.default.isEqual(e.original,e.current)},get json(){return e.current.map(t=>t.json)}})).actions(e=>({reset(){e.current=z.default.cloneDeep(e.original)},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)}})),Ii=y.types.model("ContextModel",{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}})),Fc=y.types.model("PanelLayoutModel",{x:y.types.number,y: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:i,moved:l}=e;return{x:t,y:n,w:r,h:i,moved:l,static:e.static}}})).actions(e=>({set(t){const{x:n,y:r,w:i,h:l,moved:s}=t;e.x=n,e.y=r,e.w=i,e.h=l,e.moved=!!s,e.static=!!t.static}})),$c=y.types.model("PanelStyleBorderModel",{enabled:y.types.boolean}).views(e=>({get json(){const{enabled:t}=e;return{enabled:t}}})).actions(e=>({setEnabled(t){e.enabled=t}})),Pc=y.types.model("PanelStyleModel",{border:$c}).views(e=>({get json(){const{border:t}=e;return{border:t.json}}})).actions(e=>({})),kc=y.types.model("PanelVizModel",{type:y.types.string,conf:y.types.frozen()}).views(e=>({get json(){return{type:e.type,conf:e.conf}}})).actions(e=>({setType(t){e.type=t},setConf(t){e.conf=t}})),Oc=y.types.model({id:y.types.string,title:y.types.string,description:y.types.string,layout:Fc,queryID:y.types.string,viz:kc,style:Pc}).views(e=>({get json(){const{id:t,title:n,description:r,queryID:i}=e;return{id:t,title:n,description:r,layout:e.layout.json,queryID:i,viz:e.viz.json,style:e.style.json}}})).actions(e=>({setID(t){e.id=t},setTitle(t){e.title=t},setDescription(t){e.description=t},setQueryID(t){e.queryID=t}})).actions(e=>({})),zc=y.types.model("PanelsModel",{list:y.types.optional(y.types.array(Oc),[])}).views(e=>({get json(){return e.list.map(t=>t.json)},get layouts(){return e.list.map(t=>({...t.layout.json,i:t.id}))},findByID(t){return e.list.find(n=>n.id===t)}})).actions(e=>({replace(t){e.list=y.cast(t)},addANewPanel(){const t=J.randomId();e.list.push({id:t,layout:{x:0,y:1/0,w:3,h:15},title:`Panel - ${t}`,description:"<p><br></p>",queryID:"",viz:{type:sn.name,conf:sn.createConfig()},style:{border:{enabled:!0}}})},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)},duplicateByID(t){const n=e.list.find(r=>r.id===t);if(!n){console.error(new Error(`[duplicate panel] Can't find a panel by id[${t}]`));return}e.list.push({...n.json,id:J.randomId(),layout:{...n.layout,x:0,y:1/0,moved:!1}})},replaceByIndex(t,n){e.list.splice(t,1,n)}})),wn=y.types.model({id:y.types.identifier,name:y.types.string,type:y.types.string,config:y.types.frozen(),panels:zc}).views(e=>({get json(){const{id:t,name:n,type:r,config:i}=e;return{id:t,name:n,type:r,config:i,panels:e.panels.json}}})).actions(e=>({setName(t){e.name=t},setType(t){e.type!==t&&(t===ve.Modal?e.config={width:"600px",height:"400px"}:e.config={},e.type=t)},setConfig(t){e.config=t},updateConfig(t,n){e.config={...e.config,[t]:n}}})).actions(e=>({})),_n=y.types.model("ViewsModel",{original:y.types.optional(y.types.array(wn),[]),current:y.types.optional(y.types.array(wn),[]),visibleViewIDs:y.types.array(y.types.string),idOfVIE:y.types.string}).views(e=>({get changed(){return e.original.length!==e.current.length?!0:e.original.some((t,n)=>!z.default.isEqual(t.json,e.current[n].json))},get json(){return e.current.map(t=>t.json)},findByID(t){return e.current.find(n=>n.id===t)},get isVIETheFirstView(){return e.current.length===0||!e.idOfVIE?!1:e.current[0].id===e.idOfVIE},get firstVisibleView(){const[t]=e.visibleViewIDs;return e.current.find(({id:n})=>n===t)},get visibleViews(){const t=new Set(e.visibleViewIDs);return e.current.filter(({id:n})=>t.has(n))},get 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}))}})).actions(e=>({reset(){const t=e.original.map(n=>({...n.json,panels:{list:n.panels.json}}));e.current.length=0,e.current.unshift(...t)},replace(t){e.current=y.cast(t)},addANewView(t,n,r){e.current.push({id:t,name:t,type:n,config:r,panels:{list:[]}})},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!==-1&&e.current.splice(n,1)},replaceByIndex(t,n){e.current.splice(t,1,n)},setIDOfVIE(t){e.idOfVIE=t,e.visibleViewIDs.length=0,e.visibleViewIDs.push(t)},addAPanelToVIE(){var t;(t=e.VIE)==null||t.panels.addANewPanel()}})).actions(e=>({addARandomNewView(){const t=J.randomId();e.addANewView(t,ve.Division,{}),e.setIDOfVIE(t)},removeVIE(){e.current.length!==1&&(e.removeByID(e.idOfVIE),e.setIDOfVIE(e.current[0].id))},rmVisibleViewID(t){const n=e.visibleViewIDs.findIndex(r=>r===t);n!==-1&&e.visibleViewIDs.splice(n,1)}}));function Di(e){const t=e.length>0?[e[0].id]:[],n=e.length>0?e[0].id:"",r=e.map(i=>({...i,panels:{list:i.panels}}));return _n.create({original:r,current:r,visibleViewIDs:t,idOfVIE:n})}const Gc=y.types.model({id:y.types.identifier,name:y.types.string,filters:yi,queries:wi,sqlSnippets:_i,views:_n,context:Ii}).views(e=>({get payloadForSQL(){return{context:e.context.current,sqlSnippets:e.sqlSnippets.current,filterValues: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.toJSON(),state:n.state,error:void 0}:{data:[],state:"idle",error:void 0}},getDataStateByID(t){var n,r;return(r=(n=e.queries.findByID(t))==null?void 0:n.state)!=null?r:[]},getDataErrorByID(t){var n,r;return(r=(n=e.queries.findByID(t))==null?void 0:n.error)!=null?r:[]}}));function In({id:e,name:t,filters:n,views:r,definition:{queries:i,sqlSnippets:l}},s){return Gc.create({id:e,name:t,filters:bi(n),queries:{original:i,current:i},sqlSnippets:{original:l,current:l},context:s,views:Di(r)})}const $g="",Lc=E.observer(function({context:t,dashboard:n,update:r,className:i="dashboard",config:l}){$e.baseURL!==l.apiBaseURL&&($e.baseURL=l.apiBaseURL);const[s,u]=C.default.useState(!1),d=C.default.useMemo(()=>In(n,t),[n]);C.default.useEffect(()=>{d.context.replace(t)},[t]);const p=async()=>{const f=[...d.queries.json],m=[...d.sqlSnippets.json],v=[...d.views.json],b={...n,filters:[...d.filters.current],views:v,definition:{sqlSnippets:m,queries:f}};await r(b)},c=j.useCreation(ni,[]);return o(be.ModalsProvider,{children:o(Vt,{value:d,children:o(ce.Provider,{value:{layoutFrozen:s,freezeLayout:u,inEditMode:!0,inUseMode:!1},children:o(a.Box,{className:`${i} dashboard-root`,sx:{position:"relative"},children:o(xe.Provider,{value:c,children:d.views.visibleViews.map(f=>o(di,{view:f,saveDashboardChanges:p},f.id))})})})})})});function Nc({context:e,dashboard:t,className:n="dashboard",config:r}){$e.baseURL!==r.apiBaseURL&&($e.baseURL=r.apiBaseURL);const i=C.default.useMemo(()=>In(t,e),[t]);return C.default.useEffect(()=>{i.context.replace(e)},[e]),o(be.ModalsProvider,{children:o(Vt,{value:i,children:o(ce.Provider,{value:{layoutFrozen:!0,freezeLayout:z.default.noop,inEditMode:!1,inUseMode:!0},children:o(a.Box,{className:`${n} dashboard-root dashboard-sticky-parent`,children:i.views.visibleViews.map(l=>o(ci,{view:l},l.id))})})})})}M.ContextModel=Ii,M.Dashboard=Lc,M.DashboardFilterType=rr,M.DashboardMode=nr,M.EViewComponentType=ve,M.FilterModel=Cn,M.FiltersModel=yi,M.LayoutStateContext=ce,M.MainDashboardView=di,M.ModelContextProvider=Vt,M.Panel=ht,M.PanelContextProvider=Qn,M.QueriesModel=wi,M.QueryModel=Si,M.ReadOnlyDashboard=Nc,M.ReadOnlyDashboardView=ci,M.SQLSnippetModel=Sn,M.SQLSnippetsModel=_i,M.ViewModel=wn,M.ViewsModel=_n,M.createDashboardModel=In,M.createDashboardViewsModel=Di,M.getInitialFiltersPayload=bi,M.useModelContext=Y,M.usePanelContext=ee,Object.defineProperties(M,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devtable/dashboard",
3
- "version": "4.16.8",
3
+ "version": "4.17.0",
4
4
  "license": "Apache-2.0",
5
5
  "publishConfig": {
6
6
  "access": "public",