adaptive-linechart 1.2.2 → 1.4.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/src/linechart.js CHANGED
@@ -1,19 +1,31 @@
1
- // Version 1.2.2
2
- // The oject represent line-chart. Constructor create HTML code for the chart. The chart
3
- // uses external CSS styles .nowrap .linechart, .chart-title, .chart-live-data, .chart-legend,
4
- // .chart-legent-item, .chart-legent-color. The chart uses global variable isMobil (Boolean).
5
- // If false, show live data by mouse over. By click on item in legend called external function
6
- // processSelectLegendItem(chartId, amount-of-lines, parId). Only positive values allowed.
7
- // Labels on axe-X and -Y will be created automaticaly. The chart can show maximal 10 lines
8
- // in different colors.
9
- // @consructor:
10
- // @param container - Reference to parent element for chart. If null use HTML BODY as parent element.
11
- // @param chartId - String. Identifier for chart. Optional. If not defined use random integer.
12
- // @param width - Integer. Width in pixel. Optional. Default use available width in parent element.
13
- // @param title - String. Title of chart. Optional. If null don't create title.
14
- // @param className - String. Class for div of chart. Optinal. Default "linechart"
1
+ // Comments https://jsdoc.app/
2
+
3
+ /**
4
+ * @version 1.4.0
5
+ * @author Andrej Koslov
6
+ */
7
+
8
+ /**
9
+ * The oject represent the chart. Constructor create object and HTML code for the chart. The chart
10
+ * uses external CSS styles .nowrap .linechart, .chart-title, .chart-live-data, .chart-legend,
11
+ * .chart-legent-item, .chart-legent-color. The chart uses global variable isMobil (Boolean). If
12
+ * false, show live data by mouse over. The line create from LineData (see above) Labels on axis X
13
+ * and Y will be created automaticaly. The chart can show maximal 10 lines in different colors.
14
+ * @class
15
+ * @param container {HTMLElement} parent element for the chart. If null use HTML BODY as parent element.
16
+ * @param chartId {number} identifier for chart. Optional. If not defined use random number.
17
+ * @param width {number} width in pixel. Optional. Default use available width in parent element.
18
+ * @param title {string} title of chart. Optional. If null don't create title.
19
+ * @param className {string} class for div of chart. Optional. Default "linechart"
20
+ * @param axisXType {string} for time based values on axis X set "time" (Default). For number based
21
+ * values "number".
22
+ * @param ifDataMissing {string} handling of missing values on axis X.
23
+ * "connect" (Default) - connect line across missing values.
24
+ * "noline" - don't draw line across missing values.
25
+ * "skip" - reserved, not yet implemented.
26
+ */
15
27
  class LineChart {
16
- constructor(container, chartId, width, title, className) {
28
+ constructor(container, chartId, width, title, className, axisXType, ifDataMissing) {
17
29
  if(container == null)
18
30
  container = document.getElementsByTagName("BODY")[0];
19
31
  if(chartId == null)
@@ -30,16 +42,14 @@ class LineChart {
30
42
  chart_id: chartId,
31
43
  style: 'float:left; width:' + width + 'px; padding-bottom:8px;'
32
44
  });
33
- // Create title if string for title not null.
45
+ // Create title for chart if parameter title is not null.
34
46
  if (title != null) {
35
- this.title = addNewElement(this.chartDiv, 'label', {
47
+ let titleElement = addNewElement(this.chartDiv, 'label', {
36
48
  class: 'chart-title nowrap',
37
- style: 'width:' + (width - 20) + 'px; text-align:center; display:block; margin-left:10px; margin-top:10px',
49
+ style: 'width:'+ (width - 20)+ 'px; text-align:center; display:block; margin-left:10px; margin-top:10px',
38
50
  });
39
- this.title.innerHTML = title;
40
- } else {
41
- this.title = null;
42
- }
51
+ titleElement.innerHTML = title;
52
+ }
43
53
  // Calculate real width of canvas based on width of chart-div. Think about margin
44
54
  // of canvas 30 = 17(margin-left) + 13(margin-right)
45
55
  var canvasWidth = width - 30;
@@ -65,25 +75,51 @@ class LineChart {
65
75
  }
66
76
  }
67
77
  // Add canvas and save reference to this one.
68
- this.canvas = addNewElement(this.chartDiv, 'canvas', {
78
+ this._canvas = addNewElement(this.chartDiv, 'canvas', {
69
79
  id: 'chart_' + chartId+ '_canvas',
70
80
  width: canvasWidth,
71
81
  height: canvasHeight,
72
82
  style: 'margin: 15px 17px 3px 13px;'
73
83
  });
84
+ // Set type of axis-X "number" or "time".
85
+ if(axisXType != null || (typeof axisXType) == "undefined" ) {
86
+ if(axisXType == "number") {
87
+ this.axisXType = "number";
88
+ } else if(axisXType == "time") {
89
+ this.axisXType = "time";
90
+ } else {
91
+ logger.warn(`Unknow value axisXType=${axisXType}. Set default "time".`)
92
+ this.axisXType = "time";
93
+ }
94
+ } else {
95
+ this.axisXType = "time";
96
+ }
97
+
98
+ // Set handling of missing values on axis-X.
99
+ if(ifDataMissing == null) {
100
+ this.ifDataMissing = "connect";
101
+ } else if(ifDataMissing == "connect" || ifDataMissing == "noline" || ifDataMissing == "skip") {
102
+ this.ifDataMissing = ifDataMissing;
103
+ } else {
104
+ logger.warn(`Unknow value ifDataMissing=${ifDataMissing}. Set default "connect".`);
105
+ this.ifDataMissing = "connect";
106
+ }
107
+
74
108
  // Used to show live data by mousemove over the canvas.
75
- this.canvas.dataset.chartId = chartId.toString();
109
+ this._canvas.dataset.axisXType = this.axisXType;
110
+ this._canvas.dataset.ifDataMissing = this.ifDataMissing;
111
+ this._canvas.dataset.chartId = chartId.toString();
76
112
  // Save reference to context.
77
- this.context = this.canvas.getContext('2d');
113
+ this._context = this._canvas.getContext('2d');
78
114
  // I don't know how it work, but this command disable/reduce antialiasing!
79
115
  // It works only if lines are 1 pixel! Need if canvas created or size changed
80
116
  // and before draw on canvas.
81
- this.context.translate(0.5, 0.5);
117
+ this._context.translate(0.5, 0.5);
82
118
  // Create element to show data by mousemove and set default '-'.
83
119
  if (!isMobil) {
84
120
  // Add events processing for canvas and show live data (value and data-time)
85
121
  // By leave the canvas remove data.
86
- this.canvas.addEventListener("mouseout", function (event) {
122
+ this._canvas.addEventListener("mouseout", function (event) {
87
123
  // Select element which show data.
88
124
  var element = document.getElementById('chart_' + this.dataset.chartId+'_livedata');
89
125
  if (element == null)
@@ -91,7 +127,7 @@ class LineChart {
91
127
  element.innerText = '-';
92
128
  });
93
129
  // By mousemove over canvas show value and date-time in special element.
94
- this.canvas.addEventListener('mousemove', function (event) {
130
+ this._canvas.addEventListener('mousemove', function (event) {
95
131
  // Select element which show data.
96
132
  var element = document.getElementById('chart_' + this.dataset.chartId+'_livedata');
97
133
  if (element == null)
@@ -101,41 +137,51 @@ class LineChart {
101
137
  element.innerText = '-';
102
138
  return;
103
139
  }
104
- // Calculate position on axe-X to value (return if invalid result) and reduce amount of decimal digits.
105
- var curVal = this.dataset.maxVal - event.offsetY / parseFloat(this.dataset.coefVal);
106
- if (isNaN(curVal)) {
140
+ // Calculate position on axe-y to value (return if invalid result) and reduce amount of decimal digits.
141
+ var curValY = this.dataset.maxVal - event.offsetY / parseFloat(this.dataset.coefVal);
142
+ if (isNaN(curValY)) {
107
143
  element.innerText = '-';
108
144
  return;
109
145
  }
110
- if (curVal < 100) {
111
- curVal = curVal.toFixed(2);
146
+ if (curValY < 100) {
147
+ curValY = curValY.toFixed(2);
112
148
  }
113
- else if (curVal < 200) {
114
- curVal = curVal.toFixed(1);
149
+ else if (curValY < 200) {
150
+ curValY = curValY.toFixed(1);
115
151
  }
116
152
  else {
117
- curVal = Math.round(curVal);
153
+ curValY = Math.round(curValY);
118
154
  }
119
- // Calculate position on axe-Y to data-time. If result invalid return.
120
- var curTs = parseInt(this.dataset.minTs) + Math.round((event.offsetX - parseInt(this.dataset.paddingLeft)) / parseFloat(this.dataset.coefTs));
121
- if (isNaN(curTs)) {
122
- element.innerText = '-';
123
- return;
155
+
156
+ // Format of data depend on type of axis-x
157
+ if(this.dataset.axisXType == "time") {
158
+ // Calculate position on axis-x to data-time. If result invalid return.
159
+ var curTs = parseInt(this.dataset.minTs) +
160
+ Math.round((event.offsetX - parseInt(this.dataset.paddingLeft)) / parseFloat(this.dataset.coefTs));
161
+ if (isNaN(curTs)) {
162
+ element.innerText = '-';
163
+ return;
164
+ }
165
+ // From Unix-Timestamp create data object that contains separate elements of data-time.
166
+ curTs = new Date(curTs * 1000).separate();
167
+ // Set current value and data-time.
168
+ element.innerHTML = 'Date <b>'+ curTs.mday+ '.'+ curTs.month+ '.'+ curTs.year+ '</b> Time <b>'+ curTs.hour+ ':'+ curTs.min+
169
+ '</b> Value <b>'+ curValY+ '</b>';
170
+ } else {
171
+ var curValX = parseFloat(this.dataset.minTs) +
172
+ Math.round((event.offsetX - parseInt(this.dataset.paddingLeft)) / parseFloat(this.dataset.coefTs));
173
+ element.innerHTML = 'Axis-X <b>'+ curValX+ '</b> Axis-Y <b>' + curValY + '</b>';
124
174
  }
125
- // From Unix-Timestamp create data object that contains separate elements of data-time.
126
- curTs = new Date(curTs * 1000).separate();
127
- // Set current value and data-time.
128
- element.innerHTML = 'Date <b>' + curTs.mday + '.' + curTs.month + '.' + curTs.year + '</b> Time <b>' + curTs.hour + ':' + curTs.min + '</b> Value <b>' + curVal + '</b>';
129
175
  });
130
176
  addNewElement(this.chartDiv, 'div', {
131
- class: "chart-live-data",
177
+ class: "chart-live-data, nowrap",
132
178
  id: 'chart_' + chartId+ '_livedata',
133
179
  style: "margin-left: 12px; margin-right: 12px; margin-bottom: 4px; max-width:95%;",
134
180
  innerText: '-'
135
181
  });
136
182
  }
137
183
  // Add div for legend. Each item in the legend is separate sub-div.
138
- this.legendDiv = addNewElement(this.chartDiv, 'div', {
184
+ this._legendDiv = addNewElement(this.chartDiv, 'div', {
139
185
  class: 'chart-legend',
140
186
  id: 'chart_' + chartId+ '_legend'
141
187
  });
@@ -143,42 +189,49 @@ class LineChart {
143
189
  this.chartId = chartId;
144
190
  // Array of objects that represent lines.
145
191
  this.lines = [];
146
- // Integer. Begin of time that show chart. Sec. Unix Time-stamp.
147
- this.minTs = 99999999999999;
148
- // Integer. End of time that show chart. Sec. Unix Time-stamp.
149
- this.maxTs = 0;
150
- // Minimal measuring value.
151
- this.minVal = Number.MAX_SAFE_INTEGER;
152
- // Maximal measuring value.
153
- this.maxVal = Number.MIN_SAFE_INTEGER;
154
- // Difference between two labels on axe Y. Real value, not a pix!
155
- this.axeYLabelStep = null;
156
- // Default and minimal distance (pixel) between labels on axe-y.
157
- this.axeYLabelHeight = 30;
158
- // Default and minimal distance (pixel) between labels on axe-x.
159
- this.axeXLabelWidth = 80;
160
- // Coefficient to convert time-stamp to coordinate X.
161
- this.coefTs = null;
162
- // Coefficient to convert values to coordinate Y.
163
- this.coefVal = null;
192
+ // Integer. Begin of time that show chart. Sec. Unix Time-stamp. Later calculate
193
+ // from data.
194
+ this._minTs = Number.MAX_SAFE_INTEGER;
195
+ // Integer. End of time that show chart. Sec. Unix Time-stamp. Later calculate
196
+ // from data.
197
+ this._maxTs = 0;
198
+ // Raw minimal/maximal measuring value of all lines (without margin).
199
+ // Later calculated from the data. Infinity/-Infinity = "no value yet".
200
+ this._minValRaw = Infinity;
201
+ this._maxValRaw = -Infinity;
202
+ // Display range (raw values + margin), calculated in draw().
203
+ this._minVal = Infinity;
204
+ this._maxVal = -Infinity;
205
+ // Distance between two labels on axis Y. Real value, not a pix! Later calculate
206
+ // from data.
207
+ this._axeYLabelStep = null;
208
+ // Default and minimal distance (pixel) between labels on axe-y. Later calculate
209
+ // from data.
210
+ this._axeYLabelHeightDefault= 30;
211
+ // Default distance (pixel) between labels on axe-x. Later calculate
212
+ // from data suitable value.
213
+ this._axeXLabelWidthDefault = 80;
214
+ // Coefficient to convert time-stamp to coordinate X. Later calculate from data.
215
+ this._coefX = null;
216
+ // Coefficient to convert values to coordinate Y. Later calculate from data.
217
+ this._coefY = null;
164
218
  // Padding in canvas where to place labels. Later adjust to real width of labels.
165
- this.padding = { left: 50, bottom: 35 };
166
- // Indicate selected in calender end-date. This parmeter used in SingleChart.
167
- this.endDate = null;
168
- // Average step. Seconds. If is valid number used to calculate step by drawing the chart.
169
- // If NaN, not used. This variable may be set manual.
219
+ this._padding = { left: 50, bottom: 35 };
220
+ /**
221
+ * Instead automatic, the average step on axis X may be set manual.
222
+ * Several measured values are combined into fixed time windows to
223
+ * flatten peaks in the graph. Value in seconds. If NaN, not used.
224
+ */
170
225
  this.avgStep = NaN;
171
226
 
172
227
  // End consctructor object LineChart.
173
228
  }
174
229
 
175
- // Add data for new line. Automaticaly create new item in legend.
176
- // @parameter lineData Object. The object represent data for one line in chart.
177
- // line.obj_name:"Proxy Server"
178
- // line.par_name:"CpuTotal"
179
- // line.par_id:"2452"
180
- // line.values: Example data-string "161111145730/3.48;161111145843/3.50;161111150013/"
181
- // @return Boolean. True if no problem detected. Else false.
230
+ /**
231
+ * Add new line and create new item in legend.
232
+ * @param lineData {LineData} object that represents the data for one line.
233
+ * @return {boolean} true if no problem detected, otherwise false.
234
+ */
182
235
  addLine (lineData) {
183
236
  if (lineData.values == null) {
184
237
  logger.error('Function LineChart.newLine(). DataString is null.');
@@ -196,24 +249,40 @@ class LineChart {
196
249
  logger.error('Function LineChart.newLine(). Function _createLine() return null.');
197
250
  return false;
198
251
  }
199
- // Add properties of line used to create legend.
200
- line.objName = lineData.obj_name;
201
- line.parName = lineData.par_name;
202
- line.parId = lineData.par_id;
203
- line.color = this.colors[this.lines.length];
252
+ // Create legend-item for the new line.
253
+ this._createLegendItem(line, lineData);
254
+ // Put new line array of lines.
255
+ this.lines.push(line);
256
+ return true;
257
+ }
258
+
259
+ /**
260
+ * Create legend-item as dom-element and attach click handler to hide/show the line.
261
+ * @param line SingleLine. Newly created line.
262
+ * @param lineData Object. Original lineData used to build the legend text.
263
+ * @private
264
+ */
265
+ _createLegendItem (line, lineData) {
204
266
  // Create legend-item as dom-element.
205
- line.legend = addNewElement(this.legendDiv, 'div', {
206
- class: 'chart-legend-item nowrap',
267
+ line.legend = addNewElement(this._legendDiv, 'div', {
268
+ class: 'chart-legend-item nowrap',
207
269
  id: `chart_${this.chartId}_legend_${lineData.par_id}`,
208
- style: `cursor: pointer; max-width:${this.chartDiv.clientWidth - 20}px;`,
209
- innerHTML: `<span class="chart-legend-color" style="background-color:${line.color}; color:${line.color};">--</span>${line.objName} / ${line.parName}`
270
+ style: `cursor: pointer; max-width:${this.chartDiv.clientWidth - 20}px;`
210
271
  });
272
+ // Add colored tag. Its color comes from the internal palette (trusted)
273
+ addNewElement(line.legend, 'span', {
274
+ class: 'chart-legend-color',
275
+ style: `background-color:${line.color}; color:${line.color};`,
276
+ innerHTML: '--'
277
+ });
278
+ // The label text is added as plain text, so obj_name/par_name cannot inject HTML (XSS).
279
+ line.legend.appendChild(document.createTextNode(line.objName + ' / ' + line.parName));
211
280
  // Set function called by click on element to hide/show line on chart.
212
281
  line.legend.addEventListener('click', function (event) {
213
282
 
214
283
  // First sub-element of class chart-legend-color is colored tag for this legend item.
215
284
  // This element used to swith color by click on legent item.
216
- var legendColor = event.target.getElementsByClassName('chart-legend-color')[0];
285
+ var legendColor = event.currentTarget.querySelector('.chart-legend-color');
217
286
 
218
287
  // By click on colored tag this varibale is null. In this case only exit.
219
288
  if(legendColor == null) return;
@@ -226,20 +295,19 @@ class LineChart {
226
295
  legendColor.style.backgroundColor = line.color;
227
296
  }
228
297
 
229
- event.target.chart.draw();
298
+ event.currentTarget.chart.draw();
230
299
  });
231
300
 
232
301
  // Link to parent chart in the legend item. Need to process click on legend item.
233
302
  line.legend.chart = this;
234
-
235
- // Put new line array of lines.
236
- this.lines.push(line);
237
- return true;
238
303
  }
239
304
 
240
- // Update data in chart and redraw this one again. All items in legend stay the same!
241
- // @parameter lines Array of objects of type SingleLine.
242
- // @return true if no problem detected else false.
305
+ /**
306
+ * Update data in chart and redraw this one. The old legend items are removed and
307
+ * recreated for the new lines.
308
+ * @param lines {LineData[]} array of lineData objects; replaces all current lines.
309
+ * @return {boolean} true if no problem detected, otherwise false.
310
+ */
243
311
  updateLines (lines) {
244
312
  if (lines == null) {
245
313
  logger.error('Function LineChart.updateLines(). Parameter lines is null.');
@@ -249,44 +317,44 @@ class LineChart {
249
317
  logger.error('Function LineChart.updateLines(). Parameter lines is not a array.');
250
318
  return false;
251
319
  }
252
- // Reset to default some parameters of chart.
320
+ // Remove old legend items.
321
+ if (this._legendDiv != null) {
322
+ while (this._legendDiv.firstChild != null) {
323
+ this._legendDiv.removeChild(this._legendDiv.firstChild);
324
+ }
325
+ }
326
+ // Reset to default some parameters of chart. Same defaults as in constructor.
253
327
  this.lines = [];
254
- this.minTs = 99999999999999;
255
- this.maxTs = 0;
256
- this.minVal = 999999999999999;
257
- this.maxVal = 0;
258
- this.axeYLabelStep = null;
259
- this.coefTs = null;
260
- this.coefVal = null;
261
- // Process lines. Each new line add to array of lines.
262
- for (var i in lines) {
328
+ this._minTs = Number.MAX_SAFE_INTEGER;
329
+ this._maxTs = 0;
330
+ this._minValRaw = Infinity;
331
+ this._maxValRaw = -Infinity;
332
+ this._minVal = Infinity;
333
+ this._maxVal = -Infinity;
334
+ this._axeYLabelStep = null;
335
+ this._coefX = null;
336
+ this._coefY = null;
337
+ // Process lines. Each new line creates a line-object and a legend-item.
338
+ for (var i = 0; i < lines.length; i++) {
263
339
  var line = this._createLine(lines[i]);
264
340
  if (line != null) {
341
+ this._createLegendItem(line, lines[i]);
265
342
  this.lines.push(line);
266
343
  }
267
344
  }
268
345
  this.draw();
269
346
  return true;
270
347
  }
271
-
272
- _processSelectLegentItem = function() {
273
- console.info("Prozess legent item");
274
- }
275
-
276
- // Create line from object that represent one line of backend's response. If found one negative
277
- // value return null and output error in logger. If data-string is empty, create line with flag
278
- // isEmpty=true. The function also update some variables of chart minTs, maxTs, minVal, maxVal.
279
- // Example data-string "161111145730/3.48;161111145843/;161111150013/"
280
- // Each element separated by ";" in each element time-stamp separated from value by "/".
281
- // Value may be empty! Always in last item the element without value. It indicate only
282
- // where is end of time-period.
348
+
349
+ /**
350
+ * Create line for chart and update some properties of chart minTs, maxTs, minVal, maxVal.
351
+ * @parameter lineData Object.
352
+ * @return SingleLine Object.
353
+ * @private
354
+ */
283
355
  _createLine (lineData) {
284
- // Create object empty line.
285
- var line = new SingleLine(lineData);
286
-
287
- // Flag. True if value of all items are NaN. In this case set min/max 0/1
288
- var isAllNaN = true;
289
-
356
+ // Create line. Add data later.
357
+ var line = new SingleLine(lineData, this.colors[this.lines.length]);
290
358
  // If par_id is missing, set number of line in the chart as par_id
291
359
  if(lineData.par_id == null)
292
360
  lineData.par_id = this.lines.length;
@@ -305,51 +373,43 @@ class LineChart {
305
373
  var item = ar[i].split('/');
306
374
 
307
375
  if (item[0] == "") {
308
- logger.warn('LineChart._createLine(). Item ' + i + ' time-stamp is empty.');
376
+ logger.warn('LineChart._createLine(). Item ' + i + '. Element for axis-x is empty.');
309
377
  continue;
310
378
  }
311
379
 
312
380
  if (isNaN(item[0])) {
313
- logger.warn('LineChart._createLine(). Item ' + i + ' contains invalid time-stamp "' + item[0] + '".');
381
+ logger.warn('LineChart._createLine(). Item ' + i + '. Element for axis-x is not a number "' + item[0] + '".');
314
382
  continue;
315
383
  }
316
384
 
317
385
  var elem = { ts: null, val: null };
318
- elem.ts = parseInt(item[0]);
386
+ // For axisXType "number" the X value may contain decimals (e.g. 0.001),
387
+ // so parse as float. For "time" it is an integer unix time-stamp in seconds.
388
+ if (this.axisXType == "number")
389
+ elem.ts = parseFloat(item[0]);
390
+ else
391
+ elem.ts = parseInt(item[0]);
319
392
  elem.val = parseFloat(item[1]);
320
393
 
321
394
  line.real.push(elem);
322
395
 
323
- // If value is valid number, update min/max and set false isAllNaN.
396
+ // If value is valid number, update raw min/max.
324
397
  if (!isNaN(elem.val)) {
325
-
326
- // Update mininal value. Positive and negative values process differently.
327
- if(elem.val < 0) {
328
-
329
- if(Math.floor(elem.val * 1.1) < this.minVal) {
330
- this.minVal = Math.floor(elem.val * 1.1);
331
- }
332
-
333
- } else {
334
-
335
- if(Math.floor(elem.val * 0.9) < this.minVal) {
336
- this.minVal = Math.floor(elem.val * 0.9);
337
- }
338
- }
339
-
340
- // Update maximal value.
341
- if (Math.ceil(elem.val * 1.1) > this.maxVal) {
342
- this.maxVal = Math.ceil(elem.val * 1.1);
343
- }
344
398
 
345
- isAllNaN = false;
399
+ // Track the raw (true) minimal and maximal measuring value over
400
+ // all lines. The 10 % margin is applied later in draw(), based
401
+ // on the whole range, not per value.
402
+ if (elem.val < this._minValRaw)
403
+ this._minValRaw = elem.val;
404
+ if (elem.val > this._maxValRaw)
405
+ this._maxValRaw = elem.val;
346
406
  }
347
407
 
348
408
  // Update min/max time-stamp
349
- if (elem.ts < this.minTs)
350
- this.minTs = elem.ts;
351
- if (elem.ts > this.maxTs)
352
- this.maxTs = elem.ts;
409
+ if (elem.ts < this._minTs)
410
+ this._minTs = elem.ts;
411
+ if (elem.ts > this._maxTs)
412
+ this._maxTs = elem.ts;
353
413
  }
354
414
 
355
415
  // If line is empty skip next operations.
@@ -357,223 +417,354 @@ class LineChart {
357
417
  return line;
358
418
 
359
419
  line.isEmpty = false;
360
- // Adjust min/max values if both 0 or all values NaN
361
- if ((this.maxVal == 0 && this.minVal == 0) || isAllNaN) {
362
- this.minVal = 0;
363
- this.maxVal = 1;
420
+
421
+ // If the chart still has no valid measuring value, use a default range.
422
+ if (this._minValRaw === Infinity) {
423
+ this._minValRaw = 0;
424
+ this._maxValRaw = 1;
364
425
  }
365
426
 
366
427
  // Calculate padding. This area used for labels. Both are type of object TextMetrics.
367
- var minValText = this.context.measureText(this.minVal.toString());
368
- var maxValText = this.context.measureText(this.maxVal.toString());
428
+ // Measure a short representation (like the Y-axis labels), not the full
429
+ // float string of the raw min/max values.
430
+ var minValTextWidth = this._getLabelWidth(this._minValRaw);
431
+ var maxValTextWidth = this._getLabelWidth(this._maxValRaw);
369
432
  // Set place for label using biggest value.
370
- if (minValText.width < maxValText.width) {
371
- this.padding.left = Math.round(maxValText.width) + 23;
433
+ if (minValTextWidth < maxValTextWidth) {
434
+ this._padding.left = Math.round(maxValTextWidth) + 23;
372
435
  } else {
373
- this.padding.left = Math.round(minValText.width) + 23;
436
+ this._padding.left = Math.round(minValTextWidth) + 23;
374
437
  }
375
438
 
376
439
  return line;
377
440
  }
378
441
 
379
- // Clear all on graphic. Legend stay visible.
442
+ /**
443
+ * Clear all on graphic. Legend stay visible.
444
+ */
380
445
  clear () {
381
- this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
446
+ this._context.clearRect(0, 0, this._canvas.width, this._canvas.height);
382
447
  }
383
448
 
384
- // Draw graphic with all elements.
449
+ /**
450
+ * Draw graphic with all elements.
451
+ */
385
452
  draw () {
386
- // Update coefficient for values and time-stamps only if line is not empty.
387
- this.coefTs = (this.canvas.width - this.padding.left) / (this.maxTs - this.minTs);
388
- this.coefVal = (this.canvas.height - this.padding.bottom) / (this.maxVal - this.minVal);
389
453
  // Clear canvas
390
- this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
454
+ this._context.clearRect(0, 0, this._canvas.width, this._canvas.height);
391
455
  // Return true if all lines in the chart are empty.
392
456
  if (this.isEmpty())
393
457
  return;
458
+ // Apply a 10 % margin around the raw value range, so the line never
459
+ // touches the top/bottom border. Constant data gets a small fixed
460
+ // range around its value. The raw values stay in _minValRaw/_maxValRaw.
461
+ var range = this._maxValRaw - this._minValRaw;
462
+ if (range == 0) {
463
+ this._minVal = this._minValRaw - 1;
464
+ this._maxVal = this._maxValRaw + 1;
465
+ } else {
466
+ var margin = range * 0.1;
467
+ this._minVal = this._minValRaw - margin;
468
+ this._maxVal = this._maxValRaw + margin;
469
+ }
470
+ // Update coefficient for values and time-stamps only if line is not empty.
471
+ this._coefX = this._getCoefX();
472
+ this._coefY = this._getCoefY();
394
473
  // Draw axe-x and labels with values
395
- this._drawAxeX();
474
+ if(this.axisXType == "time") {
475
+ this._drawAxeXTime();
476
+ }
477
+ else {
478
+ this._drawAxeXNum();
479
+ }
396
480
  // Draw axe-y and time-labels
397
481
  this._drawAxeY();
398
482
  // Draw each line separate.
399
483
  for (var i = 0; i < this.lines.length; i++) {
400
- this.drawLine(i);
484
+ this._drawLine(i);
401
485
  }
402
486
  // Refresh data need to show live-data
403
- this.canvas.dataset.minTs = this.minTs.toString();
404
- this.canvas.dataset.coefTs = this.coefTs.toString();
405
- this.canvas.dataset.maxVal = this.maxVal.toString();
406
- this.canvas.dataset.coefVal = this.coefVal.toString();
407
- this.canvas.dataset.paddingLeft = this.padding.left.toString();
408
- this.canvas.dataset.paddingBottom = this.padding.bottom.toString();
487
+ this._canvas.dataset.minTs = this._minTs.toString();
488
+ this._canvas.dataset.coefTs = this._coefX.toString();
489
+ this._canvas.dataset.maxVal = this._maxVal.toString();
490
+ this._canvas.dataset.coefVal = this._coefY.toString();
491
+ this._canvas.dataset.paddingLeft = this._padding.left.toString();
492
+ this._canvas.dataset.paddingBottom = this._padding.bottom.toString();
409
493
  }
410
494
 
411
- // Set new size E.g. if size of parent panel changed.
495
+ /**
496
+ * Calculate coefficient to convert timestamps on axis-X to pixels.
497
+ * @return {number}
498
+ * @private
499
+ */
500
+ _getCoefX () {
501
+ return (this._canvas.width - this._padding.left) / (this._maxTs - this._minTs);
502
+ }
503
+
504
+ /**
505
+ * Calculate coefficient to convert values on axis-Y to pixels.
506
+ * @return {number}
507
+ * @private
508
+ */
509
+ _getCoefY () {
510
+ return (this._canvas.height - this._padding.bottom) / (this._maxVal - this._minVal);
511
+ }
512
+
513
+ /**
514
+ * Width (in pixels) of the short label representation of a value: integers
515
+ * for values >= 10, two decimals for smaller values. This matches how the
516
+ * labels on axis-Y are displayed. Used to calculate padding.left.
517
+ * @param val {number}
518
+ * @return {number} width in pixels.
519
+ * @private
520
+ */
521
+ _getLabelWidth (val) {
522
+ var str = Math.abs(val) < 10 ? val.toFixed(2) : Math.round(val).toString();
523
+ return this._context.measureText(str).width;
524
+ }
525
+
526
+ /**
527
+ * Change size of chart and redraw. May be used if size of parent panel changed but data
528
+ * in lines stay the same.
529
+ * @param difWidth {number} difference in width (pixel).
530
+ * @param difHeight {number} difference in height (pixel).
531
+ */
412
532
  resize(difWidth, difHeight) {
413
- //if(!angular.isNumber(difWidth) || !angular.isNumber(difHeight)) return;
414
- this.canvas.width = this.canvas.width + difWidth;
415
- this.canvas.height = this.canvas.height + difHeight;
416
- this.context.translate(0.5, 0.5);
533
+ this._canvas.width = this._canvas.width + difWidth;
534
+ this._canvas.height = this._canvas.height + difHeight;
535
+ this._context.translate(0.5, 0.5);
536
+ this.draw();
417
537
  }
418
538
 
419
- // Draw axe X and labels.
420
- _drawAxeX () {
421
- // Draw axe X
422
- this.context.strokeStyle = this.colorDefault;
423
- this.context.lineWidth = 1;
424
- this.context.beginPath();
425
- this.context.moveTo(this.padding.left, this.canvas.height - this.padding.bottom);
426
- this.context.lineTo(this.canvas.width, this.canvas.height - this.padding.bottom);
427
- this.context.stroke();
428
- // Calculate suitable step between labels on axe-x.
429
- // Average distance between labels in minutes
430
- var stepTs = Math.round(this.axeXLabelWidth / this.coefTs / 60);
431
- // Variable use by loop over array.
539
+ /**
540
+ * Draw axes-x and labels for time based values.
541
+ * @private
542
+ */
543
+ _drawAxeXTime () {
544
+ this._drawAxeXBasic();
545
+ // Variable used by loop over differently arrays.
432
546
  var arLen;
433
- // Select from available steps best suitable.
434
- arLen = this.stepsX.length - 1;
435
- for (var i = 0; i < arLen; i++) {
436
- if (stepTs > this.stepsX[i] && stepTs < this.stepsX[i + 1]) {
437
- stepTs = this.stepsX[i];
438
- break;
439
- }
440
- }
441
- // Convert step in minutes to seconds.
442
- stepTs = stepTs * 60;
443
- // Calculate time-stamp of first label
444
- // Get time of day of minimal time-stamp
445
- var tsLabel = this._getBeginOfDayFromUnixTs(this.minTs);
446
- var isFound = false;
447
- // Limit time-stamp of minimal label to current time.
448
- // Time-stamp of first label can't be bigger as as current time.
449
- var tsNow = new Date().getTime() / 1000;
450
- while (tsLabel < tsNow) {
451
- if (tsLabel > this.minTs) {
452
- isFound = true;
453
- break;
547
+
548
+ // Calculate suitable step between labels on axis-x. First get average distance between
549
+ // labels in seconds.
550
+ var stepTs = Math.round(this._axeXLabelWidthDefault / this._coefX );
551
+ // If step is very small set to minimal step 1 second.
552
+ if(stepTs <= 1) {
553
+ stepTs = 1;
554
+ } else {
555
+ // Select from available steps best suitable.
556
+ arLen = this.stepsX.length - 1;
557
+ for (var i = 0; i < arLen; i++) {
558
+ if (stepTs > this.stepsX[i] && stepTs < this.stepsX[i + 1]) {
559
+ stepTs = this.stepsX[i];
560
+ break;
561
+ }
454
562
  }
455
- tsLabel += stepTs;
456
563
  }
564
+
565
+ // Timestamp des ersten Labels berechnen: das erste stepTs-Vielfache des
566
+ // Raster-Ankers, das nicht kleiner als minTs ist. Bei kleinen Schritten
567
+ // ist der Anker der Tagesbeginn, bei Monats-/Jahres-Schritten
568
+ // (stepTs >= 30 Tage) der Jahresbeginn. So liegen die Labels großer
569
+ // Zeiträume auf Kalendergrenzen.
570
+ var tsFirstLabel = stepTs >= 30 * 24 * 3600
571
+ ? this._getBeginOfYearFromUnixTs(this._minTs)
572
+ : this._getBeginOfDayFromUnixTs(this._minTs);
573
+ while (tsFirstLabel < this._minTs)
574
+ tsFirstLabel += stepTs;
575
+
457
576
  // Create array of labels width coordinate-X and time-stamp for label.
458
577
  var labels = [];
459
578
  var posX, labelStr;
460
- while (tsLabel < this.maxTs) {
461
- posX = this._convertTs2PosX(tsLabel);
462
- labelStr = this._formatTsForLabel(tsLabel, (this.maxTs - this.minTs));
579
+ while (tsFirstLabel < this._maxTs) {
580
+ posX = this._convertTs2PosX(tsFirstLabel);
581
+ labelStr = this._formatTsForLabel(tsFirstLabel, (this._maxTs - this._minTs));
463
582
  labels.push({ X: posX, str: labelStr });
464
- tsLabel = tsLabel + stepTs;
583
+ tsFirstLabel = tsFirstLabel + stepTs;
465
584
  }
585
+
466
586
  // Begin draw vertical label-lines and help-lines.
467
- this.context.beginPath();
468
- // Color for label-lines and help-lines.
469
- this.context.strokeStyle = '#e6e6e6';
587
+ this._context.beginPath();
588
+ this._context.strokeStyle = '#e6e6e6';
470
589
  // Distance between label-line and help-line.
471
- var halfStep = Math.round(stepTs * this.coefTs / 2);
590
+ var halfStep = Math.round(stepTs * this._coefX / 2);
472
591
  // For all lines position Y is the same
473
- var posY = this.canvas.height - this.padding.bottom;
592
+ var posY = this._canvas.height - this._padding.bottom;
474
593
  arLen = labels.length;
475
594
  for (var i = 0; i < arLen; i++) {
476
- this.context.moveTo(labels[i].X, 0);
477
- this.context.lineTo(labels[i].X, posY);
595
+ this._context.moveTo(labels[i].X, 0);
596
+ this._context.lineTo(labels[i].X, posY+ 10);
478
597
  // Help-line between two labels
479
- if (labels[i].X - halfStep > this.padding.left + 2) {
480
- this.context.moveTo(labels[i].X - halfStep, 0);
481
- this.context.lineTo(labels[i].X - halfStep, posY);
598
+ if (labels[i].X - halfStep > this._padding.left + 2) {
599
+ this._context.moveTo(labels[i].X - halfStep, 0);
600
+ this._context.lineTo(labels[i].X - halfStep, posY);
482
601
  }
483
602
  }
603
+
484
604
  // Last help-line after last label if not outside canvas
485
605
  if (labels[i - 1] != null) {
486
- if (labels[i - 1].X + halfStep <= this.canvas.width) {
487
- this.context.moveTo(labels[i - 1].X + halfStep, 0);
488
- this.context.lineTo(labels[i - 1].X + halfStep, posY);
606
+ if (labels[i - 1].X + halfStep <= this._canvas.width) {
607
+ this._context.moveTo(labels[i - 1].X + halfStep, 0);
608
+ this._context.lineTo(labels[i - 1].X + halfStep, posY);
489
609
  }
490
610
  }
491
- this.context.stroke();
611
+ this._context.stroke();
492
612
  // Type labels on axe-x
493
- this.context.font = "12px arial";
613
+ this._context.font = "12px arial";
494
614
  arLen = labels.length;
495
615
  for (i = 0; i < arLen; i++) {
496
616
  // Print first part of label Hour:Min
497
- this.context.fillText(labels[i].str.hm, labels[i].X - 17, (posY + 17));
617
+ this._context.fillText(labels[i].str.hm, labels[i].X - 17, (posY + 17));
498
618
  // The second part of label (Day.Mon) print only by first label at label by begin of day.
499
619
  if (i == 0) {
500
- this.context.fillText(labels[i].str.dm, labels[i].X - 17, (posY + 32));
620
+ this._context.fillText(labels[i].str.dm, labels[i].X - 17, (posY + 32));
501
621
  }
502
622
  else {
503
623
  if (labels[i].str.dm != labels[i - 1].str.dm) {
504
- this.context.fillText(labels[i].str.dm, labels[i].X - 17, (posY + 32));
624
+ this._context.fillText(labels[i].str.dm, labels[i].X - 17, (posY + 32));
505
625
  }
506
626
  }
507
627
  }
508
- this.context.closePath();
628
+ this._context.closePath();
629
+ }
630
+
631
+ /**
632
+ * Draw axis-x and labels for numeric values.
633
+ * @private
634
+ */
635
+ _drawAxeXNum () {
636
+ this._drawAxeXBasic();
637
+ // Variable use by loop over differentyl arrays.
638
+ let arLen;
639
+ // Find optimal step between labels. First get average value, then find optimal value.
640
+ let stepX = this._axeXLabelWidthDefault / this._coefX;
641
+ stepX = this._getNextPreferedNumber(stepX);
642
+ // No usable step (e.g. out of the 1-2-5 series or zero) -> don't draw
643
+ // axis-x labels. Prevents an endless loop in the label loop below.
644
+ if (stepX == null || stepX <= 0)
645
+ return;
646
+ // Calculate value of of first label
647
+ let minXLabelVal = this._getNextPreferedNumber(this._minTs);
648
+ if (minXLabelVal == null)
649
+ minXLabelVal = this._minTs;
650
+
651
+ // Decimal places needed to display stepX cleanly. Each label value is
652
+ // rounded, so repeated additions don't accumulate floating point noise
653
+ // (e.g. 1.4 + 0.2 -> 1.5999999999999999). The amount follows from the
654
+ // step itself, so small X values like 0.001 keep their precision.
655
+ let decimals = Math.max(0, Math.ceil(-Math.log10(stepX)));
656
+ minXLabelVal = roundTo(minXLabelVal, decimals);
657
+
658
+ // Create array of labels width coordinate-X and value for label.
659
+ // Round value of label to maximal 2 Digits
660
+ let labelsX = [];
661
+ while (minXLabelVal < this._maxTs) {
662
+ labelsX.push({ X: this._convertTs2PosX(minXLabelVal), str: minXLabelVal });
663
+ minXLabelVal = roundTo(minXLabelVal + stepX, decimals);
664
+ }
665
+
666
+ // Begin draw vertical label-lines and help-lines.
667
+ this._context.beginPath();
668
+ this._context.strokeStyle = '#e6e6e6';
669
+ // Distance between label-line and help-line.
670
+ let halfStep = Math.round(stepX * this._coefX / 2);
671
+ // For all lines position Y is the same
672
+ let posY = this._canvas.height - this._padding.bottom;
673
+ arLen = labelsX.length;
674
+ for (let i = 0; i < arLen; i++) {
675
+ this._context.moveTo(labelsX[i].X, 0);
676
+ this._context.lineTo(labelsX[i].X, posY+ 10);
677
+ // Help-line between two labels
678
+ if (labelsX[i].X - halfStep > this._padding.left + 2) {
679
+ this._context.moveTo(labelsX[i].X - halfStep, 0);
680
+ this._context.lineTo(labelsX[i].X - halfStep, posY);
681
+ }
682
+ }
683
+ // Last help-line after last label if not outside canvas
684
+ if (labelsX[labelsX.length - 1] != null) {
685
+ if (labelsX[labelsX.length - 1].X + halfStep <= this._canvas.width) {
686
+ this._context.moveTo(labelsX[labelsX.length - 1].X + halfStep, 0);
687
+ this._context.lineTo(labelsX[labelsX.length - 1].X + halfStep, posY);
688
+ }
689
+ }
690
+ this._context.stroke();
691
+
692
+ // Type labels on axe-x
693
+ this._context.font = "12px arial";
694
+ arLen = labelsX.length;
695
+ for (let i = 0; i < arLen; i++) {
696
+
697
+ this._context.fillText(labelsX[i].str, labelsX[i].X, (posY + 20));
698
+ }
699
+ this._context.closePath();
700
+
701
+ // End_ drawAxeNum()
702
+ }
703
+
704
+ /**
705
+ * Draw asix-x as line.
706
+ * @private
707
+ */
708
+ _drawAxeXBasic() {
709
+ this._context.strokeStyle = this.colorDefault;
710
+ this._context.lineWidth = 1 ;
711
+ this._context.beginPath();
712
+ this._context.moveTo(this._padding.left, this._canvas.height - this._padding.bottom);
713
+ this._context.lineTo(this._canvas.width, this._canvas.height - this._padding.bottom);
714
+ this._context.stroke();
509
715
  }
510
716
 
511
- // Calculate coordinates for labels on axe Y. Distance between labels approximately 40px.
512
- // Draw axe Y, labels and help-lines (the line between two labels). For labels use place
513
- // in chart.padding.left. Draw one help-line at label and second line between labels.
717
+ /**
718
+ * Calculate coordinates for labels on axis Y. Distance between labels approximately 40px.
719
+ * Draw axe Y, labels and help-lines (the line between two labels). For labels use place
720
+ * in chart.padding.left. Draw one help-line at label and second line between labels.
721
+ * @private
722
+ */
514
723
  _drawAxeY () {
515
724
  // No think to do if coefficients are null. May be the chart contains only one
516
725
  // empty line (without measuring-data). In this case don't need draw axes.
517
- if (this.coefTs == null || this.coefVal == null)
726
+ if (this._coefX == null || this._coefY == null)
518
727
  return;
519
728
  // Variable used by efficiently loop over big array.
520
729
  var arLen;
521
730
  // How much labels with default height fit into current axe Y.
522
- var labelsAmount = (this.canvas.height - this.padding.bottom) / this.axeYLabelHeight;
523
- // Find optimal step between labels based. First calculate exact step. In second step
524
- // (in loop) find optimal value of step using basic values in array steps.
525
- this.axeYLabelStep = (this.maxVal - this.minVal) / labelsAmount;
526
- // Find optimal value of step
527
- var c = 1;
528
- var isFound = false;
529
- var minStep, maxStep;
530
- while (c < 100000000000) {
531
- for (var i = 0; i < (this.stepsY.length - 1); i++) {
532
- minStep = this.stepsY[i] * c;
533
- maxStep = this.stepsY[i + 1] * c;
534
- if (minStep <= this.axeYLabelStep && this.axeYLabelStep <= maxStep) {
535
- this.axeYLabelStep = maxStep;
536
- isFound = true;
537
- break;
538
- }
539
- }
540
- if (isFound)
541
- break;
542
- c = c * 10;
543
- }
731
+ var labelsAmount = (this._canvas.height - this._padding.bottom) / this._axeYLabelHeightDefault;
732
+ // Find optimal step between labels. First get average value, then find optimal value.
733
+ this._axeYLabelStep = (this._maxVal - this._minVal) / labelsAmount;
734
+ this._axeYLabelStep = this._getNextPreferedNumber(this._axeYLabelStep);
544
735
  // Find value of first label. It is not chart.minVal! It is next
545
736
  // suitable value. Consider that chart.MinVal may be negative.
546
737
  var labelMinVal = 0;
547
- if (this.minVal < 0) {
548
- while (labelMinVal > this.minVal) {
549
- if (labelMinVal <= this.minVal)
738
+ if (this._minVal < 0) {
739
+ while (labelMinVal > this._minVal) {
740
+ if (labelMinVal <= this._minVal)
550
741
  break;
551
- labelMinVal -= this.axeYLabelStep;
742
+ labelMinVal -= this._axeYLabelStep;
552
743
  }
553
- } else if (this.minVal > 0) {
554
- while (labelMinVal < this.maxVal) {
555
- if (labelMinVal >= this.minVal)
744
+ } else if (this._minVal > 0) {
745
+ while (labelMinVal < this._maxVal) {
746
+ if (labelMinVal >= this._minVal)
556
747
  break;
557
- labelMinVal += this.axeYLabelStep;
748
+ labelMinVal += this._axeYLabelStep;
558
749
  }
559
750
  }
560
751
  // Calculate maximal hight of axe-y. This value used to prevent labels on axe-y
561
- // below axe-x. This may happy some times if this.minVal is negative.
562
- var axeYHight = this.canvas.height - this.padding.bottom;
752
+ // below axe-x. This may happy some times if this._minVal is negative.
753
+ var axeYHight = this._canvas.height - this._padding.bottom;
563
754
 
564
755
  // Create array of labels. Each item in array contains {value:value, Y:position-Y}
565
756
  // It will be used to draw labels and help-lines. The loop limit to 33 labels to
566
757
  // prevent infinite loop.
567
758
  var axeY = [];
568
- i = 0;
759
+ let i = 0;
569
760
  var labelPosY, labelValue;
570
761
 
571
762
  while (i < 33) {
572
763
 
573
- labelValue = labelMinVal + (this.axeYLabelStep * i);
764
+ labelValue = labelMinVal + (this._axeYLabelStep * i);
574
765
 
575
766
  // If step less as 1 or =2.5, format values of label to two decimal digits
576
- if (this.axeYLabelStep < 1 || this.axeYLabelStep == 2.5)
767
+ if (this._axeYLabelStep < 1 || this._axeYLabelStep == 2.5)
577
768
  labelValue = labelValue.toFixed(2);
578
769
 
579
770
  labelPosY = this._convertVal2PosY(labelValue);
@@ -582,7 +773,7 @@ class LineChart {
582
773
  if (labelPosY < 0)
583
774
  break;
584
775
 
585
- // Some time if this.minVal is negative, label at the bottom placed below axe-x.
776
+ // Some time if this._minVal is negative, label at the bottom placed below axe-x.
586
777
  // To prevent it add label to array only if label's position is smaler as available
587
778
  // hight of chart.
588
779
  if(labelPosY < axeYHight) {
@@ -592,56 +783,64 @@ class LineChart {
592
783
 
593
784
  i++;
594
785
  }
786
+ // If no label got a valid position (degenerate range or abnormal
787
+ // metrics), don't draw anything further. Prevents a TypeError on
788
+ // axeY[axeY.length - 1].
789
+ if (axeY.length == 0)
790
+ return;
595
791
  // Begin drawing.
596
- this.context.lineWidth = 1;
597
- this.context.beginPath();
792
+ this._context.lineWidth = 1;
793
+ this._context.beginPath();
598
794
  // Draw axe-Y
599
- this.context.strokeStyle = this.colorDefault;
600
- this.context.moveTo(this.padding.left, 0);
601
- this.context.lineTo(this.padding.left, this.canvas.height - this.padding.bottom);
602
- this.context.stroke();
795
+ this._context.strokeStyle = this.colorDefault;
796
+ this._context.moveTo(this._padding.left, 0);
797
+ this._context.lineTo(this._padding.left, this._canvas.height - this._padding.bottom);
798
+ this._context.stroke();
603
799
  // Create horizontal label-lines and help-lines. Begin from bottom.
604
- this.context.beginPath();
800
+ this._context.beginPath();
605
801
  // Color for label-lines and help-lines. Gray 90%
606
- this.context.strokeStyle = '#e6e6e6';
802
+ this._context.strokeStyle = '#e6e6e6';
607
803
  // Position Y for help-lines. (The line between two help-lines)
608
804
  var helpLinePosY;
609
805
  arLen = axeY.length;
610
806
  for (i = 0; i < arLen; i++) {
611
807
  // Draw help-line between labels
612
- helpLinePosY = axeY[i].Y + Math.round(this.coefVal * this.axeYLabelStep / 2);
613
- if (helpLinePosY < this.canvas.height - this.padding.bottom) {
614
- this.context.moveTo(this.padding.left, helpLinePosY);
615
- this.context.lineTo(this.canvas.width, helpLinePosY);
808
+ helpLinePosY = axeY[i].Y + Math.round(this._coefY * this._axeYLabelStep / 2);
809
+ if (helpLinePosY < this._canvas.height - this._padding.bottom) {
810
+ this._context.moveTo(this._padding.left, helpLinePosY);
811
+ this._context.lineTo(this._canvas.width, helpLinePosY);
616
812
  }
617
813
  // Create help-line where label defined. Skip if help-line on axe X.
618
- if (axeY[i].Y >= this.canvas.height - this.padding.bottom)
814
+ if (axeY[i].Y >= this._canvas.height - this._padding.bottom)
619
815
  continue;
620
- this.context.moveTo(this.padding.left, axeY[i].Y);
621
- this.context.lineTo(this.canvas.width, axeY[i].Y);
816
+ this._context.moveTo(this._padding.left, axeY[i].Y);
817
+ this._context.lineTo(this._canvas.width, axeY[i].Y);
622
818
  }
623
819
  // If possible create help-line after last top label
624
- helpLinePosY = axeY[axeY.length - 1].Y - Math.round(this.coefVal * this.axeYLabelStep / 2);
820
+ helpLinePosY = axeY[axeY.length - 1].Y - Math.round(this._coefY * this._axeYLabelStep / 2);
625
821
  if (helpLinePosY > 0) {
626
- this.context.moveTo(this.padding.left, helpLinePosY);
627
- this.context.lineTo(this.canvas.width, helpLinePosY);
822
+ this._context.moveTo(this._padding.left, helpLinePosY);
823
+ this._context.lineTo(this._canvas.width, helpLinePosY);
628
824
  }
629
825
  // Draw all created lines
630
- this.context.stroke();
826
+ this._context.stroke();
631
827
  // Draw labels on axe Y
632
- this.context.font = "12px arial";
633
- this.context.strokeStyle = this.colorDefault;
828
+ this._context.font = "12px arial";
829
+ this._context.strokeStyle = this.colorDefault;
634
830
  // Print labels on left site of axe Y and under the line.
635
831
  // The position defined left bottom corner of text-box.
636
832
  arLen = axeY.length;
637
833
  for (i = 0; i < arLen; i++) {
638
- this.context.fillText(axeY[i].value, 0, axeY[i].Y + 10);
834
+ this._context.fillText(axeY[i].value, 0, axeY[i].Y + 10);
639
835
  }
640
836
  }
641
837
 
642
- // Draw one line on existing graphic. Used afte add new line.
643
- // @param lineIndex Number. Index of line in array this.lines[]
644
- drawLine (lineIndex) {
838
+ /**
839
+ * Draw one line on existing graphic. Used afte add new line.
840
+ * @param lineIndex Number. Index of line in array this.lines[]
841
+ * @private
842
+ */
843
+ _drawLine (lineIndex) {
645
844
  // Create local reference to processed line.
646
845
  var line = this.lines[lineIndex];
647
846
  if (line == null) {
@@ -743,38 +942,91 @@ class LineChart {
743
942
  pos.push(item);
744
943
  }
745
944
  // Begin draw line
746
- this.context.strokeStyle = this.colors[lineIndex];
747
- this.context.lineWidth = 1;
748
- this.context.beginPath();
945
+ this._context.strokeStyle = this.colors[lineIndex];
946
+ this._context.lineWidth = 1;
947
+ this._context.beginPath();
749
948
  // Set first position to first valid measuring value
750
949
  arLen = pos.length;
751
950
  for (i = 0; i < arLen; i++) {
752
951
  if (!isNaN(pos[i].Y)) {
753
- this.context.moveTo(pos[i].X, pos[i].Y);
952
+ this._context.moveTo(pos[i].X, pos[i].Y);
754
953
  i++;
755
954
  break;
756
955
  }
757
956
  }
758
957
  while (i < arLen) {
958
+
959
+ // If value is valid number containe to draw line.
759
960
  if (!isNaN(pos[i].Y)) {
760
- this.context.lineTo(pos[i].X, pos[i].Y);
961
+ this._context.lineTo(pos[i].X, pos[i].Y);
761
962
  i++;
762
963
  } else {
763
- this.context.stroke();
764
- i++;
765
- while (i < pos.length) {
766
- if (!isNaN(pos[i].Y)) {
964
+ // Case valued are not a numbers. Different processing depend on flag ifDataMissing
965
+ if (this.ifDataMissing != "noline") {
966
+ // Case connect "begin" and "end" of missing range.
967
+ while (i < pos.length) {
968
+ if (!isNaN(pos[i].Y)) {
969
+ break;
970
+ }
971
+ i++;
972
+ }
973
+ } else {
974
+ // Case don't draw line where data missing
975
+ this._context.stroke();
976
+ this._context.beginPath();
977
+
978
+ while (i < pos.length) {
979
+ if (!isNaN(pos[i].Y)) {
980
+ break;
981
+ }
767
982
  i++;
768
- break;
769
983
  }
770
- i++;
771
984
  }
772
985
  }
773
986
  }
774
- this.context.stroke();
987
+ this._context.stroke();
988
+ }
989
+
990
+ /**
991
+ * Get next prefered number from 1-2-5 serie. Min 1E-09 max 1E18. Used to calculate optimal
992
+ * step on axis Y and X if type "number". See https://en.wikipedia.org/wiki/Preferred_number
993
+ * Or used to get value of fist label on axis-x.
994
+ * @param num {number} If 0 retrun 0.
995
+ * @returns number or null if step outside allowed values.
996
+ * @private
997
+ */
998
+ _getNextPreferedNumber(num) {
999
+
1000
+ if(num == 0)
1001
+ return 0;
1002
+
1003
+ // Negative numbers: apply the 1-2-5 series mirrored. The first label
1004
+ // should be >= minTs like for positive values, therefore use the lower
1005
+ // border of the interval for negative input.
1006
+ let sign = num < 0 ? -1 : 1;
1007
+ num = Math.abs(num);
1008
+
1009
+ // E1 preferred number series (1-2-5 series)
1010
+ let steps = [1E-9,2E-9,5E-9,1E-8];
1011
+ let factor = 1;
1012
+ let minStep, maxStep;
1013
+ while (factor < 1E18+1) {
1014
+ for (var i = 0; i < (steps.length - 1); i++) {
1015
+ minStep = steps[i] * factor;
1016
+ maxStep = steps[i + 1] * factor;
1017
+ if (minStep <= num && num <= maxStep) {
1018
+ //logger.info(`Counter c=${c}, avg step=${step}, new step=${maxStep}`);
1019
+ return sign > 0 ? maxStep : -minStep;
1020
+ }
1021
+ }
1022
+ factor = factor * 10;
1023
+ }
1024
+ return null;
775
1025
  }
776
1026
 
777
- // Return true if all lines are empty
1027
+ /**
1028
+ * Return true if all lines are empty
1029
+ */
778
1030
  isEmpty () {
779
1031
  var isEmpty = true;
780
1032
  for (var i = 0; i < this.lines.length; i++) {
@@ -785,25 +1037,34 @@ class LineChart {
785
1037
  return isEmpty;
786
1038
  }
787
1039
 
788
- // Calculate from time-stamp position X using coefficient for axe X and available width.
1040
+ /**
1041
+ * Calculate from time-stamp position X using coefficient for axe X and available width.
1042
+ * @private
1043
+ */
789
1044
  _convertTs2PosX (ts) {
790
- return (this.canvas.width - Math.round((this.maxTs - ts) * this.coefTs));
1045
+ return (this._canvas.width - Math.round((this._maxTs - ts) * this._coefX));
791
1046
  }
792
1047
 
793
- // Calculate from measuring value position Y using coefficient for axe Y and available height.
794
- // Return rounded integer.
1048
+ /**
1049
+ * Calculate from measuring value position Y using coefficient for axe Y and available height.
1050
+ * Return rounded integer.
1051
+ * @private
1052
+ */
795
1053
  _convertVal2PosY (val) {
796
- return (Math.round((this.maxVal - val) * this.coefVal));
1054
+ return (Math.round((this._maxVal - val) * this._coefY));
797
1055
  }
798
1056
 
799
- // Convert unix time-stamp to object that contains two elements. This object used as label on
800
- // Axe-X. Result is dependet on difference. By small difference in first line show hour:min,
801
- // second line day.mon. By difference between 3-180 days in first line show day.mon in second
802
- // line yaer. By difference > 180 days in first line show month in second line yaer. Day and
803
- // month in format DD.MM always two digits. Hours and minutes in format HH:MM always two digits.
804
- // @param ts Number. Unix-time-stamp.
805
- // @param tsdif Number. Difference between first and last timestamp
806
- // @return Object. The object used to create labels on axe-x.
1057
+ /**
1058
+ * Convert unix time-stamp to object that contains two elements. This object used as label on
1059
+ * Axe-X. Result is dependet on difference. By small difference in first line show hour:min,
1060
+ * second line day.mon. By difference between 3-180 days in first line show day.mon in second
1061
+ * line yaer. By difference > 180 days in first line show month in second line yaer. Day and
1062
+ * month in format DD.MM always two digits. Hours and minutes in format HH:MM always two digits.
1063
+ * @param ts Number. Unix-time-stamp.
1064
+ * @param tsdif Number. Difference between first and last timestamp
1065
+ * @return Object. The object used to create labels on axe-x.
1066
+ * @private
1067
+ */
807
1068
  _formatTsForLabel (ts, tsdif) {
808
1069
  let date = new Date(ts * 1000);
809
1070
 
@@ -842,15 +1103,27 @@ class LineChart {
842
1103
  return result;
843
1104
  }
844
1105
 
845
- // Calculate begin of day in seconds from unix time-stamp in seconds.
846
- // @param ts {number} unix time-stamp in seconds
847
- // @return {Number}
1106
+ /**
1107
+ * Calculate begin of day in seconds from unix time-stamp in seconds.
1108
+ * @param ts {number} unix time-stamp in seconds
1109
+ * @return {Number}
1110
+ * @private
1111
+ */
848
1112
  _getBeginOfDayFromUnixTs (ts) {
849
1113
  var result = new Date(ts * 1000);
850
1114
  result = new Date(result.getFullYear(), result.getMonth(), result.getDate());
851
- result.setMinutes(59);
852
- result.setSeconds(59);
853
- result.setMilliseconds(1000);
1115
+ return result.getTime() / 1000;
1116
+ }
1117
+
1118
+ /**
1119
+ * Calculate begin of year in seconds from unix time-stamp in seconds.
1120
+ * @param ts {number} unix time-stamp in seconds
1121
+ * @return {Number}
1122
+ * @private
1123
+ */
1124
+ _getBeginOfYearFromUnixTs (ts) {
1125
+ var result = new Date(ts * 1000);
1126
+ result = new Date(result.getFullYear(), 0, 1);
854
1127
  return result.getTime() / 1000;
855
1128
  }
856
1129
 
@@ -870,42 +1143,74 @@ class LineChart {
870
1143
 
871
1144
  // Default color used in some elements
872
1145
  colorDefault = '#657585';
873
-
874
- // Array of possible steps on axe-Y.
875
- stepsX = [2, 5, 10, 15, 20, 30, 60, 90, 2*60, 4*60, 5*60, 6*60, 12*60, 24*60, 2*24*60, 3*24*60, 4*24*60,
876
- 5*24*60, 7*24*60, 10*24*60, 15*24*60, 20*24*60, 30*24*60, 45*24*60, 60*24*60, 90*24*60, 120*24*60];
877
-
878
- // Array of minimal steps for axe-X
879
- stepsY = [0.01, 0.02, 0.05, 0.1];
880
1146
 
1147
+ // Array of possible steps on axis-X in seconds. Up to 10 years.
1148
+ stepsX = [
1149
+ 1, 2, 5, 10, 20, 30, // 1, 2, 5, 10, 20, 30 seconds
1150
+ 60, 120, 300, 600, 900, 1200, 1800, // 1, 2, 5, 10, 15, 20, 30 minutes
1151
+ 3600, 7200, 14400, 21600, 43200, // 1, 2, 4, 6, 12 hours
1152
+ 86400, 172800, 259200, 345600, 432000, // 1, 2, 3, 4, 5 days
1153
+ 604800, 864000, 1296000, 1728000, // 7, 10, 15, 20 days
1154
+ 2592000, 5184000, 7776000, 10368000, // 1, 2, 3, 4 months (30-120 days)
1155
+ 15552000, 31536000, 63072000, 157680000, 315360000 // 6 months, 1-10 years
1156
+ ];
1157
+
881
1158
  // End class LineChart
882
1159
  }
883
1160
 
884
- // The object represent line that used in charts.
885
- // @constructor:
886
- // @param lineData Object. The object represent data of one line in chart.
887
- // obj_name - String. The string used as label for th line. object_name + parameter_name.
888
- // par_id - String. Optional. May be used to request data from database.
889
- // par_name - Srtring. The string used as label for th line. object_name + parameter_name.
890
- // values - String. Semicolon separated pairs "Unix-Timestamp/Value;Unix-Timestamp/Value;.."
891
- // The values may be empty! The last element should be withoud value!!! It Indicate
892
- // end of timespane of this line. Example :
893
- // "161111145820/3.36;161111145880/3.42;161111145940/3.50;161111146000/3.58;161111146060/3.48,;161111146120/3.08;161111146120/"
1161
+ /**
1162
+ * The object represent a line in chart.
1163
+ * @class
1164
+ * @private
1165
+ * @param lineData {LineData}
1166
+ * @param color {string} color in HTML format, name or hex.
1167
+ */
894
1168
  class SingleLine {
895
- constructor(lineData) {
896
- this.parId = lineData.par_id; // This Id may be used to request data from database.
897
- this.parName = lineData.par_name; // Name of parameter representing this line. E.g "CPU Total"
898
- this.objName = lineData.obj_name; // Name of object where belong this parameter. E.g. "Proxy server"
1169
+ constructor(lineData, color) {
1170
+ this.parId = lineData.par_id;
1171
+ this.parName = lineData.par_name != null ? lineData.par_name : "";
1172
+ this.objName = lineData.obj_name != null ? lineData.obj_name : "";
899
1173
  this.real = []; // Empty array for pairs ts/val. "ts" is unix time-stamp, "val" is measuring value.
900
- // Fill with data later, because need update min/max parsmeter of chart.
1174
+
901
1175
  this.isEmpty = true; // Flag indicate that line contains no data.
902
1176
  this.hidden = false; // Property uses to hide line in chart by click on legend item.
903
- this.color = "black" // Default color for line
1177
+
1178
+ if(color == null) {
1179
+ this.color = "black"; // Default color for line
1180
+ } else {
1181
+ this.color = color;
1182
+ }
1183
+
1184
+ this.legend = null; // HTML-Element to show one elemen in chart's legend. Init later.
904
1185
  }
905
1186
  }
906
1187
 
907
- var allCharts = [];
908
-
909
- // Version
910
- LineChart.prototype.Version = "1.2.0";
911
-
1188
+ /**
1189
+ * The object represent data to create one line in chart.
1190
+ * @class
1191
+ * @param obj_name {string} name of the object, shown in the legend.
1192
+ * @param par_name {string} name of the parameter, shown in the legend.
1193
+ * @param par_id {number} internal id of the line. Optional. May be used to request data from a backend.
1194
+ * @param values {string} measurement data, elements separated by ";". Each element contains the
1195
+ * value on axis-X and the measuring value separated by "/", e.g.
1196
+ * "161111145730/3.48;161111145843/3.50;161111150013/".
1197
+ * - Axis-X value: Unix time-stamp in seconds for axisXType "time", any decimal number for
1198
+ * axisXType "number" (e.g. "0.001/5").
1199
+ * - Measuring value: any number (positive or negative). An empty measuring value marks a
1200
+ * missing value (gap); there the line is interrupted or connected according to ifDataMissing.
1201
+ * @example
1202
+ * line = {
1203
+ * obj_name:"Proxy Server",
1204
+ * par_name:"CpuTotal",
1205
+ * par_id:"2452",
1206
+ * values: "161111145730/3.48;161111145843/3.50;161111150013/"
1207
+ * }
1208
+ */
1209
+ class LineData {
1210
+ constructor(obj_name, par_name, par_id, values) {
1211
+ this.obj_name = obj_name;
1212
+ this.par_name = par_name;
1213
+ this.par_id = par_id;
1214
+ this.values = values;
1215
+ }
1216
+ }