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 if(e
.dygraph
.getOption("legendFollow")) {
132 // create floating legend div
133 var area
= e
.dygraph
.plotter_
.area
;
134 var labelsDivWidth
= e
.dygraph
.getOption("labelsDivWidth");
135 var yAxisLabelWidth
= e
.dygraph
.getOption("yAxisLabelWidth");
136 // determine floating [left, top] coordinates of the legend div
137 // within the plotter_ area
138 // offset 20 px to the left and down from the first selection point
139 // 20 px is guess based on mouse cursor size
140 var leftLegend
= points
[0].x
* area
.w
+ 20;
141 var topLegend
= points
[0].y
* area
.h
- 20;
143 // if legend floats to end of the plotting area, it flips to the other
144 // side of the selection point
145 if((leftLegend
+ labelsDivWidth
+ 1) > area
.w
) {
146 leftLegend
= leftLegend
- 2*20 - labelsDivWidth
- (yAxisLabelWidth
- area
.x
);
149 e
.dygraph
.graphDiv
.appendChild(this.legend_div_
);
150 this.legend_div_
.style
.left
= yAxisLabelWidth
+ leftLegend
+ "px";
151 this.legend_div_
.style
.top
= topLegend
+ "px";
154 var html
= generateLegendHTML(e
.dygraph
, xValue
, points
, this.one_em_width_
);
155 this.legend_div_
.innerHTML
= html
;
158 legend
.prototype.deselect
= function(e
) {
160 if(e
.dygraph
.getOption("legendFollow")) {
161 // return legend to the default non-floating position
165 // Have to do this every time, since styles might have changed.
166 var oneEmWidth
= calculateEmWidthInDiv(this.legend_div_
);
167 this.one_em_width_
= oneEmWidth
;
169 var html
= generateLegendHTML(e
.dygraph
, undefined
, undefined
, oneEmWidth
);
170 this.legend_div_
.innerHTML
= html
;
173 legend
.prototype.didDrawChart
= function(e
) {
177 // Right edge should be flush with the right edge of the charting area (which
178 // may not be the same as the right edge of the div, if we have two y-axes.
179 // TODO(danvk): is any of this really necessary? Could just set "right" in "activate".
181 * Position the labels div so that:
182 * - its right edge is flush with the right edge of the charting area
183 * - its top edge is flush with the top edge of the charting area
186 legend
.prototype.predraw
= function(e
) {
187 // Don't touch a user-specified labelsDiv.
188 if (!this.is_generated_div_
) return;
190 // TODO(danvk): only use real APIs for this.
191 e
.dygraph
.graphDiv
.appendChild(this.legend_div_
);
192 var area
= e
.dygraph
.plotter_
.area
;
193 var labelsDivWidth
= e
.dygraph
.getOption("labelsDivWidth");
194 this.legend_div_
.style
.left
= area
.x
+ area
.w
- labelsDivWidth
- 1 + "px";
195 this.legend_div_
.style
.top
= area
.y
+ "px";
196 this.legend_div_
.style
.width
= labelsDivWidth
+ "px";
200 * Called when dygraph.destroy() is called.
201 * You should null out any references and detach any DOM elements.
203 legend
.prototype.destroy
= function() {
204 this.legend_div_
= null;
209 * Generates HTML for the legend which is displayed when hovering over the
210 * chart. If no selected points are specified, a default legend is returned
211 * (this may just be the empty string).
212 * @param { Number } [x] The x-value of the selected points.
213 * @param { [Object] } [sel_points] List of selected points for the given
214 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
215 * @param { Number } [oneEmWidth] The pixel width for 1em in the legend. Only
216 * relevant when displaying a legend with no selection (i.e. {legend:
217 * 'always'}) and with dashed lines.
219 generateLegendHTML
= function(g
, x
, sel_points
, oneEmWidth
) {
220 // TODO(danvk): deprecate this option in place of {legend: 'never'}
221 if (g
.getOption('showLabelsOnHighlight') !== true) return '';
223 // If no points are selected, we display a default legend. Traditionally,
224 // this has been blank. But a better default would be a conventional legend,
225 // which provides essential information for a non-interactive chart.
226 var html
, sepLines
, i
, dash
, strokePattern
;
227 var labels
= g
.getLabels();
229 if (typeof(x
) === 'undefined') {
230 if (g
.getOption('legend') != 'always') {
234 sepLines
= g
.getOption('labelsSeparateLines');
236 for (i
= 1; i
< labels
.length
; i
++) {
237 var series
= g
.getPropertiesForSeries(labels
[i
]);
238 if (!series
.visible
) continue;
240 if (html
!== '') html
+= (sepLines
? '<br/>' : ' ');
241 strokePattern
= g
.getOption("strokePattern", labels
[i
]);
242 dash
= generateLegendDashHTML(strokePattern
, series
.color
, oneEmWidth
);
243 html
+= "<span style='font-weight: bold; color: " + series
.color
+ ";'>" +
244 dash
+ " " + escapeHTML(labels
[i
]) + "</span>";
249 // TODO(danvk): remove this use of a private API
250 var xOptView
= g
.optionsViewForAxis_('x');
251 var xvf
= xOptView('valueFormatter');
252 html
= xvf(x
, xOptView
, labels
[0], g
);
258 var num_axes
= g
.numAxes();
259 for (i
= 0; i
< num_axes
; i
++) {
260 // TODO(danvk): remove this use of a private API
261 yOptViews
[i
] = g
.optionsViewForAxis_('y' + (i
? 1 + i
: ''));
263 var showZeros
= g
.getOption("labelsShowZeroValues");
264 sepLines
= g
.getOption("labelsSeparateLines");
265 var highlightSeries
= g
.getHighlightSeries();
266 for (i
= 0; i
< sel_points
.length
; i
++) {
267 var pt
= sel_points
[i
];
268 if (pt
.yval
=== 0 && !showZeros
) continue;
269 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
270 if (sepLines
) html
+= "<br/>";
272 var series
= g
.getPropertiesForSeries(pt
.name
);
273 var yOptView
= yOptViews
[series
.axis
- 1];
274 var fmtFunc
= yOptView('valueFormatter');
275 var yval
= fmtFunc(pt
.yval
, yOptView
, pt
.name
, g
);
277 var cls
= (pt
.name
== highlightSeries
) ? " class='highlight'" : "";
279 // TODO(danvk): use a template string here and make it an attribute.
280 html
+= "<span" + cls
+ ">" + " <b><span style='color: " + series
.color
+ ";'>" +
281 escapeHTML(pt
.name
) + "</span></b>: " + yval
+ "</span>";
288 * Generates html for the "dash" displayed on the legend when using "legend: always".
289 * In particular, this works for dashed lines with any stroke pattern. It will
290 * try to scale the pattern to fit in 1em width. Or if small enough repeat the
291 * pattern for 1em width.
293 * @param strokePattern The pattern
294 * @param color The color of the series.
295 * @param oneEmWidth The width in pixels of 1em in the legend.
298 generateLegendDashHTML
= function(strokePattern
, color
, oneEmWidth
) {
299 // IE 7,8 fail at these divs, so they get boring legend, have not tested 9.
300 var isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
301 if (isIE
) return "—";
303 // Easy, common case: a solid line
304 if (!strokePattern
|| strokePattern
.length
<= 1) {
305 return "<div style=\"display: inline-block; position: relative; " +
306 "bottom: .5ex; padding-left: 1em; height: 1px; " +
307 "border-bottom: 2px solid " + color
+ ";\"></div>";
310 var i
, j
, paddingLeft
, marginRight
;
311 var strokePixelLength
= 0, segmentLoop
= 0;
312 var normalizedPattern
= [];
315 // Compute the length of the pixels including the first segment twice,
316 // since we repeat it.
317 for (i
= 0; i
<= strokePattern
.length
; i
++) {
318 strokePixelLength
+= strokePattern
[i
%strokePattern
.length
];
321 // See if we can loop the pattern by itself at least twice.
322 loop
= Math
.floor(oneEmWidth
/(strokePixelLength
-strokePattern
[0]));
324 // This pattern fits at least two times, no scaling just convert to em;
325 for (i
= 0; i
< strokePattern
.length
; i
++) {
326 normalizedPattern
[i
] = strokePattern
[i
]/oneEmWidth
;
328 // Since we are repeating the pattern, we don't worry about repeating the
329 // first segment in one draw.
330 segmentLoop
= normalizedPattern
.length
;
332 // If the pattern doesn't fit in the legend we scale it to fit.
334 for (i
= 0; i
< strokePattern
.length
; i
++) {
335 normalizedPattern
[i
] = strokePattern
[i
]/strokePixelLength
;
337 // For the scaled patterns we do redraw the first segment.
338 segmentLoop
= normalizedPattern
.length
+1;
341 // Now make the pattern.
343 for (j
= 0; j
< loop
; j
++) {
344 for (i
= 0; i
< segmentLoop
; i
+=2) {
345 // The padding is the drawn segment.
346 paddingLeft
= normalizedPattern
[i
%normalizedPattern
.length
];
347 if (i
< strokePattern
.length
) {
348 // The margin is the space segment.
349 marginRight
= normalizedPattern
[(i
+1)%normalizedPattern
.length
];
351 // The repeated first segment has no right margin.
354 dash
+= "<div style=\"display: inline-block; position: relative; " +
355 "bottom: .5ex; margin-right: " + marginRight
+ "em; padding-left: " +
356 paddingLeft
+ "em; height: 1px; border-bottom: 2px solid " + color
+