@mxtommy/kip 4.8.1 → 4.8.2

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.
Files changed (59) hide show
  1. package/CHANGELOG.md +12 -3
  2. package/package.json +1 -1
  3. package/public/{chunk-CNMFlw_H.js → chunk-7lulvsGI.js} +1 -1
  4. package/public/{chunk-CIlfzV9R.js → chunk-8hkXyEzG.js} +1 -1
  5. package/public/{chunk-DWLISAZi.js → chunk-B15lj2T8.js} +1 -1
  6. package/public/{chunk-BQr-tSkv.js → chunk-B6AwCAvV.js} +1 -1
  7. package/public/{chunk-CwSa_BNV.js → chunk-B6XxnPxk.js} +1 -1
  8. package/public/{chunk-DE4ylhpq.js → chunk-B8gfh4xf.js} +1 -1
  9. package/public/{chunk-C2VQxCXa.js → chunk-B8zRhoG8.js} +1 -1
  10. package/public/{chunk-Bp0MQwPM.js → chunk-BIYHVfJl.js} +1 -1
  11. package/public/{chunk-DzTTqoF_.js → chunk-BW4m3O2L.js} +1 -1
  12. package/public/{chunk-Ii9n-oiL.js → chunk-B_PiPxb4.js} +1 -1
  13. package/public/chunk-Bb1mO304.js +1 -0
  14. package/public/{chunk-MjWuPUhu.js → chunk-BdBWqZzL.js} +1 -1
  15. package/public/{chunk-hd2_AKwt.js → chunk-BgyxBAyq.js} +1 -1
  16. package/public/{chunk-JbEkcxJm.js → chunk-Bhah8DNM.js} +1 -1
  17. package/public/{chunk-DDqeRiB0.js → chunk-Bq-eHuZV.js} +1 -1
  18. package/public/{chunk-CpuB_ZZz.js → chunk-BxV0O2fU.js} +1 -1
  19. package/public/{chunk-PheXEqie.js → chunk-Bz9bswDl.js} +1 -1
  20. package/public/{chunk-BOAD0N2a.js → chunk-C3CwUYvD.js} +1 -1
  21. package/public/{chunk-CkXTl3su.js → chunk-C4FGoLDg.js} +1 -1
  22. package/public/{chunk-sNakMDHi.js → chunk-CCiqU2uY.js} +1 -1
  23. package/public/{chunk-00hwknVI.js → chunk-CHKQxw6E.js} +1 -1
  24. package/public/{chunk-B82ADJSs.js → chunk-CJIxuzvd.js} +1 -1
  25. package/public/{chunk-DumLX5k_.js → chunk-COMZv7NY.js} +1 -1
  26. package/public/{chunk-dgaOX1wC.js → chunk-CSpA60X7.js} +1 -1
  27. package/public/{chunk-C6UXF7BI.js → chunk-CU8RPnsi.js} +1 -1
  28. package/public/{chunk-CNNTuNlM.js → chunk-CcvYOops.js} +1 -1
  29. package/public/{chunk-CA6RRaxd.js → chunk-CdSWuWKr.js} +1 -1
  30. package/public/{chunk-DQnoPLyC.js → chunk-CjsnWLUr.js} +1 -1
  31. package/public/{chunk-BX6skw5k.js → chunk-CkfPr-c5.js} +1 -1
  32. package/public/{chunk-nu4vZg-z.js → chunk-CoEM_FqS.js} +1 -1
  33. package/public/{chunk-DNS-qsFC.js → chunk-Cr34s2uQ.js} +1 -1
  34. package/public/{chunk-BJz7Ij9E.js → chunk-Cu9FE8cB.js} +1 -1
  35. package/public/{chunk-B6bEhzNR.js → chunk-CyURmwWh.js} +1 -1
  36. package/public/{chunk-CrBxxZCe.js → chunk-D-xDPCf7.js} +1 -1
  37. package/public/{chunk-5U8d2Ygo.js → chunk-D0MyVrEL.js} +1 -1
  38. package/public/{chunk-DjZgzSiH.js → chunk-DBA0eRqb.js} +1 -1
  39. package/public/{chunk-BKj60jdq.js → chunk-DGOvRnAo.js} +1 -1
  40. package/public/{chunk-CXvG8mMq.js → chunk-DMhuBqKs.js} +1 -1
  41. package/public/{chunk-DchvLV_Y.js → chunk-DMoEBcor.js} +1 -1
  42. package/public/chunk-DSvdWjO4.js +1 -0
  43. package/public/{chunk-D4xZ2tGB.js → chunk-DVB9tiW3.js} +1 -1
  44. package/public/{chunk-Dxlia2NE.js → chunk-D_wrJJxl.js} +1 -1
  45. package/public/{chunk-BwOIef42.js → chunk-DfGLo6Tb.js} +1 -1
  46. package/public/{chunk-BdokyhBM.js → chunk-Di5pPpU7.js} +1 -1
  47. package/public/{chunk-BoNDCNGE.js → chunk-DjavLLpP.js} +1 -1
  48. package/public/{chunk-CL2xiH57.js → chunk-Dv77RFHm.js} +1 -1
  49. package/public/{chunk-AANk-NXH.js → chunk-NnB8OYZt.js} +3 -3
  50. package/public/{chunk-By8ZVvDx.js → chunk-h2q_pbbF.js} +1 -1
  51. package/public/{chunk-tAiV3ARh.js → chunk-o977r5_s.js} +1 -1
  52. package/public/{chunk-DXkKj21H.js → chunk-oPq9Nexl.js} +1 -1
  53. package/public/{chunk-VgxMqRPk.js → chunk-oZiyAw_P.js} +1 -1
  54. package/public/chunk-zg7II0hz.js +1 -0
  55. package/public/index.html +1 -1
  56. package/public/{main-BAV5VDOD.js → main-BNR44HGB.js} +20 -20
  57. package/public/chunk-Blokg6Ds.js +0 -1
  58. package/public/chunk-CpMCBDvH.js +0 -1
  59. package/public/chunk-y1imvaA-.js +0 -1
@@ -1,4 +1,4 @@
1
- import {w as w$1,n as G$1,N,i as ir,W as Wp,E as Em,D as Dt,J as JD,y as yt,b as wt,O as Op,o as eu,p as R,r as f,P as Pi,k as Qh,u as ul,T as TT,c as $h,e as EE,t as pT,B as Bh,x as DA,a as G$2,A as re,C as Ff,H as Dr,I as zA,L as Fp,S as ca,U as Kh,V as L,X as xw,Y as Aw,Z as TI,a0 as _,a1 as vA,a2 as Jt,a3 as Xt$1,a4 as Zt$1,a5 as st,_ as _w,M as Mw,a6 as Lr,a7 as Gj,a8 as H,a9 as ru,aa as N$1,ab as te,ac as Mr,ad as Qe,ae as be,af as Tu,ag as bu,ah as nn,ai as Ar,aj as zm,ak as nw,al as Zj,am as LT,an as Hh,s as sg,ao as ue,ap as Ki,aq as Bn,ar as S,as as ke$1,at as Tp,au as be$1,av as _t,aw as Cu,ax as ry,ay as lv,az as Yj,h as Fw,l as ud,g as qw,m as dd,aA as gg,d as ig,aB as gr,aC as L$1,aD as Ce$1,aE as Sr,v as vt,aF as Pr,aG as tD,aH as j,aI as ms,aJ as wm,aK as wr,aL as me,aM as At$1,aN as wt$1}from'./main-BAV5VDOD.js';function Pe(o){let t=o.cloneNode(true),e=t.querySelectorAll("[id]"),i=o.nodeName.toLowerCase();t.removeAttribute("id");for(let n=0;n<e.length;n++)e[n].removeAttribute("id");return i==="canvas"?Tt(o,t):(i==="input"||i==="select"||i==="textarea")&&It(o,t),Rt("canvas",o,t,Tt),Rt("input, textarea, select",o,t,It),t}function Rt(o,t,e,i){let n=t.querySelectorAll(o);if(n.length){let s=e.querySelectorAll(o);for(let r=0;r<n.length;r++)i(n[r],s[r]);}}var si=0;function It(o,t){t.type!=="file"&&(t.value=o.value),t.type==="radio"&&t.name&&(t.name=`mat-clone-${t.name}-${si++}`);}function Tt(o,t){let e=t.getContext("2d");if(e)try{e.drawImage(o,0,0);}catch(i){}}function Te(o){let t=o.getBoundingClientRect();return {top:t.top,right:t.right,bottom:t.bottom,left:t.left,width:t.width,height:t.height,x:t.x,y:t.y}}function ye(o,t,e){let{top:i,bottom:n,left:s,right:r}=o;return e>=i&&e<=n&&t>=s&&t<=r}function oi(o,t){let e=t.left<o.left,i=t.left+t.width>o.right,n=t.top<o.top,s=t.top+t.height>o.bottom;return e||i||n||s}function G(o,t,e){o.top+=t,o.bottom=o.top+o.height,o.left+=e,o.right=o.left+o.width;}function kt(o,t,e,i){let{top:n,right:s,bottom:r,left:a,width:l,height:d}=o,h=l*t,v=d*t;return i>n-v&&i<r+v&&e>a-h&&e<s+h}var X=class{_document;positions=new Map;constructor(t){this._document=t;}clear(){this.positions.clear();}cache(t){this.clear(),this.positions.set(this._document,{scrollPosition:this.getViewportScrollPosition()}),t.forEach(e=>{this.positions.set(e,{scrollPosition:{top:e.scrollTop,left:e.scrollLeft},clientRect:Te(e)});});}handleScroll(t){let e=me(t),i=this.positions.get(e);if(!i)return null;let n=i.scrollPosition,s,r;if(e===this._document){let d=this.getViewportScrollPosition();s=d.top,r=d.left;}else s=e.scrollTop,r=e.scrollLeft;let a=n.top-s,l=n.left-r;return this.positions.forEach((d,h)=>{d.clientRect&&e!==h&&e.contains(h)&&G(d.clientRect,a,l);}),n.top=s,n.left=r,{top:a,left:l}}getViewportScrollPosition(){return {top:window.scrollY,left:window.scrollX}}};function Wt(o,t){let e=o.rootNodes;if(e.length===1&&e[0].nodeType===t.ELEMENT_NODE)return e[0];let i=t.createElement("div");return e.forEach(n=>i.appendChild(n)),i}function ke(o,t,e){for(let i in t)if(t.hasOwnProperty(i)){let n=t[i];n?o.setProperty(i,n,e?.has(i)?"important":""):o.removeProperty(i);}return o}function A(o,t){let e=t?"":"none";ke(o.style,{"touch-action":t?"":"none","-webkit-user-drag":t?"":"none","-webkit-tap-highlight-color":t?"":"transparent","user-select":e,"-ms-user-select":e,"-webkit-user-select":e,"-moz-user-select":e});}function Ot(o,t,e){ke(o.style,{position:t?"":"fixed",top:t?"":"0",opacity:t?"":"0",left:t?"":"-999em"},e);}function J(o,t){return t&&t!="none"?o+" "+t:o}function Mt(o,t){o.style.width=`${t.width}px`,o.style.height=`${t.height}px`,o.style.transform=$(t.left,t.top);}function $(o,t){return `translate3d(${Math.round(o)}px, ${Math.round(t)}px, 0)`}var V={capture:true},we={passive:false,capture:true},ri=(()=>{class o{static \u0275fac=function(i){return new(i||o)};static \u0275cmp=JD({type:o,selectors:[["ng-component"]],hostAttrs:["cdk-drag-resets-container",""],decls:0,vars:0,template:function(i,n){},styles:[`@layer cdk-resets {
1
+ import {w as w$1,n as G$1,N,i as ir,W as Wp,E as Em,D as Dt,J as JD,y as yt,b as wt,O as Op,o as eu,p as R,r as f,P as Pi,k as Qh,u as ul,T as TT,c as $h,e as EE,t as pT,B as Bh,x as DA,a as G$2,A as re,C as Ff,H as Dr,I as zA,L as Fp,S as ca,U as Kh,V as L,X as xw,Y as Aw,Z as TI,a0 as _,a1 as vA,a2 as Jt,a3 as Xt$1,a4 as Zt$1,a5 as st,_ as _w,M as Mw,a6 as Lr,a7 as Gj,a8 as H,a9 as ru,aa as N$1,ab as te,ac as Mr,ad as Qe,ae as be,af as Tu,ag as bu,ah as nn,ai as Ar,aj as zm,ak as nw,al as Zj,am as LT,an as Hh,s as sg,ao as ue,ap as Ki,aq as Bn,ar as S,as as ke$1,at as Tp,au as be$1,av as _t,aw as Cu,ax as ry,ay as lv,az as Yj,h as Fw,l as ud,g as qw,m as dd,aA as gg,d as ig,aB as gr,aC as L$1,aD as Ce$1,aE as Sr,v as vt,aF as Pr,aG as tD,aH as j,aI as ms,aJ as wm,aK as wr,aL as me,aM as At$1,aN as wt$1}from'./main-BNR44HGB.js';function Pe(o){let t=o.cloneNode(true),e=t.querySelectorAll("[id]"),i=o.nodeName.toLowerCase();t.removeAttribute("id");for(let n=0;n<e.length;n++)e[n].removeAttribute("id");return i==="canvas"?Tt(o,t):(i==="input"||i==="select"||i==="textarea")&&It(o,t),Rt("canvas",o,t,Tt),Rt("input, textarea, select",o,t,It),t}function Rt(o,t,e,i){let n=t.querySelectorAll(o);if(n.length){let s=e.querySelectorAll(o);for(let r=0;r<n.length;r++)i(n[r],s[r]);}}var si=0;function It(o,t){t.type!=="file"&&(t.value=o.value),t.type==="radio"&&t.name&&(t.name=`mat-clone-${t.name}-${si++}`);}function Tt(o,t){let e=t.getContext("2d");if(e)try{e.drawImage(o,0,0);}catch(i){}}function Te(o){let t=o.getBoundingClientRect();return {top:t.top,right:t.right,bottom:t.bottom,left:t.left,width:t.width,height:t.height,x:t.x,y:t.y}}function ye(o,t,e){let{top:i,bottom:n,left:s,right:r}=o;return e>=i&&e<=n&&t>=s&&t<=r}function oi(o,t){let e=t.left<o.left,i=t.left+t.width>o.right,n=t.top<o.top,s=t.top+t.height>o.bottom;return e||i||n||s}function G(o,t,e){o.top+=t,o.bottom=o.top+o.height,o.left+=e,o.right=o.left+o.width;}function kt(o,t,e,i){let{top:n,right:s,bottom:r,left:a,width:l,height:d}=o,h=l*t,v=d*t;return i>n-v&&i<r+v&&e>a-h&&e<s+h}var X=class{_document;positions=new Map;constructor(t){this._document=t;}clear(){this.positions.clear();}cache(t){this.clear(),this.positions.set(this._document,{scrollPosition:this.getViewportScrollPosition()}),t.forEach(e=>{this.positions.set(e,{scrollPosition:{top:e.scrollTop,left:e.scrollLeft},clientRect:Te(e)});});}handleScroll(t){let e=me(t),i=this.positions.get(e);if(!i)return null;let n=i.scrollPosition,s,r;if(e===this._document){let d=this.getViewportScrollPosition();s=d.top,r=d.left;}else s=e.scrollTop,r=e.scrollLeft;let a=n.top-s,l=n.left-r;return this.positions.forEach((d,h)=>{d.clientRect&&e!==h&&e.contains(h)&&G(d.clientRect,a,l);}),n.top=s,n.left=r,{top:a,left:l}}getViewportScrollPosition(){return {top:window.scrollY,left:window.scrollX}}};function Wt(o,t){let e=o.rootNodes;if(e.length===1&&e[0].nodeType===t.ELEMENT_NODE)return e[0];let i=t.createElement("div");return e.forEach(n=>i.appendChild(n)),i}function ke(o,t,e){for(let i in t)if(t.hasOwnProperty(i)){let n=t[i];n?o.setProperty(i,n,e?.has(i)?"important":""):o.removeProperty(i);}return o}function A(o,t){let e=t?"":"none";ke(o.style,{"touch-action":t?"":"none","-webkit-user-drag":t?"":"none","-webkit-tap-highlight-color":t?"":"transparent","user-select":e,"-ms-user-select":e,"-webkit-user-select":e,"-moz-user-select":e});}function Ot(o,t,e){ke(o.style,{position:t?"":"fixed",top:t?"":"0",opacity:t?"":"0",left:t?"":"-999em"},e);}function J(o,t){return t&&t!="none"?o+" "+t:o}function Mt(o,t){o.style.width=`${t.width}px`,o.style.height=`${t.height}px`,o.style.transform=$(t.left,t.top);}function $(o,t){return `translate3d(${Math.round(o)}px, ${Math.round(t)}px, 0)`}var V={capture:true},we={passive:false,capture:true},ri=(()=>{class o{static \u0275fac=function(i){return new(i||o)};static \u0275cmp=JD({type:o,selectors:[["ng-component"]],hostAttrs:["cdk-drag-resets-container",""],decls:0,vars:0,template:function(i,n){},styles:[`@layer cdk-resets {
2
2
  .cdk-drag-preview {
3
3
  background: none;
4
4
  border: none;
@@ -1 +1 @@
1
- import {e as e$1}from'./chunk-B6bEhzNR.js';import {g as ge$1}from'./chunk-TakPRI3t.js';import {e9 as a,d1 as Hj,w,du as p,aS as De,bu as ut,ea as K,aY as xe,$ as $j,v as vt,D as Dt,dx as n$1,F as Fa,dn as ge,a_ as Gp,av as _t,cv as G,J as JD,y as yt,dC as x,_ as _w,cn as wd,c as $h,M as Mw,e as EE,s as sg,f as eg,K as Kw,g as qw,B as Bh,P as Pi,T as TT,u as ul}from'./main-BAV5VDOD.js';import {c,e}from'./chunk-Dxlia2NE.js';function H(i){return function(){return i}}var Mt=Math.abs,_=Math.atan2,z=Math.cos,qt=Math.max,rt=Math.min,$=Math.sin,W=Math.sqrt,S=1e-12,Z=Math.PI,tt=Z/2,Xt=2*Z;function jt(i){return i>1?0:i<-1?Z:Math.acos(i)}function Tt(i){return i>=1?tt:i<=-1?-tt:Math.asin(i)}var Ct=Math.PI,At=2*Ct,L=1e-6,ae=At-L;function Zt(i){this._+=i[0];for(let t=1,a=i.length;t<a;++t)this._+=arguments[t]+i[t];}function re(i){let t=Math.floor(i);if(!(t>=0))throw new Error(`invalid digits: ${i}`);if(t>15)return Zt;let a=10**t;return function(r){this._+=r[0];for(let e=1,n=r.length;e<n;++e)this._+=Math.round(arguments[e]*a)/a+r[e];}}var F=class{constructor(t){this._x0=this._y0=this._x1=this._y1=null,this._="",this._append=t==null?Zt:re(t);}moveTo(t,a){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+a}`;}closePath(){this._x1!==null&&(this._x1=this._x0,this._y1=this._y0,this._append`Z`);}lineTo(t,a){this._append`L${this._x1=+t},${this._y1=+a}`;}quadraticCurveTo(t,a,r,e){this._append`Q${+t},${+a},${this._x1=+r},${this._y1=+e}`;}bezierCurveTo(t,a,r,e,n,o){this._append`C${+t},${+a},${+r},${+e},${this._x1=+n},${this._y1=+o}`;}arcTo(t,a,r,e,n){if(t=+t,a=+a,r=+r,e=+e,n=+n,n<0)throw new Error(`negative radius: ${n}`);let o=this._x1,l=this._y1,m=r-t,d=e-a,s=o-t,g=l-a,c=s*s+g*g;if(this._x1===null)this._append`M${this._x1=t},${this._y1=a}`;else if(c>L)if(!(Math.abs(g*m-d*s)>L)||!n)this._append`L${this._x1=t},${this._y1=a}`;else {let y=r-o,v=e-l,k=m*m+d*d,R=y*y+v*v,x=Math.sqrt(k),h=Math.sqrt(c),M=n*Math.tan((Ct-Math.acos((k+c-R)/(2*x*h)))/2),T=M/h,f=M/x;Math.abs(T-1)>L&&this._append`L${t+T*s},${a+T*g}`,this._append`A${n},${n},0,0,${+(g*y>s*v)},${this._x1=t+f*m},${this._y1=a+f*d}`;}}arc(t,a,r,e,n,o){if(t=+t,a=+a,r=+r,o=!!o,r<0)throw new Error(`negative radius: ${r}`);let l=r*Math.cos(e),m=r*Math.sin(e),d=t+l,s=a+m,g=1^o,c=o?e-n:n-e;this._x1===null?this._append`M${d},${s}`:(Math.abs(this._x1-d)>L||Math.abs(this._y1-s)>L)&&this._append`L${d},${s}`,r&&(c<0&&(c=c%At+At),c>ae?this._append`A${r},${r},0,1,${g},${t-l},${a-m}A${r},${r},0,1,${g},${this._x1=d},${this._y1=s}`:c>L&&this._append`A${r},${r},0,${+(c>=Ct)},${g},${this._x1=t+r*Math.cos(n)},${this._y1=a+r*Math.sin(n)}`);}rect(t,a,r,e){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+a}h${r=+r}v${+e}h${-r}Z`;}toString(){return this._}};function Jt(i){let t=3;return i.digits=function(a){if(!arguments.length)return t;if(a==null)t=null;else {let r=Math.floor(a);if(!(r>=0))throw new RangeError(`invalid digits: ${a}`);t=r;}return i},()=>new F(t)}function ne(i){return i.innerRadius}function ie(i){return i.outerRadius}function se(i){return i.startAngle}function oe(i){return i.endAngle}function le(i){return i&&i.padAngle}function ce(i,t,a,r,e,n,o,l){var m=a-i,d=r-t,s=o-e,g=l-n,c=g*m-s*d;if(!(c*c<S))return c=(s*(t-n)-g*(i-e))/c,[i+c*m,t+c*d]}function nt(i,t,a,r,e,n,o){var l=i-a,m=t-r,d=(o?n:-n)/W(l*l+m*m),s=d*m,g=-d*l,c=i+s,y=t+g,v=a+s,k=r+g,R=(c+v)/2,x=(y+k)/2,h=v-c,M=k-y,T=h*h+M*M,f=e-n,u=c*k-v*y,N=(M<0?-1:1)*W(qt(0,f*f*T-u*u)),w=(u*M-h*N)/T,E=(-u*h-M*N)/T,B=(u*M+h*N)/T,C=(-u*h+M*N)/T,I=w-R,p=E-x,b=B-R,O=C-x;return I*I+p*p>b*b+O*O&&(w=B,E=C),{cx:w,cy:E,x01:-s,y01:-g,x11:w*(e/f-1),y11:E*(e/f-1)}}function Bt(){var i=ne,t=ie,a=H(0),r=null,e=se,n=oe,o=le,l=null,m=Jt(d);function d(){var s,g,c=+i.apply(this,arguments),y=+t.apply(this,arguments),v=e.apply(this,arguments)-tt,k=n.apply(this,arguments)-tt,R=Mt(k-v),x=k>v;if(l||(l=s=m()),y<c&&(g=y,y=c,c=g),!(y>S))l.moveTo(0,0);else if(R>Xt-S)l.moveTo(y*z(v),y*$(v)),l.arc(0,0,y,v,k,!x),c>S&&(l.moveTo(c*z(k),c*$(k)),l.arc(0,0,c,k,v,x));else {var h=v,M=k,T=v,f=k,u=R,N=R,w=o.apply(this,arguments)/2,E=w>S&&(r?+r.apply(this,arguments):W(c*c+y*y)),B=rt(Mt(y-c)/2,+a.apply(this,arguments)),C=B,I=B,p,b;if(E>S){var O=Tt(E/c*$(w)),U=Tt(E/y*$(w));(u-=O*2)>S?(O*=x?1:-1,T+=O,f-=O):(u=0,T=f=(v+k)/2),(N-=U*2)>S?(U*=x?1:-1,h+=U,M-=U):(N=0,h=M=(v+k)/2);}var A=y*z(h),P=y*$(h),K=c*z(f),V=c*$(f);if(B>S){var Y=y*z(M),q=y*$(M),it=c*z(T),st=c*$(T),G;if(R<Z)if(G=ce(A,P,it,st,Y,q,K,V)){var ot=A-G[0],lt=P-G[1],ct=Y-G[0],dt=q-G[1],_t=1/$(jt((ot*ct+lt*dt)/(W(ot*ot+lt*lt)*W(ct*ct+dt*dt)))/2),Rt=W(G[0]*G[0]+G[1]*G[1]);C=rt(B,(c-Rt)/(_t-1)),I=rt(B,(y-Rt)/(_t+1));}else C=I=0;}N>S?I>S?(p=nt(it,st,A,P,y,I,x),b=nt(Y,q,K,V,y,I,x),l.moveTo(p.cx+p.x01,p.cy+p.y01),I<B?l.arc(p.cx,p.cy,I,_(p.y01,p.x01),_(b.y01,b.x01),!x):(l.arc(p.cx,p.cy,I,_(p.y01,p.x01),_(p.y11,p.x11),!x),l.arc(0,0,y,_(p.cy+p.y11,p.cx+p.x11),_(b.cy+b.y11,b.cx+b.x11),!x),l.arc(b.cx,b.cy,I,_(b.y11,b.x11),_(b.y01,b.x01),!x))):(l.moveTo(A,P),l.arc(0,0,y,h,M,!x)):l.moveTo(A,P),!(c>S)||!(u>S)?l.lineTo(K,V):C>S?(p=nt(K,V,Y,q,c,-C,x),b=nt(A,P,it,st,c,-C,x),l.lineTo(p.cx+p.x01,p.cy+p.y01),C<B?l.arc(p.cx,p.cy,C,_(p.y01,p.x01),_(b.y01,b.x01),!x):(l.arc(p.cx,p.cy,C,_(p.y01,p.x01),_(p.y11,p.x11),!x),l.arc(0,0,c,_(p.cy+p.y11,p.cx+p.x11),_(b.cy+b.y11,b.cx+b.x11),x),l.arc(b.cx,b.cy,C,_(b.y11,b.x11),_(b.y01,b.x01),!x))):l.arc(0,0,c,f,T,x);}if(l.closePath(),s)return l=null,s+""||null}return d.centroid=function(){var s=(+i.apply(this,arguments)+ +t.apply(this,arguments))/2,g=(+e.apply(this,arguments)+ +n.apply(this,arguments))/2-Z/2;return [z(g)*s,$(g)*s]},d.innerRadius=function(s){return arguments.length?(i=typeof s=="function"?s:H(+s),d):i},d.outerRadius=function(s){return arguments.length?(t=typeof s=="function"?s:H(+s),d):t},d.cornerRadius=function(s){return arguments.length?(a=typeof s=="function"?s:H(+s),d):a},d.padRadius=function(s){return arguments.length?(r=s==null?null:typeof s=="function"?s:H(+s),d):r},d.startAngle=function(s){return arguments.length?(e=typeof s=="function"?s:H(+s),d):e},d.endAngle=function(s){return arguments.length?(n=typeof s=="function"?s:H(+s),d):n},d.padAngle=function(s){return arguments.length?(o=typeof s=="function"?s:H(+s),d):o},d.context=function(s){return arguments.length?(l=s??null,d):l},d}var ue=["bmsSvg"];function pe(i,t){if(i&1&&$h(0,"widget-title",1),i&2){let a=qw();Bh("text",a.displayLabel())("color",a.labelColor());}}function me(i,t){i&1&&(Pi(0,"div",3)(1,"div",4),TT(2,"No batteries detected"),ul(),Pi(3,"div",5),TT(4,"Check Signal K battery paths or select batteries in widget settings."),ul()());}var ee=class i{static BMS_DESCRIPTOR=a("widget-bms");static ROOT_PATTERN=`${i.BMS_DESCRIPTOR?.selfRootPath??"self.electrical.batteries"}.*`;id=Hj.required();type=Hj.required();theme=Hj.required();renderMode=Hj(null);static DEFAULT_CONFIG={color:"contrast",ignoreZones:false,bms:{trackedDevices:[],groups:[],banks:[]}};static VIEWBOX_WIDTH=200;static MIN_VIEWBOX_HEIGHT=1;static BANK_CARD_WIDTH=200;static BATTERY_CARD_HEIGHT=50;static BATTERY_CARD_WIDTH=200;static CARD_GAP=8;static BANK_HEADER_HEIGHT=80;static BANK_MIN_HEIGHT=75;static SINGLE_ROW_BANK_HEIGHT=100;static IN_BANK_COLUMNS=2;static IN_BANK_COLUMN_GAP=5;static IN_BANK_PADDING_X=0;static BANK_GAUGE_RADIUS=50;static BANK_GAUGE_BG_STROKE=10;static BANK_GAUGE_VALUE_STROKE=10;static COMPACT_UNASSIGNED_BATTERY_SCALE=.82;static PATH_BATCH_WINDOW_MS=500;runtime=w(p);data=w(De);units=w(ut);iconRegistry=w(K);destroyRef=w(xe);svgRef=$j.required("bmsSvg");svg;root;bankLayer;batteryLayer;bankGaugeBackgroundPath=this.buildSemiGaugeArcPath(i.BANK_GAUGE_RADIUS,1);glowFilterId="";renderFrameId=null;pendingRenderSnapshot=null;pathBatchTimerId=null;initialPathPaintDone=false;pendingPathUpdates=new Map;powerAvailableIconTemplate=null;powerRenewalIconTemplate=null;discoveredBatteryIds=vt([]);trackedBatteryDeviceIds=vt([]);banks=vt([]);cardMode=vt({displayMode:"full",metrics:[]});batteries=vt({});visibleBatteryIds=Dt(()=>{let t=this.trackedBatteryDeviceIds();return t.length?t:this.discoveredBatteryIds()});visibleBatteries=Dt(()=>{let t=this.visibleBatteryIds(),a=this.batteries();return t.map(r=>a[r]).filter(r=>!!r)});bankSummaries=Dt(()=>{let t=this.banks(),a=this.batteries();return t.map(r=>this.buildBankSummary(r,a))});activeDisplayMode=Dt(()=>this.renderMode()??this.cardMode().displayMode??"full");isCompactCardMode=Dt(()=>this.activeDisplayMode()==="compact");colorRole=Dt(()=>this.runtime.options()?.color??"contrast");ignoreZones=Dt(()=>this.runtime.options()?.ignoreZones??false);displayLabel=Dt(()=>{let t=this.bankSummaries();if(t.length===1)return t[0].name||"Bank";if(t.length>1)return "Batteries";let a=this.visibleBatteries();return a.length!==1?"Batteries":this.resolveBatteryTitleText(a[0])});labelColor=Dt(()=>{let t=this.theme();return t?c(this.colorRole(),t).dim:"var(--kip-contrast-dim-color)"});widgetColors=Dt(()=>{let t=this.theme();return t?c(this.colorRole(),t):null});batteryDisplayModels=Dt(()=>{let t=this.visibleBatteries(),a=this.theme(),r=this.widgetColors(),e$1=this.ignoreZones(),n={};for(let o of t){let l=e(o.stateOfChargeState,r?.dimmer??"var(--kip-contrast-dimmer-color)",a,e$1),m=e(o.stateOfChargeState,r?.dim??"var(--kip-contrast-dim-color)",a,e$1),d=e(o.currentState,"var(--kip-contrast-dim-color)",a,e$1),s=e(o.currentState,"var(--kip-contrast-color)",a,e$1);n[o.id]={id:o.id,titleText:this.resolveBatteryTitleText(o),chargeWidth:(i.BATTERY_CARD_WIDTH-3)*(o.stateOfCharge??0),chargeBarColorCompact:l,chargeBarColorRegular:m,currentTextColorCompact:d,currentTextColorRegular:s,currentText:`${this.formatCurrent(o.current)}`.trim(),detailLineCompact:`${this.formatVoltage(o.voltage)}\xA0\xA0\xA0\xA0${this.formatTemperature(o.temperature)}`,detailLineRegular:`${this.formatVoltage(o.voltage)}\xA0\xA0\xA0\xA0${this.formatPower(o.power)}\xA0\xA0\xA0\xA0${this.formatTemperature(o.temperature)}`.trim(),socText:this.formatSoc(o.stateOfCharge),socGlowEnabled:!e$1&&(o.stateOfChargeState===n$1.Warn||o.stateOfChargeState===n$1.Alarm||o.stateOfChargeState===n$1.Alert),remainingCapacityText:o.capacityActual?`${this.formatEnergy(o.capacityRemaining)}`:"",remainingTimeText:`${this.formatDuration(o.timeRemaining)}`.trim(),iconKey:o.current!=null&&o.current>0?"power_renewal":"power_available"};}return n});bankDisplayModels=Dt(()=>{let t=this.bankSummaries(),a=this.widgetColors(),r={};for(let e of t)r[e.id]={id:e.id,titleText:e.name||"Bank",currentText:this.formatCurrent(e.totalCurrent),powerText:this.formatPower(e.totalPower),socText:this.formatSoc(e.avgSoc),remainingTimeText:`${this.formatDuration(e.timeRemaining)}`.trim(),remainingCapacityText:e.remainingCapacity?`${this.formatEnergy(e.remainingCapacity)}`:"",gaugeValuePath:this.buildSemiGaugeArcPath(i.BANK_GAUGE_RADIUS,e.avgSoc),gaugeValueColor:a?.color??"var(--kip-contrast-color)",zoneState:null,zoneColor:null};return r});hasBatteries=Dt(()=>this.visibleBatteries().length>0);hasBanks=Dt(()=>this.bankSummaries().length>0);constructor(){Fa(()=>{let a=this.runtime.options();a&&ge(()=>this.applyConfig(a));}),Fa(()=>{let a=this.bankSummaries(),r=this.visibleBatteries(),e=this.widgetColors(),n=this.batteryDisplayModels(),o=this.bankDisplayModels();!this.svg||!e||this.requestRender({banks:a,batteries:r,batteryDisplayModels:n,bankDisplayModels:o,widgetColors:e});});let t=this.data.subscribePathTreeWithInitial(i.ROOT_PATTERN);if(t.initial.length){for(let a of t.initial)this.enqueuePathUpdate(a,true);this.flushPendingPathUpdates(),this.initialPathPaintDone=true;}t.live$.pipe(Gp(this.destroyRef)).subscribe(a=>{this.enqueuePathUpdate(a);});}ngAfterViewInit(){this.initializeSvg(),this.loadPowerIcons(),this.requestRender();}ngOnDestroy(){this.pathBatchTimerId!==null&&(clearTimeout(this.pathBatchTimerId),this.pathBatchTimerId=null),this.renderFrameId!==null&&(cancelAnimationFrame(this.renderFrameId),this.renderFrameId=null),this.pendingRenderSnapshot=null;}initializeSvg(){this.svg=ge$1(this.svgRef().nativeElement),this.svg.attr("viewBox",`0 0 ${i.VIEWBOX_WIDTH} ${i.MIN_VIEWBOX_HEIGHT}`).attr("preserveAspectRatio","xMidYMid meet").attr("role","img").attr("aria-label","Battery Management System View"),this.glowFilterId=`bms-soc-glow-${this.id()}`;let a=this.svg.append("defs").append("filter").attr("id",this.glowFilterId).attr("x","-30%").attr("y","-30%").attr("width","160%").attr("height","160%");a.append("feFlood").attr("class","bms-soc-glow-flood").attr("flood-color","var(--kip-widget-card-background-color)").attr("flood-opacity",.9).attr("result","color"),a.append("feComposite").attr("in","color").attr("in2","SourceGraphic").attr("operator","in").attr("result","coloredGlow"),a.append("feGaussianBlur").attr("in","coloredGlow").attr("stdDeviation",2).attr("result","blur");let r=a.append("feMerge");r.append("feMergeNode").attr("in","blur"),r.append("feMergeNode").attr("in","blur"),r.append("feMergeNode").attr("in","SourceGraphic"),this.root=this.svg.append("g").attr("class","bms-root"),this.bankLayer=this.root.append("g").attr("class","bms-banks"),this.batteryLayer=this.root.append("g").attr("class","bms-batteries");}loadPowerIcons(){this.loadNamedIcon("power_available",t=>{this.powerAvailableIconTemplate=t;}),this.loadNamedIcon("power_renewal",t=>{this.powerRenewalIconTemplate=t;});}loadNamedIcon(t,a){this.iconRegistry.getNamedSvgIcon(t).pipe(_t(1)).subscribe({next:r=>{a(r),this.requestRender();},error:()=>{}});}applyConfig(t){let a=this.resolveBmsConfig(t);this.trackedBatteryDeviceIds.set([...new Set((a.trackedDevices??[]).map(r=>r.id))]),this.banks.set(a.banks),this.cardMode.set(this.normalizeCardMode(a.cardMode));}resolveBmsConfig(t){let a=t.bms,r=this.normalizeTrackedDevices(a?.trackedDevices),e=this.normalizeBanksFromGroups(a?.groups),n=this.normalizeBanksFromLegacy(a?.banks);return {trackedDevices:r,groups:e,banks:e.length>0?e:n,cardMode:this.normalizeCardMode(a?.cardMode)}}normalizeTrackedDevices(t){if(!Array.isArray(t))return [];let a=new Map;return t.forEach(r=>{if(!r||typeof r!="object")return;let e=r,n=typeof e.id=="string"?e.id.trim():"",o=typeof e.source=="string"?e.source.trim():"default";if(!n||!o)return;let l=typeof e.key=="string"&&e.key.trim().length>0?e.key.trim():`${n}||${o}`;a.set(l,{id:n,source:o,key:l});}),[...a.values()].sort((r,e)=>r.key.localeCompare(e.key))}normalizeCardMode(t){let a=t&&typeof t=="object"?t:null,r=this.normalizeStringList(a?.metrics);return {displayMode:a?.displayMode==="compact"?"compact":"full",metrics:r}}normalizeStringList(t){if(!Array.isArray(t))return [];let a=new Set;return t.forEach(r=>{if(typeof r!="string")return;let e=r.trim();e.length>0&&a.add(e);}),[...a].sort((r,e)=>r.localeCompare(e))}normalizeBanksFromGroups(t){return Array.isArray(t)?t.map(a=>{let r=this.normalizeOptionalString(a?.id)??`bank-${Date.now()}`,e=this.normalizeOptionalString(a?.name)??r,n=this.normalizeStringList(a?.memberIds);return {id:r,name:e,batteryIds:n,connectionMode:this.normalizeConnectionMode(a?.connectionMode)}}).filter(a=>a.id.length>0):[]}normalizeBanksFromLegacy(t){return Array.isArray(t)?t.map(a=>{let r=this.normalizeOptionalString(a?.id)??`bank-${Date.now()}`,e=this.normalizeOptionalString(a?.name)??r,n=this.normalizeStringList(a?.batteryIds);return {id:r,name:e,batteryIds:n,connectionMode:this.normalizeConnectionMode(a?.connectionMode)}}).filter(a=>a.id.length>0):[]}normalizeOptionalString(t){if(typeof t!="string")return null;let a=t.trim();return a.length>0?a:null}normalizeConnectionMode(t){return t==="series"?"series":"parallel"}enqueuePathUpdate(t,a=false){let r=this.parseBatteryPath(t.path);if(!r)return;let{id:e,key:n}=r,o=t.update?.data?.value??null,l=t.update?.state??null,m=`${e}::${n}`;if(this.pendingPathUpdates.set(m,{id:e,key:n,value:o,state:l}),!a){if(!this.initialPathPaintDone){this.initialPathPaintDone=true,this.flushPendingPathUpdates();return}this.pathBatchTimerId===null&&(this.pathBatchTimerId=window.setTimeout(()=>{this.pathBatchTimerId=null,this.flushPendingPathUpdates();},i.PATH_BATCH_WINDOW_MS));}}flushPendingPathUpdates(){if(!this.pendingPathUpdates.size)return;let t=Array.from(this.pendingPathUpdates.values());this.pendingPathUpdates.clear(),new Set(t.map(r=>r.id)).forEach(r=>this.trackDiscoveredBattery(r)),this.batteries.update(r=>{let e=r,n=false;for(let o of t){let l=e[o.id]??{id:o.id},m=G({},l),d=this.applyBatteryValue(m,o.key,o.value,o.state),s=false;if(m.voltage!=null&&m.current!=null){let g=Number.isFinite(m.voltage)&&Number.isFinite(m.current)?m.voltage*m.current:null;Object.is(m.power,g)||(m.power=g,s=true);}!d&&!s||(n||(e=G({},e),n=true),e[o.id]=m);}return n?e:r});}parseBatteryPath(t){let a=t.match(/self\.electrical\.batteries\.([^.]+)\.(.+)$/);return a?{id:a[1],key:a[2]}:null}trackDiscoveredBattery(t){let a=this.discoveredBatteryIds();if(a.includes(t))return;let r=[...a,t].sort();this.discoveredBatteryIds.set(r);}applyBatteryValue(t,a,r,e){switch(a){case "name":{let n=r;return t.name===n?false:(t.name=n,true)}case "location":{let n=r;return t.location===n?false:(t.location=n,true)}case "associatedBus":{let n=r;return t.associatedBus===n?false:(t.associatedBus=n,true)}case "chemistry":{let n=r;return t.chemistry===n?false:(t.chemistry=n,true)}case "voltage":{let n=this.toNumber(r);return Object.is(t.voltage,n)?false:(t.voltage=n,true)}case "current":{let n=this.toNumber(r),o=!Object.is(t.currentState??null,e??null);return Object.is(t.current,n)&&!o?false:(t.current=n,t.currentState=e,true)}case "temperature":{let n=this.toNumber(r);return Object.is(t.temperature,n)?false:(t.temperature=n,true)}case "capacity.nominal":{let n=this.toNumber(r);return Object.is(t.capacityNominal,n)?false:(t.capacityNominal=n,true)}case "capacity.actual":{let n=this.toNumber(r);return Object.is(t.capacityActual,n)?false:(t.capacityActual=n,true)}case "capacity.remaining":{let n=this.toNumber(r);return Object.is(t.capacityRemaining,n)?false:(t.capacityRemaining=n,true)}case "capacity.stateOfCharge":{let n=this.toNumber(r),o=!Object.is(t.stateOfChargeState??null,e??null);return Object.is(t.stateOfCharge,n)&&!o?false:(t.stateOfCharge=n,t.stateOfChargeState=e,true)}case "capacity.timeRemaining":{let n=this.toNumber(r);return Object.is(t.timeRemaining,n)?false:(t.timeRemaining=n,true)}default:return false}}buildBankSummary(t,a){let r=t.batteryIds.map(s=>a[s]).filter(s=>!!s),e=this.normalizeConnectionMode(t.connectionMode),n=this.calculateBankCurrent(r,e),o=this.sumNumbers(r.map(s=>s.power)),l=this.sumNumbers(r.map(s=>s.capacityRemaining)),m=this.calculateBankSoc(r),d=this.calculateBankTimeRemaining(r,e);return {id:t.id,name:t.name,batteryIds:t.batteryIds,totalCurrent:n,totalPower:o,remainingCapacity:l,avgSoc:m,timeRemaining:d}}calculateBankSoc(t){let a=this.sumNumbers(t.map(n=>n.capacityRemaining)),r=this.sumNumbers(t.map(n=>n.capacityActual));if(a!=null&&r!=null&&r>0)return Math.max(0,Math.min(1,a/r));let e=this.sumNumbers(t.map(n=>n.capacityNominal));return a!=null&&e!=null&&e>0?Math.max(0,Math.min(1,a/e)):this.averageNumbers(t.map(n=>n.stateOfCharge))}calculateBankCurrent(t,a){let r=t.map(e=>e.current);return a==="series"?this.averageNumbers(r):this.sumNumbers(r)}calculateBankTimeRemaining(t,a){let r=t.map(e=>e.timeRemaining);return a==="series"?this.minNumber(r):this.averageNumbers(r)}requestRender(t){this.svg&&(this.pendingRenderSnapshot=t??this.buildRenderSnapshot(),this.pendingRenderSnapshot&&this.renderFrameId===null&&(this.renderFrameId=requestAnimationFrame(()=>{this.renderFrameId=null;let a=this.pendingRenderSnapshot;this.pendingRenderSnapshot=null,a&&this.render(a);})));}buildRenderSnapshot(){let t=this.widgetColors();return t?{banks:this.bankSummaries(),batteries:this.visibleBatteries(),batteryDisplayModels:this.batteryDisplayModels(),bankDisplayModels:this.bankDisplayModels(),widgetColors:t}:null}render(t){if(!this.bankLayer||!this.batteryLayer)return;let{banks:a,batteries:r,bankDisplayModels:e,batteryDisplayModels:n,widgetColors:o}=t,l=this.buildRenderLayout(a,r,e,n,this.isCompactCardMode()),d=this.isCompactCardMode()?e$1:e$1,s=Math.max(i.MIN_VIEWBOX_HEIGHT,l.contentHeight);this.svg?.attr("viewBox",`0 0 ${i.VIEWBOX_WIDTH} ${s}`),this.root?.attr("transform",null);let g=this.bankLayer.selectAll("g.bank-card").data(l.banks,u=>u.id),c=g.enter().append("g").attr("class","bank-card"),y=c.append("text").attr("class","bank-card-power");y.append("tspan").attr("class","bank-card-power-value"),y.append("tspan").attr("class","bank-card-power-unit");let v=c.append("text").attr("class","bank-card-current");v.append("tspan").attr("class","bank-card-current-value"),v.append("tspan").attr("class","bank-card-current-unit");let k=c.append("g").attr("class","bank-gauge");k.append("path").attr("class","bank-gauge-bg"),k.append("path").attr("class","bank-gauge-value");let R=k.append("text").attr("class","bank-gauge-soc");R.append("tspan").attr("class","bank-gauge-soc-value"),R.append("tspan").attr("class","bank-gauge-soc-unit");let x=c.append("text").attr("class","bank-actualCapacity");x.append("tspan").attr("class","bank-actualCapacity-value"),x.append("tspan").attr("class","bank-actualCapacity-unit"),c.append("text").attr("class","bank-remaining"),c.append("g").attr("class","bank-bms-batteries"),c.append("text").attr("class","bank-title");let h=c.merge(g);h.attr("transform",u=>`translate(${u.x},${u.y})`),l.banks.length>1?h.select("text.bank-title").attr("x",d.titleX).attr("y",d.titleY).attr("fill","var(--kip-contrast-dim-color)").attr("font-size",d.titleFontSize).text(u=>u.displayModel.titleText):h.select("text.bank-title").text(""),h.select("text.bank-card-current").attr("x",d.lineOneX).attr("y",d.lineOneY).attr("fill","var(--kip-contrast-color)").attr("font-size",d.lineOneFontSize),h.select("tspan.bank-card-current-value").text(u=>this.splitMetricText(u.displayModel.currentText,"A").valueText),h.select("tspan.bank-card-current-unit").attr("dx",1).attr("font-size",12).attr("fill","var(--kip-contrast-color)").text(u=>this.splitMetricText(u.displayModel.currentText,"A").unitText),h.select("text.bank-card-power").attr("x",5).attr("y",42).attr("fill","var(--kip-contrast-color)").attr("font-size",10).attr("opacity",.8),h.select("tspan.bank-card-power-value").text(u=>this.splitMetricText(u.displayModel.powerText,"W").valueText),h.select("tspan.bank-card-power-unit").attr("dx",1).attr("font-size",6).attr("fill","var(--kip-contrast-color)").text(u=>this.splitMetricText(u.displayModel.powerText,"W").unitText),h.select("g.bank-gauge").attr("transform","translate(143, 60)"),h.select("path.bank-gauge-bg").attr("d",this.bankGaugeBackgroundPath).attr("fill","none").attr("stroke","var(--kip-contrast-dimmer-color)").attr("stroke-width",i.BANK_GAUGE_BG_STROKE).attr("stroke-linecap","round"),h.select("path.bank-gauge-value").attr("d",u=>u.displayModel.gaugeValuePath).attr("fill","none").attr("stroke",u=>u.displayModel.gaugeValueColor).attr("stroke-width",i.BANK_GAUGE_VALUE_STROKE).attr("stroke-linecap","round"),h.select("text.bank-gauge-soc").attr("x",0).attr("y",-5).attr("text-anchor","middle").attr("fill","var(--kip-contrast-color)").attr("font-size",d.primaryFontSize).attr("font-weight",d.primaryFontWeight),h.select("tspan.bank-gauge-soc-value").text(u=>this.splitMetricText(u.displayModel.socText,"%").valueText),h.select("tspan.bank-gauge-soc-unit").attr("dx",1).attr("font-size",22).attr("font-weight",500).attr("fill","var(--kip-contrast-color)").text(u=>this.splitMetricText(u.displayModel.socText,"%").unitText),h.select("text.bank-remaining").attr("x",143).attr("y",26).attr("fill","var(--kip-contrast-dim-color)").attr("text-anchor","middle").attr("font-size",8).text(u=>u.displayModel.remainingTimeText),h.select("text.bank-actualCapacity").attr("x",143).attr("y",66).attr("fill","var(--kip-contrast-dim-color)").attr("text-anchor","middle").attr("font-size",8),h.select("tspan.bank-actualCapacity-value").text(u=>this.splitMetricText(u.displayModel.remainingCapacityText,"kWh").valueText),h.select("tspan.bank-actualCapacity-unit").attr("dx",1).attr("font-size",6).attr("fill","var(--kip-contrast-dim-color)").text(u=>this.splitMetricText(u.displayModel.remainingCapacityText,"kWh").unitText),h.select("g.bank-bms-batteries").each((u,N,w)=>{let B=ge$1(w[N]).selectAll("g.battery-card").data(u.batteries,p=>p.key),C=B.enter().append("g").attr("class","battery-card battery-card--in-bank");this.appendBatteryCardSkeleton(C);let I=C.merge(B);this.renderBatteryCards(I,o,t.batteries.length>1),B.exit().remove();}),g.exit().remove();let M=this.batteryLayer.selectAll("g.battery-card").data(l.unassignedBatteries,u=>u.key),T=M.enter().append("g").attr("class","battery-card battery-card--unassigned");this.appendBatteryCardSkeleton(T);let f=T.merge(M);this.renderBatteryCards(f,o,true),M.exit().remove(),this.root?.attr("data-theme","ready");}buildRenderLayout(t,a,r,e,n){let o=new Map(a.map(f=>[f.id,f])),l=new Set,m=this.computeInBankBatterySlotWidth(),d=Math.max(.35,Math.min(1,m/i.BATTERY_CARD_WIDTH)),s=i.BATTERY_CARD_HEIGHT*d,g=0,c=t.map(f=>{let u=new Set,N=f.batteryIds.map(A=>o.get(A)).filter(A=>!A||u.has(A.id)?false:(u.add(A.id),true));N.forEach(A=>l.add(A.id));let w=Math.ceil(N.length/i.IN_BANK_COLUMNS),E=i.SINGLE_ROW_BANK_HEIGHT,B=!n&&w===1,C=B?Math.max(0,E-s-i.CARD_GAP):i.BANK_HEADER_HEIGHT,I=w>0?w*s+(w-1)*i.CARD_GAP:0,p=Math.max(i.BANK_MIN_HEIGHT,C+I+i.CARD_GAP),b=B?E:p,O=N.map((A,P)=>{let K=P%i.IN_BANK_COLUMNS,V=Math.floor(P/i.IN_BANK_COLUMNS),Y=i.IN_BANK_PADDING_X+K*(m+i.IN_BANK_COLUMN_GAP),q=C+7+V*(s+i.CARD_GAP);return {id:A.id,displayModel:e[A.id],key:`${f.id}::${A.id}`,x:Y,y:q,scale:d,inBank:true,compact:true}}),U={id:f.id,name:f.name,batteryIds:f.batteryIds,totalCurrent:f.totalCurrent,totalPower:f.totalPower,avgSoc:f.avgSoc,remainingCapacity:f.remainingCapacity,timeRemaining:f.timeRemaining,displayModel:r[f.id],x:0,y:g,width:i.BANK_CARD_WIDTH,height:b,batteries:O};return g+=b+i.CARD_GAP,U}),y=c.length>0?g:0,v=n?i.COMPACT_UNASSIGNED_BATTERY_SCALE:1,k=i.BATTERY_CARD_HEIGHT*v,R=a.filter(f=>!l.has(f.id)).sort((f,u)=>f.id.localeCompare(u.id)).map((f,u)=>({id:f.id,displayModel:e[f.id],key:f.id,x:0,y:y+u*(k+i.CARD_GAP),scale:v,inBank:false,compact:n})),x=c[c.length-1],h=x?x.y+x.height:0,M=R[R.length-1],T=M?M.y+k:0;return {banks:c,unassignedBatteries:R,contentHeight:Math.max(h,T)}}computeInBankBatterySlotWidth(){return (i.BANK_CARD_WIDTH-i.IN_BANK_PADDING_X*2-i.IN_BANK_COLUMN_GAP)/i.IN_BANK_COLUMNS}appendBatteryCardSkeleton(t){t.append("rect").attr("class","bms-battery").attr("rx",4).attr("ry",4),t.append("rect").attr("class","bms-battery-tip").attr("rx",1).attr("ry",1),t.append("rect").attr("class","bms-charge-fill").attr("rx",3).attr("ry",3),t.append("g").attr("class","bms-state-icon"),t.append("text").attr("class","bms-ampere"),t.append("text").attr("class","bms-volt-power");let a=t.append("text").attr("class","bms-soc");a.append("tspan").attr("class","bms-soc-value"),a.append("tspan").attr("class","bms-soc-unit"),t.append("text").attr("class","bms-actualCapacity"),t.append("text").attr("class","bms-remaining"),t.append("text").attr("class","bms-title");}renderBatteryCards(t,a,r){t.attr("transform",e=>`translate(${e.x},${e.y}) scale(${e.scale})`),t.select("rect.bms-battery").attr("width",e=>e.inBank?i.BATTERY_CARD_WIDTH:e.compact?i.BATTERY_CARD_WIDTH-i.CARD_GAP:i.BATTERY_CARD_WIDTH).attr("height",i.BATTERY_CARD_HEIGHT).attr("fill",e=>e.compact?"var(--mat-sys-background)":"var(--kip-contrast-dimmer-color)").attr("stroke","var(--kip-contrast-dimmer-color)").attr("stroke-width",0),t.select("rect.bms-battery-tip").attr("x",i.BATTERY_CARD_WIDTH).attr("y",i.BATTERY_CARD_HEIGHT/2-10).attr("width",4).attr("height",20).attr("fill",e=>e.compact?"var(--mat-sys-background)":"var(--kip-contrast-dimmer-color)").attr("stroke",a.color).attr("stroke-width",0),t.select("rect.bms-charge-fill").attr("x",1.5).attr("y",1.5).attr("width",e=>e.displayModel.chargeWidth).attr("height",i.BATTERY_CARD_HEIGHT-3).attr("fill",e=>e.compact?e.displayModel.chargeBarColorCompact:e.displayModel.chargeBarColorRegular),r?t.select("text.bms-title").attr("x",5).attr("y",e=>e.compact?11:14).attr("fill","var(--kip-contrast-dim-color)").attr("font-size",e=>e.compact?8:12).attr("filter",e=>e.displayModel.socGlowEnabled?`url(#${this.glowFilterId})`:null).text(e=>e.displayModel.titleText):t.select("text.bms-title").text(""),t.select("text.bms-ampere").attr("x",10).attr("y",33).attr("fill",e=>e.compact?e.displayModel.currentTextColorCompact:e.displayModel.currentTextColorRegular).attr("font-size",16).attr("filter",e=>e.displayModel.socGlowEnabled?`url(#${this.glowFilterId})`:null).text(e=>e.displayModel.currentText),t.select("text.bms-volt-power").attr("x",10).attr("y",45).attr("fill","var(--kip-contrast-dim-color)").attr("font-size",8).attr("opacity",.8).attr("filter",e=>e.displayModel.socGlowEnabled?`url(#${this.glowFilterId})`:null).text(e=>e.compact?e.displayModel.detailLineCompact:e.displayModel.detailLineRegular),t.select("text.bms-soc").attr("x",i.BATTERY_CARD_WIDTH-33).attr("y",34).attr("fill",e=>e.compact?"var(--kip-contrast-dim-color)":"var(--kip-contrast-color)").attr("text-anchor","middle").attr("font-size",25).attr("font-weight",700).attr("filter",e=>e.displayModel.socGlowEnabled?`url(#${this.glowFilterId})`:null),t.select("tspan.bms-soc-value").text(e=>this.splitMetricText(e.displayModel.socText,"%").valueText),t.select("tspan.bms-soc-unit").attr("dx",1).attr("font-size",16).attr("font-weight",500).text(e=>this.splitMetricText(e.displayModel.socText,"%").unitText),t.select("text.bms-actualCapacity").attr("x",i.BATTERY_CARD_WIDTH-33).attr("y",45).attr("fill","var(--kip-contrast-dim-color)").attr("text-anchor","middle").attr("font-size",8).attr("filter",e=>e.displayModel.socGlowEnabled?`url(#${this.glowFilterId})`:null).text(e=>e.compact?"":e.displayModel.remainingCapacityText),t.select("text.bms-remaining").attr("x",i.BATTERY_CARD_WIDTH-33).attr("y",12).attr("fill","var(--kip-contrast-dim-color)").attr("text-anchor","middle").attr("font-size",6).attr("filter",e=>e.displayModel.socGlowEnabled?`url(#${this.glowFilterId})`:null).text(e=>e.compact?"":e.displayModel.remainingTimeText),t.select("g.bms-state-icon").attr("transform",`translate(${i.BATTERY_CARD_WIDTH/2-18}, ${i.BATTERY_CARD_HEIGHT/2-18})`).attr("display",e=>e.compact&&e.scale<.45?"none":null).attr("color",e=>e.compact?a.dim:a.color).attr("filter",e=>e.displayModel.socGlowEnabled?`url(#${this.glowFilterId})`:null).each((e,n,o)=>{let l=ge$1(o[n]),m=e.displayModel.iconKey,d=m==="power_renewal"?this.powerRenewalIconTemplate:this.powerAvailableIconTemplate;if(!d){l.selectAll("*").remove(),l.attr("data-icon-key",null);return}let s=l.node();if(!s||l.attr("data-icon-key")===m&&s.firstElementChild)return;l.selectAll("*").remove();let c=d.cloneNode(true);c.removeAttribute("id"),c.setAttribute("width","36"),c.setAttribute("height","36"),c.getAttribute("viewBox")||c.setAttribute("viewBox","0 0 24 24"),s.appendChild(c),l.attr("data-icon-key",m);});}formatVoltage(t){return t==null?"-- V":`${t.toFixed(1)}V`}formatCurrent(t){return t==null?"-- A":`${t.toFixed(1)}A`}formatPower(t){return t==null?"":`${t.toFixed(0)}W`}formatEnergy(t){return t==null?"":(t=this.units.convertToUnit("kWh",t),`${t}kWh`)}formatSoc(t){return t==null?"--%":`${Math.round(t*100)}%`}resolveBatteryTitleText(t){return t.name||`Battery ${t.id}`}formatDuration(t){if(t==null)return "";let a=this.units.convertToUnit("D HH:MM:SS",t);return a==null?"":typeof a=="string"?a:`${a}`}formatTemperature(t){if(t==null||typeof t!="number")return "";let a=this.units.getDefaults().Temperature,r=this.units.convertToUnit(a,t);return r===null?"":`${r.toFixed(1)} ${a==="celsius"?"\xB0C":"\xB0F"}`}splitMetricText(t,a){if(!t)return {valueText:"",unitText:""};let r=t.trim();return r?r.endsWith(a)?{valueText:r.slice(0,Math.max(0,r.length-a.length)).trim(),unitText:a}:{valueText:r,unitText:""}:{valueText:"",unitText:""}}sumNumbers(t){let a=t.filter(r=>typeof r=="number");return a.length?a.reduce((r,e)=>r+e,0):null}averageNumbers(t){let a=t.filter(r=>typeof r=="number");return a.length?a.reduce((r,e)=>r+e,0)/a.length:null}minNumber(t){let a=t.filter(r=>typeof r=="number");return a.length?Math.min(...a):null}toNumber(t){return t==null||typeof t!="number"?null:t}buildSemiGaugeArcPath(t,a){let r=Math.max(0,Math.min(1,a??0)),e=-Math.PI*.55,n=Math.PI*1.1,o=e+n*r;if(r<=0){let l=t*Math.cos(e),m=t*Math.sin(e);return `M ${l} ${m}`}return Bt()({innerRadius:t,outerRadius:t,startAngle:e,endAngle:o})??""}static \u0275fac=function(a){return new(a||i)};static \u0275cmp=JD({type:i,selectors:[["widget-bms"]],viewQuery:function(a,r){a&1&&eg(r.svgRef,ue,5),a&2&&Kw();},inputs:{id:[1,"id"],type:[1,"type"],theme:[1,"theme"],renderMode:[1,"renderMode"]},decls:4,vars:4,consts:[["bmsSvg",""],[3,"text","color"],["aria-hidden","false",1,"bms-svg"],[1,"bms-empty"],[1,"bms-empty-title"],[1,"bms-empty-sub"]],template:function(a,r){a&1&&(_w(0,pe,1,2,"widget-title",1),wd(),$h(1,"svg",2,0),_w(3,me,5,0,"div",3)),a&2&&(Mw(r.hasBanks()?0:-1),EE(),sg("bms-svg--full",!r.hasBanks()),EE(2),Mw(r.hasBatteries()?-1:3));},dependencies:[yt,x],styles:["[_nghost-%COMP%]{display:block;height:100%;width:100%;position:relative;overflow:hidden}.bms-svg[_ngcontent-%COMP%]{display:block;position:absolute;left:0;right:0;top:15%;height:85%;width:100%;overflow:hidden;padding:0 10px 10px}.bms-svg.bms-svg--full[_ngcontent-%COMP%]{top:0;height:100%;padding-top:10px}.bms-card-metric[_ngcontent-%COMP%]{fill:var(--mat-sys-on-surface);font-size:30px;font-weight:700}.bms-card-sub[_ngcontent-%COMP%]{fill:var(--mat-sys-on-surface);font-size:18px;opacity:.9}.bms-card-meta[_ngcontent-%COMP%]{fill:var(--mat-sys-on-surface);font-size:15px;opacity:.75}.bms-card-footer[_ngcontent-%COMP%]{fill:var(--mat-sys-on-surface);font-size:16px;opacity:.8}.bms-flow-line[_ngcontent-%COMP%]{stroke:var(--kip-zone-nominal-color);stroke-width:3px;stroke-dasharray:6 6;animation:_ngcontent-%COMP%_flow-dash 2s linear infinite}.bms-flow-line--out[_ngcontent-%COMP%]{stroke:var(--kip-zone-warn-color)}.bms-flow-line--in[_ngcontent-%COMP%]{stroke:var(--kip-zone-nominal-color)}.bms-flow-line--neutral[_ngcontent-%COMP%]{stroke:var(--kip-widget-card-border-color);animation:none}.bms-empty[_ngcontent-%COMP%]{position:absolute;inset:0;margin:10px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;text-align:center;color:var(--mat-sys-on-surface);background:color-mix(in srgb,var(--kip-widget-card-background-color) 92%,transparent)}.bms-empty-title[_ngcontent-%COMP%]{font-size:18px;font-weight:600}.bms-empty-sub[_ngcontent-%COMP%]{font-size:14px;opacity:.8}@keyframes _ngcontent-%COMP%_flow-dash{to{stroke-dashoffset:-12}}"]})};export{ee as WidgetBmsComponent};
1
+ import {e as e$1}from'./chunk-CyURmwWh.js';import {g as ge$1}from'./chunk-TakPRI3t.js';import {e9 as a,d1 as Hj,w,du as p,aS as De,bu as ut,ea as K,aY as xe,$ as $j,v as vt,D as Dt,dx as n$1,F as Fa,dn as ge,a_ as Gp,av as _t,cv as G,J as JD,y as yt,dC as x,_ as _w,cn as wd,c as $h,M as Mw,e as EE,s as sg,f as eg,K as Kw,g as qw,B as Bh,P as Pi,T as TT,u as ul}from'./main-BNR44HGB.js';import {c,e}from'./chunk-D_wrJJxl.js';function H(i){return function(){return i}}var Mt=Math.abs,_=Math.atan2,z=Math.cos,qt=Math.max,rt=Math.min,$=Math.sin,W=Math.sqrt,S=1e-12,Z=Math.PI,tt=Z/2,Xt=2*Z;function jt(i){return i>1?0:i<-1?Z:Math.acos(i)}function Tt(i){return i>=1?tt:i<=-1?-tt:Math.asin(i)}var Ct=Math.PI,At=2*Ct,L=1e-6,ae=At-L;function Zt(i){this._+=i[0];for(let t=1,a=i.length;t<a;++t)this._+=arguments[t]+i[t];}function re(i){let t=Math.floor(i);if(!(t>=0))throw new Error(`invalid digits: ${i}`);if(t>15)return Zt;let a=10**t;return function(r){this._+=r[0];for(let e=1,n=r.length;e<n;++e)this._+=Math.round(arguments[e]*a)/a+r[e];}}var F=class{constructor(t){this._x0=this._y0=this._x1=this._y1=null,this._="",this._append=t==null?Zt:re(t);}moveTo(t,a){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+a}`;}closePath(){this._x1!==null&&(this._x1=this._x0,this._y1=this._y0,this._append`Z`);}lineTo(t,a){this._append`L${this._x1=+t},${this._y1=+a}`;}quadraticCurveTo(t,a,r,e){this._append`Q${+t},${+a},${this._x1=+r},${this._y1=+e}`;}bezierCurveTo(t,a,r,e,n,o){this._append`C${+t},${+a},${+r},${+e},${this._x1=+n},${this._y1=+o}`;}arcTo(t,a,r,e,n){if(t=+t,a=+a,r=+r,e=+e,n=+n,n<0)throw new Error(`negative radius: ${n}`);let o=this._x1,l=this._y1,m=r-t,d=e-a,s=o-t,g=l-a,c=s*s+g*g;if(this._x1===null)this._append`M${this._x1=t},${this._y1=a}`;else if(c>L)if(!(Math.abs(g*m-d*s)>L)||!n)this._append`L${this._x1=t},${this._y1=a}`;else {let y=r-o,v=e-l,k=m*m+d*d,R=y*y+v*v,x=Math.sqrt(k),h=Math.sqrt(c),M=n*Math.tan((Ct-Math.acos((k+c-R)/(2*x*h)))/2),T=M/h,f=M/x;Math.abs(T-1)>L&&this._append`L${t+T*s},${a+T*g}`,this._append`A${n},${n},0,0,${+(g*y>s*v)},${this._x1=t+f*m},${this._y1=a+f*d}`;}}arc(t,a,r,e,n,o){if(t=+t,a=+a,r=+r,o=!!o,r<0)throw new Error(`negative radius: ${r}`);let l=r*Math.cos(e),m=r*Math.sin(e),d=t+l,s=a+m,g=1^o,c=o?e-n:n-e;this._x1===null?this._append`M${d},${s}`:(Math.abs(this._x1-d)>L||Math.abs(this._y1-s)>L)&&this._append`L${d},${s}`,r&&(c<0&&(c=c%At+At),c>ae?this._append`A${r},${r},0,1,${g},${t-l},${a-m}A${r},${r},0,1,${g},${this._x1=d},${this._y1=s}`:c>L&&this._append`A${r},${r},0,${+(c>=Ct)},${g},${this._x1=t+r*Math.cos(n)},${this._y1=a+r*Math.sin(n)}`);}rect(t,a,r,e){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+a}h${r=+r}v${+e}h${-r}Z`;}toString(){return this._}};function Jt(i){let t=3;return i.digits=function(a){if(!arguments.length)return t;if(a==null)t=null;else {let r=Math.floor(a);if(!(r>=0))throw new RangeError(`invalid digits: ${a}`);t=r;}return i},()=>new F(t)}function ne(i){return i.innerRadius}function ie(i){return i.outerRadius}function se(i){return i.startAngle}function oe(i){return i.endAngle}function le(i){return i&&i.padAngle}function ce(i,t,a,r,e,n,o,l){var m=a-i,d=r-t,s=o-e,g=l-n,c=g*m-s*d;if(!(c*c<S))return c=(s*(t-n)-g*(i-e))/c,[i+c*m,t+c*d]}function nt(i,t,a,r,e,n,o){var l=i-a,m=t-r,d=(o?n:-n)/W(l*l+m*m),s=d*m,g=-d*l,c=i+s,y=t+g,v=a+s,k=r+g,R=(c+v)/2,x=(y+k)/2,h=v-c,M=k-y,T=h*h+M*M,f=e-n,u=c*k-v*y,N=(M<0?-1:1)*W(qt(0,f*f*T-u*u)),w=(u*M-h*N)/T,E=(-u*h-M*N)/T,B=(u*M+h*N)/T,C=(-u*h+M*N)/T,I=w-R,p=E-x,b=B-R,O=C-x;return I*I+p*p>b*b+O*O&&(w=B,E=C),{cx:w,cy:E,x01:-s,y01:-g,x11:w*(e/f-1),y11:E*(e/f-1)}}function Bt(){var i=ne,t=ie,a=H(0),r=null,e=se,n=oe,o=le,l=null,m=Jt(d);function d(){var s,g,c=+i.apply(this,arguments),y=+t.apply(this,arguments),v=e.apply(this,arguments)-tt,k=n.apply(this,arguments)-tt,R=Mt(k-v),x=k>v;if(l||(l=s=m()),y<c&&(g=y,y=c,c=g),!(y>S))l.moveTo(0,0);else if(R>Xt-S)l.moveTo(y*z(v),y*$(v)),l.arc(0,0,y,v,k,!x),c>S&&(l.moveTo(c*z(k),c*$(k)),l.arc(0,0,c,k,v,x));else {var h=v,M=k,T=v,f=k,u=R,N=R,w=o.apply(this,arguments)/2,E=w>S&&(r?+r.apply(this,arguments):W(c*c+y*y)),B=rt(Mt(y-c)/2,+a.apply(this,arguments)),C=B,I=B,p,b;if(E>S){var O=Tt(E/c*$(w)),U=Tt(E/y*$(w));(u-=O*2)>S?(O*=x?1:-1,T+=O,f-=O):(u=0,T=f=(v+k)/2),(N-=U*2)>S?(U*=x?1:-1,h+=U,M-=U):(N=0,h=M=(v+k)/2);}var A=y*z(h),P=y*$(h),K=c*z(f),V=c*$(f);if(B>S){var Y=y*z(M),q=y*$(M),it=c*z(T),st=c*$(T),G;if(R<Z)if(G=ce(A,P,it,st,Y,q,K,V)){var ot=A-G[0],lt=P-G[1],ct=Y-G[0],dt=q-G[1],_t=1/$(jt((ot*ct+lt*dt)/(W(ot*ot+lt*lt)*W(ct*ct+dt*dt)))/2),Rt=W(G[0]*G[0]+G[1]*G[1]);C=rt(B,(c-Rt)/(_t-1)),I=rt(B,(y-Rt)/(_t+1));}else C=I=0;}N>S?I>S?(p=nt(it,st,A,P,y,I,x),b=nt(Y,q,K,V,y,I,x),l.moveTo(p.cx+p.x01,p.cy+p.y01),I<B?l.arc(p.cx,p.cy,I,_(p.y01,p.x01),_(b.y01,b.x01),!x):(l.arc(p.cx,p.cy,I,_(p.y01,p.x01),_(p.y11,p.x11),!x),l.arc(0,0,y,_(p.cy+p.y11,p.cx+p.x11),_(b.cy+b.y11,b.cx+b.x11),!x),l.arc(b.cx,b.cy,I,_(b.y11,b.x11),_(b.y01,b.x01),!x))):(l.moveTo(A,P),l.arc(0,0,y,h,M,!x)):l.moveTo(A,P),!(c>S)||!(u>S)?l.lineTo(K,V):C>S?(p=nt(K,V,Y,q,c,-C,x),b=nt(A,P,it,st,c,-C,x),l.lineTo(p.cx+p.x01,p.cy+p.y01),C<B?l.arc(p.cx,p.cy,C,_(p.y01,p.x01),_(b.y01,b.x01),!x):(l.arc(p.cx,p.cy,C,_(p.y01,p.x01),_(p.y11,p.x11),!x),l.arc(0,0,c,_(p.cy+p.y11,p.cx+p.x11),_(b.cy+b.y11,b.cx+b.x11),x),l.arc(b.cx,b.cy,C,_(b.y11,b.x11),_(b.y01,b.x01),!x))):l.arc(0,0,c,f,T,x);}if(l.closePath(),s)return l=null,s+""||null}return d.centroid=function(){var s=(+i.apply(this,arguments)+ +t.apply(this,arguments))/2,g=(+e.apply(this,arguments)+ +n.apply(this,arguments))/2-Z/2;return [z(g)*s,$(g)*s]},d.innerRadius=function(s){return arguments.length?(i=typeof s=="function"?s:H(+s),d):i},d.outerRadius=function(s){return arguments.length?(t=typeof s=="function"?s:H(+s),d):t},d.cornerRadius=function(s){return arguments.length?(a=typeof s=="function"?s:H(+s),d):a},d.padRadius=function(s){return arguments.length?(r=s==null?null:typeof s=="function"?s:H(+s),d):r},d.startAngle=function(s){return arguments.length?(e=typeof s=="function"?s:H(+s),d):e},d.endAngle=function(s){return arguments.length?(n=typeof s=="function"?s:H(+s),d):n},d.padAngle=function(s){return arguments.length?(o=typeof s=="function"?s:H(+s),d):o},d.context=function(s){return arguments.length?(l=s??null,d):l},d}var ue=["bmsSvg"];function pe(i,t){if(i&1&&$h(0,"widget-title",1),i&2){let a=qw();Bh("text",a.displayLabel())("color",a.labelColor());}}function me(i,t){i&1&&(Pi(0,"div",3)(1,"div",4),TT(2,"No batteries detected"),ul(),Pi(3,"div",5),TT(4,"Check Signal K battery paths or select batteries in widget settings."),ul()());}var ee=class i{static BMS_DESCRIPTOR=a("widget-bms");static ROOT_PATTERN=`${i.BMS_DESCRIPTOR?.selfRootPath??"self.electrical.batteries"}.*`;id=Hj.required();type=Hj.required();theme=Hj.required();renderMode=Hj(null);static DEFAULT_CONFIG={color:"contrast",ignoreZones:false,bms:{trackedDevices:[],groups:[],banks:[]}};static VIEWBOX_WIDTH=200;static MIN_VIEWBOX_HEIGHT=1;static BANK_CARD_WIDTH=200;static BATTERY_CARD_HEIGHT=50;static BATTERY_CARD_WIDTH=200;static CARD_GAP=8;static BANK_HEADER_HEIGHT=80;static BANK_MIN_HEIGHT=75;static SINGLE_ROW_BANK_HEIGHT=100;static IN_BANK_COLUMNS=2;static IN_BANK_COLUMN_GAP=5;static IN_BANK_PADDING_X=0;static BANK_GAUGE_RADIUS=50;static BANK_GAUGE_BG_STROKE=10;static BANK_GAUGE_VALUE_STROKE=10;static COMPACT_UNASSIGNED_BATTERY_SCALE=.82;static PATH_BATCH_WINDOW_MS=500;runtime=w(p);data=w(De);units=w(ut);iconRegistry=w(K);destroyRef=w(xe);svgRef=$j.required("bmsSvg");svg;root;bankLayer;batteryLayer;bankGaugeBackgroundPath=this.buildSemiGaugeArcPath(i.BANK_GAUGE_RADIUS,1);glowFilterId="";renderFrameId=null;pendingRenderSnapshot=null;pathBatchTimerId=null;initialPathPaintDone=false;pendingPathUpdates=new Map;powerAvailableIconTemplate=null;powerRenewalIconTemplate=null;discoveredBatteryIds=vt([]);trackedBatteryDeviceIds=vt([]);banks=vt([]);cardMode=vt({displayMode:"full",metrics:[]});batteries=vt({});visibleBatteryIds=Dt(()=>{let t=this.trackedBatteryDeviceIds();return t.length?t:this.discoveredBatteryIds()});visibleBatteries=Dt(()=>{let t=this.visibleBatteryIds(),a=this.batteries();return t.map(r=>a[r]).filter(r=>!!r)});bankSummaries=Dt(()=>{let t=this.banks(),a=this.batteries();return t.map(r=>this.buildBankSummary(r,a))});activeDisplayMode=Dt(()=>this.renderMode()??this.cardMode().displayMode??"full");isCompactCardMode=Dt(()=>this.activeDisplayMode()==="compact");colorRole=Dt(()=>this.runtime.options()?.color??"contrast");ignoreZones=Dt(()=>this.runtime.options()?.ignoreZones??false);displayLabel=Dt(()=>{let t=this.bankSummaries();if(t.length===1)return t[0].name||"Bank";if(t.length>1)return "Batteries";let a=this.visibleBatteries();return a.length!==1?"Batteries":this.resolveBatteryTitleText(a[0])});labelColor=Dt(()=>{let t=this.theme();return t?c(this.colorRole(),t).dim:"var(--kip-contrast-dim-color)"});widgetColors=Dt(()=>{let t=this.theme();return t?c(this.colorRole(),t):null});batteryDisplayModels=Dt(()=>{let t=this.visibleBatteries(),a=this.theme(),r=this.widgetColors(),e$1=this.ignoreZones(),n={};for(let o of t){let l=e(o.stateOfChargeState,r?.dimmer??"var(--kip-contrast-dimmer-color)",a,e$1),m=e(o.stateOfChargeState,r?.dim??"var(--kip-contrast-dim-color)",a,e$1),d=e(o.currentState,"var(--kip-contrast-dim-color)",a,e$1),s=e(o.currentState,"var(--kip-contrast-color)",a,e$1);n[o.id]={id:o.id,titleText:this.resolveBatteryTitleText(o),chargeWidth:(i.BATTERY_CARD_WIDTH-3)*(o.stateOfCharge??0),chargeBarColorCompact:l,chargeBarColorRegular:m,currentTextColorCompact:d,currentTextColorRegular:s,currentText:`${this.formatCurrent(o.current)}`.trim(),detailLineCompact:`${this.formatVoltage(o.voltage)}\xA0\xA0\xA0\xA0${this.formatTemperature(o.temperature)}`,detailLineRegular:`${this.formatVoltage(o.voltage)}\xA0\xA0\xA0\xA0${this.formatPower(o.power)}\xA0\xA0\xA0\xA0${this.formatTemperature(o.temperature)}`.trim(),socText:this.formatSoc(o.stateOfCharge),socGlowEnabled:!e$1&&(o.stateOfChargeState===n$1.Warn||o.stateOfChargeState===n$1.Alarm||o.stateOfChargeState===n$1.Alert),remainingCapacityText:o.capacityActual?`${this.formatEnergy(o.capacityRemaining)}`:"",remainingTimeText:`${this.formatDuration(o.timeRemaining)}`.trim(),iconKey:o.current!=null&&o.current>0?"power_renewal":"power_available"};}return n});bankDisplayModels=Dt(()=>{let t=this.bankSummaries(),a=this.widgetColors(),r={};for(let e of t)r[e.id]={id:e.id,titleText:e.name||"Bank",currentText:this.formatCurrent(e.totalCurrent),powerText:this.formatPower(e.totalPower),socText:this.formatSoc(e.avgSoc),remainingTimeText:`${this.formatDuration(e.timeRemaining)}`.trim(),remainingCapacityText:e.remainingCapacity?`${this.formatEnergy(e.remainingCapacity)}`:"",gaugeValuePath:this.buildSemiGaugeArcPath(i.BANK_GAUGE_RADIUS,e.avgSoc),gaugeValueColor:a?.color??"var(--kip-contrast-color)",zoneState:null,zoneColor:null};return r});hasBatteries=Dt(()=>this.visibleBatteries().length>0);hasBanks=Dt(()=>this.bankSummaries().length>0);constructor(){Fa(()=>{let a=this.runtime.options();a&&ge(()=>this.applyConfig(a));}),Fa(()=>{let a=this.bankSummaries(),r=this.visibleBatteries(),e=this.widgetColors(),n=this.batteryDisplayModels(),o=this.bankDisplayModels();!this.svg||!e||this.requestRender({banks:a,batteries:r,batteryDisplayModels:n,bankDisplayModels:o,widgetColors:e});});let t=this.data.subscribePathTreeWithInitial(i.ROOT_PATTERN);if(t.initial.length){for(let a of t.initial)this.enqueuePathUpdate(a,true);this.flushPendingPathUpdates(),this.initialPathPaintDone=true;}t.live$.pipe(Gp(this.destroyRef)).subscribe(a=>{this.enqueuePathUpdate(a);});}ngAfterViewInit(){this.initializeSvg(),this.loadPowerIcons(),this.requestRender();}ngOnDestroy(){this.pathBatchTimerId!==null&&(clearTimeout(this.pathBatchTimerId),this.pathBatchTimerId=null),this.renderFrameId!==null&&(cancelAnimationFrame(this.renderFrameId),this.renderFrameId=null),this.pendingRenderSnapshot=null;}initializeSvg(){this.svg=ge$1(this.svgRef().nativeElement),this.svg.attr("viewBox",`0 0 ${i.VIEWBOX_WIDTH} ${i.MIN_VIEWBOX_HEIGHT}`).attr("preserveAspectRatio","xMidYMid meet").attr("role","img").attr("aria-label","Battery Management System View"),this.glowFilterId=`bms-soc-glow-${this.id()}`;let a=this.svg.append("defs").append("filter").attr("id",this.glowFilterId).attr("x","-30%").attr("y","-30%").attr("width","160%").attr("height","160%");a.append("feFlood").attr("class","bms-soc-glow-flood").attr("flood-color","var(--kip-widget-card-background-color)").attr("flood-opacity",.9).attr("result","color"),a.append("feComposite").attr("in","color").attr("in2","SourceGraphic").attr("operator","in").attr("result","coloredGlow"),a.append("feGaussianBlur").attr("in","coloredGlow").attr("stdDeviation",2).attr("result","blur");let r=a.append("feMerge");r.append("feMergeNode").attr("in","blur"),r.append("feMergeNode").attr("in","blur"),r.append("feMergeNode").attr("in","SourceGraphic"),this.root=this.svg.append("g").attr("class","bms-root"),this.bankLayer=this.root.append("g").attr("class","bms-banks"),this.batteryLayer=this.root.append("g").attr("class","bms-batteries");}loadPowerIcons(){this.loadNamedIcon("power_available",t=>{this.powerAvailableIconTemplate=t;}),this.loadNamedIcon("power_renewal",t=>{this.powerRenewalIconTemplate=t;});}loadNamedIcon(t,a){this.iconRegistry.getNamedSvgIcon(t).pipe(_t(1)).subscribe({next:r=>{a(r),this.requestRender();},error:()=>{}});}applyConfig(t){let a=this.resolveBmsConfig(t);this.trackedBatteryDeviceIds.set([...new Set((a.trackedDevices??[]).map(r=>r.id))]),this.banks.set(a.banks),this.cardMode.set(this.normalizeCardMode(a.cardMode));}resolveBmsConfig(t){let a=t.bms,r=this.normalizeTrackedDevices(a?.trackedDevices),e=this.normalizeBanksFromGroups(a?.groups),n=this.normalizeBanksFromLegacy(a?.banks);return {trackedDevices:r,groups:e,banks:e.length>0?e:n,cardMode:this.normalizeCardMode(a?.cardMode)}}normalizeTrackedDevices(t){if(!Array.isArray(t))return [];let a=new Map;return t.forEach(r=>{if(!r||typeof r!="object")return;let e=r,n=typeof e.id=="string"?e.id.trim():"",o=typeof e.source=="string"?e.source.trim():"default";if(!n||!o)return;let l=typeof e.key=="string"&&e.key.trim().length>0?e.key.trim():`${n}||${o}`;a.set(l,{id:n,source:o,key:l});}),[...a.values()].sort((r,e)=>r.key.localeCompare(e.key))}normalizeCardMode(t){let a=t&&typeof t=="object"?t:null,r=this.normalizeStringList(a?.metrics);return {displayMode:a?.displayMode==="compact"?"compact":"full",metrics:r}}normalizeStringList(t){if(!Array.isArray(t))return [];let a=new Set;return t.forEach(r=>{if(typeof r!="string")return;let e=r.trim();e.length>0&&a.add(e);}),[...a].sort((r,e)=>r.localeCompare(e))}normalizeBanksFromGroups(t){return Array.isArray(t)?t.map(a=>{let r=this.normalizeOptionalString(a?.id)??`bank-${Date.now()}`,e=this.normalizeOptionalString(a?.name)??r,n=this.normalizeStringList(a?.memberIds);return {id:r,name:e,batteryIds:n,connectionMode:this.normalizeConnectionMode(a?.connectionMode)}}).filter(a=>a.id.length>0):[]}normalizeBanksFromLegacy(t){return Array.isArray(t)?t.map(a=>{let r=this.normalizeOptionalString(a?.id)??`bank-${Date.now()}`,e=this.normalizeOptionalString(a?.name)??r,n=this.normalizeStringList(a?.batteryIds);return {id:r,name:e,batteryIds:n,connectionMode:this.normalizeConnectionMode(a?.connectionMode)}}).filter(a=>a.id.length>0):[]}normalizeOptionalString(t){if(typeof t!="string")return null;let a=t.trim();return a.length>0?a:null}normalizeConnectionMode(t){return t==="series"?"series":"parallel"}enqueuePathUpdate(t,a=false){let r=this.parseBatteryPath(t.path);if(!r)return;let{id:e,key:n}=r,o=t.update?.data?.value??null,l=t.update?.state??null,m=`${e}::${n}`;if(this.pendingPathUpdates.set(m,{id:e,key:n,value:o,state:l}),!a){if(!this.initialPathPaintDone){this.initialPathPaintDone=true,this.flushPendingPathUpdates();return}this.pathBatchTimerId===null&&(this.pathBatchTimerId=window.setTimeout(()=>{this.pathBatchTimerId=null,this.flushPendingPathUpdates();},i.PATH_BATCH_WINDOW_MS));}}flushPendingPathUpdates(){if(!this.pendingPathUpdates.size)return;let t=Array.from(this.pendingPathUpdates.values());this.pendingPathUpdates.clear(),new Set(t.map(r=>r.id)).forEach(r=>this.trackDiscoveredBattery(r)),this.batteries.update(r=>{let e=r,n=false;for(let o of t){let l=e[o.id]??{id:o.id},m=G({},l),d=this.applyBatteryValue(m,o.key,o.value,o.state),s=false;if(m.voltage!=null&&m.current!=null){let g=Number.isFinite(m.voltage)&&Number.isFinite(m.current)?m.voltage*m.current:null;Object.is(m.power,g)||(m.power=g,s=true);}!d&&!s||(n||(e=G({},e),n=true),e[o.id]=m);}return n?e:r});}parseBatteryPath(t){let a=t.match(/self\.electrical\.batteries\.([^.]+)\.(.+)$/);return a?{id:a[1],key:a[2]}:null}trackDiscoveredBattery(t){let a=this.discoveredBatteryIds();if(a.includes(t))return;let r=[...a,t].sort();this.discoveredBatteryIds.set(r);}applyBatteryValue(t,a,r,e){switch(a){case "name":{let n=r;return t.name===n?false:(t.name=n,true)}case "location":{let n=r;return t.location===n?false:(t.location=n,true)}case "associatedBus":{let n=r;return t.associatedBus===n?false:(t.associatedBus=n,true)}case "chemistry":{let n=r;return t.chemistry===n?false:(t.chemistry=n,true)}case "voltage":{let n=this.toNumber(r);return Object.is(t.voltage,n)?false:(t.voltage=n,true)}case "current":{let n=this.toNumber(r),o=!Object.is(t.currentState??null,e??null);return Object.is(t.current,n)&&!o?false:(t.current=n,t.currentState=e,true)}case "temperature":{let n=this.toNumber(r);return Object.is(t.temperature,n)?false:(t.temperature=n,true)}case "capacity.nominal":{let n=this.toNumber(r);return Object.is(t.capacityNominal,n)?false:(t.capacityNominal=n,true)}case "capacity.actual":{let n=this.toNumber(r);return Object.is(t.capacityActual,n)?false:(t.capacityActual=n,true)}case "capacity.remaining":{let n=this.toNumber(r);return Object.is(t.capacityRemaining,n)?false:(t.capacityRemaining=n,true)}case "capacity.stateOfCharge":{let n=this.toNumber(r),o=!Object.is(t.stateOfChargeState??null,e??null);return Object.is(t.stateOfCharge,n)&&!o?false:(t.stateOfCharge=n,t.stateOfChargeState=e,true)}case "capacity.timeRemaining":{let n=this.toNumber(r);return Object.is(t.timeRemaining,n)?false:(t.timeRemaining=n,true)}default:return false}}buildBankSummary(t,a){let r=t.batteryIds.map(s=>a[s]).filter(s=>!!s),e=this.normalizeConnectionMode(t.connectionMode),n=this.calculateBankCurrent(r,e),o=this.sumNumbers(r.map(s=>s.power)),l=this.sumNumbers(r.map(s=>s.capacityRemaining)),m=this.calculateBankSoc(r),d=this.calculateBankTimeRemaining(r,e);return {id:t.id,name:t.name,batteryIds:t.batteryIds,totalCurrent:n,totalPower:o,remainingCapacity:l,avgSoc:m,timeRemaining:d}}calculateBankSoc(t){let a=this.sumNumbers(t.map(n=>n.capacityRemaining)),r=this.sumNumbers(t.map(n=>n.capacityActual));if(a!=null&&r!=null&&r>0)return Math.max(0,Math.min(1,a/r));let e=this.sumNumbers(t.map(n=>n.capacityNominal));return a!=null&&e!=null&&e>0?Math.max(0,Math.min(1,a/e)):this.averageNumbers(t.map(n=>n.stateOfCharge))}calculateBankCurrent(t,a){let r=t.map(e=>e.current);return a==="series"?this.averageNumbers(r):this.sumNumbers(r)}calculateBankTimeRemaining(t,a){let r=t.map(e=>e.timeRemaining);return a==="series"?this.minNumber(r):this.averageNumbers(r)}requestRender(t){this.svg&&(this.pendingRenderSnapshot=t??this.buildRenderSnapshot(),this.pendingRenderSnapshot&&this.renderFrameId===null&&(this.renderFrameId=requestAnimationFrame(()=>{this.renderFrameId=null;let a=this.pendingRenderSnapshot;this.pendingRenderSnapshot=null,a&&this.render(a);})));}buildRenderSnapshot(){let t=this.widgetColors();return t?{banks:this.bankSummaries(),batteries:this.visibleBatteries(),batteryDisplayModels:this.batteryDisplayModels(),bankDisplayModels:this.bankDisplayModels(),widgetColors:t}:null}render(t){if(!this.bankLayer||!this.batteryLayer)return;let{banks:a,batteries:r,bankDisplayModels:e,batteryDisplayModels:n,widgetColors:o}=t,l=this.buildRenderLayout(a,r,e,n,this.isCompactCardMode()),d=this.isCompactCardMode()?e$1:e$1,s=Math.max(i.MIN_VIEWBOX_HEIGHT,l.contentHeight);this.svg?.attr("viewBox",`0 0 ${i.VIEWBOX_WIDTH} ${s}`),this.root?.attr("transform",null);let g=this.bankLayer.selectAll("g.bank-card").data(l.banks,u=>u.id),c=g.enter().append("g").attr("class","bank-card"),y=c.append("text").attr("class","bank-card-power");y.append("tspan").attr("class","bank-card-power-value"),y.append("tspan").attr("class","bank-card-power-unit");let v=c.append("text").attr("class","bank-card-current");v.append("tspan").attr("class","bank-card-current-value"),v.append("tspan").attr("class","bank-card-current-unit");let k=c.append("g").attr("class","bank-gauge");k.append("path").attr("class","bank-gauge-bg"),k.append("path").attr("class","bank-gauge-value");let R=k.append("text").attr("class","bank-gauge-soc");R.append("tspan").attr("class","bank-gauge-soc-value"),R.append("tspan").attr("class","bank-gauge-soc-unit");let x=c.append("text").attr("class","bank-actualCapacity");x.append("tspan").attr("class","bank-actualCapacity-value"),x.append("tspan").attr("class","bank-actualCapacity-unit"),c.append("text").attr("class","bank-remaining"),c.append("g").attr("class","bank-bms-batteries"),c.append("text").attr("class","bank-title");let h=c.merge(g);h.attr("transform",u=>`translate(${u.x},${u.y})`),l.banks.length>1?h.select("text.bank-title").attr("x",d.titleX).attr("y",d.titleY).attr("fill","var(--kip-contrast-dim-color)").attr("font-size",d.titleFontSize).text(u=>u.displayModel.titleText):h.select("text.bank-title").text(""),h.select("text.bank-card-current").attr("x",d.lineOneX).attr("y",d.lineOneY).attr("fill","var(--kip-contrast-color)").attr("font-size",d.lineOneFontSize),h.select("tspan.bank-card-current-value").text(u=>this.splitMetricText(u.displayModel.currentText,"A").valueText),h.select("tspan.bank-card-current-unit").attr("dx",1).attr("font-size",12).attr("fill","var(--kip-contrast-color)").text(u=>this.splitMetricText(u.displayModel.currentText,"A").unitText),h.select("text.bank-card-power").attr("x",5).attr("y",42).attr("fill","var(--kip-contrast-color)").attr("font-size",10).attr("opacity",.8),h.select("tspan.bank-card-power-value").text(u=>this.splitMetricText(u.displayModel.powerText,"W").valueText),h.select("tspan.bank-card-power-unit").attr("dx",1).attr("font-size",6).attr("fill","var(--kip-contrast-color)").text(u=>this.splitMetricText(u.displayModel.powerText,"W").unitText),h.select("g.bank-gauge").attr("transform","translate(143, 60)"),h.select("path.bank-gauge-bg").attr("d",this.bankGaugeBackgroundPath).attr("fill","none").attr("stroke","var(--kip-contrast-dimmer-color)").attr("stroke-width",i.BANK_GAUGE_BG_STROKE).attr("stroke-linecap","round"),h.select("path.bank-gauge-value").attr("d",u=>u.displayModel.gaugeValuePath).attr("fill","none").attr("stroke",u=>u.displayModel.gaugeValueColor).attr("stroke-width",i.BANK_GAUGE_VALUE_STROKE).attr("stroke-linecap","round"),h.select("text.bank-gauge-soc").attr("x",0).attr("y",-5).attr("text-anchor","middle").attr("fill","var(--kip-contrast-color)").attr("font-size",d.primaryFontSize).attr("font-weight",d.primaryFontWeight),h.select("tspan.bank-gauge-soc-value").text(u=>this.splitMetricText(u.displayModel.socText,"%").valueText),h.select("tspan.bank-gauge-soc-unit").attr("dx",1).attr("font-size",22).attr("font-weight",500).attr("fill","var(--kip-contrast-color)").text(u=>this.splitMetricText(u.displayModel.socText,"%").unitText),h.select("text.bank-remaining").attr("x",143).attr("y",26).attr("fill","var(--kip-contrast-dim-color)").attr("text-anchor","middle").attr("font-size",8).text(u=>u.displayModel.remainingTimeText),h.select("text.bank-actualCapacity").attr("x",143).attr("y",66).attr("fill","var(--kip-contrast-dim-color)").attr("text-anchor","middle").attr("font-size",8),h.select("tspan.bank-actualCapacity-value").text(u=>this.splitMetricText(u.displayModel.remainingCapacityText,"kWh").valueText),h.select("tspan.bank-actualCapacity-unit").attr("dx",1).attr("font-size",6).attr("fill","var(--kip-contrast-dim-color)").text(u=>this.splitMetricText(u.displayModel.remainingCapacityText,"kWh").unitText),h.select("g.bank-bms-batteries").each((u,N,w)=>{let B=ge$1(w[N]).selectAll("g.battery-card").data(u.batteries,p=>p.key),C=B.enter().append("g").attr("class","battery-card battery-card--in-bank");this.appendBatteryCardSkeleton(C);let I=C.merge(B);this.renderBatteryCards(I,o,t.batteries.length>1),B.exit().remove();}),g.exit().remove();let M=this.batteryLayer.selectAll("g.battery-card").data(l.unassignedBatteries,u=>u.key),T=M.enter().append("g").attr("class","battery-card battery-card--unassigned");this.appendBatteryCardSkeleton(T);let f=T.merge(M);this.renderBatteryCards(f,o,true),M.exit().remove(),this.root?.attr("data-theme","ready");}buildRenderLayout(t,a,r,e,n){let o=new Map(a.map(f=>[f.id,f])),l=new Set,m=this.computeInBankBatterySlotWidth(),d=Math.max(.35,Math.min(1,m/i.BATTERY_CARD_WIDTH)),s=i.BATTERY_CARD_HEIGHT*d,g=0,c=t.map(f=>{let u=new Set,N=f.batteryIds.map(A=>o.get(A)).filter(A=>!A||u.has(A.id)?false:(u.add(A.id),true));N.forEach(A=>l.add(A.id));let w=Math.ceil(N.length/i.IN_BANK_COLUMNS),E=i.SINGLE_ROW_BANK_HEIGHT,B=!n&&w===1,C=B?Math.max(0,E-s-i.CARD_GAP):i.BANK_HEADER_HEIGHT,I=w>0?w*s+(w-1)*i.CARD_GAP:0,p=Math.max(i.BANK_MIN_HEIGHT,C+I+i.CARD_GAP),b=B?E:p,O=N.map((A,P)=>{let K=P%i.IN_BANK_COLUMNS,V=Math.floor(P/i.IN_BANK_COLUMNS),Y=i.IN_BANK_PADDING_X+K*(m+i.IN_BANK_COLUMN_GAP),q=C+7+V*(s+i.CARD_GAP);return {id:A.id,displayModel:e[A.id],key:`${f.id}::${A.id}`,x:Y,y:q,scale:d,inBank:true,compact:true}}),U={id:f.id,name:f.name,batteryIds:f.batteryIds,totalCurrent:f.totalCurrent,totalPower:f.totalPower,avgSoc:f.avgSoc,remainingCapacity:f.remainingCapacity,timeRemaining:f.timeRemaining,displayModel:r[f.id],x:0,y:g,width:i.BANK_CARD_WIDTH,height:b,batteries:O};return g+=b+i.CARD_GAP,U}),y=c.length>0?g:0,v=n?i.COMPACT_UNASSIGNED_BATTERY_SCALE:1,k=i.BATTERY_CARD_HEIGHT*v,R=a.filter(f=>!l.has(f.id)).sort((f,u)=>f.id.localeCompare(u.id)).map((f,u)=>({id:f.id,displayModel:e[f.id],key:f.id,x:0,y:y+u*(k+i.CARD_GAP),scale:v,inBank:false,compact:n})),x=c[c.length-1],h=x?x.y+x.height:0,M=R[R.length-1],T=M?M.y+k:0;return {banks:c,unassignedBatteries:R,contentHeight:Math.max(h,T)}}computeInBankBatterySlotWidth(){return (i.BANK_CARD_WIDTH-i.IN_BANK_PADDING_X*2-i.IN_BANK_COLUMN_GAP)/i.IN_BANK_COLUMNS}appendBatteryCardSkeleton(t){t.append("rect").attr("class","bms-battery").attr("rx",4).attr("ry",4),t.append("rect").attr("class","bms-battery-tip").attr("rx",1).attr("ry",1),t.append("rect").attr("class","bms-charge-fill").attr("rx",3).attr("ry",3),t.append("g").attr("class","bms-state-icon"),t.append("text").attr("class","bms-ampere"),t.append("text").attr("class","bms-volt-power");let a=t.append("text").attr("class","bms-soc");a.append("tspan").attr("class","bms-soc-value"),a.append("tspan").attr("class","bms-soc-unit"),t.append("text").attr("class","bms-actualCapacity"),t.append("text").attr("class","bms-remaining"),t.append("text").attr("class","bms-title");}renderBatteryCards(t,a,r){t.attr("transform",e=>`translate(${e.x},${e.y}) scale(${e.scale})`),t.select("rect.bms-battery").attr("width",e=>e.inBank?i.BATTERY_CARD_WIDTH:e.compact?i.BATTERY_CARD_WIDTH-i.CARD_GAP:i.BATTERY_CARD_WIDTH).attr("height",i.BATTERY_CARD_HEIGHT).attr("fill",e=>e.compact?"var(--mat-sys-background)":"var(--kip-contrast-dimmer-color)").attr("stroke","var(--kip-contrast-dimmer-color)").attr("stroke-width",0),t.select("rect.bms-battery-tip").attr("x",i.BATTERY_CARD_WIDTH).attr("y",i.BATTERY_CARD_HEIGHT/2-10).attr("width",4).attr("height",20).attr("fill",e=>e.compact?"var(--mat-sys-background)":"var(--kip-contrast-dimmer-color)").attr("stroke",a.color).attr("stroke-width",0),t.select("rect.bms-charge-fill").attr("x",1.5).attr("y",1.5).attr("width",e=>e.displayModel.chargeWidth).attr("height",i.BATTERY_CARD_HEIGHT-3).attr("fill",e=>e.compact?e.displayModel.chargeBarColorCompact:e.displayModel.chargeBarColorRegular),r?t.select("text.bms-title").attr("x",5).attr("y",e=>e.compact?11:14).attr("fill","var(--kip-contrast-dim-color)").attr("font-size",e=>e.compact?8:12).attr("filter",e=>e.displayModel.socGlowEnabled?`url(#${this.glowFilterId})`:null).text(e=>e.displayModel.titleText):t.select("text.bms-title").text(""),t.select("text.bms-ampere").attr("x",10).attr("y",33).attr("fill",e=>e.compact?e.displayModel.currentTextColorCompact:e.displayModel.currentTextColorRegular).attr("font-size",16).attr("filter",e=>e.displayModel.socGlowEnabled?`url(#${this.glowFilterId})`:null).text(e=>e.displayModel.currentText),t.select("text.bms-volt-power").attr("x",10).attr("y",45).attr("fill","var(--kip-contrast-dim-color)").attr("font-size",8).attr("opacity",.8).attr("filter",e=>e.displayModel.socGlowEnabled?`url(#${this.glowFilterId})`:null).text(e=>e.compact?e.displayModel.detailLineCompact:e.displayModel.detailLineRegular),t.select("text.bms-soc").attr("x",i.BATTERY_CARD_WIDTH-33).attr("y",34).attr("fill",e=>e.compact?"var(--kip-contrast-dim-color)":"var(--kip-contrast-color)").attr("text-anchor","middle").attr("font-size",25).attr("font-weight",700).attr("filter",e=>e.displayModel.socGlowEnabled?`url(#${this.glowFilterId})`:null),t.select("tspan.bms-soc-value").text(e=>this.splitMetricText(e.displayModel.socText,"%").valueText),t.select("tspan.bms-soc-unit").attr("dx",1).attr("font-size",16).attr("font-weight",500).text(e=>this.splitMetricText(e.displayModel.socText,"%").unitText),t.select("text.bms-actualCapacity").attr("x",i.BATTERY_CARD_WIDTH-33).attr("y",45).attr("fill","var(--kip-contrast-dim-color)").attr("text-anchor","middle").attr("font-size",8).attr("filter",e=>e.displayModel.socGlowEnabled?`url(#${this.glowFilterId})`:null).text(e=>e.compact?"":e.displayModel.remainingCapacityText),t.select("text.bms-remaining").attr("x",i.BATTERY_CARD_WIDTH-33).attr("y",12).attr("fill","var(--kip-contrast-dim-color)").attr("text-anchor","middle").attr("font-size",6).attr("filter",e=>e.displayModel.socGlowEnabled?`url(#${this.glowFilterId})`:null).text(e=>e.compact?"":e.displayModel.remainingTimeText),t.select("g.bms-state-icon").attr("transform",`translate(${i.BATTERY_CARD_WIDTH/2-18}, ${i.BATTERY_CARD_HEIGHT/2-18})`).attr("display",e=>e.compact&&e.scale<.45?"none":null).attr("color",e=>e.compact?a.dim:a.color).attr("filter",e=>e.displayModel.socGlowEnabled?`url(#${this.glowFilterId})`:null).each((e,n,o)=>{let l=ge$1(o[n]),m=e.displayModel.iconKey,d=m==="power_renewal"?this.powerRenewalIconTemplate:this.powerAvailableIconTemplate;if(!d){l.selectAll("*").remove(),l.attr("data-icon-key",null);return}let s=l.node();if(!s||l.attr("data-icon-key")===m&&s.firstElementChild)return;l.selectAll("*").remove();let c=d.cloneNode(true);c.removeAttribute("id"),c.setAttribute("width","36"),c.setAttribute("height","36"),c.getAttribute("viewBox")||c.setAttribute("viewBox","0 0 24 24"),s.appendChild(c),l.attr("data-icon-key",m);});}formatVoltage(t){return t==null?"-- V":`${t.toFixed(1)}V`}formatCurrent(t){return t==null?"-- A":`${t.toFixed(1)}A`}formatPower(t){return t==null?"":`${t.toFixed(0)}W`}formatEnergy(t){return t==null?"":(t=this.units.convertToUnit("kWh",t),`${t}kWh`)}formatSoc(t){return t==null?"--%":`${Math.round(t*100)}%`}resolveBatteryTitleText(t){return t.name||`Battery ${t.id}`}formatDuration(t){if(t==null)return "";let a=this.units.convertToUnit("D HH:MM:SS",t);return a==null?"":typeof a=="string"?a:`${a}`}formatTemperature(t){if(t==null||typeof t!="number")return "";let a=this.units.getDefaults().Temperature,r=this.units.convertToUnit(a,t);return r===null?"":`${r.toFixed(1)} ${a==="celsius"?"\xB0C":"\xB0F"}`}splitMetricText(t,a){if(!t)return {valueText:"",unitText:""};let r=t.trim();return r?r.endsWith(a)?{valueText:r.slice(0,Math.max(0,r.length-a.length)).trim(),unitText:a}:{valueText:r,unitText:""}:{valueText:"",unitText:""}}sumNumbers(t){let a=t.filter(r=>typeof r=="number");return a.length?a.reduce((r,e)=>r+e,0):null}averageNumbers(t){let a=t.filter(r=>typeof r=="number");return a.length?a.reduce((r,e)=>r+e,0)/a.length:null}minNumber(t){let a=t.filter(r=>typeof r=="number");return a.length?Math.min(...a):null}toNumber(t){return t==null||typeof t!="number"?null:t}buildSemiGaugeArcPath(t,a){let r=Math.max(0,Math.min(1,a??0)),e=-Math.PI*.55,n=Math.PI*1.1,o=e+n*r;if(r<=0){let l=t*Math.cos(e),m=t*Math.sin(e);return `M ${l} ${m}`}return Bt()({innerRadius:t,outerRadius:t,startAngle:e,endAngle:o})??""}static \u0275fac=function(a){return new(a||i)};static \u0275cmp=JD({type:i,selectors:[["widget-bms"]],viewQuery:function(a,r){a&1&&eg(r.svgRef,ue,5),a&2&&Kw();},inputs:{id:[1,"id"],type:[1,"type"],theme:[1,"theme"],renderMode:[1,"renderMode"]},decls:4,vars:4,consts:[["bmsSvg",""],[3,"text","color"],["aria-hidden","false",1,"bms-svg"],[1,"bms-empty"],[1,"bms-empty-title"],[1,"bms-empty-sub"]],template:function(a,r){a&1&&(_w(0,pe,1,2,"widget-title",1),wd(),$h(1,"svg",2,0),_w(3,me,5,0,"div",3)),a&2&&(Mw(r.hasBanks()?0:-1),EE(),sg("bms-svg--full",!r.hasBanks()),EE(2),Mw(r.hasBatteries()?-1:3));},dependencies:[yt,x],styles:["[_nghost-%COMP%]{display:block;height:100%;width:100%;position:relative;overflow:hidden}.bms-svg[_ngcontent-%COMP%]{display:block;position:absolute;left:0;right:0;top:15%;height:85%;width:100%;overflow:hidden;padding:0 10px 10px}.bms-svg.bms-svg--full[_ngcontent-%COMP%]{top:0;height:100%;padding-top:10px}.bms-card-metric[_ngcontent-%COMP%]{fill:var(--mat-sys-on-surface);font-size:30px;font-weight:700}.bms-card-sub[_ngcontent-%COMP%]{fill:var(--mat-sys-on-surface);font-size:18px;opacity:.9}.bms-card-meta[_ngcontent-%COMP%]{fill:var(--mat-sys-on-surface);font-size:15px;opacity:.75}.bms-card-footer[_ngcontent-%COMP%]{fill:var(--mat-sys-on-surface);font-size:16px;opacity:.8}.bms-flow-line[_ngcontent-%COMP%]{stroke:var(--kip-zone-nominal-color);stroke-width:3px;stroke-dasharray:6 6;animation:_ngcontent-%COMP%_flow-dash 2s linear infinite}.bms-flow-line--out[_ngcontent-%COMP%]{stroke:var(--kip-zone-warn-color)}.bms-flow-line--in[_ngcontent-%COMP%]{stroke:var(--kip-zone-nominal-color)}.bms-flow-line--neutral[_ngcontent-%COMP%]{stroke:var(--kip-widget-card-border-color);animation:none}.bms-empty[_ngcontent-%COMP%]{position:absolute;inset:0;margin:10px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;text-align:center;color:var(--mat-sys-on-surface);background:color-mix(in srgb,var(--kip-widget-card-background-color) 92%,transparent)}.bms-empty-title[_ngcontent-%COMP%]{font-size:18px;font-weight:600}.bms-empty-sub[_ngcontent-%COMP%]{font-size:14px;opacity:.8}@keyframes _ngcontent-%COMP%_flow-dash{to{stroke-dashoffset:-12}}"]})};export{ee as WidgetBmsComponent};
@@ -1 +1 @@
1
- import {C,e as e$1}from'./chunk-B6bEhzNR.js';import {g as ge$1}from'./chunk-TakPRI3t.js';import {e9 as a,d1 as Hj,w,du as p,aS as De,bu as ut,aY as xe,$ as $j,v as vt,D as Dt,F as Fa,dn as ge,a_ as Gp,cv as G,cw as z,dx as n$1,J as JD,dC as x,c as $h,cn as wd,_ as _w,B as Bh,e as EE,M as Mw,f as eg,K as Kw,P as Pi,T as TT,u as ul}from'./main-BAV5VDOD.js';import {c,e}from'./chunk-Dxlia2NE.js';var ie=["alternatorSvg"];function oe(d,e){d&1&&(Pi(0,"div",3)(1,"div",4),TT(2,"No alternators detected"),ul(),Pi(3,"div",5),TT(4,"Check Signal K alternator paths or select alternators in widget settings."),ul()());}function ne(d){return d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Z=class d{static ALTERNATOR_DESCRIPTOR=a("widget-alternator");static SELF_ROOT_PATH=(()=>{let e=d.ALTERNATOR_DESCRIPTOR?.selfRootPath;if(!e)throw new Error("[WidgetAlternatorComponent] Descriptor missing or selfRootPath not set; check widget registration.");return e})();static ROOT_PATTERN=`${d.SELF_ROOT_PATH}.*`;static PATH_REGEX=new RegExp(`^${ne(d.SELF_ROOT_PATH)}\\.([^.]+)\\.(.+)$`);static VIEWBOX_WIDTH=200;static CARD_HEIGHT=100;static COMPACT_CARD_HEIGHT=100;static CARD_GAP=8;static PATH_BATCH_WINDOW_MS=500;static DEFAULT_CONFIG={color:"contrast",ignoreZones:false,alternator:{trackedDevices:[],optionsById:{}}};id=Hj.required();type=Hj.required();theme=Hj.required();renderMode=Hj(null);runtime=w(p);data=w(De);units=w(ut);destroyRef=w(xe);svgRef=$j.required("alternatorSvg");svg;layer;pendingPathUpdates=new Map;pathBatchTimerId=null;initialPathPaintDone=false;renderFrameId=null;pendingRenderSnapshot=null;discoveredAlternatorIds=vt([]);trackedDevices=vt([]);optionsById=vt({});cardMode=vt({displayMode:"full",metrics:["voltage","current","power","revolutions"]});alternatorsByKey=vt({});visibleAlternatorKeys=Dt(()=>{let e=this.trackedDevices();if(e.length)return e.map(i=>i.key);let r=this.alternatorsByKey(),t=new Set(this.discoveredAlternatorIds());return Object.keys(r).filter(i=>{let a=r[i];return !!a&&t.has(a.id)}).sort((i,a)=>i.localeCompare(a))});visibleAlternators=Dt(()=>{let e=this.visibleAlternatorKeys(),r=this.alternatorsByKey();return e.map(t=>r[t]).filter(t=>!!t)});hasAlternators=Dt(()=>this.visibleAlternators().length>0);activeDisplayMode=Dt(()=>this.renderMode()??this.cardMode().displayMode??"full");isCompactCardMode=Dt(()=>this.activeDisplayMode()==="compact");colorRole=Dt(()=>this.runtime.options()?.color??"contrast");ignoreZones=Dt(()=>this.runtime.options()?.ignoreZones??false);displayLabel=Dt(()=>{let e=this.visibleAlternators();return e.length!==1?"Alternators":this.resolveTitleText(e[0])});labelColor=Dt(()=>{let e=this.theme();return e?c(this.colorRole(),e).dim:"var(--kip-contrast-dim-color)"});widgetColors=Dt(()=>{let e=this.theme();return e?c(this.colorRole(),e):null});displayModels=Dt(()=>{let e$1=this.visibleAlternators(),r=this.theme(),t=this.widgetColors(),i=this.ignoreZones(),a=new Map;e$1.forEach(o=>a.set(o.id,(a.get(o.id)??0)+1));let l=new Set([...a.entries()].filter(([,o])=>o>1).map(([o])=>o)),s={};for(let o of e$1){let c=o.deviceKey??o.id,n=!!o.source&&l.has(o.id),p=this.resolveMostSevereState(o.powerState??null,o.currentState??null,o.voltageState??null,o.temperatureState??null,o.chargingModeState??null,o.revolutionsState??null,o.fieldDriveState??null,o.regulatorTemperatureState??null),T=this.resolveMostSevereState(o.voltageState??null,o.currentState??null),C=this.resolveMostSevereState(o.powerState??null,o.revolutionsState??null,o.temperatureState??null,o.regulatorTemperatureState??null),[u,I]=this.buildMetricRows(o);s[c]={id:o.id,titleText:this.resolveTitleText(o),modeText:this.isCompactCardMode()?"":this.resolveModeText(o),busText:this.isCompactCardMode()?"":n?o.source??"-":o.associatedBus||o.location||"-",metricsLineOne:u,metricsLineTwo:I,stateBarColor:e(p,t?.dim??"var(--kip-contrast-color)",r,i),titleTextColor:e(p,"var(--kip-contrast-color)",r,i),metaTextColor:e(this.resolveMostSevereState(o.chargingModeState??null,o.fieldDriveState??null),"var(--kip-contrast-dim-color)",r,i),primaryMetricsTextColor:e(T,"var(--kip-contrast-color)",r,i),secondaryMetricsTextColor:e(C,"var(--kip-contrast-color)",r,i)};}return s});constructor(){Fa(()=>{let t=this.runtime.options();t&&ge(()=>this.applyConfig(t));}),Fa(()=>{let t=this.displayModels(),i=this.visibleAlternators(),a=this.widgetColors();!this.svg||!a||this.requestRender({alternators:i,displayModels:t,widgetColors:a});});let e=[this.data.subscribePathTreeWithInitial(d.ROOT_PATTERN)],r=false;for(let t of e)if(t.initial.length){r=true;for(let i of t.initial)this.enqueuePathUpdate(i,true);}r&&(this.flushPendingPathUpdates(),this.initialPathPaintDone=true);for(let t of e)t.live$.pipe(Gp(this.destroyRef)).subscribe(i=>{this.enqueuePathUpdate(i);});}ngAfterViewInit(){this.initializeSvg(),this.requestRender();}ngOnDestroy(){this.pathBatchTimerId!==null&&(clearTimeout(this.pathBatchTimerId),this.pathBatchTimerId=null),this.renderFrameId!==null&&(cancelAnimationFrame(this.renderFrameId),this.renderFrameId=null),this.pendingRenderSnapshot=null;}initializeSvg(){this.svg=ge$1(this.svgRef().nativeElement),this.svg.attr("viewBox",`0 0 ${d.VIEWBOX_WIDTH} ${d.CARD_HEIGHT}`).attr("preserveAspectRatio","xMidYMid meet").attr("role","img").attr("aria-label","Alternator View"),this.layer=this.svg.append("g").attr("class","alternator-layer");}applyConfig(e){let r=this.resolveAlternatorConfig(e);this.trackedDevices.set(r.trackedDevices??[]),this.reprojectSnapshotsToDeviceKeys(r.trackedDevices??[]),this.optionsById.set(r.optionsById),this.cardMode.set(this.normalizeCardMode(r.cardMode));}reprojectSnapshotsToDeviceKeys(e){if(!e.length)return;let r=new Map;e.forEach(t=>{let i=r.get(t.id)??[];i.push(t.key),r.set(t.id,i);}),this.alternatorsByKey.update(t=>{let i=t,a=false;return r.forEach((l,s)=>{let o=t[s];if(o){for(let c of l){if(t[c])continue;let n=e.find(p=>p.key===c);a||(i=G({},t),a=true),i[c]=z(G({},o),{source:n?.source??null,deviceKey:c});}a&&i[s]?.deviceKey===void 0&&delete i[s];}}),a?i:t});}resolveAlternatorConfig(e){let r=e.alternator,t=this.normalizeOptionsById(r?.optionsById??r?.alternatorOptionsById);return {trackedDevices:this.normalizeTrackedDevices(r?.trackedDevices),optionsById:t,cardMode:this.normalizeCardMode(r?.cardMode)}}normalizeTrackedDevices(e){if(!Array.isArray(e))return [];let r=new Map;return e.forEach(t=>{if(!t||typeof t!="object")return;let i=t,a=this.normalizeOptionalString(i.id),l=this.normalizeOptionalString(i.source);if(!a||!l)return;let s=this.normalizeOptionalString(i.key)??`${a}||${l}`;r.set(s,{id:a,source:l,key:s});}),[...r.values()].sort((t,i)=>t.key.localeCompare(i.key))}buildIdToDeviceKeysMap(){let e=new Map;return this.trackedDevices().forEach(r=>{let t=e.get(r.id)??[];t.push(r.key),e.set(r.id,t);}),e}normalizeCardMode(e){let r=e&&typeof e=="object"?e:null;if(!r)return {displayMode:"full",metrics:["voltage","current","power","revolutions"]};let t=this.normalizeStringList(r?.metrics);return {displayMode:r?.displayMode==="compact"?"compact":"full",metrics:t.length?t:["voltage","current","power","revolutions"]}}normalizeStringList(e){if(!Array.isArray(e))return [];let r=new Set;return e.forEach(t=>{if(typeof t!="string")return;let i=t.trim();i.length>0&&r.add(i);}),[...r].sort((t,i)=>t.localeCompare(i))}normalizeOptionsById(e){if(!e||typeof e!="object")return {};let r={};return Object.entries(e).forEach(([t])=>{let i=this.normalizeOptionalString(t);i&&(r[i]={});}),r}normalizeOptionalString(e){if(typeof e!="string")return null;let r=e.trim();return r.length>0?r:null}enqueuePathUpdate(e,r=false){let t=this.parsePath(e.path);if(!t)return;let i=e.update?.data?.value??null,a=e.update?.state??null,l=`${t.id}::${t.key}`;if(this.pendingPathUpdates.set(l,{id:t.id,key:t.key,value:i,state:a}),!r){if(!this.initialPathPaintDone){this.initialPathPaintDone=true,this.flushPendingPathUpdates();return}this.pathBatchTimerId===null&&(this.pathBatchTimerId=window.setTimeout(()=>{this.pathBatchTimerId=null,this.flushPendingPathUpdates();},d.PATH_BATCH_WINDOW_MS));}}parsePath(e){let r=e.match(d.PATH_REGEX);return r?{id:r[1],key:r[2]}:null}flushPendingPathUpdates(){if(!this.pendingPathUpdates.size)return;let e=Array.from(this.pendingPathUpdates.values());this.pendingPathUpdates.clear(),new Set(e.map(i=>i.id)).forEach(i=>this.trackDiscoveredAlternator(i));let t=this.buildIdToDeviceKeysMap();this.alternatorsByKey.update(i=>{let a=i,l=false;for(let s of e){let o=t.get(s.id),c=o?.length?o:[s.id];for(let n of c){let p=!!o?.length,T=p?this.trackedDevices().find(Q=>Q.key===n):null,C=a[n]??{id:s.id,source:T?.source??null,deviceKey:p?n:void 0},u=G({},C);if(!this.applyValue(u,s.key,s.value,s.state))continue;let D=u.rawPower!=null?u.rawPower:u.voltage!=null&&u.current!=null?u.voltage*u.current:null;D!=null?u.power=Number.isFinite(D)?D:null:u.power=null,u.rawPower==null&&(u.powerState=this.resolveMostSevereState(u.voltageState??null,u.currentState??null)),l||(a=G({},a),l=true),a[n]=u;}}return l?a:i});}trackDiscoveredAlternator(e){let r=this.discoveredAlternatorIds();r.includes(e)||this.discoveredAlternatorIds.set([...r,e].sort((t,i)=>t.localeCompare(i)));}applyValue(e,r,t,i){switch(r){case "name":return this.setValue(e,"name",this.toStringValue(t));case "location":return this.setValue(e,"location",this.toStringValue(t));case "associatedBus":return this.setValue(e,"associatedBus",this.toStringValue(t));case "chargingMode":return this.setMetricValue(e,"chargingMode","chargingModeState",this.toStringValue(t),i);case "voltage":return this.setMetricValue(e,"voltage","voltageState",this.toNumber(t,"V"),i);case "current":return this.setMetricValue(e,"current","currentState",this.toNumber(t,"A"),i);case "power":case "realPower":return this.setMetricValue(e,"rawPower","powerState",this.toNumber(t,"W"),i);case "temperature":return this.setMetricValue(e,"temperature","temperatureState",this.toNumber(t,this.units.getDefaults().Temperature),i);case "revolutions":return this.setMetricValue(e,"revolutions","revolutionsState",this.toNumber(t,"Hz"),i);case "fieldDrive":return this.setMetricValue(e,"fieldDrive","fieldDriveState",this.toNumber(t,"%"),i);case "regulatorTemperature":return this.setMetricValue(e,"regulatorTemperature","regulatorTemperatureState",this.toNumber(t,this.units.getDefaults().Temperature),i);case "setpointVoltage":return this.setMetricValue(e,"setpointVoltage","setpointVoltageState",this.toNumber(t,"V"),i);case "setpointCurrent":return this.setMetricValue(e,"setpointCurrent","setpointCurrentState",this.toNumber(t,"A"),i);default:return false}}setValue(e,r,t){return Object.is(e[r],t)?false:(e[r]=t,true)}setMetricValue(e,r,t,i,a){let l=!Object.is(e[r],i),s=!Object.is(e[t],a);return !l&&!s?false:(e[r]=i,e[t]=a,true)}requestRender(e){let r=this.widgetColors();!this.svg||!r||(this.pendingRenderSnapshot=e??{alternators:this.visibleAlternators(),displayModels:this.displayModels(),widgetColors:r},this.renderFrameId===null&&(this.renderFrameId=requestAnimationFrame(()=>{this.renderFrameId=null;let t=this.pendingRenderSnapshot;this.pendingRenderSnapshot=null,t&&this.render(t);})));}render(e){if(!this.layer||!this.svg)return;let r=this.isCompactCardMode(),t=r?C:e$1,i=r?d.COMPACT_CARD_HEIGHT:d.CARD_HEIGHT,a=e.alternators.map((n,p)=>({key:n.deviceKey??n.id,alternator:n,y:p*(i+d.CARD_GAP)})),l=a.length?a[a.length-1].y+i:i;this.svg.attr("viewBox",`0 0 ${d.VIEWBOX_WIDTH} ${l}`);let s=this.layer.selectAll("g.alternator-card").data(a,n=>n.key),o=s.enter().append("g").attr("class","alternator-card");o.append("rect").attr("class","alternator-card-bg"),o.append("rect").attr("class","alternator-state-bar"),o.append("text").attr("class","alternator-title"),o.append("text").attr("class","alternator-id"),o.append("text").attr("class","alternator-mode"),o.append("text").attr("class","alternator-bus"),o.append("text").attr("class","alternator-metrics-1"),o.append("text").attr("class","alternator-metrics-2");let c=o.merge(s);c.attr("transform",n=>`translate(0, ${n.y})`),c.select("rect.alternator-card-bg").attr("x",.5).attr("y",.5).attr("rx",t.cardCornerRadius).attr("ry",t.cardCornerRadius).attr("width",d.VIEWBOX_WIDTH-1).attr("height",i-1).attr("stroke","var(--mat-sys-outline-variant)").attr("stroke-width",.5).attr("fill","none"),c.select("rect.alternator-state-bar").attr("x",1.5).attr("y",1.5).attr("rx",t.stateBarCornerRadius).attr("ry",t.stateBarCornerRadius).attr("width",3).attr("height",i-3).attr("fill",n=>e.displayModels[n.key]?.stateBarColor??e.widgetColors.dim),e.alternators.length>1?c.select("text.alternator-title").attr("x",t.titleX).attr("y",t.titleY).attr("font-size",t.titleFontSize).attr("fill",n=>e.displayModels[n.key]?.titleTextColor??"var(--kip-contrast-color)").text(n=>e.displayModels[n.key]?.titleText??this.resolveTitleText(n.alternator)):c.select("text.alternator-title").text(""),c.select("text.alternator-id").attr("x",t.idX).attr("y",t.idY).attr("text-anchor","end").attr("font-size",t.idFontSize).attr("fill","var(--kip-contrast-dim-color)").text(n=>n.alternator.id),c.select("text.alternator-mode").attr("x",t.metaLeftX).attr("y",t.metaY).attr("font-size",t.metaFontSize).attr("opacity",.8).attr("fill",n=>e.displayModels[n.key]?.metaTextColor??"var(--kip-contrast-dim-color)").text(n=>e.displayModels[n.key]?.modeText??""),c.select("text.alternator-bus").attr("x",t.metaRightX).attr("y",t.metaY).attr("text-anchor","end").attr("font-size",t.metaFontSize).attr("opacity",.8).attr("fill",n=>e.displayModels[n.key]?.metaTextColor??"var(--kip-contrast-dim-color)").text(n=>e.displayModels[n.key]?.busText??""),c.select("text.alternator-metrics-1").attr("x",t.lineOneX).attr("y",t.lineOneY).attr("font-size",t.lineOneFontSize).attr("fill",n=>e.displayModels[n.key]?.primaryMetricsTextColor??"var(--kip-contrast-color)").text(n=>e.displayModels[n.key]?.metricsLineOne??""),c.select("text.alternator-metrics-2").attr("x",t.lineTwoX).attr("y",t.lineTwoY).attr("font-size",t.lineTwoFontSize).attr("opacity",.85).attr("fill",n=>e.displayModels[n.key]?.secondaryMetricsTextColor??"var(--kip-contrast-color)").text(n=>e.displayModels[n.key]?.metricsLineTwo??""),s.exit().remove();}displayName(e){return e.name?.trim()||e.id}resolveTitleText(e){return e.name||`Alternator ${e.id}`}resolveModeText(e){return e.chargingMode?`Mode ${e.chargingMode}`:e.fieldDrive!=null?`Field ${e.fieldDrive.toFixed(0)} %`:"Mode -"}buildMetricRows(e){let r=this.cardMode();if(this.activeDisplayMode()==="full")return [`V ${this.formatValue(e.voltage,"V")} A ${this.formatValue(e.current,"A")}`,`P ${this.formatValue(e.power,"W")} RPM ${this.formatRevolutions(e.revolutions)}`];let t=r.metrics.map(l=>this.toMetricLabel(l,e)).filter(l=>!!l);if(!t.length)return ["V - A -","P - RPM -"];let i=t.slice(0,2).join(" "),a=t.slice(2,4).join(" ");return [i||" ",a||" "]}toMetricLabel(e,r){switch(e){case "voltage":return `V ${this.formatValue(r.voltage,"V")}`;case "current":return `A ${this.formatValue(r.current,"A")}`;case "power":return `P ${this.formatValue(r.power,"W")}`;case "temperature":return `T ${this.formatTemperature(r.temperature)}`;case "revolutions":return `RPM ${this.formatRevolutions(r.revolutions)}`;case "fieldDrive":return `FD ${this.formatPercent(r.fieldDrive)}`;case "regulatorTemperature":return `RT ${this.formatTemperature(r.regulatorTemperature)}`;default:return null}}formatValue(e,r){return e==null||Number.isNaN(e)?"-":`${e.toFixed(1)} ${r}`}formatTemperature(e){return e==null||Number.isNaN(e)?"-":`${e.toFixed(1)} ${this.units.getDefaults().Temperature==="celsius"?"\xB0C":"\xB0F"}`}formatRevolutions(e){return e==null||Number.isNaN(e)?"-":Math.round(e*60).toString()}formatPercent(e){return e==null||Number.isNaN(e)?"-":`${e.toFixed(0)} %`}toStringValue(e){return typeof e=="string"?e:null}resolveMostSevereState(...e){return e.some(r=>r===n$1.Alert)?n$1.Alert:e.some(r=>r===n$1.Alarm)?n$1.Alarm:e.some(r=>r===n$1.Warn)?n$1.Warn:e.some(r=>r===n$1.Normal)?n$1.Normal:null}toNumber(e,r){if(e==null||typeof e=="boolean")return null;let t=typeof e=="number"?e:Number(e);if(!Number.isFinite(t))return null;let i=this.units.convertToUnit(r,t);return Number.isFinite(i)?i:t}static \u0275fac=function(r){return new(r||d)};static \u0275cmp=JD({type:d,selectors:[["widget-alternator"]],viewQuery:function(r,t){r&1&&eg(t.svgRef,ie,5),r&2&&Kw();},inputs:{id:[1,"id"],type:[1,"type"],theme:[1,"theme"],renderMode:[1,"renderMode"]},decls:4,vars:3,consts:[["alternatorSvg",""],[3,"text","color"],["aria-hidden","false",1,"alternator-svg"],[1,"alternator-empty"],[1,"alternator-empty-title"],[1,"alternator-empty-sub"]],template:function(r,t){r&1&&($h(0,"widget-title",1),wd(),$h(1,"svg",2,0),_w(3,oe,5,0,"div",3)),r&2&&(Bh("text",t.displayLabel())("color",t.labelColor()),EE(3),Mw(t.hasAlternators()?-1:3));},dependencies:[x],styles:["[_nghost-%COMP%]{display:block;height:100%;width:100%;position:relative;overflow:hidden}.alternator-svg[_ngcontent-%COMP%]{display:block;position:absolute;left:0;right:0;top:15%;height:85%;width:100%;overflow:hidden;z-index:20;padding:0 10px 10px}.alternator-empty[_ngcontent-%COMP%]{position:absolute;inset:0;margin:10px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;text-align:center;color:var(--mat-sys-on-surface);background:color-mix(in srgb,var(--kip-widget-card-background-color) 92%,transparent)}.alternator-empty-title[_ngcontent-%COMP%]{font-size:18px;font-weight:600}.alternator-empty-sub[_ngcontent-%COMP%]{font-size:14px;opacity:.8}"]})};export{Z as WidgetAlternatorComponent};
1
+ import {C,e as e$1}from'./chunk-CyURmwWh.js';import {g as ge$1}from'./chunk-TakPRI3t.js';import {e9 as a,d1 as Hj,w,du as p,aS as De,bu as ut,aY as xe,$ as $j,v as vt,D as Dt,F as Fa,dn as ge,a_ as Gp,cv as G,cw as z,dx as n$1,J as JD,dC as x,c as $h,cn as wd,_ as _w,B as Bh,e as EE,M as Mw,f as eg,K as Kw,P as Pi,T as TT,u as ul}from'./main-BNR44HGB.js';import {c,e}from'./chunk-D_wrJJxl.js';var ie=["alternatorSvg"];function oe(d,e){d&1&&(Pi(0,"div",3)(1,"div",4),TT(2,"No alternators detected"),ul(),Pi(3,"div",5),TT(4,"Check Signal K alternator paths or select alternators in widget settings."),ul()());}function ne(d){return d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Z=class d{static ALTERNATOR_DESCRIPTOR=a("widget-alternator");static SELF_ROOT_PATH=(()=>{let e=d.ALTERNATOR_DESCRIPTOR?.selfRootPath;if(!e)throw new Error("[WidgetAlternatorComponent] Descriptor missing or selfRootPath not set; check widget registration.");return e})();static ROOT_PATTERN=`${d.SELF_ROOT_PATH}.*`;static PATH_REGEX=new RegExp(`^${ne(d.SELF_ROOT_PATH)}\\.([^.]+)\\.(.+)$`);static VIEWBOX_WIDTH=200;static CARD_HEIGHT=100;static COMPACT_CARD_HEIGHT=100;static CARD_GAP=8;static PATH_BATCH_WINDOW_MS=500;static DEFAULT_CONFIG={color:"contrast",ignoreZones:false,alternator:{trackedDevices:[],optionsById:{}}};id=Hj.required();type=Hj.required();theme=Hj.required();renderMode=Hj(null);runtime=w(p);data=w(De);units=w(ut);destroyRef=w(xe);svgRef=$j.required("alternatorSvg");svg;layer;pendingPathUpdates=new Map;pathBatchTimerId=null;initialPathPaintDone=false;renderFrameId=null;pendingRenderSnapshot=null;discoveredAlternatorIds=vt([]);trackedDevices=vt([]);optionsById=vt({});cardMode=vt({displayMode:"full",metrics:["voltage","current","power","revolutions"]});alternatorsByKey=vt({});visibleAlternatorKeys=Dt(()=>{let e=this.trackedDevices();if(e.length)return e.map(i=>i.key);let r=this.alternatorsByKey(),t=new Set(this.discoveredAlternatorIds());return Object.keys(r).filter(i=>{let a=r[i];return !!a&&t.has(a.id)}).sort((i,a)=>i.localeCompare(a))});visibleAlternators=Dt(()=>{let e=this.visibleAlternatorKeys(),r=this.alternatorsByKey();return e.map(t=>r[t]).filter(t=>!!t)});hasAlternators=Dt(()=>this.visibleAlternators().length>0);activeDisplayMode=Dt(()=>this.renderMode()??this.cardMode().displayMode??"full");isCompactCardMode=Dt(()=>this.activeDisplayMode()==="compact");colorRole=Dt(()=>this.runtime.options()?.color??"contrast");ignoreZones=Dt(()=>this.runtime.options()?.ignoreZones??false);displayLabel=Dt(()=>{let e=this.visibleAlternators();return e.length!==1?"Alternators":this.resolveTitleText(e[0])});labelColor=Dt(()=>{let e=this.theme();return e?c(this.colorRole(),e).dim:"var(--kip-contrast-dim-color)"});widgetColors=Dt(()=>{let e=this.theme();return e?c(this.colorRole(),e):null});displayModels=Dt(()=>{let e$1=this.visibleAlternators(),r=this.theme(),t=this.widgetColors(),i=this.ignoreZones(),a=new Map;e$1.forEach(o=>a.set(o.id,(a.get(o.id)??0)+1));let l=new Set([...a.entries()].filter(([,o])=>o>1).map(([o])=>o)),s={};for(let o of e$1){let c=o.deviceKey??o.id,n=!!o.source&&l.has(o.id),p=this.resolveMostSevereState(o.powerState??null,o.currentState??null,o.voltageState??null,o.temperatureState??null,o.chargingModeState??null,o.revolutionsState??null,o.fieldDriveState??null,o.regulatorTemperatureState??null),T=this.resolveMostSevereState(o.voltageState??null,o.currentState??null),C=this.resolveMostSevereState(o.powerState??null,o.revolutionsState??null,o.temperatureState??null,o.regulatorTemperatureState??null),[u,I]=this.buildMetricRows(o);s[c]={id:o.id,titleText:this.resolveTitleText(o),modeText:this.isCompactCardMode()?"":this.resolveModeText(o),busText:this.isCompactCardMode()?"":n?o.source??"-":o.associatedBus||o.location||"-",metricsLineOne:u,metricsLineTwo:I,stateBarColor:e(p,t?.dim??"var(--kip-contrast-color)",r,i),titleTextColor:e(p,"var(--kip-contrast-color)",r,i),metaTextColor:e(this.resolveMostSevereState(o.chargingModeState??null,o.fieldDriveState??null),"var(--kip-contrast-dim-color)",r,i),primaryMetricsTextColor:e(T,"var(--kip-contrast-color)",r,i),secondaryMetricsTextColor:e(C,"var(--kip-contrast-color)",r,i)};}return s});constructor(){Fa(()=>{let t=this.runtime.options();t&&ge(()=>this.applyConfig(t));}),Fa(()=>{let t=this.displayModels(),i=this.visibleAlternators(),a=this.widgetColors();!this.svg||!a||this.requestRender({alternators:i,displayModels:t,widgetColors:a});});let e=[this.data.subscribePathTreeWithInitial(d.ROOT_PATTERN)],r=false;for(let t of e)if(t.initial.length){r=true;for(let i of t.initial)this.enqueuePathUpdate(i,true);}r&&(this.flushPendingPathUpdates(),this.initialPathPaintDone=true);for(let t of e)t.live$.pipe(Gp(this.destroyRef)).subscribe(i=>{this.enqueuePathUpdate(i);});}ngAfterViewInit(){this.initializeSvg(),this.requestRender();}ngOnDestroy(){this.pathBatchTimerId!==null&&(clearTimeout(this.pathBatchTimerId),this.pathBatchTimerId=null),this.renderFrameId!==null&&(cancelAnimationFrame(this.renderFrameId),this.renderFrameId=null),this.pendingRenderSnapshot=null;}initializeSvg(){this.svg=ge$1(this.svgRef().nativeElement),this.svg.attr("viewBox",`0 0 ${d.VIEWBOX_WIDTH} ${d.CARD_HEIGHT}`).attr("preserveAspectRatio","xMidYMid meet").attr("role","img").attr("aria-label","Alternator View"),this.layer=this.svg.append("g").attr("class","alternator-layer");}applyConfig(e){let r=this.resolveAlternatorConfig(e);this.trackedDevices.set(r.trackedDevices??[]),this.reprojectSnapshotsToDeviceKeys(r.trackedDevices??[]),this.optionsById.set(r.optionsById),this.cardMode.set(this.normalizeCardMode(r.cardMode));}reprojectSnapshotsToDeviceKeys(e){if(!e.length)return;let r=new Map;e.forEach(t=>{let i=r.get(t.id)??[];i.push(t.key),r.set(t.id,i);}),this.alternatorsByKey.update(t=>{let i=t,a=false;return r.forEach((l,s)=>{let o=t[s];if(o){for(let c of l){if(t[c])continue;let n=e.find(p=>p.key===c);a||(i=G({},t),a=true),i[c]=z(G({},o),{source:n?.source??null,deviceKey:c});}a&&i[s]?.deviceKey===void 0&&delete i[s];}}),a?i:t});}resolveAlternatorConfig(e){let r=e.alternator,t=this.normalizeOptionsById(r?.optionsById??r?.alternatorOptionsById);return {trackedDevices:this.normalizeTrackedDevices(r?.trackedDevices),optionsById:t,cardMode:this.normalizeCardMode(r?.cardMode)}}normalizeTrackedDevices(e){if(!Array.isArray(e))return [];let r=new Map;return e.forEach(t=>{if(!t||typeof t!="object")return;let i=t,a=this.normalizeOptionalString(i.id),l=this.normalizeOptionalString(i.source);if(!a||!l)return;let s=this.normalizeOptionalString(i.key)??`${a}||${l}`;r.set(s,{id:a,source:l,key:s});}),[...r.values()].sort((t,i)=>t.key.localeCompare(i.key))}buildIdToDeviceKeysMap(){let e=new Map;return this.trackedDevices().forEach(r=>{let t=e.get(r.id)??[];t.push(r.key),e.set(r.id,t);}),e}normalizeCardMode(e){let r=e&&typeof e=="object"?e:null;if(!r)return {displayMode:"full",metrics:["voltage","current","power","revolutions"]};let t=this.normalizeStringList(r?.metrics);return {displayMode:r?.displayMode==="compact"?"compact":"full",metrics:t.length?t:["voltage","current","power","revolutions"]}}normalizeStringList(e){if(!Array.isArray(e))return [];let r=new Set;return e.forEach(t=>{if(typeof t!="string")return;let i=t.trim();i.length>0&&r.add(i);}),[...r].sort((t,i)=>t.localeCompare(i))}normalizeOptionsById(e){if(!e||typeof e!="object")return {};let r={};return Object.entries(e).forEach(([t])=>{let i=this.normalizeOptionalString(t);i&&(r[i]={});}),r}normalizeOptionalString(e){if(typeof e!="string")return null;let r=e.trim();return r.length>0?r:null}enqueuePathUpdate(e,r=false){let t=this.parsePath(e.path);if(!t)return;let i=e.update?.data?.value??null,a=e.update?.state??null,l=`${t.id}::${t.key}`;if(this.pendingPathUpdates.set(l,{id:t.id,key:t.key,value:i,state:a}),!r){if(!this.initialPathPaintDone){this.initialPathPaintDone=true,this.flushPendingPathUpdates();return}this.pathBatchTimerId===null&&(this.pathBatchTimerId=window.setTimeout(()=>{this.pathBatchTimerId=null,this.flushPendingPathUpdates();},d.PATH_BATCH_WINDOW_MS));}}parsePath(e){let r=e.match(d.PATH_REGEX);return r?{id:r[1],key:r[2]}:null}flushPendingPathUpdates(){if(!this.pendingPathUpdates.size)return;let e=Array.from(this.pendingPathUpdates.values());this.pendingPathUpdates.clear(),new Set(e.map(i=>i.id)).forEach(i=>this.trackDiscoveredAlternator(i));let t=this.buildIdToDeviceKeysMap();this.alternatorsByKey.update(i=>{let a=i,l=false;for(let s of e){let o=t.get(s.id),c=o?.length?o:[s.id];for(let n of c){let p=!!o?.length,T=p?this.trackedDevices().find(Q=>Q.key===n):null,C=a[n]??{id:s.id,source:T?.source??null,deviceKey:p?n:void 0},u=G({},C);if(!this.applyValue(u,s.key,s.value,s.state))continue;let D=u.rawPower!=null?u.rawPower:u.voltage!=null&&u.current!=null?u.voltage*u.current:null;D!=null?u.power=Number.isFinite(D)?D:null:u.power=null,u.rawPower==null&&(u.powerState=this.resolveMostSevereState(u.voltageState??null,u.currentState??null)),l||(a=G({},a),l=true),a[n]=u;}}return l?a:i});}trackDiscoveredAlternator(e){let r=this.discoveredAlternatorIds();r.includes(e)||this.discoveredAlternatorIds.set([...r,e].sort((t,i)=>t.localeCompare(i)));}applyValue(e,r,t,i){switch(r){case "name":return this.setValue(e,"name",this.toStringValue(t));case "location":return this.setValue(e,"location",this.toStringValue(t));case "associatedBus":return this.setValue(e,"associatedBus",this.toStringValue(t));case "chargingMode":return this.setMetricValue(e,"chargingMode","chargingModeState",this.toStringValue(t),i);case "voltage":return this.setMetricValue(e,"voltage","voltageState",this.toNumber(t,"V"),i);case "current":return this.setMetricValue(e,"current","currentState",this.toNumber(t,"A"),i);case "power":case "realPower":return this.setMetricValue(e,"rawPower","powerState",this.toNumber(t,"W"),i);case "temperature":return this.setMetricValue(e,"temperature","temperatureState",this.toNumber(t,this.units.getDefaults().Temperature),i);case "revolutions":return this.setMetricValue(e,"revolutions","revolutionsState",this.toNumber(t,"Hz"),i);case "fieldDrive":return this.setMetricValue(e,"fieldDrive","fieldDriveState",this.toNumber(t,"%"),i);case "regulatorTemperature":return this.setMetricValue(e,"regulatorTemperature","regulatorTemperatureState",this.toNumber(t,this.units.getDefaults().Temperature),i);case "setpointVoltage":return this.setMetricValue(e,"setpointVoltage","setpointVoltageState",this.toNumber(t,"V"),i);case "setpointCurrent":return this.setMetricValue(e,"setpointCurrent","setpointCurrentState",this.toNumber(t,"A"),i);default:return false}}setValue(e,r,t){return Object.is(e[r],t)?false:(e[r]=t,true)}setMetricValue(e,r,t,i,a){let l=!Object.is(e[r],i),s=!Object.is(e[t],a);return !l&&!s?false:(e[r]=i,e[t]=a,true)}requestRender(e){let r=this.widgetColors();!this.svg||!r||(this.pendingRenderSnapshot=e??{alternators:this.visibleAlternators(),displayModels:this.displayModels(),widgetColors:r},this.renderFrameId===null&&(this.renderFrameId=requestAnimationFrame(()=>{this.renderFrameId=null;let t=this.pendingRenderSnapshot;this.pendingRenderSnapshot=null,t&&this.render(t);})));}render(e){if(!this.layer||!this.svg)return;let r=this.isCompactCardMode(),t=r?C:e$1,i=r?d.COMPACT_CARD_HEIGHT:d.CARD_HEIGHT,a=e.alternators.map((n,p)=>({key:n.deviceKey??n.id,alternator:n,y:p*(i+d.CARD_GAP)})),l=a.length?a[a.length-1].y+i:i;this.svg.attr("viewBox",`0 0 ${d.VIEWBOX_WIDTH} ${l}`);let s=this.layer.selectAll("g.alternator-card").data(a,n=>n.key),o=s.enter().append("g").attr("class","alternator-card");o.append("rect").attr("class","alternator-card-bg"),o.append("rect").attr("class","alternator-state-bar"),o.append("text").attr("class","alternator-title"),o.append("text").attr("class","alternator-id"),o.append("text").attr("class","alternator-mode"),o.append("text").attr("class","alternator-bus"),o.append("text").attr("class","alternator-metrics-1"),o.append("text").attr("class","alternator-metrics-2");let c=o.merge(s);c.attr("transform",n=>`translate(0, ${n.y})`),c.select("rect.alternator-card-bg").attr("x",.5).attr("y",.5).attr("rx",t.cardCornerRadius).attr("ry",t.cardCornerRadius).attr("width",d.VIEWBOX_WIDTH-1).attr("height",i-1).attr("stroke","var(--mat-sys-outline-variant)").attr("stroke-width",.5).attr("fill","none"),c.select("rect.alternator-state-bar").attr("x",1.5).attr("y",1.5).attr("rx",t.stateBarCornerRadius).attr("ry",t.stateBarCornerRadius).attr("width",3).attr("height",i-3).attr("fill",n=>e.displayModels[n.key]?.stateBarColor??e.widgetColors.dim),e.alternators.length>1?c.select("text.alternator-title").attr("x",t.titleX).attr("y",t.titleY).attr("font-size",t.titleFontSize).attr("fill",n=>e.displayModels[n.key]?.titleTextColor??"var(--kip-contrast-color)").text(n=>e.displayModels[n.key]?.titleText??this.resolveTitleText(n.alternator)):c.select("text.alternator-title").text(""),c.select("text.alternator-id").attr("x",t.idX).attr("y",t.idY).attr("text-anchor","end").attr("font-size",t.idFontSize).attr("fill","var(--kip-contrast-dim-color)").text(n=>n.alternator.id),c.select("text.alternator-mode").attr("x",t.metaLeftX).attr("y",t.metaY).attr("font-size",t.metaFontSize).attr("opacity",.8).attr("fill",n=>e.displayModels[n.key]?.metaTextColor??"var(--kip-contrast-dim-color)").text(n=>e.displayModels[n.key]?.modeText??""),c.select("text.alternator-bus").attr("x",t.metaRightX).attr("y",t.metaY).attr("text-anchor","end").attr("font-size",t.metaFontSize).attr("opacity",.8).attr("fill",n=>e.displayModels[n.key]?.metaTextColor??"var(--kip-contrast-dim-color)").text(n=>e.displayModels[n.key]?.busText??""),c.select("text.alternator-metrics-1").attr("x",t.lineOneX).attr("y",t.lineOneY).attr("font-size",t.lineOneFontSize).attr("fill",n=>e.displayModels[n.key]?.primaryMetricsTextColor??"var(--kip-contrast-color)").text(n=>e.displayModels[n.key]?.metricsLineOne??""),c.select("text.alternator-metrics-2").attr("x",t.lineTwoX).attr("y",t.lineTwoY).attr("font-size",t.lineTwoFontSize).attr("opacity",.85).attr("fill",n=>e.displayModels[n.key]?.secondaryMetricsTextColor??"var(--kip-contrast-color)").text(n=>e.displayModels[n.key]?.metricsLineTwo??""),s.exit().remove();}displayName(e){return e.name?.trim()||e.id}resolveTitleText(e){return e.name||`Alternator ${e.id}`}resolveModeText(e){return e.chargingMode?`Mode ${e.chargingMode}`:e.fieldDrive!=null?`Field ${e.fieldDrive.toFixed(0)} %`:"Mode -"}buildMetricRows(e){let r=this.cardMode();if(this.activeDisplayMode()==="full")return [`V ${this.formatValue(e.voltage,"V")} A ${this.formatValue(e.current,"A")}`,`P ${this.formatValue(e.power,"W")} RPM ${this.formatRevolutions(e.revolutions)}`];let t=r.metrics.map(l=>this.toMetricLabel(l,e)).filter(l=>!!l);if(!t.length)return ["V - A -","P - RPM -"];let i=t.slice(0,2).join(" "),a=t.slice(2,4).join(" ");return [i||" ",a||" "]}toMetricLabel(e,r){switch(e){case "voltage":return `V ${this.formatValue(r.voltage,"V")}`;case "current":return `A ${this.formatValue(r.current,"A")}`;case "power":return `P ${this.formatValue(r.power,"W")}`;case "temperature":return `T ${this.formatTemperature(r.temperature)}`;case "revolutions":return `RPM ${this.formatRevolutions(r.revolutions)}`;case "fieldDrive":return `FD ${this.formatPercent(r.fieldDrive)}`;case "regulatorTemperature":return `RT ${this.formatTemperature(r.regulatorTemperature)}`;default:return null}}formatValue(e,r){return e==null||Number.isNaN(e)?"-":`${e.toFixed(1)} ${r}`}formatTemperature(e){return e==null||Number.isNaN(e)?"-":`${e.toFixed(1)} ${this.units.getDefaults().Temperature==="celsius"?"\xB0C":"\xB0F"}`}formatRevolutions(e){return e==null||Number.isNaN(e)?"-":Math.round(e*60).toString()}formatPercent(e){return e==null||Number.isNaN(e)?"-":`${e.toFixed(0)} %`}toStringValue(e){return typeof e=="string"?e:null}resolveMostSevereState(...e){return e.some(r=>r===n$1.Alert)?n$1.Alert:e.some(r=>r===n$1.Alarm)?n$1.Alarm:e.some(r=>r===n$1.Warn)?n$1.Warn:e.some(r=>r===n$1.Normal)?n$1.Normal:null}toNumber(e,r){if(e==null||typeof e=="boolean")return null;let t=typeof e=="number"?e:Number(e);if(!Number.isFinite(t))return null;let i=this.units.convertToUnit(r,t);return Number.isFinite(i)?i:t}static \u0275fac=function(r){return new(r||d)};static \u0275cmp=JD({type:d,selectors:[["widget-alternator"]],viewQuery:function(r,t){r&1&&eg(t.svgRef,ie,5),r&2&&Kw();},inputs:{id:[1,"id"],type:[1,"type"],theme:[1,"theme"],renderMode:[1,"renderMode"]},decls:4,vars:3,consts:[["alternatorSvg",""],[3,"text","color"],["aria-hidden","false",1,"alternator-svg"],[1,"alternator-empty"],[1,"alternator-empty-title"],[1,"alternator-empty-sub"]],template:function(r,t){r&1&&($h(0,"widget-title",1),wd(),$h(1,"svg",2,0),_w(3,oe,5,0,"div",3)),r&2&&(Bh("text",t.displayLabel())("color",t.labelColor()),EE(3),Mw(t.hasAlternators()?-1:3));},dependencies:[x],styles:["[_nghost-%COMP%]{display:block;height:100%;width:100%;position:relative;overflow:hidden}.alternator-svg[_ngcontent-%COMP%]{display:block;position:absolute;left:0;right:0;top:15%;height:85%;width:100%;overflow:hidden;z-index:20;padding:0 10px 10px}.alternator-empty[_ngcontent-%COMP%]{position:absolute;inset:0;margin:10px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;text-align:center;color:var(--mat-sys-on-surface);background:color-mix(in srgb,var(--kip-widget-card-background-color) 92%,transparent)}.alternator-empty-title[_ngcontent-%COMP%]{font-size:18px;font-weight:600}.alternator-empty-sub[_ngcontent-%COMP%]{font-size:14px;opacity:.8}"]})};export{Z as WidgetAlternatorComponent};
@@ -1 +1 @@
1
- import'./chunk-By8ZVvDx.js';import {d1 as Hj,w,du as p,ao as ue,dy as K,dw as S,aZ as F,bu as ut,i as ir,$ as $j,a6 as Lr,b0 as Wl,W as Wp,E as Em,F as Fa,dn as ge,cw as z,cv as G,J as JD,cp as Uh,f as eg,K as Kw}from'./main-BAV5VDOD.js';var tt=["widgetDataChart"],mt=(()=>{class O{id=Hj.required();type=Hj.required();theme=Hj.required();runtime=w(p,{optional:true});static DEFAULT_CONFIG={filterSelfPaths:true,color:"contrast",timeScale:"Last 30 Minutes"};ngZone=w(ue);_dataset=w(K);datasetLifecycle=w(S);canvasService=w(F);unitsService=w(ut);responsive=w(ir);isPhonePortrait;widgetDataChart=$j("widgetDataChart",{read:Lr});lineChartData={datasets:[]};lineChartOptions={parsing:false,datasets:{line:{pointRadius:0,pointHoverRadius:0,tension:.3}},animations:{tension:{easing:"easeInOutCubic"}}};lineChartType="line";chart=null;_dsDirectionSub=null;_dsSpeedSub=null;_chartUpdateRafId=null;datasetConfig=null;dataSourceInfo=null;xCenter=null;xStep=null;xCenterSpeed=null;xStepSpeed=null;CENTER_LINE_WIDTH=4;GRID_LINE_WIDTH=1;EDGE_EXTEND_UP_PX=42;EDGE_SPEED_LABEL_OFFSET=5;EDGE_DIR_LABEL_OFFSET=5;TICK_LABEL_FONT_SIZE=20;TICK_LABEL_PHONE_PORTRAIT_FONT_SIZE=11;CENTER_LABEL_FONT_SIZE=22;CENTER_LABEL_PHONE_PORTRAIT_FONT_SIZE=13;SPEED_VALUE_FONT_SIZE=62;SPEED_VALUE_PHONE_PORTRAIT_FONT_SIZE=32;TOP_VALUE_Y_OFFSET=62;TOP_VALUE_PHONE_PORTRAIT_Y_OFFSET=44;TOP_UNIT_Y_OFFSET=51;TOP_UNIT_PHONE_PORTRAIT_Y_OFFSET=38;UNIT_FONT_SIZE=28;UNIT_PHONE_PORTRAIT_FONT_SIZE=14;UNIT_PADDING=8;UNIT_PHONE_PORTRAIT_PADDING=3;isPortrait=()=>this.isPhonePortrait()?.matches===true;gridBackgroundPlugin={id:"xSpeedGridBackground",beforeDraw:e=>{let t=e.chartArea;if(!t)return;let a=e.ctx,i=this.theme();a.save(),a.globalCompositeOperation="destination-over",a.fillStyle=i.background,a.fillRect(t.left,t.top,t.width/2,t.height),a.restore();}};centerTickPlugin={id:"centerTickStyle",afterDraw:e=>{let t=e.ctx,a=e.chartArea,i=this.theme(),n=this.getThemeColors(),o=Wl.defaults.font,u=e.scales,c=e.options?.scales,r=e.data?.datasets?.[0]?.data,d=e.data?.datasets?.[5]?.data,f=(r?.length??0)>=2&&(d?.length??0)>=2,h=(p,g)=>{let l=u?.[p],x=c;if(!l)return;let E=l,v=x?.[p]?.min??E.min,C=x?.[p]?.max??E.max;if(typeof v!="number"||typeof C!="number"||!isFinite(v)||!isFinite(C))return;let y=(v+C)/2,L=l.getPixelForValue(y);t.save(),t.strokeStyle=i.contrastDim,t.lineWidth=this.CENTER_LINE_WIDTH,t.beginPath(),t.moveTo(L,a.top),t.lineTo(L,a.bottom),t.stroke(),t.restore(),t.save(),t.fillStyle=i.contrastDim,t.font=this.isPortrait()?`bold ${this.CENTER_LABEL_PHONE_PORTRAIT_FONT_SIZE}px ${o.family}`:`bold ${this.CENTER_LABEL_FONT_SIZE}px ${o.family}`,t.textAlign="center",t.textBaseline="top";let J=this.axisTopLabelY(l);t.fillText(g(y),L,J),t.restore();};h("x",p=>`${((p%360+360)%360).toFixed(0)}\xB0`),h("xSpeed",p=>`${p.toFixed(1)}`);let s=u?.xSpeed;if(s){let p=c,g=s,l=p?.xSpeed?.max??g.max;if(typeof l=="number"&&isFinite(l)){let x=s.getPixelForValue(l);t.save(),t.fillStyle=this.resolveTickColor(e,s,l),t.font=this.isPortrait()?`normal ${this.TICK_LABEL_PHONE_PORTRAIT_FONT_SIZE}px ${o.family}`:`normal ${this.TICK_LABEL_FONT_SIZE}px ${o.family}`,t.textAlign="right",t.textBaseline="top";let E=this.axisTopLabelY(s),v=this.xStepSpeed??1,C=Math.max(0,Math.min(3,Math.ceil(-Math.log10(v))));t.fillText(`${l.toFixed(C)}`,x-this.EDGE_SPEED_LABEL_OFFSET,E),t.restore(),t.save(),t.strokeStyle=i.contrastDim,t.lineWidth=this.GRID_LINE_WIDTH,t.beginPath();let y=Math.round(x)+.5;t.moveTo(y,a.bottom),t.lineTo(y,a.top-this.EDGE_EXTEND_UP_PX),t.stroke(),t.restore();}}let m=u?.x;if(m){let p=c,g=m,l=p?.x?.min??g.min;if(typeof l=="number"&&isFinite(l)){let x=m.getPixelForValue(l);t.save(),t.fillStyle=this.resolveTickColor(e,m,l),t.font=this.isPortrait()?`normal ${this.TICK_LABEL_PHONE_PORTRAIT_FONT_SIZE}px ${o.family}`:`normal ${this.TICK_LABEL_FONT_SIZE}px ${o.family}`,t.textAlign="left",t.textBaseline="top";let E=this.axisTopLabelY(m),v=this.normalizeAngle(l);t.fillText(`${v.toFixed(0)}\xB0`,x+this.EDGE_DIR_LABEL_OFFSET,E),t.restore();}}let _=e.data?.datasets,S=_?.[5]?.data,D=S?.length?S.length-1:-1,b=D>=0?S[D]?.x:void 0;if(typeof b=="number"&&isFinite(b)){t.save(),t.fillStyle=n.chartValue,t.font=this.isPortrait()?`bold ${this.SPEED_VALUE_PHONE_PORTRAIT_FONT_SIZE}px ${o.family}`:`bold ${this.SPEED_VALUE_FONT_SIZE}px ${o.family}`,t.textAlign="center",t.textBaseline="middle";let p=`${b.toFixed(1)}`,g=a.left+a.width/4,l=a.top-(this.isPortrait()?this.TOP_VALUE_PHONE_PORTRAIT_Y_OFFSET:this.TOP_VALUE_Y_OFFSET);t.fillText(p,g,l);let x=t.measureText(p),E=g+x.width/2+(this.isPortrait()?this.UNIT_PHONE_PORTRAIT_PADDING:this.UNIT_PADDING),v=a.top-(this.isPortrait()?this.TOP_UNIT_PHONE_PORTRAIT_Y_OFFSET:this.TOP_UNIT_Y_OFFSET);t.font=this.isPortrait()?`bold ${this.UNIT_PHONE_PORTRAIT_FONT_SIZE}px ${o.family}`:`bold ${this.UNIT_FONT_SIZE}px ${o.family}`,t.textAlign="left",t.fillText("kts",E,v),t.restore();}let F=_?.[0]?.data,N=F?.length?F.length-1:-1,T=N>=0?F[N]?.x:void 0;if(typeof T=="number"&&isFinite(T)){let p=this.normalizeAngle(T);t.save(),t.fillStyle=n.chartValue,t.font=this.isPortrait()?`bold ${this.SPEED_VALUE_PHONE_PORTRAIT_FONT_SIZE}px ${o.family}`:`bold ${this.SPEED_VALUE_FONT_SIZE}px ${o.family}`,t.textAlign="center",t.textBaseline="middle",t.fillText(`${p.toFixed(0)}\xB0`,a.left+3*a.width/4,a.top-(this.isPortrait()?this.TOP_VALUE_PHONE_PORTRAIT_Y_OFFSET:this.TOP_VALUE_Y_OFFSET)),t.restore();}if(!f){let p=Math.min(a.width*.7,420),g=90,l=a.left+(a.width-p)/2,x=a.top+(a.height-g)/2;t.save(),t.globalAlpha=.82,t.fillStyle=i.background,t.fillRect(l,x,p,g),t.restore(),t.save(),t.strokeStyle=i.contrastDim,t.lineWidth=2,t.strokeRect(l,x,p,g),t.restore(),t.save(),t.fillStyle=this.getThemeColors().chartLabel,t.textAlign="center",t.textBaseline="middle",t.font=`bold 18px ${o.family}`,t.fillText("Data acquisition...",l+p/2,x+g/2),t.restore();}}};constructor(){this.isPhonePortrait=Wp(this.responsive.observe(Em.HandsetPortrait),{initialValue:void 0}),Fa(()=>{let e=this.theme(),t=this.runtime?.options();!e||!t||ge(()=>{this.datasetConfig&&this.chart&&(this.setChartOptions(),this.setDatasetsColors(),this.ngZone.runOutsideAngular(()=>this.chart?.update("none")));});}),Fa(()=>{let e=this.runtime?.options();if(!e)return;!this.datasetConfig||this.datasetConfig.timeScaleFormat!==e.timeScale?(this.syncServiceDatasets(),this.startWidget()):this.chart&&this.setChartOptions();});}startWidget(){if(this.widgetDataChart()&&(this.datasetConfig=this._dataset.getDatasetConfig(`${this.id()}-twd`)??null,this.dataSourceInfo=this._dataset.getDataSourceInfo(`${this.id()}-twd`)??null,!!this.datasetConfig)){if(this.createDatasets(),this.setChartOptions(),this.chart)this.ngZone.runOutsideAngular(()=>this.chart?.update("none"));else {let e=this.widgetDataChart()?.nativeElement.getContext("2d");if(!e)return;this.chart=new Wl(e,{type:this.lineChartType,data:this.lineChartData,options:this.lineChartOptions,plugins:[this.gridBackgroundPlugin,this.centerTickPlugin]}),this.ngZone.runOutsideAngular(()=>this.chart?.update("none"));}this.startStreaming();}}syncServiceDatasets(){let e=this.runtime?.options();!e||e.timeScale===""||this.datasetLifecycle.syncWindTrendsDatasets(this.id(),e.timeScale);}setChartOptions(){let e=this.datasetConfig,t=this.dataSourceInfo;if(!e||!t)return;this.lineChartOptions.maintainAspectRatio=false,this.lineChartOptions.animation=false,this.lineChartOptions.indexAxis="y";let a=0,i=360,n=(i-a)/4,o=0,u=20,c=(u-o)/4;this.lineChartOptions.scales={y:{type:"linear",display:true,position:"right",reverse:true,title:{display:true,text:`${e.timeScaleFormat}`,align:"center"},ticks:{count:6,autoSkip:false,includeBounds:true,align:"inner",major:{enabled:true},font:this.isPortrait()?{size:12}:{size:16},callback:r=>{let d=Number(r),f=e.timeScaleFormat,h=this.getWindowMs(f);return f==="Last 5 Minutes"?`${Math.round(d/6e4)}'`:h>=10*6e4?`${Math.round(d/6e4)}'`:`${Math.round(d/1e3)}"`}},grid:{display:true,color:this.theme().contrastDimmer}},x:{type:"linear",position:"top",stack:"trends",beginAtZero:false,bounds:"ticks",min:a,max:i,title:{display:false},ticks:{count:5,align:"inner",autoSkip:false,includeBounds:true,stepSize:n,minRotation:0,maxRotation:0,callback:r=>{let d=Number(r),f=this.xCenter??Number.NaN;if(this.nearlyEqual(d,f))return "";let s=this.chart?.options?.scales?.x?.min;return typeof s=="number"&&this.nearlyEqual(d,s)?"":`${((d%360+360)%360).toFixed(0)}\xB0`},font:r=>{let d=r.tick?.value??Number.NaN,f=this.xCenter??Number.NaN,h=this.nearlyEqual(d,f);return this.isPortrait()?{size:11,weight:h?"bold":"normal"}:{size:20,weight:h?"bold":"normal"}},color:r=>{let d=r.tick?.value??Number.NaN,f=this.xCenter??Number.NaN;return this.nearlyEqual(d,f)?this.theme().contrast:void 0}},grid:{display:true,color:r=>{let d=r.tick?.value??Number.NaN,f=r.scale,h=this.chart?.options?.scales,s=f,m=h?.x?.min??s.min;return this.nearlyEqual(d,m)?"rgba(0,0,0,0)":this.theme().contrastDimmer},lineWidth:1}},xSpeed:{type:"linear",position:"top",stack:"trends",beginAtZero:false,bounds:"ticks",min:o,max:u,title:{display:false},ticks:{count:5,align:"inner",autoSkip:false,includeBounds:true,stepSize:c,minRotation:0,maxRotation:0,callback:r=>{let d=this.xCenterSpeed??Number.NaN;if(this.nearlyEqual(r,d))return "";let h=this.chart?.options?.scales?.xSpeed?.max;if(typeof h=="number"&&this.nearlyEqual(r,h))return "";let s=this.xStepSpeed??Number.NaN,m=Number.isFinite(s)?s:1,_=Math.max(0,Math.min(3,Math.ceil(-Math.log10(m))));return `${r.toFixed(_)}`},font:r=>{let d=r.tick?.value??Number.NaN,f=this.xCenterSpeed??Number.NaN,h=this.nearlyEqual(d,f);return this.isPortrait()?{size:11,weight:h?"bold":"normal"}:{size:20,weight:h?"bold":"normal"}},color:r=>{let d=r.tick?.value??Number.NaN,f=this.xCenterSpeed??Number.NaN;return this.nearlyEqual(d,f)?this.theme().contrast:void 0}},grid:{display:true,color:r=>{let d=r.tick?.value??Number.NaN,f=r.scale,h=this.chart?.options?.scales,s=f,m=h?.xSpeed?.max??s.max;return this.nearlyEqual(d,m)?"rgba(0,0,0,0)":this.theme().contrastDimmer},lineWidth:1}}},this.lineChartOptions.plugins={title:{display:true,align:"end",text:"TWD ",color:this.getThemeColors().chartLabel,padding:this.isPortrait()?{top:3,bottom:0}:{top:3,bottom:0},font:this.isPortrait()?{size:16,weight:"normal"}:{size:35,weight:"normal"}},subtitle:{display:true,align:"start",text:" TWS",color:this.getThemeColors().chartLabel,padding:this.isPortrait()?{top:-18,bottom:12}:{top:-41,bottom:12},font:this.isPortrait()?{size:16}:{size:35}},legend:{display:false},annotation:{annotations:{}},streaming:{duration:t.maxDataPoints*t.sampleTime,delay:t.sampleTime,frameRate:e.timeScaleFormat==="day"?5:e.timeScaleFormat==="hour"?8:e.timeScaleFormat==="minute"?15:30}},this.xCenter=(a+i)/2,this.xStep=n,this.xCenterSpeed=(o+u)/2,this.xStepSpeed=c;}createDatasets(){this.lineChartData.datasets=[],this.lineChartData.datasets.push({label:"Value",data:[],order:2,parsing:false,normalized:true,tension:0,pointRadius:0,pointHoverRadius:0,pointHitRadius:0,borderWidth:1,fill:false,xAxisID:"x"},{label:"SMA",data:[],order:0,parsing:false,normalized:true,tension:.3,pointRadius:0,pointHoverRadius:0,pointHitRadius:0,borderWidth:10,fill:false,borderColor:e=>{let t=e.chart,{ctx:a}=t;return this.lineGradientForAxis(a,t,"x")??this.getThemeColors().averageLine},backgroundColor:"red",xAxisID:"x"},{label:"lastAverage",data:[],order:1,parsing:false,normalized:true,tension:0,pointRadius:0,pointHoverRadius:0,pointHitRadius:0,borderWidth:0,borderColor:"",fill:false,hidden:true,xAxisID:"x"},{label:"lastMinimum",data:[],order:3,parsing:false,normalized:true,hidden:true,xAxisID:"x"},{label:"lastMaximum",data:[],order:4,parsing:false,normalized:true,hidden:true,xAxisID:"x"},{label:"Value Speed",data:[],order:2,parsing:false,normalized:true,tension:0,pointRadius:0,pointHoverRadius:0,pointHitRadius:0,borderWidth:1,fill:false,xAxisID:"xSpeed"},{label:"SMA Speed",data:[],order:0,parsing:false,normalized:true,tension:.2,pointRadius:0,pointHoverRadius:0,pointHitRadius:0,borderWidth:3,fill:false,borderColor:e=>{let t=e.chart,{ctx:a}=t;return this.lineGradientForAxis(a,t,"xSpeed")??this.getThemeColors().averageLine},xAxisID:"xSpeed"},{label:"lastAverage Speed",data:[],order:1,parsing:false,normalized:true,tension:0,pointRadius:0,pointHoverRadius:0,pointHitRadius:0,borderWidth:0,borderColor:"",fill:false,hidden:true,xAxisID:"xSpeed"},{label:"lastMinimum Speed",data:[],order:3,parsing:false,normalized:true,hidden:true,xAxisID:"xSpeed"},{label:"lastMaximum Speed",data:[],order:4,parsing:false,normalized:true,hidden:true,xAxisID:"xSpeed"}),this.setDatasetsColors();}startStreaming(){if(this._dsDirectionSub?.unsubscribe(),this._dsSpeedSub?.unsubscribe(),!this.chart||!this.dataSourceInfo)return;let e=this._dataset.getDatasetBatchThenLiveObservable(`${this.id()}-twd`),t=this._dataset.getDatasetBatchThenLiveObservable(`${this.id()}-tws`);!e||!t||(this._dsDirectionSub=e.subscribe(a=>{let i=this.chart,n=this.dataSourceInfo;if(!(!i||!n)){if(Array.isArray(a))this.pushRowsToDatasets(a);else {this.pushRowsToDatasets([a]);let o=i.data.datasets[0]?.data;if(Array.isArray(o)&&o.length>n.maxDataPoints)for(let u=0;u<=4;u++){let c=i.data.datasets[u]?.data;Array.isArray(c)&&c.shift();}}this.scheduleChartUpdate();}}),this._dsSpeedSub=t.subscribe(a=>{let i=this.chart,n=this.dataSourceInfo;if(!(!i||!n)){if(Array.isArray(a))this.pushRowsToSpeedDatasets(a);else {this.pushRowsToSpeedDatasets([a]);let o=i.data.datasets[5]?.data;if(Array.isArray(o)&&o.length>n.maxDataPoints)for(let u=5;u<=9;u++){let c=i.data.datasets[u]?.data;Array.isArray(c)&&c.shift();}}this.scheduleChartUpdate();}}));}unwrapAngles(e){if(e.length===0)return [];let t=[],a=null;for(let i of e){if(i==null){t.push(null);continue}if(a==null){t.push(i),a=i;continue}let n=i-a;n>180&&(n-=360),n<-180&&(n+=360),t.push(t[t.length-1]+n),a=i;}return t}pushRowsToDatasets(e){this.pushRowsGeneric(e,0,"deg",true);}pushRowsToSpeedDatasets(e){this.pushRowsGeneric(e,5,"knots",false);}getRowValue(e,t){switch(t){case "value":return e.data.value??null;case "sma":return e.data.sma??null;case "ema":return e.data.ema??null;case "dema":return e.data.doubleEma??null;case "avg":return e.data.lastAverage??null;case "min":return e.data.lastMinimum??null;case "max":return e.data.lastMaximum??null;default:return null}}transformRows(e,t,a,i){let n=e.map(u=>{let c=this.getRowValue(u,t);return c==null?null:this.unitsService.convertToUnit(a,c)}),o=i?this.unwrapAngles(n):n;return e.map((u,c)=>({x:o[c],y:u.timestamp,ts:u.timestamp}))}pushRowsGeneric(e,t,a,i){let n=this.chart;if(!n)return;["value","sma","avg","min","max"].forEach((u,c)=>{let r=n.data.datasets[t+c];!r||!Array.isArray(r.data)||r.data.push(...this.transformRows(e,u,a,i));});}normalizeAngle(e){return (e%360+360)%360}angularDiff(e,t){let a=(e-t+540)%360-180;return Math.abs(a)}niceStepFromMantissas(e,t){if(!isFinite(e)||e<=0)return 1;let a=Math.floor(Math.log10(e)),i=e/Math.pow(10,a);return (t.find(o=>i<=o)??t[t.length-1])*Math.pow(10,a)}scheduleChartUpdate(){this._chartUpdateRafId==null&&(this._chartUpdateRafId=requestAnimationFrame(()=>{this._chartUpdateRafId=null,!(!this.chart||!this.hasValidDatasets())&&(this.updateChartAfterDataChange(),this.ngZone.runOutsideAngular(()=>this.chart?.update("none")));}));}hasValidDatasets(){let e=this.chart?.data?.datasets;if(!Array.isArray(e)||e.length<10)return false;for(let t=0;t<10;t++){let a=e[t];if(!a||!Array.isArray(a.data))return false}return true}updateChartAfterDataChange(){let e=this.chart;if(!e)return;let t=e.data.datasets[2]?.data,a=e.data.datasets[1]?.data,i=e.data.datasets[0]?.data,n=!!t?.length,o=!!a?.length,u=!!i?.length,c=n?t[t.length-1].x:o?a[a.length-1].x:u?i[i.length-1].x:void 0;if(typeof c=="number"&&isFinite(c)){let h=e.data.datasets[3]?.data,s=e.data.datasets[4]?.data,m=h?.length?h[h.length-1].x:void 0,_=s?.length?s[s.length-1].x:void 0,S=typeof m=="number"&&isFinite(m)?this.angularDiff(c,m):Number.NaN,D=typeof _=="number"&&isFinite(_)?this.angularDiff(c,_):Number.NaN,b=Number.isFinite(S)||Number.isFinite(D)?Math.max(Number.isFinite(S)?S:0,Number.isFinite(D)?D:0):Number.NaN;if(!Number.isFinite(b)){let x=n?t:o?a:i,E=Math.min(30,x?.length??0);if(E>1){let C=x.slice(x.length-E).map(y=>y.x).filter(y=>typeof y=="number"&&isFinite(y));C.length&&(b=C.reduce((y,L)=>Math.max(y,this.angularDiff(c,L)),0));}}b=Math.max(b||0,15);let N=2*b/4,T=this.niceStepFromMantissas(N,[1,1.5,2,2.5,5,7.5,10]),p=c-2*T,g=c+2*T,l=e.options.scales;l.x&&(l.x.min=p,l.x.max=g,l.x.ticks=z(G({},l.x.ticks??{}),{stepSize:T})),this.xCenter=c,this.xStep=T;}let r=e.data.datasets[7]?.data;if(r&&r.length){let h=r.length-1,s=r[h]?.x??0,m=e.data.datasets[8].data[h]?.x??s,_=e.data.datasets[9].data[h]?.x??s,S=Math.abs(s-m),D=Math.abs(_-s),b=Math.max(S,D);b=Math.max(b,.5);let N=2*b/4,T=this.niceStepFromMantissas(N,[1,2,2.5,5,10]),p=s-2*T,g=s+2*T,l=e.options.scales;l.xSpeed&&(l.xSpeed.min=p,l.xSpeed.max=g,l.xSpeed.ticks=z(G({},l.xSpeed.ticks??{}),{stepSize:T})),this.xCenterSpeed=s,this.xStepSpeed=T;}let d=this.getWindowMs(this.datasetConfig?.timeScaleFormat);if(e.data.datasets[0].data.length>0){let h=Date.now();e.data.datasets.forEach(S=>{S.data.forEach(D=>{let b=D.ts??D.y;D.y=Math.max(0,Math.min(d,h-b));});});let s=e.options.scales;s.y&&(s.y.min=0,s.y.max=d);let m;switch(this.datasetConfig?.timeScaleFormat){case "Last Minute":m=15e3;break;case "Last 5 Minutes":m=6e4;break;case "Last 30 Minutes":m=5*6e4;break;default:m=d/5;break}if(s.y){let S=G({},s.y.ticks??{});delete S.count,S.stepSize=m,s.y.ticks=S;}}}getWindowMs(e){switch(e){case "Last 30 Minutes":return 30*6e4;case "Last 5 Minutes":return 5*6e4;case "Last Minute":return 6e4;default:return 6e4}}lineGradientForAxis(e,t,a){let i=t.chartArea;if(!i)return null;let n=t.scales?.[a];if(!n)return null;let o=t.options?.scales,u=n,c=o?.[a]?.min??u.min,r=o?.[a]?.max??u.max;if(typeof c!="number"||typeof r!="number"||!isFinite(c)||!isFinite(r))return null;let d=(c+r)/2,f=n.getPixelForValue(d),h=Math.max(0,Math.min(1,(f-i.left)/i.width)),s=e.createLinearGradient(i.left,0,i.right,0);return s.addColorStop(0,this.theme().port),s.addColorStop(h,this.theme().port),s.addColorStop(h,this.theme().starboard),s.addColorStop(1,this.theme().starboard),s}setDatasetsColors(){this.lineChartData.datasets.forEach(e=>{e.label==="Value"&&(e.borderColor=this.getThemeColors().valueLine,e.backgroundColor=this.getThemeColors().valueFill),e.label==="Value Speed"&&(e.borderColor=this.getThemeColors().valueLine,e.backgroundColor=this.getThemeColors().valueFill);});}getThemeColors(){let e=this.runtime?.options()?.color,t={valueLine:"",valueFill:"",averageLine:"",averageFill:"",averageChartLine:"",chartLabel:"",chartValue:""};switch(e){case "contrast":t.valueLine=this.theme().contrastDim,t.valueFill=this.theme().contrastDimmer,t.averageLine=this.theme().contrast,t.averageFill=this.theme().contrast,t.chartValue=this.theme().contrast,t.averageChartLine=this.theme().contrast,t.chartLabel=this.theme().contrastDim;break;case "blue":t.valueLine=this.theme().blueDim,t.valueFill=this.theme().blueDimmer,t.averageLine=this.theme().blue,t.averageFill=this.theme().blue,t.chartValue=this.theme().blue,t.averageChartLine=this.theme().blueDim,t.chartLabel=this.theme().blueDim;break;case "green":t.valueLine=this.theme().greenDim,t.valueFill=this.theme().greenDimmer,t.averageLine=this.theme().green,t.averageFill=this.theme().green,t.chartValue=this.theme().green,t.averageChartLine=this.theme().greenDim,t.chartLabel=this.theme().greenDim;break;case "pink":t.valueLine=this.theme().pinkDim,t.valueFill=this.theme().pinkDimmer,t.averageLine=this.theme().pink,t.averageFill=this.theme().pink,t.chartValue=this.theme().pink,t.averageChartLine=this.theme().pinkDim,t.chartLabel=this.theme().pinkDim;break;case "orange":t.valueLine=this.theme().orangeDim,t.valueFill=this.theme().orangeDimmer,t.averageLine=this.theme().orange,t.averageFill=this.theme().orange,t.chartValue=this.theme().orange,t.averageChartLine=this.theme().orangeDim,t.chartLabel=this.theme().orangeDim;break;case "purple":t.valueLine=this.theme().purpleDim,t.valueFill=this.theme().purpleDimmer,t.averageLine=this.theme().purple,t.averageFill=this.theme().purple,t.chartValue=this.theme().purple,t.averageChartLine=this.theme().purpleDim,t.chartLabel=this.theme().purpleDim;break;case "grey":t.valueLine=this.theme().greyDim,t.valueFill=this.theme().greyDimmer,t.averageLine=this.theme().grey,t.averageFill=this.theme().grey,t.chartValue=this.theme().grey,t.averageChartLine=this.theme().greyDim,t.chartLabel=this.theme().greyDim;break;case "yellow":t.valueLine=this.theme().yellowDim,t.valueFill=this.theme().yellowDimmer,t.averageLine=this.theme().yellow,t.averageFill=this.theme().yellow,t.chartValue=this.theme().yellow,t.averageChartLine=this.theme().yellowDim,t.chartLabel=this.theme().yellowDim;break}return t}nearlyEqual(e,t,a=1e-6){if(!Number.isFinite(e)||!Number.isFinite(t))return false;let i=Math.max(1,Math.max(Math.abs(e),Math.abs(t)));return Math.abs(e-t)<=a*i}resolveTickColor(e,t,a){let n=t.options.ticks?.color;return typeof n=="function"?n({chart:e,scale:t,tick:{value:a}})??Wl.defaults.color:typeof n=="string"?n:Wl.defaults.color}axisTopLabelY(e){return e.options?.position==="top"?e.top+4:e.bottom+2}ngOnDestroy(){this._dsDirectionSub?.unsubscribe(),this._dsSpeedSub?.unsubscribe(),this._chartUpdateRafId!=null&&(cancelAnimationFrame(this._chartUpdateRafId),this._chartUpdateRafId=null),this.chart?.destroy();let e=this.widgetDataChart?.()?.nativeElement;this.canvasService.releaseCanvas(e,{clear:true,removeFromDom:true});}static \u0275fac=function(t){return new(t||O)};static \u0275cmp=JD({type:O,selectors:[["widget-windtrends-chart"]],viewQuery:function(t,a){t&1&&eg(a.widgetDataChart,tt,5,Lr),t&2&&Kw();},inputs:{id:[1,"id"],type:[1,"type"],theme:[1,"theme"]},decls:2,vars:0,consts:[["widgetDataChart",""],[2,"z-index","inherit"]],template:function(t,a){t&1&&Uh(0,"canvas",1,0);},styles:["[_nghost-%COMP%]{display:block;width:100%;height:100%}"]})}return O})();export{mt as WidgetWindTrendsChartComponent};
1
+ import'./chunk-h2q_pbbF.js';import {d1 as Hj,w,du as p,ao as ue,dy as K,dw as S,aZ as R,bu as ut,i as ir,$ as $j,a6 as Lr,b0 as Wl,W as Wp,E as Em,F as Fa,dn as ge,cw as z,cv as G,J as JD,cp as Uh,f as eg,K as Kw}from'./main-BNR44HGB.js';var tt=["widgetDataChart"],mt=(()=>{class O{id=Hj.required();type=Hj.required();theme=Hj.required();runtime=w(p,{optional:true});static DEFAULT_CONFIG={filterSelfPaths:true,color:"contrast",timeScale:"Last 30 Minutes"};ngZone=w(ue);_dataset=w(K);datasetLifecycle=w(S);canvasService=w(R);unitsService=w(ut);responsive=w(ir);isPhonePortrait;widgetDataChart=$j("widgetDataChart",{read:Lr});lineChartData={datasets:[]};lineChartOptions={parsing:false,datasets:{line:{pointRadius:0,pointHoverRadius:0,tension:.3}},animations:{tension:{easing:"easeInOutCubic"}}};lineChartType="line";chart=null;_dsDirectionSub=null;_dsSpeedSub=null;_chartUpdateRafId=null;datasetConfig=null;dataSourceInfo=null;xCenter=null;xStep=null;xCenterSpeed=null;xStepSpeed=null;CENTER_LINE_WIDTH=4;GRID_LINE_WIDTH=1;EDGE_EXTEND_UP_PX=42;EDGE_SPEED_LABEL_OFFSET=5;EDGE_DIR_LABEL_OFFSET=5;TICK_LABEL_FONT_SIZE=20;TICK_LABEL_PHONE_PORTRAIT_FONT_SIZE=11;CENTER_LABEL_FONT_SIZE=22;CENTER_LABEL_PHONE_PORTRAIT_FONT_SIZE=13;SPEED_VALUE_FONT_SIZE=62;SPEED_VALUE_PHONE_PORTRAIT_FONT_SIZE=32;TOP_VALUE_Y_OFFSET=62;TOP_VALUE_PHONE_PORTRAIT_Y_OFFSET=44;TOP_UNIT_Y_OFFSET=51;TOP_UNIT_PHONE_PORTRAIT_Y_OFFSET=38;UNIT_FONT_SIZE=28;UNIT_PHONE_PORTRAIT_FONT_SIZE=14;UNIT_PADDING=8;UNIT_PHONE_PORTRAIT_PADDING=3;isPortrait=()=>this.isPhonePortrait()?.matches===true;gridBackgroundPlugin={id:"xSpeedGridBackground",beforeDraw:e=>{let t=e.chartArea;if(!t)return;let a=e.ctx,i=this.theme();a.save(),a.globalCompositeOperation="destination-over",a.fillStyle=i.background,a.fillRect(t.left,t.top,t.width/2,t.height),a.restore();}};centerTickPlugin={id:"centerTickStyle",afterDraw:e=>{let t=e.ctx,a=e.chartArea,i=this.theme(),n=this.getThemeColors(),o=Wl.defaults.font,u=e.scales,c=e.options?.scales,r=e.data?.datasets?.[0]?.data,d=e.data?.datasets?.[5]?.data,f=(r?.length??0)>=2&&(d?.length??0)>=2,h=(p,g)=>{let l=u?.[p],x=c;if(!l)return;let E=l,v=x?.[p]?.min??E.min,C=x?.[p]?.max??E.max;if(typeof v!="number"||typeof C!="number"||!isFinite(v)||!isFinite(C))return;let y=(v+C)/2,L=l.getPixelForValue(y);t.save(),t.strokeStyle=i.contrastDim,t.lineWidth=this.CENTER_LINE_WIDTH,t.beginPath(),t.moveTo(L,a.top),t.lineTo(L,a.bottom),t.stroke(),t.restore(),t.save(),t.fillStyle=i.contrastDim,t.font=this.isPortrait()?`bold ${this.CENTER_LABEL_PHONE_PORTRAIT_FONT_SIZE}px ${o.family}`:`bold ${this.CENTER_LABEL_FONT_SIZE}px ${o.family}`,t.textAlign="center",t.textBaseline="top";let J=this.axisTopLabelY(l);t.fillText(g(y),L,J),t.restore();};h("x",p=>`${((p%360+360)%360).toFixed(0)}\xB0`),h("xSpeed",p=>`${p.toFixed(1)}`);let s=u?.xSpeed;if(s){let p=c,g=s,l=p?.xSpeed?.max??g.max;if(typeof l=="number"&&isFinite(l)){let x=s.getPixelForValue(l);t.save(),t.fillStyle=this.resolveTickColor(e,s,l),t.font=this.isPortrait()?`normal ${this.TICK_LABEL_PHONE_PORTRAIT_FONT_SIZE}px ${o.family}`:`normal ${this.TICK_LABEL_FONT_SIZE}px ${o.family}`,t.textAlign="right",t.textBaseline="top";let E=this.axisTopLabelY(s),v=this.xStepSpeed??1,C=Math.max(0,Math.min(3,Math.ceil(-Math.log10(v))));t.fillText(`${l.toFixed(C)}`,x-this.EDGE_SPEED_LABEL_OFFSET,E),t.restore(),t.save(),t.strokeStyle=i.contrastDim,t.lineWidth=this.GRID_LINE_WIDTH,t.beginPath();let y=Math.round(x)+.5;t.moveTo(y,a.bottom),t.lineTo(y,a.top-this.EDGE_EXTEND_UP_PX),t.stroke(),t.restore();}}let m=u?.x;if(m){let p=c,g=m,l=p?.x?.min??g.min;if(typeof l=="number"&&isFinite(l)){let x=m.getPixelForValue(l);t.save(),t.fillStyle=this.resolveTickColor(e,m,l),t.font=this.isPortrait()?`normal ${this.TICK_LABEL_PHONE_PORTRAIT_FONT_SIZE}px ${o.family}`:`normal ${this.TICK_LABEL_FONT_SIZE}px ${o.family}`,t.textAlign="left",t.textBaseline="top";let E=this.axisTopLabelY(m),v=this.normalizeAngle(l);t.fillText(`${v.toFixed(0)}\xB0`,x+this.EDGE_DIR_LABEL_OFFSET,E),t.restore();}}let _=e.data?.datasets,S=_?.[5]?.data,D=S?.length?S.length-1:-1,b=D>=0?S[D]?.x:void 0;if(typeof b=="number"&&isFinite(b)){t.save(),t.fillStyle=n.chartValue,t.font=this.isPortrait()?`bold ${this.SPEED_VALUE_PHONE_PORTRAIT_FONT_SIZE}px ${o.family}`:`bold ${this.SPEED_VALUE_FONT_SIZE}px ${o.family}`,t.textAlign="center",t.textBaseline="middle";let p=`${b.toFixed(1)}`,g=a.left+a.width/4,l=a.top-(this.isPortrait()?this.TOP_VALUE_PHONE_PORTRAIT_Y_OFFSET:this.TOP_VALUE_Y_OFFSET);t.fillText(p,g,l);let x=t.measureText(p),E=g+x.width/2+(this.isPortrait()?this.UNIT_PHONE_PORTRAIT_PADDING:this.UNIT_PADDING),v=a.top-(this.isPortrait()?this.TOP_UNIT_PHONE_PORTRAIT_Y_OFFSET:this.TOP_UNIT_Y_OFFSET);t.font=this.isPortrait()?`bold ${this.UNIT_PHONE_PORTRAIT_FONT_SIZE}px ${o.family}`:`bold ${this.UNIT_FONT_SIZE}px ${o.family}`,t.textAlign="left",t.fillText("kts",E,v),t.restore();}let F=_?.[0]?.data,N=F?.length?F.length-1:-1,T=N>=0?F[N]?.x:void 0;if(typeof T=="number"&&isFinite(T)){let p=this.normalizeAngle(T);t.save(),t.fillStyle=n.chartValue,t.font=this.isPortrait()?`bold ${this.SPEED_VALUE_PHONE_PORTRAIT_FONT_SIZE}px ${o.family}`:`bold ${this.SPEED_VALUE_FONT_SIZE}px ${o.family}`,t.textAlign="center",t.textBaseline="middle",t.fillText(`${p.toFixed(0)}\xB0`,a.left+3*a.width/4,a.top-(this.isPortrait()?this.TOP_VALUE_PHONE_PORTRAIT_Y_OFFSET:this.TOP_VALUE_Y_OFFSET)),t.restore();}if(!f){let p=Math.min(a.width*.7,420),g=90,l=a.left+(a.width-p)/2,x=a.top+(a.height-g)/2;t.save(),t.globalAlpha=.82,t.fillStyle=i.background,t.fillRect(l,x,p,g),t.restore(),t.save(),t.strokeStyle=i.contrastDim,t.lineWidth=2,t.strokeRect(l,x,p,g),t.restore(),t.save(),t.fillStyle=this.getThemeColors().chartLabel,t.textAlign="center",t.textBaseline="middle",t.font=`bold 18px ${o.family}`,t.fillText("Data acquisition...",l+p/2,x+g/2),t.restore();}}};constructor(){this.isPhonePortrait=Wp(this.responsive.observe(Em.HandsetPortrait),{initialValue:void 0}),Fa(()=>{let e=this.theme(),t=this.runtime?.options();!e||!t||ge(()=>{this.datasetConfig&&this.chart&&(this.setChartOptions(),this.setDatasetsColors(),this.ngZone.runOutsideAngular(()=>this.chart?.update("none")));});}),Fa(()=>{let e=this.runtime?.options();if(!e)return;!this.datasetConfig||this.datasetConfig.timeScaleFormat!==e.timeScale?(this.syncServiceDatasets(),this.startWidget()):this.chart&&this.setChartOptions();});}startWidget(){if(this.widgetDataChart()&&(this.datasetConfig=this._dataset.getDatasetConfig(`${this.id()}-twd`)??null,this.dataSourceInfo=this._dataset.getDataSourceInfo(`${this.id()}-twd`)??null,!!this.datasetConfig)){if(this.createDatasets(),this.setChartOptions(),this.chart)this.ngZone.runOutsideAngular(()=>this.chart?.update("none"));else {let e=this.widgetDataChart()?.nativeElement.getContext("2d");if(!e)return;this.chart=new Wl(e,{type:this.lineChartType,data:this.lineChartData,options:this.lineChartOptions,plugins:[this.gridBackgroundPlugin,this.centerTickPlugin]}),this.ngZone.runOutsideAngular(()=>this.chart?.update("none"));}this.startStreaming();}}syncServiceDatasets(){let e=this.runtime?.options();!e||e.timeScale===""||this.datasetLifecycle.syncWindTrendsDatasets(this.id(),e.timeScale);}setChartOptions(){let e=this.datasetConfig,t=this.dataSourceInfo;if(!e||!t)return;this.lineChartOptions.maintainAspectRatio=false,this.lineChartOptions.animation=false,this.lineChartOptions.indexAxis="y";let a=0,i=360,n=(i-a)/4,o=0,u=20,c=(u-o)/4;this.lineChartOptions.scales={y:{type:"linear",display:true,position:"right",reverse:true,title:{display:true,text:`${e.timeScaleFormat}`,align:"center"},ticks:{count:6,autoSkip:false,includeBounds:true,align:"inner",major:{enabled:true},font:this.isPortrait()?{size:12}:{size:16},callback:r=>{let d=Number(r),f=e.timeScaleFormat,h=this.getWindowMs(f);return f==="Last 5 Minutes"?`${Math.round(d/6e4)}'`:h>=10*6e4?`${Math.round(d/6e4)}'`:`${Math.round(d/1e3)}"`}},grid:{display:true,color:this.theme().contrastDimmer}},x:{type:"linear",position:"top",stack:"trends",beginAtZero:false,bounds:"ticks",min:a,max:i,title:{display:false},ticks:{count:5,align:"inner",autoSkip:false,includeBounds:true,stepSize:n,minRotation:0,maxRotation:0,callback:r=>{let d=Number(r),f=this.xCenter??Number.NaN;if(this.nearlyEqual(d,f))return "";let s=this.chart?.options?.scales?.x?.min;return typeof s=="number"&&this.nearlyEqual(d,s)?"":`${((d%360+360)%360).toFixed(0)}\xB0`},font:r=>{let d=r.tick?.value??Number.NaN,f=this.xCenter??Number.NaN,h=this.nearlyEqual(d,f);return this.isPortrait()?{size:11,weight:h?"bold":"normal"}:{size:20,weight:h?"bold":"normal"}},color:r=>{let d=r.tick?.value??Number.NaN,f=this.xCenter??Number.NaN;return this.nearlyEqual(d,f)?this.theme().contrast:void 0}},grid:{display:true,color:r=>{let d=r.tick?.value??Number.NaN,f=r.scale,h=this.chart?.options?.scales,s=f,m=h?.x?.min??s.min;return this.nearlyEqual(d,m)?"rgba(0,0,0,0)":this.theme().contrastDimmer},lineWidth:1}},xSpeed:{type:"linear",position:"top",stack:"trends",beginAtZero:false,bounds:"ticks",min:o,max:u,title:{display:false},ticks:{count:5,align:"inner",autoSkip:false,includeBounds:true,stepSize:c,minRotation:0,maxRotation:0,callback:r=>{let d=this.xCenterSpeed??Number.NaN;if(this.nearlyEqual(r,d))return "";let h=this.chart?.options?.scales?.xSpeed?.max;if(typeof h=="number"&&this.nearlyEqual(r,h))return "";let s=this.xStepSpeed??Number.NaN,m=Number.isFinite(s)?s:1,_=Math.max(0,Math.min(3,Math.ceil(-Math.log10(m))));return `${r.toFixed(_)}`},font:r=>{let d=r.tick?.value??Number.NaN,f=this.xCenterSpeed??Number.NaN,h=this.nearlyEqual(d,f);return this.isPortrait()?{size:11,weight:h?"bold":"normal"}:{size:20,weight:h?"bold":"normal"}},color:r=>{let d=r.tick?.value??Number.NaN,f=this.xCenterSpeed??Number.NaN;return this.nearlyEqual(d,f)?this.theme().contrast:void 0}},grid:{display:true,color:r=>{let d=r.tick?.value??Number.NaN,f=r.scale,h=this.chart?.options?.scales,s=f,m=h?.xSpeed?.max??s.max;return this.nearlyEqual(d,m)?"rgba(0,0,0,0)":this.theme().contrastDimmer},lineWidth:1}}},this.lineChartOptions.plugins={title:{display:true,align:"end",text:"TWD ",color:this.getThemeColors().chartLabel,padding:this.isPortrait()?{top:3,bottom:0}:{top:3,bottom:0},font:this.isPortrait()?{size:16,weight:"normal"}:{size:35,weight:"normal"}},subtitle:{display:true,align:"start",text:" TWS",color:this.getThemeColors().chartLabel,padding:this.isPortrait()?{top:-18,bottom:12}:{top:-41,bottom:12},font:this.isPortrait()?{size:16}:{size:35}},legend:{display:false},annotation:{annotations:{}},streaming:{duration:t.maxDataPoints*t.sampleTime,delay:t.sampleTime,frameRate:e.timeScaleFormat==="day"?5:e.timeScaleFormat==="hour"?8:e.timeScaleFormat==="minute"?15:30}},this.xCenter=(a+i)/2,this.xStep=n,this.xCenterSpeed=(o+u)/2,this.xStepSpeed=c;}createDatasets(){this.lineChartData.datasets=[],this.lineChartData.datasets.push({label:"Value",data:[],order:2,parsing:false,normalized:true,tension:0,pointRadius:0,pointHoverRadius:0,pointHitRadius:0,borderWidth:1,fill:false,xAxisID:"x"},{label:"SMA",data:[],order:0,parsing:false,normalized:true,tension:.3,pointRadius:0,pointHoverRadius:0,pointHitRadius:0,borderWidth:10,fill:false,borderColor:e=>{let t=e.chart,{ctx:a}=t;return this.lineGradientForAxis(a,t,"x")??this.getThemeColors().averageLine},backgroundColor:"red",xAxisID:"x"},{label:"lastAverage",data:[],order:1,parsing:false,normalized:true,tension:0,pointRadius:0,pointHoverRadius:0,pointHitRadius:0,borderWidth:0,borderColor:"",fill:false,hidden:true,xAxisID:"x"},{label:"lastMinimum",data:[],order:3,parsing:false,normalized:true,hidden:true,xAxisID:"x"},{label:"lastMaximum",data:[],order:4,parsing:false,normalized:true,hidden:true,xAxisID:"x"},{label:"Value Speed",data:[],order:2,parsing:false,normalized:true,tension:0,pointRadius:0,pointHoverRadius:0,pointHitRadius:0,borderWidth:1,fill:false,xAxisID:"xSpeed"},{label:"SMA Speed",data:[],order:0,parsing:false,normalized:true,tension:.2,pointRadius:0,pointHoverRadius:0,pointHitRadius:0,borderWidth:3,fill:false,borderColor:e=>{let t=e.chart,{ctx:a}=t;return this.lineGradientForAxis(a,t,"xSpeed")??this.getThemeColors().averageLine},xAxisID:"xSpeed"},{label:"lastAverage Speed",data:[],order:1,parsing:false,normalized:true,tension:0,pointRadius:0,pointHoverRadius:0,pointHitRadius:0,borderWidth:0,borderColor:"",fill:false,hidden:true,xAxisID:"xSpeed"},{label:"lastMinimum Speed",data:[],order:3,parsing:false,normalized:true,hidden:true,xAxisID:"xSpeed"},{label:"lastMaximum Speed",data:[],order:4,parsing:false,normalized:true,hidden:true,xAxisID:"xSpeed"}),this.setDatasetsColors();}startStreaming(){if(this._dsDirectionSub?.unsubscribe(),this._dsSpeedSub?.unsubscribe(),!this.chart||!this.dataSourceInfo)return;let e=this._dataset.getDatasetBatchThenLiveObservable(`${this.id()}-twd`),t=this._dataset.getDatasetBatchThenLiveObservable(`${this.id()}-tws`);!e||!t||(this._dsDirectionSub=e.subscribe(a=>{let i=this.chart,n=this.dataSourceInfo;if(!(!i||!n)){if(Array.isArray(a))this.pushRowsToDatasets(a);else {this.pushRowsToDatasets([a]);let o=i.data.datasets[0]?.data;if(Array.isArray(o)&&o.length>n.maxDataPoints)for(let u=0;u<=4;u++){let c=i.data.datasets[u]?.data;Array.isArray(c)&&c.shift();}}this.scheduleChartUpdate();}}),this._dsSpeedSub=t.subscribe(a=>{let i=this.chart,n=this.dataSourceInfo;if(!(!i||!n)){if(Array.isArray(a))this.pushRowsToSpeedDatasets(a);else {this.pushRowsToSpeedDatasets([a]);let o=i.data.datasets[5]?.data;if(Array.isArray(o)&&o.length>n.maxDataPoints)for(let u=5;u<=9;u++){let c=i.data.datasets[u]?.data;Array.isArray(c)&&c.shift();}}this.scheduleChartUpdate();}}));}unwrapAngles(e){if(e.length===0)return [];let t=[],a=null;for(let i of e){if(i==null){t.push(null);continue}if(a==null){t.push(i),a=i;continue}let n=i-a;n>180&&(n-=360),n<-180&&(n+=360),t.push(t[t.length-1]+n),a=i;}return t}pushRowsToDatasets(e){this.pushRowsGeneric(e,0,"deg",true);}pushRowsToSpeedDatasets(e){this.pushRowsGeneric(e,5,"knots",false);}getRowValue(e,t){switch(t){case "value":return e.data.value??null;case "sma":return e.data.sma??null;case "ema":return e.data.ema??null;case "dema":return e.data.doubleEma??null;case "avg":return e.data.lastAverage??null;case "min":return e.data.lastMinimum??null;case "max":return e.data.lastMaximum??null;default:return null}}transformRows(e,t,a,i){let n=e.map(u=>{let c=this.getRowValue(u,t);return c==null?null:this.unitsService.convertToUnit(a,c)}),o=i?this.unwrapAngles(n):n;return e.map((u,c)=>({x:o[c],y:u.timestamp,ts:u.timestamp}))}pushRowsGeneric(e,t,a,i){let n=this.chart;if(!n)return;["value","sma","avg","min","max"].forEach((u,c)=>{let r=n.data.datasets[t+c];!r||!Array.isArray(r.data)||r.data.push(...this.transformRows(e,u,a,i));});}normalizeAngle(e){return (e%360+360)%360}angularDiff(e,t){let a=(e-t+540)%360-180;return Math.abs(a)}niceStepFromMantissas(e,t){if(!isFinite(e)||e<=0)return 1;let a=Math.floor(Math.log10(e)),i=e/Math.pow(10,a);return (t.find(o=>i<=o)??t[t.length-1])*Math.pow(10,a)}scheduleChartUpdate(){this._chartUpdateRafId==null&&(this._chartUpdateRafId=requestAnimationFrame(()=>{this._chartUpdateRafId=null,!(!this.chart||!this.hasValidDatasets())&&(this.updateChartAfterDataChange(),this.ngZone.runOutsideAngular(()=>this.chart?.update("none")));}));}hasValidDatasets(){let e=this.chart?.data?.datasets;if(!Array.isArray(e)||e.length<10)return false;for(let t=0;t<10;t++){let a=e[t];if(!a||!Array.isArray(a.data))return false}return true}updateChartAfterDataChange(){let e=this.chart;if(!e)return;let t=e.data.datasets[2]?.data,a=e.data.datasets[1]?.data,i=e.data.datasets[0]?.data,n=!!t?.length,o=!!a?.length,u=!!i?.length,c=n?t[t.length-1].x:o?a[a.length-1].x:u?i[i.length-1].x:void 0;if(typeof c=="number"&&isFinite(c)){let h=e.data.datasets[3]?.data,s=e.data.datasets[4]?.data,m=h?.length?h[h.length-1].x:void 0,_=s?.length?s[s.length-1].x:void 0,S=typeof m=="number"&&isFinite(m)?this.angularDiff(c,m):Number.NaN,D=typeof _=="number"&&isFinite(_)?this.angularDiff(c,_):Number.NaN,b=Number.isFinite(S)||Number.isFinite(D)?Math.max(Number.isFinite(S)?S:0,Number.isFinite(D)?D:0):Number.NaN;if(!Number.isFinite(b)){let x=n?t:o?a:i,E=Math.min(30,x?.length??0);if(E>1){let C=x.slice(x.length-E).map(y=>y.x).filter(y=>typeof y=="number"&&isFinite(y));C.length&&(b=C.reduce((y,L)=>Math.max(y,this.angularDiff(c,L)),0));}}b=Math.max(b||0,15);let N=2*b/4,T=this.niceStepFromMantissas(N,[1,1.5,2,2.5,5,7.5,10]),p=c-2*T,g=c+2*T,l=e.options.scales;l.x&&(l.x.min=p,l.x.max=g,l.x.ticks=z(G({},l.x.ticks??{}),{stepSize:T})),this.xCenter=c,this.xStep=T;}let r=e.data.datasets[7]?.data;if(r&&r.length){let h=r.length-1,s=r[h]?.x??0,m=e.data.datasets[8].data[h]?.x??s,_=e.data.datasets[9].data[h]?.x??s,S=Math.abs(s-m),D=Math.abs(_-s),b=Math.max(S,D);b=Math.max(b,.5);let N=2*b/4,T=this.niceStepFromMantissas(N,[1,2,2.5,5,10]),p=s-2*T,g=s+2*T,l=e.options.scales;l.xSpeed&&(l.xSpeed.min=p,l.xSpeed.max=g,l.xSpeed.ticks=z(G({},l.xSpeed.ticks??{}),{stepSize:T})),this.xCenterSpeed=s,this.xStepSpeed=T;}let d=this.getWindowMs(this.datasetConfig?.timeScaleFormat);if(e.data.datasets[0].data.length>0){let h=Date.now();e.data.datasets.forEach(S=>{S.data.forEach(D=>{let b=D.ts??D.y;D.y=Math.max(0,Math.min(d,h-b));});});let s=e.options.scales;s.y&&(s.y.min=0,s.y.max=d);let m;switch(this.datasetConfig?.timeScaleFormat){case "Last Minute":m=15e3;break;case "Last 5 Minutes":m=6e4;break;case "Last 30 Minutes":m=5*6e4;break;default:m=d/5;break}if(s.y){let S=G({},s.y.ticks??{});delete S.count,S.stepSize=m,s.y.ticks=S;}}}getWindowMs(e){switch(e){case "Last 30 Minutes":return 30*6e4;case "Last 5 Minutes":return 5*6e4;case "Last Minute":return 6e4;default:return 6e4}}lineGradientForAxis(e,t,a){let i=t.chartArea;if(!i)return null;let n=t.scales?.[a];if(!n)return null;let o=t.options?.scales,u=n,c=o?.[a]?.min??u.min,r=o?.[a]?.max??u.max;if(typeof c!="number"||typeof r!="number"||!isFinite(c)||!isFinite(r))return null;let d=(c+r)/2,f=n.getPixelForValue(d),h=Math.max(0,Math.min(1,(f-i.left)/i.width)),s=e.createLinearGradient(i.left,0,i.right,0);return s.addColorStop(0,this.theme().port),s.addColorStop(h,this.theme().port),s.addColorStop(h,this.theme().starboard),s.addColorStop(1,this.theme().starboard),s}setDatasetsColors(){this.lineChartData.datasets.forEach(e=>{e.label==="Value"&&(e.borderColor=this.getThemeColors().valueLine,e.backgroundColor=this.getThemeColors().valueFill),e.label==="Value Speed"&&(e.borderColor=this.getThemeColors().valueLine,e.backgroundColor=this.getThemeColors().valueFill);});}getThemeColors(){let e=this.runtime?.options()?.color,t={valueLine:"",valueFill:"",averageLine:"",averageFill:"",averageChartLine:"",chartLabel:"",chartValue:""};switch(e){case "contrast":t.valueLine=this.theme().contrastDim,t.valueFill=this.theme().contrastDimmer,t.averageLine=this.theme().contrast,t.averageFill=this.theme().contrast,t.chartValue=this.theme().contrast,t.averageChartLine=this.theme().contrast,t.chartLabel=this.theme().contrastDim;break;case "blue":t.valueLine=this.theme().blueDim,t.valueFill=this.theme().blueDimmer,t.averageLine=this.theme().blue,t.averageFill=this.theme().blue,t.chartValue=this.theme().blue,t.averageChartLine=this.theme().blueDim,t.chartLabel=this.theme().blueDim;break;case "green":t.valueLine=this.theme().greenDim,t.valueFill=this.theme().greenDimmer,t.averageLine=this.theme().green,t.averageFill=this.theme().green,t.chartValue=this.theme().green,t.averageChartLine=this.theme().greenDim,t.chartLabel=this.theme().greenDim;break;case "pink":t.valueLine=this.theme().pinkDim,t.valueFill=this.theme().pinkDimmer,t.averageLine=this.theme().pink,t.averageFill=this.theme().pink,t.chartValue=this.theme().pink,t.averageChartLine=this.theme().pinkDim,t.chartLabel=this.theme().pinkDim;break;case "orange":t.valueLine=this.theme().orangeDim,t.valueFill=this.theme().orangeDimmer,t.averageLine=this.theme().orange,t.averageFill=this.theme().orange,t.chartValue=this.theme().orange,t.averageChartLine=this.theme().orangeDim,t.chartLabel=this.theme().orangeDim;break;case "purple":t.valueLine=this.theme().purpleDim,t.valueFill=this.theme().purpleDimmer,t.averageLine=this.theme().purple,t.averageFill=this.theme().purple,t.chartValue=this.theme().purple,t.averageChartLine=this.theme().purpleDim,t.chartLabel=this.theme().purpleDim;break;case "grey":t.valueLine=this.theme().greyDim,t.valueFill=this.theme().greyDimmer,t.averageLine=this.theme().grey,t.averageFill=this.theme().grey,t.chartValue=this.theme().grey,t.averageChartLine=this.theme().greyDim,t.chartLabel=this.theme().greyDim;break;case "yellow":t.valueLine=this.theme().yellowDim,t.valueFill=this.theme().yellowDimmer,t.averageLine=this.theme().yellow,t.averageFill=this.theme().yellow,t.chartValue=this.theme().yellow,t.averageChartLine=this.theme().yellowDim,t.chartLabel=this.theme().yellowDim;break}return t}nearlyEqual(e,t,a=1e-6){if(!Number.isFinite(e)||!Number.isFinite(t))return false;let i=Math.max(1,Math.max(Math.abs(e),Math.abs(t)));return Math.abs(e-t)<=a*i}resolveTickColor(e,t,a){let n=t.options.ticks?.color;return typeof n=="function"?n({chart:e,scale:t,tick:{value:a}})??Wl.defaults.color:typeof n=="string"?n:Wl.defaults.color}axisTopLabelY(e){return e.options?.position==="top"?e.top+4:e.bottom+2}ngOnDestroy(){this._dsDirectionSub?.unsubscribe(),this._dsSpeedSub?.unsubscribe(),this._chartUpdateRafId!=null&&(cancelAnimationFrame(this._chartUpdateRafId),this._chartUpdateRafId=null),this.chart?.destroy();let e=this.widgetDataChart?.()?.nativeElement;this.canvasService.releaseCanvas(e,{clear:true,removeFromDom:true});}static \u0275fac=function(t){return new(t||O)};static \u0275cmp=JD({type:O,selectors:[["widget-windtrends-chart"]],viewQuery:function(t,a){t&1&&eg(a.widgetDataChart,tt,5,Lr),t&2&&Kw();},inputs:{id:[1,"id"],type:[1,"type"],theme:[1,"theme"]},decls:2,vars:0,consts:[["widgetDataChart",""],[2,"z-index","inherit"]],template:function(t,a){t&1&&Uh(0,"canvas",1,0);},styles:["[_nghost-%COMP%]{display:block;width:100%;height:100%}"]})}return O})();export{mt as WidgetWindTrendsChartComponent};
@@ -1 +1 @@
1
- import {p as p$1}from'./chunk-CaD3zVfK.js';import {G as Gt,L as Lt}from'./chunk-BQr-tSkv.js';import {u}from'./chunk-hd2_AKwt.js';import {k}from'./chunk-BwOIef42.js';import {d1 as Hj,w,du as p,dv as rt,dD as _,bu as ut,$ as $j,a6 as Lr,v as vt,D as Dt,F as Fa,dn as ge,J as JD,_ as _w,M as Mw,f as eg,K as Kw,h as Fw,P as Pi,k as Qh,u as ul,g as qw,B as Bh,an as Hh,l as ud,m as dd,dx as n$1}from'./main-BAV5VDOD.js';import {c}from'./chunk-Dxlia2NE.js';var L=["radialGauge"];function F(n,q){if(n&1){let t=Fw();Pi(0,"radial-gauge",2,0),Qh("resizeChange",function(a){ud(t);let e=qw();return dd(e.onResized(a))}),ul();}if(n&2){let t=qw();Bh("options",t.gaugeOptions)("value",t.displayValue()),Hh("value-text",t.textValue());}}var ne=(()=>{class n{id=Hj.required();type=Hj.required();theme=Hj.required();runtime=w(p);streams=w(rt);metadata=w(_);unitsService=w(ut);static DEFAULT_CONFIG={supportAutomaticHistoricalSeries:true,displayName:"Gauge Label",filterSelfPaths:true,paths:{gaugePath:{description:"Numeric Data",path:null,source:null,pathType:"number",suppressBootstrapNull:true,isPathConfigurable:true,showPathSkUnitsFilter:true,pathSkUnitsFilter:null,convertUnitTo:"unitless",sampleTime:500}},displayScale:{lower:0,upper:100,type:"linear"},gauge:{type:"ngRadial",subType:"measuring",highlightsWidth:5,scaleStart:180,barStartPosition:"left",enableTicks:true,enableProgressbar:true,enableNeedle:true},numInt:1,numDecimal:0,enableTimeout:false,color:"contrast",dataTimeout:5,ignoreZones:false};LINE="line";ANIMATION_TARGET_NEEDLE="needle";ngGauge=$j("radialGauge");gauge=$j("radialGauge",{read:Lr});value=vt(void 0);displayValue=Dt(()=>this.value()??0);shouldRenderGauge=Dt(()=>this.value()!==void 0);textValue=vt("--");colorStrokeTicks=vt("");gaugeBootstrapped=vt(false);animationEnabled=Dt(()=>this.gaugeBootstrapped());normalizedConfig=Dt(()=>this.runtime.options()??n.DEFAULT_CONFIG);gaugePathConfig=Dt(()=>this.normalizedConfig().paths?.gaugePath);adjustedScale=Dt(()=>{let t=this.normalizedConfig();return t.gauge?.subType==="capacity"?{min:t.displayScale?.lower??0,max:t.displayScale?.upper??100,majorTicks:[]}:p$1(t.displayScale?.lower??0,t.displayScale?.upper??100,t.gauge?.barStartPosition==="right")});highlights=Dt(()=>{let t=this.metadata.zones(),i=this.normalizedConfig(),a=this.theme(),e=this.gaugePathConfig();if(!t?.length)return [];if(!a)return [];if(i.ignoreZones)return [];if(i.gauge?.subType!=="measuring")return [];if(!e)return [];let o=this.adjustedScale(),r=i.gauge?.barStartPosition==="right";return k(t,a,e.convertUnitTo??"",this.unitsService,o.min,o.max,r)});displayName=Dt(()=>this.normalizedConfig().displayName??"Gauge Label");pathDataState=vt(null);viewReady=vt(false);gaugeOptions={};constructor(){Fa(()=>{let t=this.normalizedConfig(),i=this.theme(),a=this.gaugePathConfig();!i||!a?.path||ge(()=>this.streams.observe("gaugePath",e=>{e.state!==this.pathDataState()&&this.pathDataState.set(e.state||null);let o=e?.data?.value??null;if(o==null)this.value.set(t.displayScale?.lower??0),this.textValue.set("--");else {let r=t.displayScale?.lower??0,h=t.displayScale?.upper??100,f=Math.min(Math.max(o,r),h);this.value.set(f),this.textValue()==="--"&&this.textValue.set("");}}));}),Fa(()=>{this.normalizedConfig().ignoreZones||ge(()=>this.metadata.observe("gaugePath"));}),Fa(()=>{let t=this.highlights();this.viewReady()&&ge(()=>{try{if(!t.length)this.ngGauge()?.update({highlights:[]});else {let i=JSON.stringify(t);this.ngGauge()?.update({highlights:i,highlightsWidth:this.normalizedConfig().gauge?.highlightsWidth});}}catch(i){}});}),Fa(()=>{let t=this.normalizedConfig(),i=this.theme(),a=this.adjustedScale();i&&ge(()=>{if(this.buildGaugeOptions(t,i,a),this.viewReady())try{this.ngGauge()?.update(this.gaugeOptions);}catch(e){}});}),Fa(()=>{let t=this.ngGauge();!t||this.gaugeBootstrapped()||ge(()=>{try{requestAnimationFrame(()=>{this.gaugeBootstrapped.set(!0);try{t.update({animation:!0,animatedValue:!0});}catch(i){}});}catch(i){}});}),Fa(()=>{let t=this.pathDataState();this.viewReady()&&ge(()=>{let i=this.normalizedConfig(),a=this.theme();if(!a||i.ignoreZones)return;let e={},o=c(i.color??"contrast",a);switch(t){case n$1.Alarm:e.colorBorderMiddle=a.cardColor,e.colorBarProgress=a.zoneAlarm,e.colorValueText=a.zoneAlarm;break;case n$1.Warn:e.colorBorderMiddle=a.cardColor,e.colorBarProgress=a.zoneWarn,e.colorValueText=a.zoneWarn;break;case n$1.Alert:e.colorBorderMiddle=a.cardColor,e.colorBarProgress=a.zoneAlert,e.colorValueText=a.zoneAlert;break;default:e.colorBorderMiddle=a.cardColor,e.colorBarProgress=i.gauge?.subType==="measuring"?o.color:o.dim,e.colorValueText=o.color;}try{this.ngGauge()?.update(e);}catch(r){}});});}ngAfterViewInit(){this.viewReady.set(true),this.setCanvasSize();try{this.ngGauge()?.update(this.gaugeOptions);}catch(t){}}onResized(t){let i={height:t.contentRect.height,width:t.contentRect.width};try{this.ngGauge()?.update(i);}catch(a){}}setCanvasSize(){let t=this.gauge()?.nativeElement;if(!t)return;let i=t.getBoundingClientRect(),a={height:i.height,width:i.width};try{this.ngGauge()?.update(a);}catch(e){}}buildGaugeOptions(t,i,a){let e={},o=this.gaugePathConfig(),r=t.gauge??n.DEFAULT_CONFIG.gauge;e.title=this.displayName(),e.minValue=a.min,e.maxValue=a.max,e.units=o?.convertUnitTo??"",e.highlights=[];let h=this.highlights();h.length&&(e.highlights=JSON.stringify(h),e.highlightsWidth=t.gauge?.highlightsWidth),e.fontTitle="Roboto",e.fontTitleWeight="bold",e.fontUnits="Roboto",e.fontUnitsSize=25,e.fontUnitsWeight="normal",e.barStrokeWidth=0,e.barShadow=0,e.colorBarStroke="",e.fontValue="Roboto",e.fontValueWeight="bold",e.valueTextShadow=false,e.colorValueBoxShadow="",e.fontNumbers="Roboto",e.fontNumbersWeight="bold",e.valueInt=t.numInt??1,e.valueDec=t.numDecimal??2,e.majorTicksInt=e.valueInt,e.majorTicksDec=e.valueDec,e.highlightsWidth=t.gauge?.highlightsWidth,e.animation=this.animationEnabled(),e.animateOnInit=false,e.animatedValue=this.animationEnabled(),e.animationRule="linear";let f=o?.sampleTime??500;e.animationDuration=f-25,e.colorBorderShadow=false,e.colorBorderOuter=i.cardColor,e.colorBorderOuterEnd="",e.colorBorderMiddle=i.cardColor,e.colorBorderMiddleEnd="",e.colorPlate=e.colorPlateEnd=i.cardColor,e.colorBar=i.background;let g=c(t.color??"contrast",i);e.barProgress=t.gauge?.enableProgressbar,e.colorBarProgress=g.color,e.colorNeedle=g.color,e.colorNeedleEnd=g.color,e.needleShadow=true,e.colorNeedleShadowUp="black",e.colorNeedleShadowDown="black",e.colorNeedleCircleInner=e.colorPlate,e.colorNeedleCircleInnerEnd=e.colorPlate,e.colorNeedleCircleOuter=e.colorPlate,e.colorNeedleCircleOuterEnd=e.colorPlate,e.colorTitle=i.contrastDim,e.colorUnits=i.contrastDim,e.colorValueText=g.color,this.colorStrokeTicks.set(i.contrastDim),e.colorMinorTicks=i.contrastDim,e.animationTarget=this.ANIMATION_TARGET_NEEDLE,e.useMinPath=false,r.subType==="capacity"?(e.fontTitleSize=40,e.valueBox=true,e.fontValueSize=60,e.valueBoxWidth=10,e.valueBoxBorderRadius=5,e.valueBoxStroke=0,e.colorValueBoxBackground="",e.colorMajorTicks=e.colorPlate,e.colorNumbers=e.colorMinorTicks="",e.barWidth=20,e.colorBarProgress=g.dim,e.needle=r.enableNeedle,e.needleType=this.LINE,e.needleWidth=2,e.needleStart=75,e.needleEnd=95,e.needleCircleSize=1,e.needleCircleInner=false,e.needleCircleOuter=false,e.ticksAngle=360,e.startAngle=r.scaleStart||180,e.majorTicks=0,e.exactTicks=true,e.strokeTicks=false,e.minorTicks=0,e.numbersMargin=0,e.fontNumbersSize=0,e.borders=true,e.borderOuterWidth=2,e.borderMiddleWidth=1,e.borderInnerWidth=0,e.borderShadowWidth=0):(e.fontTitleSize=24,e.barWidth=15,e.valueBox=true,e.fontValueSize=60,e.valueBoxWidth=100,e.valueBoxBorderRadius=0,e.valueBoxStroke=0,e.colorValueBoxBackground="",e.needle=r.enableNeedle,e.needleType=this.LINE,e.needleWidth=2,e.needleStart=0,e.needleEnd=95,e.needleCircleSize=10,e.needleCircleInner=false,e.needleCircleOuter=false,e.ticksAngle=270,e.startAngle=45,e.barStartPosition=r.barStartPosition||"left",r.enableTicks?(e.strokeTicks=true,e.majorTicks=a.majorTicks,e.minorTicks=2,e.exactTicks=false,e.numbersMargin=3,e.fontNumbersSize=15,e.colorMajorTicks=i.contrastDim,e.colorNumbers=i.contrastDim):(e.strokeTicks=false,e.majorTicks=0,e.minorTicks=0,e.exactTicks=true,e.numbersMargin=0,e.fontNumbersSize=0,e.colorMajorTicks=e.colorPlate,e.colorNumbers=e.colorMinorTicks=""),e.borders=true,e.borderOuterWidth=2,e.borderMiddleWidth=1,e.borderInnerWidth=0,e.borderShadowWidth=0,e.animationTarget=this.ANIMATION_TARGET_NEEDLE,e.useMinPath=false),this.gaugeOptions=e;}static \u0275fac=function(i){return new(i||n)};static \u0275cmp=JD({type:n,selectors:[["widget-gauge-ng-radial"]],viewQuery:function(i,a){i&1&&eg(a.ngGauge,L,5)(a.gauge,L,5,Lr),i&2&&Kw(2);},inputs:{id:[1,"id"],type:[1,"type"],theme:[1,"theme"]},decls:1,vars:1,consts:[["radialGauge",""],["kipResizeObserver","",3,"options","value"],["kipResizeObserver","",3,"resizeChange","options","value"]],template:function(i,a){i&1&&_w(0,F,2,3,"radial-gauge",1),i&2&&Mw(a.shouldRenderGauge()?0:-1);},dependencies:[u,Gt,Lt],styles:["[_nghost-%COMP%]{display:block;width:100%;height:100%} radial-gauge{display:block;position:relative;width:100%;min-width:8px;height:100%;overflow:clip} radial-gauge>canvas{display:block;position:absolute;height:100%;width:100%;left:50%;top:50%;transform:translate(-50%,-50%);padding:0}"]})}return n})();export{ne as WidgetGaugeNgRadialComponent};
1
+ import {p as p$1}from'./chunk-CaD3zVfK.js';import {G as Gt,L as Lt}from'./chunk-B6AwCAvV.js';import {u}from'./chunk-BgyxBAyq.js';import {k}from'./chunk-DfGLo6Tb.js';import {d1 as Hj,w,du as p,dv as rt,dD as _,bu as ut,$ as $j,a6 as Lr,v as vt,D as Dt,F as Fa,dn as ge,J as JD,_ as _w,M as Mw,f as eg,K as Kw,h as Fw,P as Pi,k as Qh,u as ul,g as qw,B as Bh,an as Hh,l as ud,m as dd,dx as n$1}from'./main-BNR44HGB.js';import {c}from'./chunk-D_wrJJxl.js';var L=["radialGauge"];function F(n,q){if(n&1){let t=Fw();Pi(0,"radial-gauge",2,0),Qh("resizeChange",function(a){ud(t);let e=qw();return dd(e.onResized(a))}),ul();}if(n&2){let t=qw();Bh("options",t.gaugeOptions)("value",t.displayValue()),Hh("value-text",t.textValue());}}var ne=(()=>{class n{id=Hj.required();type=Hj.required();theme=Hj.required();runtime=w(p);streams=w(rt);metadata=w(_);unitsService=w(ut);static DEFAULT_CONFIG={supportAutomaticHistoricalSeries:true,displayName:"Gauge Label",filterSelfPaths:true,paths:{gaugePath:{description:"Numeric Data",path:null,source:null,pathType:"number",suppressBootstrapNull:true,isPathConfigurable:true,showPathSkUnitsFilter:true,pathSkUnitsFilter:null,convertUnitTo:"unitless",sampleTime:500}},displayScale:{lower:0,upper:100,type:"linear"},gauge:{type:"ngRadial",subType:"measuring",highlightsWidth:5,scaleStart:180,barStartPosition:"left",enableTicks:true,enableProgressbar:true,enableNeedle:true},numInt:1,numDecimal:0,enableTimeout:false,color:"contrast",dataTimeout:5,ignoreZones:false};LINE="line";ANIMATION_TARGET_NEEDLE="needle";ngGauge=$j("radialGauge");gauge=$j("radialGauge",{read:Lr});value=vt(void 0);displayValue=Dt(()=>this.value()??0);shouldRenderGauge=Dt(()=>this.value()!==void 0);textValue=vt("--");colorStrokeTicks=vt("");gaugeBootstrapped=vt(false);animationEnabled=Dt(()=>this.gaugeBootstrapped());normalizedConfig=Dt(()=>this.runtime.options()??n.DEFAULT_CONFIG);gaugePathConfig=Dt(()=>this.normalizedConfig().paths?.gaugePath);adjustedScale=Dt(()=>{let t=this.normalizedConfig();return t.gauge?.subType==="capacity"?{min:t.displayScale?.lower??0,max:t.displayScale?.upper??100,majorTicks:[]}:p$1(t.displayScale?.lower??0,t.displayScale?.upper??100,t.gauge?.barStartPosition==="right")});highlights=Dt(()=>{let t=this.metadata.zones(),i=this.normalizedConfig(),a=this.theme(),e=this.gaugePathConfig();if(!t?.length)return [];if(!a)return [];if(i.ignoreZones)return [];if(i.gauge?.subType!=="measuring")return [];if(!e)return [];let o=this.adjustedScale(),r=i.gauge?.barStartPosition==="right";return k(t,a,e.convertUnitTo??"",this.unitsService,o.min,o.max,r)});displayName=Dt(()=>this.normalizedConfig().displayName??"Gauge Label");pathDataState=vt(null);viewReady=vt(false);gaugeOptions={};constructor(){Fa(()=>{let t=this.normalizedConfig(),i=this.theme(),a=this.gaugePathConfig();!i||!a?.path||ge(()=>this.streams.observe("gaugePath",e=>{e.state!==this.pathDataState()&&this.pathDataState.set(e.state||null);let o=e?.data?.value??null;if(o==null)this.value.set(t.displayScale?.lower??0),this.textValue.set("--");else {let r=t.displayScale?.lower??0,h=t.displayScale?.upper??100,f=Math.min(Math.max(o,r),h);this.value.set(f),this.textValue()==="--"&&this.textValue.set("");}}));}),Fa(()=>{this.normalizedConfig().ignoreZones||ge(()=>this.metadata.observe("gaugePath"));}),Fa(()=>{let t=this.highlights();this.viewReady()&&ge(()=>{try{if(!t.length)this.ngGauge()?.update({highlights:[]});else {let i=JSON.stringify(t);this.ngGauge()?.update({highlights:i,highlightsWidth:this.normalizedConfig().gauge?.highlightsWidth});}}catch(i){}});}),Fa(()=>{let t=this.normalizedConfig(),i=this.theme(),a=this.adjustedScale();i&&ge(()=>{if(this.buildGaugeOptions(t,i,a),this.viewReady())try{this.ngGauge()?.update(this.gaugeOptions);}catch(e){}});}),Fa(()=>{let t=this.ngGauge();!t||this.gaugeBootstrapped()||ge(()=>{try{requestAnimationFrame(()=>{this.gaugeBootstrapped.set(!0);try{t.update({animation:!0,animatedValue:!0});}catch(i){}});}catch(i){}});}),Fa(()=>{let t=this.pathDataState();this.viewReady()&&ge(()=>{let i=this.normalizedConfig(),a=this.theme();if(!a||i.ignoreZones)return;let e={},o=c(i.color??"contrast",a);switch(t){case n$1.Alarm:e.colorBorderMiddle=a.cardColor,e.colorBarProgress=a.zoneAlarm,e.colorValueText=a.zoneAlarm;break;case n$1.Warn:e.colorBorderMiddle=a.cardColor,e.colorBarProgress=a.zoneWarn,e.colorValueText=a.zoneWarn;break;case n$1.Alert:e.colorBorderMiddle=a.cardColor,e.colorBarProgress=a.zoneAlert,e.colorValueText=a.zoneAlert;break;default:e.colorBorderMiddle=a.cardColor,e.colorBarProgress=i.gauge?.subType==="measuring"?o.color:o.dim,e.colorValueText=o.color;}try{this.ngGauge()?.update(e);}catch(r){}});});}ngAfterViewInit(){this.viewReady.set(true),this.setCanvasSize();try{this.ngGauge()?.update(this.gaugeOptions);}catch(t){}}onResized(t){let i={height:t.contentRect.height,width:t.contentRect.width};try{this.ngGauge()?.update(i);}catch(a){}}setCanvasSize(){let t=this.gauge()?.nativeElement;if(!t)return;let i=t.getBoundingClientRect(),a={height:i.height,width:i.width};try{this.ngGauge()?.update(a);}catch(e){}}buildGaugeOptions(t,i,a){let e={},o=this.gaugePathConfig(),r=t.gauge??n.DEFAULT_CONFIG.gauge;e.title=this.displayName(),e.minValue=a.min,e.maxValue=a.max,e.units=o?.convertUnitTo??"",e.highlights=[];let h=this.highlights();h.length&&(e.highlights=JSON.stringify(h),e.highlightsWidth=t.gauge?.highlightsWidth),e.fontTitle="Roboto",e.fontTitleWeight="bold",e.fontUnits="Roboto",e.fontUnitsSize=25,e.fontUnitsWeight="normal",e.barStrokeWidth=0,e.barShadow=0,e.colorBarStroke="",e.fontValue="Roboto",e.fontValueWeight="bold",e.valueTextShadow=false,e.colorValueBoxShadow="",e.fontNumbers="Roboto",e.fontNumbersWeight="bold",e.valueInt=t.numInt??1,e.valueDec=t.numDecimal??2,e.majorTicksInt=e.valueInt,e.majorTicksDec=e.valueDec,e.highlightsWidth=t.gauge?.highlightsWidth,e.animation=this.animationEnabled(),e.animateOnInit=false,e.animatedValue=this.animationEnabled(),e.animationRule="linear";let f=o?.sampleTime??500;e.animationDuration=f-25,e.colorBorderShadow=false,e.colorBorderOuter=i.cardColor,e.colorBorderOuterEnd="",e.colorBorderMiddle=i.cardColor,e.colorBorderMiddleEnd="",e.colorPlate=e.colorPlateEnd=i.cardColor,e.colorBar=i.background;let g=c(t.color??"contrast",i);e.barProgress=t.gauge?.enableProgressbar,e.colorBarProgress=g.color,e.colorNeedle=g.color,e.colorNeedleEnd=g.color,e.needleShadow=true,e.colorNeedleShadowUp="black",e.colorNeedleShadowDown="black",e.colorNeedleCircleInner=e.colorPlate,e.colorNeedleCircleInnerEnd=e.colorPlate,e.colorNeedleCircleOuter=e.colorPlate,e.colorNeedleCircleOuterEnd=e.colorPlate,e.colorTitle=i.contrastDim,e.colorUnits=i.contrastDim,e.colorValueText=g.color,this.colorStrokeTicks.set(i.contrastDim),e.colorMinorTicks=i.contrastDim,e.animationTarget=this.ANIMATION_TARGET_NEEDLE,e.useMinPath=false,r.subType==="capacity"?(e.fontTitleSize=40,e.valueBox=true,e.fontValueSize=60,e.valueBoxWidth=10,e.valueBoxBorderRadius=5,e.valueBoxStroke=0,e.colorValueBoxBackground="",e.colorMajorTicks=e.colorPlate,e.colorNumbers=e.colorMinorTicks="",e.barWidth=20,e.colorBarProgress=g.dim,e.needle=r.enableNeedle,e.needleType=this.LINE,e.needleWidth=2,e.needleStart=75,e.needleEnd=95,e.needleCircleSize=1,e.needleCircleInner=false,e.needleCircleOuter=false,e.ticksAngle=360,e.startAngle=r.scaleStart||180,e.majorTicks=0,e.exactTicks=true,e.strokeTicks=false,e.minorTicks=0,e.numbersMargin=0,e.fontNumbersSize=0,e.borders=true,e.borderOuterWidth=2,e.borderMiddleWidth=1,e.borderInnerWidth=0,e.borderShadowWidth=0):(e.fontTitleSize=24,e.barWidth=15,e.valueBox=true,e.fontValueSize=60,e.valueBoxWidth=100,e.valueBoxBorderRadius=0,e.valueBoxStroke=0,e.colorValueBoxBackground="",e.needle=r.enableNeedle,e.needleType=this.LINE,e.needleWidth=2,e.needleStart=0,e.needleEnd=95,e.needleCircleSize=10,e.needleCircleInner=false,e.needleCircleOuter=false,e.ticksAngle=270,e.startAngle=45,e.barStartPosition=r.barStartPosition||"left",r.enableTicks?(e.strokeTicks=true,e.majorTicks=a.majorTicks,e.minorTicks=2,e.exactTicks=false,e.numbersMargin=3,e.fontNumbersSize=15,e.colorMajorTicks=i.contrastDim,e.colorNumbers=i.contrastDim):(e.strokeTicks=false,e.majorTicks=0,e.minorTicks=0,e.exactTicks=true,e.numbersMargin=0,e.fontNumbersSize=0,e.colorMajorTicks=e.colorPlate,e.colorNumbers=e.colorMinorTicks=""),e.borders=true,e.borderOuterWidth=2,e.borderMiddleWidth=1,e.borderInnerWidth=0,e.borderShadowWidth=0,e.animationTarget=this.ANIMATION_TARGET_NEEDLE,e.useMinPath=false),this.gaugeOptions=e;}static \u0275fac=function(i){return new(i||n)};static \u0275cmp=JD({type:n,selectors:[["widget-gauge-ng-radial"]],viewQuery:function(i,a){i&1&&eg(a.ngGauge,L,5)(a.gauge,L,5,Lr),i&2&&Kw(2);},inputs:{id:[1,"id"],type:[1,"type"],theme:[1,"theme"]},decls:1,vars:1,consts:[["radialGauge",""],["kipResizeObserver","",3,"options","value"],["kipResizeObserver","",3,"resizeChange","options","value"]],template:function(i,a){i&1&&_w(0,F,2,3,"radial-gauge",1),i&2&&Mw(a.shouldRenderGauge()?0:-1);},dependencies:[u,Gt,Lt],styles:["[_nghost-%COMP%]{display:block;width:100%;height:100%} radial-gauge{display:block;position:relative;width:100%;min-width:8px;height:100%;overflow:clip} radial-gauge>canvas{display:block;position:absolute;height:100%;width:100%;left:50%;top:50%;transform:translate(-50%,-50%);padding:0}"]})}return n})();export{ne as WidgetGaugeNgRadialComponent};