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