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