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