Track code size on PRs
[dygraphs.git] / src / 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
3ce712e6
DV
12var DygraphLayout = (function() {
13
758a629f 14/*global Dygraph:false */
c0f54d4f
DV
15"use strict";
16
74a5af31
DV
17/**
18 * Creates a new DygraphLayout object.
19 *
20 * This class contains all the data to be charted.
21 * It uses data coordinates, but also records the chart range (in data
22 * coordinates) and hence is able to calculate percentage positions ('In this
23 * view, Point A lies 25% down the x-axis.')
24 *
25 * Two things that it does not do are:
26 * 1. Record pixel coordinates for anything.
27 * 2. (oddly) determine anything about the layout of chart elements.
28 *
29 * The naming is a vestige of Dygraph's original PlotKit roots.
30 *
31 * @constructor
32 */
c0f54d4f 33var DygraphLayout = function(dygraph) {
74a5af31 34 this.dygraph_ = dygraph;
30a5cfc6
KW
35 /**
36 * Array of points for each series.
37 *
38 * [series index][row index in series] = |Point| structure,
39 * where series index refers to visible series only, and the
40 * point index is for the reduced set of points for the current
41 * zoom region (including one point just outside the window).
42 * All points in the same row index share the same X value.
43 *
44 * @type {Array.<Array.<Dygraph.PointType>>}
45 */
46 this.points = [];
82c6fe4d 47 this.setNames = [];
758a629f 48 this.annotations = [];
74a5af31
DV
49 this.yAxes_ = null;
50
51 // TODO(danvk): it's odd that xTicks_ and yTicks_ are inputs, but xticks and
52 // yticks are outputs. Clean this up.
53 this.xTicks_ = null;
54 this.yTicks_ = null;
55};
56
30a5cfc6
KW
57/**
58 * Add points for a single series.
59 *
60 * @param {string} setname Name of the series.
61 * @param {Array.<Dygraph.PointType>} set_xy Points for the series.
62 */
74a5af31 63DygraphLayout.prototype.addDataset = function(setname, set_xy) {
30a5cfc6 64 this.points.push(set_xy);
82c6fe4d 65 this.setNames.push(setname);
74a5af31
DV
66};
67
141064ff
DE
68/**
69 * Returns the box which the chart should be drawn in. This is the canvas's
70 * box, less space needed for the axis and chart labels.
71 *
72 * @return {{x: number, y: number, w: number, h: number}}
73 */
70be5ed1 74DygraphLayout.prototype.getPlotArea = function() {
0d216a60 75 return this.area_;
758a629f 76};
70be5ed1 77
ccd9d7c2 78// Compute the box which the chart should be drawn in. This is the canvas's
ad617f17 79// box, less space needed for axis, chart labels, and other plug-ins.
ec475f44 80// NOTE: This should only be called by Dygraph.predraw_().
0d216a60 81DygraphLayout.prototype.computePlotArea = function() {
ccd9d7c2
PF
82 var area = {
83 // TODO(danvk): per-axis setting.
84 x: 0,
85 y: 0
86 };
f8540c66 87
7e64db42 88 area.w = this.dygraph_.width_ - area.x - this.dygraph_.getOption('rightGap');
ccd9d7c2 89 area.h = this.dygraph_.height_;
6dca682f
DV
90
91 // Let plugins reserve space.
92 var e = {
93 chart_div: this.dygraph_.graphDiv,
94 reserveSpaceLeft: function(px) {
95 var r = {
96 x: area.x,
97 y: area.y,
98 w: px,
99 h: area.h
100 };
101 area.x += px;
102 area.w -= px;
103 return r;
104 },
1c177b6a
DV
105 reserveSpaceRight: function(px) {
106 var r = {
107 x: area.x + area.w - px,
108 y: area.y,
109 w: px,
110 h: area.h
111 };
112 area.w -= px;
113 return r;
114 },
6dca682f
DV
115 reserveSpaceTop: function(px) {
116 var r = {
117 x: area.x,
118 y: area.y,
119 w: area.w,
120 h: px
121 };
122 area.y += px;
123 area.h -= px;
124 return r;
125 },
1c177b6a
DV
126 reserveSpaceBottom: function(px) {
127 var r = {
128 x: area.x,
129 y: area.y + area.h - px,
130 w: area.w,
131 h: px
132 };
133 area.h -= px;
134 return r;
135 },
6dca682f
DV
136 chartRect: function() {
137 return {x:area.x, y:area.y, w:area.w, h:area.h};
138 }
139 };
140 this.dygraph_.cascadeEvents_('layout', e);
141
0d216a60 142 this.area_ = area;
ccd9d7c2
PF
143};
144
74a5af31
DV
145DygraphLayout.prototype.setAnnotations = function(ann) {
146 // The Dygraph object's annotations aren't parsed. We parse them here and
147 // save a copy. If there is no parser, then the user must be using raw format.
148 this.annotations = [];
7e64db42 149 var parse = this.dygraph_.getOption('xValueParser') || function(x) { return x; };
74a5af31
DV
150 for (var i = 0; i < ann.length; i++) {
151 var a = {};
b5481aea 152 if (!ann[i].xval && ann[i].x === undefined) {
8a68db7d 153 console.error("Annotations must have an 'x' property");
74a5af31
DV
154 return;
155 }
156 if (ann[i].icon &&
157 !(ann[i].hasOwnProperty('width') &&
158 ann[i].hasOwnProperty('height'))) {
8a68db7d 159 console.error("Must set width and height when setting " +
464b5f50 160 "annotation.icon property");
74a5af31
DV
161 return;
162 }
163 Dygraph.update(a, ann[i]);
164 if (!a.xval) a.xval = parse(a.x);
165 this.annotations.push(a);
166 }
167};
168
169DygraphLayout.prototype.setXTicks = function(xTicks) {
170 this.xTicks_ = xTicks;
171};
172
173// TODO(danvk): add this to the Dygraph object's API or move it into Layout.
174DygraphLayout.prototype.setYAxes = function (yAxes) {
175 this.yAxes_ = yAxes;
176};
177
74a5af31 178DygraphLayout.prototype.evaluate = function() {
5b9b2142 179 this._xAxis = {};
74a5af31
DV
180 this._evaluateLimits();
181 this._evaluateLineCharts();
182 this._evaluateLineTicks();
183 this._evaluateAnnotations();
184};
185
186DygraphLayout.prototype._evaluateLimits = function() {
fa460473 187 var xlimits = this.dygraph_.xAxisRange();
bacf5ce2
RK
188 this._xAxis.minval = xlimits[0];
189 this._xAxis.maxval = xlimits[1];
fa460473 190 var xrange = xlimits[1] - xlimits[0];
bacf5ce2 191 this._xAxis.scale = (xrange !== 0 ? 1 / xrange : 1.0);
74a5af31 192
5b9b2142 193 if (this.dygraph_.getOptionForAxis("logscale", 'x')) {
bacf5ce2 194 this._xAxis.xlogrange = Dygraph.log10(this._xAxis.maxval) - Dygraph.log10(this._xAxis.minval);
5b9b2142
RK
195 this._xAxis.xlogscale = (this._xAxis.xlogrange !== 0 ? 1.0 / this._xAxis.xlogrange : 1.0);
196 }
74a5af31
DV
197 for (var i = 0; i < this.yAxes_.length; i++) {
198 var axis = this.yAxes_[i];
199 axis.minyval = axis.computedValueRange[0];
200 axis.maxyval = axis.computedValueRange[1];
201 axis.yrange = axis.maxyval - axis.minyval;
758a629f 202 axis.yscale = (axis.yrange !== 0 ? 1.0 / axis.yrange : 1.0);
74a5af31 203
5b9b2142 204 if (this.dygraph_.getOption("logscale")) {
74a5af31 205 axis.ylogrange = Dygraph.log10(axis.maxyval) - Dygraph.log10(axis.minyval);
758a629f 206 axis.ylogscale = (axis.ylogrange !== 0 ? 1.0 / axis.ylogrange : 1.0);
74a5af31 207 if (!isFinite(axis.ylogrange) || isNaN(axis.ylogrange)) {
8a68db7d 208 console.error('axis ' + i + ' of graph at ' + axis.g +
464b5f50
DV
209 ' can\'t be displayed in log scale for range [' +
210 axis.minyval + ' - ' + axis.maxyval + ']');
74a5af31
DV
211 }
212 }
213 }
214};
215
bacf5ce2 216DygraphLayout.calcXNormal_ = function(value, xAxis, logscale) {
5b9b2142 217 if (logscale) {
bacf5ce2 218 return ((Dygraph.log10(value) - Dygraph.log10(xAxis.minval)) * xAxis.xlogscale);
5b9b2142 219 } else {
bacf5ce2 220 return (value - xAxis.minval) * xAxis.scale;
5b9b2142
RK
221 }
222};
223
e956b69b
DV
224/**
225 * @param {DygraphAxisType} axis
226 * @param {number} value
227 * @param {boolean} logscale
228 * @return {number}
229 */
230DygraphLayout.calcYNormal_ = function(axis, value, logscale) {
23db4e07 231 if (logscale) {
b7ec6c55 232 var x = 1.0 - ((Dygraph.log10(value) - Dygraph.log10(axis.minyval)) * axis.ylogscale);
40a54d29 233 return isFinite(x) ? x : NaN; // shim for v8 issue; see pull request 276
7f028980
DV
234 } else {
235 return 1.0 - ((value - axis.minyval) * axis.yscale);
236 }
237};
238
74a5af31 239DygraphLayout.prototype._evaluateLineCharts = function() {
7e64db42 240 var isStacked = this.dygraph_.getOption("stackedGraph");
5b9b2142 241 var isLogscaleForX = this.dygraph_.getOptionForAxis("logscale", 'x');
a12a78ae 242
30a5cfc6
KW
243 for (var setIdx = 0; setIdx < this.points.length; setIdx++) {
244 var points = this.points[setIdx];
82c6fe4d 245 var setName = this.setNames[setIdx];
7e64db42 246 var connectSeparated = this.dygraph_.getOption('connectSeparatedPoints', setName);
74a5af31 247 var axis = this.dygraph_.axisPropertiesForSeries(setName);
23db4e07 248 // TODO (konigsberg): use optionsForAxis instead.
8e19509a 249 var logscale = this.dygraph_.attributes_.getForSeries("logscale", setName);
74a5af31 250
30a5cfc6
KW
251 for (var j = 0; j < points.length; j++) {
252 var point = points[j];
ecf9b464 253
4ab8db0c 254 // Range from 0-1 where 0 represents left and 1 represents right.
335011fd 255 point.x = DygraphLayout.calcXNormal_(point.xval, this._xAxis, isLogscaleForX);
7f028980 256 // Range from 0-1 where 0 represents top and 1 represents bottom
30a5cfc6
KW
257 var yval = point.yval;
258 if (isStacked) {
e956b69b 259 point.y_stacked = DygraphLayout.calcYNormal_(
30a5cfc6
KW
260 axis, point.yval_stacked, logscale);
261 if (yval !== null && !isNaN(yval)) {
262 yval = point.yval_stacked;
263 }
264 }
265 if (yval === null) {
266 yval = NaN;
267 if (!connectSeparated) {
268 point.yval = NaN;
269 }
270 }
e956b69b 271 point.y = DygraphLayout.calcYNormal_(axis, yval, logscale);
74a5af31 272 }
a49c164a
DE
273
274 this.dygraph_.dataHandler_.onLineEvaluated(points, axis, logscale);
74a5af31
DV
275 }
276};
277
278DygraphLayout.prototype._evaluateLineTicks = function() {
758a629f
DV
279 var i, tick, label, pos;
280 this.xticks = [];
281 for (i = 0; i < this.xTicks_.length; i++) {
282 tick = this.xTicks_[i];
283 label = tick.label;
5b9b2142 284 pos = this.dygraph_.toPercentXCoord(tick.v);
9146b6c0 285 if ((pos >= 0.0) && (pos < 1.0)) {
74a5af31
DV
286 this.xticks.push([pos, label]);
287 }
288 }
289
758a629f
DV
290 this.yticks = [];
291 for (i = 0; i < this.yAxes_.length; i++ ) {
74a5af31
DV
292 var axis = this.yAxes_[i];
293 for (var j = 0; j < axis.ticks.length; j++) {
758a629f
DV
294 tick = axis.ticks[j];
295 label = tick.label;
296 pos = this.dygraph_.toPercentYCoord(tick.v, i);
9146b6c0 297 if ((pos > 0.0) && (pos <= 1.0)) {
74a5af31
DV
298 this.yticks.push([i, pos, label]);
299 }
300 }
301 }
302};
303
74a5af31
DV
304DygraphLayout.prototype._evaluateAnnotations = function() {
305 // Add the annotations to the point to which they belong.
306 // Make a map from (setName, xval) to annotation for quick lookups.
758a629f 307 var i;
74a5af31 308 var annotations = {};
758a629f 309 for (i = 0; i < this.annotations.length; i++) {
74a5af31
DV
310 var a = this.annotations[i];
311 annotations[a.xval + "," + a.series] = a;
312 }
313
314 this.annotated_points = [];
d570a072
AR
315
316 // Exit the function early if there are no annotations.
317 if (!this.annotations || !this.annotations.length) {
318 return;
319 }
ccd9d7c2 320
d570a072 321 // TODO(antrob): loop through annotations not points.
a12a78ae
DV
322 for (var setIdx = 0; setIdx < this.points.length; setIdx++) {
323 var points = this.points[setIdx];
324 for (i = 0; i < points.length; i++) {
325 var p = points[i];
326 var k = p.xval + "," + p.name;
327 if (k in annotations) {
328 p.annotation = annotations[k];
329 this.annotated_points.push(p);
330 }
74a5af31
DV
331 }
332 }
333};
334
335/**
336 * Convenience function to remove all the data sets from a graph
337 */
338DygraphLayout.prototype.removeAllDatasets = function() {
30a5cfc6 339 delete this.points;
82c6fe4d
KW
340 delete this.setNames;
341 delete this.setPointsLengths;
342 delete this.setPointsOffsets;
30a5cfc6 343 this.points = [];
82c6fe4d
KW
344 this.setNames = [];
345 this.setPointsLengths = [];
346 this.setPointsOffsets = [];
74a5af31 347};
3ce712e6
DV
348
349return DygraphLayout;
350
351})();