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