3 * Copyright 2012 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
7 Dygraph
.Plugins
.Legend
= (function() {
10 Current 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.
19 /*jshint globalstrict: true */
20 /*global Dygraph:false */
25 * Creates the legend, which appears when the user hovers over the chart.
26 * The legend can be either a user-specified or generated div.
30 var legend
= function() {
31 this.legend_div_
= null;
32 this.is_generated_div_
= false; // do we own this div, or was it user-specified?
35 legend
.prototype.toString
= function() {
36 return "Legend Plugin";
40 var generateLegendHTML
, generateLegendDashHTML
;
43 * This is called during the dygraph constructor, after options have been set
44 * but before the data is available.
46 * Proper tasks to do here include:
47 * - Reading your own options
49 * - Registering event listeners
51 * @param {Dygraph} g Graph instance.
52 * @return {object.<string, function(ev)>} Mapping of event names to callbacks.
54 legend
.prototype.activate
= function(g
) {
56 var divWidth
= g
.getOption('labelsDivWidth');
58 var userLabelsDiv
= g
.getOption('labelsDiv');
59 if (userLabelsDiv
&& null !== userLabelsDiv
) {
60 if (typeof(userLabelsDiv
) == "string" || userLabelsDiv
instanceof String
) {
61 div
= document
.getElementById(userLabelsDiv
);
66 // Default legend styles. These can be overridden in CSS by adding
67 // "!important" after your rule, e.g. "left: 30px !important;"
69 "position": "absolute",
72 "width": divWidth
+ "px",
74 "left": (g
.size().width
- divWidth
- 2) + "px",
75 "background": "white",
76 "lineHeight": "normal",
78 "overflow": "hidden"};
80 // TODO(danvk): get rid of labelsDivStyles? CSS is better.
81 Dygraph
.update(messagestyle
, g
.getOption('labelsDivStyles'));
82 div
= document
.createElement("div");
83 div
.className
= "dygraph-legend";
84 for (var name
in messagestyle
) {
85 if (!messagestyle
.hasOwnProperty(name
)) continue;
88 div
.style
[name
] = messagestyle
[name
];
90 this.warn("You are using unsupported css properties for your " +
91 "browser in labelsDivStyles");
95 // TODO(danvk): come up with a cleaner way to expose this.
96 g
.graphDiv
.appendChild(div
);
97 this.is_generated_div_
= true;
100 this.legend_div_
= div
;
101 this.one_em_width_
= 10; // just a guess, will be updated.
105 deselect
: this.deselect
,
106 // TODO(danvk): rethink the name "predraw" before we commit to it in any API.
107 predraw
: this.predraw
,
108 didDrawChart
: this.didDrawChart
112 // Needed for dashed lines.
113 var calculateEmWidthInDiv
= function(div
) {
114 var sizeSpan
= document
.createElement('span');
115 sizeSpan
.setAttribute('style', 'margin: 0; padding: 0 0 0 1em; border: 0;');
116 div
.appendChild(sizeSpan
);
117 var oneEmWidth
=sizeSpan
.offsetWidth
;
118 div
.removeChild(sizeSpan
);
122 legend
.prototype.select
= function(e
) {
123 var xValue
= e
.selectedX
;
124 var points
= e
.selectedPoints
;
126 var html
= generateLegendHTML(e
.dygraph
, xValue
, points
, this.one_em_width_
);
127 this.legend_div_
.innerHTML
= html
;
130 legend
.prototype.deselect
= function(e
) {
131 // Have to do this every time, since styles might have changed.
132 var oneEmWidth
= calculateEmWidthInDiv(this.legend_div_
);
133 this.one_em_width_
= oneEmWidth
;
135 var html
= generateLegendHTML(e
.dygraph
, undefined
, undefined
, oneEmWidth
);
136 this.legend_div_
.innerHTML
= html
;
139 legend
.prototype.didDrawChart
= function(e
) {
143 // Right edge should be flush with the right edge of the charting area (which
144 // may not be the same as the right edge of the div, if we have two y-axes.
145 // TODO(danvk): is any of this really necessary? Could just set "right" in "activate".
147 * Position the labels div so that:
148 * - its right edge is flush with the right edge of the charting area
149 * - its top edge is flush with the top edge of the charting area
152 legend
.prototype.predraw
= function(e
) {
153 // Don't touch a user-specified labelsDiv.
154 if (!this.is_generated_div_
) return;
156 // TODO(danvk): only use real APIs for this.
157 e
.dygraph
.graphDiv
.appendChild(this.legend_div_
);
158 var area
= e
.dygraph
.plotter_
.area
;
159 var labelsDivWidth
= e
.dygraph
.getOption("labelsDivWidth");
160 this.legend_div_
.style
.left
= area
.x
+ area
.w
- labelsDivWidth
- 1 + "px";
161 this.legend_div_
.style
.top
= area
.y
+ "px";
162 this.legend_div_
.style
.width
= labelsDivWidth
+ "px";
166 * Called when dygraph.destroy() is called.
167 * You should null out any references and detach any DOM elements.
169 legend
.prototype.destroy
= function() {
170 this.legend_div_
= null;
175 * Generates HTML for the legend which is displayed when hovering over the
176 * chart. If no selected points are specified, a default legend is returned
177 * (this may just be the empty string).
178 * @param { Number } [x] The x-value of the selected points.
179 * @param { [Object] } [sel_points] List of selected points for the given
180 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
181 * @param { Number } [oneEmWidth] The pixel width for 1em in the legend. Only
182 * relevant when displaying a legend with no selection (i.e. {legend:
183 * 'always'}) and with dashed lines.
185 generateLegendHTML
= function(g
, x
, sel_points
, oneEmWidth
) {
186 // TODO(danvk): deprecate this option in place of {legend: 'never'}
187 if (g
.getOption('showLabelsOnHighlight') !== true) return '';
189 // If no points are selected, we display a default legend. Traditionally,
190 // this has been blank. But a better default would be a conventional legend,
191 // which provides essential information for a non-interactive chart.
192 var html
, sepLines
, i
, c
, dash
, strokePattern
;
193 var labels
= g
.getLabels();
195 if (typeof(x
) === 'undefined') {
196 if (g
.getOption('legend') != 'always') {
200 sepLines
= g
.getOption('labelsSeparateLines');
202 for (i
= 1; i
< labels
.length
; i
++) {
203 var series
= g
.getPropertiesForSeries(labels
[i
]);
204 if (!series
.visible
) continue;
206 if (html
!== '') html
+= (sepLines
? '<br/>' : ' ');
207 strokePattern
= g
.getOption("strokePattern", labels
[i
]);
208 dash
= generateLegendDashHTML(strokePattern
, series
.color
, oneEmWidth
);
209 html
+= "<span style='font-weight: bold; color: " + series
.color
+ ";'>" +
210 dash
+ " " + labels
[i
] + "</span>";
215 // TODO(danvk): remove this use of a private API
216 var xOptView
= g
.optionsViewForAxis_('x');
217 var xvf
= xOptView('valueFormatter');
218 html
= xvf(x
, xOptView
, labels
[0], g
);
224 var num_axes
= g
.numAxes();
225 for (i
= 0; i
< num_axes
; i
++) {
226 // TODO(danvk): remove this use of a private API
227 yOptViews
[i
] = g
.optionsViewForAxis_('y' + (i
? 1 + i
: ''));
229 var showZeros
= g
.getOption("labelsShowZeroValues");
230 sepLines
= g
.getOption("labelsSeparateLines");
231 var highlightSeries
= g
.getHighlightSeries();
232 for (i
= 0; i
< sel_points
.length
; i
++) {
233 var pt
= sel_points
[i
];
234 if (pt
.yval
=== 0 && !showZeros
) continue;
235 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
236 if (sepLines
) html
+= "<br/>";
238 var series
= g
.getPropertiesForSeries(pt
.name
);
239 var yOptView
= yOptViews
[series
.axis
- 1];
240 var fmtFunc
= yOptView('valueFormatter');
241 var yval
= fmtFunc(pt
.yval
, yOptView
, pt
.name
, g
);
243 var cls
= (pt
.name
== highlightSeries
) ? " class='highlight'" : "";
245 // TODO(danvk): use a template string here and make it an attribute.
246 html
+= "<span" + cls
+ ">" + " <b><span style='color: " + series
.color
+ ";'>" +
247 pt
.name
+ "</span></b>:" + yval
+ "</span>";
254 * Generates html for the "dash" displayed on the legend when using "legend: always".
255 * In particular, this works for dashed lines with any stroke pattern. It will
256 * try to scale the pattern to fit in 1em width. Or if small enough repeat the
257 * pattern for 1em width.
259 * @param strokePattern The pattern
260 * @param color The color of the series.
261 * @param oneEmWidth The width in pixels of 1em in the legend.
264 generateLegendDashHTML
= function(strokePattern
, color
, oneEmWidth
) {
265 // IE 7,8 fail at these divs, so they get boring legend, have not tested 9.
266 var isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
267 if (isIE
) return "—";
269 // Easy, common case: a solid line
270 if (!strokePattern
|| strokePattern
.length
<= 1) {
271 return "<div style=\"display: inline-block; position: relative; " +
272 "bottom: .5ex; padding-left: 1em; height: 1px; " +
273 "border-bottom: 2px solid " + color
+ ";\"></div>";
276 var i
, j
, paddingLeft
, marginRight
;
277 var strokePixelLength
= 0, segmentLoop
= 0;
278 var normalizedPattern
= [];
281 // Compute the length of the pixels including the first segment twice,
282 // since we repeat it.
283 for (i
= 0; i
<= strokePattern
.length
; i
++) {
284 strokePixelLength
+= strokePattern
[i
%strokePattern
.length
];
287 // See if we can loop the pattern by itself at least twice.
288 loop
= Math
.floor(oneEmWidth
/(strokePixelLength
-strokePattern
[0]));
290 // This pattern fits at least two times, no scaling just convert to em;
291 for (i
= 0; i
< strokePattern
.length
; i
++) {
292 normalizedPattern
[i
] = strokePattern
[i
]/oneEmWidth
;
294 // Since we are repeating the pattern, we don't worry about repeating the
295 // first segment in one draw.
296 segmentLoop
= normalizedPattern
.length
;
298 // If the pattern doesn't fit in the legend we scale it to fit.
300 for (i
= 0; i
< strokePattern
.length
; i
++) {
301 normalizedPattern
[i
] = strokePattern
[i
]/strokePixelLength
;
303 // For the scaled patterns we do redraw the first segment.
304 segmentLoop
= normalizedPattern
.length
+1;
307 // Now make the pattern.
309 for (j
= 0; j
< loop
; j
++) {
310 for (i
= 0; i
< segmentLoop
; i
+=2) {
311 // The padding is the drawn segment.
312 paddingLeft
= normalizedPattern
[i
%normalizedPattern
.length
];
313 if (i
< strokePattern
.length
) {
314 // The margin is the space segment.
315 marginRight
= normalizedPattern
[(i
+1)%normalizedPattern
.length
];
317 // The repeated first segment has no right margin.
320 dash
+= "<div style=\"display: inline-block; position: relative; " +
321 "bottom: .5ex; margin-right: " + marginRight
+ "em; padding-left: " +
322 paddingLeft
+ "em; height: 1px; border-bottom: 2px solid " + color
+