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