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