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