Initial implementation
[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
285a6bda 27 Date,SeriesA,SeriesB,...
6a1aa64f
DV
28 YYYYMMDD,A1,sigmaA1,B1,sigmaB1,...
29 YYYYMMDD,A2,sigmaA2,B2,sigmaB2,...
30
31 If the 'fractions' option is set, the input should be of the form:
32
285a6bda 33 Date,SeriesA,SeriesB,...
6a1aa64f
DV
34 YYYYMMDD,A1/B1,A2/B2,...
35 YYYYMMDD,A1/B1,A2/B2,...
36
37 And error bars will be calculated automatically using a binomial distribution.
38
727439b4 39 For further documentation and examples, see http://dygraphs.com/
6a1aa64f
DV
40
41 */
42
43/**
44 * An interactive, zoomable graph
45 * @param {String | Function} file A file containing CSV data or a function that
46 * returns this data. The expected format for each line is
47 * YYYYMMDD,val1,val2,... or, if attrs.errorBars is set,
48 * YYYYMMDD,val1,stddev1,val2,stddev2,...
6a1aa64f
DV
49 * @param {Object} attrs Various other attributes, e.g. errorBars determines
50 * whether the input data contains error ranges.
51 */
285a6bda
DV
52Dygraph = function(div, data, opts) {
53 if (arguments.length > 0) {
54 if (arguments.length == 4) {
55 // Old versions of dygraphs took in the series labels as a constructor
56 // parameter. This doesn't make sense anymore, but it's easy to continue
57 // to support this usage.
58 this.warn("Using deprecated four-argument dygraph constructor");
59 this.__old_init__(div, data, arguments[2], arguments[3]);
60 } else {
61 this.__init__(div, data, opts);
62 }
63 }
6a1aa64f
DV
64};
65
285a6bda
DV
66Dygraph.NAME = "Dygraph";
67Dygraph.VERSION = "1.2";
68Dygraph.__repr__ = function() {
6a1aa64f
DV
69 return "[" + this.NAME + " " + this.VERSION + "]";
70};
285a6bda 71Dygraph.toString = function() {
6a1aa64f
DV
72 return this.__repr__();
73};
74
15b00ba8 75/**
7201b11e
JB
76 * Formatting to use for an integer number.
77 *
78 * @param {Number} x The number to format
79 * @param {Number} unused_precision The precision to use, ignored.
80 * @return {String} A string formatted like %g in printf. The max generated
81 * string length should be precision + 6 (e.g 1.123e+300).
82 */
83Dygraph.intFormat = function(x, unused_precision) {
84 return x.toString();
85}
86
87/**
15b00ba8
JB
88 * Number formatting function which mimicks the behavior of %g in printf, i.e.
89 * either exponential or fixed format (without trailing 0s) is used depending on
90 * the length of the generated string. The advantage of this format is that
062ef401
JB
91 * there is a predictable upper bound on the resulting string length,
92 * significant figures are not dropped, and normal numbers are not displayed in
93 * exponential notation.
15b00ba8
JB
94 *
95 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
96 * It creates strings which are too long for absolute values between 10^-4 and
062ef401 97 * 10^-6. See tests/number-format.html for output examples.
15b00ba8
JB
98 *
99 * @param {Number} x The number to format
100 * @param {Number} opt_precision The precision to use, default 2.
101 * @return {String} A string formatted like %g in printf. The max generated
062ef401 102 * string length should be precision + 6 (e.g 1.123e+300).
15b00ba8 103 */
7201b11e 104Dygraph.floatFormat = function(x, opt_precision) {
15b00ba8
JB
105 // Avoid invalid precision values; [1, 21] is the valid range.
106 var p = Math.min(Math.max(1, opt_precision || 2), 21);
107
108 // This is deceptively simple. The actual algorithm comes from:
109 //
110 // Max allowed length = p + 4
111 // where 4 comes from 'e+n' and '.'.
112 //
113 // Length of fixed format = 2 + y + p
114 // where 2 comes from '0.' and y = # of leading zeroes.
115 //
116 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
117 // 1.0e-3.
118 //
119 // Since the behavior of toPrecision() is identical for larger numbers, we
120 // don't have to worry about the other bound.
121 //
122 // Finally, the argument for toExponential() is the number of trailing digits,
123 // so we take off 1 for the value before the '.'.
124 return (Math.abs(x) < 1.0e-3 && x != 0.0) ?
125 x.toExponential(p - 1) : x.toPrecision(p);
126};
127
6a1aa64f 128// Various default values
285a6bda
DV
129Dygraph.DEFAULT_ROLL_PERIOD = 1;
130Dygraph.DEFAULT_WIDTH = 480;
131Dygraph.DEFAULT_HEIGHT = 320;
132Dygraph.AXIS_LINE_WIDTH = 0.3;
6a1aa64f 133
d59b6f34 134Dygraph.LOG_SCALE = 10;
0037b2a4 135Dygraph.LN_TEN = Math.log(Dygraph.LOG_SCALE);
d59b6f34 136Dygraph.log10 = function(x) {
0037b2a4 137 return Math.log(x) / Dygraph.LN_TEN;
d59b6f34 138}
062ef401 139
8e4a6af3 140// Default attribute values.
285a6bda 141Dygraph.DEFAULT_ATTRS = {
a9fc39ab 142 highlightCircleSize: 3,
8e4a6af3 143 pixelsPerXLabel: 60,
c6336f04 144 pixelsPerYLabel: 30,
285a6bda 145
8e4a6af3
DV
146 labelsDivWidth: 250,
147 labelsDivStyles: {
148 // TODO(danvk): move defaults from createStatusMessage_ here.
285a6bda
DV
149 },
150 labelsSeparateLines: false,
bcd3ebf0 151 labelsShowZeroValues: true,
285a6bda 152 labelsKMB: false,
afefbcdb 153 labelsKMG2: false,
d160cc3b 154 showLabelsOnHighlight: true,
12e4c741 155
4cb5e2d2
JB
156 yValueFormatter: function(x, opt_precision) {
157 var s = Dygraph.floatFormat(x, opt_precision);
158 var s2 = Dygraph.intFormat(x);
d916677a 159 return s.length < s2.length ? s : s2;
4cb5e2d2 160 },
285a6bda
DV
161
162 strokeWidth: 1.0,
8e4a6af3 163
8846615a
DV
164 axisTickSize: 3,
165 axisLabelFontSize: 14,
166 xAxisLabelWidth: 50,
167 yAxisLabelWidth: 50,
bf640e56 168 xAxisLabelFormatter: Dygraph.dateAxisFormatter,
8846615a 169 rightGap: 5,
285a6bda
DV
170
171 showRoller: false,
172 xValueFormatter: Dygraph.dateString_,
173 xValueParser: Dygraph.dateParser,
174 xTicker: Dygraph.dateTicker,
175
3d67f03b
DV
176 delimiter: ',',
177
285a6bda
DV
178 sigma: 2.0,
179 errorBars: false,
180 fractions: false,
181 wilsonInterval: true, // only relevant if fractions is true
5954ef32 182 customBars: false,
43af96e7
NK
183 fillGraph: false,
184 fillAlpha: 0.15,
f032c51d 185 connectSeparatedPoints: false,
43af96e7
NK
186
187 stackedGraph: false,
afdc483f
NN
188 hideOverlayOnMouseOut: true,
189
2fccd3dc
DV
190 // TODO(danvk): support 'onmouseover' and 'never', and remove synonyms.
191 legend: 'onmouseover', // the only relevant value at the moment is 'always'.
192
00c281d4 193 stepPlot: false,
062ef401
JB
194 avoidMinZero: false,
195
ad1798c2
DV
196 // Sizes of the various chart labels.
197 titleHeight: 16,
198 xLabelHeight: 16,
199 yLabelWidth: 16,
200
062ef401 201 interactionModel: null // will be set to Dygraph.defaultInteractionModel.
285a6bda
DV
202};
203
204// Various logging levels.
205Dygraph.DEBUG = 1;
206Dygraph.INFO = 2;
207Dygraph.WARNING = 3;
208Dygraph.ERROR = 3;
209
39b0e098
RK
210// Directions for panning and zooming. Use bit operations when combined
211// values are possible.
212Dygraph.HORIZONTAL = 1;
213Dygraph.VERTICAL = 2;
214
5c528fa2
DV
215// Used for initializing annotation CSS rules only once.
216Dygraph.addedAnnotationCSS = false;
217
285a6bda
DV
218Dygraph.prototype.__old_init__ = function(div, file, labels, attrs) {
219 // Labels is no longer a constructor parameter, since it's typically set
220 // directly from the data source. It also conains a name for the x-axis,
221 // which the previous constructor form did not.
222 if (labels != null) {
223 var new_labels = ["Date"];
224 for (var i = 0; i < labels.length; i++) new_labels.push(labels[i]);
fc80a396 225 Dygraph.update(attrs, { 'labels': new_labels });
285a6bda
DV
226 }
227 this.__init__(div, file, attrs);
8e4a6af3
DV
228};
229
6a1aa64f 230/**
285a6bda 231 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
7aedf6fe 232 * and context &lt;canvas&gt; inside of it. See the constructor for details.
6a1aa64f 233 * on the parameters.
12e4c741 234 * @param {Element} div the Element to render the graph into.
6a1aa64f 235 * @param {String | Function} file Source data
6a1aa64f
DV
236 * @param {Object} attrs Miscellaneous other options
237 * @private
238 */
285a6bda 239Dygraph.prototype.__init__ = function(div, file, attrs) {
a2c8fff4
DV
240 // Hack for IE: if we're using excanvas and the document hasn't finished
241 // loading yet (and hence may not have initialized whatever it needs to
242 // initialize), then keep calling this routine periodically until it has.
243 if (/MSIE/.test(navigator.userAgent) && !window.opera &&
244 typeof(G_vmlCanvasManager) != 'undefined' &&
245 document.readyState != 'complete') {
246 var self = this;
247 setTimeout(function() { self.__init__(div, file, attrs) }, 100);
248 }
249
285a6bda
DV
250 // Support two-argument constructor
251 if (attrs == null) { attrs = {}; }
252
6a1aa64f 253 // Copy the important bits into the object
32988383 254 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
6a1aa64f 255 this.maindiv_ = div;
6a1aa64f 256 this.file_ = file;
285a6bda 257 this.rollPeriod_ = attrs.rollPeriod || Dygraph.DEFAULT_ROLL_PERIOD;
6a1aa64f 258 this.previousVerticalX_ = -1;
6a1aa64f 259 this.fractions_ = attrs.fractions || false;
6a1aa64f 260 this.dateWindow_ = attrs.dateWindow || null;
8b83c6cc 261
6a1aa64f 262 this.wilsonInterval_ = attrs.wilsonInterval || true;
fe0b7c03 263 this.is_initial_draw_ = true;
5c528fa2 264 this.annotations_ = [];
7aedf6fe 265
6be8e54c
JB
266 // Number of digits to use when labeling the x (if numeric) and y axis
267 // ticks.
268 this.numXDigits_ = 2;
269 this.numYDigits_ = 2;
270
271 // When labeling x (if numeric) or y values in the legend, there are
272 // numDigits + numExtraDigits of precision used. For axes labels with N
273 // digits of precision, the data should be displayed with at least N+1 digits
274 // of precision. The reason for this is to divide each interval between
275 // successive ticks into tenths (for 1) or hundredths (for 2), etc. For
276 // example, if the labels are [0, 1, 2], we want data to be displayed as
277 // 0.1, 1.3, etc.
278 this.numExtraDigits_ = 1;
8e4a6af3 279
f7d6278e
DV
280 // Clear the div. This ensure that, if multiple dygraphs are passed the same
281 // div, then only one will be drawn.
282 div.innerHTML = "";
283
c21d2c2d 284 // If the div isn't already sized then inherit from our attrs or
285 // give it a default size.
285a6bda 286 if (div.style.width == '') {
ddd1b11f 287 div.style.width = (attrs.width || Dygraph.DEFAULT_WIDTH) + "px";
285a6bda
DV
288 }
289 if (div.style.height == '') {
ddd1b11f 290 div.style.height = (attrs.height || Dygraph.DEFAULT_HEIGHT) + "px";
32988383 291 }
285a6bda
DV
292 this.width_ = parseInt(div.style.width, 10);
293 this.height_ = parseInt(div.style.height, 10);
c21d2c2d 294 // The div might have been specified as percent of the current window size,
295 // convert that to an appropriate number of pixels.
296 if (div.style.width.indexOf("%") == div.style.width.length - 1) {
c6f45033 297 this.width_ = div.offsetWidth;
c21d2c2d 298 }
299 if (div.style.height.indexOf("%") == div.style.height.length - 1) {
c6f45033 300 this.height_ = div.offsetHeight;
c21d2c2d 301 }
32988383 302
10a6456d
DV
303 if (this.width_ == 0) {
304 this.error("dygraph has zero width. Please specify a width in pixels.");
305 }
306 if (this.height_ == 0) {
307 this.error("dygraph has zero height. Please specify a height in pixels.");
308 }
309
344ba8c0 310 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
43af96e7
NK
311 if (attrs['stackedGraph']) {
312 attrs['fillGraph'] = true;
313 // TODO(nikhilk): Add any other stackedGraph checks here.
314 }
315
285a6bda
DV
316 // Dygraphs has many options, some of which interact with one another.
317 // To keep track of everything, we maintain two sets of options:
318 //
c21d2c2d 319 // this.user_attrs_ only options explicitly set by the user.
285a6bda
DV
320 // this.attrs_ defaults, options derived from user_attrs_, data.
321 //
322 // Options are then accessed this.attr_('attr'), which first looks at
323 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
324 // defaults without overriding behavior that the user specifically asks for.
325 this.user_attrs_ = {};
fc80a396 326 Dygraph.update(this.user_attrs_, attrs);
6a1aa64f 327
285a6bda 328 this.attrs_ = {};
fc80a396 329 Dygraph.update(this.attrs_, Dygraph.DEFAULT_ATTRS);
6a1aa64f 330
16269f6e 331 this.boundaryIds_ = [];
6a1aa64f 332
285a6bda
DV
333 // Make a note of whether labels will be pulled from the CSV file.
334 this.labelsFromCSV_ = (this.attr_("labels") == null);
6a1aa64f
DV
335
336 // Create the containing DIV and other interactive elements
337 this.createInterface_();
338
738fc797 339 this.start_();
6a1aa64f
DV
340};
341
22bd1dfb
RK
342Dygraph.prototype.toString = function() {
343 var maindiv = this.maindiv_;
344 var id = (maindiv && maindiv.id) ? maindiv.id : maindiv
345 return "[Dygraph " + id + "]";
346}
347
227b93cc 348Dygraph.prototype.attr_ = function(name, seriesName) {
028ddf8a
DV
349// <REMOVE_FOR_COMBINED>
350 if (typeof(Dygraph.OPTIONS_REFERENCE) === 'undefined') {
351 this.error('Must include options reference JS for testing');
352 } else if (!Dygraph.OPTIONS_REFERENCE.hasOwnProperty(name)) {
353 this.error('Dygraphs is using property ' + name + ', which has no entry ' +
354 'in the Dygraphs.OPTIONS_REFERENCE listing.');
355 // Only log this error once.
356 Dygraph.OPTIONS_REFERENCE[name] = true;
357 }
358// </REMOVE_FOR_COMBINED>
227b93cc
DV
359 if (seriesName &&
360 typeof(this.user_attrs_[seriesName]) != 'undefined' &&
361 this.user_attrs_[seriesName] != null &&
362 typeof(this.user_attrs_[seriesName][name]) != 'undefined') {
363 return this.user_attrs_[seriesName][name];
450fe64b 364 } else if (typeof(this.user_attrs_[name]) != 'undefined') {
285a6bda
DV
365 return this.user_attrs_[name];
366 } else if (typeof(this.attrs_[name]) != 'undefined') {
367 return this.attrs_[name];
368 } else {
369 return null;
370 }
371};
372
373// TODO(danvk): any way I can get the line numbers to be this.warn call?
374Dygraph.prototype.log = function(severity, message) {
375 if (typeof(console) != 'undefined') {
376 switch (severity) {
377 case Dygraph.DEBUG:
378 console.debug('dygraphs: ' + message);
379 break;
380 case Dygraph.INFO:
381 console.info('dygraphs: ' + message);
382 break;
383 case Dygraph.WARNING:
384 console.warn('dygraphs: ' + message);
385 break;
386 case Dygraph.ERROR:
387 console.error('dygraphs: ' + message);
388 break;
389 }
390 }
391}
392Dygraph.prototype.info = function(message) {
393 this.log(Dygraph.INFO, message);
394}
395Dygraph.prototype.warn = function(message) {
396 this.log(Dygraph.WARNING, message);
397}
398Dygraph.prototype.error = function(message) {
399 this.log(Dygraph.ERROR, message);
400}
401
6a1aa64f
DV
402/**
403 * Returns the current rolling period, as set by the user or an option.
6faebb69 404 * @return {Number} The number of points in the rolling window
6a1aa64f 405 */
285a6bda 406Dygraph.prototype.rollPeriod = function() {
6a1aa64f 407 return this.rollPeriod_;
76171648
DV
408};
409
599fb4ad
DV
410/**
411 * Returns the currently-visible x-range. This can be affected by zooming,
412 * panning or a call to updateOptions.
413 * Returns a two-element array: [left, right].
414 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
415 */
416Dygraph.prototype.xAxisRange = function() {
417 if (this.dateWindow_) return this.dateWindow_;
418
419 // The entire chart is visible.
420 var left = this.rawData_[0][0];
421 var right = this.rawData_[this.rawData_.length - 1][0];
422 return [left, right];
423};
424
3230c662 425/**
d58ae307
DV
426 * Returns the currently-visible y-range for an axis. This can be affected by
427 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
428 * called with no arguments, returns the range of the first axis.
3230c662
DV
429 * Returns a two-element array: [bottom, top].
430 */
d58ae307 431Dygraph.prototype.yAxisRange = function(idx) {
d63e6799 432 if (typeof(idx) == "undefined") idx = 0;
d58ae307
DV
433 if (idx < 0 || idx >= this.axes_.length) return null;
434 return [ this.axes_[idx].computedValueRange[0],
435 this.axes_[idx].computedValueRange[1] ];
436};
437
438/**
439 * Returns the currently-visible y-ranges for each axis. This can be affected by
440 * zooming, panning, calls to updateOptions, etc.
441 * Returns an array of [bottom, top] pairs, one for each y-axis.
442 */
443Dygraph.prototype.yAxisRanges = function() {
444 var ret = [];
445 for (var i = 0; i < this.axes_.length; i++) {
446 ret.push(this.yAxisRange(i));
447 }
448 return ret;
3230c662
DV
449};
450
d58ae307 451// TODO(danvk): use these functions throughout dygraphs.
3230c662
DV
452/**
453 * Convert from data coordinates to canvas/div X/Y coordinates.
d58ae307
DV
454 * If specified, do this conversion for the coordinate system of a particular
455 * axis. Uses the first axis by default.
3230c662 456 * Returns a two-element array: [X, Y]
ff022deb 457 *
0747928a 458 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
ff022deb 459 * instead of toDomCoords(null, y, axis).
3230c662 460 */
d58ae307 461Dygraph.prototype.toDomCoords = function(x, y, axis) {
ff022deb
RK
462 return [ this.toDomXCoord(x), this.toDomYCoord(y, axis) ];
463};
464
465/**
466 * Convert from data x coordinates to canvas/div X coordinate.
467 * If specified, do this conversion for the coordinate system of a particular
0037b2a4
RK
468 * axis.
469 * Returns a single value or null if x is null.
ff022deb
RK
470 */
471Dygraph.prototype.toDomXCoord = function(x) {
472 if (x == null) {
473 return null;
474 };
475
3230c662 476 var area = this.plotter_.area;
ff022deb
RK
477 var xRange = this.xAxisRange();
478 return area.x + (x - xRange[0]) / (xRange[1] - xRange[0]) * area.w;
479}
3230c662 480
ff022deb
RK
481/**
482 * Convert from data x coordinates to canvas/div Y coordinate and optional
483 * axis. Uses the first axis by default.
484 *
485 * returns a single value or null if y is null.
486 */
487Dygraph.prototype.toDomYCoord = function(y, axis) {
0747928a 488 var pct = this.toPercentYCoord(y, axis);
3230c662 489
ff022deb
RK
490 if (pct == null) {
491 return null;
492 }
e4416fb9 493 var area = this.plotter_.area;
ff022deb
RK
494 return area.y + pct * area.h;
495}
3230c662
DV
496
497/**
498 * Convert from canvas/div coords to data coordinates.
d58ae307
DV
499 * If specified, do this conversion for the coordinate system of a particular
500 * axis. Uses the first axis by default.
ff022deb
RK
501 * Returns a two-element array: [X, Y].
502 *
0747928a 503 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
ff022deb 504 * instead of toDataCoords(null, y, axis).
3230c662 505 */
d58ae307 506Dygraph.prototype.toDataCoords = function(x, y, axis) {
ff022deb
RK
507 return [ this.toDataXCoord(x), this.toDataYCoord(y, axis) ];
508};
509
510/**
511 * Convert from canvas/div x coordinate to data coordinate.
512 *
513 * If x is null, this returns null.
514 */
515Dygraph.prototype.toDataXCoord = function(x) {
516 if (x == null) {
517 return null;
3230c662
DV
518 }
519
ff022deb
RK
520 var area = this.plotter_.area;
521 var xRange = this.xAxisRange();
522 return xRange[0] + (x - area.x) / area.w * (xRange[1] - xRange[0]);
523};
524
525/**
526 * Convert from canvas/div y coord to value.
527 *
528 * If y is null, this returns null.
529 * if axis is null, this uses the first axis.
530 */
531Dygraph.prototype.toDataYCoord = function(y, axis) {
532 if (y == null) {
533 return null;
3230c662
DV
534 }
535
ff022deb
RK
536 var area = this.plotter_.area;
537 var yRange = this.yAxisRange(axis);
538
b70247dc
RK
539 if (typeof(axis) == "undefined") axis = 0;
540 if (!this.axes_[axis].logscale) {
ff022deb
RK
541 return yRange[0] + (area.h - y) / area.h * (yRange[1] - yRange[0]);
542 } else {
543 // Computing the inverse of toDomCoord.
544 var pct = (y - area.y) / area.h
545
546 // Computing the inverse of toPercentYCoord. The function was arrived at with
547 // the following steps:
548 //
549 // Original calcuation:
d59b6f34 550 // pct = (logr1 - Dygraph.log10(y)) / (logr1 - Dygraph.log10(yRange[0]));
ff022deb
RK
551 //
552 // Move denominator to both sides:
d59b6f34 553 // pct * (logr1 - Dygraph.log10(yRange[0])) = logr1 - Dygraph.log10(y);
ff022deb
RK
554 //
555 // subtract logr1, and take the negative value.
d59b6f34 556 // logr1 - (pct * (logr1 - Dygraph.log10(yRange[0]))) = Dygraph.log10(y);
ff022deb
RK
557 //
558 // Swap both sides of the equation, and we can compute the log of the
559 // return value. Which means we just need to use that as the exponent in
560 // e^exponent.
d59b6f34 561 // Dygraph.log10(y) = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
ff022deb 562
d59b6f34
RK
563 var logr1 = Dygraph.log10(yRange[1]);
564 var exponent = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
565 var value = Math.pow(Dygraph.LOG_SCALE, exponent);
ff022deb
RK
566 return value;
567 }
3230c662
DV
568};
569
e99fde05 570/**
ff022deb
RK
571 * Converts a y for an axis to a percentage from the top to the
572 * bottom of the div.
573 *
574 * If the coordinate represents a value visible on the canvas, then
575 * the value will be between 0 and 1, where 0 is the top of the canvas.
576 * However, this method will return values outside the range, as
577 * values can fall outside the canvas.
578 *
579 * If y is null, this returns null.
580 * if axis is null, this uses the first axis.
581 */
582Dygraph.prototype.toPercentYCoord = function(y, axis) {
583 if (y == null) {
584 return null;
585 }
7d0e7a0d 586 if (typeof(axis) == "undefined") axis = 0;
ff022deb
RK
587
588 var area = this.plotter_.area;
589 var yRange = this.yAxisRange(axis);
590
591 var pct;
7d0e7a0d 592 if (!this.axes_[axis].logscale) {
ff022deb
RK
593 // yrange[1] - y is unit distance from the bottom.
594 // yrange[1] - yrange[0] is the scale of the range.
595 // (yRange[1] - y) / (yRange[1] - yRange[0]) is the % from the bottom.
596 pct = (yRange[1] - y) / (yRange[1] - yRange[0]);
597 } else {
d59b6f34
RK
598 var logr1 = Dygraph.log10(yRange[1]);
599 pct = (logr1 - Dygraph.log10(y)) / (logr1 - Dygraph.log10(yRange[0]));
ff022deb
RK
600 }
601 return pct;
602}
603
604/**
e99fde05
DV
605 * Returns the number of columns (including the independent variable).
606 */
607Dygraph.prototype.numColumns = function() {
608 return this.rawData_[0].length;
609};
610
611/**
612 * Returns the number of rows (excluding any header/label row).
613 */
614Dygraph.prototype.numRows = function() {
615 return this.rawData_.length;
616};
617
618/**
619 * Returns the value in the given row and column. If the row and column exceed
620 * the bounds on the data, returns null. Also returns null if the value is
621 * missing.
622 */
623Dygraph.prototype.getValue = function(row, col) {
624 if (row < 0 || row > this.rawData_.length) return null;
625 if (col < 0 || col > this.rawData_[row].length) return null;
626
627 return this.rawData_[row][col];
628};
629
76171648
DV
630Dygraph.addEvent = function(el, evt, fn) {
631 var normed_fn = function(e) {
632 if (!e) var e = window.event;
633 fn(e);
634 };
635 if (window.addEventListener) { // Mozilla, Netscape, Firefox
636 el.addEventListener(evt, normed_fn, false);
637 } else { // IE
638 el.attachEvent('on' + evt, normed_fn);
639 }
640};
6a1aa64f 641
062ef401
JB
642
643// Based on the article at
644// http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
645Dygraph.cancelEvent = function(e) {
646 e = e ? e : window.event;
647 if (e.stopPropagation) {
648 e.stopPropagation();
649 }
650 if (e.preventDefault) {
651 e.preventDefault();
652 }
653 e.cancelBubble = true;
654 e.cancel = true;
655 e.returnValue = false;
656 return false;
657}
658
659
6a1aa64f 660/**
285a6bda 661 * Generates interface elements for the Dygraph: a containing div, a div to
6a1aa64f 662 * display the current point, and a textbox to adjust the rolling average
697e70b2 663 * period. Also creates the Renderer/Layout elements.
6a1aa64f
DV
664 * @private
665 */
285a6bda 666Dygraph.prototype.createInterface_ = function() {
6a1aa64f
DV
667 // Create the all-enclosing graph div
668 var enclosing = this.maindiv_;
669
b0c3b730
DV
670 this.graphDiv = document.createElement("div");
671 this.graphDiv.style.width = this.width_ + "px";
672 this.graphDiv.style.height = this.height_ + "px";
673 enclosing.appendChild(this.graphDiv);
674
675 // Create the canvas for interactive parts of the chart.
f8cfec73 676 this.canvas_ = Dygraph.createCanvas();
b0c3b730
DV
677 this.canvas_.style.position = "absolute";
678 this.canvas_.width = this.width_;
679 this.canvas_.height = this.height_;
f8cfec73
DV
680 this.canvas_.style.width = this.width_ + "px"; // for IE
681 this.canvas_.style.height = this.height_ + "px"; // for IE
b0c3b730
DV
682
683 // ... and for static parts of the chart.
6a1aa64f 684 this.hidden_ = this.createPlotKitCanvas_(this.canvas_);
76171648 685
eb7bf005
EC
686 // The interactive parts of the graph are drawn on top of the chart.
687 this.graphDiv.appendChild(this.hidden_);
688 this.graphDiv.appendChild(this.canvas_);
689 this.mouseEventElement_ = this.canvas_;
690
76171648 691 var dygraph = this;
eb7bf005 692 Dygraph.addEvent(this.mouseEventElement_, 'mousemove', function(e) {
76171648
DV
693 dygraph.mouseMove_(e);
694 });
eb7bf005 695 Dygraph.addEvent(this.mouseEventElement_, 'mouseout', function(e) {
76171648
DV
696 dygraph.mouseOut_(e);
697 });
697e70b2
DV
698
699 // Create the grapher
700 // TODO(danvk): why does the Layout need its own set of options?
701 this.layoutOptions_ = { 'xOriginIsZero': false };
702 Dygraph.update(this.layoutOptions_, this.attrs_);
703 Dygraph.update(this.layoutOptions_, this.user_attrs_);
704 Dygraph.update(this.layoutOptions_, {
705 'errorBars': (this.attr_("errorBars") || this.attr_("customBars")) });
706
707 this.layout_ = new DygraphLayout(this, this.layoutOptions_);
708
709 // TODO(danvk): why does the Renderer need its own set of options?
710 this.renderOptions_ = { colorScheme: this.colors_,
711 strokeColor: null,
712 axisLineWidth: Dygraph.AXIS_LINE_WIDTH };
713 Dygraph.update(this.renderOptions_, this.attrs_);
714 Dygraph.update(this.renderOptions_, this.user_attrs_);
697e70b2
DV
715
716 this.createStatusMessage_();
697e70b2 717 this.createDragInterface_();
4cfcc38c
DV
718};
719
720/**
721 * Detach DOM elements in the dygraph and null out all data references.
722 * Calling this when you're done with a dygraph can dramatically reduce memory
723 * usage. See, e.g., the tests/perf.html example.
724 */
725Dygraph.prototype.destroy = function() {
726 var removeRecursive = function(node) {
727 while (node.hasChildNodes()) {
728 removeRecursive(node.firstChild);
729 node.removeChild(node.firstChild);
730 }
731 };
732 removeRecursive(this.maindiv_);
733
734 var nullOut = function(obj) {
735 for (var n in obj) {
736 if (typeof(obj[n]) === 'object') {
737 obj[n] = null;
738 }
739 }
740 };
741
742 // These may not all be necessary, but it can't hurt...
743 nullOut(this.layout_);
744 nullOut(this.plotter_);
745 nullOut(this);
746};
6a1aa64f
DV
747
748/**
749 * Creates the canvas containing the PlotKit graph. Only plotkit ever draws on
285a6bda 750 * this particular canvas. All Dygraph work is done on this.canvas_.
8846615a 751 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
6a1aa64f
DV
752 * @return {Object} The newly-created canvas
753 * @private
754 */
285a6bda 755Dygraph.prototype.createPlotKitCanvas_ = function(canvas) {
f8cfec73 756 var h = Dygraph.createCanvas();
6a1aa64f 757 h.style.position = "absolute";
9ac5e4ae
DV
758 // TODO(danvk): h should be offset from canvas. canvas needs to include
759 // some extra area to make it easier to zoom in on the far left and far
760 // right. h needs to be precisely the plot area, so that clipping occurs.
6a1aa64f
DV
761 h.style.top = canvas.style.top;
762 h.style.left = canvas.style.left;
763 h.width = this.width_;
764 h.height = this.height_;
f8cfec73
DV
765 h.style.width = this.width_ + "px"; // for IE
766 h.style.height = this.height_ + "px"; // for IE
6a1aa64f
DV
767 return h;
768};
769
f474c2a3
DV
770// Taken from MochiKit.Color
771Dygraph.hsvToRGB = function (hue, saturation, value) {
772 var red;
773 var green;
774 var blue;
775 if (saturation === 0) {
776 red = value;
777 green = value;
778 blue = value;
779 } else {
780 var i = Math.floor(hue * 6);
781 var f = (hue * 6) - i;
782 var p = value * (1 - saturation);
783 var q = value * (1 - (saturation * f));
784 var t = value * (1 - (saturation * (1 - f)));
785 switch (i) {
786 case 1: red = q; green = value; blue = p; break;
787 case 2: red = p; green = value; blue = t; break;
788 case 3: red = p; green = q; blue = value; break;
789 case 4: red = t; green = p; blue = value; break;
790 case 5: red = value; green = p; blue = q; break;
791 case 6: // fall through
792 case 0: red = value; green = t; blue = p; break;
793 }
794 }
795 red = Math.floor(255 * red + 0.5);
796 green = Math.floor(255 * green + 0.5);
797 blue = Math.floor(255 * blue + 0.5);
798 return 'rgb(' + red + ',' + green + ',' + blue + ')';
799};
800
801
6a1aa64f
DV
802/**
803 * Generate a set of distinct colors for the data series. This is done with a
804 * color wheel. Saturation/Value are customizable, and the hue is
805 * equally-spaced around the color wheel. If a custom set of colors is
806 * specified, that is used instead.
6a1aa64f
DV
807 * @private
808 */
285a6bda
DV
809Dygraph.prototype.setColors_ = function() {
810 // TODO(danvk): compute this directly into this.attrs_['colorScheme'] and do
811 // away with this.renderOptions_.
812 var num = this.attr_("labels").length - 1;
6a1aa64f 813 this.colors_ = [];
285a6bda
DV
814 var colors = this.attr_('colors');
815 if (!colors) {
816 var sat = this.attr_('colorSaturation') || 1.0;
817 var val = this.attr_('colorValue') || 0.5;
2aa21213 818 var half = Math.ceil(num / 2);
6a1aa64f 819 for (var i = 1; i <= num; i++) {
ec1959eb 820 if (!this.visibility()[i-1]) continue;
43af96e7 821 // alternate colors for high contrast.
2aa21213 822 var idx = i % 2 ? Math.ceil(i / 2) : (half + i / 2);
43af96e7
NK
823 var hue = (1.0 * idx/ (1 + num));
824 this.colors_.push(Dygraph.hsvToRGB(hue, sat, val));
6a1aa64f
DV
825 }
826 } else {
827 for (var i = 0; i < num; i++) {
ec1959eb 828 if (!this.visibility()[i]) continue;
285a6bda 829 var colorStr = colors[i % colors.length];
f474c2a3 830 this.colors_.push(colorStr);
6a1aa64f
DV
831 }
832 }
285a6bda 833
c21d2c2d 834 // TODO(danvk): update this w/r/t/ the new options system.
285a6bda 835 this.renderOptions_.colorScheme = this.colors_;
fc80a396
DV
836 Dygraph.update(this.plotter_.options, this.renderOptions_);
837 Dygraph.update(this.layoutOptions_, this.user_attrs_);
838 Dygraph.update(this.layoutOptions_, this.attrs_);
6a1aa64f
DV
839}
840
43af96e7
NK
841/**
842 * Return the list of colors. This is either the list of colors passed in the
843 * attributes, or the autogenerated list of rgb(r,g,b) strings.
844 * @return {Array<string>} The list of colors.
845 */
846Dygraph.prototype.getColors = function() {
847 return this.colors_;
848};
849
5e60386d
DV
850// The following functions are from quirksmode.org with a modification for Safari from
851// http://blog.firetree.net/2005/07/04/javascript-find-position/
3df0ccf0
DV
852// http://www.quirksmode.org/js/findpos.html
853Dygraph.findPosX = function(obj) {
854 var curleft = 0;
5e60386d 855 if(obj.offsetParent)
50360fd0 856 while(1)
5e60386d 857 {
3df0ccf0 858 curleft += obj.offsetLeft;
5e60386d
DV
859 if(!obj.offsetParent)
860 break;
3df0ccf0
DV
861 obj = obj.offsetParent;
862 }
5e60386d 863 else if(obj.x)
3df0ccf0
DV
864 curleft += obj.x;
865 return curleft;
866};
c21d2c2d 867
3df0ccf0
DV
868Dygraph.findPosY = function(obj) {
869 var curtop = 0;
5e60386d
DV
870 if(obj.offsetParent)
871 while(1)
872 {
3df0ccf0 873 curtop += obj.offsetTop;
5e60386d
DV
874 if(!obj.offsetParent)
875 break;
3df0ccf0
DV
876 obj = obj.offsetParent;
877 }
5e60386d 878 else if(obj.y)
3df0ccf0
DV
879 curtop += obj.y;
880 return curtop;
881};
882
5e60386d 883
71a11a8e 884
6a1aa64f
DV
885/**
886 * Create the div that contains information on the selected point(s)
887 * This goes in the top right of the canvas, unless an external div has already
888 * been specified.
889 * @private
890 */
fedbd797 891Dygraph.prototype.createStatusMessage_ = function() {
892 var userLabelsDiv = this.user_attrs_["labelsDiv"];
893 if (userLabelsDiv && null != userLabelsDiv
894 && (typeof(userLabelsDiv) == "string" || userLabelsDiv instanceof String)) {
895 this.user_attrs_["labelsDiv"] = document.getElementById(userLabelsDiv);
896 }
285a6bda
DV
897 if (!this.attr_("labelsDiv")) {
898 var divWidth = this.attr_('labelsDivWidth');
b0c3b730 899 var messagestyle = {
6a1aa64f
DV
900 "position": "absolute",
901 "fontSize": "14px",
902 "zIndex": 10,
903 "width": divWidth + "px",
904 "top": "0px",
8846615a 905 "left": (this.width_ - divWidth - 2) + "px",
6a1aa64f
DV
906 "background": "white",
907 "textAlign": "left",
b0c3b730 908 "overflow": "hidden"};
fc80a396 909 Dygraph.update(messagestyle, this.attr_('labelsDivStyles'));
b0c3b730
DV
910 var div = document.createElement("div");
911 for (var name in messagestyle) {
85b99f0b
DV
912 if (messagestyle.hasOwnProperty(name)) {
913 div.style[name] = messagestyle[name];
914 }
b0c3b730
DV
915 }
916 this.graphDiv.appendChild(div);
285a6bda 917 this.attrs_.labelsDiv = div;
6a1aa64f
DV
918 }
919};
920
921/**
ad1798c2
DV
922 * Position the labels div so that:
923 * - its right edge is flush with the right edge of the charting area
924 * - its top edge is flush with the top edge of the charting area
0abfbd7e
DV
925 */
926Dygraph.prototype.positionLabelsDiv_ = function() {
927 // Don't touch a user-specified labelsDiv.
928 if (this.user_attrs_.hasOwnProperty("labelsDiv")) return;
929
930 var area = this.plotter_.area;
931 var div = this.attr_("labelsDiv");
8c21adcf 932 div.style.left = area.x + area.w - this.attr_("labelsDivWidth") - 1 + "px";
ad1798c2 933 div.style.top = area.y + "px";
0abfbd7e
DV
934};
935
936/**
6a1aa64f 937 * Create the text box to adjust the averaging period
6a1aa64f
DV
938 * @private
939 */
285a6bda 940Dygraph.prototype.createRollInterface_ = function() {
8c69de65
DV
941 // Create a roller if one doesn't exist already.
942 if (!this.roller_) {
943 this.roller_ = document.createElement("input");
944 this.roller_.type = "text";
945 this.roller_.style.display = "none";
946 this.graphDiv.appendChild(this.roller_);
947 }
948
949 var display = this.attr_('showRoller') ? 'block' : 'none';
26ca7938 950
b0c3b730
DV
951 var textAttr = { "position": "absolute",
952 "zIndex": 10,
953 "top": (this.plotter_.area.h - 25) + "px",
954 "left": (this.plotter_.area.x + 1) + "px",
955 "display": display
6a1aa64f 956 };
8c69de65
DV
957 this.roller_.size = "2";
958 this.roller_.value = this.rollPeriod_;
b0c3b730 959 for (var name in textAttr) {
85b99f0b 960 if (textAttr.hasOwnProperty(name)) {
8c69de65 961 this.roller_.style[name] = textAttr[name];
85b99f0b 962 }
b0c3b730
DV
963 }
964
76171648 965 var dygraph = this;
8c69de65 966 this.roller_.onchange = function() { dygraph.adjustRoll(dygraph.roller_.value); };
76171648
DV
967};
968
969// These functions are taken from MochiKit.Signal
970Dygraph.pageX = function(e) {
971 if (e.pageX) {
972 return (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
973 } else {
974 var de = document;
975 var b = document.body;
976 return e.clientX +
977 (de.scrollLeft || b.scrollLeft) -
978 (de.clientLeft || 0);
979 }
980};
981
982Dygraph.pageY = function(e) {
983 if (e.pageY) {
984 return (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
985 } else {
986 var de = document;
987 var b = document.body;
988 return e.clientY +
989 (de.scrollTop || b.scrollTop) -
990 (de.clientTop || 0);
991 }
992};
6a1aa64f 993
062ef401
JB
994Dygraph.prototype.dragGetX_ = function(e, context) {
995 return Dygraph.pageX(e) - context.px
996};
bce01b0f 997
062ef401
JB
998Dygraph.prototype.dragGetY_ = function(e, context) {
999 return Dygraph.pageY(e) - context.py
1000};
ee672584 1001
062ef401
JB
1002// Called in response to an interaction model operation that
1003// should start the default panning behavior.
1004//
1005// It's used in the default callback for "mousedown" operations.
1006// Custom interaction model builders can use it to provide the default
1007// panning behavior.
1008//
1009Dygraph.startPan = function(event, g, context) {
062ef401
JB
1010 context.isPanning = true;
1011 var xRange = g.xAxisRange();
1012 context.dateRange = xRange[1] - xRange[0];
ec291cbe
RK
1013 context.initialLeftmostDate = xRange[0];
1014 context.xUnitsPerPixel = context.dateRange / (g.plotter_.area.w - 1);
062ef401
JB
1015
1016 // Record the range of each y-axis at the start of the drag.
1017 // If any axis has a valueRange or valueWindow, then we want a 2D pan.
1018 context.is2DPan = false;
1019 for (var i = 0; i < g.axes_.length; i++) {
1020 var axis = g.axes_[i];
1021 var yRange = g.yAxisRange(i);
ec291cbe 1022 // TODO(konigsberg): These values should be in |context|.
ed898bdd
RK
1023 // In log scale, initialTopValue, dragValueRange and unitsPerPixel are log scale.
1024 if (axis.logscale) {
1025 axis.initialTopValue = Dygraph.log10(yRange[1]);
1026 axis.dragValueRange = Dygraph.log10(yRange[1]) - Dygraph.log10(yRange[0]);
1027 } else {
1028 axis.initialTopValue = yRange[1];
1029 axis.dragValueRange = yRange[1] - yRange[0];
1030 }
ec291cbe 1031 axis.unitsPerPixel = axis.dragValueRange / (g.plotter_.area.h - 1);
ed898bdd
RK
1032
1033 // While calculating axes, set 2dpan.
062ef401
JB
1034 if (axis.valueWindow || axis.valueRange) context.is2DPan = true;
1035 }
062ef401 1036};
6a1aa64f 1037
062ef401
JB
1038// Called in response to an interaction model operation that
1039// responds to an event that pans the view.
1040//
1041// It's used in the default callback for "mousemove" operations.
1042// Custom interaction model builders can use it to provide the default
1043// panning behavior.
1044//
1045Dygraph.movePan = function(event, g, context) {
1046 context.dragEndX = g.dragGetX_(event, context);
1047 context.dragEndY = g.dragGetY_(event, context);
79b3ee42 1048
ec291cbe
RK
1049 var minDate = context.initialLeftmostDate -
1050 (context.dragEndX - context.dragStartX) * context.xUnitsPerPixel;
062ef401
JB
1051 var maxDate = minDate + context.dateRange;
1052 g.dateWindow_ = [minDate, maxDate];
1053
1054 // y-axis scaling is automatic unless this is a full 2D pan.
1055 if (context.is2DPan) {
1056 // Adjust each axis appropriately.
062ef401
JB
1057 for (var i = 0; i < g.axes_.length; i++) {
1058 var axis = g.axes_[i];
ed898bdd
RK
1059
1060 var pixelsDragged = context.dragEndY - context.dragStartY;
1061 var unitsDragged = pixelsDragged * axis.unitsPerPixel;
1062
1063 // In log scale, maxValue and minValue are the logs of those values.
1064 var maxValue = axis.initialTopValue + unitsDragged;
062ef401 1065 var minValue = maxValue - axis.dragValueRange;
ed898bdd 1066 if (axis.logscale) {
5db0e241
DV
1067 axis.valueWindow = [ Math.pow(Dygraph.LOG_SCALE, minValue),
1068 Math.pow(Dygraph.LOG_SCALE, maxValue) ];
ed898bdd
RK
1069 } else {
1070 axis.valueWindow = [ minValue, maxValue ];
1071 }
6faebb69 1072 }
062ef401 1073 }
bce01b0f 1074
062ef401
JB
1075 g.drawGraph_();
1076}
ee672584 1077
062ef401
JB
1078// Called in response to an interaction model operation that
1079// responds to an event that ends panning.
1080//
1081// It's used in the default callback for "mouseup" operations.
1082// Custom interaction model builders can use it to provide the default
1083// panning behavior.
1084//
1085Dygraph.endPan = function(event, g, context) {
ec291cbe
RK
1086 // TODO(konigsberg): Clear the context data from the axis.
1087 // TODO(konigsberg): mouseup should just delete the
1088 // context object, and mousedown should create a new one.
062ef401
JB
1089 context.isPanning = false;
1090 context.is2DPan = false;
ec291cbe 1091 context.initialLeftmostDate = null;
062ef401
JB
1092 context.dateRange = null;
1093 context.valueRange = null;
1094}
ee672584 1095
062ef401
JB
1096// Called in response to an interaction model operation that
1097// responds to an event that starts zooming.
1098//
1099// It's used in the default callback for "mousedown" operations.
1100// Custom interaction model builders can use it to provide the default
1101// zooming behavior.
1102//
1103Dygraph.startZoom = function(event, g, context) {
1104 context.isZooming = true;
1105}
1106
1107// Called in response to an interaction model operation that
1108// responds to an event that defines zoom boundaries.
1109//
1110// It's used in the default callback for "mousemove" operations.
1111// Custom interaction model builders can use it to provide the default
1112// zooming behavior.
1113//
1114Dygraph.moveZoom = function(event, g, context) {
1115 context.dragEndX = g.dragGetX_(event, context);
1116 context.dragEndY = g.dragGetY_(event, context);
1117
1118 var xDelta = Math.abs(context.dragStartX - context.dragEndX);
1119 var yDelta = Math.abs(context.dragStartY - context.dragEndY);
1120
1121 // drag direction threshold for y axis is twice as large as x axis
1122 context.dragDirection = (xDelta < yDelta / 2) ? Dygraph.VERTICAL : Dygraph.HORIZONTAL;
1123
1124 g.drawZoomRect_(
1125 context.dragDirection,
1126 context.dragStartX,
1127 context.dragEndX,
1128 context.dragStartY,
1129 context.dragEndY,
1130 context.prevDragDirection,
1131 context.prevEndX,
1132 context.prevEndY);
1133
1134 context.prevEndX = context.dragEndX;
1135 context.prevEndY = context.dragEndY;
1136 context.prevDragDirection = context.dragDirection;
1137}
1138
1139// Called in response to an interaction model operation that
1140// responds to an event that performs a zoom based on previously defined
1141// bounds..
1142//
1143// It's used in the default callback for "mouseup" operations.
1144// Custom interaction model builders can use it to provide the default
1145// zooming behavior.
1146//
1147Dygraph.endZoom = function(event, g, context) {
1148 context.isZooming = false;
1149 context.dragEndX = g.dragGetX_(event, context);
1150 context.dragEndY = g.dragGetY_(event, context);
1151 var regionWidth = Math.abs(context.dragEndX - context.dragStartX);
1152 var regionHeight = Math.abs(context.dragEndY - context.dragStartY);
1153
1154 if (regionWidth < 2 && regionHeight < 2 &&
1155 g.lastx_ != undefined && g.lastx_ != -1) {
1156 // TODO(danvk): pass along more info about the points, e.g. 'x'
1157 if (g.attr_('clickCallback') != null) {
1158 g.attr_('clickCallback')(event, g.lastx_, g.selPoints_);
1159 }
1160 if (g.attr_('pointClickCallback')) {
1161 // check if the click was on a particular point.
1162 var closestIdx = -1;
1163 var closestDistance = 0;
1164 for (var i = 0; i < g.selPoints_.length; i++) {
1165 var p = g.selPoints_[i];
1166 var distance = Math.pow(p.canvasx - context.dragEndX, 2) +
1167 Math.pow(p.canvasy - context.dragEndY, 2);
1168 if (closestIdx == -1 || distance < closestDistance) {
1169 closestDistance = distance;
1170 closestIdx = i;
d58ae307
DV
1171 }
1172 }
e3489f4f 1173
062ef401
JB
1174 // Allow any click within two pixels of the dot.
1175 var radius = g.attr_('highlightCircleSize') + 2;
1176 if (closestDistance <= 5 * 5) {
1177 g.attr_('pointClickCallback')(event, g.selPoints_[closestIdx]);
6faebb69 1178 }
062ef401
JB
1179 }
1180 }
0a52ab7a 1181
062ef401
JB
1182 if (regionWidth >= 10 && context.dragDirection == Dygraph.HORIZONTAL) {
1183 g.doZoomX_(Math.min(context.dragStartX, context.dragEndX),
1184 Math.max(context.dragStartX, context.dragEndX));
1185 } else if (regionHeight >= 10 && context.dragDirection == Dygraph.VERTICAL) {
1186 g.doZoomY_(Math.min(context.dragStartY, context.dragEndY),
1187 Math.max(context.dragStartY, context.dragEndY));
1188 } else {
1189 g.canvas_.getContext("2d").clearRect(0, 0,
1190 g.canvas_.width,
1191 g.canvas_.height);
1192 }
1193 context.dragStartX = null;
1194 context.dragStartY = null;
1195}
1196
1197Dygraph.defaultInteractionModel = {
1198 // Track the beginning of drag events
1199 mousedown: function(event, g, context) {
1200 context.initializeMouseDown(event, g, context);
1201
1202 if (event.altKey || event.shiftKey) {
1203 Dygraph.startPan(event, g, context);
bce01b0f 1204 } else {
062ef401 1205 Dygraph.startZoom(event, g, context);
bce01b0f 1206 }
062ef401 1207 },
6a1aa64f 1208
062ef401
JB
1209 // Draw zoom rectangles when the mouse is down and the user moves around
1210 mousemove: function(event, g, context) {
1211 if (context.isZooming) {
1212 Dygraph.moveZoom(event, g, context);
1213 } else if (context.isPanning) {
1214 Dygraph.movePan(event, g, context);
6a1aa64f 1215 }
062ef401 1216 },
bce01b0f 1217
062ef401
JB
1218 mouseup: function(event, g, context) {
1219 if (context.isZooming) {
1220 Dygraph.endZoom(event, g, context);
1221 } else if (context.isPanning) {
1222 Dygraph.endPan(event, g, context);
bce01b0f 1223 }
062ef401 1224 },
6a1aa64f
DV
1225
1226 // Temporarily cancel the dragging event when the mouse leaves the graph
062ef401
JB
1227 mouseout: function(event, g, context) {
1228 if (context.isZooming) {
1229 context.dragEndX = null;
1230 context.dragEndY = null;
6a1aa64f 1231 }
062ef401 1232 },
6a1aa64f 1233
062ef401
JB
1234 // Disable zooming out if panning.
1235 dblclick: function(event, g, context) {
1236 if (event.altKey || event.shiftKey) {
1237 return;
1238 }
1239 // TODO(konigsberg): replace g.doUnzoom()_ with something that is
1240 // friendlier to public use.
1241 g.doUnzoom_();
1242 }
1243};
1e1bf7df 1244
062ef401 1245Dygraph.DEFAULT_ATTRS.interactionModel = Dygraph.defaultInteractionModel;
6a1aa64f 1246
062ef401
JB
1247/**
1248 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1249 * events.
1250 * @private
1251 */
1252Dygraph.prototype.createDragInterface_ = function() {
1253 var context = {
1254 // Tracks whether the mouse is down right now
1255 isZooming: false,
1256 isPanning: false, // is this drag part of a pan?
1257 is2DPan: false, // if so, is that pan 1- or 2-dimensional?
1258 dragStartX: null,
1259 dragStartY: null,
1260 dragEndX: null,
1261 dragEndY: null,
1262 dragDirection: null,
1263 prevEndX: null,
1264 prevEndY: null,
1265 prevDragDirection: null,
1266
ec291cbe
RK
1267 // The value on the left side of the graph when a pan operation starts.
1268 initialLeftmostDate: null,
1269
1270 // The number of units each pixel spans. (This won't be valid for log
1271 // scales)
1272 xUnitsPerPixel: null,
062ef401
JB
1273
1274 // TODO(danvk): update this comment
1275 // The range in second/value units that the viewport encompasses during a
1276 // panning operation.
1277 dateRange: null,
1278
1279 // Utility function to convert page-wide coordinates to canvas coords
1280 px: 0,
1281 py: 0,
1282
1283 initializeMouseDown: function(event, g, context) {
1284 // prevents mouse drags from selecting page text.
1285 if (event.preventDefault) {
1286 event.preventDefault(); // Firefox, Chrome, etc.
6a1aa64f 1287 } else {
062ef401
JB
1288 event.returnValue = false; // IE
1289 event.cancelBubble = true;
6a1aa64f
DV
1290 }
1291
062ef401
JB
1292 context.px = Dygraph.findPosX(g.canvas_);
1293 context.py = Dygraph.findPosY(g.canvas_);
1294 context.dragStartX = g.dragGetX_(event, context);
1295 context.dragStartY = g.dragGetY_(event, context);
6a1aa64f 1296 }
062ef401 1297 };
2b188b3d 1298
062ef401 1299 var interactionModel = this.attr_("interactionModel");
8b83c6cc 1300
062ef401
JB
1301 // Self is the graph.
1302 var self = this;
6faebb69 1303
062ef401
JB
1304 // Function that binds the graph and context to the handler.
1305 var bindHandler = function(handler) {
1306 return function(event) {
1307 handler(event, self, context);
1308 };
1309 };
1310
1311 for (var eventName in interactionModel) {
1312 if (!interactionModel.hasOwnProperty(eventName)) continue;
1313 Dygraph.addEvent(this.mouseEventElement_, eventName,
1314 bindHandler(interactionModel[eventName]));
1315 }
1316
1317 // If the user releases the mouse button during a drag, but not over the
1318 // canvas, then it doesn't count as a zooming action.
1319 Dygraph.addEvent(document, 'mouseup', function(event) {
1320 if (context.isZooming || context.isPanning) {
1321 context.isZooming = false;
1322 context.dragStartX = null;
1323 context.dragStartY = null;
1324 }
1325
1326 if (context.isPanning) {
1327 context.isPanning = false;
1328 context.draggingDate = null;
1329 context.dateRange = null;
1330 for (var i = 0; i < self.axes_.length; i++) {
1331 delete self.axes_[i].draggingValue;
1332 delete self.axes_[i].dragValueRange;
1333 }
1334 }
6a1aa64f
DV
1335 });
1336};
1337
062ef401 1338
6a1aa64f
DV
1339/**
1340 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1341 * up any previous zoom rectangles that were drawn. This could be optimized to
1342 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1343 * dots.
8b83c6cc 1344 *
39b0e098
RK
1345 * @param {Number} direction the direction of the zoom rectangle. Acceptable
1346 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
6a1aa64f
DV
1347 * @param {Number} startX The X position where the drag started, in canvas
1348 * coordinates.
1349 * @param {Number} endX The current X position of the drag, in canvas coords.
8b83c6cc
RK
1350 * @param {Number} startY The Y position where the drag started, in canvas
1351 * coordinates.
1352 * @param {Number} endY The current Y position of the drag, in canvas coords.
39b0e098 1353 * @param {Number} prevDirection the value of direction on the previous call to
8b83c6cc 1354 * this function. Used to avoid excess redrawing
6a1aa64f
DV
1355 * @param {Number} prevEndX The value of endX on the previous call to this
1356 * function. Used to avoid excess redrawing
8b83c6cc
RK
1357 * @param {Number} prevEndY The value of endY on the previous call to this
1358 * function. Used to avoid excess redrawing
6a1aa64f
DV
1359 * @private
1360 */
7201b11e
JB
1361Dygraph.prototype.drawZoomRect_ = function(direction, startX, endX, startY,
1362 endY, prevDirection, prevEndX,
1363 prevEndY) {
6a1aa64f
DV
1364 var ctx = this.canvas_.getContext("2d");
1365
1366 // Clean up from the previous rect if necessary
39b0e098 1367 if (prevDirection == Dygraph.HORIZONTAL) {
6a1aa64f
DV
1368 ctx.clearRect(Math.min(startX, prevEndX), 0,
1369 Math.abs(startX - prevEndX), this.height_);
39b0e098 1370 } else if (prevDirection == Dygraph.VERTICAL){
8b83c6cc
RK
1371 ctx.clearRect(0, Math.min(startY, prevEndY),
1372 this.width_, Math.abs(startY - prevEndY));
6a1aa64f
DV
1373 }
1374
1375 // Draw a light-grey rectangle to show the new viewing area
39b0e098 1376 if (direction == Dygraph.HORIZONTAL) {
8b83c6cc
RK
1377 if (endX && startX) {
1378 ctx.fillStyle = "rgba(128,128,128,0.33)";
1379 ctx.fillRect(Math.min(startX, endX), 0,
1380 Math.abs(endX - startX), this.height_);
1381 }
1382 }
39b0e098 1383 if (direction == Dygraph.VERTICAL) {
8b83c6cc
RK
1384 if (endY && startY) {
1385 ctx.fillStyle = "rgba(128,128,128,0.33)";
1386 ctx.fillRect(0, Math.min(startY, endY),
1387 this.width_, Math.abs(endY - startY));
1388 }
6a1aa64f
DV
1389 }
1390};
1391
1392/**
8b83c6cc
RK
1393 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1394 * the canvas. The exact zoom window may be slightly larger if there are no data
1395 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1396 * which accepts dates that match the raw data. This function redraws the graph.
d58ae307 1397 *
6a1aa64f
DV
1398 * @param {Number} lowX The leftmost pixel value that should be visible.
1399 * @param {Number} highX The rightmost pixel value that should be visible.
1400 * @private
1401 */
8b83c6cc 1402Dygraph.prototype.doZoomX_ = function(lowX, highX) {
6a1aa64f 1403 // Find the earliest and latest dates contained in this canvasx range.
8b83c6cc 1404 // Convert the call to date ranges of the raw data.
ff022deb
RK
1405 var minDate = this.toDataXCoord(lowX);
1406 var maxDate = this.toDataXCoord(highX);
8b83c6cc
RK
1407 this.doZoomXDates_(minDate, maxDate);
1408};
6a1aa64f 1409
8b83c6cc
RK
1410/**
1411 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1412 * method with doZoomX which accepts pixel coordinates. This function redraws
1413 * the graph.
d58ae307 1414 *
8b83c6cc
RK
1415 * @param {Number} minDate The minimum date that should be visible.
1416 * @param {Number} maxDate The maximum date that should be visible.
1417 * @private
1418 */
1419Dygraph.prototype.doZoomXDates_ = function(minDate, maxDate) {
6a1aa64f 1420 this.dateWindow_ = [minDate, maxDate];
26ca7938 1421 this.drawGraph_();
285a6bda 1422 if (this.attr_("zoomCallback")) {
ac139d19 1423 this.attr_("zoomCallback")(minDate, maxDate, this.yAxisRanges());
8b83c6cc
RK
1424 }
1425};
1426
1427/**
1428 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
d58ae307
DV
1429 * the canvas. This function redraws the graph.
1430 *
8b83c6cc
RK
1431 * @param {Number} lowY The topmost pixel value that should be visible.
1432 * @param {Number} highY The lowest pixel value that should be visible.
1433 * @private
1434 */
1435Dygraph.prototype.doZoomY_ = function(lowY, highY) {
d58ae307
DV
1436 // Find the highest and lowest values in pixel range for each axis.
1437 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1438 // This is because pixels increase as you go down on the screen, whereas data
1439 // coordinates increase as you go up the screen.
1440 var valueRanges = [];
1441 for (var i = 0; i < this.axes_.length; i++) {
ff022deb
RK
1442 var hi = this.toDataYCoord(lowY, i);
1443 var low = this.toDataYCoord(highY, i);
1444 this.axes_[i].valueWindow = [low, hi];
1445 valueRanges.push([low, hi]);
d58ae307 1446 }
8b83c6cc 1447
66c380c4 1448 this.drawGraph_();
8b83c6cc 1449 if (this.attr_("zoomCallback")) {
d58ae307
DV
1450 var xRange = this.xAxisRange();
1451 this.attr_("zoomCallback")(xRange[0], xRange[1], this.yAxisRanges());
8b83c6cc
RK
1452 }
1453};
1454
1455/**
1456 * Reset the zoom to the original view coordinates. This is the same as
1457 * double-clicking on the graph.
d58ae307 1458 *
8b83c6cc
RK
1459 * @private
1460 */
1461Dygraph.prototype.doUnzoom_ = function() {
d58ae307 1462 var dirty = false;
8b83c6cc 1463 if (this.dateWindow_ != null) {
d58ae307 1464 dirty = true;
8b83c6cc
RK
1465 this.dateWindow_ = null;
1466 }
d58ae307
DV
1467
1468 for (var i = 0; i < this.axes_.length; i++) {
1469 if (this.axes_[i].valueWindow != null) {
1470 dirty = true;
1471 delete this.axes_[i].valueWindow;
1472 }
8b83c6cc
RK
1473 }
1474
1475 if (dirty) {
437c0979
RK
1476 // Putting the drawing operation before the callback because it resets
1477 // yAxisRange.
66c380c4 1478 this.drawGraph_();
8b83c6cc
RK
1479 if (this.attr_("zoomCallback")) {
1480 var minDate = this.rawData_[0][0];
1481 var maxDate = this.rawData_[this.rawData_.length - 1][0];
d58ae307 1482 this.attr_("zoomCallback")(minDate, maxDate, this.yAxisRanges());
8b83c6cc 1483 }
67e650dc 1484 }
6a1aa64f
DV
1485};
1486
1487/**
1488 * When the mouse moves in the canvas, display information about a nearby data
1489 * point and draw dots over those points in the data series. This function
1490 * takes care of cleanup of previously-drawn dots.
1491 * @param {Object} event The mousemove event from the browser.
1492 * @private
1493 */
285a6bda 1494Dygraph.prototype.mouseMove_ = function(event) {
eb7bf005 1495 var canvasx = Dygraph.pageX(event) - Dygraph.findPosX(this.mouseEventElement_);
6a1aa64f
DV
1496 var points = this.layout_.points;
1497
e863a17d 1498 // This prevents JS errors when mousing over the canvas before data loads.
685ebbb3 1499 if (points === undefined) return;
e863a17d 1500
6a1aa64f
DV
1501 var lastx = -1;
1502 var lasty = -1;
1503
1504 // Loop through all the points and find the date nearest to our current
1505 // location.
1506 var minDist = 1e+100;
1507 var idx = -1;
1508 for (var i = 0; i < points.length; i++) {
8a7cc60e
RK
1509 var point = points[i];
1510 if (point == null) continue;
062ef401 1511 var dist = Math.abs(point.canvasx - canvasx);
f032c51d 1512 if (dist > minDist) continue;
6a1aa64f
DV
1513 minDist = dist;
1514 idx = i;
1515 }
1516 if (idx >= 0) lastx = points[idx].xval;
6a1aa64f
DV
1517
1518 // Extract the points we've selected
b258a3da 1519 this.selPoints_ = [];
50360fd0 1520 var l = points.length;
416b05ad
NK
1521 if (!this.attr_("stackedGraph")) {
1522 for (var i = 0; i < l; i++) {
1523 if (points[i].xval == lastx) {
1524 this.selPoints_.push(points[i]);
1525 }
1526 }
1527 } else {
354e15ab
DE
1528 // Need to 'unstack' points starting from the bottom
1529 var cumulative_sum = 0;
416b05ad
NK
1530 for (var i = l - 1; i >= 0; i--) {
1531 if (points[i].xval == lastx) {
354e15ab 1532 var p = {}; // Clone the point since we modify it
d4139cd8
NK
1533 for (var k in points[i]) {
1534 p[k] = points[i][k];
50360fd0
NK
1535 }
1536 p.yval -= cumulative_sum;
1537 cumulative_sum += p.yval;
d4139cd8 1538 this.selPoints_.push(p);
12e4c741 1539 }
6a1aa64f 1540 }
354e15ab 1541 this.selPoints_.reverse();
6a1aa64f
DV
1542 }
1543
b258a3da 1544 if (this.attr_("highlightCallback")) {
a4c6a67c 1545 var px = this.lastx_;
dd082dda 1546 if (px !== null && lastx != px) {
344ba8c0 1547 // only fire if the selected point has changed.
2ddb1197 1548 this.attr_("highlightCallback")(event, lastx, this.selPoints_, this.idxToRow_(idx));
43af96e7 1549 }
12e4c741 1550 }
43af96e7 1551
239c712d
NAG
1552 // Save last x position for callbacks.
1553 this.lastx_ = lastx;
50360fd0 1554
239c712d
NAG
1555 this.updateSelection_();
1556};
b258a3da 1557
239c712d 1558/**
1903f1e4 1559 * Transforms layout_.points index into data row number.
2ddb1197 1560 * @param int layout_.points index
1903f1e4 1561 * @return int row number, or -1 if none could be found.
2ddb1197
SC
1562 * @private
1563 */
1564Dygraph.prototype.idxToRow_ = function(idx) {
1903f1e4 1565 if (idx < 0) return -1;
2ddb1197 1566
1903f1e4
DV
1567 for (var i in this.layout_.datasets) {
1568 if (idx < this.layout_.datasets[i].length) {
1569 return this.boundaryIds_[0][0]+idx;
1570 }
1571 idx -= this.layout_.datasets[i].length;
1572 }
1573 return -1;
1574};
2ddb1197 1575
2fccd3dc 1576// TODO(danvk): rename this function to something like 'isNonZeroNan'.
e9fe4a2f
DV
1577Dygraph.isOK = function(x) {
1578 return x && !isNaN(x);
1579};
1580
1581Dygraph.prototype.generateLegendHTML_ = function(x, sel_points) {
2fccd3dc
DV
1582 // If no points are selected, we display a default legend. Traditionally,
1583 // this has been blank. But a better default would be a conventional legend,
1584 // which provides essential information for a non-interactive chart.
1585 if (typeof(x) === 'undefined') {
1586 if (this.attr_('legend') != 'always') return '';
1587
1588 var sepLines = this.attr_('labelsSeparateLines');
1589 var labels = this.attr_('labels');
1590 var html = '';
1591 for (var i = 1; i < labels.length; i++) {
1592 var c = new RGBColor(this.plotter_.colors[labels[i]]);
1593 if (i > 1) html += (sepLines ? '<br/>' : ' ');
1594 html += "<b><font color='" + c.toHex() + "'>&mdash;" + labels[i] +
1595 "</font></b>";
1596 }
1597 return html;
1598 }
1599
e9fe4a2f
DV
1600 var displayDigits = this.numXDigits_ + this.numExtraDigits_;
1601 var html = this.attr_('xValueFormatter')(x, displayDigits) + ":";
1602
1603 var fmtFunc = this.attr_('yValueFormatter');
1604 var showZeros = this.attr_("labelsShowZeroValues");
1605 var sepLines = this.attr_("labelsSeparateLines");
1606 for (var i = 0; i < this.selPoints_.length; i++) {
1607 var pt = this.selPoints_[i];
1608 if (pt.yval == 0 && !showZeros) continue;
1609 if (!Dygraph.isOK(pt.canvasy)) continue;
1610 if (sepLines) html += "<br/>";
1611
1612 var c = new RGBColor(this.plotter_.colors[pt.name]);
1613 var yval = fmtFunc(pt.yval, displayDigits);
2fccd3dc 1614 // TODO(danvk): use a template string here and make it an attribute.
e9fe4a2f
DV
1615 html += " <b><font color='" + c.toHex() + "'>"
1616 + pt.name + "</font></b>:"
1617 + yval;
1618 }
1619 return html;
1620};
1621
2ddb1197 1622/**
239c712d
NAG
1623 * Draw dots over the selectied points in the data series. This function
1624 * takes care of cleanup of previously-drawn dots.
1625 * @private
1626 */
1627Dygraph.prototype.updateSelection_ = function() {
6a1aa64f 1628 // Clear the previously drawn vertical, if there is one
6a1aa64f
DV
1629 var ctx = this.canvas_.getContext("2d");
1630 if (this.previousVerticalX_ >= 0) {
46dde5f9
DV
1631 // Determine the maximum highlight circle size.
1632 var maxCircleSize = 0;
227b93cc
DV
1633 var labels = this.attr_('labels');
1634 for (var i = 1; i < labels.length; i++) {
1635 var r = this.attr_('highlightCircleSize', labels[i]);
46dde5f9
DV
1636 if (r > maxCircleSize) maxCircleSize = r;
1637 }
6a1aa64f 1638 var px = this.previousVerticalX_;
46dde5f9
DV
1639 ctx.clearRect(px - maxCircleSize - 1, 0,
1640 2 * maxCircleSize + 2, this.height_);
6a1aa64f
DV
1641 }
1642
d160cc3b 1643 if (this.selPoints_.length > 0) {
6a1aa64f 1644 // Set the status message to indicate the selected point(s)
d160cc3b 1645 if (this.attr_('showLabelsOnHighlight')) {
e9fe4a2f
DV
1646 var html = this.generateLegendHTML_(this.lastx_, this.selPoints_);
1647 this.attr_("labelsDiv").innerHTML = html;
6a1aa64f 1648 }
6a1aa64f 1649
6a1aa64f 1650 // Draw colored circles over the center of each selected point
e9fe4a2f 1651 var canvasx = this.selPoints_[0].canvasx;
43af96e7 1652 ctx.save();
b258a3da 1653 for (var i = 0; i < this.selPoints_.length; i++) {
e9fe4a2f
DV
1654 var pt = this.selPoints_[i];
1655 if (!Dygraph.isOK(pt.canvasy)) continue;
1656
1657 var circleSize = this.attr_('highlightCircleSize', pt.name);
6a1aa64f 1658 ctx.beginPath();
e9fe4a2f
DV
1659 ctx.fillStyle = this.plotter_.colors[pt.name];
1660 ctx.arc(canvasx, pt.canvasy, circleSize, 0, 2 * Math.PI, false);
6a1aa64f
DV
1661 ctx.fill();
1662 }
1663 ctx.restore();
1664
1665 this.previousVerticalX_ = canvasx;
1666 }
1667};
1668
1669/**
239c712d
NAG
1670 * Set manually set selected dots, and display information about them
1671 * @param int row number that should by highlighted
1672 * false value clears the selection
1673 * @public
1674 */
1675Dygraph.prototype.setSelection = function(row) {
1676 // Extract the points we've selected
1677 this.selPoints_ = [];
1678 var pos = 0;
50360fd0 1679
239c712d 1680 if (row !== false) {
16269f6e
NAG
1681 row = row-this.boundaryIds_[0][0];
1682 }
50360fd0 1683
16269f6e 1684 if (row !== false && row >= 0) {
239c712d 1685 for (var i in this.layout_.datasets) {
16269f6e 1686 if (row < this.layout_.datasets[i].length) {
38f33a44 1687 var point = this.layout_.points[pos+row];
1688
1689 if (this.attr_("stackedGraph")) {
8c03ba63 1690 point = this.layout_.unstackPointAtIndex(pos+row);
38f33a44 1691 }
1692
1693 this.selPoints_.push(point);
16269f6e 1694 }
239c712d
NAG
1695 pos += this.layout_.datasets[i].length;
1696 }
16269f6e 1697 }
50360fd0 1698
16269f6e 1699 if (this.selPoints_.length) {
239c712d
NAG
1700 this.lastx_ = this.selPoints_[0].xval;
1701 this.updateSelection_();
1702 } else {
1703 this.lastx_ = -1;
1704 this.clearSelection();
1705 }
1706
1707};
1708
1709/**
6a1aa64f
DV
1710 * The mouse has left the canvas. Clear out whatever artifacts remain
1711 * @param {Object} event the mouseout event from the browser.
1712 * @private
1713 */
285a6bda 1714Dygraph.prototype.mouseOut_ = function(event) {
a4c6a67c
AV
1715 if (this.attr_("unhighlightCallback")) {
1716 this.attr_("unhighlightCallback")(event);
1717 }
1718
43af96e7 1719 if (this.attr_("hideOverlayOnMouseOut")) {
239c712d 1720 this.clearSelection();
43af96e7 1721 }
6a1aa64f
DV
1722};
1723
239c712d
NAG
1724/**
1725 * Remove all selection from the canvas
1726 * @public
1727 */
1728Dygraph.prototype.clearSelection = function() {
1729 // Get rid of the overlay data
1730 var ctx = this.canvas_.getContext("2d");
1731 ctx.clearRect(0, 0, this.width_, this.height_);
2fccd3dc 1732 this.attr_('labelsDiv').innerHTML = this.generateLegendHTML_();
239c712d
NAG
1733 this.selPoints_ = [];
1734 this.lastx_ = -1;
1735}
1736
103b7292
NAG
1737/**
1738 * Returns the number of the currently selected row
1739 * @return int row number, of -1 if nothing is selected
1740 * @public
1741 */
1742Dygraph.prototype.getSelection = function() {
1743 if (!this.selPoints_ || this.selPoints_.length < 1) {
1744 return -1;
1745 }
50360fd0 1746
103b7292
NAG
1747 for (var row=0; row<this.layout_.points.length; row++ ) {
1748 if (this.layout_.points[row].x == this.selPoints_[0].x) {
16269f6e 1749 return row + this.boundaryIds_[0][0];
103b7292
NAG
1750 }
1751 }
1752 return -1;
1753}
1754
285a6bda 1755Dygraph.zeropad = function(x) {
32988383
DV
1756 if (x < 10) return "0" + x; else return "" + x;
1757}
1758
6a1aa64f 1759/**
6b8e33dd
DV
1760 * Return a string version of the hours, minutes and seconds portion of a date.
1761 * @param {Number} date The JavaScript date (ms since epoch)
1762 * @return {String} A time of the form "HH:MM:SS"
1763 * @private
1764 */
bf640e56 1765Dygraph.hmsString_ = function(date) {
285a6bda 1766 var zeropad = Dygraph.zeropad;
6b8e33dd
DV
1767 var d = new Date(date);
1768 if (d.getSeconds()) {
1769 return zeropad(d.getHours()) + ":" +
1770 zeropad(d.getMinutes()) + ":" +
1771 zeropad(d.getSeconds());
6b8e33dd 1772 } else {
054531ca 1773 return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes());
6b8e33dd
DV
1774 }
1775}
1776
1777/**
bf640e56
AV
1778 * Convert a JS date to a string appropriate to display on an axis that
1779 * is displaying values at the stated granularity.
1780 * @param {Date} date The date to format
1781 * @param {Number} granularity One of the Dygraph granularity constants
1782 * @return {String} The formatted date
1783 * @private
1784 */
1785Dygraph.dateAxisFormatter = function(date, granularity) {
062ef401
JB
1786 if (granularity >= Dygraph.DECADAL) {
1787 return date.strftime('%Y');
1788 } else if (granularity >= Dygraph.MONTHLY) {
bf640e56
AV
1789 return date.strftime('%b %y');
1790 } else {
31eddad3 1791 var frac = date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds() + date.getMilliseconds();
bf640e56
AV
1792 if (frac == 0 || granularity >= Dygraph.DAILY) {
1793 return new Date(date.getTime() + 3600*1000).strftime('%d%b');
1794 } else {
1795 return Dygraph.hmsString_(date.getTime());
1796 }
1797 }
1798}
1799
1800/**
6a1aa64f
DV
1801 * Convert a JS date (millis since epoch) to YYYY/MM/DD
1802 * @param {Number} date The JavaScript date (ms since epoch)
1803 * @return {String} A date of the form "YYYY/MM/DD"
1804 * @private
1805 */
6be8e54c 1806Dygraph.dateString_ = function(date) {
285a6bda 1807 var zeropad = Dygraph.zeropad;
6a1aa64f
DV
1808 var d = new Date(date);
1809
1810 // Get the year:
1811 var year = "" + d.getFullYear();
1812 // Get a 0 padded month string
6b8e33dd 1813 var month = zeropad(d.getMonth() + 1); //months are 0-offset, sigh
6a1aa64f 1814 // Get a 0 padded day string
6b8e33dd 1815 var day = zeropad(d.getDate());
6a1aa64f 1816
6b8e33dd
DV
1817 var ret = "";
1818 var frac = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
bf640e56 1819 if (frac) ret = " " + Dygraph.hmsString_(date);
6b8e33dd
DV
1820
1821 return year + "/" + month + "/" + day + ret;
6a1aa64f
DV
1822};
1823
1824/**
6a1aa64f
DV
1825 * Fires when there's data available to be graphed.
1826 * @param {String} data Raw CSV data to be plotted
1827 * @private
1828 */
285a6bda 1829Dygraph.prototype.loadedEvent_ = function(data) {
6a1aa64f 1830 this.rawData_ = this.parseCSV_(data);
26ca7938 1831 this.predraw_();
6a1aa64f
DV
1832};
1833
285a6bda 1834Dygraph.prototype.months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
8846615a 1835 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
285a6bda 1836Dygraph.prototype.quarters = ["Jan", "Apr", "Jul", "Oct"];
6a1aa64f
DV
1837
1838/**
1839 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
1840 * @private
1841 */
285a6bda 1842Dygraph.prototype.addXTicks_ = function() {
6a1aa64f 1843 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
7201b11e 1844 var range;
6a1aa64f 1845 if (this.dateWindow_) {
7201b11e 1846 range = [this.dateWindow_[0], this.dateWindow_[1]];
6a1aa64f 1847 } else {
7201b11e
JB
1848 range = [this.rawData_[0][0], this.rawData_[this.rawData_.length - 1][0]];
1849 }
1850
1851 var formatter = this.attr_('xTicker');
1852 var ret = formatter(range[0], range[1], this);
1853 var xTicks = [];
1854
7aedf6fe
DV
1855 // Note: numericTicks() returns a {ticks: [...], numDigits: yy} dictionary,
1856 // whereas dateTicker and user-defined tickers typically just return a ticks
1857 // array.
7201b11e 1858 if (ret.ticks !== undefined) {
7201b11e 1859 xTicks = ret.ticks;
6be8e54c 1860 this.numXDigits_ = ret.numDigits;
7201b11e
JB
1861 } else {
1862 xTicks = ret;
3c1d225b 1863 }
7201b11e
JB
1864
1865 this.layout_.updateOptions({xTicks: xTicks});
32988383
DV
1866};
1867
1868// Time granularity enumeration
285a6bda 1869Dygraph.SECONDLY = 0;
20a41c17
DV
1870Dygraph.TWO_SECONDLY = 1;
1871Dygraph.FIVE_SECONDLY = 2;
1872Dygraph.TEN_SECONDLY = 3;
1873Dygraph.THIRTY_SECONDLY = 4;
1874Dygraph.MINUTELY = 5;
1875Dygraph.TWO_MINUTELY = 6;
1876Dygraph.FIVE_MINUTELY = 7;
1877Dygraph.TEN_MINUTELY = 8;
1878Dygraph.THIRTY_MINUTELY = 9;
1879Dygraph.HOURLY = 10;
1880Dygraph.TWO_HOURLY = 11;
1881Dygraph.SIX_HOURLY = 12;
1882Dygraph.DAILY = 13;
1883Dygraph.WEEKLY = 14;
1884Dygraph.MONTHLY = 15;
1885Dygraph.QUARTERLY = 16;
1886Dygraph.BIANNUAL = 17;
1887Dygraph.ANNUAL = 18;
1888Dygraph.DECADAL = 19;
062ef401
JB
1889Dygraph.CENTENNIAL = 20;
1890Dygraph.NUM_GRANULARITIES = 21;
285a6bda
DV
1891
1892Dygraph.SHORT_SPACINGS = [];
1893Dygraph.SHORT_SPACINGS[Dygraph.SECONDLY] = 1000 * 1;
20a41c17
DV
1894Dygraph.SHORT_SPACINGS[Dygraph.TWO_SECONDLY] = 1000 * 2;
1895Dygraph.SHORT_SPACINGS[Dygraph.FIVE_SECONDLY] = 1000 * 5;
285a6bda
DV
1896Dygraph.SHORT_SPACINGS[Dygraph.TEN_SECONDLY] = 1000 * 10;
1897Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_SECONDLY] = 1000 * 30;
1898Dygraph.SHORT_SPACINGS[Dygraph.MINUTELY] = 1000 * 60;
20a41c17
DV
1899Dygraph.SHORT_SPACINGS[Dygraph.TWO_MINUTELY] = 1000 * 60 * 2;
1900Dygraph.SHORT_SPACINGS[Dygraph.FIVE_MINUTELY] = 1000 * 60 * 5;
285a6bda
DV
1901Dygraph.SHORT_SPACINGS[Dygraph.TEN_MINUTELY] = 1000 * 60 * 10;
1902Dygraph.SHORT_SPACINGS[Dygraph.THIRTY_MINUTELY] = 1000 * 60 * 30;
1903Dygraph.SHORT_SPACINGS[Dygraph.HOURLY] = 1000 * 3600;
20a41c17 1904Dygraph.SHORT_SPACINGS[Dygraph.TWO_HOURLY] = 1000 * 3600 * 2;
805d5519 1905Dygraph.SHORT_SPACINGS[Dygraph.SIX_HOURLY] = 1000 * 3600 * 6;
285a6bda
DV
1906Dygraph.SHORT_SPACINGS[Dygraph.DAILY] = 1000 * 86400;
1907Dygraph.SHORT_SPACINGS[Dygraph.WEEKLY] = 1000 * 604800;
32988383
DV
1908
1909// NumXTicks()
1910//
1911// If we used this time granularity, how many ticks would there be?
1912// This is only an approximation, but it's generally good enough.
1913//
285a6bda
DV
1914Dygraph.prototype.NumXTicks = function(start_time, end_time, granularity) {
1915 if (granularity < Dygraph.MONTHLY) {
32988383 1916 // Generate one tick mark for every fixed interval of time.
285a6bda 1917 var spacing = Dygraph.SHORT_SPACINGS[granularity];
32988383
DV
1918 return Math.floor(0.5 + 1.0 * (end_time - start_time) / spacing);
1919 } else {
1920 var year_mod = 1; // e.g. to only print one point every 10 years.
1921 var num_months = 12;
285a6bda
DV
1922 if (granularity == Dygraph.QUARTERLY) num_months = 3;
1923 if (granularity == Dygraph.BIANNUAL) num_months = 2;
1924 if (granularity == Dygraph.ANNUAL) num_months = 1;
1925 if (granularity == Dygraph.DECADAL) { num_months = 1; year_mod = 10; }
062ef401 1926 if (granularity == Dygraph.CENTENNIAL) { num_months = 1; year_mod = 100; }
32988383
DV
1927
1928 var msInYear = 365.2524 * 24 * 3600 * 1000;
1929 var num_years = 1.0 * (end_time - start_time) / msInYear;
1930 return Math.floor(0.5 + 1.0 * num_years * num_months / year_mod);
1931 }
1932};
1933
1934// GetXAxis()
1935//
1936// Construct an x-axis of nicely-formatted times on meaningful boundaries
1937// (e.g. 'Jan 09' rather than 'Jan 22, 2009').
1938//
1939// Returns an array containing {v: millis, label: label} dictionaries.
1940//
285a6bda 1941Dygraph.prototype.GetXAxis = function(start_time, end_time, granularity) {
bf640e56 1942 var formatter = this.attr_("xAxisLabelFormatter");
32988383 1943 var ticks = [];
285a6bda 1944 if (granularity < Dygraph.MONTHLY) {
32988383 1945 // Generate one tick mark for every fixed interval of time.
285a6bda 1946 var spacing = Dygraph.SHORT_SPACINGS[granularity];
3d29302c 1947 var format = '%d%b'; // e.g. "1Jan"
076c9622
DV
1948
1949 // Find a time less than start_time which occurs on a "nice" time boundary
1950 // for this granularity.
1951 var g = spacing / 1000;
076c9622
DV
1952 var d = new Date(start_time);
1953 if (g <= 60) { // seconds
1954 var x = d.getSeconds(); d.setSeconds(x - x % g);
1955 } else {
1956 d.setSeconds(0);
1957 g /= 60;
1958 if (g <= 60) { // minutes
1959 var x = d.getMinutes(); d.setMinutes(x - x % g);
1960 } else {
1961 d.setMinutes(0);
1962 g /= 60;
1963
1964 if (g <= 24) { // days
1965 var x = d.getHours(); d.setHours(x - x % g);
1966 } else {
1967 d.setHours(0);
1968 g /= 24;
1969
1970 if (g == 7) { // one week
20a41c17 1971 d.setDate(d.getDate() - d.getDay());
076c9622
DV
1972 }
1973 }
1974 }
328bb812 1975 }
076c9622
DV
1976 start_time = d.getTime();
1977
32988383 1978 for (var t = start_time; t <= end_time; t += spacing) {
bf640e56 1979 ticks.push({ v:t, label: formatter(new Date(t), granularity) });
32988383
DV
1980 }
1981 } else {
1982 // Display a tick mark on the first of a set of months of each year.
1983 // Years get a tick mark iff y % year_mod == 0. This is useful for
1984 // displaying a tick mark once every 10 years, say, on long time scales.
1985 var months;
1986 var year_mod = 1; // e.g. to only print one point every 10 years.
1987
285a6bda 1988 if (granularity == Dygraph.MONTHLY) {
32988383 1989 months = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
285a6bda 1990 } else if (granularity == Dygraph.QUARTERLY) {
32988383 1991 months = [ 0, 3, 6, 9 ];
285a6bda 1992 } else if (granularity == Dygraph.BIANNUAL) {
32988383 1993 months = [ 0, 6 ];
285a6bda 1994 } else if (granularity == Dygraph.ANNUAL) {
32988383 1995 months = [ 0 ];
285a6bda 1996 } else if (granularity == Dygraph.DECADAL) {
32988383
DV
1997 months = [ 0 ];
1998 year_mod = 10;
062ef401
JB
1999 } else if (granularity == Dygraph.CENTENNIAL) {
2000 months = [ 0 ];
2001 year_mod = 100;
2002 } else {
2003 this.warn("Span of dates is too long");
32988383
DV
2004 }
2005
2006 var start_year = new Date(start_time).getFullYear();
2007 var end_year = new Date(end_time).getFullYear();
285a6bda 2008 var zeropad = Dygraph.zeropad;
32988383
DV
2009 for (var i = start_year; i <= end_year; i++) {
2010 if (i % year_mod != 0) continue;
2011 for (var j = 0; j < months.length; j++) {
2012 var date_str = i + "/" + zeropad(1 + months[j]) + "/01";
2013 var t = Date.parse(date_str);
2014 if (t < start_time || t > end_time) continue;
bf640e56 2015 ticks.push({ v:t, label: formatter(new Date(t), granularity) });
32988383
DV
2016 }
2017 }
2018 }
2019
2020 return ticks;
2021};
2022
6a1aa64f
DV
2023
2024/**
2025 * Add ticks to the x-axis based on a date range.
2026 * @param {Number} startDate Start of the date window (millis since epoch)
2027 * @param {Number} endDate End of the date window (millis since epoch)
2028 * @return {Array.<Object>} Array of {label, value} tuples.
2029 * @public
2030 */
285a6bda 2031Dygraph.dateTicker = function(startDate, endDate, self) {
32988383 2032 var chosen = -1;
285a6bda
DV
2033 for (var i = 0; i < Dygraph.NUM_GRANULARITIES; i++) {
2034 var num_ticks = self.NumXTicks(startDate, endDate, i);
2035 if (self.width_ / num_ticks >= self.attr_('pixelsPerXLabel')) {
32988383
DV
2036 chosen = i;
2037 break;
2769de62 2038 }
6a1aa64f
DV
2039 }
2040
32988383 2041 if (chosen >= 0) {
285a6bda 2042 return self.GetXAxis(startDate, endDate, chosen);
6a1aa64f 2043 } else {
32988383 2044 // TODO(danvk): signal error.
6a1aa64f 2045 }
6a1aa64f
DV
2046};
2047
c1bc242a
DV
2048// This is a list of human-friendly values at which to show tick marks on a log
2049// scale. It is k * 10^n, where k=1..9 and n=-39..+39, so:
2050// ..., 1, 2, 3, 4, 5, ..., 9, 10, 20, 30, ..., 90, 100, 200, 300, ...
5db0e241 2051// NOTE: this assumes that Dygraph.LOG_SCALE = 10.
0cfa06d1 2052Dygraph.PREFERRED_LOG_TICK_VALUES = function() {
6821efbe
RK
2053 var vals = [];
2054 for (var power = -39; power <= 39; power++) {
2055 var range = Math.pow(10, power);
4b467120
RK
2056 for (var mult = 1; mult <= 9; mult++) {
2057 var val = range * mult;
6821efbe
RK
2058 vals.push(val);
2059 }
2060 }
2061 return vals;
2062}();
2063
0cfa06d1
RK
2064// val is the value to search for
2065// arry is the value over which to search
2066// if abs > 0, find the lowest entry greater than val
2067// if abs < 0, find the highest entry less than val
2068// if abs == 0, find the entry that equals val.
2069// Currently does not work when val is outside the range of arry's values.
2070Dygraph.binarySearch = function(val, arry, abs, low, high) {
2071 if (low == null || high == null) {
2072 low = 0;
2073 high = arry.length - 1;
2074 }
2075 if (low > high) {
2076 return -1;
2077 }
2078 if (abs == null) {
2079 abs = 0;
2080 }
2081 var validIndex = function(idx) {
2082 return idx >= 0 && idx < arry.length;
2083 }
2084 var mid = parseInt((low + high) / 2);
2085 var element = arry[mid];
2086 if (element == val) {
2087 return mid;
2088 }
2089 if (element > val) {
2090 if (abs > 0) {
2091 // Accept if element > val, but also if prior element < val.
2092 var idx = mid - 1;
2093 if (validIndex(idx) && arry[idx] < val) {
2094 return mid;
2095 }
2096 }
c1bc242a 2097 return Dygraph.binarySearch(val, arry, abs, low, mid - 1);
0cfa06d1
RK
2098 }
2099 if (element < val) {
2100 if (abs < 0) {
2101 // Accept if element < val, but also if prior element > val.
2102 var idx = mid + 1;
2103 if (validIndex(idx) && arry[idx] > val) {
2104 return mid;
2105 }
2106 }
2107 return Dygraph.binarySearch(val, arry, abs, mid + 1, high);
2108 }
60a19014 2109};
0cfa06d1 2110
6a1aa64f 2111/**
3c1d225b
JB
2112 * Determine the number of significant figures in a Number up to the specified
2113 * precision. Note that there is no way to determine if a trailing '0' is
2114 * significant or not, so by convention we return 1 for all of the following
2115 * inputs: 1, 1.0, 1.00, 1.000 etc.
2116 * @param {Number} x The input value.
2117 * @param {Number} opt_maxPrecision Optional maximum precision to consider.
2118 * Default and maximum allowed value is 13.
2119 * @return {Number} The number of significant figures which is >= 1.
2120 */
2121Dygraph.significantFigures = function(x, opt_maxPrecision) {
2122 var precision = Math.max(opt_maxPrecision || 13, 13);
2123
fff1de86 2124 // Convert the number to its exponential notation form and work backwards,
3c1d225b
JB
2125 // ignoring the 'e+xx' bit. This may seem like a hack, but doing a loop and
2126 // dividing by 10 leads to roundoff errors. By using toExponential(), we let
2127 // the JavaScript interpreter handle the low level bits of the Number for us.
2128 var s = x.toExponential(precision);
2129 var ePos = s.lastIndexOf('e'); // -1 case handled by return below.
2130
2131 for (var i = ePos - 1; i >= 0; i--) {
2132 if (s[i] == '.') {
2133 // Got to the decimal place. We'll call this 1 digit of precision because
2134 // we can't know for sure how many trailing 0s are significant.
2135 return 1;
2136 } else if (s[i] != '0') {
2137 // Found the first non-zero digit. Return the number of characters
2138 // except for the '.'.
2139 return i; // This is i - 1 + 1 (-1 is for '.', +1 is for 0 based index).
2140 }
2141 }
2142
2143 // Occurs if toExponential() doesn't return a string containing 'e', which
2144 // should never happen.
2145 return 1;
2146};
2147
2148/**
6a1aa64f 2149 * Add ticks when the x axis has numbers on it (instead of dates)
ff022deb
RK
2150 * TODO(konigsberg): Update comment.
2151 *
7d0e7a0d
RK
2152 * @param {Number} minV minimum value
2153 * @param {Number} maxV maximum value
84fc6aa7 2154 * @param self
f30cf740 2155 * @param {function} attribute accessor function.
6a1aa64f
DV
2156 * @return {Array.<Object>} Array of {label, value} tuples.
2157 * @public
2158 */
0d64e596 2159Dygraph.numericTicks = function(minV, maxV, self, axis_props, vals) {
70c80071
DV
2160 var attr = function(k) {
2161 if (axis_props && axis_props.hasOwnProperty(k)) return axis_props[k];
2162 return self.attr_(k);
2163 };
f09fc545 2164
0d64e596
DV
2165 var ticks = [];
2166 if (vals) {
2167 for (var i = 0; i < vals.length; i++) {
e863a17d 2168 ticks.push({v: vals[i]});
0d64e596 2169 }
f09e46d4 2170 } else {
7d0e7a0d 2171 if (axis_props && attr("logscale")) {
ff022deb 2172 var pixelsPerTick = attr('pixelsPerYLabel');
7d0e7a0d 2173 // NOTE(konigsberg): Dan, should self.height_ be self.plotter_.area.h?
ff022deb 2174 var nTicks = Math.floor(self.height_ / pixelsPerTick);
0cfa06d1
RK
2175 var minIdx = Dygraph.binarySearch(minV, Dygraph.PREFERRED_LOG_TICK_VALUES, 1);
2176 var maxIdx = Dygraph.binarySearch(maxV, Dygraph.PREFERRED_LOG_TICK_VALUES, -1);
2177 if (minIdx == -1) {
6821efbe
RK
2178 minIdx = 0;
2179 }
0cfa06d1
RK
2180 if (maxIdx == -1) {
2181 maxIdx = Dygraph.PREFERRED_LOG_TICK_VALUES.length - 1;
6821efbe 2182 }
0cfa06d1
RK
2183 // Count the number of tick values would appear, if we can get at least
2184 // nTicks / 4 accept them.
00aa7f61 2185 var lastDisplayed = null;
0cfa06d1 2186 if (maxIdx - minIdx >= nTicks / 4) {
00aa7f61 2187 var axisId = axis_props.yAxisId;
0cfa06d1
RK
2188 for (var idx = maxIdx; idx >= minIdx; idx--) {
2189 var tickValue = Dygraph.PREFERRED_LOG_TICK_VALUES[idx];
00aa7f61
RK
2190 var domCoord = axis_props.g.toDomYCoord(tickValue, axisId);
2191 var tick = { v: tickValue };
2192 if (lastDisplayed == null) {
2193 lastDisplayed = {
2194 tickValue : tickValue,
2195 domCoord : domCoord
2196 };
2197 } else {
2198 if (domCoord - lastDisplayed.domCoord >= pixelsPerTick) {
2199 lastDisplayed = {
2200 tickValue : tickValue,
2201 domCoord : domCoord
2202 };
2203 } else {
c1bc242a 2204 tick.label = "";
00aa7f61
RK
2205 }
2206 }
2207 ticks.push(tick);
6821efbe 2208 }
0cfa06d1
RK
2209 // Since we went in backwards order.
2210 ticks.reverse();
6821efbe 2211 }
f09e46d4 2212 }
c1bc242a 2213
6821efbe
RK
2214 // ticks.length won't be 0 if the log scale function finds values to insert.
2215 if (ticks.length == 0) {
ff022deb
RK
2216 // Basic idea:
2217 // Try labels every 1, 2, 5, 10, 20, 50, 100, etc.
2218 // Calculate the resulting tick spacing (i.e. this.height_ / nTicks).
2219 // The first spacing greater than pixelsPerYLabel is what we use.
2220 // TODO(danvk): version that works on a log scale.
0d64e596 2221 if (attr("labelsKMG2")) {
ff022deb 2222 var mults = [1, 2, 4, 8];
0d64e596 2223 } else {
ff022deb 2224 var mults = [1, 2, 5];
0d64e596 2225 }
ff022deb
RK
2226 var scale, low_val, high_val, nTicks;
2227 // TODO(danvk): make it possible to set this for x- and y-axes independently.
2228 var pixelsPerTick = attr('pixelsPerYLabel');
2229 for (var i = -10; i < 50; i++) {
2230 if (attr("labelsKMG2")) {
2231 var base_scale = Math.pow(16, i);
2232 } else {
2233 var base_scale = Math.pow(10, i);
2234 }
2235 for (var j = 0; j < mults.length; j++) {
2236 scale = base_scale * mults[j];
2237 low_val = Math.floor(minV / scale) * scale;
2238 high_val = Math.ceil(maxV / scale) * scale;
2239 nTicks = Math.abs(high_val - low_val) / scale;
2240 var spacing = self.height_ / nTicks;
2241 // wish I could break out of both loops at once...
2242 if (spacing > pixelsPerTick) break;
2243 }
0d64e596
DV
2244 if (spacing > pixelsPerTick) break;
2245 }
0d64e596 2246
ff022deb
RK
2247 // Construct the set of ticks.
2248 // Allow reverse y-axis if it's explicitly requested.
2249 if (low_val > high_val) scale *= -1;
2250 for (var i = 0; i < nTicks; i++) {
2251 var tickV = low_val + i * scale;
2252 ticks.push( {v: tickV} );
2253 }
0d64e596 2254 }
6a1aa64f
DV
2255 }
2256
0d64e596 2257 // Add formatted labels to the ticks.
ed11be50
DV
2258 var k;
2259 var k_labels = [];
f09fc545 2260 if (attr("labelsKMB")) {
ed11be50
DV
2261 k = 1000;
2262 k_labels = [ "K", "M", "B", "T" ];
2263 }
f09fc545 2264 if (attr("labelsKMG2")) {
ed11be50
DV
2265 if (k) self.warn("Setting both labelsKMB and labelsKMG2. Pick one!");
2266 k = 1024;
2267 k_labels = [ "k", "M", "G", "T" ];
2268 }
3c1d225b
JB
2269 var formatter = attr('yAxisLabelFormatter') ?
2270 attr('yAxisLabelFormatter') : attr('yValueFormatter');
2271
2272 // Determine the number of decimal places needed for the labels below by
2273 // taking the maximum number of significant figures for any label. We must
2274 // take the max because we can't tell if trailing 0s are significant.
2275 var numDigits = 0;
2276 for (var i = 0; i < ticks.length; i++) {
fff1de86 2277 numDigits = Math.max(Dygraph.significantFigures(ticks[i].v), numDigits);
3c1d225b 2278 }
ed11be50 2279
0cfa06d1 2280 // Add labels to the ticks.
0d64e596 2281 for (var i = 0; i < ticks.length; i++) {
e863a17d 2282 if (ticks[i].label !== undefined) continue; // Use current label.
0d64e596 2283 var tickV = ticks[i].v;
0af6e346 2284 var absTickV = Math.abs(tickV);
3c1d225b
JB
2285 var label = (formatter !== undefined) ?
2286 formatter(tickV, numDigits) : tickV.toPrecision(numDigits);
2287 if (k_labels.length > 0) {
ed11be50
DV
2288 // Round up to an appropriate unit.
2289 var n = k*k*k*k;
2290 for (var j = 3; j >= 0; j--, n /= k) {
2291 if (absTickV >= n) {
d916677a 2292 label = formatter(tickV / n, numDigits) + k_labels[j];
ed11be50
DV
2293 break;
2294 }
afefbcdb 2295 }
6a1aa64f 2296 }
d916677a 2297 ticks[i].label = label;
6a1aa64f 2298 }
d916677a 2299
3c1d225b 2300 return {ticks: ticks, numDigits: numDigits};
6a1aa64f
DV
2301};
2302
5011e7a1
DV
2303// Computes the range of the data series (including confidence intervals).
2304// series is either [ [x1, y1], [x2, y2], ... ] or
2305// [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
2306// Returns [low, high]
2307Dygraph.prototype.extremeValues_ = function(series) {
2308 var minY = null, maxY = null;
2309
9922b78b 2310 var bars = this.attr_("errorBars") || this.attr_("customBars");
5011e7a1
DV
2311 if (bars) {
2312 // With custom bars, maxY is the max of the high values.
2313 for (var j = 0; j < series.length; j++) {
2314 var y = series[j][1][0];
2315 if (!y) continue;
2316 var low = y - series[j][1][1];
2317 var high = y + series[j][1][2];
2318 if (low > y) low = y; // this can happen with custom bars,
2319 if (high < y) high = y; // e.g. in tests/custom-bars.html
2320 if (maxY == null || high > maxY) {
2321 maxY = high;
2322 }
2323 if (minY == null || low < minY) {
2324 minY = low;
2325 }
2326 }
2327 } else {
2328 for (var j = 0; j < series.length; j++) {
2329 var y = series[j][1];
d12999d3 2330 if (y === null || isNaN(y)) continue;
5011e7a1
DV
2331 if (maxY == null || y > maxY) {
2332 maxY = y;
2333 }
2334 if (minY == null || y < minY) {
2335 minY = y;
2336 }
2337 }
2338 }
2339
2340 return [minY, maxY];
2341};
2342
6a1aa64f 2343/**
26ca7938
DV
2344 * This function is called once when the chart's data is changed or the options
2345 * dictionary is updated. It is _not_ called when the user pans or zooms. The
2346 * idea is that values derived from the chart's data can be computed here,
2347 * rather than every time the chart is drawn. This includes things like the
2348 * number of axes, rolling averages, etc.
2349 */
2350Dygraph.prototype.predraw_ = function() {
2351 // TODO(danvk): move more computations out of drawGraph_ and into here.
2352 this.computeYAxes_();
2353
2354 // Create a new plotter.
70c80071 2355 if (this.plotter_) this.plotter_.clear();
26ca7938
DV
2356 this.plotter_ = new DygraphCanvasRenderer(this,
2357 this.hidden_, this.layout_,
2358 this.renderOptions_);
2359
0abfbd7e
DV
2360 // The roller sits in the bottom left corner of the chart. We don't know where
2361 // this will be until the options are available, so it's positioned here.
8c69de65 2362 this.createRollInterface_();
26ca7938 2363
0abfbd7e
DV
2364 // Same thing applies for the labelsDiv. It's right edge should be flush with
2365 // the right edge of the charting area (which may not be the same as the right
2366 // edge of the div, if we have two y-axes.
2367 this.positionLabelsDiv_();
2368
26ca7938
DV
2369 // If the data or options have changed, then we'd better redraw.
2370 this.drawGraph_();
2371};
2372
2373/**
2374 * Update the graph with new data. This method is called when the viewing area
2375 * has changed. If the underlying data or options have changed, predraw_ will
2376 * be called before drawGraph_ is called.
6a1aa64f
DV
2377 * @private
2378 */
26ca7938
DV
2379Dygraph.prototype.drawGraph_ = function() {
2380 var data = this.rawData_;
2381
fe0b7c03
DV
2382 // This is used to set the second parameter to drawCallback, below.
2383 var is_initial_draw = this.is_initial_draw_;
2384 this.is_initial_draw_ = false;
2385
3bd9c228 2386 var minY = null, maxY = null;
6a1aa64f 2387 this.layout_.removeAllDatasets();
285a6bda 2388 this.setColors_();
9317362d 2389 this.attrs_['pointSize'] = 0.5 * this.attr_('highlightCircleSize');
285a6bda 2390
354e15ab
DE
2391 // Loop over the fields (series). Go from the last to the first,
2392 // because if they're stacked that's how we accumulate the values.
43af96e7 2393
354e15ab
DE
2394 var cumulative_y = []; // For stacked series.
2395 var datasets = [];
2396
f09fc545
DV
2397 var extremes = {}; // series name -> [low, high]
2398
354e15ab
DE
2399 // Loop over all fields and create datasets
2400 for (var i = data[0].length - 1; i >= 1; i--) {
1cf11047
DV
2401 if (!this.visibility()[i - 1]) continue;
2402
f09fc545 2403 var seriesName = this.attr_("labels")[i];
450fe64b 2404 var connectSeparatedPoints = this.attr_('connectSeparatedPoints', i);
6e6a2b0a 2405 var logScale = this.attr_('logscale', i);
450fe64b 2406
6a1aa64f
DV
2407 var series = [];
2408 for (var j = 0; j < data.length; j++) {
6e6a2b0a
RK
2409 var date = data[j][0];
2410 var point = data[j][i];
2411 if (logScale) {
2412 // On the log scale, points less than zero do not exist.
2413 // This will create a gap in the chart. Note that this ignores
2414 // connectSeparatedPoints.
e863a17d 2415 if (point <= 0) {
6e6a2b0a
RK
2416 point = null;
2417 }
2418 series.push([date, point]);
2419 } else {
2420 if (point != null || !connectSeparatedPoints) {
2421 series.push([date, point]);
2422 }
f032c51d 2423 }
6a1aa64f 2424 }
2f5e7e1a
DV
2425
2426 // TODO(danvk): move this into predraw_. It's insane to do it here.
6a1aa64f
DV
2427 series = this.rollingAverage(series, this.rollPeriod_);
2428
2429 // Prune down to the desired range, if necessary (for zooming)
1a26f3fb
DV
2430 // Because there can be lines going to points outside of the visible area,
2431 // we actually prune to visible points, plus one on either side.
9922b78b 2432 var bars = this.attr_("errorBars") || this.attr_("customBars");
6a1aa64f
DV
2433 if (this.dateWindow_) {
2434 var low = this.dateWindow_[0];
2435 var high= this.dateWindow_[1];
2436 var pruned = [];
1a26f3fb
DV
2437 // TODO(danvk): do binary search instead of linear search.
2438 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
2439 var firstIdx = null, lastIdx = null;
6a1aa64f 2440 for (var k = 0; k < series.length; k++) {
1a26f3fb
DV
2441 if (series[k][0] >= low && firstIdx === null) {
2442 firstIdx = k;
2443 }
2444 if (series[k][0] <= high) {
2445 lastIdx = k;
6a1aa64f
DV
2446 }
2447 }
1a26f3fb
DV
2448 if (firstIdx === null) firstIdx = 0;
2449 if (firstIdx > 0) firstIdx--;
2450 if (lastIdx === null) lastIdx = series.length - 1;
2451 if (lastIdx < series.length - 1) lastIdx++;
16269f6e 2452 this.boundaryIds_[i-1] = [firstIdx, lastIdx];
1a26f3fb
DV
2453 for (var k = firstIdx; k <= lastIdx; k++) {
2454 pruned.push(series[k]);
6a1aa64f
DV
2455 }
2456 series = pruned;
16269f6e
NAG
2457 } else {
2458 this.boundaryIds_[i-1] = [0, series.length-1];
6a1aa64f
DV
2459 }
2460
f09fc545 2461 var seriesExtremes = this.extremeValues_(series);
5011e7a1 2462
6a1aa64f 2463 if (bars) {
354e15ab
DE
2464 for (var j=0; j<series.length; j++) {
2465 val = [series[j][0], series[j][1][0], series[j][1][1], series[j][1][2]];
2466 series[j] = val;
2467 }
43af96e7 2468 } else if (this.attr_("stackedGraph")) {
43af96e7
NK
2469 var l = series.length;
2470 var actual_y;
2471 for (var j = 0; j < l; j++) {
354e15ab
DE
2472 // If one data set has a NaN, let all subsequent stacked
2473 // sets inherit the NaN -- only start at 0 for the first set.
2474 var x = series[j][0];
41b0f691 2475 if (cumulative_y[x] === undefined) {
354e15ab 2476 cumulative_y[x] = 0;
41b0f691 2477 }
43af96e7
NK
2478
2479 actual_y = series[j][1];
354e15ab 2480 cumulative_y[x] += actual_y;
43af96e7 2481
354e15ab 2482 series[j] = [x, cumulative_y[x]]
43af96e7 2483
41b0f691
DV
2484 if (cumulative_y[x] > seriesExtremes[1]) {
2485 seriesExtremes[1] = cumulative_y[x];
2486 }
2487 if (cumulative_y[x] < seriesExtremes[0]) {
2488 seriesExtremes[0] = cumulative_y[x];
2489 }
43af96e7 2490 }
6a1aa64f 2491 }
41b0f691 2492 extremes[seriesName] = seriesExtremes;
354e15ab
DE
2493
2494 datasets[i] = series;
6a1aa64f
DV
2495 }
2496
354e15ab 2497 for (var i = 1; i < datasets.length; i++) {
4523c1f6 2498 if (!this.visibility()[i - 1]) continue;
354e15ab 2499 this.layout_.addDataset(this.attr_("labels")[i], datasets[i]);
43af96e7
NK
2500 }
2501
6faebb69
JB
2502 this.computeYAxisRanges_(extremes);
2503 this.layout_.updateOptions( { yAxes: this.axes_,
2504 seriesToAxisMap: this.seriesToAxisMap_
9012dd21 2505 } );
f09fc545 2506
6a1aa64f
DV
2507 this.addXTicks_();
2508
2509 // Tell PlotKit to use this new data and render itself
d033ae1c 2510 this.layout_.updateOptions({dateWindow: this.dateWindow_});
6a1aa64f
DV
2511 this.layout_.evaluateWithError();
2512 this.plotter_.clear();
2513 this.plotter_.render();
f6401bf6 2514 this.canvas_.getContext('2d').clearRect(0, 0, this.canvas_.width,
2f5e7e1a 2515 this.canvas_.height);
599fb4ad 2516
2fccd3dc
DV
2517 if (is_initial_draw) {
2518 // Generate a static legend before any particular point is selected.
2519 this.attr_('labelsDiv').innerHTML = this.generateLegendHTML_();
2520 }
2521
599fb4ad 2522 if (this.attr_("drawCallback") !== null) {
fe0b7c03 2523 this.attr_("drawCallback")(this, is_initial_draw);
599fb4ad 2524 }
6a1aa64f
DV
2525};
2526
2527/**
26ca7938
DV
2528 * Determine properties of the y-axes which are independent of the data
2529 * currently being displayed. This includes things like the number of axes and
2530 * the style of the axes. It does not include the range of each axis and its
2531 * tick marks.
2532 * This fills in this.axes_ and this.seriesToAxisMap_.
2533 * axes_ = [ { options } ]
2534 * seriesToAxisMap_ = { seriesName: 0, seriesName2: 1, ... }
2535 * indices are into the axes_ array.
f09fc545 2536 */
26ca7938 2537Dygraph.prototype.computeYAxes_ = function() {
00aa7f61 2538 this.axes_ = [{ yAxisId : 0, g : this }]; // always have at least one y-axis.
26ca7938
DV
2539 this.seriesToAxisMap_ = {};
2540
2541 // Get a list of series names.
2542 var labels = this.attr_("labels");
1c77a3a1 2543 var series = {};
26ca7938 2544 for (var i = 1; i < labels.length; i++) series[labels[i]] = (i - 1);
f09fc545
DV
2545
2546 // all options which could be applied per-axis:
2547 var axisOptions = [
2548 'includeZero',
2549 'valueRange',
2550 'labelsKMB',
2551 'labelsKMG2',
2552 'pixelsPerYLabel',
2553 'yAxisLabelWidth',
2554 'axisLabelFontSize',
7d0e7a0d
RK
2555 'axisTickSize',
2556 'logscale'
f09fc545
DV
2557 ];
2558
2559 // Copy global axis options over to the first axis.
2560 for (var i = 0; i < axisOptions.length; i++) {
2561 var k = axisOptions[i];
2562 var v = this.attr_(k);
26ca7938 2563 if (v) this.axes_[0][k] = v;
f09fc545
DV
2564 }
2565
2566 // Go through once and add all the axes.
26ca7938
DV
2567 for (var seriesName in series) {
2568 if (!series.hasOwnProperty(seriesName)) continue;
f09fc545
DV
2569 var axis = this.attr_("axis", seriesName);
2570 if (axis == null) {
26ca7938 2571 this.seriesToAxisMap_[seriesName] = 0;
f09fc545
DV
2572 continue;
2573 }
2574 if (typeof(axis) == 'object') {
2575 // Add a new axis, making a copy of its per-axis options.
2576 var opts = {};
26ca7938 2577 Dygraph.update(opts, this.axes_[0]);
f09fc545 2578 Dygraph.update(opts, { valueRange: null }); // shouldn't inherit this.
00aa7f61
RK
2579 var yAxisId = this.axes_.length;
2580 opts.yAxisId = yAxisId;
2581 opts.g = this;
f09fc545 2582 Dygraph.update(opts, axis);
26ca7938 2583 this.axes_.push(opts);
00aa7f61 2584 this.seriesToAxisMap_[seriesName] = yAxisId;
f09fc545
DV
2585 }
2586 }
2587
2588 // Go through one more time and assign series to an axis defined by another
2589 // series, e.g. { 'Y1: { axis: {} }, 'Y2': { axis: 'Y1' } }
26ca7938
DV
2590 for (var seriesName in series) {
2591 if (!series.hasOwnProperty(seriesName)) continue;
f09fc545
DV
2592 var axis = this.attr_("axis", seriesName);
2593 if (typeof(axis) == 'string') {
26ca7938 2594 if (!this.seriesToAxisMap_.hasOwnProperty(axis)) {
f09fc545
DV
2595 this.error("Series " + seriesName + " wants to share a y-axis with " +
2596 "series " + axis + ", which does not define its own axis.");
2597 return null;
2598 }
26ca7938
DV
2599 var idx = this.seriesToAxisMap_[axis];
2600 this.seriesToAxisMap_[seriesName] = idx;
f09fc545
DV
2601 }
2602 }
1c77a3a1
DV
2603
2604 // Now we remove series from seriesToAxisMap_ which are not visible. We do
2605 // this last so that hiding the first series doesn't destroy the axis
2606 // properties of the primary axis.
2607 var seriesToAxisFiltered = {};
2608 var vis = this.visibility();
2609 for (var i = 1; i < labels.length; i++) {
2610 var s = labels[i];
2611 if (vis[i - 1]) seriesToAxisFiltered[s] = this.seriesToAxisMap_[s];
2612 }
2613 this.seriesToAxisMap_ = seriesToAxisFiltered;
26ca7938
DV
2614};
2615
2616/**
2617 * Returns the number of y-axes on the chart.
2618 * @return {Number} the number of axes.
2619 */
2620Dygraph.prototype.numAxes = function() {
2621 var last_axis = 0;
2622 for (var series in this.seriesToAxisMap_) {
2623 if (!this.seriesToAxisMap_.hasOwnProperty(series)) continue;
2624 var idx = this.seriesToAxisMap_[series];
2625 if (idx > last_axis) last_axis = idx;
2626 }
2627 return 1 + last_axis;
2628};
2629
2630/**
2631 * Determine the value range and tick marks for each axis.
2632 * @param {Object} extremes A mapping from seriesName -> [low, high]
2633 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2634 */
2635Dygraph.prototype.computeYAxisRanges_ = function(extremes) {
2636 // Build a map from axis number -> [list of series names]
2637 var seriesForAxis = [];
2638 for (var series in this.seriesToAxisMap_) {
2639 if (!this.seriesToAxisMap_.hasOwnProperty(series)) continue;
2640 var idx = this.seriesToAxisMap_[series];
2641 while (seriesForAxis.length <= idx) seriesForAxis.push([]);
2642 seriesForAxis[idx].push(series);
2643 }
f09fc545 2644
1eb2feb3
DV
2645 // If no series are defined or visible then fill in some reasonable defaults.
2646 if (seriesForAxis.length == 0) {
2647 var axis = this.axes_[0];
2648 axis.computedValueRange = [0, 1];
2649 var ret =
2650 Dygraph.numericTicks(axis.computedValueRange[0],
2651 axis.computedValueRange[1],
2652 this,
2653 axis);
2654 axis.ticks = ret.ticks;
2655 this.numYDigits_ = ret.numDigits;
2656 return;
2657 }
2658
f09fc545 2659 // Compute extreme values, a span and tick marks for each axis.
26ca7938
DV
2660 for (var i = 0; i < this.axes_.length; i++) {
2661 var axis = this.axes_[i];
d58ae307
DV
2662 if (axis.valueWindow) {
2663 // This is only set if the user has zoomed on the y-axis. It is never set
2664 // by a user. It takes precedence over axis.valueRange because, if you set
2665 // valueRange, you'd still expect to be able to pan.
2666 axis.computedValueRange = [axis.valueWindow[0], axis.valueWindow[1]];
2667 } else if (axis.valueRange) {
2668 // This is a user-set value range for this axis.
26ca7938
DV
2669 axis.computedValueRange = [axis.valueRange[0], axis.valueRange[1]];
2670 } else {
1c77a3a1 2671 // Calculate the extremes of extremes.
f09fc545
DV
2672 var series = seriesForAxis[i];
2673 var minY = Infinity; // extremes[series[0]][0];
2674 var maxY = -Infinity; // extremes[series[0]][1];
2675 for (var j = 0; j < series.length; j++) {
2676 minY = Math.min(extremes[series[j]][0], minY);
e3b6727e 2677 maxY = Math.max(extremes[series[j]][1], maxY);
f09fc545
DV
2678 }
2679 if (axis.includeZero && minY > 0) minY = 0;
2680
2681 // Add some padding and round up to an integer to be human-friendly.
2682 var span = maxY - minY;
2683 // special case: if we have no sense of scale, use +/-10% of the sole value.
2684 if (span == 0) { span = maxY; }
f09fc545 2685
ff022deb
RK
2686 var maxAxisY;
2687 var minAxisY;
7d0e7a0d 2688 if (axis.logscale) {
ff022deb
RK
2689 var maxAxisY = maxY + 0.1 * span;
2690 var minAxisY = minY;
2691 } else {
2692 var maxAxisY = maxY + 0.1 * span;
2693 var minAxisY = minY - 0.1 * span;
f09fc545 2694
ff022deb
RK
2695 // Try to include zero and make it minAxisY (or maxAxisY) if it makes sense.
2696 if (!this.attr_("avoidMinZero")) {
2697 if (minAxisY < 0 && minY >= 0) minAxisY = 0;
2698 if (maxAxisY > 0 && maxY <= 0) maxAxisY = 0;
2699 }
f09fc545 2700
ff022deb
RK
2701 if (this.attr_("includeZero")) {
2702 if (maxY < 0) maxAxisY = 0;
2703 if (minY > 0) minAxisY = 0;
2704 }
f09fc545
DV
2705 }
2706
26ca7938 2707 axis.computedValueRange = [minAxisY, maxAxisY];
f09fc545
DV
2708 }
2709
0d64e596
DV
2710 // Add ticks. By default, all axes inherit the tick positions of the
2711 // primary axis. However, if an axis is specifically marked as having
2712 // independent ticks, then that is permissible as well.
2713 if (i == 0 || axis.independentTicks) {
3c1d225b 2714 var ret =
0d64e596
DV
2715 Dygraph.numericTicks(axis.computedValueRange[0],
2716 axis.computedValueRange[1],
2717 this,
2718 axis);
3c1d225b 2719 axis.ticks = ret.ticks;
6be8e54c 2720 this.numYDigits_ = ret.numDigits;
0d64e596
DV
2721 } else {
2722 var p_axis = this.axes_[0];
2723 var p_ticks = p_axis.ticks;
2724 var p_scale = p_axis.computedValueRange[1] - p_axis.computedValueRange[0];
2725 var scale = axis.computedValueRange[1] - axis.computedValueRange[0];
2726 var tick_values = [];
2727 for (var i = 0; i < p_ticks.length; i++) {
2728 var y_frac = (p_ticks[i].v - p_axis.computedValueRange[0]) / p_scale;
2729 var y_val = axis.computedValueRange[0] + y_frac * scale;
2730 tick_values.push(y_val);
2731 }
2732
3c1d225b 2733 var ret =
0d64e596
DV
2734 Dygraph.numericTicks(axis.computedValueRange[0],
2735 axis.computedValueRange[1],
2736 this, axis, tick_values);
3c1d225b 2737 axis.ticks = ret.ticks;
6be8e54c 2738 this.numYDigits_ = ret.numDigits;
0d64e596 2739 }
f09fc545 2740 }
f09fc545
DV
2741};
2742
2743/**
6a1aa64f
DV
2744 * Calculates the rolling average of a data set.
2745 * If originalData is [label, val], rolls the average of those.
2746 * If originalData is [label, [, it's interpreted as [value, stddev]
2747 * and the roll is returned in the same form, with appropriately reduced
2748 * stddev for each value.
2749 * Note that this is where fractional input (i.e. '5/10') is converted into
2750 * decimal values.
2751 * @param {Array} originalData The data in the appropriate format (see above)
6faebb69
JB
2752 * @param {Number} rollPeriod The number of points over which to average the
2753 * data
6a1aa64f 2754 */
285a6bda 2755Dygraph.prototype.rollingAverage = function(originalData, rollPeriod) {
6a1aa64f
DV
2756 if (originalData.length < 2)
2757 return originalData;
2758 var rollPeriod = Math.min(rollPeriod, originalData.length - 1);
2759 var rollingData = [];
285a6bda 2760 var sigma = this.attr_("sigma");
6a1aa64f
DV
2761
2762 if (this.fractions_) {
2763 var num = 0;
2764 var den = 0; // numerator/denominator
2765 var mult = 100.0;
2766 for (var i = 0; i < originalData.length; i++) {
2767 num += originalData[i][1][0];
2768 den += originalData[i][1][1];
2769 if (i - rollPeriod >= 0) {
2770 num -= originalData[i - rollPeriod][1][0];
2771 den -= originalData[i - rollPeriod][1][1];
2772 }
2773
2774 var date = originalData[i][0];
2775 var value = den ? num / den : 0.0;
285a6bda 2776 if (this.attr_("errorBars")) {
6a1aa64f
DV
2777 if (this.wilsonInterval_) {
2778 // For more details on this confidence interval, see:
2779 // http://en.wikipedia.org/wiki/Binomial_confidence_interval
2780 if (den) {
2781 var p = value < 0 ? 0 : value, n = den;
2782 var pm = sigma * Math.sqrt(p*(1-p)/n + sigma*sigma/(4*n*n));
2783 var denom = 1 + sigma * sigma / den;
2784 var low = (p + sigma * sigma / (2 * den) - pm) / denom;
2785 var high = (p + sigma * sigma / (2 * den) + pm) / denom;
2786 rollingData[i] = [date,
2787 [p * mult, (p - low) * mult, (high - p) * mult]];
2788 } else {
2789 rollingData[i] = [date, [0, 0, 0]];
2790 }
2791 } else {
2792 var stddev = den ? sigma * Math.sqrt(value * (1 - value) / den) : 1.0;
2793 rollingData[i] = [date, [mult * value, mult * stddev, mult * stddev]];
2794 }
2795 } else {
2796 rollingData[i] = [date, mult * value];
2797 }
2798 }
9922b78b 2799 } else if (this.attr_("customBars")) {
f6885d6a
DV
2800 var low = 0;
2801 var mid = 0;
2802 var high = 0;
2803 var count = 0;
6a1aa64f
DV
2804 for (var i = 0; i < originalData.length; i++) {
2805 var data = originalData[i][1];
2806 var y = data[1];
2807 rollingData[i] = [originalData[i][0], [y, y - data[0], data[2] - y]];
f6885d6a 2808
8b91c51f 2809 if (y != null && !isNaN(y)) {
49a7d0d5
DV
2810 low += data[0];
2811 mid += y;
2812 high += data[2];
2813 count += 1;
2814 }
f6885d6a
DV
2815 if (i - rollPeriod >= 0) {
2816 var prev = originalData[i - rollPeriod];
8b91c51f 2817 if (prev[1][1] != null && !isNaN(prev[1][1])) {
49a7d0d5
DV
2818 low -= prev[1][0];
2819 mid -= prev[1][1];
2820 high -= prev[1][2];
2821 count -= 1;
2822 }
f6885d6a
DV
2823 }
2824 rollingData[i] = [originalData[i][0], [ 1.0 * mid / count,
2825 1.0 * (mid - low) / count,
2826 1.0 * (high - mid) / count ]];
2769de62 2827 }
6a1aa64f
DV
2828 } else {
2829 // Calculate the rolling average for the first rollPeriod - 1 points where
6faebb69 2830 // there is not enough data to roll over the full number of points
6a1aa64f 2831 var num_init_points = Math.min(rollPeriod - 1, originalData.length - 2);
285a6bda 2832 if (!this.attr_("errorBars")){
5011e7a1
DV
2833 if (rollPeriod == 1) {
2834 return originalData;
2835 }
2836
2847c1cf 2837 for (var i = 0; i < originalData.length; i++) {
6a1aa64f 2838 var sum = 0;
5011e7a1 2839 var num_ok = 0;
2847c1cf
DV
2840 for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
2841 var y = originalData[j][1];
8b91c51f 2842 if (y == null || isNaN(y)) continue;
5011e7a1 2843 num_ok++;
2847c1cf 2844 sum += originalData[j][1];
6a1aa64f 2845 }
5011e7a1 2846 if (num_ok) {
2847c1cf 2847 rollingData[i] = [originalData[i][0], sum / num_ok];
5011e7a1 2848 } else {
2847c1cf 2849 rollingData[i] = [originalData[i][0], null];
5011e7a1 2850 }
6a1aa64f 2851 }
2847c1cf
DV
2852
2853 } else {
2854 for (var i = 0; i < originalData.length; i++) {
6a1aa64f
DV
2855 var sum = 0;
2856 var variance = 0;
5011e7a1 2857 var num_ok = 0;
2847c1cf 2858 for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
5011e7a1 2859 var y = originalData[j][1][0];
8b91c51f 2860 if (y == null || isNaN(y)) continue;
5011e7a1 2861 num_ok++;
6a1aa64f
DV
2862 sum += originalData[j][1][0];
2863 variance += Math.pow(originalData[j][1][1], 2);
2864 }
5011e7a1
DV
2865 if (num_ok) {
2866 var stddev = Math.sqrt(variance) / num_ok;
2867 rollingData[i] = [originalData[i][0],
2868 [sum / num_ok, sigma * stddev, sigma * stddev]];
2869 } else {
2870 rollingData[i] = [originalData[i][0], [null, null, null]];
2871 }
6a1aa64f
DV
2872 }
2873 }
2874 }
2875
2876 return rollingData;
2877};
2878
2879/**
2880 * Parses a date, returning the number of milliseconds since epoch. This can be
285a6bda
DV
2881 * passed in as an xValueParser in the Dygraph constructor.
2882 * TODO(danvk): enumerate formats that this understands.
6a1aa64f
DV
2883 * @param {String} A date in YYYYMMDD format.
2884 * @return {Number} Milliseconds since epoch.
2885 * @public
2886 */
285a6bda 2887Dygraph.dateParser = function(dateStr, self) {
6a1aa64f 2888 var dateStrSlashed;
285a6bda 2889 var d;
986a5026 2890 if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
6a1aa64f 2891 dateStrSlashed = dateStr.replace("-", "/", "g");
353a0294
DV
2892 while (dateStrSlashed.search("-") != -1) {
2893 dateStrSlashed = dateStrSlashed.replace("-", "/");
2894 }
285a6bda 2895 d = Date.parse(dateStrSlashed);
2769de62 2896 } else if (dateStr.length == 8) { // e.g. '20090712'
285a6bda 2897 // TODO(danvk): remove support for this format. It's confusing.
6a1aa64f
DV
2898 dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2)
2899 + "/" + dateStr.substr(6,2);
285a6bda 2900 d = Date.parse(dateStrSlashed);
2769de62
DV
2901 } else {
2902 // Any format that Date.parse will accept, e.g. "2009/07/12" or
2903 // "2009/07/12 12:34:56"
285a6bda
DV
2904 d = Date.parse(dateStr);
2905 }
2906
2907 if (!d || isNaN(d)) {
2908 self.error("Couldn't parse " + dateStr + " as a date");
2909 }
2910 return d;
2911};
2912
2913/**
2914 * Detects the type of the str (date or numeric) and sets the various
2915 * formatting attributes in this.attrs_ based on this type.
2916 * @param {String} str An x value.
2917 * @private
2918 */
2919Dygraph.prototype.detectTypeFromString_ = function(str) {
2920 var isDate = false;
ea62df82 2921 if (str.indexOf('-') > 0 ||
285a6bda
DV
2922 str.indexOf('/') >= 0 ||
2923 isNaN(parseFloat(str))) {
2924 isDate = true;
2925 } else if (str.length == 8 && str > '19700101' && str < '20371231') {
2926 // TODO(danvk): remove support for this format.
2927 isDate = true;
2928 }
2929
2930 if (isDate) {
2931 this.attrs_.xValueFormatter = Dygraph.dateString_;
2932 this.attrs_.xValueParser = Dygraph.dateParser;
2933 this.attrs_.xTicker = Dygraph.dateTicker;
bf640e56 2934 this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter;
285a6bda 2935 } else {
05a9ef8d 2936 this.attrs_.xValueFormatter = this.attrs_.yValueFormatter;
285a6bda
DV
2937 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
2938 this.attrs_.xTicker = Dygraph.numericTicks;
bf640e56 2939 this.attrs_.xAxisLabelFormatter = this.attrs_.xValueFormatter;
6a1aa64f 2940 }
6a1aa64f
DV
2941};
2942
2943/**
5cd7ac68
DV
2944 * Parses the value as a floating point number. This is like the parseFloat()
2945 * built-in, but with a few differences:
2946 * - the empty string is parsed as null, rather than NaN.
2947 * - if the string cannot be parsed at all, an error is logged.
2948 * If the string can't be parsed, this method returns null.
2949 * @param {String} x The string to be parsed
2950 * @param {Number} opt_line_no The line number from which the string comes.
2951 * @param {String} opt_line The text of the line from which the string comes.
2952 * @private
2953 */
2954
2955// Parse the x as a float or return null if it's not a number.
2956Dygraph.prototype.parseFloat_ = function(x, opt_line_no, opt_line) {
2957 var val = parseFloat(x);
2958 if (!isNaN(val)) return val;
2959
2960 // Try to figure out what happeend.
2961 // If the value is the empty string, parse it as null.
2962 if (/^ *$/.test(x)) return null;
2963
2964 // If it was actually "NaN", return it as NaN.
2965 if (/^ *nan *$/i.test(x)) return NaN;
2966
2967 // Looks like a parsing error.
2968 var msg = "Unable to parse '" + x + "' as a number";
2969 if (opt_line !== null && opt_line_no !== null) {
2970 msg += " on line " + (1+opt_line_no) + " ('" + opt_line + "') of CSV.";
2971 }
2972 this.error(msg);
2973
2974 return null;
2975};
2976
2977/**
6a1aa64f
DV
2978 * Parses a string in a special csv format. We expect a csv file where each
2979 * line is a date point, and the first field in each line is the date string.
2980 * We also expect that all remaining fields represent series.
285a6bda 2981 * if the errorBars attribute is set, then interpret the fields as:
6a1aa64f
DV
2982 * date, series1, stddev1, series2, stddev2, ...
2983 * @param {Array.<Object>} data See above.
2984 * @private
285a6bda
DV
2985 *
2986 * @return Array.<Object> An array with one entry for each row. These entries
2987 * are an array of cells in that row. The first entry is the parsed x-value for
2988 * the row. The second, third, etc. are the y-values. These can take on one of
2989 * three forms, depending on the CSV and constructor parameters:
2990 * 1. numeric value
2991 * 2. [ value, stddev ]
2992 * 3. [ low value, center value, high value ]
6a1aa64f 2993 */
285a6bda 2994Dygraph.prototype.parseCSV_ = function(data) {
6a1aa64f
DV
2995 var ret = [];
2996 var lines = data.split("\n");
3d67f03b
DV
2997
2998 // Use the default delimiter or fall back to a tab if that makes sense.
2999 var delim = this.attr_('delimiter');
3000 if (lines[0].indexOf(delim) == -1 && lines[0].indexOf('\t') >= 0) {
3001 delim = '\t';
3002 }
3003
285a6bda 3004 var start = 0;
6a1aa64f 3005 if (this.labelsFromCSV_) {
285a6bda 3006 start = 1;
3d67f03b 3007 this.attrs_.labels = lines[0].split(delim);
6a1aa64f 3008 }
5cd7ac68 3009 var line_no = 0;
03b522a4 3010
285a6bda
DV
3011 var xParser;
3012 var defaultParserSet = false; // attempt to auto-detect x value type
3013 var expectedCols = this.attr_("labels").length;
987840a2 3014 var outOfOrder = false;
6a1aa64f
DV
3015 for (var i = start; i < lines.length; i++) {
3016 var line = lines[i];
5cd7ac68 3017 line_no = i;
6a1aa64f 3018 if (line.length == 0) continue; // skip blank lines
3d67f03b
DV
3019 if (line[0] == '#') continue; // skip comment lines
3020 var inFields = line.split(delim);
285a6bda 3021 if (inFields.length < 2) continue;
6a1aa64f
DV
3022
3023 var fields = [];
285a6bda
DV
3024 if (!defaultParserSet) {
3025 this.detectTypeFromString_(inFields[0]);
3026 xParser = this.attr_("xValueParser");
3027 defaultParserSet = true;
3028 }
3029 fields[0] = xParser(inFields[0], this);
6a1aa64f
DV
3030
3031 // If fractions are expected, parse the numbers as "A/B"
3032 if (this.fractions_) {
3033 for (var j = 1; j < inFields.length; j++) {
3034 // TODO(danvk): figure out an appropriate way to flag parse errors.
3035 var vals = inFields[j].split("/");
7219edb3
DV
3036 if (vals.length != 2) {
3037 this.error('Expected fractional "num/den" values in CSV data ' +
3038 "but found a value '" + inFields[j] + "' on line " +
3039 (1 + i) + " ('" + line + "') which is not of this form.");
3040 fields[j] = [0, 0];
3041 } else {
3042 fields[j] = [this.parseFloat_(vals[0], i, line),
3043 this.parseFloat_(vals[1], i, line)];
3044 }
6a1aa64f 3045 }
285a6bda 3046 } else if (this.attr_("errorBars")) {
6a1aa64f 3047 // If there are error bars, values are (value, stddev) pairs
7219edb3
DV
3048 if (inFields.length % 2 != 1) {
3049 this.error('Expected alternating (value, stdev.) pairs in CSV data ' +
3050 'but line ' + (1 + i) + ' has an odd number of values (' +
3051 (inFields.length - 1) + "): '" + line + "'");
3052 }
3053 for (var j = 1; j < inFields.length; j += 2) {
5cd7ac68
DV
3054 fields[(j + 1) / 2] = [this.parseFloat_(inFields[j], i, line),
3055 this.parseFloat_(inFields[j + 1], i, line)];
7219edb3 3056 }
9922b78b 3057 } else if (this.attr_("customBars")) {
6a1aa64f
DV
3058 // Bars are a low;center;high tuple
3059 for (var j = 1; j < inFields.length; j++) {
3060 var vals = inFields[j].split(";");
5cd7ac68
DV
3061 fields[j] = [ this.parseFloat_(vals[0], i, line),
3062 this.parseFloat_(vals[1], i, line),
3063 this.parseFloat_(vals[2], i, line) ];
6a1aa64f
DV
3064 }
3065 } else {
3066 // Values are just numbers
285a6bda 3067 for (var j = 1; j < inFields.length; j++) {
5cd7ac68 3068 fields[j] = this.parseFloat_(inFields[j], i, line);
285a6bda 3069 }
6a1aa64f 3070 }
987840a2
DV
3071 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
3072 outOfOrder = true;
3073 }
285a6bda
DV
3074
3075 if (fields.length != expectedCols) {
3076 this.error("Number of columns in line " + i + " (" + fields.length +
3077 ") does not agree with number of labels (" + expectedCols +
3078 ") " + line);
3079 }
6d0aaa09
DV
3080
3081 // If the user specified the 'labels' option and none of the cells of the
3082 // first row parsed correctly, then they probably double-specified the
3083 // labels. We go with the values set in the option, discard this row and
3084 // log a warning to the JS console.
3085 if (i == 0 && this.attr_('labels')) {
3086 var all_null = true;
3087 for (var j = 0; all_null && j < fields.length; j++) {
3088 if (fields[j]) all_null = false;
3089 }
3090 if (all_null) {
3091 this.warn("The dygraphs 'labels' option is set, but the first row of " +
3092 "CSV data ('" + line + "') appears to also contain labels. " +
3093 "Will drop the CSV labels and use the option labels.");
3094 continue;
3095 }
3096 }
3097 ret.push(fields);
6a1aa64f 3098 }
987840a2
DV
3099
3100 if (outOfOrder) {
3101 this.warn("CSV is out of order; order it correctly to speed loading.");
3102 ret.sort(function(a,b) { return a[0] - b[0] });
3103 }
3104
6a1aa64f
DV
3105 return ret;
3106};
3107
3108/**
285a6bda
DV
3109 * The user has provided their data as a pre-packaged JS array. If the x values
3110 * are numeric, this is the same as dygraphs' internal format. If the x values
3111 * are dates, we need to convert them from Date objects to ms since epoch.
3112 * @param {Array.<Object>} data
3113 * @return {Array.<Object>} data with numeric x values.
3114 */
3115Dygraph.prototype.parseArray_ = function(data) {
3116 // Peek at the first x value to see if it's numeric.
3117 if (data.length == 0) {
3118 this.error("Can't plot empty data set");
3119 return null;
3120 }
3121 if (data[0].length == 0) {
3122 this.error("Data set cannot contain an empty row");
3123 return null;
3124 }
3125
3126 if (this.attr_("labels") == null) {
3127 this.warn("Using default labels. Set labels explicitly via 'labels' " +
3128 "in the options parameter");
3129 this.attrs_.labels = [ "X" ];
3130 for (var i = 1; i < data[0].length; i++) {
3131 this.attrs_.labels.push("Y" + i);
3132 }
3133 }
3134
2dda3850 3135 if (Dygraph.isDateLike(data[0][0])) {
285a6bda
DV
3136 // Some intelligent defaults for a date x-axis.
3137 this.attrs_.xValueFormatter = Dygraph.dateString_;
bf640e56 3138 this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter;
285a6bda
DV
3139 this.attrs_.xTicker = Dygraph.dateTicker;
3140
3141 // Assume they're all dates.
e3ab7b40 3142 var parsedData = Dygraph.clone(data);
285a6bda
DV
3143 for (var i = 0; i < data.length; i++) {
3144 if (parsedData[i].length == 0) {
a323ff4a 3145 this.error("Row " + (1 + i) + " of data is empty");
285a6bda
DV
3146 return null;
3147 }
3148 if (parsedData[i][0] == null
3a909ec5
DV
3149 || typeof(parsedData[i][0].getTime) != 'function'
3150 || isNaN(parsedData[i][0].getTime())) {
be96a1f5 3151 this.error("x value in row " + (1 + i) + " is not a Date");
285a6bda
DV
3152 return null;
3153 }
3154 parsedData[i][0] = parsedData[i][0].getTime();
3155 }
3156 return parsedData;
3157 } else {
3158 // Some intelligent defaults for a numeric x-axis.
6be8e54c 3159 this.attrs_.xValueFormatter = this.attrs_.yValueFormatter;
285a6bda
DV
3160 this.attrs_.xTicker = Dygraph.numericTicks;
3161 return data;
3162 }
3163};
3164
3165/**
79420a1e
DV
3166 * Parses a DataTable object from gviz.
3167 * The data is expected to have a first column that is either a date or a
3168 * number. All subsequent columns must be numbers. If there is a clear mismatch
3169 * between this.xValueParser_ and the type of the first column, it will be
a685723c 3170 * fixed. Fills out rawData_.
79420a1e
DV
3171 * @param {Array.<Object>} data See above.
3172 * @private
3173 */
285a6bda 3174Dygraph.prototype.parseDataTable_ = function(data) {
79420a1e
DV
3175 var cols = data.getNumberOfColumns();
3176 var rows = data.getNumberOfRows();
3177
d955e223 3178 var indepType = data.getColumnType(0);
4440f6c8 3179 if (indepType == 'date' || indepType == 'datetime') {
285a6bda
DV
3180 this.attrs_.xValueFormatter = Dygraph.dateString_;
3181 this.attrs_.xValueParser = Dygraph.dateParser;
3182 this.attrs_.xTicker = Dygraph.dateTicker;
bf640e56 3183 this.attrs_.xAxisLabelFormatter = Dygraph.dateAxisFormatter;
33127159 3184 } else if (indepType == 'number') {
6be8e54c 3185 this.attrs_.xValueFormatter = this.attrs_.yValueFormatter;
285a6bda
DV
3186 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
3187 this.attrs_.xTicker = Dygraph.numericTicks;
bf640e56 3188 this.attrs_.xAxisLabelFormatter = this.attrs_.xValueFormatter;
285a6bda 3189 } else {
987840a2
DV
3190 this.error("only 'date', 'datetime' and 'number' types are supported for " +
3191 "column 1 of DataTable input (Got '" + indepType + "')");
79420a1e
DV
3192 return null;
3193 }
3194
a685723c
DV
3195 // Array of the column indices which contain data (and not annotations).
3196 var colIdx = [];
3197 var annotationCols = {}; // data index -> [annotation cols]
3198 var hasAnnotations = false;
3199 for (var i = 1; i < cols; i++) {
3200 var type = data.getColumnType(i);
3201 if (type == 'number') {
3202 colIdx.push(i);
3203 } else if (type == 'string' && this.attr_('displayAnnotations')) {
3204 // This is OK -- it's an annotation column.
3205 var dataIdx = colIdx[colIdx.length - 1];
3206 if (!annotationCols.hasOwnProperty(dataIdx)) {
3207 annotationCols[dataIdx] = [i];
3208 } else {
3209 annotationCols[dataIdx].push(i);
3210 }
3211 hasAnnotations = true;
3212 } else {
3213 this.error("Only 'number' is supported as a dependent type with Gviz." +
3214 " 'string' is only supported if displayAnnotations is true");
3215 }
3216 }
3217
3218 // Read column labels
3219 // TODO(danvk): add support back for errorBars
3220 var labels = [data.getColumnLabel(0)];
3221 for (var i = 0; i < colIdx.length; i++) {
3222 labels.push(data.getColumnLabel(colIdx[i]));
f9348814 3223 if (this.attr_("errorBars")) i += 1;
a685723c
DV
3224 }
3225 this.attrs_.labels = labels;
3226 cols = labels.length;
3227
79420a1e 3228 var ret = [];
987840a2 3229 var outOfOrder = false;
a685723c 3230 var annotations = [];
79420a1e
DV
3231 for (var i = 0; i < rows; i++) {
3232 var row = [];
debe4434
DV
3233 if (typeof(data.getValue(i, 0)) === 'undefined' ||
3234 data.getValue(i, 0) === null) {
129569a5
FD
3235 this.warn("Ignoring row " + i +
3236 " of DataTable because of undefined or null first column.");
debe4434
DV
3237 continue;
3238 }
3239
c21d2c2d 3240 if (indepType == 'date' || indepType == 'datetime') {
d955e223
DV
3241 row.push(data.getValue(i, 0).getTime());
3242 } else {
3243 row.push(data.getValue(i, 0));
3244 }
3e3f84e4 3245 if (!this.attr_("errorBars")) {
a685723c
DV
3246 for (var j = 0; j < colIdx.length; j++) {
3247 var col = colIdx[j];
3248 row.push(data.getValue(i, col));
3249 if (hasAnnotations &&
3250 annotationCols.hasOwnProperty(col) &&
3251 data.getValue(i, annotationCols[col][0]) != null) {
3252 var ann = {};
3253 ann.series = data.getColumnLabel(col);
3254 ann.xval = row[0];
3255 ann.shortText = String.fromCharCode(65 /* A */ + annotations.length)
3256 ann.text = '';
3257 for (var k = 0; k < annotationCols[col].length; k++) {
3258 if (k) ann.text += "\n";
3259 ann.text += data.getValue(i, annotationCols[col][k]);
3260 }
3261 annotations.push(ann);
3262 }
3e3f84e4 3263 }
92fd68d8
DV
3264
3265 // Strip out infinities, which give dygraphs problems later on.
3266 for (var j = 0; j < row.length; j++) {
3267 if (!isFinite(row[j])) row[j] = null;
3268 }
3e3f84e4
DV
3269 } else {
3270 for (var j = 0; j < cols - 1; j++) {
3271 row.push([ data.getValue(i, 1 + 2 * j), data.getValue(i, 2 + 2 * j) ]);
3272 }
79420a1e 3273 }
987840a2
DV
3274 if (ret.length > 0 && row[0] < ret[ret.length - 1][0]) {
3275 outOfOrder = true;
3276 }
243d96e8 3277 ret.push(row);
79420a1e 3278 }
987840a2
DV
3279
3280 if (outOfOrder) {
3281 this.warn("DataTable is out of order; order it correctly to speed loading.");
3282 ret.sort(function(a,b) { return a[0] - b[0] });
3283 }
a685723c
DV
3284 this.rawData_ = ret;
3285
3286 if (annotations.length > 0) {
3287 this.setAnnotations(annotations, true);
3288 }
79420a1e
DV
3289}
3290
24e5350c 3291// These functions are all based on MochiKit.
fc80a396
DV
3292Dygraph.update = function (self, o) {
3293 if (typeof(o) != 'undefined' && o !== null) {
3294 for (var k in o) {
85b99f0b
DV
3295 if (o.hasOwnProperty(k)) {
3296 self[k] = o[k];
3297 }
fc80a396
DV
3298 }
3299 }
3300 return self;
3301};
3302
2dda3850
DV
3303Dygraph.isArrayLike = function (o) {
3304 var typ = typeof(o);
3305 if (
c21d2c2d 3306 (typ != 'object' && !(typ == 'function' &&
2dda3850
DV
3307 typeof(o.item) == 'function')) ||
3308 o === null ||
3309 typeof(o.length) != 'number' ||
3310 o.nodeType === 3
3311 ) {
3312 return false;
3313 }
3314 return true;
3315};
3316
3317Dygraph.isDateLike = function (o) {
3318 if (typeof(o) != "object" || o === null ||
3319 typeof(o.getTime) != 'function') {
3320 return false;
3321 }
3322 return true;
3323};
3324
e3ab7b40
DV
3325Dygraph.clone = function(o) {
3326 // TODO(danvk): figure out how MochiKit's version works
3327 var r = [];
3328 for (var i = 0; i < o.length; i++) {
3329 if (Dygraph.isArrayLike(o[i])) {
3330 r.push(Dygraph.clone(o[i]));
3331 } else {
3332 r.push(o[i]);
3333 }
3334 }
3335 return r;
24e5350c
DV
3336};
3337
2dda3850 3338
79420a1e 3339/**
6a1aa64f
DV
3340 * Get the CSV data. If it's in a function, call that function. If it's in a
3341 * file, do an XMLHttpRequest to get it.
3342 * @private
3343 */
285a6bda 3344Dygraph.prototype.start_ = function() {
6a1aa64f 3345 if (typeof this.file_ == 'function') {
285a6bda 3346 // CSV string. Pretend we got it via XHR.
6a1aa64f 3347 this.loadedEvent_(this.file_());
2dda3850 3348 } else if (Dygraph.isArrayLike(this.file_)) {
285a6bda 3349 this.rawData_ = this.parseArray_(this.file_);
26ca7938 3350 this.predraw_();
79420a1e
DV
3351 } else if (typeof this.file_ == 'object' &&
3352 typeof this.file_.getColumnRange == 'function') {
3353 // must be a DataTable from gviz.
a685723c 3354 this.parseDataTable_(this.file_);
26ca7938 3355 this.predraw_();
285a6bda
DV
3356 } else if (typeof this.file_ == 'string') {
3357 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
3358 if (this.file_.indexOf('\n') >= 0) {
3359 this.loadedEvent_(this.file_);
3360 } else {
3361 var req = new XMLHttpRequest();
3362 var caller = this;
3363 req.onreadystatechange = function () {
3364 if (req.readyState == 4) {
3365 if (req.status == 200) {
3366 caller.loadedEvent_(req.responseText);
3367 }
6a1aa64f 3368 }
285a6bda 3369 };
6a1aa64f 3370
285a6bda
DV
3371 req.open("GET", this.file_, true);
3372 req.send(null);
3373 }
3374 } else {
3375 this.error("Unknown data format: " + (typeof this.file_));
6a1aa64f
DV
3376 }
3377};
3378
3379/**
3380 * Changes various properties of the graph. These can include:
3381 * <ul>
3382 * <li>file: changes the source data for the graph</li>
3383 * <li>errorBars: changes whether the data contains stddev</li>
3384 * </ul>
3385 * @param {Object} attrs The new properties and values
3386 */
285a6bda
DV
3387Dygraph.prototype.updateOptions = function(attrs) {
3388 // TODO(danvk): this is a mess. Rethink this function.
c65f2303 3389 if ('rollPeriod' in attrs) {
6a1aa64f
DV
3390 this.rollPeriod_ = attrs.rollPeriod;
3391 }
c65f2303 3392 if ('dateWindow' in attrs) {
6a1aa64f
DV
3393 this.dateWindow_ = attrs.dateWindow;
3394 }
450fe64b
DV
3395
3396 // TODO(danvk): validate per-series options.
46dde5f9
DV
3397 // Supported:
3398 // strokeWidth
3399 // pointSize
3400 // drawPoints
3401 // highlightCircleSize
450fe64b 3402
fc80a396 3403 Dygraph.update(this.user_attrs_, attrs);
87bb7958 3404 Dygraph.update(this.renderOptions_, attrs);
285a6bda
DV
3405
3406 this.labelsFromCSV_ = (this.attr_("labels") == null);
3407
3408 // TODO(danvk): this doesn't match the constructor logic
3409 this.layout_.updateOptions({ 'errorBars': this.attr_("errorBars") });
5e50289f 3410 if (attrs['file']) {
6a1aa64f
DV
3411 this.file_ = attrs['file'];
3412 this.start_();
3413 } else {
26ca7938 3414 this.predraw_();
6a1aa64f
DV
3415 }
3416};
3417
3418/**
697e70b2
DV
3419 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3420 * containing div (which has presumably changed size since the dygraph was
3421 * instantiated. If the width/height are specified, the div will be resized.
964f30c6
DV
3422 *
3423 * This is far more efficient than destroying and re-instantiating a
3424 * Dygraph, since it doesn't have to reparse the underlying data.
3425 *
697e70b2
DV
3426 * @param {Number} width Width (in pixels)
3427 * @param {Number} height Height (in pixels)
3428 */
3429Dygraph.prototype.resize = function(width, height) {
e8c7ef86
DV
3430 if (this.resize_lock) {
3431 return;
3432 }
3433 this.resize_lock = true;
3434
697e70b2
DV
3435 if ((width === null) != (height === null)) {
3436 this.warn("Dygraph.resize() should be called with zero parameters or " +
3437 "two non-NULL parameters. Pretending it was zero.");
3438 width = height = null;
3439 }
3440
b16e6369 3441 // TODO(danvk): there should be a clear() method.
697e70b2 3442 this.maindiv_.innerHTML = "";
b16e6369
DV
3443 this.attrs_.labelsDiv = null;
3444
697e70b2
DV
3445 if (width) {
3446 this.maindiv_.style.width = width + "px";
3447 this.maindiv_.style.height = height + "px";
3448 this.width_ = width;
3449 this.height_ = height;
3450 } else {
3451 this.width_ = this.maindiv_.offsetWidth;
3452 this.height_ = this.maindiv_.offsetHeight;
3453 }
3454
3455 this.createInterface_();
26ca7938 3456 this.predraw_();
e8c7ef86
DV
3457
3458 this.resize_lock = false;
697e70b2
DV
3459};
3460
3461/**
6faebb69 3462 * Adjusts the number of points in the rolling average. Updates the graph to
6a1aa64f 3463 * reflect the new averaging period.
6faebb69 3464 * @param {Number} length Number of points over which to average the data.
6a1aa64f 3465 */
285a6bda 3466Dygraph.prototype.adjustRoll = function(length) {
6a1aa64f 3467 this.rollPeriod_ = length;
26ca7938 3468 this.predraw_();
6a1aa64f 3469};
540d00f1 3470
f8cfec73 3471/**
1cf11047
DV
3472 * Returns a boolean array of visibility statuses.
3473 */
3474Dygraph.prototype.visibility = function() {
3475 // Do lazy-initialization, so that this happens after we know the number of
3476 // data series.
3477 if (!this.attr_("visibility")) {
f38dec01 3478 this.attrs_["visibility"] = [];
1cf11047
DV
3479 }
3480 while (this.attr_("visibility").length < this.rawData_[0].length - 1) {
f38dec01 3481 this.attr_("visibility").push(true);
1cf11047
DV
3482 }
3483 return this.attr_("visibility");
3484};
3485
3486/**
3487 * Changes the visiblity of a series.
3488 */
3489Dygraph.prototype.setVisibility = function(num, value) {
3490 var x = this.visibility();
a6c109c1 3491 if (num < 0 || num >= x.length) {
1cf11047
DV
3492 this.warn("invalid series number in setVisibility: " + num);
3493 } else {
3494 x[num] = value;
26ca7938 3495 this.predraw_();
1cf11047
DV
3496 }
3497};
3498
3499/**
5c528fa2
DV
3500 * Update the list of annotations and redraw the chart.
3501 */
a685723c 3502Dygraph.prototype.setAnnotations = function(ann, suppressDraw) {
3c51ab74
DV
3503 // Only add the annotation CSS rule once we know it will be used.
3504 Dygraph.addAnnotationRule();
5c528fa2
DV
3505 this.annotations_ = ann;
3506 this.layout_.setAnnotations(this.annotations_);
a685723c 3507 if (!suppressDraw) {
26ca7938 3508 this.predraw_();
a685723c 3509 }
5c528fa2
DV
3510};
3511
3512/**
3513 * Return the list of annotations.
3514 */
3515Dygraph.prototype.annotations = function() {
3516 return this.annotations_;
3517};
3518
46dde5f9
DV
3519/**
3520 * Get the index of a series (column) given its name. The first column is the
3521 * x-axis, so the data series start with index 1.
3522 */
3523Dygraph.prototype.indexFromSetName = function(name) {
3524 var labels = this.attr_("labels");
3525 for (var i = 0; i < labels.length; i++) {
3526 if (labels[i] == name) return i;
3527 }
3528 return null;
3529};
3530
5c528fa2
DV
3531Dygraph.addAnnotationRule = function() {
3532 if (Dygraph.addedAnnotationCSS) return;
3533
5c528fa2
DV
3534 var rule = "border: 1px solid black; " +
3535 "background-color: white; " +
3536 "text-align: center;";
22186871
DV
3537
3538 var styleSheetElement = document.createElement("style");
3539 styleSheetElement.type = "text/css";
3540 document.getElementsByTagName("head")[0].appendChild(styleSheetElement);
3541
3542 // Find the first style sheet that we can access.
3543 // We may not add a rule to a style sheet from another domain for security
3544 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3545 // adds its own style sheets from google.com.
3546 for (var i = 0; i < document.styleSheets.length; i++) {
3547 if (document.styleSheets[i].disabled) continue;
3548 var mysheet = document.styleSheets[i];
3549 try {
3550 if (mysheet.insertRule) { // Firefox
3551 var idx = mysheet.cssRules ? mysheet.cssRules.length : 0;
3552 mysheet.insertRule(".dygraphDefaultAnnotation { " + rule + " }", idx);
3553 } else if (mysheet.addRule) { // IE
3554 mysheet.addRule(".dygraphDefaultAnnotation", rule);
3555 }
3556 Dygraph.addedAnnotationCSS = true;
3557 return;
3558 } catch(err) {
3559 // Was likely a security exception.
3560 }
5c528fa2
DV
3561 }
3562
22186871 3563 this.warn("Unable to add default annotation CSS rule; display may be off.");
5c528fa2
DV
3564}
3565
3566/**
f8cfec73
DV
3567 * Create a new canvas element. This is more complex than a simple
3568 * document.createElement("canvas") because of IE and excanvas.
3569 */
3570Dygraph.createCanvas = function() {
3571 var canvas = document.createElement("canvas");
3572
3573 isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
8b8f2d59 3574 if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) {
f8cfec73
DV
3575 canvas = G_vmlCanvasManager.initElement(canvas);
3576 }
3577
3578 return canvas;
3579};
3580
540d00f1
DV
3581
3582/**
285a6bda 3583 * A wrapper around Dygraph that implements the gviz API.
540d00f1
DV
3584 * @param {Object} container The DOM object the visualization should live in.
3585 */
285a6bda 3586Dygraph.GVizChart = function(container) {
540d00f1
DV
3587 this.container = container;
3588}
3589
285a6bda 3590Dygraph.GVizChart.prototype.draw = function(data, options) {
c91f4ae8
DV
3591 // Clear out any existing dygraph.
3592 // TODO(danvk): would it make more sense to simply redraw using the current
3593 // date_graph object?
540d00f1 3594 this.container.innerHTML = '';
c91f4ae8
DV
3595 if (typeof(this.date_graph) != 'undefined') {
3596 this.date_graph.destroy();
3597 }
3598
285a6bda 3599 this.date_graph = new Dygraph(this.container, data, options);
540d00f1 3600}
285a6bda 3601
239c712d
NAG
3602/**
3603 * Google charts compatible setSelection
50360fd0 3604 * Only row selection is supported, all points in the row will be highlighted
239c712d
NAG
3605 * @param {Array} array of the selected cells
3606 * @public
3607 */
3608Dygraph.GVizChart.prototype.setSelection = function(selection_array) {
3609 var row = false;
3610 if (selection_array.length) {
3611 row = selection_array[0].row;
3612 }
3613 this.date_graph.setSelection(row);
3614}
3615
103b7292
NAG
3616/**
3617 * Google charts compatible getSelection implementation
3618 * @return {Array} array of the selected cells
3619 * @public
3620 */
3621Dygraph.GVizChart.prototype.getSelection = function() {
3622 var selection = [];
50360fd0 3623
103b7292 3624 var row = this.date_graph.getSelection();
50360fd0 3625
103b7292 3626 if (row < 0) return selection;
50360fd0 3627
103b7292
NAG
3628 col = 1;
3629 for (var i in this.date_graph.layout_.datasets) {
3630 selection.push({row: row, column: col});
3631 col++;
3632 }
3633
3634 return selection;
3635}
3636
285a6bda
DV
3637// Older pages may still use this name.
3638DateGraph = Dygraph;
028ddf8a
DV
3639
3640// <REMOVE_FOR_COMBINED>
0addac07
DV
3641Dygraph.OPTIONS_REFERENCE = // <JSON>
3642{
a38e9336
DV
3643 "xValueParser": {
3644 "default": "parseFloat() or Date.parse()*",
3645 "labels": ["CSV parsing"],
3646 "type": "function(str) -> number",
3647 "description": "A function which parses x-values (i.e. the dependent series). Must return a number, even when the values are dates. In this case, millis since epoch are used. This is used primarily for parsing CSV data. *=Dygraphs is slightly more accepting in the dates which it will parse. See code for details."
3648 },
3649 "stackedGraph": {
a96f59f4 3650 "default": "false",
a38e9336
DV
3651 "labels": ["Data Line display"],
3652 "type": "boolean",
3653 "description": "If set, stack series on top of one another rather than drawing them independently."
a96f59f4 3654 },
a38e9336 3655 "pointSize": {
a96f59f4 3656 "default": "1",
a38e9336
DV
3657 "labels": ["Data Line display"],
3658 "type": "integer",
3659 "description": "The size of the dot to draw on each point in pixels (see drawPoints). A dot is always drawn when a point is \"isolated\", i.e. there is a missing point on either side of it. This also controls the size of those dots."
a96f59f4 3660 },
a38e9336
DV
3661 "labelsDivStyles": {
3662 "default": "null",
3663 "labels": ["Legend"],
3664 "type": "{}",
3665 "description": "Additional styles to apply to the currently-highlighted points div. For example, { 'font-weight': 'bold' } will make the labels bold."
a96f59f4 3666 },
a38e9336 3667 "drawPoints": {
a96f59f4 3668 "default": "false",
a38e9336
DV
3669 "labels": ["Data Line display"],
3670 "type": "boolean",
3671 "description": "Draw a small dot at each point, in addition to a line going through the point. This makes the individual data points easier to see, but can increase visual clutter in the chart."
a96f59f4 3672 },
a38e9336
DV
3673 "height": {
3674 "default": "320",
3675 "labels": ["Overall display"],
3676 "type": "integer",
3677 "description": "Height, in pixels, of the chart. If the container div has been explicitly sized, this will be ignored."
a96f59f4
DV
3678 },
3679 "zoomCallback": {
a96f59f4 3680 "default": "null",
a38e9336
DV
3681 "labels": ["Callbacks"],
3682 "type": "function(minDate, maxDate, yRanges)",
a96f59f4
DV
3683 "description": "A function to call when the zoom window is changed (either by zooming in or out). minDate and maxDate are milliseconds since epoch. yRanges is an array of [bottom, top] pairs, one for each y-axis."
3684 },
a38e9336
DV
3685 "pointClickCallback": {
3686 "default": "",
3687 "labels": ["Callbacks", "Interactive Elements"],
3688 "type": "",
3689 "description": ""
a96f59f4 3690 },
a38e9336
DV
3691 "colors": {
3692 "default": "(see description)",
3693 "labels": ["Data Series Colors"],
3694 "type": "array<string>",
3695 "example": "['red', '#00FF00']",
3696 "description": "List of colors for the data series. These can be of the form \"#AABBCC\" or \"rgb(255,100,200)\" or \"yellow\", etc. If not specified, equally-spaced points around a color wheel are used."
a96f59f4 3697 },
a38e9336 3698 "connectSeparatedPoints": {
a96f59f4 3699 "default": "false",
a38e9336
DV
3700 "labels": ["Data Line display"],
3701 "type": "boolean",
3702 "description": "Usually, when Dygraphs encounters a missing value in a data series, it interprets this as a gap and draws it as such. If, instead, the missing values represents an x-value for which only a different series has data, then you'll want to connect the dots by setting this to true. To explicitly include a gap with this option set, use a value of NaN."
a96f59f4 3703 },
a38e9336 3704 "highlightCallback": {
a96f59f4 3705 "default": "null",
a38e9336
DV
3706 "labels": ["Callbacks"],
3707 "type": "function(event, x, points,row)",
3708 "description": "When set, this callback gets called every time a new point is highlighted. The parameters are the JavaScript mousemove event, the x-coordinate of the highlighted points and an array of highlighted points: <code>[ {name: 'series', yval: y-value}, &hellip; ]</code>"
a96f59f4 3709 },
a38e9336 3710 "includeZero": {
a96f59f4 3711 "default": "false",
a38e9336 3712 "labels": ["Axis display"],
a96f59f4 3713 "type": "boolean",
a38e9336 3714 "description": "Usually, dygraphs will use the range of the data plus some padding to set the range of the y-axis. If this option is set, the y-axis will always include zero, typically as the lowest value. This can be used to avoid exaggerating the variance in the data"
a96f59f4 3715 },
a38e9336
DV
3716 "rollPeriod": {
3717 "default": "1",
3718 "labels": ["Error Bars", "Rolling Averages"],
3719 "type": "integer &gt;= 1",
3720 "description": "Number of days over which to average data. Discussed extensively above."
a96f59f4 3721 },
a38e9336 3722 "unhighlightCallback": {
a96f59f4 3723 "default": "null",
a38e9336
DV
3724 "labels": ["Callbacks"],
3725 "type": "function(event)",
3726 "description": "When set, this callback gets called every time the user stops highlighting any point by mousing out of the graph. The parameter is the mouseout event."
a96f59f4 3727 },
a38e9336
DV
3728 "axisTickSize": {
3729 "default": "3.0",
3730 "labels": ["Axis display"],
3731 "type": "number",
3732 "description": "The size of the line to display next to each tick mark on x- or y-axes."
a96f59f4 3733 },
a38e9336 3734 "labelsSeparateLines": {
a96f59f4 3735 "default": "false",
a38e9336
DV
3736 "labels": ["Legend"],
3737 "type": "boolean",
3738 "description": "Put <code>&lt;br/&gt;</code> between lines in the label string. Often used in conjunction with <strong>labelsDiv</strong>."
a96f59f4 3739 },
a38e9336
DV
3740 "xValueFormatter": {
3741 "default": "(Round to 2 decimal places)",
3742 "labels": ["Axis display"],
3743 "type": "function(x)",
3744 "description": "Function to provide a custom display format for the X value for mouseover."
a96f59f4
DV
3745 },
3746 "pixelsPerYLabel": {
a96f59f4 3747 "default": "30",
a38e9336
DV
3748 "labels": ["Axis display", "Grid"],
3749 "type": "integer",
a96f59f4
DV
3750 "description": "Number of pixels to require between each x- and y-label. Larger values will yield a sparser axis with fewer ticks."
3751 },
a38e9336 3752 "annotationMouseOverHandler": {
5cc5f631 3753 "default": "null",
a38e9336 3754 "labels": ["Annotations"],
5cc5f631
DV
3755 "type": "function(annotation, point, dygraph, event)",
3756 "description": "If provided, this function is called whenever the user mouses over an annotation."
3757 },
3758 "annotationMouseOutHandler": {
3759 "default": "null",
3760 "labels": ["Annotations"],
3761 "type": "function(annotation, point, dygraph, event)",
3762 "description": "If provided, this function is called whenever the user mouses out of an annotation."
a96f59f4 3763 },
8165189e 3764 "annotationClickHandler": {
5cc5f631 3765 "default": "null",
8165189e 3766 "labels": ["Annotations"],
5cc5f631
DV
3767 "type": "function(annotation, point, dygraph, event)",
3768 "description": "If provided, this function is called whenever the user clicks on an annotation."
8165189e
DV
3769 },
3770 "annotationDblClickHandler": {
5cc5f631 3771 "default": "null",
8165189e 3772 "labels": ["Annotations"],
5cc5f631
DV
3773 "type": "function(annotation, point, dygraph, event)",
3774 "description": "If provided, this function is called whenever the user double-clicks on an annotation."
8165189e 3775 },
a38e9336
DV
3776 "drawCallback": {
3777 "default": "null",
3778 "labels": ["Callbacks"],
3779 "type": "function(dygraph, is_initial)",
3780 "description": "When set, this callback gets called every time the dygraph is drawn. This includes the initial draw, after zooming and repeatedly while panning. The first parameter is the dygraph being drawn. The second is a boolean value indicating whether this is the initial draw."
3781 },
3782 "labelsKMG2": {
3783 "default": "false",
3784 "labels": ["Value display/formatting"],
3785 "type": "boolean",
3786 "description": "Show k/M/G for kilo/Mega/Giga on y-axis. This is different than <code>labelsKMB</code> in that it uses base 2, not 10."
3787 },
3788 "delimiter": {
3789 "default": ",",
3790 "labels": ["CSV parsing"],
3791 "type": "string",
3792 "description": "The delimiter to look for when separating fields of a CSV file. Setting this to a tab is not usually necessary, since tab-delimited data is auto-detected."
a96f59f4
DV
3793 },
3794 "axisLabelFontSize": {
a96f59f4 3795 "default": "14",
a38e9336
DV
3796 "labels": ["Axis display"],
3797 "type": "integer",
a96f59f4
DV
3798 "description": "Size of the font (in pixels) to use in the axis labels, both x- and y-axis."
3799 },
a38e9336
DV
3800 "underlayCallback": {
3801 "default": "null",
3802 "labels": ["Callbacks"],
3803 "type": "function(canvas, area, dygraph)",
3804 "description": "When set, this callback gets called before the chart is drawn. It details on how to use this."
a96f59f4 3805 },
a38e9336
DV
3806 "width": {
3807 "default": "480",
3808 "labels": ["Overall display"],
3809 "type": "integer",
3810 "description": "Width, in pixels, of the chart. If the container div has been explicitly sized, this will be ignored."
a96f59f4 3811 },
a38e9336
DV
3812 "interactionModel": {
3813 "default": "...",
3814 "labels": ["Interactive Elements"],
3815 "type": "Object",
3816 "description": "TODO(konigsberg): document this"
3817 },
3818 "xTicker": {
3819 "default": "Dygraph.dateTicker or Dygraph.numericTicks",
3820 "labels": ["Axis display"],
3821 "type": "function(min, max, dygraph) -> [{v: ..., label: ...}, ...]",
3822 "description": "This lets you specify an arbitrary function to generate tick marks on an axis. The tick marks are an array of (value, label) pairs. The built-in functions go to great lengths to choose good tick marks so, if you set this option, you'll most likely want to call one of them and modify the result."
3823 },
3824 "xAxisLabelWidth": {
3825 "default": "50",
3826 "labels": ["Axis display"],
a96f59f4 3827 "type": "integer",
a38e9336 3828 "description": "Width, in pixels, of the x-axis labels."
a96f59f4 3829 },
a38e9336
DV
3830 "showLabelsOnHighlight": {
3831 "default": "true",
3832 "labels": ["Interactive Elements", "Legend"],
a96f59f4 3833 "type": "boolean",
a38e9336 3834 "description": "Whether to show the legend upon mouseover."
a96f59f4 3835 },
a38e9336
DV
3836 "axis": {
3837 "default": "(none)",
3838 "labels": ["Axis display"],
3839 "type": "string or object",
3840 "description": "Set to either an object ({}) filled with options for this axis or to the name of an existing data series with its own axis to re-use that axis. See tests for usage."
3841 },
3842 "pixelsPerXLabel": {
3843 "default": "60",
3844 "labels": ["Axis display", "Grid"],
a96f59f4 3845 "type": "integer",
a38e9336
DV
3846 "description": "Number of pixels to require between each x- and y-label. Larger values will yield a sparser axis with fewer ticks."
3847 },
3848 "labelsDiv": {
3849 "default": "null",
3850 "labels": ["Legend"],
3851 "type": "DOM element or string",
3852 "example": "<code style='font-size: small'>document.getElementById('foo')</code>or<code>'foo'",
3853 "description": "Show data labels in an external div, rather than on the graph. This value can either be a div element or a div id."
a96f59f4
DV
3854 },
3855 "fractions": {
a96f59f4 3856 "default": "false",
a38e9336
DV
3857 "labels": ["CSV parsing", "Error Bars"],
3858 "type": "boolean",
a96f59f4
DV
3859 "description": "When set, attempt to parse each cell in the CSV file as \"a/b\", where a and b are integers. The ratio will be plotted. This allows computation of Wilson confidence intervals (see below)."
3860 },
a38e9336
DV
3861 "logscale": {
3862 "default": "false",
3863 "labels": ["Axis display"],
a96f59f4 3864 "type": "boolean",
a109b711 3865 "description": "When set for a y-axis, the graph shows that axis in log scale. Any values less than or equal to zero are not displayed.\n\nNot compatible with showZero, and ignores connectSeparatedPoints. Also, showing log scale with valueRanges that are less than zero will result in an unviewable graph."
a38e9336
DV
3866 },
3867 "strokeWidth": {
3868 "default": "1.0",
3869 "labels": ["Data Line display"],
3870 "type": "integer",
3871 "example": "0.5, 2.0",
3872 "description": "The width of the lines connecting data points. This can be used to increase the contrast or some graphs."
3873 },
3874 "wilsonInterval": {
a96f59f4 3875 "default": "true",
a38e9336
DV
3876 "labels": ["Error Bars"],
3877 "type": "boolean",
a96f59f4
DV
3878 "description": "Use in conjunction with the \"fractions\" option. Instead of plotting +/- N standard deviations, dygraphs will compute a Wilson confidence interval and plot that. This has more reasonable behavior for ratios close to 0 or 1."
3879 },
a38e9336 3880 "fillGraph": {
a96f59f4 3881 "default": "false",
a38e9336
DV
3882 "labels": ["Data Line display"],
3883 "type": "boolean",
3884 "description": "Should the area underneath the graph be filled? This option is not compatible with error bars."
a96f59f4 3885 },
a38e9336
DV
3886 "highlightCircleSize": {
3887 "default": "3",
3888 "labels": ["Interactive Elements"],
3889 "type": "integer",
3890 "description": "The size in pixels of the dot drawn over highlighted points."
a96f59f4
DV
3891 },
3892 "gridLineColor": {
a96f59f4 3893 "default": "rgb(128,128,128)",
a38e9336
DV
3894 "labels": ["Grid"],
3895 "type": "red, blue",
a96f59f4
DV
3896 "description": "The color of the gridlines."
3897 },
a38e9336
DV
3898 "visibility": {
3899 "default": "[true, true, ...]",
3900 "labels": ["Data Line display"],
3901 "type": "Array of booleans",
3902 "description": "Which series should initially be visible? Once the Dygraph has been constructed, you can access and modify the visibility of each series using the <code>visibility</code> and <code>setVisibility</code> methods."
a96f59f4 3903 },
a38e9336
DV
3904 "valueRange": {
3905 "default": "Full range of the input is shown",
3906 "labels": ["Axis display"],
3907 "type": "Array of two numbers",
3908 "example": "[10, 110]",
3909 "description": "Explicitly set the vertical range of the graph to [low, high]."
a96f59f4 3910 },
a38e9336
DV
3911 "labelsDivWidth": {
3912 "default": "250",
3913 "labels": ["Legend"],
a96f59f4 3914 "type": "integer",
a38e9336 3915 "description": "Width (in pixels) of the div which shows information on the currently-highlighted points."
a96f59f4 3916 },
a38e9336
DV
3917 "colorSaturation": {
3918 "default": "1.0",
3919 "labels": ["Data Series Colors"],
3920 "type": "0.0 - 1.0",
3921 "description": "If <strong>colors</strong> is not specified, saturation of the automatically-generated data series colors."
3922 },
3923 "yAxisLabelWidth": {
3924 "default": "50",
3925 "labels": ["Axis display"],
a96f59f4 3926 "type": "integer",
a38e9336 3927 "description": "Width, in pixels, of the y-axis labels."
a96f59f4 3928 },
a38e9336
DV
3929 "hideOverlayOnMouseOut": {
3930 "default": "true",
3931 "labels": ["Interactive Elements", "Legend"],
a96f59f4 3932 "type": "boolean",
a38e9336 3933 "description": "Whether to hide the legend when the mouse leaves the chart area."
a96f59f4
DV
3934 },
3935 "yValueFormatter": {
a96f59f4 3936 "default": "(Round to 2 decimal places)",
a38e9336
DV
3937 "labels": ["Axis display"],
3938 "type": "function(x)",
a96f59f4
DV
3939 "description": "Function to provide a custom display format for the Y value for mouseover."
3940 },
a38e9336
DV
3941 "legend": {
3942 "default": "onmouseover",
3943 "labels": ["Legend"],
3944 "type": "string",
3945 "description": "When to display the legend. By default, it only appears when a user mouses over the chart. Set it to \"always\" to always display a legend of some sort."
3946 },
3947 "labelsShowZeroValues": {
3948 "default": "true",
3949 "labels": ["Legend"],
a96f59f4 3950 "type": "boolean",
a38e9336
DV
3951 "description": "Show zero value labels in the labelsDiv."
3952 },
3953 "stepPlot": {
a96f59f4 3954 "default": "false",
a38e9336
DV
3955 "labels": ["Data Line display"],
3956 "type": "boolean",
3957 "description": "When set, display the graph as a step plot instead of a line plot."
a96f59f4 3958 },
a38e9336
DV
3959 "labelsKMB": {
3960 "default": "false",
3961 "labels": ["Value display/formatting"],
a96f59f4 3962 "type": "boolean",
a38e9336
DV
3963 "description": "Show K/M/B for thousands/millions/billions on y-axis."
3964 },
3965 "rightGap": {
3966 "default": "5",
3967 "labels": ["Overall display"],
3968 "type": "integer",
3969 "description": "Number of pixels to leave blank at the right edge of the Dygraph. This makes it easier to highlight the right-most data point."
3970 },
3971 "avoidMinZero": {
a96f59f4 3972 "default": "false",
a38e9336
DV
3973 "labels": ["Axis display"],
3974 "type": "boolean",
3975 "description": "When set, the heuristic that fixes the Y axis at zero for a data set with the minimum Y value of zero is disabled. \nThis is particularly useful for data sets that contain many zero values, especially for step plots which may otherwise have lines not visible running along the bottom axis."
3976 },
3977 "xAxisLabelFormatter": {
3978 "default": "Dygraph.dateAxisFormatter",
3979 "labels": ["Axis display", "Value display/formatting"],
3980 "type": "function(date, granularity)",
3981 "description": "Function to call to format values along the x axis."
3982 },
3983 "clickCallback": {
3984 "snippet": "function(e, date){<br>&nbsp;&nbsp;alert(date);<br>}",
3985 "default": "null",
3986 "labels": ["Callbacks"],
3987 "type": "function(e, date)",
3988 "description": "A function to call when a data point is clicked. The function should take two arguments, the event object for the click and the date that was clicked."
3989 },
3990 "yAxisLabelFormatter": {
3991 "default": "yValueFormatter",
3992 "labels": ["Axis display", "Value display/formatting"],
3993 "type": "function(x)",
3994 "description": "Function used to format values along the Y axis. By default it uses the same as the <code>yValueFormatter</code> unless specified."
a96f59f4
DV
3995 },
3996 "labels": {
a96f59f4 3997 "default": "[\"X\", \"Y1\", \"Y2\", ...]*",
a38e9336
DV
3998 "labels": ["Legend"],
3999 "type": "array<string>",
a96f59f4
DV
4000 "description": "A name for each data series, including the independent (X) series. For CSV files and DataTable objections, this is determined by context. For raw data, this must be specified. If it is not, default values are supplied and a warning is logged."
4001 },
a38e9336
DV
4002 "dateWindow": {
4003 "default": "Full range of the input is shown",
4004 "labels": ["Axis display"],
4005 "type": "Array of two Dates or numbers",
4006 "example": "[<br>&nbsp;&nbsp;Date.parse('2006-01-01'),<br>&nbsp;&nbsp;(new Date()).valueOf()<br>]",
4007 "description": "Initially zoom in on a section of the graph. Is of the form [earliest, latest], where earliest/latest are milliseconds since epoch. If the data for the x-axis is numeric, the values in dateWindow must also be numbers."
a96f59f4 4008 },
a38e9336
DV
4009 "showRoller": {
4010 "default": "false",
4011 "labels": ["Interactive Elements", "Rolling Averages"],
4012 "type": "boolean",
4013 "description": "If the rolling average period text box should be shown."
a96f59f4 4014 },
a38e9336
DV
4015 "sigma": {
4016 "default": "2.0",
4017 "labels": ["Error Bars"],
4018 "type": "integer",
4019 "description": "When errorBars is set, shade this many standard deviations above/below each point."
a96f59f4 4020 },
a38e9336 4021 "customBars": {
a96f59f4 4022 "default": "false",
a38e9336 4023 "labels": ["CSV parsing", "Error Bars"],
a96f59f4 4024 "type": "boolean",
a38e9336 4025 "description": "When set, parse each CSV cell as \"low;middle;high\". Error bars will be drawn for each point between low and high, with the series itself going through middle."
a96f59f4 4026 },
a38e9336
DV
4027 "colorValue": {
4028 "default": "1.0",
4029 "labels": ["Data Series Colors"],
4030 "type": "float (0.0 - 1.0)",
4031 "description": "If colors is not specified, value of the data series colors, as in hue/saturation/value. (0.0-1.0, default 0.5)"
a96f59f4 4032 },
a38e9336
DV
4033 "errorBars": {
4034 "default": "false",
4035 "labels": ["CSV parsing", "Error Bars"],
a96f59f4 4036 "type": "boolean",
a38e9336 4037 "description": "Does the data contain standard deviations? Setting this to true alters the input format (see above)."
a96f59f4 4038 },
a38e9336
DV
4039 "displayAnnotations": {
4040 "default": "false",
4041 "labels": ["Annotations"],
a96f59f4 4042 "type": "boolean",
a38e9336 4043 "description": "Only applies when Dygraphs is used as a GViz chart. Causes string columns following a data series to be interpreted as annotations on points in that series. This is the same format used by Google's AnnotatedTimeLine chart."
028ddf8a 4044 }
0addac07
DV
4045}
4046; // </JSON>
4047// NOTE: in addition to parsing as JS, this snippet is expected to be valid
4048// JSON. This assumption cannot be checked in JS, but it will be checked when
4049// documentation is generated by the generate-documentation.py script.
028ddf8a
DV
4050
4051// Do a quick sanity check on the options reference.
4052(function() {
4053 var warn = function(msg) { if (console) console.warn(msg); };
4054 var flds = ['type', 'default', 'description'];
a38e9336
DV
4055 var valid_cats = [
4056 'Annotations',
4057 'Axis display',
4058 'CSV parsing',
4059 'Callbacks',
4060 'Data Line display',
4061 'Data Series Colors',
4062 'Error Bars',
4063 'Grid',
4064 'Interactive Elements',
4065 'Legend',
4066 'Overall display',
4067 'Rolling Averages',
4068 'Value display/formatting'
4069 ];
4070 var cats = {};
4071 for (var i = 0; i < valid_cats.length; i++) cats[valid_cats[i]] = true;
4072
028ddf8a
DV
4073 for (var k in Dygraph.OPTIONS_REFERENCE) {
4074 if (!Dygraph.OPTIONS_REFERENCE.hasOwnProperty(k)) continue;
4075 var op = Dygraph.OPTIONS_REFERENCE[k];
4076 for (var i = 0; i < flds.length; i++) {
4077 if (!op.hasOwnProperty(flds[i])) {
4078 warn('Option ' + k + ' missing "' + flds[i] + '" property');
4079 } else if (typeof(op[flds[i]]) != 'string') {
4080 warn(k + '.' + flds[i] + ' must be of type string');
4081 }
4082 }
a38e9336
DV
4083 var labels = op['labels'];
4084 if (typeof(labels) !== 'object') {
4085 warn('Option "' + k + '" is missing a "labels": [...] option');
4086 for (var i = 0; i < labels.length; i++) {
4087 if (!cats.hasOwnProperty(labels[i])) {
4088 warn('Option "' + k + '" has label "' + labels[i] +
4089 '", which is invalid.');
4090 }
4091 }
4092 }
028ddf8a
DV
4093 }
4094})();
4095// </REMOVE_FOR_COMBINED>