prune to visible range, plus one point on either side (for overdrawing)
[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
DV
1364 // Loop over all fields in the dataset
1365 for (var i = 1; i < data[0].length; i++) {
1cf11047
DV
1366 if (!this.visibility()[i - 1]) continue;
1367
6a1aa64f
DV
1368 var series = [];
1369 for (var j = 0; j < data.length; j++) {
1370 var date = data[j][0];
1371 series[j] = [date, data[j][i]];
1372 }
1373 series = this.rollingAverage(series, this.rollPeriod_);
1374
1375 // Prune down to the desired range, if necessary (for zooming)
1a26f3fb
DV
1376 // Because there can be lines going to points outside of the visible area,
1377 // we actually prune to visible points, plus one on either side.
9922b78b 1378 var bars = this.attr_("errorBars") || this.attr_("customBars");
6a1aa64f
DV
1379 if (this.dateWindow_) {
1380 var low = this.dateWindow_[0];
1381 var high= this.dateWindow_[1];
1382 var pruned = [];
1a26f3fb
DV
1383 // TODO(danvk): do binary search instead of linear search.
1384 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
1385 var firstIdx = null, lastIdx = null;
6a1aa64f 1386 for (var k = 0; k < series.length; k++) {
1a26f3fb
DV
1387 if (series[k][0] >= low && firstIdx === null) {
1388 firstIdx = k;
1389 }
1390 if (series[k][0] <= high) {
1391 lastIdx = k;
1392 }
1393 }
1394 if (firstIdx === null) firstIdx = 0;
1395 if (firstIdx > 0) firstIdx--;
1396 if (lastIdx === null) lastIdx = series.length - 1;
1397 if (lastIdx < series.length - 1) lastIdx++;
1398 for (var k = firstIdx; k <= lastIdx; k++) {
1399 pruned.push(series[k]);
6a1aa64f
DV
1400 }
1401 series = pruned;
6a1aa64f
DV
1402 }
1403
648acd28
DV
1404 var extremes = this.extremeValues_(series);
1405 var thisMinY = extremes[0];
1406 var thisMaxY = extremes[1];
5011e7a1
DV
1407 if (!minY || thisMinY < minY) minY = thisMinY;
1408 if (!maxY || thisMaxY > maxY) maxY = thisMaxY;
1409
6a1aa64f
DV
1410 if (bars) {
1411 var vals = [];
1412 for (var j=0; j<series.length; j++)
1413 vals[j] = [series[j][0],
1414 series[j][1][0], series[j][1][1], series[j][1][2]];
285a6bda 1415 this.layout_.addDataset(this.attr_("labels")[i], vals);
43af96e7
NK
1416 } else if (this.attr_("stackedGraph")) {
1417 var vals = [];
1418 var l = series.length;
1419 var actual_y;
1420 for (var j = 0; j < l; j++) {
1421 if (cumulative_y[series[j][0]] === undefined)
1422 cumulative_y[series[j][0]] = 0;
1423
1424 actual_y = series[j][1];
1425 cumulative_y[series[j][0]] += actual_y;
1426
1427 vals[j] = [series[j][0], cumulative_y[series[j][0]]]
1428
1429 if (!maxY || cumulative_y[series[j][0]] > maxY)
1430 maxY = cumulative_y[series[j][0]];
1431 }
344ba8c0 1432 stacked_datasets.push([this.attr_("labels")[i], vals]);
43af96e7 1433 //this.layout_.addDataset(this.attr_("labels")[i], vals);
6a1aa64f 1434 } else {
285a6bda 1435 this.layout_.addDataset(this.attr_("labels")[i], series);
6a1aa64f
DV
1436 }
1437 }
1438
344ba8c0
DV
1439 if (stacked_datasets.length > 0) {
1440 for (var i = (stacked_datasets.length - 1); i >= 0; i--) {
1441 this.layout_.addDataset(stacked_datasets[i][0], stacked_datasets[i][1]);
43af96e7
NK
1442 }
1443 }
1444
6a1aa64f
DV
1445 // Use some heuristics to come up with a good maxY value, unless it's been
1446 // set explicitly by the user.
1447 if (this.valueRange_ != null) {
1448 this.addYTicks_(this.valueRange_[0], this.valueRange_[1]);
1449 } else {
d053ab5a
DV
1450 // This affects the calculation of span, below.
1451 if (this.attr_("includeZero") && minY > 0) {
1452 minY = 0;
1453 }
1454
6a1aa64f 1455 // Add some padding and round up to an integer to be human-friendly.
3bd9c228 1456 var span = maxY - minY;
93dfacfd
DV
1457 // special case: if we have no sense of scale, use +/-10% of the sole value.
1458 if (span == 0) { span = maxY; }
3bd9c228
DV
1459 var maxAxisY = maxY + 0.1 * span;
1460 var minAxisY = minY - 0.1 * span;
1461
1462 // Try to include zero and make it minAxisY (or maxAxisY) if it makes sense.
ceb009dd
DV
1463 if (minAxisY < 0 && minY >= 0) minAxisY = 0;
1464 if (maxAxisY > 0 && maxY <= 0) maxAxisY = 0;
3bd9c228
DV
1465
1466 if (this.attr_("includeZero")) {
1467 if (maxY < 0) maxAxisY = 0;
1468 if (minY > 0) minAxisY = 0;
1469 }
1470
1471 this.addYTicks_(minAxisY, maxAxisY);
6a1aa64f
DV
1472 }
1473
1474 this.addXTicks_();
1475
1476 // Tell PlotKit to use this new data and render itself
d033ae1c 1477 this.layout_.updateOptions({dateWindow: this.dateWindow_});
6a1aa64f
DV
1478 this.layout_.evaluateWithError();
1479 this.plotter_.clear();
1480 this.plotter_.render();
f6401bf6
DV
1481 this.canvas_.getContext('2d').clearRect(0, 0, this.canvas_.width,
1482 this.canvas_.height);
599fb4ad
DV
1483
1484 if (this.attr_("drawCallback") !== null) {
fe0b7c03 1485 this.attr_("drawCallback")(this, is_initial_draw);
599fb4ad 1486 }
6a1aa64f
DV
1487};
1488
1489/**
1490 * Calculates the rolling average of a data set.
1491 * If originalData is [label, val], rolls the average of those.
1492 * If originalData is [label, [, it's interpreted as [value, stddev]
1493 * and the roll is returned in the same form, with appropriately reduced
1494 * stddev for each value.
1495 * Note that this is where fractional input (i.e. '5/10') is converted into
1496 * decimal values.
1497 * @param {Array} originalData The data in the appropriate format (see above)
1498 * @param {Number} rollPeriod The number of days over which to average the data
1499 */
285a6bda 1500Dygraph.prototype.rollingAverage = function(originalData, rollPeriod) {
6a1aa64f
DV
1501 if (originalData.length < 2)
1502 return originalData;
1503 var rollPeriod = Math.min(rollPeriod, originalData.length - 1);
1504 var rollingData = [];
285a6bda 1505 var sigma = this.attr_("sigma");
6a1aa64f
DV
1506
1507 if (this.fractions_) {
1508 var num = 0;
1509 var den = 0; // numerator/denominator
1510 var mult = 100.0;
1511 for (var i = 0; i < originalData.length; i++) {
1512 num += originalData[i][1][0];
1513 den += originalData[i][1][1];
1514 if (i - rollPeriod >= 0) {
1515 num -= originalData[i - rollPeriod][1][0];
1516 den -= originalData[i - rollPeriod][1][1];
1517 }
1518
1519 var date = originalData[i][0];
1520 var value = den ? num / den : 0.0;
285a6bda 1521 if (this.attr_("errorBars")) {
6a1aa64f
DV
1522 if (this.wilsonInterval_) {
1523 // For more details on this confidence interval, see:
1524 // http://en.wikipedia.org/wiki/Binomial_confidence_interval
1525 if (den) {
1526 var p = value < 0 ? 0 : value, n = den;
1527 var pm = sigma * Math.sqrt(p*(1-p)/n + sigma*sigma/(4*n*n));
1528 var denom = 1 + sigma * sigma / den;
1529 var low = (p + sigma * sigma / (2 * den) - pm) / denom;
1530 var high = (p + sigma * sigma / (2 * den) + pm) / denom;
1531 rollingData[i] = [date,
1532 [p * mult, (p - low) * mult, (high - p) * mult]];
1533 } else {
1534 rollingData[i] = [date, [0, 0, 0]];
1535 }
1536 } else {
1537 var stddev = den ? sigma * Math.sqrt(value * (1 - value) / den) : 1.0;
1538 rollingData[i] = [date, [mult * value, mult * stddev, mult * stddev]];
1539 }
1540 } else {
1541 rollingData[i] = [date, mult * value];
1542 }
1543 }
9922b78b 1544 } else if (this.attr_("customBars")) {
f6885d6a
DV
1545 var low = 0;
1546 var mid = 0;
1547 var high = 0;
1548 var count = 0;
6a1aa64f
DV
1549 for (var i = 0; i < originalData.length; i++) {
1550 var data = originalData[i][1];
1551 var y = data[1];
1552 rollingData[i] = [originalData[i][0], [y, y - data[0], data[2] - y]];
f6885d6a 1553
8b91c51f 1554 if (y != null && !isNaN(y)) {
49a7d0d5
DV
1555 low += data[0];
1556 mid += y;
1557 high += data[2];
1558 count += 1;
1559 }
f6885d6a
DV
1560 if (i - rollPeriod >= 0) {
1561 var prev = originalData[i - rollPeriod];
8b91c51f 1562 if (prev[1][1] != null && !isNaN(prev[1][1])) {
49a7d0d5
DV
1563 low -= prev[1][0];
1564 mid -= prev[1][1];
1565 high -= prev[1][2];
1566 count -= 1;
1567 }
f6885d6a
DV
1568 }
1569 rollingData[i] = [originalData[i][0], [ 1.0 * mid / count,
1570 1.0 * (mid - low) / count,
1571 1.0 * (high - mid) / count ]];
2769de62 1572 }
6a1aa64f
DV
1573 } else {
1574 // Calculate the rolling average for the first rollPeriod - 1 points where
1575 // there is not enough data to roll over the full number of days
1576 var num_init_points = Math.min(rollPeriod - 1, originalData.length - 2);
285a6bda 1577 if (!this.attr_("errorBars")){
5011e7a1
DV
1578 if (rollPeriod == 1) {
1579 return originalData;
1580 }
1581
2847c1cf 1582 for (var i = 0; i < originalData.length; i++) {
6a1aa64f 1583 var sum = 0;
5011e7a1 1584 var num_ok = 0;
2847c1cf
DV
1585 for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
1586 var y = originalData[j][1];
8b91c51f 1587 if (y == null || isNaN(y)) continue;
5011e7a1 1588 num_ok++;
2847c1cf 1589 sum += originalData[j][1];
6a1aa64f 1590 }
5011e7a1 1591 if (num_ok) {
2847c1cf 1592 rollingData[i] = [originalData[i][0], sum / num_ok];
5011e7a1 1593 } else {
2847c1cf 1594 rollingData[i] = [originalData[i][0], null];
5011e7a1 1595 }
6a1aa64f 1596 }
2847c1cf
DV
1597
1598 } else {
1599 for (var i = 0; i < originalData.length; i++) {
6a1aa64f
DV
1600 var sum = 0;
1601 var variance = 0;
5011e7a1 1602 var num_ok = 0;
2847c1cf 1603 for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
5011e7a1 1604 var y = originalData[j][1][0];
8b91c51f 1605 if (y == null || isNaN(y)) continue;
5011e7a1 1606 num_ok++;
6a1aa64f
DV
1607 sum += originalData[j][1][0];
1608 variance += Math.pow(originalData[j][1][1], 2);
1609 }
5011e7a1
DV
1610 if (num_ok) {
1611 var stddev = Math.sqrt(variance) / num_ok;
1612 rollingData[i] = [originalData[i][0],
1613 [sum / num_ok, sigma * stddev, sigma * stddev]];
1614 } else {
1615 rollingData[i] = [originalData[i][0], [null, null, null]];
1616 }
6a1aa64f
DV
1617 }
1618 }
1619 }
1620
1621 return rollingData;
1622};
1623
1624/**
1625 * Parses a date, returning the number of milliseconds since epoch. This can be
285a6bda
DV
1626 * passed in as an xValueParser in the Dygraph constructor.
1627 * TODO(danvk): enumerate formats that this understands.
6a1aa64f
DV
1628 * @param {String} A date in YYYYMMDD format.
1629 * @return {Number} Milliseconds since epoch.
1630 * @public
1631 */
285a6bda 1632Dygraph.dateParser = function(dateStr, self) {
6a1aa64f 1633 var dateStrSlashed;
285a6bda 1634 var d;
986a5026 1635 if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
6a1aa64f 1636 dateStrSlashed = dateStr.replace("-", "/", "g");
353a0294
DV
1637 while (dateStrSlashed.search("-") != -1) {
1638 dateStrSlashed = dateStrSlashed.replace("-", "/");
1639 }
285a6bda 1640 d = Date.parse(dateStrSlashed);
2769de62 1641 } else if (dateStr.length == 8) { // e.g. '20090712'
285a6bda 1642 // TODO(danvk): remove support for this format. It's confusing.
6a1aa64f
DV
1643 dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2)
1644 + "/" + dateStr.substr(6,2);
285a6bda 1645 d = Date.parse(dateStrSlashed);
2769de62
DV
1646 } else {
1647 // Any format that Date.parse will accept, e.g. "2009/07/12" or
1648 // "2009/07/12 12:34:56"
285a6bda
DV
1649 d = Date.parse(dateStr);
1650 }
1651
1652 if (!d || isNaN(d)) {
1653 self.error("Couldn't parse " + dateStr + " as a date");
1654 }
1655 return d;
1656};
1657
1658/**
1659 * Detects the type of the str (date or numeric) and sets the various
1660 * formatting attributes in this.attrs_ based on this type.
1661 * @param {String} str An x value.
1662 * @private
1663 */
1664Dygraph.prototype.detectTypeFromString_ = function(str) {
1665 var isDate = false;
1666 if (str.indexOf('-') >= 0 ||
1667 str.indexOf('/') >= 0 ||
1668 isNaN(parseFloat(str))) {
1669 isDate = true;
1670 } else if (str.length == 8 && str > '19700101' && str < '20371231') {
1671 // TODO(danvk): remove support for this format.
1672 isDate = true;
1673 }
1674
1675 if (isDate) {
1676 this.attrs_.xValueFormatter = Dygraph.dateString_;
1677 this.attrs_.xValueParser = Dygraph.dateParser;
1678 this.attrs_.xTicker = Dygraph.dateTicker;
1679 } else {
1680 this.attrs_.xValueFormatter = function(x) { return x; };
1681 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
1682 this.attrs_.xTicker = Dygraph.numericTicks;
6a1aa64f 1683 }
6a1aa64f
DV
1684};
1685
1686/**
1687 * Parses a string in a special csv format. We expect a csv file where each
1688 * line is a date point, and the first field in each line is the date string.
1689 * We also expect that all remaining fields represent series.
285a6bda 1690 * if the errorBars attribute is set, then interpret the fields as:
6a1aa64f
DV
1691 * date, series1, stddev1, series2, stddev2, ...
1692 * @param {Array.<Object>} data See above.
1693 * @private
285a6bda
DV
1694 *
1695 * @return Array.<Object> An array with one entry for each row. These entries
1696 * are an array of cells in that row. The first entry is the parsed x-value for
1697 * the row. The second, third, etc. are the y-values. These can take on one of
1698 * three forms, depending on the CSV and constructor parameters:
1699 * 1. numeric value
1700 * 2. [ value, stddev ]
1701 * 3. [ low value, center value, high value ]
6a1aa64f 1702 */
285a6bda 1703Dygraph.prototype.parseCSV_ = function(data) {
6a1aa64f
DV
1704 var ret = [];
1705 var lines = data.split("\n");
3d67f03b
DV
1706
1707 // Use the default delimiter or fall back to a tab if that makes sense.
1708 var delim = this.attr_('delimiter');
1709 if (lines[0].indexOf(delim) == -1 && lines[0].indexOf('\t') >= 0) {
1710 delim = '\t';
1711 }
1712
285a6bda 1713 var start = 0;
6a1aa64f 1714 if (this.labelsFromCSV_) {
285a6bda 1715 start = 1;
3d67f03b 1716 this.attrs_.labels = lines[0].split(delim);
6a1aa64f
DV
1717 }
1718
285a6bda
DV
1719 var xParser;
1720 var defaultParserSet = false; // attempt to auto-detect x value type
1721 var expectedCols = this.attr_("labels").length;
987840a2 1722 var outOfOrder = false;
6a1aa64f
DV
1723 for (var i = start; i < lines.length; i++) {
1724 var line = lines[i];
1725 if (line.length == 0) continue; // skip blank lines
3d67f03b
DV
1726 if (line[0] == '#') continue; // skip comment lines
1727 var inFields = line.split(delim);
285a6bda 1728 if (inFields.length < 2) continue;
6a1aa64f
DV
1729
1730 var fields = [];
285a6bda
DV
1731 if (!defaultParserSet) {
1732 this.detectTypeFromString_(inFields[0]);
1733 xParser = this.attr_("xValueParser");
1734 defaultParserSet = true;
1735 }
1736 fields[0] = xParser(inFields[0], this);
6a1aa64f
DV
1737
1738 // If fractions are expected, parse the numbers as "A/B"
1739 if (this.fractions_) {
1740 for (var j = 1; j < inFields.length; j++) {
1741 // TODO(danvk): figure out an appropriate way to flag parse errors.
1742 var vals = inFields[j].split("/");
1743 fields[j] = [parseFloat(vals[0]), parseFloat(vals[1])];
1744 }
285a6bda 1745 } else if (this.attr_("errorBars")) {
6a1aa64f
DV
1746 // If there are error bars, values are (value, stddev) pairs
1747 for (var j = 1; j < inFields.length; j += 2)
1748 fields[(j + 1) / 2] = [parseFloat(inFields[j]),
1749 parseFloat(inFields[j + 1])];
9922b78b 1750 } else if (this.attr_("customBars")) {
6a1aa64f
DV
1751 // Bars are a low;center;high tuple
1752 for (var j = 1; j < inFields.length; j++) {
1753 var vals = inFields[j].split(";");
1754 fields[j] = [ parseFloat(vals[0]),
1755 parseFloat(vals[1]),
1756 parseFloat(vals[2]) ];
1757 }
1758 } else {
1759 // Values are just numbers
285a6bda 1760 for (var j = 1; j < inFields.length; j++) {
6a1aa64f 1761 fields[j] = parseFloat(inFields[j]);
285a6bda 1762 }
6a1aa64f 1763 }
987840a2
DV
1764 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
1765 outOfOrder = true;
1766 }
6a1aa64f 1767 ret.push(fields);
285a6bda
DV
1768
1769 if (fields.length != expectedCols) {
1770 this.error("Number of columns in line " + i + " (" + fields.length +
1771 ") does not agree with number of labels (" + expectedCols +
1772 ") " + line);
1773 }
6a1aa64f 1774 }
987840a2
DV
1775
1776 if (outOfOrder) {
1777 this.warn("CSV is out of order; order it correctly to speed loading.");
1778 ret.sort(function(a,b) { return a[0] - b[0] });
1779 }
1780
6a1aa64f
DV
1781 return ret;
1782};
1783
1784/**
285a6bda
DV
1785 * The user has provided their data as a pre-packaged JS array. If the x values
1786 * are numeric, this is the same as dygraphs' internal format. If the x values
1787 * are dates, we need to convert them from Date objects to ms since epoch.
1788 * @param {Array.<Object>} data
1789 * @return {Array.<Object>} data with numeric x values.
1790 */
1791Dygraph.prototype.parseArray_ = function(data) {
1792 // Peek at the first x value to see if it's numeric.
1793 if (data.length == 0) {
1794 this.error("Can't plot empty data set");
1795 return null;
1796 }
1797 if (data[0].length == 0) {
1798 this.error("Data set cannot contain an empty row");
1799 return null;
1800 }
1801
1802 if (this.attr_("labels") == null) {
1803 this.warn("Using default labels. Set labels explicitly via 'labels' " +
1804 "in the options parameter");
1805 this.attrs_.labels = [ "X" ];
1806 for (var i = 1; i < data[0].length; i++) {
1807 this.attrs_.labels.push("Y" + i);
1808 }
1809 }
1810
2dda3850 1811 if (Dygraph.isDateLike(data[0][0])) {
285a6bda
DV
1812 // Some intelligent defaults for a date x-axis.
1813 this.attrs_.xValueFormatter = Dygraph.dateString_;
1814 this.attrs_.xTicker = Dygraph.dateTicker;
1815
1816 // Assume they're all dates.
e3ab7b40 1817 var parsedData = Dygraph.clone(data);
285a6bda
DV
1818 for (var i = 0; i < data.length; i++) {
1819 if (parsedData[i].length == 0) {
1820 this.error("Row " << (1 + i) << " of data is empty");
1821 return null;
1822 }
1823 if (parsedData[i][0] == null
3a909ec5
DV
1824 || typeof(parsedData[i][0].getTime) != 'function'
1825 || isNaN(parsedData[i][0].getTime())) {
be96a1f5 1826 this.error("x value in row " + (1 + i) + " is not a Date");
285a6bda
DV
1827 return null;
1828 }
1829 parsedData[i][0] = parsedData[i][0].getTime();
1830 }
1831 return parsedData;
1832 } else {
1833 // Some intelligent defaults for a numeric x-axis.
1834 this.attrs_.xValueFormatter = function(x) { return x; };
1835 this.attrs_.xTicker = Dygraph.numericTicks;
1836 return data;
1837 }
1838};
1839
1840/**
79420a1e
DV
1841 * Parses a DataTable object from gviz.
1842 * The data is expected to have a first column that is either a date or a
1843 * number. All subsequent columns must be numbers. If there is a clear mismatch
1844 * between this.xValueParser_ and the type of the first column, it will be
1845 * fixed. Returned value is in the same format as return value of parseCSV_.
1846 * @param {Array.<Object>} data See above.
1847 * @private
1848 */
285a6bda 1849Dygraph.prototype.parseDataTable_ = function(data) {
79420a1e
DV
1850 var cols = data.getNumberOfColumns();
1851 var rows = data.getNumberOfRows();
1852
1853 // Read column labels
1854 var labels = [];
1855 for (var i = 0; i < cols; i++) {
1856 labels.push(data.getColumnLabel(i));
3e3f84e4 1857 if (i != 0 && this.attr_("errorBars")) i += 1;
79420a1e 1858 }
285a6bda 1859 this.attrs_.labels = labels;
3e3f84e4 1860 cols = labels.length;
79420a1e 1861
d955e223 1862 var indepType = data.getColumnType(0);
4440f6c8 1863 if (indepType == 'date' || indepType == 'datetime') {
285a6bda
DV
1864 this.attrs_.xValueFormatter = Dygraph.dateString_;
1865 this.attrs_.xValueParser = Dygraph.dateParser;
1866 this.attrs_.xTicker = Dygraph.dateTicker;
33127159 1867 } else if (indepType == 'number') {
285a6bda
DV
1868 this.attrs_.xValueFormatter = function(x) { return x; };
1869 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
1870 this.attrs_.xTicker = Dygraph.numericTicks;
1871 } else {
987840a2
DV
1872 this.error("only 'date', 'datetime' and 'number' types are supported for " +
1873 "column 1 of DataTable input (Got '" + indepType + "')");
79420a1e
DV
1874 return null;
1875 }
1876
1877 var ret = [];
987840a2 1878 var outOfOrder = false;
79420a1e
DV
1879 for (var i = 0; i < rows; i++) {
1880 var row = [];
debe4434
DV
1881 if (typeof(data.getValue(i, 0)) === 'undefined' ||
1882 data.getValue(i, 0) === null) {
1883 this.warning("Ignoring row " + i +
1884 " of DataTable because of undefined or null first column.");
1885 continue;
1886 }
1887
c21d2c2d 1888 if (indepType == 'date' || indepType == 'datetime') {
d955e223
DV
1889 row.push(data.getValue(i, 0).getTime());
1890 } else {
1891 row.push(data.getValue(i, 0));
1892 }
3e3f84e4
DV
1893 if (!this.attr_("errorBars")) {
1894 for (var j = 1; j < cols; j++) {
1895 row.push(data.getValue(i, j));
1896 }
1897 } else {
1898 for (var j = 0; j < cols - 1; j++) {
1899 row.push([ data.getValue(i, 1 + 2 * j), data.getValue(i, 2 + 2 * j) ]);
1900 }
79420a1e 1901 }
987840a2
DV
1902 if (ret.length > 0 && row[0] < ret[ret.length - 1][0]) {
1903 outOfOrder = true;
1904 }
243d96e8 1905 ret.push(row);
79420a1e 1906 }
987840a2
DV
1907
1908 if (outOfOrder) {
1909 this.warn("DataTable is out of order; order it correctly to speed loading.");
1910 ret.sort(function(a,b) { return a[0] - b[0] });
1911 }
79420a1e
DV
1912 return ret;
1913}
1914
24e5350c 1915// These functions are all based on MochiKit.
fc80a396
DV
1916Dygraph.update = function (self, o) {
1917 if (typeof(o) != 'undefined' && o !== null) {
1918 for (var k in o) {
85b99f0b
DV
1919 if (o.hasOwnProperty(k)) {
1920 self[k] = o[k];
1921 }
fc80a396
DV
1922 }
1923 }
1924 return self;
1925};
1926
2dda3850
DV
1927Dygraph.isArrayLike = function (o) {
1928 var typ = typeof(o);
1929 if (
c21d2c2d 1930 (typ != 'object' && !(typ == 'function' &&
2dda3850
DV
1931 typeof(o.item) == 'function')) ||
1932 o === null ||
1933 typeof(o.length) != 'number' ||
1934 o.nodeType === 3
1935 ) {
1936 return false;
1937 }
1938 return true;
1939};
1940
1941Dygraph.isDateLike = function (o) {
1942 if (typeof(o) != "object" || o === null ||
1943 typeof(o.getTime) != 'function') {
1944 return false;
1945 }
1946 return true;
1947};
1948
e3ab7b40
DV
1949Dygraph.clone = function(o) {
1950 // TODO(danvk): figure out how MochiKit's version works
1951 var r = [];
1952 for (var i = 0; i < o.length; i++) {
1953 if (Dygraph.isArrayLike(o[i])) {
1954 r.push(Dygraph.clone(o[i]));
1955 } else {
1956 r.push(o[i]);
1957 }
1958 }
1959 return r;
24e5350c
DV
1960};
1961
2dda3850 1962
79420a1e 1963/**
6a1aa64f
DV
1964 * Get the CSV data. If it's in a function, call that function. If it's in a
1965 * file, do an XMLHttpRequest to get it.
1966 * @private
1967 */
285a6bda 1968Dygraph.prototype.start_ = function() {
6a1aa64f 1969 if (typeof this.file_ == 'function') {
285a6bda 1970 // CSV string. Pretend we got it via XHR.
6a1aa64f 1971 this.loadedEvent_(this.file_());
2dda3850 1972 } else if (Dygraph.isArrayLike(this.file_)) {
285a6bda
DV
1973 this.rawData_ = this.parseArray_(this.file_);
1974 this.drawGraph_(this.rawData_);
79420a1e
DV
1975 } else if (typeof this.file_ == 'object' &&
1976 typeof this.file_.getColumnRange == 'function') {
1977 // must be a DataTable from gviz.
1978 this.rawData_ = this.parseDataTable_(this.file_);
1979 this.drawGraph_(this.rawData_);
285a6bda
DV
1980 } else if (typeof this.file_ == 'string') {
1981 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
1982 if (this.file_.indexOf('\n') >= 0) {
1983 this.loadedEvent_(this.file_);
1984 } else {
1985 var req = new XMLHttpRequest();
1986 var caller = this;
1987 req.onreadystatechange = function () {
1988 if (req.readyState == 4) {
1989 if (req.status == 200) {
1990 caller.loadedEvent_(req.responseText);
1991 }
6a1aa64f 1992 }
285a6bda 1993 };
6a1aa64f 1994
285a6bda
DV
1995 req.open("GET", this.file_, true);
1996 req.send(null);
1997 }
1998 } else {
1999 this.error("Unknown data format: " + (typeof this.file_));
6a1aa64f
DV
2000 }
2001};
2002
2003/**
2004 * Changes various properties of the graph. These can include:
2005 * <ul>
2006 * <li>file: changes the source data for the graph</li>
2007 * <li>errorBars: changes whether the data contains stddev</li>
2008 * </ul>
2009 * @param {Object} attrs The new properties and values
2010 */
285a6bda
DV
2011Dygraph.prototype.updateOptions = function(attrs) {
2012 // TODO(danvk): this is a mess. Rethink this function.
6a1aa64f
DV
2013 if (attrs.rollPeriod) {
2014 this.rollPeriod_ = attrs.rollPeriod;
2015 }
2016 if (attrs.dateWindow) {
2017 this.dateWindow_ = attrs.dateWindow;
2018 }
2019 if (attrs.valueRange) {
2020 this.valueRange_ = attrs.valueRange;
2021 }
fc80a396 2022 Dygraph.update(this.user_attrs_, attrs);
285a6bda
DV
2023
2024 this.labelsFromCSV_ = (this.attr_("labels") == null);
2025
2026 // TODO(danvk): this doesn't match the constructor logic
2027 this.layout_.updateOptions({ 'errorBars': this.attr_("errorBars") });
6a1aa64f
DV
2028 if (attrs['file'] && attrs['file'] != this.file_) {
2029 this.file_ = attrs['file'];
2030 this.start_();
2031 } else {
2032 this.drawGraph_(this.rawData_);
2033 }
2034};
2035
2036/**
697e70b2
DV
2037 * Resizes the dygraph. If no parameters are specified, resizes to fill the
2038 * containing div (which has presumably changed size since the dygraph was
2039 * instantiated. If the width/height are specified, the div will be resized.
964f30c6
DV
2040 *
2041 * This is far more efficient than destroying and re-instantiating a
2042 * Dygraph, since it doesn't have to reparse the underlying data.
2043 *
697e70b2
DV
2044 * @param {Number} width Width (in pixels)
2045 * @param {Number} height Height (in pixels)
2046 */
2047Dygraph.prototype.resize = function(width, height) {
2048 if ((width === null) != (height === null)) {
2049 this.warn("Dygraph.resize() should be called with zero parameters or " +
2050 "two non-NULL parameters. Pretending it was zero.");
2051 width = height = null;
2052 }
2053
b16e6369 2054 // TODO(danvk): there should be a clear() method.
697e70b2 2055 this.maindiv_.innerHTML = "";
b16e6369
DV
2056 this.attrs_.labelsDiv = null;
2057
697e70b2
DV
2058 if (width) {
2059 this.maindiv_.style.width = width + "px";
2060 this.maindiv_.style.height = height + "px";
2061 this.width_ = width;
2062 this.height_ = height;
2063 } else {
2064 this.width_ = this.maindiv_.offsetWidth;
2065 this.height_ = this.maindiv_.offsetHeight;
2066 }
2067
2068 this.createInterface_();
964f30c6 2069 this.drawGraph_(this.rawData_);
697e70b2
DV
2070};
2071
2072/**
6a1aa64f
DV
2073 * Adjusts the number of days in the rolling average. Updates the graph to
2074 * reflect the new averaging period.
2075 * @param {Number} length Number of days over which to average the data.
2076 */
285a6bda 2077Dygraph.prototype.adjustRoll = function(length) {
6a1aa64f
DV
2078 this.rollPeriod_ = length;
2079 this.drawGraph_(this.rawData_);
2080};
540d00f1 2081
f8cfec73 2082/**
1cf11047
DV
2083 * Returns a boolean array of visibility statuses.
2084 */
2085Dygraph.prototype.visibility = function() {
2086 // Do lazy-initialization, so that this happens after we know the number of
2087 // data series.
2088 if (!this.attr_("visibility")) {
f38dec01 2089 this.attrs_["visibility"] = [];
1cf11047
DV
2090 }
2091 while (this.attr_("visibility").length < this.rawData_[0].length - 1) {
f38dec01 2092 this.attr_("visibility").push(true);
1cf11047
DV
2093 }
2094 return this.attr_("visibility");
2095};
2096
2097/**
2098 * Changes the visiblity of a series.
2099 */
2100Dygraph.prototype.setVisibility = function(num, value) {
2101 var x = this.visibility();
2102 if (num < 0 && num >= x.length) {
2103 this.warn("invalid series number in setVisibility: " + num);
2104 } else {
2105 x[num] = value;
2106 this.drawGraph_(this.rawData_);
2107 }
2108};
2109
2110/**
f8cfec73
DV
2111 * Create a new canvas element. This is more complex than a simple
2112 * document.createElement("canvas") because of IE and excanvas.
2113 */
2114Dygraph.createCanvas = function() {
2115 var canvas = document.createElement("canvas");
2116
2117 isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
2118 if (isIE) {
2119 canvas = G_vmlCanvasManager.initElement(canvas);
2120 }
2121
2122 return canvas;
2123};
2124
540d00f1
DV
2125
2126/**
285a6bda 2127 * A wrapper around Dygraph that implements the gviz API.
540d00f1
DV
2128 * @param {Object} container The DOM object the visualization should live in.
2129 */
285a6bda 2130Dygraph.GVizChart = function(container) {
540d00f1
DV
2131 this.container = container;
2132}
2133
285a6bda 2134Dygraph.GVizChart.prototype.draw = function(data, options) {
540d00f1 2135 this.container.innerHTML = '';
285a6bda 2136 this.date_graph = new Dygraph(this.container, data, options);
540d00f1 2137}
285a6bda
DV
2138
2139// Older pages may still use this name.
2140DateGraph = Dygraph;