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