forked from danvk/dygraphs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dygraph.js
2544 lines (2273 loc) · 78.5 KB
/
dygraph.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
// Copyright 2006 Dan Vanderkam ([email protected])
// All Rights Reserved.
/**
* @fileoverview Creates an interactive, zoomable graph based on a CSV file or
* string. Dygraph can handle multiple series with or without error bars. The
* date/value ranges will be automatically set. Dygraph uses the
* <canvas> tag, so it only works in FF1.5+.
* @author [email protected] (Dan Vanderkam)
Usage:
<div id="graphdiv" style="width:800px; height:500px;"></div>
<script type="text/javascript">
new Dygraph(document.getElementById("graphdiv"),
"datafile.csv", // CSV file with headers
{ }); // options
</script>
The CSV file is of the form
Date,SeriesA,SeriesB,SeriesC
YYYYMMDD,A1,B1,C1
YYYYMMDD,A2,B2,C2
If the 'errorBars' option is set in the constructor, the input should be of
the form
Date,SeriesA,SeriesB,...
YYYYMMDD,A1,sigmaA1,B1,sigmaB1,...
YYYYMMDD,A2,sigmaA2,B2,sigmaB2,...
If the 'fractions' option is set, the input should be of the form:
Date,SeriesA,SeriesB,...
YYYYMMDD,A1/B1,A2/B2,...
YYYYMMDD,A1/B1,A2/B2,...
And error bars will be calculated automatically using a binomial distribution.
For further documentation and examples, see http://www.danvk.org/dygraphs
*/
/**
* An interactive, zoomable graph
* @param {String | Function} file A file containing CSV data or a function that
* returns this data. The expected format for each line is
* YYYYMMDD,val1,val2,... or, if attrs.errorBars is set,
* YYYYMMDD,val1,stddev1,val2,stddev2,...
* @param {Object} attrs Various other attributes, e.g. errorBars determines
* whether the input data contains error ranges.
*/
Dygraph = function(div, data, opts) {
if (arguments.length > 0) {
if (arguments.length == 4) {
// Old versions of dygraphs took in the series labels as a constructor
// parameter. This doesn't make sense anymore, but it's easy to continue
// to support this usage.
this.warn("Using deprecated four-argument dygraph constructor");
this.__old_init__(div, data, arguments[2], arguments[3]);
} else {
this.__init__(div, data, opts);
}
}
};
Dygraph.NAME = "Dygraph";
Dygraph.VERSION = "1.2";
Dygraph.__repr__ = function() {
return "[" + this.NAME + " " + this.VERSION + "]";
};
Dygraph.toString = function() {
return this.__repr__();
};
// Various default values
Dygraph.DEFAULT_ROLL_PERIOD = 1;
Dygraph.DEFAULT_WIDTH = 480;
Dygraph.DEFAULT_HEIGHT = 320;
Dygraph.AXIS_LINE_WIDTH = 0.3;
// Default attribute values.
Dygraph.DEFAULT_ATTRS = {
highlightCircleSize: 3,
pixelsPerXLabel: 60,
pixelsPerYLabel: 30,
labelsDivWidth: 250,
labelsDivStyles: {
// TODO(danvk): move defaults from createStatusMessage_ here.
},
labelsSeparateLines: false,
labelsShowZeroValues: true,
labelsKMB: false,
labelsKMG2: false,
showLabelsOnHighlight: true,
yValueFormatter: function(x) { return Dygraph.round_(x, 2); },
strokeWidth: 1.0,
axisTickSize: 3,
axisLabelFontSize: 14,
xAxisLabelWidth: 50,
yAxisLabelWidth: 50,
xAxisLabelFormatter: Dygraph.dateAxisFormatter,
rightGap: 5,
showRoller: false,
xValueFormatter: Dygraph.dateString_,
xValueParser: Dygraph.dateParser,
xTicker: Dygraph.dateTicker,
delimiter: ',',
logScale: false,
sigma: 2.0,
errorBars: false,
fractions: false,
wilsonInterval: true, // only relevant if fractions is true
customBars: false,
fillGraph: false,
fillAlpha: 0.15,
connectSeparatedPoints: false,
stackedGraph: false,
hideOverlayOnMouseOut: true,
stepPlot: false,
avoidMinZero: false
};
// Various logging levels.
Dygraph.DEBUG = 1;
Dygraph.INFO = 2;
Dygraph.WARNING = 3;
Dygraph.ERROR = 3;
// Used for initializing annotation CSS rules only once.
Dygraph.addedAnnotationCSS = false;
Dygraph.prototype.__old_init__ = function(div, file, labels, attrs) {
// Labels is no longer a constructor parameter, since it's typically set
// directly from the data source. It also conains a name for the x-axis,
// which the previous constructor form did not.
if (labels != null) {
var new_labels = ["Date"];
for (var i = 0; i < labels.length; i++) new_labels.push(labels[i]);
Dygraph.update(attrs, { 'labels': new_labels });
}
this.__init__(div, file, attrs);
};
/**
* Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
* and interaction <canvas> inside of it. See the constructor for details
* on the parameters.
* @param {Element} div the Element to render the graph into.
* @param {String | Function} file Source data
* @param {Object} attrs Miscellaneous other options
* @private
*/
Dygraph.prototype.__init__ = function(div, file, attrs) {
// Support two-argument constructor
if (attrs == null) { attrs = {}; }
// Copy the important bits into the object
// TODO(danvk): most of these should just stay in the attrs_ dictionary.
this.maindiv_ = div;
this.file_ = file;
this.rollPeriod_ = attrs.rollPeriod || Dygraph.DEFAULT_ROLL_PERIOD;
this.previousVerticalX_ = -1;
this.fractions_ = attrs.fractions || false;
this.dateWindow_ = attrs.dateWindow || null;
this.valueRange_ = attrs.valueRange || null;
this.wilsonInterval_ = attrs.wilsonInterval || true;
this.is_initial_draw_ = true;
this.annotations_ = [];
// Clear the div. This ensure that, if multiple dygraphs are passed the same
// div, then only one will be drawn.
div.innerHTML = "";
// If the div isn't already sized then inherit from our attrs or
// give it a default size.
var $div = $(div);
if (!$div.width()) {
div.style.width = attrs.width || Dygraph.DEFAULT_WIDTH + "px";
}
if (!$div.height()) {
div.style.height = attrs.height || Dygraph.DEFAULT_HEIGHT + "px";
}
this.width_ = parseInt($div.width(), 10);
this.height_ = parseInt($div.height(), 10);
// The div might have been specified as percent of the current window size,
// convert that to an appropriate number of pixels.
if (div.style.width.indexOf("%") == div.style.width.length - 1) {
this.width_ = div.offsetWidth;
}
if (div.style.height.indexOf("%") == div.style.height.length - 1) {
this.height_ = div.offsetHeight;
}
if (this.width_ == 0) {
this.error("dygraph has zero width. Please specify a width in pixels.");
}
if (this.height_ == 0) {
this.error("dygraph has zero height. Please specify a height in pixels.");
}
// TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
if (attrs['stackedGraph']) {
attrs['fillGraph'] = true;
// TODO(nikhilk): Add any other stackedGraph checks here.
}
// Dygraphs has many options, some of which interact with one another.
// To keep track of everything, we maintain two sets of options:
//
// this.user_attrs_ only options explicitly set by the user.
// this.attrs_ defaults, options derived from user_attrs_, data.
//
// Options are then accessed this.attr_('attr'), which first looks at
// user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
// defaults without overriding behavior that the user specifically asks for.
this.user_attrs_ = {};
Dygraph.update(this.user_attrs_, attrs);
this.attrs_ = {};
Dygraph.update(this.attrs_, Dygraph.DEFAULT_ATTRS);
this.boundaryIds_ = [];
// Make a note of whether labels will be pulled from the CSV file.
this.labelsFromCSV_ = (this.attr_("labels") == null);
// Create the containing DIV and other interactive elements
this.createInterface_();
this.start_();
};
Dygraph.prototype.attr_ = function(name, seriesName) {
if (seriesName &&
typeof(this.user_attrs_[seriesName]) != 'undefined' &&
this.user_attrs_[seriesName] != null &&
typeof(this.user_attrs_[seriesName][name]) != 'undefined') {
return this.user_attrs_[seriesName][name];
} else if (typeof(this.user_attrs_[name]) != 'undefined') {
return this.user_attrs_[name];
} else if (typeof(this.attrs_[name]) != 'undefined') {
return this.attrs_[name];
} else {
return null;
}
};
// TODO(danvk): any way I can get the line numbers to be this.warn call?
Dygraph.prototype.log = function(severity, message) {
if (typeof(console) != 'undefined') {
switch (severity) {
case Dygraph.DEBUG:
console.debug('dygraphs: ' + message);
break;
case Dygraph.INFO:
console.info('dygraphs: ' + message);
break;
case Dygraph.WARNING:
console.warn('dygraphs: ' + message);
break;
case Dygraph.ERROR:
console.error('dygraphs: ' + message);
break;
}
}
}
Dygraph.prototype.info = function(message) {
this.log(Dygraph.INFO, message);
}
Dygraph.prototype.warn = function(message) {
this.log(Dygraph.WARNING, message);
}
Dygraph.prototype.error = function(message) {
this.log(Dygraph.ERROR, message);
}
/**
* Returns the current rolling period, as set by the user or an option.
* @return {Number} The number of days in the rolling window
*/
Dygraph.prototype.rollPeriod = function() {
return this.rollPeriod_;
};
/**
* Returns the currently-visible x-range. This can be affected by zooming,
* panning or a call to updateOptions.
* Returns a two-element array: [left, right].
* If the Dygraph has dates on the x-axis, these will be millis since epoch.
*/
Dygraph.prototype.xAxisRange = function() {
if (this.dateWindow_) return this.dateWindow_;
// The entire chart is visible.
var left = this.rawData_[0][0];
var right = this.rawData_[this.rawData_.length - 1][0];
return [left, right];
};
/**
* Returns the currently-visible y-range. This can be affected by zooming,
* panning or a call to updateOptions.
* Returns a two-element array: [bottom, top].
*/
Dygraph.prototype.yAxisRange = function() {
return this.displayedYRange_;
};
/**
* Convert from data coordinates to canvas/div X/Y coordinates.
* Returns a two-element array: [X, Y]
*/
Dygraph.prototype.toDomCoords = function(x, y) {
var ret = [null, null];
var area = this.plotter_.area;
if (x !== null) {
var xRange = this.xAxisRange();
ret[0] = area.x + (x - xRange[0]) / (xRange[1] - xRange[0]) * area.w;
}
if (y !== null) {
var yRange = this.yAxisRange();
ret[1] = area.y + (yRange[1] - y) / (yRange[1] - yRange[0]) * area.h;
}
return ret;
};
// TODO(danvk): use these functions throughout dygraphs.
/**
* Convert from canvas/div coords to data coordinates.
* Returns a two-element array: [X, Y]
*/
Dygraph.prototype.toDataCoords = function(x, y) {
var ret = [null, null];
var area = this.plotter_.area;
if (x !== null) {
var xRange = this.xAxisRange();
ret[0] = xRange[0] + (x - area.x) / area.w * (xRange[1] - xRange[0]);
}
if (y !== null) {
var yRange = this.yAxisRange();
ret[1] = yRange[0] + (area.h - y) / area.h * (yRange[1] - yRange[0]);
}
return ret;
};
/**
* Returns the number of columns (including the independent variable).
*/
Dygraph.prototype.numColumns = function() {
return this.rawData_[0].length;
};
/**
* Returns the number of rows (excluding any header/label row).
*/
Dygraph.prototype.numRows = function() {
return this.rawData_.length;
};
/**
* Returns the value in the given row and column. If the row and column exceed
* the bounds on the data, returns null. Also returns null if the value is
* missing.
*/
Dygraph.prototype.getValue = function(row, col) {
if (row < 0 || row > this.rawData_.length) return null;
if (col < 0 || col > this.rawData_[row].length) return null;
return this.rawData_[row][col];
};
Dygraph.addEvent = function(el, evt, fn) {
var normed_fn = function(e) {
if (!e) var e = window.event;
fn(e);
};
if (window.addEventListener) { // Mozilla, Netscape, Firefox
el.addEventListener(evt, normed_fn, false);
} else { // IE
el.attachEvent('on' + evt, normed_fn);
}
};
Dygraph.clipCanvas_ = function(cnv, clip) {
var ctx = cnv.getContext("2d");
ctx.beginPath();
ctx.rect(clip.left, clip.top, clip.width, clip.height);
ctx.clip();
};
/**
* Generates interface elements for the Dygraph: a containing div, a div to
* display the current point, and a textbox to adjust the rolling average
* period. Also creates the Renderer/Layout elements.
* @private
*/
Dygraph.prototype.createInterface_ = function() {
// Create the all-enclosing graph div
var enclosing = this.maindiv_;
this.graphDiv = document.createElement("div");
this.graphDiv.style.width = this.width_ + "px";
this.graphDiv.style.height = this.height_ + "px";
enclosing.appendChild(this.graphDiv);
var clip = {
top: 0,
left: this.attr_("yAxisLabelWidth") + 2 * this.attr_("axisTickSize")
};
clip.width = this.width_ - clip.left - this.attr_("rightGap");
clip.height = this.height_ - this.attr_("axisLabelFontSize")
- 2 * this.attr_("axisTickSize");
this.clippingArea_ = clip;
// Create the canvas for interactive parts of the chart.
this.canvas_ = Dygraph.createCanvas();
this.canvas_.style.position = "absolute";
this.canvas_.width = this.width_;
this.canvas_.height = this.height_;
this.canvas_.style.width = this.width_ + "px"; // for IE
this.canvas_.style.height = this.height_ + "px"; // for IE
// ... and for static parts of the chart.
this.hidden_ = this.createPlotKitCanvas_(this.canvas_);
// The interactive parts of the graph are drawn on top of the chart.
this.graphDiv.appendChild(this.hidden_);
this.graphDiv.appendChild(this.canvas_);
this.mouseEventElement_ = this.canvas_;
// Make sure we don't overdraw.
Dygraph.clipCanvas_(this.hidden_, this.clippingArea_);
Dygraph.clipCanvas_(this.canvas_, this.clippingArea_);
var dygraph = this;
/*
Dygraph.addEvent(this.mouseEventElement_, 'mousemove', function(e) {
dygraph.mouseMove_(e);
});
*/
Dygraph.addEvent(this.mouseEventElement_, 'mouseout', function(e) {
dygraph.mouseOut_(e);
});
// Create the grapher
// TODO(danvk): why does the Layout need its own set of options?
this.layoutOptions_ = { 'xOriginIsZero': false };
Dygraph.update(this.layoutOptions_, this.attrs_);
Dygraph.update(this.layoutOptions_, this.user_attrs_);
Dygraph.update(this.layoutOptions_, {
'errorBars': (this.attr_("errorBars") || this.attr_("customBars")) });
this.layout_ = new DygraphLayout(this, this.layoutOptions_);
// TODO(danvk): why does the Renderer need its own set of options?
this.renderOptions_ = { colorScheme: this.colors_,
strokeColor: null,
axisLineWidth: Dygraph.AXIS_LINE_WIDTH };
Dygraph.update(this.renderOptions_, this.attrs_);
Dygraph.update(this.renderOptions_, this.user_attrs_);
this.plotter_ = new DygraphCanvasRenderer(this,
this.hidden_, this.layout_,
this.renderOptions_);
this.createStatusMessage_();
this.createRollInterface_();
this.createDragInterface_();
};
/**
* Detach DOM elements in the dygraph and null out all data references.
* Calling this when you're done with a dygraph can dramatically reduce memory
* usage. See, e.g., the tests/perf.html example.
*/
Dygraph.prototype.destroy = function() {
var removeRecursive = function(node) {
while (node.hasChildNodes()) {
removeRecursive(node.firstChild);
node.removeChild(node.firstChild);
}
};
removeRecursive(this.maindiv_);
var nullOut = function(obj) {
for (var n in obj) {
if (typeof(obj[n]) === 'object') {
obj[n] = null;
}
}
};
// These may not all be necessary, but it can't hurt...
nullOut(this.layout_);
nullOut(this.plotter_);
nullOut(this);
};
/**
* Creates the canvas containing the PlotKit graph. Only plotkit ever draws on
* this particular canvas. All Dygraph work is done on this.canvas_.
* @param {Object} canvas The Dygraph canvas over which to overlay the plot
* @return {Object} The newly-created canvas
* @private
*/
Dygraph.prototype.createPlotKitCanvas_ = function(canvas) {
var h = Dygraph.createCanvas();
h.style.position = "absolute";
// TODO(danvk): h should be offset from canvas. canvas needs to include
// some extra area to make it easier to zoom in on the far left and far
// right. h needs to be precisely the plot area, so that clipping occurs.
h.style.top = canvas.style.top;
h.style.left = canvas.style.left;
h.width = this.width_;
h.height = this.height_;
h.style.width = this.width_ + "px"; // for IE
h.style.height = this.height_ + "px"; // for IE
return h;
};
// Taken from MochiKit.Color
Dygraph.hsvToRGB = function (hue, saturation, value) {
var red;
var green;
var blue;
if (saturation === 0) {
red = value;
green = value;
blue = value;
} else {
var i = Math.floor(hue * 6);
var f = (hue * 6) - i;
var p = value * (1 - saturation);
var q = value * (1 - (saturation * f));
var t = value * (1 - (saturation * (1 - f)));
switch (i) {
case 1: red = q; green = value; blue = p; break;
case 2: red = p; green = value; blue = t; break;
case 3: red = p; green = q; blue = value; break;
case 4: red = t; green = p; blue = value; break;
case 5: red = value; green = p; blue = q; break;
case 6: // fall through
case 0: red = value; green = t; blue = p; break;
}
}
red = Math.floor(255 * red + 0.5);
green = Math.floor(255 * green + 0.5);
blue = Math.floor(255 * blue + 0.5);
return 'rgb(' + red + ',' + green + ',' + blue + ')';
};
/**
* Generate a set of distinct colors for the data series. This is done with a
* color wheel. Saturation/Value are customizable, and the hue is
* equally-spaced around the color wheel. If a custom set of colors is
* specified, that is used instead.
* @private
*/
Dygraph.prototype.setColors_ = function() {
// TODO(danvk): compute this directly into this.attrs_['colorScheme'] and do
// away with this.renderOptions_.
var num = this.attr_("labels").length - 1;
this.colors_ = [];
var colors = this.attr_('colors');
if (!colors) {
var sat = this.attr_('colorSaturation') || 1.0;
var val = this.attr_('colorValue') || 0.5;
var half = Math.ceil(num / 2);
for (var i = 1; i <= num; i++) {
if (!this.visibility()[i-1]) continue;
// alternate colors for high contrast.
var idx = i % 2 ? Math.ceil(i / 2) : (half + i / 2);
var hue = (1.0 * idx/ (1 + num));
this.colors_.push(Dygraph.hsvToRGB(hue, sat, val));
}
} else {
for (var i = 0; i < num; i++) {
if (!this.visibility()[i]) continue;
var colorStr = colors[i % colors.length];
this.colors_.push(colorStr);
}
}
// TODO(danvk): update this w/r/t/ the new options system.
this.renderOptions_.colorScheme = this.colors_;
Dygraph.update(this.plotter_.options, this.renderOptions_);
Dygraph.update(this.layoutOptions_, this.user_attrs_);
Dygraph.update(this.layoutOptions_, this.attrs_);
}
/**
* Return the list of colors. This is either the list of colors passed in the
* attributes, or the autogenerated list of rgb(r,g,b) strings.
* @return {Array<string>} The list of colors.
*/
Dygraph.prototype.getColors = function() {
return this.colors_;
};
// The following functions are from quirksmode.org with a modification for Safari from
// http://blog.firetree.net/2005/07/04/javascript-find-position/
// http://www.quirksmode.org/js/findpos.html
Dygraph.findPosX = function(obj) {
var curleft = 0;
if(obj.offsetParent)
while(1)
{
curleft += obj.offsetLeft;
if(!obj.offsetParent)
break;
obj = obj.offsetParent;
}
else if(obj.x)
curleft += obj.x;
return curleft;
};
Dygraph.findPosY = function(obj) {
var curtop = 0;
if(obj.offsetParent)
while(1)
{
curtop += obj.offsetTop;
if(!obj.offsetParent)
break;
obj = obj.offsetParent;
}
else if(obj.y)
curtop += obj.y;
return curtop;
};
/**
* Create the div that contains information on the selected point(s)
* This goes in the top right of the canvas, unless an external div has already
* been specified.
* @private
*/
Dygraph.prototype.createStatusMessage_ = function() {
var userLabelsDiv = this.user_attrs_["labelsDiv"];
if (userLabelsDiv && null != userLabelsDiv
&& (typeof(userLabelsDiv) == "string" || userLabelsDiv instanceof String)) {
this.user_attrs_["labelsDiv"] = document.getElementById(userLabelsDiv);
}
if (!this.attr_("labelsDiv")) {
var divWidth = this.attr_('labelsDivWidth');
var messagestyle = {
"position": "absolute",
"fontSize": "14px",
"zIndex": 10,
"width": divWidth + "px",
"top": "0px",
"left": (this.width_ - divWidth - 2) + "px",
"background": "white",
"textAlign": "left",
"overflow": "hidden"};
Dygraph.update(messagestyle, this.attr_('labelsDivStyles'));
var div = document.createElement("div");
for (var name in messagestyle) {
if (messagestyle.hasOwnProperty(name)) {
div.style[name] = messagestyle[name];
}
}
this.graphDiv.appendChild(div);
this.attrs_.labelsDiv = div;
}
};
/**
* Create the text box to adjust the averaging period
* @return {Object} The newly-created text box
* @private
*/
Dygraph.prototype.createRollInterface_ = function() {
var display = this.attr_('showRoller') ? "block" : "none";
var textAttr = { "position": "absolute",
"zIndex": 10,
"top": (this.plotter_.area.h - 25) + "px",
"left": (this.plotter_.area.x + 1) + "px",
"display": display
};
var roller = document.createElement("input");
roller.type = "text";
roller.size = "2";
roller.value = this.rollPeriod_;
for (var name in textAttr) {
if (textAttr.hasOwnProperty(name)) {
roller.style[name] = textAttr[name];
}
}
var pa = this.graphDiv;
pa.appendChild(roller);
var dygraph = this;
roller.onchange = function() { dygraph.adjustRoll(roller.value); };
return roller;
};
// These functions are taken from MochiKit.Signal
Dygraph.pageX = function(e) {
if (e.pageX) {
return (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
} else {
var de = document;
var b = document.body;
return e.clientX +
(de.scrollLeft || b.scrollLeft) -
(de.clientLeft || 0);
}
};
Dygraph.pageY = function(e) {
if (e.pageY) {
return (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
} else {
var de = document;
var b = document.body;
return e.clientY +
(de.scrollTop || b.scrollTop) -
(de.clientTop || 0);
}
};
/**
* Set up all the mouse handlers needed to capture dragging behavior for zoom
* events.
* @private
*/
Dygraph.prototype.createDragInterface_ = function() {
var self = this;
// Tracks whether the mouse is down right now
var isZooming = false;
var isPanning = false;
var dragStartX = null;
var dragStartY = null;
var dragEndX = null;
var dragEndY = null;
var prevEndX = null;
var draggingDate = null;
var dateRange = null;
// Utility function to convert page-wide coordinates to canvas coords
var px = 0;
var py = 0;
var getX = function(e) { return Dygraph.pageX(e) - px };
var getY = function(e) { return Dygraph.pageY(e) - py };
// Draw zoom rectangles when the mouse is down and the user moves around
Dygraph.addEvent(this.mouseEventElement_, 'mousemove', function(event) {
if (isZooming) {
dragEndX = getX(event);
dragEndY = getY(event);
self.drawZoomRect_(dragStartX, dragEndX, prevEndX);
prevEndX = dragEndX;
} else if (isPanning) {
dragEndX = getX(event);
dragEndY = getY(event);
// Want to have it so that:
// 1. draggingDate appears at dragEndX
// 2. daterange = (dateWindow_[1] - dateWindow_[0]) is unaltered.
self.dateWindow_[0] = draggingDate - (dragEndX / self.width_) * dateRange;
self.dateWindow_[1] = self.dateWindow_[0] + dateRange;
self.drawGraph_(self.rawData_);
}
});
// Track the beginning of drag events
Dygraph.addEvent(this.mouseEventElement_, 'mousedown', function(event) {
px = Dygraph.findPosX(self.canvas_);
py = Dygraph.findPosY(self.canvas_);
dragStartX = getX(event);
dragStartY = getY(event);
if (event.altKey || event.shiftKey) {
if (!self.dateWindow_) return; // have to be zoomed in to pan.
isPanning = true;
dateRange = self.dateWindow_[1] - self.dateWindow_[0];
draggingDate = (dragStartX / self.width_) * dateRange +
self.dateWindow_[0];
} else {
isZooming = true;
}
});
// If the user releases the mouse button during a drag, but not over the
// canvas, then it doesn't count as a zooming action.
Dygraph.addEvent(document, 'mouseup', function(event) {
if (isZooming || isPanning) {
isZooming = false;
dragStartX = null;
dragStartY = null;
}
if (isPanning) {
isPanning = false;
draggingDate = null;
dateRange = null;
}
});
// Temporarily cancel the dragging event when the mouse leaves the graph
Dygraph.addEvent(this.mouseEventElement_, 'mouseout', function(event) {
if (isZooming) {
dragEndX = null;
dragEndY = null;
}
});
// If the mouse is released on the canvas during a drag event, then it's a
// zoom. Only do the zoom if it's over a large enough area (>= 10 pixels)
Dygraph.addEvent(this.mouseEventElement_, 'mouseup', function(event) {
if (isZooming) {
isZooming = false;
dragEndX = getX(event);
dragEndY = getY(event);
var regionWidth = Math.abs(dragEndX - dragStartX);
var regionHeight = Math.abs(dragEndY - dragStartY);
if (regionWidth < 2 && regionHeight < 2 &&
self.lastx_ != undefined && self.lastx_ != -1) {
// TODO(danvk): pass along more info about the points, e.g. 'x'
if (self.attr_('clickCallback') != null) {
self.attr_('clickCallback')(event, self.lastx_, self.selPoints_);
}
if (self.attr_('pointClickCallback')) {
// check if the click was on a particular point.
var closestIdx = -1;
var closestDistance = 0;
for (var i = 0; i < self.selPoints_.length; i++) {
var p = self.selPoints_[i];
var distance = Math.pow(p.canvasx - dragEndX, 2) +
Math.pow(p.canvasy - dragEndY, 2);
if (closestIdx == -1 || distance < closestDistance) {
closestDistance = distance;
closestIdx = i;
}
}
// Allow any click within two pixels of the dot.
var radius = self.attr_('highlightCircleSize') + 2;
if (closestDistance <= 5 * 5) {
self.attr_('pointClickCallback')(event, self.selPoints_[closestIdx]);
}
}
}
if (regionWidth >= 10) {
self.doZoom_(Math.min(dragStartX, dragEndX),
Math.max(dragStartX, dragEndX));
} else {
self.canvas_.getContext("2d").clearRect(0, 0,
self.canvas_.width,
self.canvas_.height);
}
dragStartX = null;
dragStartY = null;
}
if (isPanning) {
isPanning = false;
draggingDate = null;
dateRange = null;
}
});
// Double-clicking zooms back out
Dygraph.addEvent(this.mouseEventElement_, 'dblclick', function(event) {
if (self.dateWindow_ == null) return;
self.dateWindow_ = null;
self.drawGraph_(self.rawData_);
var minDate = self.rawData_[0][0];
var maxDate = self.rawData_[self.rawData_.length - 1][0];
if (self.attr_("zoomCallback")) {
self.attr_("zoomCallback")(minDate, maxDate);
}
});
};
/**
* Draw a gray zoom rectangle over the desired area of the canvas. Also clears
* up any previous zoom rectangles that were drawn. This could be optimized to
* avoid extra redrawing, but it's tricky to avoid interactions with the status
* dots.
* @param {Number} startX The X position where the drag started, in canvas
* coordinates.
* @param {Number} endX The current X position of the drag, in canvas coords.
* @param {Number} prevEndX The value of endX on the previous call to this
* function. Used to avoid excess redrawing
* @private
*/
Dygraph.prototype.drawZoomRect_ = function(startX, endX, prevEndX) {
var ctx = this.canvas_.getContext("2d");
// Clean up from the previous rect if necessary
if (prevEndX) {
ctx.clearRect(Math.min(startX, prevEndX), 0,
Math.abs(startX - prevEndX), this.height_);
}
// Draw a light-grey rectangle to show the new viewing area
if (endX && startX) {
ctx.fillStyle = "rgba(128,128,128,0.33)";
ctx.fillRect(Math.min(startX, endX), 0,
Math.abs(endX - startX), this.height_);
}
};
/**
* Zoom to something containing [lowX, highX]. These are pixel coordinates
* in the canvas. The exact zoom window may be slightly larger if there are no
* data points near lowX or highX. This function redraws the graph.
* @param {Number} lowX The leftmost pixel value that should be visible.
* @param {Number} highX The rightmost pixel value that should be visible.
* @private
*/
Dygraph.prototype.doZoom_ = function(lowX, highX) {
// Find the earliest and latest dates contained in this canvasx range.
var r = this.toDataCoords(lowX, null);
var minDate = r[0];
r = this.toDataCoords(highX, null);
var maxDate = r[0];
this.dateWindow_ = [minDate, maxDate];
this.drawGraph_(this.rawData_);
if (this.attr_("zoomCallback")) {
this.attr_("zoomCallback")(minDate, maxDate);
}
};
/**
* When the mouse moves in the canvas, display information about a nearby data
* point and draw dots over those points in the data series. This function
* takes care of cleanup of previously-drawn dots.
* @param {Object} event The mousemove event from the browser.
* @private
*/
Dygraph.prototype.mouseMove_ = function(event) {
var points = this.layout_.points;
if (!points) return;
var canvasx = Dygraph.pageX(event) - Dygraph.findPosX(this.mouseEventElement_);
var lastx = -1;
var lasty = -1;
// Loop through all the points and find the date nearest to our current
// location.
var minDist = 1e+100;
var idx = -1;
for (var i = 0; i < points.length; i++) {
var dist = Math.abs(points[i].canvasx - canvasx);
if (dist > minDist) continue;
minDist = dist;
idx = i;
}
if (idx >= 0) lastx = points[idx].xval;
// Check that you can really highlight the last day's data
if (canvasx > points[points.length-1].canvasx)
lastx = points[points.length-1].xval;
// Extract the points we've selected
this.selPoints_ = [];
var l = points.length;
if (!this.attr_("stackedGraph")) {
for (var i = 0; i < l; i++) {
if (points[i].xval == lastx) {
this.selPoints_.push(points[i]);
}
}
} else {
// Need to 'unstack' points starting from the bottom
var cumulative_sum = 0;
for (var i = l - 1; i >= 0; i--) {
if (points[i].xval == lastx) {
var p = {}; // Clone the point since we modify it
for (var k in points[i]) {
p[k] = points[i][k];
}
p.yval -= cumulative_sum;
cumulative_sum += p.yval;