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