Add JSHint and make dygraphs pass its checks.
[dygraphs.git] / dygraph-layout.js
CommitLineData
88e95c46
DV
1/**
2 * @license
3 * Copyright 2011 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
74a5af31
DV
6
7/**
8 * @fileoverview Based on PlotKitLayout, but modified to meet the needs of
9 * dygraphs.
10 */
11
758a629f
DV
12/*jshint globalstrict: true */
13/*global Dygraph:false */
c0f54d4f
DV
14"use strict";
15
74a5af31
DV
16/**
17 * Creates a new DygraphLayout object.
18 *
19 * This class contains all the data to be charted.
20 * It uses data coordinates, but also records the chart range (in data
21 * coordinates) and hence is able to calculate percentage positions ('In this
22 * view, Point A lies 25% down the x-axis.')
23 *
24 * Two things that it does not do are:
25 * 1. Record pixel coordinates for anything.
26 * 2. (oddly) determine anything about the layout of chart elements.
27 *
28 * The naming is a vestige of Dygraph's original PlotKit roots.
29 *
30 * @constructor
31 */
c0f54d4f 32var DygraphLayout = function(dygraph) {
74a5af31 33 this.dygraph_ = dygraph;
758a629f
DV
34 this.datasets = [];
35 this.annotations = [];
74a5af31
DV
36 this.yAxes_ = null;
37
38 // TODO(danvk): it's odd that xTicks_ and yTicks_ are inputs, but xticks and
39 // yticks are outputs. Clean this up.
40 this.xTicks_ = null;
41 this.yTicks_ = null;
42};
43
44DygraphLayout.prototype.attr_ = function(name) {
45 return this.dygraph_.attr_(name);
46};
47
48DygraphLayout.prototype.addDataset = function(setname, set_xy) {
49 this.datasets[setname] = set_xy;
50};
51
70be5ed1
AV
52DygraphLayout.prototype.getPlotArea = function() {
53 return this.computePlotArea_();
758a629f 54};
70be5ed1 55
ccd9d7c2
PF
56// Compute the box which the chart should be drawn in. This is the canvas's
57// box, less space needed for axis and chart labels.
58DygraphLayout.prototype.computePlotArea_ = function() {
59 var area = {
60 // TODO(danvk): per-axis setting.
61 x: 0,
62 y: 0
63 };
64 if (this.attr_('drawYAxis')) {
65 area.x = this.attr_('yAxisLabelWidth') + 2 * this.attr_('axisTickSize');
66 }
67
68 area.w = this.dygraph_.width_ - area.x - this.attr_('rightGap');
69 area.h = this.dygraph_.height_;
70 if (this.attr_('drawXAxis')) {
71 if (this.attr_('xAxisHeight')) {
72 area.h -= this.attr_('xAxisHeight');
73 } else {
74 area.h -= this.attr_('axisLabelFontSize') + 2 * this.attr_('axisTickSize');
75 }
76 }
77
78 // Shrink the drawing area to accomodate additional y-axes.
79 if (this.dygraph_.numAxes() == 2) {
80 // TODO(danvk): per-axis setting.
81 area.w -= (this.attr_('yAxisLabelWidth') + 2 * this.attr_('axisTickSize'));
82 } else if (this.dygraph_.numAxes() > 2) {
83 this.dygraph_.error("Only two y-axes are supported at this time. (Trying " +
84 "to use " + this.dygraph_.numAxes() + ")");
85 }
86
87 // Add space for chart labels: title, xlabel and ylabel.
88 if (this.attr_('title')) {
89 area.h -= this.attr_('titleHeight');
90 area.y += this.attr_('titleHeight');
91 }
92 if (this.attr_('xlabel')) {
93 area.h -= this.attr_('xLabelHeight');
94 }
95 if (this.attr_('ylabel')) {
96 // It would make sense to shift the chart here to make room for the y-axis
97 // label, but the default yAxisLabelWidth is large enough that this results
98 // in overly-padded charts. The y-axis label should fit fine. If it
99 // doesn't, the yAxisLabelWidth option can be increased.
100 }
101
102 // Add space for range selector, if needed.
103 if (this.attr_('showRangeSelector')) {
104 area.h -= this.attr_('rangeSelectorHeight') + 4;
105 }
106
107 return area;
108};
109
74a5af31
DV
110DygraphLayout.prototype.setAnnotations = function(ann) {
111 // The Dygraph object's annotations aren't parsed. We parse them here and
112 // save a copy. If there is no parser, then the user must be using raw format.
113 this.annotations = [];
114 var parse = this.attr_('xValueParser') || function(x) { return x; };
115 for (var i = 0; i < ann.length; i++) {
116 var a = {};
117 if (!ann[i].xval && !ann[i].x) {
118 this.dygraph_.error("Annotations must have an 'x' property");
119 return;
120 }
121 if (ann[i].icon &&
122 !(ann[i].hasOwnProperty('width') &&
123 ann[i].hasOwnProperty('height'))) {
124 this.dygraph_.error("Must set width and height when setting " +
125 "annotation.icon property");
126 return;
127 }
128 Dygraph.update(a, ann[i]);
129 if (!a.xval) a.xval = parse(a.x);
130 this.annotations.push(a);
131 }
132};
133
134DygraphLayout.prototype.setXTicks = function(xTicks) {
135 this.xTicks_ = xTicks;
136};
137
138// TODO(danvk): add this to the Dygraph object's API or move it into Layout.
139DygraphLayout.prototype.setYAxes = function (yAxes) {
140 this.yAxes_ = yAxes;
141};
142
143DygraphLayout.prototype.setDateWindow = function(dateWindow) {
144 this.dateWindow_ = dateWindow;
145};
146
147DygraphLayout.prototype.evaluate = function() {
148 this._evaluateLimits();
149 this._evaluateLineCharts();
150 this._evaluateLineTicks();
151 this._evaluateAnnotations();
152};
153
154DygraphLayout.prototype._evaluateLimits = function() {
155 this.minxval = this.maxxval = null;
156 if (this.dateWindow_) {
157 this.minxval = this.dateWindow_[0];
158 this.maxxval = this.dateWindow_[1];
159 } else {
160 for (var name in this.datasets) {
161 if (!this.datasets.hasOwnProperty(name)) continue;
162 var series = this.datasets[name];
163 if (series.length > 1) {
164 var x1 = series[0][0];
165 if (!this.minxval || x1 < this.minxval) this.minxval = x1;
ccd9d7c2 166
74a5af31
DV
167 var x2 = series[series.length - 1][0];
168 if (!this.maxxval || x2 > this.maxxval) this.maxxval = x2;
169 }
170 }
171 }
172 this.xrange = this.maxxval - this.minxval;
758a629f 173 this.xscale = (this.xrange !== 0 ? 1/this.xrange : 1.0);
74a5af31
DV
174
175 for (var i = 0; i < this.yAxes_.length; i++) {
176 var axis = this.yAxes_[i];
177 axis.minyval = axis.computedValueRange[0];
178 axis.maxyval = axis.computedValueRange[1];
179 axis.yrange = axis.maxyval - axis.minyval;
758a629f 180 axis.yscale = (axis.yrange !== 0 ? 1.0 / axis.yrange : 1.0);
74a5af31
DV
181
182 if (axis.g.attr_("logscale")) {
183 axis.ylogrange = Dygraph.log10(axis.maxyval) - Dygraph.log10(axis.minyval);
758a629f 184 axis.ylogscale = (axis.ylogrange !== 0 ? 1.0 / axis.ylogrange : 1.0);
74a5af31
DV
185 if (!isFinite(axis.ylogrange) || isNaN(axis.ylogrange)) {
186 axis.g.error('axis ' + i + ' of graph at ' + axis.g +
187 ' can\'t be displayed in log scale for range [' +
188 axis.minyval + ' - ' + axis.maxyval + ']');
189 }
190 }
191 }
192};
193
7f028980
DV
194DygraphLayout._calcYNormal = function(axis, value) {
195 if (axis.logscale) {
196 return 1.0 - ((Dygraph.log10(value) - Dygraph.log10(axis.minyval)) * axis.ylogscale);
197 } else {
198 return 1.0 - ((value - axis.minyval) * axis.yscale);
199 }
200};
201
74a5af31
DV
202DygraphLayout.prototype._evaluateLineCharts = function() {
203 // add all the rects
758a629f 204 this.points = [];
c3e1495b
AR
205 // An array to keep track of how many points will be drawn for each set.
206 // This will allow for the canvas renderer to not have to check every point
fc77253b
DV
207 // for every data set since the points are added in order of the sets in
208 // datasets.
758a629f 209 this.setPointsLengths = [];
c3e1495b 210
74a5af31
DV
211 for (var setName in this.datasets) {
212 if (!this.datasets.hasOwnProperty(setName)) continue;
213
214 var dataset = this.datasets[setName];
215 var axis = this.dygraph_.axisPropertiesForSeries(setName);
216
c3e1495b 217 var setPointsLength = 0;
ecf9b464 218
74a5af31
DV
219 for (var j = 0; j < dataset.length; j++) {
220 var item = dataset[j];
758a629f
DV
221 var xValue = parseFloat(item[0]);
222 var yValue = parseFloat(item[1]);
ecf9b464 223
4ab8db0c 224 // Range from 0-1 where 0 represents left and 1 represents right.
7f028980
DV
225 var xNormal = (xValue - this.minxval) * this.xscale;
226 // Range from 0-1 where 0 represents top and 1 represents bottom
227 var yNormal = DygraphLayout._calcYNormal(axis, yValue);
228
f9414b11
DV
229 var point = {
230 // TODO(danvk): here
231 x: xNormal,
232 y: yNormal,
233 xval: xValue,
234 yval: yValue,
235 name: setName
236 };
237 this.points.push(point);
238 setPointsLength += 1;
74a5af31 239 }
c3e1495b 240 this.setPointsLengths.push(setPointsLength);
74a5af31
DV
241 }
242};
243
244DygraphLayout.prototype._evaluateLineTicks = function() {
758a629f
DV
245 var i, tick, label, pos;
246 this.xticks = [];
247 for (i = 0; i < this.xTicks_.length; i++) {
248 tick = this.xTicks_[i];
249 label = tick.label;
250 pos = this.xscale * (tick.v - this.minxval);
74a5af31
DV
251 if ((pos >= 0.0) && (pos <= 1.0)) {
252 this.xticks.push([pos, label]);
253 }
254 }
255
758a629f
DV
256 this.yticks = [];
257 for (i = 0; i < this.yAxes_.length; i++ ) {
74a5af31
DV
258 var axis = this.yAxes_[i];
259 for (var j = 0; j < axis.ticks.length; j++) {
758a629f
DV
260 tick = axis.ticks[j];
261 label = tick.label;
262 pos = this.dygraph_.toPercentYCoord(tick.v, i);
74a5af31
DV
263 if ((pos >= 0.0) && (pos <= 1.0)) {
264 this.yticks.push([i, pos, label]);
265 }
266 }
267 }
268};
269
270
271/**
272 * Behaves the same way as PlotKit.Layout, but also copies the errors
273 * @private
274 */
275DygraphLayout.prototype.evaluateWithError = function() {
276 this.evaluate();
277 if (!(this.attr_('errorBars') || this.attr_('customBars'))) return;
278
279 // Copy over the error terms
758a629f 280 var i = 0; // index in this.points
74a5af31
DV
281 for (var setName in this.datasets) {
282 if (!this.datasets.hasOwnProperty(setName)) continue;
283 var j = 0;
284 var dataset = this.datasets[setName];
7f028980 285 var axis = this.dygraph_.axisPropertiesForSeries(setName);
758a629f 286 for (j = 0; j < dataset.length; j++, i++) {
74a5af31
DV
287 var item = dataset[j];
288 var xv = parseFloat(item[0]);
289 var yv = parseFloat(item[1]);
290
291 if (xv == this.points[i].xval &&
292 yv == this.points[i].yval) {
7f028980
DV
293 var errorMinus = parseFloat(item[2]);
294 var errorPlus = parseFloat(item[3]);
295
296 var yv_minus = yv - errorMinus;
297 var yv_plus = yv + errorPlus;
298 this.points[i].y_top = DygraphLayout._calcYNormal(axis, yv_minus);
299 this.points[i].y_bottom = DygraphLayout._calcYNormal(axis, yv_plus);
74a5af31
DV
300 }
301 }
302 }
303};
304
305DygraphLayout.prototype._evaluateAnnotations = function() {
306 // Add the annotations to the point to which they belong.
307 // Make a map from (setName, xval) to annotation for quick lookups.
758a629f 308 var i;
74a5af31 309 var annotations = {};
758a629f 310 for (i = 0; i < this.annotations.length; i++) {
74a5af31
DV
311 var a = this.annotations[i];
312 annotations[a.xval + "," + a.series] = a;
313 }
314
315 this.annotated_points = [];
d570a072
AR
316
317 // Exit the function early if there are no annotations.
318 if (!this.annotations || !this.annotations.length) {
319 return;
320 }
ccd9d7c2 321
d570a072 322 // TODO(antrob): loop through annotations not points.
758a629f 323 for (i = 0; i < this.points.length; i++) {
74a5af31
DV
324 var p = this.points[i];
325 var k = p.xval + "," + p.name;
326 if (k in annotations) {
327 p.annotation = annotations[k];
328 this.annotated_points.push(p);
329 }
330 }
331};
332
333/**
334 * Convenience function to remove all the data sets from a graph
335 */
336DygraphLayout.prototype.removeAllDatasets = function() {
337 delete this.datasets;
758a629f 338 this.datasets = [];
74a5af31
DV
339};
340
341/**
342 * Return a copy of the point at the indicated index, with its yval unstacked.
343 * @param int index of point in layout_.points
344 */
345DygraphLayout.prototype.unstackPointAtIndex = function(idx) {
346 var point = this.points[idx];
ccd9d7c2 347
74a5af31 348 // Clone the point since we modify it
ccd9d7c2 349 var unstackedPoint = {};
758a629f
DV
350 for (var pt in point) {
351 unstackedPoint[pt] = point[pt];
74a5af31 352 }
ccd9d7c2 353
74a5af31
DV
354 if (!this.attr_("stackedGraph")) {
355 return unstackedPoint;
356 }
ccd9d7c2
PF
357
358 // The unstacked yval is equal to the current yval minus the yval of the
74a5af31
DV
359 // next point at the same xval.
360 for (var i = idx+1; i < this.points.length; i++) {
361 if (this.points[i].xval == point.xval) {
ccd9d7c2 362 unstackedPoint.yval -= this.points[i].yval;
74a5af31
DV
363 break;
364 }
365 }
ccd9d7c2 366
74a5af31 367 return unstackedPoint;
758a629f 368};