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