From 73ec0df8a6fe512598c28ac725f76c7fabcce392 Mon Sep 17 00:00:00 2001 From: GermanBluefox Date: Mon, 13 Jan 2025 20:08:38 +0000 Subject: [PATCH] chore: release v2.0.4 - (@GermanBluefox) Correcting locale for x-axis - (@GermanBluefox) Correcting widget --- README.md | 2 +- .../{index-B6UtVddM.js => index-7UgD_MMe.js} | 2 +- admin/tab.html | 2 +- build-backend/main.js | 2 +- build-backend/main.js.map | 2 +- io-package.json | 28 +++++++++---------- package.json | 2 +- 7 files changed, 20 insertions(+), 20 deletions(-) rename admin/assets/{index-B6UtVddM.js => index-7UgD_MMe.js} (97%) diff --git a/README.md b/README.md index ac4e03e9..b83e67fd 100644 --- a/README.md +++ b/README.md @@ -115,7 +115,7 @@ You can debug view charts locally with: --> ## Changelog -### **WORK IN PROGRESS** +### 2.0.4 (2025-01-13) - (@GermanBluefox) Correcting locale for x-axis - (@GermanBluefox) Correcting widget diff --git a/admin/assets/index-B6UtVddM.js b/admin/assets/index-7UgD_MMe.js similarity index 97% rename from admin/assets/index-B6UtVddM.js rename to admin/assets/index-7UgD_MMe.js index 4dd274b4..3b0834ea 100644 --- a/admin/assets/index-B6UtVddM.js +++ b/admin/assets/index-7UgD_MMe.js @@ -820,4 +820,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho * @website https://github.com/cssinjs/jss * @license MIT */eG();var rG=Date.now(),Fk="fnValues"+rG,Bk="fnStyle"+ ++rG,xQt=function(){return{onCreateRule:function(r,n,o){if(typeof n!="function")return null;var a=xA(r,{},o);return a[Bk]=n,a},onProcessStyle:function(r,n){if(Fk in n||Bk in n)return r;var o={};for(var a in r){var i=r[a];typeof i=="function"&&(delete r[a],o[a]=i)}return n[Fk]=o,r},onUpdate:function(r,n,o,a){var i=n,s=i[Bk];s&&(i.style=s(r)||{});var l=i[Fk];if(l)for(var d in l)i.prop(d,l[d](r),a)}}},As="@global",rT="@global ",SQt=function(){function t(r,n,o){this.type="global",this.at=As,this.isProcessed=!1,this.key=r,this.options=o,this.rules=new C_(De({},o,{parent:this}));for(var a in n)this.rules.add(a,n[a]);this.rules.process()}var e=t.prototype;return e.getRule=function(n){return this.rules.get(n)},e.addRule=function(n,o,a){var i=this.rules.add(n,o,a);return i&&this.options.jss.plugins.onProcessRule(i),i},e.replaceRule=function(n,o,a){var i=this.rules.replace(n,o,a);return i&&this.options.jss.plugins.onProcessRule(i),i},e.indexOf=function(n){return this.rules.indexOf(n)},e.toString=function(n){return this.rules.toString(n)},t}(),CQt=function(){function t(r,n,o){this.type="global",this.at=As,this.isProcessed=!1,this.key=r,this.options=o;var a=r.substr(rT.length);this.rule=o.jss.createRule(a,n,De({},o,{parent:this}))}var e=t.prototype;return e.toString=function(n){return this.rule?this.rule.toString(n):""},t}(),$Qt=/\s*,\s*/g;function nG(t,e){for(var r=t.split($Qt),n="",o=0;o-1){var a=lG[e];if(!Array.isArray(a))return It.js+Fs(a)in r?It.css+a:!1;if(!o)return!1;for(var i=0;in?1:-1:r.length-n.length};return{onProcessStyle:function(r,n){if(n.type!=="style")return r;for(var o={},a=Object.keys(r).sort(t),i=0;i"u"?null:fer(),mer()]}}function dG(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=t.baseClasses,r=t.newClasses;if(t.Component,!r)return e;var n=De({},e);return Object.keys(r).forEach(function(o){r[o]&&(n[o]="".concat(e[o]," ").concat(r[o]))}),n}var Yd={set:function(e,r,n,o){var a=e.get(r);a||(a=new Map,e.set(r,a)),a.set(n,o)},get:function(e,r,n){var o=e.get(r);return o?o.get(n):void 0},delete:function(e,r,n){var o=e.get(r);o.delete(n)}},ver=m.createContext(null);function uG(){var t=m.useContext(ver);return t}var yer=eG(ger()),_er=NZt(),ber=new Map,wer={disableGeneration:!1,generateClassName:_er,jss:yer,sheetsCache:null,sheetsManager:ber,sheetsRegistry:null},xer=m.createContext(wer),a9=-1e9;function Ser(){return a9+=1,a9}var Cer={};function $er(t){var e=typeof t=="function";return{create:function(n,o){var a;try{a=e?t(n):t}catch(l){throw l}if(!o||!n.overrides||!n.overrides[o])return a;var i=n.overrides[o],s=De({},a);return Object.keys(i).forEach(function(l){s[l]=ku(s[l],i[l])}),s},options:{}}}function ker(t,e,r){var n=t.state,o=t.stylesOptions;if(o.disableGeneration)return e||{};n.cacheClasses||(n.cacheClasses={value:null,lastProp:null,lastJSS:{}});var a=!1;return n.classes!==n.cacheClasses.lastJSS&&(n.cacheClasses.lastJSS=n.classes,a=!0),e!==n.cacheClasses.lastProp&&(n.cacheClasses.lastProp=e,a=!0),a&&(n.cacheClasses.value=dG({baseClasses:n.cacheClasses.lastJSS,newClasses:e,Component:r})),n.cacheClasses.value}function Eer(t,e){var r=t.state,n=t.theme,o=t.stylesOptions,a=t.stylesCreator,i=t.name;if(!o.disableGeneration){var s=Yd.get(o.sheetsManager,a,n);s||(s={refs:0,staticSheet:null,dynamicStyles:null},Yd.set(o.sheetsManager,a,n,s));var l=De({},a.options,o,{theme:n,flip:typeof o.flip=="boolean"?o.flip:n.direction==="rtl"});l.generateId=l.serverGenerateClassName||l.generateClassName;var d=o.sheetsRegistry;if(s.refs===0){var h;o.sheetsCache&&(h=Yd.get(o.sheetsCache,a,n));var u=a.create(n,i);h||(h=o.jss.createStyleSheet(u,De({link:!1},l)),h.attach(),o.sheetsCache&&Yd.set(o.sheetsCache,a,n,h)),d&&d.add(h),s.staticSheet=h,s.dynamicStyles=tG(u)}if(s.dynamicStyles){var f=o.jss.createStyleSheet(s.dynamicStyles,De({link:!0},l));f.update(e),f.attach(),r.dynamicSheet=f,r.classes=dG({baseClasses:s.staticSheet.classes,newClasses:f.classes}),d&&d.add(f)}else r.classes=s.staticSheet.classes;s.refs+=1}}function Ter(t,e){var r=t.state;r.dynamicSheet&&r.dynamicSheet.update(e)}function Oer(t){var e=t.state,r=t.theme,n=t.stylesOptions,o=t.stylesCreator;if(!n.disableGeneration){var a=Yd.get(n.sheetsManager,o,r);a.refs-=1;var i=n.sheetsRegistry;a.refs===0&&(Yd.delete(n.sheetsManager,o,r),n.jss.removeStyleSheet(a.staticSheet),i&&i.remove(a.staticSheet)),e.dynamicSheet&&(n.jss.removeStyleSheet(e.dynamicSheet),i&&i.remove(e.dynamicSheet))}}function Der(t,e){var r=m.useRef([]),n,o=m.useMemo(function(){return{}},e);r.current!==o&&(r.current=o,n=t()),m.useEffect(function(){return function(){n&&n()}},[o])}function Aer(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=e.name,n=e.classNamePrefix,o=e.Component,a=e.defaultTheme,i=a===void 0?Cer:a,s=ji(e,["name","classNamePrefix","Component","defaultTheme"]),l=$er(t),d=r||n||"makeStyles";l.options={index:Ser(),name:r,meta:d,classNamePrefix:d};var h=function(){var f=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},g=uG()||i,y=De({},m.useContext(xer),s),b=m.useRef(),x=m.useRef();Der(function(){var T={name:r,state:{},stylesCreator:l,stylesOptions:y,theme:g};return Eer(T,f),x.current=!1,b.current=T,function(){Oer(T)}},[g,l]),m.useEffect(function(){x.current&&Ter(b.current,f),x.current=!0});var S=ker(b.current,f.classes,o);return S};return h}function pG(t){var e,r,n="";if(typeof t=="string"||typeof t=="number")n+=t;else if(typeof t=="object")if(Array.isArray(t))for(e=0;e1&&arguments[1]!==void 0?arguments[1]:{};return function(n){var o=r.defaultTheme,a=r.withTheme,i=a===void 0?!1:a,s=r.name,l=ji(r,["defaultTheme","withTheme","name"]),d=s,h=Aer(e,De({defaultTheme:o,Component:n,name:s||n.displayName,classNamePrefix:d},l)),u=m.forwardRef(function(g,y){g.classes;var b=g.innerRef,x=ji(g,["classes","innerRef"]),S=h(De({},n.defaultProps,g)),T,E=x;return(typeof s=="string"||i)&&(T=uG()||o,s&&(E=RZt({theme:T,name:s,props:x})),i&&!E.theme&&(E.theme=T)),m.createElement(n,De({ref:b||y,classes:S},E))});return bE(u,n),u}},Per=AZt();function Ner(t,e){return Mer(t,De({defaultTheme:Per},e))}var Rer=function(e){return{root:{flex:"1 1 auto",WebkitOverflowScrolling:"touch",overflowY:"auto",padding:"8px 24px","&:first-child":{paddingTop:20}},dividers:{padding:"16px 24px",borderTop:"1px solid ".concat(e.palette.divider),borderBottom:"1px solid ".concat(e.palette.divider)}}},jer=A.forwardRef(function(e,r){var n=e.classes,o=e.className,a=e.dividers,i=a===void 0?!1:a,s=ji(e,["classes","className","dividers"]);return A.createElement("div",De({className:Ier(n.root,o,i&&n.dividers),ref:r},s))});const Ler=Ner(Rer,{name:"MuiDialogContent"})(jer),Ua={timeSpan:200,aggregate:250,autoRefresh:150,bigButton:200},Nn={mainDiv:{gap:2},fieldsContainer:{"& > div":{display:"flex",pr:"20px",width:200}},popOver:{padding:16},refreshSelect:{display:"inline-block","& > div:before":{borderWidth:0},"& > div:hover:before":{borderBottom:0}},refreshSelectButtonTitle:{display:"inline-flex",paddingTop:6},settingsButton:{color:"currentColor",fontSize:16,textTransform:"inherit",flexGrow:1},grow1:{flexGrow:2},aggregateIcon:{marginTop:4},divider:t=>({borderLeftColor:t.palette.mode==="dark"?"#CCC":"#444",borderLeftStyle:"dotted",borderLeftWidth:"1px",width:"1px",height:"80%"})},zer=t=>w.jsx(Re,{component:"div",sx:t.sx,title:t.tooltip,children:w.jsx(Bn,{variant:"standard",onChange:e=>t.updateValue(parseInt(e.target.value,10)),value:t.value.toString()||"",renderValue:t.renderValue,displayEmpty:!0,children:t.options?Object.keys(t.options).map(e=>w.jsx(Xt,{value:e,children:t.noTranslate?t.options[e]:P.t(t.options[e])},e)):null})}),i9={10:"10 minutes",30:"30 minutes",60:"1 hour",120:"2 hours",180:"3 hours",360:"6 hours",720:"12 hours",1440:"1 day",2880:"2 days",4320:"3 days",10080:"7 days",20160:"14 days","1m":"1 month","2m":"2 months","3m":"3 months","6m":"6 months","1y":"1 year","2y":"2 years"},s9={now:"now","1minute":"end of minute","5minutes":"end of 5 minutes","10minutes":"end of 10 minutes","30minutes":"end of 30 minutes","1hour":"end of hour","2hours":"end of 2 hours","3hours":"end of 3 hours","4hours":"end of 4 hours","6hours":"end of 6 hours","8hours":"end of 8 hours","12hours":"end of 12 hours",today:"end of day",weekEurope:"end of sunday",weekUsa:"end of saturday",week2Europe:"end of previous sunday",week2Usa:"end of previous saturday",month:"this month",year:"this year"},l9={"":"none",5:"5 seconds",10:"10 seconds",15:"15 seconds",20:"20 seconds",30:"30 seconds",60:"1 minute",120:"2 minutes",300:"5 minutes",600:"10 minutes",900:"15 minutes",1200:"20 minutes",1800:"30 minutes",3600:"1 hour",7200:"2 hours",10800:"3 hours",21600:"6 hours",43200:"12 hours",86400:"1 day"},Xk={auto:"Auto (Line or Steps)",line:"Line",bar:"Bar",polar:"Polar",scatterplot:"Scatter plot",steps:"Steps",stepsStart:"Steps on start",spline:"Spline"},Jk={minmax:"minmax",average:"average",min:"min",max:"max",total:"total",onchange:"raw",percentile:"percentile",integral:"integral",count:"count",none:"none",current:"current"};class Fer extends m.Component{constructor(r){super(r);X(this,"windowWidth");X(this,"toolbarRef");X(this,"handleResize",()=>{this.toolbarRef.current&&this.toolbarRef.current.clientWidth!==this.state.clientWidth&&this.setState({clientWidth:this.toolbarRef.current.clientWidth})});this.windowWidth=this.props.windowWidth,this.state={timeSpanOpened:!1,aggregateOpened:!1,clientWidth:0,showMore:!1},this.toolbarRef=m.createRef()}componentDidMount(){window.addEventListener("resize",this.handleResize)}componentWillUnmount(){window.removeEventListener("resize",this.handleResize)}componentDidUpdate(){this.toolbarRef.current&&this.toolbarRef.current.clientWidth!==this.state.clientWidth&&(this.windowWidth=this.props.windowWidth,this.setState({clientWidth:this.toolbarRef.current.clientWidth}))}renderShowMore(){return this.state.showMore?w.jsxs(or,{maxWidth:"xs",fullWidth:!0,open:!0,onClose:()=>this.setState({showMore:!1}),children:[w.jsxs(Ler,{children:[this.renderTimeSpanElements(),this.renderAggregateElements(),this.renderAutoRefresh()]}),w.jsx(pr,{children:w.jsx(tt,{variant:"contained",onClick:()=>this.setState({showMore:!1}),startIcon:w.jsx(Ar,{}),children:P.t("Close")})})]}):null}renderTimeSpanElements(){return[w.jsx(Dt,{fullWidth:!0,value:this.props.presetData.timeType,updateValue:r=>{const n=JSON.parse(JSON.stringify(this.props.presetData));n.timeType=r,this.props.onChange(n),window.localStorage.setItem("App.echarts.__timeType",r.toString())},label:"Type",options:{relative:"relative",static:"static"}},"time-type"),this.props.presetData.timeType==="static"?w.jsx(ty,{fullWidth:!0,date:this.props.presetData.start.toString(),time:this.props.presetData.start_time,updateValue:(r,n)=>{const o=JSON.parse(JSON.stringify(this.props.presetData));o.start=r,o.start_time=n,this.props.onChange(o),window.localStorage.setItem("App.echarts.__start",r),window.localStorage.setItem("App.echarts.__start_time",n)},label:"Start"},"static-start"):null,this.props.presetData.timeType==="static"?w.jsx(ty,{fullWidth:!0,date:this.props.presetData.end.toString(),time:this.props.presetData.end_time,updateValue:(r,n)=>{const o=JSON.parse(JSON.stringify(this.props.presetData));o.end=r,o.end_time=n,this.props.onChange(o),window.localStorage.setItem("App.echarts.__end",r),window.localStorage.setItem("App.echarts.__end_time",n)},label:"End"},"static-end"):null,this.props.presetData.timeType!=="static"?w.jsx(Dt,{fullWidth:!0,value:this.props.presetData.relativeEnd,updateValue:r=>{const n=JSON.parse(JSON.stringify(this.props.presetData));n.relativeEnd=r,this.props.onChange(n),window.localStorage.setItem("App.echarts.__relativeEnd",r)},label:"End",options:s9},"non-static-end"):null,this.props.presetData.timeType!=="static"?w.jsx(Dt,{fullWidth:!0,value:this.props.presetData.range.toString(),updateValue:r=>{const n=JSON.parse(JSON.stringify(this.props.presetData));n.range=r,this.props.onChange(n),window.localStorage.setItem("App.echarts.__range",r)},label:"Range",options:i9},"non-static-range"):null]}renderTimeSpan(){return w.jsxs(w.Fragment,{children:[w.jsxs(tt,{color:"grey",title:P.t("Time span"),size:"small",style:Nn.settingsButton,id:"timeSpanOpenButton",onClick:()=>this.setState({timeSpanOpened:!this.state.timeSpanOpened}),children:[w.jsx(ive,{}),this.props.presetData.timeType==="relative"?`${P.t(i9[this.props.presetData.range])} ${P.t("to")} ${P.t(s9[this.props.presetData.relativeEnd])}`:`${this.props.presetData.start} ${this.props.presetData.start_time} - ${this.props.presetData.end} ${this.props.presetData.end_time}`,w.jsx(z5,{})]}),w.jsx(Re,{sx:Nn.divider}),w.jsx(WE,{style:Nn.popOver,open:this.state.timeSpanOpened,onClose:()=>{this.setState({timeSpanOpened:!1})},anchorEl:()=>document.getElementById("timeSpanOpenButton"),anchorOrigin:{vertical:"bottom",horizontal:"center"},transformOrigin:{vertical:"top",horizontal:"center"},children:w.jsx("div",{style:Nn.popOver,children:w.jsx(Re,{component:"div",sx:Nn.fieldsContainer,children:this.renderTimeSpanElements()})})})]})}renderAggregateElements(){return[w.jsx(Dt,{fullWidth:!0,value:this.props.presetData.chartType,updateValue:r=>{const n=JSON.parse(JSON.stringify(this.props.presetData));n.chartType=r,this.props.onChange(n),window.localStorage.setItem("App.echarts.__chartType",r)},label:"Chart type",options:Xk},"chart-type"),this.props.presetData.chartType!=="auto"?w.jsx(Dt,{fullWidth:!0,value:this.props.presetData.aggregate,updateValue:r=>{const n=JSON.parse(JSON.stringify(this.props.presetData));n.aggregate=r,this.props.onChange(n),window.localStorage.setItem("App.echarts.__aggregate",r)},label:"Aggregate",options:Jk},"aggregate"):null,this.props.presetData.aggregate!=="onchange"?w.jsx(Dt,{fullWidth:!0,value:this.props.presetData.aggregateType,updateValue:r=>{const n=JSON.parse(JSON.stringify(this.props.presetData));n.aggregateType=r,this.props.onChange(n),window.localStorage.setItem("App.echarts.__aggregateType",r)},label:"Step type",options:{count:"counts",step:"seconds"}},"aggregateType"):null,this.props.presetData.aggregate!=="onchange"?w.jsx(Er,{fullWidth:!0,value:this.props.presetData.aggregateSpan,updateValue:r=>{const n=JSON.parse(JSON.stringify(this.props.presetData));n.aggregateSpan=r,this.props.onChange(n),window.localStorage.setItem("App.echarts.__aggregateSpan",r.toString())},label:this.props.presetData.aggregateType==="step"?"Seconds":"Counts"},"aggregateSpan"):null]}renderAggregate(){return w.jsxs(w.Fragment,{children:[w.jsxs(tt,{color:"grey",title:P.t("Aggregate"),size:"small",style:Nn.settingsButton,id:"aggregateOpenButton",onClick:()=>this.setState({aggregateOpened:!this.state.aggregateOpened}),children:[w.jsx(iZt,{style:Nn.aggregateIcon}),Xk[this.props.presetData.chartType]?P.t(Xk[this.props.presetData.chartType]):"","/",Jk[this.props.presetData.aggregate]?P.t(Jk[this.props.presetData.aggregate]):"",w.jsx(z5,{})]}),w.jsx(Re,{sx:Nn.divider}),w.jsx(WE,{open:this.state.aggregateOpened,anchorEl:()=>document.getElementById("aggregateOpenButton"),onClose:()=>{this.setState({aggregateOpened:!1})},children:w.jsx("div",{style:Nn.popOver,children:w.jsx(Re,{component:"div",sx:Nn.fieldsContainer,children:this.renderAggregateElements()})})})]})}renderAutoRefresh(){return this.props.presetData.timeType!=="relative"?null:w.jsx(zer,{sx:Nn.refreshSelect,value:this.props.presetData.live,updateValue:r=>{const n=JSON.parse(JSON.stringify(this.props.presetData));n.live=r,this.props.onChange(n),window.localStorage.setItem("App.echarts.__live",r.toString())},tooltip:P.t("Auto-refresh"),options:l9,renderValue:()=>w.jsxs("div",{style:Nn.refreshSelectButtonTitle,children:[w.jsx(MO,{})," ",P.t(l9[this.props.presetData.live])]})})}render(){const r={timeSpan:!1,aggregate:!1,autoRefresh:!1,bigButton:!1};let n=!1;const o=(this.state.clientWidth||1024)-32-40-20,a=4,i=this.props.presetData.timeType==="relative"?1:0;return o>=Ua.timeSpan+Ua.aggregate+Ua.autoRefresh*i+Ua.bigButton+a*3?(r.timeSpan=!0,r.aggregate=!0,r.autoRefresh=!0,r.bigButton=!0):o>=Ua.timeSpan+Ua.aggregate+Ua.autoRefresh*i+48+a*3?(r.timeSpan=!0,r.aggregate=!0,r.autoRefresh=!!i,r.bigButton=!1):o>=Ua.timeSpan+Ua.aggregate+48+a*2?(r.timeSpan=!0,r.aggregate=!0,n=!!i):(o>=Ua.timeSpan+48+a&&(r.timeSpan=!0),n=!0),w.jsxs(af,{ref:this.toolbarRef,style:Nn.mainDiv,variant:"dense",children:[this.renderShowMore(),r.timeSpan?this.renderTimeSpan():null,r.aggregate?this.renderAggregate():null,r.autoRefresh?w.jsxs(w.Fragment,{children:[this.renderAutoRefresh(),w.jsx(Re,{sx:Nn.divider})]}):null,w.jsx("div",{style:Nn.grow1}),n?w.jsx(Ie,{size:"small",title:P.t("Show controls"),onClick:()=>this.setState({showMore:!0}),children:w.jsx(Ave,{})}):null,r.bigButton?w.jsx(tt,{variant:"contained",color:"primary",onClick:()=>this.props.onCreatePreset(!0),startIcon:w.jsx(Nv,{}),style:{whiteSpace:"nowrap"},children:P.t("Create preset")}):w.jsx(Ie,{size:"small",color:"primary",title:P.t("Create preset"),onClick:()=>this.props.onCreatePreset(!0),children:w.jsx(Nv,{})})]})}}const c9={darkBackground:{stroke:"#3a3a3a !important",fill:"#515151 !important"},iframe:t=>({width:"100%",height:"100%",overflow:"auto",border:0,color:t.palette.primary.main})};class Ber extends m.Component{constructor(){super(...arguments);X(this,"ready",!1);X(this,"refIframe",null);X(this,"lastPresetData","");X(this,"onReceiveMessage",r=>{var n;(r==null?void 0:r.data)==="chartReady"&&(this.ready=!0,this.lastPresetData=JSON.stringify(this.props.presetData),(n=this.refIframe.contentWindow)==null||n.postMessage(this.lastPresetData,"*"),console.log("Received ready from iframe"))})}componentDidMount(){window.addEventListener("message",this.onReceiveMessage,!1)}componentWillUnmount(){window.removeEventListener("message",this.onReceiveMessage,!1)}render(){var r;return window.location.port==="3000"?w.jsx(zn,{sx:c9.iframe,style:{background:"#333"},children:w.jsx("pre",{children:JSON.stringify(this.props.presetData,null,2)})}):(this.lastPresetData!==JSON.stringify(this.props.presetData)&&this.ready&&(this.lastPresetData=JSON.stringify(this.props.presetData),(r=this.refIframe.contentWindow)==null||r.postMessage(this.lastPresetData,"*")),w.jsx("iframe",{ref:n=>{this.refIframe=n},title:"iobrokerChart",style:ue.getStyle(this.props.theme,c9.iframe),src:this.props.src}))}}const Yk={container:{height:"100%",width:"100%",overflow:"hidden"},heightWithoutToolbar:{height:"calc(100% - 48px)"},height100:{height:"100%"}};class Wer extends m.Component{renderToolbar(){return this.props.selectedId&&typeof this.props.selectedId=="string"?null:w.jsx(Fer,{windowWidth:this.props.windowWidth,onChange:this.props.onChange,presetData:this.props.presetData,onCreatePreset:(e,r)=>this.props.onCreatePreset(e,r)})}getChartFrame(){const e=(window.location.search||"").includes("dev=true")?"http://localhost:3000/":"chart/",r=JSON.parse(JSON.stringify(this.props.presetData));return typeof this.props.selectedId=="object"&&r.l&&(delete r.l[0].aggregate,delete r.l[0].chartType),w.jsx("div",{style:typeof this.props.selectedId!="string"?Yk.heightWithoutToolbar:Yk.height100,children:this.props.visible?w.jsx(Ber,{src:`${e}index.html?edit=1`,presetData:r,theme:this.props.theme}):w.jsx(zve,{style:{height:"100%",width:"100%"}})})}render(){return w.jsx(uE,{injectFirst:!0,children:w.jsx(yE,{theme:this.props.theme,children:w.jsxs("div",{style:Yk.container,children:[this.renderToolbar(),this.getChartFrame()]})})})}}function Her(){const t=(window.location.search||"").replace(/^\?/,"").split("&"),e={};return t.forEach(r=>{const[n,o]=r.split("=");e[decodeURIComponent(n)]=o!==void 0?decodeURIComponent(o):!0}),e}const hG=A.createContext({dragDropManager:void 0});function At(t,e,...r){if(Uer()&&e===void 0)throw new Error("invariant requires an error message argument");if(!t){let n;if(e===void 0)n=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{let o=0;n=new Error(e.replace(/%s/g,function(){return r[o++]})),n.name="Invariant Violation"}throw n.framesToPop=1,n}}function Uer(){return typeof process<"u"&&!0}function Ver(t,e,r){return e.split(".").reduce((n,o)=>n&&n[o]?n[o]:r||null,t)}function qer(t,e){return t.filter(r=>r!==e)}function fG(t){return typeof t=="object"}function Ger(t,e){const r=new Map,n=a=>{r.set(a,r.has(a)?r.get(a)+1:1)};t.forEach(n),e.forEach(n);const o=[];return r.forEach((a,i)=>{a===1&&o.push(i)}),o}function Xer(t,e){return t.filter(r=>e.indexOf(r)>-1)}const kA="dnd-core/INIT_COORDS",$_="dnd-core/BEGIN_DRAG",EA="dnd-core/PUBLISH_DRAG_SOURCE",k_="dnd-core/HOVER",E_="dnd-core/DROP",T_="dnd-core/END_DRAG";function d9(t,e){return{type:kA,payload:{sourceClientOffset:e||null,clientOffset:t||null}}}const Jer={type:kA,payload:{clientOffset:null,sourceClientOffset:null}};function Yer(t){return function(r=[],n={publishSource:!0}){const{publishSource:o=!0,clientOffset:a,getSourceClientOffset:i}=n,s=t.getMonitor(),l=t.getRegistry();t.dispatch(d9(a)),Ker(r,s,l);const d=etr(r,s);if(d==null){t.dispatch(Jer);return}let h=null;if(a){if(!i)throw new Error("getSourceClientOffset must be defined");Zer(i),h=i(d)}t.dispatch(d9(a,h));const f=l.getSource(d).beginDrag(s,d);if(f==null)return;Qer(f),l.pinSource(d);const g=l.getSourceType(d);return{type:$_,payload:{itemType:g,item:f,sourceId:d,clientOffset:a||null,sourceClientOffset:h||null,isSourcePublic:!!o}}}}function Ker(t,e,r){At(!e.isDragging(),"Cannot call beginDrag while dragging."),t.forEach(function(n){At(r.getSource(n),"Expected sourceIds to be registered.")})}function Zer(t){At(typeof t=="function","When clientOffset is provided, getSourceClientOffset must be a function.")}function Qer(t){At(fG(t),"Item must be an object.")}function etr(t,e){let r=null;for(let n=t.length-1;n>=0;n--)if(e.canDragSource(t[n])){r=t[n];break}return r}function ttr(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function rtr(t){for(var e=1;e{const l=atr(i,s,o,n),d={type:E_,payload:{dropResult:rtr({},r,l)}};t.dispatch(d)})}}function otr(t){At(t.isDragging(),"Cannot call drop while not dragging."),At(!t.didDrop(),"Cannot call drop twice during one drag operation.")}function atr(t,e,r,n){const o=r.getTarget(t);let a=o?o.drop(n,t):void 0;return itr(a),typeof a>"u"&&(a=e===0?{}:n.getDropResult()),a}function itr(t){At(typeof t>"u"||fG(t),"Drop result must either be an object or undefined.")}function str(t){const e=t.getTargetIds().filter(t.canDropOnTarget,t);return e.reverse(),e}function ltr(t){return function(){const r=t.getMonitor(),n=t.getRegistry();ctr(r);const o=r.getSourceId();return o!=null&&(n.getSource(o,!0).endDrag(r,o),n.unpinSource()),{type:T_}}}function ctr(t){At(t.isDragging(),"Cannot call endDrag while not dragging.")}function aT(t,e){return e===null?t===null:Array.isArray(t)?t.some(r=>r===e):t===e}function dtr(t){return function(r,{clientOffset:n}={}){utr(r);const o=r.slice(0),a=t.getMonitor(),i=t.getRegistry(),s=a.getItemType();return htr(o,i,s),ptr(o,a,i),ftr(o,a,i),{type:k_,payload:{targetIds:o,clientOffset:n||null}}}}function utr(t){At(Array.isArray(t),"Expected targetIds to be an array.")}function ptr(t,e,r){At(e.isDragging(),"Cannot call hover while not dragging."),At(!e.didDrop(),"Cannot call hover after drop.");for(let n=0;n=0;n--){const o=t[n],a=e.getTargetType(o);aT(a,r)||t.splice(n,1)}}function ftr(t,e,r){t.forEach(function(n){r.getTarget(n).hover(e,n)})}function mtr(t){return function(){if(t.getMonitor().isDragging())return{type:EA}}}function gtr(t){return{beginDrag:Yer(t),publishDragSource:mtr(t),hover:dtr(t),drop:ntr(t),endDrag:ltr(t)}}class vtr{receiveBackend(e){this.backend=e}getMonitor(){return this.monitor}getBackend(){return this.backend}getRegistry(){return this.monitor.registry}getActions(){const e=this,{dispatch:r}=this.store;function n(a){return(...i)=>{const s=a.apply(e,i);typeof s<"u"&&r(s)}}const o=gtr(this);return Object.keys(o).reduce((a,i)=>{const s=o[i];return a[i]=n(s),a},{})}dispatch(e){this.store.dispatch(e)}constructor(e,r){this.isSetUp=!1,this.handleRefCountChange=()=>{const n=this.store.getState().refCount>0;this.backend&&(n&&!this.isSetUp?(this.backend.setup(),this.isSetUp=!0):!n&&this.isSetUp&&(this.backend.teardown(),this.isSetUp=!1))},this.store=e,this.monitor=r,e.subscribe(this.handleRefCountChange)}}function ytr(t,e){return{x:t.x+e.x,y:t.y+e.y}}function mG(t,e){return{x:t.x-e.x,y:t.y-e.y}}function _tr(t){const{clientOffset:e,initialClientOffset:r,initialSourceClientOffset:n}=t;return!e||!r||!n?null:mG(ytr(e,n),r)}function btr(t){const{clientOffset:e,initialClientOffset:r}=t;return!e||!r?null:mG(e,r)}const Bh=[],TA=[];Bh.__IS_NONE__=!0;TA.__IS_ALL__=!0;function wtr(t,e){return t===Bh?!1:t===TA||typeof e>"u"?!0:Xer(e,t).length>0}class xtr{subscribeToStateChange(e,r={}){const{handlerIds:n}=r;At(typeof e=="function","listener must be a function."),At(typeof n>"u"||Array.isArray(n),"handlerIds, when specified, must be an array of strings.");let o=this.store.getState().stateId;const a=()=>{const i=this.store.getState(),s=i.stateId;try{s===o||s===o+1&&!wtr(i.dirtyHandlerIds,n)||e()}finally{o=s}};return this.store.subscribe(a)}subscribeToOffsetChange(e){At(typeof e=="function","listener must be a function.");let r=this.store.getState().dragOffset;const n=()=>{const o=this.store.getState().dragOffset;o!==r&&(r=o,e())};return this.store.subscribe(n)}canDragSource(e){if(!e)return!1;const r=this.registry.getSource(e);return At(r,`Expected to find a valid source. sourceId=${e}`),this.isDragging()?!1:r.canDrag(this,e)}canDropOnTarget(e){if(!e)return!1;const r=this.registry.getTarget(e);if(At(r,`Expected to find a valid target. targetId=${e}`),!this.isDragging()||this.didDrop())return!1;const n=this.registry.getTargetType(e),o=this.getItemType();return aT(n,o)&&r.canDrop(this,e)}isDragging(){return!!this.getItemType()}isDraggingSource(e){if(!e)return!1;const r=this.registry.getSource(e,!0);if(At(r,`Expected to find a valid source. sourceId=${e}`),!this.isDragging()||!this.isSourcePublic())return!1;const n=this.registry.getSourceType(e),o=this.getItemType();return n!==o?!1:r.isDragging(this,e)}isOverTarget(e,r={shallow:!1}){if(!e)return!1;const{shallow:n}=r;if(!this.isDragging())return!1;const o=this.registry.getTargetType(e),a=this.getItemType();if(a&&!aT(o,a))return!1;const i=this.getTargetIds();if(!i.length)return!1;const s=i.indexOf(e);return n?s===i.length-1:s>-1}getItemType(){return this.store.getState().dragOperation.itemType}getItem(){return this.store.getState().dragOperation.item}getSourceId(){return this.store.getState().dragOperation.sourceId}getTargetIds(){return this.store.getState().dragOperation.targetIds}getDropResult(){return this.store.getState().dragOperation.dropResult}didDrop(){return this.store.getState().dragOperation.didDrop}isSourcePublic(){return!!this.store.getState().dragOperation.isSourcePublic}getInitialClientOffset(){return this.store.getState().dragOffset.initialClientOffset}getInitialSourceClientOffset(){return this.store.getState().dragOffset.initialSourceClientOffset}getClientOffset(){return this.store.getState().dragOffset.clientOffset}getSourceClientOffset(){return _tr(this.store.getState().dragOffset)}getDifferenceFromInitialOffset(){return btr(this.store.getState().dragOffset)}constructor(e,r){this.store=e,this.registry=r}}const u9=typeof global<"u"?global:self,gG=u9.MutationObserver||u9.WebKitMutationObserver;function vG(t){return function(){const r=setTimeout(o,0),n=setInterval(o,50);function o(){clearTimeout(r),clearInterval(n),t()}}}function Str(t){let e=1;const r=new gG(t),n=document.createTextNode("");return r.observe(n,{characterData:!0}),function(){e=-e,n.data=e}}const Ctr=typeof gG=="function"?Str:vG;class $tr{enqueueTask(e){const{queue:r,requestFlush:n}=this;r.length||(n(),this.flushing=!0),r[r.length]=e}constructor(){this.queue=[],this.pendingErrors=[],this.flushing=!1,this.index=0,this.capacity=1024,this.flush=()=>{const{queue:e}=this;for(;this.indexthis.capacity){for(let n=0,o=e.length-this.index;n{this.pendingErrors.push(e),this.requestErrorThrow()},this.requestFlush=Ctr(this.flush),this.requestErrorThrow=vG(()=>{if(this.pendingErrors.length)throw this.pendingErrors.shift()})}}class ktr{call(){try{this.task&&this.task()}catch(e){this.onError(e)}finally{this.task=null,this.release(this)}}constructor(e,r){this.onError=e,this.release=r,this.task=null}}class Etr{create(e){const r=this.freeTasks,n=r.length?r.pop():new ktr(this.onError,o=>r[r.length]=o);return n.task=e,n}constructor(e){this.onError=e,this.freeTasks=[]}}const yG=new $tr,Ttr=new Etr(yG.registerPendingError);function Otr(t){yG.enqueueTask(Ttr.create(t))}const OA="dnd-core/ADD_SOURCE",DA="dnd-core/ADD_TARGET",AA="dnd-core/REMOVE_SOURCE",O_="dnd-core/REMOVE_TARGET";function Dtr(t){return{type:OA,payload:{sourceId:t}}}function Atr(t){return{type:DA,payload:{targetId:t}}}function Itr(t){return{type:AA,payload:{sourceId:t}}}function Mtr(t){return{type:O_,payload:{targetId:t}}}function Ptr(t){At(typeof t.canDrag=="function","Expected canDrag to be a function."),At(typeof t.beginDrag=="function","Expected beginDrag to be a function."),At(typeof t.endDrag=="function","Expected endDrag to be a function.")}function Ntr(t){At(typeof t.canDrop=="function","Expected canDrop to be a function."),At(typeof t.hover=="function","Expected hover to be a function."),At(typeof t.drop=="function","Expected beginDrag to be a function.")}function iT(t,e){if(e&&Array.isArray(t)){t.forEach(r=>iT(r,!1));return}At(typeof t=="string"||typeof t=="symbol",e?"Type can only be a string, a symbol, or an array of either.":"Type can only be a string or a symbol.")}var qo;(function(t){t.SOURCE="SOURCE",t.TARGET="TARGET"})(qo||(qo={}));let Rtr=0;function jtr(){return Rtr++}function Ltr(t){const e=jtr().toString();switch(t){case qo.SOURCE:return`S${e}`;case qo.TARGET:return`T${e}`;default:throw new Error(`Unknown Handler Role: ${t}`)}}function p9(t){switch(t[0]){case"S":return qo.SOURCE;case"T":return qo.TARGET;default:throw new Error(`Cannot parse handler ID: ${t}`)}}function h9(t,e){const r=t.entries();let n=!1;do{const{done:o,value:[,a]}=r.next();if(a===e)return!0;n=!!o}while(!n);return!1}class ztr{addSource(e,r){iT(e),Ptr(r);const n=this.addHandler(qo.SOURCE,e,r);return this.store.dispatch(Dtr(n)),n}addTarget(e,r){iT(e,!0),Ntr(r);const n=this.addHandler(qo.TARGET,e,r);return this.store.dispatch(Atr(n)),n}containsHandler(e){return h9(this.dragSources,e)||h9(this.dropTargets,e)}getSource(e,r=!1){return At(this.isSourceId(e),"Expected a valid source ID."),r&&e===this.pinnedSourceId?this.pinnedSource:this.dragSources.get(e)}getTarget(e){return At(this.isTargetId(e),"Expected a valid target ID."),this.dropTargets.get(e)}getSourceType(e){return At(this.isSourceId(e),"Expected a valid source ID."),this.types.get(e)}getTargetType(e){return At(this.isTargetId(e),"Expected a valid target ID."),this.types.get(e)}isSourceId(e){return p9(e)===qo.SOURCE}isTargetId(e){return p9(e)===qo.TARGET}removeSource(e){At(this.getSource(e),"Expected an existing source."),this.store.dispatch(Itr(e)),Otr(()=>{this.dragSources.delete(e),this.types.delete(e)})}removeTarget(e){At(this.getTarget(e),"Expected an existing target."),this.store.dispatch(Mtr(e)),this.dropTargets.delete(e),this.types.delete(e)}pinSource(e){const r=this.getSource(e);At(r,"Expected an existing source."),this.pinnedSourceId=e,this.pinnedSource=r}unpinSource(){At(this.pinnedSource,"No source is pinned at the time."),this.pinnedSourceId=null,this.pinnedSource=null}addHandler(e,r,n){const o=Ltr(e);return this.types.set(o,r),e===qo.SOURCE?this.dragSources.set(o,n):e===qo.TARGET&&this.dropTargets.set(o,n),o}constructor(e){this.types=new Map,this.dragSources=new Map,this.dropTargets=new Map,this.pinnedSourceId=null,this.pinnedSource=null,this.store=e}}const Ftr=(t,e)=>t===e;function Btr(t,e){return!t&&!e?!0:!t||!e?!1:t.x===e.x&&t.y===e.y}function Wtr(t,e,r=Ftr){if(t.length!==e.length)return!1;for(let n=0;n0||!Wtr(r,n)))return Bh;const i=n[n.length-1],s=r[r.length-1];return i!==s&&(i&&o.push(i),s&&o.push(s)),o}function Utr(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Vtr(t){for(var e=1;e=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function orr(t,e){if(t==null)return{};var r={},n=Object.keys(t),o,a;for(a=0;a=0)&&(r[o]=t[o]);return r}let m9=0;const iv=Symbol.for("__REACT_DND_CONTEXT_INSTANCE__");var arr=A.memo(function(e){var{children:r}=e,n=nrr(e,["children"]);const[o,a]=irr(n);return A.useEffect(()=>{if(a){const i=_G();return++m9,()=>{--m9===0&&(i[iv]=null)}}},[]),w.jsx(hG.Provider,{value:o,children:r})});function irr(t){if("manager"in t)return[{dragDropManager:t.manager},!1];const e=srr(t.backend,t.context,t.options,t.debugMode),r=!t.context;return[e,r]}function srr(t,e=_G(),r,n){const o=e;return o[iv]||(o[iv]={dragDropManager:trr(t,e,r,n)}),o[iv]}function _G(){return typeof global<"u"?global:window}var Kk,g9;function lrr(){return g9||(g9=1,Kk=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,a;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(a=Object.keys(e),n=a.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,a[o]))return!1;for(o=n;o--!==0;){var i=a[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}),Kk}var crr=lrr();const drr=so(crr),Wl=typeof window<"u"?A.useLayoutEffect:A.useEffect;function urr(t,e,r){const[n,o]=A.useState(()=>e(t)),a=A.useCallback(()=>{const i=e(t);drr(n,i)||(o(i),r&&r())},[n,t,r]);return Wl(a),[n,a]}function prr(t,e,r){const[n,o]=urr(t,e,r);return Wl(function(){const i=t.getHandlerId();if(i!=null)return t.subscribeToStateChange(o,{handlerIds:[i]})},[t,o]),n}function bG(t,e,r){return prr(e,t||(()=>({})),()=>r.reconnect())}function wG(t,e){const r=[];return typeof t!="function"&&r.push(t),A.useMemo(()=>typeof t=="function"?t():t,r)}function hrr(t){return A.useMemo(()=>t.hooks.dragSource(),[t])}function frr(t){return A.useMemo(()=>t.hooks.dragPreview(),[t])}let Zk=!1,Qk=!1;class mrr{receiveHandlerId(e){this.sourceId=e}getHandlerId(){return this.sourceId}canDrag(){At(!Zk,"You may not call monitor.canDrag() inside your canDrag() implementation. Read more: http://react-dnd.github.io/react-dnd/docs/api/drag-source-monitor");try{return Zk=!0,this.internalMonitor.canDragSource(this.sourceId)}finally{Zk=!1}}isDragging(){if(!this.sourceId)return!1;At(!Qk,"You may not call monitor.isDragging() inside your isDragging() implementation. Read more: http://react-dnd.github.io/react-dnd/docs/api/drag-source-monitor");try{return Qk=!0,this.internalMonitor.isDraggingSource(this.sourceId)}finally{Qk=!1}}subscribeToStateChange(e,r){return this.internalMonitor.subscribeToStateChange(e,r)}isDraggingSource(e){return this.internalMonitor.isDraggingSource(e)}isOverTarget(e,r){return this.internalMonitor.isOverTarget(e,r)}getTargetIds(){return this.internalMonitor.getTargetIds()}isSourcePublic(){return this.internalMonitor.isSourcePublic()}getSourceId(){return this.internalMonitor.getSourceId()}subscribeToOffsetChange(e){return this.internalMonitor.subscribeToOffsetChange(e)}canDragSource(e){return this.internalMonitor.canDragSource(e)}canDropOnTarget(e){return this.internalMonitor.canDropOnTarget(e)}getItemType(){return this.internalMonitor.getItemType()}getItem(){return this.internalMonitor.getItem()}getDropResult(){return this.internalMonitor.getDropResult()}didDrop(){return this.internalMonitor.didDrop()}getInitialClientOffset(){return this.internalMonitor.getInitialClientOffset()}getInitialSourceClientOffset(){return this.internalMonitor.getInitialSourceClientOffset()}getSourceClientOffset(){return this.internalMonitor.getSourceClientOffset()}getClientOffset(){return this.internalMonitor.getClientOffset()}getDifferenceFromInitialOffset(){return this.internalMonitor.getDifferenceFromInitialOffset()}constructor(e){this.sourceId=null,this.internalMonitor=e.getMonitor()}}let eE=!1;class grr{receiveHandlerId(e){this.targetId=e}getHandlerId(){return this.targetId}subscribeToStateChange(e,r){return this.internalMonitor.subscribeToStateChange(e,r)}canDrop(){if(!this.targetId)return!1;At(!eE,"You may not call monitor.canDrop() inside your canDrop() implementation. Read more: http://react-dnd.github.io/react-dnd/docs/api/drop-target-monitor");try{return eE=!0,this.internalMonitor.canDropOnTarget(this.targetId)}finally{eE=!1}}isOver(e){return this.targetId?this.internalMonitor.isOverTarget(this.targetId,e):!1}getItemType(){return this.internalMonitor.getItemType()}getItem(){return this.internalMonitor.getItem()}getDropResult(){return this.internalMonitor.getDropResult()}didDrop(){return this.internalMonitor.didDrop()}getInitialClientOffset(){return this.internalMonitor.getInitialClientOffset()}getInitialSourceClientOffset(){return this.internalMonitor.getInitialSourceClientOffset()}getSourceClientOffset(){return this.internalMonitor.getSourceClientOffset()}getClientOffset(){return this.internalMonitor.getClientOffset()}getDifferenceFromInitialOffset(){return this.internalMonitor.getDifferenceFromInitialOffset()}constructor(e){this.targetId=null,this.internalMonitor=e.getMonitor()}}function vrr(t,e,r){const n=r.getRegistry(),o=n.addTarget(t,e);return[o,()=>n.removeTarget(o)]}function yrr(t,e,r){const n=r.getRegistry(),o=n.addSource(t,e);return[o,()=>n.removeSource(o)]}function sT(t,e,r,n){let o;if(o!==void 0)return!!o;if(t===e)return!0;if(typeof t!="object"||!t||typeof e!="object"||!e)return!1;const a=Object.keys(t),i=Object.keys(e);if(a.length!==i.length)return!1;const s=Object.prototype.hasOwnProperty.bind(e);for(let l=0;l, or turn it into a drag source or a drop target itself.`)}function brr(t){return(e=null,r=null)=>{if(!A.isValidElement(e)){const a=e;return t(a,r),a}const n=e;return _rr(n),wrr(n,r?a=>t(a,r):t)}}function xG(t){const e={};return Object.keys(t).forEach(r=>{const n=t[r];if(r.endsWith("Ref"))e[r]=t[r];else{const o=brr(n);e[r]=()=>o}}),e}function v9(t,e){typeof t=="function"?t(e):t.current=e}function wrr(t,e){const r=t.ref;return At(typeof r!="string","Cannot connect React DnD to an element with an existing string ref. Please convert it to use a callback ref instead, or wrap it into a or
. Read more: https://reactjs.org/docs/refs-and-the-dom.html#callback-refs"),r?A.cloneElement(t,{ref:n=>{v9(r,n),v9(e,n)}}):A.cloneElement(t,{ref:e})}class xrr{receiveHandlerId(e){this.handlerId!==e&&(this.handlerId=e,this.reconnect())}get connectTarget(){return this.dragSource}get dragSourceOptions(){return this.dragSourceOptionsInternal}set dragSourceOptions(e){this.dragSourceOptionsInternal=e}get dragPreviewOptions(){return this.dragPreviewOptionsInternal}set dragPreviewOptions(e){this.dragPreviewOptionsInternal=e}reconnect(){const e=this.reconnectDragSource();this.reconnectDragPreview(e)}reconnectDragSource(){const e=this.dragSource,r=this.didHandlerIdChange()||this.didConnectedDragSourceChange()||this.didDragSourceOptionsChange();return r&&this.disconnectDragSource(),this.handlerId?e?(r&&(this.lastConnectedHandlerId=this.handlerId,this.lastConnectedDragSource=e,this.lastConnectedDragSourceOptions=this.dragSourceOptions,this.dragSourceUnsubscribe=this.backend.connectDragSource(this.handlerId,e,this.dragSourceOptions)),r):(this.lastConnectedDragSource=e,r):r}reconnectDragPreview(e=!1){const r=this.dragPreview,n=e||this.didHandlerIdChange()||this.didConnectedDragPreviewChange()||this.didDragPreviewOptionsChange();if(n&&this.disconnectDragPreview(),!!this.handlerId){if(!r){this.lastConnectedDragPreview=r;return}n&&(this.lastConnectedHandlerId=this.handlerId,this.lastConnectedDragPreview=r,this.lastConnectedDragPreviewOptions=this.dragPreviewOptions,this.dragPreviewUnsubscribe=this.backend.connectDragPreview(this.handlerId,r,this.dragPreviewOptions))}}didHandlerIdChange(){return this.lastConnectedHandlerId!==this.handlerId}didConnectedDragSourceChange(){return this.lastConnectedDragSource!==this.dragSource}didConnectedDragPreviewChange(){return this.lastConnectedDragPreview!==this.dragPreview}didDragSourceOptionsChange(){return!sT(this.lastConnectedDragSourceOptions,this.dragSourceOptions)}didDragPreviewOptionsChange(){return!sT(this.lastConnectedDragPreviewOptions,this.dragPreviewOptions)}disconnectDragSource(){this.dragSourceUnsubscribe&&(this.dragSourceUnsubscribe(),this.dragSourceUnsubscribe=void 0)}disconnectDragPreview(){this.dragPreviewUnsubscribe&&(this.dragPreviewUnsubscribe(),this.dragPreviewUnsubscribe=void 0,this.dragPreviewNode=null,this.dragPreviewRef=null)}get dragSource(){return this.dragSourceNode||this.dragSourceRef&&this.dragSourceRef.current}get dragPreview(){return this.dragPreviewNode||this.dragPreviewRef&&this.dragPreviewRef.current}clearDragSource(){this.dragSourceNode=null,this.dragSourceRef=null}clearDragPreview(){this.dragPreviewNode=null,this.dragPreviewRef=null}constructor(e){this.hooks=xG({dragSource:(r,n)=>{this.clearDragSource(),this.dragSourceOptions=n||null,lT(r)?this.dragSourceRef=r:this.dragSourceNode=r,this.reconnectDragSource()},dragPreview:(r,n)=>{this.clearDragPreview(),this.dragPreviewOptions=n||null,lT(r)?this.dragPreviewRef=r:this.dragPreviewNode=r,this.reconnectDragPreview()}}),this.handlerId=null,this.dragSourceRef=null,this.dragSourceOptionsInternal=null,this.dragPreviewRef=null,this.dragPreviewOptionsInternal=null,this.lastConnectedHandlerId=null,this.lastConnectedDragSource=null,this.lastConnectedDragSourceOptions=null,this.lastConnectedDragPreview=null,this.lastConnectedDragPreviewOptions=null,this.backend=e}}class Srr{get connectTarget(){return this.dropTarget}reconnect(){const e=this.didHandlerIdChange()||this.didDropTargetChange()||this.didOptionsChange();e&&this.disconnectDropTarget();const r=this.dropTarget;if(this.handlerId){if(!r){this.lastConnectedDropTarget=r;return}e&&(this.lastConnectedHandlerId=this.handlerId,this.lastConnectedDropTarget=r,this.lastConnectedDropTargetOptions=this.dropTargetOptions,this.unsubscribeDropTarget=this.backend.connectDropTarget(this.handlerId,r,this.dropTargetOptions))}}receiveHandlerId(e){e!==this.handlerId&&(this.handlerId=e,this.reconnect())}get dropTargetOptions(){return this.dropTargetOptionsInternal}set dropTargetOptions(e){this.dropTargetOptionsInternal=e}didHandlerIdChange(){return this.lastConnectedHandlerId!==this.handlerId}didDropTargetChange(){return this.lastConnectedDropTarget!==this.dropTarget}didOptionsChange(){return!sT(this.lastConnectedDropTargetOptions,this.dropTargetOptions)}disconnectDropTarget(){this.unsubscribeDropTarget&&(this.unsubscribeDropTarget(),this.unsubscribeDropTarget=void 0)}get dropTarget(){return this.dropTargetNode||this.dropTargetRef&&this.dropTargetRef.current}clearDropTarget(){this.dropTargetRef=null,this.dropTargetNode=null}constructor(e){this.hooks=xG({dropTarget:(r,n)=>{this.clearDropTarget(),this.dropTargetOptions=n,lT(r)?this.dropTargetRef=r:this.dropTargetNode=r,this.reconnect()}}),this.handlerId=null,this.dropTargetRef=null,this.dropTargetOptionsInternal=null,this.lastConnectedHandlerId=null,this.lastConnectedDropTarget=null,this.lastConnectedDropTargetOptions=null,this.backend=e}}function Uu(){const{dragDropManager:t}=A.useContext(hG);return At(t!=null,"Expected drag drop context"),t}function Crr(t,e){const r=Uu(),n=A.useMemo(()=>new xrr(r.getBackend()),[r]);return Wl(()=>(n.dragSourceOptions=t||null,n.reconnect(),()=>n.disconnectDragSource()),[n,t]),Wl(()=>(n.dragPreviewOptions=e||null,n.reconnect(),()=>n.disconnectDragPreview()),[n,e]),n}function $rr(){const t=Uu();return A.useMemo(()=>new mrr(t),[t])}class krr{beginDrag(){const e=this.spec,r=this.monitor;let n=null;return typeof e.item=="object"?n=e.item:typeof e.item=="function"?n=e.item(r):n={},n??null}canDrag(){const e=this.spec,r=this.monitor;return typeof e.canDrag=="boolean"?e.canDrag:typeof e.canDrag=="function"?e.canDrag(r):!0}isDragging(e,r){const n=this.spec,o=this.monitor,{isDragging:a}=n;return a?a(o):r===e.getSourceId()}endDrag(){const e=this.spec,r=this.monitor,n=this.connector,{end:o}=e;o&&o(r.getItem(),r),n.reconnect()}constructor(e,r,n){this.spec=e,this.monitor=r,this.connector=n}}function Err(t,e,r){const n=A.useMemo(()=>new krr(t,e,r),[e,r]);return A.useEffect(()=>{n.spec=t},[t]),n}function Trr(t){return A.useMemo(()=>{const e=t.type;return At(e!=null,"spec.type must be defined"),e},[t])}function Orr(t,e,r){const n=Uu(),o=Err(t,e,r),a=Trr(t);Wl(function(){if(a!=null){const[s,l]=yrr(a,o,n);return e.receiveHandlerId(s),r.receiveHandlerId(s),l}},[n,e,r,o,a])}function Drr(t,e){const r=wG(t);At(!r.begin,"useDrag::spec.begin was deprecated in v14. Replace spec.begin() with spec.item(). (see more here - https://react-dnd.github.io/react-dnd/docs/api/use-drag)");const n=$rr(),o=Crr(r.options,r.previewOptions);return Orr(r,n,o),[bG(r.collect,n,o),hrr(o),frr(o)]}function Arr(t){return A.useMemo(()=>t.hooks.dropTarget(),[t])}function Irr(t){const e=Uu(),r=A.useMemo(()=>new Srr(e.getBackend()),[e]);return Wl(()=>(r.dropTargetOptions=t||null,r.reconnect(),()=>r.disconnectDropTarget()),[t]),r}function Mrr(){const t=Uu();return A.useMemo(()=>new grr(t),[t])}function Prr(t){const{accept:e}=t;return A.useMemo(()=>(At(t.accept!=null,"accept must be defined"),Array.isArray(e)?e:[e]),[e])}class Nrr{canDrop(){const e=this.spec,r=this.monitor;return e.canDrop?e.canDrop(r.getItem(),r):!0}hover(){const e=this.spec,r=this.monitor;e.hover&&e.hover(r.getItem(),r)}drop(){const e=this.spec,r=this.monitor;if(e.drop)return e.drop(r.getItem(),r)}constructor(e,r){this.spec=e,this.monitor=r}}function Rrr(t,e){const r=A.useMemo(()=>new Nrr(t,e),[e]);return A.useEffect(()=>{r.spec=t},[t]),r}function jrr(t,e,r){const n=Uu(),o=Rrr(t,e),a=Prr(t);Wl(function(){const[s,l]=vrr(a,o,n);return e.receiveHandlerId(s),r.receiveHandlerId(s),l},[n,e,o,r,a.map(i=>i.toString()).join("|")])}function Lrr(t,e){const r=wG(t),n=Mrr(),o=Irr(r.options);return jrr(r,n,o),[bG(r.collect,n,o),Arr(o)]}function SG(t){let e=null;return()=>(e==null&&(e=t()),e)}function zrr(t,e){return t.filter(r=>r!==e)}function Frr(t,e){const r=new Set,n=a=>r.add(a);t.forEach(n),e.forEach(n);const o=[];return r.forEach(a=>o.push(a)),o}class Brr{enter(e){const r=this.entered.length,n=o=>this.isNodeInDocument(o)&&(!o.contains||o.contains(e));return this.entered=Frr(this.entered.filter(n),[e]),r===0&&this.entered.length>0}leave(e){const r=this.entered.length;return this.entered=zrr(this.entered.filter(this.isNodeInDocument),e),r>0&&this.entered.length===0}reset(){this.entered=[]}constructor(e){this.entered=[],this.isNodeInDocument=e}}class Wrr{initializeExposedProperties(){Object.keys(this.config.exposeProperties).forEach(e=>{Object.defineProperty(this.item,e,{configurable:!0,enumerable:!0,get(){return console.warn(`Browser doesn't allow reading "${e}" until the drop event.`),null}})})}loadDataTransfer(e){if(e){const r={};Object.keys(this.config.exposeProperties).forEach(n=>{const o=this.config.exposeProperties[n];o!=null&&(r[n]={value:o(e,this.config.matchesTypes),configurable:!0,enumerable:!0})}),Object.defineProperties(this.item,r)}}canDrag(){return!0}beginDrag(){return this.item}isDragging(e,r){return r===e.getSourceId()}endDrag(){}constructor(e){this.config=e,this.item={},this.initializeExposedProperties()}}const CG="__NATIVE_FILE__",$G="__NATIVE_URL__",kG="__NATIVE_TEXT__",EG="__NATIVE_HTML__",y9=Object.freeze(Object.defineProperty({__proto__:null,FILE:CG,HTML:EG,TEXT:kG,URL:$G},Symbol.toStringTag,{value:"Module"}));function tE(t,e,r){const n=e.reduce((o,a)=>o||t.getData(a),"");return n??r}const cT={[CG]:{exposeProperties:{files:t=>Array.prototype.slice.call(t.files),items:t=>t.items,dataTransfer:t=>t},matchesTypes:["Files"]},[EG]:{exposeProperties:{html:(t,e)=>tE(t,e,""),dataTransfer:t=>t},matchesTypes:["Html","text/html"]},[$G]:{exposeProperties:{urls:(t,e)=>tE(t,e,"").split(` -`),dataTransfer:t=>t},matchesTypes:["Url","text/uri-list"]},[kG]:{exposeProperties:{text:(t,e)=>tE(t,e,""),dataTransfer:t=>t},matchesTypes:["Text","text/plain"]}};function Hrr(t,e){const r=cT[t];if(!r)throw new Error(`native type ${t} has no configuration`);const n=new Wrr(r);return n.loadDataTransfer(e),n}function rE(t){if(!t)return null;const e=Array.prototype.slice.call(t.types||[]);return Object.keys(cT).filter(r=>{const n=cT[r];return n!=null&&n.matchesTypes?n.matchesTypes.some(o=>e.indexOf(o)>-1):!1})[0]||null}const Urr=SG(()=>/firefox/i.test(navigator.userAgent)),TG=SG(()=>!!window.safari);class _9{interpolate(e){const{xs:r,ys:n,c1s:o,c2s:a,c3s:i}=this;let s=r.length-1;if(e===r[s])return n[s];let l=0,d=i.length-1,h;for(;l<=d;){h=Math.floor(.5*(l+d));const g=r[h];if(ge)d=h-1;else return n[h]}s=Math.max(0,d);const u=e-r[s],f=u*u;return n[s]+o[s]*u+a[s]*f+i[s]*u*f}constructor(e,r){const{length:n}=e,o=[];for(let g=0;ge[g]{let O=new _9([0,.5,1],[l.y,l.y/h*y,l.y+y-h]).interpolate(f);return TG()&&a&&(O+=(window.devicePixelRatio-1)*y),O},x=()=>new _9([0,.5,1],[l.x,l.x/d*g,l.x+g-d]).interpolate(u),{offsetX:S,offsetY:T}=o,E=S===0||S,$=T===0||T;return{x:E?S:x(),y:$?T:b()}}class Jrr{get window(){if(this.globalContext)return this.globalContext;if(typeof window<"u")return window}get document(){var e;return!((e=this.globalContext)===null||e===void 0)&&e.document?this.globalContext.document:this.window?this.window.document:void 0}get rootElement(){var e;return((e=this.optionsArgs)===null||e===void 0?void 0:e.rootElement)||this.window}constructor(e,r){this.ownerDocument=null,this.globalContext=e,this.optionsArgs=r}}function Yrr(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function b9(t){for(var e=1;e{this.sourcePreviewNodes.delete(e),this.sourcePreviewNodeOptions.delete(e)}}connectDragSource(e,r,n){this.sourceNodes.set(e,r),this.sourceNodeOptions.set(e,n);const o=i=>this.handleDragStart(i,e),a=i=>this.handleSelectStart(i);return r.setAttribute("draggable","true"),r.addEventListener("dragstart",o),r.addEventListener("selectstart",a),()=>{this.sourceNodes.delete(e),this.sourceNodeOptions.delete(e),r.removeEventListener("dragstart",o),r.removeEventListener("selectstart",a),r.setAttribute("draggable","false")}}connectDropTarget(e,r){const n=i=>this.handleDragEnter(i,e),o=i=>this.handleDragOver(i,e),a=i=>this.handleDrop(i,e);return r.addEventListener("dragenter",n),r.addEventListener("dragover",o),r.addEventListener("drop",a),()=>{r.removeEventListener("dragenter",n),r.removeEventListener("dragover",o),r.removeEventListener("drop",a)}}addEventListeners(e){e.addEventListener&&(e.addEventListener("dragstart",this.handleTopDragStart),e.addEventListener("dragstart",this.handleTopDragStartCapture,!0),e.addEventListener("dragend",this.handleTopDragEndCapture,!0),e.addEventListener("dragenter",this.handleTopDragEnter),e.addEventListener("dragenter",this.handleTopDragEnterCapture,!0),e.addEventListener("dragleave",this.handleTopDragLeaveCapture,!0),e.addEventListener("dragover",this.handleTopDragOver),e.addEventListener("dragover",this.handleTopDragOverCapture,!0),e.addEventListener("drop",this.handleTopDrop),e.addEventListener("drop",this.handleTopDropCapture,!0))}removeEventListeners(e){e.removeEventListener&&(e.removeEventListener("dragstart",this.handleTopDragStart),e.removeEventListener("dragstart",this.handleTopDragStartCapture,!0),e.removeEventListener("dragend",this.handleTopDragEndCapture,!0),e.removeEventListener("dragenter",this.handleTopDragEnter),e.removeEventListener("dragenter",this.handleTopDragEnterCapture,!0),e.removeEventListener("dragleave",this.handleTopDragLeaveCapture,!0),e.removeEventListener("dragover",this.handleTopDragOver),e.removeEventListener("dragover",this.handleTopDragOverCapture,!0),e.removeEventListener("drop",this.handleTopDrop),e.removeEventListener("drop",this.handleTopDropCapture,!0))}getCurrentSourceNodeOptions(){const e=this.monitor.getSourceId(),r=this.sourceNodeOptions.get(e);return b9({dropEffect:this.altKeyPressed?"copy":"move"},r||{})}getCurrentDropEffect(){return this.isDraggingNativeItem()?"copy":this.getCurrentSourceNodeOptions().dropEffect}getCurrentSourcePreviewNodeOptions(){const e=this.monitor.getSourceId(),r=this.sourcePreviewNodeOptions.get(e);return b9({anchorX:.5,anchorY:.5,captureDraggingState:!1},r||{})}isDraggingNativeItem(){const e=this.monitor.getItemType();return Object.keys(y9).some(r=>y9[r]===e)}beginDragNativeItem(e,r){this.clearCurrentDragSourceNode(),this.currentNativeSource=Hrr(e,r),this.currentNativeHandle=this.registry.addSource(e,this.currentNativeSource),this.actions.beginDrag([this.currentNativeHandle])}setCurrentDragSourceNode(e){this.clearCurrentDragSourceNode(),this.currentDragSourceNode=e;const r=1e3;this.mouseMoveTimeoutTimer=setTimeout(()=>{var n;return(n=this.rootElement)===null||n===void 0?void 0:n.addEventListener("mousemove",this.endDragIfSourceWasRemovedFromDOM,!0)},r)}clearCurrentDragSourceNode(){if(this.currentDragSourceNode){if(this.currentDragSourceNode=null,this.rootElement){var e;(e=this.window)===null||e===void 0||e.clearTimeout(this.mouseMoveTimeoutTimer||void 0),this.rootElement.removeEventListener("mousemove",this.endDragIfSourceWasRemovedFromDOM,!0)}return this.mouseMoveTimeoutTimer=null,!0}return!1}handleDragStart(e,r){e.defaultPrevented||(this.dragStartSourceIds||(this.dragStartSourceIds=[]),this.dragStartSourceIds.unshift(r))}handleDragEnter(e,r){this.dragEnterTargetIds.unshift(r)}handleDragOver(e,r){this.dragOverTargetIds===null&&(this.dragOverTargetIds=[]),this.dragOverTargetIds.unshift(r)}handleDrop(e,r){this.dropTargetIds.unshift(r)}constructor(e,r,n){this.sourcePreviewNodes=new Map,this.sourcePreviewNodeOptions=new Map,this.sourceNodes=new Map,this.sourceNodeOptions=new Map,this.dragStartSourceIds=null,this.dropTargetIds=[],this.dragEnterTargetIds=[],this.currentNativeSource=null,this.currentNativeHandle=null,this.currentDragSourceNode=null,this.altKeyPressed=!1,this.mouseMoveTimeoutTimer=null,this.asyncEndDragFrameId=null,this.dragOverTargetIds=null,this.lastClientOffset=null,this.hoverRafId=null,this.getSourceClientOffset=o=>{const a=this.sourceNodes.get(o);return a&&OG(a)||null},this.endDragNativeItem=()=>{this.isDraggingNativeItem()&&(this.actions.endDrag(),this.currentNativeHandle&&this.registry.removeSource(this.currentNativeHandle),this.currentNativeHandle=null,this.currentNativeSource=null)},this.isNodeInDocument=o=>!!(o&&this.document&&this.document.body&&this.document.body.contains(o)),this.endDragIfSourceWasRemovedFromDOM=()=>{const o=this.currentDragSourceNode;o==null||this.isNodeInDocument(o)||(this.clearCurrentDragSourceNode()&&this.monitor.isDragging()&&this.actions.endDrag(),this.cancelHover())},this.scheduleHover=o=>{this.hoverRafId===null&&typeof requestAnimationFrame<"u"&&(this.hoverRafId=requestAnimationFrame(()=>{this.monitor.isDragging()&&this.actions.hover(o||[],{clientOffset:this.lastClientOffset}),this.hoverRafId=null}))},this.cancelHover=()=>{this.hoverRafId!==null&&typeof cancelAnimationFrame<"u"&&(cancelAnimationFrame(this.hoverRafId),this.hoverRafId=null)},this.handleTopDragStartCapture=()=>{this.clearCurrentDragSourceNode(),this.dragStartSourceIds=[]},this.handleTopDragStart=o=>{if(o.defaultPrevented)return;const{dragStartSourceIds:a}=this;this.dragStartSourceIds=null;const i=Vg(o);this.monitor.isDragging()&&(this.actions.endDrag(),this.cancelHover()),this.actions.beginDrag(a||[],{publishSource:!1,getSourceClientOffset:this.getSourceClientOffset,clientOffset:i});const{dataTransfer:s}=o,l=rE(s);if(this.monitor.isDragging()){if(s&&typeof s.setDragImage=="function"){const h=this.monitor.getSourceId(),u=this.sourceNodes.get(h),f=this.sourcePreviewNodes.get(h)||u;if(f){const{anchorX:g,anchorY:y,offsetX:b,offsetY:x}=this.getCurrentSourcePreviewNodeOptions(),E=Xrr(u,f,i,{anchorX:g,anchorY:y},{offsetX:b,offsetY:x});s.setDragImage(f,E.x,E.y)}}try{s==null||s.setData("application/json",{})}catch{}this.setCurrentDragSourceNode(o.target);const{captureDraggingState:d}=this.getCurrentSourcePreviewNodeOptions();d?this.actions.publishDragSource():setTimeout(()=>this.actions.publishDragSource(),0)}else if(l)this.beginDragNativeItem(l);else{if(s&&!s.types&&(o.target&&!o.target.hasAttribute||!o.target.hasAttribute("draggable")))return;o.preventDefault()}},this.handleTopDragEndCapture=()=>{this.clearCurrentDragSourceNode()&&this.monitor.isDragging()&&this.actions.endDrag(),this.cancelHover()},this.handleTopDragEnterCapture=o=>{if(this.dragEnterTargetIds=[],this.isDraggingNativeItem()){var a;(a=this.currentNativeSource)===null||a===void 0||a.loadDataTransfer(o.dataTransfer)}if(!this.enterLeaveCounter.enter(o.target)||this.monitor.isDragging())return;const{dataTransfer:s}=o,l=rE(s);l&&this.beginDragNativeItem(l,s)},this.handleTopDragEnter=o=>{const{dragEnterTargetIds:a}=this;if(this.dragEnterTargetIds=[],!this.monitor.isDragging())return;this.altKeyPressed=o.altKey,a.length>0&&this.actions.hover(a,{clientOffset:Vg(o)}),a.some(s=>this.monitor.canDropOnTarget(s))&&(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect=this.getCurrentDropEffect()))},this.handleTopDragOverCapture=o=>{if(this.dragOverTargetIds=[],this.isDraggingNativeItem()){var a;(a=this.currentNativeSource)===null||a===void 0||a.loadDataTransfer(o.dataTransfer)}},this.handleTopDragOver=o=>{const{dragOverTargetIds:a}=this;if(this.dragOverTargetIds=[],!this.monitor.isDragging()){o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect="none");return}this.altKeyPressed=o.altKey,this.lastClientOffset=Vg(o),this.scheduleHover(a),(a||[]).some(s=>this.monitor.canDropOnTarget(s))?(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect=this.getCurrentDropEffect())):this.isDraggingNativeItem()?o.preventDefault():(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect="none"))},this.handleTopDragLeaveCapture=o=>{this.isDraggingNativeItem()&&o.preventDefault(),this.enterLeaveCounter.leave(o.target)&&(this.isDraggingNativeItem()&&setTimeout(()=>this.endDragNativeItem(),0),this.cancelHover())},this.handleTopDropCapture=o=>{if(this.dropTargetIds=[],this.isDraggingNativeItem()){var a;o.preventDefault(),(a=this.currentNativeSource)===null||a===void 0||a.loadDataTransfer(o.dataTransfer)}else rE(o.dataTransfer)&&o.preventDefault();this.enterLeaveCounter.reset()},this.handleTopDrop=o=>{const{dropTargetIds:a}=this;this.dropTargetIds=[],this.actions.hover(a,{clientOffset:Vg(o)}),this.actions.drop({dropEffect:this.getCurrentDropEffect()}),this.isDraggingNativeItem()?this.endDragNativeItem():this.monitor.isDragging()&&this.actions.endDrag(),this.cancelHover()},this.handleSelectStart=o=>{const a=o.target;typeof a.dragDrop=="function"&&(a.tagName==="INPUT"||a.tagName==="SELECT"||a.tagName==="TEXTAREA"||a.isContentEditable||(o.preventDefault(),a.dragDrop()))},this.options=new Jrr(r,n),this.actions=e.getActions(),this.monitor=e.getMonitor(),this.registry=e.getRegistry(),this.enterLeaveCounter=new Brr(this.isNodeInDocument)}}const Zrr=function(e,r,n){return new Krr(e,r,n)},ad="_consumption_",Qrr=!window.location.search.includes("hidden=false");function DG(t){let e=[];return Object.values(t.subFolders||{}).forEach(r=>e=e.concat(DG(r))),e}const enr=t=>{const{onDrop:e}=t,[{isOver:r,isOverAny:n},o]=Lrr({accept:"item",drop:a=>e(a.name),collect:a=>({isOver:a.isOver({shallow:!0}),isOverAny:a.isOver()})});return w.jsx("div",{ref:o,style:{background:r?"#40adff":void 0,opacity:n?.3:void 0},children:t.children})},tnr=t=>{const{name:e}=t,[{opacity:r},n]=Drr({type:"item",item:()=>({name:e}),collect:o=>({opacity:o.isDragging()?.3:1})});return w.jsx("div",{ref:n,style:{opacity:r,transform:"translate3d(0, 0, 0)"},children:t.children})},w9=16,nE=/[.\][*,;'"`<>\\?]/g,Tt={noGutters:{pt:0,pb:0,width:"100%"},changed:t=>({position:"relative","&:after":{content:'""',position:"absolute",top:2,right:2,width:5,height:5,borderRadius:5,background:(t.palette.mode==="dark","#CC0000")}}),itemIcon:{width:32,height:32,marginRight:4},itemIconFolder:{cursor:"pointer"},buttonsContainer:{"& button":{whiteSpace:"nowrap"}},itemIconPreset:t=>({color:t.palette.mode==="dark"?t.palette.primary.light:t.palette.primary.dark,position:"relative"}),folderIconPreset:t=>({color:t.palette.mode==="dark"?t.palette.secondary.dark:t.palette.secondary.light}),width100:{width:"100%"},buttonIcon:{marginRight:4},itemIconRoot:{minWidth:24},listItemSubTitle:{fontSize:"smaller",opacity:.7,fontStyle:"italic",display:"inline-block",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",width:"100%"},mainList:{width:"calc(100% - 8px)",ml:"8px"},iconCopy:{width:16},listItemSecondaryAction:{right:7},listItemTitle:{lineHeight:1,width:"100%"},listItemTitleDiv:{display:"inline-block",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",width:"100%"},itemIconNumber:t=>({position:"absolute",fontSize:12,top:8,left:-1,width:"100%",textAlign:"center",color:t.palette.mode==="dark"?"#000":"#FFF"}),textColor:t=>({color:t.palette.mode==="dark"?"#FFF !important":"#000 !important"}),selected:t=>({color:t.palette.mode==="dark"?t.palette.primary.light:t.palette.primary.dark})};class oy extends A.Component{constructor(r){super(r);X(this,"refSelected");X(this,"scrollToSelect",!1);X(this,"scrollTimeout",null);X(this,"onPresetChange",(r,n)=>{if(!(r!=null&&r.startsWith("echarts.")))return;let o,a=!1;if(n?(n.common=n.common||{},n.native=n.native||{},JSON.stringify(n)!==JSON.stringify(this.state.presets[r])&&(o=JSON.parse(JSON.stringify(this.state.presets)),o[r]=n,a=!0)):this.state.presets[r]&&(o=JSON.parse(JSON.stringify(this.state.presets)),delete o[r],a=!0),a){const i=this.getEmptyFolders(),s={presets:o,changingPreset:"",presetFolders:oy.buildPresetTree(o,i)};setTimeout(()=>this.informAboutSubFolders(s.presetFolders),200),this.setState(s)}});X(this,"addPresetToFolderPrefix",async(r,n,o)=>{const a=r._id,i=r._id.split(".").pop();r._id=`${this.props.adapterName}.0.${n}${n?".":""}${i}`;try{if(await this.props.socket.setObject(r._id,r),console.log(`Deleted ${a}`),await this.props.socket.delObject(a),console.log(`Set new ID: ${r._id}`),!o){const s=await this.getAllPresets();this.setState(s)}}catch(s){this.onError(s,`Cannot delete object ${a}`)}});let n;try{n=JSON.parse(window.localStorage.getItem("App.echarts.presets.opened"))||[]}catch{n=[]}this.state={presetsOpened:n,presets:{},presetFolders:null,changingPreset:"",deletePresetDialog:"",movePresetDialog:"",newPresetFolder:"",addPresetFolderName:"",editPresetFolderDialog:null,editFolderDialogTitleOrigin:"",editPresetFolderName:"",renameDialog:"",renamePresetDialogTitle:""},this.refSelected=m.createRef(),this.getAllPresets().then(o=>this.setState(o))}async componentDidMount(){await this.props.socket.subscribeObject(`${this.props.adapterName}.0.*`,this.onPresetChange)}async componentWillUnmount(){this.scrollTimeout&&(clearTimeout(this.scrollTimeout),this.scrollTimeout=null),await this.props.socket.unsubscribeObject(`${this.props.adapterName}.0.*`,this.onPresetChange)}informAboutSubFolders(r){r=r||this.state.presetFolders||{},this.props.onShowReorder(!!Object.keys(r.subFolders||{}).length)}getEmptyFolders(r,n,o){if(o=o||[],n=n||[],r=r||this.state.presetFolders||{},r.id){const a=[...n];a.push(r.id),o.push(a.join("."))}return r.subFolders&&Object.keys(r.subFolders).forEach(a=>this.getEmptyFolders(r.subFolders[a],n,o)),o}async getAllPresets(r,n){r=r||{};const o={},a=await this.props.socket.getObjectViewSystem("chart",`${this.props.adapterName}.`,`${this.props.adapterName}.香`);return a&&Object.values(a).forEach(i=>i._id&&!i._id.toString().endsWith(".")&&(o[i._id]=i)),r.presets=o,r.changingPreset="",Object.keys(r.presets).forEach(i=>{const s=r.presets[i];s.common=s.common||{},s.native=s.native||{}}),n=n||this.getEmptyFolders(),r.presetFolders=oy.buildPresetTree(o,n),setTimeout(()=>this.informAboutSubFolders(r.presetFolders),200),r}renderPreset(r,n){var d,h;const o=this.state.presets[r._id],a=typeof r.common.name=="object"?r.common.name[P.getLanguage()]||r.common.name.en:r.common.name;if(!o||this.props.search&&!a.includes(this.props.search))return null;n=n||0;const i=(this.props.reorder?n:n-1)*w9;let s=null;((d=r.native.data.l||r.native.data.lines)==null?void 0:d.length)>1&&(s=w.jsx(Re,{sx:Tt.itemIconNumber,children:(h=r.native.data.l||r.native.data.lines)==null?void 0:h.length}));const l=w.jsxs(Ev,{sx:{"&.MuiListItemButton-gutters":ue.getStyle(this.props.theme,Tt.noGutters,this.props.selectedId===r._id&&this.props.selectedPresetChanged&&Tt.changed),"&.Mui-selected":Tt.selected,height:48},selected:this.props.selectedId===r._id,style:{paddingLeft:i},className:this.props.reorder?"item-reorder":"",ref:this.props.selectedId===r._id?this.refSelected:null,onClick:()=>this.props.onSelectedChanged(o._id),children:[w.jsxs(ba,{sx:ue.getStyle(this.props.theme,Tt.itemIconRoot,Tt.itemIconPreset),children:[w.jsx(JKt,{style:Tt.itemIcon}),s]}),w.jsx(_o,{sx:{"& .MuiListItemText-primary":Tt.listItemTitle,"& .MuiListItemText-secondary":Tt.listItemSubTitle},primary:w.jsx("div",{style:Tt.listItemTitleDiv,children:ue.getObjectNameFromObj(o,null,{language:P.getLanguage()})}),secondary:ue.getObjectNameFromObj(o,null,{language:P.getLanguage()},!0)}),this.state.changingPreset===o._id?w.jsx(pO,{size:24}):this.props.reorder?null:w.jsxs(w.Fragment,{children:[this.props.selectedId!==o._id||!this.props.selectedPresetChanged?w.jsx(Ie,{size:"small","aria-label":"Rename",title:P.t("Rename"),sx:Tt.textColor,onClick:u=>{u.stopPropagation(),this.setState({renameDialog:o._id,renamePresetDialogTitle:a})},children:w.jsx(JR,{})}):null,w.jsx(Ie,{size:"small","aria-label":"Copy",title:P.t("Copy"),sx:Tt.textColor,onClick:()=>this.props.onCopyPreset(o._id),children:w.jsx(Di,{style:Tt.iconCopy})}),w.jsx(Ie,{size:"small",sx:Tt.textColor,"aria-label":"Delete",title:P.t("Delete"),onClick:()=>this.setState({deletePresetDialog:o._id}),children:w.jsx(yu,{})})]})]},r._id);return this.props.reorder?w.jsx(tnr,{name:r._id,draggableId:r._id,children:l},`draggable_${r._id}`):l}renderFolder(r,n){const o=[];n=n||0;const a=this.props.reorder||(this.state.presetsOpened&&r?this.state.presetsOpened.includes(r.prefix):!1),i=(this.props.reorder?n:n-1)*w9,s=[];if(r&&(a||!r.id)){const l=Object.values(r.presets||{}),d=Object.values(r.subFolders||{});d.sort((h,u)=>h.id>u.id?1:h.id!(Qrr&&h.id===ad)).forEach(h=>s.push(this.renderFolder(h,n+1))),l.length||d.length?l.sort((h,u)=>h._id>u._id?1:h._ids.push(this.renderPreset(h,n+1))):n===0&&s.push(w.jsx(of,{sx:{"&.MuiListItem-gutters":Tt.noGutters},children:w.jsx(_o,{style:Tt.folderItem,children:P.t("No presets created yet")})},"no presets"))}if(r&&(r.id||this.props.reorder)){const l=w.jsxs(of,{sx:{"&.MuiListItem-gutters":Tt.noGutters},className:this.props.reorder?"folder-reorder":"",style:{...Tt.width100,...Tt.folderItem,paddingLeft:i,height:48},secondaryAction:w.jsxs(w.Fragment,{children:[!this.props.reorder&&r&&r.id&&a?w.jsx(Ie,{size:"small",sx:Tt.textColor,onClick:()=>this.props.onCreatePreset(r.id),title:P.t("Create new preset"),children:w.jsx(Il,{})}):null,this.props.reorder?null:w.jsx(Ie,{size:"small",sx:Tt.textColor,onClick:()=>this.setState({editPresetFolderDialog:r,editPresetFolderName:r.id,editFolderDialogTitleOrigin:r.id}),title:P.t("Edit folder name"),children:w.jsx(JR,{})}),this.props.reorder?null:w.jsx(Ie,{size:"small",onClick:()=>this.togglePresetsFolder(r),sx:Tt.textColor,title:a?P.t("Collapse"):P.t("Expand"),children:w.jsx(sf,{style:{transform:a?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease-in-out"}})})]}),children:[w.jsx(ba,{sx:ue.getStyle(this.props.theme,Tt.itemIconRoot,Tt.folderIconPreset),onClick:()=>this.togglePresetsFolder(r),children:a?w.jsx(vf,{style:{...Tt.itemIcon,...Tt.itemIconFolder}}):w.jsx(yf,{style:{...Tt.itemIcon,...Tt.itemIconFolder}})}),w.jsx(_o,{children:r.id||P.t("Root")})]},r.prefix);this.props.reorder?o.push(w.jsx(enr,{droppableId:"tree",name:r.prefix,onDrop:d=>this.onDragFinish(d,`echarts.0${r.prefix?".":""}${r.prefix}`),children:l},`droppable_${r.prefix}`)):o.push(l)}return s.forEach(l=>o.push(l)),o}async renamePresetFolder(r,n){this.setState({changingPreset:r.id});let o;const a=this.state.presetsOpened.indexOf(r.prefix);if(a!==-1){const u=[...this.state.presetsOpened];u.splice(a,1),u.push(n),u.sort(),this.setState({presetsOpened:u})}const i=r.prefix.split(".");i[i.length-1]=n;const s=i.join(".");Object.keys(r.presets).find(u=>u===this.props.selectedId)&&(o=`${this.props.adapterName}.0.${s}.${this.props.selectedId.split(".").pop()}`);const l=Object.keys(r.presets);for(let u=0;u0;u--)d[u]===d[u-1]&&d.splice(u,1)}setTimeout(async()=>{const u=await this.getAllPresets(null,d);this.setState(u,()=>this.props.onSelectedChanged(o))},100)}isNameUnique(r,n){const o=r.split(".").length;return n===ad?!1:!Object.keys(this.state.presets).find(a=>o===a.split(".").length&&this.state.presets[a].common.name===n)}static buildPresetTree(r,n){const o=Object.values(r),a={subFolders:{},presets:{},id:"",prefix:""};return o.forEach(i=>{const s=i._id,l=s.split(".");l.shift(),l.shift();let d=a,h="";for(let u=0;u{const s=i.split(".");let l=a,d="";for(let h=0;h{this.setState({presetFolders:o,presetsOpened:i},()=>s())})}togglePresetsFolder(r){const n=[...this.state.presetsOpened],o=n.indexOf(r.prefix);if(o===-1)n.push(r.prefix);else if(n.splice(o,1),Object.keys(r.presets).includes(this.props.selectedId)){this.props.onSelectedChanged(null,a=>{a!==!1&&(window.localStorage.setItem("App.echarts.presets.opened",JSON.stringify(n)),this.setState({presetsOpened:n}))});return}window.localStorage.setItem("App.echarts.presets.opened",JSON.stringify(n)),this.setState({presetsOpened:n})}renderAddFolderDialog(){return this.props.addPresetFolderDialog?w.jsxs(or,{maxWidth:"md",fullWidth:!0,open:!0,onClose:()=>this.props.onClosePresetFolderDialog(),children:[w.jsx(_r,{children:P.t("Create folder")}),w.jsx(Wr,{style:Tt.p,children:w.jsx(Ht,{variant:"standard",fullWidth:!0,autoFocus:!0,label:P.t("Title"),value:this.state.addPresetFolderName,onChange:r=>this.setState({addPresetFolderName:r.target.value.replace(nE,"_").trim()}),onKeyUp:r=>{this.state.addPresetFolderName&&r.key==="Enter"&&this.state.addPresetFolderName!==ad&&(r.preventDefault(),r.stopPropagation(),this.addFolder(null,this.state.addPresetFolderName).then(()=>this.props.onClosePresetFolderDialog(()=>this.informAboutSubFolders())))}})}),w.jsxs(pr,{style:{...Tt.alignRight,...Tt.buttonsContainer},children:[w.jsx(tt,{variant:"contained",disabled:!this.state.addPresetFolderName||!!Object.keys(this.state.presetFolders&&this.state.presetFolders.subFolders||{}).find(r=>r===this.state.addPresetFolderName)||this.state.addPresetFolderName===ad,onClick:()=>this.addFolder(null,this.state.addPresetFolderName).then(()=>this.props.onClosePresetFolderDialog(()=>this.informAboutSubFolders())),color:"primary",autoFocus:!0,startIcon:w.jsx(sh,{}),children:P.t("Create")}),w.jsx(tt,{color:"grey",variant:"contained",onClick:()=>this.props.onClosePresetFolderDialog(),startIcon:w.jsx(wo,{}),children:P.t("Cancel")})]})]}):null}renderRenameFolderDialog(){if(!this.state.editPresetFolderDialog)return null;const r=!Object.keys(this.state.presetFolders&&this.state.presetFolders.subFolders||{}).find(n=>n===this.state.editPresetFolderName);return w.jsxs(or,{maxWidth:"md",fullWidth:!0,open:!!this.state.editPresetFolderDialog,onClose:()=>this.setState({editPresetFolderDialog:null}),children:[w.jsx(_r,{children:P.t("Edit folder")}),w.jsx(Wr,{children:w.jsx(Ht,{variant:"standard",fullWidth:!0,autoFocus:!0,label:P.t("Title"),value:this.state.editPresetFolderName,onKeyUp:n=>{this.state.editPresetFolderName&&n.key==="Enter"&&this.state.editPresetFolderName!==ad&&this.state.editFolderDialogTitleOrigin!==this.state.editPresetFolderName&&r&&(n.preventDefault(),n.stopPropagation(),this.renamePresetFolder(this.state.editPresetFolderDialog,this.state.editPresetFolderName).then(()=>this.setState({editPresetFolderDialog:null})))},onChange:n=>this.setState({editPresetFolderName:n.target.value.replace(nE,"_").trim()})})}),w.jsxs(pr,{style:{...Tt.alignRight,...Tt.buttonsContainer},children:[w.jsx(tt,{variant:"contained",disabled:!this.state.editPresetFolderName||this.state.editFolderDialogTitleOrigin===this.state.editPresetFolderName||!r||this.state.editPresetFolderName===ad,onClick:()=>{this.renamePresetFolder(this.state.editPresetFolderDialog,this.state.editPresetFolderName).then(()=>this.setState({editPresetFolderDialog:null}))},color:"primary",startIcon:w.jsx(sh,{}),children:P.t("Rename")}),w.jsx(tt,{color:"grey",variant:"contained",onClick:()=>this.setState({editPresetFolderDialog:null}),startIcon:w.jsx(wo,{}),children:P.t("Cancel")})]})]})}renderMoveDialog(){if(!this.state.movePresetDialog)return null;const r=this.state.newPresetFolder==="__root__"?"":this.state.newPresetFolder,n=this.state.movePresetDialog,o=`preset.0.${r}${r?".":""}${n}`,a=!Object.keys(this.state.presets).find(i=>i===o);return w.jsxs(or,{maxWidth:"md",fullWidth:!0,open:!0,onClose:()=>this.setState({movePresetDialog:null}),children:[w.jsx(_r,{children:P.t("Move to folder")}),w.jsx(Wr,{children:w.jsxs(_a,{style:Tt.width100,variant:"standard",children:[w.jsx($l,{shrink:!0,children:P.t("Folder")}),w.jsx(Bn,{variant:"standard",autoFocus:!0,fullWidth:!0,style:Tt.width100,value:this.state.newPresetFolder||"__root__",onChange:i=>this.setState({newPresetFolder:i.target.value}),onKeyUp:i=>{a&&i.which===13&&(i.preventDefault(),i.stopPropagation(),this.setState({movePresetDialog:null},()=>this.addPresetToFolderPrefix(this.state.presets[n],this.state.newPresetFolder==="__root__"?"":this.state.newPresetFolder)))},children:DG(this.state.presetFolders||{}).map(i=>w.jsx(Xt,{value:i.prefix||"__root__",children:i.prefix?i.prefix.replace("."," > "):P.t("Root")},i.prefix))})]})}),w.jsxs(pr,{style:{...Tt.alignRight,...Tt.buttonsContainer},children:[w.jsx(tt,{variant:"contained",disabled:!a,color:"primary",onClick:()=>this.setState({movePresetDialog:null},()=>this.addPresetToFolderPrefix(this.state.presets[n],this.state.newPresetFolder==="__root__"?"":this.state.newPresetFolder)),startIcon:w.jsx(sh,{}),children:P.t("Move to folder")}),w.jsxs(tt,{color:"grey",variant:"contained",onClick:()=>this.setState({movePresetDialog:null}),startIcon:w.jsx(wo,{}),children:[w.jsx(wo,{style:Tt.buttonIcon}),P.t("Cancel")]})]})]},"movePresetDialog")}onError(r,n){n&&console.error(n),this.props.onShowError(r.toString())}async onDragFinish(r,n){let o=`${n}.${r.split(".").pop()}`;if(o!==r){this.state.presets[o]&&(o+=`_${P.t("copy")}`);try{const a=await this.props.socket.getObject(r);if(a)try{await this.props.socket.setObject(o,a),await this.props.socket.delObject(r);const i=await this.getAllPresets();this.setState(i)}catch(i){this.onError(i,`Cannot delete object ${o}`)}}catch(a){this.onError(a,`Cannot read object ${r}`)}}}renderRenameDialog(){if(!this.state.renameDialog)return null;const r=this.state.renameDialog;return w.jsxs(or,{maxWidth:"md",fullWidth:!0,open:!0,onClose:()=>this.setState({renameDialog:null}),children:[w.jsx(_r,{children:P.t("Rename preset")}),w.jsx(Wr,{children:w.jsx(_a,{style:Tt.width100,variant:"standard",children:w.jsx(Ht,{variant:"standard",fullWidth:!0,autoFocus:!0,label:P.t("Name"),value:this.state.renamePresetDialogTitle,onKeyUp:n=>{n.keyCode===13&&this.state.renamePresetDialogTitle&&this.isNameUnique(r,this.state.renamePresetDialogTitle)&&(n.stopPropagation(),n.preventDefault(),this.setState({renameDialog:null},()=>this.renamePreset(r,this.state.renamePresetDialogTitle)))},onChange:n=>this.setState({renamePresetDialogTitle:n.target.value})})})}),w.jsxs(pr,{style:{...Tt.alignRight,...Tt.buttonsContainer},children:[w.jsx(tt,{variant:"contained",disabled:!this.state.renamePresetDialogTitle||!this.isNameUnique(r,this.state.renamePresetDialogTitle),color:"primary",onClick:()=>this.setState({renameDialog:null},()=>this.renamePreset(r,this.state.renamePresetDialogTitle)),startIcon:w.jsx(sh,{}),children:P.t("Rename")}),w.jsx(tt,{color:"grey",variant:"contained",onClick:()=>this.setState({renameDialog:null}),startIcon:w.jsx(wo,{}),children:P.t("Cancel")})]})]},"renameDialog")}renderDeleteDialog(){return this.state.deletePresetDialog?w.jsx(PO,{title:P.t("Please confirm"),text:P.t("Are you sure for delete this preset?"),ok:P.t("Delete"),cancel:P.t("Cancel"),suppressQuestionMinutes:3,dialogName:"echarts.deletePresetDialog",onClose:r=>{r?this.deletePreset(this.state.deletePresetDialog,()=>this.setState({deletePresetDialog:""})):this.setState({deletePresetDialog:""})}},"deletePresetDialog"):null}async deletePreset(r,n){try{await this.props.socket.delObject(r);const o=await this.getAllPresets();this.setState(o,()=>{if(r===this.props.selectedId){const a=Object.keys(this.state.presets);this.props.onSelectedChanged(a[0]||null)}})}catch(o){this.onError(o,`Cannot delete object ${r}`)}n()}async renamePreset(r,n){try{const o=await this.props.socket.getObject(r);o.common.name=n;const a=r.split(".");a.splice(-1,1),a.push(n.replace(nE,"_").trim()),o._id=a.join("."),await this.props.socket.setObject(o._id,o),await this.props.socket.delObject(r);const i=await this.getAllPresets();r===this.props.selectedId?this.setState(i,()=>this.props.onSelectedChanged(o._id)):this.setState(i)}catch(o){this.onError(o,`Cannot get object ${r}`)}}render(){return this.scrollToSelect!==this.props.scrollToSelect&&(this.scrollToSelect=this.props.scrollToSelect,this.scrollToSelect&&!this.scrollTimeout&&(this.scrollTimeout=setTimeout(()=>{var r;this.scrollTimeout=null,(r=this.refSelected.current)==null||r.scrollIntoView({behavior:"auto",block:"center",inline:"center"})},100))),w.jsxs(w.Fragment,{children:[w.jsx(arr,{backend:Zrr,children:w.jsx(vu,{sx:{...Tt.scroll,...Tt.mainList},children:this.renderFolder(this.state.presetFolders)})}),this.renderAddFolderDialog(),this.renderRenameFolderDialog(),this.renderDeleteDialog(),this.renderMoveDialog(),this.renderRenameDialog()]})}}const rnr=qs()(oy);function nnr(t){return Pr({tag:"svg",attr:{viewBox:"0 0 1024 1024"},child:[{tag:"path",attr:{d:"M888 792H200V168c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v688c0 4.4 3.6 8 8 8h752c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm-616-64h536c4.4 0 8-3.6 8-8V284c0-7.2-8.7-10.7-13.7-5.7L592 488.6l-125.4-124a8.03 8.03 0 0 0-11.3 0l-189 189.6a7.87 7.87 0 0 0-2.3 5.6V720c0 4.4 3.6 8 8 8z"},child:[]}]})(t)}const x9=34,id=20,S9=30,Zp=15;class AG extends A.Component{render(){const e=w.jsxs("div",{style:{width:this.props.size==="small"?S9:x9,height:id,display:"flex",alignItems:"center",cursor:"pointer",position:"relative",opacity:this.props.disabled?.7:1},onClick:r=>{this.props.disabled||(r.stopPropagation(),r.preventDefault(),this.props.onChange(!this.props.checked))},children:[w.jsx("div",{style:{borderRadius:15,width:"100%",height:(this.props.size==="small"?Zp:id)*.7,opacity:.6,backgroundColor:this.props.checked?this.props.theme.palette.primary.main:this.props.theme.palette.text.disabled}}),w.jsx("div",{style:{position:"absolute",top:this.props.size==="small"?(id-Zp)/2:0,left:this.props.checked?this.props.size==="small"?S9-Zp:x9-id:0,transition:"left 0.2s",borderRadius:50,width:this.props.size==="small"?Zp:id,height:this.props.size==="small"?Zp:id,backgroundColor:this.props.checked?this.props.theme.palette.primary.main:"#EEE",boxShadow:"rgba(0, 0, 0, 0.2) 0px 2px 1px -1px, rgba(0, 0, 0, 0.14) 0px 1px 1px 0px, rgba(0, 0, 0, 0.12) 0px 1px 3px 0px"}})]});return this.props.labelOn||this.props.labelOff?w.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[this.props.labelOff,e,this.props.labelOn]}):e}}function C9(t,e){const r=typeof t=="object"?t._id.replace("system.adapter.",""):t.replace("system.adapter.",""),n=typeof e=="object"?e._id.replace("system.adapter.",""):e.replace("system.adapter.","");return r>n?1:r{t[n].common.members.includes(e)&&!r.includes(n)&&r.push(n)}),r}const $9=16,Vt={noGutters:{paddingTop:0,paddingBottom:0,paddingLeft:0,width:"100%"},itemIconFolder:{cursor:"pointer",marginLeft:8},width100:{width:"100%"},itemIcon:{width:32,height:32,marginRight:4},itemIconRoot:{minWidth:24},itemNameDiv:{marginTop:5},itemName:{verticalAlign:"top",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",width:"calc(100% - 26px)",display:"inline-block"},itemName0:{},itemName1:{fontSize:14,opacity:.6},itemName2:{fontSize:12,opacity:.6},itemName3:{fontSize:10,opacity:.6},itemName4:{fontSize:8,opacity:.6},itemName5:{fontSize:6,opacity:.6},groupName:{verticalAlign:"top",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",width:"calc(100% - 66px)",display:"inline-block"},itemSecondaryName:{overflow:"hidden",textOverflow:"ellipsis",width:"100%",fontSize:"smaller",opacity:.6,fontStyle:"italic",whiteSpace:"nowrap",display:"inline-block"},listItemSubTitle:{fontSize:"smaller",opacity:.6,fontStyle:"italic"},adapterIcon:{width:20,height:20,borderRadius:2,marginRight:4},mainList:{width:"100%"},listItemSecondaryAction:{marginRight:4},folderItem:t=>({backgroundColor:t.palette.secondary.main,pl:"8px"})};class anr extends A.Component{constructor(r){super(r);X(this,"refSelected");X(this,"scrollToSelect",!1);X(this,"adapterPromises",{});X(this,"toggleChartFolder",r=>{const n=JSON.parse(JSON.stringify(this.state.chartsOpened));n[r]=!n[r],window.localStorage.setItem("App.echarts.opened",JSON.stringify(n));const o={chartsOpened:n};if(!n[r]){const a=r.split("///")[0];this.props.selectedId&&typeof this.props.selectedId=="object"&&this.props.selectedId.instance}this.setState(o,()=>this.props.onSelectedChanged(null))});let n;try{n=JSON.parse(window.localStorage.getItem("App.echarts.opened"))||{}}catch{n={}}this.state={instances:[],chartsOpened:n,enums:null,showAddStateDialog:""},this.refSelected=m.createRef(),this.getAllEnums().then(o=>this.getAllCharts(o)).then(o=>this.setState(o,()=>this.props.selectedId&&this.props.onSelectedChanged(this.props.selectedId)))}UNSAFE_componentWillReceiveProps(r){r.scrollToSelect!==this.scrollToSelect&&(this.scrollToSelect=r.scrollToSelect,this.scrollToSelect&&setTimeout(()=>{var n;(n=this.refSelected.current)==null||n.scrollIntoView({behavior:"auto",block:"center",inline:"center"})},100))}async getAllEnums(r){r=r||{};try{const n=await this.props.socket.getEnums();return r.enums={},Object.keys(n).forEach(o=>{var a,i,s;(o.startsWith("enum.functions.")||o.startsWith("enum.rooms."))&&((s=(i=(a=n[o])==null?void 0:a.common)==null?void 0:i.members)!=null&&s.length)&&(r.enums[o]={_id:o,common:{members:[...n[o].common.members],name:ue.getObjectNameFromObj(n[o],null,{language:P.getLanguage()})},type:"enum",native:{}})}),r}catch(n){return this.onError(n,"Cannot read enums"),{}}}async getAdapterIcon(r){var a;const n=r.split(".");if(n.length<2||n[0]==="0_userdata")return null;let o;n[0]==="system"?(n.splice(4),o=n.join(".")):(n.splice(2),o=`system.adapter.${n.join(".")}`),this.adapterPromises[o]instanceof Promise||(this.adapterPromises[o]=this.props.socket.getObject(o));try{const i=await this.adapterPromises[o];if((a=i==null?void 0:i.common)!=null&&a.icon)return ue.getObjectIcon(i)}catch(i){this.onError(i,`Cannot read object ${o}`)}return null}onError(r,n){n&&console.error(n),this.props.onShowError(r.toString())}async getChartIconAndName(r,n){let o;const a=[];if(!n)return null;const i=P.getLanguage(),s=n._id;n.common&&(n.common.icon&&(o=ue.getObjectIcon(n)),a.push(ue.getObjectNameFromObj(n,null,{language:i})));const l=ue.getParentId(n._id);if((l==null?void 0:l.split(".").length)>2)try{const d=await this.props.socket.getObject(l);if(d&&(d.type==="channel"||d.type==="device")&&d.common){!o&&d.common.icon&&(o=ue.getObjectIcon(d)),a.push(ue.getObjectNameFromObj(d,null,{language:i}));const h=ue.getParentId(l);if((h==null?void 0:h.split(".").length)>2){const u=await this.props.socket.getObject(h);if(u&&(u.type==="channel"||u.type==="device")&&u.common){!o&&u.common.icon&&(o=ue.getObjectIcon(u)),a.push(ue.getObjectNameFromObj(u,null,{language:i}));const f=ue.getParentId(h);if((f==null?void 0:f.split(".").length)>2){const g=await this.props.socket.getObject(f);g&&(g.type==="channel"||g.type==="device")&&g.common&&(!o&&g.common.icon&&(o=ue.getObjectIcon(g)),a.push(ue.getObjectNameFromObj(g,null,{language:i})))}}}}}catch(d){console.error(`Cannot read object: ${d}`)}return o=o||await this.getAdapterIcon(s),{groupId:r,id:s,img:o,name:a.filter(d=>d)}}async getAllCharts(r){r=r||{};const n=this.props.instances.map(u=>u._id.substring(15)),o=await this.props.socket.getObjectViewSystem("custom-full","",""),a={};r.enums=r.enums||this.state.enums;const i=[];Object.values(o).forEach(u=>{const f=n.find(g=>Object.keys(u.common.custom).includes(g));if(f){const g=this.props.instances.find(y=>y._id.endsWith(f));a[f]=a[f]||{_id:`system.adapter.${f}`,enabledDP:{},names:{},statesEnums:{},icon:g.common.icon,name:g.common.name||"",types:{},icons:{}},a[f].enabledDP[u._id]=u,a[f].names[u._id]=ue.getObjectNameFromObj(u,null,{language:P.getLanguage()}),a[f].types[u._id]=u.common.type==="boolean"?"boolean":"number",a[f].statesEnums[u._id]=onr(r.enums,u._id),i.push(this.getChartIconAndName(f,u))}});const s=JSON.parse(JSON.stringify(this.state.chartsOpened)),l=Object.keys(r.enums).filter(u=>u.startsWith("enum.functions.")),d=Object.keys(r.enums).filter(u=>u.startsWith("enum.rooms.")),h=Object.values(a).map(u=>{var b;const f={};Object.keys(u.enabledDP).forEach(x=>{f[x]=u.enabledDP[x],f[x].group=u._id}),u.enabledDP=f,s[u._id]=s[u._id]!==void 0?this.state.chartsOpened[u._id]||!1:!0,Object.keys(r.enums).forEach(x=>{Object.keys(f).find(S=>r.enums[x].common.members.includes(S))&&(u.enums=u.enums||[],u.enums.includes(x)||u.enums.push(x))});const g={_id:`enum.functions.${u._id}`,type:"enum",common:{members:[],name:P.t("Others")},native:{}},y={_id:`enum.rooms.${u._id}`,type:"enum",common:{members:[],name:P.t("Others")},native:{}};return Object.keys(f).forEach(x=>{l.find(S=>r.enums[S].common.members.includes(x))||g.common.members.push(x),d.find(S=>r.enums[S].common.members.includes(x))||y.common.members.push(x)}),g.common.members.length&&(u.enums=u.enums||[],u.enums.push(`enum.functions.${u._id}`),r.enums[`enum.functions.${u._id}`]=g),y.common.members.length&&(u.enums=u.enums||[],u.enums.push(`enum.rooms.${u._id}`),r.enums[`enum.rooms.${u._id}`]=y),(b=u.enums)==null||b.sort((x,S)=>r.enums[x].common.name>r.enums[S].common.name?1:r.enums[x].common.namethis.props.onSelectedChanged({id:u,instance:h[0]._id}),500)}return r.instances=h,r.chartsOpened=s,setTimeout(()=>{Promise.all(i).then(u=>{const f=JSON.parse(JSON.stringify(this.state.instances));let g=!1;u.forEach(y=>{if(y!=null&&y.groupId){const b=f.find(x=>x._id===`system.adapter.${y.groupId}`);b&&(y.img&&(b.icons[y.id]=y.img),y.name&&(b.names[y.id]=y.name),g=!0)}}),g&&this.setState({instances:f})})},100),r}renderSelectIdDialog(){return this.state.showAddStateDialog?w.jsx(OV,{theme:this.props.theme,imagePrefix:"../..",socket:this.props.socket,dialogName:"Add",title:P.t("Enable logging for state"),onOk:r=>{const n=Array.isArray(r)?r[0]:r;console.log(`Selected ${JSON.stringify(n)}`);const o=this.state.showAddStateDialog.replace("system.adapter.","");n&&this.props.socket.getObject(n).then(a=>{var i;if(!(a!=null&&a.common)){this.props.onShowError(P.t("Invalid object"));return}if((i=a.common.custom)!=null&&i[o]){this.props.onShowToast(P.t("Already enabled"));return}a.common.custom=a.common.custom||{},a.common.custom[o]={enabled:!0},this.props.socket.setObject(n,a).then(()=>{const s=JSON.parse(JSON.stringify(this.state.instances)),l=s.find(d=>d._id===`system.adapter.${o}`);l.enabledDP=l.enabledDP||{},l.enabledDP[a._id]=a,this.setState({instances:s},()=>this.getAllCharts())}).catch(s=>this.onError(s,`Cannot read object ${n}`))}).catch(a=>this.onError(a,`Cannot read object ${n}`)),this.setState({showAddStateDialog:""})},onClose:()=>this.setState({showAddStateDialog:""})},"selectDialog_add"):null}renderListItem(r,n,o,a){a=a||0;const i=r._id,s=this.props.selectedId&&typeof this.props.selectedId=="object"&&this.props.selectedId.id===n&&this.props.selectedId.instance===i;let l;if(typeof r.names[n]=="object"){const d=[...r.names[n]];l=w.jsx("span",{style:Vt.itemName,title:d.join(" / "),children:d.map((h,u)=>w.jsx("span",{style:Vt[`itemName${u}`],children:(u?" / ":"")+h},u))})}else{const d=(r.names[n]||"").toString();l=w.jsx("span",{style:Vt.itemName,title:d,children:d})}return w.jsxs(Ev,{ref:s?this.refSelected:null,sx:{"&.MuiListItemButton-gutters":Vt.noGutters},style:{paddingLeft:$9*a,height:48,position:"relative"},selected:s,onClick:o?void 0:()=>this.props.onSelectedChanged({id:n,instance:i}),children:[w.jsx(ba,{style:Vt.itemIconRoot,children:r.types[n]==="boolean"?w.jsx(YKt,{style:Vt.itemIcon}):w.jsx(nnr,{style:Vt.itemIcon})}),w.jsxs("div",{style:{flexGrow:1,overflow:"hidden"},children:[w.jsxs("div",{style:Vt.itemNameDiv,children:[ue.getIcon({icon:r.icons[n],prefix:"../../"},{width:20,height:20,borderRadius:2,marginRight:4}),l]}),w.jsx("div",{style:Vt.itemSecondaryName,title:n,children:n.replace("system.adapter.","")})]}),!o&&this.props.multiple&&this.props.chartsList?w.jsxs("div",{style:Vt.listItemSecondaryAction,children:[w.jsx(AG,{size:"small",theme:this.props.theme,onChange:d=>{const h=JSON.parse(JSON.stringify(this.props.chartsList)),u=h.find(f=>f.id===n&&f.instance===i);d&&!u?(h.push({id:n,instance:i}),h.sort((f,g)=>f.instance>g.instance?1:f.instanceg.id?1:f.idthis.props.onChangeList(h)):this.props.onChangeList(h)):!d&&u&&(h.splice(h.indexOf(u),1),this.props.onChangeList(h))},checked:!!this.props.chartsList.find(d=>d.id===n&&d.instance===i)})," "]}):null]},`${i}_${n}`)}renderListItems(r,n,o,a){if(a.gIndex=a.gIndex||0,!(n!=null&&n.length))return null;const i=r._id,s=1;if(!o)return n.map(f=>w.jsx(EE,{isDragDisabled:!this.props.selectedId||typeof this.props.selectedId=="object",draggableId:`${i}***${f}`,index:a.gIndex++,children:(g,y)=>w.jsxs(w.Fragment,{children:[w.jsx("div",{ref:g.innerRef,...g.draggableProps,...g.dragHandleProps,style:g.draggableProps.style,className:"drag-items",children:this.renderListItem(r,f,!1,s)},`${i}_${f}_item`),y.isDragging?w.jsx("div",{className:"react-beautiful-dnd-copy",children:this.renderListItem(r,f,!0)},`${i}_${f}_dnd`):null]})},`${i}_${f}`));const l=`${i}///${o}`,d=this.state.chartsOpened[l];d&&(n=n.filter(f=>this.state.enums[o].common.members.includes(f)));const h=this.state.enums[o].common.name,u=typeof h=="object"?h[P.getLanguage()]||h.en:h;return[w.jsxs(of,{style:{...Vt.width100,paddingLeft:$9*s,height:48},sx:ue.getStyle(this.props.theme,Vt.folderItem,{"&.MuiListItem-gutters":Vt.noGutters}),secondaryAction:w.jsx(Ie,{size:"small",onClick:()=>this.toggleChartFolder(l),title:d?P.t("Collapse"):P.t("Expand"),children:w.jsx(sf,{style:{transform:d?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease-in-out"}})}),children:[w.jsx(ba,{style:Vt.itemIconRoot,onClick:()=>this.toggleChartFolder(l),children:d?w.jsx(vf,{style:{...Vt.itemIcon,...Vt.itemIconFolder}}):w.jsx(yf,{style:{...Vt.itemIcon,...Vt.itemIconFolder}})}),w.jsx(_o,{primary:u})]},l),d?w.jsx(vu,{children:n.map(f=>w.jsx(EE,{isDragDisabled:!this.props.selectedId||typeof this.props.selectedId=="object",draggableId:`${i}***${f}`,index:a.gIndex++,children:(g,y)=>w.jsxs(w.Fragment,{children:[w.jsx("div",{ref:g.innerRef,...g.draggableProps,...g.dragHandleProps,style:g.draggableProps.style,className:"drag-items",children:this.renderListItem(r,f,!1,2)},`${i}_${f}_item`),y.isDragging?w.jsx("div",{className:"react-beautiful-dnd-copy",children:this.renderListItem(r,f,!0)},`${i}_${f}_dnd`):null]})},`${i}_${f}`))},`${l}_LIST`):null]}render(){const r={gIndex:0};return w.jsxs(w.Fragment,{children:[this.renderSelectIdDialog(),w.jsx(QT,{droppableId:"Lines",isDropDisabled:!0,children:n=>w.jsx("div",{ref:n.innerRef,children:w.jsx(vu,{style:{...Vt.scroll,...Vt.mainList},children:w.jsxs(w.Fragment,{children:[this.state.instances.map(o=>{const a=this.state.chartsOpened[o._id];let i=null;if(a){const s=Object.keys(o.enabledDP).filter(l=>!this.props.search||l.includes(this.props.search)||o.names[l].includes(this.props.search));this.props.groupBy?i=(o.enums||[]).filter(l=>l.startsWith(`enum.${this.props.groupBy}.`)).map(l=>this.renderListItems(o,s,l,r)):(s.sort(C9),i=this.renderListItems(o,s,null,r))}return[w.jsxs(of,{sx:ue.getStyle(this.props.theme,Vt.width100,Vt.folderItem,{height:48,color:this.props.theme.palette.mode==="dark"?void 0:"#FFF"},{"&.MuiListItem-gutters":Vt.noGutters}),secondaryAction:w.jsxs(w.Fragment,{children:[a?w.jsx(Ie,{size:"small",onClick:()=>this.setState({showAddStateDialog:o._id}),style:{color:this.props.theme.palette.mode==="dark"?void 0:"#FFF"},title:P.t("Enable logging for new state"),children:w.jsx(Il,{})}):null,w.jsx(Ie,{size:"small",onClick:()=>this.toggleChartFolder(o._id),title:a?P.t("Collapse"):P.t("Expand"),style:{color:this.props.theme.palette.mode==="dark"?void 0:"#FFF"},children:w.jsx(sf,{style:{transform:a?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease-in-out"}})})]}),children:[w.jsx(ba,{style:Vt.itemIconRoot,sx:{color:this.props.theme.palette.mode==="dark"?void 0:"#FFF"},onClick:()=>this.toggleChartFolder(o._id),children:a?w.jsx(vf,{style:{...Vt.itemIcon,...Vt.itemIconFolder}}):w.jsx(yf,{style:{...Vt.itemIcon,...Vt.itemIconFolder}})}),w.jsx(_o,{primary:w.jsxs("div",{style:Vt.itemNameDiv,children:[w.jsx("img",{style:Vt.adapterIcon,alt:"",src:`../../adapter/${o.name}/${o.icon}`}),w.jsx("div",{style:Vt.groupName,children:o._id.replace("system.adapter.","")})]})})]},o._id),i]}),n.placeholder]})},"chartList")},"chartListDiv")},"charts")]})}}const inr=qs()(anr),k9=48,Fo={mainListDiv:{width:"100%",height:"100%",overflow:"hidden"},mainToolbar:t=>({background:t.palette.primary.main}),secondaryColors:t=>({background:"#888",color:t.palette.mode==="dark"?"#000":"#FFF"}),smallMargin:{marginTop:"8px !important"},heightMinusTwoToolbars:{height:`calc(100% - ${k9*2}px)`,overflow:"auto"},heightMinusToolbar:{height:`calc(100% - ${k9}px)`,overflow:"auto"},textColor:t=>({color:t.palette.mode==="dark"?"#000 !important":"#FFF !important"})};class snr extends A.Component{constructor(r){super(r);X(this,"isIFrame");this.state={search:null,multiple:window.localStorage.getItem("App.echarts.multiple")==="true",showSearch:!1,groupBy:window.localStorage.getItem("App.echarts.groupBy")||"",addPresetFolderDialog:!1,reorder:!1,showReorder:!1};try{this.isIFrame=window.self!==window.top}catch{this.isIFrame=!0}if(this.state.multiple){const n=window.localStorage.getItem("App.echarts.chartList")||"[]";let o;try{o=JSON.parse(n)}catch{o=[]}setTimeout(()=>this.props.onChangeList(o),100)}}renderListToolbar(){return w.jsxs(af,{variant:"dense",sx:Fo.mainToolbar,children:[this.state.reorder?null:w.jsx(Ie,{onClick:()=>this.props.onCreatePreset(!1),title:P.t("Create new preset"),children:w.jsx(Il,{})}),this.state.reorder?null:w.jsx(Ie,{onClick:()=>this.setState({addPresetFolderDialog:!0}),title:P.t("Create new folder"),children:w.jsx(Fpe,{})}),this.state.reorder?null:w.jsx("span",{style:Fo.right,children:w.jsx(Ie,{onClick:()=>this.setState({showSearch:!this.state.showSearch,search:""}),children:w.jsx(Nve,{})})}),this.state.showSearch?w.jsx(Ht,{variant:"standard",value:this.state.search,style:Fo.textInput,onChange:r=>this.setState({search:r.target.value}),InputProps:{endAdornment:this.state.search?w.jsx(Ie,{onClick:()=>this.setState({search:""}),children:w.jsx(Ar,{})}):void 0}}):null,w.jsx("div",{style:{flexGrow:1}}),!this.state.showSearch&&this.state.showReorder||this.state.reorder?w.jsx(Ie,{title:P.t("Reorder presets in folders"),style:{color:this.state.reorder?"red":"inherit",float:"right"},onClick:r=>{r.stopPropagation(),this.setState({reorder:!this.state.reorder})},children:w.jsx(zpe,{})},"reorder"):null,!this.state.showSearch&&this.isIFrame?w.jsx(Ie,{onClick:()=>window.open(window.location.href,"own-echarts"),title:P.t("Open in own window"),children:w.jsx(hH,{})}):null]},"toolbar")}renderFooter(){return w.jsxs(af,{variant:"dense",sx:Fo.secondaryColors,style:{gap:8},children:[this.props.selectedPresetChanged?null:w.jsx(AG,{style:{width:58},checked:this.state.multiple,theme:this.props.theme,onChange:r=>{if(window.localStorage.setItem("App.echarts.multiple",r?"true":"false"),r){const n=this.props.selectedId;n&&typeof n=="object"?this.setState({multiple:!0},()=>this.props.onChangeList([JSON.parse(JSON.stringify(n))])):this.setState({multiple:!0},()=>this.props.onChangeList([]))}else this.setState({multiple:!1},()=>this.props.onChangeList(null))},labelOn:P.t("Multiple")}),w.jsxs(_a,{variant:"standard",style:{minWidth:100},sx:Fo.textColor,children:[w.jsx($l,{shrink:!0,sx:Fo.textColor,style:{whiteSpace:"nowrap",top:5},children:P.t("Group by")}),w.jsxs(Bn,{variant:"standard",label:P.t("Group by"),sx:Fo.textColor,onChange:r=>{window.localStorage.setItem("App.echarts.groupBy",r.target.value),this.setState({groupBy:r.target.value})},value:this.state.groupBy||"",style:Fo.smallMargin,displayEmpty:!0,children:[w.jsx(Xt,{value:"",children:P.t("None")}),w.jsx(Xt,{value:"rooms",children:P.t("Rooms")}),w.jsx(Xt,{value:"functions",children:P.t("Functions")})]})]}),w.jsx("div",{style:{flex:1}}),w.jsx(Ie,{size:"small",sx:Fo.textColor,title:P.t("Charts preview"),onClick:()=>{const r=window.location.pathname.split("/");r.pop(),r.push("preview/index.html"),window.location.href=`${window.location.protocol}//${window.location.host}${r.join("/")}`},children:w.jsx(Mve,{})})]},"toolbarBottom")}render(){return w.jsxs("div",{style:Fo.mainListDiv,children:[this.renderListToolbar(),w.jsxs("div",{style:this.state.reorder?Fo.heightMinusToolbar:Fo.heightMinusTwoToolbars,children:[w.jsx(rnr,{socket:this.props.socket,scrollToSelect:this.props.scrollToSelect,addPresetFolderDialog:this.state.addPresetFolderDialog,onClosePresetFolderDialog:r=>this.setState({addPresetFolderDialog:!1},r),onCreatePreset:(r,n)=>this.props.onCreatePreset(r,n),onCopyPreset:r=>this.props.onCopyPreset(r),adapterName:this.props.adapterName,selectedPresetChanged:this.props.selectedPresetChanged,onShowToast:r=>this.props.onShowToast(r),onShowError:r=>this.props.onShowToast(r),onShowReorder:r=>{r!==this.props.showReorder&&this.setState({showReorder:r})},theme:this.props.theme,search:this.state.search,reorder:this.state.reorder,selectedId:this.props.selectedId,systemConfig:this.props.systemConfig,onSelectedChanged:(r,n)=>this.props.onSelectedChanged(r,n)}),this.state.reorder?null:w.jsx(inr,{socket:this.props.socket,scrollToSelect:this.props.scrollToSelect,instances:this.props.instances,adapterName:this.props.adapterName,onShowToast:r=>this.props.onShowToast(r),onShowError:r=>this.props.onShowToast(r),search:this.state.search,multiple:this.state.multiple&&!this.props.selectedPresetChanged,theme:this.props.theme,groupBy:this.state.groupBy,selectedId:this.props.selectedId,onChangeList:r=>{window.localStorage.setItem("App.echarts.chartList",JSON.stringify(r)),this.props.onChangeList(r)},chartsList:this.props.chartsList,onSelectedChanged:(r,n)=>this.props.onSelectedChanged(r,n)})]}),this.state.reorder?null:this.renderFooter()]},"mainMenuDiv")}}const lnr=qs()(snr);function cnr(t,e){const r={};return t.replace(/\+/g," ").split("&").forEach(n=>{const o=n.split("=");let a=decodeURIComponent(o[0]),i,s=0,l=a.split("]["),d=l.length-1;if(/\[/.test(l[0])&&/]$/.test(l[d])?(l[d]=l[d].replace(/]$/,""),l=l.shift().split("[").concat(l),d=l.length-1):d=0,o.length===2)if(i=decodeURIComponent(o[1]),d){let h=r;for(;s<=d;s++)a=l[s]===""?h.length:l[s],h=h[a]=s{const a=$h(t,e,o);a&&a.then(()=>{})});if(!e||!e.length)return r(),null;const n=e.shift();return n?t.getObject(n._id).catch(()=>null).then(o=>{o?(console.log(`Object ${n._id} already exists and will not be converted`),setTimeout(()=>$h(t,e,r),50)):t.setObject(n._id,n).then(()=>setTimeout(()=>$h(t,e,r),50))}):setTimeout(()=>$h(t,e,r),50),null}function pnr(t,e){const r={_id:t._id.replace(/^flot.\d+/,`echarts.${e}`),common:{name:t.common.name,expert:!0},native:{},type:"chart"};r._id.endsWith(".")&&(r._id=`empty_${Math.round(Math.random()*1e4)}`);const n=dnr(cnr(t.native.url));return n.lines||(n.lines=n.l,delete n.l),r.native.data=n,console.log(`Convert ${t._id} => ${r._id}`),r}function hnr(t,e){e=e||0;let r;return t.getObject(`system.adapter.echarts.${e}`).then(n=>(r=n,n&&n.native&&!n.native.convertDone?unr(t):Promise.resolve([]))).then(n=>$h(t,n.map(o=>pnr(o,e)))).then(()=>r.native.convertDone?Promise.resolve():(r.native.convertDone=!0,t.setObject(r._id,r))).catch(n=>(console.error(`Cannot convert flot: ${n}`),Promise.resolve()))}const Qp={root:t=>({width:"100%",height:"100%",background:t.palette.background.default,color:t.palette.mode==="dark"?"#FFF":"#000",fontFamily:'"Roboto", "Helvetica", "Arial", sans-serif'}),menuDiv:{overflow:"hidden"},content:t=>({width:"100%",height:"100%",backgroundColor:t.palette.background.default,position:"relative"}),menuDivWithoutMenu:{"&>div:first-child":{display:"none"},"&>.layout-splitter":{display:"none"}},progress:{margin:100},menuOpenCloseButton:t=>({position:"absolute",left:0,borderRadius:"0 5px 5px 0",top:6,pt:"8px",cursor:"pointer",zIndex:1,height:25,width:20,background:t.palette.secondary.main,color:t.palette.primary.main,pl:"3px","&:hover":{color:"white"}}),buttonsContainer:{"& button":{whiteSpace:"nowrap"}}},E9=/[.\][*,;'"`<>\\?]/g;function T9(t,e){const r=window.localStorage.getItem(`App.echarts.__${t}`);return r?parseFloat(r):e}function eh(t,e){return window.localStorage.getItem(`App.echarts.__${t}`)||e}function sd(t,e){return window.localStorage.getItem(`App.echarts.__${t}`)||e}function O9(){if(window.location.hash){const t={};return window.location.hash.replace(/^#/,"").split("&").forEach(e=>{const[r,n]=e.split("=");t[r]=window.decodeURIComponent(n),r==="instance"&&!t[r].startsWith("system.adapter")&&(t[r]=`system.adapter.${t[r]}`)}),t}return null}class ay extends ys{constructor(r){const n={socket:{}},o=Her();n.socket.port=o.port||(parseInt(window.location.port)>=3e3&&parseInt(window.location.port)<=3020?8081:window.location.port),n.socket.host=o.host||window.location.hostname,n.translations={en:gwt,de:_Ct,ru:xEt,pt:$Ot,nl:TIt,fr:ANt,it:P3t,es:jLt,pl:F6t,uk:H9t,"zh-cn":qHt},n.sentryDSN=window.sentryDSN,window.location.port==="3000"&&(n.socket={port:"8081"}),window.socketUrl&&window.socketUrl.startsWith(":")&&(window.socketUrl=`${window.location.protocol}//${window.location.hostname}${window.socketUrl}`);super(r,n);X(this,"config");X(this,"objects",{});X(this,"confirmCB",null);X(this,"onCopyPreset",async r=>{try{const n=await this.socket.getObject(r);if(n){const{id:o,name:a}=await this.getUniqueId(r,typeof n.common.name=="object"?n.common.name[P.getLanguage()]||n.common.name.en:n.common.name);n._id=o,n.common.name=a;try{await this.socket.setObject(n._id,n),this.loadChartOrPreset(o)}catch(i){this.onError(i,"Cannot save object")}}}catch(n){this.onError(n,"Cannot save object")}});X(this,"onCreatePreset",async(r,n)=>{var i;let o,a;if(r===!0){let s="";const l=this.state.selectedId,d=JSON.parse(JSON.stringify(this.state.chartsList||[]));d.find(f=>f.id===l.id&&f.instance===l.instance)||d.push(l);let h=null;d.length===1&&(h=await this.socket.getObject(d[0].id)),h&&((i=h==null?void 0:h.common)!=null&&i.name)&&(s=typeof h.common.name=="object"?(h.common.name[P.getLanguage()]||h.common.name.en||"").trim():h.common.name);const u=await this.getNewPresetName(n,s);a=`${this.adapterName}.0.${n?`${n}.`:""}${s.replace(E9,"_")}`,o={_id:a,common:{name:u,expert:!0},native:{data:JSON.parse(JSON.stringify(this.state.presetData))},type:"chart"}}else{const s=await this.getNewPresetName(n);a=`${this.adapterName}.0.${n?`${n}.`:""}${s.replace(E9,"_")}`,o={_id:a,common:{name:s},native:{url:"",data:G2(this.state.systemConfig,null,null,P.getLanguage())},type:"chart"}}try{await this.socket.setObject(a,o),this.loadChartOrPreset(a)}catch(s){this.onError(s,"Cannot save object")}});X(this,"savePreset",async()=>{if(!this.state.presetData)throw this.showError(P.t("Empty preset cannot be saved!")),new Error(P.t("Empty preset cannot be saved!"));try{const r=await this.socket.getObject(this.state.selectedId);if(!(r!=null&&r.native)){this.showError(P.t("Invalid object"));return}r.native.data=this.state.presetData;try{await this.socket.setObject(r._id,r)}catch(n){this.onError(n,"Cannot save object")}this.setState({originalPresetData:JSON.stringify(this.state.presetData),selectedPresetChanged:!1})}catch(r){this.onError(r,"Cannot read object")}});X(this,"onDragEnd",async r=>{const{source:n,destination:o,draggableId:a}=r;if(o&&a.includes("***")&&n.droppableId==="Lines"){const[i,s]=a.split("***");try{const l=await this.socket.getObject(s),d=JSON.parse(JSON.stringify(this.state.presetData)),h=Lh(this.state.systemConfig,i,l,P.getLanguage());for(let u=0;u=o.index&&(d.l[u].commonYAxis=d.l[u].commonYAxis+1);if(d.l.splice(o.index,0,h),d.l.length>1){if(h.unit){for(let u=0;uu.chartType==="bar")?h.chartType="bar":d.l.find(u=>u.chartType==="polar")&&(h.chartType="polar",h.aggregate="current")}this.setState({presetData:d,selectedPresetChanged:JSON.stringify(d)!==this.state.originalPresetData})}catch(l){this.onError(l,"Cannot read object")}}else if(o&&n.droppableId===o.droppableId){const i=JSON.parse(JSON.stringify(this.state.presetData));for(let l=0;lthis.setState({scrollToSelect:!0},()=>this.setState({scrollToSelect:!1})))}async onConnectionReady(){var h,u,f;const r=window.localStorage.getItem("App.echarts.selectedId");let n;if(r)try{n=JSON.parse(r)}catch{n=null}!n&&((h=this.config)!=null&&h.preset)?n=this.config.preset:!n&&((u=this.config)!=null&&u.id)&&(n={id:this.config.id,instance:this.config.instance});const o=window.localStorage.getItem("App.echarts.settingsSizes");let a=[25,75];if(o)try{a=JSON.parse(o)}catch{}a=a||[25,75];const i=window.localStorage.getItem("App.echarts.menuSizes");let s=[25,75];if(i)try{s=JSON.parse(i)}catch{}s=s||[25,75];const l={ready:!1,instances:[],splitSizes:a,menuSizes:s,selectedId:n,selectedPresetChanged:!1,presetData:null,originalPresetData:null,chartsList:null,progress:0,autoSave:window.localStorage.getItem("App.echarts.autoSave")==="true",discardChangesConfirmDialog:!1,resizing:!1,menuOpened:window.localStorage.getItem("App.echarts.menuOpened")!=="false",logHorzLayout:window.localStorage.getItem("App.echarts.logHorzLayout")==="true"};this.objects={};const d=await this.socket.getSystemConfig();if(l.systemConfig=d,l.presetData=G2(d),(f=this.config)!=null&&f.id){const g=this.config;l.selectedId={id:g.id,instance:g.instance},g.menuOpened!==void 0&&(l.menuOpened=g.menuOpened===!0),this.config=null}this.setState(l,async()=>{hnr(this.socket,this.instance);try{const y=(await this.socket.getAdapterInstances("")).filter(b=>{var x;return((x=b==null?void 0:b.common)==null?void 0:x.getHistory)&&b.common.enabled});this.setState({ready:!0,instances:y})}catch(g){this.onError(g,"Cannot read system config")}})}async getNewPresetName(r,n,o){o=o||(n?"":"1"),n=n||"preset_";let a;do{try{a=await this.socket.getObject(`${this.adapterName}.${this.instance}.${r?`${r}.`:""}${n}${o}`)}catch{return n+o}if(!a)return n+o;o?o=(parseInt(o,10)+1).toString():o="2"}while(a)}async getUniqueId(r,n){let o=0,a;do{const i=`${r}_${P.t("copy")}${o?`_${o}`:""}`,s=`${n} ${P.t("copy")}${o?` ${o}`:""}`;try{a=await this.socket.getObject(i)}catch{}if(!a)return{name:s,id:i};o++}while(o<100);throw new Error(P.t("Cannot create unique ID"))}onError(r,n){n&&console.error(n),this.showError(r.toString())}static normalizePreset(r){var n;r.lines&&(r.l=r.lines,delete r.lines),typeof r.range=="string"&&!r.range.includes("m")&&!r.range.includes("y")&&(r.range=parseInt(r.range,10)),(n=r.l)==null||n.forEach(o=>{typeof o.commonYAxis=="string"&&(o.commonYAxis===""?delete o.commonYAxis:o.commonYAxis=parseInt(o.commonYAxis,10)),typeof o.fill=="string"&&(o.fill===""?delete o.fill:o.fill=parseFloat(o.fill))})}async loadChartOrPreset(r){var n,o;if(window.localStorage.setItem("App.echarts.selectedId",JSON.stringify(r)),r&&typeof r=="object"){if(this.state.chartsList)for(const s of this.state.chartsList)this.objects[s.id]===void 0&&(this.objects[s.id]=await this.socket.getObject(s.id)||null);else this.objects={};this.objects[r.id]===void 0&&(this.objects[r.id]=await this.socket.getObject(r.id)||null);const a=(this.state.chartsList||[]).map(s=>Lh(this.state.systemConfig,s.instance,this.objects[s.id],P.getLanguage()));if((n=this.state.chartsList)!=null&&n.find(s=>s.id===r.id&&s.instance===r.instance)||a.push(Lh(this.state.systemConfig,r.instance,this.objects[r.id],P.getLanguage())),a.length>1){const s=a.find(l=>!l.isBoolean);if(s){const l=a.indexOf(s);if(s.yaxe="left",s.unit)for(let d=l+1;d1?"nw":""};ay.normalizePreset(i),await new Promise(s=>{this.setState({presetData:i,originalPresetData:"",selectedPresetChanged:!1,selectedId:r},()=>{const l=`#id=${r.id}&instance=${r.instance.replace(/^system\.adapter\./,"")}`;window.location.hash!==l&&(window.location.hash=l),s()})})}else if(r){const a=await this.socket.getObject(r);if((o=a==null?void 0:a.native)!=null&&o.data){const i=`#preset=${r}`;window.location.hash!==i&&(window.location.hash=i);const s={presetData:a.native.data,originalPresetData:JSON.stringify(a.native.data),selectedPresetChanged:!1,selectedId:r};ay.normalizePreset(s.presetData),await new Promise(l=>this.setState(s,()=>l()))}}else await new Promise(a=>{this.setState({presetData:null,originalPresetData:"",selectedPresetChanged:!1,selectedId:null},()=>a())})}discardChangesConfirmDialog(){return this.state.discardChangesConfirmDialog?w.jsxs(or,{maxWidth:"lg",fullWidth:!0,open:!0,onClose:()=>this.setState({discardChangesConfirmDialog:!1},()=>this.confirmCB&&this.confirmCB(!1)),children:[w.jsx(_r,{children:this.state.discardChangesConfirmDialog==="chart"?P.t("Are you sure for loading the chart and discard unsaved changes?"):this.state.discardChangesConfirmDialog==="preset"?P.t("Are you sure for loading the preset and discard unsaved changes?"):P.t("Are you sure for closing folder and discard unsaved changes?")}),w.jsxs(pr,{sx:{...Qp.alignRight,...Qp.buttonsContainer},children:[w.jsx(tt,{color:"grey",variant:"outlined",onClick:()=>this.setState({discardChangesConfirmDialog:!1},()=>this.confirmCB&&this.confirmCB(!0)),children:P.t("Load without save")}),w.jsx(tt,{variant:"contained",color:"secondary",autoFocus:!0,onClick:()=>this.savePreset().then(()=>this.setState({discardChangesConfirmDialog:!1},()=>this.confirmCB&&this.confirmCB(!0))),startIcon:w.jsx(pH,{}),children:P.t("Save current preset and load")}),w.jsx(tt,{color:"grey",variant:"contained",onClick:()=>this.setState({discardChangesConfirmDialog:!1},()=>this.confirmCB&&this.confirmCB(!1)),startIcon:w.jsx(wo,{}),children:P.t("Cancel")})]})]},"discardChangesConfirmDialog"):null}renderMain(){let r=null,n=null;this.state.presetData&&this.state.selectedId&&typeof this.state.selectedId=="string"&&(r=w.jsx(aZt,{socket:this.socket,width:window.innerWidth,theme:this.state.theme,onChange:a=>{this.state.autoSave?this.setState({presetData:a},()=>this.savePreset()):this.setState({presetData:a,selectedPresetChanged:JSON.stringify(a)!==this.state.originalPresetData})},presetData:this.state.presetData,selectedId:this.state.selectedId,instances:this.state.instances,systemConfig:this.state.systemConfig,selectedPresetChanged:this.state.selectedPresetChanged,savePreset:this.savePreset,autoSave:this.state.autoSave,onAutoSave:a=>{window.localStorage.setItem("App.echarts.autoSave",a?"true":"false"),a&&this.state.selectedPresetChanged?this.savePreset().then(()=>this.setState({autoSave:a})):this.setState({autoSave:a})},windowWidth:this.state.menuSizes[1]},"Editor")),this.state.selectedId&&(n=w.jsx(Wer,{visible:!this.state.resizing,theme:this.state.theme,onChange:a=>this.setState({presetData:a}),presetData:this.state.presetData,selectedId:this.state.selectedId,onCreatePreset:this.onCreatePreset,windowWidth:this.state.menuSizes[1]},"MainChart"));let o;return n&&r?o=w.jsxs(CP,{direction:this.state.logHorzLayout?Tr.Horizontal:Tr.Vertical,initialSizes:this.state.splitSizes,minWidths:[100,450],onResizeStarted:()=>this.setState({resizing:!0}),onResizeFinished:(a,i)=>{this.setState({resizing:!1,splitSizes:i}),window.localStorage.setItem("App.echarts.settingsSizes",JSON.stringify(i))},gutterClassName:this.state.themeType==="dark"?"Dark visGutter":"Light visGutter",children:[n,r]}):o=n,[w.jsxs(Re,{component:"div",sx:Qp.content,className:"iobVerticalSplitter",children:[w.jsx(Re,{component:"div",sx:Qp.menuOpenCloseButton,onClick:()=>{window.localStorage.setItem("App.echarts.menuOpened",this.state.menuOpened?"false":"true"),this.setState({menuOpened:!this.state.menuOpened,resizing:!0}),setTimeout(()=>this.setState({resizing:!1}),300)},children:this.state.menuOpened?w.jsx(Bpe,{}):w.jsx(HE,{})},"confirmdiv"),o]},"confirmdialog")]}renderMenu(){return w.jsx(lnr,{scrollToSelect:this.state.scrollToSelect,socket:this.socket,theme:this.state.theme,adapterName:this.adapterName,instances:this.state.instances,systemConfig:this.state.systemConfig,onShowToast:r=>this.showToast(r),selectedPresetChanged:this.state.selectedPresetChanged,chartsList:this.state.chartsList,selectedId:this.state.selectedId,onCopyPreset:this.onCopyPreset,onCreatePreset:this.onCreatePreset,onChangeList:r=>{let n=this.state.selectedId;if(r&&this.state.chartsList&&r.length&&r.length!r.find(s=>s.id===i.id&&s.instance===i.instance)),a=this.state.chartsList.indexOf(o);this.state.chartsList[a+1]?n=this.state.chartsList[a+1]:this.state.chartsList[a-1]?n=this.state.chartsList[a-1]:n=r[0]}this.setState({chartsList:r},()=>this.loadChartOrPreset(n))},onSelectedChanged:(r,n)=>{this.state.selectedPresetChanged?(this.confirmCB=o=>{o?this.loadChartOrPreset(r).then(()=>n&&n(r)):n&&n(!1),this.confirmCB=null},this.setState({discardChangesConfirmDialog:r&&typeof r=="object"?"chart":r?"preset":"folder"})):this.loadChartOrPreset(r)}},"menuList")}render(){if(!this.state.ready)return w.jsx(uE,{injectFirst:!0,children:w.jsx(yE,{theme:this.state.theme,children:w.jsx(QH,{themeType:this.state.themeType})})});let r;return this.state.menuOpened?r=w.jsx(XN,{onDragEnd:this.onDragEnd,children:w.jsxs(CP,{direction:Tr.Horizontal,initialSizes:this.state.menuSizes,minWidths:[307,300],onResizeStarted:()=>this.setState({resizing:!0}),onResizeFinished:(n,o)=>{this.setState({resizing:!1,menuSizes:[o[0],100-o[0]]}),window.localStorage.setItem("App.echarts.menuSizes",JSON.stringify(o))},gutterClassName:this.state.themeType==="dark"?"Dark visGutter":"Light visGutter",children:[this.renderMenu(),this.renderMain()]})}):r=r=w.jsx(XN,{onDragEnd:this.onDragEnd,children:this.renderMain()}),w.jsx(uE,{injectFirst:!0,children:w.jsxs(yE,{theme:this.state.theme,children:[w.jsx(Re,{sx:Qp.root,children:r}),this.discardChangesConfirmDialog(),this.renderError(),this.renderToast()]})})}}const fnr=qs()(ay);window.location.hostname==="localhost"||window.location.hostname==="[::1]"||window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/);function mnr(){"serviceWorker"in navigator&&navigator.serviceWorker.ready.then(t=>t.unregister())}const gnr="echarts.edit",vnr="1.9.2",ynr={"@devbookhq/splitter":"^1.4.2","@vitejs/plugin-react":"^4.3.4","@types/react-color":"^3.0.13","@types/react-beautiful-dnd":"^13.1.8","material-ui-color-picker":"^3.5.1",moment:"^2.30.1",react:"^18.3.1","react-beautiful-dnd":"^13.1.1","react-dnd":"^16.0.1","react-dnd-html5-backend":"^16.0.1","react-dnd-touch-backend":"^16.0.1","react-dom":"^18.3.1","react-i18next":"^15.4.0","react-icons":"^5.4.0",typescript:"^5.7.2"},_nr=".",bnr={start:"vite dev --config vite.config.mjs --host",build:"vite build --config vite.config.mjs",lint:"eslint -c eslint.config.mjs --debug",npm:"npm i -f",tsc:"tsc -p tsconfig.json"},wnr="http://127.0.0.1:8081",xnr=["127.0.0.1"],Snr={extends:"react-app"},Cnr=[">0.2%","not dead","not ie <= 11","not op_mini all"],$nr={name:gnr,version:vnr,private:!0,dependencies:ynr,homepage:_nr,scripts:bnr,_proxy:wnr,allowedHosts:xnr,eslintConfig:Snr,browserslist:Cnr};window.adapterName="echarts";window.sentryDSN="https://709f116e1de34029921e4f2696d6740f@sentry.iobroker.net/88";console.log(`iobroker.${window.adapterName}@${$nr.version}`);const D9=document.getElementById("root");D9&&LJ.createRoot(D9).render(w.jsx(fnr,{}));mnr()});export default knr(); +`),dataTransfer:t=>t},matchesTypes:["Url","text/uri-list"]},[kG]:{exposeProperties:{text:(t,e)=>tE(t,e,""),dataTransfer:t=>t},matchesTypes:["Text","text/plain"]}};function Hrr(t,e){const r=cT[t];if(!r)throw new Error(`native type ${t} has no configuration`);const n=new Wrr(r);return n.loadDataTransfer(e),n}function rE(t){if(!t)return null;const e=Array.prototype.slice.call(t.types||[]);return Object.keys(cT).filter(r=>{const n=cT[r];return n!=null&&n.matchesTypes?n.matchesTypes.some(o=>e.indexOf(o)>-1):!1})[0]||null}const Urr=SG(()=>/firefox/i.test(navigator.userAgent)),TG=SG(()=>!!window.safari);class _9{interpolate(e){const{xs:r,ys:n,c1s:o,c2s:a,c3s:i}=this;let s=r.length-1;if(e===r[s])return n[s];let l=0,d=i.length-1,h;for(;l<=d;){h=Math.floor(.5*(l+d));const g=r[h];if(ge)d=h-1;else return n[h]}s=Math.max(0,d);const u=e-r[s],f=u*u;return n[s]+o[s]*u+a[s]*f+i[s]*u*f}constructor(e,r){const{length:n}=e,o=[];for(let g=0;ge[g]{let O=new _9([0,.5,1],[l.y,l.y/h*y,l.y+y-h]).interpolate(f);return TG()&&a&&(O+=(window.devicePixelRatio-1)*y),O},x=()=>new _9([0,.5,1],[l.x,l.x/d*g,l.x+g-d]).interpolate(u),{offsetX:S,offsetY:T}=o,E=S===0||S,$=T===0||T;return{x:E?S:x(),y:$?T:b()}}class Jrr{get window(){if(this.globalContext)return this.globalContext;if(typeof window<"u")return window}get document(){var e;return!((e=this.globalContext)===null||e===void 0)&&e.document?this.globalContext.document:this.window?this.window.document:void 0}get rootElement(){var e;return((e=this.optionsArgs)===null||e===void 0?void 0:e.rootElement)||this.window}constructor(e,r){this.ownerDocument=null,this.globalContext=e,this.optionsArgs=r}}function Yrr(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function b9(t){for(var e=1;e{this.sourcePreviewNodes.delete(e),this.sourcePreviewNodeOptions.delete(e)}}connectDragSource(e,r,n){this.sourceNodes.set(e,r),this.sourceNodeOptions.set(e,n);const o=i=>this.handleDragStart(i,e),a=i=>this.handleSelectStart(i);return r.setAttribute("draggable","true"),r.addEventListener("dragstart",o),r.addEventListener("selectstart",a),()=>{this.sourceNodes.delete(e),this.sourceNodeOptions.delete(e),r.removeEventListener("dragstart",o),r.removeEventListener("selectstart",a),r.setAttribute("draggable","false")}}connectDropTarget(e,r){const n=i=>this.handleDragEnter(i,e),o=i=>this.handleDragOver(i,e),a=i=>this.handleDrop(i,e);return r.addEventListener("dragenter",n),r.addEventListener("dragover",o),r.addEventListener("drop",a),()=>{r.removeEventListener("dragenter",n),r.removeEventListener("dragover",o),r.removeEventListener("drop",a)}}addEventListeners(e){e.addEventListener&&(e.addEventListener("dragstart",this.handleTopDragStart),e.addEventListener("dragstart",this.handleTopDragStartCapture,!0),e.addEventListener("dragend",this.handleTopDragEndCapture,!0),e.addEventListener("dragenter",this.handleTopDragEnter),e.addEventListener("dragenter",this.handleTopDragEnterCapture,!0),e.addEventListener("dragleave",this.handleTopDragLeaveCapture,!0),e.addEventListener("dragover",this.handleTopDragOver),e.addEventListener("dragover",this.handleTopDragOverCapture,!0),e.addEventListener("drop",this.handleTopDrop),e.addEventListener("drop",this.handleTopDropCapture,!0))}removeEventListeners(e){e.removeEventListener&&(e.removeEventListener("dragstart",this.handleTopDragStart),e.removeEventListener("dragstart",this.handleTopDragStartCapture,!0),e.removeEventListener("dragend",this.handleTopDragEndCapture,!0),e.removeEventListener("dragenter",this.handleTopDragEnter),e.removeEventListener("dragenter",this.handleTopDragEnterCapture,!0),e.removeEventListener("dragleave",this.handleTopDragLeaveCapture,!0),e.removeEventListener("dragover",this.handleTopDragOver),e.removeEventListener("dragover",this.handleTopDragOverCapture,!0),e.removeEventListener("drop",this.handleTopDrop),e.removeEventListener("drop",this.handleTopDropCapture,!0))}getCurrentSourceNodeOptions(){const e=this.monitor.getSourceId(),r=this.sourceNodeOptions.get(e);return b9({dropEffect:this.altKeyPressed?"copy":"move"},r||{})}getCurrentDropEffect(){return this.isDraggingNativeItem()?"copy":this.getCurrentSourceNodeOptions().dropEffect}getCurrentSourcePreviewNodeOptions(){const e=this.monitor.getSourceId(),r=this.sourcePreviewNodeOptions.get(e);return b9({anchorX:.5,anchorY:.5,captureDraggingState:!1},r||{})}isDraggingNativeItem(){const e=this.monitor.getItemType();return Object.keys(y9).some(r=>y9[r]===e)}beginDragNativeItem(e,r){this.clearCurrentDragSourceNode(),this.currentNativeSource=Hrr(e,r),this.currentNativeHandle=this.registry.addSource(e,this.currentNativeSource),this.actions.beginDrag([this.currentNativeHandle])}setCurrentDragSourceNode(e){this.clearCurrentDragSourceNode(),this.currentDragSourceNode=e;const r=1e3;this.mouseMoveTimeoutTimer=setTimeout(()=>{var n;return(n=this.rootElement)===null||n===void 0?void 0:n.addEventListener("mousemove",this.endDragIfSourceWasRemovedFromDOM,!0)},r)}clearCurrentDragSourceNode(){if(this.currentDragSourceNode){if(this.currentDragSourceNode=null,this.rootElement){var e;(e=this.window)===null||e===void 0||e.clearTimeout(this.mouseMoveTimeoutTimer||void 0),this.rootElement.removeEventListener("mousemove",this.endDragIfSourceWasRemovedFromDOM,!0)}return this.mouseMoveTimeoutTimer=null,!0}return!1}handleDragStart(e,r){e.defaultPrevented||(this.dragStartSourceIds||(this.dragStartSourceIds=[]),this.dragStartSourceIds.unshift(r))}handleDragEnter(e,r){this.dragEnterTargetIds.unshift(r)}handleDragOver(e,r){this.dragOverTargetIds===null&&(this.dragOverTargetIds=[]),this.dragOverTargetIds.unshift(r)}handleDrop(e,r){this.dropTargetIds.unshift(r)}constructor(e,r,n){this.sourcePreviewNodes=new Map,this.sourcePreviewNodeOptions=new Map,this.sourceNodes=new Map,this.sourceNodeOptions=new Map,this.dragStartSourceIds=null,this.dropTargetIds=[],this.dragEnterTargetIds=[],this.currentNativeSource=null,this.currentNativeHandle=null,this.currentDragSourceNode=null,this.altKeyPressed=!1,this.mouseMoveTimeoutTimer=null,this.asyncEndDragFrameId=null,this.dragOverTargetIds=null,this.lastClientOffset=null,this.hoverRafId=null,this.getSourceClientOffset=o=>{const a=this.sourceNodes.get(o);return a&&OG(a)||null},this.endDragNativeItem=()=>{this.isDraggingNativeItem()&&(this.actions.endDrag(),this.currentNativeHandle&&this.registry.removeSource(this.currentNativeHandle),this.currentNativeHandle=null,this.currentNativeSource=null)},this.isNodeInDocument=o=>!!(o&&this.document&&this.document.body&&this.document.body.contains(o)),this.endDragIfSourceWasRemovedFromDOM=()=>{const o=this.currentDragSourceNode;o==null||this.isNodeInDocument(o)||(this.clearCurrentDragSourceNode()&&this.monitor.isDragging()&&this.actions.endDrag(),this.cancelHover())},this.scheduleHover=o=>{this.hoverRafId===null&&typeof requestAnimationFrame<"u"&&(this.hoverRafId=requestAnimationFrame(()=>{this.monitor.isDragging()&&this.actions.hover(o||[],{clientOffset:this.lastClientOffset}),this.hoverRafId=null}))},this.cancelHover=()=>{this.hoverRafId!==null&&typeof cancelAnimationFrame<"u"&&(cancelAnimationFrame(this.hoverRafId),this.hoverRafId=null)},this.handleTopDragStartCapture=()=>{this.clearCurrentDragSourceNode(),this.dragStartSourceIds=[]},this.handleTopDragStart=o=>{if(o.defaultPrevented)return;const{dragStartSourceIds:a}=this;this.dragStartSourceIds=null;const i=Vg(o);this.monitor.isDragging()&&(this.actions.endDrag(),this.cancelHover()),this.actions.beginDrag(a||[],{publishSource:!1,getSourceClientOffset:this.getSourceClientOffset,clientOffset:i});const{dataTransfer:s}=o,l=rE(s);if(this.monitor.isDragging()){if(s&&typeof s.setDragImage=="function"){const h=this.monitor.getSourceId(),u=this.sourceNodes.get(h),f=this.sourcePreviewNodes.get(h)||u;if(f){const{anchorX:g,anchorY:y,offsetX:b,offsetY:x}=this.getCurrentSourcePreviewNodeOptions(),E=Xrr(u,f,i,{anchorX:g,anchorY:y},{offsetX:b,offsetY:x});s.setDragImage(f,E.x,E.y)}}try{s==null||s.setData("application/json",{})}catch{}this.setCurrentDragSourceNode(o.target);const{captureDraggingState:d}=this.getCurrentSourcePreviewNodeOptions();d?this.actions.publishDragSource():setTimeout(()=>this.actions.publishDragSource(),0)}else if(l)this.beginDragNativeItem(l);else{if(s&&!s.types&&(o.target&&!o.target.hasAttribute||!o.target.hasAttribute("draggable")))return;o.preventDefault()}},this.handleTopDragEndCapture=()=>{this.clearCurrentDragSourceNode()&&this.monitor.isDragging()&&this.actions.endDrag(),this.cancelHover()},this.handleTopDragEnterCapture=o=>{if(this.dragEnterTargetIds=[],this.isDraggingNativeItem()){var a;(a=this.currentNativeSource)===null||a===void 0||a.loadDataTransfer(o.dataTransfer)}if(!this.enterLeaveCounter.enter(o.target)||this.monitor.isDragging())return;const{dataTransfer:s}=o,l=rE(s);l&&this.beginDragNativeItem(l,s)},this.handleTopDragEnter=o=>{const{dragEnterTargetIds:a}=this;if(this.dragEnterTargetIds=[],!this.monitor.isDragging())return;this.altKeyPressed=o.altKey,a.length>0&&this.actions.hover(a,{clientOffset:Vg(o)}),a.some(s=>this.monitor.canDropOnTarget(s))&&(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect=this.getCurrentDropEffect()))},this.handleTopDragOverCapture=o=>{if(this.dragOverTargetIds=[],this.isDraggingNativeItem()){var a;(a=this.currentNativeSource)===null||a===void 0||a.loadDataTransfer(o.dataTransfer)}},this.handleTopDragOver=o=>{const{dragOverTargetIds:a}=this;if(this.dragOverTargetIds=[],!this.monitor.isDragging()){o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect="none");return}this.altKeyPressed=o.altKey,this.lastClientOffset=Vg(o),this.scheduleHover(a),(a||[]).some(s=>this.monitor.canDropOnTarget(s))?(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect=this.getCurrentDropEffect())):this.isDraggingNativeItem()?o.preventDefault():(o.preventDefault(),o.dataTransfer&&(o.dataTransfer.dropEffect="none"))},this.handleTopDragLeaveCapture=o=>{this.isDraggingNativeItem()&&o.preventDefault(),this.enterLeaveCounter.leave(o.target)&&(this.isDraggingNativeItem()&&setTimeout(()=>this.endDragNativeItem(),0),this.cancelHover())},this.handleTopDropCapture=o=>{if(this.dropTargetIds=[],this.isDraggingNativeItem()){var a;o.preventDefault(),(a=this.currentNativeSource)===null||a===void 0||a.loadDataTransfer(o.dataTransfer)}else rE(o.dataTransfer)&&o.preventDefault();this.enterLeaveCounter.reset()},this.handleTopDrop=o=>{const{dropTargetIds:a}=this;this.dropTargetIds=[],this.actions.hover(a,{clientOffset:Vg(o)}),this.actions.drop({dropEffect:this.getCurrentDropEffect()}),this.isDraggingNativeItem()?this.endDragNativeItem():this.monitor.isDragging()&&this.actions.endDrag(),this.cancelHover()},this.handleSelectStart=o=>{const a=o.target;typeof a.dragDrop=="function"&&(a.tagName==="INPUT"||a.tagName==="SELECT"||a.tagName==="TEXTAREA"||a.isContentEditable||(o.preventDefault(),a.dragDrop()))},this.options=new Jrr(r,n),this.actions=e.getActions(),this.monitor=e.getMonitor(),this.registry=e.getRegistry(),this.enterLeaveCounter=new Brr(this.isNodeInDocument)}}const Zrr=function(e,r,n){return new Krr(e,r,n)},ad="_consumption_",Qrr=!window.location.search.includes("hidden=false");function DG(t){let e=[];return Object.values(t.subFolders||{}).forEach(r=>e=e.concat(DG(r))),e}const enr=t=>{const{onDrop:e}=t,[{isOver:r,isOverAny:n},o]=Lrr({accept:"item",drop:a=>e(a.name),collect:a=>({isOver:a.isOver({shallow:!0}),isOverAny:a.isOver()})});return w.jsx("div",{ref:o,style:{background:r?"#40adff":void 0,opacity:n?.3:void 0},children:t.children})},tnr=t=>{const{name:e}=t,[{opacity:r},n]=Drr({type:"item",item:()=>({name:e}),collect:o=>({opacity:o.isDragging()?.3:1})});return w.jsx("div",{ref:n,style:{opacity:r,transform:"translate3d(0, 0, 0)"},children:t.children})},w9=16,nE=/[.\][*,;'"`<>\\?]/g,Tt={noGutters:{pt:0,pb:0,width:"100%"},changed:t=>({position:"relative","&:after":{content:'""',position:"absolute",top:2,right:2,width:5,height:5,borderRadius:5,background:(t.palette.mode==="dark","#CC0000")}}),itemIcon:{width:32,height:32,marginRight:4},itemIconFolder:{cursor:"pointer"},buttonsContainer:{"& button":{whiteSpace:"nowrap"}},itemIconPreset:t=>({color:t.palette.mode==="dark"?t.palette.primary.light:t.palette.primary.dark,position:"relative"}),folderIconPreset:t=>({color:t.palette.mode==="dark"?t.palette.secondary.dark:t.palette.secondary.light}),width100:{width:"100%"},buttonIcon:{marginRight:4},itemIconRoot:{minWidth:24},listItemSubTitle:{fontSize:"smaller",opacity:.7,fontStyle:"italic",display:"inline-block",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",width:"100%"},mainList:{width:"calc(100% - 8px)",ml:"8px"},iconCopy:{width:16},listItemSecondaryAction:{right:7},listItemTitle:{lineHeight:1,width:"100%"},listItemTitleDiv:{display:"inline-block",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",width:"100%"},itemIconNumber:t=>({position:"absolute",fontSize:12,top:8,left:-1,width:"100%",textAlign:"center",color:t.palette.mode==="dark"?"#000":"#FFF"}),textColor:t=>({color:t.palette.mode==="dark"?"#FFF !important":"#000 !important"}),selected:t=>({backgroundColor:t.palette.mode==="dark"?"rgba(77, 171, 245, 0.16)":t.palette.primary.light,"&:hover":{backgroundColor:t.palette.mode==="dark"?"rgba(77, 171, 245, 0.10)":"#76d0fd80"}})};class oy extends A.Component{constructor(r){super(r);X(this,"refSelected");X(this,"scrollToSelect",!1);X(this,"scrollTimeout",null);X(this,"onPresetChange",(r,n)=>{if(!(r!=null&&r.startsWith("echarts.")))return;let o,a=!1;if(n?(n.common=n.common||{},n.native=n.native||{},JSON.stringify(n)!==JSON.stringify(this.state.presets[r])&&(o=JSON.parse(JSON.stringify(this.state.presets)),o[r]=n,a=!0)):this.state.presets[r]&&(o=JSON.parse(JSON.stringify(this.state.presets)),delete o[r],a=!0),a){const i=this.getEmptyFolders(),s={presets:o,changingPreset:"",presetFolders:oy.buildPresetTree(o,i)};setTimeout(()=>this.informAboutSubFolders(s.presetFolders),200),this.setState(s)}});X(this,"addPresetToFolderPrefix",async(r,n,o)=>{const a=r._id,i=r._id.split(".").pop();r._id=`${this.props.adapterName}.0.${n}${n?".":""}${i}`;try{if(await this.props.socket.setObject(r._id,r),console.log(`Deleted ${a}`),await this.props.socket.delObject(a),console.log(`Set new ID: ${r._id}`),!o){const s=await this.getAllPresets();this.setState(s)}}catch(s){this.onError(s,`Cannot delete object ${a}`)}});let n;try{n=JSON.parse(window.localStorage.getItem("App.echarts.presets.opened"))||[]}catch{n=[]}this.state={presetsOpened:n,presets:{},presetFolders:null,changingPreset:"",deletePresetDialog:"",movePresetDialog:"",newPresetFolder:"",addPresetFolderName:"",editPresetFolderDialog:null,editFolderDialogTitleOrigin:"",editPresetFolderName:"",renameDialog:"",renamePresetDialogTitle:""},this.refSelected=m.createRef(),this.getAllPresets().then(o=>this.setState(o))}async componentDidMount(){await this.props.socket.subscribeObject(`${this.props.adapterName}.0.*`,this.onPresetChange)}async componentWillUnmount(){this.scrollTimeout&&(clearTimeout(this.scrollTimeout),this.scrollTimeout=null),await this.props.socket.unsubscribeObject(`${this.props.adapterName}.0.*`,this.onPresetChange)}informAboutSubFolders(r){r=r||this.state.presetFolders||{},this.props.onShowReorder(!!Object.keys(r.subFolders||{}).length)}getEmptyFolders(r,n,o){if(o=o||[],n=n||[],r=r||this.state.presetFolders||{},r.id){const a=[...n];a.push(r.id),o.push(a.join("."))}return r.subFolders&&Object.keys(r.subFolders).forEach(a=>this.getEmptyFolders(r.subFolders[a],n,o)),o}async getAllPresets(r,n){r=r||{};const o={},a=await this.props.socket.getObjectViewSystem("chart",`${this.props.adapterName}.`,`${this.props.adapterName}.香`);return a&&Object.values(a).forEach(i=>i._id&&!i._id.toString().endsWith(".")&&(o[i._id]=i)),r.presets=o,r.changingPreset="",Object.keys(r.presets).forEach(i=>{const s=r.presets[i];s.common=s.common||{},s.native=s.native||{}}),n=n||this.getEmptyFolders(),r.presetFolders=oy.buildPresetTree(o,n),setTimeout(()=>this.informAboutSubFolders(r.presetFolders),200),r}renderPreset(r,n){var d,h;const o=this.state.presets[r._id],a=typeof r.common.name=="object"?r.common.name[P.getLanguage()]||r.common.name.en:r.common.name;if(!o||this.props.search&&!a.includes(this.props.search))return null;n=n||0;const i=(this.props.reorder?n:n-1)*w9;let s=null;((d=r.native.data.l||r.native.data.lines)==null?void 0:d.length)>1&&(s=w.jsx(Re,{sx:Tt.itemIconNumber,children:(h=r.native.data.l||r.native.data.lines)==null?void 0:h.length}));const l=w.jsxs(Ev,{sx:{"&.MuiListItemButton-gutters":ue.getStyle(this.props.theme,Tt.noGutters,this.props.selectedId===r._id&&this.props.selectedPresetChanged&&Tt.changed),"&.Mui-selected":Tt.selected,height:48},selected:this.props.selectedId===r._id,style:{paddingLeft:i},className:this.props.reorder?"item-reorder":"",ref:this.props.selectedId===r._id?this.refSelected:null,onClick:()=>this.props.onSelectedChanged(o._id),children:[w.jsxs(ba,{sx:ue.getStyle(this.props.theme,Tt.itemIconRoot,Tt.itemIconPreset),children:[w.jsx(JKt,{style:Tt.itemIcon}),s]}),w.jsx(_o,{sx:{"& .MuiListItemText-primary":Tt.listItemTitle,"& .MuiListItemText-secondary":Tt.listItemSubTitle},primary:w.jsx("div",{style:Tt.listItemTitleDiv,children:ue.getObjectNameFromObj(o,null,{language:P.getLanguage()})}),secondary:ue.getObjectNameFromObj(o,null,{language:P.getLanguage()},!0)}),this.state.changingPreset===o._id?w.jsx(pO,{size:24}):this.props.reorder?null:w.jsxs(w.Fragment,{children:[this.props.selectedId!==o._id||!this.props.selectedPresetChanged?w.jsx(Ie,{size:"small","aria-label":"Rename",title:P.t("Rename"),sx:Tt.textColor,onClick:u=>{u.stopPropagation(),this.setState({renameDialog:o._id,renamePresetDialogTitle:a})},children:w.jsx(JR,{})}):null,w.jsx(Ie,{size:"small","aria-label":"Copy",title:P.t("Copy"),sx:Tt.textColor,onClick:()=>this.props.onCopyPreset(o._id),children:w.jsx(Di,{style:Tt.iconCopy})}),w.jsx(Ie,{size:"small",sx:Tt.textColor,"aria-label":"Delete",title:P.t("Delete"),onClick:()=>this.setState({deletePresetDialog:o._id}),children:w.jsx(yu,{})})]})]},r._id);return this.props.reorder?w.jsx(tnr,{name:r._id,draggableId:r._id,children:l},`draggable_${r._id}`):l}renderFolder(r,n){const o=[];n=n||0;const a=this.props.reorder||(this.state.presetsOpened&&r?this.state.presetsOpened.includes(r.prefix):!1),i=(this.props.reorder?n:n-1)*w9,s=[];if(r&&(a||!r.id)){const l=Object.values(r.presets||{}),d=Object.values(r.subFolders||{});d.sort((h,u)=>h.id>u.id?1:h.id!(Qrr&&h.id===ad)).forEach(h=>s.push(this.renderFolder(h,n+1))),l.length||d.length?l.sort((h,u)=>h._id>u._id?1:h._ids.push(this.renderPreset(h,n+1))):n===0&&s.push(w.jsx(of,{sx:{"&.MuiListItem-gutters":Tt.noGutters},children:w.jsx(_o,{style:Tt.folderItem,children:P.t("No presets created yet")})},"no presets"))}if(r&&(r.id||this.props.reorder)){const l=w.jsxs(of,{sx:{"&.MuiListItem-gutters":Tt.noGutters},className:this.props.reorder?"folder-reorder":"",style:{...Tt.width100,...Tt.folderItem,paddingLeft:i,height:48},secondaryAction:w.jsxs(w.Fragment,{children:[!this.props.reorder&&r&&r.id&&a?w.jsx(Ie,{size:"small",sx:Tt.textColor,onClick:()=>this.props.onCreatePreset(r.id),title:P.t("Create new preset"),children:w.jsx(Il,{})}):null,this.props.reorder?null:w.jsx(Ie,{size:"small",sx:Tt.textColor,onClick:()=>this.setState({editPresetFolderDialog:r,editPresetFolderName:r.id,editFolderDialogTitleOrigin:r.id}),title:P.t("Edit folder name"),children:w.jsx(JR,{})}),this.props.reorder?null:w.jsx(Ie,{size:"small",onClick:()=>this.togglePresetsFolder(r),sx:Tt.textColor,title:a?P.t("Collapse"):P.t("Expand"),children:w.jsx(sf,{style:{transform:a?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease-in-out"}})})]}),children:[w.jsx(ba,{sx:ue.getStyle(this.props.theme,Tt.itemIconRoot,Tt.folderIconPreset),onClick:()=>this.togglePresetsFolder(r),children:a?w.jsx(vf,{style:{...Tt.itemIcon,...Tt.itemIconFolder}}):w.jsx(yf,{style:{...Tt.itemIcon,...Tt.itemIconFolder}})}),w.jsx(_o,{children:r.id||P.t("Root")})]},r.prefix);this.props.reorder?o.push(w.jsx(enr,{droppableId:"tree",name:r.prefix,onDrop:d=>this.onDragFinish(d,`echarts.0${r.prefix?".":""}${r.prefix}`),children:l},`droppable_${r.prefix}`)):o.push(l)}return s.forEach(l=>o.push(l)),o}async renamePresetFolder(r,n){this.setState({changingPreset:r.id});let o;const a=this.state.presetsOpened.indexOf(r.prefix);if(a!==-1){const u=[...this.state.presetsOpened];u.splice(a,1),u.push(n),u.sort(),this.setState({presetsOpened:u})}const i=r.prefix.split(".");i[i.length-1]=n;const s=i.join(".");Object.keys(r.presets).find(u=>u===this.props.selectedId)&&(o=`${this.props.adapterName}.0.${s}.${this.props.selectedId.split(".").pop()}`);const l=Object.keys(r.presets);for(let u=0;u0;u--)d[u]===d[u-1]&&d.splice(u,1)}setTimeout(async()=>{const u=await this.getAllPresets(null,d);this.setState(u,()=>this.props.onSelectedChanged(o))},100)}isNameUnique(r,n){const o=r.split(".").length;return n===ad?!1:!Object.keys(this.state.presets).find(a=>o===a.split(".").length&&this.state.presets[a].common.name===n)}static buildPresetTree(r,n){const o=Object.values(r),a={subFolders:{},presets:{},id:"",prefix:""};return o.forEach(i=>{const s=i._id,l=s.split(".");l.shift(),l.shift();let d=a,h="";for(let u=0;u{const s=i.split(".");let l=a,d="";for(let h=0;h{this.setState({presetFolders:o,presetsOpened:i},()=>s())})}togglePresetsFolder(r){const n=[...this.state.presetsOpened],o=n.indexOf(r.prefix);if(o===-1)n.push(r.prefix);else if(n.splice(o,1),Object.keys(r.presets).includes(this.props.selectedId)){this.props.onSelectedChanged(null,a=>{a!==!1&&(window.localStorage.setItem("App.echarts.presets.opened",JSON.stringify(n)),this.setState({presetsOpened:n}))});return}window.localStorage.setItem("App.echarts.presets.opened",JSON.stringify(n)),this.setState({presetsOpened:n})}renderAddFolderDialog(){return this.props.addPresetFolderDialog?w.jsxs(or,{maxWidth:"md",fullWidth:!0,open:!0,onClose:()=>this.props.onClosePresetFolderDialog(),children:[w.jsx(_r,{children:P.t("Create folder")}),w.jsx(Wr,{style:Tt.p,children:w.jsx(Ht,{variant:"standard",fullWidth:!0,autoFocus:!0,label:P.t("Title"),value:this.state.addPresetFolderName,onChange:r=>this.setState({addPresetFolderName:r.target.value.replace(nE,"_").trim()}),onKeyUp:r=>{this.state.addPresetFolderName&&r.key==="Enter"&&this.state.addPresetFolderName!==ad&&(r.preventDefault(),r.stopPropagation(),this.addFolder(null,this.state.addPresetFolderName).then(()=>this.props.onClosePresetFolderDialog(()=>this.informAboutSubFolders())))}})}),w.jsxs(pr,{style:{...Tt.alignRight,...Tt.buttonsContainer},children:[w.jsx(tt,{variant:"contained",disabled:!this.state.addPresetFolderName||!!Object.keys(this.state.presetFolders&&this.state.presetFolders.subFolders||{}).find(r=>r===this.state.addPresetFolderName)||this.state.addPresetFolderName===ad,onClick:()=>this.addFolder(null,this.state.addPresetFolderName).then(()=>this.props.onClosePresetFolderDialog(()=>this.informAboutSubFolders())),color:"primary",autoFocus:!0,startIcon:w.jsx(sh,{}),children:P.t("Create")}),w.jsx(tt,{color:"grey",variant:"contained",onClick:()=>this.props.onClosePresetFolderDialog(),startIcon:w.jsx(wo,{}),children:P.t("Cancel")})]})]}):null}renderRenameFolderDialog(){if(!this.state.editPresetFolderDialog)return null;const r=!Object.keys(this.state.presetFolders&&this.state.presetFolders.subFolders||{}).find(n=>n===this.state.editPresetFolderName);return w.jsxs(or,{maxWidth:"md",fullWidth:!0,open:!!this.state.editPresetFolderDialog,onClose:()=>this.setState({editPresetFolderDialog:null}),children:[w.jsx(_r,{children:P.t("Edit folder")}),w.jsx(Wr,{children:w.jsx(Ht,{variant:"standard",fullWidth:!0,autoFocus:!0,label:P.t("Title"),value:this.state.editPresetFolderName,onKeyUp:n=>{this.state.editPresetFolderName&&n.key==="Enter"&&this.state.editPresetFolderName!==ad&&this.state.editFolderDialogTitleOrigin!==this.state.editPresetFolderName&&r&&(n.preventDefault(),n.stopPropagation(),this.renamePresetFolder(this.state.editPresetFolderDialog,this.state.editPresetFolderName).then(()=>this.setState({editPresetFolderDialog:null})))},onChange:n=>this.setState({editPresetFolderName:n.target.value.replace(nE,"_").trim()})})}),w.jsxs(pr,{style:{...Tt.alignRight,...Tt.buttonsContainer},children:[w.jsx(tt,{variant:"contained",disabled:!this.state.editPresetFolderName||this.state.editFolderDialogTitleOrigin===this.state.editPresetFolderName||!r||this.state.editPresetFolderName===ad,onClick:()=>{this.renamePresetFolder(this.state.editPresetFolderDialog,this.state.editPresetFolderName).then(()=>this.setState({editPresetFolderDialog:null}))},color:"primary",startIcon:w.jsx(sh,{}),children:P.t("Rename")}),w.jsx(tt,{color:"grey",variant:"contained",onClick:()=>this.setState({editPresetFolderDialog:null}),startIcon:w.jsx(wo,{}),children:P.t("Cancel")})]})]})}renderMoveDialog(){if(!this.state.movePresetDialog)return null;const r=this.state.newPresetFolder==="__root__"?"":this.state.newPresetFolder,n=this.state.movePresetDialog,o=`preset.0.${r}${r?".":""}${n}`,a=!Object.keys(this.state.presets).find(i=>i===o);return w.jsxs(or,{maxWidth:"md",fullWidth:!0,open:!0,onClose:()=>this.setState({movePresetDialog:null}),children:[w.jsx(_r,{children:P.t("Move to folder")}),w.jsx(Wr,{children:w.jsxs(_a,{style:Tt.width100,variant:"standard",children:[w.jsx($l,{shrink:!0,children:P.t("Folder")}),w.jsx(Bn,{variant:"standard",autoFocus:!0,fullWidth:!0,style:Tt.width100,value:this.state.newPresetFolder||"__root__",onChange:i=>this.setState({newPresetFolder:i.target.value}),onKeyUp:i=>{a&&i.which===13&&(i.preventDefault(),i.stopPropagation(),this.setState({movePresetDialog:null},()=>this.addPresetToFolderPrefix(this.state.presets[n],this.state.newPresetFolder==="__root__"?"":this.state.newPresetFolder)))},children:DG(this.state.presetFolders||{}).map(i=>w.jsx(Xt,{value:i.prefix||"__root__",children:i.prefix?i.prefix.replace("."," > "):P.t("Root")},i.prefix))})]})}),w.jsxs(pr,{style:{...Tt.alignRight,...Tt.buttonsContainer},children:[w.jsx(tt,{variant:"contained",disabled:!a,color:"primary",onClick:()=>this.setState({movePresetDialog:null},()=>this.addPresetToFolderPrefix(this.state.presets[n],this.state.newPresetFolder==="__root__"?"":this.state.newPresetFolder)),startIcon:w.jsx(sh,{}),children:P.t("Move to folder")}),w.jsxs(tt,{color:"grey",variant:"contained",onClick:()=>this.setState({movePresetDialog:null}),startIcon:w.jsx(wo,{}),children:[w.jsx(wo,{style:Tt.buttonIcon}),P.t("Cancel")]})]})]},"movePresetDialog")}onError(r,n){n&&console.error(n),this.props.onShowError(r.toString())}async onDragFinish(r,n){let o=`${n}.${r.split(".").pop()}`;if(o!==r){this.state.presets[o]&&(o+=`_${P.t("copy")}`);try{const a=await this.props.socket.getObject(r);if(a)try{await this.props.socket.setObject(o,a),await this.props.socket.delObject(r);const i=await this.getAllPresets();this.setState(i)}catch(i){this.onError(i,`Cannot delete object ${o}`)}}catch(a){this.onError(a,`Cannot read object ${r}`)}}}renderRenameDialog(){if(!this.state.renameDialog)return null;const r=this.state.renameDialog;return w.jsxs(or,{maxWidth:"md",fullWidth:!0,open:!0,onClose:()=>this.setState({renameDialog:null}),children:[w.jsx(_r,{children:P.t("Rename preset")}),w.jsx(Wr,{children:w.jsx(_a,{style:Tt.width100,variant:"standard",children:w.jsx(Ht,{variant:"standard",fullWidth:!0,autoFocus:!0,label:P.t("Name"),value:this.state.renamePresetDialogTitle,onKeyUp:n=>{n.keyCode===13&&this.state.renamePresetDialogTitle&&this.isNameUnique(r,this.state.renamePresetDialogTitle)&&(n.stopPropagation(),n.preventDefault(),this.setState({renameDialog:null},()=>this.renamePreset(r,this.state.renamePresetDialogTitle)))},onChange:n=>this.setState({renamePresetDialogTitle:n.target.value})})})}),w.jsxs(pr,{style:{...Tt.alignRight,...Tt.buttonsContainer},children:[w.jsx(tt,{variant:"contained",disabled:!this.state.renamePresetDialogTitle||!this.isNameUnique(r,this.state.renamePresetDialogTitle),color:"primary",onClick:()=>this.setState({renameDialog:null},()=>this.renamePreset(r,this.state.renamePresetDialogTitle)),startIcon:w.jsx(sh,{}),children:P.t("Rename")}),w.jsx(tt,{color:"grey",variant:"contained",onClick:()=>this.setState({renameDialog:null}),startIcon:w.jsx(wo,{}),children:P.t("Cancel")})]})]},"renameDialog")}renderDeleteDialog(){return this.state.deletePresetDialog?w.jsx(PO,{title:P.t("Please confirm"),text:P.t("Are you sure for delete this preset?"),ok:P.t("Delete"),cancel:P.t("Cancel"),suppressQuestionMinutes:3,dialogName:"echarts.deletePresetDialog",onClose:r=>{r?this.deletePreset(this.state.deletePresetDialog,()=>this.setState({deletePresetDialog:""})):this.setState({deletePresetDialog:""})}},"deletePresetDialog"):null}async deletePreset(r,n){try{await this.props.socket.delObject(r);const o=await this.getAllPresets();this.setState(o,()=>{if(r===this.props.selectedId){const a=Object.keys(this.state.presets);this.props.onSelectedChanged(a[0]||null)}})}catch(o){this.onError(o,`Cannot delete object ${r}`)}n()}async renamePreset(r,n){try{const o=await this.props.socket.getObject(r);o.common.name=n;const a=r.split(".");a.splice(-1,1),a.push(n.replace(nE,"_").trim()),o._id=a.join("."),await this.props.socket.setObject(o._id,o),await this.props.socket.delObject(r);const i=await this.getAllPresets();r===this.props.selectedId?this.setState(i,()=>this.props.onSelectedChanged(o._id)):this.setState(i)}catch(o){this.onError(o,`Cannot get object ${r}`)}}render(){return this.scrollToSelect!==this.props.scrollToSelect&&(this.scrollToSelect=this.props.scrollToSelect,this.scrollToSelect&&!this.scrollTimeout&&(this.scrollTimeout=setTimeout(()=>{var r;this.scrollTimeout=null,(r=this.refSelected.current)==null||r.scrollIntoView({behavior:"auto",block:"center",inline:"center"})},100))),w.jsxs(w.Fragment,{children:[w.jsx(arr,{backend:Zrr,children:w.jsx(vu,{sx:{...Tt.scroll,...Tt.mainList},children:this.renderFolder(this.state.presetFolders)})}),this.renderAddFolderDialog(),this.renderRenameFolderDialog(),this.renderDeleteDialog(),this.renderMoveDialog(),this.renderRenameDialog()]})}}const rnr=qs()(oy);function nnr(t){return Pr({tag:"svg",attr:{viewBox:"0 0 1024 1024"},child:[{tag:"path",attr:{d:"M888 792H200V168c0-4.4-3.6-8-8-8h-56c-4.4 0-8 3.6-8 8v688c0 4.4 3.6 8 8 8h752c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm-616-64h536c4.4 0 8-3.6 8-8V284c0-7.2-8.7-10.7-13.7-5.7L592 488.6l-125.4-124a8.03 8.03 0 0 0-11.3 0l-189 189.6a7.87 7.87 0 0 0-2.3 5.6V720c0 4.4 3.6 8 8 8z"},child:[]}]})(t)}const x9=34,id=20,S9=30,Zp=15;class AG extends A.Component{render(){const e=w.jsxs("div",{style:{width:this.props.size==="small"?S9:x9,height:id,display:"flex",alignItems:"center",cursor:"pointer",position:"relative",opacity:this.props.disabled?.7:1},onClick:r=>{this.props.disabled||(r.stopPropagation(),r.preventDefault(),this.props.onChange(!this.props.checked))},children:[w.jsx("div",{style:{borderRadius:15,width:"100%",height:(this.props.size==="small"?Zp:id)*.7,opacity:.6,backgroundColor:this.props.checked?this.props.theme.palette.primary.main:this.props.theme.palette.text.disabled}}),w.jsx("div",{style:{position:"absolute",top:this.props.size==="small"?(id-Zp)/2:0,left:this.props.checked?this.props.size==="small"?S9-Zp:x9-id:0,transition:"left 0.2s",borderRadius:50,width:this.props.size==="small"?Zp:id,height:this.props.size==="small"?Zp:id,backgroundColor:this.props.checked?this.props.theme.palette.primary.main:"#EEE",boxShadow:"rgba(0, 0, 0, 0.2) 0px 2px 1px -1px, rgba(0, 0, 0, 0.14) 0px 1px 1px 0px, rgba(0, 0, 0, 0.12) 0px 1px 3px 0px"}})]});return this.props.labelOn||this.props.labelOff?w.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[this.props.labelOff,e,this.props.labelOn]}):e}}function C9(t,e){const r=typeof t=="object"?t._id.replace("system.adapter.",""):t.replace("system.adapter.",""),n=typeof e=="object"?e._id.replace("system.adapter.",""):e.replace("system.adapter.","");return r>n?1:r{t[n].common.members.includes(e)&&!r.includes(n)&&r.push(n)}),r}const $9=16,Vt={noGutters:{paddingTop:0,paddingBottom:0,paddingLeft:0,width:"100%"},itemIconFolder:{cursor:"pointer",marginLeft:8},width100:{width:"100%"},itemIcon:{width:32,height:32,marginRight:4},itemIconRoot:{minWidth:24},itemNameDiv:{marginTop:5},itemName:{verticalAlign:"top",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",width:"calc(100% - 26px)",display:"inline-block"},itemName0:{},itemName1:{fontSize:14,opacity:.6},itemName2:{fontSize:12,opacity:.6},itemName3:{fontSize:10,opacity:.6},itemName4:{fontSize:8,opacity:.6},itemName5:{fontSize:6,opacity:.6},groupName:{verticalAlign:"top",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",width:"calc(100% - 66px)",display:"inline-block"},itemSecondaryName:{overflow:"hidden",textOverflow:"ellipsis",width:"100%",fontSize:"smaller",opacity:.6,fontStyle:"italic",whiteSpace:"nowrap",display:"inline-block"},listItemSubTitle:{fontSize:"smaller",opacity:.6,fontStyle:"italic"},adapterIcon:{width:20,height:20,borderRadius:2,marginRight:4},mainList:{width:"100%"},listItemSecondaryAction:{marginRight:4},folderItem:t=>({backgroundColor:t.palette.secondary.main,pl:"8px"}),selected:t=>({backgroundColor:t.palette.mode==="dark"?"rgba(77, 171, 245, 0.16)":t.palette.primary.light,"&:hover":{backgroundColor:t.palette.mode==="dark"?"rgba(77, 171, 245, 0.10)":"#76d0fd80"}})};class anr extends A.Component{constructor(r){super(r);X(this,"refSelected");X(this,"scrollToSelect",!1);X(this,"adapterPromises",{});X(this,"toggleChartFolder",r=>{const n=JSON.parse(JSON.stringify(this.state.chartsOpened));n[r]=!n[r],window.localStorage.setItem("App.echarts.opened",JSON.stringify(n));const o={chartsOpened:n};if(!n[r]){const a=r.split("///")[0];this.props.selectedId&&typeof this.props.selectedId=="object"&&this.props.selectedId.instance}this.setState(o,()=>this.props.onSelectedChanged(null))});let n;try{n=JSON.parse(window.localStorage.getItem("App.echarts.opened"))||{}}catch{n={}}this.state={instances:[],chartsOpened:n,enums:null,showAddStateDialog:""},this.refSelected=m.createRef(),this.getAllEnums().then(o=>this.getAllCharts(o)).then(o=>this.setState(o,()=>this.props.selectedId&&this.props.onSelectedChanged(this.props.selectedId)))}UNSAFE_componentWillReceiveProps(r){r.scrollToSelect!==this.scrollToSelect&&(this.scrollToSelect=r.scrollToSelect,this.scrollToSelect&&setTimeout(()=>{var n;(n=this.refSelected.current)==null||n.scrollIntoView({behavior:"auto",block:"center",inline:"center"})},100))}async getAllEnums(r){r=r||{};try{const n=await this.props.socket.getEnums();return r.enums={},Object.keys(n).forEach(o=>{var a,i,s;(o.startsWith("enum.functions.")||o.startsWith("enum.rooms."))&&((s=(i=(a=n[o])==null?void 0:a.common)==null?void 0:i.members)!=null&&s.length)&&(r.enums[o]={_id:o,common:{members:[...n[o].common.members],name:ue.getObjectNameFromObj(n[o],null,{language:P.getLanguage()})},type:"enum",native:{}})}),r}catch(n){return this.onError(n,"Cannot read enums"),{}}}async getAdapterIcon(r){var a;const n=r.split(".");if(n.length<2||n[0]==="0_userdata")return null;let o;n[0]==="system"?(n.splice(4),o=n.join(".")):(n.splice(2),o=`system.adapter.${n.join(".")}`),this.adapterPromises[o]instanceof Promise||(this.adapterPromises[o]=this.props.socket.getObject(o));try{const i=await this.adapterPromises[o];if((a=i==null?void 0:i.common)!=null&&a.icon)return ue.getObjectIcon(i)}catch(i){this.onError(i,`Cannot read object ${o}`)}return null}onError(r,n){n&&console.error(n),this.props.onShowError(r.toString())}async getChartIconAndName(r,n){let o;const a=[];if(!n)return null;const i=P.getLanguage(),s=n._id;n.common&&(n.common.icon&&(o=ue.getObjectIcon(n)),a.push(ue.getObjectNameFromObj(n,null,{language:i})));const l=ue.getParentId(n._id);if((l==null?void 0:l.split(".").length)>2)try{const d=await this.props.socket.getObject(l);if(d&&(d.type==="channel"||d.type==="device")&&d.common){!o&&d.common.icon&&(o=ue.getObjectIcon(d)),a.push(ue.getObjectNameFromObj(d,null,{language:i}));const h=ue.getParentId(l);if((h==null?void 0:h.split(".").length)>2){const u=await this.props.socket.getObject(h);if(u&&(u.type==="channel"||u.type==="device")&&u.common){!o&&u.common.icon&&(o=ue.getObjectIcon(u)),a.push(ue.getObjectNameFromObj(u,null,{language:i}));const f=ue.getParentId(h);if((f==null?void 0:f.split(".").length)>2){const g=await this.props.socket.getObject(f);g&&(g.type==="channel"||g.type==="device")&&g.common&&(!o&&g.common.icon&&(o=ue.getObjectIcon(g)),a.push(ue.getObjectNameFromObj(g,null,{language:i})))}}}}}catch(d){console.error(`Cannot read object: ${d}`)}return o=o||await this.getAdapterIcon(s),{groupId:r,id:s,img:o,name:a.filter(d=>d)}}async getAllCharts(r){r=r||{};const n=this.props.instances.map(u=>u._id.substring(15)),o=await this.props.socket.getObjectViewSystem("custom-full","",""),a={};r.enums=r.enums||this.state.enums;const i=[];Object.values(o).forEach(u=>{const f=n.find(g=>Object.keys(u.common.custom).includes(g));if(f){const g=this.props.instances.find(y=>y._id.endsWith(f));a[f]=a[f]||{_id:`system.adapter.${f}`,enabledDP:{},names:{},statesEnums:{},icon:g.common.icon,name:g.common.name||"",types:{},icons:{}},a[f].enabledDP[u._id]=u,a[f].names[u._id]=ue.getObjectNameFromObj(u,null,{language:P.getLanguage()}),a[f].types[u._id]=u.common.type==="boolean"?"boolean":"number",a[f].statesEnums[u._id]=onr(r.enums,u._id),i.push(this.getChartIconAndName(f,u))}});const s=JSON.parse(JSON.stringify(this.state.chartsOpened)),l=Object.keys(r.enums).filter(u=>u.startsWith("enum.functions.")),d=Object.keys(r.enums).filter(u=>u.startsWith("enum.rooms.")),h=Object.values(a).map(u=>{var b;const f={};Object.keys(u.enabledDP).forEach(x=>{f[x]=u.enabledDP[x],f[x].group=u._id}),u.enabledDP=f,s[u._id]=s[u._id]!==void 0?this.state.chartsOpened[u._id]||!1:!0,Object.keys(r.enums).forEach(x=>{Object.keys(f).find(S=>r.enums[x].common.members.includes(S))&&(u.enums=u.enums||[],u.enums.includes(x)||u.enums.push(x))});const g={_id:`enum.functions.${u._id}`,type:"enum",common:{members:[],name:P.t("Others")},native:{}},y={_id:`enum.rooms.${u._id}`,type:"enum",common:{members:[],name:P.t("Others")},native:{}};return Object.keys(f).forEach(x=>{l.find(S=>r.enums[S].common.members.includes(x))||g.common.members.push(x),d.find(S=>r.enums[S].common.members.includes(x))||y.common.members.push(x)}),g.common.members.length&&(u.enums=u.enums||[],u.enums.push(`enum.functions.${u._id}`),r.enums[`enum.functions.${u._id}`]=g),y.common.members.length&&(u.enums=u.enums||[],u.enums.push(`enum.rooms.${u._id}`),r.enums[`enum.rooms.${u._id}`]=y),(b=u.enums)==null||b.sort((x,S)=>r.enums[x].common.name>r.enums[S].common.name?1:r.enums[x].common.namethis.props.onSelectedChanged({id:u,instance:h[0]._id}),500)}return r.instances=h,r.chartsOpened=s,setTimeout(()=>{Promise.all(i).then(u=>{const f=JSON.parse(JSON.stringify(this.state.instances));let g=!1;u.forEach(y=>{if(y!=null&&y.groupId){const b=f.find(x=>x._id===`system.adapter.${y.groupId}`);b&&(y.img&&(b.icons[y.id]=y.img),y.name&&(b.names[y.id]=y.name),g=!0)}}),g&&this.setState({instances:f})})},100),r}renderSelectIdDialog(){return this.state.showAddStateDialog?w.jsx(OV,{theme:this.props.theme,imagePrefix:"../..",socket:this.props.socket,dialogName:"Add",title:P.t("Enable logging for state"),onOk:r=>{const n=Array.isArray(r)?r[0]:r;console.log(`Selected ${JSON.stringify(n)}`);const o=this.state.showAddStateDialog.replace("system.adapter.","");n&&this.props.socket.getObject(n).then(a=>{var i;if(!(a!=null&&a.common)){this.props.onShowError(P.t("Invalid object"));return}if((i=a.common.custom)!=null&&i[o]){this.props.onShowToast(P.t("Already enabled"));return}a.common.custom=a.common.custom||{},a.common.custom[o]={enabled:!0},this.props.socket.setObject(n,a).then(()=>{const s=JSON.parse(JSON.stringify(this.state.instances)),l=s.find(d=>d._id===`system.adapter.${o}`);l.enabledDP=l.enabledDP||{},l.enabledDP[a._id]=a,this.setState({instances:s},()=>this.getAllCharts())}).catch(s=>this.onError(s,`Cannot read object ${n}`))}).catch(a=>this.onError(a,`Cannot read object ${n}`)),this.setState({showAddStateDialog:""})},onClose:()=>this.setState({showAddStateDialog:""})},"selectDialog_add"):null}renderListItem(r,n,o,a){a=a||0;const i=r._id,s=this.props.selectedId&&typeof this.props.selectedId=="object"&&this.props.selectedId.id===n&&this.props.selectedId.instance===i;let l;if(typeof r.names[n]=="object"){const d=[...r.names[n]];l=w.jsx("span",{style:Vt.itemName,title:d.join(" / "),children:d.map((h,u)=>w.jsx("span",{style:Vt[`itemName${u}`],children:(u?" / ":"")+h},u))})}else{const d=(r.names[n]||"").toString();l=w.jsx("span",{style:Vt.itemName,title:d,children:d})}return w.jsxs(Ev,{ref:s?this.refSelected:null,sx:{"&.MuiListItemButton-gutters":Vt.noGutters,"&.Mui-selected":Vt.selected},style:{paddingLeft:$9*a,height:48,position:"relative"},selected:s,onClick:o?void 0:()=>this.props.onSelectedChanged({id:n,instance:i}),children:[w.jsx(ba,{style:Vt.itemIconRoot,children:r.types[n]==="boolean"?w.jsx(YKt,{style:Vt.itemIcon}):w.jsx(nnr,{style:Vt.itemIcon})}),w.jsxs("div",{style:{flexGrow:1,overflow:"hidden"},children:[w.jsxs("div",{style:Vt.itemNameDiv,children:[ue.getIcon({icon:r.icons[n],prefix:"../../"},{width:20,height:20,borderRadius:2,marginRight:4}),l]}),w.jsx("div",{style:Vt.itemSecondaryName,title:n,children:n.replace("system.adapter.","")})]}),!o&&this.props.multiple&&this.props.chartsList?w.jsxs("div",{style:Vt.listItemSecondaryAction,children:[w.jsx(AG,{size:"small",theme:this.props.theme,onChange:d=>{const h=JSON.parse(JSON.stringify(this.props.chartsList)),u=h.find(f=>f.id===n&&f.instance===i);d&&!u?(h.push({id:n,instance:i}),h.sort((f,g)=>f.instance>g.instance?1:f.instanceg.id?1:f.idthis.props.onChangeList(h)):this.props.onChangeList(h)):!d&&u&&(h.splice(h.indexOf(u),1),this.props.onChangeList(h))},checked:!!this.props.chartsList.find(d=>d.id===n&&d.instance===i)})," "]}):null]},`${i}_${n}`)}renderListItems(r,n,o,a){if(a.gIndex=a.gIndex||0,!(n!=null&&n.length))return null;const i=r._id,s=1;if(!o)return n.map(f=>w.jsx(EE,{isDragDisabled:!this.props.selectedId||typeof this.props.selectedId=="object",draggableId:`${i}***${f}`,index:a.gIndex++,children:(g,y)=>w.jsxs(w.Fragment,{children:[w.jsx("div",{ref:g.innerRef,...g.draggableProps,...g.dragHandleProps,style:g.draggableProps.style,className:"drag-items",children:this.renderListItem(r,f,!1,s)},`${i}_${f}_item`),y.isDragging?w.jsx("div",{className:"react-beautiful-dnd-copy",children:this.renderListItem(r,f,!0)},`${i}_${f}_dnd`):null]})},`${i}_${f}`));const l=`${i}///${o}`,d=this.state.chartsOpened[l];d&&(n=n.filter(f=>this.state.enums[o].common.members.includes(f)));const h=this.state.enums[o].common.name,u=typeof h=="object"?h[P.getLanguage()]||h.en:h;return[w.jsxs(of,{style:{...Vt.width100,paddingLeft:$9*s,height:48},sx:ue.getStyle(this.props.theme,Vt.folderItem,{"&.MuiListItem-gutters":Vt.noGutters}),secondaryAction:w.jsx(Ie,{size:"small",onClick:()=>this.toggleChartFolder(l),title:d?P.t("Collapse"):P.t("Expand"),children:w.jsx(sf,{style:{transform:d?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease-in-out"}})}),children:[w.jsx(ba,{style:Vt.itemIconRoot,onClick:()=>this.toggleChartFolder(l),children:d?w.jsx(vf,{style:{...Vt.itemIcon,...Vt.itemIconFolder}}):w.jsx(yf,{style:{...Vt.itemIcon,...Vt.itemIconFolder}})}),w.jsx(_o,{primary:u})]},l),d?w.jsx(vu,{children:n.map(f=>w.jsx(EE,{isDragDisabled:!this.props.selectedId||typeof this.props.selectedId=="object",draggableId:`${i}***${f}`,index:a.gIndex++,children:(g,y)=>w.jsxs(w.Fragment,{children:[w.jsx("div",{ref:g.innerRef,...g.draggableProps,...g.dragHandleProps,style:g.draggableProps.style,className:"drag-items",children:this.renderListItem(r,f,!1,2)},`${i}_${f}_item`),y.isDragging?w.jsx("div",{className:"react-beautiful-dnd-copy",children:this.renderListItem(r,f,!0)},`${i}_${f}_dnd`):null]})},`${i}_${f}`))},`${l}_LIST`):null]}render(){const r={gIndex:0};return w.jsxs(w.Fragment,{children:[this.renderSelectIdDialog(),w.jsx(QT,{droppableId:"Lines",isDropDisabled:!0,children:n=>w.jsx("div",{ref:n.innerRef,children:w.jsx(vu,{style:{...Vt.scroll,...Vt.mainList},children:w.jsxs(w.Fragment,{children:[this.state.instances.map(o=>{const a=this.state.chartsOpened[o._id];let i=null;if(a){const s=Object.keys(o.enabledDP).filter(l=>!this.props.search||l.includes(this.props.search)||o.names[l].includes(this.props.search));this.props.groupBy?i=(o.enums||[]).filter(l=>l.startsWith(`enum.${this.props.groupBy}.`)).map(l=>this.renderListItems(o,s,l,r)):(s.sort(C9),i=this.renderListItems(o,s,null,r))}return[w.jsxs(of,{sx:ue.getStyle(this.props.theme,Vt.width100,Vt.folderItem,{height:48,color:this.props.theme.palette.mode==="dark"?void 0:"#FFF"},{"&.MuiListItem-gutters":Vt.noGutters}),secondaryAction:w.jsxs(w.Fragment,{children:[a?w.jsx(Ie,{size:"small",onClick:()=>this.setState({showAddStateDialog:o._id}),style:{color:this.props.theme.palette.mode==="dark"?void 0:"#FFF"},title:P.t("Enable logging for new state"),children:w.jsx(Il,{})}):null,w.jsx(Ie,{size:"small",onClick:()=>this.toggleChartFolder(o._id),title:a?P.t("Collapse"):P.t("Expand"),style:{color:this.props.theme.palette.mode==="dark"?void 0:"#FFF"},children:w.jsx(sf,{style:{transform:a?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease-in-out"}})})]}),children:[w.jsx(ba,{style:Vt.itemIconRoot,sx:{color:this.props.theme.palette.mode==="dark"?void 0:"#FFF"},onClick:()=>this.toggleChartFolder(o._id),children:a?w.jsx(vf,{style:{...Vt.itemIcon,...Vt.itemIconFolder}}):w.jsx(yf,{style:{...Vt.itemIcon,...Vt.itemIconFolder}})}),w.jsx(_o,{primary:w.jsxs("div",{style:Vt.itemNameDiv,children:[w.jsx("img",{style:Vt.adapterIcon,alt:"",src:`../../adapter/${o.name}/${o.icon}`}),w.jsx("div",{style:Vt.groupName,children:o._id.replace("system.adapter.","")})]})})]},o._id),i]}),n.placeholder]})},"chartList")},"chartListDiv")},"charts")]})}}const inr=qs()(anr),k9=48,Fo={mainListDiv:{width:"100%",height:"100%",overflow:"hidden"},mainToolbar:t=>({background:t.palette.primary.main}),secondaryColors:t=>({background:"#888",color:t.palette.mode==="dark"?"#000":"#FFF"}),smallMargin:{marginTop:"8px !important"},heightMinusTwoToolbars:{height:`calc(100% - ${k9*2}px)`,overflow:"auto"},heightMinusToolbar:{height:`calc(100% - ${k9}px)`,overflow:"auto"},textColor:t=>({color:t.palette.mode==="dark"?"#000 !important":"#FFF !important"})};class snr extends A.Component{constructor(r){super(r);X(this,"isIFrame");this.state={search:null,multiple:window.localStorage.getItem("App.echarts.multiple")==="true",showSearch:!1,groupBy:window.localStorage.getItem("App.echarts.groupBy")||"",addPresetFolderDialog:!1,reorder:!1,showReorder:!1};try{this.isIFrame=window.self!==window.top}catch{this.isIFrame=!0}if(this.state.multiple){const n=window.localStorage.getItem("App.echarts.chartList")||"[]";let o;try{o=JSON.parse(n)}catch{o=[]}setTimeout(()=>this.props.onChangeList(o),100)}}renderListToolbar(){return w.jsxs(af,{variant:"dense",sx:Fo.mainToolbar,children:[this.state.reorder?null:w.jsx(Ie,{onClick:()=>this.props.onCreatePreset(!1),title:P.t("Create new preset"),children:w.jsx(Il,{})}),this.state.reorder?null:w.jsx(Ie,{onClick:()=>this.setState({addPresetFolderDialog:!0}),title:P.t("Create new folder"),children:w.jsx(Fpe,{})}),this.state.reorder?null:w.jsx("span",{style:Fo.right,children:w.jsx(Ie,{onClick:()=>this.setState({showSearch:!this.state.showSearch,search:""}),children:w.jsx(Nve,{})})}),this.state.showSearch?w.jsx(Ht,{variant:"standard",value:this.state.search,style:Fo.textInput,onChange:r=>this.setState({search:r.target.value}),InputProps:{endAdornment:this.state.search?w.jsx(Ie,{onClick:()=>this.setState({search:""}),children:w.jsx(Ar,{})}):void 0}}):null,w.jsx("div",{style:{flexGrow:1}}),!this.state.showSearch&&this.state.showReorder||this.state.reorder?w.jsx(Ie,{title:P.t("Reorder presets in folders"),style:{color:this.state.reorder?"red":"inherit",float:"right"},onClick:r=>{r.stopPropagation(),this.setState({reorder:!this.state.reorder})},children:w.jsx(zpe,{})},"reorder"):null,!this.state.showSearch&&this.isIFrame?w.jsx(Ie,{onClick:()=>window.open(window.location.href,"own-echarts"),title:P.t("Open in own window"),children:w.jsx(hH,{})}):null]},"toolbar")}renderFooter(){return w.jsxs(af,{variant:"dense",sx:Fo.secondaryColors,style:{gap:8},children:[this.props.selectedPresetChanged?null:w.jsx(AG,{style:{width:58},checked:this.state.multiple,theme:this.props.theme,onChange:r=>{if(window.localStorage.setItem("App.echarts.multiple",r?"true":"false"),r){const n=this.props.selectedId;n&&typeof n=="object"?this.setState({multiple:!0},()=>this.props.onChangeList([JSON.parse(JSON.stringify(n))])):this.setState({multiple:!0},()=>this.props.onChangeList([]))}else this.setState({multiple:!1},()=>this.props.onChangeList(null))},labelOn:P.t("Multiple")}),w.jsxs(_a,{variant:"standard",style:{minWidth:100},sx:Fo.textColor,children:[w.jsx($l,{shrink:!0,sx:Fo.textColor,style:{whiteSpace:"nowrap",top:5},children:P.t("Group by")}),w.jsxs(Bn,{variant:"standard",label:P.t("Group by"),sx:Fo.textColor,onChange:r=>{window.localStorage.setItem("App.echarts.groupBy",r.target.value),this.setState({groupBy:r.target.value})},value:this.state.groupBy||"",style:Fo.smallMargin,displayEmpty:!0,children:[w.jsx(Xt,{value:"",children:P.t("None")}),w.jsx(Xt,{value:"rooms",children:P.t("Rooms")}),w.jsx(Xt,{value:"functions",children:P.t("Functions")})]})]}),w.jsx("div",{style:{flex:1}}),w.jsx(Ie,{size:"small",sx:Fo.textColor,title:P.t("Charts preview"),onClick:()=>{const r=window.location.pathname.split("/");r.pop(),r.push("preview/index.html"),window.location.href=`${window.location.protocol}//${window.location.host}${r.join("/")}`},children:w.jsx(Mve,{})})]},"toolbarBottom")}render(){return w.jsxs("div",{style:Fo.mainListDiv,children:[this.renderListToolbar(),w.jsxs("div",{style:this.state.reorder?Fo.heightMinusToolbar:Fo.heightMinusTwoToolbars,children:[w.jsx(rnr,{socket:this.props.socket,scrollToSelect:this.props.scrollToSelect,addPresetFolderDialog:this.state.addPresetFolderDialog,onClosePresetFolderDialog:r=>this.setState({addPresetFolderDialog:!1},r),onCreatePreset:(r,n)=>this.props.onCreatePreset(r,n),onCopyPreset:r=>this.props.onCopyPreset(r),adapterName:this.props.adapterName,selectedPresetChanged:this.props.selectedPresetChanged,onShowToast:r=>this.props.onShowToast(r),onShowError:r=>this.props.onShowToast(r),onShowReorder:r=>{r!==this.props.showReorder&&this.setState({showReorder:r})},theme:this.props.theme,search:this.state.search,reorder:this.state.reorder,selectedId:this.props.selectedId,systemConfig:this.props.systemConfig,onSelectedChanged:(r,n)=>this.props.onSelectedChanged(r,n)}),this.state.reorder?null:w.jsx(inr,{socket:this.props.socket,scrollToSelect:this.props.scrollToSelect,instances:this.props.instances,adapterName:this.props.adapterName,onShowToast:r=>this.props.onShowToast(r),onShowError:r=>this.props.onShowToast(r),search:this.state.search,multiple:this.state.multiple&&!this.props.selectedPresetChanged,theme:this.props.theme,groupBy:this.state.groupBy,selectedId:this.props.selectedId,onChangeList:r=>{window.localStorage.setItem("App.echarts.chartList",JSON.stringify(r)),this.props.onChangeList(r)},chartsList:this.props.chartsList,onSelectedChanged:(r,n)=>this.props.onSelectedChanged(r,n)})]}),this.state.reorder?null:this.renderFooter()]},"mainMenuDiv")}}const lnr=qs()(snr);function cnr(t,e){const r={};return t.replace(/\+/g," ").split("&").forEach(n=>{const o=n.split("=");let a=decodeURIComponent(o[0]),i,s=0,l=a.split("]["),d=l.length-1;if(/\[/.test(l[0])&&/]$/.test(l[d])?(l[d]=l[d].replace(/]$/,""),l=l.shift().split("[").concat(l),d=l.length-1):d=0,o.length===2)if(i=decodeURIComponent(o[1]),d){let h=r;for(;s<=d;s++)a=l[s]===""?h.length:l[s],h=h[a]=s{const a=$h(t,e,o);a&&a.then(()=>{})});if(!e||!e.length)return r(),null;const n=e.shift();return n?t.getObject(n._id).catch(()=>null).then(o=>{o?(console.log(`Object ${n._id} already exists and will not be converted`),setTimeout(()=>$h(t,e,r),50)):t.setObject(n._id,n).then(()=>setTimeout(()=>$h(t,e,r),50))}):setTimeout(()=>$h(t,e,r),50),null}function pnr(t,e){const r={_id:t._id.replace(/^flot.\d+/,`echarts.${e}`),common:{name:t.common.name,expert:!0},native:{},type:"chart"};r._id.endsWith(".")&&(r._id=`empty_${Math.round(Math.random()*1e4)}`);const n=dnr(cnr(t.native.url));return n.lines||(n.lines=n.l,delete n.l),r.native.data=n,console.log(`Convert ${t._id} => ${r._id}`),r}function hnr(t,e){e=e||0;let r;return t.getObject(`system.adapter.echarts.${e}`).then(n=>(r=n,n&&n.native&&!n.native.convertDone?unr(t):Promise.resolve([]))).then(n=>$h(t,n.map(o=>pnr(o,e)))).then(()=>r.native.convertDone?Promise.resolve():(r.native.convertDone=!0,t.setObject(r._id,r))).catch(n=>(console.error(`Cannot convert flot: ${n}`),Promise.resolve()))}const Qp={root:t=>({width:"100%",height:"100%",background:t.palette.background.default,color:t.palette.mode==="dark"?"#FFF":"#000",fontFamily:'"Roboto", "Helvetica", "Arial", sans-serif'}),menuDiv:{overflow:"hidden"},content:t=>({width:"100%",height:"100%",backgroundColor:t.palette.background.default,position:"relative"}),menuDivWithoutMenu:{"&>div:first-child":{display:"none"},"&>.layout-splitter":{display:"none"}},progress:{margin:100},menuOpenCloseButton:t=>({position:"absolute",left:0,borderRadius:"0 5px 5px 0",top:6,pt:"8px",cursor:"pointer",zIndex:1,height:25,width:20,background:t.palette.secondary.main,color:t.palette.primary.main,pl:"3px","&:hover":{color:"white"}}),buttonsContainer:{"& button":{whiteSpace:"nowrap"}}},E9=/[.\][*,;'"`<>\\?]/g;function T9(t,e){const r=window.localStorage.getItem(`App.echarts.__${t}`);return r?parseFloat(r):e}function eh(t,e){return window.localStorage.getItem(`App.echarts.__${t}`)||e}function sd(t,e){return window.localStorage.getItem(`App.echarts.__${t}`)||e}function O9(){if(window.location.hash){const t={};return window.location.hash.replace(/^#/,"").split("&").forEach(e=>{const[r,n]=e.split("=");t[r]=window.decodeURIComponent(n),r==="instance"&&!t[r].startsWith("system.adapter")&&(t[r]=`system.adapter.${t[r]}`)}),t}return null}class ay extends ys{constructor(r){const n={socket:{}},o=Her();n.socket.port=o.port||(parseInt(window.location.port)>=3e3&&parseInt(window.location.port)<=3020?8081:window.location.port),n.socket.host=o.host||window.location.hostname,n.translations={en:gwt,de:_Ct,ru:xEt,pt:$Ot,nl:TIt,fr:ANt,it:P3t,es:jLt,pl:F6t,uk:H9t,"zh-cn":qHt},n.sentryDSN=window.sentryDSN,window.location.port==="3000"&&(n.socket={port:"8081"}),window.socketUrl&&window.socketUrl.startsWith(":")&&(window.socketUrl=`${window.location.protocol}//${window.location.hostname}${window.socketUrl}`);super(r,n);X(this,"config");X(this,"objects",{});X(this,"confirmCB",null);X(this,"onCopyPreset",async r=>{try{const n=await this.socket.getObject(r);if(n){const{id:o,name:a}=await this.getUniqueId(r,typeof n.common.name=="object"?n.common.name[P.getLanguage()]||n.common.name.en:n.common.name);n._id=o,n.common.name=a;try{await this.socket.setObject(n._id,n),this.loadChartOrPreset(o)}catch(i){this.onError(i,"Cannot save object")}}}catch(n){this.onError(n,"Cannot save object")}});X(this,"onCreatePreset",async(r,n)=>{var i;let o,a;if(r===!0){let s="";const l=this.state.selectedId,d=JSON.parse(JSON.stringify(this.state.chartsList||[]));d.find(f=>f.id===l.id&&f.instance===l.instance)||d.push(l);let h=null;d.length===1&&(h=await this.socket.getObject(d[0].id)),h&&((i=h==null?void 0:h.common)!=null&&i.name)&&(s=typeof h.common.name=="object"?(h.common.name[P.getLanguage()]||h.common.name.en||"").trim():h.common.name);const u=await this.getNewPresetName(n,s);a=`${this.adapterName}.0.${n?`${n}.`:""}${s.replace(E9,"_")}`,o={_id:a,common:{name:u,expert:!0},native:{data:JSON.parse(JSON.stringify(this.state.presetData))},type:"chart"}}else{const s=await this.getNewPresetName(n);a=`${this.adapterName}.0.${n?`${n}.`:""}${s.replace(E9,"_")}`,o={_id:a,common:{name:s},native:{url:"",data:G2(this.state.systemConfig,null,null,P.getLanguage())},type:"chart"}}try{await this.socket.setObject(a,o),this.loadChartOrPreset(a)}catch(s){this.onError(s,"Cannot save object")}});X(this,"savePreset",async()=>{if(!this.state.presetData)throw this.showError(P.t("Empty preset cannot be saved!")),new Error(P.t("Empty preset cannot be saved!"));try{const r=await this.socket.getObject(this.state.selectedId);if(!(r!=null&&r.native)){this.showError(P.t("Invalid object"));return}r.native.data=this.state.presetData;try{await this.socket.setObject(r._id,r)}catch(n){this.onError(n,"Cannot save object")}this.setState({originalPresetData:JSON.stringify(this.state.presetData),selectedPresetChanged:!1})}catch(r){this.onError(r,"Cannot read object")}});X(this,"onDragEnd",async r=>{const{source:n,destination:o,draggableId:a}=r;if(o&&a.includes("***")&&n.droppableId==="Lines"){const[i,s]=a.split("***");try{const l=await this.socket.getObject(s),d=JSON.parse(JSON.stringify(this.state.presetData)),h=Lh(this.state.systemConfig,i,l,P.getLanguage());for(let u=0;u=o.index&&(d.l[u].commonYAxis=d.l[u].commonYAxis+1);if(d.l.splice(o.index,0,h),d.l.length>1){if(h.unit){for(let u=0;uu.chartType==="bar")?h.chartType="bar":d.l.find(u=>u.chartType==="polar")&&(h.chartType="polar",h.aggregate="current")}this.setState({presetData:d,selectedPresetChanged:JSON.stringify(d)!==this.state.originalPresetData})}catch(l){this.onError(l,"Cannot read object")}}else if(o&&n.droppableId===o.droppableId){const i=JSON.parse(JSON.stringify(this.state.presetData));for(let l=0;lthis.setState({scrollToSelect:!0},()=>this.setState({scrollToSelect:!1})))}async onConnectionReady(){var h,u,f;const r=window.localStorage.getItem("App.echarts.selectedId");let n;if(r)try{n=JSON.parse(r)}catch{n=null}!n&&((h=this.config)!=null&&h.preset)?n=this.config.preset:!n&&((u=this.config)!=null&&u.id)&&(n={id:this.config.id,instance:this.config.instance});const o=window.localStorage.getItem("App.echarts.settingsSizes");let a=[25,75];if(o)try{a=JSON.parse(o)}catch{}a=a||[25,75];const i=window.localStorage.getItem("App.echarts.menuSizes");let s=[25,75];if(i)try{s=JSON.parse(i)}catch{}s=s||[25,75];const l={ready:!1,instances:[],splitSizes:a,menuSizes:s,selectedId:n,selectedPresetChanged:!1,presetData:null,originalPresetData:null,chartsList:null,progress:0,autoSave:window.localStorage.getItem("App.echarts.autoSave")==="true",discardChangesConfirmDialog:!1,resizing:!1,menuOpened:window.localStorage.getItem("App.echarts.menuOpened")!=="false",logHorzLayout:window.localStorage.getItem("App.echarts.logHorzLayout")==="true"};this.objects={};const d=await this.socket.getSystemConfig();if(l.systemConfig=d,l.presetData=G2(d),(f=this.config)!=null&&f.id){const g=this.config;l.selectedId={id:g.id,instance:g.instance},g.menuOpened!==void 0&&(l.menuOpened=g.menuOpened===!0),this.config=null}this.setState(l,async()=>{hnr(this.socket,this.instance);try{const y=(await this.socket.getAdapterInstances("")).filter(b=>{var x;return((x=b==null?void 0:b.common)==null?void 0:x.getHistory)&&b.common.enabled});this.setState({ready:!0,instances:y})}catch(g){this.onError(g,"Cannot read system config")}})}async getNewPresetName(r,n,o){o=o||(n?"":"1"),n=n||"preset_";let a;do{try{a=await this.socket.getObject(`${this.adapterName}.${this.instance}.${r?`${r}.`:""}${n}${o}`)}catch{return n+o}if(!a)return n+o;o?o=(parseInt(o,10)+1).toString():o="2"}while(a)}async getUniqueId(r,n){let o=0,a;do{const i=`${r}_${P.t("copy")}${o?`_${o}`:""}`,s=`${n} ${P.t("copy")}${o?` ${o}`:""}`;try{a=await this.socket.getObject(i)}catch{}if(!a)return{name:s,id:i};o++}while(o<100);throw new Error(P.t("Cannot create unique ID"))}onError(r,n){n&&console.error(n),this.showError(r.toString())}static normalizePreset(r){var n;r.lines&&(r.l=r.lines,delete r.lines),typeof r.range=="string"&&!r.range.includes("m")&&!r.range.includes("y")&&(r.range=parseInt(r.range,10)),(n=r.l)==null||n.forEach(o=>{typeof o.commonYAxis=="string"&&(o.commonYAxis===""?delete o.commonYAxis:o.commonYAxis=parseInt(o.commonYAxis,10)),typeof o.fill=="string"&&(o.fill===""?delete o.fill:o.fill=parseFloat(o.fill))})}async loadChartOrPreset(r){var n,o;if(window.localStorage.setItem("App.echarts.selectedId",JSON.stringify(r)),r&&typeof r=="object"){if(this.state.chartsList)for(const s of this.state.chartsList)this.objects[s.id]===void 0&&(this.objects[s.id]=await this.socket.getObject(s.id)||null);else this.objects={};this.objects[r.id]===void 0&&(this.objects[r.id]=await this.socket.getObject(r.id)||null);const a=(this.state.chartsList||[]).map(s=>Lh(this.state.systemConfig,s.instance,this.objects[s.id],P.getLanguage()));if((n=this.state.chartsList)!=null&&n.find(s=>s.id===r.id&&s.instance===r.instance)||a.push(Lh(this.state.systemConfig,r.instance,this.objects[r.id],P.getLanguage())),a.length>1){const s=a.find(l=>!l.isBoolean);if(s){const l=a.indexOf(s);if(s.yaxe="left",s.unit)for(let d=l+1;d1?"nw":""};ay.normalizePreset(i),await new Promise(s=>{this.setState({presetData:i,originalPresetData:"",selectedPresetChanged:!1,selectedId:r},()=>{const l=`#id=${r.id}&instance=${r.instance.replace(/^system\.adapter\./,"")}`;window.location.hash!==l&&(window.location.hash=l),s()})})}else if(r){const a=await this.socket.getObject(r);if((o=a==null?void 0:a.native)!=null&&o.data){const i=`#preset=${r}`;window.location.hash!==i&&(window.location.hash=i);const s={presetData:a.native.data,originalPresetData:JSON.stringify(a.native.data),selectedPresetChanged:!1,selectedId:r};ay.normalizePreset(s.presetData),await new Promise(l=>this.setState(s,()=>l()))}}else await new Promise(a=>{this.setState({presetData:null,originalPresetData:"",selectedPresetChanged:!1,selectedId:null},()=>a())})}discardChangesConfirmDialog(){return this.state.discardChangesConfirmDialog?w.jsxs(or,{maxWidth:"lg",fullWidth:!0,open:!0,onClose:()=>this.setState({discardChangesConfirmDialog:!1},()=>this.confirmCB&&this.confirmCB(!1)),children:[w.jsx(_r,{children:this.state.discardChangesConfirmDialog==="chart"?P.t("Are you sure for loading the chart and discard unsaved changes?"):this.state.discardChangesConfirmDialog==="preset"?P.t("Are you sure for loading the preset and discard unsaved changes?"):P.t("Are you sure for closing folder and discard unsaved changes?")}),w.jsxs(pr,{sx:{...Qp.alignRight,...Qp.buttonsContainer},children:[w.jsx(tt,{color:"grey",variant:"outlined",onClick:()=>this.setState({discardChangesConfirmDialog:!1},()=>this.confirmCB&&this.confirmCB(!0)),children:P.t("Load without save")}),w.jsx(tt,{variant:"contained",color:"secondary",autoFocus:!0,onClick:()=>this.savePreset().then(()=>this.setState({discardChangesConfirmDialog:!1},()=>this.confirmCB&&this.confirmCB(!0))),startIcon:w.jsx(pH,{}),children:P.t("Save current preset and load")}),w.jsx(tt,{color:"grey",variant:"contained",onClick:()=>this.setState({discardChangesConfirmDialog:!1},()=>this.confirmCB&&this.confirmCB(!1)),startIcon:w.jsx(wo,{}),children:P.t("Cancel")})]})]},"discardChangesConfirmDialog"):null}renderMain(){let r=null,n=null;this.state.presetData&&this.state.selectedId&&typeof this.state.selectedId=="string"&&(r=w.jsx(aZt,{socket:this.socket,width:window.innerWidth,theme:this.state.theme,onChange:a=>{this.state.autoSave?this.setState({presetData:a},()=>this.savePreset()):this.setState({presetData:a,selectedPresetChanged:JSON.stringify(a)!==this.state.originalPresetData})},presetData:this.state.presetData,selectedId:this.state.selectedId,instances:this.state.instances,systemConfig:this.state.systemConfig,selectedPresetChanged:this.state.selectedPresetChanged,savePreset:this.savePreset,autoSave:this.state.autoSave,onAutoSave:a=>{window.localStorage.setItem("App.echarts.autoSave",a?"true":"false"),a&&this.state.selectedPresetChanged?this.savePreset().then(()=>this.setState({autoSave:a})):this.setState({autoSave:a})},windowWidth:this.state.menuSizes[1]},"Editor")),this.state.selectedId&&(n=w.jsx(Wer,{visible:!this.state.resizing,theme:this.state.theme,onChange:a=>this.setState({presetData:a}),presetData:this.state.presetData,selectedId:this.state.selectedId,onCreatePreset:this.onCreatePreset,windowWidth:this.state.menuSizes[1]},"MainChart"));let o;return n&&r?o=w.jsxs(CP,{direction:this.state.logHorzLayout?Tr.Horizontal:Tr.Vertical,initialSizes:this.state.splitSizes,minWidths:[100,450],onResizeStarted:()=>this.setState({resizing:!0}),onResizeFinished:(a,i)=>{this.setState({resizing:!1,splitSizes:i}),window.localStorage.setItem("App.echarts.settingsSizes",JSON.stringify(i))},gutterClassName:this.state.themeType==="dark"?"Dark visGutter":"Light visGutter",children:[n,r]}):o=n,[w.jsxs(Re,{component:"div",sx:Qp.content,className:"iobVerticalSplitter",children:[w.jsx(Re,{component:"div",sx:Qp.menuOpenCloseButton,onClick:()=>{window.localStorage.setItem("App.echarts.menuOpened",this.state.menuOpened?"false":"true"),this.setState({menuOpened:!this.state.menuOpened,resizing:!0}),setTimeout(()=>this.setState({resizing:!1}),300)},children:this.state.menuOpened?w.jsx(Bpe,{}):w.jsx(HE,{})},"confirmdiv"),o]},"confirmdialog")]}renderMenu(){return w.jsx(lnr,{scrollToSelect:this.state.scrollToSelect,socket:this.socket,theme:this.state.theme,adapterName:this.adapterName,instances:this.state.instances,systemConfig:this.state.systemConfig,onShowToast:r=>this.showToast(r),selectedPresetChanged:this.state.selectedPresetChanged,chartsList:this.state.chartsList,selectedId:this.state.selectedId,onCopyPreset:this.onCopyPreset,onCreatePreset:this.onCreatePreset,onChangeList:r=>{let n=this.state.selectedId;if(r&&this.state.chartsList&&r.length&&r.length!r.find(s=>s.id===i.id&&s.instance===i.instance)),a=this.state.chartsList.indexOf(o);this.state.chartsList[a+1]?n=this.state.chartsList[a+1]:this.state.chartsList[a-1]?n=this.state.chartsList[a-1]:n=r[0]}this.setState({chartsList:r},()=>this.loadChartOrPreset(n))},onSelectedChanged:(r,n)=>{this.state.selectedPresetChanged?(this.confirmCB=o=>{o?this.loadChartOrPreset(r).then(()=>n&&n(r)):n&&n(!1),this.confirmCB=null},this.setState({discardChangesConfirmDialog:r&&typeof r=="object"?"chart":r?"preset":"folder"})):this.loadChartOrPreset(r)}},"menuList")}render(){if(!this.state.ready)return w.jsx(uE,{injectFirst:!0,children:w.jsx(yE,{theme:this.state.theme,children:w.jsx(QH,{themeType:this.state.themeType})})});let r;return this.state.menuOpened?r=w.jsx(XN,{onDragEnd:this.onDragEnd,children:w.jsxs(CP,{direction:Tr.Horizontal,initialSizes:this.state.menuSizes,minWidths:[307,300],onResizeStarted:()=>this.setState({resizing:!0}),onResizeFinished:(n,o)=>{this.setState({resizing:!1,menuSizes:[o[0],100-o[0]]}),window.localStorage.setItem("App.echarts.menuSizes",JSON.stringify(o))},gutterClassName:this.state.themeType==="dark"?"Dark visGutter":"Light visGutter",children:[this.renderMenu(),this.renderMain()]})}):r=r=w.jsx(XN,{onDragEnd:this.onDragEnd,children:this.renderMain()}),w.jsx(uE,{injectFirst:!0,children:w.jsxs(yE,{theme:this.state.theme,children:[w.jsx(Re,{sx:Qp.root,children:r}),this.discardChangesConfirmDialog(),this.renderError(),this.renderToast()]})})}}const fnr=qs()(ay);window.location.hostname==="localhost"||window.location.hostname==="[::1]"||window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/);function mnr(){"serviceWorker"in navigator&&navigator.serviceWorker.ready.then(t=>t.unregister())}const gnr="echarts.edit",vnr="1.9.2",ynr={"@devbookhq/splitter":"^1.4.2","@vitejs/plugin-react":"^4.3.4","@types/react-color":"^3.0.13","@types/react-beautiful-dnd":"^13.1.8","material-ui-color-picker":"^3.5.1",moment:"^2.30.1",react:"^18.3.1","react-beautiful-dnd":"^13.1.1","react-dnd":"^16.0.1","react-dnd-html5-backend":"^16.0.1","react-dnd-touch-backend":"^16.0.1","react-dom":"^18.3.1","react-i18next":"^15.4.0","react-icons":"^5.4.0",typescript:"^5.7.2"},_nr=".",bnr={start:"vite dev --config vite.config.mjs --host",build:"vite build --config vite.config.mjs",lint:"eslint -c eslint.config.mjs --debug",npm:"npm i -f",tsc:"tsc -p tsconfig.json"},wnr="http://127.0.0.1:8081",xnr=["127.0.0.1"],Snr={extends:"react-app"},Cnr=[">0.2%","not dead","not ie <= 11","not op_mini all"],$nr={name:gnr,version:vnr,private:!0,dependencies:ynr,homepage:_nr,scripts:bnr,_proxy:wnr,allowedHosts:xnr,eslintConfig:Snr,browserslist:Cnr};window.adapterName="echarts";window.sentryDSN="https://709f116e1de34029921e4f2696d6740f@sentry.iobroker.net/88";console.log(`iobroker.${window.adapterName}@${$nr.version}`);const D9=document.getElementById("root");D9&&LJ.createRoot(D9).render(w.jsx(fnr,{}));mnr()});export default knr(); diff --git a/admin/tab.html b/admin/tab.html index 2f410e8d..214a304a 100644 --- a/admin/tab.html +++ b/admin/tab.html @@ -45,7 +45,7 @@ document.head.appendChild(script); Echarts [ioBroker] - + diff --git a/build-backend/main.js b/build-backend/main.js index a29bde93..0d42ea5c 100644 --- a/build-backend/main.js +++ b/build-backend/main.js @@ -4,7 +4,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); * * ioBroker echarts Adapter * - * (c) 2020-2024 bluefox + * (c) 2020-2025 bluefox * * MIT License * diff --git a/build-backend/main.js.map b/build-backend/main.js.map index 6ad31ac8..673146b8 100644 --- a/build-backend/main.js.map +++ b/build-backend/main.js.map @@ -1 +1 @@ -{"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":";;AAAA;;;;;;;;GAQG;AACH,yDAAsE;AACtE,qCAAsD;AACtD,iDAAqE;AACrE,mDAA4C;AAC5C,iCAAiC;AACjC,+BAA6B;AAC7B,4BAA0B;AAC1B,4BAA0B;AAC1B,4BAA0B;AAC1B,4BAA0B;AAC1B,4BAA0B;AAC1B,4BAA0B;AAC1B,4BAA0B;AAC1B,+BAA6B;AAC7B,4BAA0B;AAE1B,2DAAkD;AAClD,qCAAgE;AAChE,mCAAiF;AAGjF,mBAAmB;AACnB,8GAA8G;AAC9G,mBAAmB;AACnB,IAAI,YAA2F,CAAC;AAChG,IAAI,UAAoC,CAAC;AAEzC,SAAS,aAAa,CAAC,IAAY,EAAE,QAA0B;IAC3D,kBAAkB;IAClB,OAAO,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,UAAU,CAAC,QAAkB,CAAC,IAAI,EAAE,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;AACpF,CAAC;AAED,MAAM,cAAe,SAAQ,sBAAO;IACzB,iBAAiB,GAAG,CAAC,CAAC;IACtB,iBAAiB,GAAG,EAAE,CAAC;IACtB,eAAe,GAAuE,EAAE,CAAC;IACzF,eAAe,GAAe,IAAI,CAAC;IAE3C,YAAmB,UAAmC,EAAE;QACpD,KAAK,CAAC;YACF,GAAG,OAAO;YACV,IAAI,EAAE,SAAS;SAClB,CAAC,CAAC;QACH,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;QACpC,IAAI,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,MA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AAC,EAAE,CAAC;AACnC,CAAC","sourcesContent":["/**\n *\n * ioBroker echarts Adapter\n *\n * (c) 2020-2024 bluefox \n *\n * MIT License\n *\n */\nimport { Adapter, type AdapterOptions } from '@iobroker/adapter-core';\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport ChartModel, { type BarAndLineSeries } from './lib/ChartModel';\nimport ChartOption from './lib/ChartOption';\nimport * as moment from 'moment';\nimport 'moment/locale/en-gb';\nimport 'moment/locale/es';\nimport 'moment/locale/fr';\nimport 'moment/locale/pl';\nimport 'moment/locale/pt';\nimport 'moment/locale/it';\nimport 'moment/locale/nl';\nimport 'moment/locale/ru';\nimport 'moment/locale/zh-cn';\nimport 'moment/locale/de';\nimport type { EchartsOptions, Connection, ChartConfigMore } from './types';\nimport { getSocket } from './lib/socketSimulator';\nimport { type EChartsType, init as echartsInit } from 'echarts';\nimport { Canvas, type JpegConfig, type PdfConfig, type PngConfig } from 'canvas';\nimport { type JSDOM } from 'jsdom';\n\n// let echartsInit:\n// | ((canvas: HTMLElement | null, theme?: string | object | null, opts?: EChartsInitOpts) => EChartsType)\n// | undefined;\nlet createCanvas: ((width: number, height: number, type?: 'pdf' | 'svg') => Canvas) | undefined;\nlet JsDomClass: typeof JSDOM | undefined;\n\nfunction calcTextWidth(text: string, fontSize?: number | string): number {\n // try to simulate\n return Math.ceil((text.length * (parseFloat(fontSize as string) || 12)) / 0.75);\n}\n\nclass EchartsAdapter extends Adapter {\n public __lastMessageTime = 0;\n public __lastMessageText = '';\n private cachedSnapshots: Record = {};\n private socketSimulator: Connection = null;\n\n public constructor(options: Partial = {}) {\n super({\n ...options,\n name: 'echarts',\n });\n this.on('ready', () => this.main());\n this.on('message', obj => obj?.command === 'send' && this.processMessage(obj));\n }\n\n // Todo: queue requests as global.window is \"global\"\n async renderImage(options: EchartsOptions): Promise {\n if (!createCanvas) {\n try {\n createCanvas = (await import('canvas')).createCanvas;\n JsDomClass = (await import('jsdom')).JSDOM;\n this.socketSimulator = getSocket(this);\n } catch (e) {\n this.log.error(`Cannot find required modules: ${e}`);\n throw new Error(\n 'Cannot find required modules: looks like it is not possible to generate charts on your Hardware/OS',\n );\n }\n }\n\n return new Promise((resolve, reject) => {\n options.width = parseFloat(options.width as unknown as string) || 1024;\n options.height = parseFloat(options.height as unknown as string) || 300;\n\n const chartData = new ChartModel(this.socketSimulator, options.preset, { serverSide: true });\n\n chartData.onError(err => this.log.error(err.toString()));\n\n chartData.onUpdate(\n (\n seriesData: BarAndLineSeries[],\n _actualValues?: (number | null | boolean | string)[],\n barCategories?: number[],\n ) => {\n const systemConfig = chartData.getSystemConfig();\n moment.locale(systemConfig?.language || 'en');\n const theme = options.theme || options.themeType || 'light';\n\n const chartOption = new ChartOption(moment, theme, calcTextWidth);\n const option = chartOption.getOption(\n seriesData,\n chartData.getConfig() as ChartConfigMore,\n null,\n barCategories,\n );\n const { window } = new JsDomClass();\n\n // @ts-expect-error must be so\n global.window = window;\n global.navigator = window.navigator;\n global.document = window.document;\n\n let chart: EChartsType;\n let canvas: Canvas | undefined;\n let root: HTMLDivElement | undefined;\n if (options.renderer && options.renderer !== 'svg') {\n canvas = createCanvas(options.width, options.height);\n canvas.width = options.width;\n canvas.height = options.height;\n chart = echartsInit(canvas as unknown as HTMLElement);\n if (options.background) {\n option.backgroundColor = options.background;\n }\n } else {\n root = global.document.createElement('div');\n root.style.cssText = `width: ${options.width}px; height: ${options.height}px;${\n options.background\n ? ` background: ${options.background}`\n : theme === 'dark'\n ? ' background: #000;'\n : ''\n }`;\n chart = echartsInit(root, undefined, { renderer: 'svg' });\n }\n\n chart.setOption(option);\n\n let data: string;\n switch (options.renderer || '') {\n case 'png': {\n data = `data:image/png;base64,${canvas\n .toBuffer('image/png', {\n compressionLevel: options.compressionLevel || 3,\n filters: options.filters || Canvas.PNG_FILTER_NONE,\n } as PngConfig)\n .toString('base64')}`;\n break;\n }\n case 'jpg': {\n data = `data:image/jpeg;base64,${canvas\n .toBuffer('image/jpeg', {\n quality: options.quality || 0.8,\n } as JpegConfig)\n .toString('base64')}`;\n break;\n }\n case 'pdf': {\n data = `data:application/pdf;base64,${canvas\n .toBuffer('application/pdf', {\n title: options.title || 'ioBroker Chart',\n creationDate: new Date(),\n } as PdfConfig)\n .toString('base64')}`;\n break;\n }\n case '':\n case 'svg': {\n const svg = root.querySelector('svg').outerHTML;\n data = `data:image/svg+xml;base64,${Buffer.from(svg).toString('base64')}`;\n break;\n }\n default:\n reject(new Error('Unsupported format'));\n return;\n }\n\n chart?.dispose();\n\n if (options.fileOnDisk) {\n writeFileSync(options.fileOnDisk, Buffer.from(data.split(',')[1], 'base64'));\n }\n if (options.fileName) {\n this.writeFile(\n this.namespace,\n options.fileName,\n Buffer.from(data.split(',')[1], 'base64'),\n err => (err ? reject(err) : resolve(data)),\n );\n } else {\n resolve(data);\n }\n },\n );\n });\n }\n\n async fixSystemObject(): Promise {\n const obj = await this.getForeignObjectAsync('_design/system');\n if (obj?.views && !obj.views.chart) {\n obj.views.chart = {\n map: `function(doc) { if (doc.type === 'chart') emit(doc._id, doc) }`,\n };\n await this.setForeignObjectAsync(obj._id, obj);\n return true;\n }\n return false;\n }\n\n processMessage(obj: ioBroker.Message): void {\n if (!obj?.message) {\n return;\n }\n\n // filter out the double messages\n const json = JSON.stringify(obj.message);\n if (this.__lastMessageTime && this.__lastMessageText === json && Date.now() - this.__lastMessageTime < 300) {\n return this.log.debug(\n `Filter out double message [first was for ${Date.now() - this.__lastMessageTime}ms]: ${json}`,\n );\n }\n\n this.__lastMessageTime = Date.now();\n this.__lastMessageText = json;\n\n const message: EchartsOptions = obj.message;\n\n if (!message?.preset) {\n this.log.error(\n 'Please define settings: {\"preset\": \"echarts.0.XXX\", width: 500, height: 200, renderer: \"png/svg\"}',\n );\n if (obj.callback) {\n this.sendTo(\n obj.from,\n 'send',\n {\n error: 'Please define settings: {\"preset\": \"echarts.0.XXX\", width: 500, height: 200, renderer: \"svg/png\"}',\n },\n obj.callback,\n );\n }\n } else {\n // delete cached snapshots\n Object.keys(this.cachedSnapshots).forEach(preset => {\n if (this.cachedSnapshots[preset].ts < Date.now()) {\n delete this.cachedSnapshots[preset];\n }\n });\n\n if (\n message.cache &&\n !message.forceRefresh &&\n this.cachedSnapshots[message.preset] &&\n this.cachedSnapshots[message.preset].ts >= Date.now()\n ) {\n if (obj.callback) {\n this.sendTo(\n obj.from,\n 'send',\n {\n data: this.cachedSnapshots[message.preset].data,\n error: this.cachedSnapshots[message.preset].error,\n },\n obj.callback,\n );\n }\n } else {\n this.renderImage(message)\n .then(data => {\n if (message.cache) {\n if (!this.cachedSnapshots[message.preset]) {\n this.cachedSnapshots[message.preset] = {\n ts: Date.now() + message.cache * 1000,\n data,\n error: null,\n };\n } else {\n this.cachedSnapshots[message.preset].ts = Date.now() + message.cache * 1000;\n this.cachedSnapshots[message.preset].data = data;\n this.cachedSnapshots[message.preset].error = null;\n }\n }\n if (obj.callback) {\n this.sendTo(obj.from, 'send', { data }, obj.callback);\n }\n })\n .catch(error => {\n if (message.cache) {\n if (!this.cachedSnapshots[message.preset]) {\n this.cachedSnapshots[message.preset] = {\n ts: Date.now() + message.cache * 1000,\n data: null,\n error,\n };\n } else {\n this.cachedSnapshots[message.preset].ts = Date.now() + message.cache * 1000;\n this.cachedSnapshots[message.preset].data = null;\n this.cachedSnapshots[message.preset].error = error;\n }\n }\n if (obj.callback) {\n this.sendTo(obj.from, 'send', { error }, obj.callback);\n }\n });\n }\n }\n }\n\n async main(): Promise {\n // fix _design/chart\n let designObject: ioBroker.DesignObject | null | undefined = await this.getForeignObjectAsync('_design/chart');\n const _obj: any = JSON.parse(readFileSync(`${__dirname}/../io-package.json`).toString('utf8')).objects.find(\n (ob: ioBroker.Object) => ob._id === '_design/chart',\n );\n\n if (!designObject || (_obj && JSON.stringify(designObject.views) !== JSON.stringify(_obj.views))) {\n designObject = { language: 'javascript' } as ioBroker.DesignObject;\n designObject.views = _obj?.views\n ? _obj.views\n : { chart: { map: `function(doc) { if (doc.type === 'chart') emit(doc._id, doc); }` } };\n await this.setForeignObjectAsync('_design/chart', designObject);\n }\n\n // fix _design/system\n const systemDesign = await this.getForeignObjectAsync('_design/system');\n if (systemDesign?.views && !systemDesign.views.chart) {\n systemDesign.views.chart = {\n map: \"function(doc) { if (doc.type === 'chart') emit(doc._id, doc); }\",\n };\n await this.setForeignObjectAsync('_design/system', systemDesign);\n }\n\n // enabled mode daemon and message box\n const adapterInstance = await this.getForeignObjectAsync(`system.adapter.${this.namespace}`);\n if (\n adapterInstance?.common &&\n (adapterInstance.common.mode !== 'daemon' || !adapterInstance.common.messagebox)\n ) {\n adapterInstance.common.mode = 'daemon';\n adapterInstance.common.messagebox = true;\n await this.setForeignObjectAsync(adapterInstance._id, adapterInstance);\n }\n\n if (await this.fixSystemObject()) {\n this.log.debug('Added chart view to system object');\n }\n\n /*renderImage({preset: 'Test', theme: 'dark', renderer: 'png', background: '#000000'})\n .then(data => {\n const base64 = Buffer.from(data.split(',')[1], 'base64');\n require('fs').writeFileSync('image.png', base64);\n });*/\n }\n}\n\nif (require.main !== module) {\n // Export the constructor in compact mode\n module.exports = (options: Partial | undefined) => new EchartsAdapter(options);\n} else {\n // otherwise start the instance directly\n (() => new EchartsAdapter())();\n}\n"]} \ No newline at end of file +{"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":";;AAAA;;;;;;;;GAQG;AACH,yDAAsE;AACtE,qCAAsD;AACtD,iDAAqE;AACrE,mDAA4C;AAC5C,iCAAiC;AACjC,+BAA6B;AAC7B,4BAA0B;AAC1B,4BAA0B;AAC1B,4BAA0B;AAC1B,4BAA0B;AAC1B,4BAA0B;AAC1B,4BAA0B;AAC1B,4BAA0B;AAC1B,+BAA6B;AAC7B,4BAA0B;AAE1B,2DAAkD;AAClD,qCAAgE;AAChE,mCAAiF;AAGjF,mBAAmB;AACnB,8GAA8G;AAC9G,mBAAmB;AACnB,IAAI,YAA2F,CAAC;AAChG,IAAI,UAAoC,CAAC;AAEzC,SA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AC,MAAM,CAAC,UAAU,CAAC,EAClF,CAAC;YACC,eAAe,CAAC,MAAM,CAAC,IAAI,GAAG,QAAQ,CAAC;YACvC,eAAe,CAAC,MAAM,CAAC,UAAU,GAAG,IAAI,CAAC;YACzC,MAAM,IAAI,CAAC,qBAAqB,CAAC,eAAe,CAAC,GAAG,EAAE,eAAe,CAAC,CAAC;QAC3E,CAAC;QAED,IAAI,MAAM,IAAI,CAAC,eAAe,EAAE,EAAE,CAAC;YAC/B,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,mCAAmC,CAAC,CAAC;QACxD,CAAC;QAED;;;;iBAIS;IACb,CAAC;CACJ;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;IAC1B,yCAAyC;IACzC,MAAM,CAAC,OAAO,GAAG,CAAC,OAA4C,EAAE,EAAE,CAAC,IAAI,cAAc,CAAC,OAAO,CAAC,CAAC;AACnG,CAAC;KAAM,CAAC;IACJ,wCAAwC;IACxC,CAAC,GAAG,EAAE,CAAC,IAAI,cAAc,EAAE,CAAC,EAAE,CAAC;AACnC,CAAC","sourcesContent":["/**\n *\n * ioBroker echarts Adapter\n *\n * (c) 2020-2025 bluefox \n *\n * MIT License\n *\n */\nimport { Adapter, type AdapterOptions } from '@iobroker/adapter-core';\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport ChartModel, { type BarAndLineSeries } from './lib/ChartModel';\nimport ChartOption from './lib/ChartOption';\nimport * as moment from 'moment';\nimport 'moment/locale/en-gb';\nimport 'moment/locale/es';\nimport 'moment/locale/fr';\nimport 'moment/locale/pl';\nimport 'moment/locale/pt';\nimport 'moment/locale/it';\nimport 'moment/locale/nl';\nimport 'moment/locale/ru';\nimport 'moment/locale/zh-cn';\nimport 'moment/locale/de';\nimport type { EchartsOptions, Connection, ChartConfigMore } from './types';\nimport { getSocket } from './lib/socketSimulator';\nimport { type EChartsType, init as echartsInit } from 'echarts';\nimport { Canvas, type JpegConfig, type PdfConfig, type PngConfig } from 'canvas';\nimport { type JSDOM } from 'jsdom';\n\n// let echartsInit:\n// | ((canvas: HTMLElement | null, theme?: string | object | null, opts?: EChartsInitOpts) => EChartsType)\n// | undefined;\nlet createCanvas: ((width: number, height: number, type?: 'pdf' | 'svg') => Canvas) | undefined;\nlet JsDomClass: typeof JSDOM | undefined;\n\nfunction calcTextWidth(text: string, fontSize?: number | string): number {\n // try to simulate\n return Math.ceil((text.length * (parseFloat(fontSize as string) || 12)) / 0.75);\n}\n\nclass EchartsAdapter extends Adapter {\n public __lastMessageTime = 0;\n public __lastMessageText = '';\n private cachedSnapshots: Record = {};\n private socketSimulator: Connection = null;\n\n public constructor(options: Partial = {}) {\n super({\n ...options,\n name: 'echarts',\n });\n this.on('ready', () => this.main());\n this.on('message', obj => obj?.command === 'send' && this.processMessage(obj));\n }\n\n // Todo: queue requests as global.window is \"global\"\n async renderImage(options: EchartsOptions): Promise {\n if (!createCanvas) {\n try {\n createCanvas = (await import('canvas')).createCanvas;\n JsDomClass = (await import('jsdom')).JSDOM;\n this.socketSimulator = getSocket(this);\n } catch (e) {\n this.log.error(`Cannot find required modules: ${e}`);\n throw new Error(\n 'Cannot find required modules: looks like it is not possible to generate charts on your Hardware/OS',\n );\n }\n }\n\n return new Promise((resolve, reject) => {\n options.width = parseFloat(options.width as unknown as string) || 1024;\n options.height = parseFloat(options.height as unknown as string) || 300;\n\n const chartData = new ChartModel(this.socketSimulator, options.preset, { serverSide: true });\n\n chartData.onError(err => this.log.error(err.toString()));\n\n chartData.onUpdate(\n (\n seriesData: BarAndLineSeries[],\n _actualValues?: (number | null | boolean | string)[],\n barCategories?: number[],\n ) => {\n const systemConfig = chartData.getSystemConfig();\n moment.locale(systemConfig?.language || 'en');\n const theme = options.theme || options.themeType || 'light';\n\n const chartOption = new ChartOption(moment, theme, calcTextWidth);\n const option = chartOption.getOption(\n seriesData,\n chartData.getConfig() as ChartConfigMore,\n null,\n barCategories,\n );\n const { window } = new JsDomClass();\n\n // @ts-expect-error must be so\n global.window = window;\n global.navigator = window.navigator;\n global.document = window.document;\n\n let chart: EChartsType;\n let canvas: Canvas | undefined;\n let root: HTMLDivElement | undefined;\n if (options.renderer && options.renderer !== 'svg') {\n canvas = createCanvas(options.width, options.height);\n canvas.width = options.width;\n canvas.height = options.height;\n chart = echartsInit(canvas as unknown as HTMLElement);\n if (options.background) {\n option.backgroundColor = options.background;\n }\n } else {\n root = global.document.createElement('div');\n root.style.cssText = `width: ${options.width}px; height: ${options.height}px;${\n options.background\n ? ` background: ${options.background}`\n : theme === 'dark'\n ? ' background: #000;'\n : ''\n }`;\n chart = echartsInit(root, undefined, { renderer: 'svg' });\n }\n\n chart.setOption(option);\n\n let data: string;\n switch (options.renderer || '') {\n case 'png': {\n data = `data:image/png;base64,${canvas\n .toBuffer('image/png', {\n compressionLevel: options.compressionLevel || 3,\n filters: options.filters || Canvas.PNG_FILTER_NONE,\n } as PngConfig)\n .toString('base64')}`;\n break;\n }\n case 'jpg': {\n data = `data:image/jpeg;base64,${canvas\n .toBuffer('image/jpeg', {\n quality: options.quality || 0.8,\n } as JpegConfig)\n .toString('base64')}`;\n break;\n }\n case 'pdf': {\n data = `data:application/pdf;base64,${canvas\n .toBuffer('application/pdf', {\n title: options.title || 'ioBroker Chart',\n creationDate: new Date(),\n } as PdfConfig)\n .toString('base64')}`;\n break;\n }\n case '':\n case 'svg': {\n const svg = root.querySelector('svg').outerHTML;\n data = `data:image/svg+xml;base64,${Buffer.from(svg).toString('base64')}`;\n break;\n }\n default:\n reject(new Error('Unsupported format'));\n return;\n }\n\n chart?.dispose();\n\n if (options.fileOnDisk) {\n writeFileSync(options.fileOnDisk, Buffer.from(data.split(',')[1], 'base64'));\n }\n if (options.fileName) {\n this.writeFile(\n this.namespace,\n options.fileName,\n Buffer.from(data.split(',')[1], 'base64'),\n err => (err ? reject(err) : resolve(data)),\n );\n } else {\n resolve(data);\n }\n },\n );\n });\n }\n\n async fixSystemObject(): Promise {\n const obj = await this.getForeignObjectAsync('_design/system');\n if (obj?.views && !obj.views.chart) {\n obj.views.chart = {\n map: `function(doc) { if (doc.type === 'chart') emit(doc._id, doc) }`,\n };\n await this.setForeignObjectAsync(obj._id, obj);\n return true;\n }\n return false;\n }\n\n processMessage(obj: ioBroker.Message): void {\n if (!obj?.message) {\n return;\n }\n\n // filter out the double messages\n const json = JSON.stringify(obj.message);\n if (this.__lastMessageTime && this.__lastMessageText === json && Date.now() - this.__lastMessageTime < 300) {\n return this.log.debug(\n `Filter out double message [first was for ${Date.now() - this.__lastMessageTime}ms]: ${json}`,\n );\n }\n\n this.__lastMessageTime = Date.now();\n this.__lastMessageText = json;\n\n const message: EchartsOptions = obj.message;\n\n if (!message?.preset) {\n this.log.error(\n 'Please define settings: {\"preset\": \"echarts.0.XXX\", width: 500, height: 200, renderer: \"png/svg\"}',\n );\n if (obj.callback) {\n this.sendTo(\n obj.from,\n 'send',\n {\n error: 'Please define settings: {\"preset\": \"echarts.0.XXX\", width: 500, height: 200, renderer: \"svg/png\"}',\n },\n obj.callback,\n );\n }\n } else {\n // delete cached snapshots\n Object.keys(this.cachedSnapshots).forEach(preset => {\n if (this.cachedSnapshots[preset].ts < Date.now()) {\n delete this.cachedSnapshots[preset];\n }\n });\n\n if (\n message.cache &&\n !message.forceRefresh &&\n this.cachedSnapshots[message.preset] &&\n this.cachedSnapshots[message.preset].ts >= Date.now()\n ) {\n if (obj.callback) {\n this.sendTo(\n obj.from,\n 'send',\n {\n data: this.cachedSnapshots[message.preset].data,\n error: this.cachedSnapshots[message.preset].error,\n },\n obj.callback,\n );\n }\n } else {\n this.renderImage(message)\n .then(data => {\n if (message.cache) {\n if (!this.cachedSnapshots[message.preset]) {\n this.cachedSnapshots[message.preset] = {\n ts: Date.now() + message.cache * 1000,\n data,\n error: null,\n };\n } else {\n this.cachedSnapshots[message.preset].ts = Date.now() + message.cache * 1000;\n this.cachedSnapshots[message.preset].data = data;\n this.cachedSnapshots[message.preset].error = null;\n }\n }\n if (obj.callback) {\n this.sendTo(obj.from, 'send', { data }, obj.callback);\n }\n })\n .catch(error => {\n if (message.cache) {\n if (!this.cachedSnapshots[message.preset]) {\n this.cachedSnapshots[message.preset] = {\n ts: Date.now() + message.cache * 1000,\n data: null,\n error,\n };\n } else {\n this.cachedSnapshots[message.preset].ts = Date.now() + message.cache * 1000;\n this.cachedSnapshots[message.preset].data = null;\n this.cachedSnapshots[message.preset].error = error;\n }\n }\n if (obj.callback) {\n this.sendTo(obj.from, 'send', { error }, obj.callback);\n }\n });\n }\n }\n }\n\n async main(): Promise {\n // fix _design/chart\n let designObject: ioBroker.DesignObject | null | undefined = await this.getForeignObjectAsync('_design/chart');\n const _obj: any = JSON.parse(readFileSync(`${__dirname}/../io-package.json`).toString('utf8')).objects.find(\n (ob: ioBroker.Object) => ob._id === '_design/chart',\n );\n\n if (!designObject || (_obj && JSON.stringify(designObject.views) !== JSON.stringify(_obj.views))) {\n designObject = { language: 'javascript' } as ioBroker.DesignObject;\n designObject.views = _obj?.views\n ? _obj.views\n : { chart: { map: `function(doc) { if (doc.type === 'chart') emit(doc._id, doc); }` } };\n await this.setForeignObjectAsync('_design/chart', designObject);\n }\n\n // fix _design/system\n const systemDesign = await this.getForeignObjectAsync('_design/system');\n if (systemDesign?.views && !systemDesign.views.chart) {\n systemDesign.views.chart = {\n map: \"function(doc) { if (doc.type === 'chart') emit(doc._id, doc); }\",\n };\n await this.setForeignObjectAsync('_design/system', systemDesign);\n }\n\n // enabled mode daemon and message box\n const adapterInstance = await this.getForeignObjectAsync(`system.adapter.${this.namespace}`);\n if (\n adapterInstance?.common &&\n (adapterInstance.common.mode !== 'daemon' || !adapterInstance.common.messagebox)\n ) {\n adapterInstance.common.mode = 'daemon';\n adapterInstance.common.messagebox = true;\n await this.setForeignObjectAsync(adapterInstance._id, adapterInstance);\n }\n\n if (await this.fixSystemObject()) {\n this.log.debug('Added chart view to system object');\n }\n\n /*renderImage({preset: 'Test', theme: 'dark', renderer: 'png', background: '#000000'})\n .then(data => {\n const base64 = Buffer.from(data.split(',')[1], 'base64');\n require('fs').writeFileSync('image.png', base64);\n });*/\n }\n}\n\nif (require.main !== module) {\n // Export the constructor in compact mode\n module.exports = (options: Partial | undefined) => new EchartsAdapter(options);\n} else {\n // otherwise start the instance directly\n (() => new EchartsAdapter())();\n}\n"]} \ No newline at end of file diff --git a/io-package.json b/io-package.json index 7b6ab46d..073a6d09 100644 --- a/io-package.json +++ b/io-package.json @@ -1,8 +1,21 @@ { "common": { "name": "echarts", - "version": "2.0.3", + "version": "2.0.4", "news": { + "2.0.4": { + "en": "Correcting locale for x-axis\nCorrecting widget", + "de": "Ortskorrektur für x-Achse\nKorrektur Widget", + "ru": "Корректировка лока для x-оси\nИсправление виджета", + "pt": "Correção local para eixo x\nWidget de correção", + "nl": "Lokale corrigeren voor x-as\nWidget wordt gecorrigeerd", + "fr": "Corriger le local pour l'axe des x\nCorrection du widget", + "it": "Correggere locale per x-assi\nCorreggere widget", + "es": "Corrección local para eje x\nWidget corrector", + "pl": "Korekcja lokalizacji osi x\nKorekcja widżetu", + "uk": "Виправлення локалізації для осі x\nВиправлення віджету", + "zh-cn": "纠正 x 轴的定位\n校正部件" + }, "2.0.3": { "en": "Corrected the convert functionality", "de": "Korrektur der Konvertierungsfunktionalität", @@ -80,19 +93,6 @@ "pl": "zmodernizowane zależności", "uk": "покращені залежності", "zh-cn": "升级的依赖关系" - }, - "1.7.2": { - "en": "Added option to hide the value in the future", - "de": "Option hinzugefügt, um den Wert in der Zukunft zu verbergen", - "ru": "Добавлена возможность скрыть значение в будущем", - "pt": "Opção adicionada para esconder o valor no futuro", - "nl": "Optie om de waarde in de toekomst te verbergen", - "fr": "Option supplémentaire pour cacher la valeur dans le futur", - "it": "Aggiunta opzione per nascondere il valore in futuro", - "es": "Opción agregada para ocultar el valor en el futuro", - "pl": "Wstępna możliwość ukrywania wartości w przyszłości", - "uk": "Додана можливість приховати значення в майбутньому", - "zh-cn": "增加今后隐藏价值的选择" } }, "titleLang": { diff --git a/package.json b/package.json index 8a52b607..9ea895c7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "iobroker.echarts", - "version": "2.0.3", + "version": "2.0.4", "description": "Build useful charts in ioBroker", "author": { "name": "bluefox",