d63f080b6d64a19c48316e02c93395e5007129e4
[dygraphs.git] / plugins / legend.js
1 Dygraph.Plugins.Legend = (function() {
2
3 /*
4
5 Current bits of jankiness:
6 - Uses two private APIs:
7 1. Dygraph.optionsViewForAxis_
8 2. dygraph.plotter_.area
9 - Registers for a "predraw" event, which should be renamed.
10 - I call calculateEmWidthInDiv more often than needed.
11
12 */
13
14 "use strict";
15
16
17 /**
18 * Creates the legend, which appears when the user hovers over the chart.
19 * The legend can be either a user-specified or generated div.
20 *
21 * @constructor
22 */
23 var legend = function() {
24 this.legend_div_ = null;
25 this.is_generated_div_ = false; // do we own this div, or was it user-specified?
26 };
27
28 legend.prototype.toString = function() {
29 return "Legend Plugin";
30 };
31
32 /**
33 * This is called during the dygraph constructor, after options have been set
34 * but before the data is available.
35 *
36 * Proper tasks to do here include:
37 * - Reading your own options
38 * - DOM manipulation
39 * - Registering event listeners
40 *
41 * @param {Dygraph} g Graph instance.
42 * @return {object.<string, function(ev)>} Mapping of event names to callbacks.
43 */
44 legend.prototype.activate = function(g) {
45 var div;
46 var divWidth = g.getOption('labelsDivWidth');
47
48 var userLabelsDiv = g.getOption('labelsDiv');
49 if (userLabelsDiv && null !== userLabelsDiv) {
50 if (typeof(userLabelsDiv) == "string" || userLabelsDiv instanceof String) {
51 div = document.getElementById(userLabelsDiv);
52 } else {
53 div = userLabelsDiv;
54 }
55 } else {
56 // Default legend styles. These can be overridden in CSS by adding
57 // "!important" after your rule, e.g. "left: 30px !important;"
58 var messagestyle = {
59 "position": "absolute",
60 "fontSize": "14px",
61 "zIndex": 10,
62 "width": divWidth + "px",
63 "top": "0px",
64 "left": (g.size().width - divWidth - 2) + "px",
65 "background": "white",
66 "lineHeight": "normal",
67 "textAlign": "left",
68 "overflow": "hidden"};
69
70 // TODO(danvk): get rid of labelsDivStyles? CSS is better.
71 Dygraph.update(messagestyle, g.getOption('labelsDivStyles'));
72 div = document.createElement("div");
73 div.className = "dygraph-legend";
74 for (var name in messagestyle) {
75 if (!messagestyle.hasOwnProperty(name)) continue;
76
77 try {
78 div.style[name] = messagestyle[name];
79 } catch (e) {
80 this.warn("You are using unsupported css properties for your " +
81 "browser in labelsDivStyles");
82 }
83 }
84
85 // TODO(danvk): come up with a cleaner way to expose this.
86 g.graphDiv.appendChild(div);
87 this.is_generated_div_ = true;
88 }
89
90 this.legend_div_ = div;
91
92 return {
93 select: this.select,
94 deselect: this.deselect,
95 // TODO(danvk): rethink the name "predraw" before we commit to it in any API.
96 predraw: this.predraw,
97 drawChart: this.drawChart
98 };
99 };
100
101 // Needed for dashed lines.
102 var calculateEmWidthInDiv = function(div) {
103 var sizeSpan = document.createElement('span');
104 sizeSpan.setAttribute('style', 'margin: 0; padding: 0 0 0 1em; border: 0;');
105 div.appendChild(sizeSpan);
106 var oneEmWidth=sizeSpan.offsetWidth;
107 div.removeChild(sizeSpan);
108 return oneEmWidth;
109 };
110
111 legend.prototype.select = function(e) {
112 var xValue = e.selectedX;
113 var points = e.selectedPoints;
114
115 // Have to do this every time, since styles might have changed.
116 // TODO(danvk): this is not necessary; dashes never used in this case.
117 var oneEmWidth = calculateEmWidthInDiv(this.legend_div_);
118
119 var html = generateLegendHTML(e.dygraph, xValue, points, oneEmWidth);
120 this.legend_div_.innerHTML = html;
121 };
122
123 legend.prototype.deselect = function(e) {
124 var oneEmWidth = calculateEmWidthInDiv(this.legend_div_);
125 var html = generateLegendHTML(e.dygraph, undefined, undefined, oneEmWidth);
126 this.legend_div_.innerHTML = html;
127 };
128
129 legend.prototype.drawChart = function(e) {
130 this.deselect(e);
131 }
132
133 // Right edge should be flush with the right edge of the charting area (which
134 // may not be the same as the right edge of the div, if we have two y-axes.
135 // TODO(danvk): is any of this really necessary? Could just set "right" in "activate".
136 /**
137 * Position the labels div so that:
138 * - its right edge is flush with the right edge of the charting area
139 * - its top edge is flush with the top edge of the charting area
140 * @private
141 */
142 legend.prototype.predraw = function(e) {
143 // Don't touch a user-specified labelsDiv.
144 if (!this.is_generated_div_) return;
145
146 // TODO(danvk): only use real APIs for this.
147 e.dygraph.graphDiv.appendChild(this.legend_div_);
148 var area = e.dygraph.plotter_.area;
149 this.legend_div_.style.left = area.x + area.w - e.dygraph.getOption("labelsDivWidth") - 1 + "px";
150 this.legend_div_.style.top = area.y + "px";
151 };
152
153 /**
154 * Called when dygraph.destroy() is called.
155 * You should null out any references and detach any DOM elements.
156 */
157 legend.prototype.destroy = function() {
158 this.legend_div_ = null;
159 };
160
161 /**
162 * @private
163 * Generates HTML for the legend which is displayed when hovering over the
164 * chart. If no selected points are specified, a default legend is returned
165 * (this may just be the empty string).
166 * @param { Number } [x] The x-value of the selected points.
167 * @param { [Object] } [sel_points] List of selected points for the given
168 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
169 * @param { Number } [oneEmWidth] The pixel width for 1em in the legend. Only
170 * relevant when displaying a legend with no selection (i.e. {legend:
171 * 'always'}) and with dashed lines.
172 */
173 var generateLegendHTML = function(g, x, sel_points, oneEmWidth) {
174 // TODO(danvk): deprecate this option in place of {legend: 'never'}
175 if (g.getOption('showLabelsOnHighlight') !== true) return '';
176
177 // If no points are selected, we display a default legend. Traditionally,
178 // this has been blank. But a better default would be a conventional legend,
179 // which provides essential information for a non-interactive chart.
180 var html, sepLines, i, c, dash, strokePattern;
181 var labels = g.getLabels();
182
183 if (typeof(x) === 'undefined') {
184 if (g.getOption('legend') != 'always') {
185 return '';
186 }
187
188 sepLines = g.getOption('labelsSeparateLines');
189 html = '';
190 for (i = 1; i < labels.length; i++) {
191 var series = g.getPropertiesForSeries(labels[i]);
192 if (!series.visible) continue;
193
194 if (html !== '') html += (sepLines ? '<br/>' : ' ');
195 strokePattern = g.getOption("strokePattern", labels[i]);
196 dash = generateLegendDashHTML(strokePattern, series.color, oneEmWidth);
197 html += "<span style='font-weight: bold; color: " + series.color + ";'>" +
198 dash + " " + labels[i] + "</span>";
199 }
200 return html;
201 }
202
203 // TODO(danvk): remove this use of a private API
204 var xOptView = g.optionsViewForAxis_('x');
205 var xvf = xOptView('valueFormatter');
206 html = xvf(x, xOptView, labels[0], g) + ":";
207
208 var yOptViews = [];
209 var num_axes = g.numAxes();
210 for (i = 0; i < num_axes; i++) {
211 // TODO(danvk): remove this use of a private API
212 yOptViews[i] = g.optionsViewForAxis_('y' + (i ? 1 + i : ''));
213 }
214 var showZeros = g.getOption("labelsShowZeroValues");
215 sepLines = g.getOption("labelsSeparateLines");
216 var highlightSeries = g.getHighlightSeries();
217 for (i = 0; i < sel_points.length; i++) {
218 var pt = sel_points[i];
219 if (pt.yval === 0 && !showZeros) continue;
220 if (!Dygraph.isOK(pt.canvasy)) continue;
221 if (sepLines) html += "<br/>";
222
223 var series = g.getPropertiesForSeries(pt.name);
224 var yOptView = yOptViews[series.axis - 1];
225 var fmtFunc = yOptView('valueFormatter');
226 var yval = fmtFunc(pt.yval, yOptView, pt.name, g);
227
228 var cls = (pt.name == highlightSeries) ? " class='highlight'" : "";
229
230 // TODO(danvk): use a template string here and make it an attribute.
231 html += "<span" + cls + ">" + " <b><span style='color: " + series.color + ";'>" +
232 pt.name + "</span></b>:" + yval + "</span>";
233 }
234 return html;
235 };
236
237
238 /**
239 * Generates html for the "dash" displayed on the legend when using "legend: always".
240 * In particular, this works for dashed lines with any stroke pattern. It will
241 * try to scale the pattern to fit in 1em width. Or if small enough repeat the
242 * pattern for 1em width.
243 *
244 * @param strokePattern The pattern
245 * @param color The color of the series.
246 * @param oneEmWidth The width in pixels of 1em in the legend.
247 * @private
248 */
249 var generateLegendDashHTML = function(strokePattern, color, oneEmWidth) {
250 // IE 7,8 fail at these divs, so they get boring legend, have not tested 9.
251 var isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
252 if (isIE) return "&mdash;";
253
254 // Easy, common case: a solid line
255 if (!strokePattern || strokePattern.length <= 1) {
256 return "<div style=\"display: inline-block; position: relative; " +
257 "bottom: .5ex; padding-left: 1em; height: 1px; " +
258 "border-bottom: 2px solid " + color + ";\"></div>";
259 }
260
261 var i, j, paddingLeft, marginRight;
262 var strokePixelLength = 0, segmentLoop = 0;
263 var normalizedPattern = [];
264 var loop;
265
266 // Compute the length of the pixels including the first segment twice,
267 // since we repeat it.
268 for (i = 0; i <= strokePattern.length; i++) {
269 strokePixelLength += strokePattern[i%strokePattern.length];
270 }
271
272 // See if we can loop the pattern by itself at least twice.
273 loop = Math.floor(oneEmWidth/(strokePixelLength-strokePattern[0]));
274 if (loop > 1) {
275 // This pattern fits at least two times, no scaling just convert to em;
276 for (i = 0; i < strokePattern.length; i++) {
277 normalizedPattern[i] = strokePattern[i]/oneEmWidth;
278 }
279 // Since we are repeating the pattern, we don't worry about repeating the
280 // first segment in one draw.
281 segmentLoop = normalizedPattern.length;
282 } else {
283 // If the pattern doesn't fit in the legend we scale it to fit.
284 loop = 1;
285 for (i = 0; i < strokePattern.length; i++) {
286 normalizedPattern[i] = strokePattern[i]/strokePixelLength;
287 }
288 // For the scaled patterns we do redraw the first segment.
289 segmentLoop = normalizedPattern.length+1;
290 }
291
292 // Now make the pattern.
293 var dash = "";
294 for (j = 0; j < loop; j++) {
295 for (i = 0; i < segmentLoop; i+=2) {
296 // The padding is the drawn segment.
297 paddingLeft = normalizedPattern[i%normalizedPattern.length];
298 if (i < strokePattern.length) {
299 // The margin is the space segment.
300 marginRight = normalizedPattern[(i+1)%normalizedPattern.length];
301 } else {
302 // The repeated first segment has no right margin.
303 marginRight = 0;
304 }
305 dash += "<div style=\"display: inline-block; position: relative; " +
306 "bottom: .5ex; margin-right: " + marginRight + "em; padding-left: " +
307 paddingLeft + "em; height: 1px; border-bottom: 2px solid " + color +
308 ";\"></div>";
309 }
310 }
311 return dash;
312 };
313
314
315 return legend;
316 })();