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