-
Notifications
You must be signed in to change notification settings - Fork 58
/
visavail.js
1726 lines (1545 loc) · 58.7 KB
/
visavail.js
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
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.visavail = factory());
}(this, (function () { 'use strict';
var visavail = {};
//ie11 fixing
Number.isInteger = Number.isInteger || function(value) {
return typeof value === "number" &&
isFinite(value) &&
Math.floor(value) === value;
};
Element.prototype.remove = Element.prototype.remove || function() {
if (this.parentNode) {
this.parentNode.removeChild(this);
}
};
function visavailChart(custom_options, dataset) {
var d3 = window.d3 ? window.d3 : typeof require !== 'undefined' ? require("d3") : undefined;
var moment = window.moment ? window.moment : typeof require !== 'undefined' ? require("moment") : undefined;
var t0, start_event;
if(!d3)
throw new Error('Require D3.js before visavail script');
if(!moment)
throw new Error('Require moment before visavail script');
var options = {
id: "",
id_div_container: "visavail_container",
id_div_graph: "example",
margin: {
// top margin includes title and legend
top: 65,
// right margin should provide space for last horz. axis title and y percentage
right: 60,
bottom: 20,
// left margin should provide space for y axis titles
left: 100,
},
width: 960,
moment_locale: window.navigator.userLanguage || window.navigator.language,
reduce_space_wrap: 35,
line_spacing: 35,
padding:{
top: -49,
bottom: 0,
right: 60,
left: -100
},
// year ticks to be emphasized or not
emphasize_year_ticks: true,
emphasize_month_ticks: true,
ticks_for_graph: 6,
// define chart pagination
// max. no. of datasets that is displayed, 0: all
max_display_datasets: 0,
// dataset that is displayed first in the current
// display, chart will show datasets "cur_display_first_dataset" to
// "cur_display_first_dataset+max_display_datasets"
cur_display_first_dataset: 0,
// range of dates that will be shown
// if from-date (1st element) or to-date (2nd element) is zero,
// it will be determined according to your data (default: automatically)
display_date_range: ["",""],
//if true reminder to use the correct data format for d3
custom_categories: false,
is_date_only_format: true,
date_in_utc: false,
date_is_descending: false,
// if false remeber to set the padding and margin
show_y_title: true,
// y_title additional class when some_unavailability
y_title_some_unavailability_class: 'some_unavailability',
// y_title additional class when total_unavailability
y_title_total_unavailability_class: 'total_unavailability',
// y_title additional class when total_availability
y_title_total_availability_class: 'total_availability',
y_percentage: {
enabled: false,
// percentage additional class when some_unavailability
some_unavailability_class: 'some_unavailability',
// percentage additional class when total_unavailability
total_unavailability_class: 'total_unavailability',
// percentage additional class when total availability
total_availability_class: 'total_availability',
// availability percentage format function
percentageFormat: d3.format('.2%'),
// percentage of unavailability if true
unavailability_percentage: false,
custom_percentage: false
},
defined_blocks: false,
y_title_tooltip: {
enabled: false,
class: 'y-tooltip',
type: 'right',
spacing:{left: 15, right:15, top: 15,bottom:10},
fixed: false,
duration: 150,
},
tooltip: {
class: 'tooltip',
//height of tooltip , correspond to line-height of class tooltip from css
height: 11,
//position: "top" is a div before bar follow the mouse only left, "overlay" follow the mouse left and height
position: "top",
left_spacing: 0,
date_plus_time: false,
only_first_date: false,
duration: 150,
hover_zoom: {
enabled: false,
ratio: .4,
}
},
legend: {
enabled: true,
line_space: 12,
offset: 5,
// legend x position offset from right
x_right_offset: 150,
has_no_data_text: 'No Data available',
has_data_text: 'Data available'
},
// title of chart is drawn or not (default: true)
title: {
enabled: true,
text: 'Data Availability Plot',
line_spacing: 16
},
sub_title: {
enabled: true,
from_text: 'from',
to_text: 'to',
line_spacing: 16
},
sub_chart: {
enabled: false,
height: 0,
animation: true,
margin:{ top:20, bottom:0 },
graph: {
enabled: true,
width:7,
height:7,
line_spacing: 7
}
},
//custom icon call (for example font awesome)
icon:{
class_has_data : 'fas fa-fw fa-check',
class_has_no_data: 'fas fa-fw fa-times'
},
zoom: {
enabled: false,
//return domain of current scale
onZoom: function onZoom(){},
//return event of at start
onZoomStart: function onZoomStart(){},
//return domain of current scale at the endo of the scale zoom
onZoomEnd: function onZoomEnd(){},
},
onClickBlock: function onclickblock(){},
graph:{
type: "bar" ,
width: 18,
height:18,
hover_zoom: 5
},
responsive: {
enabled: false,
onresize: function onresize(){},
},
//copy the correct format from https://github.com/d3/d3-time-format/tree/master/locale
// locale: {
// "dateTime": "%A %e %B %Y, %X",
// "date": "%d/%m/%Y",
// "time": "%H:%M:%S",
// "periods": ["AM", "PM"],
// "days": moment.weekdays(),
// "shortDays": moment.weekdaysShort(),
// "months": moment.months(),
// "shortMonths": moment.monthsShort()
// },
//use custom time format (for infomation about symbol visit: http://pubs.opengroup.org/onlinepubs/009604599/utilities/date.html)
custom_time_format : {
format_millisecond : ".%L",
format_second : ":%S",
format_minute : "%H:%M",
format_hour : "%H",
format_day : "%a %d",
format_week : "%b %d",
format_month : "%B",
format_year : "%Y"
},
}
function convertMomentToStrftime(momentFormat){
var replacements = {"ddd":"a","dddd":"A","MMM":"b","MMMM":"B","lll":"c","DD":"d","D":"e","YYYY-MM-DD":"F","HH":"H","H":"H","hh":"I","h":"I","DDDD":"j","DDD":"-j","MM":"m","M":"-m","mm":"M","m":"-M","A":"p","a":"P","ss":"S","s":"-S","E":"u","d":"w","WW":"W","ll":"x","LTS":"X","YY":"y","YYYY":"Y","ZZ":"z","z":"Z","SSS":"L","%":"%"}
var tokens = momentFormat.split(/( |\/|:|,|\]|\[|\.)/);
var strftime = tokens.map(function (token) {
// Replace strftime tokens with moment formats
if(token[0] == ":" || token[0] == "/" || token[0] == " " || token[0] == ",")
return token
else
if (token[0] == "[" || token[0] == "]")
return
else
if (replacements.hasOwnProperty(token))
return "%" + replacements[token];
// Escape non-token strings to avoid accidental formatting
return token.length > 0 ? '[' + token + ']' : token;
}).join('');
return strftime;
}
function periodInLocal(){
if (date_format_local.LTS.indexOf('a') > -1 || date_format_local.LTS.indexOf('A') > -1)
return true;
return false;
}
function loadConfig(default_option, custom_options){
Object.keys(custom_options).forEach(function (key) {
if(key in default_option){
if(typeof(default_option[key]) === 'object'){
//console.log("KEY => ", key, ", DEF_KEY => ", default_option[key],", CUST_KEY => ", custom_options[key])
loadConfig(default_option[key], custom_options[key])
} else {
//console.log("KEY => ", key, ", DEF_KEY => ", default_option[key],", CUST_KEY => ", custom_options[key], typeof custom_options[key] == typeof default_option[key])
if(typeof custom_options[key] == typeof default_option[key]){
default_option[key] = custom_options[key];
}
}
}
});
}
loadConfig(options, custom_options)
moment.locale(options.moment_locale);
var date_format_local = moment().creationData().locale._longDateFormat;
options.locale = {
"dateTime": convertMomentToStrftime(date_format_local.LLLL),
"date": convertMomentToStrftime(date_format_local.L),
"time": convertMomentToStrftime(date_format_local.LTS),
"periods": ["AM", "PM"],
"days": moment.weekdays(),
"shortDays": moment.weekdaysShort(),
"months": moment.months(),
"shortMonths": moment.monthsShort()
};
if (!options.custom_time_format){
options.custom_time_format = {
format_millisecond : convertMomentToStrftime("SSS"),
format_second : convertMomentToStrftime(":ss"),
format_minute : convertMomentToStrftime(date_format_local.LT),
format_hour : convertMomentToStrftime(date_format_local.LT.substring(0,1) + (periodInLocal()? " " + date_format_local.LT.slice(-1): "") ),
format_day : convertMomentToStrftime("ddd DD"),
format_week : convertMomentToStrftime("MMM DD"),
format_month : convertMomentToStrftime("MMMM"),
format_year : convertMomentToStrftime("YYYY")
};
};
if(!custom_options.hasOwnProperty("width"))
options.width = document.getElementById(options.id_div_graph).offsetWidth;
options.id = "visavail-" + Math.random().toString(36).substring(7);
//function for custom tick format of x axis
function multiFormat(date) {
return (d3.timeSecond(date) < date ? d3.timeFormat(options.custom_time_format.format_millisecond)
: d3.timeMinute(date) < date ? d3.timeFormat(options.custom_time_format.format_second)
: d3.timeHour(date) < date ? d3.timeFormat(options.custom_time_format.format_minute)
: d3.timeDay(date) < date ? d3.timeFormat(options.custom_time_format.format_hour)
: d3.timeMonth(date) < date ? (d3.timeWeek(date) < date ? d3.timeFormat(options.custom_time_format.format_day)
: d3.timeFormat(options.custom_time_format.format_week))
: d3.timeYear(date) < date ? d3.timeFormat(options.custom_time_format.format_month)
: d3.timeFormat(options.custom_time_format.format_year))(date);
}
function chart(selection) {
//t0 = performance.now();
selection.each(function drawGraph(dataset) {
//set to locale with moment
d3.timeFormatDefaultLocale(options.locale);
// global div for tooltip
var div = d3.select('#'+options.id_div_container).append('div')
.attr('class', "visavail-tooltip " + options.id)
.attr('id', options.id)
.append('div')
.attr('class', (options.tooltip.class+"-"+options.tooltip.position ))
.style('opacity', 0);
var yTitlediv = d3.select('#'+options.id_div_container).append('div')
.attr('class', "visavail-ytitle-tooltip " + options.id)
.attr('id', options.id)
.append('div')
.attr('class', (options.y_title_tooltip.class))
.style('opacity', 0);
var width = options.width - options.margin.left - options.margin.right;
if(!options.oldwidth)
options.oldwidth = width
var maxPages = 0;
var startSet;
var endSet;
if (options.max_display_datasets !== 0) {
startSet = options.cur_display_first_dataset;
if (options.cur_display_first_dataset + options.max_display_datasets > dataset.length) {
endSet = dataset.length;
} else {
endSet = options.cur_display_first_dataset + options.max_display_datasets;
}
maxPages = Math.ceil(dataset.length / options.max_display_datasets);
} else {
startSet = 0;
endSet = dataset.length;
}
// append data attribute in HTML for pagination interface
selection.attr('data-max-pages', maxPages);
var noOfDatasets = endSet - startSet;
var height = options.graph.height * noOfDatasets + options.line_spacing * noOfDatasets - 1;
// check how data is arranged
for (var i = 0; i < dataset.length; i++) {
if(dataset[i].description)
options.tooltip.description = true;
if (dataset[i].data[0] != null && dataset[i].data[0].length == 3 ){
options.defined_blocks = true
if(!options.custom_categories && !Number.isInteger(dataset[i].data[0][1]))
options.custom_categories = true;
break;
}
}
//parse data text strings to JavaScript date stamps
// var parseDate = d3.timeParse('%Y-%m-%d');
// var parseDateTime = d3.timeParse('%Y-%m-%d %H:%M:%S');
// if(options.date_in_utc){
// var parseDate = function(date) {return moment.utc(date).toDate()};
// var parseDateTime = function(date) {return moment.utc(date).toDate()};
// } else {
// var parseDate = function(date) {return moment(date).toDate()};
// var parseDateTime = function(date) {return moment(date).toDate()};
// }
// var format_utc = d3.utcParse('%Y-%m-%d');
// if(options.date_in_utc){
// var parseDate = function(date) {return moment.utc(date).toDate()};
// var parseDateTime = function(date) {return moment.utc(date).toDate()};
// } else {
// var parseDate = function(date) {
// var format = d3.timeParse('%Y-%m-%d');;
// var date_converted = new Date(date);
// var userTimezoneOffset = new Date(date).getTimezoneOffset()*60000
// return (format(date))
// };
// var parseDateTime = function(date) {
// var format = d3.timeParse('%Y-%m-%d %H:%M:%S');;
// var date_converted = new Date(date);
// var userTimezoneOffset = new Date(date).getTimezoneOffset()*60000
// return (format(date))
// };
// }
var format = d3.timeParse("%Y-%m-%d");
var format_utc_time = d3.utcParse("%Y-%m-%d %H:%M:%S");
var format_utc= d3.utcParse("%Y-%m-%d");
if (options.date_in_utc) {
var parseDate = function(date) {
return format_utc(date);
};
var parseDateTime = function(date) {
return format_utc_time(date);
};
} else {
var parseDate = function(date) {
return format(date);
};
var parseDateTime = function(date) {
return new Date(date);
};
}
var parseDateRegEx = new RegExp(/^\d{4}-\d{2}-\d{2}$/);
var parseDateTimeRegEx = new RegExp(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);
var t0 = performance.now()
dataset.forEach(function (d) {
d.data.forEach(function (d1) {
if (!(d1[0] instanceof Date)) {
if (parseDateTimeRegEx.test(d1[0])) {
// d1[0] is date with time data
d1[0] = parseDateTime(d1[0]);
options.is_date_only_format = false;
} else if (parseDateRegEx.test(d1[0])) {
// d1[0] is date without time data
d1[0] = parseDate(d1[0]);
} else {
throw new Error('Date/time format not recognized. Pick between \'YYYY-MM-DD\' or ' +
'\'YYYY-MM-DD HH:MM:SS\'.');
}
}
if (!(d1[2] instanceof Date)) {
if (!options.defined_blocks) {
d1[2] = d3.timeSecond.offset(d1[0], d.interval_s);
} else {
if(d1[2]){
if (parseDateTimeRegEx.test(d1[2])) {
// d1[2] is date with time data
d1[2] = parseDateTime(d1[2]);
} else if (parseDateRegEx.test(d1[2])) {
// d1[2] is date without time data
d1[2] = parseDate(d1[2]);
} else {
d1[2] = d1[0];
if(options.graph.type != "rhombus")
console.error('Date/time format not recognized. Pick between \'YYYY-MM-DD\' or ' +
'\'YYYY-MM-DD HH:MM:SS\'.');
}
} else
throw new Error('Defined block true but dataset not correct');
}
}
});
});
//console.log(performance.now()-t0)
var startDate = moment().year(2999).toDate(),
endDate = moment().year(0).toDate();
// cluster data by dates to form time blocks
dataset.forEach(function (series, seriesI) {
var tmpData = [];
var dataLength = series.data.length;
series.data.forEach(function (d, i) {
// if(moment(d[2]).isSameOrAfter(endDate))
// endDate = d[2]
// if(moment(d[0]).isSameOrBefore(startDate))
// startDate = d[0]
// var temp = [moment(d[0]).valueOf(), moment(d[2]).valueOf()]
// var temp2 = [moment(startDate).valueOf(), moment(endDate).valueOf()]
// if(temp[1] >= temp2[1])
// endDate = d[2]
// if(temp[0] <= temp2[0])
// startDate = d[0]
if(d[2] >= endDate)
endDate = d[2]
if(d[0] <= startDate)
startDate = d[0]
if (i !== 0 && i < dataLength) {
if (d[1] === tmpData[tmpData.length - 1][1]) {
// the value has not changed since the last date
if (options.defined_blocks) {
if (tmpData[tmpData.length - 1][2].getTime() === d[0].getTime()) {
// end of old and start of new block are the same
tmpData[tmpData.length - 1][2] = d[2];
tmpData[tmpData.length - 1][3] = d[1];
} else {
tmpData.push(d);
}
} else {
tmpData[tmpData.length - 1][2] = d[2];
tmpData[tmpData.length - 1][3] = d[1];
}
} else {
// the value has changed since the last date
if (!options.defined_blocks) {
// extend last block until new block starts
tmpData[tmpData.length - 1][2] = d[0];
}
tmpData.push(d);
}
} else if (i === 0) {
if(d.length < 3)
d[2] = d[0];
tmpData.push(d);
}
});
dataset[seriesI].disp_data = tmpData;
// console.log(dataset[seriesI].disp_data)
});
// determine start and end dates among all nested datasets
if(options.display_date_range && (options.display_date_range[0] || options.display_date_range[1])){
if(options.display_date_range[0]){
if (!(options.display_date_range[0] instanceof Date)) {
if (parseDateRegEx.test(options.display_date_range[0])) {
options.display_date_range[0] = parseDate(options.display_date_range[0]);
} else if (parseDateTimeRegEx.test(options.display_date_range[0])) {
options.display_date_range[0] = parseDateTime(options.display_date_range[0]);
} else {
throw new Error('Option of Display range Date/time format not recognized. Pick between \'YYYY-MM-DD\' or ' +
'\'YYYY-MM-DD HH:MM:SS\'.');
}
startDate = options.display_date_range[0];
} else {
if(options.date_in_utc)
startDate = moment.utc(options.display_date_range[0]).toDate();
else
startDate = options.display_date_range[0];
}
}
if(options.display_date_range[1]){
if (!(options.display_date_range[1] instanceof Date)) {
if (parseDateRegEx.test(options.display_date_range[1])) {
options.display_date_range[1] = parseDate(options.display_date_range[1]);
} else if (parseDateTimeRegEx.test(options.display_date_range[1])) {
options.display_date_range[1] = parseDateTime(options.display_date_range[1]);
} else {
throw new Error('Option of Display range Date/time format not recognized. Pick between \'YYYY-MM-DD\' or ' +
'\'YYYY-MM-DD HH:MM:SS\'.');
}
endDate = options.display_date_range[1];
} else {
if(options.date_in_utc)
endDate = moment.utc(options.display_date_range[1]).toDate();
else
endDate = options.display_date_range[1];
}
}
}
// define total percentage times
if (options.y_percentage.enabled && !options.y_percentage.custom_percentage)
dataset.forEach(function (series, seriesI) {
dataset[seriesI].timeup_ms = 0;
dataset[seriesI].timedown_ms = 0;
if (!options.custom_categories)
series.disp_data.forEach(function (disp) {
if (disp[1])
dataset[seriesI].timeup_ms += disp[2].getTime() - disp[0].getTime();
else
dataset[seriesI].timedown_ms += disp[2].getTime() - disp[0].getTime();
});
else
series.disp_data.forEach(function (disp) {
if (disp[1] === series.category_percentage)
dataset[seriesI].timeup_ms += disp[2].getTime() - disp[0].getTime();
else
dataset[seriesI].timedown_ms += disp[2].getTime() - disp[0].getTime();
});
});
// define scales
var xScale = d3.scaleTime()
.domain([startDate, endDate])
.range([0, width])
var xScale2 = d3.scaleTime()
.domain([startDate, endDate])
.range([0, width])
if(options.date_is_descending){
xScale.domain([endDate, startDate])
xScale2.domain([endDate, startDate])
}
options.xScale = xScale;
// define axes
var xAxis = d3.axisTop(options.xScale)
.scale(options.xScale)
.ticks(options.ticks_for_graph)
.tickFormat(multiFormat);
var subChartXAxis = d3.axisBottom(xScale2)
.scale(xScale2)
.ticks(options.ticks_for_graph)
.tickFormat(multiFormat);
// create SVG element
var svg = d3.select(this).append('svg')
.attr('width', width + options.margin.left + options.margin.right)
.attr('height', height + options.margin.top + options.margin.bottom + options.sub_chart.height + options.sub_chart.margin.top + options.sub_chart.margin.bottom)
.append('g')
.attr('transform', 'translate(' + options.margin.left + ',' + options.margin.top + ')');
// create basic element groups
svg.append('g').attr('id', 'g_axis');
svg.append('g')
.attr('id', 'g_data')
.append('rect')
.attr('id', 'zoom')
.attr('width', width)
.attr('height', height)
.attr('fill-opacity', 0)
.attr('x', 0)
.attr('y', 0)
svg.append('g').attr('id', 'g_axis_text');
svg.append('g').attr('id', 'g_title');
options.zoomed = d3.zoom()
.scaleExtent([1,Infinity])
.translateExtent([[0,0],[width, options.height]])
.extent([[0, 0], [width, options.height]])
.on("start", function () {
var e = d3.event;
//console.log("start", e.transform, d3.zoomTransform(svg.select("#g_data").node()))
if (e.sourceEvent && e.sourceEvent.type === "brush") {
return;
}
if( e.sourceEvent && e.sourceEvent.type === "touchstart" && e.sourceEvent.cancelable){
event.preventDefault();
event.stopImmediatePropagation();
}
//define startEvent for fix error in click
if(e.transform.k || e.transform.x){
start_event = e;
options.zoom.onZoomStart.call(this, e);
}
})
.on("zoom", zoomed)
.on('end', function () {
var e = d3.event;
//console.log( e.type, e.transform.k, e.transform.x, e.sourceEvent)
if(e == null)
return
if (e.sourceEvent && e.sourceEvent.type === "brush") {
return;
}
if(e.sourceEvent && e.sourceEvent.type === "touchend" && e.sourceEvent.cancelable){
event.preventDefault();
event.stopImmediatePropagation();
}
// if click, do nothing. otherwise, click interaction will be canceled.
// if (start_event.sourceEvent && e.sourceEvent && start_event.sourceEvent.type === "touchend"&&
// start_event.sourceEvent.clientX == e.sourceEvent.clientX && start_event.sourceEvent.clientY == e.sourceEvent.clientY) {
// console.log("enter to click")
// return;
// }
if(e.transform.k || e.transform.x){
options["scale"] = d3.zoomTransform(svg.select("#g_data").node())
options.zoom.onZoomEnd.call(this, options.xScale.domain());
} else {
e.transform.k = start_event.transform.k;
e.transform.x = start_event.transform.x;
options["scale"] = d3.zoomIdentity.translate(e.transform.x, e.transform.y).scale(e.transform.k)
options.zoom.onZoomEnd.call(this, options.xScale.domain());
}
});
if (options.zoom.enabled)
svg.select("#g_data")
.call(options.zoomed)
.attr('cursor', "ew-resize")
function wrap() {
var self = d3.select(this),
textLength = self.node().getComputedTextLength(),
text = self.text();
while (textLength > (-1 * options.padding.left + options.reduce_space_wrap) && text.length > 0) {
text = text.slice(0, -1);
self.text(text + '...');
textLength = self.node().getComputedTextLength();
}
}
if (options.show_y_title) {
// create y axis labels
var y_axis_title = svg.select('#g_axis_text').append('g').attr('id', 'yAxis');
y_axis_title.selectAll('text')
.data(dataset.slice(startSet, endSet))
.enter()
.append('g')
.attr('id', function (d,i) {
return i;
});
y_axis_title.selectAll("g").append('text')
.attr('x', options.padding.left)
.attr('y', function (d,i){
return ((options.line_spacing + options.graph.height) * i) + options.line_spacing + (options.graph.height) / 2;
})
.attr('dy', "0.5ex")
.text(function (d) {
return d.measure || d.measure_html;
/*if (!(d.measure_html != null)) {
return d.measure;
}*/
})
.each(wrap)
.attr('class', function (d) {
var returnCSSClass = 'ytitle';
if (d.measure_url != null) {
returnCSSClass = returnCSSClass + ' link';
}
if (options.y_percentage.enabled && !options.y_percentage.custom_percentage)
if (d.timedown_ms == 0)
returnCSSClass += ' ' + options.y_title_total_availability_class;
else
if (d.timeup_ms == 0)
returnCSSClass += ' ' + options.y_title_total_unavailability_class;
else
returnCSSClass += ' ' + options.y_title_some_unavailability_class;
return returnCSSClass;
})
.on('click', function (d) {
if (d.measure_url != null) {
return window.open(d.measure_url);
}
return null;
})
y_axis_title.selectAll("g")
.append("circle")
.attr('class', function (d) {
return 'ytitle_icon_background ' + ((d.icon || "").background_class || "");
})
.attr('cx', function (d) {
if (d.icon && d.icon.width)
return options.padding.left - d.icon.width/2 - ((d.icon.padding || 0).right || 0) - (d.icon.padding_right || 0);
return 0;
})
.attr('cy', function (d,i){
if (d.icon && d.icon.height)
return ((options.line_spacing + options.graph.height ) * i) + options.line_spacing + (options.graph.height) / 2;
return 0;
})
.attr("r", function (d) {
if (d.icon && d.icon.width)
return d.icon.width/2 ;
return 0;
});
y_axis_title.selectAll("g")
.append("image")
.attr('class', function (d) {
return 'ytitle_icon_image ' + ((d.icon || "").image_class || "");
})
.attr("xlink:href", function (d) {
if (d.icon && d.icon.url)
return d.icon.url ;
return "";
})
.attr('x', function (d) {
if (d.icon && d.icon.width)
return options.padding.left - d.icon.width - ((d.icon.padding || 0).right || 0) - (d.icon.padding_right || 0);
return 0;
})
.attr('y', function (d,i){
if (d.icon && d.icon.height)
return ((options.line_spacing + options.graph.height ) * i) - d.icon.height/2 + options.line_spacing + (options.graph.height) / 2;
return 0;
})
.attr("width", function (d) {
if (d.icon && d.icon.width)
return d.icon.width ;
return 0;
})
.attr("height", function (d) {
if (d.icon && d.icon.height)
return d.icon.height ;
return 0;
});
if(options.y_title_tooltip.enabled){
y_axis_title.selectAll("g").selectAll('text')
.on('mouseover', function (d, i) {
drawTitleTooltipWhenOver(this, dataset, d, i);
})
.on("touchstart", function (d, i) {
drawTitleTooltipWhenOver(this, d, i);
})
.on('mouseout', function () {
hideTitleTooltipWhenOver()
})
.on("touchleave", function () {
hideTitleTooltipWhenOver()
})
.on("touchcancel", function () {
hideTitleTooltipWhenOver()
});
function drawTitleTooltipWhenOver(obj, dataset, d, i){
if (options.y_title_tooltip.enabled){
var matrix = obj.getCTM().translate(obj.getAttribute('x'), obj.getAttribute('y'));
yTitlediv.transition()
.duration(options.y_title_tooltip.duration)
.style('opacity', 1);
yTitlediv.html(function () {
var output = d.measure_description || "";
return output;
})
if(options.y_title_tooltip.type == "right"){
yTitlediv.style('left', function(){
if(options.y_title_tooltip.fixed)
return -1 * options.padding.left + 'px';
return options.y_title_tooltip.spacing.right + d3.select(obj).node().getComputedTextLength() + 'px';
})
.classed(options.y_title_tooltip.type, true)
.style('top', matrix.f - (document.getElementsByClassName(options.y_title_tooltip.class)[0].offsetHeight + ((options.line_spacing + options.graph.height) * i))/2 + 'px')
}
if(options.y_title_tooltip.type == "top"){
yTitlediv.style('left', '0px')
.style("top", matrix.f - (document.getElementsByClassName(options.y_title_tooltip.class)[0].offsetHeight + options.y_title_tooltip.spacing.top) + 'px')
.classed(options.y_title_tooltip.type, true)
}
if(options.y_title_tooltip.type == "bottom"){
yTitlediv.style('left', '0px')
.style("top", matrix.f + options.y_title_tooltip.spacing.bottom + 'px')
.classed(options.y_title_tooltip.type, true)
}
}
}
function hideTitleTooltipWhenOver(){
yTitlediv.transition()
.duration(options.y_title_tooltip.duration)
.style('opacity', 0);
}
} else {
y_axis_title.selectAll("g").append('title')
.text(function (d) {
return d.measure_description || d.measure;
});
}
/*svg.select('#yAxis').selectAll("g")
.insert('text', ':first-child')
.attr('x', options.padding.left)
.attr('y', options.line_spacing)
.attr('transform', function (d, i) {
return 'translate(0,' + ((options.line_spacing + options.graph.height) * i) + ')';
})
.attr('width', -1 * options.padding.left)
.attr('height', options.graph.height)
.attr('class', 'ytitle')
.append("xhtml:div")
.html(function (d) {
if (d.measure_html != null) {
return d.measure_html;
}
});
*/
}
if (options.y_percentage.enabled) {
// create y axis labels
var y_percentage_title = svg.select('#g_axis_text').append('g').attr('id', 'yPercentage');
y_percentage_title.selectAll('text')
.data(dataset.slice(startSet, endSet))
.enter()
.append('g')
.attr('id', function (d,i) {
return i;
});
y_percentage_title.selectAll("g").append('text')
.attr('x', width)
.attr('dx', options.padding.right)
.attr('y', function (d,i){
return ((options.line_spacing + options.graph.height) * i) + options.line_spacing + (options.graph.height) / 2;
})
.attr('dy', "0.5ex")
.attr("text-anchor", "end")
.text(function (d) {
if (!options.custom_categories && options.y_percentage.unavailability_percentage)
return options.y_percentage.percentageFormat(d.timedown_ms/(d.timedown_ms+d.timeup_ms));
else if(options.y_percentage.custom_percentage )
return (d.percentage || "").measure || "";
else
return options.y_percentage.percentageFormat(d.timeup_ms/(d.timeup_ms+d.timedown_ms));
})
.each(wrap)
.attr('class', function (d) {
var returnCSSClass = 'ypercentage';
if (!options.y_percentage.custom_percentage)
if (d.timedown_ms == 0)
returnCSSClass += ' ' + options.y_percentage.total_availability_class;
else
if (d.timeup_ms == 0)
returnCSSClass += ' ' + options.y_percentage.total_unavailability_class;
else
returnCSSClass += ' ' + options.y_percentage.some_unavailability_class;
else if(options.y_percentage.custom_percentage)
returnCSSClass += ' ' + (d.percentage || "").class || "";;
return returnCSSClass;
});
}
//xAxis
svg.select('#g_axis').append('g').attr('id', 'vGrid');
function createVGrid(scale){
svg.select('#vGrid')
.selectAll('line.vert_grid')
.data(scale.ticks(options.ticks_for_graph))
.enter()
.append('line')
.attr('x1', function (d) {
return scale(d);
})
.attr('x2', function (d) {
return scale(d);
})
.attr('y1', 0)
.attr('y2', options.graph.height * noOfDatasets + options.line_spacing * noOfDatasets - 1 + options.margin.bottom)
.attr('class', 'vert_grid');
}
// create vertical grid
if (noOfDatasets) {
createVGrid(options.xScale)
}
// create horizontal grid
svg.select('#g_axis').append('g').attr('id', 'hGrid').selectAll('line.horz_grid').data(dataset)
.enter()
.append('line')
.attr('x1', 0)
.attr('x2', width)
.attr('y1', function (d, i) {
return ((options.line_spacing + options.graph.height) * i) + options.line_spacing + options.graph.height / 2;
})
.attr('y2', function (d, i) {
return ((options.line_spacing + options.graph.height) * i) + options.line_spacing + options.graph.height / 2;
})
.attr('class', 'horz_grid');
// create x axis
if (noOfDatasets) {
svg.select('#g_axis').append('g')
.attr('class', 'xAxis')
.call(xAxis);
}
// make y groups for different data series
var g = svg.select('#g_data').selectAll('.g_data')
.data(dataset.slice(startSet, endSet))
.enter()
.append('g')
.attr('transform', function (d, i) {
return 'translate(0,' + ((options.line_spacing + options.graph.height) * i) + ')';
})
.attr('cursor', 'pointer')
.attr('class', 'dataset');
// g.selectAll('rect')
// .data(function (d) {
// return d.disp_data;
// })
// .enter()
// .append('rect')
// add data series
g.selectAll('rect')
.data(function (d) {
return d.disp_data;
})
.enter()
.append('rect')
.attr('x', function (d) {
return xForPoint(d, options.graph.width, options.xScale, 0)
})
.attr('width', function (d) {
return widthForPoint(d, options.graph.width, options.xScale, 0)