-
Notifications
You must be signed in to change notification settings - Fork 4
/
nv.d3.js
14241 lines (11245 loc) · 452 KB
/
nv.d3.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(){
var nv = window.nv || {};
nv.version = '1.1.11b';
nv.dev = true //set false when in production
window.nv = nv;
nv.tooltip = {}; // For the tooltip system
nv.utils = {}; // Utility subsystem
nv.models = {}; //stores all the possible models/components
nv.charts = {}; //stores all the ready to use charts
nv.graphs = []; //stores all the graphs currently on the page
nv.logs = {}; //stores some statistics and potential error messages
nv.dispatch = d3.dispatch('render_start', 'render_end');
// *************************************************************************
// Development render timers - disabled if dev = false
if (nv.dev) {
nv.dispatch.on('render_start', function(e) {
nv.logs.startTime = +new Date();
});
nv.dispatch.on('render_end', function(e) {
nv.logs.endTime = +new Date();
nv.logs.totalTime = nv.logs.endTime - nv.logs.startTime;
nv.log('total', nv.logs.totalTime); // used for development, to keep track of graph generation times
});
}
// ********************************************
// Public Core NV functions
// Logs all arguments, and returns the last so you can test things in place
// Note: in IE8 console.log is an object not a function, and if modernizr is used
// then calling Function.prototype.bind with with anything other than a function
// causes a TypeError to be thrown.
nv.log = function() {
if (nv.dev && console.log && console.log.apply)
console.log.apply(console, arguments)
else if (nv.dev && typeof console.log == "function" && Function.prototype.bind) {
var log = Function.prototype.bind.call(console.log, console);
log.apply(console, arguments);
}
return arguments[arguments.length - 1];
};
nv.render = function render(step) {
step = step || 1; // number of graphs to generate in each timeout loop
nv.render.active = true;
nv.dispatch.render_start();
setTimeout(function() {
var chart, graph;
for (var i = 0; i < step && (graph = nv.render.queue[i]); i++) {
chart = graph.generate();
if (typeof graph.callback == typeof(Function)) graph.callback(chart);
nv.graphs.push(chart);
}
nv.render.queue.splice(0, i);
if (nv.render.queue.length) setTimeout(arguments.callee, 0);
else { nv.render.active = false; nv.dispatch.render_end(); }
}, 0);
};
nv.render.active = false;
nv.render.queue = [];
nv.addGraph = function(obj) {
if (typeof arguments[0] === typeof(Function))
obj = {generate: arguments[0], callback: arguments[1]};
nv.render.queue.push(obj);
if (!nv.render.active) nv.render();
};
nv.identity = function(d) { return d; };
nv.strip = function(s) { return s.replace(/(\s|&)/g,''); };
function daysInMonth(month,year) {
return (new Date(year, month+1, 0)).getDate();
}
function d3_time_range(floor, step, number) {
return function(t0, t1, dt) {
var time = floor(t0), times = [];
if (time < t0) step(time);
if (dt > 1) {
while (time < t1) {
var date = new Date(+time);
if ((number(date) % dt === 0)) times.push(date);
step(time);
}
} else {
while (time < t1) { times.push(new Date(+time)); step(time); }
}
return times;
};
}
d3.time.monthEnd = function(date) {
return new Date(date.getFullYear(), date.getMonth(), 0);
};
d3.time.monthEnds = d3_time_range(d3.time.monthEnd, function(date) {
date.setUTCDate(date.getUTCDate() + 1);
date.setDate(daysInMonth(date.getMonth() + 1, date.getFullYear()));
}, function(date) {
return date.getMonth();
}
);
/* Utility class to handle creation of an interactive layer.
This places a rectangle on top of the chart. When you mouse move over it, it sends a dispatch
containing the X-coordinate. It can also render a vertical line where the mouse is located.
dispatch.elementMousemove is the important event to latch onto. It is fired whenever the mouse moves over
the rectangle. The dispatch is given one object which contains the mouseX/Y location.
It also has 'pointXValue', which is the conversion of mouseX to the x-axis scale.
*/
nv.interactiveGuideline = function() {
"use strict";
var tooltip = nv.models.tooltip();
//Public settings
var width = null
, height = null
//Please pass in the bounding chart's top and left margins
//This is important for calculating the correct mouseX/Y positions.
, margin = {left: 0, top: 0}
, xScale = d3.scale.linear()
, yScale = d3.scale.linear()
, dispatch = d3.dispatch('elementMousemove', 'elementMouseout','elementDblclick')
, showGuideLine = true
, svgContainer = null
//Must pass in the bounding chart's <svg> container.
//The mousemove event is attached to this container.
;
//Private variables
var isMSIE = navigator.userAgent.indexOf("MSIE") !== -1 //Check user-agent for Microsoft Internet Explorer.
;
function layer(selection) {
selection.each(function(data) {
var container = d3.select(this);
var availableWidth = (width || 960), availableHeight = (height || 400);
var wrap = container.selectAll("g.nv-wrap.nv-interactiveLineLayer").data([data]);
var wrapEnter = wrap.enter()
.append("g").attr("class", " nv-wrap nv-interactiveLineLayer");
wrapEnter.append("g").attr("class","nv-interactiveGuideLine");
if (!svgContainer) {
return;
}
function mouseHandler() {
var d3mouse = d3.mouse(this);
var mouseX = d3mouse[0];
var mouseY = d3mouse[1];
var subtractMargin = true;
var mouseOutAnyReason = false;
if (isMSIE) {
/*
D3.js (or maybe SVG.getScreenCTM) has a nasty bug in Internet Explorer 10.
d3.mouse() returns incorrect X,Y mouse coordinates when mouse moving
over a rect in IE 10.
However, d3.event.offsetX/Y also returns the mouse coordinates
relative to the triggering <rect>. So we use offsetX/Y on IE.
*/
mouseX = d3.event.offsetX;
mouseY = d3.event.offsetY;
/*
On IE, if you attach a mouse event listener to the <svg> container,
it will actually trigger it for all the child elements (like <path>, <circle>, etc).
When this happens on IE, the offsetX/Y is set to where ever the child element
is located.
As a result, we do NOT need to subtract margins to figure out the mouse X/Y
position under this scenario. Removing the line below *will* cause
the interactive layer to not work right on IE.
*/
if(d3.event.target.tagName !== "svg")
subtractMargin = false;
if (d3.event.target.className.baseVal.match("nv-legend"))
mouseOutAnyReason = true;
}
if(subtractMargin) {
mouseX -= margin.left;
mouseY -= margin.top;
}
/* If mouseX/Y is outside of the chart's bounds,
trigger a mouseOut event.
*/
if (mouseX < 0 || mouseY < 0
|| mouseX > availableWidth || mouseY > availableHeight
|| (d3.event.relatedTarget && d3.event.relatedTarget.ownerSVGElement === undefined)
|| mouseOutAnyReason
)
{
if (isMSIE) {
if (d3.event.relatedTarget
&& d3.event.relatedTarget.ownerSVGElement === undefined
&& d3.event.relatedTarget.className.match(tooltip.nvPointerEventsClass)) {
return;
}
}
dispatch.elementMouseout({
mouseX: mouseX,
mouseY: mouseY
});
layer.renderGuideLine(null); //hide the guideline
return;
}
var pointXValue = xScale.invert(mouseX);
dispatch.elementMousemove({
mouseX: mouseX,
mouseY: mouseY,
pointXValue: pointXValue
});
//If user double clicks the layer, fire a elementDblclick dispatch.
if (d3.event.type === "dblclick") {
dispatch.elementDblclick({
mouseX: mouseX,
mouseY: mouseY,
pointXValue: pointXValue
});
}
}
svgContainer
.on("mousemove",mouseHandler, true)
.on("mouseout" ,mouseHandler,true)
.on("dblclick" ,mouseHandler)
;
//Draws a vertical guideline at the given X postion.
layer.renderGuideLine = function(x) {
if (!showGuideLine) return;
var line = wrap.select(".nv-interactiveGuideLine")
.selectAll("line")
.data((x != null) ? [nv.utils.NaNtoZero(x)] : [], String);
line.enter()
.append("line")
.attr("class", "nv-guideline")
.attr("x1", function(d) { return d;})
.attr("x2", function(d) { return d;})
.attr("y1", availableHeight)
.attr("y2",0)
;
line.exit().remove();
}
});
}
layer.dispatch = dispatch;
layer.tooltip = tooltip;
layer.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return layer;
};
layer.width = function(_) {
if (!arguments.length) return width;
width = _;
return layer;
};
layer.height = function(_) {
if (!arguments.length) return height;
height = _;
return layer;
};
layer.xScale = function(_) {
if (!arguments.length) return xScale;
xScale = _;
return layer;
};
layer.showGuideLine = function(_) {
if (!arguments.length) return showGuideLine;
showGuideLine = _;
return layer;
};
layer.svgContainer = function(_) {
if (!arguments.length) return svgContainer;
svgContainer = _;
return layer;
};
return layer;
};
/* Utility class that uses d3.bisect to find the index in a given array, where a search value can be inserted.
This is different from normal bisectLeft; this function finds the nearest index to insert the search value.
For instance, lets say your array is [1,2,3,5,10,30], and you search for 28.
Normal d3.bisectLeft will return 4, because 28 is inserted after the number 10. But interactiveBisect will return 5
because 28 is closer to 30 than 10.
Unit tests can be found in: interactiveBisectTest.html
Has the following known issues:
* Will not work if the data points move backwards (ie, 10,9,8,7, etc) or if the data points are in random order.
* Won't work if there are duplicate x coordinate values.
*/
nv.interactiveBisect = function (values, searchVal, xAccessor) {
"use strict";
if (! values instanceof Array) return null;
if (typeof xAccessor !== 'function') xAccessor = function(d,i) { return d.x;}
var bisect = d3.bisector(xAccessor).left;
var index = d3.max([0, bisect(values,searchVal) - 1]);
var currentValue = xAccessor(values[index], index);
if (typeof currentValue === 'undefined') currentValue = index;
if (currentValue === searchVal) return index; //found exact match
var nextIndex = d3.min([index+1, values.length - 1]);
var nextValue = xAccessor(values[nextIndex], nextIndex);
if (typeof nextValue === 'undefined') nextValue = nextIndex;
if (Math.abs(nextValue - searchVal) >= Math.abs(currentValue - searchVal))
return index;
else
return nextIndex
};/* Tooltip rendering model for nvd3 charts.
window.nv.models.tooltip is the updated,new way to render tooltips.
window.nv.tooltip.show is the old tooltip code.
window.nv.tooltip.* also has various helper methods.
*/
(function() {
"use strict";
window.nv.tooltip = {};
/* Model which can be instantiated to handle tooltip rendering.
Example usage:
var tip = nv.models.tooltip().gravity('w').distance(23)
.data(myDataObject);
tip(); //just invoke the returned function to render tooltip.
*/
window.nv.models.tooltip = function() {
var content = null //HTML contents of the tooltip. If null, the content is generated via the data variable.
, data = null /* Tooltip data. If data is given in the proper format, a consistent tooltip is generated.
Format of data:
{
key: "Date",
value: "August 2009",
series: [
{
key: "Series 1",
value: "Value 1",
color: "#000"
},
{
key: "Series 2",
value: "Value 2",
color: "#00f"
}
]
}
*/
, gravity = 'w' //Can be 'n','s','e','w'. Determines how tooltip is positioned.
, distance = 50 //Distance to offset tooltip from the mouse location.
, snapDistance = 25 //Tolerance allowed before tooltip is moved from its current position (creates 'snapping' effect)
, fixedTop = null //If not null, this fixes the top position of the tooltip.
, classes = null //Attaches additional CSS classes to the tooltip DIV that is created.
, chartContainer = null //Parent DIV, of the SVG Container that holds the chart.
, tooltipElem = null //actual DOM element representing the tooltip.
, position = {left: null, top: null} //Relative position of the tooltip inside chartContainer.
, enabled = true //True -> tooltips are rendered. False -> don't render tooltips.
//Generates a unique id when you create a new tooltip() object
, id = "nvtooltip-" + Math.floor(Math.random() * 100000)
;
//CSS class to specify whether element should not have mouse events.
var nvPointerEventsClass = "nv-pointer-events-none";
//Format function for the tooltip values column
var valueFormatter = function(d,i) {
return d;
};
//Format function for the tooltip header value.
var headerFormatter = function(d) {
return d;
};
//By default, the tooltip model renders a beautiful table inside a DIV.
//You can override this function if a custom tooltip is desired.
var contentGenerator = function(d) {
if (content != null) return content;
if (d == null) return '';
var table = d3.select(document.createElement("table"));
var theadEnter = table.selectAll("thead")
.data([d])
.enter().append("thead");
theadEnter.append("tr")
.append("td")
.attr("colspan",3)
.append("strong")
.classed("x-value",true)
.text(headerFormatter(d.value));
var tbodyEnter = table.selectAll("tbody")
.data([d])
.enter().append("tbody");
var trowEnter = tbodyEnter.selectAll("tr")
.data(function(p) { return p.series})
.enter()
.append("tr")
.classed("highlight", function(p) { return p.highlight})
;
trowEnter.append("td")
.classed("legend-color-guide",true)
.append("div")
.style("background-color", function(p) { return p.color});
trowEnter.append("td")
.classed("key",true)
.text(function(p) {return p.key});
trowEnter.append("td")
.classed("value",true)
.text(function(p,i) { return valueFormatter(p.value,i) });
trowEnter.selectAll("td").each(function(p) {
if (p.highlight)
d3.select(this)
.style("border-bottom","solid 1px " + p.color)
.style("border-top","solid 1px " + p.color)
;
});
var html = table.node().outerHTML;
if (d.footer !== undefined)
html += "<div class='footer'>" + d.footer + "</div>";
return html;
};
var dataSeriesExists = function(d) {
if (d && d.series && d.series.length > 0) return true;
return false;
};
//In situations where the chart is in a 'viewBox', re-position the tooltip based on how far chart is zoomed.
function convertViewBoxRatio() {
if (chartContainer) {
var svg = d3.select(chartContainer);
if (svg.node().tagName !== "svg") {
svg = svg.select("svg");
}
var viewBox = (svg.node()) ? svg.attr('viewBox') : null;
if (viewBox) {
viewBox = viewBox.split(' ');
var ratio = parseInt(svg.style('width')) / viewBox[2];
position.left = position.left * ratio;
position.top = position.top * ratio;
}
}
}
//Creates new tooltip container, or uses existing one on DOM.
function getTooltipContainer(newContent) {
var body;
if (chartContainer)
body = d3.select(chartContainer);
else
body = d3.select("body");
var container = body.select(".nvtooltip");
if (container.node() === null) {
//Create new tooltip div if it doesn't exist on DOM.
container = body.append("div")
.attr("class", "nvtooltip " + (classes? classes: "xy-tooltip"))
.attr("id",id)
;
}
container.node().innerHTML = newContent;
container.style("top",0).style("left",0).style("opacity",0);
container.selectAll("div, table, td, tr").classed(nvPointerEventsClass,true)
container.classed(nvPointerEventsClass,true);
return container.node();
}
//Draw the tooltip onto the DOM.
function nvtooltip() {
if (!enabled) return;
if (!dataSeriesExists(data)) return;
convertViewBoxRatio();
var left = position.left;
var top = (fixedTop != null) ? fixedTop : position.top;
var container = getTooltipContainer(contentGenerator(data));
tooltipElem = container;
if (chartContainer) {
var svgComp = chartContainer.getElementsByTagName("svg")[0];
var boundRect = (svgComp) ? svgComp.getBoundingClientRect() : chartContainer.getBoundingClientRect();
var svgOffset = {left:0,top:0};
if (svgComp) {
var svgBound = svgComp.getBoundingClientRect();
var chartBound = chartContainer.getBoundingClientRect();
var svgBoundTop = svgBound.top;
//Defensive code. Sometimes, svgBoundTop can be a really negative
// number, like -134254. That's a bug.
// If such a number is found, use zero instead. FireFox bug only
if (svgBoundTop < 0) {
var containerBound = chartContainer.getBoundingClientRect();
svgBoundTop = (Math.abs(svgBoundTop) > containerBound.height) ? 0 : svgBoundTop;
}
svgOffset.top = Math.abs(svgBoundTop - chartBound.top);
svgOffset.left = Math.abs(svgBound.left - chartBound.left);
}
//If the parent container is an overflow <div> with scrollbars, subtract the scroll offsets.
//You need to also add any offset between the <svg> element and its containing <div>
//Finally, add any offset of the containing <div> on the whole page.
left += chartContainer.offsetLeft + svgOffset.left - 2*chartContainer.scrollLeft;
top += chartContainer.offsetTop + svgOffset.top - 2*chartContainer.scrollTop;
}
if (snapDistance && snapDistance > 0) {
top = Math.floor(top/snapDistance) * snapDistance;
}
nv.tooltip.calcTooltipPosition([left,top], gravity, distance, container);
return nvtooltip;
};
nvtooltip.nvPointerEventsClass = nvPointerEventsClass;
nvtooltip.content = function(_) {
if (!arguments.length) return content;
content = _;
return nvtooltip;
};
//Returns tooltipElem...not able to set it.
nvtooltip.tooltipElem = function() {
return tooltipElem;
};
nvtooltip.contentGenerator = function(_) {
if (!arguments.length) return contentGenerator;
if (typeof _ === 'function') {
contentGenerator = _;
}
return nvtooltip;
};
nvtooltip.data = function(_) {
if (!arguments.length) return data;
data = _;
return nvtooltip;
};
nvtooltip.gravity = function(_) {
if (!arguments.length) return gravity;
gravity = _;
return nvtooltip;
};
nvtooltip.distance = function(_) {
if (!arguments.length) return distance;
distance = _;
return nvtooltip;
};
nvtooltip.snapDistance = function(_) {
if (!arguments.length) return snapDistance;
snapDistance = _;
return nvtooltip;
};
nvtooltip.classes = function(_) {
if (!arguments.length) return classes;
classes = _;
return nvtooltip;
};
nvtooltip.chartContainer = function(_) {
if (!arguments.length) return chartContainer;
chartContainer = _;
return nvtooltip;
};
nvtooltip.position = function(_) {
if (!arguments.length) return position;
position.left = (typeof _.left !== 'undefined') ? _.left : position.left;
position.top = (typeof _.top !== 'undefined') ? _.top : position.top;
return nvtooltip;
};
nvtooltip.fixedTop = function(_) {
if (!arguments.length) return fixedTop;
fixedTop = _;
return nvtooltip;
};
nvtooltip.enabled = function(_) {
if (!arguments.length) return enabled;
enabled = _;
return nvtooltip;
};
nvtooltip.valueFormatter = function(_) {
if (!arguments.length) return valueFormatter;
if (typeof _ === 'function') {
valueFormatter = _;
}
return nvtooltip;
};
nvtooltip.headerFormatter = function(_) {
if (!arguments.length) return headerFormatter;
if (typeof _ === 'function') {
headerFormatter = _;
}
return nvtooltip;
};
//id() is a read-only function. You can't use it to set the id.
nvtooltip.id = function() {
return id;
};
return nvtooltip;
};
//Original tooltip.show function. Kept for backward compatibility.
// pos = [left,top]
nv.tooltip.show = function(pos, content, gravity, dist, parentContainer, classes) {
//Create new tooltip div if it doesn't exist on DOM.
var container = document.createElement('div');
container.className = 'nvtooltip ' + (classes ? classes : 'xy-tooltip');
var body = parentContainer;
if ( !parentContainer || parentContainer.tagName.match(/g|svg/i)) {
//If the parent element is an SVG element, place tooltip in the <body> element.
body = document.getElementsByTagName('body')[0];
}
container.style.left = 0;
container.style.top = 0;
container.style.opacity = 0;
container.innerHTML = content;
body.appendChild(container);
//If the parent container is an overflow <div> with scrollbars, subtract the scroll offsets.
if (parentContainer) {
pos[0] = pos[0] - parentContainer.scrollLeft;
pos[1] = pos[1] - parentContainer.scrollTop;
}
nv.tooltip.calcTooltipPosition(pos, gravity, dist, container);
};
//Looks up the ancestry of a DOM element, and returns the first NON-svg node.
nv.tooltip.findFirstNonSVGParent = function(Elem) {
while(Elem.tagName.match(/^g|svg$/i) !== null) {
Elem = Elem.parentNode;
}
return Elem;
};
//Finds the total offsetTop of a given DOM element.
//Looks up the entire ancestry of an element, up to the first relatively positioned element.
nv.tooltip.findTotalOffsetTop = function ( Elem, initialTop ) {
var offsetTop = initialTop;
do {
if( !isNaN( Elem.offsetTop ) ) {
offsetTop += (Elem.offsetTop);
}
} while( Elem = Elem.offsetParent );
return offsetTop;
};
//Finds the total offsetLeft of a given DOM element.
//Looks up the entire ancestry of an element, up to the first relatively positioned element.
nv.tooltip.findTotalOffsetLeft = function ( Elem, initialLeft) {
var offsetLeft = initialLeft;
do {
if( !isNaN( Elem.offsetLeft ) ) {
offsetLeft += (Elem.offsetLeft);
}
} while( Elem = Elem.offsetParent );
return offsetLeft;
};
//Global utility function to render a tooltip on the DOM.
//pos = [left,top] coordinates of where to place the tooltip, relative to the SVG chart container.
//gravity = how to orient the tooltip
//dist = how far away from the mouse to place tooltip
//container = tooltip DIV
nv.tooltip.calcTooltipPosition = function(pos, gravity, dist, container) {
var height = parseInt(container.offsetHeight),
width = parseInt(container.offsetWidth),
windowWidth = nv.utils.windowSize().width,
windowHeight = nv.utils.windowSize().height,
scrollTop = window.pageYOffset,
scrollLeft = window.pageXOffset,
left, top;
windowHeight = window.innerWidth >= document.body.scrollWidth ? windowHeight : windowHeight - 16;
windowWidth = window.innerHeight >= document.body.scrollHeight ? windowWidth : windowWidth - 16;
gravity = gravity || 's';
dist = dist || 20;
var tooltipTop = function ( Elem ) {
return nv.tooltip.findTotalOffsetTop(Elem, top);
};
var tooltipLeft = function ( Elem ) {
return nv.tooltip.findTotalOffsetLeft(Elem,left);
};
switch (gravity) {
case 'e':
left = pos[0] - width - dist;
top = pos[1] - (height / 2);
var tLeft = tooltipLeft(container);
var tTop = tooltipTop(container);
if (tLeft < scrollLeft) left = pos[0] + dist > scrollLeft ? pos[0] + dist : scrollLeft - tLeft + left;
if (tTop < scrollTop) top = scrollTop - tTop + top;
if (tTop + height > scrollTop + windowHeight) top = scrollTop + windowHeight - tTop + top - height;
break;
case 'w':
left = pos[0] + dist;
top = pos[1] - (height / 2);
var tLeft = tooltipLeft(container);
var tTop = tooltipTop(container);
if (tLeft + width > windowWidth) left = pos[0] - width - dist;
if (tTop < scrollTop) top = scrollTop + 5;
if (tTop + height > scrollTop + windowHeight) top = scrollTop + windowHeight - tTop + top - height;
break;
case 'n':
left = pos[0] - (width / 2) - 5;
top = pos[1] + dist;
var tLeft = tooltipLeft(container);
var tTop = tooltipTop(container);
if (tLeft < scrollLeft) left = scrollLeft + 5;
if (tLeft + width > windowWidth) left = left - width/2 + 5;
if (tTop + height > scrollTop + windowHeight) top = scrollTop + windowHeight - tTop + top - height;
break;
case 's':
left = pos[0] - (width / 2);
top = pos[1] - height - dist;
var tLeft = tooltipLeft(container);
var tTop = tooltipTop(container);
if (tLeft < scrollLeft) left = scrollLeft + 5;
if (tLeft + width > windowWidth) left = left - width/2 + 5;
if (scrollTop > tTop) top = scrollTop;
break;
case 'none':
left = pos[0];
top = pos[1] - dist;
var tLeft = tooltipLeft(container);
var tTop = tooltipTop(container);
break;
}
container.style.left = left+'px';
container.style.top = top+'px';
container.style.opacity = 1;
container.style.position = 'absolute';
return container;
};
//Global utility function to remove tooltips from the DOM.
nv.tooltip.cleanup = function() {
// Find the tooltips, mark them for removal by this class (so others cleanups won't find it)
var tooltips = document.getElementsByClassName('nvtooltip');
var purging = [];
while(tooltips.length) {
purging.push(tooltips[0]);
tooltips[0].style.transitionDelay = '0 !important';
tooltips[0].style.opacity = 0;
tooltips[0].className = 'nvtooltip-pending-removal';
}
setTimeout(function() {
while (purging.length) {
var removeMe = purging.pop();
removeMe.parentNode.removeChild(removeMe);
}
}, 500);
};
})();
nv.utils.windowSize = function() {
// Sane defaults
var size = {width: 640, height: 480};
// Earlier IE uses Doc.body
if (document.body && document.body.offsetWidth) {
size.width = document.body.offsetWidth;
size.height = document.body.offsetHeight;
}
// IE can use depending on mode it is in
if (document.compatMode=='CSS1Compat' &&
document.documentElement &&
document.documentElement.offsetWidth ) {
size.width = document.documentElement.offsetWidth;
size.height = document.documentElement.offsetHeight;
}
// Most recent browsers use
if (window.innerWidth && window.innerHeight) {
size.width = window.innerWidth;
size.height = window.innerHeight;
}
return (size);
};
// Easy way to bind multiple functions to window.onresize
// TODO: give a way to remove a function after its bound, other than removing all of them
nv.utils.windowResize = function(fun){
if (fun === undefined) return;
var oldresize = window.onresize;
window.onresize = function(e) {
if (typeof oldresize == 'function') oldresize(e);
fun(e);
}
}
// Backwards compatible way to implement more d3-like coloring of graphs.
// If passed an array, wrap it in a function which implements the old default
// behavior
nv.utils.getColor = function(color) {
if (!arguments.length) return nv.utils.defaultColor(); //if you pass in nothing, get default colors back
if( Object.prototype.toString.call( color ) === '[object Array]' )
return function(d, i) { return d.color || color[i % color.length]; };
else
return color;
//can't really help it if someone passes rubbish as color
}
// Default color chooser uses the index of an object as before.
nv.utils.defaultColor = function() {
var colors = d3.scale.category20().range();
return function(d, i) { return d.color || colors[i % colors.length] };
}
// Returns a color function that takes the result of 'getKey' for each series and
// looks for a corresponding color from the dictionary,
nv.utils.customTheme = function(dictionary, getKey, defaultColors) {
getKey = getKey || function(series) { return series.key }; // use default series.key if getKey is undefined
defaultColors = defaultColors || d3.scale.category20().range(); //default color function
var defIndex = defaultColors.length; //current default color (going in reverse)
return function(series, index) {
var key = getKey(series);
if (!defIndex) defIndex = defaultColors.length; //used all the default colors, start over
if (typeof dictionary[key] !== "undefined")
return (typeof dictionary[key] === "function") ? dictionary[key]() : dictionary[key];
else
return defaultColors[--defIndex]; // no match in dictionary, use default color
}
}
// From the PJAX example on d3js.org, while this is not really directly needed
// it's a very cool method for doing pjax, I may expand upon it a little bit,
// open to suggestions on anything that may be useful
nv.utils.pjax = function(links, content) {
d3.selectAll(links).on("click", function() {
history.pushState(this.href, this.textContent, this.href);
load(this.href);
d3.event.preventDefault();
});
function load(href) {
d3.html(href, function(fragment) {
var target = d3.select(content).node();
target.parentNode.replaceChild(d3.select(fragment).select(content).node(), target);
nv.utils.pjax(links, content);
});
}
d3.select(window).on("popstate", function() {
if (d3.event.state) load(d3.event.state);
});
}
/* For situations where we want to approximate the width in pixels for an SVG:text element.
Most common instance is when the element is in a display:none; container.
Forumla is : text.length * font-size * constant_factor
*/
nv.utils.calcApproxTextWidth = function (svgTextElem) {
if (svgTextElem instanceof d3.selection) {
var fontSize = parseInt(svgTextElem.style("font-size").replace("px",""));
var textLength = svgTextElem.text().length;
return textLength * fontSize * 0.5;
}
return 0;
};
/* Numbers that are undefined, null or NaN, convert them to zeros.
*/
nv.utils.NaNtoZero = function(n) {
if (typeof n !== 'number'
|| isNaN(n)
|| n === null
|| n === Infinity) return 0;
return n;
};
/*
Snippet of code you can insert into each nv.models.* to give you the ability to
do things like:
chart.options({
showXAxis: true,
tooltips: true
});
To enable in the chart:
chart.options = nv.utils.optionsFunc.bind(chart);
*/
nv.utils.optionsFunc = function(args) {
if (args) {
d3.map(args).forEach((function(key,value) {
if (typeof this[key] === "function") {
this[key](value);
}
}).bind(this));
}
return this;
};nv.models.axis = function() {
"use strict";
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var axis = d3.svg.axis()
;