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