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