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