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/CHANGELOG.md +18 -0
- package/DEVELOPER.md +37 -0
- package/README.md +210 -108
- package/build.js +36 -0
- package/dist/linechart-all.min.js +1 -1
- package/example/{example.csv → example1.csv} +5 -5
- package/example/example2.csv +745 -0
- package/example/index.html +85 -2
- package/package.json +7 -1
- package/src/chart-util.js +32 -1
- package/src/linechart.js +283 -154
- package/tools/updoc.js +35 -0
- package/Developer How-To.md +0 -17
- package/example/example.js +0 -70
- package/example/test.html +0 -18
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.4.0 (28 Nov 2026)
|
|
4
|
+
|
|
5
|
+
* New
|
|
6
|
+
|
|
7
|
+
* New parameter **ifDataMissing** in LineChart() constructor replaces **connectIfMissing** in
|
|
8
|
+
lineData() and applies to all lines in the chart.
|
|
9
|
+
* Step up to 10 years.
|
|
10
|
+
|
|
11
|
+
* Fixes
|
|
12
|
+
|
|
13
|
+
* Fix: `updateLines()` now correct removes the old legend and creates a new one from the new data.
|
|
14
|
+
* Fix: min/max values are determined from the raw range over all lines with a 10 % margin.
|
|
15
|
+
* Fix: charts with future data are handled correctly .
|
|
16
|
+
* Fix: decimal labels on axis-X are rounded to the step precision (no more visual garbage like 1.5999999999999999).
|
|
17
|
+
* Fix: in some cases prevent endless loops.
|
|
18
|
+
* Fix: legend item is XSS-safe and clicking on the colored tag also hides/shows the line.
|
|
19
|
+
* Fix: prevent creation global variables.
|
|
20
|
+
|
|
3
21
|
## 1.3.0 (14 Aug 2023)
|
|
4
22
|
* The data on axis-X may be data-time or numerical values. To switch between type of chart use parameter **axisXType**.
|
|
5
23
|
* New parameter for line **connectIfMissing**. It define how to draw line if part of data are missing.
|
package/DEVELOPER.md
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# Prepare files for distribution
|
|
2
|
+
|
|
3
|
+
* Update version in README, package.json, linechart.js
|
|
4
|
+
* Put information about changes in CHANGELOG
|
|
5
|
+
|
|
6
|
+
# Build
|
|
7
|
+
|
|
8
|
+
Terser is a devDependency of this project (see package.json). Install and
|
|
9
|
+
build with:
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
npm install // once: installs terser from package.json
|
|
13
|
+
npm run build // runs node build.js ->
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
`build.js` concatenates `src/chart-util.js` (first, it defines the globals)
|
|
17
|
+
and `src/linechart.js`, minifies them with terser, writes to `dist/linechart-all.min.js`
|
|
18
|
+
and copies `dist/linechart.css` writes the bundle.
|
|
19
|
+
|
|
20
|
+
# Generate API documentation in README.md
|
|
21
|
+
|
|
22
|
+
Transfer API description from JSDoc comments in the source code into the
|
|
23
|
+
`<!-- @API --> ... <!-- /@API -->` section of README.md:
|
|
24
|
+
|
|
25
|
+
```
|
|
26
|
+
npm run updoc // runs node tools/updoc.js
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Internal methods/classes are marked `@private` in the code and are left out of
|
|
30
|
+
the generated documentation.
|
|
31
|
+
|
|
32
|
+
# Test and Upload to NPM
|
|
33
|
+
|
|
34
|
+
```
|
|
35
|
+
npm pack --dry-run // Preview files to publish. Check if it correct
|
|
36
|
+
npm publish
|
|
37
|
+
```
|
package/README.md
CHANGED
|
@@ -1,108 +1,210 @@
|
|
|
1
|
-
# adaptive-linechart :chart_with_upwards_trend:
|
|
2
|
-
Version 1.
|
|
3
|
-
|
|
4
|
-
This is a small library to draw charts in the browser. All elements of chart will be set up
|
|
5
|
-
automaticaly based on data. You can adjust the layout of the chart by
|
|
6
|
-
for
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
{
|
|
22
|
-
obj_name: 'Stock preis',
|
|
23
|
-
par_name: '
|
|
24
|
-
|
|
25
|
-
},
|
|
26
|
-
{
|
|
27
|
-
obj_name: 'Stock preis',
|
|
28
|
-
par_name: '
|
|
29
|
-
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
1
|
+
# adaptive-linechart :chart_with_upwards_trend:
|
|
2
|
+
Version 1.4.0
|
|
3
|
+
|
|
4
|
+
This is a small library to draw charts in the browser. All elements of chart will be set up
|
|
5
|
+
automaticaly based on data. You can adjust the layout of the chart by using external CSS styles
|
|
6
|
+
for .nowrap .linechart, .chart-title, .chart-live-data, .chart-legend, .chart-legend-item,
|
|
7
|
+
.chart-legend-color. Maximal 10 lines in the chart. The values on axis-x may be Unix time-stamp
|
|
8
|
+
or numercal. The chart uses the global variable isMobil (Boolean). If false, live data are shown
|
|
9
|
+
by "mouse-over". By click on item in the legend hide/show line on chart. The library has own
|
|
10
|
+
simple logger that writes messages to the console. If needed, you can rewrite this logger and
|
|
11
|
+
redirect messages to another target.
|
|
12
|
+
|
|
13
|
+
Additional supplied function to convert CSV to time-series.
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
# Example
|
|
17
|
+
|
|
18
|
+
This example creates a chart with 3 lines in parent element with ID 'charts':
|
|
19
|
+
```js
|
|
20
|
+
var chartData = [
|
|
21
|
+
{
|
|
22
|
+
obj_name: 'Stock preis',
|
|
23
|
+
par_name: ' Open',
|
|
24
|
+
values: '1565301600/138.6100;1565560800/137.0700;1565647200/136.0500;1565733600/136.3600;1565820000/134.3900'
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
obj_name: 'Stock preis',
|
|
28
|
+
par_name: ' Hight',
|
|
29
|
+
vaues: '1565301600/139.3800;1565560800/137.8600;1565647200/138.8000;1565733600/136.9200;1565820000/134.5800'
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
obj_name: 'Stock preis',
|
|
33
|
+
par_name: ' Low',
|
|
34
|
+
values: '1565301600/136.4600;1565560800/135.2400;1565647200/135.0000;1565733600/133.6700;1565820000/132.2500'
|
|
35
|
+
}
|
|
36
|
+
];
|
|
37
|
+
|
|
38
|
+
var lchart = new LineChart(document.getElementById('charts'),null, null, 'Example Chart-Line', null);
|
|
39
|
+
|
|
40
|
+
for(i=0; i < chartData.length; i++) {
|
|
41
|
+
lchart.addLine(chartData[i]);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
lchart.draw();
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
[Live example](https://andk.dev/adaptive-linechart.html)
|
|
48
|
+
|
|
49
|
+
<!-- @API -->
|
|
50
|
+
|
|
51
|
+
## Classes
|
|
52
|
+
|
|
53
|
+
<dl>
|
|
54
|
+
<dt><a href="#LineChart">LineChart</a></dt>
|
|
55
|
+
<dd><p>The oject represent the chart. Constructor create object and HTML code for the chart. The chart
|
|
56
|
+
uses external CSS styles .nowrap .linechart, .chart-title, .chart-live-data, .chart-legend,
|
|
57
|
+
.chart-legent-item, .chart-legent-color. The chart uses global variable isMobil (Boolean). If
|
|
58
|
+
false, show live data by mouse over. The line create from LineData (see above) Labels on axis X
|
|
59
|
+
and Y will be created automaticaly. The chart can show maximal 10 lines in different colors.</p>
|
|
60
|
+
</dd>
|
|
61
|
+
<dt><a href="#LineData">LineData</a></dt>
|
|
62
|
+
<dd><p>The object represent data to create one line in chart.</p>
|
|
63
|
+
</dd>
|
|
64
|
+
</dl>
|
|
65
|
+
|
|
66
|
+
<a name="LineChart"></a>
|
|
67
|
+
|
|
68
|
+
## LineChart
|
|
69
|
+
The oject represent the chart. Constructor create object and HTML code for the chart. The chart
|
|
70
|
+
uses external CSS styles .nowrap .linechart, .chart-title, .chart-live-data, .chart-legend,
|
|
71
|
+
.chart-legent-item, .chart-legent-color. The chart uses global variable isMobil (Boolean). If
|
|
72
|
+
false, show live data by mouse over. The line create from LineData (see above) Labels on axis X
|
|
73
|
+
and Y will be created automaticaly. The chart can show maximal 10 lines in different colors.
|
|
74
|
+
|
|
75
|
+
**Kind**: global class
|
|
76
|
+
|
|
77
|
+
* [LineChart](#LineChart)
|
|
78
|
+
* [new LineChart(container, chartId, width, title, className, axisXType, ifDataMissing)](#new_LineChart_new)
|
|
79
|
+
* [.avgStep](#LineChart+avgStep)
|
|
80
|
+
* [.addLine(lineData)](#LineChart+addLine) ⇒ <code>boolean</code>
|
|
81
|
+
* [.updateLines(lines)](#LineChart+updateLines) ⇒ <code>boolean</code>
|
|
82
|
+
* [.clear()](#LineChart+clear)
|
|
83
|
+
* [.draw()](#LineChart+draw)
|
|
84
|
+
* [.resize(difWidth, difHeight)](#LineChart+resize)
|
|
85
|
+
* [.isEmpty()](#LineChart+isEmpty)
|
|
86
|
+
|
|
87
|
+
<a name="new_LineChart_new"></a>
|
|
88
|
+
|
|
89
|
+
### new LineChart(container, chartId, width, title, className, axisXType, ifDataMissing)
|
|
90
|
+
|
|
91
|
+
| Param | Type | Description |
|
|
92
|
+
| --- | --- | --- |
|
|
93
|
+
| container | <code>HTMLElement</code> | parent element for the chart. If null use HTML BODY as parent element. |
|
|
94
|
+
| chartId | <code>number</code> | identifier for chart. Optional. If not defined use random number. |
|
|
95
|
+
| width | <code>number</code> | width in pixel. Optional. Default use available width in parent element. |
|
|
96
|
+
| title | <code>string</code> | title of chart. Optional. If null don't create title. |
|
|
97
|
+
| className | <code>string</code> | class for div of chart. Optional. Default "linechart" |
|
|
98
|
+
| axisXType | <code>string</code> | for time based values on axis X set "time" (Default). For number based values "number". |
|
|
99
|
+
| ifDataMissing | <code>string</code> | handling of missing values on axis X. "connect" (Default) - connect line across missing values. "noline" - don't draw line across missing values. "skip" - reserved, not yet implemented. |
|
|
100
|
+
|
|
101
|
+
<a name="LineChart+avgStep"></a>
|
|
102
|
+
|
|
103
|
+
### lineChart.avgStep
|
|
104
|
+
Instead automatic, the average step on axis X may be set manual.
|
|
105
|
+
Several measured values are combined into fixed time windows to
|
|
106
|
+
flatten peaks in the graph. Value in seconds. If NaN, not used.
|
|
107
|
+
|
|
108
|
+
**Kind**: instance property of [<code>LineChart</code>](#LineChart)
|
|
109
|
+
<a name="LineChart+addLine"></a>
|
|
110
|
+
|
|
111
|
+
### lineChart.addLine(lineData) ⇒ <code>boolean</code>
|
|
112
|
+
Add new line and create new item in legend.
|
|
113
|
+
|
|
114
|
+
**Kind**: instance method of [<code>LineChart</code>](#LineChart)
|
|
115
|
+
**Returns**: <code>boolean</code> - true if no problem detected, otherwise false.
|
|
116
|
+
|
|
117
|
+
| Param | Type | Description |
|
|
118
|
+
| --- | --- | --- |
|
|
119
|
+
| lineData | [<code>LineData</code>](#LineData) | object that represents the data for one line. |
|
|
120
|
+
|
|
121
|
+
<a name="LineChart+updateLines"></a>
|
|
122
|
+
|
|
123
|
+
### lineChart.updateLines(lines) ⇒ <code>boolean</code>
|
|
124
|
+
Update data in chart and redraw this one. The old legend items are removed and
|
|
125
|
+
recreated for the new lines.
|
|
126
|
+
|
|
127
|
+
**Kind**: instance method of [<code>LineChart</code>](#LineChart)
|
|
128
|
+
**Returns**: <code>boolean</code> - true if no problem detected, otherwise false.
|
|
129
|
+
|
|
130
|
+
| Param | Type | Description |
|
|
131
|
+
| --- | --- | --- |
|
|
132
|
+
| lines | [<code>Array.<LineData></code>](#LineData) | array of lineData objects; replaces all current lines. |
|
|
133
|
+
|
|
134
|
+
<a name="LineChart+clear"></a>
|
|
135
|
+
|
|
136
|
+
### lineChart.clear()
|
|
137
|
+
Clear all on graphic. Legend stay visible.
|
|
138
|
+
|
|
139
|
+
**Kind**: instance method of [<code>LineChart</code>](#LineChart)
|
|
140
|
+
<a name="LineChart+draw"></a>
|
|
141
|
+
|
|
142
|
+
### lineChart.draw()
|
|
143
|
+
Draw graphic with all elements.
|
|
144
|
+
|
|
145
|
+
**Kind**: instance method of [<code>LineChart</code>](#LineChart)
|
|
146
|
+
<a name="LineChart+resize"></a>
|
|
147
|
+
|
|
148
|
+
### lineChart.resize(difWidth, difHeight)
|
|
149
|
+
Change size of chart and redraw. May be used if size of parent panel changed but data
|
|
150
|
+
in lines stay the same.
|
|
151
|
+
|
|
152
|
+
**Kind**: instance method of [<code>LineChart</code>](#LineChart)
|
|
153
|
+
|
|
154
|
+
| Param | Type | Description |
|
|
155
|
+
| --- | --- | --- |
|
|
156
|
+
| difWidth | <code>number</code> | difference in width (pixel). |
|
|
157
|
+
| difHeight | <code>number</code> | difference in height (pixel). |
|
|
158
|
+
|
|
159
|
+
<a name="LineChart+isEmpty"></a>
|
|
160
|
+
|
|
161
|
+
### lineChart.isEmpty()
|
|
162
|
+
Return true if all lines are empty
|
|
163
|
+
|
|
164
|
+
**Kind**: instance method of [<code>LineChart</code>](#LineChart)
|
|
165
|
+
<a name="LineData"></a>
|
|
166
|
+
|
|
167
|
+
## LineData
|
|
168
|
+
The object represent data to create one line in chart.
|
|
169
|
+
|
|
170
|
+
**Kind**: global class
|
|
171
|
+
<a name="new_LineData_new"></a>
|
|
172
|
+
|
|
173
|
+
### new LineData(obj_name, par_name, par_id, values)
|
|
174
|
+
|
|
175
|
+
| Param | Type | Description |
|
|
176
|
+
| --- | --- | --- |
|
|
177
|
+
| obj_name | <code>string</code> | name of the object, shown in the legend. |
|
|
178
|
+
| par_name | <code>string</code> | name of the parameter, shown in the legend. |
|
|
179
|
+
| par_id | <code>number</code> | internal id of the line. Optional. May be used to request data from a backend. |
|
|
180
|
+
| values | <code>string</code> | measurement data, elements separated by ";". Each element contains the value on axis-X and the measuring value separated by "/", e.g. "161111145730/3.48;161111145843/3.50;161111150013/". - Axis-X value: Unix time-stamp in seconds for axisXType "time", any decimal number for axisXType "number" (e.g. "0.001/5"). - Measuring value: any number (positive or negative). An empty measuring value marks a missing value (gap); there the line is interrupted or connected according to ifDataMissing. |
|
|
181
|
+
|
|
182
|
+
**Example**
|
|
183
|
+
```js
|
|
184
|
+
line = {
|
|
185
|
+
obj_name:"Proxy Server",
|
|
186
|
+
par_name:"CpuTotal",
|
|
187
|
+
par_id:"2452",
|
|
188
|
+
values: "161111145730/3.48;161111145843/3.50;161111150013/"
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
<!-- /@API -->
|
|
193
|
+
|
|
194
|
+
## Utility
|
|
195
|
+
|
|
196
|
+
**`scvToTimeSeries(csv)`** - process CSV and return array of objects
|
|
197
|
+
|
|
198
|
+
`{name: "Name of serie", data: "Unix-Timestamp/Value;Unix-Timestamp/Value"}`.
|
|
199
|
+
|
|
200
|
+
Assume the first column contains data-time as string. The CSV may contain many columns. Name of
|
|
201
|
+
serie taken from header. Values may be empty. This function needs the package [Moment.js](https://momentjs.com)
|
|
202
|
+
|
|
203
|
+
## Contact
|
|
204
|
+
|
|
205
|
+
If you have any questions, please contact me `adaptive-linechart@my.mail.de`
|
|
206
|
+
|
|
207
|
+
## License
|
|
208
|
+
|
|
209
|
+
[MIT](https://opensource.org/licenses/MIT) © Andrej Koslov
|
|
210
|
+
|
package/build.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Build script for adaptive-linechart.
|
|
2
|
+
// Concatenates src/chart-util.js and src/linechart.js (in this order, because
|
|
3
|
+
// chart-util.js defines the global helpers used by linechart.js), minifies
|
|
4
|
+
// them with terser and writes dist/linechart-all.min.js. The CSS is copied
|
|
5
|
+
// unchanged.
|
|
6
|
+
//
|
|
7
|
+
// Usage: npm run build (or: node build.js)
|
|
8
|
+
const fs = require('fs');
|
|
9
|
+
const path = require('path');
|
|
10
|
+
const terser = require('terser');
|
|
11
|
+
|
|
12
|
+
(async function () {
|
|
13
|
+
const src = path.join(__dirname, 'src');
|
|
14
|
+
const dist = path.join(__dirname, 'dist');
|
|
15
|
+
|
|
16
|
+
// Order matters: chart-util.js first, it defines the globals (logger,
|
|
17
|
+
// addNewElement, getAvgValue, ...) used by linechart.js.
|
|
18
|
+
const code = [
|
|
19
|
+
fs.readFileSync(path.join(src, 'chart-util.js'), 'utf8'),
|
|
20
|
+
fs.readFileSync(path.join(src, 'linechart.js'), 'utf8')
|
|
21
|
+
].join('\n'); // Separator between files
|
|
22
|
+
|
|
23
|
+
// Default options: top-level names (LineChart, logger, scvToTimeSeries,
|
|
24
|
+
// ...) stay untouched, so the public API keeps working.
|
|
25
|
+
const result = await terser.minify(code, {});
|
|
26
|
+
if (result.error) {
|
|
27
|
+
console.error('terser error:', result.error);
|
|
28
|
+
process.exit(1);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
fs.writeFileSync(path.join(dist, 'linechart-all.min.js'), result.code);
|
|
32
|
+
fs.copyFileSync(path.join(src, 'linechart.css'), path.join(dist, 'linechart.css'));
|
|
33
|
+
|
|
34
|
+
console.log('dist/linechart-all.min.js ' + (result.code.length / 1024).toFixed(1) + ' KB');
|
|
35
|
+
console.log('dist/linechart.css ' + (fs.statSync(path.join(dist, 'linechart.css')).size / 1024).toFixed(1) + ' KB');
|
|
36
|
+
})();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
class LineChart{constructor(container,chartId,width,title,className,axisXType){if(container==null)container=document.getElementsByTagName("BODY")[0];if(chartId==null)chartId=getRandomInt();if(className==null)className="linechart";if(width==null)width=container.clientWidth;this.chartDiv=addNewElement(container,"div",{class:className,id:"chart_"+chartId,chart_id:chartId,style:"float:left; width:"+width+"px; padding-bottom:8px;"});if(title!=null){let titleElement=addNewElement(this.chartDiv,"label",{class:"chart-title nowrap",style:"width:"+(width-20)+"px; text-align:center; display:block; margin-left:10px; margin-top:10px"});titleElement.innerHTML=title}var canvasWidth=width-30;var canvasHeight=300;if(isMobil){canvasHeight=220}else{if(width<200){canvasHeight=200}else if(width<300){canvasHeight=220}else if(width<400){canvasHeight=240}else if(width<500){canvasHeight=260}else if(width<600){canvasHeight=280}}this._canvas=addNewElement(this.chartDiv,"canvas",{id:"chart_"+chartId+"_canvas",width:canvasWidth,height:canvasHeight,style:"margin: 15px 17px 3px 13px;"});if(axisXType!=null||typeof axisXType=="undefined"){if(axisXType=="number"){this.axisXType="number"}else if(axisXType=="time"){this.axisXType="time"}else{logger.warn(`Unknow value axisXType=${axisXType}. Set default "time".`);this.axisXType="time"}}else{this.axisXType=="time"}this._canvas.dataset.axisXType=this.axisXType;this._canvas.dataset.chartId=chartId.toString();this._context=this._canvas.getContext("2d");this._context.translate(.5,.5);if(!isMobil){this._canvas.addEventListener("mouseout",(function(event){var element=document.getElementById("chart_"+this.dataset.chartId+"_livedata");if(element==null)return;element.innerText="-"}));this._canvas.addEventListener("mousemove",(function(event){var element=document.getElementById("chart_"+this.dataset.chartId+"_livedata");if(element==null)return;if(this.height-event.offsetY<this.dataset.paddingBottom||event.offsetX<this.dataset.paddingLeft){element.innerText="-";return}var curValY=this.dataset.maxVal-event.offsetY/parseFloat(this.dataset.coefVal);if(isNaN(curValY)){element.innerText="-";return}if(curValY<100){curValY=curValY.toFixed(2)}else if(curValY<200){curValY=curValY.toFixed(1)}else{curValY=Math.round(curValY)}if(this.dataset.axisXType=="time"){var curTs=parseInt(this.dataset.minTs)+Math.round((event.offsetX-parseInt(this.dataset.paddingLeft))/parseFloat(this.dataset.coefTs));if(isNaN(curTs)){element.innerText="-";return}curTs=new Date(curTs*1e3).separate();element.innerHTML="Date <b>"+curTs.mday+"."+curTs.month+"."+curTs.year+"</b> Time <b>"+curTs.hour+":"+curTs.min+"</b> Value <b>"+curValY+"</b>"}else{var curValX=parseInt(this.dataset.minTs)+Math.round((event.offsetX-parseInt(this.dataset.paddingLeft))/parseFloat(this.dataset.coefTs));element.innerHTML="Axis-X <b>"+curValX+"</b> Axis-Y <b>"+curValY+"</b>"}}));addNewElement(this.chartDiv,"div",{class:"chart-live-data, nowrap",id:"chart_"+chartId+"_livedata",style:"margin-left: 12px; margin-right: 12px; margin-bottom: 4px; max-width:95%;",innerText:"-"})}this._legendDiv=addNewElement(this.chartDiv,"div",{class:"chart-legend",id:"chart_"+chartId+"_legend"});this.chartId=chartId;this.lines=[];this._minTs=Number.MAX_SAFE_INTEGER;this._maxTs=0;this._minVal=Number.MAX_VALUE;this._maxVal=Number.MIN_VALUE;this._axeYLabelStep=null;this._axeYLabelHeight=30;this._axeXLabelWidth=80;this._coefTs=null;this._coefVal=null;this._padding={left:50,bottom:35};this.avgStep=NaN}addLine(lineData){if(lineData.values==null){logger.error("Function LineChart.newLine(). DataString is null.");return false}if(!isString(lineData.values)){logger.error("Function LineChart.newLine(). DataString is not a string.");return false}var line=this._createLine(lineData);if(line==null){logger.error("Function LineChart.newLine(). Function _createLine() return null.");return false}line.legend=addNewElement(this._legendDiv,"div",{class:"chart-legend-item nowrap",id:`chart_${this.chartId}_legend_${lineData.par_id}`,style:`cursor: pointer; max-width:${this.chartDiv.clientWidth-20}px;`,innerHTML:`<span class="chart-legend-color" style="background-color:${line.color}; color:${line.color};">--</span>${line.objName} / ${line.parName}`});line.legend.addEventListener("click",(function(event){var legendColor=event.target.getElementsByClassName("chart-legend-color")[0];if(legendColor==null)return;if(line.hidden==false){line.hidden=true;legendColor.style.backgroundColor="white"}else{line.hidden=false;legendColor.style.backgroundColor=line.color}event.target.chart.draw()}));line.legend.chart=this;this.lines.push(line);return true}updateLines(lines){if(lines==null){logger.error("Function LineChart.updateLines(). Parameter lines is null.");return false}if(!Array.isArray(lines)){logger.error("Function LineChart.updateLines(). Parameter lines is not a array.");return false}this.lines=[];this._minTs=99999999999999;this._maxTs=0;this._minVal=999999999999999;this._maxVal=0;this._axeYLabelStep=null;this._coefTs=null;this._coefVal=null;for(var i in lines){var line=this._createLine(lines[i]);if(line!=null){this.lines.push(line)}}this.draw();return true}_createLine(lineData){var line=new SingleLine(lineData,this.colors[this.lines.length]);var isAllNaN=true;if(lineData.par_id==null)lineData.par_id=this.lines.length;if(lineData.values.length==0)return line;var ar=lineData.values.split(";");var arLen=ar.length;for(var i=0;i<arLen;++i){var item=ar[i].split("/");if(item[0]==""){logger.warn("LineChart._createLine(). Item "+i+". Element for axis-x is empty.");continue}if(isNaN(item[0])){logger.warn("LineChart._createLine(). Item "+i+'. Element for axis-x is not a number "'+item[0]+'".');continue}var elem={ts:null,val:null};elem.ts=parseInt(item[0]);elem.val=parseFloat(item[1]);line.real.push(elem);if(!isNaN(elem.val)){if(elem.val<0){if(Math.floor(elem.val*1.1)<this._minVal){this._minVal=Math.floor(elem.val*1.1)}}else{if(Math.floor(elem.val*.9)<this._minVal){this._minVal=Math.floor(elem.val*.9)}}if(Math.ceil(elem.val*1.1)>this._maxVal){this._maxVal=Math.ceil(elem.val*1.1)}isAllNaN=false}if(elem.ts<this._minTs)this._minTs=elem.ts;if(elem.ts>this._maxTs)this._maxTs=elem.ts}if(line.real.length==0)return line;line.isEmpty=false;if(this._maxVal==0&&this._minVal==0||isAllNaN){this._minVal=0;this._maxVal=1}var minValText=this._context.measureText(this._minVal.toString());var maxValText=this._context.measureText(this._maxVal.toString());if(minValText.width<maxValText.width){this._padding.left=Math.round(maxValText.width)+23}else{this._padding.left=Math.round(minValText.width)+23}return line}clear(){this._context.clearRect(0,0,this._canvas.width,this._canvas.height)}draw(){this._coefTs=(this._canvas.width-this._padding.left)/(this._maxTs-this._minTs);this._coefVal=(this._canvas.height-this._padding.bottom)/(this._maxVal-this._minVal);this._context.clearRect(0,0,this._canvas.width,this._canvas.height);if(this.isEmpty())return;if(this.axisXType=="time"){this._drawAxeXTime()}else{this._drawAxeXNum()}this._drawAxeY();for(var i=0;i<this.lines.length;i++){this._drawLine(i)}this._canvas.dataset.minTs=this._minTs.toString();this._canvas.dataset.coefTs=this._coefTs.toString();this._canvas.dataset.maxVal=this._maxVal.toString();this._canvas.dataset.coefVal=this._coefVal.toString();this._canvas.dataset.paddingLeft=this._padding.left.toString();this._canvas.dataset.paddingBottom=this._padding.bottom.toString()}resize(difWidth,difHeight){this._canvas.width=this._canvas.width+difWidth;this._canvas.height=this._canvas.height+difHeight;this._context.translate(.5,.5);this.draw()}_drawAxeXTime(){this._drawAxeXBasic();var arLen;var stepTs=Math.round(this._axeXLabelWidth/this._coefTs);if(stepTs<=1){stepTs=1}else{arLen=this.stepsX.length-1;for(var i=0;i<arLen;i++){if(stepTs>this.stepsX[i]&&stepTs<this.stepsX[i+1]){stepTs=this.stepsX[i];break}}}var tsLabel=this._getBeginOfDayFromUnixTs(this._minTs);var isFound=false;var tsNow=(new Date).getTime()/1e3;while(tsLabel<tsNow){if(tsLabel>this._minTs){isFound=true;break}tsLabel+=stepTs}var labels=[];var posX,labelStr;while(tsLabel<this._maxTs){posX=this._convertTs2PosX(tsLabel);labelStr=this._formatTsForLabel(tsLabel,this._maxTs-this._minTs);labels.push({X:posX,str:labelStr});tsLabel=tsLabel+stepTs}this._context.beginPath();this._context.strokeStyle="#e6e6e6";var halfStep=Math.round(stepTs*this._coefTs/2);var posY=this._canvas.height-this._padding.bottom;arLen=labels.length;for(var i=0;i<arLen;i++){this._context.moveTo(labels[i].X,0);this._context.lineTo(labels[i].X,posY+10);if(labels[i].X-halfStep>this._padding.left+2){this._context.moveTo(labels[i].X-halfStep,0);this._context.lineTo(labels[i].X-halfStep,posY)}}if(labels[i-1]!=null){if(labels[i-1].X+halfStep<=this._canvas.width){this._context.moveTo(labels[i-1].X+halfStep,0);this._context.lineTo(labels[i-1].X+halfStep,posY)}}this._context.stroke();this._context.font="12px arial";arLen=labels.length;for(i=0;i<arLen;i++){this._context.fillText(labels[i].str.hm,labels[i].X-17,posY+17);if(i==0){this._context.fillText(labels[i].str.dm,labels[i].X-17,posY+32)}else{if(labels[i].str.dm!=labels[i-1].str.dm){this._context.fillText(labels[i].str.dm,labels[i].X-17,posY+32)}}}this._context.closePath()}_drawAxeXNum(){this._drawAxeXBasic();let arLen;let stepX=Math.round(this._axeXLabelWidth/this._coefTs);stepX=this._getNextPreferedNumber(stepX);let minXLabelVal=this._getNextPreferedNumber(this._minTs);let labelsX=[];while(minXLabelVal<this._maxTs){labelsX.push({X:this._convertTs2PosX(minXLabelVal),str:minXLabelVal});minXLabelVal=minXLabelVal+stepX}this._context.beginPath();this._context.strokeStyle="#e6e6e6";let halfStep=Math.round(stepX*this._coefTs/2);let posY=this._canvas.height-this._padding.bottom;arLen=labelsX.length;for(i=0;i<arLen;i++){this._context.moveTo(labelsX[i].X,0);this._context.lineTo(labelsX[i].X,posY+10);if(labelsX[i].X-halfStep>this._padding.left+2){this._context.moveTo(labelsX[i].X-halfStep,0);this._context.lineTo(labelsX[i].X-halfStep,posY)}}if(labelsX[i-1]!=null){if(labelsX[i-1].X+halfStep<=this._canvas.width){this._context.moveTo(labelsX[i-1].X+halfStep,0);this._context.lineTo(labelsX[i-1].X+halfStep,posY)}}this._context.stroke();this._context.font="12px arial";arLen=labelsX.length;for(i=0;i<arLen;i++){this._context.fillText(labelsX[i].str,labelsX[i].X,posY+20)}this._context.closePath()}_drawAxeXBasic(){this._context.strokeStyle=this.colorDefault;this._context.lineWidth=1;this._context.beginPath();this._context.moveTo(this._padding.left,this._canvas.height-this._padding.bottom);this._context.lineTo(this._canvas.width,this._canvas.height-this._padding.bottom);this._context.stroke()}_drawAxeY(){if(this._coefTs==null||this._coefVal==null)return;var arLen;var labelsAmount=(this._canvas.height-this._padding.bottom)/this._axeYLabelHeight;this._axeYLabelStep=(this._maxVal-this._minVal)/labelsAmount;this._axeYLabelStep=this._getNextPreferedNumber(this._axeYLabelStep);var labelMinVal=0;if(this._minVal<0){while(labelMinVal>this._minVal){if(labelMinVal<=this._minVal)break;labelMinVal-=this._axeYLabelStep}}else if(this._minVal>0){while(labelMinVal<this._maxVal){if(labelMinVal>=this._minVal)break;labelMinVal+=this._axeYLabelStep}}var axeYHight=this._canvas.height-this._padding.bottom;var axeY=[];i=0;var labelPosY,labelValue;while(i<33){labelValue=labelMinVal+this._axeYLabelStep*i;if(this._axeYLabelStep<1||this._axeYLabelStep==2.5)labelValue=labelValue.toFixed(2);labelPosY=this._convertVal2PosY(labelValue);if(labelPosY<0)break;if(labelPosY<axeYHight){var label={value:labelValue,Y:labelPosY};axeY.push(label)}i++}this._context.lineWidth=1;this._context.beginPath();this._context.strokeStyle=this.colorDefault;this._context.moveTo(this._padding.left,0);this._context.lineTo(this._padding.left,this._canvas.height-this._padding.bottom);this._context.stroke();this._context.beginPath();this._context.strokeStyle="#e6e6e6";var helpLinePosY;arLen=axeY.length;for(i=0;i<arLen;i++){helpLinePosY=axeY[i].Y+Math.round(this._coefVal*this._axeYLabelStep/2);if(helpLinePosY<this._canvas.height-this._padding.bottom){this._context.moveTo(this._padding.left,helpLinePosY);this._context.lineTo(this._canvas.width,helpLinePosY)}if(axeY[i].Y>=this._canvas.height-this._padding.bottom)continue;this._context.moveTo(this._padding.left,axeY[i].Y);this._context.lineTo(this._canvas.width,axeY[i].Y)}helpLinePosY=axeY[axeY.length-1].Y-Math.round(this._coefVal*this._axeYLabelStep/2);if(helpLinePosY>0){this._context.moveTo(this._padding.left,helpLinePosY);this._context.lineTo(this._canvas.width,helpLinePosY)}this._context.stroke();this._context.font="12px arial";this._context.strokeStyle=this.colorDefault;arLen=axeY.length;for(i=0;i<arLen;i++){this._context.fillText(axeY[i].value,0,axeY[i].Y+10)}}_drawLine(lineIndex){var line=this.lines[lineIndex];if(line==null){logger.error("Function LineChart.drawLine(lineId). The line with ID "+lineIndex+" not found!");return}if(line.isEmpty==true||line.real.length==0||line.hidden)return;var pos=[];var lastX=-1;var avgY=[];var arLen;var lineData=[];if(!isNaN(this.avgStep)){var avgNextPoint=this._getBeginOfDayFromUnixTs(line.real[0].ts);while(avgNextPoint<line.real[0].ts){avgNextPoint+=this.avgStep}arLen=line.real.length;for(var x=0;x<arLen;x++){if(line.real[x].ts<avgNextPoint){avgY.push(line.real[x].val)}else{var maxCounter=0;while(line.real[x].ts>avgNextPoint+this.avgStep){avgNextPoint+=this.avgStep;maxCounter++;if(maxCounter>1e3){logger.warn("drawLine(). Can't calculate average values for this line. "+new Date(line.real[x].ts*1e3).formatISOLocal()+"/"+line.real[x].val);return}}var item={ts:avgNextPoint,val:getAvgValue(avgY,2)};lineData.push(item);avgY=[];avgY.push(line.real[x].val);avgNextPoint+=this.avgStep}}if(avgY.length>0){var item={ts:avgNextPoint,val:getAvgValue(avgY,2)};lineData.push(item)}}avgY=[];if(lineData.length==0)lineData=line.real;arLen=lineData.length;for(var i=0;i<arLen;i++){var item={X:NaN,Y:NaN};item.X=this._convertTs2PosX(lineData[i].ts);if(!isNaN(lineData[i].val))item.Y=this._convertVal2PosY(lineData[i].val);if(item.X==lastX){avgY.push(item.Y);continue}else{lastX=item.X;if(avgY.length>0&&i>0){avgY.push(pos[pos.length-1].Y);pos[pos.length-1].Y=getAvgValue(avgY,2);avgY=[]}}pos.push(item)}this._context.strokeStyle=this.colors[lineIndex];this._context.lineWidth=1;this._context.beginPath();arLen=pos.length;for(i=0;i<arLen;i++){if(!isNaN(pos[i].Y)){this._context.moveTo(pos[i].X,pos[i].Y);i++;break}}while(i<arLen){if(!isNaN(pos[i].Y)){this._context.lineTo(pos[i].X,pos[i].Y);i++}else{if(this.connectIfMissing==true){while(i<pos.length){if(!isNaN(pos[i].Y)){break}i++}}else{this._context.stroke();this._context.beginPath();while(i<pos.length){if(!isNaN(pos[i].Y)){break}i++}}}}this._context.stroke()}_getNextPreferedNumber(num){if(num==0)return 0;let steps=[1e-9,2e-9,5e-9,1e-8];let factor=1;let minStep,maxStep;while(factor<1e18+1){for(var i=0;i<steps.length-1;i++){minStep=steps[i]*factor;maxStep=steps[i+1]*factor;if(minStep<=num&&num<=maxStep){return maxStep}}factor=factor*10}return null}isEmpty(){var isEmpty=true;for(var i=0;i<this.lines.length;i++){if(!this.lines[i].isEmpty){isEmpty=false}}return isEmpty}_convertTs2PosX(ts){return this._canvas.width-Math.round((this._maxTs-ts)*this._coefTs)}_convertVal2PosY(val){return Math.round((this._maxVal-val)*this._coefVal)}_formatTsForLabel(ts,tsdif){let date=new Date(ts*1e3);tsdif=tsdif/(3600*24);let yaer=date.getFullYear();let mon=date.getMonth()+1;if(mon<10)mon="0"+mon.toString();let mday=date.getDate();if(parseInt(mday)<10)mday="0"+mday.toString();let hours=date.getHours();if(parseInt(hours)<10)hours="0"+hours;let min=date.getMinutes();if(parseInt(min)<10)min="0"+min.toString();let result={};if(tsdif<3){result={dm:mday+"."+mon,hm:hours+":"+min}}else if(tsdif>=3&&tsdif<180){result={dm:yaer,hm:mday+"."+mon}}else{result={dm:yaer,hm:" "+mon}}return result}_getBeginOfDayFromUnixTs(ts){var result=new Date(ts*1e3);result=new Date(result.getFullYear(),result.getMonth(),result.getDate());result.setMinutes(59);result.setSeconds(59);result.setMilliseconds(1e3);return result.getTime()/1e3}colors=["#0044CC","#008000","#FF8533","#6A6A6A","#C71585","#8B4513","#1E90FF","#FF4500","#00FF00","#8A2BE2"];colorDefault="#657585";stepsX=[1,2,5,10,20,30,1*60,2*60,5*60,10*60,15*60,20*60,30*60,60*60,2*60*60,4*60*60,6*60*60,12*60*60,24*60*60,2*24*60*60,3*24*60*60,4*24*60*60,5*24*60*60,7*24*60*60,10*24*60*60,15*24*60*60,20*24*60*60,30*24*60*60,45*24*60*60,60*24*60*60,90*24*60*60,120*24*60*60]}class SingleLine{constructor(lineData,color){this.parId=lineData.par_id;this.parName=lineData.par_name!=null?lineData.par_name:"";this.objName=lineData.obj_name!=null?lineData.obj_name:"";this.real=[];if(lineData.connectIfmissing==null){this.connectIfmissing=false}else{this.connectIfmissing=lineData.connectIfmissing}this.isEmpty=true;this.hidden=false;if(color==null){this.color="black"}else{this.color=color}this.legend=null}}class LineData{constructor(obj_name,par_name,par_id,values,connectIfMissing){this.obj_name=obj_name;this.par_name=par_name;this.par_id=par_id;this.values=values;this.connectIfMissing=connectIfMissing}}if(typeof logger!="notdefined"){var logger={info:function(message){console.info(message)},warn:function(message){console.warn(message)},error:function(message){console.error(message)},debug:function(message){console.debug(message)}}}function addNewElement(parent,tag,attrSet){if(attrSet==null)attrSet={};if(attrSet.id!=null){if(document.getElementById(attrSet.id)!=null){newElementCounter++;attrSet.id=newElementCounter.toString()+"_"+(new Date).getTime().toString()}}else{newElementCounter++;attrSet.id=newElementCounter.toString()+"_"+(new Date).getTime().toString()}if(tag==null){var element=document.createElement("div")}else{var element=document.createElement(tag)}for(var attribute in attrSet){element.setAttribute(attribute,attrSet[attribute])}if(attrSet.innerText!=null)element.innerText=attrSet.innerText;if(attrSet.innerHTML!=null)element.innerHTML=attrSet.innerHTML;if(parent==null){document.body.appendChild(element)}else{parent.appendChild(element)}return document.getElementById(attrSet.id)}var newElementCounter=0;function getAvgValue(arData,precision){if(arData==null||arData.length==0)return NaN;if(precision==null||isNaN(precision))precision=2;var sum=0;var count=0;for(var i=0;i<arData.length;i++){if(!isNaN(arData[i])){sum+=arData[i];count+=1}}if(count==0){return NaN}else{return(sum/count).toFixed(precision)}}function getRandomInt(){return Math.random()*1e17}function isString(variable){return typeof variable==="string"||variable instanceof String}Date.prototype.separate=function(){var dt={};dt.year=this.getFullYear();dt.month=this.getMonth()+1;dt.mday=this.getDate();dt.hour=this.getHours();dt.min=this.getMinutes();dt.sec=this.getSeconds();dt.msec=this.getMilliseconds();if(dt.month<10)dt.month="0"+dt.month;if(dt.mday<10)dt.mday="0"+dt.mday;if(dt.hour<10)dt.hour="0"+dt.hour;if(dt.min<10)dt.min="0"+dt.min;if(dt.sec<10)dt.sec="0"+dt.sec;if(dt.msec<10){dt.msec="00"+dt.msec}else if(dt.msec<100){dt.msec="0"+dt.msec}return dt};function scvToTimeSeries(csv){let arResult=[];if(csv==null){return arResult}let arLines=csv.split(/\r?\n/);if(arLines.length<2){return arResult}var arHeader=arLines[0].split(",");for(let x=1;x<arHeader.length;x++){let obSerie={name:arHeader[x],data:""};for(let i=arLines.length-1;i>0;i--){let arElements=arLines[i].split(",");if(arElements.length!=arHeader.length)continue;obSerie.data+=moment(arElements[0]).format("X")+"/"+arElements[x]+";"}obSerie.data=obSerie.data.slice(0,-1);arResult.push(obSerie)}return arResult}
|
|
1
|
+
if(void 0===logger)var logger={info:function(t){console.info(t)},warn:function(t){console.warn(t)},error:function(t){console.error(t)},debug:function(t){console.debug(t)}};function addNewElement(t,e,i){if(null==i&&(i={}),null!=i.id?null!=document.getElementById(i.id)&&(newElementCounter++,i.id=newElementCounter.toString()+"_"+(new Date).getTime().toString()):(newElementCounter++,i.id=newElementCounter.toString()+"_"+(new Date).getTime().toString()),null==e)var a=document.createElement("div");else a=document.createElement(e);for(var n in i)a.setAttribute(n,i[n]);return null!=i.innerText&&(a.innerText=i.innerText),null!=i.innerHTML&&(a.innerHTML=i.innerHTML),null==t?document.body.appendChild(a):t.appendChild(a),document.getElementById(i.id)}var newElementCounter=0;function getAvgValue(t,e){if(null==t||0==t.length)return NaN;(null==e||isNaN(e))&&(e=2);for(var i=0,a=0,n=0;n<t.length;n++)isNaN(t[n])||(i+=t[n],a+=1);return 0==a?NaN:(i/a).toFixed(e)}function getRandomInt(){return 1e17*Math.random()}function isString(t){return"string"==typeof t||t instanceof String}function roundTo(t,e){if(null==t||isNaN(t))return t;(null==e||e<0)&&(e=0);var i=Math.pow(10,e);return Math.round(t*i)/i}function scvToTimeSeries(t){let e=[];if(null==t)return e;let i=t.split(/\r?\n/);if(i.length<2)return e;var a=i[0].split(",");for(let t=1;t<a.length;t++){let n={name:a[t],data:""};for(let e=i.length-1;e>0;e--){let s=i[e].split(",");s.length==a.length&&(n.data+=moment(s[0]).format("X")+"/"+s[t]+";")}n.data=n.data.slice(0,-1),e.push(n)}return e}Date.prototype.separate=function(){var t={};return t.year=this.getFullYear(),t.month=this.getMonth()+1,t.mday=this.getDate(),t.hour=this.getHours(),t.min=this.getMinutes(),t.sec=this.getSeconds(),t.msec=this.getMilliseconds(),t.month<10&&(t.month="0"+t.month),t.mday<10&&(t.mday="0"+t.mday),t.hour<10&&(t.hour="0"+t.hour),t.min<10&&(t.min="0"+t.min),t.sec<10&&(t.sec="0"+t.sec),t.msec<10?t.msec="00"+t.msec:t.msec<100&&(t.msec="0"+t.msec),t},Date.prototype.formatISOLocal=function(){var t=this.separate();return t.year+"-"+t.month+"-"+t.mday+" "+t.hour+":"+t.min+":"+t.sec};class LineChart{constructor(t,e,i,a,n,s,h){if(null==t&&(t=document.getElementsByTagName("BODY")[0]),null==e&&(e=getRandomInt()),null==n&&(n="linechart"),null==i&&(i=t.clientWidth),this.chartDiv=addNewElement(t,"div",{class:n,id:"chart_"+e,chart_id:e,style:"float:left; width:"+i+"px; padding-bottom:8px;"}),null!=a){addNewElement(this.chartDiv,"label",{class:"chart-title nowrap",style:"width:"+(i-20)+"px; text-align:center; display:block; margin-left:10px; margin-top:10px"}).innerHTML=a}var r=i-30,l=300;isMobil?l=220:i<200?l=200:i<300?l=220:i<400?l=240:i<500?l=260:i<600&&(l=280),this._canvas=addNewElement(this.chartDiv,"canvas",{id:"chart_"+e+"_canvas",width:r,height:l,style:"margin: 15px 17px 3px 13px;"}),null!=s||void 0===s?"number"==s?this.axisXType="number":("time"==s||logger.warn(`Unknow value axisXType=${s}. Set default "time".`),this.axisXType="time"):this.axisXType="time",null==h?this.ifDataMissing="connect":"connect"==h||"noline"==h||"skip"==h?this.ifDataMissing=h:(logger.warn(`Unknow value ifDataMissing=${h}. Set default "connect".`),this.ifDataMissing="connect"),this._canvas.dataset.axisXType=this.axisXType,this._canvas.dataset.ifDataMissing=this.ifDataMissing,this._canvas.dataset.chartId=e.toString(),this._context=this._canvas.getContext("2d"),this._context.translate(.5,.5),isMobil||(this._canvas.addEventListener("mouseout",function(t){var e=document.getElementById("chart_"+this.dataset.chartId+"_livedata");null!=e&&(e.innerText="-")}),this._canvas.addEventListener("mousemove",function(t){var e=document.getElementById("chart_"+this.dataset.chartId+"_livedata");if(null!=e)if(this.height-t.offsetY<this.dataset.paddingBottom||t.offsetX<this.dataset.paddingLeft)e.innerText="-";else{var i=this.dataset.maxVal-t.offsetY/parseFloat(this.dataset.coefVal);if(isNaN(i))e.innerText="-";else if(i=i<100?i.toFixed(2):i<200?i.toFixed(1):Math.round(i),"time"==this.dataset.axisXType){var a=parseInt(this.dataset.minTs)+Math.round((t.offsetX-parseInt(this.dataset.paddingLeft))/parseFloat(this.dataset.coefTs));if(isNaN(a))return void(e.innerText="-");a=new Date(1e3*a).separate(),e.innerHTML="Date <b>"+a.mday+"."+a.month+"."+a.year+"</b> Time <b>"+a.hour+":"+a.min+"</b> Value <b>"+i+"</b>"}else{var n=parseFloat(this.dataset.minTs)+Math.round((t.offsetX-parseInt(this.dataset.paddingLeft))/parseFloat(this.dataset.coefTs));e.innerHTML="Axis-X <b>"+n+"</b> Axis-Y <b>"+i+"</b>"}}}),addNewElement(this.chartDiv,"div",{class:"chart-live-data, nowrap",id:"chart_"+e+"_livedata",style:"margin-left: 12px; margin-right: 12px; margin-bottom: 4px; max-width:95%;",innerText:"-"})),this._legendDiv=addNewElement(this.chartDiv,"div",{class:"chart-legend",id:"chart_"+e+"_legend"}),this.chartId=e,this.lines=[],this._minTs=Number.MAX_SAFE_INTEGER,this._maxTs=0,this._minValRaw=1/0,this._maxValRaw=-1/0,this._minVal=1/0,this._maxVal=-1/0,this._axeYLabelStep=null,this._axeYLabelHeightDefault=30,this._axeXLabelWidthDefault=80,this._coefX=null,this._coefY=null,this._padding={left:50,bottom:35},this.avgStep=NaN}addLine(t){if(null==t.values)return logger.error("Function LineChart.newLine(). DataString is null."),!1;if(!isString(t.values))return logger.error("Function LineChart.newLine(). DataString is not a string."),!1;var e=this._createLine(t);return null==e?(logger.error("Function LineChart.newLine(). Function _createLine() return null."),!1):(this._createLegendItem(e,t),this.lines.push(e),!0)}_createLegendItem(t,e){t.legend=addNewElement(this._legendDiv,"div",{class:"chart-legend-item nowrap",id:`chart_${this.chartId}_legend_${e.par_id}`,style:`cursor: pointer; max-width:${this.chartDiv.clientWidth-20}px;`}),addNewElement(t.legend,"span",{class:"chart-legend-color",style:`background-color:${t.color}; color:${t.color};`,innerHTML:"--"}),t.legend.appendChild(document.createTextNode(t.objName+" / "+t.parName)),t.legend.addEventListener("click",function(e){var i=e.currentTarget.querySelector(".chart-legend-color");null!=i&&(0==t.hidden?(t.hidden=!0,i.style.backgroundColor="white"):(t.hidden=!1,i.style.backgroundColor=t.color),e.currentTarget.chart.draw())}),t.legend.chart=this}updateLines(t){if(null==t)return logger.error("Function LineChart.updateLines(). Parameter lines is null."),!1;if(!Array.isArray(t))return logger.error("Function LineChart.updateLines(). Parameter lines is not a array."),!1;if(null!=this._legendDiv)for(;null!=this._legendDiv.firstChild;)this._legendDiv.removeChild(this._legendDiv.firstChild);this.lines=[],this._minTs=Number.MAX_SAFE_INTEGER,this._maxTs=0,this._minValRaw=1/0,this._maxValRaw=-1/0,this._minVal=1/0,this._maxVal=-1/0,this._axeYLabelStep=null,this._coefX=null,this._coefY=null;for(var e=0;e<t.length;e++){var i=this._createLine(t[e]);null!=i&&(this._createLegendItem(i,t[e]),this.lines.push(i))}return this.draw(),!0}_createLine(t){var e=new SingleLine(t,this.colors[this.lines.length]);if(null==t.par_id&&(t.par_id=this.lines.length),0==t.values.length)return e;for(var i=t.values.split(";"),a=i.length,n=0;n<a;++n){var s=i[n].split("/");if(""!=s[0])if(isNaN(s[0]))logger.warn("LineChart._createLine(). Item "+n+'. Element for axis-x is not a number "'+s[0]+'".');else{var h={ts:null,val:null};"number"==this.axisXType?h.ts=parseFloat(s[0]):h.ts=parseInt(s[0]),h.val=parseFloat(s[1]),e.real.push(h),isNaN(h.val)||(h.val<this._minValRaw&&(this._minValRaw=h.val),h.val>this._maxValRaw&&(this._maxValRaw=h.val)),h.ts<this._minTs&&(this._minTs=h.ts),h.ts>this._maxTs&&(this._maxTs=h.ts)}else logger.warn("LineChart._createLine(). Item "+n+". Element for axis-x is empty.")}if(0==e.real.length)return e;e.isEmpty=!1,this._minValRaw===1/0&&(this._minValRaw=0,this._maxValRaw=1);var r=this._getLabelWidth(this._minValRaw),l=this._getLabelWidth(this._maxValRaw);return this._padding.left=r<l?Math.round(l)+23:Math.round(r)+23,e}clear(){this._context.clearRect(0,0,this._canvas.width,this._canvas.height)}draw(){if(this._context.clearRect(0,0,this._canvas.width,this._canvas.height),!this.isEmpty()){var t=this._maxValRaw-this._minValRaw;if(0==t)this._minVal=this._minValRaw-1,this._maxVal=this._maxValRaw+1;else{var e=.1*t;this._minVal=this._minValRaw-e,this._maxVal=this._maxValRaw+e}this._coefX=this._getCoefX(),this._coefY=this._getCoefY(),"time"==this.axisXType?this._drawAxeXTime():this._drawAxeXNum(),this._drawAxeY();for(var i=0;i<this.lines.length;i++)this._drawLine(i);this._canvas.dataset.minTs=this._minTs.toString(),this._canvas.dataset.coefTs=this._coefX.toString(),this._canvas.dataset.maxVal=this._maxVal.toString(),this._canvas.dataset.coefVal=this._coefY.toString(),this._canvas.dataset.paddingLeft=this._padding.left.toString(),this._canvas.dataset.paddingBottom=this._padding.bottom.toString()}}_getCoefX(){return(this._canvas.width-this._padding.left)/(this._maxTs-this._minTs)}_getCoefY(){return(this._canvas.height-this._padding.bottom)/(this._maxVal-this._minVal)}_getLabelWidth(t){var e=Math.abs(t)<10?t.toFixed(2):Math.round(t).toString();return this._context.measureText(e).width}resize(t,e){this._canvas.width=this._canvas.width+t,this._canvas.height=this._canvas.height+e,this._context.translate(.5,.5),this.draw()}_drawAxeXTime(){var t;this._drawAxeXBasic();var e=Math.round(this._axeXLabelWidthDefault/this._coefX);if(e<=1)e=1;else{t=this.stepsX.length-1;for(var i=0;i<t;i++)if(e>this.stepsX[i]&&e<this.stepsX[i+1]){e=this.stepsX[i];break}}for(var a=e>=2592e3?this._getBeginOfYearFromUnixTs(this._minTs):this._getBeginOfDayFromUnixTs(this._minTs);a<this._minTs;)a+=e;for(var n,s,h=[];a<this._maxTs;)n=this._convertTs2PosX(a),s=this._formatTsForLabel(a,this._maxTs-this._minTs),h.push({X:n,str:s}),a+=e;this._context.beginPath(),this._context.strokeStyle="#e6e6e6";var r=Math.round(e*this._coefX/2),l=this._canvas.height-this._padding.bottom;t=h.length;for(i=0;i<t;i++)this._context.moveTo(h[i].X,0),this._context.lineTo(h[i].X,l+10),h[i].X-r>this._padding.left+2&&(this._context.moveTo(h[i].X-r,0),this._context.lineTo(h[i].X-r,l));for(null!=h[i-1]&&h[i-1].X+r<=this._canvas.width&&(this._context.moveTo(h[i-1].X+r,0),this._context.lineTo(h[i-1].X+r,l)),this._context.stroke(),this._context.font="12px arial",t=h.length,i=0;i<t;i++)this._context.fillText(h[i].str.hm,h[i].X-17,l+17),(0==i||h[i].str.dm!=h[i-1].str.dm)&&this._context.fillText(h[i].str.dm,h[i].X-17,l+32);this._context.closePath()}_drawAxeXNum(){let t;this._drawAxeXBasic();let e=this._axeXLabelWidthDefault/this._coefX;if(e=this._getNextPreferedNumber(e),null==e||e<=0)return;let i=this._getNextPreferedNumber(this._minTs);null==i&&(i=this._minTs);let a=Math.max(0,Math.ceil(-Math.log10(e)));i=roundTo(i,a);let n=[];for(;i<this._maxTs;)n.push({X:this._convertTs2PosX(i),str:i}),i=roundTo(i+e,a);this._context.beginPath(),this._context.strokeStyle="#e6e6e6";let s=Math.round(e*this._coefX/2),h=this._canvas.height-this._padding.bottom;t=n.length;for(let e=0;e<t;e++)this._context.moveTo(n[e].X,0),this._context.lineTo(n[e].X,h+10),n[e].X-s>this._padding.left+2&&(this._context.moveTo(n[e].X-s,0),this._context.lineTo(n[e].X-s,h));null!=n[n.length-1]&&n[n.length-1].X+s<=this._canvas.width&&(this._context.moveTo(n[n.length-1].X+s,0),this._context.lineTo(n[n.length-1].X+s,h)),this._context.stroke(),this._context.font="12px arial",t=n.length;for(let e=0;e<t;e++)this._context.fillText(n[e].str,n[e].X,h+20);this._context.closePath()}_drawAxeXBasic(){this._context.strokeStyle=this.colorDefault,this._context.lineWidth=1,this._context.beginPath(),this._context.moveTo(this._padding.left,this._canvas.height-this._padding.bottom),this._context.lineTo(this._canvas.width,this._canvas.height-this._padding.bottom),this._context.stroke()}_drawAxeY(){if(null==this._coefX||null==this._coefY)return;var t,e=(this._canvas.height-this._padding.bottom)/this._axeYLabelHeightDefault;this._axeYLabelStep=(this._maxVal-this._minVal)/e,this._axeYLabelStep=this._getNextPreferedNumber(this._axeYLabelStep);var i=0;if(this._minVal<0)for(;i>this._minVal&&!(i<=this._minVal);)i-=this._axeYLabelStep;else if(this._minVal>0)for(;i<this._maxVal&&!(i>=this._minVal);)i+=this._axeYLabelStep;var a=this._canvas.height-this._padding.bottom,n=[];let s=0;for(var h,r;s<33&&(r=i+this._axeYLabelStep*s,(this._axeYLabelStep<1||2.5==this._axeYLabelStep)&&(r=r.toFixed(2)),!((h=this._convertVal2PosY(r))<0));){if(h<a){var l={value:r,Y:h};n.push(l)}s++}if(0!=n.length){var o;for(this._context.lineWidth=1,this._context.beginPath(),this._context.strokeStyle=this.colorDefault,this._context.moveTo(this._padding.left,0),this._context.lineTo(this._padding.left,this._canvas.height-this._padding.bottom),this._context.stroke(),this._context.beginPath(),this._context.strokeStyle="#e6e6e6",t=n.length,s=0;s<t;s++)(o=n[s].Y+Math.round(this._coefY*this._axeYLabelStep/2))<this._canvas.height-this._padding.bottom&&(this._context.moveTo(this._padding.left,o),this._context.lineTo(this._canvas.width,o)),n[s].Y>=this._canvas.height-this._padding.bottom||(this._context.moveTo(this._padding.left,n[s].Y),this._context.lineTo(this._canvas.width,n[s].Y));for((o=n[n.length-1].Y-Math.round(this._coefY*this._axeYLabelStep/2))>0&&(this._context.moveTo(this._padding.left,o),this._context.lineTo(this._canvas.width,o)),this._context.stroke(),this._context.font="12px arial",this._context.strokeStyle=this.colorDefault,t=n.length,s=0;s<t;s++)this._context.fillText(n[s].value,0,n[s].Y+10)}}_drawLine(t){var e=this.lines[t];if(null!=e){if(1!=e.isEmpty&&0!=e.real.length&&!e.hidden){var i,a=[],n=-1,s=[],h=[];if(!isNaN(this.avgStep)){for(var r=this._getBeginOfDayFromUnixTs(e.real[0].ts);r<e.real[0].ts;)r+=this.avgStep;i=e.real.length;for(var l=0;l<i;l++)if(e.real[l].ts<r)s.push(e.real[l].val);else{for(var o=0;e.real[l].ts>r+this.avgStep;)if(r+=this.avgStep,++o>1e3)return void logger.warn("drawLine(). Can't calculate average values for this line. "+new Date(1e3*e.real[l].ts).formatISOLocal()+"/"+e.real[l].val);var d={ts:r,val:getAvgValue(s,2)};h.push(d),(s=[]).push(e.real[l].val),r+=this.avgStep}if(s.length>0){d={ts:r,val:getAvgValue(s,2)};h.push(d)}}s=[],0==h.length&&(h=e.real),i=h.length;for(var _=0;_<i;_++){(d={X:NaN,Y:NaN}).X=this._convertTs2PosX(h[_].ts),isNaN(h[_].val)||(d.Y=this._convertVal2PosY(h[_].val)),d.X!=n?(n=d.X,s.length>0&&_>0&&(s.push(a[a.length-1].Y),a[a.length-1].Y=getAvgValue(s,2),s=[]),a.push(d)):s.push(d.Y)}for(this._context.strokeStyle=this.colors[t],this._context.lineWidth=1,this._context.beginPath(),i=a.length,_=0;_<i;_++)if(!isNaN(a[_].Y)){this._context.moveTo(a[_].X,a[_].Y),_++;break}for(;_<i;)if(isNaN(a[_].Y))if("noline"!=this.ifDataMissing)for(;_<a.length&&isNaN(a[_].Y);)_++;else for(this._context.stroke(),this._context.beginPath();_<a.length&&isNaN(a[_].Y);)_++;else this._context.lineTo(a[_].X,a[_].Y),_++;this._context.stroke()}}else logger.error("Function LineChart.drawLine(lineId). The line with ID "+t+" not found!")}_getNextPreferedNumber(t){if(0==t)return 0;let e=t<0?-1:1;t=Math.abs(t);let i,a,n=[1e-9,2e-9,5e-9,1e-8],s=1;for(;s<1e18;){for(var h=0;h<n.length-1;h++)if(i=n[h]*s,a=n[h+1]*s,i<=t&&t<=a)return e>0?a:-i;s*=10}return null}isEmpty(){for(var t=!0,e=0;e<this.lines.length;e++)this.lines[e].isEmpty||(t=!1);return t}_convertTs2PosX(t){return this._canvas.width-Math.round((this._maxTs-t)*this._coefX)}_convertVal2PosY(t){return Math.round((this._maxVal-t)*this._coefY)}_formatTsForLabel(t,e){let i=new Date(1e3*t);e/=86400;let a=i.getFullYear(),n=i.getMonth()+1;n<10&&(n="0"+n.toString());let s=i.getDate();parseInt(s)<10&&(s="0"+s.toString());let h=i.getHours();parseInt(h)<10&&(h="0"+h);let r=i.getMinutes();parseInt(r)<10&&(r="0"+r.toString());let l={};return l=e<3?{dm:s+"."+n,hm:h+":"+r}:e>=3&&e<180?{dm:a,hm:s+"."+n}:{dm:a,hm:" "+n},l}_getBeginOfDayFromUnixTs(t){var e=new Date(1e3*t);return(e=new Date(e.getFullYear(),e.getMonth(),e.getDate())).getTime()/1e3}_getBeginOfYearFromUnixTs(t){var e=new Date(1e3*t);return(e=new Date(e.getFullYear(),0,1)).getTime()/1e3}colors=["#0044CC","#008000","#FF8533","#6A6A6A","#C71585","#8B4513","#1E90FF","#FF4500","#00FF00","#8A2BE2"];colorDefault="#657585";stepsX=[1,2,5,10,20,30,60,120,300,600,900,1200,1800,3600,7200,14400,21600,43200,86400,172800,259200,345600,432e3,604800,864e3,1296e3,1728e3,2592e3,5184e3,7776e3,10368e3,15552e3,31536e3,63072e3,15768e4,31536e4]}class SingleLine{constructor(t,e){this.parId=t.par_id,this.parName=null!=t.par_name?t.par_name:"",this.objName=null!=t.obj_name?t.obj_name:"",this.real=[],this.isEmpty=!0,this.hidden=!1,this.color=null==e?"black":e,this.legend=null}}class LineData{constructor(t,e,i,a){this.obj_name=t,this.par_name=e,this.par_id=i,this.values=a}}
|
|
@@ -69,11 +69,11 @@ timestamp,open,high,low,close,volume
|
|
|
69
69
|
2019-09-25,137.5000,139.9580,136.0300,139.3600,22544054
|
|
70
70
|
2019-09-24,140.3600,140.6900,136.8800,137.3800,30016670
|
|
71
71
|
2019-09-23,139.2300,139.6300,138.4400,139.1400,17408374
|
|
72
|
-
2019-09-20,141.0100,
|
|
73
|
-
2019-09-19,
|
|
74
|
-
2019-09-18,
|
|
75
|
-
2019-09-17,136.9600,137.5200,
|
|
76
|
-
2019-09-16,135.8300,136.7000,
|
|
72
|
+
2019-09-20,141.0100,141.6500,138.2500,139.4400,40040766
|
|
73
|
+
2019-09-19,140.3000,142.3700,140.0736,141.0700,36095413
|
|
74
|
+
2019-09-18,137.3600,138.6700,136.5299,138.5200,24473386
|
|
75
|
+
2019-09-17,136.9600,137.5200,136.4250,137.3900,17976285
|
|
76
|
+
2019-09-16,135.8300,136.7000,135.6600,136.3300,16731440
|
|
77
77
|
2019-09-13,137.7800,138.0600,136.5700,137.3200,23363057
|
|
78
78
|
2019-09-12,137.8500,138.4200,136.8700,137.5200,27009981
|
|
79
79
|
2019-09-11,135.9100,136.2700,135.0900,136.1200,24726117
|