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 this.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 legend
.prototype.select
= function(e
) {
124 var xValue
= e
.selectedX
;
125 var points
= e
.selectedPoints
;
127 var html
= generateLegendHTML(e
.dygraph
, xValue
, points
, this.one_em_width_
);
128 this.legend_div_
.innerHTML
= html
;
131 legend
.prototype.deselect
= function(e
) {
132 // Have to do this every time, since styles might have changed.
133 var oneEmWidth
= calculateEmWidthInDiv(this.legend_div_
);
134 this.one_em_width_
= oneEmWidth
;
136 var html
= generateLegendHTML(e
.dygraph
, undefined
, undefined
, oneEmWidth
);
137 this.legend_div_
.innerHTML
= html
;
140 legend
.prototype.didDrawChart
= function(e
) {
144 // Right edge should be flush with the right edge of the charting area (which
145 // may not be the same as the right edge of the div, if we have two y-axes.
146 // TODO(danvk): is any of this really necessary? Could just set "right" in "activate".
148 * Position the labels div so that:
149 * - its right edge is flush with the right edge of the charting area
150 * - its top edge is flush with the top edge of the charting area
153 legend
.prototype.predraw
= function(e
) {
154 // Don't touch a user-specified labelsDiv.
155 if (!this.is_generated_div_
) return;
157 // TODO(danvk): only use real APIs for this.
158 e
.dygraph
.graphDiv
.appendChild(this.legend_div_
);
159 var area
= e
.dygraph
.plotter_
.area
;
160 var labelsDivWidth
= e
.dygraph
.getOption("labelsDivWidth");
161 this.legend_div_
.style
.left
= area
.x
+ area
.w
- labelsDivWidth
- 1 + "px";
162 this.legend_div_
.style
.top
= area
.y
+ "px";
163 this.legend_div_
.style
.width
= labelsDivWidth
+ "px";
167 * Called when dygraph.destroy() is called.
168 * You should null out any references and detach any DOM elements.
170 legend
.prototype.destroy
= function() {
171 this.legend_div_
= null;
176 * Generates HTML for the legend which is displayed when hovering over the
177 * chart. If no selected points are specified, a default legend is returned
178 * (this may just be the empty string).
179 * @param { Number } [x] The x-value of the selected points.
180 * @param { [Object] } [sel_points] List of selected points for the given
181 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
182 * @param { Number } [oneEmWidth] The pixel width for 1em in the legend. Only
183 * relevant when displaying a legend with no selection (i.e. {legend:
184 * 'always'}) and with dashed lines.
186 generateLegendHTML
= function(g
, x
, sel_points
, oneEmWidth
) {
187 // TODO(danvk): deprecate this option in place of {legend: 'never'}
188 if (g
.getOption('showLabelsOnHighlight') !== true) return '';
190 // If no points are selected, we display a default legend. Traditionally,
191 // this has been blank. But a better default would be a conventional legend,
192 // which provides essential information for a non-interactive chart.
193 var html
, sepLines
, i
, dash
, strokePattern
;
194 var labels
= g
.getLabels();
196 if (typeof(x
) === 'undefined') {
197 if (g
.getOption('legend') != 'always') {
201 sepLines
= g
.getOption('labelsSeparateLines');
203 for (i
= 1; i
< labels
.length
; i
++) {
204 var series
= g
.getPropertiesForSeries(labels
[i
]);
205 if (!series
.visible
) continue;
207 if (html
!== '') html
+= (sepLines
? '<br/>' : ' ');
208 strokePattern
= g
.getOption("strokePattern", labels
[i
]);
209 dash
= generateLegendDashHTML(strokePattern
, series
.color
, oneEmWidth
);
210 html
+= "<span style='font-weight: bold; color: " + series
.color
+ ";'>" +
211 dash
+ " " + labels
[i
] + "</span>";
216 // TODO(danvk): remove this use of a private API
217 var xOptView
= g
.optionsViewForAxis_('x');
218 var xvf
= xOptView('valueFormatter');
219 html
= xvf(x
, xOptView
, labels
[0], g
);
225 var num_axes
= g
.numAxes();
226 for (i
= 0; i
< num_axes
; i
++) {
227 // TODO(danvk): remove this use of a private API
228 yOptViews
[i
] = g
.optionsViewForAxis_('y' + (i
? 1 + i
: ''));
230 var showZeros
= g
.getOption("labelsShowZeroValues");
231 sepLines
= g
.getOption("labelsSeparateLines");
232 var highlightSeries
= g
.getHighlightSeries();
233 for (i
= 0; i
< sel_points
.length
; i
++) {
234 var pt
= sel_points
[i
];
235 if (pt
.yval
=== 0 && !showZeros
) continue;
236 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
237 if (sepLines
) html
+= "<br/>";
239 var series
= g
.getPropertiesForSeries(pt
.name
);
240 var yOptView
= yOptViews
[series
.axis
- 1];
241 var fmtFunc
= yOptView('valueFormatter');
242 var yval
= fmtFunc(pt
.yval
, yOptView
, pt
.name
, g
);
244 var cls
= (pt
.name
== highlightSeries
) ? " class='highlight'" : "";
246 // TODO(danvk): use a template string here and make it an attribute.
247 html
+= "<span" + cls
+ ">" + " <b><span style='color: " + series
.color
+ ";'>" +
248 pt
.name
+ "</span></b>:" + yval
+ "</span>";
255 * Generates html for the "dash" displayed on the legend when using "legend: always".
256 * In particular, this works for dashed lines with any stroke pattern. It will
257 * try to scale the pattern to fit in 1em width. Or if small enough repeat the
258 * pattern for 1em width.
260 * @param strokePattern The pattern
261 * @param color The color of the series.
262 * @param oneEmWidth The width in pixels of 1em in the legend.
265 generateLegendDashHTML
= function(strokePattern
, color
, oneEmWidth
) {
266 // IE 7,8 fail at these divs, so they get boring legend, have not tested 9.
267 var isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
268 if (isIE
) return "—";
270 // Easy, common case: a solid line
271 if (!strokePattern
|| strokePattern
.length
<= 1) {
272 return "<div style=\"display: inline-block; position: relative; " +
273 "bottom: .5ex; padding-left: 1em; height: 1px; " +
274 "border-bottom: 2px solid " + color
+ ";\"></div>";
277 var i
, j
, paddingLeft
, marginRight
;
278 var strokePixelLength
= 0, segmentLoop
= 0;
279 var normalizedPattern
= [];
282 // Compute the length of the pixels including the first segment twice,
283 // since we repeat it.
284 for (i
= 0; i
<= strokePattern
.length
; i
++) {
285 strokePixelLength
+= strokePattern
[i
%strokePattern
.length
];
288 // See if we can loop the pattern by itself at least twice.
289 loop
= Math
.floor(oneEmWidth
/(strokePixelLength
-strokePattern
[0]));
291 // This pattern fits at least two times, no scaling just convert to em;
292 for (i
= 0; i
< strokePattern
.length
; i
++) {
293 normalizedPattern
[i
] = strokePattern
[i
]/oneEmWidth
;
295 // Since we are repeating the pattern, we don't worry about repeating the
296 // first segment in one draw.
297 segmentLoop
= normalizedPattern
.length
;
299 // If the pattern doesn't fit in the legend we scale it to fit.
301 for (i
= 0; i
< strokePattern
.length
; i
++) {
302 normalizedPattern
[i
] = strokePattern
[i
]/strokePixelLength
;
304 // For the scaled patterns we do redraw the first segment.
305 segmentLoop
= normalizedPattern
.length
+1;
308 // Now make the pattern.
310 for (j
= 0; j
< loop
; j
++) {
311 for (i
= 0; i
< segmentLoop
; i
+=2) {
312 // The padding is the drawn segment.
313 paddingLeft
= normalizedPattern
[i
%normalizedPattern
.length
];
314 if (i
< strokePattern
.length
) {
315 // The margin is the space segment.
316 marginRight
= normalizedPattern
[(i
+1)%normalizedPattern
.length
];
318 // The repeated first segment has no right margin.
321 dash
+= "<div style=\"display: inline-block; position: relative; " +
322 "bottom: .5ex; margin-right: " + marginRight
+ "em; padding-left: " +
323 paddingLeft
+ "em; height: 1px; border-bottom: 2px solid " + color
+