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