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