@eox/chart 2.0.0-alpha10 → 2.0.0-alpha12

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.
@@ -22,4 +22,4 @@ var tc=Object.defineProperty;var ec=(i,t,e)=>t in i?tc(i,t,{enumerable:!0,config
22
22
  * Released under the MIT license
23
23
  */const ip={datetime:O.DATETIME_MED_WITH_SECONDS,millisecond:"h:mm:ss.SSS a",second:O.TIME_WITH_SECONDS,minute:O.TIME_SIMPLE,hour:{hour:"numeric"},day:{day:"numeric",month:"short"},week:"DD",month:{month:"short",year:"numeric"},quarter:"'Q'q - yyyy",year:{year:"numeric"}};Ma._date.override({_id:"luxon",_create:function(i){return O.fromMillis(i,this.options)},init(i){this.options.locale||(this.options.locale=i.locale)},formats:function(){return ip},parse:function(i,t){const e=this.options,s=typeof i;return i===null||s==="undefined"?null:(s==="number"?i=this._create(i):s==="string"?typeof t=="string"?i=O.fromFormat(i,t,e):i=O.fromISO(i,e):i instanceof Date?i=O.fromJSDate(i,e):s==="object"&&!(i instanceof O)&&(i=O.fromObject(i,e)),i.isValid?i.valueOf():null)},format:function(i,t){const e=this._create(i);return typeof t=="string"?e.toFormat(t):e.toLocaleString(t)},add:function(i,t,e){const s={};return s[e]=t,this._create(i).plus(s).valueOf()},diff:function(i,t,e){return this._create(i).diff(this._create(t)).as(e).valueOf()},startOf:function(i,t,e){if(t==="isoWeek"){e=Math.trunc(Math.min(Math.max(0,e),6));const s=this._create(i);return s.minus({days:(s.weekday-e+7)%7}).startOf("day").valueOf()}return t?this._create(i).startOf(t).valueOf():i},endOf:function(i,t){return this._create(i).endOf(t).valueOf()}});function sp(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var vn={},np={get exports(){return vn},set exports(i){vn=i}},jl={};function St(i,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(i)),this._timeouts=i,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}var rp=St;St.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)};St.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null};St.prototype.retry=function(i){if(this._timeout&&clearTimeout(this._timeout),!i)return!1;var t=new Date().getTime();if(i&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(i),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(i);var e=this._timeouts.shift();if(e===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),e=this._cachedTimeouts.slice(-1);else return!1;var s=this;return this._timer=setTimeout(function(){s._attempts++,s._operationTimeoutCb&&(s._timeout=setTimeout(function(){s._operationTimeoutCb(s._attempts)},s._operationTimeout),s._options.unref&&s._timeout.unref()),s._fn(s._attempts)},e),this._options.unref&&this._timer.unref(),!0};St.prototype.attempt=function(i,t){this._fn=i,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var e=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){e._operationTimeoutCb()},e._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};St.prototype.try=function(i){console.log("Using RetryOperation.try() is deprecated"),this.attempt(i)};St.prototype.start=function(i){console.log("Using RetryOperation.start() is deprecated"),this.attempt(i)};St.prototype.start=St.prototype.try;St.prototype.errors=function(){return this._errors};St.prototype.attempts=function(){return this._attempts};St.prototype.mainError=function(){if(this._errors.length===0)return null;for(var i={},t=null,e=0,s=0;s<this._errors.length;s++){var n=this._errors[s],r=n.message,o=(i[r]||0)+1;i[r]=o,o>=e&&(t=n,e=o)}return t};(function(i){var t=rp;i.operation=function(e){var s=i.timeouts(e);return new t(s,{forever:e&&(e.forever||e.retries===1/0),unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})},i.timeouts=function(e){if(e instanceof Array)return[].concat(e);var s={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var n in e)s[n]=e[n];if(s.minTimeout>s.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var r=[],o=0;o<s.retries;o++)r.push(this.createTimeout(o,s));return e&&e.forever&&!r.length&&r.push(this.createTimeout(o,s)),r.sort(function(a,l){return a-l}),r},i.createTimeout=function(e,s){var n=s.randomize?Math.random()+1:1,r=Math.round(n*Math.max(s.minTimeout,1)*Math.pow(s.factor,e));return r=Math.min(r,s.maxTimeout),r},i.wrap=function(e,s,n){if(s instanceof Array&&(n=s,s=null),!n){n=[];for(var r in e)typeof e[r]=="function"&&n.push(r)}for(var o=0;o<n.length;o++){var a=n[o],l=e[a];e[a]=function(h){var u=i.operation(s),d=Array.prototype.slice.call(arguments,1),f=d.pop();d.push(function(m){u.retry(m)||(m&&(arguments[0]=u.mainError()),f.apply(this,arguments))}),u.attempt(function(){h.apply(e,d)})}.bind(e,l),e[a].options=s}}})(jl);(function(i){i.exports=jl})(np);const op=sp(vn),ap=new Set(["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed"]);class Ul extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}}const lp=(i,t,e)=>{const s=e.retries-(t-1);return i.attemptNumber=t,i.retriesLeft=s,i},cp=i=>ap.has(i),Bo=i=>globalThis.DOMException===void 0?new Error(i):new DOMException(i);async function hp(i,t){return new Promise((e,s)=>{t={onFailedAttempt(){},retries:10,...t};const n=op.operation(t);n.attempt(async r=>{try{e(await i(r))}catch(o){if(!(o instanceof Error)){s(new TypeError(`Non-error was thrown: "${o}". You should only throw errors.`));return}if(o instanceof Ul)n.stop(),s(o.originalError);else if(o instanceof TypeError&&!cp(o.message))n.stop(),s(o);else{lp(o,r,t);try{await t.onFailedAttempt(o)}catch(a){s(a);return}n.retry(o)||s(n.mainError())}}}),t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",()=>{n.stop();const r=t.signal.reason===void 0?Bo("The operation was aborted."):t.signal.reason;s(r instanceof Error?r:Bo(r))},{once:!0})})}const Ps={errorBarLineWidth:{v:[1,3]},errorBarColor:{v:["#2c2c2c","#1f1f1f"]},errorBarWhiskerLineWidth:{v:[1,3]},errorBarWhiskerRatio:{v:[.2,.25]},errorBarWhiskerSize:{v:[20,24]},errorBarWhiskerColor:{v:["#2c2c2c","#1f1f1f"]}},Yn={_scriptable:!0,_indexable:i=>i!=="v"},Ho=Object.keys(Ps);function Zn(i,t){const e=Array.isArray(i)?i:[i],s=Array.isArray(t)?t:[t];if(e.length===s.length)return e.map((r,o)=>[r,s[o]]);const n=Math.max(e.length,s.length);return Array(n).map((r,o)=>[e[o%e.length],s[o%s.length]])}function dt(i,t){if(typeof i=="string"||typeof i=="number")return i;const e=Array.isArray(i)?i:i.v;return e[t%e.length]}function qn(i,t,e){const s=dt(t.errorBarWhiskerRatio,e);return i!=null&&s>0?i*s*.5:dt(t.errorBarWhiskerSize,e)*.5}function up(i,t,e,s,n){n.save(),n.translate(i.x,0);const r=Zn(t??i.y,e??i.y);r.reverse().forEach(([o,a],l)=>{const c=r.length-l-1,h=qn(i.width,s,c);n.lineWidth=dt(s.errorBarLineWidth,c),n.strokeStyle=dt(s.errorBarColor,c),n.beginPath(),n.moveTo(0,o),n.lineTo(0,a),n.stroke(),n.lineWidth=dt(s.errorBarWhiskerLineWidth,c),n.strokeStyle=dt(s.errorBarWhiskerColor,c),n.beginPath(),n.moveTo(-h,o),n.lineTo(h,o),n.moveTo(-h,a),n.lineTo(h,a),n.stroke()}),n.restore()}function dp(i,t,e,s,n){n.save(),n.translate(0,i.y);const r=Zn(t??i.x,e??i.x);r.reverse().forEach(([o,a],l)=>{const c=r.length-l-1,h=qn(i.height,s,c);n.lineWidth=dt(s.errorBarLineWidth,c),n.strokeStyle=dt(s.errorBarColor,c),n.beginPath(),n.moveTo(o,0),n.lineTo(a,0),n.stroke(),n.lineWidth=dt(s.errorBarWhiskerLineWidth,c),n.strokeStyle=dt(s.errorBarWhiskerColor,c),n.beginPath(),n.moveTo(o,-h),n.lineTo(o,h),n.moveTo(a,-h),n.lineTo(a,h),n.stroke()}),n.restore()}function Yl(i,t){var e,s,n,r;const o=i.getProps(["x","y","width","height","xMin","xMax","yMin","yMax"]);(o.xMin!=null||o.xMax!=null)&&dp(o,(e=o.xMin)!==null&&e!==void 0?e:null,(s=o.xMax)!==null&&s!==void 0?s:null,i.options,t),(o.yMin!=null||o.yMax!=null)&&up(o,(n=o.yMin)!==null&&n!==void 0?n:null,(r=o.yMax)!==null&&r!==void 0?r:null,i.options,t)}function fp(i,t,e,s,n){n.save(),n.translate(i.x,i.y);const r=(i.startAngle+i.endAngle)/2,o=Math.cos(r),a=Math.sin(r),l={x:-a,y:o},c=Math.sqrt(l.x*l.x+l.y*l.y);l.x/=c,l.y/=c;const h=Zn(t??i.outerRadius,e??i.outerRadius);h.reverse().forEach(([u,d],f)=>{const m=h.length-f-1,g=u*o,p=u*a,b=d*o,y=d*a,v=qn(null,s,m),_=l.x*v,x=l.y*v;n.lineWidth=dt(s.errorBarLineWidth,m),n.strokeStyle=dt(s.errorBarColor,m),n.beginPath(),n.moveTo(g,p),n.lineTo(b,y),n.stroke(),n.lineWidth=dt(s.errorBarWhiskerLineWidth,m),n.strokeStyle=dt(s.errorBarWhiskerColor,m),n.beginPath(),n.moveTo(g+_,p+x),n.lineTo(g-_,p-x),n.moveTo(b+_,y+x),n.lineTo(b-_,y-x),n.stroke()}),n.restore()}function mp(i,t){const e=i.getProps(["x","y","startAngle","endAngle","rMin","rMax","outerRadius"]);(e.rMin!=null||e.rMax!=null)&&fp(e,e.rMin,e.rMax,i.options,t)}class Ze extends xe{draw(t){super.draw(t),Yl(this,t)}}Ze.id="barWithErrorBar";Ze.defaults={...xe.defaults,...Ps};Ze.defaultRoutes=xe.defaultRoutes;Ze.descriptors=Yn;class yt extends ye{draw(t,e){super.draw.call(this,t,e),Yl(this,t)}}yt.id="pointWithErrorBar";yt.defaults={...ye.defaults,...Ps};yt.defaultRoutes=ye.defaultRoutes;yt.descriptors=Yn;class qe extends be{draw(t){super.draw(t),mp(this,t)}}qe.id="arcWithErrorBar";qe.defaults={...be.defaults,...Ps};qe.defaultRoutes=be.defaultRoutes;qe.descriptors=Yn;const wn=["xMin","xMax","yMin","yMax"];function Zl(i){return i?wn.slice(0,2):wn.slice(2)}function Ei(i,t,e,s,n){const r=[`${s.axis}Min`,`${s.axis}Max`],o=s.getBasePixel();for(const a of r){const l=t[a];Array.isArray(l)?i[a]=l.map(c=>n?o:s.getPixelForValue(c,e)):typeof l=="number"?i[a]=n?o:s.getPixelForValue(l,e):i[a]=null}}function gp(i,t,e,s,n){const r=n.animation,o=[`${e.axis}Min`,`${e.axis}Max`],a=l=>{const c=e.getDistanceFromCenterForValue(l),h=r.animateScale?0:c;return s?h:c};for(const l of o){const c=t[l];Array.isArray(c)?i[l]=c.map(a):typeof c=="number"?i[l]=a(c):i[l]=null}}function Xn(i){return Array.isArray(i)?i.slice().reverse():i}function ql(i){const t=Zl(i.element.horizontal),e=$a.defaults.callbacks.label.call(this,i),s=i.chart.data.datasets[i.datasetIndex].data[i.dataIndex];return s==null||t.every(n=>s[n]==null)?e:`${e} (${Xn(s[t[0]])} .. ${s[t[1]]})`}function pp(i){const t=i.chart.data.datasets[i.datasetIndex].data[i.dataIndex],e=(s,n)=>{const r=Zl(n);return t==null||r.every(o=>t[o]==null)?s:`${s} [${Xn(t[r[0]])} .. ${t[r[1]]}]`};return`(${e(i.label,!0)}, ${e(i.parsed.y,!1)})`}function bp(i){const t=Ft.overrides.plugins.tooltip.callbacks.label.call(this,i),e=i.chart.data.datasets[i.datasetIndex].data[i.dataIndex],s=["rMin","rMax"];return e==null||s.every(n=>e[n]==null)?t:`${t} [${Xn(e[s[0]])} .. ${e[s[1]]}]`}const Xl={color(i,t,e){const s=i||"transparent",n=t||"transparent";if(s===n)return t;const r=ds(s),o=r.valid&&ds(n);return o&&o.valid?o.mix(r,e).hexString():t},number(i,t,e){return i===t?t:i+(t-i)*e}};function Gl(i,t,e,s,n){if(typeof i===s&&typeof t===s)return n(i,t,e);if(Array.isArray(i)&&Array.isArray(t))return i.map((o,a)=>n(o,t[a],e));const r=o=>o&&Array.isArray(o.v);return r(i)&&r(t)?{v:i.v.map((o,a)=>n(o,t.v[a],e))}:t}function yp(i,t,e){return Gl(i,t,e,"number",Xl.number)}function xp(i,t,e){return Gl(i,t,e,"string",Xl.color)}const Is={animations:{numberArray:{fn:yp,properties:wn.concat(Ho.filter(i=>!i.endsWith("Color")),["rMin","rMax"])},colorArray:{fn:xp,properties:Ho.filter(i=>i.endsWith("Color"))}}};function Ls(i,t){const{axis:e}=i;i.axis=`${e}MinMin`;const{min:s}=t(i);i.axis=`${e}MaxMax`;const{max:n}=t(i);return i.axis=e,{min:s,max:n}}function $o(i,t,e){return Array.isArray(t)?e(i,...t):typeof t=="number"?e(i,t):i}function He(i,t,e,s,n){const r=typeof t=="string"?t:t.axis,o=`${r}Min`,a=`${r}Max`,l=`${r}MinMin`,c=`${r}MaxMax`;for(let h=0;h<n;h+=1){const u=h+s,d=i[h];d[o]=typeof e[u]=="object"?e[u][o]:null,d[a]=typeof e[u]=="object"?e[u][a]:null,d[l]=$o(d[r],d[o],Math.min),d[c]=$o(d[r],d[a],Math.max)}}function Jl(i,t,e,s){const{axis:n}=t,r=t.getLabels();for(let o=0;o<s;o+=1){const a=o+e,l=i[o];l[n]=t.parse(r[a],a)}}function Fs(i,t,e,s=[],n=[]){at.addControllers(e),Array.isArray(s)?at.addElements(...s):at.addElements(s),Array.isArray(n)?at.addScales(...n):at.addScales(n);const r=t;return r.type=i,r}class Xe extends te{getMinMax(t,e){return Ls(t,s=>super.getMinMax(s,e))}parsePrimitiveData(t,e,s,n){const r=super.parsePrimitiveData(t,e,s,n);return this.parseErrorData(r,t,e,s,n),r}parseObjectData(t,e,s,n){const r=super.parseObjectData(t,e,s,n);return this.parseErrorData(r,t,e,s,n),r}parseErrorData(t,e,s,n,r){He(t,e.vScale,s,n,r),Jl(t,e.iScale,n,r)}updateElement(t,e,s,n){typeof e=="number"&&Ei(s,this.getParsed(e),e,this._cachedMeta.vScale,n==="reset"),super.updateElement(t,e,s,n)}}Xe.id="barWithErrorBars";Xe.defaults=bt({},[te.defaults,Is,{dataElementType:Ze.id}]);Xe.overrides=bt({},[te.overrides,{plugins:{tooltip:{callbacks:{label:ql}}}}]);Xe.defaultRoutes=te.defaultRoutes;class _p extends ht{constructor(t,e){super(t,Fs("barWithErrorBars",e,Xe,Ze,[Me,We]))}}_p.id=Xe.id;const jo=["linear","logarithmic","time","timeseries"];class Te extends $t{getMinMax(t,e){return Ls(t,s=>super.getMinMax(s,e))}parsePrimitiveData(t,e,s,n){const r=super.parsePrimitiveData(t,e,s,n);return this.parseErrorData(r,t,e,s,n),r}parseObjectData(t,e,s,n){const r=super.parseObjectData(t,e,s,n);return this.parseErrorData(r,t,e,s,n),r}parseErrorData(t,e,s,n,r){He(t,e.vScale,s,n,r);const o=e.iScale;jo.includes(o.type)?He(t,e.iScale,s,n,r):Jl(t,e.iScale,n,r)}updateElement(t,e,s,n){t instanceof yt&&typeof e=="number"&&this.updateElementScale(e,s,n),super.updateElement(t,e,s,n)}updateElementScale(t,e,s){Ei(e,this.getParsed(t),t,this._cachedMeta.vScale,s==="reset");const n=this._cachedMeta.iScale;jo.includes(n.type)&&Ei(e,this.getParsed(t),t,this._cachedMeta.iScale,s==="reset")}updateElements(t,e,s,n){const r=n==="reset",a=this.chart._animationsDisabled||r||n==="none";if(super.updateElements(t,e,s,n),!!a)for(let l=e;l<e+s;++l){const c=t[l];c instanceof yt&&this.updateElementScale(l,c,n)}}}Te.id="lineWithErrorBars";Te.defaults=bt({},[$t.defaults,Is,{dataElementType:yt.id}]);Te.overrides=bt({},[$t.overrides,{plugins:{tooltip:{callbacks:{label:ql}}}}]);Te.defaultRoutes=$t.defaultRoutes;class Kl extends ht{constructor(t,e){super(t,Fs("lineWithErrorBars",e,Te,yt,[Me,We]))}}Kl.id=Te.id;class Oe extends pe{getMinMax(t,e){return Ls(t,s=>super.getMinMax(s,e))}parsePrimitiveData(t,e,s,n){const r=super.parsePrimitiveData(t,e,s,n);return this.parseErrorData(r,t,e,s,n),r}parseObjectData(t,e,s,n){const r=super.parseObjectData(t,e,s,n);return this.parseErrorData(r,t,e,s,n),r}parseErrorData(t,e,s,n,r){He(t,e.xScale,s,n,r),He(t,e.yScale,s,n,r)}updateElement(t,e,s,n){t instanceof yt&&typeof e=="number"&&this.updateElementScale(e,s,n),super.updateElement(t,e,s,n)}updateElementScale(t,e,s){Ei(e,this.getParsed(t),t,this._cachedMeta.xScale,s==="reset"),Ei(e,this.getParsed(t),t,this._cachedMeta.yScale,s==="reset")}updateElements(t,e,s,n){const r=n==="reset",a=this.chart._animationsDisabled||r||n==="none";if(super.updateElements(t,e,s,n),!!a)for(let l=e;l<e+s;++l){const c=t[l];c instanceof yt&&this.updateElementScale(l,c,n)}}}Oe.id="scatterWithErrorBars";Oe.defaults=bt({},[pe.defaults,Is,{dataElementType:yt.id}]);Oe.overrides=bt({},[pe.overrides,{plugins:{tooltip:{callbacks:{label:pp}}}}]);Oe.defaultRoutes=$t.defaultRoutes;class Ql extends ht{constructor(t,e){super(t,Fs("scatterWithErrorBars",e,Oe,yt,[Me]))}}Ql.id=Oe.id;class Ge extends Ft{getMinMaxImpl(t){const e=this._cachedMeta,s={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY};return e.data.forEach((n,r)=>{const o=this.getParsed(r)[t.axis];Number.isNaN(o)||!this.chart.getDataVisibility(r)||(o<s.min&&(s.min=o),o>s.max&&(s.max=o))}),s}getMinMax(t){return Ls(t,e=>this.getMinMaxImpl(e))}countVisibleElements(){const t=this._cachedMeta;return t.data.reduce((e,s,n)=>!Number.isNaN(t._parsed[n].r)&&this.chart.getDataVisibility(n)?e+1:e,0)}parsePrimitiveData(t,e,s,n){const r=super.parsePrimitiveData(t,e,s,n);return this.parseErrorData(r,t,e,s,n),r}parseObjectData(t,e,s,n){const r=super.parseObjectData(t,e,s,n);return this.parseErrorData(r,t,e,s,n),r}parseErrorData(t,e,s,n,r){const o=e.rScale;for(let a=0;a<r;a+=1){const l=a+n,c=s[l],h=o.parse(c[o.axis],l);t[a]={[o.axis]:h}}He(t,o,s,n,r)}updateElement(t,e,s,n){typeof e=="number"&&gp(s,this.getParsed(e),this._cachedMeta.rScale,n==="reset",this.chart.options),super.updateElement(t,e,s,n)}updateElements(t,e,s,n){const r=this.chart.scales.r,o=r.getDistanceFromCenterForValue;r.getDistanceFromCenterForValue=function(l){return typeof l=="number"?o.call(this,l):o.call(this,l.r)},super.updateElements(t,e,s,n),r.getDistanceFromCenterForValue=o}}Ge.id="polarAreaWithErrorBars";Ge.defaults=bt({},[Ft.defaults,Is,{dataElementType:qe.id}]);Ge.overrides=bt({},[Ft.overrides,{plugins:{tooltip:{callbacks:{label:bp}}}}]);Ge.defaultRoutes=Ft.defaultRoutes;class vp extends ht{constructor(t,e){super(t,Fs("polarAreaWithErrorBars",e,Ge,qe,[Le]))}}vp.id=Ge.id;ht.register(Te,Kl,yt,Ql,Oe,Me,We);class wp{constructor(t,e){k(this,"chart");k(this,"startTime");k(this,"endTime");k(this,"timeAggregation");k(this,"options");k(this,"chartOptions");k(this,"dataStorage");k(this,"status");k(this,"activeFields");k(this,"additionalYAxis");this.chart=t,this.options=e,this.startTime=O.now().minus(e.timeInterval),this.endTime=O.now(),e.startTime&&e.endTime&&(this.startTime=O.fromISO(e.startTime).setZone("UTC"),this.endTime=O.fromISO(e.endTime).setZone("UTC")),this.options.timeAggregation&&(this.timeAggregation=this.options.timeAggregation),this.options.retries=this.options.retries?this.options.retries:5,this.options.normalize=this.options.normalize?this.options.normalize:!1,this.options.showMinMax=this.options.showMinMax?this.options.showMinMax:!1,this.additionalYAxis=this.options.additionalYAxis?this.options.additionalYAxis:null,this.dataStorage={},this.options.features.forEach((s,n)=>this.dataStorage[n]={}),this.status="ready",this.chartOptions={scales:{x:{type:"time",min:this.startTime.toISODate(),max:this.endTime.toISODate(),ticks:{minRotation:0,maxRotation:0}}},interaction:{axis:"x",mode:"nearest",intersect:!1},plugins:{legend:{labels:{usePointStyle:!0,pointStyle:"rect",padding:5,sort:(s,n)=>s.text.localeCompare(n.text)},position:"right",onClick:(s,n)=>{if(n.hidden)this.setActiveFields([...this.activeFields,n.text]);else{const r=this.activeFields.indexOf(n.text),o=this.activeFields;o.splice(r,1),this.setActiveFields(o)}}},tooltip:{callbacks:{title:s=>{var r;return((r=s[0])==null?void 0:r.raw).x.toISODate()},label:s=>{const n=s.raw;return`${s.dataset.label}: ↔ ${n.y.toPrecision(3)}; ↓ ${n.yMin.toPrecision(3)}, ↑ ${n.yMax.toPrecision(3)}`}}}}};for(let s=0;s<this.additionalYAxis.length;s++){const n=this.additionalYAxis[s];this.chartOptions.scales[n.id]={type:"linear",position:"right"}}}checkLoadingStatus(){const t=document.getElementById("loadingIndicator");let e=!1;Object.keys(this.dataStorage).forEach((s,n)=>{Object.keys(this.dataStorage[n]).forEach(r=>{this.dataStorage[n][r].status==="fetching"&&(e=!0)})}),t.className=e?"loader":"loader hidden"}fetchSignals(t,e,s){const n=this.options.features[t].map(c=>`feature=${c}`).join("&"),r=`${e?"&start_date="+e.toISODate():""}${s?"&end_date="+s.toISODate():""}`,o=`${this.options.endpoint}?source=${this.options.source}&${n}${r}`,a=this.options.geometry;async function l(){const c=await fetch(o,{headers:{"Content-Type":"application/json; charset=utf-8"},method:"POST",mode:"cors",body:JSON.stringify({geometry:a})});if(c.status===404)throw new Ul(c.statusText);if(c.status!==200)throw Error(c.statusText);return c}return hp(l,{onFailedAttempt:c=>{console.log(`Attempt ${c.attemptNumber} failed. There are ${c.retriesLeft} retries left.`)},retries:this.options.retries}).then(function(c){return c.json()})}updateChart(){this.checkLoadingStatus(),this.chart.options=this.chartOptions;const t=[];this.options.features.flat().forEach((e,s)=>{let n=-1;if(this.options.features.forEach((r,o)=>{r.includes(e)&&(n=o)}),n!==-1){let r=[];Object.keys(this.dataStorage[n]).forEach(u=>{const d=this.dataStorage[n][u];d.status==="finished"?Object.keys(d.data).length!==0&&Object.keys(d.data).includes(e)&&r.push(...d.data[e]):r.push({date:"missing"})});let o=!1,a=Number.MIN_VALUE,l=Number.MAX_VALUE,c=r.map(u=>{let d={};if(u&&u.date!=="missing"){const f=u.basicStats;this.options.showMinMax?(l=f.min<l?f.min:l,a=f.max>a?f.max:a):(l=f.mean<l?f.mean:l,a=f.mean>a?f.mean:a),d={x:O.fromISO(u.date).setZone("UTC"),y:u.basicStats.mean,yMin:u.basicStats.min,yMax:u.basicStats.max},o=!0}return d});if(o&&this.timeAggregation){a=Number.MIN_VALUE,l=Number.MAX_VALUE;const u=[];let d=0,f=O.fromObject({year:this.startTime.year,month:this.startTime.month,day:this.startTime.day});for(;f<this.endTime;){let m=0,g=0,p=0;for(;d<c.length&&(Object.keys(c[d]).length===0||c[d].x<f);)d++;const b=d;for(;d<c.length&&(Object.keys(c[d]).length===0||c[d].x<f.plus(this.timeAggregation));){const _=c[d];m+=_.y,g+=_.yMin,p+=_.yMax,d++}const v=d-b;if(v>0){const _=m/v,x=g/v,w=p/v;this.options.showMinMax?(l=x<l?x:l,a=w>a?w:a):(l=_<l?_:l,a=_>a?_:a),u.push({x:f,y:_,yMin:x,yMax:w})}f=f.plus(this.timeAggregation)}c=u}o&&this.options.normalize&&(c=c.map(u=>(u.y=(u.y-l)/(a-l),u.yMin=(u.yMin-l)/(a-l),u.yMax=(u.yMax-l)/(a-l),u)));let h={type:"line",label:e,data:c,hidden:!this.activeFields.includes(e)};if(this.options.showMinMax&&(h={type:"lineWithErrorBars",label:e,data:c,hidden:!this.activeFields.includes(e),errorBarWhiskerLineWidth:2,errorBarColor:"#00000000"}),this.options.colors&&this.options.colors.length>=s){const u=this.options.colors[s];h.backgroundColor=u,h.borderColor=u,this.options.showMinMax&&(h={type:"lineWithErrorBars",label:e,data:c,hidden:!this.activeFields.includes(e),errorBarWhiskerLineWidth:2,errorBarColor:"#00000000",errorBarWhiskerColor:u,errorBarWhiskerSize:10,backgroundColor:u,borderColor:u})}if(this.additionalYAxis!==null)for(let u=0;u<this.additionalYAxis.length;u++){const d=this.additionalYAxis[u];d.containedSignals.includes(e)&&(h.yAxisID=d.id)}t.push(h)}}),this.chart.data={datasets:t},this.chart.update("none")}retrieveMissingData(){const t=[];this.activeFields.forEach(n=>{this.options.features.forEach((r,o)=>{r.includes(n)&&!t.includes(o)&&t.push(o)})});let e=O.fromObject({year:this.endTime.year,month:this.endTime.month}).plus({month:1}).minus({second:1});const s=O.fromObject({year:this.startTime.year,month:this.startTime.month}).plus({month:1}).minus({second:1});for(;e>s;){const n=e.toFormat("yyyyMM");t.forEach(r=>{if(!(n in this.dataStorage[r])){const o=this.fetchSignals(r,O.fromObject({year:e.year,month:e.month}),O.fromObject({year:e.year,month:e.month}).plus({month:1}).minus({second:1})).then(a=>{this.dataStorage[r][n].data=a,this.dataStorage[r][n].status="finished",this.updateChart()}).catch(()=>{this.dataStorage[r][n].status="failed",this.updateChart()});this.dataStorage[r][n]={request:o,status:"fetching"}}}),e=e.minus({months:1})}}triggerCSVDownload(){const t=[],e=[],s=this.activeFields;s.forEach((l,c)=>{let h=-1;if(this.options.features.forEach((u,d)=>{u.includes(l)&&(h=d)}),h!==-1){let u=[];Object.keys(this.dataStorage[h]).forEach(d=>{const f=this.dataStorage[h][d];f.status==="finished"&&Object.keys(f.data).length!==0&&Object.keys(f.data).includes(l)&&u.push(...f.data[l])}),u.length>0&&(e.push(s[c]),t.push(u))}});const n={};e.forEach((l,c)=>{t[c].forEach(h=>{n[h.date]||(n[h.date]={}),n[h.date][l]=h.basicStats})});let r="time,";const o=e.map(l=>[l,`${l}_max`,`${l}_min`]);r+=o.flat().join(","),r+=`
24
24
  `,Object.keys(n).forEach(l=>{const c=[l];e.forEach(h=>{const u=n[l][h]?n[l][h]:null;u!=null?c.push(u.mean,u.max,u.min):c.push("","","")}),r+=c.join(","),r+=`
25
- `});var a=document.createElement("a");a.href="data:text/csv;charset=utf-8,"+encodeURI(r),a.target="_blank",a.download="chart_data.csv",a.click()}setGeometry(t){this.dataStorage={},this.options.features.forEach((e,s)=>this.dataStorage[s]={}),this.options.geometry=t,this.retrieveMissingData(),this.updateChart()}setActiveFields(t){this.activeFields=t,this.retrieveMissingData(),this.updateChart()}setTimeInterval(t,e){this.startTime=t,this.endTime=e,this.chartOptions.scales.x.min=t.toISODate(),this.chartOptions.scales.x.max=e.toISODate(),this.retrieveMissingData(),this.updateChart()}setNormalize(t){this.options.normalize=t,this.updateChart()}setShowMinMax(t){this.options.showMinMax=t,this.updateChart()}setTimeAggregation(t){this.timeAggregation=t,this.updateChart()}}class Mp{constructor(t,e,s,n){k(this,"element");k(this,"sdm");k(this,"sdmOptions");k(this,"options");this.element=t,this.sdm=e,this.options=n,this.sdmOptions=s,this.generateTimeAggregationOptions(),this.addNormalizeCheckbox(),this.addShowMinMax(),this.addCSVDownload(),this.generateTimeSelectionOptions();const r=document.createElement("span");r.id="loadingIndicator",r.className="loader hidden",this.element.appendChild(r)}removeStartEndInputs(){const t=document.getElementById("startInput"),e=document.getElementById("endInput"),s=document.getElementById("setTime");t&&e&&s&&(t.remove(),e.remove(),s.remove())}addStartEndInputs(){const t=document.createElement("input");t.id="startInput",t.size=8,t.value=this.sdm.startTime.toISODate();const e=document.createElement("input");e.id="endInput",e.size=8,e.value=this.sdm.endTime.toISODate(),this.element.appendChild(t),this.element.appendChild(e);var s=document.createElement("button");s.id="setTime",s.textContent="ok",this.element.appendChild(s),s.addEventListener("click",()=>{const n=O.fromISO(t.value),r=O.fromISO(e.value);n.isValid&&r.isValid?(this.sdm.setTimeInterval(n,r),this.removeStartEndInputs()):(t.className=n.isValid?"":"parsingError",e.className=r.isValid?"":"parsingError")})}addNormalizeCheckbox(){var t=document.createElement("input");t.type="checkbox",t.id="normalize",t.value="normalize",t.checked=this.sdmOptions.normalize;var e=document.createElement("label");e.htmlFor="normalize",e.appendChild(document.createTextNode("normalize")),this.element.appendChild(e),this.element.appendChild(t),t.addEventListener("change",()=>{this.sdm.setNormalize(t.checked)})}addShowMinMax(){var t=document.createElement("input");t.type="checkbox",t.id="showMinMax",t.value="showMinMax",t.checked=this.sdmOptions.showMinMax;var e=document.createElement("label");e.htmlFor="showMinMax",e.appendChild(document.createTextNode("show min/max")),this.element.appendChild(e),this.element.appendChild(t),t.addEventListener("change",()=>{this.sdm.setShowMinMax(t.checked)})}addCSVDownload(){var t=document.createElement("button");t.id="csvDownload",t.textContent="download csv",this.element.appendChild(t),t.addEventListener("click",()=>{this.sdm.triggerCSVDownload()})}generateTimeSelectionOptions(){const t=[{text:"3 months back",value:"month-3"},{text:"6 months back",value:"month-6"},{text:"1 year back",value:"year-1"},{text:"2 years back",value:"year-2"},{text:"3 years back",value:"year-3"},{text:"custom",value:"custom"}],e=document.createElement("select");t.forEach(s=>{const n=document.createElement("option");n.text=s.text,n.value=s.value,e.appendChild(n)}),this.element.appendChild(e),e.addEventListener("change",s=>{const n=O.now(),[r,o]=s.target.value.split("-");switch(this.removeStartEndInputs(),r){case"month":this.sdm.setTimeInterval(n.minus({month:Number(o)}),n);break;case"year":this.sdm.setTimeInterval(n.minus({year:Number(o)}),n);break;case"custom":this.addStartEndInputs();break}})}generateTimeAggregationOptions(){const t=[{text:"no aggregation",value:"none"},{text:"1 week",value:"week-1"},{text:"2 weeks",value:"week-2"},{text:"1 month",value:"month-1"},{text:"3 months",value:"month-3"},{text:"6 months",value:"month-6"}],e=document.createElement("select");t.forEach(n=>{const r=document.createElement("option");r.text=n.text,r.value=n.value,e.appendChild(r)}),this.element.appendChild(e),e.addEventListener("change",n=>{const[r,o]=n.target.value.split("-");switch(r){case"none":this.sdm.setTimeAggregation(null);break;case"week":this.sdm.setTimeAggregation({week:Number(o)});break;case"month":this.sdm.setTimeAggregation({month:Number(o)});break;case"year":this.sdm.setTimeAggregation({year:Number(o)});break}});const s=document.createElement("span");s.id="loadingIndicator",s.className="loader hidden",this.element.appendChild(s)}}const de=new ht(document.getElementById("chart"),{data:{labels:[],datasets:[]},plugins:[{id:"selectionLineHighlight",afterDraw:i=>{if(i&&i.tooltip){const t=i.tooltip.getActiveElements();if(t!=null&&t.length){let e=t[0].element.x,s=i.scales.y,n=i.ctx;n.save(),n.beginPath(),n.moveTo(e,s.top),n.lineTo(e,s.bottom),n.lineWidth=1,n.strokeStyle="rgba(0, 0, 255, 0.4)",n.stroke(),n.restore()}}}}]});let vi=null,Mn;window.addEventListener("message",i=>{i.data==="init"&&(Mn=i.ports[0],Mn.onmessage=Sp)});const Sp=i=>{if(i.data.ts)switch(i.data.type){case"getFoo":console.log(i.data.body),Mn.postMessage({ts:i.data.ts,body:"foo bar"});break}else switch(i.data.type){case"setData":de.data=i.data.body.data,de.update("none");break;case"setSignalsEndpoint":kp(i.data.body.options);break;case"setSignalsGeometry":Tp(i.data.body.options);break;case"setSignalsData":de.data={datasets:Object.entries(i.data.body.data).map(([t,e])=>({type:"line",label:t,data:e}))},de.update("none");break;case"setOptions":de.options=i.data.body.options,de.update("none");break}},kp=i=>{vi=new wp(de,i),new Mp(document.getElementById("controls"),vi,i),vi.setActiveFields(i.active)},Tp=i=>{vi&&vi.setGeometry(i)};
25
+ `});var a=document.createElement("a");a.href="data:text/csv;charset=utf-8,"+encodeURI(r),a.target="_blank",a.download="chart_data.csv",a.click()}setGeometry(t){this.dataStorage={},this.options.features.forEach((e,s)=>this.dataStorage[s]={}),this.options.geometry=t,this.retrieveMissingData(),this.updateChart()}setActiveFields(t){this.activeFields=t,this.retrieveMissingData(),this.updateChart()}setTimeInterval(t,e){this.startTime=t,this.endTime=e,this.chartOptions.scales.x.min=t.toISODate(),this.chartOptions.scales.x.max=e.toISODate(),this.retrieveMissingData(),this.updateChart()}setNormalize(t){this.options.normalize=t,this.updateChart()}setShowMinMax(t){this.options.showMinMax=t,this.updateChart()}setTimeAggregation(t){this.timeAggregation=t,this.updateChart()}}class Mp{constructor(t,e,s,n){k(this,"element");k(this,"sdm");k(this,"sdmOptions");k(this,"options");this.element=t,this.sdm=e,this.options=n,this.sdmOptions=s,this.generateTimeAggregationOptions(),this.addNormalizeCheckbox(),this.addShowMinMax(),this.addCSVDownload(),this.generateTimeSelectionOptions();const r=document.createElement("span");r.id="loadingIndicator",r.className="loader hidden",this.element.appendChild(r)}removeStartEndInputs(){const t=document.getElementById("startInput"),e=document.getElementById("endInput"),s=document.getElementById("setTime");t&&e&&s&&(t.remove(),e.remove(),s.remove())}addStartEndInputs(){const t=document.createElement("input");t.id="startInput",t.size=8,t.value=this.sdm.startTime.toISODate();const e=document.createElement("input");e.id="endInput",e.size=8,e.value=this.sdm.endTime.toISODate(),this.element.appendChild(t),this.element.appendChild(e);var s=document.createElement("button");s.id="setTime",s.textContent="ok",this.element.appendChild(s),s.addEventListener("click",()=>{const n=O.fromISO(t.value),r=O.fromISO(e.value);n.isValid&&r.isValid?(this.sdm.setTimeInterval(n,r),this.removeStartEndInputs()):(t.className=n.isValid?"":"parsingError",e.className=r.isValid?"":"parsingError")})}addNormalizeCheckbox(){var t=document.createElement("input");t.type="checkbox",t.id="normalize",t.value="normalize",t.checked=this.sdmOptions.normalize;var e=document.createElement("label");e.htmlFor="normalize",e.appendChild(document.createTextNode("normalize")),this.element.appendChild(e),this.element.appendChild(t),t.addEventListener("change",()=>{this.sdm.setNormalize(t.checked)})}addShowMinMax(){var t=document.createElement("input");t.type="checkbox",t.id="showMinMax",t.value="showMinMax",t.checked=this.sdmOptions.showMinMax;var e=document.createElement("label");e.htmlFor="showMinMax",e.appendChild(document.createTextNode("show min/max")),this.element.appendChild(e),this.element.appendChild(t),t.addEventListener("change",()=>{this.sdm.setShowMinMax(t.checked)})}addCSVDownload(){var t=document.createElement("button");t.id="csvDownload",t.textContent="download csv",this.element.appendChild(t),t.addEventListener("click",()=>{this.sdm.triggerCSVDownload()})}generateTimeSelectionOptions(){const t=[{text:"3 months back",value:"month-3"},{text:"6 months back",value:"month-6"},{text:"1 year back",value:"year-1"},{text:"2 years back",value:"year-2"},{text:"3 years back",value:"year-3"},{text:"custom",value:"custom"}],e=document.createElement("select");t.forEach(s=>{const n=document.createElement("option");n.text=s.text,n.value=s.value,e.appendChild(n)}),this.element.appendChild(e),e.addEventListener("change",s=>{const n=O.now(),[r,o]=s.target.value.split("-");switch(this.removeStartEndInputs(),r){case"month":this.sdm.setTimeInterval(n.minus({month:Number(o)}),n);break;case"year":this.sdm.setTimeInterval(n.minus({year:Number(o)}),n);break;case"custom":this.addStartEndInputs();break}})}generateTimeAggregationOptions(){const t=[{text:"no aggregation",value:"none"},{text:"1 week",value:"week-1"},{text:"2 weeks",value:"week-2"},{text:"1 month",value:"month-1"},{text:"3 months",value:"month-3"},{text:"6 months",value:"month-6"}],e=document.createElement("select");t.forEach(n=>{const r=document.createElement("option");r.text=n.text,r.value=n.value,e.appendChild(r)}),this.element.appendChild(e),e.addEventListener("change",n=>{const[r,o]=n.target.value.split("-");switch(r){case"none":this.sdm.setTimeAggregation(null);break;case"week":this.sdm.setTimeAggregation({week:Number(o)});break;case"month":this.sdm.setTimeAggregation({month:Number(o)});break;case"year":this.sdm.setTimeAggregation({year:Number(o)});break}});const s=document.createElement("span");s.id="loadingIndicator",s.className="loader hidden",this.element.appendChild(s)}}const de=new ht(document.getElementById("chart"),{data:{labels:[],datasets:[]},plugins:[{id:"selectionLineHighlight",afterDraw:i=>{if(i&&i.tooltip){const t=i.tooltip.getActiveElements();if(t!=null&&t.length){let e=t[0].element.x,s=i.scales.y,n=i.ctx;n.save(),n.beginPath(),n.moveTo(e,s.top),n.lineTo(e,s.bottom),n.lineWidth=1,n.strokeStyle="rgba(0, 0, 255, 0.4)",n.stroke(),n.restore()}}}}]});let vi=null,Mn;window.addEventListener("message",i=>{i.data==="init"&&(Mn=i.ports[0],Mn.onmessage=Sp)});const Sp=i=>{if(i.data.ts)switch(i.data.type){case"getFoo":console.log(i.data.body),Mn.postMessage({ts:i.data.ts,body:"foo bar"});break}else switch(i.data.type){case"setData":de.data=i.data.body.data,de.update("none");break;case"setSignalsEndpoint":kp(i.data.body.options);break;case"setSignalsGeometry":Tp(i.data.body.geometry);break;case"setSignalsData":de.data={datasets:Object.entries(i.data.body.data).map(([t,e])=>({type:"line",label:t,data:e}))},de.update("none");break;case"setOptions":de.options=i.data.body.options,de.update("none");break}},kp=i=>{vi=new wp(de,i),new Mp(document.getElementById("controls"),vi,i),vi.setActiveFields(i.active)},Tp=i=>{vi&&vi.setGeometry(i)};
package/dist/index.html CHANGED
@@ -73,7 +73,7 @@
73
73
  padding-top: 30px;
74
74
  }
75
75
  </style>
76
- <script type="module" crossorigin src="./assets/main-ec32ac01.js"></script>
76
+ <script type="module" crossorigin src="./assets/main-6438d57a.js"></script>
77
77
  </head>
78
78
  <body>
79
79
  <div id="controls" class="controls" data-cy="controls"></div>
@@ -1,7 +1,7 @@
1
1
  var f = Object.defineProperty;
2
2
  var x = (s, t, e) => t in s ? f(s, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : s[t] = e;
3
3
  var h = (s, t, e) => (x(s, typeof t != "symbol" ? t + "" : t, e), e);
4
- const b = "@eox/chart", w = "2.0.0-alpha8", v = {
4
+ const b = "@eox/chart", w = "2.0.0-alpha12", v = {
5
5
  "chart.js": "^4.2.1",
6
6
  "chartjs-adapter-luxon": "^1.3.1",
7
7
  "chartjs-chart-error-bars": "^4.1.2"
@@ -1 +1 @@
1
- (function(n,s){typeof exports=="object"&&typeof module<"u"?s(exports):typeof define=="function"&&define.amd?define(["exports"],s):(n=typeof globalThis<"u"?globalThis:n||self,s(n.Interface={}))})(this,function(n){"use strict";var v=Object.defineProperty;var S=(n,s,o)=>s in n?v(n,s,{enumerable:!0,configurable:!0,writable:!0,value:o}):n[s]=o;var y=(n,s,o)=>(S(n,typeof s!="symbol"?s+"":s,o),o);const g={name:"@eox/chart",version:"2.0.0-alpha8",dependencies:{"chart.js":"^4.2.1","chartjs-adapter-luxon":"^1.3.1","chartjs-chart-error-bars":"^4.1.2"},devDependencies:{"@eox/eslint-config":"^1.0.0","@types/luxon":"^3.2.0","@typescript-eslint/eslint-plugin":"^5.50.0","@typescript-eslint/parser":"^5.50.0",cypress:"^12.6.0","cypress-vite":"^1.3.0","eslint-plugin-cypress":"^2.12.1","eslint-plugin-typescript":"^0.14.0",install:"^0.13.0",luxon:"^3.3.0",npm:"^9.6.3","p-retry":"^5.1.2","pre-commit":"^1.2.2","start-server-and-test":"^1.15.2",typescript:"^4.9.3",vite:"^4.0.0"},engines:{npm:">=8.0.0",node:">=18.0.0"},files:["dist","scripts","src","typings"],main:"./dist/interface.mjs",scripts:{start:"vite",build:"tsc && vite build --config vite.config.interface.ts && vite build --config vite.config.map.ts",watch:"node scripts/watch.mjs",preview:"vite preview",format:"prettier --write .",lint:"eslint --ext .js,.ts .","lint:fix":"eslint --ext .js,.ts . --fix",cypress:"start-server-and-test start 5173 'cypress open'",test:"start-server-and-test start 5173 'cypress run'"},"pre-commit":["format","lint:fix"]},d=new MessageChannel,i=d.port1;class b{constructor(e){y(this,"iframe");this.iframe=e}setData(e){i.postMessage({type:"setData",body:{data:e}})}setSignalsData(e){i.postMessage({type:"setSignalsData",body:{data:e}})}setSignalsEndpoint(e){i.postMessage({type:"setSignalsEndpoint",body:{options:e}})}setSignalsGeometry(e){i.postMessage({type:"setSignalsGeometry",body:{geometry:e}})}setOptions(e){i.postMessage({type:"setOptions",body:{options:e}})}getFoo(){return new Promise(e=>{const t=Date.now();i.onmessage=c=>{c.data.ts===t&&e(c.data.body)},i.postMessage({ts:t,type:"getFoo",body:"hello world"})})}}const w=r=>r?new Promise(e=>{var l,u;const t=document.createElement("iframe");if(t.style.cssText="width: 100%; height: 100%; display: block; margin: 0; border: none;",t.setAttribute("src",(l=typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:document.currentScript&&document.currentScript.src||new URL("interface.umd.js",document.baseURI).href)!=null&&l.includes("localhost")?"http://localhost:5173/index.html":"about:blank"),t.setAttribute("id","EOxChart"),r==null||r.appendChild(t),!((u=typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:document.currentScript&&document.currentScript.src||new URL("interface.umd.js",document.baseURI).href)!=null&&u.includes("localhost"))){const a=`https://www.unpkg.com/@eox/chart@${g.version}/dist`;fetch(`${a}/index.html`).then(p=>p.text()).then(p=>{var f,m,h;const x=p.replace("./assets/",`${a}/assets/`);(f=t.contentDocument)==null||f.open(),(m=t.contentDocument)==null||m.write(x),(h=t.contentDocument)==null||h.close()})}let c=!1;t.onload=()=>{var a;c||((a=t.contentWindow)==null||a.postMessage("init","*",[d.port2]),c=!0,e(new b(t)))}}):(console.error("no div selected"),null);n.createChart=w,Object.defineProperty(n,Symbol.toStringTag,{value:"Module"})});
1
+ (function(n,s){typeof exports=="object"&&typeof module<"u"?s(exports):typeof define=="function"&&define.amd?define(["exports"],s):(n=typeof globalThis<"u"?globalThis:n||self,s(n.Interface={}))})(this,function(n){"use strict";var v=Object.defineProperty;var S=(n,s,o)=>s in n?v(n,s,{enumerable:!0,configurable:!0,writable:!0,value:o}):n[s]=o;var y=(n,s,o)=>(S(n,typeof s!="symbol"?s+"":s,o),o);const g={name:"@eox/chart",version:"2.0.0-alpha12",dependencies:{"chart.js":"^4.2.1","chartjs-adapter-luxon":"^1.3.1","chartjs-chart-error-bars":"^4.1.2"},devDependencies:{"@eox/eslint-config":"^1.0.0","@types/luxon":"^3.2.0","@typescript-eslint/eslint-plugin":"^5.50.0","@typescript-eslint/parser":"^5.50.0",cypress:"^12.6.0","cypress-vite":"^1.3.0","eslint-plugin-cypress":"^2.12.1","eslint-plugin-typescript":"^0.14.0",install:"^0.13.0",luxon:"^3.3.0",npm:"^9.6.3","p-retry":"^5.1.2","pre-commit":"^1.2.2","start-server-and-test":"^1.15.2",typescript:"^4.9.3",vite:"^4.0.0"},engines:{npm:">=8.0.0",node:">=18.0.0"},files:["dist","scripts","src","typings"],main:"./dist/interface.mjs",scripts:{start:"vite",build:"tsc && vite build --config vite.config.interface.ts && vite build --config vite.config.map.ts",watch:"node scripts/watch.mjs",preview:"vite preview",format:"prettier --write .",lint:"eslint --ext .js,.ts .","lint:fix":"eslint --ext .js,.ts . --fix",cypress:"start-server-and-test start 5173 'cypress open'",test:"start-server-and-test start 5173 'cypress run'"},"pre-commit":["format","lint:fix"]},d=new MessageChannel,i=d.port1;class b{constructor(e){y(this,"iframe");this.iframe=e}setData(e){i.postMessage({type:"setData",body:{data:e}})}setSignalsData(e){i.postMessage({type:"setSignalsData",body:{data:e}})}setSignalsEndpoint(e){i.postMessage({type:"setSignalsEndpoint",body:{options:e}})}setSignalsGeometry(e){i.postMessage({type:"setSignalsGeometry",body:{geometry:e}})}setOptions(e){i.postMessage({type:"setOptions",body:{options:e}})}getFoo(){return new Promise(e=>{const t=Date.now();i.onmessage=c=>{c.data.ts===t&&e(c.data.body)},i.postMessage({ts:t,type:"getFoo",body:"hello world"})})}}const w=r=>r?new Promise(e=>{var l,u;const t=document.createElement("iframe");if(t.style.cssText="width: 100%; height: 100%; display: block; margin: 0; border: none;",t.setAttribute("src",(l=typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:document.currentScript&&document.currentScript.src||new URL("interface.umd.js",document.baseURI).href)!=null&&l.includes("localhost")?"http://localhost:5173/index.html":"about:blank"),t.setAttribute("id","EOxChart"),r==null||r.appendChild(t),!((u=typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:document.currentScript&&document.currentScript.src||new URL("interface.umd.js",document.baseURI).href)!=null&&u.includes("localhost"))){const a=`https://www.unpkg.com/@eox/chart@${g.version}/dist`;fetch(`${a}/index.html`).then(p=>p.text()).then(p=>{var f,m,h;const x=p.replace("./assets/",`${a}/assets/`);(f=t.contentDocument)==null||f.open(),(m=t.contentDocument)==null||m.write(x),(h=t.contentDocument)==null||h.close()})}let c=!1;t.onload=()=>{var a;c||((a=t.contentWindow)==null||a.postMessage("init","*",[d.port2]),c=!0,e(new b(t)))}}):(console.error("no div selected"),null);n.createChart=w,Object.defineProperty(n,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eox/chart",
3
- "version": "2.0.0-alpha10",
3
+ "version": "2.0.0-alpha12",
4
4
  "dependencies": {
5
5
  "chart.js": "^4.2.1",
6
6
  "chartjs-adapter-luxon": "^1.3.1",
@@ -0,0 +1,206 @@
1
+ <template>
2
+ <div ref="chartControls" id="controls" class="controls" data-cy="controls"></div>
3
+ <canvas ref="chartCanvas" id="chart" class="chart" data-cy="chart"></canvas>
4
+ </template>
5
+
6
+ <script setup lang="ts">
7
+ import { ref, onMounted } from 'vue'
8
+ import Chart, { ChartDataset } from "chart.js/auto";
9
+ import "chartjs-adapter-luxon";
10
+ import SignalsDataManager from "./signalsDataManager";
11
+ import ChartControls from "./chartControls";
12
+
13
+ const chartCanvas = ref(null)
14
+ const chartControls = ref(null)
15
+ const props = defineProps([
16
+ 'data',
17
+ 'options',
18
+ 'signalsdata',
19
+ 'signalsendpoint'
20
+ ])
21
+
22
+ let eoxchart
23
+ let sdmInstance: SignalsDataManager | null = null;
24
+
25
+ onMounted(() => {
26
+ eoxchart = new Chart(
27
+ <HTMLCanvasElement>chartCanvas.value,
28
+ {
29
+ data: {
30
+ labels: [],
31
+ datasets: [],
32
+ },
33
+ plugins: [
34
+ {
35
+ id: "selectionLineHighlight",
36
+ afterDraw: (chart) => {
37
+ if (chart && chart.tooltip) {
38
+ const active = chart.tooltip.getActiveElements();
39
+ if (active?.length) {
40
+ let x = active[0].element.x;
41
+ let yAxis = chart.scales.y;
42
+ let ctx = chart.ctx;
43
+ ctx.save();
44
+ ctx.beginPath();
45
+ ctx.moveTo(x, yAxis.top);
46
+ ctx.lineTo(x, yAxis.bottom);
47
+ ctx.lineWidth = 1;
48
+ ctx.strokeStyle = "rgba(0, 0, 255, 0.4)";
49
+ ctx.stroke();
50
+ ctx.restore();
51
+ }
52
+ }
53
+ },
54
+ },
55
+ ],
56
+ }
57
+ );
58
+ // TODO remove timeout hack
59
+ setTimeout(() => {
60
+ if (props.data) {
61
+ eoxchart.data = JSON.parse(props.data)
62
+ }
63
+ if (props.signalsdata) {
64
+ eoxchart.data = {
65
+ datasets: Object.entries(JSON.parse(props.signalsdata)).map(
66
+ ([key, item]): ChartDataset => {
67
+ return {
68
+ type: "line",
69
+ label: key,
70
+ data: <number[]>item,
71
+ };
72
+ }
73
+ ),
74
+ };
75
+ }
76
+ if (props.options) {
77
+ eoxchart.options = JSON.parse(props.options)
78
+ }
79
+ if (props.signalsendpoint) {
80
+ setSignalsEndpoint(JSON.parse(props.signalsendpoint));
81
+ }
82
+ eoxchart.update("none")
83
+ }, 0)
84
+ })
85
+
86
+ const setSignalsEndpoint = (options: {
87
+ source: string;
88
+ endpoint: string;
89
+ active: string[];
90
+ features: string[][];
91
+ geometry: object;
92
+ timeInterval: object;
93
+ startTime?: string;
94
+ endTime?: string;
95
+ }) => {
96
+ sdmInstance = new SignalsDataManager(eoxchart, options);
97
+ new ChartControls(chartControls.value, sdmInstance, options);
98
+ sdmInstance.setActiveFields(options.active);
99
+ };
100
+
101
+ const setSignalsGeometry = (geometry: object) => {
102
+ if (sdmInstance) {
103
+ sdmInstance.setGeometry(geometry);
104
+ }
105
+ };
106
+
107
+
108
+ // export default {
109
+ // props: {
110
+ // data: String,
111
+ // },
112
+ // data: () => ({
113
+ // eoxchart: undefined
114
+ // }),
115
+ // computed: {
116
+ // parsedData() {
117
+ // if (!this.data) {
118
+ // return
119
+ // }
120
+ // return JSON.parse(this.data)
121
+ // }
122
+ // },
123
+ // watch: {
124
+ // parsedData(newData) {
125
+ // // setTimeout(() => {
126
+ // // this.eoxchart.data = newData
127
+ // // console.log(this.eoxchart.update)
128
+ // this.eoxchart.update();
129
+ // // }, 3000)
130
+ // }
131
+ // },
132
+ // mounted() {
133
+ // }
134
+ // }
135
+ </script>
136
+
137
+ <style>
138
+ * {
139
+ font-family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
140
+ font-size: 0.95em;
141
+ }
142
+ label {
143
+ margin-top: 2.5px;
144
+ }
145
+ html,
146
+ body {
147
+ margin: 0;
148
+ padding: 0;
149
+ }
150
+ html,
151
+ body,
152
+ .chart {
153
+ width: 100%;
154
+ height: 100%;
155
+ }
156
+ .hidden {
157
+ visibility: hidden;
158
+ }
159
+ .loader {
160
+ position: absolute;
161
+ top: 5px;
162
+ right: 30px;
163
+ width: 24px;
164
+ height: 24px;
165
+ border-radius: 50%;
166
+ display: inline-block;
167
+ border-top: 4px solid #000;
168
+ border-right: 4px solid transparent;
169
+ box-sizing: border-box;
170
+ animation: rotation 1s linear infinite;
171
+ }
172
+ .loader::after {
173
+ content: "";
174
+ box-sizing: border-box;
175
+ position: absolute;
176
+ left: 0;
177
+ top: 0;
178
+ width: 24px;
179
+ height: 24px;
180
+ border-radius: 50%;
181
+ border-left: 4px solid #004170;
182
+ border-bottom: 4px solid transparent;
183
+ animation: rotation 0.5s linear infinite reverse;
184
+ }
185
+ @keyframes rotation {
186
+ 0% {
187
+ transform: rotate(0deg);
188
+ }
189
+ 100% {
190
+ transform: rotate(360deg);
191
+ }
192
+ }
193
+ #controls {
194
+ position: absolute;
195
+ width: 100%;
196
+ display: flex;
197
+ gap: 5px;
198
+ flex-direction: row;
199
+ }
200
+ .parsingError {
201
+ background-color: #ff6d6d;
202
+ }
203
+ #chart {
204
+ padding-top: 30px;
205
+ }
206
+ </style>
@@ -0,0 +1,111 @@
1
+ import Chart, { ChartDataset } from "chart.js/auto";
2
+ import "chartjs-adapter-luxon";
3
+ import SignalsDataManager from "./signalsDataManager";
4
+ import ChartControls from "./chartControls";
5
+
6
+ const eoxchart = new Chart(
7
+ <HTMLCanvasElement>document.getElementById("chart"),
8
+ {
9
+ data: {
10
+ labels: [],
11
+ datasets: [],
12
+ },
13
+ plugins: [
14
+ {
15
+ id: "selectionLineHighlight",
16
+ afterDraw: (chart) => {
17
+ if (chart && chart.tooltip) {
18
+ const active = chart.tooltip.getActiveElements();
19
+ if (active?.length) {
20
+ let x = active[0].element.x;
21
+ let yAxis = chart.scales.y;
22
+ let ctx = chart.ctx;
23
+ ctx.save();
24
+ ctx.beginPath();
25
+ ctx.moveTo(x, yAxis.top);
26
+ ctx.lineTo(x, yAxis.bottom);
27
+ ctx.lineWidth = 1;
28
+ ctx.strokeStyle = "rgba(0, 0, 255, 0.4)";
29
+ ctx.stroke();
30
+ ctx.restore();
31
+ }
32
+ }
33
+ },
34
+ },
35
+ ],
36
+ }
37
+ );
38
+
39
+ let sdmInstance: SignalsDataManager | null = null;
40
+
41
+ let application: MessagePort;
42
+
43
+ window.addEventListener("message", (event) => {
44
+ if (event.data === "init") {
45
+ application = event.ports[0];
46
+ application.onmessage = onMessage;
47
+ }
48
+ });
49
+
50
+ const onMessage = (event: MessageEvent) => {
51
+ if (event.data.ts) {
52
+ switch (event.data.type) {
53
+ case "getFoo":
54
+ console.log(event.data.body);
55
+ application.postMessage({ ts: event.data.ts, body: "foo bar" });
56
+ break;
57
+ }
58
+ } else {
59
+ switch (event.data.type) {
60
+ case "setData":
61
+ eoxchart.data = event.data.body.data;
62
+ eoxchart.update("none");
63
+ break;
64
+ case "setSignalsEndpoint":
65
+ setSignalsEndpoint(event.data.body.options);
66
+ break;
67
+ case "setSignalsGeometry":
68
+ setSignalsGeometry(event.data.body.geometry);
69
+ break;
70
+ case "setSignalsData":
71
+ eoxchart.data = {
72
+ datasets: Object.entries(event.data.body.data).map(
73
+ ([key, item]): ChartDataset => {
74
+ return {
75
+ type: "line",
76
+ label: key,
77
+ data: <number[]>item,
78
+ };
79
+ }
80
+ ),
81
+ };
82
+ eoxchart.update("none");
83
+ break;
84
+ case "setOptions":
85
+ eoxchart.options = event.data.body.options;
86
+ eoxchart.update("none");
87
+ break;
88
+ }
89
+ }
90
+ };
91
+
92
+ const setSignalsEndpoint = (options: {
93
+ source: string;
94
+ endpoint: string;
95
+ active: string[];
96
+ features: string[][];
97
+ geometry: object;
98
+ timeInterval: object;
99
+ startTime?: string;
100
+ endTime?: string;
101
+ }) => {
102
+ sdmInstance = new SignalsDataManager(eoxchart, options);
103
+ new ChartControls(document.getElementById("controls"), sdmInstance, options);
104
+ sdmInstance.setActiveFields(options.active);
105
+ };
106
+
107
+ const setSignalsGeometry = (geometry: object) => {
108
+ if (sdmInstance) {
109
+ sdmInstance.setGeometry(geometry);
110
+ }
111
+ };
@@ -17,9 +17,6 @@ class ChartControls {
17
17
  ) {
18
18
  this.element = element;
19
19
  this.sdm = sdm;
20
- this.sdm.on("ready", (info) => {
21
- console.log(info);
22
- });
23
20
  this.options = options;
24
21
  this.sdmOptions = sdmOptions;
25
22
  this.generateTimeAggregationOptions();
@@ -33,12 +30,6 @@ class ChartControls {
33
30
  this.element.appendChild(spinner);
34
31
  }
35
32
 
36
- private createMessagesElements() {
37
- const messages = document.createElement("div");
38
- messages.id = "messages";
39
- this.element.appendChild(messages);
40
- }
41
-
42
33
  private removeStartEndInputs() {
43
34
  const start = document.getElementById("startInput");
44
35
  const end = document.getElementById("endInput");
package/src/main.ts CHANGED
@@ -65,7 +65,7 @@ const onMessage = (event: MessageEvent) => {
65
65
  setSignalsEndpoint(event.data.body.options);
66
66
  break;
67
67
  case "setSignalsGeometry":
68
- setSignalsGeometry(event.data.body.options);
68
+ setSignalsGeometry(event.data.body.geometry);
69
69
  break;
70
70
  case "setSignalsData":
71
71
  eoxchart.data = {
@@ -15,8 +15,6 @@ import {
15
15
  PointWithErrorBar,
16
16
  } from "chartjs-chart-error-bars";
17
17
 
18
- import { EventEmitter } from "events";
19
-
20
18
  Chart.register(
21
19
  LineWithErrorBarsController,
22
20
  LineWithErrorBarsChart,
@@ -64,7 +62,7 @@ export interface SDMOptions {
64
62
  additionalYAxis?: yAxisObject[];
65
63
  }
66
64
 
67
- class SignalsDataManager extends EventEmitter {
65
+ class SignalsDataManager {
68
66
  chart: Chart;
69
67
  startTime: DateTime;
70
68
  endTime: DateTime;
@@ -77,7 +75,6 @@ class SignalsDataManager extends EventEmitter {
77
75
  additionalYAxis: yAxisObject[] | null;
78
76
 
79
77
  constructor(chart: Chart, options: SDMOptions) {
80
- super();
81
78
  this.chart = chart;
82
79
  this.options = options;
83
80
  this.startTime = DateTime.now().minus(options.timeInterval);
@@ -165,7 +162,6 @@ class SignalsDataManager extends EventEmitter {
165
162
  position: "right",
166
163
  };
167
164
  }
168
- this.emit("ready", "someinfo");
169
165
  }
170
166
 
171
167
  private checkLoadingStatus() {
@@ -215,7 +211,6 @@ class SignalsDataManager extends EventEmitter {
215
211
  console.log(
216
212
  `Attempt ${error.attemptNumber} failed. There are ${error.retriesLeft} retries left.`
217
213
  );
218
- throw new Error();
219
214
  },
220
215
  retries: this.options.retries,
221
216
  }).then(function (res) {