-
Notifications
You must be signed in to change notification settings - Fork 46
/
px-vis-behavior-chart.html
3518 lines (3022 loc) · 97.9 KB
/
px-vis-behavior-chart.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!--
Copyright (c) 2018, General Electric
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<link rel="import" href="px-vis-behavior-common.html" />
<link rel="import" href="px-vis-behavior-d3.html" />
<link rel="import" href="px-vis-behavior-datetime.html" />
<link rel="import" href="../iron-resizable-behavior/iron-resizable-behavior.html">
<script>
var PxVisBehaviorChart = window.PxVisBehaviorChart = (window.PxVisBehaviorChart || {});
/*
Name:
PxVisBehaviorChart.searchToolbar
Description:
Behavior providing a convenience function for searching for a toolbar in a chart
@polymerBehavior PxVisBehaviorChart.searchToolbar
*/
PxVisBehaviorChart.searchToolbar = {
/**
* Convenience method for searching for a toolbar in a chart.
*/
getToolbar: function() {
return this.$$('px-vis-toolbar');
}
};
/*
Name:
PxVisBehaviorChart.chartCommonMethods
Description:
Polymer behavior that provides some general methods used accross charts
Dependencies:
- D3.js
@polymerBehavior PxVisBehaviorChart.chartCommonMethods
*/
PxVisBehaviorChart.chartCommonMethods = [{
/**
* Goes through an array of objects and gathers all unique keys. Returns a list of keys
*
* Expects and array of objects
*
* Returns an array of strings
*/
_returnAllKeys: function(d) {
var o = {},
k;
for(var i = 0; i < d.length; i++) {
k = Object.keys(d[i]);
for(var j = 0; j < k.length; j++) {
o[k[j]] = true;
}
}
return Object.keys(o)
},
}, PxColorsBehavior.getSeriesColors, PxVisBehaviorChart.searchToolbar];
/*
Name:
PxVisBehaviorChart.chartCommon
Description:
Polymer behavior that provides the basic listeners and methods for charts built with px-vis.
Dependencies:
- D3.js
@polymerBehavior PxVisBehaviorChart.chartCommon
*/
PxVisBehaviorChart.chartCommon = [{
properties: {
/**
* A configuration file to associate series order, name, type, and colors.
*
* Association of name, type, and seriesNumber should be developer set. Color and axis are optional.
*
*```
* {
* "seriesKey": { //seriesKey is a unique identifier for the configuration
* "type": "line", //line or scatter or both
* "priority": 0, //relative priority is used to decide which series draw on top of each other. priority 0 => smaller priority. 2 draws over 1, which itself draws over 0, etc.. CANVAS ONLY
* "markerSymbol": "diamond" //if using scatter different markerSymbol can be used. See "markerSymbol" in px-vis-scatter
* "markerSize": "64" //if using scatter allows to change the size of markers
* "markerScale": "2" //if using scatter allows to scale the size of markers
* "markerFillOpacity": "0.5" //if using scatter allows to specify the opacity of the inside of the marker
* "markerStrokeOpacity": "1" //if using scatter allows to specify the opacity of the outside of the marker
* "strokeWidth": "1" //if using line, allows you to specify the thickness of the line
* "mutedOpacity": "0.3" //opacity value to use when muting a serie
* "name": "My Series", //human readable name
* "x": "x", //index or key name for independent variable
* "y": "y", //index or key name for dependent variable
* "xAxisUnit": "Volt" //Unit to be used for the X axis. Can be ignored if x axis is time based
* "yAxisUnit": "Oranges" //unit to be used for the Y axis.
* "xMin": 0, // minimum x value
* "xMax": 100, //maximum x value
* "yMin": 5, //minimum y value
* "yMax": 50, //maximum y value
* "hideInRegister": true, //dont show in the register
* "color": "rgb(0,0,0)", //color you want for the series
* "negativeColor": "rgb(255,255,255)", //color you want negative values of the series to be (not all charts)
* "interpolationFunction": Px.d3.curveBasis, //The line interpretor you want to use. See property 'interpolationFunction'
* "axis": {
* "id": "AXIS_ID" //a unique identifier
* "side": "left" //the side that you want the axis to draw on, `left` or `right`
* "number": 1 //the order of the axis on each side
* }
* }
* }
*```
*/
seriesConfig: {
type: Object,
value: function() {
return {}
}
},
/**
* A default configuration file. It fills in the missing parts of seriesConfig. Any options from seriesConfig can be specified in the defaultSeriesConfig and will be automatically used if not defined in the seriesConfig
*
* Default:
*
* ```
* {
* "type": "line",
* "x": 'x',
* "axis": {
* "id": "defaultAxis",
* "side": "left",
* "number": 1
* }}
* ```
*/
_defaultSeriesConfig: {
type: Object,
value: function() {
return {
"type": "line",
"x": 'x',
"axis": {
"id": "defaultAxis",
"side": "left",
"number": 1
}
}
}
},
/**
* Overwrites to the default configuration file. The defaultSeriesConfig is used to fill in the missing parts of seriesConfig. Any option from seriesConfig can be specified in the defaultSeriesConfig and will be automatically used if not defined in the seriesConfig
*
*/
defaultSeriesConfig: {
type: Object,
value: function() { return {}; },
observer: '_updateDSC'
},
/**
* A boolean flag on whether to include all the series in the data.
* - `false`: only series defined in the seriesConfig file will be drawn
* - `true`: All series in the dataset will be drawn. Defaults will be used for the seriesConfig. If this is used do not specify a seriesConfig
*/
includeAllSeries: {
type: Boolean,
value: false
},
/**
* Representes the keys avaiable in completeSeriesConfig. It's being set
* before completeSeriesConfig is set
*/
_seriesKeys: {
type: Array
},
preventCompleteSeriesConfigCalc: {
type: Boolean,
value: false
}
},
observers: [
'_setCompleteSeriesConfig(_defaultSeriesConfig.*,chartData.*,seriesConfig.*,seriesColorList.*)'
],
/**
* Calcs the extents of the charts
*/
_calcChartExts: function(mins,maxes,axis) {
if(this._isOrdinalType(this[axis + 'AxisType'])) {
return [];
}
//make sure we have at lease one valid number
mins.push(Infinity);
maxes.push(-Infinity);
return [ Math.min.apply(null, mins) , Math.max.apply(null, maxes) ];
},
/**
* Creates the real series confit object based on the default settings, the dev defined series config, and the includeAllSeries flag.
*
*/
_setCompleteSeriesConfig: function() {
if(this.hasUndefinedArguments(arguments)) {
return;
}
if(this._doesObjHaveValues(this._defaultSeriesConfig) && this._doesObjHaveValues(this.chartData) && this._doesObjHaveValues(this.seriesColorList) && !this.preventCompleteSeriesConfigCalc) {
// FUTURE TODO refactor: use MAPs and SETs instead of Objects when IE has support / is no longer supported by us
// We could use d3 sets and maps... worth it?
var fullConfig = (this.seriesConfig) ? this.clone(this.seriesConfig) : {},
k = Object.keys(fullConfig),
kLen = k.length,
allYs = (this.includeAllSeries) ? this._returnAllKeys(this.chartData) : [],
// create a new object with the y keys as config keys
objYs = allYs.reduce(function(obj, item) {
obj[item] = {};
return obj;
}, {}),
defaultConfigProps = Object.keys(this._defaultSeriesConfig),
xMins = [],
xMaxes = [],
yMins = [],
yMaxes = [],
missingYs,
x,
isUpdate = this.completeSeriesConfig ? true : false,
addedSeriesKeys = [],
removedSeriesKeys = [],
updatedSeriesKeys = [],
extsObj = {},
skipProperties = ['xMin','xMax','yMin','yMax'];
// First, fill in the series specified in seriesConfig.
for(var i = 0; i < kLen; i++) {
if(!fullConfig[k[i]].hasOwnProperty('y')) {
console.warn("(✿◠‿◠) Configuration " + k[i] + " does not have a y-value associated with it. Falling back to ID (✿◠‿◠)");
fullConfig[k[i]]['y'] = k[i];
}
if(!fullConfig[k[i]].hasOwnProperty('x')) {
if(!this.defaultSeriesConfig['x']) {
console.warn("(。◕‿◕。) Configuration " + k[i] + " does not have a x-value associated with it. Falling back to default (。◕‿◕。)");
}
fullConfig[k[i]]['x'] = this._defaultSeriesConfig['x'];
}
if(!fullConfig[k[i]]['name']) {
fullConfig[k[i]]['name'] = k[i];
}
if(!fullConfig[k[i]]['color'] && !this._dontCalcColors) {
fullConfig[k[i]]['color'] = this._getColor(i);
}
//copy values from default config if needed
for(var j = 0; j < defaultConfigProps.length; j++) {
var property = defaultConfigProps[j];
//if we dont already have the property, the default exists, and we want to copy the property
if(typeof fullConfig[k[i]][property] === 'undefined' && typeof this._defaultSeriesConfig[property] !== 'undefined' && skipProperties.indexOf(property) === -1) {
fullConfig[k[i]][property] = this._defaultSeriesConfig[property];
}
}
if(fullConfig[k[i]]['xMin']) {
xMins.push(fullConfig[k[i]]['xMin']);
}
if(fullConfig[k[i]]['xMax']) {
xMaxes.push(fullConfig[k[i]]['xMax']);
}
if(fullConfig[k[i]]['yMin']) {
yMins.push(fullConfig[k[i]]['yMin']);
}
if(fullConfig[k[i]]['yMax']) {
yMaxes.push(fullConfig[k[i]]['yMax']);
}
// delete this y / key from objYs if includeAllSeries is on so we have a unique set
delete objYs[ fullConfig[k[i]]['y'] ];
}
// delete the 'x' key from our all y keys obj
//figure out what x is, either a config value (assuming all x are the same) or the default
if(this.includeAllSeries) {
x = this.defaultSeriesConfig['x'] ? this.defaultSeriesConfig['x'] : this._defaultSeriesConfig['x'];
} else {
x = (k.length > 0) ? fullConfig[k[0]]['x'] : this._defaultSeriesConfig['x'];
}
delete objYs [x];
// create a new set of whatever Ys are left so we can iterate over it
missingYs = Object.keys(objYs);
// add the missing keys to our configuration, use y as the config key by default
for(var i = 0; i < missingYs.length; i++) {
// copy all vals from the default
objYs[ missingYs[i] ] = JSON.parse(JSON.stringify(this._defaultSeriesConfig));
//overwrite specific keys
objYs[ missingYs[i] ]['name'] = missingYs[i];
objYs[ missingYs[i] ]['x'] = x;
objYs[ missingYs[i] ]['y'] = missingYs[i];
if(!this._dontCalcColors) {
objYs[ missingYs[i] ]['color'] = this._getColor(kLen + i);
}
// copy the obj to our config
fullConfig[ missingYs[i] ] = objYs[ missingYs[i] ];
}
if(this.range) {
var min = Number(Px.moment(this.range.from, Px.moment.ISO_8601).format('x')),
max = Number(Px.moment(this.range.to, Px.moment.ISO_8601).format('x'));
extsObj["x"] = [min,max];
}
if(!extsObj.x) {
extsObj['x'] = this._calcChartExts(xMins,xMaxes,'x');
}
if(!extsObj.y) {
extsObj['y'] = this._calcChartExts(yMins,yMaxes,'y');
}
//if this is an update bof series config find out additions/deletions
var deletion = false,
addition = false,
mutedKeys = [];
if(isUpdate) {
var currKeys = Object.keys(this.completeSeriesConfig),
newKeys = Object.keys(fullConfig);
//process updates and additions
for(var i=0; i<newKeys.length; i++) {
if(currKeys.includes(newKeys[i])) {
updatedSeriesKeys.push(newKeys[i]);
} else {
addedSeriesKeys.push(newKeys[i]);
addition = true;
}
}
//process deletions
for(var i=0; i<currKeys.length; i++) {
if(!newKeys.includes(currKeys[i])) {
removedSeriesKeys.push(currKeys[i]);
deletion = true;
}
}
}
if(deletion) {
// check mutedSeries
if(this.mutedSeries) {
for(var i = 0; i < removedSeriesKeys.length; i++) {
//if it is currently muted, unmute it.
if(this.mutedSeries[removedSeriesKeys[i]]) {
this.muteUnmuteSeries(removedSeriesKeys[i]);
mutedKeys.push(removedSeriesKeys[i]);
} else if(typeof this.mutedSeries[removedSeriesKeys[i]] === 'boolean') {
mutedKeys.push(removedSeriesKeys[i]);
}
}
}
//we need to flush before setting completeSeriesConfig for deletion
//but need setting completeSeriesConfig before flushing for additions.
//Process the deletions first and we will process the addtions after setting
//completeseriesconfig (if needed)
this.set('_seriesKeys', updatedSeriesKeys);
//make sure we flush for all the components dom-repeating over _seriesKeys:
//if a serie needs to be removed this should be processed before we pass
//the new completeSeriesConfig or observers will run on the not-yet deleted serie
Polymer.dom.flush();
//clear out mutedSeries of the deleted stuff
if(mutedKeys.length > 0) {
for(var i = 0; i < mutedKeys.length; i++) {
delete this.mutedSeries[mutedKeys[i]];
}
}
} else {
//update or addition
this.set('_seriesKeys', Object.keys(fullConfig));
}
this.fire('px-vis-data-extents', { 'dataVar': 'dataExtents', 'data': extsObj, 'method':'set' });
this.set('dataExtents', extsObj);
this.fire('px-vis-complete-series-config', { 'dataVar': 'completeSeriesConfig', 'data': fullConfig, 'method':'set' });
this.set('completeSeriesConfig', fullConfig);
if(deletion && addition) {
//we have processed updates and deleton, now need to process the additions
//now that we have the new completeSeriesConfig process the additions
this.set('_seriesKeys', Object.keys(fullConfig));
}
} else if(this.chartData && this.chartData.length === 0) {
this.set('_seriesKeys', []);
Polymer.dom.flush();
}
},
/**
* Helper function for the register. Returns true if the side register should exist
*
*/
_sideRegister:function(location) {
return location === 'side' || location === 'both';
},
/**
* Helper function for the register. Returns true if the top register should exist
*
*/
_topRegister:function(location) {
return location === 'top' || location === 'both';
},
/**
* Helper function for the line series. Returns true if the series is a line
*
*/
_chartTypeLine: function(key,obj) {
if(this.hasUndefinedArguments(arguments)) {
return;
}
return obj && obj[key] && (obj[key]['type'] === 'line' || obj[key]['type'] === 'both');
},
/**
* Helper function for the line series. Returns true if the series is a line
*
*/
_chartTypeScatter: function(key,obj) {
if(this.hasUndefinedArguments(arguments)) {
return;
}
return obj && obj[key] && (obj[key]['type'] === 'scatter' || obj[key]['type'] === 'both');
},
/**
* returns the keys of an object
*
*/
_returnKeys: function(obj) {
return Object.keys(obj);
},
_updateDSC: function(dsc) {
if(dsc === undefined) {
return;
}
var k = Object.keys(this.defaultSeriesConfig),
val;
for(var i = 0; i < k.length; i++) {
val = this.defaultSeriesConfig[k[i]];
this._defaultSeriesConfig[k[i]] = val;
}
this.notifyPath('_defaultSeriesConfig');
}
},
PxVisBehavior.observerCheck,
PxColorsBehavior.dataVisColors ,
PxVisBehaviorChart.chartCommonMethods,
PxVisBehavior.commonMethods,
PxVisBehavior.completeSeriesConfig,
PxVisBehavior.axisTypes,
PxVisBehavior.muteUnmuteSeries,
PxVisBehavior.scaleTypeCheck
];
/*
Name:
PxVisBehaviorChart.chartId
Description:
Polymer behavior that allows the chart to have a unique ID
@polymerBehavior PxVisBehaviorChart.chartId
*/
PxVisBehaviorChart.chartId = [{
properties: {
/**
* Internal unique ID
*/
chartId: {
type: String
},
}
}, PxVisBehavior.uniqueIds];
/*
Name:
PxVisBehaviorChart.webWorkerSynchronization
Description:
Polymer behavior that allows the chart to keep its data synced in a web worker
@polymerBehavior PxVisBehaviorChart.webWorkerSynchronization
*/
PxVisBehaviorChart.webWorkerSynchronization = [{
properties: {
_wwSyncRequestDataDeletion: {
type: Boolean,
value: false
},
_wwSyncDataDeleted: {
type: Boolean,
value: false
},
/**
* After detaching the chart time after which we will delete
* the synced data of the chart from the webworker. If the
* chart is re-attached in the meantime the deletion will
* be canceled to avoid a re-sync
*/
_wwSyncDataDeletionTimeout: {
type: Number,
value: 1500
},
/**
* Name of the property to be kept in sync. Usually chartData but can
* be overriden for a filtered dataset instead for example
*/
_wwSyncDataPropName: {
type: String,
value: 'chartData'
}
},
ready: function() {
this.chartId = this.generateRandomID('chart');
},
attached: function() {
if(!this.preventWebWorkerSynchronization) {
this._wwSyncRequestDataDeletion = false;
//request a data update if we have been detached, data has
//been deleted and then re attached
if(this.chartData && this._wwSyncDataDeleted) {
this._keepDataInSync();
}
}
},
detached: function() {
if(!this.preventWebWorkerSynchronization) {
this._wwSyncRequestDataDeletion = true;
window.setTimeout(function() {
//only process if we haven't been re attached
if(this._wwSyncRequestDataDeletion) {
Px.vis.scheduler.process({
'action': 'unregisterChart',
'originatorName': this.nodeName,
'chartId': this.chartId,
'data': null});
//async, the data hasn't been actually deleted yet but we
//don't have a way to cancel it anymore and an update
//request would always queue after this request
this._wwSyncDataDeleted = true;
//do we need this?
//this.set('wwDataSyncCounter', 0);
}
}.bind(this), this._wwSyncDataDeletionTimeout);
}
},
_keepDataInSync: function() {
if(this.hasUndefinedArguments(arguments)) {
return;
}
if(!this.preventWebWorkerSynchronization && this[this._wwSyncDataPropName]) {
this._wwSyncDataDeleted = false;
Px.vis.scheduler.process({
'action': 'updateData',
'originatorName': this.nodeName,
'chartId': this.chartId,
'data': {'chartData': this[this._wwSyncDataPropName]}});
this.set('wwDataSyncCounter', this.wwDataSyncCounter ? this.wwDataSyncCounter+1 : 1);
}
}
}, PxVisBehavior.observerCheck, PxVisBehavior.dataset, PxVisBehavior.preventWebWorkerSynchronization, PxVisBehavior.wwDataSyncCounter];
/*
Name:
PxVisBehaviorChart.saveImage
Description:
Polymer behavior that allows the chart to return an image of itself based on
its canvas and/or SVG
@polymerBehavior PxVisBehaviorChart.saveImage
*/
PxVisBehaviorChart.saveImage = [{
/**
* Takes a graphic "snapshot" of the component and pass results through a callback:
* - a canvas containing the graphical snapshot
* - a png base 64 data uri
*
* callback object:
* {
* canvas: theCanvasObject
* image: "data:image/png;base64;iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACN..."
* }
*
* the data uri can be used to save the image and the canvas object to do
* further processing, such as combining different elements snapshot into one image
*
*/
getImage: function(callback, renderLegend) {
//create a new canvas to render both the canvas and svg elements on it
var canvas = document.createElement('canvas'),
context,
result,
svgData,
elementsToRender = [],
canvasKeys = Object.keys(this.canvasLayers),
//try to fetch extendeWwidth, then smaller side, then width
drawingWidth = this._extendedWidth ? this._extendedWidth : (this._smallerSide ? this._smallerSide : this.width),
drawingHeight = this._smallerSide ? this._smallerSide : this.height;
canvas.width = drawingWidth + (renderLegend ? this._getRegisterWidth(drawingWidth, drawingHeight) : 0);
canvas.height = drawingHeight;
context = canvas.getContext('2d');
//draw in the same order as px-vis-svg-canvas....
//true = svg, false = canvas
elementsToRender.push([this.pxSvgElemLower, true]);
elementsToRender.push([this.canvasContext, false]);
for(var i=0; i<canvasKeys.length; i++) {
elementsToRender.push([this.canvasLayers[canvasKeys[i]], false]);
}
elementsToRender.push([this.pxSvgElem, true]);
//now render all elements found
var fn = function() {
if(elementsToRender.length>0) {
var target = elementsToRender.shift();
//if this element is defined
if(target[0]) {
if(!target[1]) {
//canvas
var opacity = getComputedStyle(target[0].canvas).getPropertyValue('opacity'),
context = canvas.getContext('2d'),
oldAlpha = context.globalAlpha;
context.globalAlpha = opacity;
context.drawImage(target[0].canvas, 0, 0);
context.globalAlpha = oldAlpha;
//if we have more element keep drawing, else finish
if(elementsToRender.length > 0) {
fn();
} else {
this._finishGetImage(callback, canvas, renderLegend, drawingWidth, drawingHeight);
}
fn();
} else {
//svg
this._drawSVGOnCanvas(canvas, target[0], function(resultCanvas) {
canvas = resultCanvas;
//if we have more element keep drawing, else finish
if(elementsToRender.length > 0) {
fn();
} else {
this._finishGetImage(callback, canvas, renderLegend, drawingWidth, drawingHeight);
}
}.bind(this));
}
} else {
//ellement is null, continue iterating
fn();
}
}
}.bind(this);
fn();
},
_finishGetImage: function(callback, canvas, renderLegend, drawingWidth, drawingHeight) {
if(renderLegend) {
this._drawRegister(canvas.getContext('2d'), drawingWidth, drawingHeight);
}
callback({canvas: canvas, image: canvas.toDataURL()});
},
_getRegisterWidth: function(drawingWidth, drawingHeight) {
if(this.completeSeriesConfig) {
var canvas = document.createElement('canvas');
canvas.height = drawingHeight;
canvas.width = 9999;
var curY = 0,
curX = drawingWidth + 5,
keys = Object.keys(this.completeSeriesConfig),
maxWidth = 0,
maxTotalWidth = 5,
context = canvas.getContext('2d');
curTextWidth = 0;
for(var i=0; i<keys.length; i++) {
curY += 30;
curTextWidth = context.measureText(this.completeSeriesConfig[keys[i]].name).width;
maxWidth = Math.max(maxWidth, curTextWidth);
if( (curY + 30) > drawingHeight) {
curX += maxWidth + 15;
curY = 0;
maxTotalWidth += maxWidth + 15;
maxWidth = 0;
}
}
maxTotalWidth += maxWidth + 30;
return maxTotalWidth;
} else {
return 0;
}
},
/**
* Draws a fake representation of the registers
*/
_drawRegister: function(context, startWidth, drawingHeight) {
if(this.completeSeriesConfig) {
var curY = 0,
lineLength = 25,
strokeWidth = 3,
curX = startWidth + 5,
keys = Object.keys(this.completeSeriesConfig),
maxWidth = 0,
curTextWidth = 0;
//draw each serie
for(var i=0; i<keys.length; i++) {
curY += 30;
context.fillStyle = this.completeSeriesConfig[keys[i]].color;
context.fillRect(curX,curY,strokeWidth, lineLength);
context.fillStyle = this._checkThemeVariable("--px-vis-register-data-value", 'rgb(0,0,0)');
context.fillText(this.completeSeriesConfig[keys[i]].name, curX + strokeWidth + 5, curY + 10);
curTextWidth = context.measureText(this.completeSeriesConfig[keys[i]].name).width;
maxWidth = Math.max(maxWidth, curTextWidth);
if( (curY + 30) > drawingHeight ) {
curX += maxWidth + 15;
curY = 0;
}
}
}
}
}, PxVisBehavior.completeSeriesConfig];
/**
Name:
PxVisBehaviorChart.chartAutoResize
Description:
Polymer behavior that provides auto resize options for charts. Charts
implementing this behavior can define a `_resizeCalculations` function
which will be called when the chart needs to redo its size calculations
(typically measure its parents and adjust its height/width)
Dependencies:
- D3.js
@polymerBehavior PxVisBehaviorChart.chartAutoResize
*/
PxVisBehaviorChart.chartAutoResize = [{
properties: {
/**
* Prevents the chart from automatically resizing to fit its container
*/
preventResize: {
type: Boolean,
value: false,
observer: '_preventResizeChanged'
},
/**
* This allows to decide how the chart
* drawing will be horizontally aligned when smaller than its container. Values:
* - center
* - left
* - right
*
* if any other value is used then left alignment will be chosen
*/
chartHorizontalAlignment: {
type: String,
value: 'center'
},
/**
* This allows to decide how the chart
* drawing will be vertically aligned when smaller than its container. Values:
* - center
* - top
* - bottom
*
* if any other value is used then top alignment will be chosen
*/
chartVerticalAlignment: {
type: String,
value: 'center'
},
/**
* Class to be used on the external wrapper within the chart
*/
_chartWrapperClass: {
type: String,
computed: '_getChartWrapperClass(chartHorizontalAlignment, chartVerticalAlignment)'
},
/**
* Timing (in ms) to be used for iron resize when the chart auto size
* (preventResize = false)
*/
debounceResizeTiming: {
type: Number,
value: 250
}
},
listeners: {'iron-resize': '_onIronResize'},
_preventResizeChanged: function() {
if(this.hasUndefinedArguments(arguments)) {
return;
}
if(!this.preventResize) {
this.notifyResize();
}
},
_getChartWrapperClass: function(hor, vert) {
if(this.hasUndefinedArguments(arguments)) {
return;
}
var base = 'flex wrapper ';
if(hor === 'center') {
base += 'flex--center ';
} else if(hor === 'right') {
base += 'flex--right ';
} else {
base += 'flex--left ';
}
if(vert === 'center') {
base += 'flex--middle';
} else if(vert === 'bottom') {
base += 'flex--bottom';
} else {
base += 'flex--top';
}
return base;
},
_onIronResize: function() {
if(this.preventResize) {
return;
}
this.debounce('ironresize', () => {
requestAnimationFrame(this._resizeCalculations.bind(this));
}, this.debounceResizeTiming);
}
}, PxVisBehavior.observerCheck, Polymer.IronResizableBehavior];
/**
Name:
PxVisBehaviorChart.subConfiguration
Description:
Polymer behavior that provides subConfiguration for elements such as axes, register, etc.
Dependencies:
@polymerBehavior PxVisBehaviorChart.subConfiguration
*/
PxVisBehaviorChart.subConfiguration = {
properties: {
},
/**
* Applies the config object to the element. Each key in the config object
* is the name of the property to be applied
*
*/
_applyConfigToElement: function(config, element) {
if(typeof(config) === 'string') {
config = JSON.parse(config);
}
if(typeof(config) !== 'object') {
console.error('Configuration object must be valid JSON: ' + config);
return;
}
if(!element) {
console.error('Cannot apply config to undefined element');
return;
}
var keys = Object.keys(config);
for(var i = 0; i < keys.length; i++) {
var key = keys[i];
element.set(key, config[key])
}
},
};
/**
Name:
PxVisBehaviorChart.timeFiltering
Description:
Polymer behavior that allows to filter chartData based on time, providing a _filteredData object
Dependencies:
@polymerBehavior PxVisBehaviorChart.timeFiltering
*/
PxVisBehaviorChart.timeFiltering = [{
properties: {
/**
* Name of the variable holding the time stamp in the data
*/
timeData: {
type: String,
value: 'Timestamp'
},
/**
* Data that has been time filtered
*/
_filteredData: {
type: Object,
computed: '_filterData(chartData, timeDomain, timeData)'
}
},
observers: [
'_setTimeKey(timeData)'
],
_setTimeKey: function() {
if(this.timeData) {
//harmonise key referencing time across charts
this.set('timeKey', this.timeData);
}
},
/**
* returns a filtered dataset based on the time domain
*/
_filterData: function(chartData, timeDomain, timeData) {
if(this.hasUndefinedArguments(arguments)) {
return;
}
if(timeDomain.x && timeDomain.x.length === 2) {
var min = Number(timeDomain.x[0]),
max = Number(timeDomain.x[1]);
return chartData.filter(function(val) {
var timeVal = Number(val[timeData]);
// if the data doesn't have Date value, return the data as it is
if (typeof(val[timeData]) === 'undefined') {
return val;
// Otherwise return the data matching the selected time range
} else {
return (timeVal >= min && timeVal <= max);
}