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