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