adaptive-linechart 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,6 +1,12 @@
1
1
  # Changelog
2
2
 
3
- ## 1.2.1 (20 Nov 2022)
3
+ ## 1.3.0 (14 Aug 2023)
4
+ * The data on axis-X may be data-time or numerical values. To switch between type of chart use parameter **axisXType**.
5
+ * New parameter for line **connectIfMissing**. It define how to draw line if part of data are missing.
6
+ * All internal properties in class LineChart rename with prefix _.
7
+ * Rewrite comments by JS standard https://jsdoc.app
8
+
9
+ ## 1.2.2 (20 Nov 2022)
4
10
  * In README change link to demo and move to new repository.
5
11
 
6
12
  ## 1.2.0 (01 Nov 2020)
@@ -0,0 +1,17 @@
1
+ # Prepare files for distribution
2
+
3
+ * Update version in README, package.json, linechart.js
4
+ * Put information about changes in CHANGELOG
5
+
6
+ ```
7
+ npm -i terser -g
8
+
9
+ terser src\linechart.js src\chart-util.js -o dist\linechart-all.min.js
10
+ type src\linechart.css > dist\linechart.css
11
+ ```
12
+ # Uplod to NPM
13
+ ```
14
+ npm publish
15
+ ```
16
+
17
+
package/README.md CHANGED
@@ -1,67 +1,56 @@
1
- ## adaptive-linechart :chart_with_upwards_trend:
2
- :
3
- Version 1.2.0.0
1
+ # adaptive-linechart :chart_with_upwards_trend:
2
+ Version 1.3.0
4
3
 
5
- This is a small library to draw charts in the browser. Why is it "adaptive"? Because it automaticaly
6
- adjust chart to available size depend on min/max values on and timespan. Additional you
7
- can adjust the layout of the chart. The chart uses the external CSS styles .nowrap .linechart,
8
- .chart-title, .chart-live-data, .chart-legend, .chart-legend-item, .chart-legend-color.
4
+ This is a small library to draw charts in the browser. All elements of chart will be set up
5
+ automaticaly based on data. You can adjust the layout of the chart by usinf external CSS styles
6
+ for classes .nowrap .linechart, .chart-title, .chart-live-data, .chart-legend, .chart-legend-item, .chart-legend-color. Maximal 10 lines in the chart. The values on axis-x may be Unix time-stamp or numercal. The chart uses the global variable isMobil (Boolean). If false, live data are shown by "mouse-over". By click on item in the legend hide/show line on chart. The library has own simple logger that writes messages to the console. If needed, you can rewrite this logger and redirect messages to another target.
9
7
 
10
- Maximal 10 lines. Since version 1.1.0 allowed negative and positive values in randge from
11
- -9007199254740991 till 9007199254740991. The chart uses the global variable isMobil (Boolean). If
12
- false, live data are shown by "mouse-over". By click on item in the legend hide/show line on chart
13
- and switch colored tag of item.
8
+ Additional supplied function to convert CSV to time-series.
14
9
 
15
- The chart accepts data as time-series in the format (string) "Unix-Timestamp/Value;Unix-Timestamp/Value;..".
16
- Additional (chart-util) supplied function to convert CSV (with header) to time-series.
17
10
 
18
- The library uses its own simple logger that writes messages to the console. If needed, you can
19
- rewrite this object and redirect messages to another target.
20
-
21
- ## Example
11
+ # Example
22
12
 
23
13
  This example creates a chart with 3 lines in parent element with ID 'charts':
24
14
  ```js
25
- var arTimeSeries = [
15
+ var chartData = [
26
16
  {
27
- name: 'Open',
28
- data: '1565301600/138.6100;1565560800/137.0700;1565647200/136.0500;1565733600/136.3600;1565820000/134.3900'
17
+ obj_name: 'Stock preis',
18
+ par_name: ' Open',
19
+ values: '1565301600/138.6100;1565560800/137.0700;1565647200/136.0500;1565733600/136.3600;1565820000/134.3900'
29
20
  },
30
21
  {
31
- name: 'Hight',
32
- data: '1565301600/139.3800;1565560800/137.8600;1565647200/138.8000;1565733600/136.9200;1565820000/134.5800'
22
+ obj_name: 'Stock preis',
23
+ par_name: ' Hight',
24
+ vaues: '1565301600/139.3800;1565560800/137.8600;1565647200/138.8000;1565733600/136.9200;1565820000/134.5800'
33
25
  },
34
26
  {
35
- name: ' Low',
36
- data: '1565301600/136.4600;1565560800/135.2400;1565647200/135.0000;1565733600/133.6700;1565820000/132.2500'
37
- },
27
+ obj_name: 'Stock preis',
28
+ par_name: ' Low',
29
+ values: '1565301600/136.4600;1565560800/135.2400;1565647200/135.0000;1565733600/133.6700;1565820000/132.2500'
30
+ }
38
31
  ];
39
32
 
40
33
  var lchart = new LineChart(document.getElementById('charts'),null, null, 'Example Chart-Line', null);
41
34
 
42
- for(let i=0; i < arTimeSeries.length; i++) {
43
- let line = {
44
- obj_name: 'Stock preis',
45
- par_name: arTimeSeries[i].name,
46
- values: arTimeSeries[i].data
47
- };
48
- lchart.addLine(line);
49
- }
35
+ for(i=0; i < chartData.length; i++) {
36
+ lchart.addLine(chartData[i]);
37
+ }
50
38
 
51
39
  lchart.draw();
52
40
  ```
53
41
 
54
42
  [Live example](https://www.softdorado.com/adaptive-linechart.html)
55
43
 
56
- ## Public methods
44
+ # Public methods
57
45
 
58
46
  **`LineChart(container, chartId, width, title, className)`** - create an object of type LineChart
59
- and create HTML code for the chart.
47
+ and HTML code for the chart.
60
48
  - **container** - Reference to parent element for chart. If null: use BODY as parent element.
61
- - **chartId** - String. Identifier for chart. Optional. If not defined use random integer.
62
- - **width** - Integer. Width in pixel. Optional. Default use available width in parent element.
49
+ - **chartId** - String. Identifier for the chart. Optional. If not defined use random integer.
50
+ - **width** - Integer. Width in pixel. Optional. Default use available width in parent element. Height set automaticaly.
63
51
  - **title** - String. Title of chart. Optional. If null: don't create title.
64
52
  - **className** - String. Class for div of chart. Optional. Default "linechart".
53
+ - **axisXType** String. For time based values on axis X set "time" (Default). For number based values "numer".
65
54
 
66
55
  **`addLine(lineData)`** - add data for a new line and automatically create a new item in the legend.
67
56
  Return true if no problem detected, otherwise false.
@@ -70,17 +59,35 @@ Return true if no problem detected, otherwise false.
70
59
  - **obj_name** - String. Name of object related to the chart. Used in legend.
71
60
  - **par_name** - String. Name of the parameter that represents the current line. Used in legend.
72
61
  - **par_id** - Integer. Optional ID of this line. May be used to request data from backend.
73
- - **values** - String. Time-series in format "Unix-Timestamp/Value;Unix-Timestamp/Value;.."
62
+ - **values** - String. If axisXType "time" format "Unix-Timestamp/Value;Unix-Timestamp/Value;..".
63
+ If axisXType "number" format "Number X/Number Y; Number X/Number Y/..."
64
+ For number the step min. 1E-09 max. 1E18.
65
+ - **connectIfMissing** - Boolean. If false don't draw line where data are missing, else connect
66
+ begin and end of range where data are mising. Default false.
74
67
 
75
68
  **`draw()`** - draw graphic. Skip lines if properties hidden=true or isEmpty=true.
76
69
 
77
70
  **`clear()`** - clear graphic. Legend stays visible.
78
71
 
79
- **`resize(difWidth, difHeight)`** - set a new size. E.g. if the size of parent element is changed.
72
+ **`resize(difWidth, difHeight)`** - Change size of chart and redraw. May be used if size of parent
73
+ panel changed but data in lines stay the same.
80
74
  - **difWidth** - Signed integer. Difference in width.
81
75
  - **difHeight** - Signed integer. Difference in height.
82
76
 
83
- **`isEmpty()`** Return true if all lines are empty
77
+ **`updateLines(lines)`** - Update data in chart and redraw this one. Return true if no problem
78
+ detected, else false. May be used if data inlines changed.
79
+ - **lines** - Array of lineData.
80
+
81
+ **`isEmpty()`** - Return true if all lines are empty
82
+
83
+ **`avgStep`** - Set time interval of measurement data on graph. Several measured values are
84
+ combined to flatten peaks in the graph. value in seconds. Optional.
85
+
86
+ **`lines[]`** - array containing all lines
87
+
88
+ **`chartId`** - chart Id. Used to reference exactly to object or HTML element.
89
+
90
+
84
91
 
85
92
  ## Utility
86
93
 
@@ -1,2 +1 @@
1
- class LineChart{constructor(t,e,i,a,s){null==t&&(t=document.getElementsByTagName("BODY")[0]),null==e&&(e=getRandomInt()),null==s&&(s="linechart"),null==i&&(i=t.clientWidth),this.chartDiv=addNewElement(t,"div",{class:s,id:"chart_"+e,chart_id:e,style:"float:left; width:"+i+"px; padding-bottom:8px;"}),null!=a?(this.title=addNewElement(this.chartDiv,"label",{class:"chart-title nowrap",style:"width:"+(i-20)+"px; text-align:center; display:block; margin-left:10px; margin-top:10px"}),this.title.innerHTML=a):this.title=null;var n=i-30,h=300;isMobil?h=220:i<200?h=200:i<300?h=220:i<400?h=240:i<500?h=260:i<600&&(h=280),this.canvas=addNewElement(this.chartDiv,"canvas",{id:"chart_"+e+"_canvas",width:n,height:h,style:"margin: 15px 17px 3px 13px;"}),this.canvas.dataset.chartId=e.toString(),this.context=this.canvas.getContext("2d"),this.context.translate(.5,.5),isMobil||(this.canvas.addEventListener("mouseout",(function(t){var e=document.getElementById("chart_"+this.dataset.chartId+"_livedata");null!=e&&(e.innerText="-")})),this.canvas.addEventListener("mousemove",(function(t){var e=document.getElementById("chart_"+this.dataset.chartId+"_livedata");if(null!=e)if(this.height-t.offsetY<this.dataset.paddingBottom||t.offsetX<this.dataset.paddingLeft)e.innerText="-";else{var i=this.dataset.maxVal-t.offsetY/parseFloat(this.dataset.coefVal);if(isNaN(i))e.innerText="-";else{i=i<100?i.toFixed(2):i<200?i.toFixed(1):Math.round(i);var a=parseInt(this.dataset.minTs)+Math.round((t.offsetX-parseInt(this.dataset.paddingLeft))/parseFloat(this.dataset.coefTs));isNaN(a)?e.innerText="-":(a=new Date(1e3*a).separate(),e.innerHTML="Date <b>"+a.mday+"."+a.month+"."+a.year+"</b> Time <b>"+a.hour+":"+a.min+"</b> Value <b>"+i+"</b>")}}})),addNewElement(this.chartDiv,"div",{class:"chart-live-data",id:"chart_"+e+"_livedata",style:"margin-left: 12px; margin-right: 12px; margin-bottom: 4px; max-width:95%;",innerText:"-"})),this.legendDiv=addNewElement(this.chartDiv,"div",{class:"chart-legend",id:"chart_"+e+"_legend"}),this.chartId=e,this.lines=[],this.minTs=99999999999999,this.maxTs=0,this.minVal=Number.MAX_SAFE_INTEGER,this.maxVal=Number.MIN_SAFE_INTEGER,this.axeYLabelStep=null,this.axeYLabelHeight=30,this.axeXLabelWidth=80,this.coefTs=null,this.coefVal=null,this.padding={left:50,bottom:35},this.endDate=null,this.avgStep=NaN}addLine(t){if(null==t.values)return logger.error("Function LineChart.newLine(). DataString is null."),!1;if(!isString(t.values))return logger.error("Function LineChart.newLine(). DataString is not a string."),!1;var e=this._createLine(t);return null==e?(logger.error("Function LineChart.newLine(). Function _createLine() return null."),!1):(e.objName=t.obj_name,e.parName=t.par_name,e.parId=t.par_id,e.color=this.colors[this.lines.length],e.legend=addNewElement(this.legendDiv,"div",{class:"chart-legend-item nowrap",id:`chart_${this.chartId}_legend_${t.par_id}`,style:`cursor: pointer; max-width:${this.chartDiv.clientWidth-20}px;`,innerHTML:`<span class="chart-legend-color" style="background-color:${e.color}; color:${e.color};">--</span>${e.objName} / ${e.parName}`}),e.legend.addEventListener("click",(function(t){var i=t.target.getElementsByClassName("chart-legend-color")[0];null!=i&&(0==e.hidden?(e.hidden=!0,i.style.backgroundColor="white"):(e.hidden=!1,i.style.backgroundColor=e.color),t.target.chart.draw())})),e.legend.chart=this,this.lines.push(e),!0)}updateLines(t){if(null==t)return logger.error("Function LineChart.updateLines(). Parameter lines is null."),!1;if(!Array.isArray(t))return logger.error("Function LineChart.updateLines(). Parameter lines is not a array."),!1;for(var e in this.lines=[],this.minTs=99999999999999,this.maxTs=0,this.minVal=999999999999999,this.maxVal=0,this.axeYLabelStep=null,this.coefTs=null,this.coefVal=null,t){var i=this._createLine(t[e]);null!=i&&this.lines.push(i)}return this.draw(),!0}_processSelectLegentItem=function(){console.info("Prozess legent item")};_createLine(t){var e=new SingleLine(t),i=!0;if(null==t.par_id&&(t.par_id=this.lines.length),0==t.values.length)return e;for(var a=t.values.split(";"),s=a.length,n=0;n<s;++n){var h=a[n].split("/");if(""!=h[0])if(isNaN(h[0]))logger.warn("LineChart._createLine(). Item "+n+' contains invalid time-stamp "'+h[0]+'".');else{var l={ts:null,val:null};l.ts=parseInt(h[0]),l.val=parseFloat(h[1]),e.real.push(l),isNaN(l.val)||(l.val<0?Math.floor(1.1*l.val)<this.minVal&&(this.minVal=Math.floor(1.1*l.val)):Math.floor(.9*l.val)<this.minVal&&(this.minVal=Math.floor(.9*l.val)),Math.ceil(1.1*l.val)>this.maxVal&&(this.maxVal=Math.ceil(1.1*l.val)),i=!1),l.ts<this.minTs&&(this.minTs=l.ts),l.ts>this.maxTs&&(this.maxTs=l.ts)}else logger.warn("LineChart._createLine(). Item "+n+" time-stamp is empty.")}if(0==e.real.length)return e;e.isEmpty=!1,(0==this.maxVal&&0==this.minVal||i)&&(this.minVal=0,this.maxVal=1);var r=this.context.measureText(this.minVal.toString()),o=this.context.measureText(this.maxVal.toString());return r.width<o.width?this.padding.left=Math.round(o.width)+23:this.padding.left=Math.round(r.width)+23,e}clear(){this.context.clearRect(0,0,this.canvas.width,this.canvas.height)}draw(){if(this.coefTs=(this.canvas.width-this.padding.left)/(this.maxTs-this.minTs),this.coefVal=(this.canvas.height-this.padding.bottom)/(this.maxVal-this.minVal),this.context.clearRect(0,0,this.canvas.width,this.canvas.height),!this.isEmpty()){this._drawAxeX(),this._drawAxeY();for(var t=0;t<this.lines.length;t++)this.drawLine(t);this.canvas.dataset.minTs=this.minTs.toString(),this.canvas.dataset.coefTs=this.coefTs.toString(),this.canvas.dataset.maxVal=this.maxVal.toString(),this.canvas.dataset.coefVal=this.coefVal.toString(),this.canvas.dataset.paddingLeft=this.padding.left.toString(),this.canvas.dataset.paddingBottom=this.padding.bottom.toString()}}resize(t,e){this.canvas.width=this.canvas.width+t,this.canvas.height=this.canvas.height+e,this.context.translate(.5,.5)}_drawAxeX(){this.context.strokeStyle=this.colorDefault,this.context.lineWidth=1,this.context.beginPath(),this.context.moveTo(this.padding.left,this.canvas.height-this.padding.bottom),this.context.lineTo(this.canvas.width,this.canvas.height-this.padding.bottom),this.context.stroke();var t,e=Math.round(this.axeXLabelWidth/this.coefTs/60);t=this.stepsX.length-1;for(var i=0;i<t;i++)if(e>this.stepsX[i]&&e<this.stepsX[i+1]){e=this.stepsX[i];break}e*=60;for(var a=this._getBeginOfDayFromUnixTs(this.minTs),s=(new Date).getTime()/1e3;a<s;){if(a>this.minTs){!0;break}a+=e}for(var n,h,l=[];a<this.maxTs;)n=this._convertTs2PosX(a),h=this._formatTsForLabel(a,this.maxTs-this.minTs),l.push({X:n,str:h}),a+=e;this.context.beginPath(),this.context.strokeStyle="#e6e6e6";var r=Math.round(e*this.coefTs/2),o=this.canvas.height-this.padding.bottom;t=l.length;for(i=0;i<t;i++)this.context.moveTo(l[i].X,0),this.context.lineTo(l[i].X,o),l[i].X-r>this.padding.left+2&&(this.context.moveTo(l[i].X-r,0),this.context.lineTo(l[i].X-r,o));for(null!=l[i-1]&&l[i-1].X+r<=this.canvas.width&&(this.context.moveTo(l[i-1].X+r,0),this.context.lineTo(l[i-1].X+r,o)),this.context.stroke(),this.context.font="12px arial",t=l.length,i=0;i<t;i++)this.context.fillText(l[i].str.hm,l[i].X-17,o+17),(0==i||l[i].str.dm!=l[i-1].str.dm)&&this.context.fillText(l[i].str.dm,l[i].X-17,o+32);this.context.closePath()}_drawAxeY(){if(null!=this.coefTs&&null!=this.coefVal){var t,e=(this.canvas.height-this.padding.bottom)/this.axeYLabelHeight;this.axeYLabelStep=(this.maxVal-this.minVal)/e;for(var i,a,s=1,n=!1;s<1e11;){for(var h=0;h<this.stepsY.length-1;h++)if(i=this.stepsY[h]*s,a=this.stepsY[h+1]*s,i<=this.axeYLabelStep&&this.axeYLabelStep<=a){this.axeYLabelStep=a,n=!0;break}if(n)break;s*=10}var l=0;if(this.minVal<0)for(;l>this.minVal&&!(l<=this.minVal);)l-=this.axeYLabelStep;else if(this.minVal>0)for(;l<this.maxVal&&!(l>=this.minVal);)l+=this.axeYLabelStep;var r,o,c,d=this.canvas.height-this.padding.bottom,g=[];for(h=0;h<33&&(o=l+this.axeYLabelStep*h,(this.axeYLabelStep<1||2.5==this.axeYLabelStep)&&(o=o.toFixed(2)),!((r=this._convertVal2PosY(o))<0));){if(r<d){var m={value:o,Y:r};g.push(m)}h++}for(this.context.lineWidth=1,this.context.beginPath(),this.context.strokeStyle=this.colorDefault,this.context.moveTo(this.padding.left,0),this.context.lineTo(this.padding.left,this.canvas.height-this.padding.bottom),this.context.stroke(),this.context.beginPath(),this.context.strokeStyle="#e6e6e6",t=g.length,h=0;h<t;h++)(c=g[h].Y+Math.round(this.coefVal*this.axeYLabelStep/2))<this.canvas.height-this.padding.bottom&&(this.context.moveTo(this.padding.left,c),this.context.lineTo(this.canvas.width,c)),g[h].Y>=this.canvas.height-this.padding.bottom||(this.context.moveTo(this.padding.left,g[h].Y),this.context.lineTo(this.canvas.width,g[h].Y));for((c=g[g.length-1].Y-Math.round(this.coefVal*this.axeYLabelStep/2))>0&&(this.context.moveTo(this.padding.left,c),this.context.lineTo(this.canvas.width,c)),this.context.stroke(),this.context.font="12px arial",this.context.strokeStyle=this.colorDefault,t=g.length,h=0;h<t;h++)this.context.fillText(g[h].value,0,g[h].Y+10)}}drawLine(t){var e=this.lines[t];if(null!=e){if(1!=e.isEmpty&&0!=e.real.length&&!e.hidden){var i,a=[],s=-1,n=[],h=[];if(!isNaN(this.avgStep)){for(var l=this._getBeginOfDayFromUnixTs(e.real[0].ts);l<e.real[0].ts;)l+=this.avgStep;i=e.real.length;for(var r=0;r<i;r++)if(e.real[r].ts<l)n.push(e.real[r].val);else{for(var o=0;e.real[r].ts>l+this.avgStep;)if(l+=this.avgStep,++o>1e3)return void logger.warn("drawLine(). Can't calculate average values for this line. "+new Date(1e3*e.real[r].ts).formatISOLocal()+"/"+e.real[r].val);var c={ts:l,val:getAvgValue(n,2)};h.push(c),(n=[]).push(e.real[r].val),l+=this.avgStep}if(n.length>0){c={ts:l,val:getAvgValue(n,2)};h.push(c)}}n=[],0==h.length&&(h=e.real),i=h.length;for(var d=0;d<i;d++){(c={X:NaN,Y:NaN}).X=this._convertTs2PosX(h[d].ts),isNaN(h[d].val)||(c.Y=this._convertVal2PosY(h[d].val)),c.X!=s?(s=c.X,n.length>0&&d>0&&(n.push(a[a.length-1].Y),a[a.length-1].Y=getAvgValue(n,2),n=[]),a.push(c)):n.push(c.Y)}for(this.context.strokeStyle=this.colors[t],this.context.lineWidth=1,this.context.beginPath(),i=a.length,d=0;d<i;d++)if(!isNaN(a[d].Y)){this.context.moveTo(a[d].X,a[d].Y),d++;break}for(;d<i;)if(isNaN(a[d].Y))for(this.context.stroke(),d++;d<a.length;){if(!isNaN(a[d].Y)){d++;break}d++}else this.context.lineTo(a[d].X,a[d].Y),d++;this.context.stroke()}}else logger.error("Function LineChart.drawLine(lineId). The line with ID "+t+" not found!")}isEmpty(){for(var t=!0,e=0;e<this.lines.length;e++)this.lines[e].isEmpty||(t=!1);return t}_convertTs2PosX(t){return this.canvas.width-Math.round((this.maxTs-t)*this.coefTs)}_convertVal2PosY(t){return Math.round((this.maxVal-t)*this.coefVal)}_formatTsForLabel(t,e){let i=new Date(1e3*t);e/=86400;let a=i.getFullYear(),s=i.getMonth()+1;s<10&&(s="0"+s.toString());let n=i.getDate();parseInt(n)<10&&(n="0"+n.toString());let h=i.getHours();parseInt(h)<10&&(h="0"+h);let l=i.getMinutes();parseInt(l)<10&&(l="0"+l.toString());let r={};return r=e<3?{dm:n+"."+s,hm:h+":"+l}:e>=3&&e<180?{dm:a,hm:n+"."+s}:{dm:a,hm:" "+s},r}_getBeginOfDayFromUnixTs(t){var e=new Date(1e3*t);return(e=new Date(e.getFullYear(),e.getMonth(),e.getDate())).setMinutes(59),e.setSeconds(59),e.setMilliseconds(1e3),e.getTime()/1e3}colors=["#0044CC","#008000","#FF8533","#6A6A6A","#C71585","#8B4513","#1E90FF","#FF4500","#00FF00","#8A2BE2"];colorDefault="#657585";stepsX=[2,5,10,15,20,30,60,90,120,240,300,360,720,1440,2880,4320,5760,7200,10080,14400,21600,28800,43200,64800,86400,129600,172800];stepsY=[.01,.02,.05,.1]}class SingleLine{constructor(t){this.parId=t.par_id,this.parName=t.par_name,this.objName=t.obj_name,this.real=[],this.isEmpty=!0,this.hidden=!1,this.color="black"}}var allCharts=[];LineChart.prototype.Version="1.2.0";
2
- if("notdefined"!=typeof logger)var logger={info:function(e){console.info(e)},warn:function(e){console.warn(e)},error:function(e){console.error(e)},debug:function(e){console.debug(bessage)}};function addNewElement(e,n,t){if(null==t&&(t={}),null!=t.id?null!=document.getElementById(t.id)&&(newElementCounter++,t.id=newElementCounter.toString()+"_"+(new Date).getTime().toString()):(newElementCounter++,t.id=newElementCounter.toString()+"_"+(new Date).getTime().toString()),null==n)var r=document.createElement("div");else r=document.createElement(n);for(var i in t)r.setAttribute(i,t[i]);return null!=t.innerText&&(r.innerText=t.innerText),null!=t.innerHTML&&(r.innerHTML=t.innerHTML),null==e?document.body.appendChild(r):e.appendChild(r),document.getElementById(t.id)}var newElementCounter=0;function getAvgValue(e,n){if(null==e||0==e.length)return NaN;(null==n||isNaN(n))&&(n=2);for(var t=0,r=0,i=0;i<e.length;i++)isNaN(e[i])||(t+=e[i],r+=1);return 0==r?NaN:(t/r).toFixed(n)}function getRandomInt(){return 1e17*Math.random()}function isString(e){return"string"==typeof e||e instanceof String}function scvToTimeSeries(e){let n=[];if(null==e)return n;let t=e.split(/\r?\n/);if(t.length<2)return n;var r=t[0].split(",");for(let e=1;e<r.length;e++){let i={name:r[e],data:""};for(let n=t.length-1;n>0;n--){let o=t[n].split(",");o.length==r.length&&(i.data+=moment(o[0]).format("X")+"/"+o[e]+";")}i.data=i.data.slice(0,-1),n.push(i)}return n}Date.prototype.separate=function(){var e={};return e.year=this.getFullYear(),e.month=this.getMonth()+1,e.mday=this.getDate(),e.hour=this.getHours(),e.min=this.getMinutes(),e.sec=this.getSeconds(),e.msec=this.getMilliseconds(),e.month<10&&(e.month="0"+e.month),e.mday<10&&(e.mday="0"+e.mday),e.hour<10&&(e.hour="0"+e.hour),e.min<10&&(e.min="0"+e.min),e.sec<10&&(e.sec="0"+e.sec),e.msec<10?e.msec="00"+e.msec:e.msec<100&&(e.msec="0"+e.msec),e};
1
+ class LineChart{constructor(container,chartId,width,title,className,axisXType){if(container==null)container=document.getElementsByTagName("BODY")[0];if(chartId==null)chartId=getRandomInt();if(className==null)className="linechart";if(width==null)width=container.clientWidth;this.chartDiv=addNewElement(container,"div",{class:className,id:"chart_"+chartId,chart_id:chartId,style:"float:left; width:"+width+"px; padding-bottom:8px;"});if(title!=null){let titleElement=addNewElement(this.chartDiv,"label",{class:"chart-title nowrap",style:"width:"+(width-20)+"px; text-align:center; display:block; margin-left:10px; margin-top:10px"});titleElement.innerHTML=title}var canvasWidth=width-30;var canvasHeight=300;if(isMobil){canvasHeight=220}else{if(width<200){canvasHeight=200}else if(width<300){canvasHeight=220}else if(width<400){canvasHeight=240}else if(width<500){canvasHeight=260}else if(width<600){canvasHeight=280}}this._canvas=addNewElement(this.chartDiv,"canvas",{id:"chart_"+chartId+"_canvas",width:canvasWidth,height:canvasHeight,style:"margin: 15px 17px 3px 13px;"});if(axisXType!=null||typeof axisXType=="undefined"){if(axisXType=="number"){this.axisXType="number"}else if(axisXType=="time"){this.axisXType="time"}else{logger.warn(`Unknow value axisXType=${axisXType}. Set default "time".`);this.axisXType="time"}}else{this.axisXType=="time"}this._canvas.dataset.axisXType=this.axisXType;this._canvas.dataset.chartId=chartId.toString();this._context=this._canvas.getContext("2d");this._context.translate(.5,.5);if(!isMobil){this._canvas.addEventListener("mouseout",(function(event){var element=document.getElementById("chart_"+this.dataset.chartId+"_livedata");if(element==null)return;element.innerText="-"}));this._canvas.addEventListener("mousemove",(function(event){var element=document.getElementById("chart_"+this.dataset.chartId+"_livedata");if(element==null)return;if(this.height-event.offsetY<this.dataset.paddingBottom||event.offsetX<this.dataset.paddingLeft){element.innerText="-";return}var curValY=this.dataset.maxVal-event.offsetY/parseFloat(this.dataset.coefVal);if(isNaN(curValY)){element.innerText="-";return}if(curValY<100){curValY=curValY.toFixed(2)}else if(curValY<200){curValY=curValY.toFixed(1)}else{curValY=Math.round(curValY)}if(this.dataset.axisXType=="time"){var curTs=parseInt(this.dataset.minTs)+Math.round((event.offsetX-parseInt(this.dataset.paddingLeft))/parseFloat(this.dataset.coefTs));if(isNaN(curTs)){element.innerText="-";return}curTs=new Date(curTs*1e3).separate();element.innerHTML="Date <b>"+curTs.mday+"."+curTs.month+"."+curTs.year+"</b> Time <b>"+curTs.hour+":"+curTs.min+"</b> Value <b>"+curValY+"</b>"}else{var curValX=parseInt(this.dataset.minTs)+Math.round((event.offsetX-parseInt(this.dataset.paddingLeft))/parseFloat(this.dataset.coefTs));element.innerHTML="Axis-X <b>"+curValX+"</b> Axis-Y <b>"+curValY+"</b>"}}));addNewElement(this.chartDiv,"div",{class:"chart-live-data, nowrap",id:"chart_"+chartId+"_livedata",style:"margin-left: 12px; margin-right: 12px; margin-bottom: 4px; max-width:95%;",innerText:"-"})}this._legendDiv=addNewElement(this.chartDiv,"div",{class:"chart-legend",id:"chart_"+chartId+"_legend"});this.chartId=chartId;this.lines=[];this._minTs=Number.MAX_SAFE_INTEGER;this._maxTs=0;this._minVal=Number.MAX_VALUE;this._maxVal=Number.MIN_VALUE;this._axeYLabelStep=null;this._axeYLabelHeight=30;this._axeXLabelWidth=80;this._coefTs=null;this._coefVal=null;this._padding={left:50,bottom:35};this.avgStep=NaN}addLine(lineData){if(lineData.values==null){logger.error("Function LineChart.newLine(). DataString is null.");return false}if(!isString(lineData.values)){logger.error("Function LineChart.newLine(). DataString is not a string.");return false}var line=this._createLine(lineData);if(line==null){logger.error("Function LineChart.newLine(). Function _createLine() return null.");return false}line.legend=addNewElement(this._legendDiv,"div",{class:"chart-legend-item nowrap",id:`chart_${this.chartId}_legend_${lineData.par_id}`,style:`cursor: pointer; max-width:${this.chartDiv.clientWidth-20}px;`,innerHTML:`<span class="chart-legend-color" style="background-color:${line.color}; color:${line.color};">--</span>${line.objName} / ${line.parName}`});line.legend.addEventListener("click",(function(event){var legendColor=event.target.getElementsByClassName("chart-legend-color")[0];if(legendColor==null)return;if(line.hidden==false){line.hidden=true;legendColor.style.backgroundColor="white"}else{line.hidden=false;legendColor.style.backgroundColor=line.color}event.target.chart.draw()}));line.legend.chart=this;this.lines.push(line);return true}updateLines(lines){if(lines==null){logger.error("Function LineChart.updateLines(). Parameter lines is null.");return false}if(!Array.isArray(lines)){logger.error("Function LineChart.updateLines(). Parameter lines is not a array.");return false}this.lines=[];this._minTs=99999999999999;this._maxTs=0;this._minVal=999999999999999;this._maxVal=0;this._axeYLabelStep=null;this._coefTs=null;this._coefVal=null;for(var i in lines){var line=this._createLine(lines[i]);if(line!=null){this.lines.push(line)}}this.draw();return true}_createLine(lineData){var line=new SingleLine(lineData,this.colors[this.lines.length]);var isAllNaN=true;if(lineData.par_id==null)lineData.par_id=this.lines.length;if(lineData.values.length==0)return line;var ar=lineData.values.split(";");var arLen=ar.length;for(var i=0;i<arLen;++i){var item=ar[i].split("/");if(item[0]==""){logger.warn("LineChart._createLine(). Item "+i+". Element for axis-x is empty.");continue}if(isNaN(item[0])){logger.warn("LineChart._createLine(). Item "+i+'. Element for axis-x is not a number "'+item[0]+'".');continue}var elem={ts:null,val:null};elem.ts=parseInt(item[0]);elem.val=parseFloat(item[1]);line.real.push(elem);if(!isNaN(elem.val)){if(elem.val<0){if(Math.floor(elem.val*1.1)<this._minVal){this._minVal=Math.floor(elem.val*1.1)}}else{if(Math.floor(elem.val*.9)<this._minVal){this._minVal=Math.floor(elem.val*.9)}}if(Math.ceil(elem.val*1.1)>this._maxVal){this._maxVal=Math.ceil(elem.val*1.1)}isAllNaN=false}if(elem.ts<this._minTs)this._minTs=elem.ts;if(elem.ts>this._maxTs)this._maxTs=elem.ts}if(line.real.length==0)return line;line.isEmpty=false;if(this._maxVal==0&&this._minVal==0||isAllNaN){this._minVal=0;this._maxVal=1}var minValText=this._context.measureText(this._minVal.toString());var maxValText=this._context.measureText(this._maxVal.toString());if(minValText.width<maxValText.width){this._padding.left=Math.round(maxValText.width)+23}else{this._padding.left=Math.round(minValText.width)+23}return line}clear(){this._context.clearRect(0,0,this._canvas.width,this._canvas.height)}draw(){this._coefTs=(this._canvas.width-this._padding.left)/(this._maxTs-this._minTs);this._coefVal=(this._canvas.height-this._padding.bottom)/(this._maxVal-this._minVal);this._context.clearRect(0,0,this._canvas.width,this._canvas.height);if(this.isEmpty())return;if(this.axisXType=="time"){this._drawAxeXTime()}else{this._drawAxeXNum()}this._drawAxeY();for(var i=0;i<this.lines.length;i++){this._drawLine(i)}this._canvas.dataset.minTs=this._minTs.toString();this._canvas.dataset.coefTs=this._coefTs.toString();this._canvas.dataset.maxVal=this._maxVal.toString();this._canvas.dataset.coefVal=this._coefVal.toString();this._canvas.dataset.paddingLeft=this._padding.left.toString();this._canvas.dataset.paddingBottom=this._padding.bottom.toString()}resize(difWidth,difHeight){this._canvas.width=this._canvas.width+difWidth;this._canvas.height=this._canvas.height+difHeight;this._context.translate(.5,.5);this.draw()}_drawAxeXTime(){this._drawAxeXBasic();var arLen;var stepTs=Math.round(this._axeXLabelWidth/this._coefTs);if(stepTs<=1){stepTs=1}else{arLen=this.stepsX.length-1;for(var i=0;i<arLen;i++){if(stepTs>this.stepsX[i]&&stepTs<this.stepsX[i+1]){stepTs=this.stepsX[i];break}}}var tsLabel=this._getBeginOfDayFromUnixTs(this._minTs);var isFound=false;var tsNow=(new Date).getTime()/1e3;while(tsLabel<tsNow){if(tsLabel>this._minTs){isFound=true;break}tsLabel+=stepTs}var labels=[];var posX,labelStr;while(tsLabel<this._maxTs){posX=this._convertTs2PosX(tsLabel);labelStr=this._formatTsForLabel(tsLabel,this._maxTs-this._minTs);labels.push({X:posX,str:labelStr});tsLabel=tsLabel+stepTs}this._context.beginPath();this._context.strokeStyle="#e6e6e6";var halfStep=Math.round(stepTs*this._coefTs/2);var posY=this._canvas.height-this._padding.bottom;arLen=labels.length;for(var i=0;i<arLen;i++){this._context.moveTo(labels[i].X,0);this._context.lineTo(labels[i].X,posY+10);if(labels[i].X-halfStep>this._padding.left+2){this._context.moveTo(labels[i].X-halfStep,0);this._context.lineTo(labels[i].X-halfStep,posY)}}if(labels[i-1]!=null){if(labels[i-1].X+halfStep<=this._canvas.width){this._context.moveTo(labels[i-1].X+halfStep,0);this._context.lineTo(labels[i-1].X+halfStep,posY)}}this._context.stroke();this._context.font="12px arial";arLen=labels.length;for(i=0;i<arLen;i++){this._context.fillText(labels[i].str.hm,labels[i].X-17,posY+17);if(i==0){this._context.fillText(labels[i].str.dm,labels[i].X-17,posY+32)}else{if(labels[i].str.dm!=labels[i-1].str.dm){this._context.fillText(labels[i].str.dm,labels[i].X-17,posY+32)}}}this._context.closePath()}_drawAxeXNum(){this._drawAxeXBasic();let arLen;let stepX=Math.round(this._axeXLabelWidth/this._coefTs);stepX=this._getNextPreferedNumber(stepX);let minXLabelVal=this._getNextPreferedNumber(this._minTs);let labelsX=[];while(minXLabelVal<this._maxTs){labelsX.push({X:this._convertTs2PosX(minXLabelVal),str:minXLabelVal});minXLabelVal=minXLabelVal+stepX}this._context.beginPath();this._context.strokeStyle="#e6e6e6";let halfStep=Math.round(stepX*this._coefTs/2);let posY=this._canvas.height-this._padding.bottom;arLen=labelsX.length;for(i=0;i<arLen;i++){this._context.moveTo(labelsX[i].X,0);this._context.lineTo(labelsX[i].X,posY+10);if(labelsX[i].X-halfStep>this._padding.left+2){this._context.moveTo(labelsX[i].X-halfStep,0);this._context.lineTo(labelsX[i].X-halfStep,posY)}}if(labelsX[i-1]!=null){if(labelsX[i-1].X+halfStep<=this._canvas.width){this._context.moveTo(labelsX[i-1].X+halfStep,0);this._context.lineTo(labelsX[i-1].X+halfStep,posY)}}this._context.stroke();this._context.font="12px arial";arLen=labelsX.length;for(i=0;i<arLen;i++){this._context.fillText(labelsX[i].str,labelsX[i].X,posY+20)}this._context.closePath()}_drawAxeXBasic(){this._context.strokeStyle=this.colorDefault;this._context.lineWidth=1;this._context.beginPath();this._context.moveTo(this._padding.left,this._canvas.height-this._padding.bottom);this._context.lineTo(this._canvas.width,this._canvas.height-this._padding.bottom);this._context.stroke()}_drawAxeY(){if(this._coefTs==null||this._coefVal==null)return;var arLen;var labelsAmount=(this._canvas.height-this._padding.bottom)/this._axeYLabelHeight;this._axeYLabelStep=(this._maxVal-this._minVal)/labelsAmount;this._axeYLabelStep=this._getNextPreferedNumber(this._axeYLabelStep);var labelMinVal=0;if(this._minVal<0){while(labelMinVal>this._minVal){if(labelMinVal<=this._minVal)break;labelMinVal-=this._axeYLabelStep}}else if(this._minVal>0){while(labelMinVal<this._maxVal){if(labelMinVal>=this._minVal)break;labelMinVal+=this._axeYLabelStep}}var axeYHight=this._canvas.height-this._padding.bottom;var axeY=[];i=0;var labelPosY,labelValue;while(i<33){labelValue=labelMinVal+this._axeYLabelStep*i;if(this._axeYLabelStep<1||this._axeYLabelStep==2.5)labelValue=labelValue.toFixed(2);labelPosY=this._convertVal2PosY(labelValue);if(labelPosY<0)break;if(labelPosY<axeYHight){var label={value:labelValue,Y:labelPosY};axeY.push(label)}i++}this._context.lineWidth=1;this._context.beginPath();this._context.strokeStyle=this.colorDefault;this._context.moveTo(this._padding.left,0);this._context.lineTo(this._padding.left,this._canvas.height-this._padding.bottom);this._context.stroke();this._context.beginPath();this._context.strokeStyle="#e6e6e6";var helpLinePosY;arLen=axeY.length;for(i=0;i<arLen;i++){helpLinePosY=axeY[i].Y+Math.round(this._coefVal*this._axeYLabelStep/2);if(helpLinePosY<this._canvas.height-this._padding.bottom){this._context.moveTo(this._padding.left,helpLinePosY);this._context.lineTo(this._canvas.width,helpLinePosY)}if(axeY[i].Y>=this._canvas.height-this._padding.bottom)continue;this._context.moveTo(this._padding.left,axeY[i].Y);this._context.lineTo(this._canvas.width,axeY[i].Y)}helpLinePosY=axeY[axeY.length-1].Y-Math.round(this._coefVal*this._axeYLabelStep/2);if(helpLinePosY>0){this._context.moveTo(this._padding.left,helpLinePosY);this._context.lineTo(this._canvas.width,helpLinePosY)}this._context.stroke();this._context.font="12px arial";this._context.strokeStyle=this.colorDefault;arLen=axeY.length;for(i=0;i<arLen;i++){this._context.fillText(axeY[i].value,0,axeY[i].Y+10)}}_drawLine(lineIndex){var line=this.lines[lineIndex];if(line==null){logger.error("Function LineChart.drawLine(lineId). The line with ID "+lineIndex+" not found!");return}if(line.isEmpty==true||line.real.length==0||line.hidden)return;var pos=[];var lastX=-1;var avgY=[];var arLen;var lineData=[];if(!isNaN(this.avgStep)){var avgNextPoint=this._getBeginOfDayFromUnixTs(line.real[0].ts);while(avgNextPoint<line.real[0].ts){avgNextPoint+=this.avgStep}arLen=line.real.length;for(var x=0;x<arLen;x++){if(line.real[x].ts<avgNextPoint){avgY.push(line.real[x].val)}else{var maxCounter=0;while(line.real[x].ts>avgNextPoint+this.avgStep){avgNextPoint+=this.avgStep;maxCounter++;if(maxCounter>1e3){logger.warn("drawLine(). Can't calculate average values for this line. "+new Date(line.real[x].ts*1e3).formatISOLocal()+"/"+line.real[x].val);return}}var item={ts:avgNextPoint,val:getAvgValue(avgY,2)};lineData.push(item);avgY=[];avgY.push(line.real[x].val);avgNextPoint+=this.avgStep}}if(avgY.length>0){var item={ts:avgNextPoint,val:getAvgValue(avgY,2)};lineData.push(item)}}avgY=[];if(lineData.length==0)lineData=line.real;arLen=lineData.length;for(var i=0;i<arLen;i++){var item={X:NaN,Y:NaN};item.X=this._convertTs2PosX(lineData[i].ts);if(!isNaN(lineData[i].val))item.Y=this._convertVal2PosY(lineData[i].val);if(item.X==lastX){avgY.push(item.Y);continue}else{lastX=item.X;if(avgY.length>0&&i>0){avgY.push(pos[pos.length-1].Y);pos[pos.length-1].Y=getAvgValue(avgY,2);avgY=[]}}pos.push(item)}this._context.strokeStyle=this.colors[lineIndex];this._context.lineWidth=1;this._context.beginPath();arLen=pos.length;for(i=0;i<arLen;i++){if(!isNaN(pos[i].Y)){this._context.moveTo(pos[i].X,pos[i].Y);i++;break}}while(i<arLen){if(!isNaN(pos[i].Y)){this._context.lineTo(pos[i].X,pos[i].Y);i++}else{if(this.connectIfMissing==true){while(i<pos.length){if(!isNaN(pos[i].Y)){break}i++}}else{this._context.stroke();this._context.beginPath();while(i<pos.length){if(!isNaN(pos[i].Y)){break}i++}}}}this._context.stroke()}_getNextPreferedNumber(num){if(num==0)return 0;let steps=[1e-9,2e-9,5e-9,1e-8];let factor=1;let minStep,maxStep;while(factor<1e18+1){for(var i=0;i<steps.length-1;i++){minStep=steps[i]*factor;maxStep=steps[i+1]*factor;if(minStep<=num&&num<=maxStep){return maxStep}}factor=factor*10}return null}isEmpty(){var isEmpty=true;for(var i=0;i<this.lines.length;i++){if(!this.lines[i].isEmpty){isEmpty=false}}return isEmpty}_convertTs2PosX(ts){return this._canvas.width-Math.round((this._maxTs-ts)*this._coefTs)}_convertVal2PosY(val){return Math.round((this._maxVal-val)*this._coefVal)}_formatTsForLabel(ts,tsdif){let date=new Date(ts*1e3);tsdif=tsdif/(3600*24);let yaer=date.getFullYear();let mon=date.getMonth()+1;if(mon<10)mon="0"+mon.toString();let mday=date.getDate();if(parseInt(mday)<10)mday="0"+mday.toString();let hours=date.getHours();if(parseInt(hours)<10)hours="0"+hours;let min=date.getMinutes();if(parseInt(min)<10)min="0"+min.toString();let result={};if(tsdif<3){result={dm:mday+"."+mon,hm:hours+":"+min}}else if(tsdif>=3&&tsdif<180){result={dm:yaer,hm:mday+"."+mon}}else{result={dm:yaer,hm:" "+mon}}return result}_getBeginOfDayFromUnixTs(ts){var result=new Date(ts*1e3);result=new Date(result.getFullYear(),result.getMonth(),result.getDate());result.setMinutes(59);result.setSeconds(59);result.setMilliseconds(1e3);return result.getTime()/1e3}colors=["#0044CC","#008000","#FF8533","#6A6A6A","#C71585","#8B4513","#1E90FF","#FF4500","#00FF00","#8A2BE2"];colorDefault="#657585";stepsX=[1,2,5,10,20,30,1*60,2*60,5*60,10*60,15*60,20*60,30*60,60*60,2*60*60,4*60*60,6*60*60,12*60*60,24*60*60,2*24*60*60,3*24*60*60,4*24*60*60,5*24*60*60,7*24*60*60,10*24*60*60,15*24*60*60,20*24*60*60,30*24*60*60,45*24*60*60,60*24*60*60,90*24*60*60,120*24*60*60]}class SingleLine{constructor(lineData,color){this.parId=lineData.par_id;this.parName=lineData.par_name!=null?lineData.par_name:"";this.objName=lineData.obj_name!=null?lineData.obj_name:"";this.real=[];if(lineData.connectIfmissing==null){this.connectIfmissing=false}else{this.connectIfmissing=lineData.connectIfmissing}this.isEmpty=true;this.hidden=false;if(color==null){this.color="black"}else{this.color=color}this.legend=null}}class LineData{constructor(obj_name,par_name,par_id,values,connectIfMissing){this.obj_name=obj_name;this.par_name=par_name;this.par_id=par_id;this.values=values;this.connectIfMissing=connectIfMissing}}if(typeof logger!="notdefined"){var logger={info:function(message){console.info(message)},warn:function(message){console.warn(message)},error:function(message){console.error(message)},debug:function(message){console.debug(message)}}}function addNewElement(parent,tag,attrSet){if(attrSet==null)attrSet={};if(attrSet.id!=null){if(document.getElementById(attrSet.id)!=null){newElementCounter++;attrSet.id=newElementCounter.toString()+"_"+(new Date).getTime().toString()}}else{newElementCounter++;attrSet.id=newElementCounter.toString()+"_"+(new Date).getTime().toString()}if(tag==null){var element=document.createElement("div")}else{var element=document.createElement(tag)}for(var attribute in attrSet){element.setAttribute(attribute,attrSet[attribute])}if(attrSet.innerText!=null)element.innerText=attrSet.innerText;if(attrSet.innerHTML!=null)element.innerHTML=attrSet.innerHTML;if(parent==null){document.body.appendChild(element)}else{parent.appendChild(element)}return document.getElementById(attrSet.id)}var newElementCounter=0;function getAvgValue(arData,precision){if(arData==null||arData.length==0)return NaN;if(precision==null||isNaN(precision))precision=2;var sum=0;var count=0;for(var i=0;i<arData.length;i++){if(!isNaN(arData[i])){sum+=arData[i];count+=1}}if(count==0){return NaN}else{return(sum/count).toFixed(precision)}}function getRandomInt(){return Math.random()*1e17}function isString(variable){return typeof variable==="string"||variable instanceof String}Date.prototype.separate=function(){var dt={};dt.year=this.getFullYear();dt.month=this.getMonth()+1;dt.mday=this.getDate();dt.hour=this.getHours();dt.min=this.getMinutes();dt.sec=this.getSeconds();dt.msec=this.getMilliseconds();if(dt.month<10)dt.month="0"+dt.month;if(dt.mday<10)dt.mday="0"+dt.mday;if(dt.hour<10)dt.hour="0"+dt.hour;if(dt.min<10)dt.min="0"+dt.min;if(dt.sec<10)dt.sec="0"+dt.sec;if(dt.msec<10){dt.msec="00"+dt.msec}else if(dt.msec<100){dt.msec="0"+dt.msec}return dt};function scvToTimeSeries(csv){let arResult=[];if(csv==null){return arResult}let arLines=csv.split(/\r?\n/);if(arLines.length<2){return arResult}var arHeader=arLines[0].split(",");for(let x=1;x<arHeader.length;x++){let obSerie={name:arHeader[x],data:""};for(let i=arLines.length-1;i>0;i--){let arElements=arLines[i].split(",");if(arElements.length!=arHeader.length)continue;obSerie.data+=moment(arElements[0]).format("X")+"/"+arElements[x]+";"}obSerie.data=obSerie.data.slice(0,-1);arResult.push(obSerie)}return arResult}
@@ -11,7 +11,7 @@
11
11
  }
12
12
 
13
13
  .chart-title {
14
- font-size: x-large;
14
+ font-size:large;
15
15
  }
16
16
 
17
17
  .chart-live-data {
@@ -69,11 +69,11 @@ timestamp,open,high,low,close,volume
69
69
  2019-09-25,137.5000,139.9580,136.0300,139.3600,22544054
70
70
  2019-09-24,140.3600,140.6900,136.8800,137.3800,30016670
71
71
  2019-09-23,139.2300,139.6300,138.4400,139.1400,17408374
72
- 2019-09-20,141.0100,141.6500,138.2500,139.4400,40040766
73
- 2019-09-19,140.3000,142.3700,140.0736,141.0700,36095413
74
- 2019-09-18,137.3600,138.6700,136.5299,138.5200,24473386
75
- 2019-09-17,136.9600,137.5200,136.4250,137.3900,17976285
76
- 2019-09-16,135.8300,136.7000,135.6600,136.3300,16731440
72
+ 2019-09-20,141.0100,140.6500,137.2500,138.4400,40040766
73
+ 2019-09-19,152.3000,153.3700,150.0736,153.0700,36095413
74
+ 2019-09-18,147.3600,148.6700,142.5299,148.5200,24473386
75
+ 2019-09-17,136.9600,137.5200,132.4250,137.3900,17976285
76
+ 2019-09-16,135.8300,136.7000,133.6600,134.3300,16731440
77
77
  2019-09-13,137.7800,138.0600,136.5700,137.3200,23363057
78
78
  2019-09-12,137.8500,138.4200,136.8700,137.5200,27009981
79
79
  2019-09-11,135.9100,136.2700,135.0900,136.1200,24726117
@@ -3,82 +3,68 @@ document.addEventListener('DOMContentLoaded', function () {
3
3
  });
4
4
 
5
5
  var isMobil = false;
6
- var request;
7
6
  var charts = [];
8
7
 
9
- // Example time-series. Semicolon separated pairs "Unix-Timestamp/Value;Unix-Timestamp/Value;.."
10
- // The values may be empty. The last element may be withoud value. It Indicate end of timespane
11
- // of this line.
12
- var arTimeSeries = [
13
- {
14
- name: 'Example one',
15
- data: '1565301600/-11.2;1565560800/-9;1565647200/-7.2;1565733600/-5.89;1565820000/-5.2;1565906400/-2.50;1566165600/-1.21;1566252000/0.20;1566338400/-2;1566424800/-4.5;1566511200/-6.2;1566770400/-8.3;1566856800/-10.0;1566943200/-11;1567029600/-13.8;1567116000/-15.8;1567461600/-12.9;1567548000/-8.9;1567634400/-8.94;1567720800/-10.96'
16
- },
17
- {
18
- name: 'Example Two',
19
- data: '1565301600/11.2;1565560800/6;1565647200/4;1565733600/2;1565820000/-2;1565906400/-3;1566165600/-4;1566252000/-6;1566338400/-7;1566424800/-8;1566511200/-8;1566770400/-5.5;1566856800/-3.6;1566943200/-0.6;1567029600/1.8;1567116000/3.8;1567461600/4.2;1567548000/5.4;1567634400/6.94;1567720800/7.96'
20
- },
21
- {
22
- name: 'Example Two',
23
- data: '1565301000/0;1565560200/-0.4;1565646600/-1.1;1565733000/-2;1565819400/-0.5;1565905800/-0.01;1566165000/0.2;1566252000/0.3;1566337800/2.2;1566424200/4.2;1566510600/5.2;1566779800/6.1;1566856200/7.4;1566942600/8;1567029000/8.2;1567115400/8.8;1567461000/9.2;1567547400/11.4;1567633800/12.94;1567720200/11.96'
24
- }
25
- ];
26
-
27
8
  function createCharts () {
28
-
29
- // Create first chart in div id "charts"
30
- let lchart;
31
9
 
32
- lchart = new LineChart(document.getElementById('charts'),null, null, 'Example Chart-Line', null);
33
-
34
- for(let i=0; i < arTimeSeries.length; i++) {
35
- let line = {
36
- obj_name: 'Chart',
37
- par_name: arTimeSeries[i].name,
38
- values: arTimeSeries[i].data
39
- };
40
- lchart.addLine(line);
41
- }
42
-
43
- lchart.draw();
10
+ // Parent element for charts
11
+ let parent = document.getElementById('charts');
44
12
 
13
+ // Create chart with numerical axis-x and attach to array
14
+ let lchart = new LineChart(parent,null , null,
15
+ 'Example with numerical values on axis-x', null, "number");
45
16
  charts.push(lchart);
46
17
 
47
- // Example convert CSV to time-series
48
- request = new XMLHttpRequest();
18
+ let lineData1 = {
19
+ obj_name: "Line one",
20
+ values: ""
21
+ };
22
+
23
+ // Create two examples as math. function. Last ";" don't need
24
+ for(i = 0; i < 91 ; i++){
25
+ lineData1.values += i+ "/"+ (i* Math.cos(i))+";";
26
+ }
27
+ lineData1.values = lineData1.values.substring(0, lineData1.values.length -1);
28
+ lchart.addLine(lineData1);
29
+
30
+ let lineData2 = {
31
+ obj_name: "Line two",
32
+ values: ""
33
+ };
34
+ for(i = 0; i < 90 ; i++){
35
+ lineData2.values += i+ "/"+ (i* Math.cos(i) * 2)+";";
36
+ }
37
+ lineData2.values = lineData2.values.substring(0, lineData2.values.length -1);
38
+ lchart.addLine(lineData2);
39
+
40
+ lchart.draw();
41
+
42
+ // Extract data from CSV and create new chart with time-based axis-x.
43
+ let request = new XMLHttpRequest();
49
44
  request.open("GET","example.csv");
50
45
  request.addEventListener('load', function(event) {
51
46
  if (request.status == 200) {
52
47
 
53
- // Convert SCV to format suitable for chart.
54
- let arTimeSeries = scvToTimeSeries(request.responseText);
55
-
56
- // Create next chart in div id "charts"
57
- lchart = new LineChart(document.getElementById('charts'),null, null, 'Example Chart-Line with data from CSV', null);
58
-
59
- for(let i=0; i < arTimeSeries.length - 1; i++) {
48
+ let arScvData = scvToTimeSeries(request.responseText);
49
+ lchart = new LineChart(document.getElementById('charts'),null, null,
50
+ "Example data from CSV and data-time on axis-x.", null, "time");
51
+ charts.push(lchart);
52
+
53
+ for(let i=0; i < arScvData.length - 1; i++) {
60
54
  let line = {
61
55
  obj_name: 'Stock preis',
62
- par_name: arTimeSeries[i].name,
63
- values: arTimeSeries[i].data
56
+ par_name: arScvData[i].name,
57
+ values: arScvData[i].data
64
58
  };
65
59
  lchart.addLine(line);
66
60
  }
67
61
 
68
62
  lchart.draw();
69
-
70
- charts.push(lchart);
71
63
  } else {
72
-
73
- console.warn("Request CSV failed status "+ request.statusText+ " Responce "+ request.responseText);
64
+ parent.innerHTML("Failed get CSV. "+ request.statusText+ " Responce "+ request.responseText);
74
65
  }
75
- });
66
+ });
76
67
 
77
68
  request.send();
78
69
  }
79
-
80
-
81
-
82
-
83
-
84
-
70
+
@@ -0,0 +1,18 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
6
+ <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
7
+ <title>Example Adaptive-Linecharts</title>
8
+ <link type="text/css" rel="stylesheet" href="../src/linechart.css" >
9
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
10
+ <script src="../src/linechart.js"></script>
11
+ <script src="../src/chart-util.js"></script>
12
+ <script src="example.js"></script>
13
+ </head>
14
+
15
+ <body>
16
+ <div id="charts" style="width: 99%;"> </div>
17
+ </body>
18
+ </html>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "adaptive-linechart",
3
- "version": "1.2.1",
3
+ "version": "1.3.0",
4
4
  "description": "Independent library to draw line-chart in browser.",
5
5
  "scripts": {
6
6
  "test": "echo \"Error: no test specified\" && exit 1"
package/src/chart-util.js CHANGED
@@ -2,25 +2,30 @@
2
2
  // Collection of small utilities
3
3
  //
4
4
 
5
- // Create simple logger. Used to log pisible error by processing data of chart.
5
+ /**
6
+ * Create simple logger. Used to log posible error by processing data of chart.
7
+ */
6
8
  if(typeof logger != "notdefined") {
7
9
  var logger = {
8
10
  info: function (message) { console.info(message);},
9
11
  warn: function (message) {console.warn(message);},
10
12
  error: function (message) {console.error(message);},
11
- debug: function (message) {console.debug(bessage);}
13
+ debug: function (message) {console.debug(message);}
12
14
  };
13
15
  }
14
16
 
15
- // Add new element with predefined attributes and return reference to new element.
16
- // @param parent - Reference to parent element. If null create new element in <body>.
17
- // @param tag String. Tag of new element. Default <div>
18
- // @param attrSet Object. Contains sub-elements. Each is one attribute of DOM element.
19
- // id - String. ID of new element. If not defined or is not unique create random.
20
- // innerText - String. If defined add as innerText.
21
- // innerHTML - String- If defined add as innerHTML.
22
- // Example {id:'chart_legend_item', style: 'display:none; padding:10px;'}
23
- // @return Reference to DOM element.
17
+ /**
18
+ * Add new element with predefined attributes and return reference to new element.
19
+ * @param reference to parent element. If null create new element in <body>.
20
+ * @param tag String. Tag of new element. Default <div>
21
+ * @param attrSet Object. Contains sub-elements. Each is one attribute of DOM element.
22
+ * id - String. ID of new element. If not defined or is not unique create random.
23
+ * innerText - String. If defined add as innerText.
24
+ * innerHTML - String- If defined add as innerHTML.
25
+ * @return reference to DOM element.
26
+ * @example
27
+ * var n = addNewElement(x, y, {id:'chart_legend_item', style: 'display:none; padding:10px;'});
28
+ */
24
29
  function addNewElement(parent, tag, attrSet) {
25
30
  if (attrSet == null) attrSet = {};
26
31
 
@@ -61,14 +66,18 @@ function addNewElement(parent, tag, attrSet) {
61
66
  return document.getElementById(attrSet.id);
62
67
  }
63
68
 
64
- // Counter that used in function addNewElement() to generate unique id
69
+ /**
70
+ * Counter that used in function addNewElement() to generate unique id
71
+ */
65
72
  var newElementCounter = 0;
66
73
 
67
- // Calculate average value from array and return float with defined precision
68
- // if at least one item in array is a number else return NaN.
69
- // @param arData - Array. Array of numbers.
70
- // $param precision - Integer. Default 2 digits.
71
- // @return Float or NaN.
74
+ /**
75
+ * Calculate average value from array and return float with defined precision if at least
76
+ * one item in array is a number else return NaN.
77
+ * @param arData - Array. Array of numbers.
78
+ * @param precision - Integer. Default 2 digits.
79
+ * @return float or NaN.
80
+ */
72
81
  function getAvgValue (arData, precision) {
73
82
 
74
83
  if(arData == null || arData.length == 0) return NaN;
@@ -92,18 +101,27 @@ function getAvgValue (arData, precision) {
92
101
  }
93
102
  }
94
103
 
95
- // Get random integer with 16 digits.
104
+ /**
105
+ * Get random integer with 16 digits.
106
+ * @returns number
107
+ */
96
108
  function getRandomInt () {
97
109
  return Math.random() * 100000000000000000;
98
- };
110
+ }
99
111
 
100
- // If variable is string return true, else false.
112
+ /**
113
+ * If variable is string return true, else false.
114
+ * @param variable {any}
115
+ * @returns boolean
116
+ */
101
117
  function isString(variable) {
102
118
  return typeof variable === 'string' || variable instanceof String;
103
119
  }
104
120
 
105
- // Function return object that contains pieces of data-time as strings. Year long, month 01..12,
106
- // day of month 01..31, hour 01..23, min 01..59, sec 01..59, msec 001...999
121
+ /**
122
+ * Function return object that contains pieces of data-time as strings. Year long, month 01..12,
123
+ * day of month 01..31, hour 01..23, min 01..59, sec 01..59, msec 001...999
124
+ */
107
125
  Date.prototype.separate = function() {
108
126
 
109
127
  var dt = {};
@@ -128,12 +146,14 @@ Date.prototype.separate = function() {
128
146
  }
129
147
 
130
148
  return dt;
131
- };
149
+ }
132
150
 
133
- // Convert CSV with header to array of time-series. Assume first value is data-time as string.
134
- // Name of serie take from header. CSV may contains many series (columns). Values may be empty.
135
- // Each serie is object {name: "Name of serie", data: "Unix-Timestamp/Value;Unix-Timestam/Value"}
136
- // This function need package Moment.js https://momentjs.com
151
+ /**
152
+ * Convert CSV with header to array of time-series. Assume first value is data-time as string.
153
+ * Name of serie take from header. CSV may contains many series (columns). Values may be empty.
154
+ * Each serie is object {name: "Name of serie", data: "Unix-Timestamp/Value;Unix-Timestam/Value"}
155
+ * This function need package Moment.js https://momentjs.com
156
+ */
137
157
  function scvToTimeSeries(csv) {
138
158
 
139
159
  let arResult = [];
@@ -179,7 +199,3 @@ function scvToTimeSeries(csv) {
179
199
 
180
200
  return arResult;
181
201
  }
182
-
183
- //
184
- // Extentions existing types
185
- //
package/src/linechart.css CHANGED
@@ -11,7 +11,7 @@
11
11
  }
12
12
 
13
13
  .chart-title {
14
- font-size: x-large;
14
+ font-size:large;
15
15
  }
16
16
 
17
17
  .chart-live-data {