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