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