3 * Copyright 2012 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
6 /*global Dygraph:false */
8 Dygraph
.Plugins
.Legend
= (function() {
11 Current bits of jankiness:
12 - Uses two private APIs:
13 1. Dygraph.optionsViewForAxis_
14 2. dygraph.plotter_.area
15 - Registers for a "predraw" event, which should be renamed.
16 - I call calculateEmWidthInDiv more often than needed.
20 /*jshint globalstrict: true */
21 /*global Dygraph:false */
26 * Creates the legend, which appears when the user hovers over the chart.
27 * The legend can be either a user-specified or generated div.
31 var legend
= function() {
32 this.legend_div_
= null;
33 this.is_generated_div_
= false; // do we own this div, or was it user-specified?
36 legend
.prototype.toString
= function() {
37 return "Legend Plugin";
41 var generateLegendHTML
, generateLegendDashHTML
;
44 * This is called during the dygraph constructor, after options have been set
45 * but before the data is available.
47 * Proper tasks to do here include:
48 * - Reading your own options
50 * - Registering event listeners
52 * @param {Dygraph} g Graph instance.
53 * @return {object.<string, function(ev)>} Mapping of event names to callbacks.
55 legend
.prototype.activate
= function(g
) {
57 var divWidth
= g
.getOption('labelsDivWidth');
59 var userLabelsDiv
= g
.getOption('labelsDiv');
60 if (userLabelsDiv
&& null !== userLabelsDiv
) {
61 if (typeof(userLabelsDiv
) == "string" || userLabelsDiv
instanceof String
) {
62 div
= document
.getElementById(userLabelsDiv
);
67 // Default legend styles. These can be overridden in CSS by adding
68 // "!important" after your rule, e.g. "left: 30px !important;"
70 "position": "absolute",
73 "width": divWidth
+ "px",
75 "left": (g
.size().width
- divWidth
- 2) + "px",
76 "background": "white",
77 "lineHeight": "normal",
79 "overflow": "hidden"};
81 // TODO(danvk): get rid of labelsDivStyles? CSS is better.
82 Dygraph
.update(messagestyle
, g
.getOption('labelsDivStyles'));
83 div
= document
.createElement("div");
84 div
.className
= "dygraph-legend";
85 for (var name
in messagestyle
) {
86 if (!messagestyle
.hasOwnProperty(name
)) continue;
89 div
.style
[name
] = messagestyle
[name
];
91 Dygraph
.warn("You are using unsupported css properties for your " +
92 "browser in labelsDivStyles");
96 // TODO(danvk): come up with a cleaner way to expose this.
97 g
.graphDiv
.appendChild(div
);
98 this.is_generated_div_
= true;
101 this.legend_div_
= div
;
102 this.one_em_width_
= 10; // just a guess, will be updated.
106 deselect
: this.deselect
,
107 // TODO(danvk): rethink the name "predraw" before we commit to it in any API.
108 predraw
: this.predraw
,
109 didDrawChart
: this.didDrawChart
113 // Needed for dashed lines.
114 var calculateEmWidthInDiv
= function(div
) {
115 var sizeSpan
= document
.createElement('span');
116 sizeSpan
.setAttribute('style', 'margin: 0; padding: 0 0 0 1em; border: 0;');
117 div
.appendChild(sizeSpan
);
118 var oneEmWidth
=sizeSpan
.offsetWidth
;
119 div
.removeChild(sizeSpan
);
123 var escapeHTML
= function(str
) {
124 return str
.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
127 legend
.prototype.select
= function(e
) {
128 var xValue
= e
.selectedX
;
129 var points
= e
.selectedPoints
;
131 var html
= generateLegendHTML(e
.dygraph
, xValue
, points
, this.one_em_width_
);
132 this.legend_div_
.innerHTML
= html
;
135 legend
.prototype.deselect
= function(e
) {
136 // Have to do this every time, since styles might have changed.
137 var oneEmWidth
= calculateEmWidthInDiv(this.legend_div_
);
138 this.one_em_width_
= oneEmWidth
;
140 var html
= generateLegendHTML(e
.dygraph
, undefined
, undefined
, oneEmWidth
);
141 this.legend_div_
.innerHTML
= html
;
144 legend
.prototype.didDrawChart
= function(e
) {
148 // Right edge should be flush with the right edge of the charting area (which
149 // may not be the same as the right edge of the div, if we have two y-axes.
150 // TODO(danvk): is any of this really necessary? Could just set "right" in "activate".
152 * Position the labels div so that:
153 * - its right edge is flush with the right edge of the charting area
154 * - its top edge is flush with the top edge of the charting area
157 legend
.prototype.predraw
= function(e
) {
158 // Don't touch a user-specified labelsDiv.
159 if (!this.is_generated_div_
) return;
161 // TODO(danvk): only use real APIs for this.
162 e
.dygraph
.graphDiv
.appendChild(this.legend_div_
);
163 var area
= e
.dygraph
.plotter_
.area
;
164 var labelsDivWidth
= e
.dygraph
.getOption("labelsDivWidth");
165 this.legend_div_
.style
.left
= area
.x
+ area
.w
- labelsDivWidth
- 1 + "px";
166 this.legend_div_
.style
.top
= area
.y
+ "px";
167 this.legend_div_
.style
.width
= labelsDivWidth
+ "px";
171 * Called when dygraph.destroy() is called.
172 * You should null out any references and detach any DOM elements.
174 legend
.prototype.destroy
= function() {
175 this.legend_div_
= null;
180 * Generates HTML for the legend which is displayed when hovering over the
181 * chart. If no selected points are specified, a default legend is returned
182 * (this may just be the empty string).
183 * @param { Number } [x] The x-value of the selected points.
184 * @param { [Object] } [sel_points] List of selected points for the given
185 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
186 * @param { Number } [oneEmWidth] The pixel width for 1em in the legend. Only
187 * relevant when displaying a legend with no selection (i.e. {legend:
188 * 'always'}) and with dashed lines.
190 generateLegendHTML
= function(g
, x
, sel_points
, oneEmWidth
) {
191 // TODO(danvk): deprecate this option in place of {legend: 'never'}
192 if (g
.getOption('showLabelsOnHighlight') !== true) return '';
194 // If no points are selected, we display a default legend. Traditionally,
195 // this has been blank. But a better default would be a conventional legend,
196 // which provides essential information for a non-interactive chart.
197 var html
, sepLines
, i
, dash
, strokePattern
;
198 var labels
= g
.getLabels();
200 if (typeof(x
) === 'undefined') {
201 if (g
.getOption('legend') != 'always') {
205 sepLines
= g
.getOption('labelsSeparateLines');
207 for (i
= 1; i
< labels
.length
; i
++) {
208 var series
= g
.getPropertiesForSeries(labels
[i
]);
209 if (!series
.visible
) continue;
211 if (html
!== '') html
+= (sepLines
? '<br/>' : ' ');
212 strokePattern
= g
.getOption("strokePattern", labels
[i
]);
213 dash
= generateLegendDashHTML(strokePattern
, series
.color
, oneEmWidth
);
214 html
+= "<span style='font-weight: bold; color: " + series
.color
+ ";'>" +
215 dash
+ " " + escapeHTML(labels
[i
]) + "</span>";
220 // TODO(danvk): remove this use of a private API
221 var xOptView
= g
.optionsViewForAxis_('x');
222 var xvf
= xOptView('valueFormatter');
223 html
= xvf(x
, xOptView
, labels
[0], g
);
229 var num_axes
= g
.numAxes();
230 for (i
= 0; i
< num_axes
; i
++) {
231 // TODO(danvk): remove this use of a private API
232 yOptViews
[i
] = g
.optionsViewForAxis_('y' + (i
? 1 + i
: ''));
234 var showZeros
= g
.getOption("labelsShowZeroValues");
235 sepLines
= g
.getOption("labelsSeparateLines");
236 var highlightSeries
= g
.getHighlightSeries();
237 for (i
= 0; i
< sel_points
.length
; i
++) {
238 var pt
= sel_points
[i
];
239 if (pt
.yval
=== 0 && !showZeros
) continue;
240 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
241 if (sepLines
) html
+= "<br/>";
243 var series
= g
.getPropertiesForSeries(pt
.name
);
244 var yOptView
= yOptViews
[series
.axis
- 1];
245 var fmtFunc
= yOptView('valueFormatter');
246 var yval
= fmtFunc(pt
.yval
, yOptView
, pt
.name
, g
);
248 var cls
= (pt
.name
== highlightSeries
) ? " class='highlight'" : "";
250 // TODO(danvk): use a template string here and make it an attribute.
251 html
+= "<span" + cls
+ ">" + " <b><span style='color: " + series
.color
+ ";'>" +
252 escapeHTML(pt
.name
) + "</span></b>: " + yval
+ "</span>";
259 * Generates html for the "dash" displayed on the legend when using "legend: always".
260 * In particular, this works for dashed lines with any stroke pattern. It will
261 * try to scale the pattern to fit in 1em width. Or if small enough repeat the
262 * pattern for 1em width.
264 * @param strokePattern The pattern
265 * @param color The color of the series.
266 * @param oneEmWidth The width in pixels of 1em in the legend.
269 generateLegendDashHTML
= function(strokePattern
, color
, oneEmWidth
) {
270 // IE 7,8 fail at these divs, so they get boring legend, have not tested 9.
271 var isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
272 if (isIE
) return "—";
274 // Easy, common case: a solid line
275 if (!strokePattern
|| strokePattern
.length
<= 1) {
276 return "<div style=\"display: inline-block; position: relative; " +
277 "bottom: .5ex; padding-left: 1em; height: 1px; " +
278 "border-bottom: 2px solid " + color
+ ";\"></div>";
281 var i
, j
, paddingLeft
, marginRight
;
282 var strokePixelLength
= 0, segmentLoop
= 0;
283 var normalizedPattern
= [];
286 // Compute the length of the pixels including the first segment twice,
287 // since we repeat it.
288 for (i
= 0; i
<= strokePattern
.length
; i
++) {
289 strokePixelLength
+= strokePattern
[i
%strokePattern
.length
];
292 // See if we can loop the pattern by itself at least twice.
293 loop
= Math
.floor(oneEmWidth
/(strokePixelLength
-strokePattern
[0]));
295 // This pattern fits at least two times, no scaling just convert to em;
296 for (i
= 0; i
< strokePattern
.length
; i
++) {
297 normalizedPattern
[i
] = strokePattern
[i
]/oneEmWidth
;
299 // Since we are repeating the pattern, we don't worry about repeating the
300 // first segment in one draw.
301 segmentLoop
= normalizedPattern
.length
;
303 // If the pattern doesn't fit in the legend we scale it to fit.
305 for (i
= 0; i
< strokePattern
.length
; i
++) {
306 normalizedPattern
[i
] = strokePattern
[i
]/strokePixelLength
;
308 // For the scaled patterns we do redraw the first segment.
309 segmentLoop
= normalizedPattern
.length
+1;
312 // Now make the pattern.
314 for (j
= 0; j
< loop
; j
++) {
315 for (i
= 0; i
< segmentLoop
; i
+=2) {
316 // The padding is the drawn segment.
317 paddingLeft
= normalizedPattern
[i
%normalizedPattern
.length
];
318 if (i
< strokePattern
.length
) {
319 // The margin is the space segment.
320 marginRight
= normalizedPattern
[(i
+1)%normalizedPattern
.length
];
322 // The repeated first segment has no right margin.
325 dash
+= "<div style=\"display: inline-block; position: relative; " +
326 "bottom: .5ex; margin-right: " + marginRight
+ "em; padding-left: " +
327 paddingLeft
+ "em; height: 1px; border-bottom: 2px solid " + color
+