iobroker.admin 7.6.13 → 7.6.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -8
- package/adminWww/assets/{AdapterUpdateDialog-B8g_ZuhP.js → AdapterUpdateDialog-DnnNHIQJ.js} +1 -1
- package/adminWww/assets/{Adapters-XtPWdL3s.js → Adapters-Ctxos-gw.js} +4 -4
- package/adminWww/assets/{Config-Dhj9WMpz.js → Config-Dyad6_tq.js} +1 -1
- package/adminWww/assets/CustomModal-BNDSg_P8.js +1 -0
- package/adminWww/assets/{CustomTab-CSgGzXlh.js → CustomTab-BEL1ttN8.js} +1 -1
- package/adminWww/assets/{EasyMode-Bwx_UimW.js → EasyMode-3ydknWSd.js} +1 -1
- package/adminWww/assets/{Enums-B-PrqYys.js → Enums-nRoQYhch.js} +2 -2
- package/adminWww/assets/{Fields-CYjxm_8L.js → Fields-Bwvci3VO.js} +1 -1
- package/adminWww/assets/{Files-CsBMd5VX.js → Files-Dzs9GmrC.js} +1 -1
- package/adminWww/assets/{Hosts-D7aAXH9U.js → Hosts-BjpHSLCf.js} +3 -3
- package/adminWww/assets/{Instances-Bj8CqStT.js → Instances-BtTV4PMv.js} +2 -2
- package/adminWww/assets/Intro-DD3K3IVm.js +2 -0
- package/adminWww/assets/{Logs-Bb16bYuu.js → Logs-BXU61QOI.js} +1 -1
- package/adminWww/assets/{Objects-C7k5tHdx.js → Objects-jsWq-neK.js} +2 -2
- package/adminWww/assets/{State-DPLzxZ6D.js → State-CuA1h-bU.js} +1 -1
- package/adminWww/assets/{Users-BQ3pWAxq.js → Users-BFdQMyo4.js} +1 -1
- package/adminWww/assets/{ace-j1VT51C2.js → ace-CI9-Cq3I.js} +2 -2
- package/adminWww/assets/{bootstrap-BNkcLa73.js → bootstrap-FCtLxt0T.js} +14 -14
- package/adminWww/assets/{index-jZ28cZd6.js → index-3IvffoSA.js} +1 -1
- package/adminWww/assets/{index-C6O1p4S2.js → index-DPxBLJAn.js} +2 -2
- package/adminWww/assets/{sentry-9i5rBs6L.js → sentry-BNaNpYqi.js} +1 -1
- package/adminWww/assets/{zh-cn-CULr7ytT.js → zh-cn-CbEN7EL2.js} +1 -1
- package/adminWww/index.html +1 -1
- package/adminWww/mf-manifest.json +1 -1
- package/adminWww/remoteEntry.js +2 -2
- package/io-package.json +15 -15
- package/package.json +12 -7
- package/adminWww/assets/CustomModal-4eTuDNla.js +0 -1
- package/adminWww/assets/Intro-sAT0x17e.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{j as y}from"./DefaultPropsProvider-BrbE0teb.js";import{i as at,R as vh}from"./iobroker_admin__loadShare__react__loadShare__-DtlEM_52.js";import{w as Wn,f as rn,J as gh,i as w,a as X,u as Gl,v as $x,D as mh,x as Yx,y as qt,z as ks,U as jt,B as Xx,M as Cd,R as yh,I as G,E as ty,K as Td,N as qx,O as Ad,P as Zx,b as Ca,Q as ey,q as Kx,V as Rs,W as Jx}from"./bootstrap-BNkcLa73.js";import{l as Qx}from"./index-8HslT92O.js";import{a as tw,i as ew}from"./iobroker_admin__mf_v__runtimeInit__mf_v__-VDoBF19b.js";import{c as rw,d as iw,e as nw,f as Md}from"./index-HOidq_rM.js";import{a as aw}from"./_commonjsHelpers-D6-XlEtG.js";import{h as Ul}from"./zh-cn-CULr7ytT.js";import{C as ow}from"./CustomModal-4eTuDNla.js";import"./iobroker_admin__loadShare__prop_mf_2_types__loadShare__-BGyJCibC.js";import"./emotion-serialize.esm-BUa21YfQ.js";import"./iobroker_admin__loadShare___mf_0_emotion_mf_1_react__loadShare__-gw2iqPBS.js";import"./ace-j1VT51C2.js";import"./FilledInput-D-tz8rvg.js";import"./preload-helper-C1FmrZbK.js";import"./blueGrey-B0oIowPK.js";import"./emotion-cache.browser.esm-B8BFze5o.js";import"./iobroker_admin__loadShare__leaflet__loadShare__-B1OZ7tj-.js";import"./extends-CF3RwP-h.js";import"./iconBase-CgxZ5MMC.js";const Ut={paper:{height:"100%",maxHeight:"100%",maxWidth:"100%",overflow:"hidden"},headingIcon:{marginRight:5,width:32,height:32},titleEnabled:{float:"right",fontSize:16,color:"#7ff57f",textTransform:"uppercase",fontWeight:"bold",paddingLeft:20},scrollDiv:{width:"100%",height:"100%",overflow:"auto"},enabledControl:{width:130,display:"inline-block",verticalAlign:"top"},customControls:{width:"calc(100% - 130px)",maxWidth:800,display:"inline-block",verticalAlign:"top",paddingTop:16},accordionOdd:{},accordionEven:{backgroundColor:"rgba(128, 128, 128, 0.1)"},accordionHeaderOdd:{backgroundColor:"rgba(128, 128, 128, 0.2)"},accordionHeaderEven:{backgroundColor:"rgba(128, 128, 128, 0.3)"},accordionHeaderEnabledOdd:{backgroundColor:"rgba(128, 255, 128, 0.2)"},accordionHeaderEnabledEven:{backgroundColor:"rgba(128, 255, 128, 0.2)"},enabledVisible:{display:"inline-block"},enabledInvisible:{display:"none"}},sw=".";class Ls extends at.Component{changedIds;scrollDivRef;jsonConfigs;refTemplate;customObj;commonConfig={};cb;cachedNewValues;constructor(t){super(t);let e;try{e=JSON.parse((window._localStorage||window.localStorage).getItem("App.customsExpanded")||"[]")}catch{e=[]}this.changedIds=[],this.state={loaded:!1,expanded:e,newValues:{},confirmed:!1,showConfirmation:!1,maxOids:0,systemConfig:this.props.systemConfig},this.scrollDivRef=at.createRef(),this.jsonConfigs={},this.refTemplate={},this.props.customsInstances.map(i=>this.refTemplate[i]=at.createRef()),this.customObj=this.props.objectIDs.length>1?{common:{custom:{}},native:{}}:rn.deepClone(this.props.objects[this.props.objectIDs[0]]||null),this.customObj&&this.loadAllCustoms().then(()=>{this.commonConfig=this.getCommonConfig(),this.setState({loaded:!0,newValues:{}})})}async componentDidMount(){this.state.systemConfig||this.setState({systemConfig:await this.props.socket.getCompactSystemConfig()}),this.props.registerSaveFunc&&this.props.registerSaveFunc(this.onSave)}componentWillUnmount(){this.props.registerSaveFunc&&this.props.registerSaveFunc()}async loadAllCustoms(){const t=[];for(const e of this.props.customsInstances){if(e==="_")continue;const i=e.replace(/\.\d+$/,"").replace("system.adapter.","");this.jsonConfigs[i]===void 0&&(this.jsonConfigs[i]=null,t.push(this.getCustomTemplate(i)))}await Promise.all(t),this.props.customsInstances.forEach(e=>{var n,a;const i=e.replace(/\.\d+$/,"").replace("system.adapter.","");this.jsonConfigs[i]&&(this.jsonConfigs[i].instanceObjs=this.jsonConfigs[i].instanceObjs||{},this.jsonConfigs[i].instanceObjs[e]={_id:e,common:JSON.parse(JSON.stringify((n=this.props.objects[`system.adapter.${e}`])==null?void 0:n.common)),native:JSON.parse(JSON.stringify((a=this.props.objects[`system.adapter.${e}`])==null?void 0:a.native)),type:"instance",instanceObjects:[],objects:[]})})}async getCustomTemplate(t){var i;const e=this.props.objects[`system.adapter.${t}`]?rn.deepClone(this.props.objects[`system.adapter.${t}`]):null;if(!e){console.error(`Cannot find adapter "${t}"`);return}if(rn.fixAdminUI(e),((i=e.common)==null?void 0:i.adminUI.custom)==="json")try{const n=await this.props.socket.fileExists(`${t}.admin`,"jsonCustom.json5");let a,o;n?o=await this.props.socket.readFile(`${t}.admin`,"jsonCustom.json5"):o=await this.props.socket.readFile(`${t}.admin`,"jsonCustom.json"),o.file!==void 0?a=o.file:a=o;let s;try{s=Qx.parse(a),this.jsonConfigs[t]=this.jsonConfigs[t]||{},this.jsonConfigs[t].json=s}catch(l){console.error(`Cannot parse jsonConfig of ${t}: ${l}`),window.alert(`Cannot parse jsonConfig of ${t}: ${l}`)}await gh.loadI18n(this.props.socket,s.i18n,t);return}catch(n){console.error(`Cannot load jsonConfig of ${t}: ${n}`),window.alert(`Cannot load jsonConfig of ${t}: ${n}`)}console.error(`Adapter ${t} is not yet supported by this version of admin`),window.alert(`Adapter ${t} is not yet supported by this version of admin`)}_executeCustom(t,e,i,n,a,o,s){if(s.includes(o))return;s.push(o);let l=[],u;if(t&&typeof t=="object"?(l=t.alsoDependsOn||[],typeof l=="string"&&(l=[l]),u=t.func):u=t,l.forEach(h=>{if(!a[h])console.error(`[JsonConfigComponent] attribute "${h}" does not exist!`);else if(!a[h].defaultFunc)console.error(`[JsonConfigComponent] attribute "${h}" is not required to be includes in "alsoDependsOn" while has static value!`);else{const c=this._executeCustom(a[h].defaultFunc,e,i,n,a,h,s);c!==void 0&&(e[h]=c)}}),!u)e[o]=a[o].default===void 0?null:a[o].default;else try{const h=new Function("data","originalData","_system","instanceObj","customObj","_socket",u.includes("return")?u:`return ${u}`);e[o]=h(e||this.props.data,this.props.originalData,this.props.systemConfig,n,i,this.props.socket)}catch(h){console.error(`Cannot execute ${t}: ${h}`),e[o]=!a[o]||a[o].default===void 0?null:a[o].default}return e[o]}static flattenItems(t,e={}){return t&&Object.keys(t).forEach(i=>{t[i].items?Ls.flattenItems(t[i].items,e):e[i]=t[i]}),e}getDefaultValues(t,e){const i={enabled:!1},n=t.split(".")[0];if(this.jsonConfigs[n]&&!this.jsonConfigs[n].disabled){const a=Ls.flattenItems(this.jsonConfigs[n].json.items);if(a){const o=[],s=Object.keys(a).filter(l=>a[l]);s.forEach(l=>{!a[l].defaultFunc&&a[l].default!==void 0&&(i[l]=a[l].default)}),s.forEach(l=>{a[l].defaultFunc&&this._executeCustom(a[l].defaultFunc,i,e,this.jsonConfigs[n].instanceObjs[t],a,l,o)})}}return i}getCommonConfig(){const t=this.props.objectIDs||[],e=this.props.objects,i={};return this.props.customsInstances.forEach(n=>{const a=n.split(".")[0];this.jsonConfigs[a]&&this.jsonConfigs[a].disabled||(i[n]={},t.forEach(o=>{var u;const s=e[o],l=(u=s==null?void 0:s.common)!=null&&u.custom&&s.common.custom[n]||null;if(l)Object.keys(l).forEach(h=>{h.startsWith("_")||(i[n][h]===void 0?i[n][h]=l[h]:i[n][h]!==l[h]&&(Array.isArray(i[n][h])||(i[n][h]=[i[n][h]]),i[n][h].includes(l[h])||i[n][h].push(l[h])))});else{const h=this.getDefaultValues(n,s);h.enabled=!1,Object.keys(h).forEach(c=>{c.startsWith("_")||(i[n][c]===void 0?i[n][c]=h[c]:i[n][c]!==h[c]&&(Array.isArray(i[n][c])||(i[n][c]=[i[n][c]]),i[n][c].includes(h[c])||i[n][c].push(h[c])))})}}),Object.keys(i[n]).forEach(o=>{Array.isArray(i[n][o])&&i[n][o].sort()}))}),i}isChanged(t){return t=t||this.state.newValues,Object.keys(t).find(e=>t[e]===null||t[e]&&Object.keys(t[e]).find(i=>!i.startsWith("_")))}combineNewAndOld(t,e=!1){const i={...this.commonConfig[t]||{},...this.state.newValues[t]||{}};return e&&Object.keys(i).forEach(n=>{n.startsWith("_")&&delete i[n]}),this.state.newValues[t]===null&&(i.enabled=!1),i}renderOneCustom(t,e,i,n){var f,d;const a=t.split(".")[0],o=`${sw}/adapter/${a}/${this.props.objects[`system.adapter.${a}`].common.icon}`,s=this.state.newValues[t]!==void 0&&(!this.state.newValues[t]||this.state.newValues[t].enabled!==void 0)?!!(this.state.newValues[t]&&this.state.newValues[t].enabled):this.state.newValues[t]===null?!1:this.commonConfig[t].enabled,l=Array.isArray(s)&&(!this.state.newValues[t]||this.state.newValues[t].enabled===void 0),u=(d=(f=this.jsonConfigs[a])==null?void 0:f.json)==null?void 0:d.disabled,h=this.combineNewAndOld(t);if(u&&this.jsonConfigs[a].json.hidden===!0||typeof this.jsonConfigs[a].json.hidden=="string"&&this._executeCustom(this.jsonConfigs[a].json.hidden,h,i,e,this.jsonConfigs[a].json.items,"enabled",[]))return null;let c=null;return u&&this.jsonConfigs[a].json.help&&(typeof this.jsonConfigs[a].json.help=="object"?c=this.jsonConfigs[a].json.help[this.props.lang]||this.jsonConfigs[a].json.help.en:c=this.props.t(this.jsonConfigs[a].json.help)),y.jsxs(w.Accordion,{id:`Accordion_${t}`,style:n%2?Ut.accordionOdd:Ut.accordionEven,expanded:this.state.expanded.includes(t),ref:this.refTemplate[t],onChange:()=>{const p=[...this.state.expanded],v=p.indexOf(t);v===-1?p.push(t):p.splice(v,1),(window._localStorage||window.localStorage).setItem("App.customsExpanded",JSON.stringify(p)),v===-1&&(window._localStorage||window.localStorage).setItem("App.customsLastExpanded",t),this.setState({expanded:p})},children:[y.jsxs(w.AccordionSummary,{expandIcon:y.jsx(X.ExpandMore,{}),"data-id":t,style:n%2?s?Ut.accordionHeaderEnabledOdd:Ut.accordionHeaderOdd:s?Ut.accordionHeaderEnabledEven:Ut.accordionHeaderEven,children:[y.jsx("img",{src:o,style:Ut.headingIcon,alt:""}),y.jsx(w.Typography,{style:Ut.heading,children:this.props.t("Settings %s",t)}),y.jsx("div",{className:"titleEnabled",style:{...Ut.titleEnabled,...s?Ut.enabledVisible:Ut.enabledInvisible},children:this.props.t("Enabled")})]}),y.jsxs(w.AccordionDetails,{children:[y.jsx("div",{style:Ut.enabledControl,children:y.jsx(w.FormControlLabel,{style:Ut.formControl,control:y.jsx(w.Checkbox,{indeterminate:l,checked:!!s,disabled:!!u,onChange:p=>{this.cachedNewValues=this.cachedNewValues||this.state.newValues;const v=rn.deepClone(this.cachedNewValues);v[t]=v[t]||{},l||p.target.checked?v[t].enabled=!0:s&&this.commonConfig[t].enabled?v[t]=null:delete v[t],this.cachedNewValues=v,this.setState({newValues:v,hasChanges:this.isChanged(v)},()=>{this.cachedNewValues=void 0,this.props.onChange&&this.props.onChange(!!this.state.hasChanges)})}}),label:this.props.t("Enabled")})}),y.jsxs("div",{style:Ut.customControls,children:[!u&&(s||l)&&this.state.systemConfig?y.jsx(gh,{instanceObj:e,customObj:i,custom:!0,adapterName:a,instance:parseInt((t==null?void 0:t.split(".").pop())??"0",10)||0,socket:this.props.socket,themeName:this.props.themeName,themeType:this.props.themeType,theme:this.props.theme,multiEdit:this.props.objectIDs.length>1,schema:this.jsonConfigs[a].json,data:h,isFloatComma:this.props.systemConfig.common.isFloatComma,dateFormat:this.props.systemConfig.common.dateFormat,onError:p=>this.setState({error:p},()=>this.props.onError&&this.props.onError(p)),onValueChange:(p,v)=>{var m;this.cachedNewValues=this.cachedNewValues||this.state.newValues,console.log(`${p} => ${v}`);const g=rn.deepClone(this.cachedNewValues);g[t]=g[t]||{},JSON.stringify(Gl.getValue((m=this.commonConfig)==null?void 0:m[t],p))===JSON.stringify(v)?(Gl.setValue(g[t],p,null),Object.keys(g[t]).length||delete g[t]):Gl.setValue(g[t],p,v),this.cachedNewValues=g,this.setState({newValues:g,hasChanges:this.isChanged(g)},()=>{this.cachedNewValues=void 0,this.props.onChange&&this.props.onChange(!!this.state.hasChanges)})}}):null,c]})]})]},t)}renderErrorMessage(){return!!this.state.error&&y.jsx($x,{title:this.props.t("Error"),text:this.state.error?"Error":"",onClose:()=>this.setState({error:!1})})}getObject(t,e,i){return t[i]?Promise.resolve(t[i]):this.props.socket.getObject(i).then(n=>(e[i]=rn.deepClone(n),t[i]=n,n))}saveOneState(t,e,i,n){if(i=i||{},n=n||{},t!=null&&t.length){const a=this.state.maxOids||t.length;this.state.maxOids===null&&this.setState({maxOids:t.length},()=>this.props.onProgress(!0)),this.setState({progress:Math.round((a-t.length)/a*50)});const o=t.shift();this.getObject(i,n,o).then(s=>{var u,h,c;if(!s){window.alert(`Invalid object ${o}`);return}(u=s.common)!=null&&u.custom&&Object.keys(s.common.custom).forEach(f=>{(!s.common.custom[f]||!s.common.custom[f].enabled)&&(s.common.custom[f]=null)});const l=Object.keys(this.state.newValues);for(let f=0;f<l.length;f++){const d=l[f],p=this.combineNewAndOld(d,!0);if(p.enabled===!1)(c=(h=s.common)==null?void 0:h.custom)!=null&&c[d]&&(s.common.custom[d]=null);else if(p.enabled){if(s.common=s.common||{},Array.isArray(p.enabled)&&(!s.common.custom||!s.common.custom[d]||!s.common.custom[d].enabled)){s.common.custom&&s.common.custom[d]&&(s.common.custom[d]=null);continue}if(s.common.custom=s.common.custom||{},!s.common.custom[d]||!s.common.custom[d].enabled){const g=this.getDefaultValues(d,s);s.common.custom[d]=JSON.parse(JSON.stringify(g||{})),Object.keys(s.common.custom[d]).forEach(m=>{m.startsWith("_")&&delete s.common.custom[d][m]})}const v=this.props.objectIDs.length>1;s.common.custom[d].enabled=!0,Object.keys(p).forEach(g=>{if(!g.startsWith("_")){if(Array.isArray(p[g])&&v)return;s.common.custom[d][g]=p[g]}})}}setTimeout(()=>this.saveOneState(t,e,i,n),0)})}else{const a=Object.keys(i);if(!a.length)this.setState({maxOids:0},()=>this.props.onProgress(!1)),e&&e();else{this.setState({progress:Math.round((this.state.maxOids-a.length)/this.state.maxOids*50)+50});const o=a.shift();if(JSON.stringify(i[o].common)!==JSON.stringify(n[o].common)){this.changedIds.includes(o)||this.changedIds.push(o),this.props.socket.setObject(o,i[o]).then(async()=>{delete i[o],delete n[o],this.props.objects[o]=await this.props.socket.getObject(o),setTimeout(()=>this.saveOneState(t,e,i,n),0)});return}delete i[o],delete n[o],setTimeout(()=>this.saveOneState(t,e,i,n),0)}}}renderConfirmationDialog(){return this.state.showConfirmation?y.jsx(mh,{text:this.props.t("The changes will be applied to %s states. Are you sure?",this.props.objectIDs.length.toString()),ok:this.props.t("Yes"),onClose:t=>{t?this.setState({showConfirmation:!1,confirmed:!0},()=>{const e=this.cb;this.cb=void 0,this.onSave(e)}):(this.cb=void 0,this.setState({showConfirmation:!1}))}}):null}onSave=t=>{this.props.objectIDs.length>10&&!this.state.confirmed?(this.cb=t,this.setState({showConfirmation:!0})):this.saveOneState([...this.props.objectIDs],()=>{this.cachedNewValues={},this.commonConfig=this.getCommonConfig(),this.setState({confirmed:!1,hasChanges:void 0,newValues:{}},()=>{this.props.reportChangedIds(this.changedIds),this.props.onChange(!1,!0),t&&setTimeout(()=>t(),100)})})};render(){if(this.customObj===null)return y.jsx("div",{style:{color:"#F55",fontSize:32},children:this.props.t("Object does not exist!")});if(!this.state.loaded)return y.jsx(w.LinearProgress,{});let t=0;return y.jsxs(w.Paper,{style:Ut.paper,children:[this.state.maxOids>1&&y.jsx(w.LinearProgress,{color:"secondary",variant:"determinate",value:this.state.progress}),y.jsx("div",{style:Ut.scrollDiv,ref:this.scrollDivRef,children:this.state.maxOids===0&&Object.values(this.jsonConfigs).map(e=>e?Object.keys(e.instanceObjs).map(i=>this.renderOneCustom(i,e.instanceObjs[i],this.customObj,t++)):null)}),this.renderErrorMessage(),this.renderConfirmationDialog()]})}}const lw=Wn()(Ls),{loadShare:uw}=ew,{initPromise:hw}=tw,cw=hw.then(r=>uw("date-fns/locale",{customShareInfo:{shareConfig:{singleton:!0,strictVersion:!1,requiredVersion:"*"}}})),fw=await cw.then(r=>r());var we=fw;const Os={en:we.enUS,fr:we.fr,ru:we.ru,de:we.de,es:we.es,br:we.ptBR,nl:we.nl,it:we.it,pt:we.pt,pl:we.pl,uk:we.uk,"zh-cn":we.zhCN},rt={paper:{height:"100%",maxHeight:"100%",maxWidth:"100%",overflow:"hidden"},tableDiv:r=>({height:`calc(100% - ${parseInt(r.mixins.toolbar.minHeight,10)+8}px)`,overflow:"hidden",width:"100%"}),container:{height:"100%"},table:r=>({minWidth:960,width:"100%","& td:nth-of-type(5)":{overflow:"hidden",whiteSpace:"nowrap"},"& tr:nth-child(even)":{backgroundColor:r.palette.mode==="dark"?"#383838":"#b2b2b2"}}),row:{userSelect:"none",position:"relative","&:hover":{opacity:.7},"& td":{position:"relative"}},updatedRow:{animation:"updated 1s"},rowInterpolated:{opacity:.5},selectHistoryControl:{width:130},selectRelativeTime:{marginLeft:10,width:200},notAliveInstance:{opacity:.5},customRange:r=>({color:r.palette.primary.main}),rowSelected:r=>({backgroundColor:r.palette.secondary.main,color:r.palette.secondary.contrastText,"& td":{color:r.palette.secondary.contrastText,backgroundColor:r.palette.secondary.main}}),rowFocused:r=>({position:"absolute",pointerEvents:"none",top:0,bottom:0,left:0,right:0,m:"3px",border:`1px dotted ${r.palette.action.active}`}),grow:{flexGrow:1},msInput:{width:50,pt:"10px",ml:"5px","& label":{mt:"15px"}},cellAckTrue:r=>({color:r.palette.mode==="dark"?"#66ff7f":"#04a821"}),cellAckFalse:{color:"#FF6666"},toolbarDate:{width:124,mt:"9px","& fieldset":{display:"none"},"& input":{padding:"8px 0 0 0"},"& .MuiInputAdornment-root":{ml:0,mt:"7px"}},toolbarTime:{width:84,mt:"9px","& fieldset":{display:"none"},"& input":{padding:"8px 0 0 0"},"& .MuiInputAdornment-root":{ml:0,mt:"7px"}},toolbarTimeGrid:{position:"relative",marginLeft:8,paddingLeft:8,paddingRight:8,paddingTop:4,paddingBottom:4,border:"1px dotted #AAAAAA",borderRadius:8,display:"flex"},toolbarTimeLabel:{position:"absolute",padding:8,fontSize:"0.8rem",left:2,top:-9},noLoadingProgress:{width:"100%",height:4},colValue:{},colAck:{},colFrom:{},colLastChange:{},colTs:{}};class Es extends at.Component{adminInstance;supportedFeaturesPromises;unit;timeTimer;readSupportedFeaturesTimeout;rangeValues;rangeRef;subscribes;localStorage;constructor(t){super(t),this.localStorage=window._localStorage||window.localStorage;let e=this.localStorage.getItem("App.relativeRange")||"absolute";const i=parseInt(this.localStorage.getItem("App.absoluteStart"),10)||0,n=parseInt(this.localStorage.getItem("App.absoluteEnd"),10)||0,a=this.localStorage.getItem("App.historySelected")||"",o=parseInt(this.localStorage.getItem("App.historyLastSelected"),10)||null,s=this.localStorage.getItem("App.historyLastSelectedColumn")||null;(!i||!n)&&(!e||e==="absolute")&&(e="30"),i&&n&&(e="absolute");let l;try{l=JSON.parse(a)}catch{l=[]}this.state={start:i,end:n,values:null,relativeRange:e,selected:l,lastSelected:o,lastSelectedColumn:s,historyInstance:"",updateOpened:!1,insertOpened:!1,historyInstances:null,lcVisible:!0,ackVisible:!0,fromVisible:!0,supportedFeatures:[],ampm:!1,edit:{}},this.adminInstance=parseInt(window.location.search.slice(1),10)||0,this.supportedFeaturesPromises={},this.unit=this.props.obj.common&&this.props.obj.common.unit?` ${this.props.obj.common.unit}`:"",this.timeTimer=void 0,this.subscribes=[],this.prepareData().then(()=>this.readHistoryRange()).then(()=>{e!=="absolute"?this.setRelativeInterval(this.state.relativeRange,!0):this.readHistory()})}readSupportedFeatures(t){return t=t||this.state.historyInstance,t?this.supportedFeaturesPromises[t]instanceof Promise?this.supportedFeaturesPromises[t]:(this.supportedFeaturesPromises[t]=new Promise(e=>{this.readSupportedFeaturesTimeout&&clearTimeout(this.readSupportedFeaturesTimeout),this.readSupportedFeaturesTimeout=setTimeout(()=>{this.readSupportedFeaturesTimeout=void 0,e([])},2e3),this.props.socket.sendTo(t,"features",null).then(i=>{this.readSupportedFeaturesTimeout?(clearTimeout(this.readSupportedFeaturesTimeout),this.readSupportedFeaturesTimeout=void 0,e(i?i.supportedFeatures||[]:[])):this.setState({supportedFeatures:i?i.supportedFeatures||[]:[]})})}),this.supportedFeaturesPromises[t]):Promise.resolve([])}async componentDidMount(){await this.props.socket.subscribeState(this.props.obj._id,this.onChange)}componentWillUnmount(){this.timeTimer&&(clearTimeout(this.timeTimer),this.timeTimer=void 0);for(let t=0;t<this.subscribes.length;t++)this.props.socket.unsubscribeState(this.subscribes[t],this.onChange);this.subscribes=[],this.props.socket.unsubscribeState(this.props.obj._id,this.onChange)}onChange=(t,e)=>{if(t===this.props.obj._id&&e&&this.state.values&&(!this.state.values.length||this.state.values[this.state.values.length-1].ts<e.ts)){const i=[...this.state.values,e];this.setState({values:i})}else if(t.startsWith("system.adapter.")&&t.endsWith(".alive")){const i=t.substring(15,t.length-6),n=this.state.historyInstances,a=n.findIndex(o=>o.id===i);if(a!==-1&&n[a].alive!==!!(e!=null&&e.val)){const o=JSON.parse(JSON.stringify(n));o[a].alive=!!(e!=null&&e.val),this.setState({historyInstances:o},()=>{o[a].alive&&this.state.historyInstance===i&&this.readHistoryRange().then(()=>this.readHistory())})}}};async prepareData(){var o;const t=await this.getHistoryInstances(),e=await this.props.socket.getCompactSystemConfig(),i=(o=e==null?void 0:e.common)==null?void 0:o.defaultHistory;let n=this.localStorage.getItem("App.historyInstance")||"";if((!n||!t.find(s=>s.id===n&&s.alive))&&(n=i),!n||!t.find(s=>s.id===n&&s.alive)){const s=t.find(l=>l.alive);s&&(n=s.id)}!n&&t.length&&(n=i);const a=await this.readSupportedFeatures(n);await new Promise(s=>{this.setState({ampm:(e.common.dateFormat||"").includes("/"),historyInstances:t,historyInstance:n,supportedFeatures:a},()=>s())})}getHistoryInstances(){const t=[],e=[];return this.props.customsInstances.forEach(i=>{const n=this.props.objects[`system.adapter.${i}`];if(n&&n.common&&n.common.getHistory){const a={id:i,alive:!1};t.push(a),e.push(`system.adapter.${i}.alive`)}}),e.length?this.props.socket.getForeignStates(e).then(async i=>{Object.keys(i).forEach(n=>{var o;const a=t.find(s=>n.endsWith(`${s.id}.alive`));a&&(a.alive=!!((o=i[n])!=null&&o.val))}),this.subscribes=e;for(let n=0;n<e.length;n++)await this.props.socket.subscribeState(e[n],this.onChange);return t}):Promise.resolve(t)}readHistory(t,e){var i;return t=t||this.state.start,e=e||this.state.end,!this.state.historyInstance||!((i=this.state.historyInstances)!=null&&i.find(n=>n.id===this.state.historyInstance&&n.alive))?null:(this.setState({loading:!0}),this.props.socket.getHistory(this.props.obj._id,{instance:this.state.historyInstance,start:t,end:e,from:!0,ack:!0,q:!0,addId:!1,aggregate:"none",returnNewestEntries:!0}).then(n=>{const a=[],o=this.rangeValues;let s=!1,l=!1,u=!1;if(o&&o.length&&(!n||!n.length||o[0].ts<n[0].ts)&&(a.push(o[0]),a.push({ts:o[0].ts+1,e:!0}),console.log(`add ${new Date(o[0].ts).toISOString()}: ${o[0].val}`),!l&&o[0].ack!==void 0&&(l=!0),!u&&o[0].from&&(u=!0)),n!=null&&n.length)for(let h=0;h<n.length;h++)n[h]&&(!a.length||a[a.length-1].ts<n[h].ts)?(a.push(n[h]),n[h].from&&(n[h].from.startsWith("system.adapter.")?n[h].from=n[h].from.substring(15):n[h].from.startsWith("system.host.")&&(n[h].from=n[h].from.substring(7))),!s&&n[h].lc&&(s=!0),!l&&n[h].ack!==void 0&&(l=!0),!u&&n[h].from&&(u=!0),console.log(`add value ${new Date(n[h].ts).toISOString()}: ${n[h].val}`)):a[a.length-1].ts===n[h].ts&&a[a.length-1].val!==n[h].ts&&console.error("Strange data!");else a.push({noDataForPeriod:!0});a.length||a.push({noData:!0}),this.setState({loading:!1,values:a,lcVisible:s,fromVisible:u,ackVisible:l})}))}readHistoryRange(){var i;const t=new Date,e=new Date(2e3,0,1);return!this.state.historyInstance||!((i=this.state.historyInstances)!=null&&i.find(n=>n.id===this.state.historyInstance&&n.alive))?Promise.resolve():(this.setState({loading:!0}),this.props.socket.getHistory(this.props.obj._id,{instance:this.state.historyInstance,start:e.getTime(),end:t.getTime(),limit:1,from:!1,ack:!1,q:!1,addId:!1,aggregate:"none"}).then(n=>{n.length?((n[0].val===null||n[0].ts===e.getTime())&&n.shift(),n.forEach(a=>a.i=!0),this.rangeValues=n,this.setState({loading:!1})):(this.rangeValues=[],this.setState({loading:!1}))}))}onToggleSelect(t,e,i){let n=[...this.state.selected];const a=n.indexOf(e);if(t.shiftKey&&this.state.lastSelected){let o=-1,s=-1;n=[];for(let l=0;l<this.state.values.length&&!(this.state.values[l].ts===e&&(o=l,s!==o&&n.push(this.state.values[l].ts),o!==-1&&s!==-1)||this.state.values[l].ts===this.state.lastSelected&&(s=l,s!==o&&n.push(this.state.values[l].ts),o!==-1&&s!==-1));l++)(o!==-1||s!==-1)&&n.push(this.state.values[l].ts)}else t.ctrlKey?(a!==-1?n.splice(a,1):n.push(e),n.sort()):n=[e];this.localStorage.setItem("App.historyLastSelected",e.toString()),this.localStorage.setItem("App.historyLastSelectedColumn",i),this.localStorage.setItem("App.historySelected",JSON.stringify(n)),this.setState({selected:n,lastSelected:e,lastSelectedColumn:i})}getTableRows(){const t=[];for(let e=this.state.values.length-1;e>=0;e--){const i=this.state.values[e],n=i.ts;if(i.e)t.push(y.jsxs(w.TableRow,{sx:{...rt.row,...rt.updatedRow,...rt.rowInterpolated},hover:!0,children:[y.jsx(w.TableCell,{}),y.jsx(w.TableCell,{children:"..."}),this.state.ackVisible?y.jsx(w.TableCell,{}):null,this.state.fromVisible?y.jsx(w.TableCell,{}):null,this.state.lcVisible?y.jsx(w.TableCell,{}):null]},n));else if(i.noData||i.noDataForPeriod)t.push(y.jsxs(w.TableRow,{sx:{...rt.row,...rt.updatedRow,...rt.rowNoData},hover:!0,children:[y.jsx(w.TableCell,{}),y.jsx(w.TableCell,{children:i.noData?this.props.t("No data in history"):this.props.t("No data in history for selected period")}),this.state.ackVisible?y.jsx(w.TableCell,{}):null,this.state.fromVisible?y.jsx(w.TableCell,{}):null,this.state.lcVisible?y.jsx(w.TableCell,{}):null]},i.noData?"nodata":""));else{const a=i.i,o=this.state.lastSelected===n;let s=i.val;this.props.isFloatComma&&this.props.obj.common.type==="number"&&s&&(s=s.toString().replace(".",",")),s===null&&(s="null"),s===void 0&&(s="_");const l=this.state.selected.includes(n);t.push(y.jsxs(w.TableRow,{sx:{...rt.row,...rt.updatedRow,...a?rt.rowInterpolated:void 0,...l?rt.rowSelected:void 0},children:[y.jsxs(w.TableCell,{onClick:u=>!a&&this.onToggleSelect(u,n,"ts"),children:[`${Es.formatTimestamp(i.ts)}`,o&&this.state.lastSelectedColumn==="ts"?y.jsx(w.Box,{component:"div",sx:rt.rowFocused}):""]}),y.jsxs(w.TableCell,{onClick:u=>!a&&this.onToggleSelect(u,n,"val"),children:[s+this.unit,o&&this.state.lastSelectedColumn==="val"?y.jsx(w.Box,{component:"div",sx:rt.rowFocused}):""]}),this.state.ackVisible?y.jsxs(w.TableCell,{onClick:u=>!a&&this.onToggleSelect(u,n,"ack"),sx:i.ack?rt.cellAckTrue:rt.cellAckFalse,children:[i.ack?"true":"false",o&&this.state.lastSelectedColumn==="ack"?y.jsx(w.Box,{component:"div",sx:rt.rowFocused}):""]}):null,this.state.fromVisible?y.jsxs(w.TableCell,{onClick:u=>!a&&this.onToggleSelect(u,n,"from"),children:[i.from||"",o&&this.state.lastSelectedColumn==="from"?y.jsx(w.Box,{component:"div",sx:rt.rowFocused}):""]}):null,this.state.lcVisible?y.jsxs(w.TableCell,{onClick:u=>!a&&this.onToggleSelect(u,n,"lc"),children:[i.lc?`${new Date(i.lc).toLocaleDateString()} ${new Date(i.lc).toLocaleTimeString()}.${(i.ts%1e3).toString().padStart(3,"0")}`:"",o&&this.state.lastSelectedColumn==="lc"?y.jsx(w.Box,{component:"div",sx:rt.rowFocused}):""]}):null]},n.toString()+(i.val||"").toString()))}}return t}shiftTime(){const t=new Date,e=6e4-t.getSeconds()-(1e3-t.getMilliseconds());t.getMilliseconds()&&t.setMilliseconds(1e3),t.getSeconds()&&t.setSeconds(60);const i=t.getTime();let n;const a=this.state.relativeRange;if(a==="day")t.setHours(0),t.setMinutes(0),t.setSeconds(0),n=t.getTime();else if(a==="week"){t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setMilliseconds(0);const o=t.getDay()||7;o!==1&&t.setHours(-24*(o-1)),n=t.getTime()}else if(a==="2weeks"){t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setDate(t.getDate()-7);const o=t.getDay()||7;o!==1&&t.setHours(-24*(o-1)),n=t.getTime()}else a==="month"?(t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setDate(1),n=t.getTime()):a==="year"?(t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setDate(1),t.setMonth(0),n=t.getTime()):a==="12months"?(t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setFullYear(t.getFullYear()-1),n=t.getTime()):n=i-parseInt(a,10)*6e4;this.setState({start:n,end:i},()=>this.readHistory()),this.timeTimer=setTimeout(()=>{this.timeTimer=void 0,this.shiftTime()},e||6e4)}setRelativeInterval(t,e){if(e||(this.localStorage.setItem("App.relativeRange",t.toString()),this.setState({relativeRange:t})),t==="absolute"){this.timeTimer&&(clearTimeout(this.timeTimer),this.timeTimer=void 0);return}this.localStorage.removeItem("App.absoluteStart"),this.localStorage.removeItem("App.absolute");const i=new Date;if(!this.timeTimer){const o=6e4-i.getSeconds()-(1e3-i.getMilliseconds());this.timeTimer=setTimeout(()=>{this.timeTimer=void 0,this.shiftTime()},o||6e4)}i.getMilliseconds()&&i.setMilliseconds(1e3),i.getSeconds()&&i.setSeconds(60);const n=i.getTime();let a;if(t==="day")i.setHours(0),i.setMinutes(0),i.setSeconds(0),a=i.getTime();else if(t==="week"){i.setHours(0),i.setMinutes(0),i.setSeconds(0);const o=i.getDay()||7;o!==1&&i.setHours(-24*(o-1)),a=i.getTime()}else if(t==="2weeks"){i.setHours(0),i.setMinutes(0),i.setSeconds(0),i.setDate(i.getDate()-7);const o=i.getDay()||7;o!==1&&i.setHours(-24*(o-1)),a=i.getTime()}else t==="month"?(i.setHours(0),i.setMinutes(0),i.setSeconds(0),i.setDate(1),a=i.getTime()):t==="year"?(i.setHours(0),i.setMinutes(0),i.setSeconds(0),i.setDate(1),i.setMonth(0),a=i.getTime()):t==="12months"?(i.setHours(0),i.setMinutes(0),i.setSeconds(0),i.setFullYear(i.getFullYear()-1),a=i.getTime()):(t=Number(t),a=n-t*6e4);this.setState({start:a,end:n},()=>this.readHistory())}renderTable(){var t;if(!this.state.historyInstance)return y.jsx("div",{style:{marginTop:20,fontSize:24},children:this.props.t("History instance not selected")});if(!((t=this.state.historyInstances)!=null&&t.find(e=>e.id===this.state.historyInstance&&e.alive)))return y.jsx("div",{style:{marginTop:20,fontSize:24},children:this.props.t("History instance not alive")});if(this.state.values){const e=[200,"auto"],i=[190,100];return this.state.ackVisible&&(e.push(50),i.push(50)),this.state.fromVisible&&(e.push(150),i.push(150)),this.state.lcVisible&&(e.push(200),i.push(190)),y.jsx(w.TableContainer,{style:rt.container,children:y.jsxs(Yx,{stickyHeader:!0,sx:rt.table,initialWidths:e,minWidths:i,dblTitle:this.props.t("ra_Double click to reset table layout"),children:[y.jsx(w.TableHead,{children:y.jsxs(w.TableRow,{children:[y.jsx(w.TableCell,{style:rt.colTs,children:this.props.t("Timestamp")}),y.jsx(w.TableCell,{style:rt.colValue,children:this.props.t("Value")}),this.state.ackVisible?y.jsx(w.TableCell,{style:rt.colAck,children:this.props.t("Ack")}):null,this.state.fromVisible?y.jsx(w.TableCell,{style:rt.colFrom,children:this.props.t("From")}):null,this.state.lcVisible?y.jsx(w.TableCell,{style:rt.colLastChange,children:this.props.t("lc")}):null]})}),y.jsx(w.TableBody,{children:this.getTableRows()})]})})}return y.jsx(w.LinearProgress,{})}renderDialogConfirm(){return y.jsxs(w.Dialog,{open:!!this.state.areYouSure,onClose:()=>this.setState({areYouSure:!1}),"aria-labelledby":"alert-dialog-title","aria-describedby":"alert-dialog-description",children:[y.jsx(w.DialogTitle,{id:"alert-dialog-title"}),y.jsxs(w.DialogContent,{children:[y.jsx(w.DialogContentText,{id:"alert-dialog-description",children:this.props.t("Are you sure?")}),y.jsx(w.FormControlLabel,{control:y.jsx(w.Checkbox,{value:this.state.suppressMessage,onChange:()=>this.setState({suppressMessage:!0})}),label:this.props.t("Suppress for 5 minutes")})]}),y.jsxs(w.DialogActions,{children:[y.jsx(w.Button,{variant:"contained",onClick:()=>this.setState({areYouSure:!1,suppressMessage:this.state.suppressMessage&&Date.now()},()=>this.onDelete()),color:"primary",autoFocus:!0,startIcon:y.jsx(X.Delete,{}),children:this.props.t("Delete")}),y.jsx(w.Button,{variant:"contained",onClick:()=>this.setState({areYouSure:!1}),color:"secondary",startIcon:y.jsx(X.Close,{}),children:this.props.t("Cancel")})]})]})}onDelete(){const t=this.state.selected.map(e=>({state:{ts:e},id:this.props.obj._id}));this.props.socket.sendTo(this.state.historyInstance,"delete",t).then(()=>this.readHistory())}onUpdate(){let t=this.state.edit.val;this.props.obj.common&&(this.props.obj.common.type==="number"?typeof t!="number"&&(t=parseFloat(t.toString().replace(",","."))):this.props.obj.common.type==="boolean"&&(t=t==="true"||t==="TRUE"||t===!0||t==="1"||t===1));const e={val:t,ack:this.state.edit.ack,ts:this.state.selected[0],from:`system.adapter.admin.${this.adminInstance}`,q:this.state.edit.q};for(const[i,n]of Object.entries(e))n===void 0&&delete e[i];!this.state.lcVisible&&e.lc&&delete e.lc,this.props.socket.sendTo(this.state.historyInstance,"update",[{id:this.props.obj._id,state:e}]).then(()=>this.readHistory())}onInsert(){let t=this.state.edit.val;this.props.obj.common&&(this.props.obj.common.type==="number"?t=parseFloat(t.toString().replace(",",".")):this.props.obj.common.type==="boolean"&&(t=t==="true"||t==="TRUE"||t===!0||t==="1"||t===1));const e=this.state.edit.date;e.setHours(this.state.edit.time.getHours()),e.setMinutes(this.state.edit.time.getMinutes()),e.setSeconds(this.state.edit.time.getSeconds()),e.setMilliseconds(parseInt(this.state.edit.ms,10));const i={ts:e.getTime(),val:t,ack:this.state.edit.ack,from:`system.adapter.admin.${this.adminInstance}`,q:this.state.edit.q||0};!this.state.lcVisible&&i.lc&&delete i.lc;for(const[n,a]of Object.entries(i))a===void 0&&delete i[n];this.props.socket.sendTo(this.state.historyInstance,"insert",[{id:this.props.obj._id,state:i}]).then(()=>this.readHistory())}updateEdit(t,e){const i=JSON.parse(JSON.stringify(this.state.edit));i.time=new Date(i.time),i.date=new Date(i.date),i[t]=e,this.setState({edit:i})}renderEditDialog(){return y.jsxs(w.Dialog,{open:this.state.updateOpened||this.state.insertOpened,onClose:()=>this.setState({updateOpened:!1,insertOpened:!1}),"aria-labelledby":"edit-dialog-title","aria-describedby":"edit-dialog-description",children:[y.jsx(w.DialogTitle,{id:"edit-dialog-title",children:this.state.updateOpened?this.props.t("Update entry"):this.props.t("Insert entry")}),y.jsx(w.DialogContent,{children:y.jsxs("form",{noValidate:!0,autoComplete:"off",children:[typeof this.state.edit.val=="boolean"?y.jsx(w.FormControlLabel,{control:y.jsx(w.Checkbox,{checked:this.state.edit.val,onChange:t=>this.updateEdit("val",t.target.checked)}),label:this.props.t("Value")}):y.jsx(w.TextField,{variant:"standard",label:this.props.t("Value"),value:this.state.edit.val,onChange:t=>this.updateEdit("val",t.target.value)}),y.jsx("br",{}),y.jsx(w.FormControlLabel,{control:y.jsx(w.Checkbox,{checked:this.state.edit.ack,onChange:t=>this.updateEdit("ack",t.target.checked)}),label:this.props.t("Acknowledged")}),this.state.insertOpened?y.jsx(qt.LocalizationProvider,{dateAdapter:ks,adapterLocale:Os[this.props.lang],children:y.jsxs("div",{style:rt.toolbarTimeGrid,children:[y.jsx("div",{style:rt.toolbarTimeLabel,children:this.props.t("Time")}),y.jsx(qt.DatePicker,{sx:rt.toolbarDate,value:this.state.edit.date,onChange:t=>this.updateEdit("date",t)}),y.jsx(qt.TimePicker,{sx:rt.toolbarTime,ampm:this.state.ampm,views:["hours","minutes","seconds"],value:this.state.edit.time,onChange:t=>this.updateEdit("time",t)}),y.jsx(w.TextField,{variant:"standard",sx:rt.msInput,helperText:this.props.t("ms"),type:"number",slotProps:{htmlInput:{max:999,min:0}},value:this.state.edit.ms,onChange:t=>this.updateEdit("ms",t.target.value)})]})}):null]})}),y.jsxs(w.DialogActions,{children:[y.jsx(w.Button,{variant:"contained",disabled:this.state.edit.val==="",onClick:()=>{const t=this.state.updateOpened;this.setState({updateOpened:!1,insertOpened:!1},()=>t?this.onUpdate():this.onInsert())},color:"primary",autoFocus:!0,children:this.state.updateOpened?this.props.t("Update"):this.props.t("Add")}),y.jsx(w.Button,{variant:"contained",onClick:()=>this.setState({updateOpened:!1,insertOpened:!1}),color:"grey",children:this.props.t("Cancel")})]})]})}setStartDate(t){const e=t.getTime();this.timeTimer&&(clearTimeout(this.timeTimer),this.timeTimer=void 0),this.localStorage.setItem("App.relativeRange","absolute"),this.localStorage.setItem("App.absoluteStart",e.toString()),this.localStorage.setItem("App.absoluteEnd",this.state.end.toString()),this.setState({start:e,relativeRange:"absolute"},()=>this.readHistory())}setEndDate(t){const e=t.getTime();this.localStorage.setItem("App.relativeRange","absolute"),this.localStorage.setItem("App.absoluteStart",this.state.start.toString()),this.localStorage.setItem("App.absoluteEnd",e.toString()),this.timeTimer&&(clearTimeout(this.timeTimer),this.timeTimer=void 0),this.setState({end:e,relativeRange:"absolute"},()=>this.readHistory())}renderToolbar(){var t,e;return y.jsxs(w.Toolbar,{children:[y.jsxs(w.FormControl,{variant:"standard",style:rt.selectHistoryControl,children:[y.jsx(w.InputLabel,{children:this.props.t("History instance")}),y.jsx(w.Select,{variant:"standard",value:this.state.historyInstance||"",onChange:i=>{const n=i.target.value;this.localStorage.setItem("App.historyInstance",n),this.readSupportedFeatures(n).then(a=>this.setState({historyInstance:n,supportedFeatures:a},()=>this.readHistory()))},children:(t=this.state.historyInstances)==null?void 0:t.map(i=>y.jsx(w.MenuItem,{value:i.id,style:i.alive?void 0:rt.notAliveInstance,children:i.id},i.id))})]}),y.jsxs(w.FormControl,{variant:"standard",style:rt.selectRelativeTime,children:[y.jsx(w.InputLabel,{children:this.props.t("Relative")}),y.jsxs(w.Select,{variant:"standard",ref:this.rangeRef,value:this.state.relativeRange,onChange:i=>this.setRelativeInterval(i.target.value),children:[y.jsx(w.MenuItem,{value:"absolute",sx:rt.customRange,children:this.props.t("custom range")},"custom"),y.jsx(w.MenuItem,{value:10,children:this.props.t("last 10 minutes")},"1"),y.jsx(w.MenuItem,{value:30,children:this.props.t("last 30 minutes")},"2"),y.jsx(w.MenuItem,{value:60,children:this.props.t("last hour")},"3"),y.jsx(w.MenuItem,{value:"day",children:this.props.t("this day")},"4"),y.jsx(w.MenuItem,{value:24*60,children:this.props.t("last 24 hours")},"5"),y.jsx(w.MenuItem,{value:"week",children:this.props.t("this week")},"6"),y.jsx(w.MenuItem,{value:24*60*7,children:this.props.t("last week")},"7"),y.jsx(w.MenuItem,{value:"2weeks",children:this.props.t("this 2 weeks")},"8"),y.jsx(w.MenuItem,{value:24*60*14,children:this.props.t("last 2 weeks")},"9"),y.jsx(w.MenuItem,{value:"month",children:this.props.t("this month")},"10"),y.jsx(w.MenuItem,{value:30*24*60,children:this.props.t("last 30 days")},"11"),y.jsx(w.MenuItem,{value:"year",children:this.props.t("this year")},"12"),y.jsx(w.MenuItem,{value:"12months",children:this.props.t("last 12 months")},"13")]})]}),y.jsxs(qt.LocalizationProvider,{dateAdapter:ks,adapterLocale:Os[this.props.lang],children:[y.jsxs("div",{style:rt.toolbarTimeGrid,children:[y.jsx("div",{style:{...rt.toolbarTimeLabel,opacity:this.state.relativeRange!=="absolute"?.5:void 0},children:this.props.t("Start time")}),y.jsx(qt.DatePicker,{sx:rt.toolbarDate,disabled:this.state.relativeRange!=="absolute",value:new Date(this.state.start),onChange:i=>this.setStartDate(i)}),y.jsx(qt.TimePicker,{disabled:this.state.relativeRange!=="absolute",sx:rt.toolbarTime,ampm:this.state.ampm,value:new Date(this.state.start),onChange:i=>this.setStartDate(i)})]}),y.jsxs("div",{style:rt.toolbarTimeGrid,children:[y.jsx("div",{style:{...rt.toolbarTimeLabel,opacity:this.state.relativeRange!=="absolute"?.5:void 0},children:this.props.t("End time")}),y.jsx(qt.DatePicker,{disabled:this.state.relativeRange!=="absolute",sx:rt.toolbarDate,value:new Date(this.state.end),onChange:i=>this.setEndDate(i)}),y.jsx(qt.TimePicker,{disabled:this.state.relativeRange!=="absolute",sx:rt.toolbarTime,ampm:this.state.ampm,value:new Date(this.state.end),onChange:i=>this.setEndDate(i)})]})]}),y.jsx(w.Box,{component:"div",sx:rt.grow}),(e=this.state.values)!=null&&e.length?y.jsx(w.IconButton,{size:"large",onClick:()=>this.exportData(),title:this.props.t("Save data as csv"),children:y.jsx(rw,{})}):null,this.state.supportedFeatures.includes("insert")&&this.props.expertMode?y.jsx(w.IconButton,{size:"large",onClick:()=>{const i=new Date,n={ack:this.state.values[this.state.values.length-1].ack,val:this.state.values[this.state.values.length-1].val,date:new Date(i),ms:0,time:new Date(i),q:0};this.setState({edit:n,insertOpened:!0})},children:y.jsx(iw,{})}):null,this.state.supportedFeatures.includes("update")&&this.props.expertMode?y.jsx(w.IconButton,{size:"large",disabled:this.state.selected.length!==1,onClick:()=>{const i=JSON.parse(JSON.stringify(this.state.values.find(a=>a.ts===this.state.lastSelected))),n=new Date(i.ts);i.date=new Date(n),i.time=new Date(n),this.setState({edit:i,updateOpened:!0})},children:y.jsx(X.Edit,{})}):null,this.state.supportedFeatures.includes("delete")&&this.props.expertMode?y.jsx(w.IconButton,{size:"large",disabled:!this.state.selected.length,onClick:()=>{typeof this.state.suppressMessage=="number"&&Date.now()-this.state.suppressMessage<3e5?this.onDelete():this.setState({areYouSure:!0})},children:y.jsx(X.Delete,{})}):null]})}exportData(){let t=window.document.getElementById("export-file");t||(t=document.createElement("a"),t.setAttribute("id","export-file"),t.style.display="none",document.body.appendChild(t));const e=["timestamp;value;acknowledged;from;"];this.state.values.forEach(i=>!i.i&&!i.e&&e.push([Es.formatTimestamp(i.ts),i.val===null||i.val===void 0?"null":i.val.toString(),i.ack?"true":"false",i.from||""].join(";"))),t.setAttribute("href",`data:text/plain;charset=utf-8,${encodeURIComponent(e.join(`
|
|
1
|
+
import{j as y}from"./DefaultPropsProvider-BrbE0teb.js";import{i as at,R as vh}from"./iobroker_admin__loadShare__react__loadShare__-DtlEM_52.js";import{w as Wn,f as rn,J as gh,i as w,a as X,u as Gl,v as $x,D as mh,x as Yx,y as qt,z as ks,U as jt,B as Xx,M as Cd,R as yh,I as G,E as ty,K as Td,N as qx,O as Ad,P as Zx,b as Ca,Q as ey,q as Kx,V as Rs,W as Jx}from"./bootstrap-FCtLxt0T.js";import{l as Qx}from"./index-8HslT92O.js";import{a as tw,i as ew}from"./iobroker_admin__mf_v__runtimeInit__mf_v__-VDoBF19b.js";import{c as rw,d as iw,e as nw,f as Md}from"./index-HOidq_rM.js";import{a as aw}from"./_commonjsHelpers-D6-XlEtG.js";import{h as Ul}from"./zh-cn-CbEN7EL2.js";import{C as ow}from"./CustomModal-BNDSg_P8.js";import"./iobroker_admin__loadShare__prop_mf_2_types__loadShare__-BGyJCibC.js";import"./emotion-serialize.esm-BUa21YfQ.js";import"./iobroker_admin__loadShare___mf_0_emotion_mf_1_react__loadShare__-gw2iqPBS.js";import"./ace-CI9-Cq3I.js";import"./FilledInput-D-tz8rvg.js";import"./preload-helper-C1FmrZbK.js";import"./blueGrey-B0oIowPK.js";import"./emotion-cache.browser.esm-B8BFze5o.js";import"./iobroker_admin__loadShare__leaflet__loadShare__-B1OZ7tj-.js";import"./extends-CF3RwP-h.js";import"./iconBase-CgxZ5MMC.js";const Ut={paper:{height:"100%",maxHeight:"100%",maxWidth:"100%",overflow:"hidden"},headingIcon:{marginRight:5,width:32,height:32},titleEnabled:{float:"right",fontSize:16,color:"#7ff57f",textTransform:"uppercase",fontWeight:"bold",paddingLeft:20},scrollDiv:{width:"100%",height:"100%",overflow:"auto"},enabledControl:{width:130,display:"inline-block",verticalAlign:"top"},customControls:{width:"calc(100% - 130px)",maxWidth:800,display:"inline-block",verticalAlign:"top",paddingTop:16},accordionOdd:{},accordionEven:{backgroundColor:"rgba(128, 128, 128, 0.1)"},accordionHeaderOdd:{backgroundColor:"rgba(128, 128, 128, 0.2)"},accordionHeaderEven:{backgroundColor:"rgba(128, 128, 128, 0.3)"},accordionHeaderEnabledOdd:{backgroundColor:"rgba(128, 255, 128, 0.2)"},accordionHeaderEnabledEven:{backgroundColor:"rgba(128, 255, 128, 0.2)"},enabledVisible:{display:"inline-block"},enabledInvisible:{display:"none"}},sw=".";class Ls extends at.Component{changedIds;scrollDivRef;jsonConfigs;refTemplate;customObj;commonConfig={};cb;cachedNewValues;constructor(t){super(t);let e;try{e=JSON.parse((window._localStorage||window.localStorage).getItem("App.customsExpanded")||"[]")}catch{e=[]}this.changedIds=[],this.state={loaded:!1,expanded:e,newValues:{},confirmed:!1,showConfirmation:!1,maxOids:0,systemConfig:this.props.systemConfig},this.scrollDivRef=at.createRef(),this.jsonConfigs={},this.refTemplate={},this.props.customsInstances.map(i=>this.refTemplate[i]=at.createRef()),this.customObj=this.props.objectIDs.length>1?{common:{custom:{}},native:{}}:rn.deepClone(this.props.objects[this.props.objectIDs[0]]||null),this.customObj&&this.loadAllCustoms().then(()=>{this.commonConfig=this.getCommonConfig(),this.setState({loaded:!0,newValues:{}})})}async componentDidMount(){this.state.systemConfig||this.setState({systemConfig:await this.props.socket.getCompactSystemConfig()}),this.props.registerSaveFunc&&this.props.registerSaveFunc(this.onSave)}componentWillUnmount(){this.props.registerSaveFunc&&this.props.registerSaveFunc()}async loadAllCustoms(){const t=[];for(const e of this.props.customsInstances){if(e==="_")continue;const i=e.replace(/\.\d+$/,"").replace("system.adapter.","");this.jsonConfigs[i]===void 0&&(this.jsonConfigs[i]=null,t.push(this.getCustomTemplate(i)))}await Promise.all(t),this.props.customsInstances.forEach(e=>{var n,a;const i=e.replace(/\.\d+$/,"").replace("system.adapter.","");this.jsonConfigs[i]&&(this.jsonConfigs[i].instanceObjs=this.jsonConfigs[i].instanceObjs||{},this.jsonConfigs[i].instanceObjs[e]={_id:e,common:JSON.parse(JSON.stringify((n=this.props.objects[`system.adapter.${e}`])==null?void 0:n.common)),native:JSON.parse(JSON.stringify((a=this.props.objects[`system.adapter.${e}`])==null?void 0:a.native)),type:"instance",instanceObjects:[],objects:[]})})}async getCustomTemplate(t){var i;const e=this.props.objects[`system.adapter.${t}`]?rn.deepClone(this.props.objects[`system.adapter.${t}`]):null;if(!e){console.error(`Cannot find adapter "${t}"`);return}if(rn.fixAdminUI(e),((i=e.common)==null?void 0:i.adminUI.custom)==="json")try{const n=await this.props.socket.fileExists(`${t}.admin`,"jsonCustom.json5");let a,o;n?o=await this.props.socket.readFile(`${t}.admin`,"jsonCustom.json5"):o=await this.props.socket.readFile(`${t}.admin`,"jsonCustom.json"),o.file!==void 0?a=o.file:a=o;let s;try{s=Qx.parse(a),this.jsonConfigs[t]=this.jsonConfigs[t]||{},this.jsonConfigs[t].json=s}catch(l){console.error(`Cannot parse jsonConfig of ${t}: ${l}`),window.alert(`Cannot parse jsonConfig of ${t}: ${l}`)}await gh.loadI18n(this.props.socket,s.i18n,t);return}catch(n){console.error(`Cannot load jsonConfig of ${t}: ${n}`),window.alert(`Cannot load jsonConfig of ${t}: ${n}`)}console.error(`Adapter ${t} is not yet supported by this version of admin`),window.alert(`Adapter ${t} is not yet supported by this version of admin`)}_executeCustom(t,e,i,n,a,o,s){if(s.includes(o))return;s.push(o);let l=[],u;if(t&&typeof t=="object"?(l=t.alsoDependsOn||[],typeof l=="string"&&(l=[l]),u=t.func):u=t,l.forEach(h=>{if(!a[h])console.error(`[JsonConfigComponent] attribute "${h}" does not exist!`);else if(!a[h].defaultFunc)console.error(`[JsonConfigComponent] attribute "${h}" is not required to be includes in "alsoDependsOn" while has static value!`);else{const c=this._executeCustom(a[h].defaultFunc,e,i,n,a,h,s);c!==void 0&&(e[h]=c)}}),!u)e[o]=a[o].default===void 0?null:a[o].default;else try{const h=new Function("data","originalData","_system","instanceObj","customObj","_socket",u.includes("return")?u:`return ${u}`);e[o]=h(e||this.props.data,this.props.originalData,this.props.systemConfig,n,i,this.props.socket)}catch(h){console.error(`Cannot execute ${t}: ${h}`),e[o]=!a[o]||a[o].default===void 0?null:a[o].default}return e[o]}static flattenItems(t,e={}){return t&&Object.keys(t).forEach(i=>{t[i].items?Ls.flattenItems(t[i].items,e):e[i]=t[i]}),e}getDefaultValues(t,e){const i={enabled:!1},n=t.split(".")[0];if(this.jsonConfigs[n]&&!this.jsonConfigs[n].disabled){const a=Ls.flattenItems(this.jsonConfigs[n].json.items);if(a){const o=[],s=Object.keys(a).filter(l=>a[l]);s.forEach(l=>{!a[l].defaultFunc&&a[l].default!==void 0&&(i[l]=a[l].default)}),s.forEach(l=>{a[l].defaultFunc&&this._executeCustom(a[l].defaultFunc,i,e,this.jsonConfigs[n].instanceObjs[t],a,l,o)})}}return i}getCommonConfig(){const t=this.props.objectIDs||[],e=this.props.objects,i={};return this.props.customsInstances.forEach(n=>{const a=n.split(".")[0];this.jsonConfigs[a]&&this.jsonConfigs[a].disabled||(i[n]={},t.forEach(o=>{var u;const s=e[o],l=(u=s==null?void 0:s.common)!=null&&u.custom&&s.common.custom[n]||null;if(l)Object.keys(l).forEach(h=>{h.startsWith("_")||(i[n][h]===void 0?i[n][h]=l[h]:i[n][h]!==l[h]&&(Array.isArray(i[n][h])||(i[n][h]=[i[n][h]]),i[n][h].includes(l[h])||i[n][h].push(l[h])))});else{const h=this.getDefaultValues(n,s);h.enabled=!1,Object.keys(h).forEach(c=>{c.startsWith("_")||(i[n][c]===void 0?i[n][c]=h[c]:i[n][c]!==h[c]&&(Array.isArray(i[n][c])||(i[n][c]=[i[n][c]]),i[n][c].includes(h[c])||i[n][c].push(h[c])))})}}),Object.keys(i[n]).forEach(o=>{Array.isArray(i[n][o])&&i[n][o].sort()}))}),i}isChanged(t){return t=t||this.state.newValues,Object.keys(t).find(e=>t[e]===null||t[e]&&Object.keys(t[e]).find(i=>!i.startsWith("_")))}combineNewAndOld(t,e=!1){const i={...this.commonConfig[t]||{},...this.state.newValues[t]||{}};return e&&Object.keys(i).forEach(n=>{n.startsWith("_")&&delete i[n]}),this.state.newValues[t]===null&&(i.enabled=!1),i}renderOneCustom(t,e,i,n){var f,d;const a=t.split(".")[0],o=`${sw}/adapter/${a}/${this.props.objects[`system.adapter.${a}`].common.icon}`,s=this.state.newValues[t]!==void 0&&(!this.state.newValues[t]||this.state.newValues[t].enabled!==void 0)?!!(this.state.newValues[t]&&this.state.newValues[t].enabled):this.state.newValues[t]===null?!1:this.commonConfig[t].enabled,l=Array.isArray(s)&&(!this.state.newValues[t]||this.state.newValues[t].enabled===void 0),u=(d=(f=this.jsonConfigs[a])==null?void 0:f.json)==null?void 0:d.disabled,h=this.combineNewAndOld(t);if(u&&this.jsonConfigs[a].json.hidden===!0||typeof this.jsonConfigs[a].json.hidden=="string"&&this._executeCustom(this.jsonConfigs[a].json.hidden,h,i,e,this.jsonConfigs[a].json.items,"enabled",[]))return null;let c=null;return u&&this.jsonConfigs[a].json.help&&(typeof this.jsonConfigs[a].json.help=="object"?c=this.jsonConfigs[a].json.help[this.props.lang]||this.jsonConfigs[a].json.help.en:c=this.props.t(this.jsonConfigs[a].json.help)),y.jsxs(w.Accordion,{id:`Accordion_${t}`,style:n%2?Ut.accordionOdd:Ut.accordionEven,expanded:this.state.expanded.includes(t),ref:this.refTemplate[t],onChange:()=>{const p=[...this.state.expanded],v=p.indexOf(t);v===-1?p.push(t):p.splice(v,1),(window._localStorage||window.localStorage).setItem("App.customsExpanded",JSON.stringify(p)),v===-1&&(window._localStorage||window.localStorage).setItem("App.customsLastExpanded",t),this.setState({expanded:p})},children:[y.jsxs(w.AccordionSummary,{expandIcon:y.jsx(X.ExpandMore,{}),"data-id":t,style:n%2?s?Ut.accordionHeaderEnabledOdd:Ut.accordionHeaderOdd:s?Ut.accordionHeaderEnabledEven:Ut.accordionHeaderEven,children:[y.jsx("img",{src:o,style:Ut.headingIcon,alt:""}),y.jsx(w.Typography,{style:Ut.heading,children:this.props.t("Settings %s",t)}),y.jsx("div",{className:"titleEnabled",style:{...Ut.titleEnabled,...s?Ut.enabledVisible:Ut.enabledInvisible},children:this.props.t("Enabled")})]}),y.jsxs(w.AccordionDetails,{children:[y.jsx("div",{style:Ut.enabledControl,children:y.jsx(w.FormControlLabel,{style:Ut.formControl,control:y.jsx(w.Checkbox,{indeterminate:l,checked:!!s,disabled:!!u,onChange:p=>{this.cachedNewValues=this.cachedNewValues||this.state.newValues;const v=rn.deepClone(this.cachedNewValues);v[t]=v[t]||{},l||p.target.checked?v[t].enabled=!0:s&&this.commonConfig[t].enabled?v[t]=null:delete v[t],this.cachedNewValues=v,this.setState({newValues:v,hasChanges:this.isChanged(v)},()=>{this.cachedNewValues=void 0,this.props.onChange&&this.props.onChange(!!this.state.hasChanges)})}}),label:this.props.t("Enabled")})}),y.jsxs("div",{style:Ut.customControls,children:[!u&&(s||l)&&this.state.systemConfig?y.jsx(gh,{instanceObj:e,customObj:i,custom:!0,adapterName:a,instance:parseInt((t==null?void 0:t.split(".").pop())??"0",10)||0,socket:this.props.socket,themeName:this.props.themeName,themeType:this.props.themeType,theme:this.props.theme,multiEdit:this.props.objectIDs.length>1,schema:this.jsonConfigs[a].json,data:h,isFloatComma:this.props.systemConfig.common.isFloatComma,dateFormat:this.props.systemConfig.common.dateFormat,onError:p=>this.setState({error:p},()=>this.props.onError&&this.props.onError(p)),onValueChange:(p,v)=>{var m;this.cachedNewValues=this.cachedNewValues||this.state.newValues,console.log(`${p} => ${v}`);const g=rn.deepClone(this.cachedNewValues);g[t]=g[t]||{},JSON.stringify(Gl.getValue((m=this.commonConfig)==null?void 0:m[t],p))===JSON.stringify(v)?(Gl.setValue(g[t],p,null),Object.keys(g[t]).length||delete g[t]):Gl.setValue(g[t],p,v),this.cachedNewValues=g,this.setState({newValues:g,hasChanges:this.isChanged(g)},()=>{this.cachedNewValues=void 0,this.props.onChange&&this.props.onChange(!!this.state.hasChanges)})}}):null,c]})]})]},t)}renderErrorMessage(){return!!this.state.error&&y.jsx($x,{title:this.props.t("Error"),text:this.state.error?"Error":"",onClose:()=>this.setState({error:!1})})}getObject(t,e,i){return t[i]?Promise.resolve(t[i]):this.props.socket.getObject(i).then(n=>(e[i]=rn.deepClone(n),t[i]=n,n))}saveOneState(t,e,i,n){if(i=i||{},n=n||{},t!=null&&t.length){const a=this.state.maxOids||t.length;this.state.maxOids===null&&this.setState({maxOids:t.length},()=>this.props.onProgress(!0)),this.setState({progress:Math.round((a-t.length)/a*50)});const o=t.shift();this.getObject(i,n,o).then(s=>{var u,h,c;if(!s){window.alert(`Invalid object ${o}`);return}(u=s.common)!=null&&u.custom&&Object.keys(s.common.custom).forEach(f=>{(!s.common.custom[f]||!s.common.custom[f].enabled)&&(s.common.custom[f]=null)});const l=Object.keys(this.state.newValues);for(let f=0;f<l.length;f++){const d=l[f],p=this.combineNewAndOld(d,!0);if(p.enabled===!1)(c=(h=s.common)==null?void 0:h.custom)!=null&&c[d]&&(s.common.custom[d]=null);else if(p.enabled){if(s.common=s.common||{},Array.isArray(p.enabled)&&(!s.common.custom||!s.common.custom[d]||!s.common.custom[d].enabled)){s.common.custom&&s.common.custom[d]&&(s.common.custom[d]=null);continue}if(s.common.custom=s.common.custom||{},!s.common.custom[d]||!s.common.custom[d].enabled){const g=this.getDefaultValues(d,s);s.common.custom[d]=JSON.parse(JSON.stringify(g||{})),Object.keys(s.common.custom[d]).forEach(m=>{m.startsWith("_")&&delete s.common.custom[d][m]})}const v=this.props.objectIDs.length>1;s.common.custom[d].enabled=!0,Object.keys(p).forEach(g=>{if(!g.startsWith("_")){if(Array.isArray(p[g])&&v)return;s.common.custom[d][g]=p[g]}})}}setTimeout(()=>this.saveOneState(t,e,i,n),0)})}else{const a=Object.keys(i);if(!a.length)this.setState({maxOids:0},()=>this.props.onProgress(!1)),e&&e();else{this.setState({progress:Math.round((this.state.maxOids-a.length)/this.state.maxOids*50)+50});const o=a.shift();if(JSON.stringify(i[o].common)!==JSON.stringify(n[o].common)){this.changedIds.includes(o)||this.changedIds.push(o),this.props.socket.setObject(o,i[o]).then(async()=>{delete i[o],delete n[o],this.props.objects[o]=await this.props.socket.getObject(o),setTimeout(()=>this.saveOneState(t,e,i,n),0)});return}delete i[o],delete n[o],setTimeout(()=>this.saveOneState(t,e,i,n),0)}}}renderConfirmationDialog(){return this.state.showConfirmation?y.jsx(mh,{text:this.props.t("The changes will be applied to %s states. Are you sure?",this.props.objectIDs.length.toString()),ok:this.props.t("Yes"),onClose:t=>{t?this.setState({showConfirmation:!1,confirmed:!0},()=>{const e=this.cb;this.cb=void 0,this.onSave(e)}):(this.cb=void 0,this.setState({showConfirmation:!1}))}}):null}onSave=t=>{this.props.objectIDs.length>10&&!this.state.confirmed?(this.cb=t,this.setState({showConfirmation:!0})):this.saveOneState([...this.props.objectIDs],()=>{this.cachedNewValues={},this.commonConfig=this.getCommonConfig(),this.setState({confirmed:!1,hasChanges:void 0,newValues:{}},()=>{this.props.reportChangedIds(this.changedIds),this.props.onChange(!1,!0),t&&setTimeout(()=>t(),100)})})};render(){if(this.customObj===null)return y.jsx("div",{style:{color:"#F55",fontSize:32},children:this.props.t("Object does not exist!")});if(!this.state.loaded)return y.jsx(w.LinearProgress,{});let t=0;return y.jsxs(w.Paper,{style:Ut.paper,children:[this.state.maxOids>1&&y.jsx(w.LinearProgress,{color:"secondary",variant:"determinate",value:this.state.progress}),y.jsx("div",{style:Ut.scrollDiv,ref:this.scrollDivRef,children:this.state.maxOids===0&&Object.values(this.jsonConfigs).map(e=>e?Object.keys(e.instanceObjs).map(i=>this.renderOneCustom(i,e.instanceObjs[i],this.customObj,t++)):null)}),this.renderErrorMessage(),this.renderConfirmationDialog()]})}}const lw=Wn()(Ls),{loadShare:uw}=ew,{initPromise:hw}=tw,cw=hw.then(r=>uw("date-fns/locale",{customShareInfo:{shareConfig:{singleton:!0,strictVersion:!1,requiredVersion:"*"}}})),fw=await cw.then(r=>r());var we=fw;const Os={en:we.enUS,fr:we.fr,ru:we.ru,de:we.de,es:we.es,br:we.ptBR,nl:we.nl,it:we.it,pt:we.pt,pl:we.pl,uk:we.uk,"zh-cn":we.zhCN},rt={paper:{height:"100%",maxHeight:"100%",maxWidth:"100%",overflow:"hidden"},tableDiv:r=>({height:`calc(100% - ${parseInt(r.mixins.toolbar.minHeight,10)+8}px)`,overflow:"hidden",width:"100%"}),container:{height:"100%"},table:r=>({minWidth:960,width:"100%","& td:nth-of-type(5)":{overflow:"hidden",whiteSpace:"nowrap"},"& tr:nth-child(even)":{backgroundColor:r.palette.mode==="dark"?"#383838":"#b2b2b2"}}),row:{userSelect:"none",position:"relative","&:hover":{opacity:.7},"& td":{position:"relative"}},updatedRow:{animation:"updated 1s"},rowInterpolated:{opacity:.5},selectHistoryControl:{width:130},selectRelativeTime:{marginLeft:10,width:200},notAliveInstance:{opacity:.5},customRange:r=>({color:r.palette.primary.main}),rowSelected:r=>({backgroundColor:r.palette.secondary.main,color:r.palette.secondary.contrastText,"& td":{color:r.palette.secondary.contrastText,backgroundColor:r.palette.secondary.main}}),rowFocused:r=>({position:"absolute",pointerEvents:"none",top:0,bottom:0,left:0,right:0,m:"3px",border:`1px dotted ${r.palette.action.active}`}),grow:{flexGrow:1},msInput:{width:50,pt:"10px",ml:"5px","& label":{mt:"15px"}},cellAckTrue:r=>({color:r.palette.mode==="dark"?"#66ff7f":"#04a821"}),cellAckFalse:{color:"#FF6666"},toolbarDate:{width:124,mt:"9px","& fieldset":{display:"none"},"& input":{padding:"8px 0 0 0"},"& .MuiInputAdornment-root":{ml:0,mt:"7px"}},toolbarTime:{width:84,mt:"9px","& fieldset":{display:"none"},"& input":{padding:"8px 0 0 0"},"& .MuiInputAdornment-root":{ml:0,mt:"7px"}},toolbarTimeGrid:{position:"relative",marginLeft:8,paddingLeft:8,paddingRight:8,paddingTop:4,paddingBottom:4,border:"1px dotted #AAAAAA",borderRadius:8,display:"flex"},toolbarTimeLabel:{position:"absolute",padding:8,fontSize:"0.8rem",left:2,top:-9},noLoadingProgress:{width:"100%",height:4},colValue:{},colAck:{},colFrom:{},colLastChange:{},colTs:{}};class Es extends at.Component{adminInstance;supportedFeaturesPromises;unit;timeTimer;readSupportedFeaturesTimeout;rangeValues;rangeRef;subscribes;localStorage;constructor(t){super(t),this.localStorage=window._localStorage||window.localStorage;let e=this.localStorage.getItem("App.relativeRange")||"absolute";const i=parseInt(this.localStorage.getItem("App.absoluteStart"),10)||0,n=parseInt(this.localStorage.getItem("App.absoluteEnd"),10)||0,a=this.localStorage.getItem("App.historySelected")||"",o=parseInt(this.localStorage.getItem("App.historyLastSelected"),10)||null,s=this.localStorage.getItem("App.historyLastSelectedColumn")||null;(!i||!n)&&(!e||e==="absolute")&&(e="30"),i&&n&&(e="absolute");let l;try{l=JSON.parse(a)}catch{l=[]}this.state={start:i,end:n,values:null,relativeRange:e,selected:l,lastSelected:o,lastSelectedColumn:s,historyInstance:"",updateOpened:!1,insertOpened:!1,historyInstances:null,lcVisible:!0,ackVisible:!0,fromVisible:!0,supportedFeatures:[],ampm:!1,edit:{}},this.adminInstance=parseInt(window.location.search.slice(1),10)||0,this.supportedFeaturesPromises={},this.unit=this.props.obj.common&&this.props.obj.common.unit?` ${this.props.obj.common.unit}`:"",this.timeTimer=void 0,this.subscribes=[],this.prepareData().then(()=>this.readHistoryRange()).then(()=>{e!=="absolute"?this.setRelativeInterval(this.state.relativeRange,!0):this.readHistory()})}readSupportedFeatures(t){return t=t||this.state.historyInstance,t?this.supportedFeaturesPromises[t]instanceof Promise?this.supportedFeaturesPromises[t]:(this.supportedFeaturesPromises[t]=new Promise(e=>{this.readSupportedFeaturesTimeout&&clearTimeout(this.readSupportedFeaturesTimeout),this.readSupportedFeaturesTimeout=setTimeout(()=>{this.readSupportedFeaturesTimeout=void 0,e([])},2e3),this.props.socket.sendTo(t,"features",null).then(i=>{this.readSupportedFeaturesTimeout?(clearTimeout(this.readSupportedFeaturesTimeout),this.readSupportedFeaturesTimeout=void 0,e(i?i.supportedFeatures||[]:[])):this.setState({supportedFeatures:i?i.supportedFeatures||[]:[]})})}),this.supportedFeaturesPromises[t]):Promise.resolve([])}async componentDidMount(){await this.props.socket.subscribeState(this.props.obj._id,this.onChange)}componentWillUnmount(){this.timeTimer&&(clearTimeout(this.timeTimer),this.timeTimer=void 0);for(let t=0;t<this.subscribes.length;t++)this.props.socket.unsubscribeState(this.subscribes[t],this.onChange);this.subscribes=[],this.props.socket.unsubscribeState(this.props.obj._id,this.onChange)}onChange=(t,e)=>{if(t===this.props.obj._id&&e&&this.state.values&&(!this.state.values.length||this.state.values[this.state.values.length-1].ts<e.ts)){const i=[...this.state.values,e];this.setState({values:i})}else if(t.startsWith("system.adapter.")&&t.endsWith(".alive")){const i=t.substring(15,t.length-6),n=this.state.historyInstances,a=n.findIndex(o=>o.id===i);if(a!==-1&&n[a].alive!==!!(e!=null&&e.val)){const o=JSON.parse(JSON.stringify(n));o[a].alive=!!(e!=null&&e.val),this.setState({historyInstances:o},()=>{o[a].alive&&this.state.historyInstance===i&&this.readHistoryRange().then(()=>this.readHistory())})}}};async prepareData(){var o;const t=await this.getHistoryInstances(),e=await this.props.socket.getCompactSystemConfig(),i=(o=e==null?void 0:e.common)==null?void 0:o.defaultHistory;let n=this.localStorage.getItem("App.historyInstance")||"";if((!n||!t.find(s=>s.id===n&&s.alive))&&(n=i),!n||!t.find(s=>s.id===n&&s.alive)){const s=t.find(l=>l.alive);s&&(n=s.id)}!n&&t.length&&(n=i);const a=await this.readSupportedFeatures(n);await new Promise(s=>{this.setState({ampm:(e.common.dateFormat||"").includes("/"),historyInstances:t,historyInstance:n,supportedFeatures:a},()=>s())})}getHistoryInstances(){const t=[],e=[];return this.props.customsInstances.forEach(i=>{const n=this.props.objects[`system.adapter.${i}`];if(n&&n.common&&n.common.getHistory){const a={id:i,alive:!1};t.push(a),e.push(`system.adapter.${i}.alive`)}}),e.length?this.props.socket.getForeignStates(e).then(async i=>{Object.keys(i).forEach(n=>{var o;const a=t.find(s=>n.endsWith(`${s.id}.alive`));a&&(a.alive=!!((o=i[n])!=null&&o.val))}),this.subscribes=e;for(let n=0;n<e.length;n++)await this.props.socket.subscribeState(e[n],this.onChange);return t}):Promise.resolve(t)}readHistory(t,e){var i;return t=t||this.state.start,e=e||this.state.end,!this.state.historyInstance||!((i=this.state.historyInstances)!=null&&i.find(n=>n.id===this.state.historyInstance&&n.alive))?null:(this.setState({loading:!0}),this.props.socket.getHistory(this.props.obj._id,{instance:this.state.historyInstance,start:t,end:e,from:!0,ack:!0,q:!0,addId:!1,aggregate:"none",returnNewestEntries:!0}).then(n=>{const a=[],o=this.rangeValues;let s=!1,l=!1,u=!1;if(o&&o.length&&(!n||!n.length||o[0].ts<n[0].ts)&&(a.push(o[0]),a.push({ts:o[0].ts+1,e:!0}),console.log(`add ${new Date(o[0].ts).toISOString()}: ${o[0].val}`),!l&&o[0].ack!==void 0&&(l=!0),!u&&o[0].from&&(u=!0)),n!=null&&n.length)for(let h=0;h<n.length;h++)n[h]&&(!a.length||a[a.length-1].ts<n[h].ts)?(a.push(n[h]),n[h].from&&(n[h].from.startsWith("system.adapter.")?n[h].from=n[h].from.substring(15):n[h].from.startsWith("system.host.")&&(n[h].from=n[h].from.substring(7))),!s&&n[h].lc&&(s=!0),!l&&n[h].ack!==void 0&&(l=!0),!u&&n[h].from&&(u=!0),console.log(`add value ${new Date(n[h].ts).toISOString()}: ${n[h].val}`)):a[a.length-1].ts===n[h].ts&&a[a.length-1].val!==n[h].ts&&console.error("Strange data!");else a.push({noDataForPeriod:!0});a.length||a.push({noData:!0}),this.setState({loading:!1,values:a,lcVisible:s,fromVisible:u,ackVisible:l})}))}readHistoryRange(){var i;const t=new Date,e=new Date(2e3,0,1);return!this.state.historyInstance||!((i=this.state.historyInstances)!=null&&i.find(n=>n.id===this.state.historyInstance&&n.alive))?Promise.resolve():(this.setState({loading:!0}),this.props.socket.getHistory(this.props.obj._id,{instance:this.state.historyInstance,start:e.getTime(),end:t.getTime(),limit:1,from:!1,ack:!1,q:!1,addId:!1,aggregate:"none"}).then(n=>{n.length?((n[0].val===null||n[0].ts===e.getTime())&&n.shift(),n.forEach(a=>a.i=!0),this.rangeValues=n,this.setState({loading:!1})):(this.rangeValues=[],this.setState({loading:!1}))}))}onToggleSelect(t,e,i){let n=[...this.state.selected];const a=n.indexOf(e);if(t.shiftKey&&this.state.lastSelected){let o=-1,s=-1;n=[];for(let l=0;l<this.state.values.length&&!(this.state.values[l].ts===e&&(o=l,s!==o&&n.push(this.state.values[l].ts),o!==-1&&s!==-1)||this.state.values[l].ts===this.state.lastSelected&&(s=l,s!==o&&n.push(this.state.values[l].ts),o!==-1&&s!==-1));l++)(o!==-1||s!==-1)&&n.push(this.state.values[l].ts)}else t.ctrlKey?(a!==-1?n.splice(a,1):n.push(e),n.sort()):n=[e];this.localStorage.setItem("App.historyLastSelected",e.toString()),this.localStorage.setItem("App.historyLastSelectedColumn",i),this.localStorage.setItem("App.historySelected",JSON.stringify(n)),this.setState({selected:n,lastSelected:e,lastSelectedColumn:i})}getTableRows(){const t=[];for(let e=this.state.values.length-1;e>=0;e--){const i=this.state.values[e],n=i.ts;if(i.e)t.push(y.jsxs(w.TableRow,{sx:{...rt.row,...rt.updatedRow,...rt.rowInterpolated},hover:!0,children:[y.jsx(w.TableCell,{}),y.jsx(w.TableCell,{children:"..."}),this.state.ackVisible?y.jsx(w.TableCell,{}):null,this.state.fromVisible?y.jsx(w.TableCell,{}):null,this.state.lcVisible?y.jsx(w.TableCell,{}):null]},n));else if(i.noData||i.noDataForPeriod)t.push(y.jsxs(w.TableRow,{sx:{...rt.row,...rt.updatedRow,...rt.rowNoData},hover:!0,children:[y.jsx(w.TableCell,{}),y.jsx(w.TableCell,{children:i.noData?this.props.t("No data in history"):this.props.t("No data in history for selected period")}),this.state.ackVisible?y.jsx(w.TableCell,{}):null,this.state.fromVisible?y.jsx(w.TableCell,{}):null,this.state.lcVisible?y.jsx(w.TableCell,{}):null]},i.noData?"nodata":""));else{const a=i.i,o=this.state.lastSelected===n;let s=i.val;this.props.isFloatComma&&this.props.obj.common.type==="number"&&s&&(s=s.toString().replace(".",",")),s===null&&(s="null"),s===void 0&&(s="_");const l=this.state.selected.includes(n);t.push(y.jsxs(w.TableRow,{sx:{...rt.row,...rt.updatedRow,...a?rt.rowInterpolated:void 0,...l?rt.rowSelected:void 0},children:[y.jsxs(w.TableCell,{onClick:u=>!a&&this.onToggleSelect(u,n,"ts"),children:[`${Es.formatTimestamp(i.ts)}`,o&&this.state.lastSelectedColumn==="ts"?y.jsx(w.Box,{component:"div",sx:rt.rowFocused}):""]}),y.jsxs(w.TableCell,{onClick:u=>!a&&this.onToggleSelect(u,n,"val"),children:[s+this.unit,o&&this.state.lastSelectedColumn==="val"?y.jsx(w.Box,{component:"div",sx:rt.rowFocused}):""]}),this.state.ackVisible?y.jsxs(w.TableCell,{onClick:u=>!a&&this.onToggleSelect(u,n,"ack"),sx:i.ack?rt.cellAckTrue:rt.cellAckFalse,children:[i.ack?"true":"false",o&&this.state.lastSelectedColumn==="ack"?y.jsx(w.Box,{component:"div",sx:rt.rowFocused}):""]}):null,this.state.fromVisible?y.jsxs(w.TableCell,{onClick:u=>!a&&this.onToggleSelect(u,n,"from"),children:[i.from||"",o&&this.state.lastSelectedColumn==="from"?y.jsx(w.Box,{component:"div",sx:rt.rowFocused}):""]}):null,this.state.lcVisible?y.jsxs(w.TableCell,{onClick:u=>!a&&this.onToggleSelect(u,n,"lc"),children:[i.lc?`${new Date(i.lc).toLocaleDateString()} ${new Date(i.lc).toLocaleTimeString()}.${(i.ts%1e3).toString().padStart(3,"0")}`:"",o&&this.state.lastSelectedColumn==="lc"?y.jsx(w.Box,{component:"div",sx:rt.rowFocused}):""]}):null]},n.toString()+(i.val||"").toString()))}}return t}shiftTime(){const t=new Date,e=6e4-t.getSeconds()-(1e3-t.getMilliseconds());t.getMilliseconds()&&t.setMilliseconds(1e3),t.getSeconds()&&t.setSeconds(60);const i=t.getTime();let n;const a=this.state.relativeRange;if(a==="day")t.setHours(0),t.setMinutes(0),t.setSeconds(0),n=t.getTime();else if(a==="week"){t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setMilliseconds(0);const o=t.getDay()||7;o!==1&&t.setHours(-24*(o-1)),n=t.getTime()}else if(a==="2weeks"){t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setDate(t.getDate()-7);const o=t.getDay()||7;o!==1&&t.setHours(-24*(o-1)),n=t.getTime()}else a==="month"?(t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setDate(1),n=t.getTime()):a==="year"?(t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setDate(1),t.setMonth(0),n=t.getTime()):a==="12months"?(t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setFullYear(t.getFullYear()-1),n=t.getTime()):n=i-parseInt(a,10)*6e4;this.setState({start:n,end:i},()=>this.readHistory()),this.timeTimer=setTimeout(()=>{this.timeTimer=void 0,this.shiftTime()},e||6e4)}setRelativeInterval(t,e){if(e||(this.localStorage.setItem("App.relativeRange",t.toString()),this.setState({relativeRange:t})),t==="absolute"){this.timeTimer&&(clearTimeout(this.timeTimer),this.timeTimer=void 0);return}this.localStorage.removeItem("App.absoluteStart"),this.localStorage.removeItem("App.absolute");const i=new Date;if(!this.timeTimer){const o=6e4-i.getSeconds()-(1e3-i.getMilliseconds());this.timeTimer=setTimeout(()=>{this.timeTimer=void 0,this.shiftTime()},o||6e4)}i.getMilliseconds()&&i.setMilliseconds(1e3),i.getSeconds()&&i.setSeconds(60);const n=i.getTime();let a;if(t==="day")i.setHours(0),i.setMinutes(0),i.setSeconds(0),a=i.getTime();else if(t==="week"){i.setHours(0),i.setMinutes(0),i.setSeconds(0);const o=i.getDay()||7;o!==1&&i.setHours(-24*(o-1)),a=i.getTime()}else if(t==="2weeks"){i.setHours(0),i.setMinutes(0),i.setSeconds(0),i.setDate(i.getDate()-7);const o=i.getDay()||7;o!==1&&i.setHours(-24*(o-1)),a=i.getTime()}else t==="month"?(i.setHours(0),i.setMinutes(0),i.setSeconds(0),i.setDate(1),a=i.getTime()):t==="year"?(i.setHours(0),i.setMinutes(0),i.setSeconds(0),i.setDate(1),i.setMonth(0),a=i.getTime()):t==="12months"?(i.setHours(0),i.setMinutes(0),i.setSeconds(0),i.setFullYear(i.getFullYear()-1),a=i.getTime()):(t=Number(t),a=n-t*6e4);this.setState({start:a,end:n},()=>this.readHistory())}renderTable(){var t;if(!this.state.historyInstance)return y.jsx("div",{style:{marginTop:20,fontSize:24},children:this.props.t("History instance not selected")});if(!((t=this.state.historyInstances)!=null&&t.find(e=>e.id===this.state.historyInstance&&e.alive)))return y.jsx("div",{style:{marginTop:20,fontSize:24},children:this.props.t("History instance not alive")});if(this.state.values){const e=[200,"auto"],i=[190,100];return this.state.ackVisible&&(e.push(50),i.push(50)),this.state.fromVisible&&(e.push(150),i.push(150)),this.state.lcVisible&&(e.push(200),i.push(190)),y.jsx(w.TableContainer,{style:rt.container,children:y.jsxs(Yx,{stickyHeader:!0,sx:rt.table,initialWidths:e,minWidths:i,dblTitle:this.props.t("ra_Double click to reset table layout"),children:[y.jsx(w.TableHead,{children:y.jsxs(w.TableRow,{children:[y.jsx(w.TableCell,{style:rt.colTs,children:this.props.t("Timestamp")}),y.jsx(w.TableCell,{style:rt.colValue,children:this.props.t("Value")}),this.state.ackVisible?y.jsx(w.TableCell,{style:rt.colAck,children:this.props.t("Ack")}):null,this.state.fromVisible?y.jsx(w.TableCell,{style:rt.colFrom,children:this.props.t("From")}):null,this.state.lcVisible?y.jsx(w.TableCell,{style:rt.colLastChange,children:this.props.t("lc")}):null]})}),y.jsx(w.TableBody,{children:this.getTableRows()})]})})}return y.jsx(w.LinearProgress,{})}renderDialogConfirm(){return y.jsxs(w.Dialog,{open:!!this.state.areYouSure,onClose:()=>this.setState({areYouSure:!1}),"aria-labelledby":"alert-dialog-title","aria-describedby":"alert-dialog-description",children:[y.jsx(w.DialogTitle,{id:"alert-dialog-title"}),y.jsxs(w.DialogContent,{children:[y.jsx(w.DialogContentText,{id:"alert-dialog-description",children:this.props.t("Are you sure?")}),y.jsx(w.FormControlLabel,{control:y.jsx(w.Checkbox,{value:this.state.suppressMessage,onChange:()=>this.setState({suppressMessage:!0})}),label:this.props.t("Suppress for 5 minutes")})]}),y.jsxs(w.DialogActions,{children:[y.jsx(w.Button,{variant:"contained",onClick:()=>this.setState({areYouSure:!1,suppressMessage:this.state.suppressMessage&&Date.now()},()=>this.onDelete()),color:"primary",autoFocus:!0,startIcon:y.jsx(X.Delete,{}),children:this.props.t("Delete")}),y.jsx(w.Button,{variant:"contained",onClick:()=>this.setState({areYouSure:!1}),color:"secondary",startIcon:y.jsx(X.Close,{}),children:this.props.t("Cancel")})]})]})}onDelete(){const t=this.state.selected.map(e=>({state:{ts:e},id:this.props.obj._id}));this.props.socket.sendTo(this.state.historyInstance,"delete",t).then(()=>this.readHistory())}onUpdate(){let t=this.state.edit.val;this.props.obj.common&&(this.props.obj.common.type==="number"?typeof t!="number"&&(t=parseFloat(t.toString().replace(",","."))):this.props.obj.common.type==="boolean"&&(t=t==="true"||t==="TRUE"||t===!0||t==="1"||t===1));const e={val:t,ack:this.state.edit.ack,ts:this.state.selected[0],from:`system.adapter.admin.${this.adminInstance}`,q:this.state.edit.q};for(const[i,n]of Object.entries(e))n===void 0&&delete e[i];!this.state.lcVisible&&e.lc&&delete e.lc,this.props.socket.sendTo(this.state.historyInstance,"update",[{id:this.props.obj._id,state:e}]).then(()=>this.readHistory())}onInsert(){let t=this.state.edit.val;this.props.obj.common&&(this.props.obj.common.type==="number"?t=parseFloat(t.toString().replace(",",".")):this.props.obj.common.type==="boolean"&&(t=t==="true"||t==="TRUE"||t===!0||t==="1"||t===1));const e=this.state.edit.date;e.setHours(this.state.edit.time.getHours()),e.setMinutes(this.state.edit.time.getMinutes()),e.setSeconds(this.state.edit.time.getSeconds()),e.setMilliseconds(parseInt(this.state.edit.ms,10));const i={ts:e.getTime(),val:t,ack:this.state.edit.ack,from:`system.adapter.admin.${this.adminInstance}`,q:this.state.edit.q||0};!this.state.lcVisible&&i.lc&&delete i.lc;for(const[n,a]of Object.entries(i))a===void 0&&delete i[n];this.props.socket.sendTo(this.state.historyInstance,"insert",[{id:this.props.obj._id,state:i}]).then(()=>this.readHistory())}updateEdit(t,e){const i=JSON.parse(JSON.stringify(this.state.edit));i.time=new Date(i.time),i.date=new Date(i.date),i[t]=e,this.setState({edit:i})}renderEditDialog(){return y.jsxs(w.Dialog,{open:this.state.updateOpened||this.state.insertOpened,onClose:()=>this.setState({updateOpened:!1,insertOpened:!1}),"aria-labelledby":"edit-dialog-title","aria-describedby":"edit-dialog-description",children:[y.jsx(w.DialogTitle,{id:"edit-dialog-title",children:this.state.updateOpened?this.props.t("Update entry"):this.props.t("Insert entry")}),y.jsx(w.DialogContent,{children:y.jsxs("form",{noValidate:!0,autoComplete:"off",children:[typeof this.state.edit.val=="boolean"?y.jsx(w.FormControlLabel,{control:y.jsx(w.Checkbox,{checked:this.state.edit.val,onChange:t=>this.updateEdit("val",t.target.checked)}),label:this.props.t("Value")}):y.jsx(w.TextField,{variant:"standard",label:this.props.t("Value"),value:this.state.edit.val,onChange:t=>this.updateEdit("val",t.target.value)}),y.jsx("br",{}),y.jsx(w.FormControlLabel,{control:y.jsx(w.Checkbox,{checked:this.state.edit.ack,onChange:t=>this.updateEdit("ack",t.target.checked)}),label:this.props.t("Acknowledged")}),this.state.insertOpened?y.jsx(qt.LocalizationProvider,{dateAdapter:ks,adapterLocale:Os[this.props.lang],children:y.jsxs("div",{style:rt.toolbarTimeGrid,children:[y.jsx("div",{style:rt.toolbarTimeLabel,children:this.props.t("Time")}),y.jsx(qt.DatePicker,{sx:rt.toolbarDate,value:this.state.edit.date,onChange:t=>this.updateEdit("date",t)}),y.jsx(qt.TimePicker,{sx:rt.toolbarTime,ampm:this.state.ampm,views:["hours","minutes","seconds"],value:this.state.edit.time,onChange:t=>this.updateEdit("time",t)}),y.jsx(w.TextField,{variant:"standard",sx:rt.msInput,helperText:this.props.t("ms"),type:"number",slotProps:{htmlInput:{max:999,min:0}},value:this.state.edit.ms,onChange:t=>this.updateEdit("ms",t.target.value)})]})}):null]})}),y.jsxs(w.DialogActions,{children:[y.jsx(w.Button,{variant:"contained",disabled:this.state.edit.val==="",onClick:()=>{const t=this.state.updateOpened;this.setState({updateOpened:!1,insertOpened:!1},()=>t?this.onUpdate():this.onInsert())},color:"primary",autoFocus:!0,children:this.state.updateOpened?this.props.t("Update"):this.props.t("Add")}),y.jsx(w.Button,{variant:"contained",onClick:()=>this.setState({updateOpened:!1,insertOpened:!1}),color:"grey",children:this.props.t("Cancel")})]})]})}setStartDate(t){const e=t.getTime();this.timeTimer&&(clearTimeout(this.timeTimer),this.timeTimer=void 0),this.localStorage.setItem("App.relativeRange","absolute"),this.localStorage.setItem("App.absoluteStart",e.toString()),this.localStorage.setItem("App.absoluteEnd",this.state.end.toString()),this.setState({start:e,relativeRange:"absolute"},()=>this.readHistory())}setEndDate(t){const e=t.getTime();this.localStorage.setItem("App.relativeRange","absolute"),this.localStorage.setItem("App.absoluteStart",this.state.start.toString()),this.localStorage.setItem("App.absoluteEnd",e.toString()),this.timeTimer&&(clearTimeout(this.timeTimer),this.timeTimer=void 0),this.setState({end:e,relativeRange:"absolute"},()=>this.readHistory())}renderToolbar(){var t,e;return y.jsxs(w.Toolbar,{children:[y.jsxs(w.FormControl,{variant:"standard",style:rt.selectHistoryControl,children:[y.jsx(w.InputLabel,{children:this.props.t("History instance")}),y.jsx(w.Select,{variant:"standard",value:this.state.historyInstance||"",onChange:i=>{const n=i.target.value;this.localStorage.setItem("App.historyInstance",n),this.readSupportedFeatures(n).then(a=>this.setState({historyInstance:n,supportedFeatures:a},()=>this.readHistory()))},children:(t=this.state.historyInstances)==null?void 0:t.map(i=>y.jsx(w.MenuItem,{value:i.id,style:i.alive?void 0:rt.notAliveInstance,children:i.id},i.id))})]}),y.jsxs(w.FormControl,{variant:"standard",style:rt.selectRelativeTime,children:[y.jsx(w.InputLabel,{children:this.props.t("Relative")}),y.jsxs(w.Select,{variant:"standard",ref:this.rangeRef,value:this.state.relativeRange,onChange:i=>this.setRelativeInterval(i.target.value),children:[y.jsx(w.MenuItem,{value:"absolute",sx:rt.customRange,children:this.props.t("custom range")},"custom"),y.jsx(w.MenuItem,{value:10,children:this.props.t("last 10 minutes")},"1"),y.jsx(w.MenuItem,{value:30,children:this.props.t("last 30 minutes")},"2"),y.jsx(w.MenuItem,{value:60,children:this.props.t("last hour")},"3"),y.jsx(w.MenuItem,{value:"day",children:this.props.t("this day")},"4"),y.jsx(w.MenuItem,{value:24*60,children:this.props.t("last 24 hours")},"5"),y.jsx(w.MenuItem,{value:"week",children:this.props.t("this week")},"6"),y.jsx(w.MenuItem,{value:24*60*7,children:this.props.t("last week")},"7"),y.jsx(w.MenuItem,{value:"2weeks",children:this.props.t("this 2 weeks")},"8"),y.jsx(w.MenuItem,{value:24*60*14,children:this.props.t("last 2 weeks")},"9"),y.jsx(w.MenuItem,{value:"month",children:this.props.t("this month")},"10"),y.jsx(w.MenuItem,{value:30*24*60,children:this.props.t("last 30 days")},"11"),y.jsx(w.MenuItem,{value:"year",children:this.props.t("this year")},"12"),y.jsx(w.MenuItem,{value:"12months",children:this.props.t("last 12 months")},"13")]})]}),y.jsxs(qt.LocalizationProvider,{dateAdapter:ks,adapterLocale:Os[this.props.lang],children:[y.jsxs("div",{style:rt.toolbarTimeGrid,children:[y.jsx("div",{style:{...rt.toolbarTimeLabel,opacity:this.state.relativeRange!=="absolute"?.5:void 0},children:this.props.t("Start time")}),y.jsx(qt.DatePicker,{sx:rt.toolbarDate,disabled:this.state.relativeRange!=="absolute",value:new Date(this.state.start),onChange:i=>this.setStartDate(i)}),y.jsx(qt.TimePicker,{disabled:this.state.relativeRange!=="absolute",sx:rt.toolbarTime,ampm:this.state.ampm,value:new Date(this.state.start),onChange:i=>this.setStartDate(i)})]}),y.jsxs("div",{style:rt.toolbarTimeGrid,children:[y.jsx("div",{style:{...rt.toolbarTimeLabel,opacity:this.state.relativeRange!=="absolute"?.5:void 0},children:this.props.t("End time")}),y.jsx(qt.DatePicker,{disabled:this.state.relativeRange!=="absolute",sx:rt.toolbarDate,value:new Date(this.state.end),onChange:i=>this.setEndDate(i)}),y.jsx(qt.TimePicker,{disabled:this.state.relativeRange!=="absolute",sx:rt.toolbarTime,ampm:this.state.ampm,value:new Date(this.state.end),onChange:i=>this.setEndDate(i)})]})]}),y.jsx(w.Box,{component:"div",sx:rt.grow}),(e=this.state.values)!=null&&e.length?y.jsx(w.IconButton,{size:"large",onClick:()=>this.exportData(),title:this.props.t("Save data as csv"),children:y.jsx(rw,{})}):null,this.state.supportedFeatures.includes("insert")&&this.props.expertMode?y.jsx(w.IconButton,{size:"large",onClick:()=>{const i=new Date,n={ack:this.state.values[this.state.values.length-1].ack,val:this.state.values[this.state.values.length-1].val,date:new Date(i),ms:0,time:new Date(i),q:0};this.setState({edit:n,insertOpened:!0})},children:y.jsx(iw,{})}):null,this.state.supportedFeatures.includes("update")&&this.props.expertMode?y.jsx(w.IconButton,{size:"large",disabled:this.state.selected.length!==1,onClick:()=>{const i=JSON.parse(JSON.stringify(this.state.values.find(a=>a.ts===this.state.lastSelected))),n=new Date(i.ts);i.date=new Date(n),i.time=new Date(n),this.setState({edit:i,updateOpened:!0})},children:y.jsx(X.Edit,{})}):null,this.state.supportedFeatures.includes("delete")&&this.props.expertMode?y.jsx(w.IconButton,{size:"large",disabled:!this.state.selected.length,onClick:()=>{typeof this.state.suppressMessage=="number"&&Date.now()-this.state.suppressMessage<3e5?this.onDelete():this.setState({areYouSure:!0})},children:y.jsx(X.Delete,{})}):null]})}exportData(){let t=window.document.getElementById("export-file");t||(t=document.createElement("a"),t.setAttribute("id","export-file"),t.style.display="none",document.body.appendChild(t));const e=["timestamp;value;acknowledged;from;"];this.state.values.forEach(i=>!i.i&&!i.e&&e.push([Es.formatTimestamp(i.ts),i.val===null||i.val===void 0?"null":i.val.toString(),i.ack?"true":"false",i.from||""].join(";"))),t.setAttribute("href",`data:text/plain;charset=utf-8,${encodeURIComponent(e.join(`
|
|
2
2
|
`))}`),t.setAttribute("download",`${jt.getObjectName({[this.props.obj._id]:this.props.obj},this.props.obj._id,this.props.lang)}.csv`),t.click(),document.body.removeChild(t)}render(){return this.state.historyInstances?y.jsxs(w.Paper,{style:rt.paper,children:[this.state.loading?y.jsx(w.LinearProgress,{}):y.jsx("div",{style:rt.noLoadingProgress}),this.renderToolbar(),y.jsx(w.Box,{component:"div",sx:rt.tableDiv,children:this.renderTable()}),this.renderDialogConfirm(),this.renderEditDialog()]}):y.jsx(w.LinearProgress,{})}static formatTimestamp(t){return`${new Date(t).toLocaleDateString()} ${new Date(t).toLocaleTimeString()}.${(t%1e3).toString().padStart(3,"0")}`}}const dw=Wn()(Es);var ry={};/*! *****************************************************************************
|
|
3
3
|
Copyright (c) Microsoft Corporation.
|
|
4
4
|
|
|
@@ -57,4 +57,4 @@ yyyy`);var i=Le(t),n=e?"getUTC":"get",a=i[n+"FullYear"](),o=i[n+"Month"]()+1,s=i
|
|
|
57
57
|
`:"";function i(n){var a=n.children,o=n.tag,s=n.attrs,l=n.text;return XL(o,s)+(o!=="style"?Kt(l):l||"")+(a?""+e+V(a,function(u){return i(u)}).join(e)+e:"")+qL(o)}return i(r)}function ZL(r,t,e){e=e||{};var i=e.newline?`
|
|
58
58
|
`:"",n=" {"+i,a=i+"}",o=V(vt(r),function(l){return l+n+V(vt(r[l]),function(u){return u+":"+r[l][u]+";"}).join(i)+a}).join(i),s=V(vt(t),function(l){return"@keyframes "+l+n+V(vt(t[l]),function(u){return u+n+V(vt(t[l][u]),function(h){var c=t[l][u][h];return h==="d"&&(c='path("'+c+'")'),h+":"+c+";"}).join(i)+a}).join(i)+a}).join(i);return!o&&!s?"":["<![CDATA[",o,s,"]]>"].join(i)}function Rc(r){return{zrId:r,shadowCache:{},patternCache:{},gradientCache:{},clipPathCache:{},defs:{},cssNodes:{},cssAnims:{},cssStyleCache:{},cssAnimIdx:0,shadowIdx:0,gradientIdx:0,patternIdx:0,clipPathIdx:0}}function Bm(r,t,e,i){return Nt("svg","root",{width:r,height:t,xmlns:Px,"xmlns:xlink":kx,version:"1.1",baseProfile:"full",viewBox:i?"0 0 "+r+" "+t:!1},e)}var KL=0;function Lx(){return KL++}var zm={cubicIn:"0.32,0,0.67,0",cubicOut:"0.33,1,0.68,1",cubicInOut:"0.65,0,0.35,1",quadraticIn:"0.11,0,0.5,0",quadraticOut:"0.5,1,0.89,1",quadraticInOut:"0.45,0,0.55,1",quarticIn:"0.5,0,0.75,0",quarticOut:"0.25,1,0.5,1",quarticInOut:"0.76,0,0.24,1",quinticIn:"0.64,0,0.78,0",quinticOut:"0.22,1,0.36,1",quinticInOut:"0.83,0,0.17,1",sinusoidalIn:"0.12,0,0.39,0",sinusoidalOut:"0.61,1,0.88,1",sinusoidalInOut:"0.37,0,0.63,1",exponentialIn:"0.7,0,0.84,0",exponentialOut:"0.16,1,0.3,1",exponentialInOut:"0.87,0,0.13,1",circularIn:"0.55,0,1,0.45",circularOut:"0,0.55,0.45,1",circularInOut:"0.85,0,0.15,1"},Di="transform-origin";function JL(r,t,e){var i=N({},r.shape);N(i,t),r.buildPath(e,i);var n=new Ix;return n.reset(Fy(r)),e.rebuildPath(n,1),n.generateStr(),n.getStr()}function QL(r,t){var e=t.originX,i=t.originY;(e||i)&&(r[Di]=e+"px "+i+"px")}var tO={fill:"fill",opacity:"opacity",lineWidth:"stroke-width",lineDashOffset:"stroke-dashoffset"};function Ox(r,t){var e=t.zrId+"-ani-"+t.cssAnimIdx++;return t.cssAnims[e]=r,e}function eO(r,t,e){var i=r.shape.paths,n={},a,o;if(A(i,function(l){var u=Rc(e.zrId);u.animation=!0,Wl(l,{},u,!0);var h=u.cssAnims,c=u.cssNodes,f=vt(h),d=f.length;if(d){o=f[d-1];var p=h[o];for(var v in p){var g=p[v];n[v]=n[v]||{d:""},n[v].d+=g.d||""}for(var m in c){var _=c[m].animation;_.indexOf(o)>=0&&(a=_)}}}),!!a){t.d=!1;var s=Ox(n,e);return a.replace(o,s)}}function Vm(r){return U(r)?zm[r]?"cubic-bezier("+zm[r]+")":Yc(r)?r:"":""}function Wl(r,t,e,i){var n=r.animators,a=n.length,o=[];if(r instanceof hf){var s=eO(r,t,e);if(s)o.push(s);else if(!a)return}else if(!a)return;for(var l={},u=0;u<a;u++){var h=n[u],c=[h.getMaxTime()/1e3+"s"],f=Vm(h.getClip().easing),d=h.getDelay();f?c.push(f):c.push("linear"),d&&c.push(d/1e3+"s"),h.getLoop()&&c.push("infinite");var p=c.join(" ");l[p]=l[p]||[p,[]],l[p][1].push(h)}function v(_){var b=_[1],x=b.length,C={},S={},T={},M="animation-timing-function";function D(Lt,xt,z){for(var Y=Lt.getTracks(),K=Lt.getMaxTime(),Ot=0;Ot<Y.length;Ot++){var St=Y[Ot];if(St.needsAnimate()){var se=St.keyframes,je=St.propName;if(z&&(je=z(je)),je)for(var ei=0;ei<se.length;ei++){var Tr=se[ei],ri=Math.round(Tr.time/K*100)+"%",qn=Vm(Tr.easing),Zn=Tr.rawValue;(U(Zn)||At(Zn))&&(xt[ri]=xt[ri]||{},xt[ri][je]=Tr.rawValue,qn&&(xt[ri][M]=qn))}}}}for(var I=0;I<x;I++){var P=b[I],k=P.targetName;k?k==="shape"&&D(P,S):!i&&D(P,C)}for(var R in C){var L={};Wy(L,r),N(L,C[R]);var j=By(L),E=C[R][M];T[R]=j?{transform:j}:{},QL(T[R],L),E&&(T[R][M]=E)}var q,W=!0;for(var R in S){T[R]=T[R]||{};var $=!q,E=S[R][M];$&&(q=new Jr);var et=q.len();q.reset(),T[R].d=JL(r,S[R],q);var ut=q.len();if(!$&&et!==ut){W=!1;break}E&&(T[R][M]=E)}if(!W)for(var R in T)delete T[R].d;if(!i)for(var I=0;I<x;I++){var P=b[I],k=P.targetName;k==="style"&&D(P,T,function(Y){return tO[Y]})}for(var ot=vt(T),ft=!0,gt,I=1;I<ot.length;I++){var B=ot[I-1],Rt=ot[I];if(T[B][Di]!==T[Rt][Di]){ft=!1;break}gt=T[B][Di]}if(ft&>){for(var R in T)T[R][Di]&&delete T[R][Di];t[Di]=gt}if(It(ot,function(Lt){return vt(T[Lt]).length>0}).length){var Mt=Ox(T,e);return Mt+" "+_[0]+" both"}}for(var g in l){var s=v(l[g]);s&&o.push(s)}if(o.length){var m=e.zrId+"-cls-"+Lx();e.cssNodes["."+m]={animation:o.join(",")},t.class=m}}function rO(r,t,e){if(!r.ignore)if(r.isSilent()){var i={"pointer-events":"none"};Hm(i,t,e)}else{var n=r.states.emphasis&&r.states.emphasis.style?r.states.emphasis.style:{},a=n.fill;if(!a){var o=r.style&&r.style.fill,s=r.states.select&&r.states.select.style&&r.states.select.style.fill,l=r.currentStates.indexOf("select")>=0&&s||o;l&&(a=Hs(l))}var u=n.lineWidth;if(u){var h=!n.strokeNoScale&&r.transform?r.transform[0]:1;u=u/h}var i={cursor:"pointer"};a&&(i.fill=a),n.stroke&&(i.stroke=n.stroke),u&&(i["stroke-width"]=u),Hm(i,t,e)}}function Hm(r,t,e,i){var n=JSON.stringify(r),a=e.cssStyleCache[n];a||(a=e.zrId+"-cls-"+Lx(),e.cssStyleCache[n]=a,e.cssNodes["."+a+":hover"]=r),t.class=t.class?t.class+" "+a:a}var go=Math.round;function Ex(r){return r&&U(r.src)}function jx(r){return r&&tt(r.toDataURL)}function dd(r,t,e,i){UL(function(n,a){var o=n==="fill"||n==="stroke";o&&Ny(a)?Fx(t,r,n,i):o&&qc(a)?Bx(e,r,n,i):r[n]=a,o&&i.ssr&&a==="none"&&(r["pointer-events"]="visible")},t,e,!1),uO(e,r,i)}function pd(r,t){var e=Yy(t);e&&(e.each(function(i,n){i!=null&&(r[(Fm+n).toLowerCase()]=i+"")}),t.isSilent()&&(r[Fm+"silent"]="true"))}function Wm(r){return Wr(r[0]-1)&&Wr(r[1])&&Wr(r[2])&&Wr(r[3]-1)}function iO(r){return Wr(r[4])&&Wr(r[5])}function vd(r,t,e){if(t&&!(iO(t)&&Wm(t))){var i=1e4;r.transform=Wm(t)?"translate("+go(t[4]*i)/i+" "+go(t[5]*i)/i+")":dS(t)}}function Gm(r,t,e){for(var i=r.points,n=[],a=0;a<i.length;a++)n.push(go(i[a][0]*e)/e),n.push(go(i[a][1]*e)/e);t.points=n.join(" ")}function Um(r){return!r.smooth}function nO(r){var t=V(r,function(e){return typeof e=="string"?[e,e]:e});return function(e,i,n){for(var a=0;a<t.length;a++){var o=t[a],s=e[o[0]];s!=null&&(i[o[1]]=go(s*n)/n)}}}var aO={circle:[nO(["cx","cy","r"])],polyline:[Gm,Um],polygon:[Gm,Um]};function oO(r){for(var t=r.animators,e=0;e<t.length;e++)if(t[e].targetName==="shape")return!0;return!1}function Nx(r,t){var e=r.style,i=r.shape,n=aO[r.type],a={},o=t.animation,s="path",l=r.style.strokePercent,u=t.compress&&Fy(r)||4;if(n&&!t.willUpdate&&!(n[1]&&!n[1](i))&&!(o&&oO(r))&&!(l<1)){s=r.type;var h=Math.pow(10,u);n[0](i,a,h)}else{var c=!r.path||r.shapeChanged();r.path||r.createPathProxy();var f=r.path;c&&(f.beginPath(),r.buildPath(f,r.shape),r.pathUpdated());var d=f.getVersion(),p=r,v=p.__svgPathBuilder;(p.__svgPathVersion!==d||!v||l!==p.__svgPathStrokePercent)&&(v||(v=p.__svgPathBuilder=new Ix),v.reset(u),f.rebuildPath(v,l),v.generateStr(),p.__svgPathVersion=d,p.__svgPathStrokePercent=l),a.d=v.getStr()}return vd(a,r.transform),dd(a,e,r,t),pd(a,r),t.animation&&Wl(r,a,t),t.emphasis&&rO(r,a,t),Nt(s,r.id+"",a)}function sO(r,t){var e=r.style,i=e.image;if(i&&!U(i)&&(Ex(i)?i=i.src:jx(i)&&(i=i.toDataURL())),!!i){var n=e.x||0,a=e.y||0,o=e.width,s=e.height,l={href:i,width:o,height:s};return n&&(l.x=n),a&&(l.y=a),vd(l,r.transform),dd(l,e,r,t),pd(l,r),t.animation&&Wl(r,l,t),Nt("image",r.id+"",l)}}function lO(r,t){var e=r.style,i=e.text;if(i!=null&&(i+=""),!(!i||isNaN(e.x)||isNaN(e.y))){var n=e.font||qr,a=e.x||0,o=vS(e.y||0,cl(n),e.textBaseline),s=pS[e.textAlign]||e.textAlign,l={"dominant-baseline":"central","text-anchor":s};if(g0(e)){var u="",h=e.fontStyle,c=v0(e.fontSize);if(!parseFloat(c))return;var f=e.fontFamily||oy,d=e.fontWeight;u+="font-size:"+c+";font-family:"+f+";",h&&h!=="normal"&&(u+="font-style:"+h+";"),d&&d!=="normal"&&(u+="font-weight:"+d+";"),l.style=u}else l.style="font: "+n;return i.match(/\s/)&&(l["xml:space"]="preserve"),a&&(l.x=a),o&&(l.y=o),vd(l,r.transform),dd(l,e,r,t),pd(l,r),t.animation&&Wl(r,l,t),Nt("text",r.id+"",l,void 0,i)}}function $m(r,t){if(r instanceof bt)return Nx(r,t);if(r instanceof Ze)return sO(r,t);if(r instanceof no)return lO(r,t)}function uO(r,t,e){var i=r.style;if(gS(i)){var n=mS(r),a=e.shadowCache,o=a[n];if(!o){var s=r.getGlobalScale(),l=s[0],u=s[1];if(!l||!u)return;var h=i.shadowOffsetX||0,c=i.shadowOffsetY||0,f=i.shadowBlur,d=Ja(i.shadowColor),p=d.opacity,v=d.color,g=f/2/l,m=f/2/u,_=g+" "+m;o=e.zrId+"-s"+e.shadowIdx++,e.defs[o]=Nt("filter",o,{id:o,x:"-100%",y:"-100%",width:"300%",height:"300%"},[Nt("feDropShadow","",{dx:h/l,dy:c/u,stdDeviation:_,"flood-color":v,"flood-opacity":p})]),a[n]=o}t.filter=ul(o)}}function Fx(r,t,e,i){var n=r[e],a,o={gradientUnits:n.global?"userSpaceOnUse":"objectBoundingBox"};if(Ey(n))a="linearGradient",o.x1=n.x,o.y1=n.y,o.x2=n.x2,o.y2=n.y2;else if(jy(n))a="radialGradient",o.cx=Q(n.x,.5),o.cy=Q(n.y,.5),o.r=Q(n.r,.5);else return;for(var s=n.colorStops,l=[],u=0,h=s.length;u<h;++u){var c=Rh(s[u].offset)*100+"%",f=s[u].color,d=Ja(f),p=d.color,v=d.opacity,g={offset:c};g["stop-color"]=p,v<1&&(g["stop-opacity"]=v),l.push(Nt("stop",u+"",g))}var m=Nt(a,"",o,l),_=fd(m),b=i.gradientCache,x=b[_];x||(x=i.zrId+"-g"+i.gradientIdx++,b[_]=x,o.id=x,i.defs[x]=Nt(a,x,o,l)),t[e]=ul(x)}function Bx(r,t,e,i){var n=r.style[e],a=r.getBoundingRect(),o={},s=n.repeat,l=s==="no-repeat",u=s==="repeat-x",h=s==="repeat-y",c;if(Oy(n)){var f=n.imageWidth,d=n.imageHeight,p=void 0,v=n.image;if(U(v)?p=v:Ex(v)?p=v.src:jx(v)&&(p=v.toDataURL()),typeof Image>"u"){var g="Image width/height must been given explictly in svg-ssr renderer.";be(f,g),be(d,g)}else if(f==null||d==null){var m=function(I,P){if(I){var k=I.elm,R=f||P.width,L=d||P.height;I.tag==="pattern"&&(u?(L=1,R/=a.width):h&&(R=1,L/=a.height)),I.attrs.width=R,I.attrs.height=L,k&&(k.setAttribute("width",R),k.setAttribute("height",L))}},_=af(p,null,r,function(I){l||m(S,I),m(c,I)});_&&_.width&&_.height&&(f=f||_.width,d=d||_.height)}c=Nt("image","img",{href:p,width:f,height:d}),o.width=f,o.height=d}else n.svgElement&&(c=it(n.svgElement),o.width=n.svgWidth,o.height=n.svgHeight);if(c){var b,x;l?b=x=1:u?(x=1,b=o.width/a.width):h?(b=1,x=o.height/a.height):o.patternUnits="userSpaceOnUse",b!=null&&!isNaN(b)&&(o.width=b),x!=null&&!isNaN(x)&&(o.height=x);var C=By(n);C&&(o.patternTransform=C);var S=Nt("pattern","",o,[c]),T=fd(S),M=i.patternCache,D=M[T];D||(D=i.zrId+"-p"+i.patternIdx++,M[T]=D,o.id=D,S=i.defs[D]=Nt("pattern",D,o,[c])),t[e]=ul(D)}}function hO(r,t,e){var i=e.clipPathCache,n=e.defs,a=i[r.id];if(!a){a=e.zrId+"-c"+e.clipPathIdx++;var o={id:a};i[r.id]=a,n[a]=Nt("clipPath",a,o,[Nx(r,e)])}t["clip-path"]=ul(a)}function Ym(r){return document.createTextNode(r)}function ki(r,t,e){r.insertBefore(t,e)}function Xm(r,t){r.removeChild(t)}function qm(r,t){r.appendChild(t)}function zx(r){return r.parentNode}function Vx(r){return r.nextSibling}function ph(r,t){r.textContent=t}var Zm=58,cO=120,fO=Nt("","");function Lc(r){return r===void 0}function ir(r){return r!==void 0}function dO(r,t,e){for(var i={},n=t;n<=e;++n){var a=r[n].key;a!==void 0&&(i[a]=n)}return i}function Ra(r,t){var e=r.key===t.key,i=r.tag===t.tag;return i&&e}function mo(r){var t,e=r.children,i=r.tag;if(ir(i)){var n=r.elm=Rx(i);if(gd(fO,r),H(e))for(t=0;t<e.length;++t){var a=e[t];a!=null&&qm(n,mo(a))}else ir(r.text)&&!Z(r.text)&&qm(n,Ym(r.text))}else r.elm=Ym(r.text);return r.elm}function Hx(r,t,e,i,n){for(;i<=n;++i){var a=e[i];a!=null&&ki(r,mo(a),t)}}function al(r,t,e,i){for(;e<=i;++e){var n=t[e];if(n!=null)if(ir(n.tag)){var a=zx(n.elm);Xm(a,n.elm)}else Xm(r,n.elm)}}function gd(r,t){var e,i=t.elm,n=r&&r.attrs||{},a=t.attrs||{};if(n!==a){for(e in a){var o=a[e],s=n[e];s!==o&&(o===!0?i.setAttribute(e,""):o===!1?i.removeAttribute(e):e==="style"?i.style.cssText=o:e.charCodeAt(0)!==cO?i.setAttribute(e,o):e==="xmlns:xlink"||e==="xmlns"?i.setAttributeNS($L,e,o):e.charCodeAt(3)===Zm?i.setAttributeNS(YL,e,o):e.charCodeAt(5)===Zm?i.setAttributeNS(kx,e,o):i.setAttribute(e,o))}for(e in n)e in a||i.removeAttribute(e)}}function pO(r,t,e){for(var i=0,n=0,a=t.length-1,o=t[0],s=t[a],l=e.length-1,u=e[0],h=e[l],c,f,d,p;i<=a&&n<=l;)o==null?o=t[++i]:s==null?s=t[--a]:u==null?u=e[++n]:h==null?h=e[--l]:Ra(o,u)?(Sn(o,u),o=t[++i],u=e[++n]):Ra(s,h)?(Sn(s,h),s=t[--a],h=e[--l]):Ra(o,h)?(Sn(o,h),ki(r,o.elm,Vx(s.elm)),o=t[++i],h=e[--l]):Ra(s,u)?(Sn(s,u),ki(r,s.elm,o.elm),s=t[--a],u=e[++n]):(Lc(c)&&(c=dO(t,i,a)),f=c[u.key],Lc(f)?ki(r,mo(u),o.elm):(d=t[f],d.tag!==u.tag?ki(r,mo(u),o.elm):(Sn(d,u),t[f]=void 0,ki(r,d.elm,o.elm))),u=e[++n]);(i<=a||n<=l)&&(i>a?(p=e[l+1]==null?null:e[l+1].elm,Hx(r,p,e,n,l)):al(r,t,i,a))}function Sn(r,t){var e=t.elm=r.elm,i=r.children,n=t.children;r!==t&&(gd(r,t),Lc(t.text)?ir(i)&&ir(n)?i!==n&&pO(e,i,n):ir(n)?(ir(r.text)&&ph(e,""),Hx(e,null,n,0,n.length-1)):ir(i)?al(e,i,0,i.length-1):ir(r.text)&&ph(e,""):r.text!==t.text&&(ir(i)&&al(e,i,0,i.length-1),ph(e,t.text)))}function vO(r,t){if(Ra(r,t))Sn(r,t);else{var e=r.elm,i=zx(e);mo(t),i!==null&&(ki(i,t.elm,Vx(e)),al(i,[r],0,0))}return t}var gO=0,mO=function(){function r(t,e,i){if(this.type="svg",this.refreshHover=Km(),this.configLayer=Km(),this.storage=e,this._opts=i=N({},i),this.root=t,this._id="zr"+gO++,this._oldVNode=Bm(i.width,i.height),t&&!i.ssr){var n=this._viewport=document.createElement("div");n.style.cssText="position:relative;overflow:hidden";var a=this._svgDom=this._oldVNode.elm=Rx("svg");gd(null,this._oldVNode),n.appendChild(a),t.appendChild(n)}this.resize(i.width,i.height)}return r.prototype.getType=function(){return this.type},r.prototype.getViewportRoot=function(){return this._viewport},r.prototype.getViewportRootOffset=function(){var t=this.getViewportRoot();if(t)return{offsetLeft:t.offsetLeft||0,offsetTop:t.offsetTop||0}},r.prototype.getSvgDom=function(){return this._svgDom},r.prototype.refresh=function(){if(this.root){var t=this.renderToVNode({willUpdate:!0});t.attrs.style="position:absolute;left:0;top:0;user-select:none",vO(this._oldVNode,t),this._oldVNode=t}},r.prototype.renderOneToVNode=function(t){return $m(t,Rc(this._id))},r.prototype.renderToVNode=function(t){t=t||{};var e=this.storage.getDisplayList(!0),i=this._width,n=this._height,a=Rc(this._id);a.animation=t.animation,a.willUpdate=t.willUpdate,a.compress=t.compress,a.emphasis=t.emphasis,a.ssr=this._opts.ssr;var o=[],s=this._bgVNode=yO(i,n,this._backgroundColor,a);s&&o.push(s);var l=t.compress?null:this._mainVNode=Nt("g","main",{},[]);this._paintList(e,a,l?l.children:o),l&&o.push(l);var u=V(vt(a.defs),function(f){return a.defs[f]});if(u.length&&o.push(Nt("defs","defs",{},u)),t.animation){var h=ZL(a.cssNodes,a.cssAnims,{newline:!0});if(h){var c=Nt("style","stl",{},[],h);o.push(c)}}return Bm(i,n,o,t.useViewBox)},r.prototype.renderToString=function(t){return t=t||{},fd(this.renderToVNode({animation:Q(t.cssAnimation,!0),emphasis:Q(t.cssEmphasis,!0),willUpdate:!1,compress:!0,useViewBox:Q(t.useViewBox,!0)}),{newline:!0})},r.prototype.setBackgroundColor=function(t){this._backgroundColor=t},r.prototype.getSvgRoot=function(){return this._mainVNode&&this._mainVNode.elm},r.prototype._paintList=function(t,e,i){for(var n=t.length,a=[],o=0,s,l,u=0,h=0;h<n;h++){var c=t[h];if(!c.invisible){var f=c.__clipPaths,d=f&&f.length||0,p=l&&l.length||0,v=void 0;for(v=Math.max(d-1,p-1);v>=0&&!(f&&l&&f[v]===l[v]);v--);for(var g=p-1;g>v;g--)o--,s=a[o-1];for(var m=v+1;m<d;m++){var _={};hO(f[m],_,e);var b=Nt("g","clip-g-"+u++,_,[]);(s?s.children:i).push(b),a[o++]=b,s=b}l=f;var x=$m(c,e);x&&(s?s.children:i).push(x)}}},r.prototype.resize=function(t,e){var i=this._opts,n=this.root,a=this._viewport;if(t!=null&&(i.width=t),e!=null&&(i.height=e),n&&a&&(a.style.display="none",t=Xv(n,0,i),e=Xv(n,1,i),a.style.display=""),this._width!==t||this._height!==e){if(this._width=t,this._height=e,a){var o=a.style;o.width=t+"px",o.height=e+"px"}if(qc(this._backgroundColor))this.refresh();else{var s=this._svgDom;s&&(s.setAttribute("width",t),s.setAttribute("height",e));var l=this._bgVNode&&this._bgVNode.elm;l&&(l.setAttribute("width",t),l.setAttribute("height",e))}}},r.prototype.getWidth=function(){return this._width},r.prototype.getHeight=function(){return this._height},r.prototype.dispose=function(){this.root&&(this.root.innerHTML=""),this._svgDom=this._viewport=this.storage=this._oldVNode=this._bgVNode=this._mainVNode=null},r.prototype.clear=function(){this._svgDom&&(this._svgDom.innerHTML=null),this._oldVNode=null},r.prototype.toDataURL=function(t){var e=this.renderToString(),i="data:image/svg+xml;";return t?(e=_S(e),e&&i+"base64,"+e):i+"charset=UTF-8,"+encodeURIComponent(e)},r}();function Km(r){return function(){}}function yO(r,t,e,i){var n;if(e&&e!=="none")if(n=Nt("rect","bg",{width:r,height:t,x:"0",y:"0"}),Ny(e))Fx({fill:e},n.attrs,"fill",i);else if(qc(e))Bx({style:{fill:e},dirty:Gt,getBoundingRect:function(){return{width:r,height:t}}},n.attrs,"fill",i);else{var a=Ja(e),o=a.color,s=a.opacity;n.attrs.fill=o,s<1&&(n.attrs["fill-opacity"]=s)}return n}function _O(r){r.registerPainter("svg",mO)}const bO=""+new URL("echarts-BDq-rBJC.png",import.meta.url).href;Yi([BL,sL,IL,AL,gR,GP,_O]);const Et={paper:{height:"100%",maxHeight:"100%",maxWidth:"100%",overflow:"hidden",width:"100%"},chart:{width:"100%",overflow:"hidden"},chartWithToolbar:r=>({height:`calc(100% - ${parseInt(r.mixins.toolbar.minHeight,10)+8}px)`}),chartWithoutToolbar:{height:"100%"},selectHistoryControl:{width:130},selectRelativeTime:{marginLeft:10,width:200},notAliveInstance:{opacity:.5},customRange:r=>({color:r.palette.primary.main}),splitLineButtonIcon:{marginRight:8},grow:{flexGrow:1},toolbarDate:{width:124,mt:"9px","& fieldset":{display:"none"},"& input":{padding:"8px 0 0 0"},"& .MuiInputAdornment-root":{ml:0,mt:"7px"}},toolbarTime:{width:84,mt:"9px","& fieldset":{display:"none"},"& input":{padding:"8px 0 0 0"},"& .MuiInputAdornment-root":{ml:0,mt:"7px"}},toolbarTimeLabel:{position:"absolute",padding:8,fontSize:"0.8rem",left:2,top:-9},toolbarTimeGrid:{position:"relative",marginLeft:8,paddingLeft:8,paddingRight:8,paddingTop:4,paddingBottom:4,border:"1px dotted #AAAAAA",borderRadius:8,display:"flex"},buttonIcon:{width:24,height:24},echartsButton:{marginRight:8,height:34,width:34}},he=80,Mi=25;class xO extends at.Component{echartsReact;rangeRef;readTimeout=null;chartValues;rangeValues;subscribes;unit;divRef;chart;timerResize=null;updateTimer=null;minY;maxY;timeTimer=null;maxYLenTimeout=null;mouseDown;start;end;localStorage;constructor(t){if(super(t),this.localStorage=window._localStorage||window.localStorage,this.props.from)this.start=this.props.from;else{const a=new Date;a.setHours(a.getHours()-24*7),this.start=a.getTime()}this.props.end?this.end=this.props.end:this.end=Date.now();let e=this.localStorage.getItem("App.relativeRange")||"30";const i=parseInt(this.localStorage.getItem("App.absoluteStart"),10)||0,n=parseInt(this.localStorage.getItem("App.absoluteEnd"),10)||0;(!i||!n)&&(!e||e==="absolute")&&(e="30"),n&&i&&(e="absolute"),this.state={historyInstance:this.props.historyInstance||"",historyInstances:null,defaultHistory:"",chartHeight:300,chartWidth:500,ampm:!1,relativeRange:e,splitLine:this.localStorage.getItem("App.splitLine")==="true",min:i,max:n,maxYLen:0,stepType:"",echartsJump:!1},this.echartsReact=null,this.rangeRef=at.createRef(),this.readTimeout=null,this.chartValues=null,this.rangeValues=null,this.subscribes=[],this.unit=this.props.obj.common&&this.props.obj.common.unit?` ${this.props.obj.common.unit}`:"",this.divRef=at.createRef(),this.chart={}}componentDidMount(){this.props.socket.subscribeState(this.props.obj._id,this.onChange),window.addEventListener("resize",this.onResize),this.prepareData().then(()=>!this.props.noToolbar&&this.readHistoryRange()).then(()=>this.setRelativeInterval(this.state.relativeRange,!0,()=>this.forceUpdate()))}componentWillUnmount(){this.readTimeout&&(clearTimeout(this.readTimeout),this.readTimeout=null),this.timeTimer&&(clearTimeout(this.timeTimer),this.timeTimer=null),this.maxYLenTimeout&&(clearTimeout(this.maxYLenTimeout),this.maxYLenTimeout=null),this.timerResize&&(clearTimeout(this.timerResize),this.timerResize=null),this.updateTimer&&(clearTimeout(this.updateTimer),this.updateTimer=null),this.echartsReact&&this.echartsReact.getEchartsInstance().dispose();for(let t=0;t<this.subscribes.length;t++)this.props.socket.unsubscribeState(this.subscribes[t],this.onChange);this.subscribes=[],this.props.socket.unsubscribeState(this.props.obj._id,this.onChange),window.removeEventListener("resize",this.onResize)}onResize=()=>{this.timerResize&&clearTimeout(this.timerResize),this.timerResize=setTimeout(()=>{this.timerResize=null,this.componentDidUpdate()})};onChange=(t,e)=>{if(t===this.props.obj._id&&e&&this.rangeValues&&(!this.rangeValues.length||this.rangeValues[this.rangeValues.length-1].ts<e.ts))(!this.state.max||e.ts-this.state.max<12e4)&&(this.chartValues&&this.chartValues.push({val:e.val,ts:e.ts}),this.rangeValues.push({val:e.val,ts:e.ts}),e.ts>=this.chart.min&&e.ts<=this.chart.max+3e5&&this.updateChart());else if(t.startsWith("system.adapter.")&&t.endsWith(".alive")&&this.state.historyInstances){const i=t.substring(15,t.length-6),n=this.state.historyInstances,a=n.findIndex(o=>o.id===i);if(a!==-1&&n[a].alive!==!!(e!=null&&e.val)){const o=JSON.parse(JSON.stringify(n));o[a].alive=!!(e!=null&&e.val),this.setState({historyInstances:o},()=>{o[a].alive&&this.state.historyInstance===i&&this.readHistoryRange().then(()=>this.updateChart())})}}};async prepareData(){var s;if(this.props.noToolbar){const l=this.props.defaultHistory&&await this.props.socket.getState(`system.adapter.${this.props.defaultHistory}.alive`);this.subscribes.length||(this.subscribes=[`system.adapter.${this.props.defaultHistory}.alive`],await this.props.socket.subscribeState(`system.adapter.${this.props.defaultHistory}.alive`,this.onChange)),await new Promise(u=>{this.setState({defaultHistory:this.props.defaultHistory,historyInstance:this.props.defaultHistory,historyInstances:[{id:this.props.defaultHistory,alive:!!(l!=null&&l.val)}]},()=>u(null))});return}let t=await this.getHistoryInstances();const e=await this.props.socket.getCompactSystemConfig();let i=[];this.props.showJumpToEchart&&(i=await this.props.socket.getAdapterInstances("echarts",!0));const n=!!i.find(l=>l._id.startsWith("system.adapter.echarts.")),a=e&&e.common&&e.common.defaultHistory;this.props.obj.common.custom&&(t=t.filter(l=>this.props.obj.common.custom[l.id]));let o=this.localStorage.getItem("App.historyInstance")||"";if((!o||!t.find(l=>l.id===o&&l.alive))&&(o=a),!o||!t.find(l=>l.id===o&&l.alive)){const l=t.find(u=>u.alive);l&&(o=l.id)}!o&&t.length&&(o=a),this.setState({ampm:e.common.dateFormat.includes("/"),historyInstances:t,defaultHistory:a,historyInstance:o,echartsJump:n,stepType:this.props.obj.common.custom&&((s=this.props.obj.common.custom[o])==null?void 0:s.chartStep)||""})}getHistoryInstances(){if(this.props.historyInstance)return Promise.resolve([]);const t=[],e=[];return this.props.customsInstances.forEach(i=>{var a;const n=this.props.objects[`system.adapter.${i}`];if((a=n==null?void 0:n.common)!=null&&a.getHistory){const o={id:i,alive:!1};t.push(o),e.push(`system.adapter.${i}.alive`)}}),e.length?this.props.socket.getForeignStates(e).then(async i=>{Object.keys(i).forEach(n=>{var o;const a=t.find(s=>n.endsWith(`${s.id}.alive`));a&&(a.alive=!!((o=i[n])!=null&&o.val))}),this.subscribes=e;for(let n=0;n<e.length;n++)await this.props.socket.subscribeState(e[n],this.onChange);return t}):Promise.resolve(t)}readHistoryRange(){var i;const t=new Date,e=new Date(2e3,0,1);return(i=this.state.historyInstances)!=null&&i.find(n=>n.id===this.state.historyInstance&&n.alive)?this.props.socket.getHistory(this.props.obj._id,{instance:this.state.historyInstance,start:e.getTime(),end:t.getTime(),limit:1,from:!1,ack:!1,q:!1,addId:!1,aggregate:"none"}).then(n=>{var a;n&&((a=n[0])==null?void 0:a.val)===null&&n.shift(),this.rangeValues=n}):Promise.resolve()}readHistory(t,e){var n;if(!this.state.historyInstance||!((n=this.state.historyInstances)!=null&&n.find(a=>a.id===this.state.historyInstance&&a.alive)))return Promise.resolve([]);const i={instance:this.state.historyInstance,start:t,end:e,from:!1,ack:!1,q:!1,addId:!1,aggregate:"none",returnNewestEntries:!0};return e-t>6e4*24&&!(this.props.obj.common.type==="boolean"||this.props.obj.common.type==="number"&&this.props.obj.common.states)&&(i.aggregate="minmax"),this.props.socket.getHistory(this.props.obj._id,i).then(a=>{const o=[];let s=0;const l=this.rangeValues;let u=null,h=null;for(let c=0;c<a.length;c++){if(l)for(;s<l.length&&l[s].ts<a[c].ts;)o.push(l[s]),s++;!o.length||o[o.length-1].ts<a[c].ts?o.push(a[c]):o[o.length-1].ts===a[c].ts&&o[o.length-1].val!==a[c].ts&&console.error("Strange data!"),(u===null||a[c].val<u)&&(u=a[c].val),(h===null||a[c].val>h)&&(h=a[c].val)}if(l)for(;s<l.length;)o.push(l[s]),console.log(`add range ${new Date(l[s].ts).toISOString()}: ${l[s].val}`),s++;return o.sort((c,f)=>c.ts>f.ts?1:c.ts<f.ts?-1:0),this.chartValues=o,this.minY=u,this.maxY=h,this.minY<10?this.minY=Math.round(this.minY*10)/10:this.minY=Math.ceil(this.minY),this.maxY<10?this.maxY=Math.round(this.maxY*10)/10:this.maxY=Math.ceil(this.maxY),o})}convertData(t){t=t||this.chartValues;const e=[];if(!t.length)return[];for(let i=0;i<t.length;i++){const n={value:[t[i].ts,t[i].val]};t[i].i&&(n.exact=!1),e.push(n)}return this.chart.min||(this.chart.min=t[0].ts,this.chart.max=t[t.length-1].ts),e}getOption(){let t;if(this.minY!==null&&this.minY!==void 0&&(t=(this.minY.toString()+this.unit).length*9+12),this.maxY!==null&&this.maxY!==void 0){const a=(this.maxY.toString()+this.unit).length*9+12;a>t&&(t=a)}if(this.state.maxYLen){const a=this.state.maxYLen*9+12;a>t&&(t=a)}const e={xAxisIndex:0,type:"line",step:this.state.stepType==="stepStart"?"start":this.state.stepType==="stepMiddle"?"middle":this.state.stepType==="stepEnd"?"end":void 0,showSymbol:!1,hoverAnimation:!0,animation:!1,data:this.convertData(),lineStyle:{color:"#4dabf5"},areaStyle:{}},i={type:"value",boundaryGap:[0,"100%"],splitLine:{show:this.props.noToolbar||!!this.state.splitLine},splitNumber:Math.round(this.state.chartHeight/50),axisLabel:{formatter:a=>{let o;return this.props.isFloatComma?o=a.toString().replace(",",".")+this.unit:o=a+this.unit,this.state.maxYLen<o.length&&(this.maxYLenTimeout&&clearTimeout(this.maxYLenTimeout),this.maxYLenTimeout=setTimeout(s=>{this.maxYLenTimeout=null,this.setState({maxYLen:s})},200,o.length)),o},showMaxLabel:!0,showMinLabel:!0},axisTick:{alignWithLabel:!0}};if(this.props.obj.common.type==="boolean")e.step="end",i.axisLabel.showMaxLabel=!1,i.axisLabel.formatter=a=>a===1?"TRUE":"FALSE",i.max=1.5,i.interval=1,t=50;else if(this.props.obj.common.type==="number"&&this.props.obj.common.states){e.step="end",i.axisLabel.showMaxLabel=!1;const a=this.props.obj.common.states;i.axisLabel.formatter=l=>a[l]!==void 0?a[l]:l;const o=Object.keys(this.props.obj.common.states);o.sort(),i.max=parseFloat(o[o.length-1])+.5,i.interval=1;let s="";for(let l=0;l<o.length;l++)typeof a[o[l]]=="string"&&a[o[l]].length>s.length&&(s=a[o[l]]);t=(s.length*9||50)+12}const n=this.chart.withSeconds?Math.round((this.state.chartWidth-Mi-he)/100):Math.round((this.state.chartWidth-Mi-he)/60);return{backgroundColor:"transparent",title:{text:this.props.noToolbar?"":jt.getObjectNameFromObj(this.props.obj,this.props.lang),padding:[10,0,0,t?t+10:he+10]},grid:{left:t||he,top:8,right:this.props.noToolbar?5:Mi,bottom:40},tooltip:{trigger:"axis",formatter:a=>{const o=a[0],s=new Date(o.value[0]);let l=o.value[1];return l!==null&&this.props.isFloatComma&&(l=l.toString().replace(".",",")),`${o.exact===!1?"i":""}${s.toLocaleString()}.${s.getMilliseconds().toString().padStart(3,"0")}: ${l}${this.unit}`},axisPointer:{animation:!0}},xAxis:{splitLine:{show:!1},splitNumber:n,min:this.chart.min,max:this.chart.max,axisTick:{alignWithLabel:!0},axisLabel:{formatter:a=>{const o=new Date(a);return this.chart.withSeconds?`${o.getHours().toString().padStart(2,"0")}:${o.getMinutes().toString().padStart(2,"0")}:${o.getSeconds().toString().padStart(2,"0")}`:this.chart.withTime?`${o.getHours().toString().padStart(2,"0")}:${o.getMinutes().toString().padStart(2,"0")}
|
|
59
59
|
${o.getDate().toString().padStart(2,"0")}.${(o.getMonth()+1).toString().padStart(2,"0")}`:`${o.getDate().toString().padStart(2,"0")}.${(o.getMonth()+1).toString().padStart(2,"0")}
|
|
60
|
-
${o.getFullYear()}`}}},yAxis:i,toolbox:{left:"right",feature:this.props.noToolbar?void 0:{saveAsImage:{title:this.props.t("Save as image"),show:!0}}},series:[e]}}static getDerivedStateFromProps(t,e){return null}updateChart(t,e,i,n){t&&(this.start=t),e&&(this.end=e),t=t||this.start,e=e||this.end,this.readTimeout&&clearTimeout(this.readTimeout),this.readTimeout=setTimeout(()=>{var o;this.readTimeout=null;const a=this.chart.max-this.chart.min;a!==this.chart.diff&&(this.chart.diff=a,this.chart.withTime=this.chart.diff<36e5*24*7,this.chart.withSeconds=this.chart.diff<6e4*30),i?this.readHistory(t,e).then(s=>{var l;typeof((l=this.echartsReact)==null?void 0:l.getEchartsInstance)=="function"&&this.echartsReact.getEchartsInstance().setOption({series:[{data:this.convertData(s)}],xAxis:{min:this.chart.min,max:this.chart.max}}),n&&n()}):(typeof((o=this.echartsReact)==null?void 0:o.getEchartsInstance)=="function"&&this.echartsReact.getEchartsInstance().setOption({series:[{data:this.convertData()}],xAxis:{min:this.chart.min,max:this.chart.max}}),n&&n())},400)}setNewRange(t){var e;this.chart.diff=this.chart.max-this.chart.min,this.chart.withTime=this.chart.diff<36e5*24*7,this.chart.withSeconds=this.chart.diff<6e4*30,this.state.relativeRange!=="absolute"?(this.setState({relativeRange:"absolute"}),this.timeTimer&&(clearTimeout(this.timeTimer),this.timeTimer=null)):typeof((e=this.echartsReact)==null?void 0:e.getEchartsInstance)=="function"&&(this.echartsReact.getEchartsInstance().setOption({xAxis:{min:this.chart.min,max:this.chart.max}}),t&&this.updateChart(this.chart.min,this.chart.max,!0))}shiftTime(){const t=new Date,e=6e4-t.getSeconds()-(1e3-t.getMilliseconds());t.getMilliseconds()&&t.setMilliseconds(1e3),t.getSeconds()&&t.setSeconds(60);const i=t.getTime();let n;const a=this.state.relativeRange;if(a==="day")t.setHours(0),t.setMinutes(0),t.setSeconds(0),n=t.getTime();else if(a==="week"){t.setHours(0),t.setMinutes(0),t.setSeconds(0);const o=t.getDay()||7;o!==1&&t.setHours(-24*(o-1)),n=t.getTime()}else if(a==="2weeks"){t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setDate(t.getDate()-7);const o=t.getDay()||7;o!==1&&t.setHours(-24*(o-1)),n=t.getTime()}else a==="month"?(t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setDate(1),n=t.getTime()):a==="year"?(t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setDate(1),t.setMonth(0),n=t.getTime()):a==="12months"?(t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setFullYear(t.getFullYear()-1),n=t.getTime()):n=i-parseInt(a,10)*6e4;this.chart.min=n,this.chart.max=i,this.setState({min:n,max:i},()=>this.updateChart(this.chart.min,this.chart.max,!0)),this.timeTimer=setTimeout(()=>{this.timeTimer=null,this.shiftTime()},e||6e4)}setRelativeInterval(t,e,i){if(e||(this.localStorage.setItem("App.relativeRange",t),this.setState({relativeRange:t})),t==="absolute"){this.timeTimer&&(clearTimeout(this.timeTimer),this.timeTimer=null),this.updateChart(this.chart.min,this.chart.max,!0,i);return}this.localStorage.removeItem("App.absoluteStart"),this.localStorage.removeItem("App.absoluteEnd");const n=new Date;if(!this.timeTimer){const a=6e4-n.getSeconds()-(1e3-n.getMilliseconds());this.timeTimer=setTimeout(()=>{this.timeTimer=null,this.shiftTime()},a||6e4)}if(n.getMilliseconds()&&n.setMilliseconds(1e3),n.getSeconds()&&n.setSeconds(60),this.chart.max=n.getTime(),t==="day")n.setHours(0),n.setMinutes(0),n.setSeconds(0),this.chart.min=n.getTime();else if(t==="week"){n.setHours(0),n.setMinutes(0),n.setSeconds(0);const a=n.getDay()||7;a!==1&&n.setHours(-24*(a-1)),this.chart.min=n.getTime()}else if(t==="2weeks"){n.setHours(0),n.setMinutes(0),n.setSeconds(0),n.setDate(n.getDate()-7);const a=n.getDay()||7;a!==1&&n.setHours(-24*(a-1)),this.chart.min=n.getTime()}else t==="month"?(n.setHours(0),n.setMinutes(0),n.setSeconds(0),n.setDate(1),this.chart.min=n.getTime()):t==="year"?(n.setHours(0),n.setMinutes(0),n.setSeconds(0),n.setDate(1),n.setMonth(0),this.chart.min=n.getTime()):t==="12months"?(n.setHours(0),n.setMinutes(0),n.setSeconds(0),n.setFullYear(n.getFullYear()-1),this.chart.min=n.getTime()):this.chart.min=this.chart.max-parseInt(t,10)*6e4;this.setState({min:this.chart.min,max:this.chart.max},()=>this.updateChart(this.chart.min,this.chart.max,!0,i))}installEventHandlers(){if(!this.echartsReact||typeof this.echartsReact.getEchartsInstance!="function")return;const t=this.echartsReact.getEchartsInstance().getZr();t._iobInstalled||(t._iobInstalled=!0,t.on("mousedown",e=>{console.log("mouse down"),this.mouseDown=!0,this.chart.lastX=e.offsetX}),t.on("mouseup",()=>{console.log("mouse up"),this.mouseDown=!1,this.setNewRange(!0)}),t.on("mousewheel",e=>{let i=this.chart.max-this.chart.min;const n=this.state.chartWidth-Mi-he,o=(e.offsetX-he)/n,s=i,l=e.wheelDelta>0?1.1:.9;i*=l;const u=s-i;this.chart.max+=u*(1-o),this.chart.min-=u*o,this.setNewRange()}),t.on("mousemove",e=>{if(this.mouseDown){const i=this.chart.lastX-(e.offsetX-he);this.chart.lastX=e.offsetX-he;const n=this.chart.max-this.chart.min,a=this.state.chartWidth-Mi-he,o=Math.round(i*n/a);this.chart.min+=o,this.chart.max+=o,this.setNewRange()}}),t.on("touchstart",e=>{e.preventDefault(),this.mouseDown=!0;const i=e.touches||e.originalEvent.touches;i&&(this.chart.lastX=i[i.length-1].pageX,i.length>1?this.chart.lastWidth=Math.abs(i[0].pageX-i[1].pageX):this.chart.lastWidth=null)}),t.on("touchend",e=>{e.preventDefault(),this.mouseDown=!1,this.setNewRange(!0)}),t.on("touchmove",e=>{e.preventDefault();const i=e.touches||e.originalEvent.touches;if(!i)return;const n=i[i.length-1].pageX-he;if(this.mouseDown)if(i.length>1){const a=Math.abs(i[0].pageX-i[1].pageX);if(this.chart.lastWidth!==null&&a!==this.chart.lastWidth){let o=this.chart.max-this.chart.min;const s=this.state.chartWidth-Mi-he,l=a>this.chart.lastWidth?1.1:.9,h=(i[0].pageX>i[1].pageX?i[1].pageX-he+a/2:i[0].pageX-he+a/2)/s,c=o;o*=l;const f=c-o;this.chart.max+=f*(1-h),this.chart.min-=f*h,this.setNewRange()}this.chart.lastWidth=a}else{const a=this.chart.lastX-n,o=this.chart.max-this.chart.min,s=this.state.chartWidth-Mi-he,l=Math.round(a*o/s);this.chart.min+=l,this.chart.max+=l,this.setNewRange()}this.chart.lastX=n}))}renderChart(){var t;return this.state.historyInstance?(t=this.state.historyInstances)!=null&&t.find(e=>e.id===this.state.historyInstance&&e.alive)?this.chartValues?y.jsx(Uw,{ref:e=>this.echartsReact=e,echarts:gP,option:this.getOption(),notMerge:!0,lazyUpdate:!0,theme:this.props.themeType==="dark"?"dark":"",style:{height:`${this.state.chartHeight}px`,width:"100%"},opts:{renderer:"svg"},onEvents:{rendered:()=>this.installEventHandlers()}}):y.jsx(w.LinearProgress,{}):y.jsx("div",{style:{marginTop:20,fontSize:24,marginLeft:24},children:this.props.t("History instance not alive")}):y.jsx("div",{style:{marginTop:20,fontSize:24,marginLeft:24},children:this.props.t("History instance not selected")})}componentDidUpdate(){if(this.divRef.current){const t=this.divRef.current.offsetWidth,e=this.divRef.current.offsetHeight;this.state.chartHeight!==e&&(this.updateTimer&&clearTimeout(this.updateTimer),this.updateTimer=setTimeout(()=>{this.updateTimer=null,this.setState({chartHeight:e,chartWidth:t})},100))}}setStartDate(t){const e=t.getTime();this.timeTimer&&(clearTimeout(this.timeTimer),this.timeTimer=null),this.localStorage.setItem("App.relativeRange","absolute"),this.localStorage.setItem("App.absoluteStart",e.toString()),this.localStorage.setItem("App.absoluteEnd",this.state.max.toString()),this.chart.min=e,this.setState({min:e,relativeRange:"absolute"},()=>this.updateChart(this.chart.min,this.chart.max,!0))}setEndDate(t){const e=t.getTime();this.localStorage.setItem("App.relativeRange","absolute"),this.localStorage.setItem("App.absoluteStart",this.state.min.toString()),this.localStorage.setItem("App.absoluteEnd",e.toString()),this.timeTimer&&(clearTimeout(this.timeTimer),this.timeTimer=null),this.chart.max=e,this.setState({max:e,relativeRange:"absolute"},()=>this.updateChart(this.chart.min,this.chart.max,!0))}openEcharts(){const t=[`id=${window.encodeURIComponent(this.props.obj._id)}`,`instance=${window.encodeURIComponent(this.state.historyInstance)}`,"menuOpened=false"];this.state.relativeRange==="absolute"?(t.push(`start=${this.chart.min}`),t.push(`end=${this.chart.max}`)):t.push(`range=${this.state.relativeRange}`),window.open(`${window.location.protocol}//${window.location.host}/adapter/echarts/tab.html#${t.join("&")}`,"echarts")}async onStepChanged(t){const e=await this.props.socket.getObject(this.props.obj._id);e.common.custom&&e.common.custom[this.state.historyInstance]&&e.common.custom[this.state.historyInstance].chartStep!==t&&(e.common.custom[this.state.historyInstance].chartStep=t,await this.props.socket.setObject(e._id,e)),this.setState({stepType:t,showStepMenu:null})}renderToolbar(){return this.props.noToolbar?null:y.jsxs(w.Toolbar,{children:[!this.props.historyInstance&&y.jsxs(w.FormControl,{variant:"standard",style:Et.selectHistoryControl,children:[y.jsx(w.InputLabel,{children:this.props.t("History instance")}),y.jsx(w.Select,{variant:"standard",value:this.state.historyInstance,onChange:t=>{this.localStorage.setItem("App.historyInstance",t.target.value),this.setState({historyInstance:t.target.value})},children:this.state.historyInstances.map(t=>y.jsx(w.MenuItem,{value:t.id,style:t.alive?void 0:Et.notAliveInstance,children:t.id},t.id))})]}),y.jsxs(w.FormControl,{variant:"standard",style:Et.selectRelativeTime,children:[y.jsx(w.InputLabel,{children:this.props.t("Relative")}),y.jsxs(w.Select,{variant:"standard",ref:this.rangeRef,value:this.state.relativeRange,onChange:t=>this.setRelativeInterval(t.target.value),children:[y.jsx(w.MenuItem,{value:"absolute",sx:Et.customRange,children:this.props.t("custom range")},"custom"),y.jsx(w.MenuItem,{value:10,children:this.props.t("last 10 minutes")},"1"),y.jsx(w.MenuItem,{value:30,children:this.props.t("last 30 minutes")},"2"),y.jsx(w.MenuItem,{value:60,children:this.props.t("last hour")},"3"),y.jsx(w.MenuItem,{value:"day",children:this.props.t("this day")},"4"),y.jsx(w.MenuItem,{value:24*60,children:this.props.t("last 24 hours")},"5"),y.jsx(w.MenuItem,{value:"week",children:this.props.t("this week")},"6"),y.jsx(w.MenuItem,{value:24*60*7,children:this.props.t("last week")},"7"),y.jsx(w.MenuItem,{value:"2weeks",children:this.props.t("this 2 weeks")},"8"),y.jsx(w.MenuItem,{value:24*60*14,children:this.props.t("last 2 weeks")},"9"),y.jsx(w.MenuItem,{value:"month",children:this.props.t("this month")},"10"),y.jsx(w.MenuItem,{value:30*24*60,children:this.props.t("last 30 days")},"11"),y.jsx(w.MenuItem,{value:"year",children:this.props.t("this year")},"12"),y.jsx(w.MenuItem,{value:"12months",children:this.props.t("last 12 months")},"13")]})]}),y.jsxs(qt.LocalizationProvider,{dateAdapter:ks,adapterLocale:Os[this.props.lang],children:[y.jsxs("div",{style:Et.toolbarTimeGrid,children:[y.jsx("div",{style:{...Et.toolbarTimeLabel,opacity:this.state.relativeRange!=="absolute"?.5:void 0},children:this.props.t("Start time")}),y.jsx(qt.DatePicker,{sx:Et.toolbarDate,disabled:this.state.relativeRange!=="absolute",value:new Date(this.state.min),onChange:t=>this.setStartDate(t)}),y.jsx(qt.TimePicker,{disabled:this.state.relativeRange!=="absolute",sx:Et.toolbarTime,ampm:this.state.ampm,value:new Date(this.state.min),onChange:t=>this.setStartDate(t)})]}),y.jsxs("div",{style:Et.toolbarTimeGrid,children:[y.jsx("div",{style:{...Et.toolbarTimeLabel,opacity:this.state.relativeRange!=="absolute"?.5:void 0},children:this.props.t("End time")}),y.jsx(qt.DatePicker,{disabled:this.state.relativeRange!=="absolute",sx:Et.toolbarDate,value:new Date(this.state.max),onChange:t=>this.setEndDate(t)}),y.jsx(qt.TimePicker,{disabled:this.state.relativeRange!=="absolute",sx:Et.toolbarTime,ampm:this.state.ampm,value:new Date(this.state.max),onChange:t=>this.setEndDate(t)})]})]}),y.jsx("div",{style:Et.grow}),y.jsx(w.Button,{style:{marginRight:10},variant:"outlined",onClick:t=>this.setState({showStepMenu:t.target}),children:this.state.stepType?this.props.t(this.state.stepType):this.props.t("Step type")}),this.state.showStepMenu?y.jsxs(w.Menu,{open:!0,anchorEl:this.state.showStepMenu,onClose:()=>this.setState({showStepMenu:null}),children:[y.jsx(w.MenuItem,{selected:this.state.stepType==="",onClick:()=>this.onStepChanged(""),children:this.props.t("None")}),y.jsx(w.MenuItem,{selected:this.state.stepType==="stepStart",onClick:()=>this.onStepChanged("stepStart"),children:this.props.t("stepStart")})]}):null,this.props.showJumpToEchart&&this.state.echartsJump&&y.jsx(w.Fab,{style:Et.echartsButton,size:"small",onClick:()=>this.openEcharts(),title:this.props.t("Open charts in new window"),children:y.jsx("img",{src:bO,alt:"echarts",style:Et.buttonIcon})}),y.jsxs(w.Fab,{variant:"extended",size:"small",color:this.state.splitLine?"primary":"default","aria-label":"show lines",onClick:()=>{this.localStorage.setItem("App.splitLine",this.state.splitLine?"false":"true"),this.setState({splitLine:!this.state.splitLine})},children:[y.jsx(nw,{style:Et.splitLineButtonIcon}),this.props.t("Show lines")]})]})}render(){return!this.state.historyInstances&&!this.state.defaultHistory?y.jsx(w.LinearProgress,{}):y.jsxs(w.Paper,{style:Et.paper,children:[this.renderToolbar(),y.jsx("div",{ref:this.divRef,style:jt.getStyle(this.props.theme,Et.chart,this.props.noToolbar?Et.chartWithoutToolbar:Et.chartWithToolbar),children:this.renderChart()})]})}}const Wx=Wn()(xO),rr={dialog:{height:"100%"},paper:{height:"calc(100% - 64px)"},content:{textAlign:"center",overflow:"hidden"},tabPanel:r=>({width:"100%",overflow:"hidden",height:`calc(100% - ${r.mixins.toolbar.minHeight}px)`}),tabSelected:r=>({color:r.palette.mode==="dark"?r.palette.secondary.contrastText:"#FFFFFF !important"}),tabsIndicator:r=>({backgroundColor:r.palette.secondary.main})};class wO extends Cd{chartAvailable;saveFunc=null;constructor(t){super(t);let e=parseInt((window._localStorage||window.localStorage).getItem("App.objectCustomTab")||"0",10);if(this.chartAvailable=this.isChartAvailable(),this.chartAvailable){const i=yh.getLocation();i.arg==="chart"?e=2:i.arg==="table"&&(e=1)}else e=0;this.state={hasChanges:!1,currentTab:e,confirmDialog:!1,mobile:Cd.isMobile(),progressRunning:!1,showWarning:this.props.allVisibleObjects}}isChartAvailable(){var e,i;let t=this.props.objectIDs.length===1;if(t){const n=this.props.objectIDs[0];(i=(e=this.props.objects[n])==null?void 0:e.common)!=null&&i.custom?t=!!Object.keys(this.props.objects[n].common.custom).find(a=>{const o=this.props.objects[`system.adapter.${a}`];return o&&o.common&&o.common.getHistory}):t=!1}return t}renderCharts(){return y.jsx(Wx,{id:"custom-tabpanel-chart",isFloatComma:this.props.isFloatComma,showJumpToEchart:!0,t:this.props.t,lang:this.props.lang,expertMode:this.props.expertMode,socket:this.props.socket,obj:this.props.objects[this.props.objectIDs[0]],customsInstances:this.props.customsInstances,themeType:this.props.themeType,theme:this.props.theme,objects:this.props.objects})}renderTable(){return y.jsx(dw,{id:"custom-tabpanel-history",t:this.props.t,isFloatComma:this.props.isFloatComma,lang:this.props.lang,expertMode:this.props.expertMode,socket:this.props.socket,obj:this.props.objects[this.props.objectIDs[0]],customsInstances:this.props.customsInstances,themeName:this.props.themeName,objects:this.props.objects})}renderCustomEditor(){return y.jsx(lw,{id:"custom-tabpanel-settings",registerSaveFunc:t=>this.saveFunc=t,t:this.props.t,allVisibleObjects:this.props.allVisibleObjects,lang:this.props.lang,expertMode:this.props.expertMode,socket:this.props.socket,objectIDs:this.props.objectIDs,customsInstances:this.props.customsInstances,objects:this.props.objects,onProgress:t=>this.setState({progressRunning:t}),reportChangedIds:this.props.reportChangedIds,onChange:(t,e)=>{this.setState({hasChanges:t},()=>{if(e){const i=this.isChartAvailable();i!==this.chartAvailable&&(this.chartAvailable=i,this.forceUpdate())}})},theme:this.props.theme,themeName:this.props.themeName,themeType:this.props.themeType,systemConfig:this.props.systemConfig})}renderDialogConfirm(){return this.state.confirmDialog?y.jsx(mh,{title:G.t("You have unsaved changes"),text:G.t("Discard?"),ok:G.t("Yes"),cancel:G.t("Cancel"),onClose:t=>this.setState({confirmDialog:!1},()=>t&&this.props.onClose())}):null}onClose(){this.state.hasChanges?this.setState({confirmDialog:!0}):this.props.onClose()}renderWarningDialog(){return this.state.showWarning?y.jsx(mh,{text:y.jsx("div",{style:{color:"#F00"},children:this.props.t("Your are intend to edit ALL objects. Are you sure?")}),ok:this.props.t("Yes"),onClose:t=>{this.setState({showWarning:!1}),t||this.onClose()}}):null}render(){var e,i;const t=(i=(e=this.props.objects[this.props.objectIDs[0]])==null?void 0:e.common)==null?void 0:i.type;return y.jsxs(w.Dialog,{sx:{"&.MuiDialog-scrollPaper":rr.dialog,"& .MuiDialog-paper":rr.paper},scroll:"paper",open:!0,onClose:()=>this.props.onClose(),fullWidth:!0,maxWidth:"xl","aria-labelledby":"form-dialog-title",children:[this.renderDialogConfirm(),this.renderWarningDialog(),y.jsx(w.DialogTitle,{children:this.props.objectIDs.length>1?this.props.t("Edit config for %s states",this.props.objectIDs.length):this.props.t("Edit config: %s",this.props.objectIDs[0])}),y.jsxs(w.DialogContent,{style:rr.content,children:[y.jsx(w.AppBar,{position:"static",children:y.jsxs(w.Tabs,{value:this.state.currentTab,onChange:(n,a)=>{yh.doNavigate(null,null,null,a===1?"table":a===2?"chart":"config"),this.setState({currentTab:a}),(window._localStorage||window.localStorage).setItem("App.objectCustomTab",a)},sx:{"& .MuiTabs-indicator":rr.tabsIndicator},indicatorColor:"secondary",children:[y.jsx(w.Tab,{disabled:this.state.progressRunning,label:this.props.t("Custom settings"),id:"custom-settings-tab","aria-controls":"custom-tabpanel-settings",sx:{"&.Mui-selected":rr.tabSelected}}),this.props.objectIDs.length===1&&this.chartAvailable?y.jsx(w.Tab,{disabled:this.state.progressRunning,label:this.props.t("History data"),id:"history-data-tab","aria-controls":"custom-tabpanel-history",sx:{"&.Mui-selected":rr.tabSelected}}):null,(t==="number"||t==="boolean")&&this.props.objectIDs.length===1&&this.chartAvailable?y.jsx(w.Tab,{disabled:this.state.progressRunning,label:this.props.t("Chart"),id:"chart-tab","aria-controls":"custom-tabpanel-chart",sx:{"&.Mui-selected":rr.tabSelected}}):null]})}),this.state.currentTab===0?y.jsx(w.Box,{component:"div",sx:rr.tabPanel,children:this.renderCustomEditor()}):null,this.props.objectIDs.length===1&&this.chartAvailable&&this.state.currentTab===1?y.jsx(w.Box,{component:"div",sx:rr.tabPanel,children:this.renderTable()}):null,(t==="number"||t==="boolean")&&this.props.objectIDs.length===1&&this.chartAvailable&&this.state.currentTab===2?y.jsx(w.Box,{component:"div",sx:rr.tabPanel,children:this.renderCharts()}):null]}),y.jsxs(w.DialogActions,{children:[this.state.currentTab===0&&y.jsx(w.Button,{id:"object-custom-dialog-save",variant:"contained",color:"primary",disabled:!this.state.hasChanges||this.state.progressRunning,onClick:()=>this.saveFunc&&this.saveFunc(),children:this.getButtonTitle(y.jsx(X.Save,{}),this.props.t("Save"))}),this.state.currentTab===0&&y.jsx(w.Button,{id:"object-custom-dialog-save-close",variant:"contained",color:"primary",disabled:!this.state.hasChanges||this.state.progressRunning,onClick:()=>{this.saveFunc?this.saveFunc(n=>!n&&this.onClose()):this.onClose()},children:this.getButtonTitle(y.jsx(X.Save,{}),this.props.t("Save & close"),y.jsx(X.Close,{}))}),y.jsx(w.Button,{id:"object-custom-dialog-close",disabled:this.state.progressRunning,variant:"contained",onClick:()=>this.onClose(),color:"grey",children:this.getButtonTitle(y.jsx(X.Close,{}),this.props.t("Close"))})]})]})}}const ve={formControl:{minWidth:100},quality:{width:"calc(100% - 88px)"},expire:{ml:1,width:80},readOnly:{backgroundColor:"#b74848"},readOnlyText:{color:"#b74848",marginLeft:8},wrapperButton:{"@media screen and (max-width: 465px)":{"& *":{fontSize:12}},"@media screen and (max-width: 380px)":{"& *":{fontSize:11}}},ackCheckbox:{marginLeft:4},dialog:{minHeight:window.clientHeight-50>500?500:window.clientHeight-50},tooltip:{pointerEvents:"none"}};class Dn extends at.Component{propsValue;chartFrom;ack;inputRef=vh.createRef();q;expire;constructor(t){super(t);let e=this.props.type;e||(e=typeof this.props.value);let i=this.props.value;if(this.propsValue=i,this.propsValue===null?this.propsValue="null":this.propsValue===void 0&&(this.propsValue="undefined"),this.props.states)e="states";else if(e==="string"||e==="json"){if(i&&typeof i=="string"&&(i.startsWith("[")&&i.endsWith("]")||i.startsWith("{")&&i.endsWith("}")))try{i=JSON.parse(i),i=JSON.stringify(i,null,2),this.propsValue=i,e="json"}catch{}}else e==="number"&&(i=parseFloat(this.propsValue)||0);this.state={type:e,chart:!1,chartEnabled:(window._localStorage||window.localStorage).getItem("App.chartSetValue")!=="false",fullScreen:(window._localStorage||window.localStorage).getItem("App.fullScreen")==="true",targetValue:i,valid:!0,jsonError:!1},this.ack=!1,this.q=0,this.expire=0,this.inputRef=vh.createRef(),this.chartFrom=Date.now()-36e5*2}componentDidMount(){var t,e,i;this.props.defaultHistory&&((e=(t=this.props.object)==null?void 0:t.common)!=null&&e.custom)&&((i=this.props.object.common.custom[this.props.defaultHistory])!=null&&i.enabled)&&this.props.socket.getState(`system.adapter.${this.props.defaultHistory}.alive`).then(n=>this.setState({chart:!!(n!=null&&n.val)})),setTimeout(()=>{var n;if((n=this.inputRef)!=null&&n.current){const a=this.inputRef.current,o=a.value||"",s=a.type;a.type==="number"&&(a.type="text"),a.setSelectionRange(0,o.length),s==="number"&&(a.type=s)}},200)}onUpdate(t){t&&(t.stopPropagation(),t.preventDefault());let e=this.state.targetValue;if(this.state.type==="states")if(e==="null")e=null;else{const i=this.props.type||typeof this.state.targetValue;e=typeof e=="object"?e.value:e,i==="number"?typeof e=="string"&&(e=parseFloat(e.replace(",","."))||0):i==="boolean"&&(e=e===!0||e==="true"||e==="1"||e==="ON"||e==="on")}else this.state.type==="number"?e==="null"?e=null:typeof e=="string"&&(e=parseFloat(e.replace(",","."))||0):this.state.type==="boolean"&&(e==="null"?e=null:e=e===!0||e==="true"||e==="1"||e==="ON"||e==="on");this.props.onClose({val:e,ack:this.ack,q:this.q,expire:parseInt(this.expire,10)||void 0})}static isNumberValid(t){const{common:e,value:i}=t;if(i==="")return!1;const n=Number(i);return typeof e.min=="number"&&n<e.min?!1:!(typeof e.max=="number"&&n>e.max)}renderTimePicker(){return y.jsxs(qt.LocalizationProvider,{adapterLocale:Os[this.props.lang],dateAdapter:ks,children:[y.jsx(qt.DatePicker,{value:Number(this.state.targetValue),onChange:t=>{t&&this.setState({targetValue:Math.round(t.getTime())})}}),y.jsx(qt.TimePicker,{value:Number(this.state.targetValue),views:["hours","minutes","seconds"],onChange:t=>{t&&this.setState({targetValue:Math.round(t.getTime())})}})]})}renderChart(){return y.jsx(Wx,{t:this.props.t,isFloatComma:this.props.isFloatComma,showJumpToEchart:!1,lang:this.props.lang,socket:this.props.socket,obj:this.props.object,themeType:this.props.themeType,theme:this.props.theme,from:this.chartFrom,end:Date.now(),noToolbar:!0,dateFormat:this.props.dateFormat,defaultHistory:this.props.defaultHistory})}static checkJsonError(t){try{return JSON.parse(t),!1}catch{return!0}}renderJsonEditor(){return y.jsx(ty,{error:this.state.jsonError,editValueMode:!0,themeType:this.props.themeType,defaultValue:(this.propsValue||"").toString(),onChange:t=>this.setState({targetValue:t,jsonError:Dn.checkJsonError(t)})})}renderStates(){if(!this.props.states)return null;if(this.props.type==="number"&&this.props.object.common.max!==void 0&&this.props.object.common.min!==void 0){const t=Object.keys(this.props.states).map(e=>({label:this.props.states[e],value:e}));return y.jsx(w.Autocomplete,{style:ve.formControl,disablePortal:!0,defaultValue:this.props.states[this.propsValue]!==void 0?this.props.states[this.propsValue]:this.propsValue,options:t,noOptionsText:"",freeSolo:!0,getOptionLabel:e=>(e==null?void 0:e.label)||(e!=null?e.toString():""),onChange:(e,i)=>this.setState({targetValue:i}),onInputChange:(e,i)=>this.setState({targetValue:i}),onKeyUp:e=>e.key==="Enter"&&this.onUpdate(e),renderInput:e=>y.jsx(w.TextField,{...e,label:this.props.t("Value"),variant:"standard"})})}return y.jsxs(w.FormControl,{variant:"standard",style:ve.formControl,children:[y.jsx(w.InputLabel,{children:this.props.t("Value")}),y.jsx(w.Select,{variant:"standard",defaultValue:this.propsValue,onChange:t=>this.setState({targetValue:t.target.value}),children:Object.keys(this.props.states).map((t,e)=>y.jsx(w.MenuItem,{value:t,children:this.props.states[t]},e))})]})}render(){var e,i,n;const t=y.jsxs("div",{style:{display:"flex",alignItems:"center"},children:[y.jsx(w.FormControlLabel,{style:{...ve.formControl,...this.props.expertMode?void 0:ve.ackCheckbox},control:y.jsx(w.Checkbox,{defaultChecked:!1,onChange:a=>this.ack=a.target.checked}),label:this.props.t("Acknowledged")}),y.jsx(w.Tooltip,{title:this.props.t("Acknowledged explanation"),slotProps:{popper:{sx:ve.tooltip}},children:y.jsx(X.Info,{color:"primary"})})]});return y.jsxs(w.Dialog,{open:!0,maxWidth:this.state.type==="number"||this.state.type==="boolean"||this.state.type==="states"?this.state.chart&&this.state.chartEnabled?"lg":void 0:"md",fullWidth:this.state.type==="json"&&this.state.fullScreen||this.state.type!=="number"&&this.state.type!=="boolean"&&this.state.type!=="states"||this.state.chart&&this.state.chartEnabled,fullScreen:this.state.type==="json"&&this.state.fullScreen,onClose:()=>this.props.onClose(),"aria-labelledby":"edit-value-dialog-title","aria-describedby":"edit-value-dialog-description",sx:{"&. MuiDialog-paper":this.state.type==="json"?ve.dialog:void 0},children:[y.jsxs(w.DialogTitle,{id:"edit-value-dialog-title",children:[this.props.t("Write value"),((e=this.props.object.common)==null?void 0:e.write)===!1?y.jsxs("span",{style:ve.readOnlyText,children:["(",this.props.t("read only"),")"]}):null,this.state.chart?y.jsx(w.Fab,{style:{float:"right"},size:"small",color:this.state.chartEnabled?"primary":"default",onClick:()=>{(window._localStorage||window.localStorage).setItem("App.chartSetValue",this.state.chartEnabled?"false":"true"),this.setState({chartEnabled:!this.state.chartEnabled})},children:y.jsx(X.ShowChart,{})}):null,this.state.type==="json"?y.jsx(w.IconButton,{style:{float:"right"},onClick:()=>{(window._localStorage||window.localStorage).setItem("App.fullScreen",this.state.fullScreen?"false":"true"),this.setState({fullScreen:!this.state.fullScreen})},children:this.state.fullScreen?y.jsx(X.FullscreenExit,{}):y.jsx(X.Fullscreen,{})}):null]}),y.jsx(w.DialogContent,{children:y.jsx("form",{noValidate:!0,autoComplete:"off",onSubmit:()=>!1,style:{...ve.dialogForm,height:"100%"},children:y.jsxs(w.Grid2,{container:!0,direction:"row",spacing:2,style:{height:"100%"},children:[y.jsx(w.Grid2,{size:{xs:this.state.chart&&this.state.chartEnabled?6:12},style:{height:"100%"},children:y.jsxs(w.Grid2,{container:!0,direction:"column",spacing:2,style:{marginTop:0,height:"100%"},children:[this.props.expertMode?y.jsx(w.Grid2,{children:y.jsxs(w.Grid2,{container:!0,direction:"row",spacing:2,style:{marginTop:0},children:[this.props.expertMode?y.jsx(w.Grid2,{children:y.jsxs(w.FormControl,{style:ve.formControl,children:[y.jsx(w.InputLabel,{style:{marginTop:10,marginLeft:-14},children:this.props.t("Value type")}),y.jsxs(w.Select,{variant:"standard",value:this.state.type,onChange:a=>{this.setState({type:a.target.value,valid:a.target.value==="number"?Dn.isNumberValid({value:this.state.targetValue,common:this.props.object.common}):!0,jsonError:!1},()=>{this.state.type==="json"&&this.setState({targetValue:(this.state.targetValue||"").toString(),jsonError:Dn.checkJsonError((this.state.targetValue||"").toString())})})},children:[y.jsx(w.MenuItem,{value:"string",children:"String"}),y.jsx(w.MenuItem,{value:"number",children:"Number"}),y.jsx(w.MenuItem,{value:"boolean",children:"Boolean"}),y.jsx(w.MenuItem,{value:"json",children:"JSON"}),this.props.states?y.jsx(w.MenuItem,{value:"states",children:"States"}):null]})]})}):null,this.state.type==="json"?y.jsx(w.Grid2,{flex:1}):null]})}):null,y.jsx(w.Grid2,{flex:this.state.type==="json"&&this.state.fullScreen?1:void 0,style:{paddingTop:0},children:this.state.type==="boolean"?y.jsx(w.Typography,{component:"div",style:this.props.expertMode?{marginTop:20,width:"100%",backgroundColor:this.props.themeType==="dark"?"#595959":"#dadada",borderRadius:5,padding:5}:void 0,children:y.jsxs(w.Grid2,{component:"label",container:!0,alignItems:"center",spacing:1,children:[y.jsxs(w.Grid2,{style:{marginRight:10},children:[this.props.t("Value"),":"]}),y.jsx(w.Grid2,{children:"FALSE"}),y.jsx(w.Grid2,{children:y.jsx(w.Switch,{autoFocus:!0,defaultChecked:this.propsValue==="null"||this.propsValue==="undefined"?!1:!!this.propsValue,onKeyUp:a=>a.key==="Enter"&&this.onUpdate(a),onChange:a=>this.setState({targetValue:a.target.checked})})}),y.jsx(w.Grid2,{children:"TRUE"})]})}):this.state.type==="number"?y.jsx(w.TextField,{variant:"standard",fullWidth:!0,autoFocus:!0,error:!this.state.valid,type:"number",slotProps:{htmlInput:{step:this.props.object.common.step,min:this.props.object.common.min,max:this.props.object.common.max}},inputRef:this.inputRef,helperText:this.props.t("Press ENTER to write the value, when focused"),value:this.state.targetValue.toString(),label:this.props.t("Value")+(this.props.object.common.min!==void 0||this.props.object.common.unit==="%"?`, ${this.props.t("min:")} ${this.props.object.common.min!==void 0?this.props.object.common.min:0}`:"")+(this.props.object.common.max!==void 0||this.props.object.common.unit==="%"?`, ${this.props.t("max:")} ${this.props.object.common.max!==void 0?this.props.object.common.max:100}`:""),onKeyUp:a=>a.key==="Enter"&&this.state.valid&&this.onUpdate(a),onChange:a=>{this.setState({targetValue:a.target.value,valid:Dn.isNumberValid({value:a.target.value,common:this.props.object.common})})}}):this.state.type==="json"?this.renderJsonEditor():this.state.type==="states"?this.renderStates():y.jsx(w.TextField,{variant:"standard",fullWidth:!0,inputRef:this.inputRef,autoFocus:!0,helperText:this.props.t("Press CTRL+ENTER to write the value, when focused"),label:this.props.t("Value"),multiline:!0,onKeyDown:a=>a.ctrlKey&&a.key==="Enter"&&this.onUpdate(a),defaultValue:this.propsValue.toString(),onChange:a=>this.setState({targetValue:a.target.value})})}),(this.props.role==="date"||(i=this.props.role)!=null&&i.startsWith("date."))&&this.state.type==="number"?y.jsx(w.Grid2,{style:{display:"flex",gap:"5px"},size:{xs:6},children:this.renderTimePicker()}):null,this.props.expertMode?y.jsx(w.Grid2,{children:t}):null,this.props.expertMode?y.jsxs(w.Grid2,{children:[y.jsxs(w.FormControl,{variant:"standard",style:ve.quality,children:[y.jsx(w.InputLabel,{children:this.props.t("Quality")}),y.jsxs(w.Select,{variant:"standard",defaultValue:0,onChange:a=>this.q=Number(a.target.value),children:[y.jsx(w.MenuItem,{value:0,children:"0x00 - good"}),y.jsx(w.MenuItem,{value:1,children:"0x01 - general problem"}),y.jsx(w.MenuItem,{value:2,children:"0x02 - no connection problem"}),y.jsx(w.MenuItem,{value:16,children:"0x10 - substitute value from controller"}),y.jsx(w.MenuItem,{value:32,children:"0x20 - substitute initial value"}),y.jsx(w.MenuItem,{value:64,children:"0x40 - substitute value from device or instance"}),y.jsx(w.MenuItem,{value:128,children:"0x80 - substitute value from sensor"}),y.jsx(w.MenuItem,{value:17,children:"0x11 - general problem by instance"}),y.jsx(w.MenuItem,{value:65,children:"0x41 - general problem by device"}),y.jsx(w.MenuItem,{value:129,children:"0x81 - general problem by sensor"}),y.jsx(w.MenuItem,{value:18,children:"0x12 - instance not connected"}),y.jsx(w.MenuItem,{value:66,children:"0x42 - device not connected"}),y.jsx(w.MenuItem,{value:130,children:"0x82 - sensor not connected"}),y.jsx(w.MenuItem,{value:68,children:"0x44 - device reports error"}),y.jsx(w.MenuItem,{value:132,children:"0x84 - sensor reports error"})]})]}),y.jsx(w.TextField,{variant:"standard",title:this.props.t("0 - no expiration"),sx:{"&.MuiTextField-root":ve.expire},label:this.props.t("Expire"),type:"number",slotProps:{htmlInput:{min:0}},helperText:this.props.t("in seconds"),defaultValue:this.expire,onChange:a=>this.expire=Number(a.target.value)})]}):null]})}),this.state.chart&&this.state.chartEnabled&&this.state.type!=="json"?y.jsx(w.Grid2,{size:{xs:6},style:{minHeight:300},sx:{display:{sm:"none",md:"inline-block"}},children:this.renderChart()}):null]})})}),y.jsxs(w.DialogActions,{sx:ve.wrapperButton,children:[this.props.expertMode?null:t,this.props.expertMode?null:y.jsx("div",{style:{flexGrow:1}}),y.jsx(w.Button,{variant:"contained",disabled:!this.state.valid,onClick:a=>this.onUpdate(a),color:"primary",startIcon:this.props.width!=="xs"?y.jsx(X.Check,{}):void 0,style:((n=this.props.object.common)==null?void 0:n.write)===!1?ve.readOnly:void 0,children:this.props.width!=="xs"?this.props.t("Set value"):y.jsx(X.Check,{fontSize:"large"})}),y.jsx(w.Button,{variant:"contained",onClick:()=>this.props.onClose(),color:"grey",startIcon:this.props.width!=="xs"?y.jsx(X.Close,{}):void 0,children:this.props.width!=="xs"?this.props.t("Cancel"):y.jsx(X.Close,{fontSize:"large"})})]})]})}}const O={divWithoutTitle:{width:"100%",height:"100%",border:"2px solid #00000000"},divWithoutTitleAndTab:{height:"calc(100% - 48px)"},error:{border:"2px solid #FF0000"},id:{fontStyle:"italic"},dialog:{height:"calc(100% - 64px)"},aliasIdEdit:{width:368},button:{marginTop:20,marginLeft:8},funcDivEdit:{width:"100%"},funcEditName:{display:"inline-block",width:85},funcEdit:{width:400},funcIcon:{width:16,height:16},marginTop:{marginTop:20},commonTabWrapper:{flexFlow:"wrap",display:"flex",gap:8},commonWrapper:{width:500,minWidth:300},flexDrop:{width:"100%",maxWidth:500,margin:"auto",display:"flex"},marginBlock:{marginTop:20},buttonAdd:{minWidth:150},textField:{width:"100%"},flex:{display:"flex","& > div":{mr:"8px"}},close:{width:"20px",height:"20px",opacity:"0.9",cursor:"pointer",position:"relative",top:20,transition:"all 0.6s ease","&:hover":{transform:"rotate(90deg)"},"&:before":{position:"absolute",left:"9px",content:'""',height:"20px",width:"3px",backgroundColor:"#ff4f4f",transform:"rotate(45deg)"},"&:after":{position:"absolute",left:"9px",content:'""',height:"20px",width:"3px",backgroundColor:"#ff4f4f",transform:"rotate(-45deg)"}},color:{width:70},buttonRemoveWrapper:{position:"absolute",zIndex:222,right:0},tabsPadding:{padding:"0px 24px"},wrapperButton:{"@media screen and (max-width: 465px)":{"& *":{fontSize:10}},"@media screen and (max-width: 380px)":{"& *":{fontSize:9}}},commonDeleteTip:{color:"#fa4a4a"},typeNameEng:{marginLeft:8,opacity:.7,fontStyle:"italic",fontSize:"smaller"},tooltip:{pointerEvents:"none"},stateRow:{width:"100%",display:"flex",justifyContent:"space-between",padding:3},stateTitle:{minWidth:150,fontWeight:"bold"},stateUnit:{opacity:.7,marginLeft:4},stateValue:{animation:"newStateEditorAnimation 2s ease-in-out"},stateTime:{fontStyle:"italic"},stateImage:{maxWidth:200,maxHeight:200}};function SO(r,t){return{"@keyframes newStateEditorAnimation":{"0%":{color:r.palette.mode==="dark"?"#27cf00":"#174e00"},"100%":{color:t||(r.palette.mode==="dark"?"#ffffff":"#000000")}}}}const yo=[{role:"button",type:"boolean",r:!1,w:!0},{role:"button.close.blind",type:"boolean",r:!1,w:!0},{role:"button.fastforward",type:"boolean",r:!1,w:!0},{role:"button.forward",type:"boolean",r:!1,w:!0},{role:"button.long",type:"boolean",r:!1,w:!0},{role:"button.mode",type:"boolean",r:!1,w:!0},{role:"button.mode.auto",type:"boolean",r:!1,w:!0},{role:"button.mode.silent",type:"boolean",r:!1,w:!0},{role:"button.next",type:"boolean",r:!1,w:!0},{role:"button.open.blind",type:"boolean",r:!1,w:!0},{role:"button.open.door",type:"boolean",r:!1,w:!0},{role:"button.pause",type:"boolean",r:!1,w:!0},{role:"button.stop",type:"boolean",r:!1,w:!0},{role:"button.stop.tilt",type:"boolean",r:!1,w:!0},{role:"button.volume.up",type:"boolean",r:!1,w:!0},{role:"chart",type:"string"},{role:"date",type:"string"},{role:"date",type:"number"},{role:"date.end",type:"string"},{role:"date.end",type:"number"},{role:"date.forecast.1",type:"string"},{role:"date.start",type:"string"},{role:"date.start",type:"number"},{role:"date.sunrise",type:"string"},{role:"date.sunrise",type:"number"},{role:"date.sunset",type:"string"},{role:"date.sunset",type:"number"},{role:"dayofweek",type:"number"},{role:"html",type:"string"},{role:"indicator",type:"boolean",w:!1},{role:"indicator.alarm",type:"boolean",w:!1},{role:"indicator.alarm.fire",type:"boolean",w:!1},{role:"indicator.alarm.flood",type:"boolean",w:!1},{role:"indicator.alarm.health",type:"boolean",w:!1},{role:"indicator.alarm.secure",type:"boolean",w:!1},{role:"indicator.connected",type:"boolean",w:!1},{role:"indicator.maintenance",type:"boolean",w:!1},{role:"indicator.maintenance.alarm",type:"boolean",w:!1},{role:"indicator.maintenance.lowbat",type:"boolean",w:!1},{role:"indicator.maintenance.waste",type:"boolean",w:!1},{role:"indicator.reachable",type:"boolean",w:!1},{role:"info.address",type:"string",w:!1},{role:"info.display",type:"string",w:!1},{role:"info.firmware",type:"string",w:!1},{role:"info.hardware",type:"string",w:!1},{role:"info.ip",type:"string",w:!1},{role:"info.mac",type:"string",w:!1},{role:"info.name",type:"string",w:!1},{role:"info.port",type:"string",w:!1},{role:"info.port",type:"number",w:!1},{role:"info.serial",type:"string",w:!1},{role:"info.standby",type:"string",w:!1},{role:"info.status",w:!1},{role:"json",type:"string"},{role:"level",type:"number",w:!0},{role:"level.bass",type:"number",w:!0},{role:"level.blind",type:"number",w:!0},{role:"level.color.blue",type:"number",w:!0},{role:"level.color.hue",type:"number",w:!0},{role:"level.color.luminance",type:"number",w:!0},{role:"level.color.red",type:"number",w:!0},{role:"level.color.saturation",type:"number",w:!0},{role:"level.curtain",type:"number",w:!0},{role:"level.mode.airconditioner",type:"number",w:!0},{role:"level.mode.cleanup",type:"number",w:!0},{role:"level.mode.fan",type:"number",w:!0},{role:"level.mode.swing",type:"number",w:!0},{role:"level.mode.thermostat",type:"number",w:!0},{role:"level.mode.work",type:"number",w:!0},{role:"level.temperature",type:"number",w:!0},{role:"level.tilt",type:"number",w:!0},{role:"level.timer",type:"number",w:!0},{role:"level.treble",type:"number",w:!0},{role:"level.valve",type:"number",w:!0},{role:"level.volume",type:"number",w:!0},{role:"level.volume.group",type:"number",w:!0},{role:"list",type:"string"},{role:"list",type:"array"},{role:"location",type:"string"},{role:"media.add",type:"string"},{role:"media.bitrate",type:"string"},{role:"media.bitrate",type:"number"},{role:"media.broadcastDate",type:"string"},{role:"media.browser",type:"string"},{role:"media.clear",type:"boolean"},{role:"media.content",type:"string"},{role:"media.cover",type:"string"},{role:"media.cover.big",type:"string"},{role:"media.cover.small",type:"string"},{role:"media.date",type:"string"},{role:"media.duration",type:"number"},{role:"media.duration",type:"string"},{role:"media.duration.text",type:"string"},{role:"media.elapsed",type:"number"},{role:"media.elapsed",type:"string"},{role:"media.elapsed.text",type:"string"},{role:"media.episode",type:"number"},{role:"media.episode",type:"string"},{role:"media.genre",type:"string"},{role:"media.input",type:"string"},{role:"media.jump",type:"string"},{role:"media.link",type:"string"},{role:"media.mode.repeat",type:"string"},{role:"media.mode.shuffle",type:"string"},{role:"media.mute",type:"string"},{role:"media.mute.group",type:"string"},{role:"media.playid",type:"string"},{role:"media.playlist",type:"string"},{role:"media.season",type:"string"},{role:"media.seek",type:"string"},{role:"media.state",type:"string"},{role:"media.titel",type:"string"},{role:"media.track",type:"string"},{role:"media.tts",type:"string"},{role:"media.url",type:"string"},{role:"media.url.announcement",type:"string"},{role:"medien.artist",type:"string"},{role:"sensor.alarm",type:"boolean",w:!1},{role:"sensor.alarm.fire",type:"boolean",w:!1},{role:"sensor.alarm.flood",type:"boolean",w:!1},{role:"sensor.alarm.power",type:"boolean",w:!1},{role:"sensor.alarm.secure",type:"boolean",w:!1},{role:"sensor.door",type:"boolean",w:!1},{role:"sensor.light",type:"boolean",w:!1},{role:"sensor.lock",type:"boolean",w:!1},{role:"sensor.motion",type:"boolean",w:!1},{role:"sensor.noise",type:"boolean",w:!1},{role:"sensor.rain",type:"boolean",w:!1},{role:"sensor.window",type:"boolean",w:!1},{role:"state",type:"mixed"},{role:"switch",type:"boolean",w:!0},{role:"switch.enable",type:"boolean",w:!0},{role:"switch.gate",type:"boolean",w:!0},{role:"switch.gate",type:"boolean",w:!0},{role:"switch.light",type:"boolean",w:!0},{role:"switch.lock.door",type:"boolean",w:!0},{role:"switch.lock.window",type:"boolean",w:!0},{role:"switch.mode",type:"boolean",w:!0},{role:"switch.mode.auto",type:"boolean",w:!0},{role:"switch.mode.boost",type:"boolean",w:!0},{role:"switch.mode.color",type:"boolean",w:!0},{role:"switch.mode.manual",type:"boolean",w:!0},{role:"switch.mode.moonlight",type:"boolean",w:!0},{role:"switch.mode.party",type:"boolean",w:!0},{role:"switch.mode.silent",type:"boolean",w:!0},{role:"switch.power",type:"boolean",w:!0},{role:"switch.power.zone",type:"boolean",w:!0},{role:"text",type:"string"},{role:"text.phone",type:"string"},{role:"text.url",type:"string"},{role:"url",type:"string"},{role:"url.audio",type:"string"},{role:"url.blank",type:"string"},{role:"url.cam",type:"string"},{role:"url.same",type:"string"},{role:"value",type:"number",w:!1},{role:"value.battery",type:"number",w:!1},{role:"value.blind",type:"number",w:!1},{role:"value.blood.sugar",type:"number",w:!1},{role:"value.brightness",type:"number",w:!1},{role:"value.clouds",type:"number",w:!1},{role:"value.current",type:"number",w:!1},{role:"value.curtain",type:"number",w:!1},{role:"value.default",type:"number",w:!1},{role:"value.direction",type:"number",w:!1},{role:"value.direction.max.wind",type:"number",w:!1},{role:"value.direction.min.wind",type:"number",w:!1},{role:"value.direction.wind",type:"number",w:!1},{role:"value.direction.wind.forecast.0",type:"number",w:!1},{role:"value.direction.wind.forecast.1",type:"number",w:!1},{role:"value.distance",type:"number",w:!1},{role:"value.fill",type:"number",w:!1},{role:"value.gate",type:"number",w:!1},{role:"value.gps",type:"number",w:!1},{role:"value.gps.accuracy",type:"number",w:!1},{role:"value.gps.elevation",type:"number",w:!1},{role:"value.gps.latitude",type:"number",w:!1},{role:"value.gps.longitude",type:"number",w:!1},{role:"value.gps.radius",type:"number",w:!1},{role:"value.health.bmi",type:"number",w:!1},{role:"value.health.bpm",type:"number",w:!1},{role:"value.health.calories",type:"number",w:!1},{role:"value.health.fat",type:"number",w:!1},{role:"value.health.steps",type:"number",w:!1},{role:"value.health.weight",type:"number",w:!1},{role:"value.humidity",type:"number",w:!1},{role:"value.humidity",type:"number",w:!1},{role:"value.humidity.max",type:"number",w:!1},{role:"value.humidity.min",type:"number",w:!1},{role:"value.interval",type:"number",w:!1},{role:"value.lock",type:"number",w:!1},{role:"value.min",type:"number",w:!1},{role:"value.position",type:"number",w:!1},{role:"value.power",type:"number",w:!1},{role:"value.power.consumption",type:"number",w:!1},{role:"value.power.production",type:"number",w:!1},{role:"value.power.reactive",type:"number",w:!1},{role:"value.precipitation",type:"number",w:!1},{role:"value.precipitation.chance",type:"number",w:!1},{role:"value.precipitation.day.forecast.0",type:"number",w:!1},{role:"value.precipitation.forecast.0",type:"number",w:!1},{role:"value.precipitation.hour",type:"number",w:!1},{role:"value.precipitation.night.forecast.0",type:"number",w:!1},{role:"value.precipitation.today",type:"number",w:!1},{role:"value.precipitation.type",type:"number",w:!1},{role:"value.prepitation.forecast.0",type:"number",w:!1},{role:"value.prepitation.forecast.1",type:"number",w:!1},{role:"value.prepitation.forecast.1",type:"number",w:!1},{role:"value.pressure",type:"number",w:!1},{role:"value.pressure.forecast.0",type:"number",w:!1},{role:"value.pressure.forecast.1",type:"number",w:!1},{role:"value.radiation",type:"number",w:!1},{role:"value.rain",type:"number",w:!1},{role:"value.rain.hour",type:"number",w:!1},{role:"value.rain.today",type:"number",w:!1},{role:"value.severity",type:"number",w:!1},{role:"value.snow",type:"number",w:!1},{role:"value.snow.hour",type:"number",w:!1},{role:"value.snow.today",type:"number",w:!1},{role:"value.snowline",type:"number",w:!1},{role:"value.speed",type:"number",w:!1},{role:"value.speed.max.wind",type:"number",w:!1},{role:"value.speed.min.wind",type:"number",w:!1},{role:"value.speed.wind",type:"number",w:!1},{role:"value.speed.wind.forecast.0",type:"number",w:!1},{role:"value.speed.wind.gust",type:"number",w:!1},{role:"value.state",type:"number",w:!1},{role:"value.sun.azimuth",type:"number",w:!1},{role:"value.sun.elevation",type:"number",w:!1},{role:"value.temperature",type:"number",w:!1},{role:"value.temperature",type:"number",w:!1},{role:"value.temperature.dewpoint",type:"number",w:!1},{role:"value.temperature.feelslike",type:"number",w:!1},{role:"value.temperature.max",type:"number",w:!1},{role:"value.temperature.max.forecast.0",type:"number",w:!1},{role:"value.temperature.min",type:"number",w:!1},{role:"value.temperature.min.forecast.0",type:"number",w:!1},{role:"value.temperature.min.forecast.1",type:"number",w:!1},{role:"value.temperature.windchill",type:"number",w:!1},{role:"value.tilt",type:"number",w:!1},{role:"value.time",type:"number",w:!1},{role:"value.uv",type:"number",w:!1},{role:"value.valve",type:"number",w:!1},{role:"value.voltage",type:"number",w:!1},{role:"value.warning",type:"number",w:!1},{role:"value.waste",type:"number",w:!1},{role:"value.water",type:"number",w:!1},{role:"waether.title",type:"string",w:!1},{role:"weather.chart.url",type:"string",w:!1},{role:"weather.chart.url.forecast",type:"string",w:!1},{role:"weather.direction.wind",type:"number",w:!1},{role:"weather.direction.wind.forecast.0",type:"number",w:!1},{role:"weather.html",type:"string",w:!1},{role:"weather.icon",type:"string",w:!1},{role:"weather.icon.forecast.1",type:"string",w:!1},{role:"weather.icon.name",type:"string",w:!1},{role:"weather.icon.wind",type:"string",w:!1},{role:"weather.json",type:"string",w:!1},{role:"weather.state",type:"number",w:!1},{role:"weather.state",type:"string",w:!1},{role:"weather.state.forecast.0",type:"string",w:!1},{role:"weather.state.forecast.1",type:"string",w:!1},{role:"weather.title.forecast.0",type:"string",w:!1},{role:"weather.title.short",type:"string",w:!1},{role:"weather.type",type:"number",w:!1},{role:"weather.type",type:"string",w:!1}];class Ht extends at.Component{originalObj;subscribed=!1;updateTimer=null;constructor(t){super(t);const e=this.props.obj._id.startsWith("alias.0")&&this.props.obj.type==="state";let i=(window._localStorage||window.localStorage).getItem(`${this.props.dialogName||"App"}.editTab`)||"object";i==="alias"&&!e&&(i="common"),this.props.aliasTab&&e&&(i="alias");const n=this.props.obj,a=n.common&&"type"in n.common&&"alias"in n.common?n.common.alias.read:void 0,o=n.common&&"type"in n.common&&"alias"in n.common?n.common.alias.write:void 0;this.state={text:JSON.stringify(this.props.obj,null,2),error:!1,customError:!1,changed:!1,readError:this.checkFunction(a,!1),writeError:this.checkFunction(o,!0),tab:i,showCopyDialog:"",showCommonDeleteMessage:!1,selectId:!1,selectRead:!1,selectWrite:!1,newId:"",lang:G.getLanguage(),value:void 0},Ul.locale(this.state.lang),this.originalObj=JSON.stringify(this.props.obj,null,2)}async componentDidMount(){var i,n,a;const t=((n=(i=this.props.obj)==null?void 0:i.common)==null?void 0:n.editSchemas)||((a=this.props.obj)==null?void 0:a.editSchemas),e=[];if(t)if(typeof t=="object"){const o=Object.keys(t);for(let s=0;s<o.length;s++)try{const l=await Td(t[o[s]],this.props.socket);if(l.key=o[s],l&&typeof l=="object"&&e.push(l),l.icon)try{const u=qx(l.icon);if(u.type!=="base64"&&u.type!=="http"){const h=await Td(u,this.props.socket);h&&(l.icon=h)}}catch(u){console.warn(`Cannot get icon for schema from "${l.icon}": ${u}`),l.icon=void 0}}catch(l){console.warn(`Cannot get edit schema for "${t[o[s]]}": ${l}`)}e.length&&(e.sort((s,l)=>s.order!==void 0&&l.order!==void 0?s.order-l.order:s.order!==void 0?-1:l.order!==void 0||s.key>l.key?1:-1),this.setState({customEditTabs:e}))}else console.warn(`Invalid edit schema for "${t}": expected object, but got ${typeof t}`);this.state.tab==="alias"&&(!this.props.obj._id.startsWith("alias.0")||this.props.obj.type!=="state")?this.setState({tab:"object"}):this.state.tab==="state"&&this.props.obj.type!=="state"?this.setState({tab:"object"}):this.state.tab!=="object"&&this.state.tab!=="common"&&this.state.tab!=="alias"&&this.state.tab!=="state"&&!e.find(o=>o.key===this.state.tab)&&this.setState({tab:"object"}),this.state.tab==="state"&&this.subscribeOnState(!0),this.props.socket.subscribeObject(this.props.obj._id,this.onObjectUpdated)}componentWillUnmount(){this.updateTimer&&(clearInterval(this.updateTimer),this.updateTimer=null),this.subscribeOnState(!1),this.props.socket.unsubscribeObject(this.props.obj._id,this.onObjectUpdated)}onObjectUpdated=(t,e)=>{this.originalObj!==JSON.stringify(e,null,2)&&(this.originalObj=JSON.stringify(e,null,2),this.state.changed?this.forceUpdate():this.setState({text:this.originalObj}))};checkFunction(t,e){var a,o,s,l;if(!t||t.includes("JSON.parse("))return"";let i;try{i=JSON.parse(this.state.text)}catch{}let n;try{n=new Function("val",t.includes("return")?t:`return ${t}`)}catch{return this.props.t("Cannot parse code!")}if((a=i==null?void 0:i.common)!=null&&a.type&&((l=(s=this.props.objects[(o=i.common.alias)==null?void 0:o.id])==null?void 0:s.common)!=null&&l.type)){const u=e?i.common.type:this.props.objects[i.common.alias.id].common.type,h=e?this.props.objects[i.common.alias.id].common.type:i.common.type;if(u&&h){let c=null;if(u==="boolean"?c=!0:u==="number"?c=1:(u==="string"||u==="mixed")&&(c="string"),c!==null)try{const f=n(c);return h==="mixed"?"":f!==null&&typeof f!==h?this.props.t("Type of result is not as expected: %s",h):""}catch(f){return`${this.props.t("Cannot execute function")}: ${f.toString()}`}}}return""}prepareObject(t){var e,i,n,a;t=t||this.state.text;try{const o=JSON.parse(t);return o._id=this.props.obj._id,(e=o.common)!=null&&e.alias&&(o.common.alias.id||delete o.common.alias.id,(!o.common.alias.read&&o.common.alias.read!==void 0||o.common.alias.read==="val")&&delete o.common.alias.read,(!o.common.alias.write&&o.common.alias.write!==void 0||o.common.alias.write==="val")&&delete o.common.alias.write,!o.common.alias.id&&!o.common.alias.read&&!o.common.alias.write&&delete o.common.alias),((i=o.common)==null?void 0:i.min)!==void 0&&typeof o.common.min!="number"&&(o.common.min=parseFloat(o.common.min)),((n=o.common)==null?void 0:n.max)!==void 0&&typeof o.common.max!="number"&&(o.common.max=parseFloat(o.common.max)),((a=o.common)==null?void 0:a.step)!==void 0&&typeof o.common.step!="number"&&(o.common.step=parseFloat(o.common.step)),o}catch{return null}}onChange(t,e){var a,o,s,l;const i=this.prepareObject(t),n={text:t};if(i){n.changed=this.originalObj!==JSON.stringify(i,null,2),n.showCommonDeleteMessage=!1;const u=JSON.parse(this.originalObj);i.common&&Object.keys(u.common||{}).forEach(h=>{i.common[h]===void 0&&(n.showCommonDeleteMessage=!0)}),n.error=!1,n.readError=this.checkFunction((o=(a=i.common)==null?void 0:a.alias)==null?void 0:o.read,!1),n.writeError=this.checkFunction((l=(s=i.common)==null?void 0:s.alias)==null?void 0:l.write,!0)}else n.showCommonDeleteMessage=!1,n.error=!0;this.setState(n,()=>e&&e())}onUpdate(){var t,e,i,n;try{const a=JSON.parse(this.state.text);a._id=this.props.obj._id,(t=a.common)!=null&&t.alias&&(a.common.alias.id||delete a.common.alias.id,(!a.common.alias.read&&a.common.alias.read!==void 0||a.common.alias.read==="val")&&delete a.common.alias.read,(!a.common.alias.write&&a.common.alias.write!==void 0||a.common.alias.write==="val")&&delete a.common.alias.write,!a.common.alias.id&&!a.common.alias.read&&!a.common.alias.write&&delete a.common.alias),((e=a.common)==null?void 0:e.min)!==void 0&&typeof a.common.min!="number"&&(a.common.min=parseFloat(a.common.min)),((i=a.common)==null?void 0:i.max)!==void 0&&typeof a.common.max!="number"&&(a.common.max=parseFloat(a.common.max)),((n=a.common)==null?void 0:n.step)!==void 0&&typeof a.common.step!="number"&&(a.common.step=parseFloat(a.common.step)),this.props.onClose(a)}catch{console.error(`Cannot parse: ${this.state.text}`)}}static getPartOfObject(t,e){return e?Ad(JSON.parse(t),e.split(".")):JSON.parse(t)}static setPartOfObject(t,e,i){let n=JSON.parse(t);return n===void 0?t:(n=Zx(n,i.split("."),e),JSON.stringify(n,null,2))}renderCustomPanel(){var i;const t=(i=this.state.customEditTabs)==null?void 0:i.find(n=>n.key===this.state.tab);if(!t)return null;let e;try{e=Ht.getPartOfObject(this.state.text,t.path)}catch(n){return console.error(`Cannot get data for ${t.path}: ${n}`),y.jsx("div",{children:G.t("Cannot get data for %s: %s",t.path,n)})}return e?y.jsx(gh,{theme:this.props.theme,socket:this.props.socket,themeName:this.props.theme.palette.mode,themeType:this.props.theme.palette.mode,dateFormat:this.props.dateFormat,isFloatComma:this.props.isFloatComma,schema:t.json,data:e,onChange:n=>{try{const a=Ht.setPartOfObject(this.state.text,n,t.path);this.onChange(a)}catch(a){console.error(`Cannot set data for ${t.path}: ${a}`)}},adapterName:"",instance:0,onError:n=>{console.warn(`Error in JSON editor: ${n}`),this.state.customError!==n&&this.setState({customError:n})}}):y.jsx("div",{children:G.t("Cannot get data for %s",t.path)})}renderCustomTab(t,e){var a;let i;if(!e||!Ad(e,(a=t.path)==null?void 0:a.split(".")))return null;t.color&&(i={backgroundColor:t.color,color:jt.invertColor(t.color,!0)});const n=t.label&&typeof t.label=="object"?t.label[this.state.lang]||t.label.en:t.noTranslation?t.label||t.key:this.props.t(t.label||t.key);return y.jsx(w.Tab,{disabled:this.state.error||this.state.customError,value:t.key,label:n,style:i,iconPosition:"start",icon:t.icon?y.jsx(Ca,{src:t.icon,style:O.funcIcon}):void 0})}renderStateTab(){return this.props.obj.type!=="state"||this.props.obj.common.type==="file"?null:y.jsx(w.Tab,{disabled:this.state.customError||this.state.error,value:"state",label:this.props.t("State")})}renderStatePanel(){var a;if(this.state.value===void 0||this.state.value===null)return y.jsx("div",{children:this.props.t("State does not exist")});if(typeof this.state.value!="object")return y.jsxs("div",{style:{maxWidth:700},children:[y.jsx("div",{children:this.props.t("State is invalid")}),y.jsx("div",{children:y.jsx("pre",{children:JSON.stringify(this.state.value,null,4)})})]});let t;const e={},i=this.state.value.val,n=typeof i;if(i===void 0)t="[undef]",e.color="#bc6400",e.fontStyle="italic";else if(i===null)t="(null)",e.color="#0047b1",e.fontStyle="italic";else if(typeof this.props.obj.common.role=="string"&&this.props.obj.common.role.match(/^value\.time|^date/))if(i&&n==="string")if(jt.isStringInteger(i))t=new Date(parseInt(i,10)).toString();else try{const o=new Date(i);jt.isValidDate(o)&&(t=o.toString())}catch{}else i&&n==="number"&&(i>946681200&&i<9466812e5?t=new Date(i*1e3).toString():i>9466812e8&&(t=new Date(i).toString()));return t||(n==="number"?Number.isInteger(i)||(t=(Math.round(i*1e9)/1e9).toString(),this.props.isFloatComma&&(t=t.toString().replace(".",","))):n==="boolean"?(t=i?G.t("true"):G.t("false"),e.color=i?"#139800":"#cd6b55"):n==="object"?t=JSON.stringify(i):n==="string"&&i.startsWith("data:image/")?t=y.jsx("img",{src:i,alt:"img",style:O.stateImage}):t=i.toString()),Object.assign(e,SO(this.props.theme,e.color)),y.jsxs(w.Box,{style:{...O.divWithoutTitle,padding:"24px 24px 0 24px",fontSize:16,maxWidth:400},sx:{"& .value-line:hover":{backgroundColor:"#00000030"}},children:[y.jsxs("div",{className:"value-line",style:{...O.stateRow,marginBottom:24},children:[y.jsxs("div",{style:O.stateTitle,children:[G.t("ra_tooltip_value"),":"]}),y.jsxs(w.Box,{component:"div",sx:e,style:O.stateValue,children:[t,(a=this.props.obj.common)!=null&&a.unit?y.jsx("span",{style:O.stateUnit,children:this.props.obj.common.unit}):null]},typeof t=="string"?t:"image")]}),y.jsxs("div",{style:O.stateRow,className:"value-line",children:[y.jsxs("div",{style:O.stateTitle,children:[G.t("Type"),":"]}),y.jsx("div",{style:O.stateValue,children:n})]}),y.jsxs("div",{style:O.stateRow,className:"value-line",children:[y.jsxs("div",{style:O.stateTitle,children:[G.t("ra_tooltip_ts"),":"]}),y.jsx(w.Tooltip,{title:new Date(this.state.value.ts).toLocaleString(),slotProps:{popper:{sx:O.tooltip}},children:y.jsx("div",{style:O.stateValue,children:y.jsx("span",{style:O.stateTime,children:Ul(this.state.value.ts).fromNow()})})})]}),y.jsxs("div",{style:O.stateRow,className:"value-line",children:[y.jsxs("div",{style:O.stateTitle,children:[G.t("ra_tooltip_ack"),":"]}),y.jsxs("div",{style:{...O.stateValue,color:this.state.value.ack?"green":"red"},children:[this.state.value.ack?G.t("Acknowledged"):G.t("Command"),this.state.value.ack?" (true)":" (false)"]})]}),y.jsxs("div",{style:O.stateRow,className:"value-line",children:[y.jsxs("div",{style:O.stateTitle,children:[G.t("ra_tooltip_lc"),":"]}),y.jsx(w.Tooltip,{title:new Date(this.state.value.lc).toLocaleString(),slotProps:{popper:{sx:O.tooltip}},children:y.jsx("div",{style:O.stateValue,children:y.jsx("span",{style:O.stateTime,children:Ul(this.state.value.lc).fromNow()})})})]}),y.jsxs("div",{style:O.stateRow,className:"value-line",children:[y.jsxs("div",{style:O.stateTitle,children:[G.t("ra_tooltip_quality"),":"]}),y.jsx("div",{style:O.stateValue,children:jt.quality2text(this.state.value.q||0).join(", ")})]}),y.jsxs("div",{style:O.stateRow,className:"value-line",children:[y.jsxs("div",{style:O.stateTitle,children:[G.t("ra_tooltip_from"),":"]}),y.jsx("div",{style:O.stateValue,children:this.state.value.from})]}),y.jsxs("div",{style:O.stateRow,className:"value-line",children:[y.jsxs("div",{style:O.stateTitle,children:[G.t("ra_tooltip_user"),":"]}),y.jsx("div",{style:O.stateValue,children:this.state.value.user||"--"})]}),this.state.value.expire?y.jsxs("div",{style:O.stateRow,className:"value-line",children:[y.jsxs("div",{style:O.stateTitle,children:[G.t("ra_tooltip_expire"),":"]}),y.jsxs("div",{style:O.stateValue,children:[this.state.value.expire," ",G.t("sc_seconds")]})]}):null,this.state.value.c?y.jsxs("div",{style:O.stateRow,className:"value-line",children:[y.jsxs("div",{style:O.stateTitle,children:[G.t("ra_tooltip_comment"),":"]}),y.jsx("div",{style:O.stateValue,children:this.state.value.c})]}):null]})}onStateChange=(t,e)=>{JSON.stringify(e)!==JSON.stringify(this.state.value)&&this.setState({value:e})};subscribeOnState(t){t?this.subscribed||(this.updateTimer||(this.updateTimer=setInterval(()=>{this.forceUpdate()},5e3)),this.subscribed=!0,this.props.socket.subscribeState(this.props.obj._id,this.onStateChange)):this.subscribed&&(this.updateTimer&&(clearInterval(this.updateTimer),this.updateTimer=null),this.subscribed=!1,this.props.socket.unsubscribeState(this.props.obj._id,this.onStateChange))}renderTabs(t){var e;return y.jsxs(w.Tabs,{style:O.tabsPadding,value:this.state.tab,onChange:(i,n)=>{var a,o,s;if((window._localStorage||window.localStorage).setItem(`${this.props.dialogName||"App"}.editTab`,n),n==="object"){try{const l=JSON.parse(this.state.text);let u=!1;((a=l.common)==null?void 0:a.min)!==void 0&&typeof l.common.min!="number"&&(l.common.min=parseFloat(l.common.min),u=!0),((o=l.common)==null?void 0:o.max)!==void 0&&typeof l.common.max!="number"&&(l.common.max=parseFloat(l.common.max),u=!0),((s=l.common)==null?void 0:s.step)!==void 0&&typeof l.common.step!="number"&&(l.common.step=parseFloat(l.common.step),u=!0),u&&this.setState({text:JSON.stringify(l,null,2)})}catch{}this.subscribeOnState(!1)}else n==="state"?this.subscribeOnState(!0):this.subscribeOnState(!1);this.setState({tab:n})},children:[y.jsx(w.Tab,{value:"common",disabled:this.state.customError||this.state.error,label:this.props.t("common")}),y.jsx(w.Tab,{value:"object",disabled:this.state.customError,label:this.props.t("Object data")}),this.renderStateTab(),this.props.obj._id.startsWith("alias.0")&&this.props.obj.type==="state"&&y.jsx(w.Tab,{disabled:this.state.customError||this.state.error,value:"alias",label:this.props.t("Alias")}),(e=this.state.customEditTabs)==null?void 0:e.map(i=>this.renderCustomTab(i,t))]})}renderSelectDialog(){var i,n,a,o;if(!this.state.selectId&&!this.state.selectRead&&!this.state.selectWrite)return null;let t="",e;try{e=JSON.parse(this.state.text);const s=e.common&&"type"in e.common&&"alias"in e.common?(i=e.common.alias)==null?void 0:i.read:"",l=e.common&&"type"in e.common&&"alias"in e.common?(n=e.common.alias)==null?void 0:n.write:"";this.state.selectId?t=((o=(a=e.common)==null?void 0:a.alias)==null?void 0:o.id)||"":this.state.selectRead?t=s??"":this.state.selectWrite&&(t=l??"")}catch{console.error(`Cannot parse ${this.state.text}`)}return y.jsx(ey,{imagePrefix:".",dateFormat:this.props.dateFormat,theme:this.props.theme,isFloatComma:this.props.isFloatComma,socket:this.props.socket,dialogName:"aliasesEdit",title:`${this.props.t("Select for")} ${this.props.obj._id}`,selected:t,onOk:s=>{const l=this.state.selectRead,u=this.state.selectWrite,h=this.state.selectId,c=Array.isArray(s)?s[0]:s;this.setState({selectId:!1,selectRead:!1,selectWrite:!1},()=>{l?this.setAliasItem(e,"id.read",c):u?this.setAliasItem(e,"id.write",c):h&&this.setAliasItem(e,"id",c)})},onClose:()=>this.setState({selectId:!1,selectRead:!1,selectWrite:!1})},"selectDialog")}setAliasItem(t,e,i,n){t.common=t.common||{};const a=t.common.alias||{};e==="id.read"?a.id&&typeof a.id=="object"?a.id.read=i:a.id={read:i,write:i}:e==="id.write"?a.id&&typeof a.id=="object"?a.id.write=i:a.id={read:i,write:i}:a[e]=i,t.common.alias=a,this.onChange(JSON.stringify(t,null,2),n)}setCommonItem(t,e,i){t.common[e]=i,this.onChange(JSON.stringify(t,null,2))}removeCommonItem(t,e){delete t.common[e],this.onChange(JSON.stringify(t,null,2))}static buttonAddKey(t,e){return y.jsx("div",{style:O.marginBlock,children:y.jsx(w.Button,{style:O.buttonAdd,variant:"contained",color:"secondary",startIcon:y.jsx(X.Add,{}),onClick:e,children:G.t(t)})})}buttonRemoveKey(t,e){const{t:i}=this.props;return y.jsx(w.Tooltip,{title:i("Remove attribute %s",i(t)),slotProps:{popper:{sx:O.tooltip}},children:y.jsx(w.Box,{component:"div",sx:O.close,onClick:e})})}static filterRoles(t,e){const i=[];return t.forEach(n=>(n.type==="mixed"||n.type)===e&&!i.includes(n.role)&&i.push(n.role)),yo.forEach(n=>(n.type==="mixed"||n.type)===e&&!i.includes(n.role)&&i.push(n.role)),i.sort(),i}renderCommonEdit(){try{const t=JSON.parse(this.state.text),e=["number","string","boolean","array","object","mixed"],i=!1,{t:n,obj:a}=this.props,o=a.type==="state",s=a.type==="channel"||a.type==="device"||o,l=Ht.filterRoles(this.props.roleArray,t.common.type);let u;if(t.common.icon&&(u=t.type==="instance"||t.type==="adapter"?`./adapter/${t.common.name}/${t.common.icon}`:t.common.icon,!u.startsWith(".")&&!u.startsWith("/")&&!u.startsWith("data:"))){const f=a._id.split(".");f[0]==="system"?u=`adapter/${f[2]}${u.startsWith("/")?"":"/"}${u}`:u=`adapter/${f[0]}${u.startsWith("/")?"":"/"}${u}`}const h=typeof t.common.desc=="object"&&t.common.desc?t.common.desc[G.getLanguage()]||t.common.desc.en||"":t.common.desc||"",c=jt.getObjectNameFromObj(t,G.getLanguage(),{},!1,!0);return y.jsxs(w.Box,{style:O.commonTabWrapper,onKeyDown:f=>{f.key==="Enter"&&(f.preventDefault(),f.stopPropagation(),this.onUpdate())},children:[y.jsxs(w.Box,{style:{...O.commonWrapper,width:this.props.width==="xs"?"100%":void 0,minWidth:this.props.width==="xs"?"100%":void 0,gap:this.props.width==="xs"?10:8,display:this.props.width==="xs"?"flex":void 0,flexDirection:this.props.width==="xs"?"column":void 0},children:[typeof t.common.name<"u"?y.jsx(w.TextField,{variant:"standard",disabled:i,label:n("Name"),style:{...O.textField,marginTop:8},fullWidth:!0,slotProps:{input:{endAdornment:c?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{size:"small",onClick:()=>this.setCommonItem(t,"name",""),children:y.jsx(X.Close,{})})}):null}},value:c,onChange:f=>this.setCommonItem(t,"name",f.target.value)}):Ht.buttonAddKey("Name",()=>this.setCommonItem(t,"name","")),typeof t.common.desc<"u"?y.jsxs(w.Box,{component:"div",sx:O.flex,children:[y.jsx(w.TextField,{variant:"standard",disabled:i,label:n("Description"),style:{...O.textField,marginTop:8},fullWidth:!0,slotProps:{input:{endAdornment:h?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{size:"small",onClick:()=>this.setCommonItem(t,"desc",""),children:y.jsx(X.Close,{})})}):null}},value:h,onChange:f=>this.setCommonItem(t,"desc",f.target.value)}),this.buttonRemoveKey("Description",()=>this.removeCommonItem(t,"desc"))]}):Ht.buttonAddKey("Description",()=>this.setCommonItem(t,"desc","")),o?typeof t.common.type<"u"?y.jsxs(w.Box,{component:"div",sx:O.flex,children:[y.jsxs(w.FormControl,{style:O.marginBlock,fullWidth:!0,children:[y.jsx(w.InputLabel,{style:{transform:"scale(0.75)"},children:n("State type")}),y.jsx(w.Select,{variant:"standard",disabled:i,value:t.common.type,onChange:f=>this.setCommonItem(t,"type",f.target.value),children:e.map(f=>y.jsxs(w.MenuItem,{value:f,children:[n(f),y.jsxs("span",{style:O.typeNameEng,children:["(",f,")"]})]},f))})]}),this.buttonRemoveKey("State type",()=>this.removeCommonItem(t,"type"))]}):Ht.buttonAddKey("State type",()=>this.setCommonItem(t,"type","string")):null,y.jsxs(w.Box,{component:"div",sx:{...O.flex,flexWrap:this.props.width==="xs"?"wrap":void 0},children:[o?typeof t.common.read<"u"?y.jsxs(w.Box,{component:"div",sx:O.flex,children:[y.jsx(w.FormControlLabel,{style:O.marginBlock,control:y.jsx(w.Checkbox,{disabled:i,checked:t.common.read,onChange:f=>this.setCommonItem(t,"read",f.target.checked)}),label:n("Readable")}),this.buttonRemoveKey("Readable",()=>this.removeCommonItem(t,"read"))]}):Ht.buttonAddKey("Readable",()=>this.setCommonItem(t,"read",!0)):null,o?typeof t.common.write<"u"?y.jsxs(w.Box,{component:"div",sx:O.flex,children:[y.jsx(w.FormControlLabel,{style:O.marginBlock,control:y.jsx(w.Checkbox,{disabled:i,checked:t.common.write,onChange:f=>this.setCommonItem(t,"write",f.target.checked)}),label:n("Writeable")}),this.buttonRemoveKey("Writeable",()=>this.removeCommonItem(t,"write"))]}):Ht.buttonAddKey("Writeable",()=>this.setCommonItem(t,"write",!0)):null]}),s?typeof t.common.role<"u"?y.jsxs(w.Box,{component:"div",sx:O.flex,children:[y.jsx(w.Autocomplete,{style:O.marginBlock,fullWidth:!0,disabled:i,value:t.common.role,onChange:(f,d)=>{const p=yo.find(v=>v.role===d);p&&(p.w!==void 0&&p.r!==void 0?(this.setCommonItem(t,"write",p.w),this.setCommonItem(t,"read",p.r)):p.w!==void 0?this.setCommonItem(t,"write",p.w):p.r!==void 0&&this.setCommonItem(t,"read",p.r)),d.startsWith("level")||d.startsWith("indicator")||d.startsWith("sensor")||d.startsWith("weather")?t.common.write&&this.setCommonItem(t,"write",!1):d.startsWith("value")||d.startsWith("indicator")||d.startsWith("sensor")||d.startsWith("weather")?t.common.write&&this.setCommonItem(t,"write",!1):d.startsWith("level")||d.startsWith("switch")?t.common.write&&this.setCommonItem(t,"write",!0):d.startsWith("button")&&t.common.read&&this.setCommonItem(t,"read",!1),this.setCommonItem(t,"role",d)},options:l,renderInput:f=>y.jsx(w.TextField,{variant:"standard",...f,label:n("Role")})}),this.buttonRemoveKey("Role",()=>this.removeCommonItem(t,"role"))]}):Ht.buttonAddKey("Role",()=>this.setCommonItem(t,"role","")):null,typeof t.common.color<"u"?y.jsxs(w.Box,{component:"div",sx:O.flex,children:[y.jsx(w.TextField,{variant:"standard",disabled:i,style:{...O.marginBlock,...O.color},label:n("Color"),type:"color",slotProps:{input:{endAdornment:t.common.color?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{size:"small",onClick:()=>this.setCommonItem(t,"color",""),children:y.jsx(X.Close,{})})}):null}},value:t.common.color,onChange:f=>this.setCommonItem(t,"color",f.target.value)}),this.buttonRemoveKey("Color",()=>this.removeCommonItem(t,"color"))]}):Ht.buttonAddKey("Color",()=>this.setCommonItem(t,"color","")),y.jsxs(w.Box,{component:"div",sx:{...O.flex,flexWrap:this.props.width==="xs"?"wrap":void 0,gap:this.props.width==="xs"?"10px":void 0},children:[t.common.type==="number"?typeof t.common.min<"u"?y.jsxs(w.Box,{component:"div",sx:O.flex,children:[y.jsx(w.TextField,{variant:"standard",disabled:i,className:{...O.marginBlock,...O.color},label:n("Min"),value:t.common.min,onChange:f=>this.setCommonItem(t,"min",f.target.value)}),this.buttonRemoveKey("Min",()=>this.removeCommonItem(t,"min"))]}):y.jsx(w.Box,{component:"div",sx:O.flex,children:Ht.buttonAddKey("Min",()=>this.setCommonItem(t,"min",0))}):null,t.common.type==="number"?typeof t.common.max<"u"?y.jsxs(w.Box,{component:"div",sx:O.flex,children:[y.jsx(w.TextField,{variant:"standard",disabled:i,className:{...O.marginBlock,...O.color},label:n("Max"),value:t.common.max,onChange:f=>this.setCommonItem(t,"max",f.target.value)}),this.buttonRemoveKey("Max",()=>this.removeCommonItem(t,"max"))]}):y.jsx(w.Box,{component:"div",sx:O.flex,children:Ht.buttonAddKey("Max",()=>this.setCommonItem(t,"max",100))}):null,t.common.type==="number"?typeof t.common.step<"u"?y.jsxs(w.Box,{component:"div",sx:O.flex,children:[y.jsx(w.TextField,{variant:"standard",disabled:i,className:{...O.marginBlock,...O.color},label:n("Step"),value:t.common.step,onChange:f=>this.setCommonItem(t,"step",f.target.value)}),this.buttonRemoveKey("Step",()=>this.removeCommonItem(t,"step"))]}):y.jsx(w.Box,{component:"div",sx:O.flex,children:Ht.buttonAddKey("Step",()=>this.setCommonItem(t,"step",1))}):null]}),t.common.type==="number"?typeof t.common.unit<"u"?y.jsxs(w.Box,{component:"div",sx:O.flex,children:[y.jsx(w.TextField,{variant:"standard",disabled:i,className:{...O.marginBlock,...O.color},label:n("Unit"),slotProps:{input:{endAdornment:t.common.unit?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{size:"small",onClick:()=>this.setCommonItem(t,"unit",""),children:y.jsx(X.Close,{})})}):null}},value:t.common.unit,onChange:f=>this.setCommonItem(t,"unit",f.target.value)}),this.buttonRemoveKey("Unit",()=>this.removeCommonItem(t,"unit"))]}):y.jsx("div",{style:O.flexDrop,children:Ht.buttonAddKey("Unit",()=>this.setCommonItem(t,"unit",""))}):null]}),typeof t.common.icon<"u"?y.jsxs(w.Box,{component:"div",sx:O.flex,style:{flexGrow:1,minWidth:158},children:[y.jsx(Kx,{disabled:i,maxSize:10*1024,icon:u,removeIconFunc:()=>this.setCommonItem(t,"icon",""),onChange:f=>this.setCommonItem(t,"icon",f)}),this.buttonRemoveKey("Icon",()=>this.removeCommonItem(t,"icon"))]}):y.jsx(w.Box,{component:"div",sx:O.flex,children:Ht.buttonAddKey("Icon",()=>this.setCommonItem(t,"icon",""))})]})}catch{return y.jsx("div",{children:this.props.t("Cannot parse JSON!")})}}renderAliasEdit(){var t,e,i,n,a,o,s,l,u,h,c,f,d,p,v,g,m,_,b,x,C,S,T,M,D,I,P,k,R,L,j,E,q,W,$,et,ut,ot,ft,gt;try{const B=JSON.parse(this.state.text),Rt=((e=(t=B.common)==null?void 0:t.alias)==null?void 0:e.read)!==void 0||((n=(i=B.common)==null?void 0:i.alias)==null?void 0:n.write)!==void 0;return y.jsxs(w.Grid2,{container:!0,direction:"column",style:O.marginTop,children:[y.jsx(w.Grid2,{children:y.jsx(w.FormControlLabel,{control:y.jsx(w.Checkbox,{checked:typeof((o=(a=B.common)==null?void 0:a.alias)==null?void 0:o.id)=="object",onChange:()=>{var Mt,Lt,xt,z,Y,K,Ot;typeof((Lt=(Mt=B.common)==null?void 0:Mt.alias)==null?void 0:Lt.id)=="object"?this.setAliasItem(B,"id",((Y=(z=(xt=B.common)==null?void 0:xt.alias)==null?void 0:z.id)==null?void 0:Y.read)||""):this.setAliasItem(B,"id.read",((Ot=(K=B.common)==null?void 0:K.alias)==null?void 0:Ot.id)||"")}}),label:this.props.t("Different IDs for read and write")})}),typeof((l=(s=B.common)==null?void 0:s.alias)==null?void 0:l.id)!="object"?y.jsxs(w.Grid2,{children:[y.jsx(w.TextField,{variant:"standard",label:this.props.t("Alias state"),value:((h=(u=B.common)==null?void 0:u.alias)==null?void 0:h.id)||"",style:O.aliasIdEdit,slotProps:{input:{endAdornment:(f=(c=B.common)==null?void 0:c.alias)!=null&&f.id?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{size:"large",onClick:()=>this.setAliasItem(B,"id",""),children:y.jsx(X.Close,{})})}):null}},onChange:Mt=>this.setAliasItem(B,"id",Mt.target.value),margin:"normal"}),y.jsx(w.Fab,{style:O.button,size:"small",onClick:()=>this.setState({selectId:!0,selectRead:!1,selectWrite:!1}),children:"..."})]}):null,typeof((p=(d=B.common)==null?void 0:d.alias)==null?void 0:p.id)=="object"?y.jsxs(w.Grid2,{children:[y.jsx(w.TextField,{variant:"standard",label:this.props.t("Alias read state"),value:((m=(g=(v=B.common)==null?void 0:v.alias)==null?void 0:g.id)==null?void 0:m.read)||"",style:O.aliasIdEdit,slotProps:{input:{endAdornment:(x=(b=(_=B.common)==null?void 0:_.alias)==null?void 0:b.id)!=null&&x.read?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{size:"large",onClick:()=>this.setAliasItem(B,"id.read",""),children:y.jsx(X.Close,{})})}):null}},onChange:Mt=>this.setAliasItem(B,"id.read",Mt.target.value),margin:"normal"}),y.jsx(w.Fab,{style:O.button,size:"small",onClick:()=>this.setState({selectId:!1,selectRead:!0,selectWrite:!1}),children:"..."})]}):null,typeof((S=(C=B.common)==null?void 0:C.alias)==null?void 0:S.id)=="object"?y.jsxs(w.Grid2,{children:[y.jsx(w.TextField,{variant:"standard",label:this.props.t("Alias write state"),value:((D=(M=(T=B.common)==null?void 0:T.alias)==null?void 0:M.id)==null?void 0:D.write)||"",style:O.aliasIdEdit,slotProps:{input:{endAdornment:(k=(P=(I=B.common)==null?void 0:I.alias)==null?void 0:P.id)!=null&&k.write?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{size:"large",onClick:()=>this.setAliasItem(B,"id.write",""),children:y.jsx(X.Close,{})})}):null}},onChange:Mt=>this.setAliasItem(B,"id.write",Mt.target.value),margin:"normal"}),y.jsx(w.Fab,{style:O.button,size:"small",onClick:()=>this.setState({selectId:!1,selectRead:!1,selectWrite:!0}),children:"..."})]}):null,y.jsx(w.Grid2,{style:O.marginTop,children:y.jsx(w.FormControlLabel,{control:y.jsx(w.Checkbox,{checked:((L=(R=B.common)==null?void 0:R.alias)==null?void 0:L.read)!==void 0||((E=(j=B.common)==null?void 0:j.alias)==null?void 0:E.write)!==void 0,onChange:()=>{Rt?(delete B.common.alias.read,delete B.common.alias.write):(B.common=B.common||{},B.common.alias=B.common.alias||{},B.common.alias.read="val",B.common.alias.write="val"),this.onChange(JSON.stringify(B,null,2))}}),label:this.props.t("Use convert functions")})}),Rt?y.jsx(w.Grid2,{children:y.jsx(w.TextField,{variant:"standard",label:this.props.t("Read converter"),value:((W=(q=B.common)==null?void 0:q.alias)==null?void 0:W.read)||"val",style:O.funcEdit,error:!!this.state.readError,slotProps:{input:{endAdornment:(et=($=B.common)==null?void 0:$.alias)!=null&&et.read?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{size:"large",onClick:()=>this.setAliasItem(B,"read",""),children:y.jsx(X.Close,{})})}):null,startAdornment:y.jsx(w.InputAdornment,{position:"start",children:y.jsx(Rs,{style:O.funcIcon})})}},onChange:Mt=>this.setAliasItem(B,"read",Mt.target.value),helperText:this.state.readError||`${this.props.t("JS function like")} "val / 5 + 21"`,margin:"normal"})}):null,Rt?y.jsx(w.Grid2,{children:y.jsx(w.TextField,{variant:"standard",label:this.props.t("Write converter"),error:!!this.state.writeError,value:((ot=(ut=B.common)==null?void 0:ut.alias)==null?void 0:ot.write)||"val",helperText:this.state.writeError||`${this.props.t("JS function like")} "(val - 21) * 5"`,style:O.funcEdit,slotProps:{input:{endAdornment:(gt=(ft=B.common)==null?void 0:ft.alias)!=null&>.write?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{size:"large",onClick:()=>this.setAliasItem(B,"write",""),children:y.jsx(X.Close,{})})}):null,startAdornment:y.jsx(w.InputAdornment,{position:"start",children:y.jsx(Rs,{style:O.funcIcon})})}},onChange:Mt=>this.setAliasItem(B,"write",Mt.target.value),margin:"normal"})}):null]})}catch{return y.jsx("div",{children:this.props.t("Cannot parse JSON!")})}}onCopy(t){jt.copyToClipboard(this.state.text,t),window.alert(this.props.t("ra_Copied"))}onClone(t,e){const i=JSON.parse(JSON.stringify(this.props.objects[t]));delete i.from,delete i.ts,delete i.user,i._id=e,this.props.objects[i._id]=i,this.props.onNewObject(i)}renderCopyDialog(){return this.state.showCopyDialog?y.jsxs(w.Dialog,{open:!0,maxWidth:"md",fullWidth:!0,onClose:()=>this.setState({showCopyDialog:""}),children:[y.jsx(w.DialogTitle,{children:this.props.t("Enter new ID for this object")}),y.jsx(w.DialogContent,{children:y.jsx(w.TextField,{variant:"standard",autoFocus:!0,fullWidth:!0,label:this.props.t("New object ID"),value:this.state.newId,slotProps:{input:{endAdornment:this.state.newId?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{size:"small",onClick:()=>this.setState({newId:""}),children:y.jsx(X.Close,{})})}):null}},onKeyDown:t=>{t.key==="Enter"&&!this.props.objects[this.state.newId]&&(this.setState({showCopyDialog:""}),this.onClone(this.state.showCopyDialog,this.state.newId))},onChange:t=>this.setState({newId:t.target.value})})}),y.jsxs(w.DialogActions,{children:[y.jsx(w.Button,{disabled:!!this.props.objects[this.state.newId],onClick:()=>{this.setState({showCopyDialog:""}),this.onClone(this.state.showCopyDialog,this.state.newId)},color:"primary",startIcon:y.jsx(X.FileCopy,{}),children:this.props.t("Clone")}),y.jsx(w.Button,{color:"grey",onClick:()=>this.setState({showCopyDialog:""}),startIcon:y.jsx(X.Close,{}),children:this.props.t("Cancel")})]})]}):null}renderPanelObject(t){return y.jsxs("div",{style:{...O.divWithoutTitle,...t?O.divWithoutTitleAndTab:void 0,...this.state.error?O.error:void 0},onKeyDown:e=>{e.ctrlKey&&e.key==="Enter"&&(e.preventDefault(),e.stopPropagation(),this.onUpdate())},children:[y.jsx(ty,{value:this.state.text,onChange:e=>this.onChange(e),name:"UNIQUE_ID_OF_DIV",themeType:this.props.themeType}),this.state.showCommonDeleteMessage?y.jsx("div",{style:O.commonDeleteTip,children:G.t("common_delete_tip")}):null]})}render(){const t=this.props.obj,e=t._id.startsWith("alias.0")&&t.type==="state";let i=O.dialog;window.innerWidth>1920&&(i={...i,maxWidth:"calc(100% - 150px)"});let n;try{n=JSON.parse(this.state.text)}catch{}return y.jsxs(w.Dialog,{sx:{"& .MuiPaper-root":i},open:!0,maxWidth:"xl",fullWidth:!0,fullScreen:!1,onClose:()=>this.props.onClose(),"aria-labelledby":"edit-value-dialog-title","aria-describedby":"edit-value-dialog-description",children:[y.jsxs(w.DialogTitle,{id:"edit-value-dialog-title",style:{width:"calc(100% - 32px)",overflow:"hidden",textOverflow:"ellipsis"},children:[this.props.t("Edit object:")," ",y.jsx(w.Box,{component:"span",style:O.id,sx:{fontSize:{xs:10}},children:this.props.obj._id})]}),this.renderTabs(n),this.renderCopyDialog(),y.jsxs(w.DialogContent,{sx:{p:this.props.width==="xs"&&this.state.tab==="object"?"6px":this.state.tab==="object"||this.state.tab==="common"||this.state.tab==="alias"?"0 24px":"0 6px",overflow:this.state.tab==="object"||this.state.tab==="common"||this.state.tab==="alias"?void 0:"hidden"},children:[this.state.tab==="object"?this.renderPanelObject(e):null,this.state.tab==="alias"&&this.props.obj._id.startsWith("alias.0")&&this.props.obj.type==="state"?this.renderAliasEdit():null,this.state.tab==="common"?this.renderCommonEdit():null,this.state.tab==="state"?this.renderStatePanel():null,this.renderCustomPanel(),this.renderSelectDialog()]}),y.jsxs(w.DialogActions,{sx:O.wrapperButton,children:[y.jsx(w.Button,{color:"grey",onClick:()=>this.setState({showCopyDialog:this.props.obj._id,newId:this.props.obj._id}),disabled:this.state.error||this.state.changed,title:this.props.t("Create a copy of this object"),children:y.jsx(X.FileCopy,{fontSize:this.props.width==="xs"?"large":void 0})}),y.jsx("div",{style:{flexGrow:1}}),this.state.tab==="object"&&y.jsx(w.Button,{color:"grey",onClick:a=>this.onCopy(a),disabled:this.state.error,title:this.props.width==="xs"?this.props.t("Copy into clipboard"):"",startIcon:this.props.width==="xs"?void 0:y.jsx(Md,{}),children:this.props.width==="xs"?y.jsx(Md,{fontSize:32}):this.props.t("Copy into clipboard")}),y.jsx(w.Button,{variant:"contained",disabled:this.state.error||!this.state.changed||this.state.customError,onClick:()=>this.onUpdate(),startIcon:this.props.width==="xs"?void 0:y.jsx(X.Check,{}),color:"primary",children:this.props.width==="xs"?y.jsx(X.Check,{fontSize:"large"}):this.props.t("Write")}),y.jsx(w.Button,{color:"grey",variant:"contained",onClick:()=>this.props.onClose(),startIcon:this.props.width==="xs"?void 0:y.jsx(X.Close,{}),children:this.props.width==="xs"?y.jsx(X.Close,{fontSize:"large"}):this.props.t("Cancel")})]})]})}}class md extends at.Component{object=null;constructor(t){super(t),this.state={role:null,initRole:null,roleInput:null}}componentDidMount(){this.props.socket.getObject(this.props.id).then(t=>{var i;this.object=t;const e=((i=t==null?void 0:t.common)==null?void 0:i.role)||null;this.setState({role:e,initRole:e,roleInput:e})}).catch(t=>console.error(t))}onUpdate(){this.object.common=this.object.common||{},this.object.common.role=this.state.roleInput,this.props.socket.setObject(this.object._id,this.object).then(()=>this.props.onClose(this.object))}static filterRoles(t,e){const i=[];return t.forEach(n=>(n.type==="mixed"||n.type)===e&&!i.includes(n.role)&&i.push(n.role)),yo.forEach(n=>(n.type==="mixed"||n.type)===e&&!i.includes(n.role)&&i.push(n.role)),i.sort(),i}render(){return y.jsxs(w.Dialog,{open:!0,maxWidth:"sm",fullWidth:!0,onClose:()=>this.props.onClose(),"aria-labelledby":"edit-role-dialog-title","aria-describedby":"edit-role-dialog-description",children:[y.jsx(w.DialogTitle,{id:"edit-role-dialog-title",children:this.object?this.props.t("Update role for %s",this.object._id):null}),y.jsx(w.DialogContent,{children:y.jsx(w.Autocomplete,{freeSolo:!0,options:md.filterRoles(this.props.roleArray,this.props.commonType),style:{width:"100%"},value:this.state.role,onChange:(t,e)=>this.setState({role:e,roleInput:e}),onInputChange:(t,e)=>this.setState({roleInput:e}),renderInput:t=>y.jsx(w.TextField,{variant:"standard",...t,label:this.props.t("Role")})})}),y.jsxs(w.DialogActions,{children:[y.jsx(w.Button,{disabled:this.state.initRole===this.state.roleInput,variant:"contained",onClick:()=>this.onUpdate(),color:"primary",startIcon:y.jsx(X.Check,{}),children:this.props.t("Apply")}),y.jsx(w.Button,{variant:"contained",onClick:()=>this.props.onClose(),color:"grey",startIcon:y.jsx(X.Close,{}),children:this.props.t("Cancel")})]})]},"objectBrowserEditRole")}}const CO=["array","boolean","file","json","mixed","number","object","string"],TO={boolean:!1,string:"",number:0},Be={state:{name:"State",value:"state"},channel:{name:"Channel",value:"channel"},device:{name:"Device",value:"device"},folder:{name:"Folder",value:"folder"}},AO=({onClose:r,onApply:t,selected:e,setObject:i,objects:n,expertMode:a,initialType:o,initialStateType:s})=>{var T;const l={state:G.t("New state"),channel:G.t("New channel"),device:G.t("New device"),folder:G.t("New folder")},u=[],h=(T=n[e])==null?void 0:T.type;n[e]?h==="channel"?(u.push(Be.state),o=o||"state"):h==="device"?(o=o||"channel",u.push(Be.state),u.push(Be.channel)):h==="state"?o=o||"":(u.push(Be.state),u.push(Be.channel),u.push(Be.device),e.startsWith("0_userdata.")||e.startsWith("alias.0.")||e==="0_userdata"||e==="alias.0"?(u.push(Be.folder),o=o||"folder"):o=o||"state"):(u.push(Be.folder),o=o||"folder",a&&(e.startsWith("mqtt.")||e.startsWith("javascript."))&&(u.push(Be.state),u.push(Be.channel),u.push(Be.device)));const c=(window._localStorage||window.localStorage).getItem("App.lastObjectType");c&&u.find(M=>M.value===c)&&(o=c);function f(M){return`${e}.${M.toString().replace(jt.FORBIDDEN_CHARS,"_").replace(/\s/g,"_").replace(/\./g,"_")}`}const[d,p]=at.useState(o),[v,g]=at.useState(l[o]),[m,_]=at.useState(s||(window._localStorage||window.localStorage).getItem("App.lastStateType")||"string"),[b,x]=at.useState(!n[f(l.state)]),C=()=>{const M={common:{name:v,desc:G.t("Manually created")},type:d};d==="state"?(M.common={...M.common,role:"state",type:m,read:!0,write:!0,def:TO[m]},M.native={}):d!=="folder"?M.common={...M.common,role:"",icon:""}:delete M.common.desc,i(`${e}.${v.split(" ").join("_")}`,M).then(()=>t())},S=G.getLanguage();return y.jsxs(w.Dialog,{open:!0,fullWidth:!0,maxWidth:"md",disableEscapeKeyDown:!1,onClose:r,children:[y.jsx(w.DialogTitle,{children:y.jsxs("div",{style:{margin:10,fontSize:20,display:"flex",alignItems:"center",gap:8},children:[y.jsx(X.AddBox,{}),G.t("Add new object:"),y.jsxs("span",{style:{fontStyle:"italic"},children:[e,".",v]})]})}),y.jsx(w.DialogContent,{children:y.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[y.jsx(w.TextField,{variant:"standard",label:G.t("Parent"),style:{margin:"5px 0"},disabled:!0,value:e}),y.jsxs(w.FormControl,{variant:"standard",style:{marginTop:10,marginBottom:16},children:[y.jsx(w.InputLabel,{children:G.t("Type")}),y.jsx(w.Select,{variant:"standard",value:d,onChange:M=>{(window._localStorage||window.localStorage).setItem("App.lastObjectType",M.target.value),v===l[d]&&(g(l[M.target.value]),x(!!n[f(l[M.target.value])])),p(M.target.value)},children:u.map(M=>y.jsxs(w.MenuItem,{value:M.value,children:[G.t(M.name),S!=="en"&&y.jsxs("span",{style:{fontSize:"smaller",opacity:.6,marginLeft:4},children:["(",M.value,")"]})]},M.value))})]}),d==="state"&&y.jsxs(w.FormControl,{style:{marginTop:10,marginBottom:16},children:[y.jsx(w.InputLabel,{style:{left:-14},children:G.t("State type")}),y.jsx(w.Select,{style:{marginTop:6},variant:"standard",value:m,onChange:M=>{(window._localStorage||window.localStorage).setItem("App.lastStateType",M.target.value),_(M.target.value)},children:CO.map(M=>y.jsxs(w.MenuItem,{value:M,children:[G.t(M),S!=="en"&&G.t(M)!==M&&y.jsxs("span",{style:{fontSize:"smaller",opacity:.6,marginLeft:4},children:["(",M,")"]})]},M))})]}),y.jsx(w.TextField,{variant:"standard",label:G.t("Name"),style:{margin:"5px 0"},autoFocus:!0,value:v,onKeyDown:M=>{M.key==="Enter"&&(M.preventDefault(),v&&C())},slotProps:{input:{endAdornment:v?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{size:"small",onClick:()=>g(""),children:y.jsx(X.Close,{})})}):null}},onChange:M=>{x(!n[f(M.target.value)]),g(M.target.value)}})]})}),y.jsxs(w.DialogActions,{children:[y.jsx(w.Button,{id:"add-new-object-dialog-add",startIcon:y.jsx(X.Check,{}),disabled:!v||!d||!b||d==="state"&&!m,onClick:()=>C(),variant:"contained",color:"primary",children:G.t("add")}),y.jsx(w.Button,{id:"add-new-object-dialog-cancel",color:"grey",onClick:r,variant:"contained",startIcon:y.jsx(X.Close,{}),children:G.t("ra_Cancel")})]})]})},MO=[{Owner:[{name:"read",valueNum:1024,title:"read owner"},{name:"write",valueNum:512,title:"write owner"}]},{Group:[{name:"read",valueNum:64,title:"read group"},{name:"write",valueNum:32,title:"write group"}]},{Everyone:[{name:"read",valueNum:4,title:"read everyone"},{name:"write",valueNum:2,title:"write everyone"}]}];function Jm(r,t,e){return r|=t&e,r&=t|~e&65535,r}const Qm=({value:r,setValue:t,t:e,differentValues:i,applyToChildren:n,mask:a,setMask:o,disabled:s})=>{at.useEffect(()=>{if(n){let u=0;for(let h=0;h<i.length;h++)u|=r^i[h];o(u)}else o(0)},[i,n,o,r]);let l=r;return y.jsx("div",{style:{display:"flex",width:"fit-content",margin:20,border:"1px solid",borderLeft:0},children:MO.map(u=>{const h=Object.keys(u)[0];return y.jsxs("div",{style:{width:150,height:150,display:"flex",flexDirection:"column",alignItems:"center",borderLeft:"1px solid"},children:[y.jsx("div",{style:{height:50,display:"flex",alignItems:"center",fontSize:18,borderBottom:"1px solid silver",width:"100%",justifyContent:"center"},children:e(h)}),y.jsx("div",{style:{display:"flex",width:"100%"},children:u[h].map((c,f)=>{let d=!1;l-c.valueNum>=0&&(l-=c.valueNum,d=!0);const p=a&c.valueNum;return y.jsxs("div",{style:{display:"flex",flexDirection:"column",flex:1,alignItems:"center",borderRight:f===0?"1px solid":0},children:[y.jsx("div",{style:{height:50,borderBottom:"1px solid",width:"100%",justifyContent:"center",display:"flex",alignItems:"center",color:"silver"},children:e(c.name)}),y.jsx("div",{style:{height:50,display:"flex"},children:y.jsx(w.Checkbox,{disabled:s,checked:d,color:p?"primary":"secondary",indeterminate:!!p,style:p?{opacity:.5}:void 0,onChange:v=>{p&&(a&=~c.valueNum&65535,o(a));let g=r;v.target.checked?g|=c.valueNum:g&=~c.valueNum&65535,t(g)}})})]},c.valueNum)})})]},h)})})},DO=({onClose:r,onApply:t,selected:e,extendObject:i,objects:n,t:a,modalEmptyId:o,themeType:s,theme:l})=>{const[u,h]=at.useState(null),[c,f]=at.useState(null),[d,p]=at.useState([]),[v,g]=at.useState([]),[m,_]=at.useState(!1),[b,x]=at.useState(!1),[C,S]=at.useState(0),[T,M]=at.useState(null),[D,I]=at.useState(null),[P,k]=at.useState(!1),[R,L]=at.useState(!1),[j,E]=at.useState([]),[q,W]=at.useState([]),[$,et]=at.useState(0),[ut,ot]=at.useState(0),[ft,gt]=at.useState([]),[B,Rt]=at.useState(!1),[Mt,Lt]=at.useState(!0),xt=a("different");return at.useEffect(()=>{var bd,xd,wd,Sd;let z=0;const Y=[],K=[],Ot=e||o,St=`${Ot}.`,se=Object.keys(n).sort();let je=!1;const ei=[],Tr=[],ri=G.getLanguage();let qn=!1,Zn=!1,tn=null,en=null,ii=null,ni=null;const _d=[];for(let ai=0;ai<se.length;ai++){const Ar=se[ai],ht=n[Ar];if(ht&&(Ar===Ot||Ar.startsWith(St))){if(z++,_d.push(Ar),!ht.acl)continue;ii===null&&ht.acl.object!==void 0&&(ii=ht.acl.object),ni===null&&ht.acl.state!==void 0&&(ni=ht.acl.state),tn===null&&ht.acl.owner!==void 0&&(tn=ht.acl.owner),en===null&&ht.acl.ownerGroup!==void 0&&(en=ht.acl.ownerGroup),!P&&tn!==ht.acl.owner&&ht.acl.owner!==void 0&&(qn=!0),!R&&en!==ht.acl.ownerGroup&&ht.acl.ownerGroup!==void 0&&(Zn=!0),ht.acl.state!==void 0&&ni!==ht.acl.state&&!Y.includes(ht.acl.state)&&Y.push(ht.acl.state),ht.acl.object!==void 0&&ii!==ht.acl.object&&!K.includes(ht.acl.object)&&K.push(ht.acl.object),ht.type==="state"&&(je=!0)}Ar.startsWith("system.group.")&&(ht==null?void 0:ht.type)==="group"?ei.push({name:jt.getObjectNameFromObj(ht,ri).replace("system.group.",""),value:Ar,icon:(bd=ht.common)==null?void 0:bd.icon,color:(xd=ht.common)==null?void 0:xd.color}):Ar.startsWith("system.user.")&&(ht==null?void 0:ht.type)==="user"&&Tr.push({name:jt.getObjectNameFromObj(ht,ri).replace("system.user.",""),value:Ar,icon:(wd=ht.common)==null?void 0:wd.icon,color:(Sd=ht.common)==null?void 0:Sd.color})}tn=tn||n["system.config"].common.defaultNewAcl.owner,en=en||n["system.config"].common.defaultNewAcl.ownerGroup,ii=ii||n["system.config"].common.defaultNewAcl.object,M(Number.isNaN(ii)?n["system.config"].common.defaultNewAcl.object:ii),je&&(ni=ni||n["system.config"].common.defaultNewAcl.state,I(Number.isNaN(ni)?n["system.config"].common.defaultNewAcl.state:ni));const Gx=Tr.find(ai=>ai.value===tn),Ux=ei.find(ai=>ai.value===en);h(Gx),f(Ux),k(qn),L(Zn),p(Tr),g(ei),je&&x(!0),o&&_(!0),S(z),E(Y),W(K),gt(_d)},[n,e,R,P,o]),at.useEffect(()=>{m?(R&&(c.value!=="different"&&f({name:xt,value:"different"}),v.find(z=>z.value==="different")||g(z=>[{name:xt,value:"different"},...z])),P&&((!u||u.value!=="different")&&h({name:xt,value:"different"}),d.find(z=>z.value==="different")||p(z=>[{name:xt,value:"different"},...z]))):(u&&u.value==="different"&&h(n[e].acl.owner),c&&c.value==="different"&&f(n[e].acl.ownerGroup),g(z=>z.filter(({value:Y})=>Y!=="different")),p(z=>z.filter(({value:Y})=>Y!=="different")))},[d,m,P,R,n,e,c,u,xt,v]),ft.length?y.jsx(ow,{theme:l,titleButtonApply:"apply",overflowHidden:!0,disableApply:Mt,progress:B,onClose:r,onApply:()=>{Rt(!0),setTimeout(()=>{if(m){const z=~$&65535,Y=~ut&65535;for(let K=0;K<ft.length;K++){const Ot=ft[K],St=n[Ot],se=jt.clone(St.acl||{});se.object=Jm(St.acl.object,T,z),u&&u.value!=="different"&&(se.owner=u.value),c&&c.value!=="different"&&(se.ownerGroup=c.value),St.type==="state"&&(se.state=Jm(St.acl.state,D,Y)),i(Ot,{acl:se})}}else{const z=jt.clone(n[e].acl||{});z.object=T,z.owner=u?u.value:"system.user.admin",z.ownerGroup=c?c.value:"system.group.administrator",n[e].type==="state"&&(z.state=D),i(e,{acl:z})}Rt(!1),t()},200)},children:y.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[y.jsx("div",{style:{margin:10,fontSize:20},children:a("Access control list: %s",e||o)}),y.jsxs("div",{style:{display:"flex"},children:[y.jsxs(w.FormControl,{variant:"standard",fullWidth:!0,style:{marginRight:10},children:[y.jsx(w.InputLabel,{children:a("Owner user")}),y.jsx(w.Select,{variant:"standard",disabled:B,value:u?u.value:"",renderValue:()=>y.jsxs("span",{children:[u!=null&&u.icon?y.jsx(Ca,{src:u.icon,style:{width:16,height:16,marginRight:8}}):null,u?u.name:""]}),style:(u==null?void 0:u.value)==="different"?{opacity:.5}:{color:(u==null?void 0:u.color)||void 0,backgroundColor:jt.getInvertedColor(u==null?void 0:u.color,s)},onChange:z=>{const Y=d.find(K=>K.value===z.target.value);h(Y),Lt(!1)},children:d.map(z=>y.jsxs(w.MenuItem,{style:z.value==="different"?{opacity:.5}:{color:z.color||void 0,backgroundColor:jt.getInvertedColor(z.color,s)},value:z.value,children:[z.icon?y.jsx(Ca,{src:z.icon,style:{width:16,height:16,marginRight:8}}):null,z.name]},z.value))})]}),y.jsxs(w.FormControl,{variant:"standard",fullWidth:!0,children:[y.jsx(w.InputLabel,{children:a("Owner group")}),y.jsx(w.Select,{variant:"standard",disabled:B,value:c?c.value:"",renderValue:()=>y.jsxs("span",{children:[c!=null&&c.icon?y.jsx(Ca,{src:c.icon,style:{width:16,height:16,marginRight:8}}):null,c?c.name:""]}),style:(c==null?void 0:c.value)==="different"?{opacity:.5}:{color:(c==null?void 0:c.color)||void 0,backgroundColor:jt.getInvertedColor(c==null?void 0:c.color,s)},onChange:z=>{const Y=v.find(K=>K.value===z.target.value);f(Y),Lt(!1)},children:v.map(z=>y.jsxs(w.MenuItem,{value:z.value,style:z.value==="different"?{opacity:.5}:{color:z.color||void 0,backgroundColor:jt.getInvertedColor(z.color,s)},children:[z.icon?y.jsx(Ca,{src:z.icon,style:{width:16,height:16,marginRight:8}}):null,z.name]},z.value))})]})]}),y.jsxs("div",{style:{display:"flex",margin:10,alignItems:"center",fontSize:10,marginLeft:0,color:"silver"},children:[y.jsx("div",{style:m?null:{color:"green"},children:a("to apply one item")}),y.jsx(w.Switch,{disabled:B||!!o||C===1,checked:!!o||m,onChange:z=>{_(z.target.checked),Lt(!1)},color:"primary"}),y.jsxs("div",{style:m?{color:"green"}:null,children:[a("to apply with children")," ",o||C>1?`(${C} ${a("object(s)")})`:""]})]}),B&&y.jsx(w.LinearProgress,{}),y.jsxs("div",{style:{overflowY:"auto"},children:[y.jsxs("div",{children:[y.jsx("h2",{children:a("Object rights")}),y.jsx(Qm,{mask:ut,disabled:B,setMask:ot,applyToChildren:m,differentValues:q,t:a,setValue:z=>{M(z),Lt(!1)},value:T})]}),b&&y.jsxs("div",{children:[y.jsx("h2",{children:a("States rights")}),y.jsx(Qm,{mask:$,disabled:B,setMask:et,applyToChildren:m,differentValues:m?j:[],t:a,setValue:z=>{I(z),Lt(!1)},value:D})]})]})]})}):y.jsx(w.LinearProgress,{})},bn={dialog:{height:"100%",maxHeight:"100%",maxWidth:"100%"},content:{textAlign:"center"},error:r=>({color:r.palette.mode==="dark"?"#ff7777":"#c20000"}),image:{height:"100%",width:"auto"},text:{fontFamily:"Lucida Console, Courier, monospace",width:"100%"},download:{textDecoration:"none",textTransform:"uppercase",fontSize:14,color:"white",border:"1px solid white",borderRadius:5,padding:"8px 16px",marginRight:8}};class IO extends at.Component{audioRef;constructor(t){super(t);const e=this.props.obj._id.split(".");this.state={error:"",image:null,text:null,binary:null,fileName:`${e[e.length-2]}.${e[e.length-1]}`},this.audioRef=vh.createRef()}componentDidMount(){this.props.socket.getBinaryState(this.props.obj._id).then(t=>{let e=this.props.obj._id.toLowerCase().split(".").pop();const i=jt.detectMimeType(t);if(i&&(e=i),e==="jpg")this.setState({image:!0,binary:t,mime:"image/jpeg"});else if(e==="svg")this.setState({image:!0,binary:t,mime:"image/svg+xml"});else if(e==="png"||e==="bmp")this.setState({image:!0,binary:t,mime:`image/${e}`});else if(e==="mp3")this.setState({audio:!0,binary:t,mime:"audio/mpeg"});else if(e==="ogg")this.setState({audio:!0,binary:t,mime:"audio/ogg"});else if(e==="txt"||e==="log")try{const n=btoa(t);this.setState({text:n,binary:t,mime:"text/plain"})}catch{}}).catch(t=>this.setState({error:t}))}render(){return y.jsxs(w.Dialog,{style:bn.dialog,open:!0,maxWidth:this.state.audio?"sm":"md",onClose:()=>this.props.onClose(),fullWidth:!0,"aria-labelledby":"object-view-dialog-title",children:[y.jsx(w.DialogTitle,{id:"object-view-dialog-title",children:this.props.t("View file in state: %s",this.props.obj._id)}),y.jsxs(w.DialogContent,{style:bn.content,children:[this.state.error?y.jsx(w.Box,{component:"div",sx:bn.error,children:this.state.error==="State is not binary"?this.props.t("No file stored yet"):this.props.t(this.state.error)}):null,this.state.audio?y.jsx("audio",{ref:this.audioRef,src:`data:${this.state.mime};base64,${this.state.binary}`}):null,this.state.audio?y.jsx(w.Fab,{color:"primary",onClick:()=>this.audioRef.current&&this.audioRef.current.play(),children:y.jsx(X.PlayArrow,{})}):null,this.state.image?y.jsx("img",{src:`data:${this.state.mime};base64,${this.state.binary}`,alt:this.props.obj._id,style:bn.image}):null,this.state.text!==null?y.jsx("pre",{style:bn.text,children:this.state.text}):null]}),y.jsxs(w.DialogActions,{children:[y.jsxs("a",{style:bn.download,download:this.state.fileName,href:`data:${this.state.mime};base64,${this.state.binary}`,children:[y.jsx(X.GetApp,{style:{paddingRight:8,height:12}}),y.jsx("span",{children:this.props.t("Download")})]}),y.jsx(w.Button,{variant:"contained",onClick:()=>this.props.onClose(),startIcon:y.jsx(X.Close,{}),color:"grey",children:this.props.t("Close")})]})]})}}const PO=Wn()(IO),zt={funcIcon:{width:16,height:16},formControlLabel:{marginBottom:16},color:{width:70},typeNameEng:{marginLeft:8,opacity:.7,fontStyle:"italic",fontSize:"smaller"},usedInAlias:{},addNewAlias:r=>({backgroundColor:r.palette.primary.main})},kO=["array","boolean","file","json","mixed","number","object","string"];class Ya extends at.Component{aliasIDs;constructor(t){var n;super(t);const e=[],i=this.props.obj._id;this.aliasIDs=Object.keys(this.props.objects).filter(a=>a.startsWith("alias.0"));for(let a=0;a<this.aliasIDs.length;a++){const o=(n=this.props.objects[this.aliasIDs[a]].common)==null?void 0:n.alias;((o==null?void 0:o.id)===i||typeof(o==null?void 0:o.id)=="object"&&(o.id.read===i||o.id.write===i))&&e.push(this.aliasIDs[a])}this.state={usedInAliases:e,showAddNewAlias:!e.length,newAliasId:this.props.obj._id,newAliasName:Ya.getText(this.props.obj.common.name||this.props.obj._id)||"",newAliasRole:this.props.obj.common.role||"",newAliasRead:this.props.obj.common.read,newAliasWrite:this.props.obj.common.write,newAliasUnit:this.props.obj.common.unit,newAliasDesc:Ya.getText(this.props.obj.common.desc)||"",newAliasType:this.props.obj.common.type,newAliasMin:this.props.obj.common.min===void 0?"":this.props.obj.common.min.toString(),newAliasMax:this.props.obj.common.max===void 0?"":this.props.obj.common.max.toString(),newAliasUseFormula:!1,newAliasReadFormula:"val",newAliasWriteFormula:"val",newAliasColor:this.props.obj.common.color,newAliasIcon:this.props.obj.common.icon}}static getText(t){return t?typeof t=="object"?t[G.getLanguage()]||t.en||"":t.toString():""}static filterRoles(t,e){const i=[];return yo.forEach(n=>(n.type==="mixed"||n.type===e)&&!i.includes(n.role)&&i.push(n.role)),t.forEach(n=>(n.type==="mixed"||n.type)===e&&!i.includes(n.role)&&i.push(n.role)),i.sort(),i}renderAddNewAlias(){return this.state.showAddNewAlias?y.jsxs(w.Dialog,{open:!0,onClose:()=>this.setState({showAddNewAlias:!1}),children:[y.jsx(w.DialogTitle,{children:G.t("Create new alias: %s",`alias.0.${this.state.newAliasId}`)}),y.jsxs(w.DialogContent,{children:[y.jsx(w.TextField,{style:zt.formControlLabel,variant:"standard",value:this.state.newAliasId,slotProps:{input:{endAdornment:this.state.newAliasId?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{size:"small",onClick:()=>this.setState({newAliasId:""}),children:y.jsx(X.Close,{})})}):null}},onChange:t=>this.setState({newAliasId:t.target.value}),label:G.t("Alias ID"),helperText:`alias.0.${this.state.newAliasId}`,fullWidth:!0}),y.jsx(w.TextField,{style:zt.formControlLabel,variant:"standard",value:this.state.newAliasName,slotProps:{input:{endAdornment:this.state.newAliasName?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{size:"small",onClick:()=>this.setState({newAliasName:""}),children:y.jsx(X.Close,{})})}):null}},onChange:t=>this.setState({newAliasName:t.target.value}),label:G.t("Alias name"),fullWidth:!0}),y.jsx(w.TextField,{style:zt.formControlLabel,variant:"standard",value:this.state.newAliasDesc,slotProps:{input:{endAdornment:this.state.newAliasDesc?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{size:"small",onClick:()=>this.setState({newAliasDesc:""}),children:y.jsx(X.Close,{})})}):null}},onChange:t=>this.setState({newAliasDesc:t.target.value}),label:G.t("Alias description"),fullWidth:!0}),y.jsxs(w.FormControl,{style:zt.formControlLabel,fullWidth:!0,children:[y.jsx(w.InputLabel,{children:G.t("State type")}),y.jsx(w.Select,{variant:"standard",value:this.state.newAliasType,onChange:t=>this.setState({newAliasType:t.target.value}),children:kO.map(t=>y.jsxs(w.MenuItem,{value:t,children:[G.t(t),y.jsxs("span",{style:zt.typeNameEng,children:["(",t,")"]})]},t))})]}),this.state.newAliasType==="number"?y.jsx(w.TextField,{style:zt.formControlLabel,variant:"standard",value:this.state.newAliasUnit||"",slotProps:{input:{endAdornment:this.state.newAliasUnit?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{size:"small",onClick:()=>this.setState({newAliasUnit:""}),children:y.jsx(X.Close,{})})}):null}},onChange:t=>this.setState({newAliasUnit:t.target.value}),label:G.t("Alias units"),fullWidth:!0}):null,this.state.newAliasType==="number"?y.jsx(w.TextField,{variant:"standard",value:this.state.newAliasMin,type:"number",error:this.state.newAliasMin?isNaN(parseFloat(this.state.newAliasMin)):!1,onChange:t=>this.setState({newAliasMin:t.target.value}),label:G.t("Min"),style:{width:"calc(50% - 4px)",marginBottom:16,marginRight:8}}):null,this.state.newAliasType==="number"?y.jsx(w.TextField,{variant:"standard",value:this.state.newAliasMax,type:"number",error:this.state.newAliasMax?isNaN(parseFloat(this.state.newAliasMax)):!1,onChange:t=>this.setState({newAliasMax:t.target.value}),label:G.t("Max"),fullWidth:!0,style:{width:"calc(50% - 4px)",marginBottom:16}}):null,y.jsx(w.TextField,{variant:"standard",style:{...zt.formControlLabel,...zt.color},label:G.t("Color"),type:"color",value:this.state.newAliasColor,onChange:t=>this.setState({newAliasColor:t.target.value})}),y.jsx(w.Autocomplete,{style:{...zt.formControlLabel},fullWidth:!0,value:this.state.newAliasRole,onChange:(t,e)=>{const i=yo.find(n=>n.role===e);if(i){if(i.w!==void 0&&i.r!==void 0){this.setState({newAliasRole:e,newAliasRead:i.r,newAliasWrite:i.w});return}if(i.w!==void 0){this.setState({newAliasRole:e,newAliasWrite:i.w});return}if(i.r!==void 0){this.setState({newAliasRole:e,newAliasRead:i.r});return}}if(e.startsWith("value")||e.startsWith("indicator")||e.startsWith("sensor")||e.startsWith("weather")){if(this.state.newAliasWrite){this.setState({newAliasRole:e,newAliasWrite:!1});return}}else if(e.startsWith("level")||e.startsWith("switch")){if(!this.state.newAliasWrite){this.setState({newAliasRole:e,newAliasWrite:!0});return}}else if(e.startsWith("button")&&this.state.newAliasRead){this.setState({newAliasRole:e,newAliasRead:!1});return}this.setState({newAliasRole:e})},options:Ya.filterRoles(this.props.roleArray,this.state.newAliasType),renderInput:t=>y.jsx(w.TextField,{variant:"standard",...t,label:G.t("Role")})}),y.jsx(w.FormControlLabel,{style:{...zt.formControlLabel,marginLeft:16},control:y.jsx(w.Checkbox,{indeterminate:this.state.newAliasRead===void 0||this.state.newAliasRead===null,checked:this.state.newAliasRead,onChange:t=>{const e={newAliasRead:t.target.checked};e.newAliasRead===!1&&this.state.newAliasWrite===!1&&(e.newAliasWrite=!0),this.setState(e)}}),label:G.t("Alias read")}),y.jsx(w.FormControlLabel,{style:zt.formControlLabel,control:y.jsx(w.Checkbox,{indeterminate:this.state.newAliasWrite===void 0||this.state.newAliasWrite===null,checked:this.state.newAliasWrite,onChange:t=>{const e={newAliasWrite:t.target.checked};e.newAliasRead===!1&&this.state.newAliasWrite===!1&&(e.newAliasRead=!0),this.setState(e)}}),label:G.t("Alias write")}),y.jsx(w.FormControlLabel,{style:zt.formControlLabel,control:y.jsx(w.Checkbox,{checked:this.state.newAliasUseFormula,onChange:t=>this.setState({newAliasUseFormula:t.target.checked})}),label:G.t("Use convert functions")}),this.state.newAliasUseFormula&&this.state.newAliasRead?y.jsx(w.TextField,{style:zt.formControlLabel,variant:"standard",value:this.state.newAliasReadFormula,onChange:t=>this.setState({newAliasReadFormula:t.target.value}),label:G.t("Read formula"),helperText:`${G.t("JS function like")} "val / 5 + 21"`,slotProps:{input:{endAdornment:this.state.newAliasReadFormula&&this.state.newAliasReadFormula!=="val"?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{size:"small",onClick:()=>this.setState({newAliasReadFormula:"val"}),children:y.jsx(X.Close,{})})}):null,startAdornment:y.jsx(w.InputAdornment,{position:"start",children:y.jsx(Rs,{style:zt.funcIcon})})}},fullWidth:!0}):null,this.state.newAliasUseFormula&&this.state.newAliasWrite?y.jsx(w.TextField,{style:zt.formControlLabel,variant:"standard",value:this.state.newAliasWriteFormula,onChange:t=>this.setState({newAliasWriteFormula:t.target.value}),label:G.t("Write formula"),slotProps:{input:{endAdornment:this.state.newAliasWriteFormula&&this.state.newAliasWriteFormula!=="val"?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{size:"small",onClick:()=>this.setState({newAliasWriteFormula:"val"}),children:y.jsx(X.Close,{})})}):null,startAdornment:y.jsx(w.InputAdornment,{position:"start",children:y.jsx(Rs,{style:zt.funcIcon})})}},helperText:`${G.t("JS function like")} "val / 5 + 21"`,fullWidth:!0}):null]}),y.jsxs(w.DialogActions,{children:[y.jsx(w.Button,{variant:"contained",disabled:!this.state.newAliasId||!!this.props.objects[`alias.0.${this.state.newAliasId}`],onClick:async()=>{const t={_id:`alias.0.${this.state.newAliasId}`,type:"state",common:{name:this.state.newAliasName,type:this.props.obj.common.type,alias:{id:this.props.obj._id}},native:{}};this.state.newAliasDesc&&(t.common.desc=this.state.newAliasDesc),this.state.newAliasType&&(t.common.type=this.state.newAliasType),this.state.newAliasType==="number"&&this.state.newAliasUnit&&(t.common.unit=this.state.newAliasUnit),this.state.newAliasRole&&(t.common.role=this.state.newAliasRole),this.state.newAliasType==="number"&&this.state.newAliasMin&&(t.common.min=parseFloat(this.state.newAliasMin)),this.state.newAliasType==="number"&&this.state.newAliasMax&&(t.common.max=parseFloat(this.state.newAliasMax)),this.state.newAliasRole&&(t.common.role=this.state.newAliasRole),this.state.newAliasRead!==void 0&&this.state.newAliasRead!==null&&(t.common.read=this.state.newAliasRead),this.state.newAliasWrite!==void 0&&this.state.newAliasWrite!==null&&(t.common.write=this.state.newAliasWrite),this.state.newAliasColor&&(t.common.color=this.state.newAliasColor),this.state.newAliasIcon&&(t.common.icon=this.state.newAliasIcon),this.state.newAliasUseFormula&&(t.common.read!==!1&&this.state.newAliasReadFormula&&this.state.newAliasReadFormula!=="val"&&(t.common.alias.read=this.state.newAliasReadFormula),t.common.write!==!1&&this.state.newAliasWriteFormula&&this.state.newAliasWriteFormula!=="val"&&(t.common.alias.write=this.state.newAliasWriteFormula)),await this.props.socket.setObject(t._id,t),this.setState({showAddNewAlias:!1}),this.props.onRedirect(t._id,2e3),this.props.onClose()},startIcon:y.jsx(X.AddLink,{}),color:"primary",children:this.props.t("Create")}),y.jsx(w.Button,{variant:"contained",onClick:()=>this.setState({showAddNewAlias:!1}),startIcon:y.jsx(X.Close,{}),color:"grey",children:this.props.t("Close")})]})]}):null}render(){return y.jsxs(w.Dialog,{open:!0,maxWidth:"sm",onClose:()=>this.props.onClose(),fullWidth:!0,"aria-labelledby":"object-alias-dialog-title",children:[this.renderAddNewAlias(),y.jsx(w.DialogTitle,{id:"object-alias-dialog-title",children:this.state.usedInAliases.length?G.t("This object is used in aliases"):G.t("This object does not used in any aliases yet")}),y.jsx(w.DialogContent,{children:y.jsxs(w.MenuList,{style:{maxWidth:400},children:[this.state.usedInAliases.map(t=>y.jsxs(w.MenuItem,{style:zt.usedInAlias,onClick:()=>this.props.onRedirect(t),children:[y.jsx(w.ListItemIcon,{children:y.jsx(X.Link,{fontSize:"small"})}),y.jsx(w.ListItemText,{children:t})]},t)),y.jsxs(w.MenuItem,{onClick:()=>this.setState({showAddNewAlias:!0}),sx:zt.addNewAlias,children:[y.jsx(w.ListItemIcon,{children:y.jsx(X.AddLink,{fontSize:"small"})}),y.jsx(w.ListItemText,{children:G.t("Create alias from this ID")})]})]})}),y.jsx(w.DialogActions,{children:y.jsx(w.Button,{variant:"contained",onClick:()=>this.props.onClose(),startIcon:y.jsx(X.Close,{}),color:"grey",children:this.props.t("Close")})})]},"editAlias")}}const RO=Wn()(Ya);class yd extends at.Component{checkTimer=null;objects={};constructor(t){super(t);const e=this.props.id.split("."),i=e.pop()||"";this.state={name:i,parentId:e.join("."),renameAllChildren:!0,newExists:!0,showParentDialog:!1,showHistoryWarning:!1,withHistory:[]}}componentWillUnmount(){this.checkTimer&&(clearTimeout(this.checkTimer),this.checkTimer=null)}static calculateNewId(t,e,i){const n=t.split("."),a=e.split(".");let o=0;for(;n[o]===a[o];)o++;const s=i.split(".");return s.splice(0,o+1),`${e}.${s.join(".")}`}async getInstancesWithHistory(){const t=await this.props.socket.getAdapterInstances();return t==null?void 0:t.filter(e=>e.common.getHistory).map(e=>e._id.replace("system.adapter.",""))}async checkHistory(){this.objects={};const t=await this.getInstancesWithHistory(),e=[];try{const i=await this.props.socket.getObject(this.props.id);i&&(this.objects[i._id]=i)}catch{}for(const i of this.props.childrenIds)try{const n=await this.props.socket.getObject(i);n&&(this.objects[n._id]=n)}catch{}return Object.values(this.objects).forEach(i=>{var n;(n=i.common)!=null&&n.custom&&Object.keys(i.common.custom).find(a=>t.includes(a)&&!i.common.custom[a].aliasId)&&e.push(i._id)}),e.length?(this.setState({showHistoryWarning:!0,withHistory:e}),!1):!0}showHistoryWarning(){return this.state.showHistoryWarning?y.jsxs(w.Dialog,{open:!0,onClose:()=>this.setState({showHistoryWarning:!1}),children:[y.jsx(w.DialogTitle,{children:this.props.t("Found states with history")}),y.jsxs(w.DialogContent,{children:[this.state.withHistory.length>2?this.props.t("You want to move %s states with enabled history",this.state.withHistory.length):`${this.props.t("Following states have history enabled")}: ${this.state.withHistory.join(", ")}`,y.jsx("div",{children:this.props.t("move_states_with_history_warning")})]}),y.jsxs(w.DialogActions,{children:[y.jsx(w.Button,{variant:"contained",color:"primary",onClick:async()=>{const t=`${this.state.parentId}.${this.state.name}`;await this.renameCopyObject(this.props.id,t,this.props.childrenIds.length&&this.state.renameAllChildren,!1),this.props.onClose()},startIcon:y.jsx(X.Check,{}),children:this.props.t("Confirm")}),y.jsx(w.Button,{color:"grey",variant:"contained",startIcon:y.jsx(X.Close,{}),onClick:()=>this.setState({showHistoryWarning:!1}),children:this.props.t("ra_Cancel")})]})]}):null}async renameCopyObject(t,e,i,n){var s;if(t===e)return;let a;try{a=((s=this.objects)==null?void 0:s[t])||await this.props.socket.getObject(t)}catch{}let o;if((a==null?void 0:a.type)==="state"&&(o=await this.props.socket.getState(t)),i)for(const l of this.props.childrenIds){const u=yd.calculateNewId(t,e,l);await this.renameCopyObject(l,u,!1,n)}a&&(await this.props.socket.setObject(e,a),o&&await this.props.socket.setState(e,o),n||await this.props.socket.delObject(t))}checkIfNewExists(){const t=`${this.state.parentId}.${this.state.name}`;this.checkTimer&&(clearTimeout(this.checkTimer),this.checkTimer=null),this.props.id===t?this.state.newExists||(this.checkTimer=setTimeout(()=>{this.checkTimer=null,this.setState({newExists:!0})},50)):this.checkTimer=setTimeout(async()=>{this.checkTimer=null;try{const e=await this.props.socket.getObject(t);e&&!this.state.newExists?this.setState({newExists:!0}):!e&&this.state.newExists&&this.setState({newExists:!1})}catch{this.state.newExists&&this.setState({newExists:!1})}},300)}renderParentSelectorDialog(){return this.state.showParentDialog?y.jsx(ey,{foldersFirst:!0,imagePrefix:"../..",expertMode:this.props.expertMode,socket:this.props.socket,columns:["name","type","role","room","func"],types:["folder","channel","device","meta"],notEditable:!0,selected:this.state.parentId,allowNonObjects:!0,filterFunc:t=>this.props.expertMode?!0:t._id.startsWith("0_userdata.0")||t._id.startsWith("javascript."),theme:this.props.theme,onSelectConfirm:(t,e)=>{let i;return Array.isArray(t)?i=t[0]:i=t,i.split(".").length<=1||e[i]&&(e[i].type==="state"||i.startsWith("system."))?Promise.resolve(!1):Promise.resolve(!0)},onClose:()=>this.setState({showParentDialog:!1}),onOk:t=>{let e;Array.isArray(t)?e=t[0]:e=t,e&&e.split(".").length>1&&this.setState({parentId:e})}}):null}render(){const t=`${this.state.parentId}.${this.state.name}`;return y.jsxs(w.Dialog,{open:!0,maxWidth:"md",fullWidth:!0,onClose:()=>this.props.onClose(),children:[this.renderParentSelectorDialog(),this.showHistoryWarning(),y.jsxs(w.DialogTitle,{children:[y.jsxs("span",{style:{opacity:.6,marginRight:8},children:[this.props.t("Rename or copy object")," -"]}),y.jsx("span",{style:{fontWeight:"bold"},children:this.props.id})]}),y.jsxs(w.DialogContent,{children:[y.jsxs("div",{style:{display:"flex",gap:8,alignItems:"end",opacity:.7},children:[y.jsx(w.TextField,{fullWidth:!0,variant:"standard",label:this.props.t("Parent ID"),value:`${this.state.parentId}.`,slotProps:{input:{readOnly:!0}}}),y.jsx(w.Button,{variant:"outlined",style:{maxWidth:40,width:40,height:32},onClick:()=>this.setState({showParentDialog:!0}),children:"..."})]}),y.jsx(w.TextField,{value:this.state.name,onChange:e=>{const i=e.target.value.replace(jt.FORBIDDEN_CHARS,"_").replace(/\./g,"_").replace(/\s/g,"_").replace(/,/g,"_").replace(/__/g,"_").replace(/__/g,"_");this.setState({name:i},()=>this.checkIfNewExists())},style:{marginTop:20},autoFocus:!0,variant:"standard",fullWidth:!0,label:this.props.t("New object ID")}),this.props.childrenIds.length?y.jsx(w.FormControlLabel,{control:y.jsx(w.Checkbox,{checked:this.state.renameAllChildren,onChange:()=>{this.setState({renameAllChildren:!this.state.renameAllChildren})}}),label:this.props.t("Rename all children")}):null,y.jsxs("div",{children:[y.jsxs("span",{style:{opacity:.6,marginRight:8,fontSize:16},children:[this.props.t("New object ID"),":"]}),y.jsx("span",{style:{fontWeight:"bold",fontSize:16},children:t})]})]}),y.jsxs(w.DialogActions,{children:[y.jsx(w.Button,{disabled:!this.state.name||t===this.props.id,color:"primary",variant:"outlined",onClick:async()=>{await this.renameCopyObject(this.props.id,t,this.props.childrenIds.length&&this.state.renameAllChildren,!0),this.props.onClose()},children:this.props.t("Create a copy")}),y.jsx(w.Button,{disabled:!this.state.name||t===this.props.id,color:"primary",variant:"contained",onClick:async()=>{await this.checkHistory()&&(await this.renameCopyObject(this.props.id,t,this.props.childrenIds.length&&this.state.renameAllChildren,!1),this.props.onClose())},children:t!==this.props.id&&this.state.newExists?this.props.t("Replace"):this.props.t("Rename")}),y.jsx(w.Button,{variant:"contained",color:"grey",onClick:()=>this.props.onClose(),startIcon:y.jsx(X.Close,{}),children:this.props.t("ra_Cancel")})]})]})}}const LO=X.Delete,vs={buttonAll:{color:"#FF0000"},id:{fontStyle:"italic"},buttonText:{whiteSpace:"nowrap"}};class OO extends at.Component{dialogName;filters;t;wordCache;constructor(t){super(t),this.dialogName="AdminObjects";const e=(window._localStorage||window.localStorage).getItem(`${this.dialogName||"App"}.filters`)||"{}";try{this.filters=JSON.parse(e)}catch{this.filters={}}const i=(window._localStorage||window.localStorage).getItem(`${this.dialogName||"App"}.selected`)||"";this.state={selected:i,name:"",toast:"",deleteObjectShow:null},this.t=this.translate,this.wordCache={}}translate=(t,e,i)=>e!==void 0?this.props.t(t,e,i):(this.wordCache[t]||(this.wordCache[t]=this.props.t(t)),this.wordCache[t]);onDelete(t){const e=this.state.deleteObjectShow.id;t?(this.props.socket.delObjects(e,!0).then(()=>this.setState({toast:this.t("All deleted")})).catch(i=>window.alert(`Cannot delete object: ${i}`)),this.setState({deleteObjectShow:null})):(this.props.socket.delObject(e,!1).catch(i=>window.alert(`Cannot delete object: ${i}`)),this.setState({deleteObjectShow:null}))}renderToast(){return y.jsx(w.Snackbar,{anchorOrigin:{vertical:"bottom",horizontal:"right"},open:!!this.state.toast,autoHideDuration:3e3,onClose:()=>this.setState({toast:""}),message:this.state.toast,action:y.jsx(w.IconButton,{size:"small","aria-label":"close",color:"inherit",onClick:()=>this.setState({toast:""}),children:y.jsx(X.Cancel,{fontSize:"small"})})},"toast")}renderDeleteDialog(){return this.state.deleteObjectShow?y.jsxs(w.Dialog,{maxWidth:"md",open:!0,onClose:()=>this.setState({deleteObjectShow:null}),"aria-labelledby":"delete-object-dialog-title","aria-describedby":"delete-object-dialog-description",children:[y.jsxs(w.DialogTitle,{id:"delete-object-dialog-title",children:[this.state.deleteObjectShow.hasChildren?this.t("Delete object(s)"):this.t("Delete object"),":"," ",y.jsx("span",{style:vs.id,children:this.state.deleteObjectShow.id})]}),y.jsx(w.DialogContent,{children:y.jsx(w.DialogContentText,{children:this.t("Are you sure?")})}),y.jsxs(w.DialogActions,{children:[this.state.deleteObjectShow.hasChildren?y.jsx(w.Button,{variant:"contained",color:"grey",sx:{"& .MuiButton-text":vs.buttonText},onClick:()=>this.onDelete(!0),startIcon:y.jsx(LO,{style:vs.buttonAll}),children:this.t("Delete with children",this.state.deleteObjectShow.childrenCount)}):null,this.state.deleteObjectShow.exists?y.jsx(w.Button,{variant:"contained",sx:{"& .MuiButton-text":vs.buttonText},onClick:()=>this.onDelete(!1),color:"primary",startIcon:y.jsx(X.Delete,{}),autoFocus:!0,children:this.t("Delete one item")}):null,y.jsx(w.Button,{variant:"contained",color:"grey",onClick:()=>this.setState({deleteObjectShow:null}),startIcon:y.jsx(X.Cancel,{}),children:this.t("ra_Cancel")})]})]},"delete"):null}render(){return[this.renderToast(),y.jsx(Jx,{dialogName:"admin",objectsWorker:this.props.objectsWorker,prefix:this.props.prefix,defaultFilters:this.filters,statesOnly:this.props.statesOnly,style:{width:"100%",height:"100%"},socket:this.props.socket,selected:this.state.selected,name:this.state.name,expertMode:this.props.expertMode,isFloatComma:this.props.isFloatComma,dateFormat:this.props.dateFormat,t:this.t,lang:this.props.lang,themeName:this.props.themeName,themeType:this.props.themeType,theme:this.props.theme,objectCustomDialog:wO,objectBrowserValue:Dn,objectBrowserEditObject:Ht,objectBrowserEditRole:md,objectBrowserViewFile:PO,objectBrowserAliasEditor:RO,objectMoveRenameDialog:yd,router:yh,enableStateValueEdit:!0,onObjectDelete:(t,e,i,n)=>this.setState({deleteObjectShow:{id:t,hasChildren:e,exists:i,childrenCount:n}}),onFilterChanged:t=>{this.filters=t,(window._localStorage||window.localStorage).setItem(`${this.dialogName||"App"}.filters`,JSON.stringify(t))},onSelect:t=>{Array.isArray(t)?(window._localStorage||window.localStorage).setItem(`${this.dialogName||"App"}.selected`,t[0]||""):(window._localStorage||window.localStorage).setItem(`${this.dialogName||"App"}.selected`,t||"")},objectEditBoolean:!0,objectAddBoolean:!0,objectStatesView:!0,objectImportExport:!0,objectEditOfAccessControl:!0,modalNewObject:t=>y.jsx(AO,{objects:t.objects,expertMode:this.props.expertMode,setObject:(e,i)=>this.props.socket.setObject(e,i).catch(n=>window.alert(n)),selected:t.state.modalNewObj.id,initialType:t.state.modalNewObj.initialType,initialStateType:t.state.modalNewObj.initialStateType,onClose:()=>t.setState({modalNewObj:null}),onApply:()=>t.setState({modalNewObj:null})}),modalEditOfAccessControl:(t,e)=>y.jsx(DO,{theme:this.props.theme,themeType:this.props.themeType,extendObject:(i,n)=>{this.props.socket.extendObject(i,n).catch(a=>window.alert(a)),e.aclTooltip=null},selected:t.state.selected[0],modalEmptyId:e.obj?"":e.id,objects:t.objects,t:this.t,onClose:()=>t.setState({modalEditOfAccess:!1,modalEditOfAccessObjData:null}),onApply:()=>t.setState({modalEditOfAccess:!1,modalEditOfAccessObjData:null})})},"browser"),this.renderDeleteDialog()]}}const eE=Wn()(OO);export{eE as default};
|
|
60
|
+
${o.getFullYear()}`}}},yAxis:i,toolbox:{left:"right",feature:this.props.noToolbar?void 0:{saveAsImage:{title:this.props.t("Save as image"),show:!0}}},series:[e]}}static getDerivedStateFromProps(t,e){return null}updateChart(t,e,i,n){t&&(this.start=t),e&&(this.end=e),t=t||this.start,e=e||this.end,this.readTimeout&&clearTimeout(this.readTimeout),this.readTimeout=setTimeout(()=>{var o;this.readTimeout=null;const a=this.chart.max-this.chart.min;a!==this.chart.diff&&(this.chart.diff=a,this.chart.withTime=this.chart.diff<36e5*24*7,this.chart.withSeconds=this.chart.diff<6e4*30),i?this.readHistory(t,e).then(s=>{var l;typeof((l=this.echartsReact)==null?void 0:l.getEchartsInstance)=="function"&&this.echartsReact.getEchartsInstance().setOption({series:[{data:this.convertData(s)}],xAxis:{min:this.chart.min,max:this.chart.max}}),n&&n()}):(typeof((o=this.echartsReact)==null?void 0:o.getEchartsInstance)=="function"&&this.echartsReact.getEchartsInstance().setOption({series:[{data:this.convertData()}],xAxis:{min:this.chart.min,max:this.chart.max}}),n&&n())},400)}setNewRange(t){var e;this.chart.diff=this.chart.max-this.chart.min,this.chart.withTime=this.chart.diff<36e5*24*7,this.chart.withSeconds=this.chart.diff<6e4*30,this.state.relativeRange!=="absolute"?(this.setState({relativeRange:"absolute"}),this.timeTimer&&(clearTimeout(this.timeTimer),this.timeTimer=null)):typeof((e=this.echartsReact)==null?void 0:e.getEchartsInstance)=="function"&&(this.echartsReact.getEchartsInstance().setOption({xAxis:{min:this.chart.min,max:this.chart.max}}),t&&this.updateChart(this.chart.min,this.chart.max,!0))}shiftTime(){const t=new Date,e=6e4-t.getSeconds()-(1e3-t.getMilliseconds());t.getMilliseconds()&&t.setMilliseconds(1e3),t.getSeconds()&&t.setSeconds(60);const i=t.getTime();let n;const a=this.state.relativeRange;if(a==="day")t.setHours(0),t.setMinutes(0),t.setSeconds(0),n=t.getTime();else if(a==="week"){t.setHours(0),t.setMinutes(0),t.setSeconds(0);const o=t.getDay()||7;o!==1&&t.setHours(-24*(o-1)),n=t.getTime()}else if(a==="2weeks"){t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setDate(t.getDate()-7);const o=t.getDay()||7;o!==1&&t.setHours(-24*(o-1)),n=t.getTime()}else a==="month"?(t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setDate(1),n=t.getTime()):a==="year"?(t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setDate(1),t.setMonth(0),n=t.getTime()):a==="12months"?(t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setFullYear(t.getFullYear()-1),n=t.getTime()):n=i-parseInt(a,10)*6e4;this.chart.min=n,this.chart.max=i,this.setState({min:n,max:i},()=>this.updateChart(this.chart.min,this.chart.max,!0)),this.timeTimer=setTimeout(()=>{this.timeTimer=null,this.shiftTime()},e||6e4)}setRelativeInterval(t,e,i){if(e||(this.localStorage.setItem("App.relativeRange",t),this.setState({relativeRange:t})),t==="absolute"){this.timeTimer&&(clearTimeout(this.timeTimer),this.timeTimer=null),this.updateChart(this.chart.min,this.chart.max,!0,i);return}this.localStorage.removeItem("App.absoluteStart"),this.localStorage.removeItem("App.absoluteEnd");const n=new Date;if(!this.timeTimer){const a=6e4-n.getSeconds()-(1e3-n.getMilliseconds());this.timeTimer=setTimeout(()=>{this.timeTimer=null,this.shiftTime()},a||6e4)}if(n.getMilliseconds()&&n.setMilliseconds(1e3),n.getSeconds()&&n.setSeconds(60),this.chart.max=n.getTime(),t==="day")n.setHours(0),n.setMinutes(0),n.setSeconds(0),this.chart.min=n.getTime();else if(t==="week"){n.setHours(0),n.setMinutes(0),n.setSeconds(0);const a=n.getDay()||7;a!==1&&n.setHours(-24*(a-1)),this.chart.min=n.getTime()}else if(t==="2weeks"){n.setHours(0),n.setMinutes(0),n.setSeconds(0),n.setDate(n.getDate()-7);const a=n.getDay()||7;a!==1&&n.setHours(-24*(a-1)),this.chart.min=n.getTime()}else t==="month"?(n.setHours(0),n.setMinutes(0),n.setSeconds(0),n.setDate(1),this.chart.min=n.getTime()):t==="year"?(n.setHours(0),n.setMinutes(0),n.setSeconds(0),n.setDate(1),n.setMonth(0),this.chart.min=n.getTime()):t==="12months"?(n.setHours(0),n.setMinutes(0),n.setSeconds(0),n.setFullYear(n.getFullYear()-1),this.chart.min=n.getTime()):this.chart.min=this.chart.max-parseInt(t,10)*6e4;this.setState({min:this.chart.min,max:this.chart.max},()=>this.updateChart(this.chart.min,this.chart.max,!0,i))}installEventHandlers(){if(!this.echartsReact||typeof this.echartsReact.getEchartsInstance!="function")return;const t=this.echartsReact.getEchartsInstance().getZr();t._iobInstalled||(t._iobInstalled=!0,t.on("mousedown",e=>{console.log("mouse down"),this.mouseDown=!0,this.chart.lastX=e.offsetX}),t.on("mouseup",()=>{console.log("mouse up"),this.mouseDown=!1,this.setNewRange(!0)}),t.on("mousewheel",e=>{let i=this.chart.max-this.chart.min;const n=this.state.chartWidth-Mi-he,o=(e.offsetX-he)/n,s=i,l=e.wheelDelta>0?1.1:.9;i*=l;const u=s-i;this.chart.max+=u*(1-o),this.chart.min-=u*o,this.setNewRange()}),t.on("mousemove",e=>{if(this.mouseDown){const i=this.chart.lastX-(e.offsetX-he);this.chart.lastX=e.offsetX-he;const n=this.chart.max-this.chart.min,a=this.state.chartWidth-Mi-he,o=Math.round(i*n/a);this.chart.min+=o,this.chart.max+=o,this.setNewRange()}}),t.on("touchstart",e=>{e.preventDefault(),this.mouseDown=!0;const i=e.touches||e.originalEvent.touches;i&&(this.chart.lastX=i[i.length-1].pageX,i.length>1?this.chart.lastWidth=Math.abs(i[0].pageX-i[1].pageX):this.chart.lastWidth=null)}),t.on("touchend",e=>{e.preventDefault(),this.mouseDown=!1,this.setNewRange(!0)}),t.on("touchmove",e=>{e.preventDefault();const i=e.touches||e.originalEvent.touches;if(!i)return;const n=i[i.length-1].pageX-he;if(this.mouseDown)if(i.length>1){const a=Math.abs(i[0].pageX-i[1].pageX);if(this.chart.lastWidth!==null&&a!==this.chart.lastWidth){let o=this.chart.max-this.chart.min;const s=this.state.chartWidth-Mi-he,l=a>this.chart.lastWidth?1.1:.9,h=(i[0].pageX>i[1].pageX?i[1].pageX-he+a/2:i[0].pageX-he+a/2)/s,c=o;o*=l;const f=c-o;this.chart.max+=f*(1-h),this.chart.min-=f*h,this.setNewRange()}this.chart.lastWidth=a}else{const a=this.chart.lastX-n,o=this.chart.max-this.chart.min,s=this.state.chartWidth-Mi-he,l=Math.round(a*o/s);this.chart.min+=l,this.chart.max+=l,this.setNewRange()}this.chart.lastX=n}))}renderChart(){var t;return this.state.historyInstance?(t=this.state.historyInstances)!=null&&t.find(e=>e.id===this.state.historyInstance&&e.alive)?this.chartValues?y.jsx(Uw,{ref:e=>this.echartsReact=e,echarts:gP,option:this.getOption(),notMerge:!0,lazyUpdate:!0,theme:this.props.themeType==="dark"?"dark":"",style:{height:`${this.state.chartHeight}px`,width:"100%"},opts:{renderer:"svg"},onEvents:{rendered:()=>this.installEventHandlers()}}):y.jsx(w.LinearProgress,{}):y.jsx("div",{style:{marginTop:20,fontSize:24,marginLeft:24},children:this.props.t("History instance not alive")}):y.jsx("div",{style:{marginTop:20,fontSize:24,marginLeft:24},children:this.props.t("History instance not selected")})}componentDidUpdate(){if(this.divRef.current){const t=this.divRef.current.offsetWidth,e=this.divRef.current.offsetHeight;this.state.chartHeight!==e&&(this.updateTimer&&clearTimeout(this.updateTimer),this.updateTimer=setTimeout(()=>{this.updateTimer=null,this.setState({chartHeight:e,chartWidth:t})},100))}}setStartDate(t){const e=t.getTime();this.timeTimer&&(clearTimeout(this.timeTimer),this.timeTimer=null),this.localStorage.setItem("App.relativeRange","absolute"),this.localStorage.setItem("App.absoluteStart",e.toString()),this.localStorage.setItem("App.absoluteEnd",this.state.max.toString()),this.chart.min=e,this.setState({min:e,relativeRange:"absolute"},()=>this.updateChart(this.chart.min,this.chart.max,!0))}setEndDate(t){const e=t.getTime();this.localStorage.setItem("App.relativeRange","absolute"),this.localStorage.setItem("App.absoluteStart",this.state.min.toString()),this.localStorage.setItem("App.absoluteEnd",e.toString()),this.timeTimer&&(clearTimeout(this.timeTimer),this.timeTimer=null),this.chart.max=e,this.setState({max:e,relativeRange:"absolute"},()=>this.updateChart(this.chart.min,this.chart.max,!0))}openEcharts(){const t=[`id=${window.encodeURIComponent(this.props.obj._id)}`,`instance=${window.encodeURIComponent(this.state.historyInstance)}`,"menuOpened=false"];this.state.relativeRange==="absolute"?(t.push(`start=${this.chart.min}`),t.push(`end=${this.chart.max}`)):t.push(`range=${this.state.relativeRange}`),window.open(`${window.location.protocol}//${window.location.host}/adapter/echarts/tab.html#${t.join("&")}`,"echarts")}async onStepChanged(t){const e=await this.props.socket.getObject(this.props.obj._id);e.common.custom&&e.common.custom[this.state.historyInstance]&&e.common.custom[this.state.historyInstance].chartStep!==t&&(e.common.custom[this.state.historyInstance].chartStep=t,await this.props.socket.setObject(e._id,e)),this.setState({stepType:t,showStepMenu:null})}renderToolbar(){return this.props.noToolbar?null:y.jsxs(w.Toolbar,{children:[!this.props.historyInstance&&y.jsxs(w.FormControl,{variant:"standard",style:Et.selectHistoryControl,children:[y.jsx(w.InputLabel,{children:this.props.t("History instance")}),y.jsx(w.Select,{variant:"standard",value:this.state.historyInstance,onChange:t=>{this.localStorage.setItem("App.historyInstance",t.target.value),this.setState({historyInstance:t.target.value})},children:this.state.historyInstances.map(t=>y.jsx(w.MenuItem,{value:t.id,style:t.alive?void 0:Et.notAliveInstance,children:t.id},t.id))})]}),y.jsxs(w.FormControl,{variant:"standard",style:Et.selectRelativeTime,children:[y.jsx(w.InputLabel,{children:this.props.t("Relative")}),y.jsxs(w.Select,{variant:"standard",ref:this.rangeRef,value:this.state.relativeRange,onChange:t=>this.setRelativeInterval(t.target.value),children:[y.jsx(w.MenuItem,{value:"absolute",sx:Et.customRange,children:this.props.t("custom range")},"custom"),y.jsx(w.MenuItem,{value:10,children:this.props.t("last 10 minutes")},"1"),y.jsx(w.MenuItem,{value:30,children:this.props.t("last 30 minutes")},"2"),y.jsx(w.MenuItem,{value:60,children:this.props.t("last hour")},"3"),y.jsx(w.MenuItem,{value:"day",children:this.props.t("this day")},"4"),y.jsx(w.MenuItem,{value:24*60,children:this.props.t("last 24 hours")},"5"),y.jsx(w.MenuItem,{value:"week",children:this.props.t("this week")},"6"),y.jsx(w.MenuItem,{value:24*60*7,children:this.props.t("last week")},"7"),y.jsx(w.MenuItem,{value:"2weeks",children:this.props.t("this 2 weeks")},"8"),y.jsx(w.MenuItem,{value:24*60*14,children:this.props.t("last 2 weeks")},"9"),y.jsx(w.MenuItem,{value:"month",children:this.props.t("this month")},"10"),y.jsx(w.MenuItem,{value:30*24*60,children:this.props.t("last 30 days")},"11"),y.jsx(w.MenuItem,{value:"year",children:this.props.t("this year")},"12"),y.jsx(w.MenuItem,{value:"12months",children:this.props.t("last 12 months")},"13")]})]}),y.jsxs(qt.LocalizationProvider,{dateAdapter:ks,adapterLocale:Os[this.props.lang],children:[y.jsxs("div",{style:Et.toolbarTimeGrid,children:[y.jsx("div",{style:{...Et.toolbarTimeLabel,opacity:this.state.relativeRange!=="absolute"?.5:void 0},children:this.props.t("Start time")}),y.jsx(qt.DatePicker,{sx:Et.toolbarDate,disabled:this.state.relativeRange!=="absolute",value:new Date(this.state.min),onChange:t=>this.setStartDate(t)}),y.jsx(qt.TimePicker,{disabled:this.state.relativeRange!=="absolute",sx:Et.toolbarTime,ampm:this.state.ampm,value:new Date(this.state.min),onChange:t=>this.setStartDate(t)})]}),y.jsxs("div",{style:Et.toolbarTimeGrid,children:[y.jsx("div",{style:{...Et.toolbarTimeLabel,opacity:this.state.relativeRange!=="absolute"?.5:void 0},children:this.props.t("End time")}),y.jsx(qt.DatePicker,{disabled:this.state.relativeRange!=="absolute",sx:Et.toolbarDate,value:new Date(this.state.max),onChange:t=>this.setEndDate(t)}),y.jsx(qt.TimePicker,{disabled:this.state.relativeRange!=="absolute",sx:Et.toolbarTime,ampm:this.state.ampm,value:new Date(this.state.max),onChange:t=>this.setEndDate(t)})]})]}),y.jsx("div",{style:Et.grow}),y.jsx(w.Button,{style:{marginRight:10},variant:"outlined",onClick:t=>this.setState({showStepMenu:t.target}),children:this.state.stepType?this.props.t(this.state.stepType):this.props.t("Step type")}),this.state.showStepMenu?y.jsxs(w.Menu,{open:!0,anchorEl:this.state.showStepMenu,onClose:()=>this.setState({showStepMenu:null}),children:[y.jsx(w.MenuItem,{selected:this.state.stepType==="",onClick:()=>this.onStepChanged(""),children:this.props.t("None")}),y.jsx(w.MenuItem,{selected:this.state.stepType==="stepStart",onClick:()=>this.onStepChanged("stepStart"),children:this.props.t("stepStart")})]}):null,this.props.showJumpToEchart&&this.state.echartsJump&&y.jsx(w.Fab,{style:Et.echartsButton,size:"small",onClick:()=>this.openEcharts(),title:this.props.t("Open charts in new window"),children:y.jsx("img",{src:bO,alt:"echarts",style:Et.buttonIcon})}),y.jsxs(w.Fab,{variant:"extended",size:"small",color:this.state.splitLine?"primary":"default","aria-label":"show lines",onClick:()=>{this.localStorage.setItem("App.splitLine",this.state.splitLine?"false":"true"),this.setState({splitLine:!this.state.splitLine})},children:[y.jsx(nw,{style:Et.splitLineButtonIcon}),this.props.t("Show lines")]})]})}render(){return!this.state.historyInstances&&!this.state.defaultHistory?y.jsx(w.LinearProgress,{}):y.jsxs(w.Paper,{style:Et.paper,children:[this.renderToolbar(),y.jsx("div",{ref:this.divRef,style:jt.getStyle(this.props.theme,Et.chart,this.props.noToolbar?Et.chartWithoutToolbar:Et.chartWithToolbar),children:this.renderChart()})]})}}const Wx=Wn()(xO),rr={dialog:{height:"100%"},paper:{height:"calc(100% - 64px)"},content:{textAlign:"center",overflow:"hidden"},tabPanel:r=>({width:"100%",overflow:"hidden",height:`calc(100% - ${r.mixins.toolbar.minHeight}px)`}),tabSelected:r=>({color:r.palette.mode==="dark"?r.palette.secondary.contrastText:"#FFFFFF !important"}),tabsIndicator:r=>({backgroundColor:r.palette.secondary.main})};class wO extends Cd{chartAvailable;saveFunc=null;constructor(t){super(t);let e=parseInt((window._localStorage||window.localStorage).getItem("App.objectCustomTab")||"0",10);if(this.chartAvailable=this.isChartAvailable(),this.chartAvailable){const i=yh.getLocation();i.arg==="chart"?e=2:i.arg==="table"&&(e=1)}else e=0;this.state={hasChanges:!1,currentTab:e,confirmDialog:!1,mobile:Cd.isMobile(),progressRunning:!1,showWarning:this.props.allVisibleObjects}}isChartAvailable(){var e,i;let t=this.props.objectIDs.length===1;if(t){const n=this.props.objectIDs[0];(i=(e=this.props.objects[n])==null?void 0:e.common)!=null&&i.custom?t=!!Object.keys(this.props.objects[n].common.custom).find(a=>{const o=this.props.objects[`system.adapter.${a}`];return o&&o.common&&o.common.getHistory}):t=!1}return t}renderCharts(){return y.jsx(Wx,{id:"custom-tabpanel-chart",isFloatComma:this.props.isFloatComma,showJumpToEchart:!0,t:this.props.t,lang:this.props.lang,expertMode:this.props.expertMode,socket:this.props.socket,obj:this.props.objects[this.props.objectIDs[0]],customsInstances:this.props.customsInstances,themeType:this.props.themeType,theme:this.props.theme,objects:this.props.objects})}renderTable(){return y.jsx(dw,{id:"custom-tabpanel-history",t:this.props.t,isFloatComma:this.props.isFloatComma,lang:this.props.lang,expertMode:this.props.expertMode,socket:this.props.socket,obj:this.props.objects[this.props.objectIDs[0]],customsInstances:this.props.customsInstances,themeName:this.props.themeName,objects:this.props.objects})}renderCustomEditor(){return y.jsx(lw,{id:"custom-tabpanel-settings",registerSaveFunc:t=>this.saveFunc=t,t:this.props.t,allVisibleObjects:this.props.allVisibleObjects,lang:this.props.lang,expertMode:this.props.expertMode,socket:this.props.socket,objectIDs:this.props.objectIDs,customsInstances:this.props.customsInstances,objects:this.props.objects,onProgress:t=>this.setState({progressRunning:t}),reportChangedIds:this.props.reportChangedIds,onChange:(t,e)=>{this.setState({hasChanges:t},()=>{if(e){const i=this.isChartAvailable();i!==this.chartAvailable&&(this.chartAvailable=i,this.forceUpdate())}})},theme:this.props.theme,themeName:this.props.themeName,themeType:this.props.themeType,systemConfig:this.props.systemConfig})}renderDialogConfirm(){return this.state.confirmDialog?y.jsx(mh,{title:G.t("You have unsaved changes"),text:G.t("Discard?"),ok:G.t("Yes"),cancel:G.t("Cancel"),onClose:t=>this.setState({confirmDialog:!1},()=>t&&this.props.onClose())}):null}onClose(){this.state.hasChanges?this.setState({confirmDialog:!0}):this.props.onClose()}renderWarningDialog(){return this.state.showWarning?y.jsx(mh,{text:y.jsx("div",{style:{color:"#F00"},children:this.props.t("Your are intend to edit ALL objects. Are you sure?")}),ok:this.props.t("Yes"),onClose:t=>{this.setState({showWarning:!1}),t||this.onClose()}}):null}render(){var e,i;const t=(i=(e=this.props.objects[this.props.objectIDs[0]])==null?void 0:e.common)==null?void 0:i.type;return y.jsxs(w.Dialog,{sx:{"&.MuiDialog-scrollPaper":rr.dialog,"& .MuiDialog-paper":rr.paper},scroll:"paper",open:!0,onClose:()=>this.props.onClose(),fullWidth:!0,maxWidth:"xl","aria-labelledby":"form-dialog-title",children:[this.renderDialogConfirm(),this.renderWarningDialog(),y.jsx(w.DialogTitle,{children:this.props.objectIDs.length>1?this.props.t("Edit config for %s states",this.props.objectIDs.length):this.props.t("Edit config: %s",this.props.objectIDs[0])}),y.jsxs(w.DialogContent,{style:rr.content,children:[y.jsx(w.AppBar,{position:"static",children:y.jsxs(w.Tabs,{value:this.state.currentTab,onChange:(n,a)=>{yh.doNavigate(null,null,null,a===1?"table":a===2?"chart":"config"),this.setState({currentTab:a}),(window._localStorage||window.localStorage).setItem("App.objectCustomTab",a)},sx:{"& .MuiTabs-indicator":rr.tabsIndicator},indicatorColor:"secondary",children:[y.jsx(w.Tab,{disabled:this.state.progressRunning,label:this.props.t("Custom settings"),id:"custom-settings-tab","aria-controls":"custom-tabpanel-settings",sx:{"&.Mui-selected":rr.tabSelected}}),this.props.objectIDs.length===1&&this.chartAvailable?y.jsx(w.Tab,{disabled:this.state.progressRunning,label:this.props.t("History data"),id:"history-data-tab","aria-controls":"custom-tabpanel-history",sx:{"&.Mui-selected":rr.tabSelected}}):null,(t==="number"||t==="boolean")&&this.props.objectIDs.length===1&&this.chartAvailable?y.jsx(w.Tab,{disabled:this.state.progressRunning,label:this.props.t("Chart"),id:"chart-tab","aria-controls":"custom-tabpanel-chart",sx:{"&.Mui-selected":rr.tabSelected}}):null]})}),this.state.currentTab===0?y.jsx(w.Box,{component:"div",sx:rr.tabPanel,children:this.renderCustomEditor()}):null,this.props.objectIDs.length===1&&this.chartAvailable&&this.state.currentTab===1?y.jsx(w.Box,{component:"div",sx:rr.tabPanel,children:this.renderTable()}):null,(t==="number"||t==="boolean")&&this.props.objectIDs.length===1&&this.chartAvailable&&this.state.currentTab===2?y.jsx(w.Box,{component:"div",sx:rr.tabPanel,children:this.renderCharts()}):null]}),y.jsxs(w.DialogActions,{children:[this.state.currentTab===0&&y.jsx(w.Button,{id:"object-custom-dialog-save",variant:"contained",color:"primary",disabled:!this.state.hasChanges||this.state.progressRunning,onClick:()=>this.saveFunc&&this.saveFunc(),children:this.getButtonTitle(y.jsx(X.Save,{}),this.props.t("Save"))}),this.state.currentTab===0&&y.jsx(w.Button,{id:"object-custom-dialog-save-close",variant:"contained",color:"primary",disabled:!this.state.hasChanges||this.state.progressRunning,onClick:()=>{this.saveFunc?this.saveFunc(n=>!n&&this.onClose()):this.onClose()},children:this.getButtonTitle(y.jsx(X.Save,{}),this.props.t("Save & close"),y.jsx(X.Close,{}))}),y.jsx(w.Button,{id:"object-custom-dialog-close",disabled:this.state.progressRunning,variant:"contained",onClick:()=>this.onClose(),color:"grey",children:this.getButtonTitle(y.jsx(X.Close,{}),this.props.t("Close"))})]})]})}}const ve={formControl:{minWidth:100},quality:{width:"calc(100% - 88px)"},expire:{ml:1,width:80},readOnly:{backgroundColor:"#b74848"},readOnlyText:{color:"#b74848",marginLeft:8},wrapperButton:{"@media screen and (max-width: 465px)":{"& *":{fontSize:12}},"@media screen and (max-width: 380px)":{"& *":{fontSize:11}}},ackCheckbox:{marginLeft:4},dialog:{minHeight:window.clientHeight-50>500?500:window.clientHeight-50},tooltip:{pointerEvents:"none"}};class Dn extends at.Component{propsValue;chartFrom;ack;inputRef=vh.createRef();q;expire;constructor(t){super(t);let e=this.props.type;e||(e=typeof this.props.value);let i=this.props.value;if(this.propsValue=i,this.propsValue===null?this.propsValue="null":this.propsValue===void 0&&(this.propsValue="undefined"),this.props.states)e="states";else if(e==="string"||e==="json"){if(i&&typeof i=="string"&&(i.startsWith("[")&&i.endsWith("]")||i.startsWith("{")&&i.endsWith("}")))try{i=JSON.parse(i),i=JSON.stringify(i,null,2),this.propsValue=i,e="json"}catch{}}else e==="number"&&(i=parseFloat(this.propsValue)||0);this.state={type:e,chart:!1,chartEnabled:(window._localStorage||window.localStorage).getItem("App.chartSetValue")!=="false",fullScreen:(window._localStorage||window.localStorage).getItem("App.fullScreen")==="true",targetValue:i,valid:!0,jsonError:!1},this.ack=!1,this.q=0,this.expire=0,this.inputRef=vh.createRef(),this.chartFrom=Date.now()-36e5*2}componentDidMount(){var t,e,i;this.props.defaultHistory&&((e=(t=this.props.object)==null?void 0:t.common)!=null&&e.custom)&&((i=this.props.object.common.custom[this.props.defaultHistory])!=null&&i.enabled)&&this.props.socket.getState(`system.adapter.${this.props.defaultHistory}.alive`).then(n=>this.setState({chart:!!(n!=null&&n.val)})),setTimeout(()=>{var n;if((n=this.inputRef)!=null&&n.current){const a=this.inputRef.current,o=a.value||"",s=a.type;a.type==="number"&&(a.type="text"),a.setSelectionRange(0,o.length),s==="number"&&(a.type=s)}},200)}onUpdate(t){t&&(t.stopPropagation(),t.preventDefault());let e=this.state.targetValue;if(this.state.type==="states")if(e==="null")e=null;else{const i=this.props.type||typeof this.state.targetValue;e=typeof e=="object"?e.value:e,i==="number"?typeof e=="string"&&(e=parseFloat(e.replace(",","."))||0):i==="boolean"&&(e=e===!0||e==="true"||e==="1"||e==="ON"||e==="on")}else this.state.type==="number"?e==="null"?e=null:typeof e=="string"&&(e=parseFloat(e.replace(",","."))||0):this.state.type==="boolean"&&(e==="null"?e=null:e=e===!0||e==="true"||e==="1"||e==="ON"||e==="on");this.props.onClose({val:e,ack:this.ack,q:this.q,expire:parseInt(this.expire,10)||void 0})}static isNumberValid(t){const{common:e,value:i}=t;if(i==="")return!1;const n=Number(i);return typeof e.min=="number"&&n<e.min?!1:!(typeof e.max=="number"&&n>e.max)}renderTimePicker(){return y.jsxs(qt.LocalizationProvider,{adapterLocale:Os[this.props.lang],dateAdapter:ks,children:[y.jsx(qt.DatePicker,{value:Number(this.state.targetValue),onChange:t=>{t&&this.setState({targetValue:Math.round(t.getTime())})}}),y.jsx(qt.TimePicker,{value:Number(this.state.targetValue),views:["hours","minutes","seconds"],onChange:t=>{t&&this.setState({targetValue:Math.round(t.getTime())})}})]})}renderChart(){return y.jsx(Wx,{t:this.props.t,isFloatComma:this.props.isFloatComma,showJumpToEchart:!1,lang:this.props.lang,socket:this.props.socket,obj:this.props.object,themeType:this.props.themeType,theme:this.props.theme,from:this.chartFrom,end:Date.now(),noToolbar:!0,dateFormat:this.props.dateFormat,defaultHistory:this.props.defaultHistory})}static checkJsonError(t){try{return JSON.parse(t),!1}catch{return!0}}renderJsonEditor(){return y.jsx(ty,{error:this.state.jsonError,editValueMode:!0,themeType:this.props.themeType,defaultValue:(this.propsValue||"").toString(),onChange:t=>this.setState({targetValue:t,jsonError:Dn.checkJsonError(t)})})}renderStates(){if(!this.props.states)return null;if(this.props.type==="number"&&this.props.object.common.max!==void 0&&this.props.object.common.min!==void 0){const t=Object.keys(this.props.states).map(e=>({label:this.props.states[e],value:e}));return y.jsx(w.Autocomplete,{style:ve.formControl,disablePortal:!0,defaultValue:this.props.states[this.propsValue]!==void 0?this.props.states[this.propsValue]:this.propsValue,options:t,noOptionsText:"",freeSolo:!0,getOptionLabel:e=>(e==null?void 0:e.label)||(e!=null?e.toString():""),onChange:(e,i)=>this.setState({targetValue:i}),onInputChange:(e,i)=>this.setState({targetValue:i}),onKeyUp:e=>e.key==="Enter"&&this.onUpdate(e),renderInput:e=>y.jsx(w.TextField,{...e,label:this.props.t("Value"),variant:"standard"})})}return y.jsxs(w.FormControl,{variant:"standard",style:ve.formControl,children:[y.jsx(w.InputLabel,{children:this.props.t("Value")}),y.jsx(w.Select,{variant:"standard",defaultValue:this.propsValue,onChange:t=>this.setState({targetValue:t.target.value}),children:Object.keys(this.props.states).map((t,e)=>y.jsx(w.MenuItem,{value:t,children:this.props.states[t]},e))})]})}render(){var e,i,n;const t=y.jsxs("div",{style:{display:"flex",alignItems:"center"},children:[y.jsx(w.FormControlLabel,{style:{...ve.formControl,...this.props.expertMode?void 0:ve.ackCheckbox},control:y.jsx(w.Checkbox,{defaultChecked:!1,onChange:a=>this.ack=a.target.checked}),label:this.props.t("Acknowledged")}),y.jsx(w.Tooltip,{title:this.props.t("Acknowledged explanation"),slotProps:{popper:{sx:ve.tooltip}},children:y.jsx(X.Info,{color:"primary"})})]});return y.jsxs(w.Dialog,{open:!0,maxWidth:this.state.type==="number"||this.state.type==="boolean"||this.state.type==="states"?this.state.chart&&this.state.chartEnabled?"lg":void 0:"md",fullWidth:this.state.type==="json"&&this.state.fullScreen||this.state.type!=="number"&&this.state.type!=="boolean"&&this.state.type!=="states"||this.state.chart&&this.state.chartEnabled,fullScreen:this.state.type==="json"&&this.state.fullScreen,onClose:()=>this.props.onClose(),"aria-labelledby":"edit-value-dialog-title","aria-describedby":"edit-value-dialog-description",sx:{"&. MuiDialog-paper":this.state.type==="json"?ve.dialog:void 0},children:[y.jsxs(w.DialogTitle,{id:"edit-value-dialog-title",children:[this.props.t("Write value"),((e=this.props.object.common)==null?void 0:e.write)===!1?y.jsxs("span",{style:ve.readOnlyText,children:["(",this.props.t("read only"),")"]}):null,this.state.chart?y.jsx(w.Fab,{style:{float:"right"},size:"small",color:this.state.chartEnabled?"primary":"default",onClick:()=>{(window._localStorage||window.localStorage).setItem("App.chartSetValue",this.state.chartEnabled?"false":"true"),this.setState({chartEnabled:!this.state.chartEnabled})},children:y.jsx(X.ShowChart,{})}):null,this.state.type==="json"?y.jsx(w.IconButton,{style:{float:"right"},onClick:()=>{(window._localStorage||window.localStorage).setItem("App.fullScreen",this.state.fullScreen?"false":"true"),this.setState({fullScreen:!this.state.fullScreen})},children:this.state.fullScreen?y.jsx(X.FullscreenExit,{}):y.jsx(X.Fullscreen,{})}):null]}),y.jsx(w.DialogContent,{children:y.jsx("form",{noValidate:!0,autoComplete:"off",onSubmit:()=>!1,style:{...ve.dialogForm,height:"100%"},children:y.jsxs(w.Grid2,{container:!0,direction:"row",spacing:2,style:{height:"100%"},children:[y.jsx(w.Grid2,{size:{xs:this.state.chart&&this.state.chartEnabled?6:12},style:{height:"100%"},children:y.jsxs(w.Grid2,{container:!0,direction:"column",spacing:2,style:{marginTop:0,height:"100%"},children:[this.props.expertMode?y.jsx(w.Grid2,{children:y.jsxs(w.Grid2,{container:!0,direction:"row",spacing:2,style:{marginTop:0},children:[this.props.expertMode?y.jsx(w.Grid2,{children:y.jsxs(w.FormControl,{style:ve.formControl,children:[y.jsx(w.InputLabel,{style:{marginTop:10,marginLeft:-14},children:this.props.t("Value type")}),y.jsxs(w.Select,{variant:"standard",value:this.state.type,onChange:a=>{this.setState({type:a.target.value,valid:a.target.value==="number"?Dn.isNumberValid({value:this.state.targetValue,common:this.props.object.common}):!0,jsonError:!1},()=>{this.state.type==="json"&&this.setState({targetValue:(this.state.targetValue||"").toString(),jsonError:Dn.checkJsonError((this.state.targetValue||"").toString())})})},children:[y.jsx(w.MenuItem,{value:"string",children:"String"}),y.jsx(w.MenuItem,{value:"number",children:"Number"}),y.jsx(w.MenuItem,{value:"boolean",children:"Boolean"}),y.jsx(w.MenuItem,{value:"json",children:"JSON"}),this.props.states?y.jsx(w.MenuItem,{value:"states",children:"States"}):null]})]})}):null,this.state.type==="json"?y.jsx(w.Grid2,{flex:1}):null]})}):null,y.jsx(w.Grid2,{flex:this.state.type==="json"&&this.state.fullScreen?1:void 0,style:{paddingTop:0},children:this.state.type==="boolean"?y.jsx(w.Typography,{component:"div",style:this.props.expertMode?{marginTop:20,width:"100%",backgroundColor:this.props.themeType==="dark"?"#595959":"#dadada",borderRadius:5,padding:5}:void 0,children:y.jsxs(w.Grid2,{component:"label",container:!0,alignItems:"center",spacing:1,children:[y.jsxs(w.Grid2,{style:{marginRight:10},children:[this.props.t("Value"),":"]}),y.jsx(w.Grid2,{children:"FALSE"}),y.jsx(w.Grid2,{children:y.jsx(w.Switch,{autoFocus:!0,defaultChecked:this.propsValue==="null"||this.propsValue==="undefined"?!1:!!this.propsValue,onKeyUp:a=>a.key==="Enter"&&this.onUpdate(a),onChange:a=>this.setState({targetValue:a.target.checked})})}),y.jsx(w.Grid2,{children:"TRUE"})]})}):this.state.type==="number"?y.jsx(w.TextField,{variant:"standard",fullWidth:!0,autoFocus:!0,error:!this.state.valid,type:"number",slotProps:{htmlInput:{step:this.props.object.common.step,min:this.props.object.common.min,max:this.props.object.common.max}},inputRef:this.inputRef,helperText:this.props.t("Press ENTER to write the value, when focused"),value:this.state.targetValue.toString(),label:this.props.t("Value")+(this.props.object.common.min!==void 0||this.props.object.common.unit==="%"?`, ${this.props.t("min:")} ${this.props.object.common.min!==void 0?this.props.object.common.min:0}`:"")+(this.props.object.common.max!==void 0||this.props.object.common.unit==="%"?`, ${this.props.t("max:")} ${this.props.object.common.max!==void 0?this.props.object.common.max:100}`:""),onKeyUp:a=>a.key==="Enter"&&this.state.valid&&this.onUpdate(a),onChange:a=>{this.setState({targetValue:a.target.value,valid:Dn.isNumberValid({value:a.target.value,common:this.props.object.common})})}}):this.state.type==="json"?this.renderJsonEditor():this.state.type==="states"?this.renderStates():y.jsx(w.TextField,{variant:"standard",fullWidth:!0,inputRef:this.inputRef,autoFocus:!0,helperText:this.props.t("Press CTRL+ENTER to write the value, when focused"),label:this.props.t("Value"),multiline:!0,onKeyDown:a=>a.ctrlKey&&a.key==="Enter"&&this.onUpdate(a),defaultValue:this.propsValue.toString(),onChange:a=>this.setState({targetValue:a.target.value})})}),(this.props.role==="date"||(i=this.props.role)!=null&&i.startsWith("date."))&&this.state.type==="number"?y.jsx(w.Grid2,{style:{display:"flex",gap:"5px"},size:{xs:6},children:this.renderTimePicker()}):null,this.props.expertMode?y.jsx(w.Grid2,{children:t}):null,this.props.expertMode?y.jsxs(w.Grid2,{children:[y.jsxs(w.FormControl,{variant:"standard",style:ve.quality,children:[y.jsx(w.InputLabel,{children:this.props.t("Quality")}),y.jsxs(w.Select,{variant:"standard",defaultValue:0,onChange:a=>this.q=Number(a.target.value),children:[y.jsx(w.MenuItem,{value:0,children:"0x00 - good"}),y.jsx(w.MenuItem,{value:1,children:"0x01 - general problem"}),y.jsx(w.MenuItem,{value:2,children:"0x02 - no connection problem"}),y.jsx(w.MenuItem,{value:16,children:"0x10 - substitute value from controller"}),y.jsx(w.MenuItem,{value:32,children:"0x20 - substitute initial value"}),y.jsx(w.MenuItem,{value:64,children:"0x40 - substitute value from device or instance"}),y.jsx(w.MenuItem,{value:128,children:"0x80 - substitute value from sensor"}),y.jsx(w.MenuItem,{value:17,children:"0x11 - general problem by instance"}),y.jsx(w.MenuItem,{value:65,children:"0x41 - general problem by device"}),y.jsx(w.MenuItem,{value:129,children:"0x81 - general problem by sensor"}),y.jsx(w.MenuItem,{value:18,children:"0x12 - instance not connected"}),y.jsx(w.MenuItem,{value:66,children:"0x42 - device not connected"}),y.jsx(w.MenuItem,{value:130,children:"0x82 - sensor not connected"}),y.jsx(w.MenuItem,{value:68,children:"0x44 - device reports error"}),y.jsx(w.MenuItem,{value:132,children:"0x84 - sensor reports error"})]})]}),y.jsx(w.TextField,{variant:"standard",title:this.props.t("0 - no expiration"),sx:{"&.MuiTextField-root":ve.expire},label:this.props.t("Expire"),type:"number",slotProps:{htmlInput:{min:0}},helperText:this.props.t("in seconds"),defaultValue:this.expire,onChange:a=>this.expire=Number(a.target.value)})]}):null]})}),this.state.chart&&this.state.chartEnabled&&this.state.type!=="json"?y.jsx(w.Grid2,{size:{xs:6},style:{minHeight:300},sx:{display:{sm:"none",md:"inline-block"}},children:this.renderChart()}):null]})})}),y.jsxs(w.DialogActions,{sx:ve.wrapperButton,children:[this.props.expertMode?null:t,this.props.expertMode?null:y.jsx("div",{style:{flexGrow:1}}),y.jsx(w.Button,{variant:"contained",disabled:!this.state.valid,onClick:a=>this.onUpdate(a),color:"primary",startIcon:this.props.width!=="xs"?y.jsx(X.Check,{}):void 0,style:((n=this.props.object.common)==null?void 0:n.write)===!1?ve.readOnly:void 0,children:this.props.width!=="xs"?this.props.t("Set value"):y.jsx(X.Check,{fontSize:"large"})}),y.jsx(w.Button,{variant:"contained",onClick:()=>this.props.onClose(),color:"grey",startIcon:this.props.width!=="xs"?y.jsx(X.Close,{}):void 0,children:this.props.width!=="xs"?this.props.t("Cancel"):y.jsx(X.Close,{fontSize:"large"})})]})]})}}const O={divWithoutTitle:{width:"100%",height:"100%",border:"2px solid #00000000"},divWithoutTitleAndTab:{height:"calc(100% - 48px)"},error:{border:"2px solid #FF0000"},id:{fontStyle:"italic"},dialog:{height:"calc(100% - 64px)"},aliasIdEdit:{width:368},button:{marginTop:20,marginLeft:8},funcDivEdit:{width:"100%"},funcEditName:{display:"inline-block",width:85},funcEdit:{width:400},funcIcon:{width:16,height:16},marginTop:{marginTop:20},commonTabWrapper:{flexFlow:"wrap",display:"flex",gap:8},commonWrapper:{width:500,minWidth:300},flexDrop:{width:"100%",maxWidth:500,margin:"auto",display:"flex"},marginBlock:{marginTop:20},buttonAdd:{minWidth:150},textField:{width:"100%"},flex:{display:"flex","& > div":{mr:"8px"}},close:{width:"20px",height:"20px",opacity:"0.9",cursor:"pointer",position:"relative",top:20,transition:"all 0.6s ease","&:hover":{transform:"rotate(90deg)"},"&:before":{position:"absolute",left:"9px",content:'""',height:"20px",width:"3px",backgroundColor:"#ff4f4f",transform:"rotate(45deg)"},"&:after":{position:"absolute",left:"9px",content:'""',height:"20px",width:"3px",backgroundColor:"#ff4f4f",transform:"rotate(-45deg)"}},color:{width:70},buttonRemoveWrapper:{position:"absolute",zIndex:222,right:0},tabsPadding:{padding:"0px 24px"},wrapperButton:{"@media screen and (max-width: 465px)":{"& *":{fontSize:10}},"@media screen and (max-width: 380px)":{"& *":{fontSize:9}}},commonDeleteTip:{color:"#fa4a4a"},typeNameEng:{marginLeft:8,opacity:.7,fontStyle:"italic",fontSize:"smaller"},tooltip:{pointerEvents:"none"},stateRow:{width:"100%",display:"flex",justifyContent:"space-between",padding:3},stateTitle:{minWidth:150,fontWeight:"bold"},stateUnit:{opacity:.7,marginLeft:4},stateValue:{animation:"newStateEditorAnimation 2s ease-in-out"},stateTime:{fontStyle:"italic"},stateImage:{maxWidth:200,maxHeight:200}};function SO(r,t){return{"@keyframes newStateEditorAnimation":{"0%":{color:r.palette.mode==="dark"?"#27cf00":"#174e00"},"100%":{color:t||(r.palette.mode==="dark"?"#ffffff":"#000000")}}}}const yo=[{role:"button",type:"boolean",r:!1,w:!0},{role:"button.close.blind",type:"boolean",r:!1,w:!0},{role:"button.fastforward",type:"boolean",r:!1,w:!0},{role:"button.forward",type:"boolean",r:!1,w:!0},{role:"button.long",type:"boolean",r:!1,w:!0},{role:"button.mode",type:"boolean",r:!1,w:!0},{role:"button.mode.auto",type:"boolean",r:!1,w:!0},{role:"button.mode.silent",type:"boolean",r:!1,w:!0},{role:"button.next",type:"boolean",r:!1,w:!0},{role:"button.open.blind",type:"boolean",r:!1,w:!0},{role:"button.open.door",type:"boolean",r:!1,w:!0},{role:"button.pause",type:"boolean",r:!1,w:!0},{role:"button.stop",type:"boolean",r:!1,w:!0},{role:"button.stop.tilt",type:"boolean",r:!1,w:!0},{role:"button.volume.up",type:"boolean",r:!1,w:!0},{role:"chart",type:"string"},{role:"date",type:"string"},{role:"date",type:"number"},{role:"date.end",type:"string"},{role:"date.end",type:"number"},{role:"date.forecast.1",type:"string"},{role:"date.start",type:"string"},{role:"date.start",type:"number"},{role:"date.sunrise",type:"string"},{role:"date.sunrise",type:"number"},{role:"date.sunset",type:"string"},{role:"date.sunset",type:"number"},{role:"dayofweek",type:"number"},{role:"html",type:"string"},{role:"indicator",type:"boolean",w:!1},{role:"indicator.alarm",type:"boolean",w:!1},{role:"indicator.alarm.fire",type:"boolean",w:!1},{role:"indicator.alarm.flood",type:"boolean",w:!1},{role:"indicator.alarm.health",type:"boolean",w:!1},{role:"indicator.alarm.secure",type:"boolean",w:!1},{role:"indicator.connected",type:"boolean",w:!1},{role:"indicator.maintenance",type:"boolean",w:!1},{role:"indicator.maintenance.alarm",type:"boolean",w:!1},{role:"indicator.maintenance.lowbat",type:"boolean",w:!1},{role:"indicator.maintenance.waste",type:"boolean",w:!1},{role:"indicator.reachable",type:"boolean",w:!1},{role:"info.address",type:"string",w:!1},{role:"info.display",type:"string",w:!1},{role:"info.firmware",type:"string",w:!1},{role:"info.hardware",type:"string",w:!1},{role:"info.ip",type:"string",w:!1},{role:"info.mac",type:"string",w:!1},{role:"info.name",type:"string",w:!1},{role:"info.port",type:"string",w:!1},{role:"info.port",type:"number",w:!1},{role:"info.serial",type:"string",w:!1},{role:"info.standby",type:"string",w:!1},{role:"info.status",w:!1},{role:"json",type:"string"},{role:"level",type:"number",w:!0},{role:"level.bass",type:"number",w:!0},{role:"level.blind",type:"number",w:!0},{role:"level.color.blue",type:"number",w:!0},{role:"level.color.hue",type:"number",w:!0},{role:"level.color.luminance",type:"number",w:!0},{role:"level.color.red",type:"number",w:!0},{role:"level.color.saturation",type:"number",w:!0},{role:"level.curtain",type:"number",w:!0},{role:"level.mode.airconditioner",type:"number",w:!0},{role:"level.mode.cleanup",type:"number",w:!0},{role:"level.mode.fan",type:"number",w:!0},{role:"level.mode.swing",type:"number",w:!0},{role:"level.mode.thermostat",type:"number",w:!0},{role:"level.mode.work",type:"number",w:!0},{role:"level.temperature",type:"number",w:!0},{role:"level.tilt",type:"number",w:!0},{role:"level.timer",type:"number",w:!0},{role:"level.treble",type:"number",w:!0},{role:"level.valve",type:"number",w:!0},{role:"level.volume",type:"number",w:!0},{role:"level.volume.group",type:"number",w:!0},{role:"list",type:"string"},{role:"list",type:"array"},{role:"location",type:"string"},{role:"media.add",type:"string"},{role:"media.bitrate",type:"string"},{role:"media.bitrate",type:"number"},{role:"media.broadcastDate",type:"string"},{role:"media.browser",type:"string"},{role:"media.clear",type:"boolean"},{role:"media.content",type:"string"},{role:"media.cover",type:"string"},{role:"media.cover.big",type:"string"},{role:"media.cover.small",type:"string"},{role:"media.date",type:"string"},{role:"media.duration",type:"number"},{role:"media.duration",type:"string"},{role:"media.duration.text",type:"string"},{role:"media.elapsed",type:"number"},{role:"media.elapsed",type:"string"},{role:"media.elapsed.text",type:"string"},{role:"media.episode",type:"number"},{role:"media.episode",type:"string"},{role:"media.genre",type:"string"},{role:"media.input",type:"string"},{role:"media.jump",type:"string"},{role:"media.link",type:"string"},{role:"media.mode.repeat",type:"string"},{role:"media.mode.shuffle",type:"string"},{role:"media.mute",type:"string"},{role:"media.mute.group",type:"string"},{role:"media.playid",type:"string"},{role:"media.playlist",type:"string"},{role:"media.season",type:"string"},{role:"media.seek",type:"string"},{role:"media.state",type:"string"},{role:"media.titel",type:"string"},{role:"media.track",type:"string"},{role:"media.tts",type:"string"},{role:"media.url",type:"string"},{role:"media.url.announcement",type:"string"},{role:"medien.artist",type:"string"},{role:"sensor.alarm",type:"boolean",w:!1},{role:"sensor.alarm.fire",type:"boolean",w:!1},{role:"sensor.alarm.flood",type:"boolean",w:!1},{role:"sensor.alarm.power",type:"boolean",w:!1},{role:"sensor.alarm.secure",type:"boolean",w:!1},{role:"sensor.door",type:"boolean",w:!1},{role:"sensor.light",type:"boolean",w:!1},{role:"sensor.lock",type:"boolean",w:!1},{role:"sensor.motion",type:"boolean",w:!1},{role:"sensor.noise",type:"boolean",w:!1},{role:"sensor.rain",type:"boolean",w:!1},{role:"sensor.window",type:"boolean",w:!1},{role:"state",type:"mixed"},{role:"switch",type:"boolean",w:!0},{role:"switch.enable",type:"boolean",w:!0},{role:"switch.gate",type:"boolean",w:!0},{role:"switch.gate",type:"boolean",w:!0},{role:"switch.light",type:"boolean",w:!0},{role:"switch.lock.door",type:"boolean",w:!0},{role:"switch.lock.window",type:"boolean",w:!0},{role:"switch.mode",type:"boolean",w:!0},{role:"switch.mode.auto",type:"boolean",w:!0},{role:"switch.mode.boost",type:"boolean",w:!0},{role:"switch.mode.color",type:"boolean",w:!0},{role:"switch.mode.manual",type:"boolean",w:!0},{role:"switch.mode.moonlight",type:"boolean",w:!0},{role:"switch.mode.party",type:"boolean",w:!0},{role:"switch.mode.silent",type:"boolean",w:!0},{role:"switch.power",type:"boolean",w:!0},{role:"switch.power.zone",type:"boolean",w:!0},{role:"text",type:"string"},{role:"text.phone",type:"string"},{role:"text.url",type:"string"},{role:"url",type:"string"},{role:"url.audio",type:"string"},{role:"url.blank",type:"string"},{role:"url.cam",type:"string"},{role:"url.same",type:"string"},{role:"value",type:"number",w:!1},{role:"value.battery",type:"number",w:!1},{role:"value.blind",type:"number",w:!1},{role:"value.blood.sugar",type:"number",w:!1},{role:"value.brightness",type:"number",w:!1},{role:"value.clouds",type:"number",w:!1},{role:"value.current",type:"number",w:!1},{role:"value.curtain",type:"number",w:!1},{role:"value.default",type:"number",w:!1},{role:"value.direction",type:"number",w:!1},{role:"value.direction.max.wind",type:"number",w:!1},{role:"value.direction.min.wind",type:"number",w:!1},{role:"value.direction.wind",type:"number",w:!1},{role:"value.direction.wind.forecast.0",type:"number",w:!1},{role:"value.direction.wind.forecast.1",type:"number",w:!1},{role:"value.distance",type:"number",w:!1},{role:"value.fill",type:"number",w:!1},{role:"value.gate",type:"number",w:!1},{role:"value.gps",type:"number",w:!1},{role:"value.gps.accuracy",type:"number",w:!1},{role:"value.gps.elevation",type:"number",w:!1},{role:"value.gps.latitude",type:"number",w:!1},{role:"value.gps.longitude",type:"number",w:!1},{role:"value.gps.radius",type:"number",w:!1},{role:"value.health.bmi",type:"number",w:!1},{role:"value.health.bpm",type:"number",w:!1},{role:"value.health.calories",type:"number",w:!1},{role:"value.health.fat",type:"number",w:!1},{role:"value.health.steps",type:"number",w:!1},{role:"value.health.weight",type:"number",w:!1},{role:"value.humidity",type:"number",w:!1},{role:"value.humidity",type:"number",w:!1},{role:"value.humidity.max",type:"number",w:!1},{role:"value.humidity.min",type:"number",w:!1},{role:"value.interval",type:"number",w:!1},{role:"value.lock",type:"number",w:!1},{role:"value.min",type:"number",w:!1},{role:"value.position",type:"number",w:!1},{role:"value.power",type:"number",w:!1},{role:"value.power.consumption",type:"number",w:!1},{role:"value.power.production",type:"number",w:!1},{role:"value.power.reactive",type:"number",w:!1},{role:"value.precipitation",type:"number",w:!1},{role:"value.precipitation.chance",type:"number",w:!1},{role:"value.precipitation.day.forecast.0",type:"number",w:!1},{role:"value.precipitation.forecast.0",type:"number",w:!1},{role:"value.precipitation.hour",type:"number",w:!1},{role:"value.precipitation.night.forecast.0",type:"number",w:!1},{role:"value.precipitation.today",type:"number",w:!1},{role:"value.precipitation.type",type:"number",w:!1},{role:"value.prepitation.forecast.0",type:"number",w:!1},{role:"value.prepitation.forecast.1",type:"number",w:!1},{role:"value.prepitation.forecast.1",type:"number",w:!1},{role:"value.pressure",type:"number",w:!1},{role:"value.pressure.forecast.0",type:"number",w:!1},{role:"value.pressure.forecast.1",type:"number",w:!1},{role:"value.radiation",type:"number",w:!1},{role:"value.rain",type:"number",w:!1},{role:"value.rain.hour",type:"number",w:!1},{role:"value.rain.today",type:"number",w:!1},{role:"value.severity",type:"number",w:!1},{role:"value.snow",type:"number",w:!1},{role:"value.snow.hour",type:"number",w:!1},{role:"value.snow.today",type:"number",w:!1},{role:"value.snowline",type:"number",w:!1},{role:"value.speed",type:"number",w:!1},{role:"value.speed.max.wind",type:"number",w:!1},{role:"value.speed.min.wind",type:"number",w:!1},{role:"value.speed.wind",type:"number",w:!1},{role:"value.speed.wind.forecast.0",type:"number",w:!1},{role:"value.speed.wind.gust",type:"number",w:!1},{role:"value.state",type:"number",w:!1},{role:"value.sun.azimuth",type:"number",w:!1},{role:"value.sun.elevation",type:"number",w:!1},{role:"value.temperature",type:"number",w:!1},{role:"value.temperature",type:"number",w:!1},{role:"value.temperature.dewpoint",type:"number",w:!1},{role:"value.temperature.feelslike",type:"number",w:!1},{role:"value.temperature.max",type:"number",w:!1},{role:"value.temperature.max.forecast.0",type:"number",w:!1},{role:"value.temperature.min",type:"number",w:!1},{role:"value.temperature.min.forecast.0",type:"number",w:!1},{role:"value.temperature.min.forecast.1",type:"number",w:!1},{role:"value.temperature.windchill",type:"number",w:!1},{role:"value.tilt",type:"number",w:!1},{role:"value.time",type:"number",w:!1},{role:"value.uv",type:"number",w:!1},{role:"value.valve",type:"number",w:!1},{role:"value.voltage",type:"number",w:!1},{role:"value.warning",type:"number",w:!1},{role:"value.waste",type:"number",w:!1},{role:"value.water",type:"number",w:!1},{role:"waether.title",type:"string",w:!1},{role:"weather.chart.url",type:"string",w:!1},{role:"weather.chart.url.forecast",type:"string",w:!1},{role:"weather.direction.wind",type:"number",w:!1},{role:"weather.direction.wind.forecast.0",type:"number",w:!1},{role:"weather.html",type:"string",w:!1},{role:"weather.icon",type:"string",w:!1},{role:"weather.icon.forecast.1",type:"string",w:!1},{role:"weather.icon.name",type:"string",w:!1},{role:"weather.icon.wind",type:"string",w:!1},{role:"weather.json",type:"string",w:!1},{role:"weather.state",type:"number",w:!1},{role:"weather.state",type:"string",w:!1},{role:"weather.state.forecast.0",type:"string",w:!1},{role:"weather.state.forecast.1",type:"string",w:!1},{role:"weather.title.forecast.0",type:"string",w:!1},{role:"weather.title.short",type:"string",w:!1},{role:"weather.type",type:"number",w:!1},{role:"weather.type",type:"string",w:!1}];class Ht extends at.Component{originalObj;subscribed=!1;updateTimer=null;constructor(t){super(t);const e=this.props.obj._id.startsWith("alias.0")&&this.props.obj.type==="state";let i=(window._localStorage||window.localStorage).getItem(`${this.props.dialogName||"App"}.editTab`)||"object";i==="alias"&&!e&&(i="common"),this.props.aliasTab&&e&&(i="alias");const n=this.props.obj,a=n.common&&"type"in n.common&&"alias"in n.common?n.common.alias.read:void 0,o=n.common&&"type"in n.common&&"alias"in n.common?n.common.alias.write:void 0;this.state={text:JSON.stringify(this.props.obj,null,2),error:!1,customError:!1,changed:!1,readError:this.checkFunction(a,!1),writeError:this.checkFunction(o,!0),tab:i,showCopyDialog:"",showCommonDeleteMessage:!1,selectId:!1,selectRead:!1,selectWrite:!1,newId:"",lang:G.getLanguage(),value:void 0},Ul.locale(this.state.lang),this.originalObj=JSON.stringify(this.props.obj,null,2)}async componentDidMount(){var i,n,a;const t=((n=(i=this.props.obj)==null?void 0:i.common)==null?void 0:n.editSchemas)||((a=this.props.obj)==null?void 0:a.editSchemas),e=[];if(t)if(typeof t=="object"){const o=Object.keys(t);for(let s=0;s<o.length;s++)try{const l=await Td(t[o[s]],this.props.socket);if(l.key=o[s],l&&typeof l=="object"&&e.push(l),l.icon)try{const u=qx(l.icon);if(u.type!=="base64"&&u.type!=="http"){const h=await Td(u,this.props.socket);h&&(l.icon=h)}}catch(u){console.warn(`Cannot get icon for schema from "${l.icon}": ${u}`),l.icon=void 0}}catch(l){console.warn(`Cannot get edit schema for "${t[o[s]]}": ${l}`)}e.length&&(e.sort((s,l)=>s.order!==void 0&&l.order!==void 0?s.order-l.order:s.order!==void 0?-1:l.order!==void 0||s.key>l.key?1:-1),this.setState({customEditTabs:e}))}else console.warn(`Invalid edit schema for "${t}": expected object, but got ${typeof t}`);this.state.tab==="alias"&&(!this.props.obj._id.startsWith("alias.0")||this.props.obj.type!=="state")?this.setState({tab:"object"}):this.state.tab==="state"&&this.props.obj.type!=="state"?this.setState({tab:"object"}):this.state.tab!=="object"&&this.state.tab!=="common"&&this.state.tab!=="alias"&&this.state.tab!=="state"&&!e.find(o=>o.key===this.state.tab)&&this.setState({tab:"object"}),this.state.tab==="state"&&this.subscribeOnState(!0),this.props.socket.subscribeObject(this.props.obj._id,this.onObjectUpdated)}componentWillUnmount(){this.updateTimer&&(clearInterval(this.updateTimer),this.updateTimer=null),this.subscribeOnState(!1),this.props.socket.unsubscribeObject(this.props.obj._id,this.onObjectUpdated)}onObjectUpdated=(t,e)=>{this.originalObj!==JSON.stringify(e,null,2)&&(this.originalObj=JSON.stringify(e,null,2),this.state.changed?this.forceUpdate():this.setState({text:this.originalObj}))};checkFunction(t,e){var a,o,s,l;if(!t||t.includes("JSON.parse("))return"";let i;try{i=JSON.parse(this.state.text)}catch{}let n;try{n=new Function("val",t.includes("return")?t:`return ${t}`)}catch{return this.props.t("Cannot parse code!")}if((a=i==null?void 0:i.common)!=null&&a.type&&((l=(s=this.props.objects[(o=i.common.alias)==null?void 0:o.id])==null?void 0:s.common)!=null&&l.type)){const u=e?i.common.type:this.props.objects[i.common.alias.id].common.type,h=e?this.props.objects[i.common.alias.id].common.type:i.common.type;if(u&&h){let c=null;if(u==="boolean"?c=!0:u==="number"?c=1:(u==="string"||u==="mixed")&&(c="string"),c!==null)try{const f=n(c);return h==="mixed"?"":f!==null&&typeof f!==h?this.props.t("Type of result is not as expected: %s",h):""}catch(f){return`${this.props.t("Cannot execute function")}: ${f.toString()}`}}}return""}prepareObject(t){var e,i,n,a;t=t||this.state.text;try{const o=JSON.parse(t);return o._id=this.props.obj._id,(e=o.common)!=null&&e.alias&&(o.common.alias.id||delete o.common.alias.id,(!o.common.alias.read&&o.common.alias.read!==void 0||o.common.alias.read==="val")&&delete o.common.alias.read,(!o.common.alias.write&&o.common.alias.write!==void 0||o.common.alias.write==="val")&&delete o.common.alias.write,!o.common.alias.id&&!o.common.alias.read&&!o.common.alias.write&&delete o.common.alias),((i=o.common)==null?void 0:i.min)!==void 0&&typeof o.common.min!="number"&&(o.common.min=parseFloat(o.common.min)),((n=o.common)==null?void 0:n.max)!==void 0&&typeof o.common.max!="number"&&(o.common.max=parseFloat(o.common.max)),((a=o.common)==null?void 0:a.step)!==void 0&&typeof o.common.step!="number"&&(o.common.step=parseFloat(o.common.step)),o}catch{return null}}onChange(t,e){var a,o,s,l;const i=this.prepareObject(t),n={text:t};if(i){n.changed=this.originalObj!==JSON.stringify(i,null,2),n.showCommonDeleteMessage=!1;const u=JSON.parse(this.originalObj);i.common&&Object.keys(u.common||{}).forEach(h=>{i.common[h]===void 0&&(n.showCommonDeleteMessage=!0)}),n.error=!1,n.readError=this.checkFunction((o=(a=i.common)==null?void 0:a.alias)==null?void 0:o.read,!1),n.writeError=this.checkFunction((l=(s=i.common)==null?void 0:s.alias)==null?void 0:l.write,!0)}else n.showCommonDeleteMessage=!1,n.error=!0;this.setState(n,()=>e&&e())}onUpdate(){var t,e,i,n;try{const a=JSON.parse(this.state.text);a._id=this.props.obj._id,(t=a.common)!=null&&t.alias&&(a.common.alias.id||delete a.common.alias.id,(!a.common.alias.read&&a.common.alias.read!==void 0||a.common.alias.read==="val")&&delete a.common.alias.read,(!a.common.alias.write&&a.common.alias.write!==void 0||a.common.alias.write==="val")&&delete a.common.alias.write,!a.common.alias.id&&!a.common.alias.read&&!a.common.alias.write&&delete a.common.alias),((e=a.common)==null?void 0:e.min)!==void 0&&typeof a.common.min!="number"&&(a.common.min=parseFloat(a.common.min)),((i=a.common)==null?void 0:i.max)!==void 0&&typeof a.common.max!="number"&&(a.common.max=parseFloat(a.common.max)),((n=a.common)==null?void 0:n.step)!==void 0&&typeof a.common.step!="number"&&(a.common.step=parseFloat(a.common.step)),this.props.onClose(a)}catch{console.error(`Cannot parse: ${this.state.text}`)}}static getPartOfObject(t,e){return e?Ad(JSON.parse(t),e.split(".")):JSON.parse(t)}static setPartOfObject(t,e,i){let n=JSON.parse(t);return n===void 0?t:(n=Zx(n,i.split("."),e),JSON.stringify(n,null,2))}renderCustomPanel(){var i;const t=(i=this.state.customEditTabs)==null?void 0:i.find(n=>n.key===this.state.tab);if(!t)return null;let e;try{e=Ht.getPartOfObject(this.state.text,t.path)}catch(n){return console.error(`Cannot get data for ${t.path}: ${n}`),y.jsx("div",{children:G.t("Cannot get data for %s: %s",t.path,n)})}return e?y.jsx(gh,{theme:this.props.theme,socket:this.props.socket,themeName:this.props.theme.palette.mode,themeType:this.props.theme.palette.mode,dateFormat:this.props.dateFormat,isFloatComma:this.props.isFloatComma,schema:t.json,data:e,onChange:n=>{try{const a=Ht.setPartOfObject(this.state.text,n,t.path);this.onChange(a)}catch(a){console.error(`Cannot set data for ${t.path}: ${a}`)}},adapterName:"",instance:0,onError:n=>{console.warn(`Error in JSON editor: ${n}`),this.state.customError!==n&&this.setState({customError:n})}}):y.jsx("div",{children:G.t("Cannot get data for %s",t.path)})}renderCustomTab(t,e){var a;let i;if(!e||!Ad(e,(a=t.path)==null?void 0:a.split(".")))return null;t.color&&(i={backgroundColor:t.color,color:jt.invertColor(t.color,!0)});const n=t.label&&typeof t.label=="object"?t.label[this.state.lang]||t.label.en:t.noTranslation?t.label||t.key:this.props.t(t.label||t.key);return y.jsx(w.Tab,{disabled:this.state.error||this.state.customError,value:t.key,label:n,style:i,iconPosition:"start",icon:t.icon?y.jsx(Ca,{src:t.icon,style:O.funcIcon}):void 0})}renderStateTab(){return this.props.obj.type!=="state"||this.props.obj.common.type==="file"?null:y.jsx(w.Tab,{disabled:this.state.customError||this.state.error,value:"state",label:this.props.t("State")})}renderStatePanel(){var a;if(this.state.value===void 0||this.state.value===null)return y.jsx("div",{children:this.props.t("State does not exist")});if(typeof this.state.value!="object")return y.jsxs("div",{style:{maxWidth:700},children:[y.jsx("div",{children:this.props.t("State is invalid")}),y.jsx("div",{children:y.jsx("pre",{children:JSON.stringify(this.state.value,null,4)})})]});let t;const e={},i=this.state.value.val,n=typeof i;if(i===void 0)t="[undef]",e.color="#bc6400",e.fontStyle="italic";else if(i===null)t="(null)",e.color="#0047b1",e.fontStyle="italic";else if(typeof this.props.obj.common.role=="string"&&this.props.obj.common.role.match(/^value\.time|^date/))if(i&&n==="string")if(jt.isStringInteger(i))t=new Date(parseInt(i,10)).toString();else try{const o=new Date(i);jt.isValidDate(o)&&(t=o.toString())}catch{}else i&&n==="number"&&(i>946681200&&i<9466812e5?t=new Date(i*1e3).toString():i>9466812e8&&(t=new Date(i).toString()));return t||(n==="number"?Number.isInteger(i)||(t=(Math.round(i*1e9)/1e9).toString(),this.props.isFloatComma&&(t=t.toString().replace(".",","))):n==="boolean"?(t=i?G.t("true"):G.t("false"),e.color=i?"#139800":"#cd6b55"):n==="object"?t=JSON.stringify(i):n==="string"&&i.startsWith("data:image/")?t=y.jsx("img",{src:i,alt:"img",style:O.stateImage}):t=i.toString()),Object.assign(e,SO(this.props.theme,e.color)),y.jsxs(w.Box,{style:{...O.divWithoutTitle,padding:"24px 24px 0 24px",fontSize:16,maxWidth:400},sx:{"& .value-line:hover":{backgroundColor:"#00000030"}},children:[y.jsxs("div",{className:"value-line",style:{...O.stateRow,marginBottom:24},children:[y.jsxs("div",{style:O.stateTitle,children:[G.t("ra_tooltip_value"),":"]}),y.jsxs(w.Box,{component:"div",sx:e,style:O.stateValue,children:[t,(a=this.props.obj.common)!=null&&a.unit?y.jsx("span",{style:O.stateUnit,children:this.props.obj.common.unit}):null]},typeof t=="string"?t:"image")]}),y.jsxs("div",{style:O.stateRow,className:"value-line",children:[y.jsxs("div",{style:O.stateTitle,children:[G.t("Type"),":"]}),y.jsx("div",{style:O.stateValue,children:n})]}),y.jsxs("div",{style:O.stateRow,className:"value-line",children:[y.jsxs("div",{style:O.stateTitle,children:[G.t("ra_tooltip_ts"),":"]}),y.jsx(w.Tooltip,{title:new Date(this.state.value.ts).toLocaleString(),slotProps:{popper:{sx:O.tooltip}},children:y.jsx("div",{style:O.stateValue,children:y.jsx("span",{style:O.stateTime,children:Ul(this.state.value.ts).fromNow()})})})]}),y.jsxs("div",{style:O.stateRow,className:"value-line",children:[y.jsxs("div",{style:O.stateTitle,children:[G.t("ra_tooltip_ack"),":"]}),y.jsxs("div",{style:{...O.stateValue,color:this.state.value.ack?"green":"red"},children:[this.state.value.ack?G.t("Acknowledged"):G.t("Command"),this.state.value.ack?" (true)":" (false)"]})]}),y.jsxs("div",{style:O.stateRow,className:"value-line",children:[y.jsxs("div",{style:O.stateTitle,children:[G.t("ra_tooltip_lc"),":"]}),y.jsx(w.Tooltip,{title:new Date(this.state.value.lc).toLocaleString(),slotProps:{popper:{sx:O.tooltip}},children:y.jsx("div",{style:O.stateValue,children:y.jsx("span",{style:O.stateTime,children:Ul(this.state.value.lc).fromNow()})})})]}),y.jsxs("div",{style:O.stateRow,className:"value-line",children:[y.jsxs("div",{style:O.stateTitle,children:[G.t("ra_tooltip_quality"),":"]}),y.jsx("div",{style:O.stateValue,children:jt.quality2text(this.state.value.q||0).join(", ")})]}),y.jsxs("div",{style:O.stateRow,className:"value-line",children:[y.jsxs("div",{style:O.stateTitle,children:[G.t("ra_tooltip_from"),":"]}),y.jsx("div",{style:O.stateValue,children:this.state.value.from})]}),y.jsxs("div",{style:O.stateRow,className:"value-line",children:[y.jsxs("div",{style:O.stateTitle,children:[G.t("ra_tooltip_user"),":"]}),y.jsx("div",{style:O.stateValue,children:this.state.value.user||"--"})]}),this.state.value.expire?y.jsxs("div",{style:O.stateRow,className:"value-line",children:[y.jsxs("div",{style:O.stateTitle,children:[G.t("ra_tooltip_expire"),":"]}),y.jsxs("div",{style:O.stateValue,children:[this.state.value.expire," ",G.t("sc_seconds")]})]}):null,this.state.value.c?y.jsxs("div",{style:O.stateRow,className:"value-line",children:[y.jsxs("div",{style:O.stateTitle,children:[G.t("ra_tooltip_comment"),":"]}),y.jsx("div",{style:O.stateValue,children:this.state.value.c})]}):null]})}onStateChange=(t,e)=>{JSON.stringify(e)!==JSON.stringify(this.state.value)&&this.setState({value:e})};subscribeOnState(t){t?this.subscribed||(this.updateTimer||(this.updateTimer=setInterval(()=>{this.forceUpdate()},5e3)),this.subscribed=!0,this.props.socket.subscribeState(this.props.obj._id,this.onStateChange)):this.subscribed&&(this.updateTimer&&(clearInterval(this.updateTimer),this.updateTimer=null),this.subscribed=!1,this.props.socket.unsubscribeState(this.props.obj._id,this.onStateChange))}renderTabs(t){var e;return y.jsxs(w.Tabs,{style:O.tabsPadding,value:this.state.tab,onChange:(i,n)=>{var a,o,s;if((window._localStorage||window.localStorage).setItem(`${this.props.dialogName||"App"}.editTab`,n),n==="object"){try{const l=JSON.parse(this.state.text);let u=!1;((a=l.common)==null?void 0:a.min)!==void 0&&typeof l.common.min!="number"&&(l.common.min=parseFloat(l.common.min),u=!0),((o=l.common)==null?void 0:o.max)!==void 0&&typeof l.common.max!="number"&&(l.common.max=parseFloat(l.common.max),u=!0),((s=l.common)==null?void 0:s.step)!==void 0&&typeof l.common.step!="number"&&(l.common.step=parseFloat(l.common.step),u=!0),u&&this.setState({text:JSON.stringify(l,null,2)})}catch{}this.subscribeOnState(!1)}else n==="state"?this.subscribeOnState(!0):this.subscribeOnState(!1);this.setState({tab:n})},children:[y.jsx(w.Tab,{value:"common",disabled:this.state.customError||this.state.error,label:this.props.t("common")}),y.jsx(w.Tab,{value:"object",disabled:this.state.customError,label:this.props.t("Object data")}),this.renderStateTab(),this.props.obj._id.startsWith("alias.0")&&this.props.obj.type==="state"&&y.jsx(w.Tab,{disabled:this.state.customError||this.state.error,value:"alias",label:this.props.t("Alias")}),(e=this.state.customEditTabs)==null?void 0:e.map(i=>this.renderCustomTab(i,t))]})}renderSelectDialog(){var i,n,a,o;if(!this.state.selectId&&!this.state.selectRead&&!this.state.selectWrite)return null;let t="",e;try{e=JSON.parse(this.state.text);const s=e.common&&"type"in e.common&&"alias"in e.common?(i=e.common.alias)==null?void 0:i.read:"",l=e.common&&"type"in e.common&&"alias"in e.common?(n=e.common.alias)==null?void 0:n.write:"";this.state.selectId?t=((o=(a=e.common)==null?void 0:a.alias)==null?void 0:o.id)||"":this.state.selectRead?t=s??"":this.state.selectWrite&&(t=l??"")}catch{console.error(`Cannot parse ${this.state.text}`)}return y.jsx(ey,{imagePrefix:".",dateFormat:this.props.dateFormat,theme:this.props.theme,isFloatComma:this.props.isFloatComma,socket:this.props.socket,dialogName:"aliasesEdit",title:`${this.props.t("Select for")} ${this.props.obj._id}`,selected:t,onOk:s=>{const l=this.state.selectRead,u=this.state.selectWrite,h=this.state.selectId,c=Array.isArray(s)?s[0]:s;this.setState({selectId:!1,selectRead:!1,selectWrite:!1},()=>{l?this.setAliasItem(e,"id.read",c):u?this.setAliasItem(e,"id.write",c):h&&this.setAliasItem(e,"id",c)})},onClose:()=>this.setState({selectId:!1,selectRead:!1,selectWrite:!1})},"selectDialog")}setAliasItem(t,e,i,n){t.common=t.common||{};const a=t.common.alias||{};e==="id.read"?a.id&&typeof a.id=="object"?a.id.read=i:a.id={read:i,write:i}:e==="id.write"?a.id&&typeof a.id=="object"?a.id.write=i:a.id={read:i,write:i}:a[e]=i,t.common.alias=a,this.onChange(JSON.stringify(t,null,2),n)}setCommonItem(t,e,i){t.common[e]=i,this.onChange(JSON.stringify(t,null,2))}removeCommonItem(t,e){delete t.common[e],this.onChange(JSON.stringify(t,null,2))}static buttonAddKey(t,e){return y.jsx("div",{style:O.marginBlock,children:y.jsx(w.Button,{style:O.buttonAdd,variant:"contained",color:"secondary",startIcon:y.jsx(X.Add,{}),onClick:e,children:G.t(t)})})}buttonRemoveKey(t,e){const{t:i}=this.props;return y.jsx(w.Tooltip,{title:i("Remove attribute %s",i(t)),slotProps:{popper:{sx:O.tooltip}},children:y.jsx(w.Box,{component:"div",sx:O.close,onClick:e})})}static filterRoles(t,e){const i=[];return t.forEach(n=>(n.type==="mixed"||n.type)===e&&!i.includes(n.role)&&i.push(n.role)),yo.forEach(n=>(n.type==="mixed"||n.type)===e&&!i.includes(n.role)&&i.push(n.role)),i.sort(),i}renderCommonEdit(){try{const t=JSON.parse(this.state.text),e=["number","string","boolean","array","object","mixed"],i=!1,{t:n,obj:a}=this.props,o=a.type==="state",s=a.type==="channel"||a.type==="device"||o,l=Ht.filterRoles(this.props.roleArray,t.common.type);let u;if(t.common.icon&&(u=t.type==="instance"||t.type==="adapter"?`./adapter/${t.common.name}/${t.common.icon}`:t.common.icon,!u.startsWith(".")&&!u.startsWith("/")&&!u.startsWith("data:"))){const f=a._id.split(".");f[0]==="system"?u=`adapter/${f[2]}${u.startsWith("/")?"":"/"}${u}`:u=`adapter/${f[0]}${u.startsWith("/")?"":"/"}${u}`}const h=typeof t.common.desc=="object"&&t.common.desc?t.common.desc[G.getLanguage()]||t.common.desc.en||"":t.common.desc||"",c=jt.getObjectNameFromObj(t,G.getLanguage(),{},!1,!0);return y.jsxs(w.Box,{style:O.commonTabWrapper,onKeyDown:f=>{f.key==="Enter"&&(f.preventDefault(),f.stopPropagation(),this.onUpdate())},children:[y.jsxs(w.Box,{style:{...O.commonWrapper,width:this.props.width==="xs"?"100%":void 0,minWidth:this.props.width==="xs"?"100%":void 0,gap:this.props.width==="xs"?10:8,display:this.props.width==="xs"?"flex":void 0,flexDirection:this.props.width==="xs"?"column":void 0},children:[typeof t.common.name<"u"?y.jsx(w.TextField,{variant:"standard",disabled:i,label:n("Name"),style:{...O.textField,marginTop:8},fullWidth:!0,slotProps:{input:{endAdornment:c?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{tabIndex:-1,size:"small",onClick:()=>this.setCommonItem(t,"name",""),children:y.jsx(X.Close,{})})}):null}},value:c,onChange:f=>this.setCommonItem(t,"name",f.target.value)}):Ht.buttonAddKey("Name",()=>this.setCommonItem(t,"name","")),typeof t.common.desc<"u"?y.jsxs(w.Box,{component:"div",sx:O.flex,children:[y.jsx(w.TextField,{variant:"standard",disabled:i,label:n("Description"),style:{...O.textField,marginTop:8},fullWidth:!0,slotProps:{input:{endAdornment:h?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{tabIndex:-1,size:"small",onClick:()=>this.setCommonItem(t,"desc",""),children:y.jsx(X.Close,{})})}):null}},value:h,onChange:f=>this.setCommonItem(t,"desc",f.target.value)}),this.buttonRemoveKey("Description",()=>this.removeCommonItem(t,"desc"))]}):Ht.buttonAddKey("Description",()=>this.setCommonItem(t,"desc","")),o?typeof t.common.type<"u"?y.jsxs(w.Box,{component:"div",sx:O.flex,children:[y.jsxs(w.FormControl,{style:O.marginBlock,fullWidth:!0,children:[y.jsx(w.InputLabel,{style:{transform:"scale(0.75)"},children:n("State type")}),y.jsx(w.Select,{variant:"standard",disabled:i,value:t.common.type,onChange:f=>this.setCommonItem(t,"type",f.target.value),children:e.map(f=>y.jsxs(w.MenuItem,{value:f,children:[n(f),y.jsxs("span",{style:O.typeNameEng,children:["(",f,")"]})]},f))})]}),this.buttonRemoveKey("State type",()=>this.removeCommonItem(t,"type"))]}):Ht.buttonAddKey("State type",()=>this.setCommonItem(t,"type","string")):null,y.jsxs(w.Box,{component:"div",sx:{...O.flex,flexWrap:this.props.width==="xs"?"wrap":void 0},children:[o?typeof t.common.read<"u"?y.jsxs(w.Box,{component:"div",sx:O.flex,children:[y.jsx(w.FormControlLabel,{style:O.marginBlock,control:y.jsx(w.Checkbox,{disabled:i,checked:t.common.read,onChange:f=>this.setCommonItem(t,"read",f.target.checked)}),label:n("Readable")}),this.buttonRemoveKey("Readable",()=>this.removeCommonItem(t,"read"))]}):Ht.buttonAddKey("Readable",()=>this.setCommonItem(t,"read",!0)):null,o?typeof t.common.write<"u"?y.jsxs(w.Box,{component:"div",sx:O.flex,children:[y.jsx(w.FormControlLabel,{style:O.marginBlock,control:y.jsx(w.Checkbox,{disabled:i,checked:t.common.write,onChange:f=>this.setCommonItem(t,"write",f.target.checked)}),label:n("Writeable")}),this.buttonRemoveKey("Writeable",()=>this.removeCommonItem(t,"write"))]}):Ht.buttonAddKey("Writeable",()=>this.setCommonItem(t,"write",!0)):null]}),s?typeof t.common.role<"u"?y.jsxs(w.Box,{component:"div",sx:O.flex,children:[y.jsx(w.Autocomplete,{style:O.marginBlock,fullWidth:!0,disabled:i,value:t.common.role,onChange:(f,d)=>{const p=yo.find(v=>v.role===d);p&&(p.w!==void 0&&p.r!==void 0?(this.setCommonItem(t,"write",p.w),this.setCommonItem(t,"read",p.r)):p.w!==void 0?this.setCommonItem(t,"write",p.w):p.r!==void 0&&this.setCommonItem(t,"read",p.r)),d.startsWith("level")||d.startsWith("indicator")||d.startsWith("sensor")||d.startsWith("weather")?t.common.write&&this.setCommonItem(t,"write",!1):d.startsWith("value")||d.startsWith("indicator")||d.startsWith("sensor")||d.startsWith("weather")?t.common.write&&this.setCommonItem(t,"write",!1):d.startsWith("level")||d.startsWith("switch")?t.common.write&&this.setCommonItem(t,"write",!0):d.startsWith("button")&&t.common.read&&this.setCommonItem(t,"read",!1),this.setCommonItem(t,"role",d)},options:l,renderInput:f=>y.jsx(w.TextField,{variant:"standard",...f,label:n("Role")})}),this.buttonRemoveKey("Role",()=>this.removeCommonItem(t,"role"))]}):Ht.buttonAddKey("Role",()=>this.setCommonItem(t,"role","")):null,typeof t.common.color<"u"?y.jsxs(w.Box,{component:"div",sx:O.flex,children:[y.jsx(w.TextField,{variant:"standard",disabled:i,style:{...O.marginBlock,...O.color},label:n("Color"),type:"color",slotProps:{input:{endAdornment:t.common.color?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{tabIndex:-1,size:"small",onClick:()=>this.setCommonItem(t,"color",""),children:y.jsx(X.Close,{})})}):null}},value:t.common.color,onChange:f=>this.setCommonItem(t,"color",f.target.value)}),this.buttonRemoveKey("Color",()=>this.removeCommonItem(t,"color"))]}):Ht.buttonAddKey("Color",()=>this.setCommonItem(t,"color","")),y.jsxs(w.Box,{component:"div",sx:{...O.flex,flexWrap:this.props.width==="xs"?"wrap":void 0,gap:this.props.width==="xs"?"10px":void 0},children:[t.common.type==="number"?typeof t.common.min<"u"?y.jsxs(w.Box,{component:"div",sx:O.flex,children:[y.jsx(w.TextField,{variant:"standard",disabled:i,className:{...O.marginBlock,...O.color},label:n("Min"),value:t.common.min,onChange:f=>this.setCommonItem(t,"min",f.target.value)}),this.buttonRemoveKey("Min",()=>this.removeCommonItem(t,"min"))]}):y.jsx(w.Box,{component:"div",sx:O.flex,children:Ht.buttonAddKey("Min",()=>this.setCommonItem(t,"min",0))}):null,t.common.type==="number"?typeof t.common.max<"u"?y.jsxs(w.Box,{component:"div",sx:O.flex,children:[y.jsx(w.TextField,{variant:"standard",disabled:i,className:{...O.marginBlock,...O.color},label:n("Max"),value:t.common.max,onChange:f=>this.setCommonItem(t,"max",f.target.value)}),this.buttonRemoveKey("Max",()=>this.removeCommonItem(t,"max"))]}):y.jsx(w.Box,{component:"div",sx:O.flex,children:Ht.buttonAddKey("Max",()=>this.setCommonItem(t,"max",100))}):null,t.common.type==="number"?typeof t.common.step<"u"?y.jsxs(w.Box,{component:"div",sx:O.flex,children:[y.jsx(w.TextField,{variant:"standard",disabled:i,className:{...O.marginBlock,...O.color},label:n("Step"),value:t.common.step,onChange:f=>this.setCommonItem(t,"step",f.target.value)}),this.buttonRemoveKey("Step",()=>this.removeCommonItem(t,"step"))]}):y.jsx(w.Box,{component:"div",sx:O.flex,children:Ht.buttonAddKey("Step",()=>this.setCommonItem(t,"step",1))}):null]}),t.common.type==="number"?typeof t.common.unit<"u"?y.jsxs(w.Box,{component:"div",sx:O.flex,children:[y.jsx(w.TextField,{variant:"standard",disabled:i,className:{...O.marginBlock,...O.color},label:n("Unit"),slotProps:{input:{endAdornment:t.common.unit?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{tabIndex:-1,size:"small",onClick:()=>this.setCommonItem(t,"unit",""),children:y.jsx(X.Close,{})})}):null}},value:t.common.unit,onChange:f=>this.setCommonItem(t,"unit",f.target.value)}),this.buttonRemoveKey("Unit",()=>this.removeCommonItem(t,"unit"))]}):y.jsx("div",{style:O.flexDrop,children:Ht.buttonAddKey("Unit",()=>this.setCommonItem(t,"unit",""))}):null]}),typeof t.common.icon<"u"?y.jsxs(w.Box,{component:"div",sx:O.flex,style:{flexGrow:1,minWidth:158},children:[y.jsx(Kx,{disabled:i,maxSize:10*1024,icon:u,removeIconFunc:()=>this.setCommonItem(t,"icon",""),onChange:f=>this.setCommonItem(t,"icon",f)}),this.buttonRemoveKey("Icon",()=>this.removeCommonItem(t,"icon"))]}):y.jsx(w.Box,{component:"div",sx:O.flex,children:Ht.buttonAddKey("Icon",()=>this.setCommonItem(t,"icon",""))})]})}catch{return y.jsx("div",{children:this.props.t("Cannot parse JSON!")})}}renderAliasEdit(){var t,e,i,n,a,o,s,l,u,h,c,f,d,p,v,g,m,_,b,x,C,S,T,M,D,I,P,k,R,L,j,E,q,W,$,et,ut,ot,ft,gt;try{const B=JSON.parse(this.state.text),Rt=((e=(t=B.common)==null?void 0:t.alias)==null?void 0:e.read)!==void 0||((n=(i=B.common)==null?void 0:i.alias)==null?void 0:n.write)!==void 0;return y.jsxs(w.Grid2,{container:!0,direction:"column",style:O.marginTop,children:[y.jsx(w.Grid2,{children:y.jsx(w.FormControlLabel,{control:y.jsx(w.Checkbox,{checked:typeof((o=(a=B.common)==null?void 0:a.alias)==null?void 0:o.id)=="object",onChange:()=>{var Mt,Lt,xt,z,Y,K,Ot;typeof((Lt=(Mt=B.common)==null?void 0:Mt.alias)==null?void 0:Lt.id)=="object"?this.setAliasItem(B,"id",((Y=(z=(xt=B.common)==null?void 0:xt.alias)==null?void 0:z.id)==null?void 0:Y.read)||""):this.setAliasItem(B,"id.read",((Ot=(K=B.common)==null?void 0:K.alias)==null?void 0:Ot.id)||"")}}),label:this.props.t("Different IDs for read and write")})}),typeof((l=(s=B.common)==null?void 0:s.alias)==null?void 0:l.id)!="object"?y.jsxs(w.Grid2,{children:[y.jsx(w.TextField,{variant:"standard",label:this.props.t("Alias state"),value:((h=(u=B.common)==null?void 0:u.alias)==null?void 0:h.id)||"",style:O.aliasIdEdit,slotProps:{input:{endAdornment:(f=(c=B.common)==null?void 0:c.alias)!=null&&f.id?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{tabIndex:-1,size:"large",onClick:()=>this.setAliasItem(B,"id",""),children:y.jsx(X.Close,{})})}):null}},onChange:Mt=>this.setAliasItem(B,"id",Mt.target.value),margin:"normal"}),y.jsx(w.Fab,{style:O.button,size:"small",onClick:()=>this.setState({selectId:!0,selectRead:!1,selectWrite:!1}),children:"..."})]}):null,typeof((p=(d=B.common)==null?void 0:d.alias)==null?void 0:p.id)=="object"?y.jsxs(w.Grid2,{children:[y.jsx(w.TextField,{variant:"standard",label:this.props.t("Alias read state"),value:((m=(g=(v=B.common)==null?void 0:v.alias)==null?void 0:g.id)==null?void 0:m.read)||"",style:O.aliasIdEdit,slotProps:{input:{endAdornment:(x=(b=(_=B.common)==null?void 0:_.alias)==null?void 0:b.id)!=null&&x.read?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{size:"large",tabIndex:-1,onClick:()=>this.setAliasItem(B,"id.read",""),children:y.jsx(X.Close,{})})}):null}},onChange:Mt=>this.setAliasItem(B,"id.read",Mt.target.value),margin:"normal"}),y.jsx(w.Fab,{style:O.button,size:"small",onClick:()=>this.setState({selectId:!1,selectRead:!0,selectWrite:!1}),children:"..."})]}):null,typeof((S=(C=B.common)==null?void 0:C.alias)==null?void 0:S.id)=="object"?y.jsxs(w.Grid2,{children:[y.jsx(w.TextField,{variant:"standard",label:this.props.t("Alias write state"),value:((D=(M=(T=B.common)==null?void 0:T.alias)==null?void 0:M.id)==null?void 0:D.write)||"",style:O.aliasIdEdit,slotProps:{input:{endAdornment:(k=(P=(I=B.common)==null?void 0:I.alias)==null?void 0:P.id)!=null&&k.write?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{size:"large",tabIndex:-1,onClick:()=>this.setAliasItem(B,"id.write",""),children:y.jsx(X.Close,{})})}):null}},onChange:Mt=>this.setAliasItem(B,"id.write",Mt.target.value),margin:"normal"}),y.jsx(w.Fab,{style:O.button,size:"small",onClick:()=>this.setState({selectId:!1,selectRead:!1,selectWrite:!0}),children:"..."})]}):null,y.jsx(w.Grid2,{style:O.marginTop,children:y.jsx(w.FormControlLabel,{control:y.jsx(w.Checkbox,{checked:((L=(R=B.common)==null?void 0:R.alias)==null?void 0:L.read)!==void 0||((E=(j=B.common)==null?void 0:j.alias)==null?void 0:E.write)!==void 0,onChange:()=>{Rt?(delete B.common.alias.read,delete B.common.alias.write):(B.common=B.common||{},B.common.alias=B.common.alias||{},B.common.alias.read="val",B.common.alias.write="val"),this.onChange(JSON.stringify(B,null,2))}}),label:this.props.t("Use convert functions")})}),Rt?y.jsx(w.Grid2,{children:y.jsx(w.TextField,{variant:"standard",label:this.props.t("Read converter"),value:((W=(q=B.common)==null?void 0:q.alias)==null?void 0:W.read)||"val",style:O.funcEdit,error:!!this.state.readError,slotProps:{input:{endAdornment:(et=($=B.common)==null?void 0:$.alias)!=null&&et.read?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{size:"large",tabIndex:-1,onClick:()=>this.setAliasItem(B,"read",""),children:y.jsx(X.Close,{})})}):null,startAdornment:y.jsx(w.InputAdornment,{position:"start",children:y.jsx(Rs,{style:O.funcIcon})})}},onChange:Mt=>this.setAliasItem(B,"read",Mt.target.value),helperText:this.state.readError||`${this.props.t("JS function like")} "val / 5 + 21"`,margin:"normal"})}):null,Rt?y.jsx(w.Grid2,{children:y.jsx(w.TextField,{variant:"standard",label:this.props.t("Write converter"),error:!!this.state.writeError,value:((ot=(ut=B.common)==null?void 0:ut.alias)==null?void 0:ot.write)||"val",helperText:this.state.writeError||`${this.props.t("JS function like")} "(val - 21) * 5"`,style:O.funcEdit,slotProps:{input:{endAdornment:(gt=(ft=B.common)==null?void 0:ft.alias)!=null&>.write?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{size:"large",tabIndex:-1,onClick:()=>this.setAliasItem(B,"write",""),children:y.jsx(X.Close,{})})}):null,startAdornment:y.jsx(w.InputAdornment,{position:"start",children:y.jsx(Rs,{style:O.funcIcon})})}},onChange:Mt=>this.setAliasItem(B,"write",Mt.target.value),margin:"normal"})}):null]})}catch{return y.jsx("div",{children:this.props.t("Cannot parse JSON!")})}}onCopy(t){jt.copyToClipboard(this.state.text,t),window.alert(this.props.t("ra_Copied"))}onClone(t,e){const i=JSON.parse(JSON.stringify(this.props.objects[t]));delete i.from,delete i.ts,delete i.user,i._id=e,this.props.objects[i._id]=i,this.props.onNewObject(i)}renderCopyDialog(){return this.state.showCopyDialog?y.jsxs(w.Dialog,{open:!0,maxWidth:"md",fullWidth:!0,onClose:()=>this.setState({showCopyDialog:""}),children:[y.jsx(w.DialogTitle,{children:this.props.t("Enter new ID for this object")}),y.jsx(w.DialogContent,{children:y.jsx(w.TextField,{variant:"standard",autoFocus:!0,fullWidth:!0,label:this.props.t("New object ID"),value:this.state.newId,slotProps:{input:{endAdornment:this.state.newId?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{size:"small",tabIndex:-1,onClick:()=>this.setState({newId:""}),children:y.jsx(X.Close,{})})}):null}},onKeyDown:t=>{t.key==="Enter"&&!this.props.objects[this.state.newId]&&(this.setState({showCopyDialog:""}),this.onClone(this.state.showCopyDialog,this.state.newId))},onChange:t=>this.setState({newId:t.target.value})})}),y.jsxs(w.DialogActions,{children:[y.jsx(w.Button,{disabled:!!this.props.objects[this.state.newId],onClick:()=>{this.setState({showCopyDialog:""}),this.onClone(this.state.showCopyDialog,this.state.newId)},color:"primary",startIcon:y.jsx(X.FileCopy,{}),children:this.props.t("Clone")}),y.jsx(w.Button,{color:"grey",onClick:()=>this.setState({showCopyDialog:""}),startIcon:y.jsx(X.Close,{}),children:this.props.t("Cancel")})]})]}):null}renderPanelObject(t){return y.jsxs("div",{style:{...O.divWithoutTitle,...t?O.divWithoutTitleAndTab:void 0,...this.state.error?O.error:void 0},onKeyDown:e=>{e.ctrlKey&&e.key==="Enter"&&(e.preventDefault(),e.stopPropagation(),this.onUpdate())},children:[y.jsx(ty,{value:this.state.text,onChange:e=>this.onChange(e),name:"UNIQUE_ID_OF_DIV",themeType:this.props.themeType}),this.state.showCommonDeleteMessage?y.jsx("div",{style:O.commonDeleteTip,children:G.t("common_delete_tip")}):null]})}render(){const t=this.props.obj,e=t._id.startsWith("alias.0")&&t.type==="state";let i=O.dialog;window.innerWidth>1920&&(i={...i,maxWidth:"calc(100% - 150px)"});let n;try{n=JSON.parse(this.state.text)}catch{}return y.jsxs(w.Dialog,{sx:{"& .MuiPaper-root":i},open:!0,maxWidth:"xl",fullWidth:!0,fullScreen:!1,onClose:()=>this.props.onClose(),"aria-labelledby":"edit-value-dialog-title","aria-describedby":"edit-value-dialog-description",children:[y.jsxs(w.DialogTitle,{id:"edit-value-dialog-title",style:{width:"calc(100% - 32px)",overflow:"hidden",textOverflow:"ellipsis"},children:[this.props.t("Edit object:")," ",y.jsx(w.Box,{component:"span",style:O.id,sx:{fontSize:{xs:10}},children:this.props.obj._id})]}),this.renderTabs(n),this.renderCopyDialog(),y.jsxs(w.DialogContent,{sx:{p:this.props.width==="xs"&&this.state.tab==="object"?"6px":this.state.tab==="object"||this.state.tab==="common"||this.state.tab==="alias"?"0 24px":"0 6px",overflow:this.state.tab==="object"||this.state.tab==="common"||this.state.tab==="alias"?void 0:"hidden"},children:[this.state.tab==="object"?this.renderPanelObject(e):null,this.state.tab==="alias"&&this.props.obj._id.startsWith("alias.0")&&this.props.obj.type==="state"?this.renderAliasEdit():null,this.state.tab==="common"?this.renderCommonEdit():null,this.state.tab==="state"?this.renderStatePanel():null,this.renderCustomPanel(),this.renderSelectDialog()]}),y.jsxs(w.DialogActions,{sx:O.wrapperButton,children:[y.jsx(w.Button,{color:"grey",onClick:()=>this.setState({showCopyDialog:this.props.obj._id,newId:this.props.obj._id}),disabled:this.state.error||this.state.changed,title:this.props.t("Create a copy of this object"),children:y.jsx(X.FileCopy,{fontSize:this.props.width==="xs"?"large":void 0})}),y.jsx("div",{style:{flexGrow:1}}),this.state.tab==="object"&&y.jsx(w.Button,{color:"grey",onClick:a=>this.onCopy(a),disabled:this.state.error,title:this.props.width==="xs"?this.props.t("Copy into clipboard"):"",startIcon:this.props.width==="xs"?void 0:y.jsx(Md,{}),children:this.props.width==="xs"?y.jsx(Md,{fontSize:32}):this.props.t("Copy into clipboard")}),y.jsx(w.Button,{variant:"contained",disabled:this.state.error||!this.state.changed||this.state.customError,onClick:()=>this.onUpdate(),startIcon:this.props.width==="xs"?void 0:y.jsx(X.Check,{}),color:"primary",children:this.props.width==="xs"?y.jsx(X.Check,{fontSize:"large"}):this.props.t("Write")}),y.jsx(w.Button,{color:"grey",variant:"contained",onClick:()=>this.props.onClose(),startIcon:this.props.width==="xs"?void 0:y.jsx(X.Close,{}),children:this.props.width==="xs"?y.jsx(X.Close,{fontSize:"large"}):this.props.t("Cancel")})]})]})}}class md extends at.Component{object=null;constructor(t){super(t),this.state={role:null,initRole:null,roleInput:null}}componentDidMount(){this.props.socket.getObject(this.props.id).then(t=>{var i;this.object=t;const e=((i=t==null?void 0:t.common)==null?void 0:i.role)||null;this.setState({role:e,initRole:e,roleInput:e})}).catch(t=>console.error(t))}onUpdate(){this.object.common=this.object.common||{},this.object.common.role=this.state.roleInput,this.props.socket.setObject(this.object._id,this.object).then(()=>this.props.onClose(this.object))}static filterRoles(t,e){const i=[];return t.forEach(n=>(n.type==="mixed"||n.type)===e&&!i.includes(n.role)&&i.push(n.role)),yo.forEach(n=>(n.type==="mixed"||n.type)===e&&!i.includes(n.role)&&i.push(n.role)),i.sort(),i}render(){return y.jsxs(w.Dialog,{open:!0,maxWidth:"sm",fullWidth:!0,onClose:()=>this.props.onClose(),"aria-labelledby":"edit-role-dialog-title","aria-describedby":"edit-role-dialog-description",children:[y.jsx(w.DialogTitle,{id:"edit-role-dialog-title",children:this.object?this.props.t("Update role for %s",this.object._id):null}),y.jsx(w.DialogContent,{children:y.jsx(w.Autocomplete,{freeSolo:!0,options:md.filterRoles(this.props.roleArray,this.props.commonType),style:{width:"100%"},value:this.state.role,onChange:(t,e)=>this.setState({role:e,roleInput:e}),onInputChange:(t,e)=>this.setState({roleInput:e}),renderInput:t=>y.jsx(w.TextField,{variant:"standard",...t,label:this.props.t("Role")})})}),y.jsxs(w.DialogActions,{children:[y.jsx(w.Button,{disabled:this.state.initRole===this.state.roleInput,variant:"contained",onClick:()=>this.onUpdate(),color:"primary",startIcon:y.jsx(X.Check,{}),children:this.props.t("Apply")}),y.jsx(w.Button,{variant:"contained",onClick:()=>this.props.onClose(),color:"grey",startIcon:y.jsx(X.Close,{}),children:this.props.t("Cancel")})]})]},"objectBrowserEditRole")}}const CO=["array","boolean","file","json","mixed","number","object","string"],TO={boolean:!1,string:"",number:0},Be={state:{name:"State",value:"state"},channel:{name:"Channel",value:"channel"},device:{name:"Device",value:"device"},folder:{name:"Folder",value:"folder"}},AO=({onClose:r,onApply:t,selected:e,setObject:i,objects:n,expertMode:a,initialType:o,initialStateType:s})=>{var T;const l={state:G.t("New state"),channel:G.t("New channel"),device:G.t("New device"),folder:G.t("New folder")},u=[],h=(T=n[e])==null?void 0:T.type;n[e]?h==="channel"?(u.push(Be.state),o=o||"state"):h==="device"?(o=o||"channel",u.push(Be.state),u.push(Be.channel)):h==="state"?o=o||"":(u.push(Be.state),u.push(Be.channel),u.push(Be.device),e.startsWith("0_userdata.")||e.startsWith("alias.0.")||e==="0_userdata"||e==="alias.0"?(u.push(Be.folder),o=o||"folder"):o=o||"state"):(u.push(Be.folder),o=o||"folder",a&&(e.startsWith("mqtt.")||e.startsWith("javascript."))&&(u.push(Be.state),u.push(Be.channel),u.push(Be.device)));const c=(window._localStorage||window.localStorage).getItem("App.lastObjectType");c&&u.find(M=>M.value===c)&&(o=c);function f(M){return`${e}.${M.toString().replace(jt.FORBIDDEN_CHARS,"_").replace(/\s/g,"_").replace(/\./g,"_")}`}const[d,p]=at.useState(o),[v,g]=at.useState(l[o]),[m,_]=at.useState(s||(window._localStorage||window.localStorage).getItem("App.lastStateType")||"string"),[b,x]=at.useState(!n[f(l.state)]),C=()=>{const M={common:{name:v,desc:G.t("Manually created")},type:d};d==="state"?(M.common={...M.common,role:"state",type:m,read:!0,write:!0,def:TO[m]},M.native={}):d!=="folder"?M.common={...M.common,role:"",icon:""}:delete M.common.desc,i(`${e}.${v.split(" ").join("_")}`,M).then(()=>t())},S=G.getLanguage();return y.jsxs(w.Dialog,{open:!0,fullWidth:!0,maxWidth:"md",disableEscapeKeyDown:!1,onClose:r,children:[y.jsx(w.DialogTitle,{children:y.jsxs("div",{style:{margin:10,fontSize:20,display:"flex",alignItems:"center",gap:8},children:[y.jsx(X.AddBox,{}),G.t("Add new object:"),y.jsxs("span",{style:{fontStyle:"italic"},children:[e,".",v]})]})}),y.jsx(w.DialogContent,{children:y.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[y.jsx(w.TextField,{variant:"standard",label:G.t("Parent"),style:{margin:"5px 0"},disabled:!0,value:e}),y.jsxs(w.FormControl,{variant:"standard",style:{marginTop:10,marginBottom:16},children:[y.jsx(w.InputLabel,{children:G.t("Type")}),y.jsx(w.Select,{variant:"standard",value:d,onChange:M=>{(window._localStorage||window.localStorage).setItem("App.lastObjectType",M.target.value),v===l[d]&&(g(l[M.target.value]),x(!!n[f(l[M.target.value])])),p(M.target.value)},children:u.map(M=>y.jsxs(w.MenuItem,{value:M.value,children:[G.t(M.name),S!=="en"&&y.jsxs("span",{style:{fontSize:"smaller",opacity:.6,marginLeft:4},children:["(",M.value,")"]})]},M.value))})]}),d==="state"&&y.jsxs(w.FormControl,{style:{marginTop:10,marginBottom:16},children:[y.jsx(w.InputLabel,{style:{left:-14},children:G.t("State type")}),y.jsx(w.Select,{style:{marginTop:6},variant:"standard",value:m,onChange:M=>{(window._localStorage||window.localStorage).setItem("App.lastStateType",M.target.value),_(M.target.value)},children:CO.map(M=>y.jsxs(w.MenuItem,{value:M,children:[G.t(M),S!=="en"&&G.t(M)!==M&&y.jsxs("span",{style:{fontSize:"smaller",opacity:.6,marginLeft:4},children:["(",M,")"]})]},M))})]}),y.jsx(w.TextField,{variant:"standard",label:G.t("Name"),style:{margin:"5px 0"},autoFocus:!0,value:v,onKeyDown:M=>{M.key==="Enter"&&(M.preventDefault(),v&&C())},slotProps:{input:{endAdornment:v?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{tabIndex:-1,size:"small",onClick:()=>g(""),children:y.jsx(X.Close,{})})}):null}},onChange:M=>{x(!n[f(M.target.value)]),g(M.target.value)}})]})}),y.jsxs(w.DialogActions,{children:[y.jsx(w.Button,{id:"add-new-object-dialog-add",startIcon:y.jsx(X.Check,{}),disabled:!v||!d||!b||d==="state"&&!m,onClick:()=>C(),variant:"contained",color:"primary",children:G.t("add")}),y.jsx(w.Button,{id:"add-new-object-dialog-cancel",color:"grey",onClick:r,variant:"contained",startIcon:y.jsx(X.Close,{}),children:G.t("ra_Cancel")})]})]})},MO=[{Owner:[{name:"read",valueNum:1024,title:"read owner"},{name:"write",valueNum:512,title:"write owner"}]},{Group:[{name:"read",valueNum:64,title:"read group"},{name:"write",valueNum:32,title:"write group"}]},{Everyone:[{name:"read",valueNum:4,title:"read everyone"},{name:"write",valueNum:2,title:"write everyone"}]}];function Jm(r,t,e){return r|=t&e,r&=t|~e&65535,r}const Qm=({value:r,setValue:t,t:e,differentValues:i,applyToChildren:n,mask:a,setMask:o,disabled:s})=>{at.useEffect(()=>{if(n){let u=0;for(let h=0;h<i.length;h++)u|=r^i[h];o(u)}else o(0)},[i,n,o,r]);let l=r;return y.jsx("div",{style:{display:"flex",width:"fit-content",margin:20,border:"1px solid",borderLeft:0},children:MO.map(u=>{const h=Object.keys(u)[0];return y.jsxs("div",{style:{width:150,height:150,display:"flex",flexDirection:"column",alignItems:"center",borderLeft:"1px solid"},children:[y.jsx("div",{style:{height:50,display:"flex",alignItems:"center",fontSize:18,borderBottom:"1px solid silver",width:"100%",justifyContent:"center"},children:e(h)}),y.jsx("div",{style:{display:"flex",width:"100%"},children:u[h].map((c,f)=>{let d=!1;l-c.valueNum>=0&&(l-=c.valueNum,d=!0);const p=a&c.valueNum;return y.jsxs("div",{style:{display:"flex",flexDirection:"column",flex:1,alignItems:"center",borderRight:f===0?"1px solid":0},children:[y.jsx("div",{style:{height:50,borderBottom:"1px solid",width:"100%",justifyContent:"center",display:"flex",alignItems:"center",color:"silver"},children:e(c.name)}),y.jsx("div",{style:{height:50,display:"flex"},children:y.jsx(w.Checkbox,{disabled:s,checked:d,color:p?"primary":"secondary",indeterminate:!!p,style:p?{opacity:.5}:void 0,onChange:v=>{p&&(a&=~c.valueNum&65535,o(a));let g=r;v.target.checked?g|=c.valueNum:g&=~c.valueNum&65535,t(g)}})})]},c.valueNum)})})]},h)})})},DO=({onClose:r,onApply:t,selected:e,extendObject:i,objects:n,t:a,modalEmptyId:o,themeType:s,theme:l})=>{const[u,h]=at.useState(null),[c,f]=at.useState(null),[d,p]=at.useState([]),[v,g]=at.useState([]),[m,_]=at.useState(!1),[b,x]=at.useState(!1),[C,S]=at.useState(0),[T,M]=at.useState(null),[D,I]=at.useState(null),[P,k]=at.useState(!1),[R,L]=at.useState(!1),[j,E]=at.useState([]),[q,W]=at.useState([]),[$,et]=at.useState(0),[ut,ot]=at.useState(0),[ft,gt]=at.useState([]),[B,Rt]=at.useState(!1),[Mt,Lt]=at.useState(!0),xt=a("different");return at.useEffect(()=>{var bd,xd,wd,Sd;let z=0;const Y=[],K=[],Ot=e||o,St=`${Ot}.`,se=Object.keys(n).sort();let je=!1;const ei=[],Tr=[],ri=G.getLanguage();let qn=!1,Zn=!1,tn=null,en=null,ii=null,ni=null;const _d=[];for(let ai=0;ai<se.length;ai++){const Ar=se[ai],ht=n[Ar];if(ht&&(Ar===Ot||Ar.startsWith(St))){if(z++,_d.push(Ar),!ht.acl)continue;ii===null&&ht.acl.object!==void 0&&(ii=ht.acl.object),ni===null&&ht.acl.state!==void 0&&(ni=ht.acl.state),tn===null&&ht.acl.owner!==void 0&&(tn=ht.acl.owner),en===null&&ht.acl.ownerGroup!==void 0&&(en=ht.acl.ownerGroup),!P&&tn!==ht.acl.owner&&ht.acl.owner!==void 0&&(qn=!0),!R&&en!==ht.acl.ownerGroup&&ht.acl.ownerGroup!==void 0&&(Zn=!0),ht.acl.state!==void 0&&ni!==ht.acl.state&&!Y.includes(ht.acl.state)&&Y.push(ht.acl.state),ht.acl.object!==void 0&&ii!==ht.acl.object&&!K.includes(ht.acl.object)&&K.push(ht.acl.object),ht.type==="state"&&(je=!0)}Ar.startsWith("system.group.")&&(ht==null?void 0:ht.type)==="group"?ei.push({name:jt.getObjectNameFromObj(ht,ri).replace("system.group.",""),value:Ar,icon:(bd=ht.common)==null?void 0:bd.icon,color:(xd=ht.common)==null?void 0:xd.color}):Ar.startsWith("system.user.")&&(ht==null?void 0:ht.type)==="user"&&Tr.push({name:jt.getObjectNameFromObj(ht,ri).replace("system.user.",""),value:Ar,icon:(wd=ht.common)==null?void 0:wd.icon,color:(Sd=ht.common)==null?void 0:Sd.color})}tn=tn||n["system.config"].common.defaultNewAcl.owner,en=en||n["system.config"].common.defaultNewAcl.ownerGroup,ii=ii||n["system.config"].common.defaultNewAcl.object,M(Number.isNaN(ii)?n["system.config"].common.defaultNewAcl.object:ii),je&&(ni=ni||n["system.config"].common.defaultNewAcl.state,I(Number.isNaN(ni)?n["system.config"].common.defaultNewAcl.state:ni));const Gx=Tr.find(ai=>ai.value===tn),Ux=ei.find(ai=>ai.value===en);h(Gx),f(Ux),k(qn),L(Zn),p(Tr),g(ei),je&&x(!0),o&&_(!0),S(z),E(Y),W(K),gt(_d)},[n,e,R,P,o]),at.useEffect(()=>{m?(R&&(c.value!=="different"&&f({name:xt,value:"different"}),v.find(z=>z.value==="different")||g(z=>[{name:xt,value:"different"},...z])),P&&((!u||u.value!=="different")&&h({name:xt,value:"different"}),d.find(z=>z.value==="different")||p(z=>[{name:xt,value:"different"},...z]))):(u&&u.value==="different"&&h(n[e].acl.owner),c&&c.value==="different"&&f(n[e].acl.ownerGroup),g(z=>z.filter(({value:Y})=>Y!=="different")),p(z=>z.filter(({value:Y})=>Y!=="different")))},[d,m,P,R,n,e,c,u,xt,v]),ft.length?y.jsx(ow,{theme:l,titleButtonApply:"apply",overflowHidden:!0,disableApply:Mt,progress:B,onClose:r,onApply:()=>{Rt(!0),setTimeout(()=>{if(m){const z=~$&65535,Y=~ut&65535;for(let K=0;K<ft.length;K++){const Ot=ft[K],St=n[Ot],se=jt.clone(St.acl||{});se.object=Jm(St.acl.object,T,z),u&&u.value!=="different"&&(se.owner=u.value),c&&c.value!=="different"&&(se.ownerGroup=c.value),St.type==="state"&&(se.state=Jm(St.acl.state,D,Y)),i(Ot,{acl:se})}}else{const z=jt.clone(n[e].acl||{});z.object=T,z.owner=u?u.value:"system.user.admin",z.ownerGroup=c?c.value:"system.group.administrator",n[e].type==="state"&&(z.state=D),i(e,{acl:z})}Rt(!1),t()},200)},children:y.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[y.jsx("div",{style:{margin:10,fontSize:20},children:a("Access control list: %s",e||o)}),y.jsxs("div",{style:{display:"flex"},children:[y.jsxs(w.FormControl,{variant:"standard",fullWidth:!0,style:{marginRight:10},children:[y.jsx(w.InputLabel,{children:a("Owner user")}),y.jsx(w.Select,{variant:"standard",disabled:B,value:u?u.value:"",renderValue:()=>y.jsxs("span",{children:[u!=null&&u.icon?y.jsx(Ca,{src:u.icon,style:{width:16,height:16,marginRight:8}}):null,u?u.name:""]}),style:(u==null?void 0:u.value)==="different"?{opacity:.5}:{color:(u==null?void 0:u.color)||void 0,backgroundColor:jt.getInvertedColor(u==null?void 0:u.color,s)},onChange:z=>{const Y=d.find(K=>K.value===z.target.value);h(Y),Lt(!1)},children:d.map(z=>y.jsxs(w.MenuItem,{style:z.value==="different"?{opacity:.5}:{color:z.color||void 0,backgroundColor:jt.getInvertedColor(z.color,s)},value:z.value,children:[z.icon?y.jsx(Ca,{src:z.icon,style:{width:16,height:16,marginRight:8}}):null,z.name]},z.value))})]}),y.jsxs(w.FormControl,{variant:"standard",fullWidth:!0,children:[y.jsx(w.InputLabel,{children:a("Owner group")}),y.jsx(w.Select,{variant:"standard",disabled:B,value:c?c.value:"",renderValue:()=>y.jsxs("span",{children:[c!=null&&c.icon?y.jsx(Ca,{src:c.icon,style:{width:16,height:16,marginRight:8}}):null,c?c.name:""]}),style:(c==null?void 0:c.value)==="different"?{opacity:.5}:{color:(c==null?void 0:c.color)||void 0,backgroundColor:jt.getInvertedColor(c==null?void 0:c.color,s)},onChange:z=>{const Y=v.find(K=>K.value===z.target.value);f(Y),Lt(!1)},children:v.map(z=>y.jsxs(w.MenuItem,{value:z.value,style:z.value==="different"?{opacity:.5}:{color:z.color||void 0,backgroundColor:jt.getInvertedColor(z.color,s)},children:[z.icon?y.jsx(Ca,{src:z.icon,style:{width:16,height:16,marginRight:8}}):null,z.name]},z.value))})]})]}),y.jsxs("div",{style:{display:"flex",margin:10,alignItems:"center",fontSize:10,marginLeft:0,color:"silver"},children:[y.jsx("div",{style:m?null:{color:"green"},children:a("to apply one item")}),y.jsx(w.Switch,{disabled:B||!!o||C===1,checked:!!o||m,onChange:z=>{_(z.target.checked),Lt(!1)},color:"primary"}),y.jsxs("div",{style:m?{color:"green"}:null,children:[a("to apply with children")," ",o||C>1?`(${C} ${a("object(s)")})`:""]})]}),B&&y.jsx(w.LinearProgress,{}),y.jsxs("div",{style:{overflowY:"auto"},children:[y.jsxs("div",{children:[y.jsx("h2",{children:a("Object rights")}),y.jsx(Qm,{mask:ut,disabled:B,setMask:ot,applyToChildren:m,differentValues:q,t:a,setValue:z=>{M(z),Lt(!1)},value:T})]}),b&&y.jsxs("div",{children:[y.jsx("h2",{children:a("States rights")}),y.jsx(Qm,{mask:$,disabled:B,setMask:et,applyToChildren:m,differentValues:m?j:[],t:a,setValue:z=>{I(z),Lt(!1)},value:D})]})]})]})}):y.jsx(w.LinearProgress,{})},bn={dialog:{height:"100%",maxHeight:"100%",maxWidth:"100%"},content:{textAlign:"center"},error:r=>({color:r.palette.mode==="dark"?"#ff7777":"#c20000"}),image:{height:"100%",width:"auto"},text:{fontFamily:"Lucida Console, Courier, monospace",width:"100%"},download:{textDecoration:"none",textTransform:"uppercase",fontSize:14,color:"white",border:"1px solid white",borderRadius:5,padding:"8px 16px",marginRight:8}};class IO extends at.Component{audioRef;constructor(t){super(t);const e=this.props.obj._id.split(".");this.state={error:"",image:null,text:null,binary:null,fileName:`${e[e.length-2]}.${e[e.length-1]}`},this.audioRef=vh.createRef()}componentDidMount(){this.props.socket.getBinaryState(this.props.obj._id).then(t=>{let e=this.props.obj._id.toLowerCase().split(".").pop();const i=jt.detectMimeType(t);if(i&&(e=i),e==="jpg")this.setState({image:!0,binary:t,mime:"image/jpeg"});else if(e==="svg")this.setState({image:!0,binary:t,mime:"image/svg+xml"});else if(e==="png"||e==="bmp")this.setState({image:!0,binary:t,mime:`image/${e}`});else if(e==="mp3")this.setState({audio:!0,binary:t,mime:"audio/mpeg"});else if(e==="ogg")this.setState({audio:!0,binary:t,mime:"audio/ogg"});else if(e==="txt"||e==="log")try{const n=btoa(t);this.setState({text:n,binary:t,mime:"text/plain"})}catch{}}).catch(t=>this.setState({error:t}))}render(){return y.jsxs(w.Dialog,{style:bn.dialog,open:!0,maxWidth:this.state.audio?"sm":"md",onClose:()=>this.props.onClose(),fullWidth:!0,"aria-labelledby":"object-view-dialog-title",children:[y.jsx(w.DialogTitle,{id:"object-view-dialog-title",children:this.props.t("View file in state: %s",this.props.obj._id)}),y.jsxs(w.DialogContent,{style:bn.content,children:[this.state.error?y.jsx(w.Box,{component:"div",sx:bn.error,children:this.state.error==="State is not binary"?this.props.t("No file stored yet"):this.props.t(this.state.error)}):null,this.state.audio?y.jsx("audio",{ref:this.audioRef,src:`data:${this.state.mime};base64,${this.state.binary}`}):null,this.state.audio?y.jsx(w.Fab,{color:"primary",onClick:()=>this.audioRef.current&&this.audioRef.current.play(),children:y.jsx(X.PlayArrow,{})}):null,this.state.image?y.jsx("img",{src:`data:${this.state.mime};base64,${this.state.binary}`,alt:this.props.obj._id,style:bn.image}):null,this.state.text!==null?y.jsx("pre",{style:bn.text,children:this.state.text}):null]}),y.jsxs(w.DialogActions,{children:[y.jsxs("a",{style:bn.download,download:this.state.fileName,href:`data:${this.state.mime};base64,${this.state.binary}`,children:[y.jsx(X.GetApp,{style:{paddingRight:8,height:12}}),y.jsx("span",{children:this.props.t("Download")})]}),y.jsx(w.Button,{variant:"contained",onClick:()=>this.props.onClose(),startIcon:y.jsx(X.Close,{}),color:"grey",children:this.props.t("Close")})]})]})}}const PO=Wn()(IO),zt={funcIcon:{width:16,height:16},formControlLabel:{marginBottom:16},color:{width:70},typeNameEng:{marginLeft:8,opacity:.7,fontStyle:"italic",fontSize:"smaller"},usedInAlias:{},addNewAlias:r=>({backgroundColor:r.palette.primary.main})},kO=["array","boolean","file","json","mixed","number","object","string"];class Ya extends at.Component{aliasIDs;constructor(t){var n;super(t);const e=[],i=this.props.obj._id;this.aliasIDs=Object.keys(this.props.objects).filter(a=>a.startsWith("alias.0"));for(let a=0;a<this.aliasIDs.length;a++){const o=(n=this.props.objects[this.aliasIDs[a]].common)==null?void 0:n.alias;((o==null?void 0:o.id)===i||typeof(o==null?void 0:o.id)=="object"&&(o.id.read===i||o.id.write===i))&&e.push(this.aliasIDs[a])}this.state={usedInAliases:e,showAddNewAlias:!e.length,newAliasId:this.props.obj._id,newAliasName:Ya.getText(this.props.obj.common.name||this.props.obj._id)||"",newAliasRole:this.props.obj.common.role||"",newAliasRead:this.props.obj.common.read,newAliasWrite:this.props.obj.common.write,newAliasUnit:this.props.obj.common.unit,newAliasDesc:Ya.getText(this.props.obj.common.desc)||"",newAliasType:this.props.obj.common.type,newAliasMin:this.props.obj.common.min===void 0?"":this.props.obj.common.min.toString(),newAliasMax:this.props.obj.common.max===void 0?"":this.props.obj.common.max.toString(),newAliasUseFormula:!1,newAliasReadFormula:"val",newAliasWriteFormula:"val",newAliasColor:this.props.obj.common.color,newAliasIcon:this.props.obj.common.icon}}static getText(t){return t?typeof t=="object"?t[G.getLanguage()]||t.en||"":t.toString():""}static filterRoles(t,e){const i=[];return yo.forEach(n=>(n.type==="mixed"||n.type===e)&&!i.includes(n.role)&&i.push(n.role)),t.forEach(n=>(n.type==="mixed"||n.type)===e&&!i.includes(n.role)&&i.push(n.role)),i.sort(),i}renderAddNewAlias(){return this.state.showAddNewAlias?y.jsxs(w.Dialog,{open:!0,onClose:()=>this.setState({showAddNewAlias:!1}),children:[y.jsx(w.DialogTitle,{children:G.t("Create new alias: %s",`alias.0.${this.state.newAliasId}`)}),y.jsxs(w.DialogContent,{children:[y.jsx(w.TextField,{style:zt.formControlLabel,variant:"standard",value:this.state.newAliasId,slotProps:{input:{endAdornment:this.state.newAliasId?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{tabIndex:-1,size:"small",onClick:()=>this.setState({newAliasId:""}),children:y.jsx(X.Close,{})})}):null}},onChange:t=>this.setState({newAliasId:t.target.value}),label:G.t("Alias ID"),helperText:`alias.0.${this.state.newAliasId}`,fullWidth:!0}),y.jsx(w.TextField,{style:zt.formControlLabel,variant:"standard",value:this.state.newAliasName,slotProps:{input:{endAdornment:this.state.newAliasName?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{tabIndex:-1,size:"small",onClick:()=>this.setState({newAliasName:""}),children:y.jsx(X.Close,{})})}):null}},onChange:t=>this.setState({newAliasName:t.target.value}),label:G.t("Alias name"),fullWidth:!0}),y.jsx(w.TextField,{style:zt.formControlLabel,variant:"standard",value:this.state.newAliasDesc,slotProps:{input:{endAdornment:this.state.newAliasDesc?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{tabIndex:-1,size:"small",onClick:()=>this.setState({newAliasDesc:""}),children:y.jsx(X.Close,{})})}):null}},onChange:t=>this.setState({newAliasDesc:t.target.value}),label:G.t("Alias description"),fullWidth:!0}),y.jsxs(w.FormControl,{style:zt.formControlLabel,fullWidth:!0,children:[y.jsx(w.InputLabel,{children:G.t("State type")}),y.jsx(w.Select,{variant:"standard",value:this.state.newAliasType,onChange:t=>this.setState({newAliasType:t.target.value}),children:kO.map(t=>y.jsxs(w.MenuItem,{value:t,children:[G.t(t),y.jsxs("span",{style:zt.typeNameEng,children:["(",t,")"]})]},t))})]}),this.state.newAliasType==="number"?y.jsx(w.TextField,{style:zt.formControlLabel,variant:"standard",value:this.state.newAliasUnit||"",slotProps:{input:{endAdornment:this.state.newAliasUnit?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{tabIndex:-1,size:"small",onClick:()=>this.setState({newAliasUnit:""}),children:y.jsx(X.Close,{})})}):null}},onChange:t=>this.setState({newAliasUnit:t.target.value}),label:G.t("Alias units"),fullWidth:!0}):null,this.state.newAliasType==="number"?y.jsx(w.TextField,{variant:"standard",value:this.state.newAliasMin,type:"number",error:this.state.newAliasMin?isNaN(parseFloat(this.state.newAliasMin)):!1,onChange:t=>this.setState({newAliasMin:t.target.value}),label:G.t("Min"),style:{width:"calc(50% - 4px)",marginBottom:16,marginRight:8}}):null,this.state.newAliasType==="number"?y.jsx(w.TextField,{variant:"standard",value:this.state.newAliasMax,type:"number",error:this.state.newAliasMax?isNaN(parseFloat(this.state.newAliasMax)):!1,onChange:t=>this.setState({newAliasMax:t.target.value}),label:G.t("Max"),fullWidth:!0,style:{width:"calc(50% - 4px)",marginBottom:16}}):null,y.jsx(w.TextField,{variant:"standard",style:{...zt.formControlLabel,...zt.color},label:G.t("Color"),type:"color",value:this.state.newAliasColor,onChange:t=>this.setState({newAliasColor:t.target.value})}),y.jsx(w.Autocomplete,{style:{...zt.formControlLabel},fullWidth:!0,value:this.state.newAliasRole,onChange:(t,e)=>{const i=yo.find(n=>n.role===e);if(i){if(i.w!==void 0&&i.r!==void 0){this.setState({newAliasRole:e,newAliasRead:i.r,newAliasWrite:i.w});return}if(i.w!==void 0){this.setState({newAliasRole:e,newAliasWrite:i.w});return}if(i.r!==void 0){this.setState({newAliasRole:e,newAliasRead:i.r});return}}if(e.startsWith("value")||e.startsWith("indicator")||e.startsWith("sensor")||e.startsWith("weather")){if(this.state.newAliasWrite){this.setState({newAliasRole:e,newAliasWrite:!1});return}}else if(e.startsWith("level")||e.startsWith("switch")){if(!this.state.newAliasWrite){this.setState({newAliasRole:e,newAliasWrite:!0});return}}else if(e.startsWith("button")&&this.state.newAliasRead){this.setState({newAliasRole:e,newAliasRead:!1});return}this.setState({newAliasRole:e})},options:Ya.filterRoles(this.props.roleArray,this.state.newAliasType),renderInput:t=>y.jsx(w.TextField,{variant:"standard",...t,label:G.t("Role")})}),y.jsx(w.FormControlLabel,{style:{...zt.formControlLabel,marginLeft:16},control:y.jsx(w.Checkbox,{indeterminate:this.state.newAliasRead===void 0||this.state.newAliasRead===null,checked:this.state.newAliasRead,onChange:t=>{const e={newAliasRead:t.target.checked};e.newAliasRead===!1&&this.state.newAliasWrite===!1&&(e.newAliasWrite=!0),this.setState(e)}}),label:G.t("Alias read")}),y.jsx(w.FormControlLabel,{style:zt.formControlLabel,control:y.jsx(w.Checkbox,{indeterminate:this.state.newAliasWrite===void 0||this.state.newAliasWrite===null,checked:this.state.newAliasWrite,onChange:t=>{const e={newAliasWrite:t.target.checked};e.newAliasRead===!1&&this.state.newAliasWrite===!1&&(e.newAliasRead=!0),this.setState(e)}}),label:G.t("Alias write")}),y.jsx(w.FormControlLabel,{style:zt.formControlLabel,control:y.jsx(w.Checkbox,{checked:this.state.newAliasUseFormula,onChange:t=>this.setState({newAliasUseFormula:t.target.checked})}),label:G.t("Use convert functions")}),this.state.newAliasUseFormula&&this.state.newAliasRead?y.jsx(w.TextField,{style:zt.formControlLabel,variant:"standard",value:this.state.newAliasReadFormula,onChange:t=>this.setState({newAliasReadFormula:t.target.value}),label:G.t("Read formula"),helperText:`${G.t("JS function like")} "val / 5 + 21"`,slotProps:{input:{endAdornment:this.state.newAliasReadFormula&&this.state.newAliasReadFormula!=="val"?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{tabIndex:-1,size:"small",onClick:()=>this.setState({newAliasReadFormula:"val"}),children:y.jsx(X.Close,{})})}):null,startAdornment:y.jsx(w.InputAdornment,{position:"start",children:y.jsx(Rs,{style:zt.funcIcon})})}},fullWidth:!0}):null,this.state.newAliasUseFormula&&this.state.newAliasWrite?y.jsx(w.TextField,{style:zt.formControlLabel,variant:"standard",value:this.state.newAliasWriteFormula,onChange:t=>this.setState({newAliasWriteFormula:t.target.value}),label:G.t("Write formula"),slotProps:{input:{endAdornment:this.state.newAliasWriteFormula&&this.state.newAliasWriteFormula!=="val"?y.jsx(w.InputAdornment,{position:"end",children:y.jsx(w.IconButton,{tabIndex:-1,size:"small",onClick:()=>this.setState({newAliasWriteFormula:"val"}),children:y.jsx(X.Close,{})})}):null,startAdornment:y.jsx(w.InputAdornment,{position:"start",children:y.jsx(Rs,{style:zt.funcIcon})})}},helperText:`${G.t("JS function like")} "val / 5 + 21"`,fullWidth:!0}):null]}),y.jsxs(w.DialogActions,{children:[y.jsx(w.Button,{variant:"contained",disabled:!this.state.newAliasId||!!this.props.objects[`alias.0.${this.state.newAliasId}`],onClick:async()=>{const t={_id:`alias.0.${this.state.newAliasId}`,type:"state",common:{name:this.state.newAliasName,type:this.props.obj.common.type,alias:{id:this.props.obj._id}},native:{}};this.state.newAliasDesc&&(t.common.desc=this.state.newAliasDesc),this.state.newAliasType&&(t.common.type=this.state.newAliasType),this.state.newAliasType==="number"&&this.state.newAliasUnit&&(t.common.unit=this.state.newAliasUnit),this.state.newAliasRole&&(t.common.role=this.state.newAliasRole),this.state.newAliasType==="number"&&this.state.newAliasMin&&(t.common.min=parseFloat(this.state.newAliasMin)),this.state.newAliasType==="number"&&this.state.newAliasMax&&(t.common.max=parseFloat(this.state.newAliasMax)),this.state.newAliasRole&&(t.common.role=this.state.newAliasRole),this.state.newAliasRead!==void 0&&this.state.newAliasRead!==null&&(t.common.read=this.state.newAliasRead),this.state.newAliasWrite!==void 0&&this.state.newAliasWrite!==null&&(t.common.write=this.state.newAliasWrite),this.state.newAliasColor&&(t.common.color=this.state.newAliasColor),this.state.newAliasIcon&&(t.common.icon=this.state.newAliasIcon),this.state.newAliasUseFormula&&(t.common.read!==!1&&this.state.newAliasReadFormula&&this.state.newAliasReadFormula!=="val"&&(t.common.alias.read=this.state.newAliasReadFormula),t.common.write!==!1&&this.state.newAliasWriteFormula&&this.state.newAliasWriteFormula!=="val"&&(t.common.alias.write=this.state.newAliasWriteFormula)),await this.props.socket.setObject(t._id,t),this.setState({showAddNewAlias:!1}),this.props.onRedirect(t._id,2e3),this.props.onClose()},startIcon:y.jsx(X.AddLink,{}),color:"primary",children:this.props.t("Create")}),y.jsx(w.Button,{variant:"contained",onClick:()=>this.setState({showAddNewAlias:!1}),startIcon:y.jsx(X.Close,{}),color:"grey",children:this.props.t("Close")})]})]}):null}render(){return y.jsxs(w.Dialog,{open:!0,maxWidth:"sm",onClose:()=>this.props.onClose(),fullWidth:!0,"aria-labelledby":"object-alias-dialog-title",children:[this.renderAddNewAlias(),y.jsx(w.DialogTitle,{id:"object-alias-dialog-title",children:this.state.usedInAliases.length?G.t("This object is used in aliases"):G.t("This object does not used in any aliases yet")}),y.jsx(w.DialogContent,{children:y.jsxs(w.MenuList,{style:{maxWidth:400},children:[this.state.usedInAliases.map(t=>y.jsxs(w.MenuItem,{style:zt.usedInAlias,onClick:()=>this.props.onRedirect(t),children:[y.jsx(w.ListItemIcon,{children:y.jsx(X.Link,{fontSize:"small"})}),y.jsx(w.ListItemText,{children:t})]},t)),y.jsxs(w.MenuItem,{onClick:()=>this.setState({showAddNewAlias:!0}),sx:zt.addNewAlias,children:[y.jsx(w.ListItemIcon,{children:y.jsx(X.AddLink,{fontSize:"small"})}),y.jsx(w.ListItemText,{children:G.t("Create alias from this ID")})]})]})}),y.jsx(w.DialogActions,{children:y.jsx(w.Button,{variant:"contained",onClick:()=>this.props.onClose(),startIcon:y.jsx(X.Close,{}),color:"grey",children:this.props.t("Close")})})]},"editAlias")}}const RO=Wn()(Ya);class yd extends at.Component{checkTimer=null;objects={};constructor(t){super(t);const e=this.props.id.split("."),i=e.pop()||"";this.state={name:i,parentId:e.join("."),renameAllChildren:!0,newExists:!0,showParentDialog:!1,showHistoryWarning:!1,withHistory:[]}}componentWillUnmount(){this.checkTimer&&(clearTimeout(this.checkTimer),this.checkTimer=null)}static calculateNewId(t,e,i){const n=t.split("."),a=e.split(".");let o=0;for(;n[o]===a[o];)o++;const s=i.split(".");return s.splice(0,o+1),`${e}.${s.join(".")}`}async getInstancesWithHistory(){const t=await this.props.socket.getAdapterInstances();return t==null?void 0:t.filter(e=>e.common.getHistory).map(e=>e._id.replace("system.adapter.",""))}async checkHistory(){this.objects={};const t=await this.getInstancesWithHistory(),e=[];try{const i=await this.props.socket.getObject(this.props.id);i&&(this.objects[i._id]=i)}catch{}for(const i of this.props.childrenIds)try{const n=await this.props.socket.getObject(i);n&&(this.objects[n._id]=n)}catch{}return Object.values(this.objects).forEach(i=>{var n;(n=i.common)!=null&&n.custom&&Object.keys(i.common.custom).find(a=>t.includes(a)&&!i.common.custom[a].aliasId)&&e.push(i._id)}),e.length?(this.setState({showHistoryWarning:!0,withHistory:e}),!1):!0}showHistoryWarning(){return this.state.showHistoryWarning?y.jsxs(w.Dialog,{open:!0,onClose:()=>this.setState({showHistoryWarning:!1}),children:[y.jsx(w.DialogTitle,{children:this.props.t("Found states with history")}),y.jsxs(w.DialogContent,{children:[this.state.withHistory.length>2?this.props.t("You want to move %s states with enabled history",this.state.withHistory.length):`${this.props.t("Following states have history enabled")}: ${this.state.withHistory.join(", ")}`,y.jsx("div",{children:this.props.t("move_states_with_history_warning")})]}),y.jsxs(w.DialogActions,{children:[y.jsx(w.Button,{variant:"contained",color:"primary",onClick:async()=>{const t=`${this.state.parentId}.${this.state.name}`;await this.renameCopyObject(this.props.id,t,this.props.childrenIds.length&&this.state.renameAllChildren,!1),this.props.onClose()},startIcon:y.jsx(X.Check,{}),children:this.props.t("Confirm")}),y.jsx(w.Button,{color:"grey",variant:"contained",startIcon:y.jsx(X.Close,{}),onClick:()=>this.setState({showHistoryWarning:!1}),children:this.props.t("ra_Cancel")})]})]}):null}async renameCopyObject(t,e,i,n){var s;if(t===e)return;let a;try{a=((s=this.objects)==null?void 0:s[t])||await this.props.socket.getObject(t)}catch{}let o;if((a==null?void 0:a.type)==="state"&&(o=await this.props.socket.getState(t)),i)for(const l of this.props.childrenIds){const u=yd.calculateNewId(t,e,l);await this.renameCopyObject(l,u,!1,n)}a&&(await this.props.socket.setObject(e,a),o&&await this.props.socket.setState(e,o),n||await this.props.socket.delObject(t))}checkIfNewExists(){const t=`${this.state.parentId}.${this.state.name}`;this.checkTimer&&(clearTimeout(this.checkTimer),this.checkTimer=null),this.props.id===t?this.state.newExists||(this.checkTimer=setTimeout(()=>{this.checkTimer=null,this.setState({newExists:!0})},50)):this.checkTimer=setTimeout(async()=>{this.checkTimer=null;try{const e=await this.props.socket.getObject(t);e&&!this.state.newExists?this.setState({newExists:!0}):!e&&this.state.newExists&&this.setState({newExists:!1})}catch{this.state.newExists&&this.setState({newExists:!1})}},300)}renderParentSelectorDialog(){return this.state.showParentDialog?y.jsx(ey,{foldersFirst:!0,imagePrefix:"../..",expertMode:this.props.expertMode,socket:this.props.socket,columns:["name","type","role","room","func"],types:["folder","channel","device","meta"],notEditable:!0,selected:this.state.parentId,allowNonObjects:!0,filterFunc:t=>this.props.expertMode?!0:t._id.startsWith("0_userdata.0")||t._id.startsWith("javascript."),theme:this.props.theme,onSelectConfirm:(t,e)=>{let i;return Array.isArray(t)?i=t[0]:i=t,i.split(".").length<=1||e[i]&&(e[i].type==="state"||i.startsWith("system."))?Promise.resolve(!1):Promise.resolve(!0)},onClose:()=>this.setState({showParentDialog:!1}),onOk:t=>{let e;Array.isArray(t)?e=t[0]:e=t,e&&e.split(".").length>1&&this.setState({parentId:e})}}):null}render(){const t=`${this.state.parentId}.${this.state.name}`;return y.jsxs(w.Dialog,{open:!0,maxWidth:"md",fullWidth:!0,onClose:()=>this.props.onClose(),children:[this.renderParentSelectorDialog(),this.showHistoryWarning(),y.jsxs(w.DialogTitle,{children:[y.jsxs("span",{style:{opacity:.6,marginRight:8},children:[this.props.t("Rename or copy object")," -"]}),y.jsx("span",{style:{fontWeight:"bold"},children:this.props.id})]}),y.jsxs(w.DialogContent,{children:[y.jsxs("div",{style:{display:"flex",gap:8,alignItems:"end",opacity:.7},children:[y.jsx(w.TextField,{fullWidth:!0,variant:"standard",label:this.props.t("Parent ID"),value:`${this.state.parentId}.`,slotProps:{input:{readOnly:!0}}}),y.jsx(w.Button,{variant:"outlined",style:{maxWidth:40,width:40,height:32},onClick:()=>this.setState({showParentDialog:!0}),children:"..."})]}),y.jsx(w.TextField,{value:this.state.name,onChange:e=>{const i=e.target.value.replace(jt.FORBIDDEN_CHARS,"_").replace(/\./g,"_").replace(/\s/g,"_").replace(/,/g,"_").replace(/__/g,"_").replace(/__/g,"_");this.setState({name:i},()=>this.checkIfNewExists())},style:{marginTop:20},autoFocus:!0,variant:"standard",fullWidth:!0,label:this.props.t("New object ID")}),this.props.childrenIds.length?y.jsx(w.FormControlLabel,{control:y.jsx(w.Checkbox,{checked:this.state.renameAllChildren,onChange:()=>{this.setState({renameAllChildren:!this.state.renameAllChildren})}}),label:this.props.t("Rename all children")}):null,y.jsxs("div",{children:[y.jsxs("span",{style:{opacity:.6,marginRight:8,fontSize:16},children:[this.props.t("New object ID"),":"]}),y.jsx("span",{style:{fontWeight:"bold",fontSize:16},children:t})]})]}),y.jsxs(w.DialogActions,{children:[y.jsx(w.Button,{disabled:!this.state.name||t===this.props.id,color:"primary",variant:"outlined",onClick:async()=>{await this.renameCopyObject(this.props.id,t,this.props.childrenIds.length&&this.state.renameAllChildren,!0),this.props.onClose()},children:this.props.t("Create a copy")}),y.jsx(w.Button,{disabled:!this.state.name||t===this.props.id,color:"primary",variant:"contained",onClick:async()=>{await this.checkHistory()&&(await this.renameCopyObject(this.props.id,t,this.props.childrenIds.length&&this.state.renameAllChildren,!1),this.props.onClose())},children:t!==this.props.id&&this.state.newExists?this.props.t("Replace"):this.props.t("Rename")}),y.jsx(w.Button,{variant:"contained",color:"grey",onClick:()=>this.props.onClose(),startIcon:y.jsx(X.Close,{}),children:this.props.t("ra_Cancel")})]})]})}}const LO=X.Delete,vs={buttonAll:{color:"#FF0000"},id:{fontStyle:"italic"},buttonText:{whiteSpace:"nowrap"}};class OO extends at.Component{dialogName;filters;t;wordCache;constructor(t){super(t),this.dialogName="AdminObjects";const e=(window._localStorage||window.localStorage).getItem(`${this.dialogName||"App"}.filters`)||"{}";try{this.filters=JSON.parse(e)}catch{this.filters={}}const i=(window._localStorage||window.localStorage).getItem(`${this.dialogName||"App"}.selected`)||"";this.state={selected:i,name:"",toast:"",deleteObjectShow:null},this.t=this.translate,this.wordCache={}}translate=(t,e,i)=>e!==void 0?this.props.t(t,e,i):(this.wordCache[t]||(this.wordCache[t]=this.props.t(t)),this.wordCache[t]);onDelete(t){const e=this.state.deleteObjectShow.id;t?(this.props.socket.delObjects(e,!0).then(()=>this.setState({toast:this.t("All deleted")})).catch(i=>window.alert(`Cannot delete object: ${i}`)),this.setState({deleteObjectShow:null})):(this.props.socket.delObject(e,!1).catch(i=>window.alert(`Cannot delete object: ${i}`)),this.setState({deleteObjectShow:null}))}renderToast(){return y.jsx(w.Snackbar,{anchorOrigin:{vertical:"bottom",horizontal:"right"},open:!!this.state.toast,autoHideDuration:3e3,onClose:()=>this.setState({toast:""}),message:this.state.toast,action:y.jsx(w.IconButton,{size:"small","aria-label":"close",color:"inherit",onClick:()=>this.setState({toast:""}),children:y.jsx(X.Cancel,{fontSize:"small"})})},"toast")}renderDeleteDialog(){return this.state.deleteObjectShow?y.jsxs(w.Dialog,{maxWidth:"md",open:!0,onClose:()=>this.setState({deleteObjectShow:null}),"aria-labelledby":"delete-object-dialog-title","aria-describedby":"delete-object-dialog-description",children:[y.jsxs(w.DialogTitle,{id:"delete-object-dialog-title",children:[this.state.deleteObjectShow.hasChildren?this.t("Delete object(s)"):this.t("Delete object"),":"," ",y.jsx("span",{style:vs.id,children:this.state.deleteObjectShow.id})]}),y.jsx(w.DialogContent,{children:y.jsx(w.DialogContentText,{children:this.t("Are you sure?")})}),y.jsxs(w.DialogActions,{children:[this.state.deleteObjectShow.hasChildren?y.jsx(w.Button,{variant:"contained",color:"grey",sx:{"& .MuiButton-text":vs.buttonText},onClick:()=>this.onDelete(!0),startIcon:y.jsx(LO,{style:vs.buttonAll}),children:this.t("Delete with children",this.state.deleteObjectShow.childrenCount)}):null,this.state.deleteObjectShow.exists?y.jsx(w.Button,{variant:"contained",sx:{"& .MuiButton-text":vs.buttonText},onClick:()=>this.onDelete(!1),color:"primary",startIcon:y.jsx(X.Delete,{}),autoFocus:!0,children:this.t("Delete one item")}):null,y.jsx(w.Button,{variant:"contained",color:"grey",onClick:()=>this.setState({deleteObjectShow:null}),startIcon:y.jsx(X.Cancel,{}),children:this.t("ra_Cancel")})]})]},"delete"):null}render(){return[this.renderToast(),y.jsx(Jx,{dialogName:"admin",objectsWorker:this.props.objectsWorker,prefix:this.props.prefix,defaultFilters:this.filters,statesOnly:this.props.statesOnly,style:{width:"100%",height:"100%"},socket:this.props.socket,selected:this.state.selected,name:this.state.name,expertMode:this.props.expertMode,isFloatComma:this.props.isFloatComma,dateFormat:this.props.dateFormat,t:this.t,lang:this.props.lang,themeName:this.props.themeName,themeType:this.props.themeType,theme:this.props.theme,objectCustomDialog:wO,objectBrowserValue:Dn,objectBrowserEditObject:Ht,objectBrowserEditRole:md,objectBrowserViewFile:PO,objectBrowserAliasEditor:RO,objectMoveRenameDialog:yd,router:yh,enableStateValueEdit:!0,onObjectDelete:(t,e,i,n)=>this.setState({deleteObjectShow:{id:t,hasChildren:e,exists:i,childrenCount:n}}),onFilterChanged:t=>{this.filters=t,(window._localStorage||window.localStorage).setItem(`${this.dialogName||"App"}.filters`,JSON.stringify(t))},onSelect:t=>{Array.isArray(t)?(window._localStorage||window.localStorage).setItem(`${this.dialogName||"App"}.selected`,t[0]||""):(window._localStorage||window.localStorage).setItem(`${this.dialogName||"App"}.selected`,t||"")},objectEditBoolean:!0,objectAddBoolean:!0,objectStatesView:!0,objectImportExport:!0,objectEditOfAccessControl:!0,modalNewObject:t=>y.jsx(AO,{objects:t.objects,expertMode:this.props.expertMode,setObject:(e,i)=>this.props.socket.setObject(e,i).catch(n=>window.alert(n)),selected:t.state.modalNewObj.id,initialType:t.state.modalNewObj.initialType,initialStateType:t.state.modalNewObj.initialStateType,onClose:()=>t.setState({modalNewObj:null}),onApply:()=>t.setState({modalNewObj:null})}),modalEditOfAccessControl:(t,e)=>y.jsx(DO,{theme:this.props.theme,themeType:this.props.themeType,extendObject:(i,n)=>{this.props.socket.extendObject(i,n).catch(a=>window.alert(a)),e.aclTooltip=null},selected:t.state.selected[0],modalEmptyId:e.obj?"":e.id,objects:t.objects,t:this.t,onClose:()=>t.setState({modalEditOfAccess:!1,modalEditOfAccessObjData:null}),onApply:()=>t.setState({modalEditOfAccess:!1,modalEditOfAccessObjData:null})})},"browser"),this.renderDeleteDialog()]}}const eE=Wn()(OO);export{eE as default};
|