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