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