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