Merge commit '9ac5e4aea125e706201c61b0ccb13a2cafe5618f' into clipping
[dygraphs.git] / dygraph.js
CommitLineData
6a1aa64f
DV
1// Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
2// All Rights Reserved.
3
4/**
5 * @fileoverview Creates an interactive, zoomable graph based on a CSV file or
285a6bda
DV
6 * string. Dygraph can handle multiple series with or without error bars. The
7 * date/value ranges will be automatically set. Dygraph uses the
6a1aa64f
DV
8 * <canvas> tag, so it only works in FF1.5+.
9 * @author danvdk@gmail.com (Dan Vanderkam)
10
11 Usage:
12 <div id="graphdiv" style="width:800px; height:500px;"></div>
13 <script type="text/javascript">
285a6bda
DV
14 new Dygraph(document.getElementById("graphdiv"),
15 "datafile.csv", // CSV file with headers
16 { }); // options
6a1aa64f
DV
17 </script>
18
19 The CSV file is of the form
20
285a6bda 21 Date,SeriesA,SeriesB,SeriesC
6a1aa64f
DV
22 YYYYMMDD,A1,B1,C1
23 YYYYMMDD,A2,B2,C2
24
6a1aa64f
DV
25 If the 'errorBars' option is set in the constructor, the input should be of
26 the form
27
285a6bda 28 Date,SeriesA,SeriesB,...
6a1aa64f
DV
29 YYYYMMDD,A1,sigmaA1,B1,sigmaB1,...
30 YYYYMMDD,A2,sigmaA2,B2,sigmaB2,...
31
32 If the 'fractions' option is set, the input should be of the form:
33
285a6bda 34 Date,SeriesA,SeriesB,...
6a1aa64f
DV
35 YYYYMMDD,A1/B1,A2/B2,...
36 YYYYMMDD,A1/B1,A2/B2,...
37
38 And error bars will be calculated automatically using a binomial distribution.
39
285a6bda 40 For further documentation and examples, see http://www.danvk.org/dygraphs
6a1aa64f
DV
41
42 */
43
44/**
45 * An interactive, zoomable graph
46 * @param {String | Function} file A file containing CSV data or a function that
47 * returns this data. The expected format for each line is
48 * YYYYMMDD,val1,val2,... or, if attrs.errorBars is set,
49 * YYYYMMDD,val1,stddev1,val2,stddev2,...
6a1aa64f
DV
50 * @param {Object} attrs Various other attributes, e.g. errorBars determines
51 * whether the input data contains error ranges.
52 */
285a6bda
DV
53Dygraph = function(div, data, opts) {
54 if (arguments.length > 0) {
55 if (arguments.length == 4) {
56 // Old versions of dygraphs took in the series labels as a constructor
57 // parameter. This doesn't make sense anymore, but it's easy to continue
58 // to support this usage.
59 this.warn("Using deprecated four-argument dygraph constructor");
60 this.__old_init__(div, data, arguments[2], arguments[3]);
61 } else {
62 this.__init__(div, data, opts);
63 }
64 }
6a1aa64f
DV
65};
66
285a6bda
DV
67Dygraph.NAME = "Dygraph";
68Dygraph.VERSION = "1.2";
69Dygraph.__repr__ = function() {
6a1aa64f
DV
70 return "[" + this.NAME + " " + this.VERSION + "]";
71};
285a6bda 72Dygraph.toString = function() {
6a1aa64f
DV
73 return this.__repr__();
74};
75
76// Various default values
285a6bda
DV
77Dygraph.DEFAULT_ROLL_PERIOD = 1;
78Dygraph.DEFAULT_WIDTH = 480;
79Dygraph.DEFAULT_HEIGHT = 320;
80Dygraph.AXIS_LINE_WIDTH = 0.3;
6a1aa64f 81
8e4a6af3 82// Default attribute values.
285a6bda 83Dygraph.DEFAULT_ATTRS = {
a9fc39ab 84 highlightCircleSize: 3,
8e4a6af3 85 pixelsPerXLabel: 60,
c6336f04 86 pixelsPerYLabel: 30,
285a6bda 87
8e4a6af3
DV
88 labelsDivWidth: 250,
89 labelsDivStyles: {
90 // TODO(danvk): move defaults from createStatusMessage_ here.
285a6bda
DV
91 },
92 labelsSeparateLines: false,
93 labelsKMB: false,
afefbcdb 94 labelsKMG2: false,
285a6bda
DV
95
96 strokeWidth: 1.0,
8e4a6af3 97
8846615a
DV
98 axisTickSize: 3,
99 axisLabelFontSize: 14,
100 xAxisLabelWidth: 50,
101 yAxisLabelWidth: 50,
102 rightGap: 5,
285a6bda
DV
103
104 showRoller: false,
105 xValueFormatter: Dygraph.dateString_,
106 xValueParser: Dygraph.dateParser,
107 xTicker: Dygraph.dateTicker,
108
3d67f03b
DV
109 delimiter: ',',
110
ff00d3e2 111 logScale: false,
285a6bda
DV
112 sigma: 2.0,
113 errorBars: false,
114 fractions: false,
115 wilsonInterval: true, // only relevant if fractions is true
5954ef32 116 customBars: false,
43af96e7
NK
117 fillGraph: false,
118 fillAlpha: 0.15,
119
120 stackedGraph: false,
121 hideOverlayOnMouseOut: true
285a6bda
DV
122};
123
124// Various logging levels.
125Dygraph.DEBUG = 1;
126Dygraph.INFO = 2;
127Dygraph.WARNING = 3;
128Dygraph.ERROR = 3;
129
130Dygraph.prototype.__old_init__ = function(div, file, labels, attrs) {
131 // Labels is no longer a constructor parameter, since it's typically set
132 // directly from the data source. It also conains a name for the x-axis,
133 // which the previous constructor form did not.
134 if (labels != null) {
135 var new_labels = ["Date"];
136 for (var i = 0; i < labels.length; i++) new_labels.push(labels[i]);
fc80a396 137 Dygraph.update(attrs, { 'labels': new_labels });
285a6bda
DV
138 }
139 this.__init__(div, file, attrs);
8e4a6af3
DV
140};
141
6a1aa64f 142/**
285a6bda 143 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
6a1aa64f
DV
144 * and interaction &lt;canvas&gt; inside of it. See the constructor for details
145 * on the parameters.
146 * @param {String | Function} file Source data
147 * @param {Array.<String>} labels Names of the data series
148 * @param {Object} attrs Miscellaneous other options
149 * @private
150 */
285a6bda
DV
151Dygraph.prototype.__init__ = function(div, file, attrs) {
152 // Support two-argument constructor
153 if (attrs == null) { attrs = {}; }
154
6a1aa64f 155 // Copy the important bits into the object
32988383 156 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
6a1aa64f 157 this.maindiv_ = div;
6a1aa64f 158 this.file_ = file;
285a6bda 159 this.rollPeriod_ = attrs.rollPeriod || Dygraph.DEFAULT_ROLL_PERIOD;
6a1aa64f 160 this.previousVerticalX_ = -1;
6a1aa64f 161 this.fractions_ = attrs.fractions || false;
6a1aa64f
DV
162 this.dateWindow_ = attrs.dateWindow || null;
163 this.valueRange_ = attrs.valueRange || null;
6a1aa64f 164 this.wilsonInterval_ = attrs.wilsonInterval || true;
fe0b7c03 165 this.is_initial_draw_ = true;
8e4a6af3 166
f7d6278e
DV
167 // Clear the div. This ensure that, if multiple dygraphs are passed the same
168 // div, then only one will be drawn.
169 div.innerHTML = "";
170
c21d2c2d 171 // If the div isn't already sized then inherit from our attrs or
172 // give it a default size.
285a6bda 173 if (div.style.width == '') {
c21d2c2d 174 div.style.width = attrs.width || Dygraph.DEFAULT_WIDTH + "px";
285a6bda
DV
175 }
176 if (div.style.height == '') {
c21d2c2d 177 div.style.height = attrs.height || Dygraph.DEFAULT_HEIGHT + "px";
32988383 178 }
285a6bda
DV
179 this.width_ = parseInt(div.style.width, 10);
180 this.height_ = parseInt(div.style.height, 10);
c21d2c2d 181 // The div might have been specified as percent of the current window size,
182 // convert that to an appropriate number of pixels.
183 if (div.style.width.indexOf("%") == div.style.width.length - 1) {
184 // Minus ten pixels keeps scrollbars from showing up for a 100% width div.
185 this.width_ = (this.width_ * self.innerWidth / 100) - 10;
186 }
187 if (div.style.height.indexOf("%") == div.style.height.length - 1) {
188 this.height_ = (this.height_ * self.innerHeight / 100) - 10;
189 }
32988383 190
344ba8c0 191 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
43af96e7
NK
192 if (attrs['stackedGraph']) {
193 attrs['fillGraph'] = true;
194 // TODO(nikhilk): Add any other stackedGraph checks here.
195 }
196
285a6bda
DV
197 // Dygraphs has many options, some of which interact with one another.
198 // To keep track of everything, we maintain two sets of options:
199 //
c21d2c2d 200 // this.user_attrs_ only options explicitly set by the user.
285a6bda
DV
201 // this.attrs_ defaults, options derived from user_attrs_, data.
202 //
203 // Options are then accessed this.attr_('attr'), which first looks at
204 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
205 // defaults without overriding behavior that the user specifically asks for.
206 this.user_attrs_ = {};
fc80a396 207 Dygraph.update(this.user_attrs_, attrs);
6a1aa64f 208
285a6bda 209 this.attrs_ = {};
fc80a396 210 Dygraph.update(this.attrs_, Dygraph.DEFAULT_ATTRS);
6a1aa64f 211
285a6bda
DV
212 // Make a note of whether labels will be pulled from the CSV file.
213 this.labelsFromCSV_ = (this.attr_("labels") == null);
6a1aa64f
DV
214
215 // Create the containing DIV and other interactive elements
216 this.createInterface_();
217
738fc797 218 this.start_();
6a1aa64f
DV
219};
220
285a6bda
DV
221Dygraph.prototype.attr_ = function(name) {
222 if (typeof(this.user_attrs_[name]) != 'undefined') {
223 return this.user_attrs_[name];
224 } else if (typeof(this.attrs_[name]) != 'undefined') {
225 return this.attrs_[name];
226 } else {
227 return null;
228 }
229};
230
231// TODO(danvk): any way I can get the line numbers to be this.warn call?
232Dygraph.prototype.log = function(severity, message) {
233 if (typeof(console) != 'undefined') {
234 switch (severity) {
235 case Dygraph.DEBUG:
236 console.debug('dygraphs: ' + message);
237 break;
238 case Dygraph.INFO:
239 console.info('dygraphs: ' + message);
240 break;
241 case Dygraph.WARNING:
242 console.warn('dygraphs: ' + message);
243 break;
244 case Dygraph.ERROR:
245 console.error('dygraphs: ' + message);
246 break;
247 }
248 }
249}
250Dygraph.prototype.info = function(message) {
251 this.log(Dygraph.INFO, message);
252}
253Dygraph.prototype.warn = function(message) {
254 this.log(Dygraph.WARNING, message);
255}
256Dygraph.prototype.error = function(message) {
257 this.log(Dygraph.ERROR, message);
258}
259
6a1aa64f
DV
260/**
261 * Returns the current rolling period, as set by the user or an option.
262 * @return {Number} The number of days in the rolling window
263 */
285a6bda 264Dygraph.prototype.rollPeriod = function() {
6a1aa64f 265 return this.rollPeriod_;
76171648
DV
266};
267
599fb4ad
DV
268/**
269 * Returns the currently-visible x-range. This can be affected by zooming,
270 * panning or a call to updateOptions.
271 * Returns a two-element array: [left, right].
272 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
273 */
274Dygraph.prototype.xAxisRange = function() {
275 if (this.dateWindow_) return this.dateWindow_;
276
277 // The entire chart is visible.
278 var left = this.rawData_[0][0];
279 var right = this.rawData_[this.rawData_.length - 1][0];
280 return [left, right];
281};
282
76171648
DV
283Dygraph.addEvent = function(el, evt, fn) {
284 var normed_fn = function(e) {
285 if (!e) var e = window.event;
286 fn(e);
287 };
288 if (window.addEventListener) { // Mozilla, Netscape, Firefox
289 el.addEventListener(evt, normed_fn, false);
290 } else { // IE
291 el.attachEvent('on' + evt, normed_fn);
292 }
293};
6a1aa64f 294
4c47502d
DV
295Dygraph.clipCanvas_ = function(cnv, clip) {
296 var ctx = cnv.getContext("2d");
297 ctx.beginPath();
298 ctx.rect(clip.left, clip.top, clip.width, clip.height);
299 ctx.clip();
300};
301
6a1aa64f 302/**
285a6bda 303 * Generates interface elements for the Dygraph: a containing div, a div to
6a1aa64f 304 * display the current point, and a textbox to adjust the rolling average
697e70b2 305 * period. Also creates the Renderer/Layout elements.
6a1aa64f
DV
306 * @private
307 */
285a6bda 308Dygraph.prototype.createInterface_ = function() {
6a1aa64f
DV
309 // Create the all-enclosing graph div
310 var enclosing = this.maindiv_;
311
b0c3b730
DV
312 this.graphDiv = document.createElement("div");
313 this.graphDiv.style.width = this.width_ + "px";
314 this.graphDiv.style.height = this.height_ + "px";
315 enclosing.appendChild(this.graphDiv);
316
4c47502d
DV
317 var clip = {
318 top: 0,
319 left: this.attr_("yAxisLabelWidth") + 2 * this.attr_("axisTickSize")
320 };
321 clip.width = this.width_ - clip.left - this.attr_("rightGap");
322 clip.height = this.height_ - this.attr_("axisLabelFontSize")
323 - 2 * this.attr_("axisTickSize");
324 this.clippingArea_ = clip;
325
b0c3b730 326 // Create the canvas for interactive parts of the chart.
f8cfec73 327 this.canvas_ = Dygraph.createCanvas();
b0c3b730
DV
328 this.canvas_.style.position = "absolute";
329 this.canvas_.width = this.width_;
330 this.canvas_.height = this.height_;
f8cfec73
DV
331 this.canvas_.style.width = this.width_ + "px"; // for IE
332 this.canvas_.style.height = this.height_ + "px"; // for IE
b0c3b730
DV
333 this.graphDiv.appendChild(this.canvas_);
334
335 // ... and for static parts of the chart.
6a1aa64f 336 this.hidden_ = this.createPlotKitCanvas_(this.canvas_);
76171648 337
4c47502d
DV
338 // Make sure we don't overdraw.
339 Dygraph.clipCanvas_(this.hidden_, this.clippingArea_);
340 Dygraph.clipCanvas_(this.canvas_, this.clippingArea_);
341
76171648
DV
342 var dygraph = this;
343 Dygraph.addEvent(this.hidden_, 'mousemove', function(e) {
344 dygraph.mouseMove_(e);
345 });
346 Dygraph.addEvent(this.hidden_, 'mouseout', function(e) {
347 dygraph.mouseOut_(e);
348 });
697e70b2
DV
349
350 // Create the grapher
351 // TODO(danvk): why does the Layout need its own set of options?
352 this.layoutOptions_ = { 'xOriginIsZero': false };
353 Dygraph.update(this.layoutOptions_, this.attrs_);
354 Dygraph.update(this.layoutOptions_, this.user_attrs_);
355 Dygraph.update(this.layoutOptions_, {
356 'errorBars': (this.attr_("errorBars") || this.attr_("customBars")) });
357
358 this.layout_ = new DygraphLayout(this, this.layoutOptions_);
359
360 // TODO(danvk): why does the Renderer need its own set of options?
361 this.renderOptions_ = { colorScheme: this.colors_,
362 strokeColor: null,
363 axisLineWidth: Dygraph.AXIS_LINE_WIDTH };
364 Dygraph.update(this.renderOptions_, this.attrs_);
365 Dygraph.update(this.renderOptions_, this.user_attrs_);
366 this.plotter_ = new DygraphCanvasRenderer(this,
367 this.hidden_, this.layout_,
368 this.renderOptions_);
369
370 this.createStatusMessage_();
371 this.createRollInterface_();
372 this.createDragInterface_();
4cfcc38c
DV
373};
374
375/**
376 * Detach DOM elements in the dygraph and null out all data references.
377 * Calling this when you're done with a dygraph can dramatically reduce memory
378 * usage. See, e.g., the tests/perf.html example.
379 */
380Dygraph.prototype.destroy = function() {
381 var removeRecursive = function(node) {
382 while (node.hasChildNodes()) {
383 removeRecursive(node.firstChild);
384 node.removeChild(node.firstChild);
385 }
386 };
387 removeRecursive(this.maindiv_);
388
389 var nullOut = function(obj) {
390 for (var n in obj) {
391 if (typeof(obj[n]) === 'object') {
392 obj[n] = null;
393 }
394 }
395 };
396
397 // These may not all be necessary, but it can't hurt...
398 nullOut(this.layout_);
399 nullOut(this.plotter_);
400 nullOut(this);
401};
6a1aa64f
DV
402
403/**
404 * Creates the canvas containing the PlotKit graph. Only plotkit ever draws on
285a6bda 405 * this particular canvas. All Dygraph work is done on this.canvas_.
8846615a 406 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
6a1aa64f
DV
407 * @return {Object} The newly-created canvas
408 * @private
409 */
285a6bda 410Dygraph.prototype.createPlotKitCanvas_ = function(canvas) {
f8cfec73 411 var h = Dygraph.createCanvas();
6a1aa64f 412 h.style.position = "absolute";
9ac5e4ae
DV
413 // TODO(danvk): h should be offset from canvas. canvas needs to include
414 // some extra area to make it easier to zoom in on the far left and far
415 // right. h needs to be precisely the plot area, so that clipping occurs.
6a1aa64f
DV
416 h.style.top = canvas.style.top;
417 h.style.left = canvas.style.left;
418 h.width = this.width_;
419 h.height = this.height_;
f8cfec73
DV
420 h.style.width = this.width_ + "px"; // for IE
421 h.style.height = this.height_ + "px"; // for IE
b0c3b730 422 this.graphDiv.appendChild(h);
6a1aa64f
DV
423 return h;
424};
425
f474c2a3
DV
426// Taken from MochiKit.Color
427Dygraph.hsvToRGB = function (hue, saturation, value) {
428 var red;
429 var green;
430 var blue;
431 if (saturation === 0) {
432 red = value;
433 green = value;
434 blue = value;
435 } else {
436 var i = Math.floor(hue * 6);
437 var f = (hue * 6) - i;
438 var p = value * (1 - saturation);
439 var q = value * (1 - (saturation * f));
440 var t = value * (1 - (saturation * (1 - f)));
441 switch (i) {
442 case 1: red = q; green = value; blue = p; break;
443 case 2: red = p; green = value; blue = t; break;
444 case 3: red = p; green = q; blue = value; break;
445 case 4: red = t; green = p; blue = value; break;
446 case 5: red = value; green = p; blue = q; break;
447 case 6: // fall through
448 case 0: red = value; green = t; blue = p; break;
449 }
450 }
451 red = Math.floor(255 * red + 0.5);
452 green = Math.floor(255 * green + 0.5);
453 blue = Math.floor(255 * blue + 0.5);
454 return 'rgb(' + red + ',' + green + ',' + blue + ')';
455};
456
457
6a1aa64f
DV
458/**
459 * Generate a set of distinct colors for the data series. This is done with a
460 * color wheel. Saturation/Value are customizable, and the hue is
461 * equally-spaced around the color wheel. If a custom set of colors is
462 * specified, that is used instead.
6a1aa64f
DV
463 * @private
464 */
285a6bda
DV
465Dygraph.prototype.setColors_ = function() {
466 // TODO(danvk): compute this directly into this.attrs_['colorScheme'] and do
467 // away with this.renderOptions_.
468 var num = this.attr_("labels").length - 1;
6a1aa64f 469 this.colors_ = [];
285a6bda
DV
470 var colors = this.attr_('colors');
471 if (!colors) {
472 var sat = this.attr_('colorSaturation') || 1.0;
473 var val = this.attr_('colorValue') || 0.5;
6a1aa64f 474 for (var i = 1; i <= num; i++) {
ec1959eb 475 if (!this.visibility()[i-1]) continue;
43af96e7
NK
476 // alternate colors for high contrast.
477 var idx = i - parseInt(i % 2 ? i / 2 : (i - num)/2, 10);
478 var hue = (1.0 * idx/ (1 + num));
479 this.colors_.push(Dygraph.hsvToRGB(hue, sat, val));
6a1aa64f
DV
480 }
481 } else {
482 for (var i = 0; i < num; i++) {
ec1959eb 483 if (!this.visibility()[i]) continue;
285a6bda 484 var colorStr = colors[i % colors.length];
f474c2a3 485 this.colors_.push(colorStr);
6a1aa64f
DV
486 }
487 }
285a6bda 488
c21d2c2d 489 // TODO(danvk): update this w/r/t/ the new options system.
285a6bda 490 this.renderOptions_.colorScheme = this.colors_;
fc80a396
DV
491 Dygraph.update(this.plotter_.options, this.renderOptions_);
492 Dygraph.update(this.layoutOptions_, this.user_attrs_);
493 Dygraph.update(this.layoutOptions_, this.attrs_);
6a1aa64f
DV
494}
495
43af96e7
NK
496/**
497 * Return the list of colors. This is either the list of colors passed in the
498 * attributes, or the autogenerated list of rgb(r,g,b) strings.
499 * @return {Array<string>} The list of colors.
500 */
501Dygraph.prototype.getColors = function() {
502 return this.colors_;
503};
504
5e60386d
DV
505// The following functions are from quirksmode.org with a modification for Safari from
506// http://blog.firetree.net/2005/07/04/javascript-find-position/
3df0ccf0
DV
507// http://www.quirksmode.org/js/findpos.html
508Dygraph.findPosX = function(obj) {
509 var curleft = 0;
5e60386d
DV
510 if(obj.offsetParent)
511 while(1)
512 {
3df0ccf0 513 curleft += obj.offsetLeft;
5e60386d
DV
514 if(!obj.offsetParent)
515 break;
3df0ccf0
DV
516 obj = obj.offsetParent;
517 }
5e60386d 518 else if(obj.x)
3df0ccf0
DV
519 curleft += obj.x;
520 return curleft;
521};
c21d2c2d 522
3df0ccf0
DV
523Dygraph.findPosY = function(obj) {
524 var curtop = 0;
5e60386d
DV
525 if(obj.offsetParent)
526 while(1)
527 {
3df0ccf0 528 curtop += obj.offsetTop;
5e60386d
DV
529 if(!obj.offsetParent)
530 break;
3df0ccf0
DV
531 obj = obj.offsetParent;
532 }
5e60386d 533 else if(obj.y)
3df0ccf0
DV
534 curtop += obj.y;
535 return curtop;
536};
537
5e60386d 538
71a11a8e 539
6a1aa64f
DV
540/**
541 * Create the div that contains information on the selected point(s)
542 * This goes in the top right of the canvas, unless an external div has already
543 * been specified.
544 * @private
545 */
285a6bda
DV
546Dygraph.prototype.createStatusMessage_ = function(){
547 if (!this.attr_("labelsDiv")) {
548 var divWidth = this.attr_('labelsDivWidth');
b0c3b730 549 var messagestyle = {
6a1aa64f
DV
550 "position": "absolute",
551 "fontSize": "14px",
552 "zIndex": 10,
553 "width": divWidth + "px",
554 "top": "0px",
8846615a 555 "left": (this.width_ - divWidth - 2) + "px",
6a1aa64f
DV
556 "background": "white",
557 "textAlign": "left",
b0c3b730 558 "overflow": "hidden"};
fc80a396 559 Dygraph.update(messagestyle, this.attr_('labelsDivStyles'));
b0c3b730
DV
560 var div = document.createElement("div");
561 for (var name in messagestyle) {
85b99f0b
DV
562 if (messagestyle.hasOwnProperty(name)) {
563 div.style[name] = messagestyle[name];
564 }
b0c3b730
DV
565 }
566 this.graphDiv.appendChild(div);
285a6bda 567 this.attrs_.labelsDiv = div;
6a1aa64f
DV
568 }
569};
570
571/**
572 * Create the text box to adjust the averaging period
573 * @return {Object} The newly-created text box
574 * @private
575 */
285a6bda 576Dygraph.prototype.createRollInterface_ = function() {
285a6bda 577 var display = this.attr_('showRoller') ? "block" : "none";
b0c3b730
DV
578 var textAttr = { "position": "absolute",
579 "zIndex": 10,
580 "top": (this.plotter_.area.h - 25) + "px",
581 "left": (this.plotter_.area.x + 1) + "px",
582 "display": display
6a1aa64f 583 };
b0c3b730
DV
584 var roller = document.createElement("input");
585 roller.type = "text";
586 roller.size = "2";
587 roller.value = this.rollPeriod_;
588 for (var name in textAttr) {
85b99f0b
DV
589 if (textAttr.hasOwnProperty(name)) {
590 roller.style[name] = textAttr[name];
591 }
b0c3b730
DV
592 }
593
6a1aa64f 594 var pa = this.graphDiv;
b0c3b730 595 pa.appendChild(roller);
76171648
DV
596 var dygraph = this;
597 roller.onchange = function() { dygraph.adjustRoll(roller.value); };
6a1aa64f 598 return roller;
76171648
DV
599};
600
601// These functions are taken from MochiKit.Signal
602Dygraph.pageX = function(e) {
603 if (e.pageX) {
604 return (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
605 } else {
606 var de = document;
607 var b = document.body;
608 return e.clientX +
609 (de.scrollLeft || b.scrollLeft) -
610 (de.clientLeft || 0);
611 }
612};
613
614Dygraph.pageY = function(e) {
615 if (e.pageY) {
616 return (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
617 } else {
618 var de = document;
619 var b = document.body;
620 return e.clientY +
621 (de.scrollTop || b.scrollTop) -
622 (de.clientTop || 0);
623 }
624};
6a1aa64f
DV
625
626/**
627 * Set up all the mouse handlers needed to capture dragging behavior for zoom
27385109 628 * events.
6a1aa64f
DV
629 * @private
630 */
285a6bda 631Dygraph.prototype.createDragInterface_ = function() {
6a1aa64f
DV
632 var self = this;
633
634 // Tracks whether the mouse is down right now
bce01b0f 635 var isZooming = false;
c776c216 636 var isPanning = false;
6a1aa64f
DV
637 var dragStartX = null;
638 var dragStartY = null;
639 var dragEndX = null;
640 var dragEndY = null;
641 var prevEndX = null;
bce01b0f
DV
642 var draggingDate = null;
643 var dateRange = null;
6a1aa64f
DV
644
645 // Utility function to convert page-wide coordinates to canvas coords
67e650dc
DV
646 var px = 0;
647 var py = 0;
76171648
DV
648 var getX = function(e) { return Dygraph.pageX(e) - px };
649 var getY = function(e) { return Dygraph.pageX(e) - py };
6a1aa64f
DV
650
651 // Draw zoom rectangles when the mouse is down and the user moves around
76171648 652 Dygraph.addEvent(this.hidden_, 'mousemove', function(event) {
bce01b0f 653 if (isZooming) {
6a1aa64f
DV
654 dragEndX = getX(event);
655 dragEndY = getY(event);
656
657 self.drawZoomRect_(dragStartX, dragEndX, prevEndX);
658 prevEndX = dragEndX;
bce01b0f
DV
659 } else if (isPanning) {
660 dragEndX = getX(event);
661 dragEndY = getY(event);
662
663 // Want to have it so that:
664 // 1. draggingDate appears at dragEndX
665 // 2. daterange = (dateWindow_[1] - dateWindow_[0]) is unaltered.
666
667 self.dateWindow_[0] = draggingDate - (dragEndX / self.width_) * dateRange;
668 self.dateWindow_[1] = self.dateWindow_[0] + dateRange;
669 self.drawGraph_(self.rawData_);
6a1aa64f
DV
670 }
671 });
672
673 // Track the beginning of drag events
76171648 674 Dygraph.addEvent(this.hidden_, 'mousedown', function(event) {
3df0ccf0
DV
675 px = Dygraph.findPosX(self.canvas_);
676 py = Dygraph.findPosY(self.canvas_);
6a1aa64f
DV
677 dragStartX = getX(event);
678 dragStartY = getY(event);
bce01b0f 679
2dab69c3 680 if (event.altKey || event.shiftKey) {
d12999d3 681 if (!self.dateWindow_) return; // have to be zoomed in to pan.
bce01b0f
DV
682 isPanning = true;
683 dateRange = self.dateWindow_[1] - self.dateWindow_[0];
d12999d3
DV
684 draggingDate = (dragStartX / self.width_) * dateRange +
685 self.dateWindow_[0];
bce01b0f
DV
686 } else {
687 isZooming = true;
688 }
6a1aa64f
DV
689 });
690
691 // If the user releases the mouse button during a drag, but not over the
692 // canvas, then it doesn't count as a zooming action.
76171648 693 Dygraph.addEvent(document, 'mouseup', function(event) {
bce01b0f
DV
694 if (isZooming || isPanning) {
695 isZooming = false;
6a1aa64f
DV
696 dragStartX = null;
697 dragStartY = null;
698 }
bce01b0f
DV
699
700 if (isPanning) {
701 isPanning = false;
702 draggingDate = null;
703 dateRange = null;
704 }
6a1aa64f
DV
705 });
706
707 // Temporarily cancel the dragging event when the mouse leaves the graph
76171648 708 Dygraph.addEvent(this.hidden_, 'mouseout', function(event) {
bce01b0f 709 if (isZooming) {
6a1aa64f
DV
710 dragEndX = null;
711 dragEndY = null;
712 }
713 });
714
715 // If the mouse is released on the canvas during a drag event, then it's a
716 // zoom. Only do the zoom if it's over a large enough area (>= 10 pixels)
76171648 717 Dygraph.addEvent(this.hidden_, 'mouseup', function(event) {
bce01b0f
DV
718 if (isZooming) {
719 isZooming = false;
6a1aa64f
DV
720 dragEndX = getX(event);
721 dragEndY = getY(event);
722 var regionWidth = Math.abs(dragEndX - dragStartX);
723 var regionHeight = Math.abs(dragEndY - dragStartY);
724
725 if (regionWidth < 2 && regionHeight < 2 &&
285a6bda 726 self.attr_('clickCallback') != null &&
6a1aa64f 727 self.lastx_ != undefined) {
b258a3da
DV
728 // TODO(danvk): pass along more info about the points.
729 self.attr_('clickCallback')(event, self.lastx_, self.selPoints_);
6a1aa64f
DV
730 }
731
732 if (regionWidth >= 10) {
733 self.doZoom_(Math.min(dragStartX, dragEndX),
734 Math.max(dragStartX, dragEndX));
735 } else {
736 self.canvas_.getContext("2d").clearRect(0, 0,
737 self.canvas_.width,
738 self.canvas_.height);
739 }
740
741 dragStartX = null;
742 dragStartY = null;
743 }
bce01b0f
DV
744
745 if (isPanning) {
746 isPanning = false;
747 draggingDate = null;
748 dateRange = null;
749 }
6a1aa64f
DV
750 });
751
752 // Double-clicking zooms back out
76171648 753 Dygraph.addEvent(this.hidden_, 'dblclick', function(event) {
b258a3da 754 if (self.dateWindow_ == null) return;
6a1aa64f
DV
755 self.dateWindow_ = null;
756 self.drawGraph_(self.rawData_);
757 var minDate = self.rawData_[0][0];
758 var maxDate = self.rawData_[self.rawData_.length - 1][0];
285a6bda
DV
759 if (self.attr_("zoomCallback")) {
760 self.attr_("zoomCallback")(minDate, maxDate);
67e650dc 761 }
6a1aa64f
DV
762 });
763};
764
765/**
766 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
767 * up any previous zoom rectangles that were drawn. This could be optimized to
768 * avoid extra redrawing, but it's tricky to avoid interactions with the status
769 * dots.
770 * @param {Number} startX The X position where the drag started, in canvas
771 * coordinates.
772 * @param {Number} endX The current X position of the drag, in canvas coords.
773 * @param {Number} prevEndX The value of endX on the previous call to this
774 * function. Used to avoid excess redrawing
775 * @private
776 */
285a6bda 777Dygraph.prototype.drawZoomRect_ = function(startX, endX, prevEndX) {
6a1aa64f
DV
778 var ctx = this.canvas_.getContext("2d");
779
780 // Clean up from the previous rect if necessary
781 if (prevEndX) {
782 ctx.clearRect(Math.min(startX, prevEndX), 0,
783 Math.abs(startX - prevEndX), this.height_);
784 }
785
786 // Draw a light-grey rectangle to show the new viewing area
787 if (endX && startX) {
788 ctx.fillStyle = "rgba(128,128,128,0.33)";
789 ctx.fillRect(Math.min(startX, endX), 0,
790 Math.abs(endX - startX), this.height_);
791 }
792};
793
794/**
795 * Zoom to something containing [lowX, highX]. These are pixel coordinates
796 * in the canvas. The exact zoom window may be slightly larger if there are no
797 * data points near lowX or highX. This function redraws the graph.
798 * @param {Number} lowX The leftmost pixel value that should be visible.
799 * @param {Number} highX The rightmost pixel value that should be visible.
800 * @private
801 */
285a6bda 802Dygraph.prototype.doZoom_ = function(lowX, highX) {
6a1aa64f
DV
803 // Find the earliest and latest dates contained in this canvasx range.
804 var points = this.layout_.points;
805 var minDate = null;
806 var maxDate = null;
807 // Find the nearest [minDate, maxDate] that contains [lowX, highX]
808 for (var i = 0; i < points.length; i++) {
809 var cx = points[i].canvasx;
810 var x = points[i].xval;
811 if (cx < lowX && (minDate == null || x > minDate)) minDate = x;
812 if (cx > highX && (maxDate == null || x < maxDate)) maxDate = x;
813 }
814 // Use the extremes if either is missing
815 if (minDate == null) minDate = points[0].xval;
816 if (maxDate == null) maxDate = points[points.length-1].xval;
817
818 this.dateWindow_ = [minDate, maxDate];
819 this.drawGraph_(this.rawData_);
285a6bda
DV
820 if (this.attr_("zoomCallback")) {
821 this.attr_("zoomCallback")(minDate, maxDate);
67e650dc 822 }
6a1aa64f
DV
823};
824
825/**
826 * When the mouse moves in the canvas, display information about a nearby data
827 * point and draw dots over those points in the data series. This function
828 * takes care of cleanup of previously-drawn dots.
829 * @param {Object} event The mousemove event from the browser.
830 * @private
831 */
285a6bda 832Dygraph.prototype.mouseMove_ = function(event) {
76171648 833 var canvasx = Dygraph.pageX(event) - Dygraph.findPosX(this.hidden_);
6a1aa64f
DV
834 var points = this.layout_.points;
835
836 var lastx = -1;
837 var lasty = -1;
838
839 // Loop through all the points and find the date nearest to our current
840 // location.
841 var minDist = 1e+100;
842 var idx = -1;
843 for (var i = 0; i < points.length; i++) {
844 var dist = Math.abs(points[i].canvasx - canvasx);
845 if (dist > minDist) break;
846 minDist = dist;
847 idx = i;
848 }
849 if (idx >= 0) lastx = points[idx].xval;
850 // Check that you can really highlight the last day's data
851 if (canvasx > points[points.length-1].canvasx)
852 lastx = points[points.length-1].xval;
853
854 // Extract the points we've selected
b258a3da 855 this.selPoints_ = [];
6a1aa64f
DV
856 for (var i = 0; i < points.length; i++) {
857 if (points[i].xval == lastx) {
b258a3da 858 this.selPoints_.push(points[i]);
6a1aa64f
DV
859 }
860 }
861
b258a3da 862 if (this.attr_("highlightCallback")) {
dd082dda
DV
863 var px = this.lastHighlightCallbackX;
864 if (px !== null && lastx != px) {
344ba8c0 865 // only fire if the selected point has changed.
dd082dda 866 this.lastHighlightCallbackX = lastx;
344ba8c0
DV
867 if (!this.attr_("stackedGraph")) {
868 this.attr_("highlightCallback")(event, lastx, this.selPoints_);
869 } else {
71a11a8e 870 // "unstack" the points.
344ba8c0
DV
871 var callbackPoints = this.selPoints_.map(
872 function(p) { return {xval: p.xval, yval: p.yval, name: p.name} });
71a11a8e
DV
873 var cumulative_sum = 0;
874 for (var j = callbackPoints.length - 1; j >= 0; j--) {
875 callbackPoints[j].yval -= cumulative_sum;
876 cumulative_sum += callbackPoints[j].yval;
877 }
344ba8c0 878 this.attr_("highlightCallback")(event, lastx, callbackPoints);
43af96e7 879 }
dd082dda 880 }
b258a3da
DV
881 }
882
6a1aa64f 883 // Clear the previously drawn vertical, if there is one
285a6bda 884 var circleSize = this.attr_('highlightCircleSize');
6a1aa64f
DV
885 var ctx = this.canvas_.getContext("2d");
886 if (this.previousVerticalX_ >= 0) {
887 var px = this.previousVerticalX_;
888 ctx.clearRect(px - circleSize - 1, 0, 2 * circleSize + 2, this.height_);
889 }
890
584ceeaa
DV
891 var isOK = function(x) { return x && !isNaN(x); };
892
b258a3da
DV
893 if (this.selPoints_.length > 0) {
894 var canvasx = this.selPoints_[0].canvasx;
6a1aa64f
DV
895
896 // Set the status message to indicate the selected point(s)
285a6bda 897 var replace = this.attr_('xValueFormatter')(lastx, this) + ":";
6a1aa64f 898 var clen = this.colors_.length;
b258a3da
DV
899 for (var i = 0; i < this.selPoints_.length; i++) {
900 if (!isOK(this.selPoints_[i].canvasy)) continue;
285a6bda 901 if (this.attr_("labelsSeparateLines")) {
6a1aa64f
DV
902 replace += "<br/>";
903 }
b258a3da 904 var point = this.selPoints_[i];
f474c2a3
DV
905 var c = new RGBColor(this.colors_[i%clen]);
906 replace += " <b><font color='" + c.toHex() + "'>"
6a1aa64f
DV
907 + point.name + "</font></b>:"
908 + this.round_(point.yval, 2);
909 }
285a6bda 910 this.attr_("labelsDiv").innerHTML = replace;
6a1aa64f
DV
911
912 // Save last x position for callbacks.
913 this.lastx_ = lastx;
914
915 // Draw colored circles over the center of each selected point
43af96e7 916 ctx.save();
b258a3da
DV
917 for (var i = 0; i < this.selPoints_.length; i++) {
918 if (!isOK(this.selPoints_[i%clen].canvasy)) continue;
6a1aa64f 919 ctx.beginPath();
f474c2a3 920 ctx.fillStyle = this.colors_[i%clen];
b258a3da 921 ctx.arc(canvasx, this.selPoints_[i%clen].canvasy, circleSize,
7bf6a9fe 922 0, 2 * Math.PI, false);
6a1aa64f
DV
923 ctx.fill();
924 }
925 ctx.restore();
926
927 this.previousVerticalX_ = canvasx;
928 }
929};
930
931/**
932 * The mouse has left the canvas. Clear out whatever artifacts remain
933 * @param {Object} event the mouseout event from the browser.
934 * @private
935 */
285a6bda 936Dygraph.prototype.mouseOut_ = function(event) {
43af96e7
NK
937 if (this.attr_("hideOverlayOnMouseOut")) {
938 // Get rid of the overlay data
939 var ctx = this.canvas_.getContext("2d");
940 ctx.clearRect(0, 0, this.width_, this.height_);
941 this.attr_("labelsDiv").innerHTML = "";
942 }
6a1aa64f
DV
943};
944
285a6bda 945Dygraph.zeropad = function(x) {
32988383
DV
946 if (x < 10) return "0" + x; else return "" + x;
947}
948
6a1aa64f 949/**
6b8e33dd
DV
950 * Return a string version of the hours, minutes and seconds portion of a date.
951 * @param {Number} date The JavaScript date (ms since epoch)
952 * @return {String} A time of the form "HH:MM:SS"
953 * @private
954 */
285a6bda
DV
955Dygraph.prototype.hmsString_ = function(date) {
956 var zeropad = Dygraph.zeropad;
6b8e33dd
DV
957 var d = new Date(date);
958 if (d.getSeconds()) {
959 return zeropad(d.getHours()) + ":" +
960 zeropad(d.getMinutes()) + ":" +
961 zeropad(d.getSeconds());
6b8e33dd 962 } else {
054531ca 963 return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes());
6b8e33dd
DV
964 }
965}
966
967/**
6a1aa64f
DV
968 * Convert a JS date (millis since epoch) to YYYY/MM/DD
969 * @param {Number} date The JavaScript date (ms since epoch)
970 * @return {String} A date of the form "YYYY/MM/DD"
971 * @private
285a6bda 972 * TODO(danvk): why is this part of the prototype?
6a1aa64f 973 */
285a6bda
DV
974Dygraph.dateString_ = function(date, self) {
975 var zeropad = Dygraph.zeropad;
6a1aa64f
DV
976 var d = new Date(date);
977
978 // Get the year:
979 var year = "" + d.getFullYear();
980 // Get a 0 padded month string
6b8e33dd 981 var month = zeropad(d.getMonth() + 1); //months are 0-offset, sigh
6a1aa64f 982 // Get a 0 padded day string
6b8e33dd 983 var day = zeropad(d.getDate());
6a1aa64f 984
6b8e33dd
DV
985 var ret = "";
986 var frac = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
285a6bda 987 if (frac) ret = " " + self.hmsString_(date);
6b8e33dd
DV
988
989 return year + "/" + month + "/" + day + ret;
6a1aa64f
DV
990};
991
992/**
993 * Round a number to the specified number of digits past the decimal point.
994 * @param {Number} num The number to round
995 * @param {Number} places The number of decimals to which to round
996 * @return {Number} The rounded number
997 * @private
998 */
285a6bda 999Dygraph.prototype.round_ = function(num, places) {
6a1aa64f
DV
1000 var shift = Math.pow(10, places);
1001 return Math.round(num * shift)/shift;
1002};
1003
1004/**
1005 * Fires when there's data available to be graphed.
1006 * @param {String} data Raw CSV data to be plotted
1007 * @private
1008 */
285a6bda 1009Dygraph.prototype.loadedEvent_ = function(data) {
6a1aa64f
DV
1010 this.rawData_ = this.parseCSV_(data);
1011 this.drawGraph_(this.rawData_);
1012};
1013
285a6bda 1014Dygraph.prototype.months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
8846615a 1015 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
285a6bda 1016Dygraph.prototype.quarters = ["Jan", "Apr", "Jul", "Oct"];
6a1aa64f
DV
1017
1018/**
1019 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
1020 * @private
1021 */
285a6bda 1022Dygraph.prototype.addXTicks_ = function() {
6a1aa64f
DV
1023 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
1024 var startDate, endDate;
1025 if (this.dateWindow_) {
1026 startDate = this.dateWindow_[0];
1027 endDate = this.dateWindow_[1];
1028 } else {
1029 startDate = this.rawData_[0][0];
1030 endDate = this.rawData_[this.rawData_.length - 1][0];
1031 }
1032
285a6bda 1033 var xTicks = this.attr_('xTicker')(startDate, endDate, this);
6a1aa64f 1034 this.layout_.updateOptions({xTicks: xTicks});
32988383
DV
1035};
1036
1037// Time granularity enumeration
285a6bda 1038Dygraph.SECONDLY = 0;
20a41c17
DV
1039Dygraph.TWO_SECONDLY = 1;
1040Dygraph.FIVE_SECONDLY = 2;
1041Dygraph.TEN_SECONDLY = 3;
1042Dygraph.THIRTY_SECONDLY = 4;
1043Dygraph.MINUTELY = 5;
1044Dygraph.TWO_MINUTELY = 6;
1045Dygraph.FIVE_MINUTELY = 7;
1046Dygraph.TEN_MINUTELY = 8;
1047Dygraph.THIRTY_MINUTELY = 9;
1048Dygraph.HOURLY = 10;
1049Dygraph.TWO_HOURLY = 11;
1050Dygraph.SIX_HOURLY = 12;
1051Dygraph.DAILY = 13;
1052Dygraph.WEEKLY = 14;
1053Dygraph.MONTHLY = 15;
1054Dygraph.QUARTERLY = 16;
1055Dygraph.BIANNUAL = 17;
1056Dygraph.ANNUAL = 18;
1057Dygraph.DECADAL = 19;
1058Dygraph.NUM_GRANULARITIES = 20;
285a6bda
DV
1059
1060Dygraph.SHORT_SPACINGS = [];
1061Dygraph.SHORT_SPACINGS[Dygraph.SECONDLY] = 1000 * 1;
20a41c17
DV
1062Dygraph.SHORT_SPACINGS[Dygraph.TWO_SECONDLY] = 1000 * 2;
1063Dygraph.SHORT_SPACINGS[Dygraph.FIVE_SECONDLY] = 1000 * 5;
285a6bda
DV
1064Dygraph.SHORT_SPACINGS[Dygraph.TEN_SECONDLY] = 1000 * 10;
1065Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_SECONDLY] = 1000 * 30;
1066Dygraph.SHORT_SPACINGS[Dygraph.MINUTELY] = 1000 * 60;
20a41c17
DV
1067Dygraph.SHORT_SPACINGS[Dygraph.TWO_MINUTELY] = 1000 * 60 * 2;
1068Dygraph.SHORT_SPACINGS[Dygraph.FIVE_MINUTELY] = 1000 * 60 * 5;
285a6bda
DV
1069Dygraph.SHORT_SPACINGS[Dygraph.TEN_MINUTELY] = 1000 * 60 * 10;
1070Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_MINUTELY] = 1000 * 60 * 30;
1071Dygraph.SHORT_SPACINGS[Dygraph.HOURLY] = 1000 * 3600;
20a41c17 1072Dygraph.SHORT_SPACINGS[Dygraph.TWO_HOURLY] = 1000 * 3600 * 2;
805d5519 1073Dygraph.SHORT_SPACINGS[Dygraph.SIX_HOURLY] = 1000 * 3600 * 6;
285a6bda
DV
1074Dygraph.SHORT_SPACINGS[Dygraph.DAILY] = 1000 * 86400;
1075Dygraph.SHORT_SPACINGS[Dygraph.WEEKLY] = 1000 * 604800;
32988383
DV
1076
1077// NumXTicks()
1078//
1079// If we used this time granularity, how many ticks would there be?
1080// This is only an approximation, but it's generally good enough.
1081//
285a6bda
DV
1082Dygraph.prototype.NumXTicks = function(start_time, end_time, granularity) {
1083 if (granularity < Dygraph.MONTHLY) {
32988383 1084 // Generate one tick mark for every fixed interval of time.
285a6bda 1085 var spacing = Dygraph.SHORT_SPACINGS[granularity];
32988383
DV
1086 return Math.floor(0.5 + 1.0 * (end_time - start_time) / spacing);
1087 } else {
1088 var year_mod = 1; // e.g. to only print one point every 10 years.
1089 var num_months = 12;
285a6bda
DV
1090 if (granularity == Dygraph.QUARTERLY) num_months = 3;
1091 if (granularity == Dygraph.BIANNUAL) num_months = 2;
1092 if (granularity == Dygraph.ANNUAL) num_months = 1;
1093 if (granularity == Dygraph.DECADAL) { num_months = 1; year_mod = 10; }
32988383
DV
1094
1095 var msInYear = 365.2524 * 24 * 3600 * 1000;
1096 var num_years = 1.0 * (end_time - start_time) / msInYear;
1097 return Math.floor(0.5 + 1.0 * num_years * num_months / year_mod);
1098 }
1099};
1100
1101// GetXAxis()
1102//
1103// Construct an x-axis of nicely-formatted times on meaningful boundaries
1104// (e.g. 'Jan 09' rather than 'Jan 22, 2009').
1105//
1106// Returns an array containing {v: millis, label: label} dictionaries.
1107//
285a6bda 1108Dygraph.prototype.GetXAxis = function(start_time, end_time, granularity) {
32988383 1109 var ticks = [];
285a6bda 1110 if (granularity < Dygraph.MONTHLY) {
32988383 1111 // Generate one tick mark for every fixed interval of time.
285a6bda 1112 var spacing = Dygraph.SHORT_SPACINGS[granularity];
3d29302c 1113 var format = '%d%b'; // e.g. "1Jan"
076c9622
DV
1114
1115 // Find a time less than start_time which occurs on a "nice" time boundary
1116 // for this granularity.
1117 var g = spacing / 1000;
076c9622
DV
1118 var d = new Date(start_time);
1119 if (g <= 60) { // seconds
1120 var x = d.getSeconds(); d.setSeconds(x - x % g);
1121 } else {
1122 d.setSeconds(0);
1123 g /= 60;
1124 if (g <= 60) { // minutes
1125 var x = d.getMinutes(); d.setMinutes(x - x % g);
1126 } else {
1127 d.setMinutes(0);
1128 g /= 60;
1129
1130 if (g <= 24) { // days
1131 var x = d.getHours(); d.setHours(x - x % g);
1132 } else {
1133 d.setHours(0);
1134 g /= 24;
1135
1136 if (g == 7) { // one week
20a41c17 1137 d.setDate(d.getDate() - d.getDay());
076c9622
DV
1138 }
1139 }
1140 }
328bb812 1141 }
076c9622
DV
1142 start_time = d.getTime();
1143
32988383
DV
1144 for (var t = start_time; t <= end_time; t += spacing) {
1145 var d = new Date(t);
1146 var frac = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
285a6bda 1147 if (frac == 0 || granularity >= Dygraph.DAILY) {
32988383
DV
1148 // the extra hour covers DST problems.
1149 ticks.push({ v:t, label: new Date(t + 3600*1000).strftime(format) });
1150 } else {
1151 ticks.push({ v:t, label: this.hmsString_(t) });
1152 }
1153 }
1154 } else {
1155 // Display a tick mark on the first of a set of months of each year.
1156 // Years get a tick mark iff y % year_mod == 0. This is useful for
1157 // displaying a tick mark once every 10 years, say, on long time scales.
1158 var months;
1159 var year_mod = 1; // e.g. to only print one point every 10 years.
1160
285a6bda 1161 if (granularity == Dygraph.MONTHLY) {
32988383 1162 months = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
285a6bda 1163 } else if (granularity == Dygraph.QUARTERLY) {
32988383 1164 months = [ 0, 3, 6, 9 ];
285a6bda 1165 } else if (granularity == Dygraph.BIANNUAL) {
32988383 1166 months = [ 0, 6 ];
285a6bda 1167 } else if (granularity == Dygraph.ANNUAL) {
32988383 1168 months = [ 0 ];
285a6bda 1169 } else if (granularity == Dygraph.DECADAL) {
32988383
DV
1170 months = [ 0 ];
1171 year_mod = 10;
1172 }
1173
1174 var start_year = new Date(start_time).getFullYear();
1175 var end_year = new Date(end_time).getFullYear();
285a6bda 1176 var zeropad = Dygraph.zeropad;
32988383
DV
1177 for (var i = start_year; i <= end_year; i++) {
1178 if (i % year_mod != 0) continue;
1179 for (var j = 0; j < months.length; j++) {
1180 var date_str = i + "/" + zeropad(1 + months[j]) + "/01";
1181 var t = Date.parse(date_str);
1182 if (t < start_time || t > end_time) continue;
1183 ticks.push({ v:t, label: new Date(t).strftime('%b %y') });
1184 }
1185 }
1186 }
1187
1188 return ticks;
1189};
1190
6a1aa64f
DV
1191
1192/**
1193 * Add ticks to the x-axis based on a date range.
1194 * @param {Number} startDate Start of the date window (millis since epoch)
1195 * @param {Number} endDate End of the date window (millis since epoch)
1196 * @return {Array.<Object>} Array of {label, value} tuples.
1197 * @public
1198 */
285a6bda 1199Dygraph.dateTicker = function(startDate, endDate, self) {
32988383 1200 var chosen = -1;
285a6bda
DV
1201 for (var i = 0; i < Dygraph.NUM_GRANULARITIES; i++) {
1202 var num_ticks = self.NumXTicks(startDate, endDate, i);
1203 if (self.width_ / num_ticks >= self.attr_('pixelsPerXLabel')) {
32988383
DV
1204 chosen = i;
1205 break;
2769de62 1206 }
6a1aa64f
DV
1207 }
1208
32988383 1209 if (chosen >= 0) {
285a6bda 1210 return self.GetXAxis(startDate, endDate, chosen);
6a1aa64f 1211 } else {
32988383 1212 // TODO(danvk): signal error.
6a1aa64f 1213 }
6a1aa64f
DV
1214};
1215
1216/**
1217 * Add ticks when the x axis has numbers on it (instead of dates)
1218 * @param {Number} startDate Start of the date window (millis since epoch)
1219 * @param {Number} endDate End of the date window (millis since epoch)
1220 * @return {Array.<Object>} Array of {label, value} tuples.
1221 * @public
1222 */
285a6bda 1223Dygraph.numericTicks = function(minV, maxV, self) {
c6336f04
DV
1224 // Basic idea:
1225 // Try labels every 1, 2, 5, 10, 20, 50, 100, etc.
1226 // Calculate the resulting tick spacing (i.e. this.height_ / nTicks).
285a6bda 1227 // The first spacing greater than pixelsPerYLabel is what we use.
ff00d3e2 1228 // TODO(danvk): version that works on a log scale.
f09e46d4
DV
1229 if (self.attr_("labelsKMG2")) {
1230 var mults = [1, 2, 4, 8];
1231 } else {
1232 var mults = [1, 2, 5];
1233 }
c6336f04 1234 var scale, low_val, high_val, nTicks;
285a6bda
DV
1235 // TODO(danvk): make it possible to set this for x- and y-axes independently.
1236 var pixelsPerTick = self.attr_('pixelsPerYLabel');
c6336f04 1237 for (var i = -10; i < 50; i++) {
f09e46d4
DV
1238 if (self.attr_("labelsKMG2")) {
1239 var base_scale = Math.pow(16, i);
1240 } else {
1241 var base_scale = Math.pow(10, i);
1242 }
c6336f04
DV
1243 for (var j = 0; j < mults.length; j++) {
1244 scale = base_scale * mults[j];
c6336f04
DV
1245 low_val = Math.floor(minV / scale) * scale;
1246 high_val = Math.ceil(maxV / scale) * scale;
1247 nTicks = (high_val - low_val) / scale;
285a6bda 1248 var spacing = self.height_ / nTicks;
c6336f04 1249 // wish I could break out of both loops at once...
285a6bda 1250 if (spacing > pixelsPerTick) break;
c6336f04 1251 }
285a6bda 1252 if (spacing > pixelsPerTick) break;
6a1aa64f
DV
1253 }
1254
1255 // Construct labels for the ticks
1256 var ticks = [];
ed11be50
DV
1257 var k;
1258 var k_labels = [];
1259 if (self.attr_("labelsKMB")) {
1260 k = 1000;
1261 k_labels = [ "K", "M", "B", "T" ];
1262 }
1263 if (self.attr_("labelsKMG2")) {
1264 if (k) self.warn("Setting both labelsKMB and labelsKMG2. Pick one!");
1265 k = 1024;
1266 k_labels = [ "k", "M", "G", "T" ];
1267 }
1268
c6336f04
DV
1269 for (var i = 0; i < nTicks; i++) {
1270 var tickV = low_val + i * scale;
0af6e346 1271 var absTickV = Math.abs(tickV);
285a6bda 1272 var label = self.round_(tickV, 2);
ed11be50
DV
1273 if (k_labels.length) {
1274 // Round up to an appropriate unit.
1275 var n = k*k*k*k;
1276 for (var j = 3; j >= 0; j--, n /= k) {
1277 if (absTickV >= n) {
1278 label = self.round_(tickV / n, 1) + k_labels[j];
1279 break;
1280 }
afefbcdb 1281 }
6a1aa64f
DV
1282 }
1283 ticks.push( {label: label, v: tickV} );
1284 }
1285 return ticks;
1286};
1287
1288/**
1289 * Adds appropriate ticks on the y-axis
1290 * @param {Number} minY The minimum Y value in the data set
1291 * @param {Number} maxY The maximum Y value in the data set
1292 * @private
1293 */
285a6bda 1294Dygraph.prototype.addYTicks_ = function(minY, maxY) {
6a1aa64f 1295 // Set the number of ticks so that the labels are human-friendly.
285a6bda
DV
1296 // TODO(danvk): make this an attribute as well.
1297 var ticks = Dygraph.numericTicks(minY, maxY, this);
6a1aa64f
DV
1298 this.layout_.updateOptions( { yAxis: [minY, maxY],
1299 yTicks: ticks } );
1300};
1301
5011e7a1
DV
1302// Computes the range of the data series (including confidence intervals).
1303// series is either [ [x1, y1], [x2, y2], ... ] or
1304// [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
1305// Returns [low, high]
1306Dygraph.prototype.extremeValues_ = function(series) {
1307 var minY = null, maxY = null;
1308
9922b78b 1309 var bars = this.attr_("errorBars") || this.attr_("customBars");
5011e7a1
DV
1310 if (bars) {
1311 // With custom bars, maxY is the max of the high values.
1312 for (var j = 0; j < series.length; j++) {
1313 var y = series[j][1][0];
1314 if (!y) continue;
1315 var low = y - series[j][1][1];
1316 var high = y + series[j][1][2];
1317 if (low > y) low = y; // this can happen with custom bars,
1318 if (high < y) high = y; // e.g. in tests/custom-bars.html
1319 if (maxY == null || high > maxY) {
1320 maxY = high;
1321 }
1322 if (minY == null || low < minY) {
1323 minY = low;
1324 }
1325 }
1326 } else {
1327 for (var j = 0; j < series.length; j++) {
1328 var y = series[j][1];
d12999d3 1329 if (y === null || isNaN(y)) continue;
5011e7a1
DV
1330 if (maxY == null || y > maxY) {
1331 maxY = y;
1332 }
1333 if (minY == null || y < minY) {
1334 minY = y;
1335 }
1336 }
1337 }
1338
1339 return [minY, maxY];
1340};
1341
6a1aa64f
DV
1342/**
1343 * Update the graph with new data. Data is in the format
1344 * [ [date1, val1, val2, ...], [date2, val1, val2, ...] if errorBars=false
1345 * or, if errorBars=true,
1346 * [ [date1, [val1,stddev1], [val2,stddev2], ...], [date2, ...], ...]
1347 * @param {Array.<Object>} data The data (see above)
1348 * @private
1349 */
285a6bda 1350Dygraph.prototype.drawGraph_ = function(data) {
fe0b7c03
DV
1351 // This is used to set the second parameter to drawCallback, below.
1352 var is_initial_draw = this.is_initial_draw_;
1353 this.is_initial_draw_ = false;
1354
3bd9c228 1355 var minY = null, maxY = null;
6a1aa64f 1356 this.layout_.removeAllDatasets();
285a6bda 1357 this.setColors_();
9317362d 1358 this.attrs_['pointSize'] = 0.5 * this.attr_('highlightCircleSize');
285a6bda 1359
43af96e7
NK
1360 // For stacked series.
1361 var cumulative_y = [];
344ba8c0 1362 var stacked_datasets = [];
43af96e7 1363
6a1aa64f 1364 // Loop over all fields in the dataset
43af96e7 1365
6a1aa64f 1366 for (var i = 1; i < data[0].length; i++) {
1cf11047
DV
1367 if (!this.visibility()[i - 1]) continue;
1368
6a1aa64f
DV
1369 var series = [];
1370 for (var j = 0; j < data.length; j++) {
1371 var date = data[j][0];
1372 series[j] = [date, data[j][i]];
1373 }
1374 series = this.rollingAverage(series, this.rollPeriod_);
1375
1376 // Prune down to the desired range, if necessary (for zooming)
9922b78b 1377 var bars = this.attr_("errorBars") || this.attr_("customBars");
6a1aa64f
DV
1378 if (this.dateWindow_) {
1379 var low = this.dateWindow_[0];
1380 var high= this.dateWindow_[1];
1381 var pruned = [];
1382 for (var k = 0; k < series.length; k++) {
9ac5e4ae 1383 // if (series[k][0] >= low && series[k][0] <= high) {
6a1aa64f 1384 pruned.push(series[k]);
9ac5e4ae 1385 // }
6a1aa64f
DV
1386 }
1387 series = pruned;
6a1aa64f
DV
1388 }
1389
648acd28
DV
1390 var extremes = this.extremeValues_(series);
1391 var thisMinY = extremes[0];
1392 var thisMaxY = extremes[1];
5011e7a1
DV
1393 if (!minY || thisMinY < minY) minY = thisMinY;
1394 if (!maxY || thisMaxY > maxY) maxY = thisMaxY;
1395
6a1aa64f
DV
1396 if (bars) {
1397 var vals = [];
1398 for (var j=0; j<series.length; j++)
1399 vals[j] = [series[j][0],
1400 series[j][1][0], series[j][1][1], series[j][1][2]];
285a6bda 1401 this.layout_.addDataset(this.attr_("labels")[i], vals);
43af96e7
NK
1402 } else if (this.attr_("stackedGraph")) {
1403 var vals = [];
1404 var l = series.length;
1405 var actual_y;
1406 for (var j = 0; j < l; j++) {
1407 if (cumulative_y[series[j][0]] === undefined)
1408 cumulative_y[series[j][0]] = 0;
1409
1410 actual_y = series[j][1];
1411 cumulative_y[series[j][0]] += actual_y;
1412
1413 vals[j] = [series[j][0], cumulative_y[series[j][0]]]
1414
1415 if (!maxY || cumulative_y[series[j][0]] > maxY)
1416 maxY = cumulative_y[series[j][0]];
1417 }
344ba8c0 1418 stacked_datasets.push([this.attr_("labels")[i], vals]);
43af96e7 1419 //this.layout_.addDataset(this.attr_("labels")[i], vals);
6a1aa64f 1420 } else {
285a6bda 1421 this.layout_.addDataset(this.attr_("labels")[i], series);
6a1aa64f
DV
1422 }
1423 }
1424
344ba8c0
DV
1425 if (stacked_datasets.length > 0) {
1426 for (var i = (stacked_datasets.length - 1); i >= 0; i--) {
1427 this.layout_.addDataset(stacked_datasets[i][0], stacked_datasets[i][1]);
43af96e7
NK
1428 }
1429 }
1430
6a1aa64f
DV
1431 // Use some heuristics to come up with a good maxY value, unless it's been
1432 // set explicitly by the user.
1433 if (this.valueRange_ != null) {
1434 this.addYTicks_(this.valueRange_[0], this.valueRange_[1]);
1435 } else {
d053ab5a
DV
1436 // This affects the calculation of span, below.
1437 if (this.attr_("includeZero") && minY > 0) {
1438 minY = 0;
1439 }
1440
6a1aa64f 1441 // Add some padding and round up to an integer to be human-friendly.
3bd9c228 1442 var span = maxY - minY;
93dfacfd
DV
1443 // special case: if we have no sense of scale, use +/-10% of the sole value.
1444 if (span == 0) { span = maxY; }
3bd9c228
DV
1445 var maxAxisY = maxY + 0.1 * span;
1446 var minAxisY = minY - 0.1 * span;
1447
1448 // Try to include zero and make it minAxisY (or maxAxisY) if it makes sense.
ceb009dd
DV
1449 if (minAxisY < 0 && minY >= 0) minAxisY = 0;
1450 if (maxAxisY > 0 && maxY <= 0) maxAxisY = 0;
3bd9c228
DV
1451
1452 if (this.attr_("includeZero")) {
1453 if (maxY < 0) maxAxisY = 0;
1454 if (minY > 0) minAxisY = 0;
1455 }
1456
1457 this.addYTicks_(minAxisY, maxAxisY);
6a1aa64f
DV
1458 }
1459
1460 this.addXTicks_();
1461
1462 // Tell PlotKit to use this new data and render itself
d033ae1c 1463 this.layout_.updateOptions({dateWindow: this.dateWindow_});
6a1aa64f
DV
1464 this.layout_.evaluateWithError();
1465 this.plotter_.clear();
1466 this.plotter_.render();
f6401bf6
DV
1467 this.canvas_.getContext('2d').clearRect(0, 0, this.canvas_.width,
1468 this.canvas_.height);
599fb4ad
DV
1469
1470 if (this.attr_("drawCallback") !== null) {
fe0b7c03 1471 this.attr_("drawCallback")(this, is_initial_draw);
599fb4ad 1472 }
6a1aa64f
DV
1473};
1474
1475/**
1476 * Calculates the rolling average of a data set.
1477 * If originalData is [label, val], rolls the average of those.
1478 * If originalData is [label, [, it's interpreted as [value, stddev]
1479 * and the roll is returned in the same form, with appropriately reduced
1480 * stddev for each value.
1481 * Note that this is where fractional input (i.e. '5/10') is converted into
1482 * decimal values.
1483 * @param {Array} originalData The data in the appropriate format (see above)
1484 * @param {Number} rollPeriod The number of days over which to average the data
1485 */
285a6bda 1486Dygraph.prototype.rollingAverage = function(originalData, rollPeriod) {
6a1aa64f
DV
1487 if (originalData.length < 2)
1488 return originalData;
1489 var rollPeriod = Math.min(rollPeriod, originalData.length - 1);
1490 var rollingData = [];
285a6bda 1491 var sigma = this.attr_("sigma");
6a1aa64f
DV
1492
1493 if (this.fractions_) {
1494 var num = 0;
1495 var den = 0; // numerator/denominator
1496 var mult = 100.0;
1497 for (var i = 0; i < originalData.length; i++) {
1498 num += originalData[i][1][0];
1499 den += originalData[i][1][1];
1500 if (i - rollPeriod >= 0) {
1501 num -= originalData[i - rollPeriod][1][0];
1502 den -= originalData[i - rollPeriod][1][1];
1503 }
1504
1505 var date = originalData[i][0];
1506 var value = den ? num / den : 0.0;
285a6bda 1507 if (this.attr_("errorBars")) {
6a1aa64f
DV
1508 if (this.wilsonInterval_) {
1509 // For more details on this confidence interval, see:
1510 // http://en.wikipedia.org/wiki/Binomial_confidence_interval
1511 if (den) {
1512 var p = value < 0 ? 0 : value, n = den;
1513 var pm = sigma * Math.sqrt(p*(1-p)/n + sigma*sigma/(4*n*n));
1514 var denom = 1 + sigma * sigma / den;
1515 var low = (p + sigma * sigma / (2 * den) - pm) / denom;
1516 var high = (p + sigma * sigma / (2 * den) + pm) / denom;
1517 rollingData[i] = [date,
1518 [p * mult, (p - low) * mult, (high - p) * mult]];
1519 } else {
1520 rollingData[i] = [date, [0, 0, 0]];
1521 }
1522 } else {
1523 var stddev = den ? sigma * Math.sqrt(value * (1 - value) / den) : 1.0;
1524 rollingData[i] = [date, [mult * value, mult * stddev, mult * stddev]];
1525 }
1526 } else {
1527 rollingData[i] = [date, mult * value];
1528 }
1529 }
9922b78b 1530 } else if (this.attr_("customBars")) {
f6885d6a
DV
1531 var low = 0;
1532 var mid = 0;
1533 var high = 0;
1534 var count = 0;
6a1aa64f
DV
1535 for (var i = 0; i < originalData.length; i++) {
1536 var data = originalData[i][1];
1537 var y = data[1];
1538 rollingData[i] = [originalData[i][0], [y, y - data[0], data[2] - y]];
f6885d6a 1539
8b91c51f 1540 if (y != null && !isNaN(y)) {
49a7d0d5
DV
1541 low += data[0];
1542 mid += y;
1543 high += data[2];
1544 count += 1;
1545 }
f6885d6a
DV
1546 if (i - rollPeriod >= 0) {
1547 var prev = originalData[i - rollPeriod];
8b91c51f 1548 if (prev[1][1] != null && !isNaN(prev[1][1])) {
49a7d0d5
DV
1549 low -= prev[1][0];
1550 mid -= prev[1][1];
1551 high -= prev[1][2];
1552 count -= 1;
1553 }
f6885d6a
DV
1554 }
1555 rollingData[i] = [originalData[i][0], [ 1.0 * mid / count,
1556 1.0 * (mid - low) / count,
1557 1.0 * (high - mid) / count ]];
2769de62 1558 }
6a1aa64f
DV
1559 } else {
1560 // Calculate the rolling average for the first rollPeriod - 1 points where
1561 // there is not enough data to roll over the full number of days
1562 var num_init_points = Math.min(rollPeriod - 1, originalData.length - 2);
285a6bda 1563 if (!this.attr_("errorBars")){
5011e7a1
DV
1564 if (rollPeriod == 1) {
1565 return originalData;
1566 }
1567
2847c1cf 1568 for (var i = 0; i < originalData.length; i++) {
6a1aa64f 1569 var sum = 0;
5011e7a1 1570 var num_ok = 0;
2847c1cf
DV
1571 for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
1572 var y = originalData[j][1];
8b91c51f 1573 if (y == null || isNaN(y)) continue;
5011e7a1 1574 num_ok++;
2847c1cf 1575 sum += originalData[j][1];
6a1aa64f 1576 }
5011e7a1 1577 if (num_ok) {
2847c1cf 1578 rollingData[i] = [originalData[i][0], sum / num_ok];
5011e7a1 1579 } else {
2847c1cf 1580 rollingData[i] = [originalData[i][0], null];
5011e7a1 1581 }
6a1aa64f 1582 }
2847c1cf
DV
1583
1584 } else {
1585 for (var i = 0; i < originalData.length; i++) {
6a1aa64f
DV
1586 var sum = 0;
1587 var variance = 0;
5011e7a1 1588 var num_ok = 0;
2847c1cf 1589 for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
5011e7a1 1590 var y = originalData[j][1][0];
8b91c51f 1591 if (y == null || isNaN(y)) continue;
5011e7a1 1592 num_ok++;
6a1aa64f
DV
1593 sum += originalData[j][1][0];
1594 variance += Math.pow(originalData[j][1][1], 2);
1595 }
5011e7a1
DV
1596 if (num_ok) {
1597 var stddev = Math.sqrt(variance) / num_ok;
1598 rollingData[i] = [originalData[i][0],
1599 [sum / num_ok, sigma * stddev, sigma * stddev]];
1600 } else {
1601 rollingData[i] = [originalData[i][0], [null, null, null]];
1602 }
6a1aa64f
DV
1603 }
1604 }
1605 }
1606
1607 return rollingData;
1608};
1609
1610/**
1611 * Parses a date, returning the number of milliseconds since epoch. This can be
285a6bda
DV
1612 * passed in as an xValueParser in the Dygraph constructor.
1613 * TODO(danvk): enumerate formats that this understands.
6a1aa64f
DV
1614 * @param {String} A date in YYYYMMDD format.
1615 * @return {Number} Milliseconds since epoch.
1616 * @public
1617 */
285a6bda 1618Dygraph.dateParser = function(dateStr, self) {
6a1aa64f 1619 var dateStrSlashed;
285a6bda 1620 var d;
986a5026 1621 if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
6a1aa64f 1622 dateStrSlashed = dateStr.replace("-", "/", "g");
353a0294
DV
1623 while (dateStrSlashed.search("-") != -1) {
1624 dateStrSlashed = dateStrSlashed.replace("-", "/");
1625 }
285a6bda 1626 d = Date.parse(dateStrSlashed);
2769de62 1627 } else if (dateStr.length == 8) { // e.g. '20090712'
285a6bda 1628 // TODO(danvk): remove support for this format. It's confusing.
6a1aa64f
DV
1629 dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2)
1630 + "/" + dateStr.substr(6,2);
285a6bda 1631 d = Date.parse(dateStrSlashed);
2769de62
DV
1632 } else {
1633 // Any format that Date.parse will accept, e.g. "2009/07/12" or
1634 // "2009/07/12 12:34:56"
285a6bda
DV
1635 d = Date.parse(dateStr);
1636 }
1637
1638 if (!d || isNaN(d)) {
1639 self.error("Couldn't parse " + dateStr + " as a date");
1640 }
1641 return d;
1642};
1643
1644/**
1645 * Detects the type of the str (date or numeric) and sets the various
1646 * formatting attributes in this.attrs_ based on this type.
1647 * @param {String} str An x value.
1648 * @private
1649 */
1650Dygraph.prototype.detectTypeFromString_ = function(str) {
1651 var isDate = false;
1652 if (str.indexOf('-') >= 0 ||
1653 str.indexOf('/') >= 0 ||
1654 isNaN(parseFloat(str))) {
1655 isDate = true;
1656 } else if (str.length == 8 && str > '19700101' && str < '20371231') {
1657 // TODO(danvk): remove support for this format.
1658 isDate = true;
1659 }
1660
1661 if (isDate) {
1662 this.attrs_.xValueFormatter = Dygraph.dateString_;
1663 this.attrs_.xValueParser = Dygraph.dateParser;
1664 this.attrs_.xTicker = Dygraph.dateTicker;
1665 } else {
1666 this.attrs_.xValueFormatter = function(x) { return x; };
1667 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
1668 this.attrs_.xTicker = Dygraph.numericTicks;
6a1aa64f 1669 }
6a1aa64f
DV
1670};
1671
1672/**
1673 * Parses a string in a special csv format. We expect a csv file where each
1674 * line is a date point, and the first field in each line is the date string.
1675 * We also expect that all remaining fields represent series.
285a6bda 1676 * if the errorBars attribute is set, then interpret the fields as:
6a1aa64f
DV
1677 * date, series1, stddev1, series2, stddev2, ...
1678 * @param {Array.<Object>} data See above.
1679 * @private
285a6bda
DV
1680 *
1681 * @return Array.<Object> An array with one entry for each row. These entries
1682 * are an array of cells in that row. The first entry is the parsed x-value for
1683 * the row. The second, third, etc. are the y-values. These can take on one of
1684 * three forms, depending on the CSV and constructor parameters:
1685 * 1. numeric value
1686 * 2. [ value, stddev ]
1687 * 3. [ low value, center value, high value ]
6a1aa64f 1688 */
285a6bda 1689Dygraph.prototype.parseCSV_ = function(data) {
6a1aa64f
DV
1690 var ret = [];
1691 var lines = data.split("\n");
3d67f03b
DV
1692
1693 // Use the default delimiter or fall back to a tab if that makes sense.
1694 var delim = this.attr_('delimiter');
1695 if (lines[0].indexOf(delim) == -1 && lines[0].indexOf('\t') >= 0) {
1696 delim = '\t';
1697 }
1698
285a6bda 1699 var start = 0;
6a1aa64f 1700 if (this.labelsFromCSV_) {
285a6bda 1701 start = 1;
3d67f03b 1702 this.attrs_.labels = lines[0].split(delim);
6a1aa64f
DV
1703 }
1704
285a6bda
DV
1705 var xParser;
1706 var defaultParserSet = false; // attempt to auto-detect x value type
1707 var expectedCols = this.attr_("labels").length;
987840a2 1708 var outOfOrder = false;
6a1aa64f
DV
1709 for (var i = start; i < lines.length; i++) {
1710 var line = lines[i];
1711 if (line.length == 0) continue; // skip blank lines
3d67f03b
DV
1712 if (line[0] == '#') continue; // skip comment lines
1713 var inFields = line.split(delim);
285a6bda 1714 if (inFields.length < 2) continue;
6a1aa64f
DV
1715
1716 var fields = [];
285a6bda
DV
1717 if (!defaultParserSet) {
1718 this.detectTypeFromString_(inFields[0]);
1719 xParser = this.attr_("xValueParser");
1720 defaultParserSet = true;
1721 }
1722 fields[0] = xParser(inFields[0], this);
6a1aa64f
DV
1723
1724 // If fractions are expected, parse the numbers as "A/B"
1725 if (this.fractions_) {
1726 for (var j = 1; j < inFields.length; j++) {
1727 // TODO(danvk): figure out an appropriate way to flag parse errors.
1728 var vals = inFields[j].split("/");
1729 fields[j] = [parseFloat(vals[0]), parseFloat(vals[1])];
1730 }
285a6bda 1731 } else if (this.attr_("errorBars")) {
6a1aa64f
DV
1732 // If there are error bars, values are (value, stddev) pairs
1733 for (var j = 1; j < inFields.length; j += 2)
1734 fields[(j + 1) / 2] = [parseFloat(inFields[j]),
1735 parseFloat(inFields[j + 1])];
9922b78b 1736 } else if (this.attr_("customBars")) {
6a1aa64f
DV
1737 // Bars are a low;center;high tuple
1738 for (var j = 1; j < inFields.length; j++) {
1739 var vals = inFields[j].split(";");
1740 fields[j] = [ parseFloat(vals[0]),
1741 parseFloat(vals[1]),
1742 parseFloat(vals[2]) ];
1743 }
1744 } else {
1745 // Values are just numbers
285a6bda 1746 for (var j = 1; j < inFields.length; j++) {
6a1aa64f 1747 fields[j] = parseFloat(inFields[j]);
285a6bda 1748 }
6a1aa64f 1749 }
987840a2
DV
1750 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
1751 outOfOrder = true;
1752 }
6a1aa64f 1753 ret.push(fields);
285a6bda
DV
1754
1755 if (fields.length != expectedCols) {
1756 this.error("Number of columns in line " + i + " (" + fields.length +
1757 ") does not agree with number of labels (" + expectedCols +
1758 ") " + line);
1759 }
6a1aa64f 1760 }
987840a2
DV
1761
1762 if (outOfOrder) {
1763 this.warn("CSV is out of order; order it correctly to speed loading.");
1764 ret.sort(function(a,b) { return a[0] - b[0] });
1765 }
1766
6a1aa64f
DV
1767 return ret;
1768};
1769
1770/**
285a6bda
DV
1771 * The user has provided their data as a pre-packaged JS array. If the x values
1772 * are numeric, this is the same as dygraphs' internal format. If the x values
1773 * are dates, we need to convert them from Date objects to ms since epoch.
1774 * @param {Array.<Object>} data
1775 * @return {Array.<Object>} data with numeric x values.
1776 */
1777Dygraph.prototype.parseArray_ = function(data) {
1778 // Peek at the first x value to see if it's numeric.
1779 if (data.length == 0) {
1780 this.error("Can't plot empty data set");
1781 return null;
1782 }
1783 if (data[0].length == 0) {
1784 this.error("Data set cannot contain an empty row");
1785 return null;
1786 }
1787
1788 if (this.attr_("labels") == null) {
1789 this.warn("Using default labels. Set labels explicitly via 'labels' " +
1790 "in the options parameter");
1791 this.attrs_.labels = [ "X" ];
1792 for (var i = 1; i < data[0].length; i++) {
1793 this.attrs_.labels.push("Y" + i);
1794 }
1795 }
1796
2dda3850 1797 if (Dygraph.isDateLike(data[0][0])) {
285a6bda
DV
1798 // Some intelligent defaults for a date x-axis.
1799 this.attrs_.xValueFormatter = Dygraph.dateString_;
1800 this.attrs_.xTicker = Dygraph.dateTicker;
1801
1802 // Assume they're all dates.
e3ab7b40 1803 var parsedData = Dygraph.clone(data);
285a6bda
DV
1804 for (var i = 0; i < data.length; i++) {
1805 if (parsedData[i].length == 0) {
1806 this.error("Row " << (1 + i) << " of data is empty");
1807 return null;
1808 }
1809 if (parsedData[i][0] == null
1810 || typeof(parsedData[i][0].getTime) != 'function') {
1811 this.error("x value in row " << (1 + i) << " is not a Date");
1812 return null;
1813 }
1814 parsedData[i][0] = parsedData[i][0].getTime();
1815 }
1816 return parsedData;
1817 } else {
1818 // Some intelligent defaults for a numeric x-axis.
1819 this.attrs_.xValueFormatter = function(x) { return x; };
1820 this.attrs_.xTicker = Dygraph.numericTicks;
1821 return data;
1822 }
1823};
1824
1825/**
79420a1e
DV
1826 * Parses a DataTable object from gviz.
1827 * The data is expected to have a first column that is either a date or a
1828 * number. All subsequent columns must be numbers. If there is a clear mismatch
1829 * between this.xValueParser_ and the type of the first column, it will be
1830 * fixed. Returned value is in the same format as return value of parseCSV_.
1831 * @param {Array.<Object>} data See above.
1832 * @private
1833 */
285a6bda 1834Dygraph.prototype.parseDataTable_ = function(data) {
79420a1e
DV
1835 var cols = data.getNumberOfColumns();
1836 var rows = data.getNumberOfRows();
1837
1838 // Read column labels
1839 var labels = [];
1840 for (var i = 0; i < cols; i++) {
1841 labels.push(data.getColumnLabel(i));
3e3f84e4 1842 if (i != 0 && this.attr_("errorBars")) i += 1;
79420a1e 1843 }
285a6bda 1844 this.attrs_.labels = labels;
3e3f84e4 1845 cols = labels.length;
79420a1e 1846
d955e223 1847 var indepType = data.getColumnType(0);
4440f6c8 1848 if (indepType == 'date' || indepType == 'datetime') {
285a6bda
DV
1849 this.attrs_.xValueFormatter = Dygraph.dateString_;
1850 this.attrs_.xValueParser = Dygraph.dateParser;
1851 this.attrs_.xTicker = Dygraph.dateTicker;
33127159 1852 } else if (indepType == 'number') {
285a6bda
DV
1853 this.attrs_.xValueFormatter = function(x) { return x; };
1854 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
1855 this.attrs_.xTicker = Dygraph.numericTicks;
1856 } else {
987840a2
DV
1857 this.error("only 'date', 'datetime' and 'number' types are supported for " +
1858 "column 1 of DataTable input (Got '" + indepType + "')");
79420a1e
DV
1859 return null;
1860 }
1861
1862 var ret = [];
987840a2 1863 var outOfOrder = false;
79420a1e
DV
1864 for (var i = 0; i < rows; i++) {
1865 var row = [];
debe4434
DV
1866 if (typeof(data.getValue(i, 0)) === 'undefined' ||
1867 data.getValue(i, 0) === null) {
1868 this.warning("Ignoring row " + i +
1869 " of DataTable because of undefined or null first column.");
1870 continue;
1871 }
1872
c21d2c2d 1873 if (indepType == 'date' || indepType == 'datetime') {
d955e223
DV
1874 row.push(data.getValue(i, 0).getTime());
1875 } else {
1876 row.push(data.getValue(i, 0));
1877 }
3e3f84e4
DV
1878 if (!this.attr_("errorBars")) {
1879 for (var j = 1; j < cols; j++) {
1880 row.push(data.getValue(i, j));
1881 }
1882 } else {
1883 for (var j = 0; j < cols - 1; j++) {
1884 row.push([ data.getValue(i, 1 + 2 * j), data.getValue(i, 2 + 2 * j) ]);
1885 }
79420a1e 1886 }
987840a2
DV
1887 if (ret.length > 0 && row[0] < ret[ret.length - 1][0]) {
1888 outOfOrder = true;
1889 }
243d96e8 1890 ret.push(row);
79420a1e 1891 }
987840a2
DV
1892
1893 if (outOfOrder) {
1894 this.warn("DataTable is out of order; order it correctly to speed loading.");
1895 ret.sort(function(a,b) { return a[0] - b[0] });
1896 }
79420a1e
DV
1897 return ret;
1898}
1899
24e5350c 1900// These functions are all based on MochiKit.
fc80a396
DV
1901Dygraph.update = function (self, o) {
1902 if (typeof(o) != 'undefined' && o !== null) {
1903 for (var k in o) {
85b99f0b
DV
1904 if (o.hasOwnProperty(k)) {
1905 self[k] = o[k];
1906 }
fc80a396
DV
1907 }
1908 }
1909 return self;
1910};
1911
2dda3850
DV
1912Dygraph.isArrayLike = function (o) {
1913 var typ = typeof(o);
1914 if (
c21d2c2d 1915 (typ != 'object' && !(typ == 'function' &&
2dda3850
DV
1916 typeof(o.item) == 'function')) ||
1917 o === null ||
1918 typeof(o.length) != 'number' ||
1919 o.nodeType === 3
1920 ) {
1921 return false;
1922 }
1923 return true;
1924};
1925
1926Dygraph.isDateLike = function (o) {
1927 if (typeof(o) != "object" || o === null ||
1928 typeof(o.getTime) != 'function') {
1929 return false;
1930 }
1931 return true;
1932};
1933
e3ab7b40
DV
1934Dygraph.clone = function(o) {
1935 // TODO(danvk): figure out how MochiKit's version works
1936 var r = [];
1937 for (var i = 0; i < o.length; i++) {
1938 if (Dygraph.isArrayLike(o[i])) {
1939 r.push(Dygraph.clone(o[i]));
1940 } else {
1941 r.push(o[i]);
1942 }
1943 }
1944 return r;
24e5350c
DV
1945};
1946
2dda3850 1947
79420a1e 1948/**
6a1aa64f
DV
1949 * Get the CSV data. If it's in a function, call that function. If it's in a
1950 * file, do an XMLHttpRequest to get it.
1951 * @private
1952 */
285a6bda 1953Dygraph.prototype.start_ = function() {
6a1aa64f 1954 if (typeof this.file_ == 'function') {
285a6bda 1955 // CSV string. Pretend we got it via XHR.
6a1aa64f 1956 this.loadedEvent_(this.file_());
2dda3850 1957 } else if (Dygraph.isArrayLike(this.file_)) {
285a6bda
DV
1958 this.rawData_ = this.parseArray_(this.file_);
1959 this.drawGraph_(this.rawData_);
79420a1e
DV
1960 } else if (typeof this.file_ == 'object' &&
1961 typeof this.file_.getColumnRange == 'function') {
1962 // must be a DataTable from gviz.
1963 this.rawData_ = this.parseDataTable_(this.file_);
1964 this.drawGraph_(this.rawData_);
285a6bda
DV
1965 } else if (typeof this.file_ == 'string') {
1966 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
1967 if (this.file_.indexOf('\n') >= 0) {
1968 this.loadedEvent_(this.file_);
1969 } else {
1970 var req = new XMLHttpRequest();
1971 var caller = this;
1972 req.onreadystatechange = function () {
1973 if (req.readyState == 4) {
1974 if (req.status == 200) {
1975 caller.loadedEvent_(req.responseText);
1976 }
6a1aa64f 1977 }
285a6bda 1978 };
6a1aa64f 1979
285a6bda
DV
1980 req.open("GET", this.file_, true);
1981 req.send(null);
1982 }
1983 } else {
1984 this.error("Unknown data format: " + (typeof this.file_));
6a1aa64f
DV
1985 }
1986};
1987
1988/**
1989 * Changes various properties of the graph. These can include:
1990 * <ul>
1991 * <li>file: changes the source data for the graph</li>
1992 * <li>errorBars: changes whether the data contains stddev</li>
1993 * </ul>
1994 * @param {Object} attrs The new properties and values
1995 */
285a6bda
DV
1996Dygraph.prototype.updateOptions = function(attrs) {
1997 // TODO(danvk): this is a mess. Rethink this function.
6a1aa64f
DV
1998 if (attrs.rollPeriod) {
1999 this.rollPeriod_ = attrs.rollPeriod;
2000 }
2001 if (attrs.dateWindow) {
2002 this.dateWindow_ = attrs.dateWindow;
2003 }
2004 if (attrs.valueRange) {
2005 this.valueRange_ = attrs.valueRange;
2006 }
fc80a396 2007 Dygraph.update(this.user_attrs_, attrs);
285a6bda
DV
2008
2009 this.labelsFromCSV_ = (this.attr_("labels") == null);
2010
2011 // TODO(danvk): this doesn't match the constructor logic
2012 this.layout_.updateOptions({ 'errorBars': this.attr_("errorBars") });
6a1aa64f
DV
2013 if (attrs['file'] && attrs['file'] != this.file_) {
2014 this.file_ = attrs['file'];
2015 this.start_();
2016 } else {
2017 this.drawGraph_(this.rawData_);
2018 }
2019};
2020
2021/**
697e70b2
DV
2022 * Resizes the dygraph. If no parameters are specified, resizes to fill the
2023 * containing div (which has presumably changed size since the dygraph was
2024 * instantiated. If the width/height are specified, the div will be resized.
964f30c6
DV
2025 *
2026 * This is far more efficient than destroying and re-instantiating a
2027 * Dygraph, since it doesn't have to reparse the underlying data.
2028 *
697e70b2
DV
2029 * @param {Number} width Width (in pixels)
2030 * @param {Number} height Height (in pixels)
2031 */
2032Dygraph.prototype.resize = function(width, height) {
2033 if ((width === null) != (height === null)) {
2034 this.warn("Dygraph.resize() should be called with zero parameters or " +
2035 "two non-NULL parameters. Pretending it was zero.");
2036 width = height = null;
2037 }
2038
b16e6369 2039 // TODO(danvk): there should be a clear() method.
697e70b2 2040 this.maindiv_.innerHTML = "";
b16e6369
DV
2041 this.attrs_.labelsDiv = null;
2042
697e70b2
DV
2043 if (width) {
2044 this.maindiv_.style.width = width + "px";
2045 this.maindiv_.style.height = height + "px";
2046 this.width_ = width;
2047 this.height_ = height;
2048 } else {
2049 this.width_ = this.maindiv_.offsetWidth;
2050 this.height_ = this.maindiv_.offsetHeight;
2051 }
2052
2053 this.createInterface_();
964f30c6 2054 this.drawGraph_(this.rawData_);
697e70b2
DV
2055};
2056
2057/**
6a1aa64f
DV
2058 * Adjusts the number of days in the rolling average. Updates the graph to
2059 * reflect the new averaging period.
2060 * @param {Number} length Number of days over which to average the data.
2061 */
285a6bda 2062Dygraph.prototype.adjustRoll = function(length) {
6a1aa64f
DV
2063 this.rollPeriod_ = length;
2064 this.drawGraph_(this.rawData_);
2065};
540d00f1 2066
f8cfec73 2067/**
1cf11047
DV
2068 * Returns a boolean array of visibility statuses.
2069 */
2070Dygraph.prototype.visibility = function() {
2071 // Do lazy-initialization, so that this happens after we know the number of
2072 // data series.
2073 if (!this.attr_("visibility")) {
f38dec01 2074 this.attrs_["visibility"] = [];
1cf11047
DV
2075 }
2076 while (this.attr_("visibility").length < this.rawData_[0].length - 1) {
f38dec01 2077 this.attr_("visibility").push(true);
1cf11047
DV
2078 }
2079 return this.attr_("visibility");
2080};
2081
2082/**
2083 * Changes the visiblity of a series.
2084 */
2085Dygraph.prototype.setVisibility = function(num, value) {
2086 var x = this.visibility();
2087 if (num < 0 && num >= x.length) {
2088 this.warn("invalid series number in setVisibility: " + num);
2089 } else {
2090 x[num] = value;
2091 this.drawGraph_(this.rawData_);
2092 }
2093};
2094
2095/**
f8cfec73
DV
2096 * Create a new canvas element. This is more complex than a simple
2097 * document.createElement("canvas") because of IE and excanvas.
2098 */
2099Dygraph.createCanvas = function() {
2100 var canvas = document.createElement("canvas");
2101
2102 isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
2103 if (isIE) {
2104 canvas = G_vmlCanvasManager.initElement(canvas);
2105 }
2106
2107 return canvas;
2108};
2109
540d00f1
DV
2110
2111/**
285a6bda 2112 * A wrapper around Dygraph that implements the gviz API.
540d00f1
DV
2113 * @param {Object} container The DOM object the visualization should live in.
2114 */
285a6bda 2115Dygraph.GVizChart = function(container) {
540d00f1
DV
2116 this.container = container;
2117}
2118
285a6bda 2119Dygraph.GVizChart.prototype.draw = function(data, options) {
540d00f1 2120 this.container.innerHTML = '';
285a6bda 2121 this.date_graph = new Dygraph(this.container, data, options);
540d00f1 2122}
285a6bda
DV
2123
2124// Older pages may still use this name.
2125DateGraph = Dygraph;