Make seriesToPoints_ and stackPoints_ private. They are being rendered as part of...
[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;
30a5cfc6
KW
34 /**
35 * Array of points for each series.
36 *
37 * [series index][row index in series] = |Point| structure,
38 * where series index refers to visible series only, and the
39 * point index is for the reduced set of points for the current
40 * zoom region (including one point just outside the window).
41 * All points in the same row index share the same X value.
42 *
43 * @type {Array.<Array.<Dygraph.PointType>>}
44 */
45 this.points = [];
82c6fe4d 46 this.setNames = [];
758a629f 47 this.annotations = [];
74a5af31
DV
48 this.yAxes_ = null;
49
50 // TODO(danvk): it's odd that xTicks_ and yTicks_ are inputs, but xticks and
51 // yticks are outputs. Clean this up.
52 this.xTicks_ = null;
53 this.yTicks_ = null;
54};
55
56DygraphLayout.prototype.attr_ = function(name) {
57 return this.dygraph_.attr_(name);
58};
59
30a5cfc6
KW
60/**
61 * Add points for a single series.
62 *
63 * @param {string} setname Name of the series.
64 * @param {Array.<Dygraph.PointType>} set_xy Points for the series.
65 */
74a5af31 66DygraphLayout.prototype.addDataset = function(setname, set_xy) {
30a5cfc6 67 this.points.push(set_xy);
82c6fe4d 68 this.setNames.push(setname);
74a5af31
DV
69};
70
141064ff
DE
71/**
72 * Returns the box which the chart should be drawn in. This is the canvas's
73 * box, less space needed for the axis and chart labels.
74 *
75 * @return {{x: number, y: number, w: number, h: number}}
76 */
70be5ed1 77DygraphLayout.prototype.getPlotArea = function() {
0d216a60 78 return this.area_;
758a629f 79};
70be5ed1 80
ccd9d7c2 81// Compute the box which the chart should be drawn in. This is the canvas's
ad617f17 82// box, less space needed for axis, chart labels, and other plug-ins.
ec475f44 83// NOTE: This should only be called by Dygraph.predraw_().
0d216a60 84DygraphLayout.prototype.computePlotArea = function() {
ccd9d7c2
PF
85 var area = {
86 // TODO(danvk): per-axis setting.
87 x: 0,
88 y: 0
89 };
f8540c66 90
ccd9d7c2
PF
91 area.w = this.dygraph_.width_ - area.x - this.attr_('rightGap');
92 area.h = this.dygraph_.height_;
6dca682f
DV
93
94 // Let plugins reserve space.
95 var e = {
96 chart_div: this.dygraph_.graphDiv,
97 reserveSpaceLeft: function(px) {
98 var r = {
99 x: area.x,
100 y: area.y,
101 w: px,
102 h: area.h
103 };
104 area.x += px;
105 area.w -= px;
106 return r;
107 },
1c177b6a
DV
108 reserveSpaceRight: function(px) {
109 var r = {
110 x: area.x + area.w - px,
111 y: area.y,
112 w: px,
113 h: area.h
114 };
115 area.w -= px;
116 return r;
117 },
6dca682f
DV
118 reserveSpaceTop: function(px) {
119 var r = {
120 x: area.x,
121 y: area.y,
122 w: area.w,
123 h: px
124 };
125 area.y += px;
126 area.h -= px;
127 return r;
128 },
1c177b6a
DV
129 reserveSpaceBottom: function(px) {
130 var r = {
131 x: area.x,
132 y: area.y + area.h - px,
133 w: area.w,
134 h: px
135 };
136 area.h -= px;
137 return r;
138 },
6dca682f
DV
139 chartRect: function() {
140 return {x:area.x, y:area.y, w:area.w, h:area.h};
141 }
142 };
143 this.dygraph_.cascadeEvents_('layout', e);
144
0d216a60 145 this.area_ = area;
ccd9d7c2
PF
146};
147
74a5af31
DV
148DygraphLayout.prototype.setAnnotations = function(ann) {
149 // The Dygraph object's annotations aren't parsed. We parse them here and
150 // save a copy. If there is no parser, then the user must be using raw format.
151 this.annotations = [];
152 var parse = this.attr_('xValueParser') || function(x) { return x; };
153 for (var i = 0; i < ann.length; i++) {
154 var a = {};
b5481aea 155 if (!ann[i].xval && ann[i].x === undefined) {
74a5af31
DV
156 this.dygraph_.error("Annotations must have an 'x' property");
157 return;
158 }
159 if (ann[i].icon &&
160 !(ann[i].hasOwnProperty('width') &&
161 ann[i].hasOwnProperty('height'))) {
162 this.dygraph_.error("Must set width and height when setting " +
163 "annotation.icon property");
164 return;
165 }
166 Dygraph.update(a, ann[i]);
167 if (!a.xval) a.xval = parse(a.x);
168 this.annotations.push(a);
169 }
170};
171
172DygraphLayout.prototype.setXTicks = function(xTicks) {
173 this.xTicks_ = xTicks;
174};
175
176// TODO(danvk): add this to the Dygraph object's API or move it into Layout.
177DygraphLayout.prototype.setYAxes = function (yAxes) {
178 this.yAxes_ = yAxes;
179};
180
74a5af31
DV
181DygraphLayout.prototype.evaluate = function() {
182 this._evaluateLimits();
183 this._evaluateLineCharts();
184 this._evaluateLineTicks();
185 this._evaluateAnnotations();
186};
187
188DygraphLayout.prototype._evaluateLimits = function() {
fa460473
KW
189 var xlimits = this.dygraph_.xAxisRange();
190 this.minxval = xlimits[0];
191 this.maxxval = xlimits[1];
192 var xrange = xlimits[1] - xlimits[0];
193 this.xscale = (xrange !== 0 ? 1 / xrange : 1.0);
74a5af31
DV
194
195 for (var i = 0; i < this.yAxes_.length; i++) {
196 var axis = this.yAxes_[i];
197 axis.minyval = axis.computedValueRange[0];
198 axis.maxyval = axis.computedValueRange[1];
199 axis.yrange = axis.maxyval - axis.minyval;
758a629f 200 axis.yscale = (axis.yrange !== 0 ? 1.0 / axis.yrange : 1.0);
74a5af31
DV
201
202 if (axis.g.attr_("logscale")) {
203 axis.ylogrange = Dygraph.log10(axis.maxyval) - Dygraph.log10(axis.minyval);
758a629f 204 axis.ylogscale = (axis.ylogrange !== 0 ? 1.0 / axis.ylogrange : 1.0);
74a5af31
DV
205 if (!isFinite(axis.ylogrange) || isNaN(axis.ylogrange)) {
206 axis.g.error('axis ' + i + ' of graph at ' + axis.g +
207 ' can\'t be displayed in log scale for range [' +
208 axis.minyval + ' - ' + axis.maxyval + ']');
209 }
210 }
211 }
212};
213
23db4e07
RK
214DygraphLayout._calcYNormal = function(axis, value, logscale) {
215 if (logscale) {
7f028980
DV
216 return 1.0 - ((Dygraph.log10(value) - Dygraph.log10(axis.minyval)) * axis.ylogscale);
217 } else {
218 return 1.0 - ((value - axis.minyval) * axis.yscale);
219 }
220};
221
74a5af31 222DygraphLayout.prototype._evaluateLineCharts = function() {
04c104d7 223 var connectSeparated = this.attr_('connectSeparatedPoints');
30a5cfc6
KW
224 var isStacked = this.attr_("stackedGraph");
225 var hasBars = this.attr_('errorBars') || this.attr_('customBars');
a12a78ae 226
30a5cfc6
KW
227 for (var setIdx = 0; setIdx < this.points.length; setIdx++) {
228 var points = this.points[setIdx];
82c6fe4d 229 var setName = this.setNames[setIdx];
74a5af31 230 var axis = this.dygraph_.axisPropertiesForSeries(setName);
23db4e07 231 // TODO (konigsberg): use optionsForAxis instead.
8e19509a 232 var logscale = this.dygraph_.attributes_.getForSeries("logscale", setName);
74a5af31 233
30a5cfc6
KW
234 for (var j = 0; j < points.length; j++) {
235 var point = points[j];
ecf9b464 236
4ab8db0c 237 // Range from 0-1 where 0 represents left and 1 represents right.
30a5cfc6 238 point.x = (point.xval - this.minxval) * this.xscale;
7f028980 239 // Range from 0-1 where 0 represents top and 1 represents bottom
30a5cfc6
KW
240 var yval = point.yval;
241 if (isStacked) {
242 point.y_stacked = DygraphLayout._calcYNormal(
243 axis, point.yval_stacked, logscale);
244 if (yval !== null && !isNaN(yval)) {
245 yval = point.yval_stacked;
246 }
247 }
248 if (yval === null) {
249 yval = NaN;
250 if (!connectSeparated) {
251 point.yval = NaN;
252 }
253 }
254 point.y = DygraphLayout._calcYNormal(axis, yval, logscale);
7f028980 255
30a5cfc6
KW
256 if (hasBars) {
257 point.y_top = DygraphLayout._calcYNormal(
258 axis, yval - point.yval_minus, logscale);
259 point.y_bottom = DygraphLayout._calcYNormal(
260 axis, yval + point.yval_plus, logscale);
b843b52c 261 }
74a5af31
DV
262 }
263 }
264};
265
57915b7a
RK
266/**
267 * Optimized replacement for parseFloat, which was way too slow when almost
268 * all values were type number, with few edge cases, none of which were strings.
269 */
270DygraphLayout.parseFloat_ = function(val) {
271 // parseFloat(null) is NaN
272 if (val === null) {
273 return NaN;
274 }
275
276 // Assume it's a number or NaN. If it's something else, I'll be shocked.
277 return val;
42a9ebb8 278};
57915b7a 279
74a5af31 280DygraphLayout.prototype._evaluateLineTicks = function() {
758a629f
DV
281 var i, tick, label, pos;
282 this.xticks = [];
283 for (i = 0; i < this.xTicks_.length; i++) {
284 tick = this.xTicks_[i];
285 label = tick.label;
286 pos = this.xscale * (tick.v - this.minxval);
74a5af31
DV
287 if ((pos >= 0.0) && (pos <= 1.0)) {
288 this.xticks.push([pos, label]);
289 }
290 }
291
758a629f
DV
292 this.yticks = [];
293 for (i = 0; i < this.yAxes_.length; i++ ) {
74a5af31
DV
294 var axis = this.yAxes_[i];
295 for (var j = 0; j < axis.ticks.length; j++) {
758a629f
DV
296 tick = axis.ticks[j];
297 label = tick.label;
298 pos = this.dygraph_.toPercentYCoord(tick.v, i);
74a5af31
DV
299 if ((pos >= 0.0) && (pos <= 1.0)) {
300 this.yticks.push([i, pos, label]);
301 }
302 }
303 }
304};
305
74a5af31
DV
306DygraphLayout.prototype._evaluateAnnotations = function() {
307 // Add the annotations to the point to which they belong.
308 // Make a map from (setName, xval) to annotation for quick lookups.
758a629f 309 var i;
74a5af31 310 var annotations = {};
758a629f 311 for (i = 0; i < this.annotations.length; i++) {
74a5af31
DV
312 var a = this.annotations[i];
313 annotations[a.xval + "," + a.series] = a;
314 }
315
316 this.annotated_points = [];
d570a072
AR
317
318 // Exit the function early if there are no annotations.
319 if (!this.annotations || !this.annotations.length) {
320 return;
321 }
ccd9d7c2 322
d570a072 323 // TODO(antrob): loop through annotations not points.
a12a78ae
DV
324 for (var setIdx = 0; setIdx < this.points.length; setIdx++) {
325 var points = this.points[setIdx];
326 for (i = 0; i < points.length; i++) {
327 var p = points[i];
328 var k = p.xval + "," + p.name;
329 if (k in annotations) {
330 p.annotation = annotations[k];
331 this.annotated_points.push(p);
332 }
74a5af31
DV
333 }
334 }
335};
336
337/**
338 * Convenience function to remove all the data sets from a graph
339 */
340DygraphLayout.prototype.removeAllDatasets = function() {
30a5cfc6 341 delete this.points;
82c6fe4d
KW
342 delete this.setNames;
343 delete this.setPointsLengths;
344 delete this.setPointsOffsets;
30a5cfc6 345 this.points = [];
82c6fe4d
KW
346 this.setNames = [];
347 this.setPointsLengths = [];
348 this.setPointsOffsets = [];
74a5af31 349};