65ee6712976da9b55a1173083e7c9c4a53527aa2
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() {
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.
18 /*global Dygraph:false */
23 * Creates the legend, which appears when the user hovers over the chart.
24 * The legend can be either a user-specified or generated div.
28 var legend
= function() {
29 this.legend_div_
= null;
30 this.is_generated_div_
= false; // do we own this div, or was it user-specified?
33 legend
.prototype.toString
= function() {
34 return "Legend Plugin";
38 var generateLegendDashHTML
;
41 * This is called during the dygraph constructor, after options have been set
42 * but before the data is available.
44 * Proper tasks to do here include:
45 * - Reading your own options
47 * - Registering event listeners
49 * @param {Dygraph} g Graph instance.
50 * @return {object.<string, function(ev)>} Mapping of event names to callbacks.
52 legend
.prototype.activate
= function(g
) {
54 var divWidth
= g
.getOption('labelsDivWidth');
56 var userLabelsDiv
= g
.getOption('labelsDiv');
57 if (userLabelsDiv
&& null !== userLabelsDiv
) {
58 if (typeof(userLabelsDiv
) == "string" || userLabelsDiv
instanceof String
) {
59 div
= document
.getElementById(userLabelsDiv
);
64 // Default legend styles. These can be overridden in CSS by adding
65 // "!important" after your rule, e.g. "left: 30px !important;"
67 "position": "absolute",
70 "width": divWidth
+ "px",
72 "left": (g
.size().width
- divWidth
- 2) + "px",
73 "background": "white",
74 "lineHeight": "normal",
76 "overflow": "hidden"};
78 // TODO(danvk): get rid of labelsDivStyles? CSS is better.
79 Dygraph
.update(messagestyle
, g
.getOption('labelsDivStyles'));
80 div
= document
.createElement("div");
81 div
.className
= "dygraph-legend";
82 for (var name
in messagestyle
) {
83 if (!messagestyle
.hasOwnProperty(name
)) continue;
86 div
.style
[name
] = messagestyle
[name
];
88 console
.warn("You are using unsupported css properties for your " +
89 "browser in labelsDivStyles");
93 // TODO(danvk): come up with a cleaner way to expose this.
94 g
.graphDiv
.appendChild(div
);
95 this.is_generated_div_
= true;
98 this.legend_div_
= div
;
99 this.one_em_width_
= 10; // just a guess, will be updated.
103 deselect
: this.deselect
,
104 // TODO(danvk): rethink the name "predraw" before we commit to it in any API.
105 predraw
: this.predraw
,
106 didDrawChart
: this.didDrawChart
110 // Needed for dashed lines.
111 var calculateEmWidthInDiv
= function(div
) {
112 var sizeSpan
= document
.createElement('span');
113 sizeSpan
.setAttribute('style', 'margin: 0; padding: 0 0 0 1em; border: 0;');
114 div
.appendChild(sizeSpan
);
115 var oneEmWidth
=sizeSpan
.offsetWidth
;
116 div
.removeChild(sizeSpan
);
120 var escapeHTML
= function(str
) {
121 return str
.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
124 legend
.prototype.select
= function(e
) {
125 var xValue
= e
.selectedX
;
126 var points
= e
.selectedPoints
;
128 var legendMode
= e
.dygraph
.getOption('legend');
129 if (legendMode
=== 'never') {
130 this.legend_div_
.style
.display
= 'none';
134 if (legendMode
=== 'follow') {
135 // create floating legend div
136 var area
= e
.dygraph
.plotter_
.area
;
137 var labelsDivWidth
= e
.dygraph
.getOption('labelsDivWidth');
138 var yAxisLabelWidth
= e
.dygraph
.getOptionForAxis('axisLabelWidth', 'y');
139 // determine floating [left, top] coordinates of the legend div
140 // within the plotter_ area
141 // offset 20 px to the right and down from the first selection point
142 // 20 px is guess based on mouse cursor size
143 var leftLegend
= points
[0].x
* area
.w
+ 20;
144 var topLegend
= points
[0].y
* area
.h
- 20;
146 // if legend floats to end of the window area, it flips to the other
147 // side of the selection point
148 if ((leftLegend
+ labelsDivWidth
+ 1) > (window
.scrollX
+ window
.innerWidth
)) {
149 leftLegend
= leftLegend
- 2 * 20 - labelsDivWidth
- (yAxisLabelWidth
- area
.x
);
152 e
.dygraph
.graphDiv
.appendChild(this.legend_div_
);
153 this.legend_div_
.style
.left
= yAxisLabelWidth
+ leftLegend
+ "px";
154 this.legend_div_
.style
.top
= topLegend
+ "px";
157 var html
= legend
.generateLegendHTML(e
.dygraph
, xValue
, points
, this.one_em_width_
);
158 this.legend_div_
.innerHTML
= html
;
159 this.legend_div_
.style
.display
= '';
162 legend
.prototype.deselect
= function(e
) {
163 var legendMode
= e
.dygraph
.getOption('legend');
164 if (legendMode
!== 'always') {
165 this.legend_div_
.style
.display
= "none";
168 // Have to do this every time, since styles might have changed.
169 var oneEmWidth
= calculateEmWidthInDiv(this.legend_div_
);
170 this.one_em_width_
= oneEmWidth
;
172 var html
= legend
.generateLegendHTML(e
.dygraph
, undefined
, undefined
, oneEmWidth
);
173 this.legend_div_
.innerHTML
= html
;
176 legend
.prototype.didDrawChart
= function(e
) {
180 // Right edge should be flush with the right edge of the charting area (which
181 // may not be the same as the right edge of the div, if we have two y-axes.
182 // TODO(danvk): is any of this really necessary? Could just set "right" in "activate".
184 * Position the labels div so that:
185 * - its right edge is flush with the right edge of the charting area
186 * - its top edge is flush with the top edge of the charting area
189 legend
.prototype.predraw
= function(e
) {
190 // Don't touch a user-specified labelsDiv.
191 if (!this.is_generated_div_
) return;
193 // TODO(danvk): only use real APIs for this.
194 e
.dygraph
.graphDiv
.appendChild(this.legend_div_
);
195 var area
= e
.dygraph
.plotter_
.area
;
196 var labelsDivWidth
= e
.dygraph
.getOption("labelsDivWidth");
197 this.legend_div_
.style
.left
= area
.x
+ area
.w
- labelsDivWidth
- 1 + "px";
198 this.legend_div_
.style
.top
= area
.y
+ "px";
199 this.legend_div_
.style
.width
= labelsDivWidth
+ "px";
203 * Called when dygraph.destroy() is called.
204 * You should null out any references and detach any DOM elements.
206 legend
.prototype.destroy
= function() {
207 this.legend_div_
= null;
212 * Generates HTML for the legend which is displayed when hovering over the
213 * chart. If no selected points are specified, a default legend is returned
214 * (this may just be the empty string).
215 * @param { Number } [x] The x-value of the selected points.
216 * @param { [Object] } [sel_points] List of selected points for the given
217 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
218 * @param { Number } [oneEmWidth] The pixel width for 1em in the legend. Only
219 * relevant when displaying a legend with no selection (i.e. {legend:
220 * 'always'}) and with dashed lines.
222 legend
.generateLegendHTML
= function(g
, x
, sel_points
, oneEmWidth
) {
223 // TODO(danvk): deprecate this option in place of {legend: 'never'}
224 if (g
.getOption('showLabelsOnHighlight') !== true) return '';
226 // If no points are selected, we display a default legend. Traditionally,
227 // this has been blank. But a better default would be a conventional legend,
228 // which provides essential information for a non-interactive chart.
229 var html
, sepLines
, i
, dash
, strokePattern
;
230 var labels
= g
.getLabels();
232 if (typeof(x
) === 'undefined') {
233 if (g
.getOption('legend') != 'always') {
237 sepLines
= g
.getOption('labelsSeparateLines');
239 for (i
= 1; i
< labels
.length
; i
++) {
240 var series
= g
.getPropertiesForSeries(labels
[i
]);
241 if (!series
.visible
) continue;
243 if (html
!== '') html
+= (sepLines
? '<br/>' : ' ');
244 strokePattern
= g
.getOption("strokePattern", labels
[i
]);
245 dash
= generateLegendDashHTML(strokePattern
, series
.color
, oneEmWidth
);
246 html
+= "<span style='font-weight: bold; color: " + series
.color
+ ";'>" +
247 dash
+ " " + escapeHTML(labels
[i
]) + "</span>";
252 // TODO(danvk): remove this use of a private API
253 var xOptView
= g
.optionsViewForAxis_('x');
254 var xvf
= xOptView('valueFormatter');
255 html
= xvf(x
, xOptView
, labels
[0], g
);
261 var num_axes
= g
.numAxes();
262 for (i
= 0; i
< num_axes
; i
++) {
263 // TODO(danvk): remove this use of a private API
264 yOptViews
[i
] = g
.optionsViewForAxis_('y' + (i
? 1 + i
: ''));
266 var showZeros
= g
.getOption("labelsShowZeroValues");
267 sepLines
= g
.getOption("labelsSeparateLines");
268 var highlightSeries
= g
.getHighlightSeries();
269 for (i
= 0; i
< sel_points
.length
; i
++) {
270 var pt
= sel_points
[i
];
271 if (pt
.yval
=== 0 && !showZeros
) continue;
272 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
273 if (sepLines
) html
+= "<br/>";
275 var series
= g
.getPropertiesForSeries(pt
.name
);
276 var yOptView
= yOptViews
[series
.axis
- 1];
277 var fmtFunc
= yOptView('valueFormatter');
278 var yval
= fmtFunc(pt
.yval
, yOptView
, pt
.name
, g
);
280 var cls
= (pt
.name
== highlightSeries
) ? " class='highlight'" : "";
282 // TODO(danvk): use a template string here and make it an attribute.
283 html
+= "<span" + cls
+ ">" + " <b><span style='color: " + series
.color
+ ";'>" +
284 escapeHTML(pt
.name
) + "</span></b>: " + yval
+ "</span>";
291 * Generates html for the "dash" displayed on the legend when using "legend: always".
292 * In particular, this works for dashed lines with any stroke pattern. It will
293 * try to scale the pattern to fit in 1em width. Or if small enough repeat the
294 * pattern for 1em width.
296 * @param strokePattern The pattern
297 * @param color The color of the series.
298 * @param oneEmWidth The width in pixels of 1em in the legend.
301 generateLegendDashHTML
= function(strokePattern
, color
, oneEmWidth
) {
302 // IE 7,8 fail at these divs, so they get boring legend, have not tested 9.
303 var isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
304 if (isIE
) return "—";
306 // Easy, common case: a solid line
307 if (!strokePattern
|| strokePattern
.length
<= 1) {
308 return "<div style=\"display: inline-block; position: relative; " +
309 "bottom: .5ex; padding-left: 1em; height: 1px; " +
310 "border-bottom: 2px solid " + color
+ ";\"></div>";
313 var i
, j
, paddingLeft
, marginRight
;
314 var strokePixelLength
= 0, segmentLoop
= 0;
315 var normalizedPattern
= [];
318 // Compute the length of the pixels including the first segment twice,
319 // since we repeat it.
320 for (i
= 0; i
<= strokePattern
.length
; i
++) {
321 strokePixelLength
+= strokePattern
[i
%strokePattern
.length
];
324 // See if we can loop the pattern by itself at least twice.
325 loop
= Math
.floor(oneEmWidth
/(strokePixelLength
-strokePattern
[0]));
327 // This pattern fits at least two times, no scaling just convert to em;
328 for (i
= 0; i
< strokePattern
.length
; i
++) {
329 normalizedPattern
[i
] = strokePattern
[i
]/oneEmWidth
;
331 // Since we are repeating the pattern, we don't worry about repeating the
332 // first segment in one draw.
333 segmentLoop
= normalizedPattern
.length
;
335 // If the pattern doesn't fit in the legend we scale it to fit.
337 for (i
= 0; i
< strokePattern
.length
; i
++) {
338 normalizedPattern
[i
] = strokePattern
[i
]/strokePixelLength
;
340 // For the scaled patterns we do redraw the first segment.
341 segmentLoop
= normalizedPattern
.length
+1;
344 // Now make the pattern.
346 for (j
= 0; j
< loop
; j
++) {
347 for (i
= 0; i
< segmentLoop
; i
+=2) {
348 // The padding is the drawn segment.
349 paddingLeft
= normalizedPattern
[i
%normalizedPattern
.length
];
350 if (i
< strokePattern
.length
) {
351 // The margin is the space segment.
352 marginRight
= normalizedPattern
[(i
+1)%normalizedPattern
.length
];
354 // The repeated first segment has no right margin.
357 dash
+= "<div style=\"display: inline-block; position: relative; " +
358 "bottom: .5ex; margin-right: " + marginRight
+ "em; padding-left: " +
359 paddingLeft
+ "em; height: 1px; border-bottom: 2px solid " + color
+