When possible, record the file/line number that logged an error/warning.
[dygraphs.git] / dygraph.js
CommitLineData
88e95c46
DV
1/**
2 * @license
3 * Copyright 2006 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6a1aa64f
DV
6
7/**
8 * @fileoverview Creates an interactive, zoomable graph based on a CSV file or
285a6bda
DV
9 * string. Dygraph can handle multiple series with or without error bars. The
10 * date/value ranges will be automatically set. Dygraph uses the
6a1aa64f
DV
11 * <canvas> tag, so it only works in FF1.5+.
12 * @author danvdk@gmail.com (Dan Vanderkam)
13
14 Usage:
15 <div id="graphdiv" style="width:800px; height:500px;"></div>
16 <script type="text/javascript">
285a6bda
DV
17 new Dygraph(document.getElementById("graphdiv"),
18 "datafile.csv", // CSV file with headers
19 { }); // options
6a1aa64f
DV
20 </script>
21
22 The CSV file is of the form
23
285a6bda 24 Date,SeriesA,SeriesB,SeriesC
6a1aa64f
DV
25 YYYYMMDD,A1,B1,C1
26 YYYYMMDD,A2,B2,C2
27
6a1aa64f
DV
28 If the 'errorBars' option is set in the constructor, the input should be of
29 the form
285a6bda 30 Date,SeriesA,SeriesB,...
6a1aa64f
DV
31 YYYYMMDD,A1,sigmaA1,B1,sigmaB1,...
32 YYYYMMDD,A2,sigmaA2,B2,sigmaB2,...
33
34 If the 'fractions' option is set, the input should be of the form:
35
285a6bda 36 Date,SeriesA,SeriesB,...
6a1aa64f
DV
37 YYYYMMDD,A1/B1,A2/B2,...
38 YYYYMMDD,A1/B1,A2/B2,...
39
40 And error bars will be calculated automatically using a binomial distribution.
41
727439b4 42 For further documentation and examples, see http://dygraphs.com/
6a1aa64f
DV
43
44 */
45
46/**
629a09ae
DV
47 * Creates an interactive, zoomable chart.
48 *
49 * @constructor
50 * @param {div | String} div A div or the id of a div into which to construct
51 * the chart.
52 * @param {String | Function} file A file containing CSV data or a function
53 * that returns this data. The most basic expected format for each line is
54 * "YYYY/MM/DD,val1,val2,...". For more information, see
55 * http://dygraphs.com/data.html.
6a1aa64f 56 * @param {Object} attrs Various other attributes, e.g. errorBars determines
629a09ae
DV
57 * whether the input data contains error ranges. For a complete list of
58 * options, see http://dygraphs.com/options.html.
6a1aa64f 59 */
285a6bda
DV
60Dygraph = function(div, data, opts) {
61 if (arguments.length > 0) {
62 if (arguments.length == 4) {
63 // Old versions of dygraphs took in the series labels as a constructor
64 // parameter. This doesn't make sense anymore, but it's easy to continue
65 // to support this usage.
66 this.warn("Using deprecated four-argument dygraph constructor");
67 this.__old_init__(div, data, arguments[2], arguments[3]);
68 } else {
69 this.__init__(div, data, opts);
70 }
71 }
6a1aa64f
DV
72};
73
285a6bda
DV
74Dygraph.NAME = "Dygraph";
75Dygraph.VERSION = "1.2";
76Dygraph.__repr__ = function() {
6a1aa64f
DV
77 return "[" + this.NAME + " " + this.VERSION + "]";
78};
629a09ae
DV
79
80/**
81 * Returns information about the Dygraph class.
82 */
285a6bda 83Dygraph.toString = function() {
6a1aa64f
DV
84 return this.__repr__();
85};
86
87// Various default values
285a6bda
DV
88Dygraph.DEFAULT_ROLL_PERIOD = 1;
89Dygraph.DEFAULT_WIDTH = 480;
90Dygraph.DEFAULT_HEIGHT = 320;
6a1aa64f 91
b1a3b195
DV
92Dygraph.ANIMATION_STEPS = 10;
93Dygraph.ANIMATION_DURATION = 200;
94
48e614ac
DV
95// These are defined before DEFAULT_ATTRS so that it can refer to them.
96/**
97 * @private
98 * Return a string version of a number. This respects the digitsAfterDecimal
99 * and maxNumberWidth options.
100 * @param {Number} x The number to be formatted
101 * @param {Dygraph} opts An options view
102 * @param {String} name The name of the point's data series
103 * @param {Dygraph} g The dygraph object
104 */
105Dygraph.numberValueFormatter = function(x, opts, pt, g) {
106 var sigFigs = opts('sigFigs');
107
108 if (sigFigs !== null) {
109 // User has opted for a fixed number of significant figures.
110 return Dygraph.floatFormat(x, sigFigs);
111 }
112
113 var digits = opts('digitsAfterDecimal');
114 var maxNumberWidth = opts('maxNumberWidth');
115
116 // switch to scientific notation if we underflow or overflow fixed display.
117 if (x !== 0.0 &&
118 (Math.abs(x) >= Math.pow(10, maxNumberWidth) ||
119 Math.abs(x) < Math.pow(10, -digits))) {
120 return x.toExponential(digits);
121 } else {
122 return '' + Dygraph.round_(x, digits);
123 }
124};
125
126/**
127 * variant for use as an axisLabelFormatter.
128 * @private
129 */
130Dygraph.numberAxisLabelFormatter = function(x, granularity, opts, g) {
131 return Dygraph.numberValueFormatter(x, opts, g);
132};
133
134/**
135 * Convert a JS date (millis since epoch) to YYYY/MM/DD
136 * @param {Number} date The JavaScript date (ms since epoch)
137 * @return {String} A date of the form "YYYY/MM/DD"
138 * @private
139 */
140Dygraph.dateString_ = function(date) {
141 var zeropad = Dygraph.zeropad;
142 var d = new Date(date);
143
144 // Get the year:
145 var year = "" + d.getFullYear();
146 // Get a 0 padded month string
147 var month = zeropad(d.getMonth() + 1); //months are 0-offset, sigh
148 // Get a 0 padded day string
149 var day = zeropad(d.getDate());
150
151 var ret = "";
152 var frac = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
153 if (frac) ret = " " + Dygraph.hmsString_(date);
154
155 return year + "/" + month + "/" + day + ret;
156};
157
158/**
159 * Convert a JS date to a string appropriate to display on an axis that
160 * is displaying values at the stated granularity.
161 * @param {Date} date The date to format
162 * @param {Number} granularity One of the Dygraph granularity constants
163 * @return {String} The formatted date
164 * @private
165 */
166Dygraph.dateAxisFormatter = function(date, granularity) {
167 if (granularity >= Dygraph.DECADAL) {
168 return date.strftime('%Y');
169 } else if (granularity >= Dygraph.MONTHLY) {
170 return date.strftime('%b %y');
171 } else {
172 var frac = date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds() + date.getMilliseconds();
173 if (frac == 0 || granularity >= Dygraph.DAILY) {
174 return new Date(date.getTime() + 3600*1000).strftime('%d%b');
175 } else {
176 return Dygraph.hmsString_(date.getTime());
177 }
178 }
179};
180
181
8e4a6af3 182// Default attribute values.
285a6bda 183Dygraph.DEFAULT_ATTRS = {
a9fc39ab 184 highlightCircleSize: 3,
285a6bda 185
8e4a6af3
DV
186 labelsDivWidth: 250,
187 labelsDivStyles: {
188 // TODO(danvk): move defaults from createStatusMessage_ here.
285a6bda
DV
189 },
190 labelsSeparateLines: false,
bcd3ebf0 191 labelsShowZeroValues: true,
285a6bda 192 labelsKMB: false,
afefbcdb 193 labelsKMG2: false,
d160cc3b 194 showLabelsOnHighlight: true,
12e4c741 195
2e1fcf1a
DV
196 digitsAfterDecimal: 2,
197 maxNumberWidth: 6,
19589a3e 198 sigFigs: null,
285a6bda
DV
199
200 strokeWidth: 1.0,
8e4a6af3 201
8846615a
DV
202 axisTickSize: 3,
203 axisLabelFontSize: 14,
204 xAxisLabelWidth: 50,
205 yAxisLabelWidth: 50,
206 rightGap: 5,
285a6bda
DV
207
208 showRoller: false,
285a6bda 209 xValueParser: Dygraph.dateParser,
285a6bda 210
3d67f03b
DV
211 delimiter: ',',
212
285a6bda
DV
213 sigma: 2.0,
214 errorBars: false,
215 fractions: false,
216 wilsonInterval: true, // only relevant if fractions is true
5954ef32 217 customBars: false,
43af96e7
NK
218 fillGraph: false,
219 fillAlpha: 0.15,
f032c51d 220 connectSeparatedPoints: false,
43af96e7
NK
221
222 stackedGraph: false,
afdc483f
NN
223 hideOverlayOnMouseOut: true,
224
2fccd3dc
DV
225 // TODO(danvk): support 'onmouseover' and 'never', and remove synonyms.
226 legend: 'onmouseover', // the only relevant value at the moment is 'always'.
227
00c281d4 228 stepPlot: false,
062ef401
JB
229 avoidMinZero: false,
230
ad1798c2 231 // Sizes of the various chart labels.
b4202b3d 232 titleHeight: 28,
86cce9e8
DV
233 xLabelHeight: 18,
234 yLabelWidth: 18,
ad1798c2 235
423f5ed3
DV
236 drawXAxis: true,
237 drawYAxis: true,
238 axisLineColor: "black",
990d6a35
DV
239 axisLineWidth: 0.3,
240 gridLineWidth: 0.3,
241 axisLabelColor: "black",
242 axisLabelFont: "Arial", // TODO(danvk): is this implemented?
243 axisLabelWidth: 50,
244 drawYGrid: true,
245 drawXGrid: true,
246 gridLineColor: "rgb(128,128,128)",
423f5ed3 247
48e614ac 248 interactionModel: null, // will be set to Dygraph.Interaction.defaultModel
b1a3b195 249 animatedZooms: false, // (for now)
48e614ac 250
ccd9d7c2
PF
251 // Range selector options
252 showRangeSelector: false,
253 rangeSelectorHeight: 40,
254 rangeSelectorPlotStrokeColor: "#808FAB",
255 rangeSelectorPlotFillColor: "#A7B1C4",
256
48e614ac
DV
257 // per-axis options
258 axes: {
259 x: {
260 pixelsPerLabel: 60,
261 axisLabelFormatter: Dygraph.dateAxisFormatter,
262 valueFormatter: Dygraph.dateString_,
263 ticker: null // will be set in dygraph-tickers.js
264 },
265 y: {
266 pixelsPerLabel: 30,
267 valueFormatter: Dygraph.numberValueFormatter,
268 axisLabelFormatter: Dygraph.numberAxisLabelFormatter,
269 ticker: null // will be set in dygraph-tickers.js
270 },
271 y2: {
272 pixelsPerLabel: 30,
273 valueFormatter: Dygraph.numberValueFormatter,
274 axisLabelFormatter: Dygraph.numberAxisLabelFormatter,
275 ticker: null // will be set in dygraph-tickers.js
276 }
277 }
285a6bda
DV
278};
279
39b0e098
RK
280// Directions for panning and zooming. Use bit operations when combined
281// values are possible.
282Dygraph.HORIZONTAL = 1;
283Dygraph.VERTICAL = 2;
284
5c528fa2
DV
285// Used for initializing annotation CSS rules only once.
286Dygraph.addedAnnotationCSS = false;
287
285a6bda
DV
288Dygraph.prototype.__old_init__ = function(div, file, labels, attrs) {
289 // Labels is no longer a constructor parameter, since it's typically set
290 // directly from the data source. It also conains a name for the x-axis,
291 // which the previous constructor form did not.
292 if (labels != null) {
293 var new_labels = ["Date"];
294 for (var i = 0; i < labels.length; i++) new_labels.push(labels[i]);
fc80a396 295 Dygraph.update(attrs, { 'labels': new_labels });
285a6bda
DV
296 }
297 this.__init__(div, file, attrs);
8e4a6af3
DV
298};
299
6a1aa64f 300/**
285a6bda 301 * Initializes the Dygraph. This creates a new DIV and constructs the PlotKit
7aedf6fe 302 * and context &lt;canvas&gt; inside of it. See the constructor for details.
6a1aa64f 303 * on the parameters.
12e4c741 304 * @param {Element} div the Element to render the graph into.
6a1aa64f 305 * @param {String | Function} file Source data
6a1aa64f
DV
306 * @param {Object} attrs Miscellaneous other options
307 * @private
308 */
285a6bda 309Dygraph.prototype.__init__ = function(div, file, attrs) {
a2c8fff4
DV
310 // Hack for IE: if we're using excanvas and the document hasn't finished
311 // loading yet (and hence may not have initialized whatever it needs to
312 // initialize), then keep calling this routine periodically until it has.
313 if (/MSIE/.test(navigator.userAgent) && !window.opera &&
314 typeof(G_vmlCanvasManager) != 'undefined' &&
315 document.readyState != 'complete') {
316 var self = this;
317 setTimeout(function() { self.__init__(div, file, attrs) }, 100);
ccd9d7c2 318 return;
a2c8fff4
DV
319 }
320
285a6bda
DV
321 // Support two-argument constructor
322 if (attrs == null) { attrs = {}; }
323
48e614ac
DV
324 attrs = Dygraph.mapLegacyOptions_(attrs);
325
326 if (!div) {
327 Dygraph.error("Constructing dygraph with a non-existent div!");
328 return;
329 }
330
920208fb
PF
331 this.isUsingExcanvas_ = typeof(G_vmlCanvasManager) != 'undefined';
332
6a1aa64f 333 // Copy the important bits into the object
32988383 334 // TODO(danvk): most of these should just stay in the attrs_ dictionary.
6a1aa64f 335 this.maindiv_ = div;
6a1aa64f 336 this.file_ = file;
285a6bda 337 this.rollPeriod_ = attrs.rollPeriod || Dygraph.DEFAULT_ROLL_PERIOD;
6a1aa64f 338 this.previousVerticalX_ = -1;
6a1aa64f 339 this.fractions_ = attrs.fractions || false;
6a1aa64f 340 this.dateWindow_ = attrs.dateWindow || null;
8b83c6cc 341
6a1aa64f 342 this.wilsonInterval_ = attrs.wilsonInterval || true;
fe0b7c03 343 this.is_initial_draw_ = true;
5c528fa2 344 this.annotations_ = [];
7aedf6fe 345
45f2c689 346 // Zoomed indicators - These indicate when the graph has been zoomed and on what axis.
57baab03
NN
347 this.zoomed_x_ = false;
348 this.zoomed_y_ = false;
45f2c689 349
f7d6278e
DV
350 // Clear the div. This ensure that, if multiple dygraphs are passed the same
351 // div, then only one will be drawn.
352 div.innerHTML = "";
353
0cb9bd91
DV
354 // For historical reasons, the 'width' and 'height' options trump all CSS
355 // rules _except_ for an explicit 'width' or 'height' on the div.
356 // As an added convenience, if the div has zero height (like <div></div> does
357 // without any styles), then we use a default height/width.
358 if (div.style.width == '' && attrs.width) {
359 div.style.width = attrs.width + "px";
285a6bda 360 }
0cb9bd91
DV
361 if (div.style.height == '' && attrs.height) {
362 div.style.height = attrs.height + "px";
32988383 363 }
ccd9d7c2 364 if (div.style.height == '' && div.clientHeight == 0) {
0cb9bd91
DV
365 div.style.height = Dygraph.DEFAULT_HEIGHT + "px";
366 if (div.style.width == '') {
367 div.style.width = Dygraph.DEFAULT_WIDTH + "px";
368 }
c21d2c2d 369 }
fffad740 370 // these will be zero if the dygraph's div is hidden.
ccd9d7c2
PF
371 this.width_ = div.clientWidth;
372 this.height_ = div.clientHeight;
32988383 373
344ba8c0 374 // TODO(danvk): set fillGraph to be part of attrs_ here, not user_attrs_.
43af96e7
NK
375 if (attrs['stackedGraph']) {
376 attrs['fillGraph'] = true;
377 // TODO(nikhilk): Add any other stackedGraph checks here.
378 }
379
285a6bda
DV
380 // Dygraphs has many options, some of which interact with one another.
381 // To keep track of everything, we maintain two sets of options:
382 //
c21d2c2d 383 // this.user_attrs_ only options explicitly set by the user.
285a6bda
DV
384 // this.attrs_ defaults, options derived from user_attrs_, data.
385 //
386 // Options are then accessed this.attr_('attr'), which first looks at
387 // user_attrs_ and then computed attrs_. This way Dygraphs can set intelligent
388 // defaults without overriding behavior that the user specifically asks for.
389 this.user_attrs_ = {};
fc80a396 390 Dygraph.update(this.user_attrs_, attrs);
6a1aa64f 391
48e614ac 392 // This sequence ensures that Dygraph.DEFAULT_ATTRS is never modified.
285a6bda 393 this.attrs_ = {};
48e614ac 394 Dygraph.updateDeep(this.attrs_, Dygraph.DEFAULT_ATTRS);
6a1aa64f 395
16269f6e 396 this.boundaryIds_ = [];
6a1aa64f 397
6a1aa64f
DV
398 // Create the containing DIV and other interactive elements
399 this.createInterface_();
400
738fc797 401 this.start_();
6a1aa64f
DV
402};
403
dcb25130
NN
404/**
405 * Returns the zoomed status of the chart for one or both axes.
406 *
407 * Axis is an optional parameter. Can be set to 'x' or 'y'.
408 *
409 * The zoomed status for an axis is set whenever a user zooms using the mouse
e5152598 410 * or when the dateWindow or valueRange are updated (unless the isZoomedIgnoreProgrammaticZoom
dcb25130
NN
411 * option is also specified).
412 */
57baab03
NN
413Dygraph.prototype.isZoomed = function(axis) {
414 if (axis == null) return this.zoomed_x_ || this.zoomed_y_;
415 if (axis == 'x') return this.zoomed_x_;
416 if (axis == 'y') return this.zoomed_y_;
417 throw "axis parameter to Dygraph.isZoomed must be missing, 'x' or 'y'.";
418};
419
629a09ae
DV
420/**
421 * Returns information about the Dygraph object, including its containing ID.
422 */
22bd1dfb
RK
423Dygraph.prototype.toString = function() {
424 var maindiv = this.maindiv_;
425 var id = (maindiv && maindiv.id) ? maindiv.id : maindiv
426 return "[Dygraph " + id + "]";
427}
428
629a09ae
DV
429/**
430 * @private
431 * Returns the value of an option. This may be set by the user (either in the
432 * constructor or by calling updateOptions) or by dygraphs, and may be set to a
433 * per-series value.
434 * @param { String } name The name of the option, e.g. 'rollPeriod'.
435 * @param { String } [seriesName] The name of the series to which the option
436 * will be applied. If no per-series value of this option is available, then
437 * the global value is returned. This is optional.
438 * @return { ... } The value of the option.
439 */
227b93cc 440Dygraph.prototype.attr_ = function(name, seriesName) {
028ddf8a
DV
441// <REMOVE_FOR_COMBINED>
442 if (typeof(Dygraph.OPTIONS_REFERENCE) === 'undefined') {
443 this.error('Must include options reference JS for testing');
444 } else if (!Dygraph.OPTIONS_REFERENCE.hasOwnProperty(name)) {
445 this.error('Dygraphs is using property ' + name + ', which has no entry ' +
446 'in the Dygraphs.OPTIONS_REFERENCE listing.');
447 // Only log this error once.
448 Dygraph.OPTIONS_REFERENCE[name] = true;
449 }
450// </REMOVE_FOR_COMBINED>
227b93cc
DV
451 if (seriesName &&
452 typeof(this.user_attrs_[seriesName]) != 'undefined' &&
453 this.user_attrs_[seriesName] != null &&
454 typeof(this.user_attrs_[seriesName][name]) != 'undefined') {
455 return this.user_attrs_[seriesName][name];
450fe64b 456 } else if (typeof(this.user_attrs_[name]) != 'undefined') {
285a6bda
DV
457 return this.user_attrs_[name];
458 } else if (typeof(this.attrs_[name]) != 'undefined') {
459 return this.attrs_[name];
460 } else {
461 return null;
462 }
463};
464
6a1aa64f 465/**
48e614ac
DV
466 * @private
467 * @param String} axis The name of the axis (i.e. 'x', 'y' or 'y2')
468 * @return { ... } A function mapping string -> option value
469 */
470Dygraph.prototype.optionsViewForAxis_ = function(axis) {
471 var self = this;
472 return function(opt) {
473 var axis_opts = self.user_attrs_['axes'];
474 if (axis_opts && axis_opts[axis] && axis_opts[axis][opt]) {
475 return axis_opts[axis][opt];
476 }
477 // user-specified attributes always trump defaults, even if they're less
478 // specific.
479 if (typeof(self.user_attrs_[opt]) != 'undefined') {
480 return self.user_attrs_[opt];
481 }
482
483 axis_opts = self.attrs_['axes'];
484 if (axis_opts && axis_opts[axis] && axis_opts[axis][opt]) {
485 return axis_opts[axis][opt];
486 }
487 // check old-style axis options
488 // TODO(danvk): add a deprecation warning if either of these match.
489 if (axis == 'y' && self.axes_[0].hasOwnProperty(opt)) {
490 return self.axes_[0][opt];
491 } else if (axis == 'y2' && self.axes_[1].hasOwnProperty(opt)) {
492 return self.axes_[1][opt];
493 }
494 return self.attr_(opt);
495 };
496};
497
498/**
6a1aa64f 499 * Returns the current rolling period, as set by the user or an option.
6faebb69 500 * @return {Number} The number of points in the rolling window
6a1aa64f 501 */
285a6bda 502Dygraph.prototype.rollPeriod = function() {
6a1aa64f 503 return this.rollPeriod_;
76171648
DV
504};
505
599fb4ad
DV
506/**
507 * Returns the currently-visible x-range. This can be affected by zooming,
508 * panning or a call to updateOptions.
509 * Returns a two-element array: [left, right].
510 * If the Dygraph has dates on the x-axis, these will be millis since epoch.
511 */
512Dygraph.prototype.xAxisRange = function() {
4cac8c7a
RK
513 return this.dateWindow_ ? this.dateWindow_ : this.xAxisExtremes();
514};
599fb4ad 515
4cac8c7a
RK
516/**
517 * Returns the lower- and upper-bound x-axis values of the
518 * data set.
519 */
520Dygraph.prototype.xAxisExtremes = function() {
599fb4ad
DV
521 var left = this.rawData_[0][0];
522 var right = this.rawData_[this.rawData_.length - 1][0];
523 return [left, right];
524};
525
3230c662 526/**
d58ae307
DV
527 * Returns the currently-visible y-range for an axis. This can be affected by
528 * zooming, panning or a call to updateOptions. Axis indices are zero-based. If
529 * called with no arguments, returns the range of the first axis.
3230c662
DV
530 * Returns a two-element array: [bottom, top].
531 */
d58ae307 532Dygraph.prototype.yAxisRange = function(idx) {
d63e6799 533 if (typeof(idx) == "undefined") idx = 0;
d64b8fea
RK
534 if (idx < 0 || idx >= this.axes_.length) {
535 return null;
536 }
537 var axis = this.axes_[idx];
538 return [ axis.computedValueRange[0], axis.computedValueRange[1] ];
d58ae307
DV
539};
540
541/**
542 * Returns the currently-visible y-ranges for each axis. This can be affected by
543 * zooming, panning, calls to updateOptions, etc.
544 * Returns an array of [bottom, top] pairs, one for each y-axis.
545 */
546Dygraph.prototype.yAxisRanges = function() {
547 var ret = [];
548 for (var i = 0; i < this.axes_.length; i++) {
549 ret.push(this.yAxisRange(i));
550 }
551 return ret;
3230c662
DV
552};
553
d58ae307 554// TODO(danvk): use these functions throughout dygraphs.
3230c662
DV
555/**
556 * Convert from data coordinates to canvas/div X/Y coordinates.
d58ae307
DV
557 * If specified, do this conversion for the coordinate system of a particular
558 * axis. Uses the first axis by default.
3230c662 559 * Returns a two-element array: [X, Y]
ff022deb 560 *
0747928a 561 * Note: use toDomXCoord instead of toDomCoords(x, null) and use toDomYCoord
ff022deb 562 * instead of toDomCoords(null, y, axis).
3230c662 563 */
d58ae307 564Dygraph.prototype.toDomCoords = function(x, y, axis) {
ff022deb
RK
565 return [ this.toDomXCoord(x), this.toDomYCoord(y, axis) ];
566};
567
568/**
569 * Convert from data x coordinates to canvas/div X coordinate.
570 * If specified, do this conversion for the coordinate system of a particular
0037b2a4
RK
571 * axis.
572 * Returns a single value or null if x is null.
ff022deb
RK
573 */
574Dygraph.prototype.toDomXCoord = function(x) {
575 if (x == null) {
576 return null;
577 };
578
3230c662 579 var area = this.plotter_.area;
ff022deb
RK
580 var xRange = this.xAxisRange();
581 return area.x + (x - xRange[0]) / (xRange[1] - xRange[0]) * area.w;
582}
3230c662 583
ff022deb
RK
584/**
585 * Convert from data x coordinates to canvas/div Y coordinate and optional
586 * axis. Uses the first axis by default.
587 *
588 * returns a single value or null if y is null.
589 */
590Dygraph.prototype.toDomYCoord = function(y, axis) {
0747928a 591 var pct = this.toPercentYCoord(y, axis);
3230c662 592
ff022deb
RK
593 if (pct == null) {
594 return null;
595 }
e4416fb9 596 var area = this.plotter_.area;
ff022deb
RK
597 return area.y + pct * area.h;
598}
3230c662
DV
599
600/**
601 * Convert from canvas/div coords to data coordinates.
d58ae307
DV
602 * If specified, do this conversion for the coordinate system of a particular
603 * axis. Uses the first axis by default.
ff022deb
RK
604 * Returns a two-element array: [X, Y].
605 *
0747928a 606 * Note: use toDataXCoord instead of toDataCoords(x, null) and use toDataYCoord
ff022deb 607 * instead of toDataCoords(null, y, axis).
3230c662 608 */
d58ae307 609Dygraph.prototype.toDataCoords = function(x, y, axis) {
ff022deb
RK
610 return [ this.toDataXCoord(x), this.toDataYCoord(y, axis) ];
611};
612
613/**
614 * Convert from canvas/div x coordinate to data coordinate.
615 *
616 * If x is null, this returns null.
617 */
618Dygraph.prototype.toDataXCoord = function(x) {
619 if (x == null) {
620 return null;
3230c662
DV
621 }
622
ff022deb
RK
623 var area = this.plotter_.area;
624 var xRange = this.xAxisRange();
625 return xRange[0] + (x - area.x) / area.w * (xRange[1] - xRange[0]);
626};
627
628/**
629 * Convert from canvas/div y coord to value.
630 *
631 * If y is null, this returns null.
632 * if axis is null, this uses the first axis.
633 */
634Dygraph.prototype.toDataYCoord = function(y, axis) {
635 if (y == null) {
636 return null;
3230c662
DV
637 }
638
ff022deb
RK
639 var area = this.plotter_.area;
640 var yRange = this.yAxisRange(axis);
641
b70247dc
RK
642 if (typeof(axis) == "undefined") axis = 0;
643 if (!this.axes_[axis].logscale) {
d9816e62 644 return yRange[0] + (area.y + area.h - y) / area.h * (yRange[1] - yRange[0]);
ff022deb
RK
645 } else {
646 // Computing the inverse of toDomCoord.
647 var pct = (y - area.y) / area.h
648
649 // Computing the inverse of toPercentYCoord. The function was arrived at with
650 // the following steps:
651 //
652 // Original calcuation:
d59b6f34 653 // pct = (logr1 - Dygraph.log10(y)) / (logr1 - Dygraph.log10(yRange[0]));
ff022deb
RK
654 //
655 // Move denominator to both sides:
d59b6f34 656 // pct * (logr1 - Dygraph.log10(yRange[0])) = logr1 - Dygraph.log10(y);
ff022deb
RK
657 //
658 // subtract logr1, and take the negative value.
d59b6f34 659 // logr1 - (pct * (logr1 - Dygraph.log10(yRange[0]))) = Dygraph.log10(y);
ff022deb
RK
660 //
661 // Swap both sides of the equation, and we can compute the log of the
662 // return value. Which means we just need to use that as the exponent in
663 // e^exponent.
d59b6f34 664 // Dygraph.log10(y) = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
ff022deb 665
d59b6f34
RK
666 var logr1 = Dygraph.log10(yRange[1]);
667 var exponent = logr1 - (pct * (logr1 - Dygraph.log10(yRange[0])));
668 var value = Math.pow(Dygraph.LOG_SCALE, exponent);
ff022deb
RK
669 return value;
670 }
3230c662
DV
671};
672
e99fde05 673/**
ff022deb 674 * Converts a y for an axis to a percentage from the top to the
4cac8c7a 675 * bottom of the drawing area.
ff022deb
RK
676 *
677 * If the coordinate represents a value visible on the canvas, then
678 * the value will be between 0 and 1, where 0 is the top of the canvas.
679 * However, this method will return values outside the range, as
680 * values can fall outside the canvas.
681 *
682 * If y is null, this returns null.
683 * if axis is null, this uses the first axis.
629a09ae
DV
684 *
685 * @param { Number } y The data y-coordinate.
686 * @param { Number } [axis] The axis number on which the data coordinate lives.
687 * @return { Number } A fraction in [0, 1] where 0 = the top edge.
ff022deb
RK
688 */
689Dygraph.prototype.toPercentYCoord = function(y, axis) {
690 if (y == null) {
691 return null;
692 }
7d0e7a0d 693 if (typeof(axis) == "undefined") axis = 0;
ff022deb
RK
694
695 var area = this.plotter_.area;
696 var yRange = this.yAxisRange(axis);
697
698 var pct;
7d0e7a0d 699 if (!this.axes_[axis].logscale) {
4cac8c7a
RK
700 // yRange[1] - y is unit distance from the bottom.
701 // yRange[1] - yRange[0] is the scale of the range.
ff022deb
RK
702 // (yRange[1] - y) / (yRange[1] - yRange[0]) is the % from the bottom.
703 pct = (yRange[1] - y) / (yRange[1] - yRange[0]);
704 } else {
d59b6f34
RK
705 var logr1 = Dygraph.log10(yRange[1]);
706 pct = (logr1 - Dygraph.log10(y)) / (logr1 - Dygraph.log10(yRange[0]));
ff022deb
RK
707 }
708 return pct;
709}
710
711/**
4cac8c7a
RK
712 * Converts an x value to a percentage from the left to the right of
713 * the drawing area.
714 *
715 * If the coordinate represents a value visible on the canvas, then
716 * the value will be between 0 and 1, where 0 is the left of the canvas.
717 * However, this method will return values outside the range, as
718 * values can fall outside the canvas.
719 *
720 * If x is null, this returns null.
629a09ae
DV
721 * @param { Number } x The data x-coordinate.
722 * @return { Number } A fraction in [0, 1] where 0 = the left edge.
4cac8c7a
RK
723 */
724Dygraph.prototype.toPercentXCoord = function(x) {
725 if (x == null) {
726 return null;
727 }
728
4cac8c7a 729 var xRange = this.xAxisRange();
965a030e 730 return (x - xRange[0]) / (xRange[1] - xRange[0]);
629a09ae 731};
4cac8c7a
RK
732
733/**
e99fde05 734 * Returns the number of columns (including the independent variable).
629a09ae 735 * @return { Integer } The number of columns.
e99fde05
DV
736 */
737Dygraph.prototype.numColumns = function() {
738 return this.rawData_[0].length;
739};
740
741/**
742 * Returns the number of rows (excluding any header/label row).
629a09ae 743 * @return { Integer } The number of rows, less any header.
e99fde05
DV
744 */
745Dygraph.prototype.numRows = function() {
746 return this.rawData_.length;
747};
748
749/**
750 * Returns the value in the given row and column. If the row and column exceed
751 * the bounds on the data, returns null. Also returns null if the value is
752 * missing.
629a09ae
DV
753 * @param { Number} row The row number of the data (0-based). Row 0 is the
754 * first row of data, not a header row.
755 * @param { Number} col The column number of the data (0-based)
756 * @return { Number } The value in the specified cell or null if the row/col
757 * were out of range.
e99fde05
DV
758 */
759Dygraph.prototype.getValue = function(row, col) {
760 if (row < 0 || row > this.rawData_.length) return null;
761 if (col < 0 || col > this.rawData_[row].length) return null;
762
763 return this.rawData_[row][col];
764};
765
629a09ae 766/**
285a6bda 767 * Generates interface elements for the Dygraph: a containing div, a div to
6a1aa64f 768 * display the current point, and a textbox to adjust the rolling average
697e70b2 769 * period. Also creates the Renderer/Layout elements.
6a1aa64f
DV
770 * @private
771 */
285a6bda 772Dygraph.prototype.createInterface_ = function() {
6a1aa64f
DV
773 // Create the all-enclosing graph div
774 var enclosing = this.maindiv_;
775
b0c3b730
DV
776 this.graphDiv = document.createElement("div");
777 this.graphDiv.style.width = this.width_ + "px";
778 this.graphDiv.style.height = this.height_ + "px";
779 enclosing.appendChild(this.graphDiv);
780
781 // Create the canvas for interactive parts of the chart.
f8cfec73 782 this.canvas_ = Dygraph.createCanvas();
b0c3b730
DV
783 this.canvas_.style.position = "absolute";
784 this.canvas_.width = this.width_;
785 this.canvas_.height = this.height_;
f8cfec73
DV
786 this.canvas_.style.width = this.width_ + "px"; // for IE
787 this.canvas_.style.height = this.height_ + "px"; // for IE
b0c3b730 788
2cf95fff
RK
789 this.canvas_ctx_ = Dygraph.getContext(this.canvas_);
790
b0c3b730 791 // ... and for static parts of the chart.
6a1aa64f 792 this.hidden_ = this.createPlotKitCanvas_(this.canvas_);
2cf95fff 793 this.hidden_ctx_ = Dygraph.getContext(this.hidden_);
76171648 794
ccd9d7c2
PF
795 if (this.attr_('showRangeSelector')) {
796 // The range selector must be created here so that its canvases and contexts get created here.
797 // For some reason, if the canvases and contexts don't get created here, things don't work in IE.
798 // The range selector also sets xAxisHeight in order to reserve space.
799 this.rangeSelector_ = new DygraphRangeSelector(this);
800 }
801
eb7bf005
EC
802 // The interactive parts of the graph are drawn on top of the chart.
803 this.graphDiv.appendChild(this.hidden_);
804 this.graphDiv.appendChild(this.canvas_);
920208fb
PF
805 this.mouseEventElement_ = this.createMouseEventElement_();
806
807 // Create the grapher
808 this.layout_ = new DygraphLayout(this);
809
810 if (this.rangeSelector_) {
811 // This needs to happen after the graph canvases are added to the div and the layout object is created.
812 this.rangeSelector_.addToGraph(this.graphDiv, this.layout_);
813 }
eb7bf005 814
ccd9d7c2
PF
815 // Create the grapher
816 this.layout_ = new DygraphLayout(this);
817
818 if (this.rangeSelector_) {
819 // This needs to happen after the graph canvases are added to the div and the layout object is created.
820 this.rangeSelector_.addToGraph(this.graphDiv, this.layout_);
821 }
822
76171648 823 var dygraph = this;
eb7bf005 824 Dygraph.addEvent(this.mouseEventElement_, 'mousemove', function(e) {
76171648
DV
825 dygraph.mouseMove_(e);
826 });
eb7bf005 827 Dygraph.addEvent(this.mouseEventElement_, 'mouseout', function(e) {
76171648
DV
828 dygraph.mouseOut_(e);
829 });
697e70b2 830
697e70b2 831 this.createStatusMessage_();
697e70b2 832 this.createDragInterface_();
4b4d1a63
DV
833
834 // Update when the window is resized.
835 // TODO(danvk): drop frames depending on complexity of the chart.
836 Dygraph.addEvent(window, 'resize', function(e) {
837 dygraph.resize();
838 });
4cfcc38c
DV
839};
840
841/**
842 * Detach DOM elements in the dygraph and null out all data references.
843 * Calling this when you're done with a dygraph can dramatically reduce memory
844 * usage. See, e.g., the tests/perf.html example.
845 */
846Dygraph.prototype.destroy = function() {
847 var removeRecursive = function(node) {
848 while (node.hasChildNodes()) {
849 removeRecursive(node.firstChild);
850 node.removeChild(node.firstChild);
851 }
852 };
853 removeRecursive(this.maindiv_);
854
855 var nullOut = function(obj) {
856 for (var n in obj) {
857 if (typeof(obj[n]) === 'object') {
858 obj[n] = null;
859 }
860 }
861 };
862
863 // These may not all be necessary, but it can't hurt...
864 nullOut(this.layout_);
865 nullOut(this.plotter_);
866 nullOut(this);
867};
6a1aa64f
DV
868
869/**
629a09ae
DV
870 * Creates the canvas on which the chart will be drawn. Only the Renderer ever
871 * draws on this particular canvas. All Dygraph work (i.e. drawing hover dots
872 * or the zoom rectangles) is done on this.canvas_.
8846615a 873 * @param {Object} canvas The Dygraph canvas over which to overlay the plot
6a1aa64f
DV
874 * @return {Object} The newly-created canvas
875 * @private
876 */
285a6bda 877Dygraph.prototype.createPlotKitCanvas_ = function(canvas) {
f8cfec73 878 var h = Dygraph.createCanvas();
6a1aa64f 879 h.style.position = "absolute";
9ac5e4ae
DV
880 // TODO(danvk): h should be offset from canvas. canvas needs to include
881 // some extra area to make it easier to zoom in on the far left and far
882 // right. h needs to be precisely the plot area, so that clipping occurs.
6a1aa64f
DV
883 h.style.top = canvas.style.top;
884 h.style.left = canvas.style.left;
885 h.width = this.width_;
886 h.height = this.height_;
f8cfec73
DV
887 h.style.width = this.width_ + "px"; // for IE
888 h.style.height = this.height_ + "px"; // for IE
6a1aa64f
DV
889 return h;
890};
891
629a09ae 892/**
920208fb
PF
893 * Creates an overlay element used to handle mouse events.
894 * @return {Object} The mouse event element.
895 * @private
896 */
897Dygraph.prototype.createMouseEventElement_ = function() {
898 if (this.isUsingExcanvas_) {
899 var elem = document.createElement("div");
900 elem.style.position = 'absolute';
901 elem.style.backgroundColor = 'white';
902 elem.style.filter = 'alpha(opacity=0)';
903 elem.style.width = this.width_ + "px";
904 elem.style.height = this.height_ + "px";
905 this.graphDiv.appendChild(elem);
906 return elem;
907 } else {
908 return this.canvas_;
909 }
910};
911
912/**
6a1aa64f
DV
913 * Generate a set of distinct colors for the data series. This is done with a
914 * color wheel. Saturation/Value are customizable, and the hue is
915 * equally-spaced around the color wheel. If a custom set of colors is
916 * specified, that is used instead.
6a1aa64f
DV
917 * @private
918 */
285a6bda 919Dygraph.prototype.setColors_ = function() {
285a6bda 920 var num = this.attr_("labels").length - 1;
6a1aa64f 921 this.colors_ = [];
285a6bda
DV
922 var colors = this.attr_('colors');
923 if (!colors) {
924 var sat = this.attr_('colorSaturation') || 1.0;
925 var val = this.attr_('colorValue') || 0.5;
2aa21213 926 var half = Math.ceil(num / 2);
6a1aa64f 927 for (var i = 1; i <= num; i++) {
ec1959eb 928 if (!this.visibility()[i-1]) continue;
43af96e7 929 // alternate colors for high contrast.
2aa21213 930 var idx = i % 2 ? Math.ceil(i / 2) : (half + i / 2);
43af96e7
NK
931 var hue = (1.0 * idx/ (1 + num));
932 this.colors_.push(Dygraph.hsvToRGB(hue, sat, val));
6a1aa64f
DV
933 }
934 } else {
935 for (var i = 0; i < num; i++) {
ec1959eb 936 if (!this.visibility()[i]) continue;
285a6bda 937 var colorStr = colors[i % colors.length];
f474c2a3 938 this.colors_.push(colorStr);
6a1aa64f
DV
939 }
940 }
600d841a
DV
941
942 this.plotter_.setColors(this.colors_);
629a09ae 943};
6a1aa64f 944
43af96e7
NK
945/**
946 * Return the list of colors. This is either the list of colors passed in the
629a09ae 947 * attributes or the autogenerated list of rgb(r,g,b) strings.
43af96e7
NK
948 * @return {Array<string>} The list of colors.
949 */
950Dygraph.prototype.getColors = function() {
951 return this.colors_;
952};
953
6a1aa64f
DV
954/**
955 * Create the div that contains information on the selected point(s)
956 * This goes in the top right of the canvas, unless an external div has already
957 * been specified.
958 * @private
959 */
fedbd797 960Dygraph.prototype.createStatusMessage_ = function() {
961 var userLabelsDiv = this.user_attrs_["labelsDiv"];
962 if (userLabelsDiv && null != userLabelsDiv
963 && (typeof(userLabelsDiv) == "string" || userLabelsDiv instanceof String)) {
964 this.user_attrs_["labelsDiv"] = document.getElementById(userLabelsDiv);
965 }
285a6bda
DV
966 if (!this.attr_("labelsDiv")) {
967 var divWidth = this.attr_('labelsDivWidth');
b0c3b730 968 var messagestyle = {
6a1aa64f
DV
969 "position": "absolute",
970 "fontSize": "14px",
971 "zIndex": 10,
972 "width": divWidth + "px",
973 "top": "0px",
8846615a 974 "left": (this.width_ - divWidth - 2) + "px",
6a1aa64f
DV
975 "background": "white",
976 "textAlign": "left",
b0c3b730 977 "overflow": "hidden"};
fc80a396 978 Dygraph.update(messagestyle, this.attr_('labelsDivStyles'));
b0c3b730 979 var div = document.createElement("div");
02d8dc64 980 div.className = "dygraph-legend";
b0c3b730 981 for (var name in messagestyle) {
85b99f0b
DV
982 if (messagestyle.hasOwnProperty(name)) {
983 div.style[name] = messagestyle[name];
984 }
b0c3b730
DV
985 }
986 this.graphDiv.appendChild(div);
285a6bda 987 this.attrs_.labelsDiv = div;
6a1aa64f
DV
988 }
989};
990
991/**
ad1798c2
DV
992 * Position the labels div so that:
993 * - its right edge is flush with the right edge of the charting area
994 * - its top edge is flush with the top edge of the charting area
629a09ae 995 * @private
0abfbd7e
DV
996 */
997Dygraph.prototype.positionLabelsDiv_ = function() {
998 // Don't touch a user-specified labelsDiv.
999 if (this.user_attrs_.hasOwnProperty("labelsDiv")) return;
1000
1001 var area = this.plotter_.area;
1002 var div = this.attr_("labelsDiv");
8c21adcf 1003 div.style.left = area.x + area.w - this.attr_("labelsDivWidth") - 1 + "px";
ad1798c2 1004 div.style.top = area.y + "px";
0abfbd7e
DV
1005};
1006
1007/**
6a1aa64f 1008 * Create the text box to adjust the averaging period
6a1aa64f
DV
1009 * @private
1010 */
285a6bda 1011Dygraph.prototype.createRollInterface_ = function() {
8c69de65
DV
1012 // Create a roller if one doesn't exist already.
1013 if (!this.roller_) {
1014 this.roller_ = document.createElement("input");
1015 this.roller_.type = "text";
1016 this.roller_.style.display = "none";
1017 this.graphDiv.appendChild(this.roller_);
1018 }
1019
1020 var display = this.attr_('showRoller') ? 'block' : 'none';
26ca7938 1021
0c38f187 1022 var area = this.plotter_.area;
b0c3b730
DV
1023 var textAttr = { "position": "absolute",
1024 "zIndex": 10,
0c38f187
DV
1025 "top": (area.y + area.h - 25) + "px",
1026 "left": (area.x + 1) + "px",
b0c3b730 1027 "display": display
6a1aa64f 1028 };
8c69de65
DV
1029 this.roller_.size = "2";
1030 this.roller_.value = this.rollPeriod_;
b0c3b730 1031 for (var name in textAttr) {
85b99f0b 1032 if (textAttr.hasOwnProperty(name)) {
8c69de65 1033 this.roller_.style[name] = textAttr[name];
85b99f0b 1034 }
b0c3b730
DV
1035 }
1036
76171648 1037 var dygraph = this;
8c69de65 1038 this.roller_.onchange = function() { dygraph.adjustRoll(dygraph.roller_.value); };
76171648
DV
1039};
1040
629a09ae
DV
1041/**
1042 * @private
629a09ae
DV
1043 * Converts page the x-coordinate of the event to pixel x-coordinates on the
1044 * canvas (i.e. DOM Coords).
1045 */
062ef401
JB
1046Dygraph.prototype.dragGetX_ = function(e, context) {
1047 return Dygraph.pageX(e) - context.px
1048};
bce01b0f 1049
629a09ae
DV
1050/**
1051 * @private
1052 * Converts page the y-coordinate of the event to pixel y-coordinates on the
1053 * canvas (i.e. DOM Coords).
1054 */
062ef401
JB
1055Dygraph.prototype.dragGetY_ = function(e, context) {
1056 return Dygraph.pageY(e) - context.py
1057};
ee672584 1058
629a09ae 1059/**
062ef401
JB
1060 * Set up all the mouse handlers needed to capture dragging behavior for zoom
1061 * events.
1062 * @private
1063 */
1064Dygraph.prototype.createDragInterface_ = function() {
1065 var context = {
1066 // Tracks whether the mouse is down right now
1067 isZooming: false,
1068 isPanning: false, // is this drag part of a pan?
1069 is2DPan: false, // if so, is that pan 1- or 2-dimensional?
8442269f
RK
1070 dragStartX: null, // pixel coordinates
1071 dragStartY: null, // pixel coordinates
1072 dragEndX: null, // pixel coordinates
1073 dragEndY: null, // pixel coordinates
062ef401 1074 dragDirection: null,
8442269f
RK
1075 prevEndX: null, // pixel coordinates
1076 prevEndY: null, // pixel coordinates
062ef401
JB
1077 prevDragDirection: null,
1078
ec291cbe
RK
1079 // The value on the left side of the graph when a pan operation starts.
1080 initialLeftmostDate: null,
1081
1082 // The number of units each pixel spans. (This won't be valid for log
1083 // scales)
1084 xUnitsPerPixel: null,
062ef401
JB
1085
1086 // TODO(danvk): update this comment
1087 // The range in second/value units that the viewport encompasses during a
1088 // panning operation.
1089 dateRange: null,
1090
8442269f
RK
1091 // Top-left corner of the canvas, in DOM coords
1092 // TODO(konigsberg): Rename topLeftCanvasX, topLeftCanvasY.
062ef401
JB
1093 px: 0,
1094 py: 0,
1095
965a030e 1096 // Values for use with panEdgeFraction, which limit how far outside the
4cac8c7a
RK
1097 // graph's data boundaries it can be panned.
1098 boundedDates: null, // [minDate, maxDate]
1099 boundedValues: null, // [[minValue, maxValue] ...]
1100
062ef401
JB
1101 initializeMouseDown: function(event, g, context) {
1102 // prevents mouse drags from selecting page text.
1103 if (event.preventDefault) {
1104 event.preventDefault(); // Firefox, Chrome, etc.
6a1aa64f 1105 } else {
062ef401
JB
1106 event.returnValue = false; // IE
1107 event.cancelBubble = true;
6a1aa64f
DV
1108 }
1109
062ef401
JB
1110 context.px = Dygraph.findPosX(g.canvas_);
1111 context.py = Dygraph.findPosY(g.canvas_);
1112 context.dragStartX = g.dragGetX_(event, context);
1113 context.dragStartY = g.dragGetY_(event, context);
6a1aa64f 1114 }
062ef401 1115 };
2b188b3d 1116
062ef401 1117 var interactionModel = this.attr_("interactionModel");
8b83c6cc 1118
062ef401
JB
1119 // Self is the graph.
1120 var self = this;
6faebb69 1121
062ef401
JB
1122 // Function that binds the graph and context to the handler.
1123 var bindHandler = function(handler) {
1124 return function(event) {
1125 handler(event, self, context);
1126 };
1127 };
1128
1129 for (var eventName in interactionModel) {
1130 if (!interactionModel.hasOwnProperty(eventName)) continue;
1131 Dygraph.addEvent(this.mouseEventElement_, eventName,
1132 bindHandler(interactionModel[eventName]));
1133 }
1134
1135 // If the user releases the mouse button during a drag, but not over the
1136 // canvas, then it doesn't count as a zooming action.
1137 Dygraph.addEvent(document, 'mouseup', function(event) {
1138 if (context.isZooming || context.isPanning) {
1139 context.isZooming = false;
1140 context.dragStartX = null;
1141 context.dragStartY = null;
1142 }
1143
1144 if (context.isPanning) {
1145 context.isPanning = false;
1146 context.draggingDate = null;
1147 context.dateRange = null;
1148 for (var i = 0; i < self.axes_.length; i++) {
1149 delete self.axes_[i].draggingValue;
1150 delete self.axes_[i].dragValueRange;
1151 }
1152 }
6a1aa64f
DV
1153 });
1154};
1155
1156/**
1157 * Draw a gray zoom rectangle over the desired area of the canvas. Also clears
1158 * up any previous zoom rectangles that were drawn. This could be optimized to
1159 * avoid extra redrawing, but it's tricky to avoid interactions with the status
1160 * dots.
ccd9d7c2 1161 *
39b0e098
RK
1162 * @param {Number} direction the direction of the zoom rectangle. Acceptable
1163 * values are Dygraph.HORIZONTAL and Dygraph.VERTICAL.
6a1aa64f
DV
1164 * @param {Number} startX The X position where the drag started, in canvas
1165 * coordinates.
1166 * @param {Number} endX The current X position of the drag, in canvas coords.
8b83c6cc
RK
1167 * @param {Number} startY The Y position where the drag started, in canvas
1168 * coordinates.
1169 * @param {Number} endY The current Y position of the drag, in canvas coords.
39b0e098 1170 * @param {Number} prevDirection the value of direction on the previous call to
8b83c6cc 1171 * this function. Used to avoid excess redrawing
6a1aa64f
DV
1172 * @param {Number} prevEndX The value of endX on the previous call to this
1173 * function. Used to avoid excess redrawing
8b83c6cc
RK
1174 * @param {Number} prevEndY The value of endY on the previous call to this
1175 * function. Used to avoid excess redrawing
6a1aa64f
DV
1176 * @private
1177 */
7201b11e
JB
1178Dygraph.prototype.drawZoomRect_ = function(direction, startX, endX, startY,
1179 endY, prevDirection, prevEndX,
1180 prevEndY) {
2cf95fff 1181 var ctx = this.canvas_ctx_;
6a1aa64f
DV
1182
1183 // Clean up from the previous rect if necessary
39b0e098 1184 if (prevDirection == Dygraph.HORIZONTAL) {
fa54c193
FXB
1185 ctx.clearRect(Math.min(startX, prevEndX), this.layout_.getPlotArea().y,
1186 Math.abs(startX - prevEndX), this.layout_.getPlotArea().h);
39b0e098 1187 } else if (prevDirection == Dygraph.VERTICAL){
fa54c193
FXB
1188 ctx.clearRect(this.layout_.getPlotArea().x, Math.min(startY, prevEndY),
1189 this.layout_.getPlotArea().w, Math.abs(startY - prevEndY));
6a1aa64f
DV
1190 }
1191
1192 // Draw a light-grey rectangle to show the new viewing area
39b0e098 1193 if (direction == Dygraph.HORIZONTAL) {
8b83c6cc
RK
1194 if (endX && startX) {
1195 ctx.fillStyle = "rgba(128,128,128,0.33)";
fa54c193
FXB
1196 ctx.fillRect(Math.min(startX, endX), this.layout_.getPlotArea().y,
1197 Math.abs(endX - startX), this.layout_.getPlotArea().h);
8b83c6cc 1198 }
920208fb 1199 } else if (direction == Dygraph.VERTICAL) {
8b83c6cc
RK
1200 if (endY && startY) {
1201 ctx.fillStyle = "rgba(128,128,128,0.33)";
fa54c193
FXB
1202 ctx.fillRect(this.layout_.getPlotArea().x, Math.min(startY, endY),
1203 this.layout_.getPlotArea().w, Math.abs(endY - startY));
8b83c6cc 1204 }
6a1aa64f 1205 }
920208fb
PF
1206
1207 if (this.isUsingExcanvas_) {
1208 this.currentZoomRectArgs_ = [direction, startX, endX, startY, endY, 0, 0, 0];
1209 }
1210};
1211
1212/**
1213 * Clear the zoom rectangle (and perform no zoom).
1214 * @private
1215 */
1216Dygraph.prototype.clearZoomRect_ = function() {
1217 this.currentZoomRectArgs_ = null;
1218 this.canvas_ctx_.clearRect(0, 0, this.canvas_.width, this.canvas_.height);
6a1aa64f
DV
1219};
1220
1221/**
8b83c6cc
RK
1222 * Zoom to something containing [lowX, highX]. These are pixel coordinates in
1223 * the canvas. The exact zoom window may be slightly larger if there are no data
1224 * points near lowX or highX. Don't confuse this function with doZoomXDates,
1225 * which accepts dates that match the raw data. This function redraws the graph.
d58ae307 1226 *
6a1aa64f
DV
1227 * @param {Number} lowX The leftmost pixel value that should be visible.
1228 * @param {Number} highX The rightmost pixel value that should be visible.
1229 * @private
1230 */
8b83c6cc 1231Dygraph.prototype.doZoomX_ = function(lowX, highX) {
920208fb 1232 this.currentZoomRectArgs_ = null;
6a1aa64f 1233 // Find the earliest and latest dates contained in this canvasx range.
8b83c6cc 1234 // Convert the call to date ranges of the raw data.
ff022deb
RK
1235 var minDate = this.toDataXCoord(lowX);
1236 var maxDate = this.toDataXCoord(highX);
8b83c6cc
RK
1237 this.doZoomXDates_(minDate, maxDate);
1238};
6a1aa64f 1239
8b83c6cc 1240/**
b1a3b195
DV
1241 * Transition function to use in animations. Returns values between 0.0
1242 * (totally old values) and 1.0 (totally new values) for each frame.
1243 * @private
1244 */
1245Dygraph.zoomAnimationFunction = function(frame, numFrames) {
1246 var k = 1.5;
1247 return (1.0 - Math.pow(k, -frame)) / (1.0 - Math.pow(k, -numFrames));
1248};
1249
1250/**
8b83c6cc
RK
1251 * Zoom to something containing [minDate, maxDate] values. Don't confuse this
1252 * method with doZoomX which accepts pixel coordinates. This function redraws
1253 * the graph.
d58ae307 1254 *
8b83c6cc
RK
1255 * @param {Number} minDate The minimum date that should be visible.
1256 * @param {Number} maxDate The maximum date that should be visible.
1257 * @private
1258 */
1259Dygraph.prototype.doZoomXDates_ = function(minDate, maxDate) {
b1a3b195
DV
1260 // TODO(danvk): when yAxisRange is null (i.e. "fit to data", the animation
1261 // can produce strange effects. Rather than the y-axis transitioning slowly
1262 // between values, it can jerk around.)
1263 var old_window = this.xAxisRange();
1264 var new_window = [minDate, maxDate];
57baab03 1265 this.zoomed_x_ = true;
b1a3b195
DV
1266 var that = this;
1267 this.doAnimatedZoom(old_window, new_window, null, null, function() {
1268 if (that.attr_("zoomCallback")) {
1269 that.attr_("zoomCallback")(minDate, maxDate, that.yAxisRanges());
1270 }
1271 });
8b83c6cc
RK
1272};
1273
1274/**
1275 * Zoom to something containing [lowY, highY]. These are pixel coordinates in
d58ae307
DV
1276 * the canvas. This function redraws the graph.
1277 *
8b83c6cc
RK
1278 * @param {Number} lowY The topmost pixel value that should be visible.
1279 * @param {Number} highY The lowest pixel value that should be visible.
1280 * @private
1281 */
1282Dygraph.prototype.doZoomY_ = function(lowY, highY) {
920208fb 1283 this.currentZoomRectArgs_ = null;
d58ae307
DV
1284 // Find the highest and lowest values in pixel range for each axis.
1285 // Note that lowY (in pixels) corresponds to the max Value (in data coords).
1286 // This is because pixels increase as you go down on the screen, whereas data
1287 // coordinates increase as you go up the screen.
b1a3b195
DV
1288 var oldValueRanges = this.yAxisRanges();
1289 var newValueRanges = [];
d58ae307 1290 for (var i = 0; i < this.axes_.length; i++) {
ff022deb
RK
1291 var hi = this.toDataYCoord(lowY, i);
1292 var low = this.toDataYCoord(highY, i);
b1a3b195 1293 newValueRanges.push([low, hi]);
d58ae307 1294 }
8b83c6cc 1295
57baab03 1296 this.zoomed_y_ = true;
b1a3b195
DV
1297 var that = this;
1298 this.doAnimatedZoom(null, null, oldValueRanges, newValueRanges, function() {
1299 if (that.attr_("zoomCallback")) {
1300 var xRange = that.xAxisRange();
1301 var yRange = that.yAxisRange();
1302 that.attr_("zoomCallback")(xRange[0], xRange[1], that.yAxisRanges());
1303 }
1304 });
8b83c6cc
RK
1305};
1306
1307/**
1308 * Reset the zoom to the original view coordinates. This is the same as
1309 * double-clicking on the graph.
d58ae307 1310 *
8b83c6cc
RK
1311 * @private
1312 */
1313Dygraph.prototype.doUnzoom_ = function() {
b1a3b195 1314 var dirty = false, dirtyX = false, dirtyY = false;
8b83c6cc 1315 if (this.dateWindow_ != null) {
d58ae307 1316 dirty = true;
b1a3b195 1317 dirtyX = true;
8b83c6cc 1318 }
d58ae307
DV
1319
1320 for (var i = 0; i < this.axes_.length; i++) {
1321 if (this.axes_[i].valueWindow != null) {
1322 dirty = true;
b1a3b195 1323 dirtyY = true;
d58ae307 1324 }
8b83c6cc
RK
1325 }
1326
da1369a5
DV
1327 // Clear any selection, since it's likely to be drawn in the wrong place.
1328 this.clearSelection();
1329
8b83c6cc 1330 if (dirty) {
57baab03
NN
1331 this.zoomed_x_ = false;
1332 this.zoomed_y_ = false;
b1a3b195
DV
1333
1334 var minDate = this.rawData_[0][0];
1335 var maxDate = this.rawData_[this.rawData_.length - 1][0];
1336
1337 // With only one frame, don't bother calculating extreme ranges.
1338 // TODO(danvk): merge this block w/ the code below.
1339 if (!this.attr_("animatedZooms")) {
1340 this.dateWindow_ = null;
1341 for (var i = 0; i < this.axes_.length; i++) {
1342 if (this.axes_[i].valueWindow != null) {
1343 delete this.axes_[i].valueWindow;
1344 }
1345 }
1346 this.drawGraph_();
1347 if (this.attr_("zoomCallback")) {
1348 this.attr_("zoomCallback")(minDate, maxDate, this.yAxisRanges());
1349 }
1350 return;
1351 }
1352
1353 var oldWindow=null, newWindow=null, oldValueRanges=null, newValueRanges=null;
1354 if (dirtyX) {
1355 oldWindow = this.xAxisRange();
1356 newWindow = [minDate, maxDate];
1357 }
1358
1359 if (dirtyY) {
1360 oldValueRanges = this.yAxisRanges();
1361 // TODO(danvk): this is pretty inefficient
1362 var packed = this.gatherDatasets_(this.rolledSeries_, null);
1363 var extremes = packed[1];
1364
1365 // this has the side-effect of modifying this.axes_.
1366 // this doesn't make much sense in this context, but it's convenient (we
1367 // need this.axes_[*].extremeValues) and not harmful since we'll be
1368 // calling drawGraph_ shortly, which clobbers these values.
1369 this.computeYAxisRanges_(extremes);
1370
1371 newValueRanges = [];
1372 for (var i = 0; i < this.axes_.length; i++) {
1373 newValueRanges.push(this.axes_[i].extremeRange);
1374 }
1375 }
1376
1377 var that = this;
1378 this.doAnimatedZoom(oldWindow, newWindow, oldValueRanges, newValueRanges,
1379 function() {
1380 that.dateWindow_ = null;
1381 for (var i = 0; i < that.axes_.length; i++) {
1382 if (that.axes_[i].valueWindow != null) {
1383 delete that.axes_[i].valueWindow;
1384 }
1385 }
1386 if (that.attr_("zoomCallback")) {
1387 that.attr_("zoomCallback")(minDate, maxDate, that.yAxisRanges());
1388 }
1389 });
1390 }
1391};
1392
1393/**
1394 * Combined animation logic for all zoom functions.
1395 * either the x parameters or y parameters may be null.
1396 * @private
1397 */
1398Dygraph.prototype.doAnimatedZoom = function(oldXRange, newXRange, oldYRanges, newYRanges, callback) {
1399 var steps = this.attr_("animatedZooms") ? Dygraph.ANIMATION_STEPS : 1;
1400
1401 var windows = [];
1402 var valueRanges = [];
1403
1404 if (oldXRange != null && newXRange != null) {
1405 for (var step = 1; step <= steps; step++) {
1406 var frac = Dygraph.zoomAnimationFunction(step, steps);
1407 windows[step-1] = [oldXRange[0]*(1-frac) + frac*newXRange[0],
1408 oldXRange[1]*(1-frac) + frac*newXRange[1]];
8b83c6cc 1409 }
67e650dc 1410 }
b1a3b195
DV
1411
1412 if (oldYRanges != null && newYRanges != null) {
1413 for (var step = 1; step <= steps; step++) {
1414 var frac = Dygraph.zoomAnimationFunction(step, steps);
1415 var thisRange = [];
1416 for (var j = 0; j < this.axes_.length; j++) {
1417 thisRange.push([oldYRanges[j][0]*(1-frac) + frac*newYRanges[j][0],
1418 oldYRanges[j][1]*(1-frac) + frac*newYRanges[j][1]]);
1419 }
1420 valueRanges[step-1] = thisRange;
1421 }
1422 }
1423
1424 var that = this;
1425 Dygraph.repeatAndCleanup(function(step) {
1426 if (valueRanges.length) {
1427 for (var i = 0; i < that.axes_.length; i++) {
1428 var w = valueRanges[step][i];
1429 that.axes_[i].valueWindow = [w[0], w[1]];
1430 }
1431 }
1432 if (windows.length) {
1433 that.dateWindow_ = windows[step];
1434 }
1435 that.drawGraph_();
1436 }, steps, Dygraph.ANIMATION_DURATION / steps, callback);
6a1aa64f
DV
1437};
1438
1439/**
1440 * When the mouse moves in the canvas, display information about a nearby data
1441 * point and draw dots over those points in the data series. This function
1442 * takes care of cleanup of previously-drawn dots.
1443 * @param {Object} event The mousemove event from the browser.
1444 * @private
1445 */
285a6bda 1446Dygraph.prototype.mouseMove_ = function(event) {
e863a17d 1447 // This prevents JS errors when mousing over the canvas before data loads.
4cac8c7a 1448 var points = this.layout_.points;
685ebbb3 1449 if (points === undefined) return;
e863a17d 1450
4cac8c7a
RK
1451 var canvasx = Dygraph.pageX(event) - Dygraph.findPosX(this.mouseEventElement_);
1452
6a1aa64f
DV
1453 var lastx = -1;
1454 var lasty = -1;
1455
1456 // Loop through all the points and find the date nearest to our current
1457 // location.
1458 var minDist = 1e+100;
1459 var idx = -1;
1460 for (var i = 0; i < points.length; i++) {
8a7cc60e
RK
1461 var point = points[i];
1462 if (point == null) continue;
062ef401 1463 var dist = Math.abs(point.canvasx - canvasx);
f032c51d 1464 if (dist > minDist) continue;
6a1aa64f
DV
1465 minDist = dist;
1466 idx = i;
1467 }
1468 if (idx >= 0) lastx = points[idx].xval;
6a1aa64f
DV
1469
1470 // Extract the points we've selected
b258a3da 1471 this.selPoints_ = [];
50360fd0 1472 var l = points.length;
416b05ad
NK
1473 if (!this.attr_("stackedGraph")) {
1474 for (var i = 0; i < l; i++) {
1475 if (points[i].xval == lastx) {
1476 this.selPoints_.push(points[i]);
1477 }
1478 }
1479 } else {
354e15ab
DE
1480 // Need to 'unstack' points starting from the bottom
1481 var cumulative_sum = 0;
416b05ad
NK
1482 for (var i = l - 1; i >= 0; i--) {
1483 if (points[i].xval == lastx) {
354e15ab 1484 var p = {}; // Clone the point since we modify it
d4139cd8
NK
1485 for (var k in points[i]) {
1486 p[k] = points[i][k];
50360fd0
NK
1487 }
1488 p.yval -= cumulative_sum;
1489 cumulative_sum += p.yval;
d4139cd8 1490 this.selPoints_.push(p);
12e4c741 1491 }
6a1aa64f 1492 }
354e15ab 1493 this.selPoints_.reverse();
6a1aa64f
DV
1494 }
1495
b258a3da 1496 if (this.attr_("highlightCallback")) {
a4c6a67c 1497 var px = this.lastx_;
dd082dda 1498 if (px !== null && lastx != px) {
344ba8c0 1499 // only fire if the selected point has changed.
2ddb1197 1500 this.attr_("highlightCallback")(event, lastx, this.selPoints_, this.idxToRow_(idx));
43af96e7 1501 }
12e4c741 1502 }
43af96e7 1503
239c712d
NAG
1504 // Save last x position for callbacks.
1505 this.lastx_ = lastx;
50360fd0 1506
239c712d
NAG
1507 this.updateSelection_();
1508};
b258a3da 1509
239c712d 1510/**
1903f1e4 1511 * Transforms layout_.points index into data row number.
2ddb1197 1512 * @param int layout_.points index
1903f1e4 1513 * @return int row number, or -1 if none could be found.
2ddb1197
SC
1514 * @private
1515 */
1516Dygraph.prototype.idxToRow_ = function(idx) {
1903f1e4 1517 if (idx < 0) return -1;
2ddb1197 1518
1903f1e4
DV
1519 for (var i in this.layout_.datasets) {
1520 if (idx < this.layout_.datasets[i].length) {
1521 return this.boundaryIds_[0][0]+idx;
1522 }
1523 idx -= this.layout_.datasets[i].length;
1524 }
1525 return -1;
1526};
2ddb1197 1527
629a09ae
DV
1528/**
1529 * @private
629a09ae
DV
1530 * Generates HTML for the legend which is displayed when hovering over the
1531 * chart. If no selected points are specified, a default legend is returned
1532 * (this may just be the empty string).
1533 * @param { Number } [x] The x-value of the selected points.
1534 * @param { [Object] } [sel_points] List of selected points for the given
1535 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
1536 */
e9fe4a2f 1537Dygraph.prototype.generateLegendHTML_ = function(x, sel_points) {
2fccd3dc
DV
1538 // If no points are selected, we display a default legend. Traditionally,
1539 // this has been blank. But a better default would be a conventional legend,
1540 // which provides essential information for a non-interactive chart.
1541 if (typeof(x) === 'undefined') {
1542 if (this.attr_('legend') != 'always') return '';
1543
1544 var sepLines = this.attr_('labelsSeparateLines');
1545 var labels = this.attr_('labels');
1546 var html = '';
1547 for (var i = 1; i < labels.length; i++) {
352c8310 1548 if (!this.visibility()[i - 1]) continue;
bafe040e 1549 var c = this.plotter_.colors[labels[i]];
352c8310 1550 if (html != '') html += (sepLines ? '<br/>' : ' ');
bafe040e
DV
1551 html += "<b><span style='color: " + c + ";'>&mdash;" + labels[i] +
1552 "</span></b>";
2fccd3dc
DV
1553 }
1554 return html;
1555 }
1556
48e614ac
DV
1557 var xOptView = this.optionsViewForAxis_('x');
1558 var xvf = xOptView('valueFormatter');
1559 var html = xvf(x, xOptView, this.attr_('labels')[0], this) + ":";
e9fe4a2f 1560
48e614ac
DV
1561 var yOptViews = [];
1562 var num_axes = this.numAxes();
1563 for (var i = 0; i < num_axes; i++) {
1564 yOptViews[i] = this.optionsViewForAxis_('y' + (i ? 1 + i : ''));
1565 }
e9fe4a2f
DV
1566 var showZeros = this.attr_("labelsShowZeroValues");
1567 var sepLines = this.attr_("labelsSeparateLines");
1568 for (var i = 0; i < this.selPoints_.length; i++) {
1569 var pt = this.selPoints_[i];
1570 if (pt.yval == 0 && !showZeros) continue;
1571 if (!Dygraph.isOK(pt.canvasy)) continue;
1572 if (sepLines) html += "<br/>";
1573
48e614ac
DV
1574 var yOptView = yOptViews[this.seriesToAxisMap_[pt.name]];
1575 var fmtFunc = yOptView('valueFormatter');
bafe040e 1576 var c = this.plotter_.colors[pt.name];
48e614ac
DV
1577 var yval = fmtFunc(pt.yval, yOptView, pt.name, this);
1578
2fccd3dc 1579 // TODO(danvk): use a template string here and make it an attribute.
bafe040e
DV
1580 html += " <b><span style='color: " + c + ";'>"
1581 + pt.name + "</span></b>:"
e9fe4a2f
DV
1582 + yval;
1583 }
1584 return html;
1585};
1586
629a09ae
DV
1587/**
1588 * @private
1589 * Displays information about the selected points in the legend. If there is no
1590 * selection, the legend will be cleared.
1591 * @param { Number } [x] The x-value of the selected points.
1592 * @param { [Object] } [sel_points] List of selected points for the given
1593 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
1594 */
91c10d9c
DV
1595Dygraph.prototype.setLegendHTML_ = function(x, sel_points) {
1596 var html = this.generateLegendHTML_(x, sel_points);
1597 var labelsDiv = this.attr_("labelsDiv");
1598 if (labelsDiv !== null) {
1599 labelsDiv.innerHTML = html;
1600 } else {
1601 if (typeof(this.shown_legend_error_) == 'undefined') {
1602 this.error('labelsDiv is set to something nonexistent; legend will not be shown.');
1603 this.shown_legend_error_ = true;
1604 }
1605 }
1606};
1607
2ddb1197 1608/**
239c712d
NAG
1609 * Draw dots over the selectied points in the data series. This function
1610 * takes care of cleanup of previously-drawn dots.
1611 * @private
1612 */
1613Dygraph.prototype.updateSelection_ = function() {
6a1aa64f 1614 // Clear the previously drawn vertical, if there is one
2cf95fff 1615 var ctx = this.canvas_ctx_;
6a1aa64f 1616 if (this.previousVerticalX_ >= 0) {
46dde5f9
DV
1617 // Determine the maximum highlight circle size.
1618 var maxCircleSize = 0;
227b93cc
DV
1619 var labels = this.attr_('labels');
1620 for (var i = 1; i < labels.length; i++) {
1621 var r = this.attr_('highlightCircleSize', labels[i]);
46dde5f9
DV
1622 if (r > maxCircleSize) maxCircleSize = r;
1623 }
6a1aa64f 1624 var px = this.previousVerticalX_;
46dde5f9
DV
1625 ctx.clearRect(px - maxCircleSize - 1, 0,
1626 2 * maxCircleSize + 2, this.height_);
6a1aa64f
DV
1627 }
1628
920208fb
PF
1629 if (this.isUsingExcanvas_ && this.currentZoomRectArgs_) {
1630 Dygraph.prototype.drawZoomRect_.apply(this, this.currentZoomRectArgs_);
1631 }
1632
d160cc3b 1633 if (this.selPoints_.length > 0) {
6a1aa64f 1634 // Set the status message to indicate the selected point(s)
d160cc3b 1635 if (this.attr_('showLabelsOnHighlight')) {
91c10d9c 1636 this.setLegendHTML_(this.lastx_, this.selPoints_);
6a1aa64f 1637 }
6a1aa64f 1638
6a1aa64f 1639 // Draw colored circles over the center of each selected point
e9fe4a2f 1640 var canvasx = this.selPoints_[0].canvasx;
43af96e7 1641 ctx.save();
b258a3da 1642 for (var i = 0; i < this.selPoints_.length; i++) {
e9fe4a2f
DV
1643 var pt = this.selPoints_[i];
1644 if (!Dygraph.isOK(pt.canvasy)) continue;
1645
1646 var circleSize = this.attr_('highlightCircleSize', pt.name);
6a1aa64f 1647 ctx.beginPath();
e9fe4a2f
DV
1648 ctx.fillStyle = this.plotter_.colors[pt.name];
1649 ctx.arc(canvasx, pt.canvasy, circleSize, 0, 2 * Math.PI, false);
6a1aa64f
DV
1650 ctx.fill();
1651 }
1652 ctx.restore();
1653
1654 this.previousVerticalX_ = canvasx;
1655 }
1656};
1657
1658/**
629a09ae
DV
1659 * Manually set the selected points and display information about them in the
1660 * legend. The selection can be cleared using clearSelection() and queried
1661 * using getSelection().
1662 * @param { Integer } row number that should be highlighted (i.e. appear with
1663 * hover dots on the chart). Set to false to clear any selection.
239c712d
NAG
1664 */
1665Dygraph.prototype.setSelection = function(row) {
1666 // Extract the points we've selected
1667 this.selPoints_ = [];
1668 var pos = 0;
50360fd0 1669
239c712d 1670 if (row !== false) {
b1a3b195 1671 row = row - this.boundaryIds_[0][0];
16269f6e 1672 }
50360fd0 1673
16269f6e 1674 if (row !== false && row >= 0) {
239c712d 1675 for (var i in this.layout_.datasets) {
16269f6e 1676 if (row < this.layout_.datasets[i].length) {
38f33a44 1677 var point = this.layout_.points[pos+row];
ccd9d7c2 1678
38f33a44 1679 if (this.attr_("stackedGraph")) {
8c03ba63 1680 point = this.layout_.unstackPointAtIndex(pos+row);
38f33a44 1681 }
ccd9d7c2 1682
38f33a44 1683 this.selPoints_.push(point);
16269f6e 1684 }
239c712d
NAG
1685 pos += this.layout_.datasets[i].length;
1686 }
16269f6e 1687 }
50360fd0 1688
16269f6e 1689 if (this.selPoints_.length) {
239c712d
NAG
1690 this.lastx_ = this.selPoints_[0].xval;
1691 this.updateSelection_();
1692 } else {
239c712d
NAG
1693 this.clearSelection();
1694 }
1695
1696};
1697
1698/**
6a1aa64f
DV
1699 * The mouse has left the canvas. Clear out whatever artifacts remain
1700 * @param {Object} event the mouseout event from the browser.
1701 * @private
1702 */
285a6bda 1703Dygraph.prototype.mouseOut_ = function(event) {
a4c6a67c
AV
1704 if (this.attr_("unhighlightCallback")) {
1705 this.attr_("unhighlightCallback")(event);
1706 }
1707
43af96e7 1708 if (this.attr_("hideOverlayOnMouseOut")) {
239c712d 1709 this.clearSelection();
43af96e7 1710 }
6a1aa64f
DV
1711};
1712
239c712d 1713/**
629a09ae
DV
1714 * Clears the current selection (i.e. points that were highlighted by moving
1715 * the mouse over the chart).
239c712d
NAG
1716 */
1717Dygraph.prototype.clearSelection = function() {
1718 // Get rid of the overlay data
2cf95fff 1719 this.canvas_ctx_.clearRect(0, 0, this.width_, this.height_);
91c10d9c 1720 this.setLegendHTML_();
239c712d
NAG
1721 this.selPoints_ = [];
1722 this.lastx_ = -1;
1723}
1724
103b7292 1725/**
629a09ae
DV
1726 * Returns the number of the currently selected row. To get data for this row,
1727 * you can use the getValue method.
1728 * @return { Integer } row number, or -1 if nothing is selected
103b7292
NAG
1729 */
1730Dygraph.prototype.getSelection = function() {
1731 if (!this.selPoints_ || this.selPoints_.length < 1) {
1732 return -1;
1733 }
50360fd0 1734
103b7292
NAG
1735 for (var row=0; row<this.layout_.points.length; row++ ) {
1736 if (this.layout_.points[row].x == this.selPoints_[0].x) {
16269f6e 1737 return row + this.boundaryIds_[0][0];
103b7292
NAG
1738 }
1739 }
1740 return -1;
2e1fcf1a 1741};
103b7292 1742
19589a3e 1743/**
6a1aa64f
DV
1744 * Fires when there's data available to be graphed.
1745 * @param {String} data Raw CSV data to be plotted
1746 * @private
1747 */
285a6bda 1748Dygraph.prototype.loadedEvent_ = function(data) {
6a1aa64f 1749 this.rawData_ = this.parseCSV_(data);
26ca7938 1750 this.predraw_();
6a1aa64f
DV
1751};
1752
6a1aa64f
DV
1753/**
1754 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
1755 * @private
1756 */
285a6bda 1757Dygraph.prototype.addXTicks_ = function() {
6a1aa64f 1758 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
7201b11e 1759 var range;
6a1aa64f 1760 if (this.dateWindow_) {
7201b11e 1761 range = [this.dateWindow_[0], this.dateWindow_[1]];
6a1aa64f 1762 } else {
7201b11e
JB
1763 range = [this.rawData_[0][0], this.rawData_[this.rawData_.length - 1][0]];
1764 }
1765
48e614ac
DV
1766 var xAxisOptionsView = this.optionsViewForAxis_('x');
1767 var xTicks = xAxisOptionsView('ticker')(
1768 range[0],
1769 range[1],
1770 this.width_, // TODO(danvk): should be area.width
1771 xAxisOptionsView,
1772 this);
1773 // var msg = 'ticker(' + range[0] + ', ' + range[1] + ', ' + this.width_ + ', ' + this.attr_('pixelsPerXLabel') + ') -> ' + JSON.stringify(xTicks);
1774 // console.log(msg);
b2c9222a 1775 this.layout_.setXTicks(xTicks);
32988383
DV
1776};
1777
629a09ae
DV
1778/**
1779 * @private
1780 * Computes the range of the data series (including confidence intervals).
1781 * @param { [Array] } series either [ [x1, y1], [x2, y2], ... ] or
1782 * [ [x1, [y1, dev_low, dev_high]], [x2, [y2, dev_low, dev_high]], ...
1783 * @return [low, high]
1784 */
5011e7a1
DV
1785Dygraph.prototype.extremeValues_ = function(series) {
1786 var minY = null, maxY = null;
1787
9922b78b 1788 var bars = this.attr_("errorBars") || this.attr_("customBars");
5011e7a1
DV
1789 if (bars) {
1790 // With custom bars, maxY is the max of the high values.
1791 for (var j = 0; j < series.length; j++) {
1792 var y = series[j][1][0];
1793 if (!y) continue;
1794 var low = y - series[j][1][1];
1795 var high = y + series[j][1][2];
1796 if (low > y) low = y; // this can happen with custom bars,
1797 if (high < y) high = y; // e.g. in tests/custom-bars.html
1798 if (maxY == null || high > maxY) {
1799 maxY = high;
1800 }
1801 if (minY == null || low < minY) {
1802 minY = low;
1803 }
1804 }
1805 } else {
1806 for (var j = 0; j < series.length; j++) {
1807 var y = series[j][1];
d12999d3 1808 if (y === null || isNaN(y)) continue;
5011e7a1
DV
1809 if (maxY == null || y > maxY) {
1810 maxY = y;
1811 }
1812 if (minY == null || y < minY) {
1813 minY = y;
1814 }
1815 }
1816 }
1817
1818 return [minY, maxY];
1819};
1820
6a1aa64f 1821/**
629a09ae 1822 * @private
26ca7938
DV
1823 * This function is called once when the chart's data is changed or the options
1824 * dictionary is updated. It is _not_ called when the user pans or zooms. The
1825 * idea is that values derived from the chart's data can be computed here,
1826 * rather than every time the chart is drawn. This includes things like the
1827 * number of axes, rolling averages, etc.
1828 */
1829Dygraph.prototype.predraw_ = function() {
7153e001
DV
1830 var start = new Date();
1831
26ca7938
DV
1832 // TODO(danvk): move more computations out of drawGraph_ and into here.
1833 this.computeYAxes_();
1834
1835 // Create a new plotter.
70c80071 1836 if (this.plotter_) this.plotter_.clear();
26ca7938 1837 this.plotter_ = new DygraphCanvasRenderer(this,
2cf95fff
RK
1838 this.hidden_,
1839 this.hidden_ctx_,
0e23cfc6 1840 this.layout_);
26ca7938 1841
0abfbd7e
DV
1842 // The roller sits in the bottom left corner of the chart. We don't know where
1843 // this will be until the options are available, so it's positioned here.
8c69de65 1844 this.createRollInterface_();
26ca7938 1845
0abfbd7e
DV
1846 // Same thing applies for the labelsDiv. It's right edge should be flush with
1847 // the right edge of the charting area (which may not be the same as the right
1848 // edge of the div, if we have two y-axes.
1849 this.positionLabelsDiv_();
1850
ccd9d7c2
PF
1851 if (this.rangeSelector_) {
1852 this.rangeSelector_.renderStaticLayer();
1853 }
1854
b1a3b195
DV
1855 // Convert the raw data (a 2D array) into the internal format and compute
1856 // rolling averages.
1857 this.rolledSeries_ = [null]; // x-axis is the first series and it's special
1858 for (var i = 1; i < this.rawData_[0].length; i++) {
1859 var connectSeparatedPoints = this.attr_('connectSeparatedPoints', i);
1860 var logScale = this.attr_('logscale', i);
1861 var series = this.extractSeries_(this.rawData_, i, logScale, connectSeparatedPoints);
1862 series = this.rollingAverage(series, this.rollPeriod_);
1863 this.rolledSeries_.push(series);
1864 }
1865
26ca7938
DV
1866 // If the data or options have changed, then we'd better redraw.
1867 this.drawGraph_();
4b4d1a63
DV
1868
1869 // This is used to determine whether to do various animations.
1870 var end = new Date();
1871 this.drawingTimeMs_ = (end - start);
26ca7938
DV
1872};
1873
1874/**
b1a3b195
DV
1875 * Loop over all fields and create datasets, calculating extreme y-values for
1876 * each series and extreme x-indices as we go.
fc4e84fa 1877 *
b1a3b195
DV
1878 * dateWindow is passed in as an explicit parameter so that we can compute
1879 * extreme values "speculatively", i.e. without actually setting state on the
1880 * dygraph.
fc4e84fa 1881 *
b1a3b195
DV
1882 * TODO(danvk): make this more of a true function
1883 * @return [ datasets, seriesExtremes, boundaryIds ]
6a1aa64f
DV
1884 * @private
1885 */
b1a3b195
DV
1886Dygraph.prototype.gatherDatasets_ = function(rolledSeries, dateWindow) {
1887 var boundaryIds = [];
354e15ab
DE
1888 var cumulative_y = []; // For stacked series.
1889 var datasets = [];
f09fc545
DV
1890 var extremes = {}; // series name -> [low, high]
1891
b1a3b195
DV
1892 // Loop over the fields (series). Go from the last to the first,
1893 // because if they're stacked that's how we accumulate the values.
1894 var num_series = rolledSeries.length - 1;
1895 for (var i = num_series; i >= 1; i--) {
1cf11047
DV
1896 if (!this.visibility()[i - 1]) continue;
1897
b1a3b195 1898 // TODO(danvk): is this copy really necessary?
6a1aa64f 1899 var series = [];
b1a3b195
DV
1900 for (var j = 0; j < rolledSeries[i].length; j++) {
1901 series.push(rolledSeries[i][j]);
6a1aa64f 1902 }
2f5e7e1a 1903
6a1aa64f 1904 // Prune down to the desired range, if necessary (for zooming)
1a26f3fb
DV
1905 // Because there can be lines going to points outside of the visible area,
1906 // we actually prune to visible points, plus one on either side.
9922b78b 1907 var bars = this.attr_("errorBars") || this.attr_("customBars");
b1a3b195
DV
1908 if (dateWindow) {
1909 var low = dateWindow[0];
1910 var high = dateWindow[1];
6a1aa64f 1911 var pruned = [];
1a26f3fb
DV
1912 // TODO(danvk): do binary search instead of linear search.
1913 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
1914 var firstIdx = null, lastIdx = null;
6a1aa64f 1915 for (var k = 0; k < series.length; k++) {
1a26f3fb
DV
1916 if (series[k][0] >= low && firstIdx === null) {
1917 firstIdx = k;
1918 }
1919 if (series[k][0] <= high) {
1920 lastIdx = k;
6a1aa64f
DV
1921 }
1922 }
1a26f3fb
DV
1923 if (firstIdx === null) firstIdx = 0;
1924 if (firstIdx > 0) firstIdx--;
1925 if (lastIdx === null) lastIdx = series.length - 1;
1926 if (lastIdx < series.length - 1) lastIdx++;
b1a3b195 1927 boundaryIds[i-1] = [firstIdx, lastIdx];
1a26f3fb
DV
1928 for (var k = firstIdx; k <= lastIdx; k++) {
1929 pruned.push(series[k]);
6a1aa64f
DV
1930 }
1931 series = pruned;
16269f6e 1932 } else {
b1a3b195 1933 boundaryIds[i-1] = [0, series.length-1];
6a1aa64f
DV
1934 }
1935
f09fc545 1936 var seriesExtremes = this.extremeValues_(series);
5011e7a1 1937
6a1aa64f 1938 if (bars) {
354e15ab
DE
1939 for (var j=0; j<series.length; j++) {
1940 val = [series[j][0], series[j][1][0], series[j][1][1], series[j][1][2]];
1941 series[j] = val;
1942 }
43af96e7 1943 } else if (this.attr_("stackedGraph")) {
43af96e7
NK
1944 var l = series.length;
1945 var actual_y;
1946 for (var j = 0; j < l; j++) {
354e15ab
DE
1947 // If one data set has a NaN, let all subsequent stacked
1948 // sets inherit the NaN -- only start at 0 for the first set.
1949 var x = series[j][0];
41b0f691 1950 if (cumulative_y[x] === undefined) {
354e15ab 1951 cumulative_y[x] = 0;
41b0f691 1952 }
43af96e7
NK
1953
1954 actual_y = series[j][1];
354e15ab 1955 cumulative_y[x] += actual_y;
43af96e7 1956
354e15ab 1957 series[j] = [x, cumulative_y[x]]
43af96e7 1958
41b0f691
DV
1959 if (cumulative_y[x] > seriesExtremes[1]) {
1960 seriesExtremes[1] = cumulative_y[x];
1961 }
1962 if (cumulative_y[x] < seriesExtremes[0]) {
1963 seriesExtremes[0] = cumulative_y[x];
1964 }
43af96e7 1965 }
6a1aa64f 1966 }
354e15ab 1967
b1a3b195
DV
1968 var seriesName = this.attr_("labels")[i];
1969 extremes[seriesName] = seriesExtremes;
354e15ab 1970 datasets[i] = series;
6a1aa64f
DV
1971 }
1972
b1a3b195
DV
1973 return [ datasets, extremes, boundaryIds ];
1974};
1975
1976/**
1977 * Update the graph with new data. This method is called when the viewing area
1978 * has changed. If the underlying data or options have changed, predraw_ will
1979 * be called before drawGraph_ is called.
1980 *
1981 * clearSelection, when undefined or true, causes this.clearSelection to be
1982 * called at the end of the draw operation. This should rarely be defined,
1983 * and never true (that is it should be undefined most of the time, and
1984 * rarely false.)
1985 *
1986 * @private
1987 */
1988Dygraph.prototype.drawGraph_ = function(clearSelection) {
1989 var start = new Date();
1990
1991 if (typeof(clearSelection) === 'undefined') {
1992 clearSelection = true;
1993 }
1994
1995 // This is used to set the second parameter to drawCallback, below.
1996 var is_initial_draw = this.is_initial_draw_;
1997 this.is_initial_draw_ = false;
1998
1999 var minY = null, maxY = null;
2000 this.layout_.removeAllDatasets();
2001 this.setColors_();
2002 this.attrs_['pointSize'] = 0.5 * this.attr_('highlightCircleSize');
2003
2004 var packed = this.gatherDatasets_(this.rolledSeries_, this.dateWindow_);
2005 var datasets = packed[0];
2006 var extremes = packed[1];
2007 this.boundaryIds_ = packed[2];
2008
354e15ab 2009 for (var i = 1; i < datasets.length; i++) {
4523c1f6 2010 if (!this.visibility()[i - 1]) continue;
354e15ab 2011 this.layout_.addDataset(this.attr_("labels")[i], datasets[i]);
43af96e7
NK
2012 }
2013
6faebb69 2014 this.computeYAxisRanges_(extremes);
b2c9222a
DV
2015 this.layout_.setYAxes(this.axes_);
2016
6a1aa64f
DV
2017 this.addXTicks_();
2018
b2c9222a 2019 // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
81856f70 2020 var tmp_zoomed_x = this.zoomed_x_;
6a1aa64f 2021 // Tell PlotKit to use this new data and render itself
b2c9222a 2022 this.layout_.setDateWindow(this.dateWindow_);
81856f70 2023 this.zoomed_x_ = tmp_zoomed_x;
6a1aa64f 2024 this.layout_.evaluateWithError();
9ca829f2
DV
2025 this.renderGraph_(is_initial_draw, false);
2026
2027 if (this.attr_("timingName")) {
2028 var end = new Date();
2029 if (console) {
2030 console.log(this.attr_("timingName") + " - drawGraph: " + (end - start) + "ms")
2031 }
2032 }
2033};
2034
2035Dygraph.prototype.renderGraph_ = function(is_initial_draw, clearSelection) {
6a1aa64f
DV
2036 this.plotter_.clear();
2037 this.plotter_.render();
f6401bf6 2038 this.canvas_.getContext('2d').clearRect(0, 0, this.canvas_.width,
2f5e7e1a 2039 this.canvas_.height);
599fb4ad 2040
2fccd3dc
DV
2041 if (is_initial_draw) {
2042 // Generate a static legend before any particular point is selected.
91c10d9c 2043 this.setLegendHTML_();
06303c32 2044 } else {
fc4e84fa
RK
2045 if (clearSelection) {
2046 if (typeof(this.selPoints_) !== 'undefined' && this.selPoints_.length) {
2047 // We should select the point nearest the page x/y here, but it's easier
2048 // to just clear the selection. This prevents erroneous hover dots from
2049 // being displayed.
2050 this.clearSelection();
2051 } else {
2052 this.clearSelection();
2053 }
06303c32 2054 }
2fccd3dc
DV
2055 }
2056
ccd9d7c2
PF
2057 if (this.rangeSelector_) {
2058 this.rangeSelector_.renderInteractiveLayer();
2059 }
2060
599fb4ad 2061 if (this.attr_("drawCallback") !== null) {
fe0b7c03 2062 this.attr_("drawCallback")(this, is_initial_draw);
599fb4ad 2063 }
6a1aa64f
DV
2064};
2065
2066/**
629a09ae 2067 * @private
26ca7938
DV
2068 * Determine properties of the y-axes which are independent of the data
2069 * currently being displayed. This includes things like the number of axes and
2070 * the style of the axes. It does not include the range of each axis and its
2071 * tick marks.
2072 * This fills in this.axes_ and this.seriesToAxisMap_.
2073 * axes_ = [ { options } ]
2074 * seriesToAxisMap_ = { seriesName: 0, seriesName2: 1, ... }
2075 * indices are into the axes_ array.
f09fc545 2076 */
26ca7938 2077Dygraph.prototype.computeYAxes_ = function() {
d64b8fea
RK
2078 // Preserve valueWindow settings if they exist, and if the user hasn't
2079 // specified a new valueRange.
2080 var valueWindows;
2081 if (this.axes_ != undefined && this.user_attrs_.hasOwnProperty("valueRange") == false) {
2082 valueWindows = [];
2083 for (var index = 0; index < this.axes_.length; index++) {
2084 valueWindows.push(this.axes_[index].valueWindow);
2085 }
2086 }
2087
00aa7f61 2088 this.axes_ = [{ yAxisId : 0, g : this }]; // always have at least one y-axis.
26ca7938
DV
2089 this.seriesToAxisMap_ = {};
2090
2091 // Get a list of series names.
2092 var labels = this.attr_("labels");
1c77a3a1 2093 var series = {};
26ca7938 2094 for (var i = 1; i < labels.length; i++) series[labels[i]] = (i - 1);
f09fc545
DV
2095
2096 // all options which could be applied per-axis:
2097 var axisOptions = [
2098 'includeZero',
2099 'valueRange',
2100 'labelsKMB',
2101 'labelsKMG2',
2102 'pixelsPerYLabel',
2103 'yAxisLabelWidth',
2104 'axisLabelFontSize',
7d0e7a0d
RK
2105 'axisTickSize',
2106 'logscale'
f09fc545
DV
2107 ];
2108
2109 // Copy global axis options over to the first axis.
2110 for (var i = 0; i < axisOptions.length; i++) {
2111 var k = axisOptions[i];
2112 var v = this.attr_(k);
26ca7938 2113 if (v) this.axes_[0][k] = v;
f09fc545
DV
2114 }
2115
2116 // Go through once and add all the axes.
26ca7938
DV
2117 for (var seriesName in series) {
2118 if (!series.hasOwnProperty(seriesName)) continue;
f09fc545
DV
2119 var axis = this.attr_("axis", seriesName);
2120 if (axis == null) {
26ca7938 2121 this.seriesToAxisMap_[seriesName] = 0;
f09fc545
DV
2122 continue;
2123 }
2124 if (typeof(axis) == 'object') {
2125 // Add a new axis, making a copy of its per-axis options.
2126 var opts = {};
26ca7938 2127 Dygraph.update(opts, this.axes_[0]);
f09fc545 2128 Dygraph.update(opts, { valueRange: null }); // shouldn't inherit this.
00aa7f61
RK
2129 var yAxisId = this.axes_.length;
2130 opts.yAxisId = yAxisId;
2131 opts.g = this;
f09fc545 2132 Dygraph.update(opts, axis);
26ca7938 2133 this.axes_.push(opts);
00aa7f61 2134 this.seriesToAxisMap_[seriesName] = yAxisId;
f09fc545
DV
2135 }
2136 }
2137
2138 // Go through one more time and assign series to an axis defined by another
2139 // series, e.g. { 'Y1: { axis: {} }, 'Y2': { axis: 'Y1' } }
26ca7938
DV
2140 for (var seriesName in series) {
2141 if (!series.hasOwnProperty(seriesName)) continue;
f09fc545
DV
2142 var axis = this.attr_("axis", seriesName);
2143 if (typeof(axis) == 'string') {
26ca7938 2144 if (!this.seriesToAxisMap_.hasOwnProperty(axis)) {
f09fc545
DV
2145 this.error("Series " + seriesName + " wants to share a y-axis with " +
2146 "series " + axis + ", which does not define its own axis.");
2147 return null;
2148 }
26ca7938
DV
2149 var idx = this.seriesToAxisMap_[axis];
2150 this.seriesToAxisMap_[seriesName] = idx;
f09fc545
DV
2151 }
2152 }
1c77a3a1
DV
2153
2154 // Now we remove series from seriesToAxisMap_ which are not visible. We do
2155 // this last so that hiding the first series doesn't destroy the axis
2156 // properties of the primary axis.
2157 var seriesToAxisFiltered = {};
2158 var vis = this.visibility();
2159 for (var i = 1; i < labels.length; i++) {
2160 var s = labels[i];
2161 if (vis[i - 1]) seriesToAxisFiltered[s] = this.seriesToAxisMap_[s];
2162 }
2163 this.seriesToAxisMap_ = seriesToAxisFiltered;
d64b8fea
RK
2164
2165 if (valueWindows != undefined) {
2166 // Restore valueWindow settings.
2167 for (var index = 0; index < valueWindows.length; index++) {
2168 this.axes_[index].valueWindow = valueWindows[index];
2169 }
2170 }
26ca7938
DV
2171};
2172
2173/**
2174 * Returns the number of y-axes on the chart.
2175 * @return {Number} the number of axes.
2176 */
2177Dygraph.prototype.numAxes = function() {
2178 var last_axis = 0;
2179 for (var series in this.seriesToAxisMap_) {
2180 if (!this.seriesToAxisMap_.hasOwnProperty(series)) continue;
2181 var idx = this.seriesToAxisMap_[series];
2182 if (idx > last_axis) last_axis = idx;
2183 }
2184 return 1 + last_axis;
2185};
2186
2187/**
629a09ae 2188 * @private
b2c9222a
DV
2189 * Returns axis properties for the given series.
2190 * @param { String } setName The name of the series for which to get axis
2191 * properties, e.g. 'Y1'.
2192 * @return { Object } The axis properties.
2193 */
2194Dygraph.prototype.axisPropertiesForSeries = function(series) {
2195 // TODO(danvk): handle errors.
2196 return this.axes_[this.seriesToAxisMap_[series]];
2197};
2198
2199/**
2200 * @private
26ca7938
DV
2201 * Determine the value range and tick marks for each axis.
2202 * @param {Object} extremes A mapping from seriesName -> [low, high]
2203 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2204 */
2205Dygraph.prototype.computeYAxisRanges_ = function(extremes) {
2206 // Build a map from axis number -> [list of series names]
2207 var seriesForAxis = [];
2208 for (var series in this.seriesToAxisMap_) {
2209 if (!this.seriesToAxisMap_.hasOwnProperty(series)) continue;
2210 var idx = this.seriesToAxisMap_[series];
2211 while (seriesForAxis.length <= idx) seriesForAxis.push([]);
2212 seriesForAxis[idx].push(series);
2213 }
f09fc545
DV
2214
2215 // Compute extreme values, a span and tick marks for each axis.
26ca7938
DV
2216 for (var i = 0; i < this.axes_.length; i++) {
2217 var axis = this.axes_[i];
25f76ae3 2218
06fc69b6
AV
2219 if (!seriesForAxis[i]) {
2220 // If no series are defined or visible then use a reasonable default
2221 axis.extremeRange = [0, 1];
2222 } else {
1c77a3a1 2223 // Calculate the extremes of extremes.
f09fc545
DV
2224 var series = seriesForAxis[i];
2225 var minY = Infinity; // extremes[series[0]][0];
2226 var maxY = -Infinity; // extremes[series[0]][1];
ba049b89 2227 var extremeMinY, extremeMaxY;
f09fc545 2228 for (var j = 0; j < series.length; j++) {
ba049b89
NN
2229 // Only use valid extremes to stop null data series' from corrupting the scale.
2230 extremeMinY = extremes[series[j]][0];
2231 if (extremeMinY != null) {
36dfa958 2232 minY = Math.min(extremeMinY, minY);
ba049b89
NN
2233 }
2234 extremeMaxY = extremes[series[j]][1];
2235 if (extremeMaxY != null) {
36dfa958 2236 maxY = Math.max(extremeMaxY, maxY);
ba049b89 2237 }
f09fc545
DV
2238 }
2239 if (axis.includeZero && minY > 0) minY = 0;
2240
ba049b89 2241 // Ensure we have a valid scale, otherwise defualt to zero for safety.
36dfa958
DV
2242 if (minY == Infinity) minY = 0;
2243 if (maxY == -Infinity) maxY = 0;
ba049b89 2244
f09fc545
DV
2245 // Add some padding and round up to an integer to be human-friendly.
2246 var span = maxY - minY;
2247 // special case: if we have no sense of scale, use +/-10% of the sole value.
2248 if (span == 0) { span = maxY; }
f09fc545 2249
ff022deb
RK
2250 var maxAxisY;
2251 var minAxisY;
7d0e7a0d 2252 if (axis.logscale) {
ff022deb
RK
2253 var maxAxisY = maxY + 0.1 * span;
2254 var minAxisY = minY;
2255 } else {
2256 var maxAxisY = maxY + 0.1 * span;
2257 var minAxisY = minY - 0.1 * span;
f09fc545 2258
ff022deb
RK
2259 // Try to include zero and make it minAxisY (or maxAxisY) if it makes sense.
2260 if (!this.attr_("avoidMinZero")) {
2261 if (minAxisY < 0 && minY >= 0) minAxisY = 0;
2262 if (maxAxisY > 0 && maxY <= 0) maxAxisY = 0;
2263 }
f09fc545 2264
ff022deb
RK
2265 if (this.attr_("includeZero")) {
2266 if (maxY < 0) maxAxisY = 0;
2267 if (minY > 0) minAxisY = 0;
2268 }
f09fc545 2269 }
4cac8c7a
RK
2270 axis.extremeRange = [minAxisY, maxAxisY];
2271 }
2272 if (axis.valueWindow) {
2273 // This is only set if the user has zoomed on the y-axis. It is never set
2274 // by a user. It takes precedence over axis.valueRange because, if you set
2275 // valueRange, you'd still expect to be able to pan.
2276 axis.computedValueRange = [axis.valueWindow[0], axis.valueWindow[1]];
2277 } else if (axis.valueRange) {
2278 // This is a user-set value range for this axis.
2279 axis.computedValueRange = [axis.valueRange[0], axis.valueRange[1]];
2280 } else {
2281 axis.computedValueRange = axis.extremeRange;
f09fc545
DV
2282 }
2283
0d64e596
DV
2284 // Add ticks. By default, all axes inherit the tick positions of the
2285 // primary axis. However, if an axis is specifically marked as having
2286 // independent ticks, then that is permissible as well.
48e614ac
DV
2287 var opts = this.optionsViewForAxis_('y' + (i ? '2' : ''));
2288 var ticker = opts('ticker');
0d64e596 2289 if (i == 0 || axis.independentTicks) {
48e614ac
DV
2290 axis.ticks = ticker(axis.computedValueRange[0],
2291 axis.computedValueRange[1],
2292 this.height_, // TODO(danvk): should be area.height
2293 opts,
2294 this);
0d64e596
DV
2295 } else {
2296 var p_axis = this.axes_[0];
2297 var p_ticks = p_axis.ticks;
2298 var p_scale = p_axis.computedValueRange[1] - p_axis.computedValueRange[0];
2299 var scale = axis.computedValueRange[1] - axis.computedValueRange[0];
2300 var tick_values = [];
25f76ae3
DV
2301 for (var k = 0; k < p_ticks.length; k++) {
2302 var y_frac = (p_ticks[k].v - p_axis.computedValueRange[0]) / p_scale;
0d64e596
DV
2303 var y_val = axis.computedValueRange[0] + y_frac * scale;
2304 tick_values.push(y_val);
2305 }
2306
48e614ac
DV
2307 axis.ticks = ticker(axis.computedValueRange[0],
2308 axis.computedValueRange[1],
2309 this.height_, // TODO(danvk): should be area.height
2310 opts,
2311 this,
2312 tick_values);
0d64e596 2313 }
f09fc545 2314 }
f09fc545 2315};
25f76ae3 2316
f09fc545 2317/**
b1a3b195
DV
2318 * Extracts one series from the raw data (a 2D array) into an array of (date,
2319 * value) tuples.
2320 *
2321 * This is where undesirable points (i.e. negative values on log scales and
2322 * missing values through which we wish to connect lines) are dropped.
2323 *
2324 * @private
2325 */
2326Dygraph.prototype.extractSeries_ = function(rawData, i, logScale, connectSeparatedPoints) {
2327 var series = [];
2328 for (var j = 0; j < rawData.length; j++) {
2329 var x = rawData[j][0];
2330 var point = rawData[j][i];
2331 if (logScale) {
2332 // On the log scale, points less than zero do not exist.
2333 // This will create a gap in the chart. Note that this ignores
2334 // connectSeparatedPoints.
2335 if (point <= 0) {
2336 point = null;
2337 }
2338 series.push([x, point]);
2339 } else {
2340 if (point != null || !connectSeparatedPoints) {
2341 series.push([x, point]);
2342 }
2343 }
2344 }
2345 return series;
2346};
2347
2348/**
629a09ae 2349 * @private
6a1aa64f
DV
2350 * Calculates the rolling average of a data set.
2351 * If originalData is [label, val], rolls the average of those.
2352 * If originalData is [label, [, it's interpreted as [value, stddev]
2353 * and the roll is returned in the same form, with appropriately reduced
2354 * stddev for each value.
2355 * Note that this is where fractional input (i.e. '5/10') is converted into
2356 * decimal values.
2357 * @param {Array} originalData The data in the appropriate format (see above)
6faebb69
JB
2358 * @param {Number} rollPeriod The number of points over which to average the
2359 * data
6a1aa64f 2360 */
285a6bda 2361Dygraph.prototype.rollingAverage = function(originalData, rollPeriod) {
6a1aa64f
DV
2362 if (originalData.length < 2)
2363 return originalData;
77b5e09d 2364 var rollPeriod = Math.min(rollPeriod, originalData.length);
6a1aa64f 2365 var rollingData = [];
285a6bda 2366 var sigma = this.attr_("sigma");
6a1aa64f
DV
2367
2368 if (this.fractions_) {
2369 var num = 0;
2370 var den = 0; // numerator/denominator
2371 var mult = 100.0;
2372 for (var i = 0; i < originalData.length; i++) {
2373 num += originalData[i][1][0];
2374 den += originalData[i][1][1];
2375 if (i - rollPeriod >= 0) {
2376 num -= originalData[i - rollPeriod][1][0];
2377 den -= originalData[i - rollPeriod][1][1];
2378 }
2379
2380 var date = originalData[i][0];
2381 var value = den ? num / den : 0.0;
285a6bda 2382 if (this.attr_("errorBars")) {
6a1aa64f
DV
2383 if (this.wilsonInterval_) {
2384 // For more details on this confidence interval, see:
2385 // http://en.wikipedia.org/wiki/Binomial_confidence_interval
2386 if (den) {
2387 var p = value < 0 ? 0 : value, n = den;
2388 var pm = sigma * Math.sqrt(p*(1-p)/n + sigma*sigma/(4*n*n));
2389 var denom = 1 + sigma * sigma / den;
2390 var low = (p + sigma * sigma / (2 * den) - pm) / denom;
2391 var high = (p + sigma * sigma / (2 * den) + pm) / denom;
2392 rollingData[i] = [date,
2393 [p * mult, (p - low) * mult, (high - p) * mult]];
2394 } else {
2395 rollingData[i] = [date, [0, 0, 0]];
2396 }
2397 } else {
2398 var stddev = den ? sigma * Math.sqrt(value * (1 - value) / den) : 1.0;
2399 rollingData[i] = [date, [mult * value, mult * stddev, mult * stddev]];
2400 }
2401 } else {
2402 rollingData[i] = [date, mult * value];
2403 }
2404 }
9922b78b 2405 } else if (this.attr_("customBars")) {
f6885d6a
DV
2406 var low = 0;
2407 var mid = 0;
2408 var high = 0;
2409 var count = 0;
6a1aa64f
DV
2410 for (var i = 0; i < originalData.length; i++) {
2411 var data = originalData[i][1];
2412 var y = data[1];
2413 rollingData[i] = [originalData[i][0], [y, y - data[0], data[2] - y]];
f6885d6a 2414
8b91c51f 2415 if (y != null && !isNaN(y)) {
49a7d0d5
DV
2416 low += data[0];
2417 mid += y;
2418 high += data[2];
2419 count += 1;
2420 }
f6885d6a
DV
2421 if (i - rollPeriod >= 0) {
2422 var prev = originalData[i - rollPeriod];
8b91c51f 2423 if (prev[1][1] != null && !isNaN(prev[1][1])) {
49a7d0d5
DV
2424 low -= prev[1][0];
2425 mid -= prev[1][1];
2426 high -= prev[1][2];
2427 count -= 1;
2428 }
f6885d6a 2429 }
502d5996
DV
2430 if (count) {
2431 rollingData[i] = [originalData[i][0], [ 1.0 * mid / count,
2432 1.0 * (mid - low) / count,
2433 1.0 * (high - mid) / count ]];
2434 } else {
2435 rollingData[i] = [originalData[i][0], [null, null, null]];
2436 }
2769de62 2437 }
6a1aa64f
DV
2438 } else {
2439 // Calculate the rolling average for the first rollPeriod - 1 points where
6faebb69 2440 // there is not enough data to roll over the full number of points
6a1aa64f 2441 var num_init_points = Math.min(rollPeriod - 1, originalData.length - 2);
285a6bda 2442 if (!this.attr_("errorBars")){
5011e7a1
DV
2443 if (rollPeriod == 1) {
2444 return originalData;
2445 }
2446
2847c1cf 2447 for (var i = 0; i < originalData.length; i++) {
6a1aa64f 2448 var sum = 0;
5011e7a1 2449 var num_ok = 0;
2847c1cf
DV
2450 for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
2451 var y = originalData[j][1];
8b91c51f 2452 if (y == null || isNaN(y)) continue;
5011e7a1 2453 num_ok++;
2847c1cf 2454 sum += originalData[j][1];
6a1aa64f 2455 }
5011e7a1 2456 if (num_ok) {
2847c1cf 2457 rollingData[i] = [originalData[i][0], sum / num_ok];
5011e7a1 2458 } else {
2847c1cf 2459 rollingData[i] = [originalData[i][0], null];
5011e7a1 2460 }
6a1aa64f 2461 }
2847c1cf
DV
2462
2463 } else {
2464 for (var i = 0; i < originalData.length; i++) {
6a1aa64f
DV
2465 var sum = 0;
2466 var variance = 0;
5011e7a1 2467 var num_ok = 0;
2847c1cf 2468 for (var j = Math.max(0, i - rollPeriod + 1); j < i + 1; j++) {
5011e7a1 2469 var y = originalData[j][1][0];
8b91c51f 2470 if (y == null || isNaN(y)) continue;
5011e7a1 2471 num_ok++;
6a1aa64f
DV
2472 sum += originalData[j][1][0];
2473 variance += Math.pow(originalData[j][1][1], 2);
2474 }
5011e7a1
DV
2475 if (num_ok) {
2476 var stddev = Math.sqrt(variance) / num_ok;
2477 rollingData[i] = [originalData[i][0],
2478 [sum / num_ok, sigma * stddev, sigma * stddev]];
2479 } else {
2480 rollingData[i] = [originalData[i][0], [null, null, null]];
2481 }
6a1aa64f
DV
2482 }
2483 }
2484 }
2485
2486 return rollingData;
2487};
2488
2489/**
285a6bda
DV
2490 * Detects the type of the str (date or numeric) and sets the various
2491 * formatting attributes in this.attrs_ based on this type.
2492 * @param {String} str An x value.
2493 * @private
2494 */
2495Dygraph.prototype.detectTypeFromString_ = function(str) {
2496 var isDate = false;
ea62df82 2497 if (str.indexOf('-') > 0 ||
285a6bda
DV
2498 str.indexOf('/') >= 0 ||
2499 isNaN(parseFloat(str))) {
2500 isDate = true;
2501 } else if (str.length == 8 && str > '19700101' && str < '20371231') {
2502 // TODO(danvk): remove support for this format.
2503 isDate = true;
2504 }
2505
2506 if (isDate) {
285a6bda 2507 this.attrs_.xValueParser = Dygraph.dateParser;
48e614ac
DV
2508 this.attrs_.axes.x.valueFormatter = Dygraph.dateString_;
2509 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
2510 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisFormatter;
285a6bda 2511 } else {
c39e1d93 2512 /** @private (shut up, jsdoc!) */
285a6bda 2513 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
48e614ac
DV
2514 // TODO(danvk): use Dygraph.numberValueFormatter here?
2515 /** @private (shut up, jsdoc!) */
2516 this.attrs_.axes.x.valueFormatter = function(x) { return x; };
2517 this.attrs_.axes.x.ticker = Dygraph.numericTicks;
2518 this.attrs_.axes.x.axisLabelFormatter = this.attrs_.axes.x.valueFormatter;
6a1aa64f 2519 }
6a1aa64f
DV
2520};
2521
2522/**
5cd7ac68
DV
2523 * Parses the value as a floating point number. This is like the parseFloat()
2524 * built-in, but with a few differences:
2525 * - the empty string is parsed as null, rather than NaN.
2526 * - if the string cannot be parsed at all, an error is logged.
2527 * If the string can't be parsed, this method returns null.
2528 * @param {String} x The string to be parsed
2529 * @param {Number} opt_line_no The line number from which the string comes.
2530 * @param {String} opt_line The text of the line from which the string comes.
2531 * @private
2532 */
2533
2534// Parse the x as a float or return null if it's not a number.
2535Dygraph.prototype.parseFloat_ = function(x, opt_line_no, opt_line) {
2536 var val = parseFloat(x);
2537 if (!isNaN(val)) return val;
2538
2539 // Try to figure out what happeend.
2540 // If the value is the empty string, parse it as null.
2541 if (/^ *$/.test(x)) return null;
2542
2543 // If it was actually "NaN", return it as NaN.
2544 if (/^ *nan *$/i.test(x)) return NaN;
2545
2546 // Looks like a parsing error.
2547 var msg = "Unable to parse '" + x + "' as a number";
2548 if (opt_line !== null && opt_line_no !== null) {
2549 msg += " on line " + (1+opt_line_no) + " ('" + opt_line + "') of CSV.";
2550 }
2551 this.error(msg);
2552
2553 return null;
2554};
2555
2556/**
629a09ae 2557 * @private
6a1aa64f
DV
2558 * Parses a string in a special csv format. We expect a csv file where each
2559 * line is a date point, and the first field in each line is the date string.
2560 * We also expect that all remaining fields represent series.
285a6bda 2561 * if the errorBars attribute is set, then interpret the fields as:
6a1aa64f 2562 * date, series1, stddev1, series2, stddev2, ...
629a09ae 2563 * @param {[Object]} data See above.
285a6bda 2564 *
629a09ae 2565 * @return [Object] An array with one entry for each row. These entries
285a6bda
DV
2566 * are an array of cells in that row. The first entry is the parsed x-value for
2567 * the row. The second, third, etc. are the y-values. These can take on one of
2568 * three forms, depending on the CSV and constructor parameters:
2569 * 1. numeric value
2570 * 2. [ value, stddev ]
2571 * 3. [ low value, center value, high value ]
6a1aa64f 2572 */
285a6bda 2573Dygraph.prototype.parseCSV_ = function(data) {
6a1aa64f
DV
2574 var ret = [];
2575 var lines = data.split("\n");
3d67f03b
DV
2576
2577 // Use the default delimiter or fall back to a tab if that makes sense.
2578 var delim = this.attr_('delimiter');
2579 if (lines[0].indexOf(delim) == -1 && lines[0].indexOf('\t') >= 0) {
2580 delim = '\t';
2581 }
2582
285a6bda 2583 var start = 0;
d7beab6b
DV
2584 if (!('labels' in this.user_attrs_)) {
2585 // User hasn't explicitly set labels, so they're (presumably) in the CSV.
285a6bda 2586 start = 1;
d7beab6b 2587 this.attrs_.labels = lines[0].split(delim); // NOTE: _not_ user_attrs_.
6a1aa64f 2588 }
5cd7ac68 2589 var line_no = 0;
03b522a4 2590
285a6bda
DV
2591 var xParser;
2592 var defaultParserSet = false; // attempt to auto-detect x value type
2593 var expectedCols = this.attr_("labels").length;
987840a2 2594 var outOfOrder = false;
6a1aa64f
DV
2595 for (var i = start; i < lines.length; i++) {
2596 var line = lines[i];
5cd7ac68 2597 line_no = i;
6a1aa64f 2598 if (line.length == 0) continue; // skip blank lines
3d67f03b
DV
2599 if (line[0] == '#') continue; // skip comment lines
2600 var inFields = line.split(delim);
285a6bda 2601 if (inFields.length < 2) continue;
6a1aa64f
DV
2602
2603 var fields = [];
285a6bda
DV
2604 if (!defaultParserSet) {
2605 this.detectTypeFromString_(inFields[0]);
2606 xParser = this.attr_("xValueParser");
2607 defaultParserSet = true;
2608 }
2609 fields[0] = xParser(inFields[0], this);
6a1aa64f
DV
2610
2611 // If fractions are expected, parse the numbers as "A/B"
2612 if (this.fractions_) {
2613 for (var j = 1; j < inFields.length; j++) {
2614 // TODO(danvk): figure out an appropriate way to flag parse errors.
2615 var vals = inFields[j].split("/");
7219edb3
DV
2616 if (vals.length != 2) {
2617 this.error('Expected fractional "num/den" values in CSV data ' +
2618 "but found a value '" + inFields[j] + "' on line " +
2619 (1 + i) + " ('" + line + "') which is not of this form.");
2620 fields[j] = [0, 0];
2621 } else {
2622 fields[j] = [this.parseFloat_(vals[0], i, line),
2623 this.parseFloat_(vals[1], i, line)];
2624 }
6a1aa64f 2625 }
285a6bda 2626 } else if (this.attr_("errorBars")) {
6a1aa64f 2627 // If there are error bars, values are (value, stddev) pairs
7219edb3
DV
2628 if (inFields.length % 2 != 1) {
2629 this.error('Expected alternating (value, stdev.) pairs in CSV data ' +
2630 'but line ' + (1 + i) + ' has an odd number of values (' +
2631 (inFields.length - 1) + "): '" + line + "'");
2632 }
2633 for (var j = 1; j < inFields.length; j += 2) {
5cd7ac68
DV
2634 fields[(j + 1) / 2] = [this.parseFloat_(inFields[j], i, line),
2635 this.parseFloat_(inFields[j + 1], i, line)];
7219edb3 2636 }
9922b78b 2637 } else if (this.attr_("customBars")) {
6a1aa64f
DV
2638 // Bars are a low;center;high tuple
2639 for (var j = 1; j < inFields.length; j++) {
327a9279
DV
2640 var val = inFields[j];
2641 if (/^ *$/.test(val)) {
2642 fields[j] = [null, null, null];
2643 } else {
2644 var vals = val.split(";");
2645 if (vals.length == 3) {
2646 fields[j] = [ this.parseFloat_(vals[0], i, line),
2647 this.parseFloat_(vals[1], i, line),
2648 this.parseFloat_(vals[2], i, line) ];
2649 } else {
2650 this.warning('When using customBars, values must be either blank ' +
2651 'or "low;center;high" tuples (got "' + val +
2652 '" on line ' + (1+i));
2653 }
2654 }
6a1aa64f
DV
2655 }
2656 } else {
2657 // Values are just numbers
285a6bda 2658 for (var j = 1; j < inFields.length; j++) {
5cd7ac68 2659 fields[j] = this.parseFloat_(inFields[j], i, line);
285a6bda 2660 }
6a1aa64f 2661 }
987840a2
DV
2662 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
2663 outOfOrder = true;
2664 }
285a6bda
DV
2665
2666 if (fields.length != expectedCols) {
2667 this.error("Number of columns in line " + i + " (" + fields.length +
2668 ") does not agree with number of labels (" + expectedCols +
2669 ") " + line);
2670 }
6d0aaa09
DV
2671
2672 // If the user specified the 'labels' option and none of the cells of the
2673 // first row parsed correctly, then they probably double-specified the
2674 // labels. We go with the values set in the option, discard this row and
2675 // log a warning to the JS console.
2676 if (i == 0 && this.attr_('labels')) {
2677 var all_null = true;
2678 for (var j = 0; all_null && j < fields.length; j++) {
2679 if (fields[j]) all_null = false;
2680 }
2681 if (all_null) {
2682 this.warn("The dygraphs 'labels' option is set, but the first row of " +
2683 "CSV data ('" + line + "') appears to also contain labels. " +
2684 "Will drop the CSV labels and use the option labels.");
2685 continue;
2686 }
2687 }
2688 ret.push(fields);
6a1aa64f 2689 }
987840a2
DV
2690
2691 if (outOfOrder) {
2692 this.warn("CSV is out of order; order it correctly to speed loading.");
2693 ret.sort(function(a,b) { return a[0] - b[0] });
2694 }
2695
6a1aa64f
DV
2696 return ret;
2697};
2698
2699/**
629a09ae 2700 * @private
285a6bda
DV
2701 * The user has provided their data as a pre-packaged JS array. If the x values
2702 * are numeric, this is the same as dygraphs' internal format. If the x values
2703 * are dates, we need to convert them from Date objects to ms since epoch.
629a09ae
DV
2704 * @param {[Object]} data
2705 * @return {[Object]} data with numeric x values.
285a6bda
DV
2706 */
2707Dygraph.prototype.parseArray_ = function(data) {
2708 // Peek at the first x value to see if it's numeric.
2709 if (data.length == 0) {
2710 this.error("Can't plot empty data set");
2711 return null;
2712 }
2713 if (data[0].length == 0) {
2714 this.error("Data set cannot contain an empty row");
2715 return null;
2716 }
2717
2718 if (this.attr_("labels") == null) {
2719 this.warn("Using default labels. Set labels explicitly via 'labels' " +
2720 "in the options parameter");
2721 this.attrs_.labels = [ "X" ];
2722 for (var i = 1; i < data[0].length; i++) {
2723 this.attrs_.labels.push("Y" + i);
2724 }
2725 }
2726
2dda3850 2727 if (Dygraph.isDateLike(data[0][0])) {
285a6bda 2728 // Some intelligent defaults for a date x-axis.
48e614ac
DV
2729 this.attrs_.axes.x.valueFormatter = Dygraph.dateString_;
2730 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisFormatter;
2731 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
285a6bda
DV
2732
2733 // Assume they're all dates.
e3ab7b40 2734 var parsedData = Dygraph.clone(data);
285a6bda
DV
2735 for (var i = 0; i < data.length; i++) {
2736 if (parsedData[i].length == 0) {
a323ff4a 2737 this.error("Row " + (1 + i) + " of data is empty");
285a6bda
DV
2738 return null;
2739 }
2740 if (parsedData[i][0] == null
3a909ec5
DV
2741 || typeof(parsedData[i][0].getTime) != 'function'
2742 || isNaN(parsedData[i][0].getTime())) {
be96a1f5 2743 this.error("x value in row " + (1 + i) + " is not a Date");
285a6bda
DV
2744 return null;
2745 }
2746 parsedData[i][0] = parsedData[i][0].getTime();
2747 }
2748 return parsedData;
2749 } else {
2750 // Some intelligent defaults for a numeric x-axis.
c39e1d93 2751 /** @private (shut up, jsdoc!) */
48e614ac
DV
2752 this.attrs_.axes.x.valueFormatter = function(x) { return x; };
2753 this.attrs_.axes.x.axisLabelFormatter = Dygraph.numberAxisLabelFormatter;
2754 this.attrs_.axes.x.ticker = Dygraph.numericTicks;
285a6bda
DV
2755 return data;
2756 }
2757};
2758
2759/**
79420a1e
DV
2760 * Parses a DataTable object from gviz.
2761 * The data is expected to have a first column that is either a date or a
2762 * number. All subsequent columns must be numbers. If there is a clear mismatch
2763 * between this.xValueParser_ and the type of the first column, it will be
a685723c 2764 * fixed. Fills out rawData_.
629a09ae 2765 * @param {[Object]} data See above.
79420a1e
DV
2766 * @private
2767 */
285a6bda 2768Dygraph.prototype.parseDataTable_ = function(data) {
79420a1e
DV
2769 var cols = data.getNumberOfColumns();
2770 var rows = data.getNumberOfRows();
2771
d955e223 2772 var indepType = data.getColumnType(0);
4440f6c8 2773 if (indepType == 'date' || indepType == 'datetime') {
285a6bda 2774 this.attrs_.xValueParser = Dygraph.dateParser;
48e614ac
DV
2775 this.attrs_.axes.x.valueFormatter = Dygraph.dateString_;
2776 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
2777 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisFormatter;
33127159 2778 } else if (indepType == 'number') {
285a6bda 2779 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
48e614ac
DV
2780 this.attrs_.axes.x.valueFormatter = function(x) { return x; };
2781 this.attrs_.axes.x.ticker = Dygraph.numericTicks;
2782 this.attrs_.axes.x.axisLabelFormatter = this.attrs_.axes.x.valueFormatter;
285a6bda 2783 } else {
987840a2
DV
2784 this.error("only 'date', 'datetime' and 'number' types are supported for " +
2785 "column 1 of DataTable input (Got '" + indepType + "')");
79420a1e
DV
2786 return null;
2787 }
2788
a685723c
DV
2789 // Array of the column indices which contain data (and not annotations).
2790 var colIdx = [];
2791 var annotationCols = {}; // data index -> [annotation cols]
2792 var hasAnnotations = false;
2793 for (var i = 1; i < cols; i++) {
2794 var type = data.getColumnType(i);
2795 if (type == 'number') {
2796 colIdx.push(i);
2797 } else if (type == 'string' && this.attr_('displayAnnotations')) {
2798 // This is OK -- it's an annotation column.
2799 var dataIdx = colIdx[colIdx.length - 1];
2800 if (!annotationCols.hasOwnProperty(dataIdx)) {
2801 annotationCols[dataIdx] = [i];
2802 } else {
2803 annotationCols[dataIdx].push(i);
2804 }
2805 hasAnnotations = true;
2806 } else {
2807 this.error("Only 'number' is supported as a dependent type with Gviz." +
2808 " 'string' is only supported if displayAnnotations is true");
2809 }
2810 }
2811
2812 // Read column labels
2813 // TODO(danvk): add support back for errorBars
2814 var labels = [data.getColumnLabel(0)];
2815 for (var i = 0; i < colIdx.length; i++) {
2816 labels.push(data.getColumnLabel(colIdx[i]));
f9348814 2817 if (this.attr_("errorBars")) i += 1;
a685723c
DV
2818 }
2819 this.attrs_.labels = labels;
2820 cols = labels.length;
2821
79420a1e 2822 var ret = [];
987840a2 2823 var outOfOrder = false;
a685723c 2824 var annotations = [];
79420a1e
DV
2825 for (var i = 0; i < rows; i++) {
2826 var row = [];
debe4434
DV
2827 if (typeof(data.getValue(i, 0)) === 'undefined' ||
2828 data.getValue(i, 0) === null) {
129569a5
FD
2829 this.warn("Ignoring row " + i +
2830 " of DataTable because of undefined or null first column.");
debe4434
DV
2831 continue;
2832 }
2833
c21d2c2d 2834 if (indepType == 'date' || indepType == 'datetime') {
d955e223
DV
2835 row.push(data.getValue(i, 0).getTime());
2836 } else {
2837 row.push(data.getValue(i, 0));
2838 }
3e3f84e4 2839 if (!this.attr_("errorBars")) {
a685723c
DV
2840 for (var j = 0; j < colIdx.length; j++) {
2841 var col = colIdx[j];
2842 row.push(data.getValue(i, col));
2843 if (hasAnnotations &&
2844 annotationCols.hasOwnProperty(col) &&
2845 data.getValue(i, annotationCols[col][0]) != null) {
2846 var ann = {};
2847 ann.series = data.getColumnLabel(col);
2848 ann.xval = row[0];
2849 ann.shortText = String.fromCharCode(65 /* A */ + annotations.length)
2850 ann.text = '';
2851 for (var k = 0; k < annotationCols[col].length; k++) {
2852 if (k) ann.text += "\n";
2853 ann.text += data.getValue(i, annotationCols[col][k]);
2854 }
2855 annotations.push(ann);
2856 }
3e3f84e4 2857 }
92fd68d8
DV
2858
2859 // Strip out infinities, which give dygraphs problems later on.
2860 for (var j = 0; j < row.length; j++) {
2861 if (!isFinite(row[j])) row[j] = null;
2862 }
3e3f84e4
DV
2863 } else {
2864 for (var j = 0; j < cols - 1; j++) {
2865 row.push([ data.getValue(i, 1 + 2 * j), data.getValue(i, 2 + 2 * j) ]);
2866 }
79420a1e 2867 }
987840a2
DV
2868 if (ret.length > 0 && row[0] < ret[ret.length - 1][0]) {
2869 outOfOrder = true;
2870 }
243d96e8 2871 ret.push(row);
79420a1e 2872 }
987840a2
DV
2873
2874 if (outOfOrder) {
2875 this.warn("DataTable is out of order; order it correctly to speed loading.");
2876 ret.sort(function(a,b) { return a[0] - b[0] });
2877 }
a685723c
DV
2878 this.rawData_ = ret;
2879
2880 if (annotations.length > 0) {
2881 this.setAnnotations(annotations, true);
2882 }
79420a1e
DV
2883}
2884
629a09ae 2885/**
6a1aa64f
DV
2886 * Get the CSV data. If it's in a function, call that function. If it's in a
2887 * file, do an XMLHttpRequest to get it.
2888 * @private
2889 */
285a6bda 2890Dygraph.prototype.start_ = function() {
6a1aa64f 2891 if (typeof this.file_ == 'function') {
285a6bda 2892 // CSV string. Pretend we got it via XHR.
6a1aa64f 2893 this.loadedEvent_(this.file_());
2dda3850 2894 } else if (Dygraph.isArrayLike(this.file_)) {
285a6bda 2895 this.rawData_ = this.parseArray_(this.file_);
26ca7938 2896 this.predraw_();
79420a1e
DV
2897 } else if (typeof this.file_ == 'object' &&
2898 typeof this.file_.getColumnRange == 'function') {
2899 // must be a DataTable from gviz.
a685723c 2900 this.parseDataTable_(this.file_);
26ca7938 2901 this.predraw_();
285a6bda
DV
2902 } else if (typeof this.file_ == 'string') {
2903 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
2904 if (this.file_.indexOf('\n') >= 0) {
2905 this.loadedEvent_(this.file_);
2906 } else {
2907 var req = new XMLHttpRequest();
2908 var caller = this;
2909 req.onreadystatechange = function () {
2910 if (req.readyState == 4) {
39338e74
DV
2911 if (req.status == 200 || // Normal http
2912 req.status == 0) { // Chrome w/ --allow-file-access-from-files
285a6bda
DV
2913 caller.loadedEvent_(req.responseText);
2914 }
6a1aa64f 2915 }
285a6bda 2916 };
6a1aa64f 2917
285a6bda
DV
2918 req.open("GET", this.file_, true);
2919 req.send(null);
2920 }
2921 } else {
2922 this.error("Unknown data format: " + (typeof this.file_));
6a1aa64f
DV
2923 }
2924};
2925
2926/**
2927 * Changes various properties of the graph. These can include:
2928 * <ul>
2929 * <li>file: changes the source data for the graph</li>
2930 * <li>errorBars: changes whether the data contains stddev</li>
2931 * </ul>
dcb25130 2932 *
ccfcc169
DV
2933 * There's a huge variety of options that can be passed to this method. For a
2934 * full list, see http://dygraphs.com/options.html.
2935 *
6a1aa64f 2936 * @param {Object} attrs The new properties and values
ccfcc169
DV
2937 * @param {Boolean} [block_redraw] Usually the chart is redrawn after every
2938 * call to updateOptions(). If you know better, you can pass true to explicitly
2939 * block the redraw. This can be useful for chaining updateOptions() calls,
2940 * avoiding the occasional infinite loop and preventing redraws when it's not
2941 * necessary (e.g. when updating a callback).
6a1aa64f 2942 */
48e614ac 2943Dygraph.prototype.updateOptions = function(input_attrs, block_redraw) {
ccfcc169
DV
2944 if (typeof(block_redraw) == 'undefined') block_redraw = false;
2945
48e614ac
DV
2946 // mapLegacyOptions_ drops the "file" parameter as a convenience to us.
2947 var file = input_attrs['file'];
2948 var attrs = Dygraph.mapLegacyOptions_(input_attrs);
2949
ccfcc169 2950 // TODO(danvk): this is a mess. Move these options into attr_.
c65f2303 2951 if ('rollPeriod' in attrs) {
6a1aa64f
DV
2952 this.rollPeriod_ = attrs.rollPeriod;
2953 }
c65f2303 2954 if ('dateWindow' in attrs) {
6a1aa64f 2955 this.dateWindow_ = attrs.dateWindow;
e5152598 2956 if (!('isZoomedIgnoreProgrammaticZoom' in attrs)) {
81856f70
NN
2957 this.zoomed_x_ = attrs.dateWindow != null;
2958 }
b7e5862d 2959 }
e5152598 2960 if ('valueRange' in attrs && !('isZoomedIgnoreProgrammaticZoom' in attrs)) {
b7e5862d 2961 this.zoomed_y_ = attrs.valueRange != null;
6a1aa64f 2962 }
450fe64b
DV
2963
2964 // TODO(danvk): validate per-series options.
46dde5f9
DV
2965 // Supported:
2966 // strokeWidth
2967 // pointSize
2968 // drawPoints
2969 // highlightCircleSize
450fe64b 2970
9ca829f2
DV
2971 // Check if this set options will require new points.
2972 var requiresNewPoints = Dygraph.isPixelChangingOptionList(this.attr_("labels"), attrs);
2973
48e614ac 2974 Dygraph.updateDeep(this.user_attrs_, attrs);
285a6bda 2975
48e614ac
DV
2976 if (file) {
2977 this.file_ = file;
ccfcc169 2978 if (!block_redraw) this.start_();
6a1aa64f 2979 } else {
9ca829f2
DV
2980 if (!block_redraw) {
2981 if (requiresNewPoints) {
48e614ac 2982 this.predraw_();
9ca829f2
DV
2983 } else {
2984 this.renderGraph_(false, false);
2985 }
2986 }
6a1aa64f
DV
2987 }
2988};
2989
2990/**
48e614ac
DV
2991 * Returns a copy of the options with deprecated names converted into current
2992 * names. Also drops the (potentially-large) 'file' attribute. If the caller is
2993 * interested in that, they should save a copy before calling this.
2994 * @private
2995 */
2996Dygraph.mapLegacyOptions_ = function(attrs) {
2997 var my_attrs = {};
2998 for (var k in attrs) {
2999 if (k == 'file') continue;
3000 if (attrs.hasOwnProperty(k)) my_attrs[k] = attrs[k];
3001 }
3002
3003 var set = function(axis, opt, value) {
3004 if (!my_attrs.axes) my_attrs.axes = {};
3005 if (!my_attrs.axes[axis]) my_attrs.axes[axis] = {};
3006 my_attrs.axes[axis][opt] = value;
3007 };
3008 var map = function(opt, axis, new_opt) {
3009 if (typeof(attrs[opt]) != 'undefined') {
3010 set(axis, new_opt, attrs[opt]);
3011 delete my_attrs[opt];
3012 }
3013 };
3014
3015 // This maps, e.g., xValueFormater -> axes: { x: { valueFormatter: ... } }
3016 map('xValueFormatter', 'x', 'valueFormatter');
3017 map('pixelsPerXLabel', 'x', 'pixelsPerLabel');
3018 map('xAxisLabelFormatter', 'x', 'axisLabelFormatter');
3019 map('xTicker', 'x', 'ticker');
3020 map('yValueFormatter', 'y', 'valueFormatter');
3021 map('pixelsPerYLabel', 'y', 'pixelsPerLabel');
3022 map('yAxisLabelFormatter', 'y', 'axisLabelFormatter');
3023 map('yTicker', 'y', 'ticker');
3024 return my_attrs;
3025};
3026
3027/**
697e70b2
DV
3028 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3029 * containing div (which has presumably changed size since the dygraph was
3030 * instantiated. If the width/height are specified, the div will be resized.
964f30c6
DV
3031 *
3032 * This is far more efficient than destroying and re-instantiating a
3033 * Dygraph, since it doesn't have to reparse the underlying data.
3034 *
629a09ae
DV
3035 * @param {Number} [width] Width (in pixels)
3036 * @param {Number} [height] Height (in pixels)
697e70b2
DV
3037 */
3038Dygraph.prototype.resize = function(width, height) {
e8c7ef86
DV
3039 if (this.resize_lock) {
3040 return;
3041 }
3042 this.resize_lock = true;
3043
697e70b2
DV
3044 if ((width === null) != (height === null)) {
3045 this.warn("Dygraph.resize() should be called with zero parameters or " +
3046 "two non-NULL parameters. Pretending it was zero.");
3047 width = height = null;
3048 }
3049
4b4d1a63
DV
3050 var old_width = this.width_;
3051 var old_height = this.height_;
b16e6369 3052
697e70b2
DV
3053 if (width) {
3054 this.maindiv_.style.width = width + "px";
3055 this.maindiv_.style.height = height + "px";
3056 this.width_ = width;
3057 this.height_ = height;
3058 } else {
ccd9d7c2
PF
3059 this.width_ = this.maindiv_.clientWidth;
3060 this.height_ = this.maindiv_.clientHeight;
697e70b2
DV
3061 }
3062
4b4d1a63
DV
3063 if (old_width != this.width_ || old_height != this.height_) {
3064 // TODO(danvk): there should be a clear() method.
3065 this.maindiv_.innerHTML = "";
77b5e09d 3066 this.roller_ = null;
4b4d1a63
DV
3067 this.attrs_.labelsDiv = null;
3068 this.createInterface_();
c9faeafd
DV
3069 if (this.annotations_.length) {
3070 // createInterface_ reset the layout, so we need to do this.
3071 this.layout_.setAnnotations(this.annotations_);
3072 }
4b4d1a63
DV
3073 this.predraw_();
3074 }
e8c7ef86
DV
3075
3076 this.resize_lock = false;
697e70b2
DV
3077};
3078
3079/**
6faebb69 3080 * Adjusts the number of points in the rolling average. Updates the graph to
6a1aa64f 3081 * reflect the new averaging period.
6faebb69 3082 * @param {Number} length Number of points over which to average the data.
6a1aa64f 3083 */
285a6bda 3084Dygraph.prototype.adjustRoll = function(length) {
6a1aa64f 3085 this.rollPeriod_ = length;
26ca7938 3086 this.predraw_();
6a1aa64f 3087};
540d00f1 3088
f8cfec73 3089/**
1cf11047
DV
3090 * Returns a boolean array of visibility statuses.
3091 */
3092Dygraph.prototype.visibility = function() {
3093 // Do lazy-initialization, so that this happens after we know the number of
3094 // data series.
3095 if (!this.attr_("visibility")) {
f38dec01 3096 this.attrs_["visibility"] = [];
1cf11047
DV
3097 }
3098 while (this.attr_("visibility").length < this.rawData_[0].length - 1) {
f38dec01 3099 this.attr_("visibility").push(true);
1cf11047
DV
3100 }
3101 return this.attr_("visibility");
3102};
3103
3104/**
3105 * Changes the visiblity of a series.
3106 */
3107Dygraph.prototype.setVisibility = function(num, value) {
3108 var x = this.visibility();
a6c109c1 3109 if (num < 0 || num >= x.length) {
1cf11047
DV
3110 this.warn("invalid series number in setVisibility: " + num);
3111 } else {
3112 x[num] = value;
26ca7938 3113 this.predraw_();
1cf11047
DV
3114 }
3115};
3116
3117/**
0cb9bd91
DV
3118 * How large of an area will the dygraph render itself in?
3119 * This is used for testing.
3120 * @return A {width: w, height: h} object.
3121 * @private
3122 */
3123Dygraph.prototype.size = function() {
3124 return { width: this.width_, height: this.height_ };
3125};
3126
3127/**
5c528fa2 3128 * Update the list of annotations and redraw the chart.
41ee764f
DV
3129 * See dygraphs.com/annotations.html for more info on how to use annotations.
3130 * @param ann {Array} An array of annotation objects.
3131 * @param suppressDraw {Boolean} Set to "true" to block chart redraw (optional).
5c528fa2 3132 */
a685723c 3133Dygraph.prototype.setAnnotations = function(ann, suppressDraw) {
3c51ab74
DV
3134 // Only add the annotation CSS rule once we know it will be used.
3135 Dygraph.addAnnotationRule();
5c528fa2
DV
3136 this.annotations_ = ann;
3137 this.layout_.setAnnotations(this.annotations_);
a685723c 3138 if (!suppressDraw) {
26ca7938 3139 this.predraw_();
a685723c 3140 }
5c528fa2
DV
3141};
3142
3143/**
3144 * Return the list of annotations.
3145 */
3146Dygraph.prototype.annotations = function() {
3147 return this.annotations_;
3148};
3149
46dde5f9
DV
3150/**
3151 * Get the index of a series (column) given its name. The first column is the
3152 * x-axis, so the data series start with index 1.
3153 */
3154Dygraph.prototype.indexFromSetName = function(name) {
3155 var labels = this.attr_("labels");
3156 for (var i = 0; i < labels.length; i++) {
3157 if (labels[i] == name) return i;
3158 }
3159 return null;
3160};
3161
629a09ae
DV
3162/**
3163 * @private
3164 * Adds a default style for the annotation CSS classes to the document. This is
3165 * only executed when annotations are actually used. It is designed to only be
3166 * called once -- all calls after the first will return immediately.
3167 */
5c528fa2
DV
3168Dygraph.addAnnotationRule = function() {
3169 if (Dygraph.addedAnnotationCSS) return;
3170
5c528fa2
DV
3171 var rule = "border: 1px solid black; " +
3172 "background-color: white; " +
3173 "text-align: center;";
22186871
DV
3174
3175 var styleSheetElement = document.createElement("style");
3176 styleSheetElement.type = "text/css";
3177 document.getElementsByTagName("head")[0].appendChild(styleSheetElement);
3178
3179 // Find the first style sheet that we can access.
3180 // We may not add a rule to a style sheet from another domain for security
3181 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3182 // adds its own style sheets from google.com.
3183 for (var i = 0; i < document.styleSheets.length; i++) {
3184 if (document.styleSheets[i].disabled) continue;
3185 var mysheet = document.styleSheets[i];
3186 try {
3187 if (mysheet.insertRule) { // Firefox
3188 var idx = mysheet.cssRules ? mysheet.cssRules.length : 0;
3189 mysheet.insertRule(".dygraphDefaultAnnotation { " + rule + " }", idx);
3190 } else if (mysheet.addRule) { // IE
3191 mysheet.addRule(".dygraphDefaultAnnotation", rule);
3192 }
3193 Dygraph.addedAnnotationCSS = true;
3194 return;
3195 } catch(err) {
3196 // Was likely a security exception.
3197 }
5c528fa2
DV
3198 }
3199
22186871 3200 this.warn("Unable to add default annotation CSS rule; display may be off.");
5c528fa2
DV
3201}
3202
285a6bda
DV
3203// Older pages may still use this name.
3204DateGraph = Dygraph;