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