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