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