forked from ento/asana-charts-extension
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nv.d3.js
10516 lines (8109 loc) · 317 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 = {
version: '0.0.1a',
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
nv.log = function() {
if (nv.dev && console.log && console.log.apply) 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 timout loop
render.active = true;
nv.dispatch.render_start();
setTimeout(function() {
var chart;
for (var i = 0; i < step && (graph = render.queue[i]); i++) {
chart = graph.generate();
if (typeof graph.callback == typeof(Function)) graph.callback(chart);
nv.graphs.push(chart);
}
render.queue.splice(0, i);
if (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();
}
);
/*****
* A no frills tooltip implementation.
*****/
(function() {
var nvtooltip = window.nv.tooltip = {};
nvtooltip.show = function(pos, content, gravity, dist, parentContainer, classes) {
var container = document.createElement('div');
container.className = 'nvtooltip ' + (classes ? classes : 'xy-tooltip');
gravity = gravity || 's';
dist = dist || 20;
var body = parentContainer ? parentContainer : document.getElementsByTagName('body')[0];
container.innerHTML = content;
container.style.left = 0;
container.style.top = 0;
container.style.opacity = 0;
body.appendChild(container);
var height = parseInt(container.offsetHeight),
width = parseInt(container.offsetWidth),
windowWidth = nv.utils.windowSize().width,
windowHeight = nv.utils.windowSize().height,
scrollTop = body.scrollTop,
scrollLeft = body.scrollLeft,
left, top;
switch (gravity) {
case 'e':
left = pos[0] - width - dist;
top = pos[1] - (height / 2);
if (left < scrollLeft) left = pos[0] + dist;
if (top < scrollTop) top = scrollTop + 5;
if (top + height > scrollTop + windowHeight) top = scrollTop - height - 5;
break;
case 'w':
left = pos[0] + dist;
top = pos[1] - (height / 2);
if (left + width > windowWidth) left = pos[0] - width - dist;
if (top < scrollTop) top = scrollTop + 5;
if (top + height > scrollTop + windowHeight) top = scrollTop - height - 5;
break;
case 'n':
left = pos[0] - (width / 2);
top = pos[1] + dist;
if (left < scrollLeft) left = scrollLeft + 5;
if (left + width > windowWidth) left = windowWidth - width - 5;
if (top + height > scrollTop + windowHeight) top = pos[1] - height - dist;
break;
case 's':
left = pos[0] - (width / 2);
top = pos[1] - height - dist;
if (left < scrollLeft) left = scrollLeft + 5;
if (left + width > windowWidth) left = windowWidth - width - 5;
if (scrollTop > top) top = pos[1] + 20;
break;
}
container.style.left = left+'px';
container.style.top = top+'px';
container.style.opacity = 1;
container.style.position = 'absolute'; //fix scroll bar issue
container.style.pointerEvents = 'none'; //fix scroll bar issue
return container;
};
nvtooltip.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 alkl of them
nv.utils.windowResize = function(fun){
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
// behaviour
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 rubish 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);
});
}
nv.models.axis = function() {
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 60 //only used for tickLabel currently
, height = 60 //only used for tickLabel currently
, scale = d3.scale.linear()
, axisLabelText = null
, showMaxMin = true //TODO: showMaxMin should be disabled on all ordinal scaled axes
, highlightZero = true
, rotateLabels = 0
, rotateYLabel = true
, staggerLabels = false
, ticks = null
;
//============================================================
//============================================================
// Private Variables
//------------------------------------------------------------
var axis = d3.svg.axis()
.scale(scale)
.orient('bottom')
, scale0;
//============================================================
function chart(selection) {
selection.each(function(data) {
var container = d3.select(this);
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-axis').data([data]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-axis');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g')
//------------------------------------------------------------
if (ticks !== null)
axis.ticks(ticks);
else if (axis.orient() == 'top' || axis.orient() == 'bottom')
axis.ticks(Math.abs(scale.range()[1] - scale.range()[0]) / 100);
//TODO: consider calculating width/height based on whether or not label is added, for reference in charts using this component
d3.transition(g)
.call(axis);
scale0 = scale0 || axis.scale();
var fmt = axis.tickFormat();
if (fmt == null) {
fmt = scale0.tickFormat();
}
var axisLabel = g.selectAll('text.nv-axislabel')
.data([axisLabelText || null]);
axisLabel.exit().remove();
switch (axis.orient()) {
case 'top':
axisLabel.enter().append('text').attr('class', 'nv-axislabel')
.attr('text-anchor', 'middle')
.attr('y', 0);
var w = (scale.range().length==2) ? scale.range()[1] : (scale.range()[scale.range().length-1]+(scale.range()[1]-scale.range()[0]));
axisLabel
.attr('x', w/2);
if (showMaxMin) {
var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
.data(scale.domain());
axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text');
axisMaxMin.exit().remove();
axisMaxMin
.attr('transform', function(d,i) {
return 'translate(' + scale(d) + ',0)'
})
.select('text')
.attr('dy', '0em')
.attr('y', -axis.tickPadding())
.attr('text-anchor', 'middle')
.text(function(d,i) {
var v = fmt(d);
return ('' + v).match('NaN') ? '' : v;
});
d3.transition(axisMaxMin)
.attr('transform', function(d,i) {
return 'translate(' + scale.range()[i] + ',0)'
});
}
break;
case 'bottom':
var xLabelMargin = 30;
var maxTextWidth = 30;
var xTicks = g.selectAll('g').select("text");
if (rotateLabels%360) {
//Calculate the longest xTick width
xTicks.each(function(d,i){
var width = this.getBBox().width;
if(width > maxTextWidth) maxTextWidth = width;
});
//Convert to radians before calculating sin. Add 30 to margin for healthy padding.
var sin = Math.abs(Math.sin(rotateLabels*Math.PI/180));
var xLabelMargin = (sin ? sin*maxTextWidth : maxTextWidth)+30;
//Rotate all xTicks
xTicks
.attr('transform', function(d,i,j) { return 'rotate(' + rotateLabels + ' 0,0)' })
.attr('text-anchor', rotateLabels%360 > 0 ? 'start' : 'end');
}
axisLabel.enter().append('text').attr('class', 'nv-axislabel')
.attr('text-anchor', 'middle')
.attr('y', xLabelMargin);
var w = (scale.range().length==2) ? scale.range()[1] : (scale.range()[scale.range().length-1]+(scale.range()[1]-scale.range()[0]));
axisLabel
.attr('x', w/2);
if (showMaxMin) {
var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
.data(scale.domain());
axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text');
axisMaxMin.exit().remove();
axisMaxMin
.attr('transform', function(d,i) {
return 'translate(' + scale(d) + ',0)'
})
.select('text')
.attr('dy', '.71em')
.attr('y', axis.tickPadding())
.attr('transform', function(d,i,j) { return 'rotate(' + rotateLabels + ' 0,0)' })
.attr('text-anchor', rotateLabels ? (rotateLabels%360 > 0 ? 'start' : 'end') : 'middle')
.text(function(d,i) {
var v = fmt(d);
return ('' + v).match('NaN') ? '' : v;
});
d3.transition(axisMaxMin)
.attr('transform', function(d,i) {
return 'translate(' + scale.range()[i] + ',0)'
});
}
if (staggerLabels)
xTicks
.attr('transform', function(d,i) { return 'translate(0,' + (i % 2 == 0 ? '0' : '12') + ')' });
break;
case 'right':
axisLabel.enter().append('text').attr('class', 'nv-axislabel')
.attr('text-anchor', rotateYLabel ? 'middle' : 'begin')
.attr('transform', rotateYLabel ? 'rotate(90)' : '')
.attr('y', rotateYLabel ? (-Math.max(margin.right,width) - 12) : -10); //TODO: consider calculating this based on largest tick width... OR at least expose this on chart
axisLabel
.attr('x', rotateYLabel ? (scale.range()[0] / 2) : axis.tickPadding());
if (showMaxMin) {
var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
.data(scale.domain());
axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text')
.style('opacity', 0);
axisMaxMin.exit().remove();
axisMaxMin
.attr('transform', function(d,i) {
return 'translate(0,' + scale(d) + ')'
})
.select('text')
.attr('dy', '.32em')
.attr('y', 0)
.attr('x', axis.tickPadding())
.attr('text-anchor', 'start')
.text(function(d,i) {
var v = fmt(d);
return ('' + v).match('NaN') ? '' : v;
});
d3.transition(axisMaxMin)
.attr('transform', function(d,i) {
return 'translate(0,' + scale.range()[i] + ')'
})
.select('text')
.style('opacity', 1);
}
break;
case 'left':
axisLabel.enter().append('text').attr('class', 'nv-axislabel')
.attr('text-anchor', rotateYLabel ? 'middle' : 'end')
.attr('transform', rotateYLabel ? 'rotate(-90)' : '')
.attr('y', rotateYLabel ? (-Math.max(margin.left,width) + 12) : -10); //TODO: consider calculating this based on largest tick width... OR at least expose this on chart
axisLabel
.attr('x', rotateYLabel ? (-scale.range()[0] / 2) : -axis.tickPadding());
if (showMaxMin) {
var axisMaxMin = wrap.selectAll('g.nv-axisMaxMin')
.data(scale.domain());
axisMaxMin.enter().append('g').attr('class', 'nv-axisMaxMin').append('text')
.style('opacity', 0);
axisMaxMin.exit().remove();
axisMaxMin
.attr('transform', function(d,i) {
return 'translate(0,' + scale0(d) + ')'
})
.select('text')
.attr('dy', '.32em')
.attr('y', 0)
.attr('x', -axis.tickPadding())
.attr('text-anchor', 'end')
.text(function(d,i) {
var v = fmt(d);
return ('' + v).match('NaN') ? '' : v;
});
d3.transition(axisMaxMin)
.attr('transform', function(d,i) {
return 'translate(0,' + scale.range()[i] + ')'
})
.select('text')
.style('opacity', 1);
}
break;
}
axisLabel
.text(function(d) { return d });
//check if max and min overlap other values, if so, hide the values that overlap
if (showMaxMin && (axis.orient() === 'left' || axis.orient() === 'right')) {
g.selectAll('g') // the g's wrapping each tick
.each(function(d,i) {
if (scale(d) < scale.range()[1] + 10 || scale(d) > scale.range()[0] - 10) { // 10 is assuming text height is 16... if d is 0, leave it!
if (d > 1e-10 || d < -1e-10) // accounts for minor floating point errors... though could be problematic if the scale is EXTREMELY SMALL
d3.select(this).remove();
else
d3.select(this).select('text').remove(); // Don't remove the ZERO line!!
}
});
}
if (showMaxMin && (axis.orient() === 'top' || axis.orient() === 'bottom')) {
var maxMinRange = [];
wrap.selectAll('g.nv-axisMaxMin')
.each(function(d,i) {
if (i) // i== 1, max position
maxMinRange.push(scale(d) - this.getBBox().width - 4) //assuming the max and min labels are as wide as the next tick (with an extra 4 pixels just in case)
else // i==0, min position
maxMinRange.push(scale(d) + this.getBBox().width + 4)
});
g.selectAll('g') // the g's wrapping each tick
.each(function(d,i) {
if (scale(d) < maxMinRange[0] || scale(d) > maxMinRange[1]) {
if (d > 1e-10 || d < -1e-10) // accounts for minor floating point errors... though could be problematic if the scale is EXTREMELY SMALL
d3.select(this).remove();
else
d3.select(this).select('text').remove(); // Don't remove the ZERO line!!
}
});
}
//highlight zero line ... Maybe should not be an option and should just be in CSS?
if (highlightZero)
g.selectAll('line.tick')
.filter(function(d) { return !parseFloat(Math.round(d*100000)/1000000) }) //this is because sometimes the 0 tick is a very small fraction, TODO: think of cleaner technique
.classed('zero', true);
//store old scales for use in transitions on update
scale0 = scale.copy();
});
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
d3.rebind(chart, axis, 'orient', 'tickValues', 'tickSubdivide', 'tickSize', 'tickPadding', 'tickFormat');
d3.rebind(chart, scale, 'domain', 'range', 'rangeBand', 'rangeBands'); //these are also accessible by chart.scale(), but added common ones directly for ease of use
chart.margin = function(_) {
if(!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
}
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.ticks = function(_) {
if (!arguments.length) return ticks;
ticks = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.axisLabel = function(_) {
if (!arguments.length) return axisLabelText;
axisLabelText = _;
return chart;
}
chart.showMaxMin = function(_) {
if (!arguments.length) return showMaxMin;
showMaxMin = _;
return chart;
}
chart.highlightZero = function(_) {
if (!arguments.length) return highlightZero;
highlightZero = _;
return chart;
}
chart.scale = function(_) {
if (!arguments.length) return scale;
scale = _;
axis.scale(scale);
d3.rebind(chart, scale, 'domain', 'range', 'rangeBand', 'rangeBands');
return chart;
}
chart.rotateYLabel = function(_) {
if(!arguments.length) return rotateYLabel;
rotateYLabel = _;
return chart;
}
chart.rotateLabels = function(_) {
if(!arguments.length) return rotateLabels;
rotateLabels = _;
return chart;
}
chart.staggerLabels = function(_) {
if (!arguments.length) return staggerLabels;
staggerLabels = _;
return chart;
};
//============================================================
return chart;
}
//TODO: consider deprecating and using multibar with single series for this
nv.models.historicalBar = function() {
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, width = 960
, height = 500
, id = Math.floor(Math.random() * 10000) //Create semi-unique ID in case user doesn't select one
, x = d3.scale.linear()
, y = d3.scale.linear()
, getX = function(d) { return d.x }
, getY = function(d) { return d.y }
, forceX = []
, forceY = [0]
, clipEdge = true
, color = nv.utils.defaultColor()
, xDomain
, yDomain
, dispatch = d3.dispatch('chartClick', 'elementClick', 'elementDblClick', 'elementMouseover', 'elementMouseout')
;
//============================================================
function chart(selection) {
selection.each(function(data) {
var availableWidth = width - margin.left - margin.right,
availableHeight = height - margin.top - margin.bottom,
container = d3.select(this);
//------------------------------------------------------------
// Setup Scales
x .domain(xDomain || d3.extent(data[0].values.map(getX).concat(forceX) ))
.range([0, availableWidth]);
y .domain(yDomain || d3.extent(data[0].values.map(getY).concat(forceY) ))
.range([availableHeight, 0]);
// If scale's domain don't have a range, slightly adjust to make one... so a chart can show a single data point
if (x.domain()[0] === x.domain()[1] || y.domain()[0] === y.domain()[1]) singlePoint = true;
if (x.domain()[0] === x.domain()[1])
x.domain()[0] ?
x.domain([x.domain()[0] - x.domain()[0] * 0.01, x.domain()[1] + x.domain()[1] * 0.01])
: x.domain([-1,1]);
if (y.domain()[0] === y.domain()[1])
y.domain()[0] ?
y.domain([y.domain()[0] + y.domain()[0] * 0.01, y.domain()[1] - y.domain()[1] * 0.01])
: y.domain([-1,1]);
//------------------------------------------------------------
//------------------------------------------------------------
// Setup containers and skeleton of chart
var wrap = container.selectAll('g.nv-wrap.nv-bar').data([data[0].values]);
var wrapEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-wrap nv-bar');
var defsEnter = wrapEnter.append('defs');
var gEnter = wrapEnter.append('g');
var g = wrap.select('g');
gEnter.append('g').attr('class', 'nv-bars');
wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
//------------------------------------------------------------
container
.on('click', function(d,i) {
dispatch.chartClick({
data: d,
index: i,
pos: d3.event,
id: id
});
});
defsEnter.append('clipPath')
.attr('id', 'nv-chart-clip-path-' + id)
.append('rect');
wrap.select('#nv-chart-clip-path-' + id + ' rect')
.attr('width', availableWidth)
.attr('height', availableHeight);
g .attr('clip-path', clipEdge ? 'url(#nv-chart-clip-path-' + id + ')' : '');
var bars = wrap.select('.nv-bars').selectAll('.nv-bar')
.data(function(d) { return d });
bars.exit().remove();
var barsEnter = bars.enter().append('rect')
//.attr('class', function(d,i,j) { return (getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive') + ' nv-bar-' + j + '-' + i })
.attr('x', 0 )
.attr('y', function(d,i) { return y(Math.max(0, getY(d,i))) })
.attr('height', function(d,i) { return Math.abs(y(getY(d,i)) - y(0)) })
.on('mouseover', function(d,i) {
d3.select(this).classed('hover', true);
dispatch.elementMouseover({
point: d,
series: data[0],
pos: [x(getX(d,i)), y(getY(d,i))], // TODO: Figure out why the value appears to be shifted
pointIndex: i,
seriesIndex: 0,
e: d3.event
});
})
.on('mouseout', function(d,i) {
d3.select(this).classed('hover', false);
dispatch.elementMouseout({
point: d,
series: data[0],
pointIndex: i,
seriesIndex: 0,
e: d3.event
});
})
.on('click', function(d,i) {
dispatch.elementClick({
//label: d[label],
value: getY(d,i),
data: d,
index: i,
pos: [x(getX(d,i)), y(getY(d,i))],
e: d3.event,
id: id
});
d3.event.stopPropagation();
})
.on('dblclick', function(d,i) {
dispatch.elementDblClick({
//label: d[label],
value: getY(d,i),
data: d,
index: i,
pos: [x(getX(d,i)), y(getY(d,i))],
e: d3.event,
id: id
});
d3.event.stopPropagation();
});
bars
.attr('fill', function(d,i) { return color(d, i); })
.attr('class', function(d,i,j) { return (getY(d,i) < 0 ? 'nv-bar negative' : 'nv-bar positive') + ' nv-bar-' + j + '-' + i })
.attr('transform', function(d,i) { return 'translate(' + (x(getX(d,i)) - ((availableWidth / data[0].values.length) * .5)) + ',0)'; }) //TODO: better width calculations that don't assume always uniform data spacing;w
.attr('width', (availableWidth / data[0].values.length) * .9 )
d3.transition(bars)
.attr('y', function(d,i) { return y(Math.max(0, getY(d,i))) })
.attr('height', function(d,i) { return Math.abs(y(getY(d,i)) - y(0)) });
//.order(); // not sure if this makes any sense for this model
});
return chart;
}
//============================================================
// Expose Public Variables
//------------------------------------------------------------
chart.dispatch = dispatch;
chart.x = function(_) {
if (!arguments.length) return getX;
getX = _;
return chart;
};
chart.y = function(_) {
if (!arguments.length) return getY;
getY = _;
return chart;
};
chart.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
return chart;
};
chart.width = function(_) {
if (!arguments.length) return width;
width = _;
return chart;
};
chart.height = function(_) {
if (!arguments.length) return height;
height = _;
return chart;
};
chart.xScale = function(_) {
if (!arguments.length) return x;
x = _;
return chart;
};
chart.yScale = function(_) {
if (!arguments.length) return y;
y = _;
return chart;
};
chart.xDomain = function(_) {
if (!arguments.length) return xDomain;
xDomain = _;
return chart;
};
chart.yDomain = function(_) {
if (!arguments.length) return yDomain;
yDomain = _;
return chart;
};
chart.forceX = function(_) {
if (!arguments.length) return forceX;
forceX = _;
return chart;
};
chart.forceY = function(_) {
if (!arguments.length) return forceY;
forceY = _;
return chart;
};
chart.clipEdge = function(_) {
if (!arguments.length) return clipEdge;
clipEdge = _;
return chart;
};
chart.color = function(_) {
if (!arguments.length) return color;
color = nv.utils.getColor(_);
return chart;
};
chart.id = function(_) {
if (!arguments.length) return id;
id = _;
return chart;
};
//============================================================
return chart;
}
// Chart design based on the recommendations of Stephen Few. Implementation
// based on the work of Clint Ivy, Jamie Love, and Jason Davies.
// http://projects.instantcognition.com/protovis/bulletchart/
nv.models.bullet = function() {
//============================================================
// Public Variables with Default Settings
//------------------------------------------------------------
var margin = {top: 0, right: 0, bottom: 0, left: 0}
, orient = 'left' // TODO top & bottom
, reverse = false
, ranges = function(d) { return d.ranges }
, markers = function(d) { return d.markers }
, measures = function(d) { return d.measures }
, forceX = [0] // List of numbers to Force into the X scale (ie. 0, or a max / min, etc.)
, width = 380
, height = 30
, tickFormat = null
, dispatch = d3.dispatch('elementMouseover', 'elementMouseout')
;
//============================================================
function chart(selection) {
selection.each(function(d, i) {
var availableWidth = width - margin.left - margin.right,
availableHeight = height - margin.top - margin.bottom,
container = d3.select(this);
var rangez = ranges.call(this, d, i).slice().sort(d3.descending),
markerz = markers.call(this, d, i).slice().sort(d3.descending),
measurez = measures.call(this, d, i).slice().sort(d3.descending);
//------------------------------------------------------------
// Setup Scales
// Compute the new x-scale.
var x1 = d3.scale.linear()
.domain([0, Math.max(rangez[0], markerz[0], measurez[0])]) // TODO: need to allow forceX and forceY, and xDomain, yDomain
.range(reverse ? [availableWidth, 0] : [0, availableWidth]);
// Retrieve the old x-scale, if this is an update.
var x0 = this.__chart__ || d3.scale.linear()
.domain([0, Infinity])