BUGFIX: Fixed typo
[dygraphs.git] / plugins / legend.js
CommitLineData
41da6a86
DV
1/**
2 * @license
3 * Copyright 2012 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
0cd1ad15 6/*global Dygraph:false */
41da6a86 7
e2c21500 8Dygraph.Plugins.Legend = (function() {
e2c21500
DV
9/*
10
11Current 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.
e2c21500
DV
17
18*/
19
42a9ebb8
DV
20/*jshint globalstrict: true */
21/*global Dygraph:false */
e2c21500
DV
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 */
31var 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
36legend.prototype.toString = function() {
37 return "Legend Plugin";
38};
39
42a9ebb8
DV
40// (defined below)
41var generateLegendHTML, generateLegendDashHTML;
42
e2c21500
DV
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
6a4457b4
KW
51 *
52 * @param {Dygraph} g Graph instance.
53 * @return {object.<string, function(ev)>} Mapping of event names to callbacks.
e2c21500 54 */
6a4457b4 55legend.prototype.activate = function(g) {
e2c21500
DV
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",
63e957d7 75 "left": (g.size().width - divWidth - 2) + "px",
e2c21500 76 "background": "white",
c12450f1 77 "lineHeight": "normal",
e2c21500
DV
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 this.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;
c3b1d17d 102 this.one_em_width_ = 10; // just a guess, will be updated.
e2c21500 103
6a4457b4
KW
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,
98eb4713 109 didDrawChart: this.didDrawChart
6a4457b4 110 };
e2c21500
DV
111};
112
113// Needed for dashed lines.
114var 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
6a4457b4 123legend.prototype.select = function(e) {
e2c21500
DV
124 var xValue = e.selectedX;
125 var points = e.selectedPoints;
126
c3b1d17d 127 var html = generateLegendHTML(e.dygraph, xValue, points, this.one_em_width_);
e2c21500
DV
128 this.legend_div_.innerHTML = html;
129};
130
6a4457b4 131legend.prototype.deselect = function(e) {
c3b1d17d 132 // Have to do this every time, since styles might have changed.
e2c21500 133 var oneEmWidth = calculateEmWidthInDiv(this.legend_div_);
c3b1d17d
DV
134 this.one_em_width_ = oneEmWidth;
135
e2c21500
DV
136 var html = generateLegendHTML(e.dygraph, undefined, undefined, oneEmWidth);
137 this.legend_div_.innerHTML = html;
138};
139
98eb4713 140legend.prototype.didDrawChart = function(e) {
6a4457b4 141 this.deselect(e);
42a9ebb8 142};
e2c21500
DV
143
144// Right edge should be flush with the right edge of the charting area (which
145// may not be the same as the right edge of the div, if we have two y-axes.
146// TODO(danvk): is any of this really necessary? Could just set "right" in "activate".
147/**
148 * Position the labels div so that:
149 * - its right edge is flush with the right edge of the charting area
150 * - its top edge is flush with the top edge of the charting area
151 * @private
152 */
6a4457b4 153legend.prototype.predraw = function(e) {
e2c21500
DV
154 // Don't touch a user-specified labelsDiv.
155 if (!this.is_generated_div_) return;
156
157 // TODO(danvk): only use real APIs for this.
0673f7c4 158 e.dygraph.graphDiv.appendChild(this.legend_div_);
e2c21500 159 var area = e.dygraph.plotter_.area;
de9ecc40
RK
160 var labelsDivWidth = e.dygraph.getOption("labelsDivWidth");
161 this.legend_div_.style.left = area.x + area.w - labelsDivWidth - 1 + "px";
e2c21500 162 this.legend_div_.style.top = area.y + "px";
de9ecc40 163 this.legend_div_.style.width = labelsDivWidth + "px";
e2c21500
DV
164};
165
166/**
167 * Called when dygraph.destroy() is called.
168 * You should null out any references and detach any DOM elements.
169 */
170legend.prototype.destroy = function() {
171 this.legend_div_ = null;
172};
173
174/**
175 * @private
176 * Generates HTML for the legend which is displayed when hovering over the
177 * chart. If no selected points are specified, a default legend is returned
178 * (this may just be the empty string).
179 * @param { Number } [x] The x-value of the selected points.
180 * @param { [Object] } [sel_points] List of selected points for the given
181 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
182 * @param { Number } [oneEmWidth] The pixel width for 1em in the legend. Only
183 * relevant when displaying a legend with no selection (i.e. {legend:
184 * 'always'}) and with dashed lines.
185 */
e8896dce 186generateLegendHTML = function(g, x, sel_points, oneEmWidth) {
e2c21500
DV
187 // TODO(danvk): deprecate this option in place of {legend: 'never'}
188 if (g.getOption('showLabelsOnHighlight') !== true) return '';
189
190 // If no points are selected, we display a default legend. Traditionally,
191 // this has been blank. But a better default would be a conventional legend,
192 // which provides essential information for a non-interactive chart.
0cd1ad15 193 var html, sepLines, i, dash, strokePattern;
e2c21500
DV
194 var labels = g.getLabels();
195
196 if (typeof(x) === 'undefined') {
197 if (g.getOption('legend') != 'always') {
198 return '';
199 }
200
201 sepLines = g.getOption('labelsSeparateLines');
202 html = '';
203 for (i = 1; i < labels.length; i++) {
204 var series = g.getPropertiesForSeries(labels[i]);
205 if (!series.visible) continue;
206
207 if (html !== '') html += (sepLines ? '<br/>' : ' ');
208 strokePattern = g.getOption("strokePattern", labels[i]);
209 dash = generateLegendDashHTML(strokePattern, series.color, oneEmWidth);
210 html += "<span style='font-weight: bold; color: " + series.color + ";'>" +
211 dash + " " + labels[i] + "</span>";
212 }
213 return html;
214 }
215
216 // TODO(danvk): remove this use of a private API
217 var xOptView = g.optionsViewForAxis_('x');
218 var xvf = xOptView('valueFormatter');
f5715653 219 html = xvf(x, xOptView, labels[0], g);
42a9ebb8
DV
220 if (html !== '') {
221 html += ':';
f5715653 222 }
e2c21500
DV
223
224 var yOptViews = [];
225 var num_axes = g.numAxes();
226 for (i = 0; i < num_axes; i++) {
227 // TODO(danvk): remove this use of a private API
228 yOptViews[i] = g.optionsViewForAxis_('y' + (i ? 1 + i : ''));
229 }
230 var showZeros = g.getOption("labelsShowZeroValues");
231 sepLines = g.getOption("labelsSeparateLines");
232 var highlightSeries = g.getHighlightSeries();
233 for (i = 0; i < sel_points.length; i++) {
234 var pt = sel_points[i];
235 if (pt.yval === 0 && !showZeros) continue;
236 if (!Dygraph.isOK(pt.canvasy)) continue;
237 if (sepLines) html += "<br/>";
238
239 var series = g.getPropertiesForSeries(pt.name);
240 var yOptView = yOptViews[series.axis - 1];
241 var fmtFunc = yOptView('valueFormatter');
242 var yval = fmtFunc(pt.yval, yOptView, pt.name, g);
243
244 var cls = (pt.name == highlightSeries) ? " class='highlight'" : "";
245
246 // TODO(danvk): use a template string here and make it an attribute.
247 html += "<span" + cls + ">" + " <b><span style='color: " + series.color + ";'>" +
29eb854d 248 pt.name + "</span></b>:&nbsp;" + yval + "</span>";
e2c21500
DV
249 }
250 return html;
251};
252
253
254/**
255 * Generates html for the "dash" displayed on the legend when using "legend: always".
256 * In particular, this works for dashed lines with any stroke pattern. It will
257 * try to scale the pattern to fit in 1em width. Or if small enough repeat the
258 * pattern for 1em width.
259 *
260 * @param strokePattern The pattern
261 * @param color The color of the series.
262 * @param oneEmWidth The width in pixels of 1em in the legend.
263 * @private
264 */
e8896dce 265generateLegendDashHTML = function(strokePattern, color, oneEmWidth) {
e2c21500
DV
266 // IE 7,8 fail at these divs, so they get boring legend, have not tested 9.
267 var isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
268 if (isIE) return "&mdash;";
269
270 // Easy, common case: a solid line
271 if (!strokePattern || strokePattern.length <= 1) {
272 return "<div style=\"display: inline-block; position: relative; " +
273 "bottom: .5ex; padding-left: 1em; height: 1px; " +
274 "border-bottom: 2px solid " + color + ";\"></div>";
275 }
276
277 var i, j, paddingLeft, marginRight;
278 var strokePixelLength = 0, segmentLoop = 0;
279 var normalizedPattern = [];
280 var loop;
281
282 // Compute the length of the pixels including the first segment twice,
283 // since we repeat it.
284 for (i = 0; i <= strokePattern.length; i++) {
285 strokePixelLength += strokePattern[i%strokePattern.length];
286 }
287
288 // See if we can loop the pattern by itself at least twice.
289 loop = Math.floor(oneEmWidth/(strokePixelLength-strokePattern[0]));
290 if (loop > 1) {
291 // This pattern fits at least two times, no scaling just convert to em;
292 for (i = 0; i < strokePattern.length; i++) {
293 normalizedPattern[i] = strokePattern[i]/oneEmWidth;
294 }
295 // Since we are repeating the pattern, we don't worry about repeating the
296 // first segment in one draw.
297 segmentLoop = normalizedPattern.length;
298 } else {
299 // If the pattern doesn't fit in the legend we scale it to fit.
300 loop = 1;
301 for (i = 0; i < strokePattern.length; i++) {
302 normalizedPattern[i] = strokePattern[i]/strokePixelLength;
303 }
304 // For the scaled patterns we do redraw the first segment.
305 segmentLoop = normalizedPattern.length+1;
306 }
307
308 // Now make the pattern.
309 var dash = "";
310 for (j = 0; j < loop; j++) {
311 for (i = 0; i < segmentLoop; i+=2) {
312 // The padding is the drawn segment.
313 paddingLeft = normalizedPattern[i%normalizedPattern.length];
314 if (i < strokePattern.length) {
315 // The margin is the space segment.
316 marginRight = normalizedPattern[(i+1)%normalizedPattern.length];
317 } else {
318 // The repeated first segment has no right margin.
319 marginRight = 0;
320 }
321 dash += "<div style=\"display: inline-block; position: relative; " +
322 "bottom: .5ex; margin-right: " + marginRight + "em; padding-left: " +
323 paddingLeft + "em; height: 1px; border-bottom: 2px solid " + color +
324 ";\"></div>";
325 }
326 }
327 return dash;
328};
329
330
331return legend;
332})();