Merge pull request #590 from danvk/540-fixup
[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 var minDate = this.rawData_[0][0];
1660 var maxDate = this.rawData_[this.rawData_.length - 1][0];
1661
1662 // With only one frame, don't bother calculating extreme ranges.
1663 // TODO(danvk): merge this block w/ the code below.
1664 if (!this.getBooleanOption("animatedZooms")) {
1665 this.dateWindow_ = null;
1666 for (i = 0; i < this.axes_.length; i++) {
1667 if (this.axes_[i].valueWindow !== null) {
1668 delete this.axes_[i].valueWindow;
1669 }
1670 }
1671 this.drawGraph_();
1672 if (this.getFunctionOption("zoomCallback")) {
1673 this.getFunctionOption("zoomCallback").call(this,
1674 minDate, maxDate, this.yAxisRanges());
1675 }
1676 return;
1677 }
1678
1679 var oldWindow=null, newWindow=null, oldValueRanges=null, newValueRanges=null;
1680 if (dirtyX) {
1681 oldWindow = this.xAxisRange();
1682 newWindow = [minDate, maxDate];
1683 }
1684
1685 if (dirtyY) {
1686 oldValueRanges = this.yAxisRanges();
1687 // TODO(danvk): this is pretty inefficient
1688 var packed = this.gatherDatasets_(this.rolledSeries_, null);
1689 var extremes = packed.extremes;
1690
1691 // this has the side-effect of modifying this.axes_.
1692 // this doesn't make much sense in this context, but it's convenient (we
1693 // need this.axes_[*].extremeValues) and not harmful since we'll be
1694 // calling drawGraph_ shortly, which clobbers these values.
1695 this.computeYAxisRanges_(extremes);
1696
1697 newValueRanges = [];
1698 for (i = 0; i < this.axes_.length; i++) {
1699 var axis = this.axes_[i];
1700 newValueRanges.push((axis.valueRange !== null &&
1701 axis.valueRange !== undefined) ?
1702 axis.valueRange : axis.extremeRange);
1703 }
1704 }
1705
1706 var that = this;
1707 this.doAnimatedZoom(oldWindow, newWindow, oldValueRanges, newValueRanges,
1708 function() {
1709 that.dateWindow_ = null;
1710 for (var i = 0; i < that.axes_.length; i++) {
1711 if (that.axes_[i].valueWindow !== null) {
1712 delete that.axes_[i].valueWindow;
1713 }
1714 }
1715 if (that.getFunctionOption("zoomCallback")) {
1716 that.getFunctionOption("zoomCallback").call(that,
1717 minDate, maxDate, that.yAxisRanges());
1718 }
1719 });
1720 }
1721 };
1722
1723 /**
1724 * Combined animation logic for all zoom functions.
1725 * either the x parameters or y parameters may be null.
1726 * @private
1727 */
1728 Dygraph.prototype.doAnimatedZoom = function(oldXRange, newXRange, oldYRanges, newYRanges, callback) {
1729 var steps = this.getBooleanOption("animatedZooms") ?
1730 Dygraph.ANIMATION_STEPS : 1;
1731
1732 var windows = [];
1733 var valueRanges = [];
1734 var step, frac;
1735
1736 if (oldXRange !== null && newXRange !== null) {
1737 for (step = 1; step <= steps; step++) {
1738 frac = Dygraph.zoomAnimationFunction(step, steps);
1739 windows[step-1] = [oldXRange[0]*(1-frac) + frac*newXRange[0],
1740 oldXRange[1]*(1-frac) + frac*newXRange[1]];
1741 }
1742 }
1743
1744 if (oldYRanges !== null && newYRanges !== null) {
1745 for (step = 1; step <= steps; step++) {
1746 frac = Dygraph.zoomAnimationFunction(step, steps);
1747 var thisRange = [];
1748 for (var j = 0; j < this.axes_.length; j++) {
1749 thisRange.push([oldYRanges[j][0]*(1-frac) + frac*newYRanges[j][0],
1750 oldYRanges[j][1]*(1-frac) + frac*newYRanges[j][1]]);
1751 }
1752 valueRanges[step-1] = thisRange;
1753 }
1754 }
1755
1756 var that = this;
1757 Dygraph.repeatAndCleanup(function(step) {
1758 if (valueRanges.length) {
1759 for (var i = 0; i < that.axes_.length; i++) {
1760 var w = valueRanges[step][i];
1761 that.axes_[i].valueWindow = [w[0], w[1]];
1762 }
1763 }
1764 if (windows.length) {
1765 that.dateWindow_ = windows[step];
1766 }
1767 that.drawGraph_();
1768 }, steps, Dygraph.ANIMATION_DURATION / steps, callback);
1769 };
1770
1771 /**
1772 * Get the current graph's area object.
1773 *
1774 * Returns: {x, y, w, h}
1775 */
1776 Dygraph.prototype.getArea = function() {
1777 return this.plotter_.area;
1778 };
1779
1780 /**
1781 * Convert a mouse event to DOM coordinates relative to the graph origin.
1782 *
1783 * Returns a two-element array: [X, Y].
1784 */
1785 Dygraph.prototype.eventToDomCoords = function(event) {
1786 if (event.offsetX && event.offsetY) {
1787 return [ event.offsetX, event.offsetY ];
1788 } else {
1789 var eventElementPos = Dygraph.findPos(this.mouseEventElement_);
1790 var canvasx = Dygraph.pageX(event) - eventElementPos.x;
1791 var canvasy = Dygraph.pageY(event) - eventElementPos.y;
1792 return [canvasx, canvasy];
1793 }
1794 };
1795
1796 /**
1797 * Given a canvas X coordinate, find the closest row.
1798 * @param {number} domX graph-relative DOM X coordinate
1799 * Returns {number} row number.
1800 * @private
1801 */
1802 Dygraph.prototype.findClosestRow = function(domX) {
1803 var minDistX = Infinity;
1804 var closestRow = -1;
1805 var sets = this.layout_.points;
1806 for (var i = 0; i < sets.length; i++) {
1807 var points = sets[i];
1808 var len = points.length;
1809 for (var j = 0; j < len; j++) {
1810 var point = points[j];
1811 if (!Dygraph.isValidPoint(point, true)) continue;
1812 var dist = Math.abs(point.canvasx - domX);
1813 if (dist < minDistX) {
1814 minDistX = dist;
1815 closestRow = point.idx;
1816 }
1817 }
1818 }
1819
1820 return closestRow;
1821 };
1822
1823 /**
1824 * Given canvas X,Y coordinates, find the closest point.
1825 *
1826 * This finds the individual data point across all visible series
1827 * that's closest to the supplied DOM coordinates using the standard
1828 * Euclidean X,Y distance.
1829 *
1830 * @param {number} domX graph-relative DOM X coordinate
1831 * @param {number} domY graph-relative DOM Y coordinate
1832 * Returns: {row, seriesName, point}
1833 * @private
1834 */
1835 Dygraph.prototype.findClosestPoint = function(domX, domY) {
1836 var minDist = Infinity;
1837 var dist, dx, dy, point, closestPoint, closestSeries, closestRow;
1838 for ( var setIdx = this.layout_.points.length - 1 ; setIdx >= 0 ; --setIdx ) {
1839 var points = this.layout_.points[setIdx];
1840 for (var i = 0; i < points.length; ++i) {
1841 point = points[i];
1842 if (!Dygraph.isValidPoint(point)) continue;
1843 dx = point.canvasx - domX;
1844 dy = point.canvasy - domY;
1845 dist = dx * dx + dy * dy;
1846 if (dist < minDist) {
1847 minDist = dist;
1848 closestPoint = point;
1849 closestSeries = setIdx;
1850 closestRow = point.idx;
1851 }
1852 }
1853 }
1854 var name = this.layout_.setNames[closestSeries];
1855 return {
1856 row: closestRow,
1857 seriesName: name,
1858 point: closestPoint
1859 };
1860 };
1861
1862 /**
1863 * Given canvas X,Y coordinates, find the touched area in a stacked graph.
1864 *
1865 * This first finds the X data point closest to the supplied DOM X coordinate,
1866 * then finds the series which puts the Y coordinate on top of its filled area,
1867 * using linear interpolation between adjacent point pairs.
1868 *
1869 * @param {number} domX graph-relative DOM X coordinate
1870 * @param {number} domY graph-relative DOM Y coordinate
1871 * Returns: {row, seriesName, point}
1872 * @private
1873 */
1874 Dygraph.prototype.findStackedPoint = function(domX, domY) {
1875 var row = this.findClosestRow(domX);
1876 var closestPoint, closestSeries;
1877 for (var setIdx = 0; setIdx < this.layout_.points.length; ++setIdx) {
1878 var boundary = this.getLeftBoundary_(setIdx);
1879 var rowIdx = row - boundary;
1880 var points = this.layout_.points[setIdx];
1881 if (rowIdx >= points.length) continue;
1882 var p1 = points[rowIdx];
1883 if (!Dygraph.isValidPoint(p1)) continue;
1884 var py = p1.canvasy;
1885 if (domX > p1.canvasx && rowIdx + 1 < points.length) {
1886 // interpolate series Y value using next point
1887 var p2 = points[rowIdx + 1];
1888 if (Dygraph.isValidPoint(p2)) {
1889 var dx = p2.canvasx - p1.canvasx;
1890 if (dx > 0) {
1891 var r = (domX - p1.canvasx) / dx;
1892 py += r * (p2.canvasy - p1.canvasy);
1893 }
1894 }
1895 } else if (domX < p1.canvasx && rowIdx > 0) {
1896 // interpolate series Y value using previous point
1897 var p0 = points[rowIdx - 1];
1898 if (Dygraph.isValidPoint(p0)) {
1899 var dx = p1.canvasx - p0.canvasx;
1900 if (dx > 0) {
1901 var r = (p1.canvasx - domX) / dx;
1902 py += r * (p0.canvasy - p1.canvasy);
1903 }
1904 }
1905 }
1906 // Stop if the point (domX, py) is above this series' upper edge
1907 if (setIdx === 0 || py < domY) {
1908 closestPoint = p1;
1909 closestSeries = setIdx;
1910 }
1911 }
1912 var name = this.layout_.setNames[closestSeries];
1913 return {
1914 row: row,
1915 seriesName: name,
1916 point: closestPoint
1917 };
1918 };
1919
1920 /**
1921 * When the mouse moves in the canvas, display information about a nearby data
1922 * point and draw dots over those points in the data series. This function
1923 * takes care of cleanup of previously-drawn dots.
1924 * @param {Object} event The mousemove event from the browser.
1925 * @private
1926 */
1927 Dygraph.prototype.mouseMove_ = function(event) {
1928 // This prevents JS errors when mousing over the canvas before data loads.
1929 var points = this.layout_.points;
1930 if (points === undefined || points === null) return;
1931
1932 var canvasCoords = this.eventToDomCoords(event);
1933 var canvasx = canvasCoords[0];
1934 var canvasy = canvasCoords[1];
1935
1936 var highlightSeriesOpts = this.getOption("highlightSeriesOpts");
1937 var selectionChanged = false;
1938 if (highlightSeriesOpts && !this.isSeriesLocked()) {
1939 var closest;
1940 if (this.getBooleanOption("stackedGraph")) {
1941 closest = this.findStackedPoint(canvasx, canvasy);
1942 } else {
1943 closest = this.findClosestPoint(canvasx, canvasy);
1944 }
1945 selectionChanged = this.setSelection(closest.row, closest.seriesName);
1946 } else {
1947 var idx = this.findClosestRow(canvasx);
1948 selectionChanged = this.setSelection(idx);
1949 }
1950
1951 var callback = this.getFunctionOption("highlightCallback");
1952 if (callback && selectionChanged) {
1953 callback.call(this, event,
1954 this.lastx_,
1955 this.selPoints_,
1956 this.lastRow_,
1957 this.highlightSet_);
1958 }
1959 };
1960
1961 /**
1962 * Fetch left offset from the specified set index or if not passed, the
1963 * first defined boundaryIds record (see bug #236).
1964 * @private
1965 */
1966 Dygraph.prototype.getLeftBoundary_ = function(setIdx) {
1967 if (this.boundaryIds_[setIdx]) {
1968 return this.boundaryIds_[setIdx][0];
1969 } else {
1970 for (var i = 0; i < this.boundaryIds_.length; i++) {
1971 if (this.boundaryIds_[i] !== undefined) {
1972 return this.boundaryIds_[i][0];
1973 }
1974 }
1975 return 0;
1976 }
1977 };
1978
1979 Dygraph.prototype.animateSelection_ = function(direction) {
1980 var totalSteps = 10;
1981 var millis = 30;
1982 if (this.fadeLevel === undefined) this.fadeLevel = 0;
1983 if (this.animateId === undefined) this.animateId = 0;
1984 var start = this.fadeLevel;
1985 var steps = direction < 0 ? start : totalSteps - start;
1986 if (steps <= 0) {
1987 if (this.fadeLevel) {
1988 this.updateSelection_(1.0);
1989 }
1990 return;
1991 }
1992
1993 var thisId = ++this.animateId;
1994 var that = this;
1995 var cleanupIfClearing = function() {
1996 // if we haven't reached fadeLevel 0 in the max frame time,
1997 // ensure that the clear happens and just go to 0
1998 if (that.fadeLevel !== 0 && direction < 0) {
1999 that.fadeLevel = 0;
2000 that.clearSelection();
2001 }
2002 };
2003 Dygraph.repeatAndCleanup(
2004 function(n) {
2005 // ignore simultaneous animations
2006 if (that.animateId != thisId) return;
2007
2008 that.fadeLevel += direction;
2009 if (that.fadeLevel === 0) {
2010 that.clearSelection();
2011 } else {
2012 that.updateSelection_(that.fadeLevel / totalSteps);
2013 }
2014 },
2015 steps, millis, cleanupIfClearing);
2016 };
2017
2018 /**
2019 * Draw dots over the selectied points in the data series. This function
2020 * takes care of cleanup of previously-drawn dots.
2021 * @private
2022 */
2023 Dygraph.prototype.updateSelection_ = function(opt_animFraction) {
2024 /*var defaultPrevented = */
2025 this.cascadeEvents_('select', {
2026 selectedRow: this.lastRow_,
2027 selectedX: this.lastx_,
2028 selectedPoints: this.selPoints_
2029 });
2030 // TODO(danvk): use defaultPrevented here?
2031
2032 // Clear the previously drawn vertical, if there is one
2033 var i;
2034 var ctx = this.canvas_ctx_;
2035 if (this.getOption('highlightSeriesOpts')) {
2036 ctx.clearRect(0, 0, this.width_, this.height_);
2037 var alpha = 1.0 - this.getNumericOption('highlightSeriesBackgroundAlpha');
2038 if (alpha) {
2039 // Activating background fade includes an animation effect for a gradual
2040 // fade. TODO(klausw): make this independently configurable if it causes
2041 // issues? Use a shared preference to control animations?
2042 var animateBackgroundFade = true;
2043 if (animateBackgroundFade) {
2044 if (opt_animFraction === undefined) {
2045 // start a new animation
2046 this.animateSelection_(1);
2047 return;
2048 }
2049 alpha *= opt_animFraction;
2050 }
2051 ctx.fillStyle = 'rgba(255,255,255,' + alpha + ')';
2052 ctx.fillRect(0, 0, this.width_, this.height_);
2053 }
2054
2055 // Redraw only the highlighted series in the interactive canvas (not the
2056 // static plot canvas, which is where series are usually drawn).
2057 this.plotter_._renderLineChart(this.highlightSet_, ctx);
2058 } else if (this.previousVerticalX_ >= 0) {
2059 // Determine the maximum highlight circle size.
2060 var maxCircleSize = 0;
2061 var labels = this.attr_('labels');
2062 for (i = 1; i < labels.length; i++) {
2063 var r = this.getNumericOption('highlightCircleSize', labels[i]);
2064 if (r > maxCircleSize) maxCircleSize = r;
2065 }
2066 var px = this.previousVerticalX_;
2067 ctx.clearRect(px - maxCircleSize - 1, 0,
2068 2 * maxCircleSize + 2, this.height_);
2069 }
2070
2071 if (this.selPoints_.length > 0) {
2072 // Draw colored circles over the center of each selected point
2073 var canvasx = this.selPoints_[0].canvasx;
2074 ctx.save();
2075 for (i = 0; i < this.selPoints_.length; i++) {
2076 var pt = this.selPoints_[i];
2077 if (!Dygraph.isOK(pt.canvasy)) continue;
2078
2079 var circleSize = this.getNumericOption('highlightCircleSize', pt.name);
2080 var callback = this.getFunctionOption("drawHighlightPointCallback", pt.name);
2081 var color = this.plotter_.colors[pt.name];
2082 if (!callback) {
2083 callback = Dygraph.Circles.DEFAULT;
2084 }
2085 ctx.lineWidth = this.getNumericOption('strokeWidth', pt.name);
2086 ctx.strokeStyle = color;
2087 ctx.fillStyle = color;
2088 callback.call(this, this, pt.name, ctx, canvasx, pt.canvasy,
2089 color, circleSize, pt.idx);
2090 }
2091 ctx.restore();
2092
2093 this.previousVerticalX_ = canvasx;
2094 }
2095 };
2096
2097 /**
2098 * Manually set the selected points and display information about them in the
2099 * legend. The selection can be cleared using clearSelection() and queried
2100 * using getSelection().
2101 * @param {number} row Row number that should be highlighted (i.e. appear with
2102 * hover dots on the chart).
2103 * @param {seriesName} optional series name to highlight that series with the
2104 * the highlightSeriesOpts setting.
2105 * @param { locked } optional If true, keep seriesName selected when mousing
2106 * over the graph, disabling closest-series highlighting. Call clearSelection()
2107 * to unlock it.
2108 */
2109 Dygraph.prototype.setSelection = function(row, opt_seriesName, opt_locked) {
2110 // Extract the points we've selected
2111 this.selPoints_ = [];
2112
2113 var changed = false;
2114 if (row !== false && row >= 0) {
2115 if (row != this.lastRow_) changed = true;
2116 this.lastRow_ = row;
2117 for (var setIdx = 0; setIdx < this.layout_.points.length; ++setIdx) {
2118 var points = this.layout_.points[setIdx];
2119 // Check if the point at the appropriate index is the point we're looking
2120 // for. If it is, just use it, otherwise search the array for a point
2121 // in the proper place.
2122 var setRow = row - this.getLeftBoundary_(setIdx);
2123 if (setRow < points.length && points[setRow].idx == row) {
2124 var point = points[setRow];
2125 if (point.yval !== null) this.selPoints_.push(point);
2126 } else {
2127 for (var pointIdx = 0; pointIdx < points.length; ++pointIdx) {
2128 var point = points[pointIdx];
2129 if (point.idx == row) {
2130 if (point.yval !== null) {
2131 this.selPoints_.push(point);
2132 }
2133 break;
2134 }
2135 }
2136 }
2137 }
2138 } else {
2139 if (this.lastRow_ >= 0) changed = true;
2140 this.lastRow_ = -1;
2141 }
2142
2143 if (this.selPoints_.length) {
2144 this.lastx_ = this.selPoints_[0].xval;
2145 } else {
2146 this.lastx_ = -1;
2147 }
2148
2149 if (opt_seriesName !== undefined) {
2150 if (this.highlightSet_ !== opt_seriesName) changed = true;
2151 this.highlightSet_ = opt_seriesName;
2152 }
2153
2154 if (opt_locked !== undefined) {
2155 this.lockedSet_ = opt_locked;
2156 }
2157
2158 if (changed) {
2159 this.updateSelection_(undefined);
2160 }
2161 return changed;
2162 };
2163
2164 /**
2165 * The mouse has left the canvas. Clear out whatever artifacts remain
2166 * @param {Object} event the mouseout event from the browser.
2167 * @private
2168 */
2169 Dygraph.prototype.mouseOut_ = function(event) {
2170 if (this.getFunctionOption("unhighlightCallback")) {
2171 this.getFunctionOption("unhighlightCallback").call(this, event);
2172 }
2173
2174 if (this.getBooleanOption("hideOverlayOnMouseOut") && !this.lockedSet_) {
2175 this.clearSelection();
2176 }
2177 };
2178
2179 /**
2180 * Clears the current selection (i.e. points that were highlighted by moving
2181 * the mouse over the chart).
2182 */
2183 Dygraph.prototype.clearSelection = function() {
2184 this.cascadeEvents_('deselect', {});
2185
2186 this.lockedSet_ = false;
2187 // Get rid of the overlay data
2188 if (this.fadeLevel) {
2189 this.animateSelection_(-1);
2190 return;
2191 }
2192 this.canvas_ctx_.clearRect(0, 0, this.width_, this.height_);
2193 this.fadeLevel = 0;
2194 this.selPoints_ = [];
2195 this.lastx_ = -1;
2196 this.lastRow_ = -1;
2197 this.highlightSet_ = null;
2198 };
2199
2200 /**
2201 * Returns the number of the currently selected row. To get data for this row,
2202 * you can use the getValue method.
2203 * @return {number} row number, or -1 if nothing is selected
2204 */
2205 Dygraph.prototype.getSelection = function() {
2206 if (!this.selPoints_ || this.selPoints_.length < 1) {
2207 return -1;
2208 }
2209
2210 for (var setIdx = 0; setIdx < this.layout_.points.length; setIdx++) {
2211 var points = this.layout_.points[setIdx];
2212 for (var row = 0; row < points.length; row++) {
2213 if (points[row].x == this.selPoints_[0].x) {
2214 return points[row].idx;
2215 }
2216 }
2217 }
2218 return -1;
2219 };
2220
2221 /**
2222 * Returns the name of the currently-highlighted series.
2223 * Only available when the highlightSeriesOpts option is in use.
2224 */
2225 Dygraph.prototype.getHighlightSeries = function() {
2226 return this.highlightSet_;
2227 };
2228
2229 /**
2230 * Returns true if the currently-highlighted series was locked
2231 * via setSelection(..., seriesName, true).
2232 */
2233 Dygraph.prototype.isSeriesLocked = function() {
2234 return this.lockedSet_;
2235 };
2236
2237 /**
2238 * Fires when there's data available to be graphed.
2239 * @param {string} data Raw CSV data to be plotted
2240 * @private
2241 */
2242 Dygraph.prototype.loadedEvent_ = function(data) {
2243 this.rawData_ = this.parseCSV_(data);
2244 this.cascadeDataDidUpdateEvent_();
2245 this.predraw_();
2246 };
2247
2248 /**
2249 * Add ticks on the x-axis representing years, months, quarters, weeks, or days
2250 * @private
2251 */
2252 Dygraph.prototype.addXTicks_ = function() {
2253 // Determine the correct ticks scale on the x-axis: quarterly, monthly, ...
2254 var range;
2255 if (this.dateWindow_) {
2256 range = [this.dateWindow_[0], this.dateWindow_[1]];
2257 } else {
2258 range = this.xAxisExtremes();
2259 }
2260
2261 var xAxisOptionsView = this.optionsViewForAxis_('x');
2262 var xTicks = xAxisOptionsView('ticker')(
2263 range[0],
2264 range[1],
2265 this.plotter_.area.w, // TODO(danvk): should be area.width
2266 xAxisOptionsView,
2267 this);
2268 // var msg = 'ticker(' + range[0] + ', ' + range[1] + ', ' + this.width_ + ', ' + this.attr_('pixelsPerXLabel') + ') -> ' + JSON.stringify(xTicks);
2269 // console.log(msg);
2270 this.layout_.setXTicks(xTicks);
2271 };
2272
2273 /**
2274 * Returns the correct handler class for the currently set options.
2275 * @private
2276 */
2277 Dygraph.prototype.getHandlerClass_ = function() {
2278 var handlerClass;
2279 if (this.attr_('dataHandler')) {
2280 handlerClass = this.attr_('dataHandler');
2281 } else if (this.fractions_) {
2282 if (this.getBooleanOption('errorBars')) {
2283 handlerClass = Dygraph.DataHandlers.FractionsBarsHandler;
2284 } else {
2285 handlerClass = Dygraph.DataHandlers.DefaultFractionHandler;
2286 }
2287 } else if (this.getBooleanOption('customBars')) {
2288 handlerClass = Dygraph.DataHandlers.CustomBarsHandler;
2289 } else if (this.getBooleanOption('errorBars')) {
2290 handlerClass = Dygraph.DataHandlers.ErrorBarsHandler;
2291 } else {
2292 handlerClass = Dygraph.DataHandlers.DefaultHandler;
2293 }
2294 return handlerClass;
2295 };
2296
2297 /**
2298 * @private
2299 * This function is called once when the chart's data is changed or the options
2300 * dictionary is updated. It is _not_ called when the user pans or zooms. The
2301 * idea is that values derived from the chart's data can be computed here,
2302 * rather than every time the chart is drawn. This includes things like the
2303 * number of axes, rolling averages, etc.
2304 */
2305 Dygraph.prototype.predraw_ = function() {
2306 var start = new Date();
2307
2308 // Create the correct dataHandler
2309 this.dataHandler_ = new (this.getHandlerClass_())();
2310
2311 this.layout_.computePlotArea();
2312
2313 // TODO(danvk): move more computations out of drawGraph_ and into here.
2314 this.computeYAxes_();
2315
2316 if (!this.is_initial_draw_) {
2317 this.canvas_ctx_.restore();
2318 this.hidden_ctx_.restore();
2319 }
2320
2321 this.canvas_ctx_.save();
2322 this.hidden_ctx_.save();
2323
2324 // Create a new plotter.
2325 this.plotter_ = new DygraphCanvasRenderer(this,
2326 this.hidden_,
2327 this.hidden_ctx_,
2328 this.layout_);
2329
2330 // The roller sits in the bottom left corner of the chart. We don't know where
2331 // this will be until the options are available, so it's positioned here.
2332 this.createRollInterface_();
2333
2334 this.cascadeEvents_('predraw');
2335
2336 // Convert the raw data (a 2D array) into the internal format and compute
2337 // rolling averages.
2338 this.rolledSeries_ = [null]; // x-axis is the first series and it's special
2339 for (var i = 1; i < this.numColumns(); i++) {
2340 // var logScale = this.attr_('logscale', i); // TODO(klausw): this looks wrong // konigsberg thinks so too.
2341 var series = this.dataHandler_.extractSeries(this.rawData_, i, this.attributes_);
2342 if (this.rollPeriod_ > 1) {
2343 series = this.dataHandler_.rollingAverage(series, this.rollPeriod_, this.attributes_);
2344 }
2345
2346 this.rolledSeries_.push(series);
2347 }
2348
2349 // If the data or options have changed, then we'd better redraw.
2350 this.drawGraph_();
2351
2352 // This is used to determine whether to do various animations.
2353 var end = new Date();
2354 this.drawingTimeMs_ = (end - start);
2355 };
2356
2357 /**
2358 * Point structure.
2359 *
2360 * xval_* and yval_* are the original unscaled data values,
2361 * while x_* and y_* are scaled to the range (0.0-1.0) for plotting.
2362 * yval_stacked is the cumulative Y value used for stacking graphs,
2363 * and bottom/top/minus/plus are used for error bar graphs.
2364 *
2365 * @typedef {{
2366 * idx: number,
2367 * name: string,
2368 * x: ?number,
2369 * xval: ?number,
2370 * y_bottom: ?number,
2371 * y: ?number,
2372 * y_stacked: ?number,
2373 * y_top: ?number,
2374 * yval_minus: ?number,
2375 * yval: ?number,
2376 * yval_plus: ?number,
2377 * yval_stacked
2378 * }}
2379 */
2380 Dygraph.PointType = undefined;
2381
2382 /**
2383 * Calculates point stacking for stackedGraph=true.
2384 *
2385 * For stacking purposes, interpolate or extend neighboring data across
2386 * NaN values based on stackedGraphNaNFill settings. This is for display
2387 * only, the underlying data value as shown in the legend remains NaN.
2388 *
2389 * @param {Array.<Dygraph.PointType>} points Point array for a single series.
2390 * Updates each Point's yval_stacked property.
2391 * @param {Array.<number>} cumulativeYval Accumulated top-of-graph stacked Y
2392 * values for the series seen so far. Index is the row number. Updated
2393 * based on the current series's values.
2394 * @param {Array.<number>} seriesExtremes Min and max values, updated
2395 * to reflect the stacked values.
2396 * @param {string} fillMethod Interpolation method, one of 'all', 'inside', or
2397 * 'none'.
2398 * @private
2399 */
2400 Dygraph.stackPoints_ = function(
2401 points, cumulativeYval, seriesExtremes, fillMethod) {
2402 var lastXval = null;
2403 var prevPoint = null;
2404 var nextPoint = null;
2405 var nextPointIdx = -1;
2406
2407 // Find the next stackable point starting from the given index.
2408 var updateNextPoint = function(idx) {
2409 // If we've previously found a non-NaN point and haven't gone past it yet,
2410 // just use that.
2411 if (nextPointIdx >= idx) return;
2412
2413 // We haven't found a non-NaN point yet or have moved past it,
2414 // look towards the right to find a non-NaN point.
2415 for (var j = idx; j < points.length; ++j) {
2416 // Clear out a previously-found point (if any) since it's no longer
2417 // valid, we shouldn't use it for interpolation anymore.
2418 nextPoint = null;
2419 if (!isNaN(points[j].yval) && points[j].yval !== null) {
2420 nextPointIdx = j;
2421 nextPoint = points[j];
2422 break;
2423 }
2424 }
2425 };
2426
2427 for (var i = 0; i < points.length; ++i) {
2428 var point = points[i];
2429 var xval = point.xval;
2430 if (cumulativeYval[xval] === undefined) {
2431 cumulativeYval[xval] = 0;
2432 }
2433
2434 var actualYval = point.yval;
2435 if (isNaN(actualYval) || actualYval === null) {
2436 if(fillMethod == 'none') {
2437 actualYval = 0;
2438 } else {
2439 // Interpolate/extend for stacking purposes if possible.
2440 updateNextPoint(i);
2441 if (prevPoint && nextPoint && fillMethod != 'none') {
2442 // Use linear interpolation between prevPoint and nextPoint.
2443 actualYval = prevPoint.yval + (nextPoint.yval - prevPoint.yval) *
2444 ((xval - prevPoint.xval) / (nextPoint.xval - prevPoint.xval));
2445 } else if (prevPoint && fillMethod == 'all') {
2446 actualYval = prevPoint.yval;
2447 } else if (nextPoint && fillMethod == 'all') {
2448 actualYval = nextPoint.yval;
2449 } else {
2450 actualYval = 0;
2451 }
2452 }
2453 } else {
2454 prevPoint = point;
2455 }
2456
2457 var stackedYval = cumulativeYval[xval];
2458 if (lastXval != xval) {
2459 // If an x-value is repeated, we ignore the duplicates.
2460 stackedYval += actualYval;
2461 cumulativeYval[xval] = stackedYval;
2462 }
2463 lastXval = xval;
2464
2465 point.yval_stacked = stackedYval;
2466
2467 if (stackedYval > seriesExtremes[1]) {
2468 seriesExtremes[1] = stackedYval;
2469 }
2470 if (stackedYval < seriesExtremes[0]) {
2471 seriesExtremes[0] = stackedYval;
2472 }
2473 }
2474 };
2475
2476
2477 /**
2478 * Loop over all fields and create datasets, calculating extreme y-values for
2479 * each series and extreme x-indices as we go.
2480 *
2481 * dateWindow is passed in as an explicit parameter so that we can compute
2482 * extreme values "speculatively", i.e. without actually setting state on the
2483 * dygraph.
2484 *
2485 * @param {Array.<Array.<Array.<(number|Array<number>)>>} rolledSeries, where
2486 * rolledSeries[seriesIndex][row] = raw point, where
2487 * seriesIndex is the column number starting with 1, and
2488 * rawPoint is [x,y] or [x, [y, err]] or [x, [y, yminus, yplus]].
2489 * @param {?Array.<number>} dateWindow [xmin, xmax] pair, or null.
2490 * @return {{
2491 * points: Array.<Array.<Dygraph.PointType>>,
2492 * seriesExtremes: Array.<Array.<number>>,
2493 * boundaryIds: Array.<number>}}
2494 * @private
2495 */
2496 Dygraph.prototype.gatherDatasets_ = function(rolledSeries, dateWindow) {
2497 var boundaryIds = [];
2498 var points = [];
2499 var cumulativeYval = []; // For stacked series.
2500 var extremes = {}; // series name -> [low, high]
2501 var seriesIdx, sampleIdx;
2502 var firstIdx, lastIdx;
2503 var axisIdx;
2504
2505 // Loop over the fields (series). Go from the last to the first,
2506 // because if they're stacked that's how we accumulate the values.
2507 var num_series = rolledSeries.length - 1;
2508 var series;
2509 for (seriesIdx = num_series; seriesIdx >= 1; seriesIdx--) {
2510 if (!this.visibility()[seriesIdx - 1]) continue;
2511
2512 // Prune down to the desired range, if necessary (for zooming)
2513 // Because there can be lines going to points outside of the visible area,
2514 // we actually prune to visible points, plus one on either side.
2515 if (dateWindow) {
2516 series = rolledSeries[seriesIdx];
2517 var low = dateWindow[0];
2518 var high = dateWindow[1];
2519
2520 // TODO(danvk): do binary search instead of linear search.
2521 // TODO(danvk): pass firstIdx and lastIdx directly to the renderer.
2522 firstIdx = null;
2523 lastIdx = null;
2524 for (sampleIdx = 0; sampleIdx < series.length; sampleIdx++) {
2525 if (series[sampleIdx][0] >= low && firstIdx === null) {
2526 firstIdx = sampleIdx;
2527 }
2528 if (series[sampleIdx][0] <= high) {
2529 lastIdx = sampleIdx;
2530 }
2531 }
2532
2533 if (firstIdx === null) firstIdx = 0;
2534 var correctedFirstIdx = firstIdx;
2535 var isInvalidValue = true;
2536 while (isInvalidValue && correctedFirstIdx > 0) {
2537 correctedFirstIdx--;
2538 // check if the y value is null.
2539 isInvalidValue = series[correctedFirstIdx][1] === null;
2540 }
2541
2542 if (lastIdx === null) lastIdx = series.length - 1;
2543 var correctedLastIdx = lastIdx;
2544 isInvalidValue = true;
2545 while (isInvalidValue && correctedLastIdx < series.length - 1) {
2546 correctedLastIdx++;
2547 isInvalidValue = series[correctedLastIdx][1] === null;
2548 }
2549
2550 if (correctedFirstIdx!==firstIdx) {
2551 firstIdx = correctedFirstIdx;
2552 }
2553 if (correctedLastIdx !== lastIdx) {
2554 lastIdx = correctedLastIdx;
2555 }
2556
2557 boundaryIds[seriesIdx-1] = [firstIdx, lastIdx];
2558
2559 // .slice's end is exclusive, we want to include lastIdx.
2560 series = series.slice(firstIdx, lastIdx + 1);
2561 } else {
2562 series = rolledSeries[seriesIdx];
2563 boundaryIds[seriesIdx-1] = [0, series.length-1];
2564 }
2565
2566 var seriesName = this.attr_("labels")[seriesIdx];
2567 var seriesExtremes = this.dataHandler_.getExtremeYValues(series,
2568 dateWindow, this.getBooleanOption("stepPlot",seriesName));
2569
2570 var seriesPoints = this.dataHandler_.seriesToPoints(series,
2571 seriesName, boundaryIds[seriesIdx-1][0]);
2572
2573 if (this.getBooleanOption("stackedGraph")) {
2574 axisIdx = this.attributes_.axisForSeries(seriesName);
2575 if (cumulativeYval[axisIdx] === undefined) {
2576 cumulativeYval[axisIdx] = [];
2577 }
2578 Dygraph.stackPoints_(seriesPoints, cumulativeYval[axisIdx], seriesExtremes,
2579 this.getBooleanOption("stackedGraphNaNFill"));
2580 }
2581
2582 extremes[seriesName] = seriesExtremes;
2583 points[seriesIdx] = seriesPoints;
2584 }
2585
2586 return { points: points, extremes: extremes, boundaryIds: boundaryIds };
2587 };
2588
2589 /**
2590 * Update the graph with new data. This method is called when the viewing area
2591 * has changed. If the underlying data or options have changed, predraw_ will
2592 * be called before drawGraph_ is called.
2593 *
2594 * @private
2595 */
2596 Dygraph.prototype.drawGraph_ = function() {
2597 var start = new Date();
2598
2599 // This is used to set the second parameter to drawCallback, below.
2600 var is_initial_draw = this.is_initial_draw_;
2601 this.is_initial_draw_ = false;
2602
2603 this.layout_.removeAllDatasets();
2604 this.setColors_();
2605 this.attrs_.pointSize = 0.5 * this.getNumericOption('highlightCircleSize');
2606
2607 var packed = this.gatherDatasets_(this.rolledSeries_, this.dateWindow_);
2608 var points = packed.points;
2609 var extremes = packed.extremes;
2610 this.boundaryIds_ = packed.boundaryIds;
2611
2612 this.setIndexByName_ = {};
2613 var labels = this.attr_("labels");
2614 if (labels.length > 0) {
2615 this.setIndexByName_[labels[0]] = 0;
2616 }
2617 var dataIdx = 0;
2618 for (var i = 1; i < points.length; i++) {
2619 this.setIndexByName_[labels[i]] = i;
2620 if (!this.visibility()[i - 1]) continue;
2621 this.layout_.addDataset(labels[i], points[i]);
2622 this.datasetIndex_[i] = dataIdx++;
2623 }
2624
2625 this.computeYAxisRanges_(extremes);
2626 this.layout_.setYAxes(this.axes_);
2627
2628 this.addXTicks_();
2629
2630 // Save the X axis zoomed status as the updateOptions call will tend to set it erroneously
2631 var tmp_zoomed_x = this.zoomed_x_;
2632 // Tell PlotKit to use this new data and render itself
2633 this.zoomed_x_ = tmp_zoomed_x;
2634 this.layout_.evaluate();
2635 this.renderGraph_(is_initial_draw);
2636
2637 if (this.getStringOption("timingName")) {
2638 var end = new Date();
2639 console.log(this.getStringOption("timingName") + " - drawGraph: " + (end - start) + "ms");
2640 }
2641 };
2642
2643 /**
2644 * This does the work of drawing the chart. It assumes that the layout and axis
2645 * scales have already been set (e.g. by predraw_).
2646 *
2647 * @private
2648 */
2649 Dygraph.prototype.renderGraph_ = function(is_initial_draw) {
2650 this.cascadeEvents_('clearChart');
2651 this.plotter_.clear();
2652
2653 if (this.getFunctionOption('underlayCallback')) {
2654 // NOTE: we pass the dygraph object to this callback twice to avoid breaking
2655 // users who expect a deprecated form of this callback.
2656 this.getFunctionOption('underlayCallback').call(this,
2657 this.hidden_ctx_, this.layout_.getPlotArea(), this, this);
2658 }
2659
2660 var e = {
2661 canvas: this.hidden_,
2662 drawingContext: this.hidden_ctx_
2663 };
2664 this.cascadeEvents_('willDrawChart', e);
2665 this.plotter_.render();
2666 this.cascadeEvents_('didDrawChart', e);
2667 this.lastRow_ = -1; // because plugins/legend.js clears the legend
2668
2669 // TODO(danvk): is this a performance bottleneck when panning?
2670 // The interaction canvas should already be empty in that situation.
2671 this.canvas_.getContext('2d').clearRect(0, 0, this.width_, this.height_);
2672
2673 if (this.getFunctionOption("drawCallback") !== null) {
2674 this.getFunctionOption("drawCallback").call(this, this, is_initial_draw);
2675 }
2676 if (is_initial_draw) {
2677 this.readyFired_ = true;
2678 while (this.readyFns_.length > 0) {
2679 var fn = this.readyFns_.pop();
2680 fn(this);
2681 }
2682 }
2683 };
2684
2685 /**
2686 * @private
2687 * Determine properties of the y-axes which are independent of the data
2688 * currently being displayed. This includes things like the number of axes and
2689 * the style of the axes. It does not include the range of each axis and its
2690 * tick marks.
2691 * This fills in this.axes_.
2692 * axes_ = [ { options } ]
2693 * indices are into the axes_ array.
2694 */
2695 Dygraph.prototype.computeYAxes_ = function() {
2696 // Preserve valueWindow settings if they exist, and if the user hasn't
2697 // specified a new valueRange.
2698 var valueWindows, axis, index, opts, v;
2699 if (this.axes_ !== undefined && this.user_attrs_.hasOwnProperty("valueRange") === false) {
2700 valueWindows = [];
2701 for (index = 0; index < this.axes_.length; index++) {
2702 valueWindows.push(this.axes_[index].valueWindow);
2703 }
2704 }
2705
2706 // this.axes_ doesn't match this.attributes_.axes_.options. It's used for
2707 // data computation as well as options storage.
2708 // Go through once and add all the axes.
2709 this.axes_ = [];
2710
2711 for (axis = 0; axis < this.attributes_.numAxes(); axis++) {
2712 // Add a new axis, making a copy of its per-axis options.
2713 opts = { g : this };
2714 Dygraph.update(opts, this.attributes_.axisOptions(axis));
2715 this.axes_[axis] = opts;
2716 }
2717
2718
2719 // Copy global valueRange option over to the first axis.
2720 // NOTE(konigsberg): Are these two statements necessary?
2721 // I tried removing it. The automated tests pass, and manually
2722 // messing with tests/zoom.html showed no trouble.
2723 v = this.attr_('valueRange');
2724 if (v) this.axes_[0].valueRange = v;
2725
2726 if (valueWindows !== undefined) {
2727 // Restore valueWindow settings.
2728
2729 // When going from two axes back to one, we only restore
2730 // one axis.
2731 var idxCount = Math.min(valueWindows.length, this.axes_.length);
2732
2733 for (index = 0; index < idxCount; index++) {
2734 this.axes_[index].valueWindow = valueWindows[index];
2735 }
2736 }
2737
2738 for (axis = 0; axis < this.axes_.length; axis++) {
2739 if (axis === 0) {
2740 opts = this.optionsViewForAxis_('y' + (axis ? '2' : ''));
2741 v = opts("valueRange");
2742 if (v) this.axes_[axis].valueRange = v;
2743 } else { // To keep old behavior
2744 var axes = this.user_attrs_.axes;
2745 if (axes && axes.y2) {
2746 v = axes.y2.valueRange;
2747 if (v) this.axes_[axis].valueRange = v;
2748 }
2749 }
2750 }
2751 };
2752
2753 /**
2754 * Returns the number of y-axes on the chart.
2755 * @return {number} the number of axes.
2756 */
2757 Dygraph.prototype.numAxes = function() {
2758 return this.attributes_.numAxes();
2759 };
2760
2761 /**
2762 * @private
2763 * Returns axis properties for the given series.
2764 * @param {string} setName The name of the series for which to get axis
2765 * properties, e.g. 'Y1'.
2766 * @return {Object} The axis properties.
2767 */
2768 Dygraph.prototype.axisPropertiesForSeries = function(series) {
2769 // TODO(danvk): handle errors.
2770 return this.axes_[this.attributes_.axisForSeries(series)];
2771 };
2772
2773 /**
2774 * @private
2775 * Determine the value range and tick marks for each axis.
2776 * @param {Object} extremes A mapping from seriesName -> [low, high]
2777 * This fills in the valueRange and ticks fields in each entry of this.axes_.
2778 */
2779 Dygraph.prototype.computeYAxisRanges_ = function(extremes) {
2780 var isNullUndefinedOrNaN = function(num) {
2781 return isNaN(parseFloat(num));
2782 };
2783 var numAxes = this.attributes_.numAxes();
2784 var ypadCompat, span, series, ypad;
2785
2786 var p_axis;
2787
2788 // Compute extreme values, a span and tick marks for each axis.
2789 for (var i = 0; i < numAxes; i++) {
2790 var axis = this.axes_[i];
2791 var logscale = this.attributes_.getForAxis("logscale", i);
2792 var includeZero = this.attributes_.getForAxis("includeZero", i);
2793 var independentTicks = this.attributes_.getForAxis("independentTicks", i);
2794 series = this.attributes_.seriesForAxis(i);
2795
2796 // Add some padding. This supports two Y padding operation modes:
2797 //
2798 // - backwards compatible (yRangePad not set):
2799 // 10% padding for automatic Y ranges, but not for user-supplied
2800 // ranges, and move a close-to-zero edge to zero except if
2801 // avoidMinZero is set, since drawing at the edge results in
2802 // invisible lines. Unfortunately lines drawn at the edge of a
2803 // user-supplied range will still be invisible. If logscale is
2804 // set, add a variable amount of padding at the top but
2805 // none at the bottom.
2806 //
2807 // - new-style (yRangePad set by the user):
2808 // always add the specified Y padding.
2809 //
2810 ypadCompat = true;
2811 ypad = 0.1; // add 10%
2812 if (this.getNumericOption('yRangePad') !== null) {
2813 ypadCompat = false;
2814 // Convert pixel padding to ratio
2815 ypad = this.getNumericOption('yRangePad') / this.plotter_.area.h;
2816 }
2817
2818 if (series.length === 0) {
2819 // If no series are defined or visible then use a reasonable default
2820 axis.extremeRange = [0, 1];
2821 } else {
2822 // Calculate the extremes of extremes.
2823 var minY = Infinity; // extremes[series[0]][0];
2824 var maxY = -Infinity; // extremes[series[0]][1];
2825 var extremeMinY, extremeMaxY;
2826
2827 for (var j = 0; j < series.length; j++) {
2828 // this skips invisible series
2829 if (!extremes.hasOwnProperty(series[j])) continue;
2830
2831 // Only use valid extremes to stop null data series' from corrupting the scale.
2832 extremeMinY = extremes[series[j]][0];
2833 if (extremeMinY !== null) {
2834 minY = Math.min(extremeMinY, minY);
2835 }
2836 extremeMaxY = extremes[series[j]][1];
2837 if (extremeMaxY !== null) {
2838 maxY = Math.max(extremeMaxY, maxY);
2839 }
2840 }
2841
2842 // Include zero if requested by the user.
2843 if (includeZero && !logscale) {
2844 if (minY > 0) minY = 0;
2845 if (maxY < 0) maxY = 0;
2846 }
2847
2848 // Ensure we have a valid scale, otherwise default to [0, 1] for safety.
2849 if (minY == Infinity) minY = 0;
2850 if (maxY == -Infinity) maxY = 1;
2851
2852 span = maxY - minY;
2853 // special case: if we have no sense of scale, center on the sole value.
2854 if (span === 0) {
2855 if (maxY !== 0) {
2856 span = Math.abs(maxY);
2857 } else {
2858 // ... and if the sole value is zero, use range 0-1.
2859 maxY = 1;
2860 span = 1;
2861 }
2862 }
2863
2864 var maxAxisY, minAxisY;
2865 if (logscale) {
2866 if (ypadCompat) {
2867 maxAxisY = maxY + ypad * span;
2868 minAxisY = minY;
2869 } else {
2870 var logpad = Math.exp(Math.log(span) * ypad);
2871 maxAxisY = maxY * logpad;
2872 minAxisY = minY / logpad;
2873 }
2874 } else {
2875 maxAxisY = maxY + ypad * span;
2876 minAxisY = minY - ypad * span;
2877
2878 // Backwards-compatible behavior: Move the span to start or end at zero if it's
2879 // close to zero, but not if avoidMinZero is set.
2880 if (ypadCompat && !this.getBooleanOption("avoidMinZero")) {
2881 if (minAxisY < 0 && minY >= 0) minAxisY = 0;
2882 if (maxAxisY > 0 && maxY <= 0) maxAxisY = 0;
2883 }
2884 }
2885 axis.extremeRange = [minAxisY, maxAxisY];
2886 }
2887 if (axis.valueWindow) {
2888 // This is only set if the user has zoomed on the y-axis. It is never set
2889 // by a user. It takes precedence over axis.valueRange because, if you set
2890 // valueRange, you'd still expect to be able to pan.
2891 axis.computedValueRange = [axis.valueWindow[0], axis.valueWindow[1]];
2892 } else if (axis.valueRange) {
2893 // This is a user-set value range for this axis.
2894 var y0 = isNullUndefinedOrNaN(axis.valueRange[0]) ? axis.extremeRange[0] : axis.valueRange[0];
2895 var y1 = isNullUndefinedOrNaN(axis.valueRange[1]) ? axis.extremeRange[1] : axis.valueRange[1];
2896 if (!ypadCompat) {
2897 if (axis.logscale) {
2898 var logpad = Math.exp(Math.log(span) * ypad);
2899 y0 *= logpad;
2900 y1 /= logpad;
2901 } else {
2902 span = y1 - y0;
2903 y0 -= span * ypad;
2904 y1 += span * ypad;
2905 }
2906 }
2907 axis.computedValueRange = [y0, y1];
2908 } else {
2909 axis.computedValueRange = axis.extremeRange;
2910 }
2911
2912
2913 if (independentTicks) {
2914 axis.independentTicks = independentTicks;
2915 var opts = this.optionsViewForAxis_('y' + (i ? '2' : ''));
2916 var ticker = opts('ticker');
2917 axis.ticks = ticker(axis.computedValueRange[0],
2918 axis.computedValueRange[1],
2919 this.plotter_.area.h,
2920 opts,
2921 this);
2922 // Define the first independent axis as primary axis.
2923 if (!p_axis) p_axis = axis;
2924 }
2925 }
2926 if (p_axis === undefined) {
2927 throw ("Configuration Error: At least one axis has to have the \"independentTicks\" option activated.");
2928 }
2929 // Add ticks. By default, all axes inherit the tick positions of the
2930 // primary axis. However, if an axis is specifically marked as having
2931 // independent ticks, then that is permissible as well.
2932 for (var i = 0; i < numAxes; i++) {
2933 var axis = this.axes_[i];
2934
2935 if (!axis.independentTicks) {
2936 var opts = this.optionsViewForAxis_('y' + (i ? '2' : ''));
2937 var ticker = opts('ticker');
2938 var p_ticks = p_axis.ticks;
2939 var p_scale = p_axis.computedValueRange[1] - p_axis.computedValueRange[0];
2940 var scale = axis.computedValueRange[1] - axis.computedValueRange[0];
2941 var tick_values = [];
2942 for (var k = 0; k < p_ticks.length; k++) {
2943 var y_frac = (p_ticks[k].v - p_axis.computedValueRange[0]) / p_scale;
2944 var y_val = axis.computedValueRange[0] + y_frac * scale;
2945 tick_values.push(y_val);
2946 }
2947
2948 axis.ticks = ticker(axis.computedValueRange[0],
2949 axis.computedValueRange[1],
2950 this.plotter_.area.h,
2951 opts,
2952 this,
2953 tick_values);
2954 }
2955 }
2956 };
2957
2958 /**
2959 * Detects the type of the str (date or numeric) and sets the various
2960 * formatting attributes in this.attrs_ based on this type.
2961 * @param {string} str An x value.
2962 * @private
2963 */
2964 Dygraph.prototype.detectTypeFromString_ = function(str) {
2965 var isDate = false;
2966 var dashPos = str.indexOf('-'); // could be 2006-01-01 _or_ 1.0e-2
2967 if ((dashPos > 0 && (str[dashPos-1] != 'e' && str[dashPos-1] != 'E')) ||
2968 str.indexOf('/') >= 0 ||
2969 isNaN(parseFloat(str))) {
2970 isDate = true;
2971 } else if (str.length == 8 && str > '19700101' && str < '20371231') {
2972 // TODO(danvk): remove support for this format.
2973 isDate = true;
2974 }
2975
2976 this.setXAxisOptions_(isDate);
2977 };
2978
2979 Dygraph.prototype.setXAxisOptions_ = function(isDate) {
2980 if (isDate) {
2981 this.attrs_.xValueParser = Dygraph.dateParser;
2982 this.attrs_.axes.x.valueFormatter = Dygraph.dateValueFormatter;
2983 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
2984 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisLabelFormatter;
2985 } else {
2986 /** @private (shut up, jsdoc!) */
2987 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
2988 // TODO(danvk): use Dygraph.numberValueFormatter here?
2989 /** @private (shut up, jsdoc!) */
2990 this.attrs_.axes.x.valueFormatter = function(x) { return x; };
2991 this.attrs_.axes.x.ticker = Dygraph.numericTicks;
2992 this.attrs_.axes.x.axisLabelFormatter = this.attrs_.axes.x.valueFormatter;
2993 }
2994 };
2995
2996 /**
2997 * @private
2998 * Parses a string in a special csv format. We expect a csv file where each
2999 * line is a date point, and the first field in each line is the date string.
3000 * We also expect that all remaining fields represent series.
3001 * if the errorBars attribute is set, then interpret the fields as:
3002 * date, series1, stddev1, series2, stddev2, ...
3003 * @param {[Object]} data See above.
3004 *
3005 * @return [Object] An array with one entry for each row. These entries
3006 * are an array of cells in that row. The first entry is the parsed x-value for
3007 * the row. The second, third, etc. are the y-values. These can take on one of
3008 * three forms, depending on the CSV and constructor parameters:
3009 * 1. numeric value
3010 * 2. [ value, stddev ]
3011 * 3. [ low value, center value, high value ]
3012 */
3013 Dygraph.prototype.parseCSV_ = function(data) {
3014 var ret = [];
3015 var line_delimiter = Dygraph.detectLineDelimiter(data);
3016 var lines = data.split(line_delimiter || "\n");
3017 var vals, j;
3018
3019 // Use the default delimiter or fall back to a tab if that makes sense.
3020 var delim = this.getStringOption('delimiter');
3021 if (lines[0].indexOf(delim) == -1 && lines[0].indexOf('\t') >= 0) {
3022 delim = '\t';
3023 }
3024
3025 var start = 0;
3026 if (!('labels' in this.user_attrs_)) {
3027 // User hasn't explicitly set labels, so they're (presumably) in the CSV.
3028 start = 1;
3029 this.attrs_.labels = lines[0].split(delim); // NOTE: _not_ user_attrs_.
3030 this.attributes_.reparseSeries();
3031 }
3032 var line_no = 0;
3033
3034 var xParser;
3035 var defaultParserSet = false; // attempt to auto-detect x value type
3036 var expectedCols = this.attr_("labels").length;
3037 var outOfOrder = false;
3038 for (var i = start; i < lines.length; i++) {
3039 var line = lines[i];
3040 line_no = i;
3041 if (line.length === 0) continue; // skip blank lines
3042 if (line[0] == '#') continue; // skip comment lines
3043 var inFields = line.split(delim);
3044 if (inFields.length < 2) continue;
3045
3046 var fields = [];
3047 if (!defaultParserSet) {
3048 this.detectTypeFromString_(inFields[0]);
3049 xParser = this.getFunctionOption("xValueParser");
3050 defaultParserSet = true;
3051 }
3052 fields[0] = xParser(inFields[0], this);
3053
3054 // If fractions are expected, parse the numbers as "A/B"
3055 if (this.fractions_) {
3056 for (j = 1; j < inFields.length; j++) {
3057 // TODO(danvk): figure out an appropriate way to flag parse errors.
3058 vals = inFields[j].split("/");
3059 if (vals.length != 2) {
3060 console.error('Expected fractional "num/den" values in CSV data ' +
3061 "but found a value '" + inFields[j] + "' on line " +
3062 (1 + i) + " ('" + line + "') which is not of this form.");
3063 fields[j] = [0, 0];
3064 } else {
3065 fields[j] = [Dygraph.parseFloat_(vals[0], i, line),
3066 Dygraph.parseFloat_(vals[1], i, line)];
3067 }
3068 }
3069 } else if (this.getBooleanOption("errorBars")) {
3070 // If there are error bars, values are (value, stddev) pairs
3071 if (inFields.length % 2 != 1) {
3072 console.error('Expected alternating (value, stdev.) pairs in CSV data ' +
3073 'but line ' + (1 + i) + ' has an odd number of values (' +
3074 (inFields.length - 1) + "): '" + line + "'");
3075 }
3076 for (j = 1; j < inFields.length; j += 2) {
3077 fields[(j + 1) / 2] = [Dygraph.parseFloat_(inFields[j], i, line),
3078 Dygraph.parseFloat_(inFields[j + 1], i, line)];
3079 }
3080 } else if (this.getBooleanOption("customBars")) {
3081 // Bars are a low;center;high tuple
3082 for (j = 1; j < inFields.length; j++) {
3083 var val = inFields[j];
3084 if (/^ *$/.test(val)) {
3085 fields[j] = [null, null, null];
3086 } else {
3087 vals = val.split(";");
3088 if (vals.length == 3) {
3089 fields[j] = [ Dygraph.parseFloat_(vals[0], i, line),
3090 Dygraph.parseFloat_(vals[1], i, line),
3091 Dygraph.parseFloat_(vals[2], i, line) ];
3092 } else {
3093 console.warn('When using customBars, values must be either blank ' +
3094 'or "low;center;high" tuples (got "' + val +
3095 '" on line ' + (1+i));
3096 }
3097 }
3098 }
3099 } else {
3100 // Values are just numbers
3101 for (j = 1; j < inFields.length; j++) {
3102 fields[j] = Dygraph.parseFloat_(inFields[j], i, line);
3103 }
3104 }
3105 if (ret.length > 0 && fields[0] < ret[ret.length - 1][0]) {
3106 outOfOrder = true;
3107 }
3108
3109 if (fields.length != expectedCols) {
3110 console.error("Number of columns in line " + i + " (" + fields.length +
3111 ") does not agree with number of labels (" + expectedCols +
3112 ") " + line);
3113 }
3114
3115 // If the user specified the 'labels' option and none of the cells of the
3116 // first row parsed correctly, then they probably double-specified the
3117 // labels. We go with the values set in the option, discard this row and
3118 // log a warning to the JS console.
3119 if (i === 0 && this.attr_('labels')) {
3120 var all_null = true;
3121 for (j = 0; all_null && j < fields.length; j++) {
3122 if (fields[j]) all_null = false;
3123 }
3124 if (all_null) {
3125 console.warn("The dygraphs 'labels' option is set, but the first row " +
3126 "of CSV data ('" + line + "') appears to also contain " +
3127 "labels. Will drop the CSV labels and use the option " +
3128 "labels.");
3129 continue;
3130 }
3131 }
3132 ret.push(fields);
3133 }
3134
3135 if (outOfOrder) {
3136 console.warn("CSV is out of order; order it correctly to speed loading.");
3137 ret.sort(function(a,b) { return a[0] - b[0]; });
3138 }
3139
3140 return ret;
3141 };
3142
3143 /**
3144 * The user has provided their data as a pre-packaged JS array. If the x values
3145 * are numeric, this is the same as dygraphs' internal format. If the x values
3146 * are dates, we need to convert them from Date objects to ms since epoch.
3147 * @param {!Array} data
3148 * @return {Object} data with numeric x values.
3149 * @private
3150 */
3151 Dygraph.prototype.parseArray_ = function(data) {
3152 // Peek at the first x value to see if it's numeric.
3153 if (data.length === 0) {
3154 console.error("Can't plot empty data set");
3155 return null;
3156 }
3157 if (data[0].length === 0) {
3158 console.error("Data set cannot contain an empty row");
3159 return null;
3160 }
3161
3162 var i;
3163 if (this.attr_("labels") === null) {
3164 console.warn("Using default labels. Set labels explicitly via 'labels' " +
3165 "in the options parameter");
3166 this.attrs_.labels = [ "X" ];
3167 for (i = 1; i < data[0].length; i++) {
3168 this.attrs_.labels.push("Y" + i); // Not user_attrs_.
3169 }
3170 this.attributes_.reparseSeries();
3171 } else {
3172 var num_labels = this.attr_("labels");
3173 if (num_labels.length != data[0].length) {
3174 console.error("Mismatch between number of labels (" + num_labels + ")" +
3175 " and number of columns in array (" + data[0].length + ")");
3176 return null;
3177 }
3178 }
3179
3180 if (Dygraph.isDateLike(data[0][0])) {
3181 // Some intelligent defaults for a date x-axis.
3182 this.attrs_.axes.x.valueFormatter = Dygraph.dateValueFormatter;
3183 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
3184 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisLabelFormatter;
3185
3186 // Assume they're all dates.
3187 var parsedData = Dygraph.clone(data);
3188 for (i = 0; i < data.length; i++) {
3189 if (parsedData[i].length === 0) {
3190 console.error("Row " + (1 + i) + " of data is empty");
3191 return null;
3192 }
3193 if (parsedData[i][0] === null ||
3194 typeof(parsedData[i][0].getTime) != 'function' ||
3195 isNaN(parsedData[i][0].getTime())) {
3196 console.error("x value in row " + (1 + i) + " is not a Date");
3197 return null;
3198 }
3199 parsedData[i][0] = parsedData[i][0].getTime();
3200 }
3201 return parsedData;
3202 } else {
3203 // Some intelligent defaults for a numeric x-axis.
3204 /** @private (shut up, jsdoc!) */
3205 this.attrs_.axes.x.valueFormatter = function(x) { return x; };
3206 this.attrs_.axes.x.ticker = Dygraph.numericTicks;
3207 this.attrs_.axes.x.axisLabelFormatter = Dygraph.numberAxisLabelFormatter;
3208 return data;
3209 }
3210 };
3211
3212 /**
3213 * Parses a DataTable object from gviz.
3214 * The data is expected to have a first column that is either a date or a
3215 * number. All subsequent columns must be numbers. If there is a clear mismatch
3216 * between this.xValueParser_ and the type of the first column, it will be
3217 * fixed. Fills out rawData_.
3218 * @param {!google.visualization.DataTable} data See above.
3219 * @private
3220 */
3221 Dygraph.prototype.parseDataTable_ = function(data) {
3222 var shortTextForAnnotationNum = function(num) {
3223 // converts [0-9]+ [A-Z][a-z]*
3224 // example: 0=A, 1=B, 25=Z, 26=Aa, 27=Ab
3225 // and continues like.. Ba Bb .. Za .. Zz..Aaa...Zzz Aaaa Zzzz
3226 var shortText = String.fromCharCode(65 /* A */ + num % 26);
3227 num = Math.floor(num / 26);
3228 while ( num > 0 ) {
3229 shortText = String.fromCharCode(65 /* A */ + (num - 1) % 26 ) + shortText.toLowerCase();
3230 num = Math.floor((num - 1) / 26);
3231 }
3232 return shortText;
3233 };
3234
3235 var cols = data.getNumberOfColumns();
3236 var rows = data.getNumberOfRows();
3237
3238 var indepType = data.getColumnType(0);
3239 if (indepType == 'date' || indepType == 'datetime') {
3240 this.attrs_.xValueParser = Dygraph.dateParser;
3241 this.attrs_.axes.x.valueFormatter = Dygraph.dateValueFormatter;
3242 this.attrs_.axes.x.ticker = Dygraph.dateTicker;
3243 this.attrs_.axes.x.axisLabelFormatter = Dygraph.dateAxisLabelFormatter;
3244 } else if (indepType == 'number') {
3245 this.attrs_.xValueParser = function(x) { return parseFloat(x); };
3246 this.attrs_.axes.x.valueFormatter = function(x) { return x; };
3247 this.attrs_.axes.x.ticker = Dygraph.numericTicks;
3248 this.attrs_.axes.x.axisLabelFormatter = this.attrs_.axes.x.valueFormatter;
3249 } else {
3250 throw new Error(
3251 "only 'date', 'datetime' and 'number' types are supported " +
3252 "for column 1 of DataTable input (Got '" + indepType + "')");
3253 }
3254
3255 // Array of the column indices which contain data (and not annotations).
3256 var colIdx = [];
3257 var annotationCols = {}; // data index -> [annotation cols]
3258 var hasAnnotations = false;
3259 var i, j;
3260 for (i = 1; i < cols; i++) {
3261 var type = data.getColumnType(i);
3262 if (type == 'number') {
3263 colIdx.push(i);
3264 } else if (type == 'string' && this.getBooleanOption('displayAnnotations')) {
3265 // This is OK -- it's an annotation column.
3266 var dataIdx = colIdx[colIdx.length - 1];
3267 if (!annotationCols.hasOwnProperty(dataIdx)) {
3268 annotationCols[dataIdx] = [i];
3269 } else {
3270 annotationCols[dataIdx].push(i);
3271 }
3272 hasAnnotations = true;
3273 } else {
3274 throw new Error(
3275 "Only 'number' is supported as a dependent type with Gviz." +
3276 " 'string' is only supported if displayAnnotations is true");
3277 }
3278 }
3279
3280 // Read column labels
3281 // TODO(danvk): add support back for errorBars
3282 var labels = [data.getColumnLabel(0)];
3283 for (i = 0; i < colIdx.length; i++) {
3284 labels.push(data.getColumnLabel(colIdx[i]));
3285 if (this.getBooleanOption("errorBars")) i += 1;
3286 }
3287 this.attrs_.labels = labels;
3288 cols = labels.length;
3289
3290 var ret = [];
3291 var outOfOrder = false;
3292 var annotations = [];
3293 for (i = 0; i < rows; i++) {
3294 var row = [];
3295 if (typeof(data.getValue(i, 0)) === 'undefined' ||
3296 data.getValue(i, 0) === null) {
3297 console.warn("Ignoring row " + i +
3298 " of DataTable because of undefined or null first column.");
3299 continue;
3300 }
3301
3302 if (indepType == 'date' || indepType == 'datetime') {
3303 row.push(data.getValue(i, 0).getTime());
3304 } else {
3305 row.push(data.getValue(i, 0));
3306 }
3307 if (!this.getBooleanOption("errorBars")) {
3308 for (j = 0; j < colIdx.length; j++) {
3309 var col = colIdx[j];
3310 row.push(data.getValue(i, col));
3311 if (hasAnnotations &&
3312 annotationCols.hasOwnProperty(col) &&
3313 data.getValue(i, annotationCols[col][0]) !== null) {
3314 var ann = {};
3315 ann.series = data.getColumnLabel(col);
3316 ann.xval = row[0];
3317 ann.shortText = shortTextForAnnotationNum(annotations.length);
3318 ann.text = '';
3319 for (var k = 0; k < annotationCols[col].length; k++) {
3320 if (k) ann.text += "\n";
3321 ann.text += data.getValue(i, annotationCols[col][k]);
3322 }
3323 annotations.push(ann);
3324 }
3325 }
3326
3327 // Strip out infinities, which give dygraphs problems later on.
3328 for (j = 0; j < row.length; j++) {
3329 if (!isFinite(row[j])) row[j] = null;
3330 }
3331 } else {
3332 for (j = 0; j < cols - 1; j++) {
3333 row.push([ data.getValue(i, 1 + 2 * j), data.getValue(i, 2 + 2 * j) ]);
3334 }
3335 }
3336 if (ret.length > 0 && row[0] < ret[ret.length - 1][0]) {
3337 outOfOrder = true;
3338 }
3339 ret.push(row);
3340 }
3341
3342 if (outOfOrder) {
3343 console.warn("DataTable is out of order; order it correctly to speed loading.");
3344 ret.sort(function(a,b) { return a[0] - b[0]; });
3345 }
3346 this.rawData_ = ret;
3347
3348 if (annotations.length > 0) {
3349 this.setAnnotations(annotations, true);
3350 }
3351 this.attributes_.reparseSeries();
3352 };
3353
3354 /**
3355 * Signals to plugins that the chart data has updated.
3356 * This happens after the data has updated but before the chart has redrawn.
3357 */
3358 Dygraph.prototype.cascadeDataDidUpdateEvent_ = function() {
3359 // TODO(danvk): there are some issues checking xAxisRange() and using
3360 // toDomCoords from handlers of this event. The visible range should be set
3361 // when the chart is drawn, not derived from the data.
3362 this.cascadeEvents_('dataDidUpdate', {});
3363 };
3364
3365 /**
3366 * Get the CSV data. If it's in a function, call that function. If it's in a
3367 * file, do an XMLHttpRequest to get it.
3368 * @private
3369 */
3370 Dygraph.prototype.start_ = function() {
3371 var data = this.file_;
3372
3373 // Functions can return references of all other types.
3374 if (typeof data == 'function') {
3375 data = data();
3376 }
3377
3378 if (Dygraph.isArrayLike(data)) {
3379 this.rawData_ = this.parseArray_(data);
3380 this.cascadeDataDidUpdateEvent_();
3381 this.predraw_();
3382 } else if (typeof data == 'object' &&
3383 typeof data.getColumnRange == 'function') {
3384 // must be a DataTable from gviz.
3385 this.parseDataTable_(data);
3386 this.cascadeDataDidUpdateEvent_();
3387 this.predraw_();
3388 } else if (typeof data == 'string') {
3389 // Heuristic: a newline means it's CSV data. Otherwise it's an URL.
3390 var line_delimiter = Dygraph.detectLineDelimiter(data);
3391 if (line_delimiter) {
3392 this.loadedEvent_(data);
3393 } else {
3394 // REMOVE_FOR_IE
3395 var req;
3396 if (window.XMLHttpRequest) {
3397 // Firefox, Opera, IE7, and other browsers will use the native object
3398 req = new XMLHttpRequest();
3399 } else {
3400 // IE 5 and 6 will use the ActiveX control
3401 req = new ActiveXObject("Microsoft.XMLHTTP");
3402 }
3403
3404 var caller = this;
3405 req.onreadystatechange = function () {
3406 if (req.readyState == 4) {
3407 if (req.status === 200 || // Normal http
3408 req.status === 0) { // Chrome w/ --allow-file-access-from-files
3409 caller.loadedEvent_(req.responseText);
3410 }
3411 }
3412 };
3413
3414 req.open("GET", data, true);
3415 req.send(null);
3416 }
3417 } else {
3418 console.error("Unknown data format: " + (typeof data));
3419 }
3420 };
3421
3422 /**
3423 * Changes various properties of the graph. These can include:
3424 * <ul>
3425 * <li>file: changes the source data for the graph</li>
3426 * <li>errorBars: changes whether the data contains stddev</li>
3427 * </ul>
3428 *
3429 * There's a huge variety of options that can be passed to this method. For a
3430 * full list, see http://dygraphs.com/options.html.
3431 *
3432 * @param {Object} input_attrs The new properties and values
3433 * @param {boolean} block_redraw Usually the chart is redrawn after every
3434 * call to updateOptions(). If you know better, you can pass true to
3435 * explicitly block the redraw. This can be useful for chaining
3436 * updateOptions() calls, avoiding the occasional infinite loop and
3437 * preventing redraws when it's not necessary (e.g. when updating a
3438 * callback).
3439 */
3440 Dygraph.prototype.updateOptions = function(input_attrs, block_redraw) {
3441 if (typeof(block_redraw) == 'undefined') block_redraw = false;
3442
3443 // copyUserAttrs_ drops the "file" parameter as a convenience to us.
3444 var file = input_attrs.file;
3445 var attrs = Dygraph.copyUserAttrs_(input_attrs);
3446
3447 // TODO(danvk): this is a mess. Move these options into attr_.
3448 if ('rollPeriod' in attrs) {
3449 this.rollPeriod_ = attrs.rollPeriod;
3450 }
3451 if ('dateWindow' in attrs) {
3452 this.dateWindow_ = attrs.dateWindow;
3453 if (!('isZoomedIgnoreProgrammaticZoom' in attrs)) {
3454 this.zoomed_x_ = (attrs.dateWindow !== null);
3455 }
3456 }
3457 if ('valueRange' in attrs && !('isZoomedIgnoreProgrammaticZoom' in attrs)) {
3458 this.zoomed_y_ = (attrs.valueRange !== null);
3459 }
3460
3461 // TODO(danvk): validate per-series options.
3462 // Supported:
3463 // strokeWidth
3464 // pointSize
3465 // drawPoints
3466 // highlightCircleSize
3467
3468 // Check if this set options will require new points.
3469 var requiresNewPoints = Dygraph.isPixelChangingOptionList(this.attr_("labels"), attrs);
3470
3471 Dygraph.updateDeep(this.user_attrs_, attrs);
3472
3473 this.attributes_.reparseSeries();
3474
3475 if (file) {
3476 // This event indicates that the data is about to change, but hasn't yet.
3477 // TODO(danvk): support cancelation of the update via this event.
3478 this.cascadeEvents_('dataWillUpdate', {});
3479
3480 this.file_ = file;
3481 if (!block_redraw) this.start_();
3482 } else {
3483 if (!block_redraw) {
3484 if (requiresNewPoints) {
3485 this.predraw_();
3486 } else {
3487 this.renderGraph_(false);
3488 }
3489 }
3490 }
3491 };
3492
3493 /**
3494 * Make a copy of input attributes, removing file as a convenience.
3495 */
3496 Dygraph.copyUserAttrs_ = function(attrs) {
3497 var my_attrs = {};
3498 for (var k in attrs) {
3499 if (!attrs.hasOwnProperty(k)) continue;
3500 if (k == 'file') continue;
3501 if (attrs.hasOwnProperty(k)) my_attrs[k] = attrs[k];
3502 }
3503 return my_attrs;
3504 };
3505
3506 /**
3507 * Resizes the dygraph. If no parameters are specified, resizes to fill the
3508 * containing div (which has presumably changed size since the dygraph was
3509 * instantiated. If the width/height are specified, the div will be resized.
3510 *
3511 * This is far more efficient than destroying and re-instantiating a
3512 * Dygraph, since it doesn't have to reparse the underlying data.
3513 *
3514 * @param {number} width Width (in pixels)
3515 * @param {number} height Height (in pixels)
3516 */
3517 Dygraph.prototype.resize = function(width, height) {
3518 if (this.resize_lock) {
3519 return;
3520 }
3521 this.resize_lock = true;
3522
3523 if ((width === null) != (height === null)) {
3524 console.warn("Dygraph.resize() should be called with zero parameters or " +
3525 "two non-NULL parameters. Pretending it was zero.");
3526 width = height = null;
3527 }
3528
3529 var old_width = this.width_;
3530 var old_height = this.height_;
3531
3532 if (width) {
3533 this.maindiv_.style.width = width + "px";
3534 this.maindiv_.style.height = height + "px";
3535 this.width_ = width;
3536 this.height_ = height;
3537 } else {
3538 this.width_ = this.maindiv_.clientWidth;
3539 this.height_ = this.maindiv_.clientHeight;
3540 }
3541
3542 if (old_width != this.width_ || old_height != this.height_) {
3543 // Resizing a canvas erases it, even when the size doesn't change, so
3544 // any resize needs to be followed by a redraw.
3545 this.resizeElements_();
3546 this.predraw_();
3547 }
3548
3549 this.resize_lock = false;
3550 };
3551
3552 /**
3553 * Adjusts the number of points in the rolling average. Updates the graph to
3554 * reflect the new averaging period.
3555 * @param {number} length Number of points over which to average the data.
3556 */
3557 Dygraph.prototype.adjustRoll = function(length) {
3558 this.rollPeriod_ = length;
3559 this.predraw_();
3560 };
3561
3562 /**
3563 * Returns a boolean array of visibility statuses.
3564 */
3565 Dygraph.prototype.visibility = function() {
3566 // Do lazy-initialization, so that this happens after we know the number of
3567 // data series.
3568 if (!this.getOption("visibility")) {
3569 this.attrs_.visibility = [];
3570 }
3571 // TODO(danvk): it looks like this could go into an infinite loop w/ user_attrs.
3572 while (this.getOption("visibility").length < this.numColumns() - 1) {
3573 this.attrs_.visibility.push(true);
3574 }
3575 return this.getOption("visibility");
3576 };
3577
3578 /**
3579 * Changes the visibility of one or more series.
3580 *
3581 * @param {number|number[]} num the series index or an array of series indices
3582 * @param {boolean} value true or false, identifying the visibility.
3583 */
3584 Dygraph.prototype.setVisibility = function(num, value) {
3585 var x = this.visibility();
3586
3587 if (num.constructor !== Array) num = [num];
3588
3589 for (var i = 0; i < num.length; i++) {
3590 if (num[i] < 0 || num[i] >= x.length) {
3591 console.warn("invalid series number in setVisibility: " + num[i]);
3592 } else {
3593 x[num[i]] = value;
3594 }
3595 }
3596
3597 this.predraw_();
3598 };
3599
3600 /**
3601 * How large of an area will the dygraph render itself in?
3602 * This is used for testing.
3603 * @return A {width: w, height: h} object.
3604 * @private
3605 */
3606 Dygraph.prototype.size = function() {
3607 return { width: this.width_, height: this.height_ };
3608 };
3609
3610 /**
3611 * Update the list of annotations and redraw the chart.
3612 * See dygraphs.com/annotations.html for more info on how to use annotations.
3613 * @param ann {Array} An array of annotation objects.
3614 * @param suppressDraw {Boolean} Set to "true" to block chart redraw (optional).
3615 */
3616 Dygraph.prototype.setAnnotations = function(ann, suppressDraw) {
3617 // Only add the annotation CSS rule once we know it will be used.
3618 Dygraph.addAnnotationRule();
3619 this.annotations_ = ann;
3620 if (!this.layout_) {
3621 console.warn("Tried to setAnnotations before dygraph was ready. " +
3622 "Try setting them in a ready() block. See " +
3623 "dygraphs.com/tests/annotation.html");
3624 return;
3625 }
3626
3627 this.layout_.setAnnotations(this.annotations_);
3628 if (!suppressDraw) {
3629 this.predraw_();
3630 }
3631 };
3632
3633 /**
3634 * Return the list of annotations.
3635 */
3636 Dygraph.prototype.annotations = function() {
3637 return this.annotations_;
3638 };
3639
3640 /**
3641 * Get the list of label names for this graph. The first column is the
3642 * x-axis, so the data series names start at index 1.
3643 *
3644 * Returns null when labels have not yet been defined.
3645 */
3646 Dygraph.prototype.getLabels = function() {
3647 var labels = this.attr_("labels");
3648 return labels ? labels.slice() : null;
3649 };
3650
3651 /**
3652 * Get the index of a series (column) given its name. The first column is the
3653 * x-axis, so the data series start with index 1.
3654 */
3655 Dygraph.prototype.indexFromSetName = function(name) {
3656 return this.setIndexByName_[name];
3657 };
3658
3659 /**
3660 * Find the row number corresponding to the given x-value.
3661 * Returns null if there is no such x-value in the data.
3662 * If there are multiple rows with the same x-value, this will return the
3663 * first one.
3664 * @param {number} xVal The x-value to look for (e.g. millis since epoch).
3665 * @return {?number} The row number, which you can pass to getValue(), or null.
3666 */
3667 Dygraph.prototype.getRowForX = function(xVal) {
3668 var low = 0,
3669 high = this.numRows() - 1;
3670
3671 while (low <= high) {
3672 var idx = (high + low) >> 1;
3673 var x = this.getValue(idx, 0);
3674 if (x < xVal) {
3675 low = idx + 1;
3676 } else if (x > xVal) {
3677 high = idx - 1;
3678 } else if (low != idx) { // equal, but there may be an earlier match.
3679 high = idx;
3680 } else {
3681 return idx;
3682 }
3683 }
3684
3685 return null;
3686 };
3687
3688 /**
3689 * Trigger a callback when the dygraph has drawn itself and is ready to be
3690 * manipulated. This is primarily useful when dygraphs has to do an XHR for the
3691 * data (i.e. a URL is passed as the data source) and the chart is drawn
3692 * asynchronously. If the chart has already drawn, the callback will fire
3693 * immediately.
3694 *
3695 * This is a good place to call setAnnotation().
3696 *
3697 * @param {function(!Dygraph)} callback The callback to trigger when the chart
3698 * is ready.
3699 */
3700 Dygraph.prototype.ready = function(callback) {
3701 if (this.is_initial_draw_) {
3702 this.readyFns_.push(callback);
3703 } else {
3704 callback.call(this, this);
3705 }
3706 };
3707
3708 /**
3709 * @private
3710 * Adds a default style for the annotation CSS classes to the document. This is
3711 * only executed when annotations are actually used. It is designed to only be
3712 * called once -- all calls after the first will return immediately.
3713 */
3714 Dygraph.addAnnotationRule = function() {
3715 // TODO(danvk): move this function into plugins/annotations.js?
3716 if (Dygraph.addedAnnotationCSS) return;
3717
3718 var rule = "border: 1px solid black; " +
3719 "background-color: white; " +
3720 "text-align: center;";
3721
3722 var styleSheetElement = document.createElement("style");
3723 styleSheetElement.type = "text/css";
3724 document.getElementsByTagName("head")[0].appendChild(styleSheetElement);
3725
3726 // Find the first style sheet that we can access.
3727 // We may not add a rule to a style sheet from another domain for security
3728 // reasons. This sometimes comes up when using gviz, since the Google gviz JS
3729 // adds its own style sheets from google.com.
3730 for (var i = 0; i < document.styleSheets.length; i++) {
3731 if (document.styleSheets[i].disabled) continue;
3732 var mysheet = document.styleSheets[i];
3733 try {
3734 if (mysheet.insertRule) { // Firefox
3735 var idx = mysheet.cssRules ? mysheet.cssRules.length : 0;
3736 mysheet.insertRule(".dygraphDefaultAnnotation { " + rule + " }", idx);
3737 } else if (mysheet.addRule) { // IE
3738 mysheet.addRule(".dygraphDefaultAnnotation", rule);
3739 }
3740 Dygraph.addedAnnotationCSS = true;
3741 return;
3742 } catch(err) {
3743 // Was likely a security exception.
3744 }
3745 }
3746
3747 console.warn("Unable to add default annotation CSS rule; display may be off.");
3748 };
3749
3750 if (typeof exports === "object" && typeof module !== "undefined") {
3751 module.exports = Dygraph;
3752 }
3753
3754 return Dygraph;
3755
3756 })();