Merge pull request #525 from danvk/this-formatter
[dygraphs.git] / dygraph-options.js
1 /**
2 * @license
3 * Copyright 2011 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6
7 /**
8 * @fileoverview DygraphOptions is responsible for parsing and returning information about options.
9 *
10 * Still tightly coupled to Dygraphs, we could remove some of that, you know.
11 */
12
13 var DygraphOptions = (function() {
14 /*jshint strict:false */
15
16 // For "production" code, this gets set to false by uglifyjs.
17 // Need to define it outside of "use strict", hence the nested IIFEs.
18 if (typeof(DEBUG) === 'undefined') DEBUG=true;
19
20 return (function() {
21
22 // TODO: remove this jshint directive & fix the warnings.
23 /*jshint sub:true */
24 /*global Dygraph:false */
25 "use strict";
26
27 /*
28 * Interesting member variables: (REMOVING THIS LIST AS I CLOSURIZE)
29 * global_ - global attributes (common among all graphs, AIUI)
30 * user - attributes set by the user
31 * series_ - { seriesName -> { idx, yAxis, options }}
32 */
33
34 /**
35 * This parses attributes into an object that can be easily queried.
36 *
37 * It doesn't necessarily mean that all options are available, specifically
38 * if labels are not yet available, since those drive details of the per-series
39 * and per-axis options.
40 *
41 * @param {Dygraph} dygraph The chart to which these options belong.
42 * @constructor
43 */
44 var DygraphOptions = function(dygraph) {
45 /**
46 * The dygraph.
47 * @type {!Dygraph}
48 */
49 this.dygraph_ = dygraph;
50
51 /**
52 * Array of axis index to { series : [ series names ] , options : { axis-specific options. }
53 * @type {Array.<{series : Array.<string>, options : Object}>} @private
54 */
55 this.yAxes_ = [];
56
57 /**
58 * Contains x-axis specific options, which are stored in the options key.
59 * This matches the yAxes_ object structure (by being a dictionary with an
60 * options element) allowing for shared code.
61 * @type {options: Object} @private
62 */
63 this.xAxis_ = {};
64 this.series_ = {};
65
66 // Once these two objects are initialized, you can call get();
67 this.global_ = this.dygraph_.attrs_;
68 this.user_ = this.dygraph_.user_attrs_ || {};
69
70 /**
71 * A list of series in columnar order.
72 * @type {Array.<string>}
73 */
74 this.labels_ = [];
75
76 this.highlightSeries_ = this.get("highlightSeriesOpts") || {};
77 this.reparseSeries();
78 };
79
80 /**
81 * Not optimal, but does the trick when you're only using two axes.
82 * If we move to more axes, this can just become a function.
83 *
84 * @type {Object.<number>}
85 * @private
86 */
87 DygraphOptions.AXIS_STRING_MAPPINGS_ = {
88 'y' : 0,
89 'Y' : 0,
90 'y1' : 0,
91 'Y1' : 0,
92 'y2' : 1,
93 'Y2' : 1
94 };
95
96 /**
97 * @param {string|number} axis
98 * @private
99 */
100 DygraphOptions.axisToIndex_ = function(axis) {
101 if (typeof(axis) == "string") {
102 if (DygraphOptions.AXIS_STRING_MAPPINGS_.hasOwnProperty(axis)) {
103 return DygraphOptions.AXIS_STRING_MAPPINGS_[axis];
104 }
105 throw "Unknown axis : " + axis;
106 }
107 if (typeof(axis) == "number") {
108 if (axis === 0 || axis === 1) {
109 return axis;
110 }
111 throw "Dygraphs only supports two y-axes, indexed from 0-1.";
112 }
113 if (axis) {
114 throw "Unknown axis : " + axis;
115 }
116 // No axis specification means axis 0.
117 return 0;
118 };
119
120 /**
121 * Reparses options that are all related to series. This typically occurs when
122 * options are either updated, or source data has been made available.
123 *
124 * TODO(konigsberg): The method name is kind of weak; fix.
125 */
126 DygraphOptions.prototype.reparseSeries = function() {
127 var labels = this.get("labels");
128 if (!labels) {
129 return; // -- can't do more for now, will parse after getting the labels.
130 }
131
132 this.labels_ = labels.slice(1);
133
134 this.yAxes_ = [ { series : [], options : {}} ]; // Always one axis at least.
135 this.xAxis_ = { options : {} };
136 this.series_ = {};
137
138 // Series are specified in the series element:
139 //
140 // {
141 // labels: [ "X", "foo", "bar" ],
142 // pointSize: 3,
143 // series : {
144 // foo : {}, // options for foo
145 // bar : {} // options for bar
146 // }
147 // }
148 //
149 // So, if series is found, it's expected to contain per-series data, otherwise set a
150 // default.
151 var seriesDict = this.user_.series || {};
152 for (var idx = 0; idx < this.labels_.length; idx++) {
153 var seriesName = this.labels_[idx];
154 var optionsForSeries = seriesDict[seriesName] || {};
155 var yAxis = DygraphOptions.axisToIndex_(optionsForSeries["axis"]);
156
157 this.series_[seriesName] = {
158 idx: idx,
159 yAxis: yAxis,
160 options : optionsForSeries };
161
162 if (!this.yAxes_[yAxis]) {
163 this.yAxes_[yAxis] = { series : [ seriesName ], options : {} };
164 } else {
165 this.yAxes_[yAxis].series.push(seriesName);
166 }
167 }
168
169 var axis_opts = this.user_["axes"] || {};
170 Dygraph.update(this.yAxes_[0].options, axis_opts["y"] || {});
171 if (this.yAxes_.length > 1) {
172 Dygraph.update(this.yAxes_[1].options, axis_opts["y2"] || {});
173 }
174 Dygraph.update(this.xAxis_.options, axis_opts["x"] || {});
175
176 if (DEBUG) this.validateOptions_();
177 };
178
179 /**
180 * Get a global value.
181 *
182 * @param {string} name the name of the option.
183 */
184 DygraphOptions.prototype.get = function(name) {
185 var result = this.getGlobalUser_(name);
186 if (result !== null) {
187 return result;
188 }
189 return this.getGlobalDefault_(name);
190 };
191
192 DygraphOptions.prototype.getGlobalUser_ = function(name) {
193 if (this.user_.hasOwnProperty(name)) {
194 return this.user_[name];
195 }
196 return null;
197 };
198
199 DygraphOptions.prototype.getGlobalDefault_ = function(name) {
200 if (this.global_.hasOwnProperty(name)) {
201 return this.global_[name];
202 }
203 if (Dygraph.DEFAULT_ATTRS.hasOwnProperty(name)) {
204 return Dygraph.DEFAULT_ATTRS[name];
205 }
206 return null;
207 };
208
209 /**
210 * Get a value for a specific axis. If there is no specific value for the axis,
211 * the global value is returned.
212 *
213 * @param {string} name the name of the option.
214 * @param {string|number} axis the axis to search. Can be the string representation
215 * ("y", "y2") or the axis number (0, 1).
216 */
217 DygraphOptions.prototype.getForAxis = function(name, axis) {
218 var axisIdx;
219 var axisString;
220
221 // Since axis can be a number or a string, straighten everything out here.
222 if (typeof(axis) == 'number') {
223 axisIdx = axis;
224 axisString = axisIdx === 0 ? "y" : "y2";
225 } else {
226 if (axis == "y1") { axis = "y"; } // Standardize on 'y'. Is this bad? I think so.
227 if (axis == "y") {
228 axisIdx = 0;
229 } else if (axis == "y2") {
230 axisIdx = 1;
231 } else if (axis == "x") {
232 axisIdx = -1; // simply a placeholder for below.
233 } else {
234 throw "Unknown axis " + axis;
235 }
236 axisString = axis;
237 }
238
239 var userAxis = (axisIdx == -1) ? this.xAxis_ : this.yAxes_[axisIdx];
240
241 // Search the user-specified axis option first.
242 if (userAxis) { // This condition could be removed if we always set up this.yAxes_ for y2.
243 var axisOptions = userAxis.options;
244 if (axisOptions.hasOwnProperty(name)) {
245 return axisOptions[name];
246 }
247 }
248
249 // User-specified global options second.
250 // But, hack, ignore globally-specified 'logscale' for 'x' axis declaration.
251 if (!(axis === 'x' && name === 'logscale')) {
252 var result = this.getGlobalUser_(name);
253 if (result !== null) {
254 return result;
255 }
256 }
257 // Default axis options third.
258 var defaultAxisOptions = Dygraph.DEFAULT_ATTRS.axes[axisString];
259 if (defaultAxisOptions.hasOwnProperty(name)) {
260 return defaultAxisOptions[name];
261 }
262
263 // Default global options last.
264 return this.getGlobalDefault_(name);
265 };
266
267 /**
268 * Get a value for a specific series. If there is no specific value for the series,
269 * the value for the axis is returned (and afterwards, the global value.)
270 *
271 * @param {string} name the name of the option.
272 * @param {string} series the series to search.
273 */
274 DygraphOptions.prototype.getForSeries = function(name, series) {
275 // Honors indexes as series.
276 if (series === this.dygraph_.getHighlightSeries()) {
277 if (this.highlightSeries_.hasOwnProperty(name)) {
278 return this.highlightSeries_[name];
279 }
280 }
281
282 if (!this.series_.hasOwnProperty(series)) {
283 throw "Unknown series: " + series;
284 }
285
286 var seriesObj = this.series_[series];
287 var seriesOptions = seriesObj["options"];
288 if (seriesOptions.hasOwnProperty(name)) {
289 return seriesOptions[name];
290 }
291
292 return this.getForAxis(name, seriesObj["yAxis"]);
293 };
294
295 /**
296 * Returns the number of y-axes on the chart.
297 * @return {number} the number of axes.
298 */
299 DygraphOptions.prototype.numAxes = function() {
300 return this.yAxes_.length;
301 };
302
303 /**
304 * Return the y-axis for a given series, specified by name.
305 */
306 DygraphOptions.prototype.axisForSeries = function(series) {
307 return this.series_[series].yAxis;
308 };
309
310 /**
311 * Returns the options for the specified axis.
312 */
313 // TODO(konigsberg): this is y-axis specific. Support the x axis.
314 DygraphOptions.prototype.axisOptions = function(yAxis) {
315 return this.yAxes_[yAxis].options;
316 };
317
318 /**
319 * Return the series associated with an axis.
320 */
321 DygraphOptions.prototype.seriesForAxis = function(yAxis) {
322 return this.yAxes_[yAxis].series;
323 };
324
325 /**
326 * Return the list of all series, in their columnar order.
327 */
328 DygraphOptions.prototype.seriesNames = function() {
329 return this.labels_;
330 };
331
332 if (DEBUG) {
333
334 /**
335 * Validate all options.
336 * This requires Dygraph.OPTIONS_REFERENCE, which is only available in debug builds.
337 * @private
338 */
339 DygraphOptions.prototype.validateOptions_ = function() {
340 if (typeof Dygraph.OPTIONS_REFERENCE === 'undefined') {
341 throw 'Called validateOptions_ in prod build.';
342 }
343
344 var that = this;
345 var validateOption = function(optionName) {
346 if (!Dygraph.OPTIONS_REFERENCE[optionName]) {
347 that.warnInvalidOption_(optionName);
348 }
349 };
350
351 var optionsDicts = [this.xAxis_.options,
352 this.yAxes_[0].options,
353 this.yAxes_[1] && this.yAxes_[1].options,
354 this.global_,
355 this.user_,
356 this.highlightSeries_];
357 var names = this.seriesNames();
358 for (var i = 0; i < names.length; i++) {
359 var name = names[i];
360 if (this.series_.hasOwnProperty(name)) {
361 optionsDicts.push(this.series_[name].options);
362 }
363 }
364 for (var i = 0; i < optionsDicts.length; i++) {
365 var dict = optionsDicts[i];
366 if (!dict) continue;
367 for (var optionName in dict) {
368 if (dict.hasOwnProperty(optionName)) {
369 validateOption(optionName);
370 }
371 }
372 }
373 };
374
375 var WARNINGS = {}; // Only show any particular warning once.
376
377 /**
378 * Logs a warning about invalid options.
379 * TODO: make this throw for testing
380 * @private
381 */
382 DygraphOptions.prototype.warnInvalidOption_ = function(optionName) {
383 if (!WARNINGS[optionName]) {
384 WARNINGS[optionName] = true;
385 var isSeries = (this.labels_.indexOf(optionName) >= 0);
386 if (isSeries) {
387 console.warn('Use new-style per-series options (saw ' + optionName + ' as top-level options key). See http://bit.ly/1tceaJs');
388 } else {
389 console.warn('Unknown option ' + optionName + ' (full list of options at dygraphs.com/options.html');
390 throw "invalid option " + optionName;
391 }
392 }
393 };
394
395 // Reset list of previously-shown warnings. Used for testing.
396 DygraphOptions.resetWarnings_ = function() {
397 WARNINGS = {};
398 };
399
400 }
401
402 return DygraphOptions;
403
404 })();
405 })();