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