adaptive-linechart 1.3.0 → 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,7 +1,7 @@
1
1
  // Comments https://jsdoc.app/
2
2
 
3
3
  /**
4
- * @version 1.3.0
4
+ * @version 1.4.0
5
5
  * @author Andrej Koslov
6
6
  */
7
7
 
@@ -12,16 +12,20 @@
12
12
  * false, show live data by mouse over. The line create from LineData (see above) Labels on axis X
13
13
  * and Y will be created automaticaly. The chart can show maximal 10 lines in different colors.
14
14
  * @class
15
- * @param reference to parent element for chart. If null use HTML BODY as parent element.
15
+ * @param container {HTMLElement} parent element for the chart. If null use HTML BODY as parent element.
16
16
  * @param chartId {number} identifier for chart. Optional. If not defined use random number.
17
17
  * @param width {number} width in pixel. Optional. Default use available width in parent element.
18
18
  * @param title {string} title of chart. Optional. If null don't create title.
19
19
  * @param className {string} class for div of chart. Optional. Default "linechart"
20
20
  * @param axisXType {string} for time based values on axis X set "time" (Default). For number based
21
- * values "numer".
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.
22
26
  */
23
27
  class LineChart {
24
- constructor(container, chartId, width, title, className, axisXType) {
28
+ constructor(container, chartId, width, title, className, axisXType, ifDataMissing) {
25
29
  if(container == null)
26
30
  container = document.getElementsByTagName("BODY")[0];
27
31
  if(chartId == null)
@@ -88,10 +92,22 @@ class LineChart {
88
92
  this.axisXType = "time";
89
93
  }
90
94
  } else {
91
- this.axisXType == "time";
95
+ this.axisXType = "time";
92
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
+
93
108
  // Used to show live data by mousemove over the canvas.
94
109
  this._canvas.dataset.axisXType = this.axisXType;
110
+ this._canvas.dataset.ifDataMissing = this.ifDataMissing;
95
111
  this._canvas.dataset.chartId = chartId.toString();
96
112
  // Save reference to context.
97
113
  this._context = this._canvas.getContext('2d');
@@ -140,7 +156,8 @@ class LineChart {
140
156
  // Format of data depend on type of axis-x
141
157
  if(this.dataset.axisXType == "time") {
142
158
  // Calculate position on axis-x to data-time. If result invalid return.
143
- var curTs = parseInt(this.dataset.minTs) + Math.round((event.offsetX - parseInt(this.dataset.paddingLeft)) / parseFloat(this.dataset.coefTs));
159
+ var curTs = parseInt(this.dataset.minTs) +
160
+ Math.round((event.offsetX - parseInt(this.dataset.paddingLeft)) / parseFloat(this.dataset.coefTs));
144
161
  if (isNaN(curTs)) {
145
162
  element.innerText = '-';
146
163
  return;
@@ -151,7 +168,8 @@ class LineChart {
151
168
  element.innerHTML = 'Date <b>'+ curTs.mday+ '.'+ curTs.month+ '.'+ curTs.year+ '</b> Time <b>'+ curTs.hour+ ':'+ curTs.min+
152
169
  '</b> Value <b>'+ curValY+ '</b>';
153
170
  } else {
154
- var curValX = parseInt(this.dataset.minTs) + Math.round((event.offsetX - parseInt(this.dataset.paddingLeft)) / parseFloat(this.dataset.coefTs));
171
+ var curValX = parseFloat(this.dataset.minTs) +
172
+ Math.round((event.offsetX - parseInt(this.dataset.paddingLeft)) / parseFloat(this.dataset.coefTs));
155
173
  element.innerHTML = 'Axis-X <b>'+ curValX+ '</b> Axis-Y <b>' + curValY + '</b>';
156
174
  }
157
175
  });
@@ -177,38 +195,42 @@ class LineChart {
177
195
  // Integer. End of time that show chart. Sec. Unix Time-stamp. Later calculate
178
196
  // from data.
179
197
  this._maxTs = 0;
180
- // Minimal measuring value. Later calculate from data.
181
- this._minVal = Number.MAX_VALUE;
182
- // Maximal measuring value. Later calculate from data.
183
- this._maxVal = Number.MIN_VALUE;
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;
184
205
  // Distance between two labels on axis Y. Real value, not a pix! Later calculate
185
206
  // from data.
186
207
  this._axeYLabelStep = null;
187
208
  // Default and minimal distance (pixel) between labels on axe-y. Later calculate
188
209
  // from data.
189
- this._axeYLabelHeight= 30;
210
+ this._axeYLabelHeightDefault= 30;
190
211
  // Default distance (pixel) between labels on axe-x. Later calculate
191
212
  // from data suitable value.
192
- this._axeXLabelWidth = 80;
213
+ this._axeXLabelWidthDefault = 80;
193
214
  // Coefficient to convert time-stamp to coordinate X. Later calculate from data.
194
- this._coefTs = null;
215
+ this._coefX = null;
195
216
  // Coefficient to convert values to coordinate Y. Later calculate from data.
196
- this._coefVal = null;
217
+ this._coefY = null;
197
218
  // Padding in canvas where to place labels. Later adjust to real width of labels.
198
219
  this._padding = { left: 50, bottom: 35 };
199
- // Instead automatic, the averadge step on axis X may be set manual. Several measured
200
- // values are combined to flatten peaks in the graph. Value in seconds. Optional.
201
- // If NaN, not used.
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
+ */
202
225
  this.avgStep = NaN;
203
226
 
204
-
205
227
  // End consctructor object LineChart.
206
228
  }
207
229
 
208
230
  /**
209
231
  * Add new line and create new item in legend.
210
- * @parameter lineData Object. The object represent data for one line in chart.
211
- * @return Boolean. True if no problem detected. Else false.
232
+ * @param lineData {LineData} object that represents the data for one line.
233
+ * @return {boolean} true if no problem detected, otherwise false.
212
234
  */
213
235
  addLine (lineData) {
214
236
  if (lineData.values == null) {
@@ -227,19 +249,40 @@ class LineChart {
227
249
  logger.error('Function LineChart.newLine(). Function _createLine() return null.');
228
250
  return false;
229
251
  }
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) {
230
266
  // Create legend-item as dom-element.
231
267
  line.legend = addNewElement(this._legendDiv, 'div', {
232
268
  class: 'chart-legend-item nowrap',
233
269
  id: `chart_${this.chartId}_legend_${lineData.par_id}`,
234
- style: `cursor: pointer; max-width:${this.chartDiv.clientWidth - 20}px;`,
235
- 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;`
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: '--'
236
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));
237
280
  // Set function called by click on element to hide/show line on chart.
238
281
  line.legend.addEventListener('click', function (event) {
239
282
 
240
283
  // First sub-element of class chart-legend-color is colored tag for this legend item.
241
284
  // This element used to swith color by click on legent item.
242
- var legendColor = event.target.getElementsByClassName('chart-legend-color')[0];
285
+ var legendColor = event.currentTarget.querySelector('.chart-legend-color');
243
286
 
244
287
  // By click on colored tag this varibale is null. In this case only exit.
245
288
  if(legendColor == null) return;
@@ -252,21 +295,18 @@ class LineChart {
252
295
  legendColor.style.backgroundColor = line.color;
253
296
  }
254
297
 
255
- event.target.chart.draw();
298
+ event.currentTarget.chart.draw();
256
299
  });
257
300
 
258
301
  // Link to parent chart in the legend item. Need to process click on legend item.
259
302
  line.legend.chart = this;
260
-
261
- // Put new line array of lines.
262
- this.lines.push(line);
263
- return true;
264
303
  }
265
304
 
266
305
  /**
267
- * Update data in chart and redraw this one. All items in legend stay the same!
268
- * @parameter lines Array of objects of type SingleLine.
269
- * @return true if no problem detected, else false.
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.
270
310
  */
271
311
  updateLines (lines) {
272
312
  if (lines == null) {
@@ -277,19 +317,28 @@ class LineChart {
277
317
  logger.error('Function LineChart.updateLines(). Parameter lines is not a array.');
278
318
  return false;
279
319
  }
280
- // 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.
281
327
  this.lines = [];
282
- this._minTs = 99999999999999;
328
+ this._minTs = Number.MAX_SAFE_INTEGER;
283
329
  this._maxTs = 0;
284
- this._minVal = 999999999999999;
285
- this._maxVal = 0;
330
+ this._minValRaw = Infinity;
331
+ this._maxValRaw = -Infinity;
332
+ this._minVal = Infinity;
333
+ this._maxVal = -Infinity;
286
334
  this._axeYLabelStep = null;
287
- this._coefTs = null;
288
- this._coefVal = null;
289
- // Process lines. Each new line add to array of lines.
290
- for (var i in lines) {
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++) {
291
339
  var line = this._createLine(lines[i]);
292
340
  if (line != null) {
341
+ this._createLegendItem(line, lines[i]);
293
342
  this.lines.push(line);
294
343
  }
295
344
  }
@@ -301,14 +350,11 @@ class LineChart {
301
350
  * Create line for chart and update some properties of chart minTs, maxTs, minVal, maxVal.
302
351
  * @parameter lineData Object.
303
352
  * @return SingleLine Object.
353
+ * @private
304
354
  */
305
355
  _createLine (lineData) {
306
356
  // Create line. Add data later.
307
357
  var line = new SingleLine(lineData, this.colors[this.lines.length]);
308
-
309
- // Flag. True if value of all items are NaN. In this case set min/max 0/1
310
- var isAllNaN = true;
311
-
312
358
  // If par_id is missing, set number of line in the chart as par_id
313
359
  if(lineData.par_id == null)
314
360
  lineData.par_id = this.lines.length;
@@ -337,34 +383,26 @@ class LineChart {
337
383
  }
338
384
 
339
385
  var elem = { ts: null, val: null };
340
- 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]);
341
392
  elem.val = parseFloat(item[1]);
342
393
 
343
394
  line.real.push(elem);
344
395
 
345
- // If value is valid number, update min/max and set false isAllNaN.
396
+ // If value is valid number, update raw min/max.
346
397
  if (!isNaN(elem.val)) {
347
-
348
- // Update mininal value. Positive and negative values process differently.
349
- if(elem.val < 0) {
350
398
 
351
- if(Math.floor(elem.val * 1.1) < this._minVal) {
352
- this._minVal = Math.floor(elem.val * 1.1);
353
- }
354
-
355
- } else {
356
-
357
- if(Math.floor(elem.val * 0.9) < this._minVal) {
358
- this._minVal = Math.floor(elem.val * 0.9);
359
- }
360
- }
361
-
362
- // Update maximal value.
363
- if (Math.ceil(elem.val * 1.1) > this._maxVal) {
364
- this._maxVal = Math.ceil(elem.val * 1.1);
365
- }
366
-
367
- 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;
368
406
  }
369
407
 
370
408
  // Update min/max time-stamp
@@ -380,20 +418,22 @@ class LineChart {
380
418
 
381
419
  line.isEmpty = false;
382
420
 
383
- // Adjust min/max values if both 0 or all values NaN
384
- if ((this._maxVal == 0 && this._minVal == 0) || isAllNaN) {
385
- this._minVal = 0;
386
- this._maxVal = 1;
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;
387
425
  }
388
426
 
389
427
  // Calculate padding. This area used for labels. Both are type of object TextMetrics.
390
- var minValText = this._context.measureText(this._minVal.toString());
391
- 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);
392
432
  // Set place for label using biggest value.
393
- if (minValText.width < maxValText.width) {
394
- this._padding.left = Math.round(maxValText.width) + 23;
433
+ if (minValTextWidth < maxValTextWidth) {
434
+ this._padding.left = Math.round(maxValTextWidth) + 23;
395
435
  } else {
396
- this._padding.left = Math.round(minValText.width) + 23;
436
+ this._padding.left = Math.round(minValTextWidth) + 23;
397
437
  }
398
438
 
399
439
  return line;
@@ -410,18 +450,31 @@ class LineChart {
410
450
  * Draw graphic with all elements.
411
451
  */
412
452
  draw () {
413
- // Update coefficient for values and time-stamps only if line is not empty.
414
- this._coefTs = (this._canvas.width - this._padding.left) / (this._maxTs - this._minTs);
415
- this._coefVal = (this._canvas.height - this._padding.bottom) / (this._maxVal - this._minVal);
416
453
  // Clear canvas
417
454
  this._context.clearRect(0, 0, this._canvas.width, this._canvas.height);
418
455
  // Return true if all lines in the chart are empty.
419
456
  if (this.isEmpty())
420
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();
421
473
  // Draw axe-x and labels with values
422
474
  if(this.axisXType == "time") {
423
475
  this._drawAxeXTime();
424
- } else {
476
+ }
477
+ else {
425
478
  this._drawAxeXNum();
426
479
  }
427
480
  // Draw axe-y and time-labels
@@ -432,16 +485,49 @@ class LineChart {
432
485
  }
433
486
  // Refresh data need to show live-data
434
487
  this._canvas.dataset.minTs = this._minTs.toString();
435
- this._canvas.dataset.coefTs = this._coefTs.toString();
488
+ this._canvas.dataset.coefTs = this._coefX.toString();
436
489
  this._canvas.dataset.maxVal = this._maxVal.toString();
437
- this._canvas.dataset.coefVal = this._coefVal.toString();
490
+ this._canvas.dataset.coefVal = this._coefY.toString();
438
491
  this._canvas.dataset.paddingLeft = this._padding.left.toString();
439
492
  this._canvas.dataset.paddingBottom = this._padding.bottom.toString();
440
493
  }
441
494
 
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
+
442
526
  /**
443
527
  * Change size of chart and redraw. May be used if size of parent panel changed but data
444
528
  * in lines stay the same.
529
+ * @param difWidth {number} difference in width (pixel).
530
+ * @param difHeight {number} difference in height (pixel).
445
531
  */
446
532
  resize(difWidth, difHeight) {
447
533
  this._canvas.width = this._canvas.width + difWidth;
@@ -452,14 +538,16 @@ class LineChart {
452
538
 
453
539
  /**
454
540
  * Draw axes-x and labels for time based values.
541
+ * @private
455
542
  */
456
543
  _drawAxeXTime () {
457
544
  this._drawAxeXBasic();
458
- // Variable use by loop over differentyl arrays.
545
+ // Variable used by loop over differently arrays.
459
546
  var arLen;
547
+
460
548
  // Calculate suitable step between labels on axis-x. First get average distance between
461
549
  // labels in seconds.
462
- var stepTs = Math.round(this._axeXLabelWidth / this._coefTs );
550
+ var stepTs = Math.round(this._axeXLabelWidthDefault / this._coefX );
463
551
  // If step is very small set to minimal step 1 second.
464
552
  if(stepTs <= 1) {
465
553
  stepTs = 1;
@@ -473,34 +561,33 @@ class LineChart {
473
561
  }
474
562
  }
475
563
  }
476
- // Calculate time-stamp of first label
477
- // Get time of day of minimal time-stamp
478
- var tsLabel = this._getBeginOfDayFromUnixTs(this._minTs);
479
- var isFound = false;
480
- // Limit time-stamp of minimal label to current time.
481
- // Time-stamp of first label can't be bigger as as current time.
482
- var tsNow = new Date().getTime() / 1000;
483
- while (tsLabel < tsNow) {
484
- if (tsLabel > this._minTs) {
485
- isFound = true;
486
- break;
487
- }
488
- tsLabel += stepTs;
489
- }
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
+
490
576
  // Create array of labels width coordinate-X and time-stamp for label.
491
577
  var labels = [];
492
578
  var posX, labelStr;
493
- while (tsLabel < this._maxTs) {
494
- posX = this._convertTs2PosX(tsLabel);
495
- 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));
496
582
  labels.push({ X: posX, str: labelStr });
497
- tsLabel = tsLabel + stepTs;
583
+ tsFirstLabel = tsFirstLabel + stepTs;
498
584
  }
585
+
499
586
  // Begin draw vertical label-lines and help-lines.
500
587
  this._context.beginPath();
501
588
  this._context.strokeStyle = '#e6e6e6';
502
589
  // Distance between label-line and help-line.
503
- var halfStep = Math.round(stepTs * this._coefTs / 2);
590
+ var halfStep = Math.round(stepTs * this._coefX / 2);
504
591
  // For all lines position Y is the same
505
592
  var posY = this._canvas.height - this._padding.bottom;
506
593
  arLen = labels.length;
@@ -513,6 +600,7 @@ class LineChart {
513
600
  this._context.lineTo(labels[i].X - halfStep, posY);
514
601
  }
515
602
  }
603
+
516
604
  // Last help-line after last label if not outside canvas
517
605
  if (labels[i - 1] != null) {
518
606
  if (labels[i - 1].X + halfStep <= this._canvas.width) {
@@ -539,36 +627,51 @@ class LineChart {
539
627
  }
540
628
  this._context.closePath();
541
629
  }
542
-
630
+
543
631
  /**
544
632
  * Draw axis-x and labels for numeric values.
633
+ * @private
545
634
  */
546
635
  _drawAxeXNum () {
547
636
  this._drawAxeXBasic();
548
637
  // Variable use by loop over differentyl arrays.
549
638
  let arLen;
550
- // Find optimal step between labels. First get average value, then find optimal value.
551
- let stepX = Math.round(this._axeXLabelWidth / this._coefTs );
639
+ // Find optimal step between labels. First get average value, then find optimal value.
640
+ let stepX = this._axeXLabelWidthDefault / this._coefX;
552
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;
553
646
  // Calculate value of of first label
554
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);
555
657
 
556
658
  // Create array of labels width coordinate-X and value for label.
659
+ // Round value of label to maximal 2 Digits
557
660
  let labelsX = [];
558
661
  while (minXLabelVal < this._maxTs) {
559
662
  labelsX.push({ X: this._convertTs2PosX(minXLabelVal), str: minXLabelVal });
560
- minXLabelVal = minXLabelVal + stepX;
663
+ minXLabelVal = roundTo(minXLabelVal + stepX, decimals);
561
664
  }
562
665
 
563
666
  // Begin draw vertical label-lines and help-lines.
564
667
  this._context.beginPath();
565
668
  this._context.strokeStyle = '#e6e6e6';
566
669
  // Distance between label-line and help-line.
567
- let halfStep = Math.round(stepX * this._coefTs / 2);
670
+ let halfStep = Math.round(stepX * this._coefX / 2);
568
671
  // For all lines position Y is the same
569
672
  let posY = this._canvas.height - this._padding.bottom;
570
673
  arLen = labelsX.length;
571
- for (i = 0; i < arLen; i++) {
674
+ for (let i = 0; i < arLen; i++) {
572
675
  this._context.moveTo(labelsX[i].X, 0);
573
676
  this._context.lineTo(labelsX[i].X, posY+ 10);
574
677
  // Help-line between two labels
@@ -578,10 +681,10 @@ class LineChart {
578
681
  }
579
682
  }
580
683
  // Last help-line after last label if not outside canvas
581
- if (labelsX[i - 1] != null) {
582
- if (labelsX[i - 1].X + halfStep <= this._canvas.width) {
583
- this._context.moveTo(labelsX[i - 1].X + halfStep, 0);
584
- this._context.lineTo(labelsX[i - 1].X + halfStep, posY);
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);
585
688
  }
586
689
  }
587
690
  this._context.stroke();
@@ -589,7 +692,7 @@ class LineChart {
589
692
  // Type labels on axe-x
590
693
  this._context.font = "12px arial";
591
694
  arLen = labelsX.length;
592
- for (i = 0; i < arLen; i++) {
695
+ for (let i = 0; i < arLen; i++) {
593
696
 
594
697
  this._context.fillText(labelsX[i].str, labelsX[i].X, (posY + 20));
595
698
  }
@@ -600,6 +703,7 @@ class LineChart {
600
703
 
601
704
  /**
602
705
  * Draw asix-x as line.
706
+ * @private
603
707
  */
604
708
  _drawAxeXBasic() {
605
709
  this._context.strokeStyle = this.colorDefault;
@@ -614,16 +718,17 @@ class LineChart {
614
718
  * Calculate coordinates for labels on axis Y. Distance between labels approximately 40px.
615
719
  * Draw axe Y, labels and help-lines (the line between two labels). For labels use place
616
720
  * in chart.padding.left. Draw one help-line at label and second line between labels.
721
+ * @private
617
722
  */
618
723
  _drawAxeY () {
619
724
  // No think to do if coefficients are null. May be the chart contains only one
620
725
  // empty line (without measuring-data). In this case don't need draw axes.
621
- if (this._coefTs == null || this._coefVal == null)
726
+ if (this._coefX == null || this._coefY == null)
622
727
  return;
623
728
  // Variable used by efficiently loop over big array.
624
729
  var arLen;
625
730
  // How much labels with default height fit into current axe Y.
626
- var labelsAmount = (this._canvas.height - this._padding.bottom) / this._axeYLabelHeight;
731
+ var labelsAmount = (this._canvas.height - this._padding.bottom) / this._axeYLabelHeightDefault;
627
732
  // Find optimal step between labels. First get average value, then find optimal value.
628
733
  this._axeYLabelStep = (this._maxVal - this._minVal) / labelsAmount;
629
734
  this._axeYLabelStep = this._getNextPreferedNumber(this._axeYLabelStep);
@@ -651,7 +756,7 @@ class LineChart {
651
756
  // It will be used to draw labels and help-lines. The loop limit to 33 labels to
652
757
  // prevent infinite loop.
653
758
  var axeY = [];
654
- i = 0;
759
+ let i = 0;
655
760
  var labelPosY, labelValue;
656
761
 
657
762
  while (i < 33) {
@@ -678,6 +783,11 @@ class LineChart {
678
783
 
679
784
  i++;
680
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;
681
791
  // Begin drawing.
682
792
  this._context.lineWidth = 1;
683
793
  this._context.beginPath();
@@ -695,7 +805,7 @@ class LineChart {
695
805
  arLen = axeY.length;
696
806
  for (i = 0; i < arLen; i++) {
697
807
  // Draw help-line between labels
698
- helpLinePosY = axeY[i].Y + Math.round(this._coefVal * this._axeYLabelStep / 2);
808
+ helpLinePosY = axeY[i].Y + Math.round(this._coefY * this._axeYLabelStep / 2);
699
809
  if (helpLinePosY < this._canvas.height - this._padding.bottom) {
700
810
  this._context.moveTo(this._padding.left, helpLinePosY);
701
811
  this._context.lineTo(this._canvas.width, helpLinePosY);
@@ -707,7 +817,7 @@ class LineChart {
707
817
  this._context.lineTo(this._canvas.width, axeY[i].Y);
708
818
  }
709
819
  // If possible create help-line after last top label
710
- 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);
711
821
  if (helpLinePosY > 0) {
712
822
  this._context.moveTo(this._padding.left, helpLinePosY);
713
823
  this._context.lineTo(this._canvas.width, helpLinePosY);
@@ -728,6 +838,7 @@ class LineChart {
728
838
  /**
729
839
  * Draw one line on existing graphic. Used afte add new line.
730
840
  * @param lineIndex Number. Index of line in array this.lines[]
841
+ * @private
731
842
  */
732
843
  _drawLine (lineIndex) {
733
844
  // Create local reference to processed line.
@@ -845,13 +956,13 @@ class LineChart {
845
956
  }
846
957
  while (i < arLen) {
847
958
 
848
- // If valu is valid number containe to draw line.
959
+ // If value is valid number containe to draw line.
849
960
  if (!isNaN(pos[i].Y)) {
850
961
  this._context.lineTo(pos[i].X, pos[i].Y);
851
962
  i++;
852
963
  } else {
853
- // Case value is no a number. Different processing depend on flag connectIfMissing
854
- if (this.connectIfMissing == true) {
964
+ // Case valued are not a numbers. Different processing depend on flag ifDataMissing
965
+ if (this.ifDataMissing != "noline") {
855
966
  // Case connect "begin" and "end" of missing range.
856
967
  while (i < pos.length) {
857
968
  if (!isNaN(pos[i].Y)) {
@@ -882,12 +993,19 @@ class LineChart {
882
993
  * Or used to get value of fist label on axis-x.
883
994
  * @param num {number} If 0 retrun 0.
884
995
  * @returns number or null if step outside allowed values.
996
+ * @private
885
997
  */
886
998
  _getNextPreferedNumber(num) {
887
999
 
888
1000
  if(num == 0)
889
1001
  return 0;
890
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
+
891
1009
  // E1 preferred number series (1-2-5 series)
892
1010
  let steps = [1E-9,2E-9,5E-9,1E-8];
893
1011
  let factor = 1;
@@ -898,7 +1016,7 @@ class LineChart {
898
1016
  maxStep = steps[i + 1] * factor;
899
1017
  if (minStep <= num && num <= maxStep) {
900
1018
  //logger.info(`Counter c=${c}, avg step=${step}, new step=${maxStep}`);
901
- return maxStep;
1019
+ return sign > 0 ? maxStep : -minStep;
902
1020
  }
903
1021
  }
904
1022
  factor = factor * 10;
@@ -921,17 +1039,19 @@ class LineChart {
921
1039
 
922
1040
  /**
923
1041
  * Calculate from time-stamp position X using coefficient for axe X and available width.
1042
+ * @private
924
1043
  */
925
1044
  _convertTs2PosX (ts) {
926
- return (this._canvas.width - Math.round((this._maxTs - ts) * this._coefTs));
1045
+ return (this._canvas.width - Math.round((this._maxTs - ts) * this._coefX));
927
1046
  }
928
1047
 
929
1048
  /**
930
1049
  * Calculate from measuring value position Y using coefficient for axe Y and available height.
931
1050
  * Return rounded integer.
1051
+ * @private
932
1052
  */
933
1053
  _convertVal2PosY (val) {
934
- return (Math.round((this._maxVal - val) * this._coefVal));
1054
+ return (Math.round((this._maxVal - val) * this._coefY));
935
1055
  }
936
1056
 
937
1057
  /**
@@ -943,6 +1063,7 @@ class LineChart {
943
1063
  * @param ts Number. Unix-time-stamp.
944
1064
  * @param tsdif Number. Difference between first and last timestamp
945
1065
  * @return Object. The object used to create labels on axe-x.
1066
+ * @private
946
1067
  */
947
1068
  _formatTsForLabel (ts, tsdif) {
948
1069
  let date = new Date(ts * 1000);
@@ -986,13 +1107,23 @@ class LineChart {
986
1107
  * Calculate begin of day in seconds from unix time-stamp in seconds.
987
1108
  * @param ts {number} unix time-stamp in seconds
988
1109
  * @return {Number}
1110
+ * @private
989
1111
  */
990
1112
  _getBeginOfDayFromUnixTs (ts) {
991
1113
  var result = new Date(ts * 1000);
992
1114
  result = new Date(result.getFullYear(), result.getMonth(), result.getDate());
993
- result.setMinutes(59);
994
- result.setSeconds(59);
995
- 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);
996
1127
  return result.getTime() / 1000;
997
1128
  }
998
1129
 
@@ -1013,18 +1144,24 @@ class LineChart {
1013
1144
  // Default color used in some elements
1014
1145
  colorDefault = '#657585';
1015
1146
 
1016
- // Array of possible steps on axis-X in seconds
1017
- stepsX = [1, 2, 5, 10, 20, 30, 1*60, 2*60, 5*60, 10*60, 15*60, 20*60, 30*60,
1018
- 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,
1019
- 4*24*60*60, 5*24*60*60, 7*24*60*60, 10*24*60*60, 15*24*60*60, 20*24*60*60,
1020
- 30*24*60*60, 45*24*60*60, 60*24*60*60, 90*24*60*60, 120*24*60*60];
1021
-
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
+
1022
1158
  // End class LineChart
1023
1159
  }
1024
1160
 
1025
1161
  /**
1026
1162
  * The object represent a line in chart.
1027
1163
  * @class
1164
+ * @private
1028
1165
  * @param lineData {LineData}
1029
1166
  * @param color {string} color in HTML format, name or hex.
1030
1167
  */
@@ -1034,14 +1171,7 @@ class SingleLine {
1034
1171
  this.parName = lineData.par_name != null ? lineData.par_name : "";
1035
1172
  this.objName = lineData.obj_name != null ? lineData.obj_name : "";
1036
1173
  this.real = []; // Empty array for pairs ts/val. "ts" is unix time-stamp, "val" is measuring value.
1037
-
1038
- // Set connectIfMissing. Default false.
1039
- if(lineData.connectIfmissing == null) {
1040
- this.connectIfmissing = false;
1041
- } else {
1042
- this.connectIfmissing = lineData.connectIfmissing; // By false don't draw line if data missing
1043
- }
1044
-
1174
+
1045
1175
  this.isEmpty = true; // Flag indicate that line contains no data.
1046
1176
  this.hidden = false; // Property uses to hide line in chart by click on legend item.
1047
1177
 
@@ -1058,30 +1188,29 @@ class SingleLine {
1058
1188
  /**
1059
1189
  * The object represent data to create one line in chart.
1060
1190
  * @class
1061
- * @param obj_name {string} is visible in legen of line.
1062
- * @param par_name {string}, tring is visible in legen of line.
1063
- * @param par_id {number} internal id of line. Optional. May be used to request data from backend.
1064
- * @param values {string}, elements separates by ";". Each element containing time-stamp and
1065
- * meassuring value separated by "/". eg. "161111145730/3.48;161111145843/3.50;161111150013/"
1066
- * Value may be in range Number.MIN_VALUE till Number.MAX_VALUE or may be missing. The last element
1067
- * must be without value. It indicating where is end of time-period for this line.
1068
- * @param connectIfMissing {boolean} if false don't draw line where data are missing, else connect
1069
- * begin and end of range where data are mising. Default false.
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.
1070
1201
  * @example
1071
1202
  * line = {
1072
1203
  * obj_name:"Proxy Server",
1073
1204
  * par_name:"CpuTotal",
1074
1205
  * par_id:"2452",
1075
- * values: "161111145730/3.48;161111145843/3.50;161111150013/",
1076
- * connectIfMissing: true
1206
+ * values: "161111145730/3.48;161111145843/3.50;161111150013/"
1077
1207
  * }
1078
1208
  */
1079
1209
  class LineData {
1080
- constructor(obj_name, par_name, par_id, values, connectIfMissing) {
1210
+ constructor(obj_name, par_name, par_id, values) {
1081
1211
  this.obj_name = obj_name;
1082
1212
  this.par_name = par_name;
1083
1213
  this.par_id = par_id;
1084
1214
  this.values = values;
1085
- this.connectIfMissing = connectIfMissing ;
1086
1215
  }
1087
1216
  }