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