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