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.
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 * This is called during the dygraph constructor, after options have been set
39 * but before the data is available.
41 * Proper tasks to do here include:
42 * - Reading your own options
44 * - Registering event listeners
46 * @param {Dygraph} g Graph instance.
47 * @return {object.<string, function(ev)>} Mapping of event names to callbacks.
49 legend
.prototype.activate
= function(g
) {
51 var divWidth
= g
.getOption('labelsDivWidth');
53 var userLabelsDiv
= g
.getOption('labelsDiv');
54 if (userLabelsDiv
&& null !== userLabelsDiv
) {
55 if (typeof(userLabelsDiv
) == "string" || userLabelsDiv
instanceof String
) {
56 div
= document
.getElementById(userLabelsDiv
);
61 // Default legend styles. These can be overridden in CSS by adding
62 // "!important" after your rule, e.g. "left: 30px !important;"
64 "position": "absolute",
67 "width": divWidth
+ "px",
69 "left": (g
.size().width
- divWidth
- 2) + "px",
70 "background": "white",
71 "lineHeight": "normal",
73 "overflow": "hidden"};
75 // TODO(danvk): get rid of labelsDivStyles? CSS is better.
76 Dygraph
.update(messagestyle
, g
.getOption('labelsDivStyles'));
77 div
= document
.createElement("div");
78 div
.className
= "dygraph-legend";
79 for (var name
in messagestyle
) {
80 if (!messagestyle
.hasOwnProperty(name
)) continue;
83 div
.style
[name
] = messagestyle
[name
];
85 this.warn("You are using unsupported css properties for your " +
86 "browser in labelsDivStyles");
90 // TODO(danvk): come up with a cleaner way to expose this.
91 g
.graphDiv
.appendChild(div
);
92 this.is_generated_div_
= true;
95 this.legend_div_
= div
;
96 this.one_em_width_
= 10; // just a guess, will be updated.
100 deselect
: this.deselect
,
101 // TODO(danvk): rethink the name "predraw" before we commit to it in any API.
102 predraw
: this.predraw
,
103 didDrawChart
: this.didDrawChart
107 // Needed for dashed lines.
108 var calculateEmWidthInDiv
= function(div
) {
109 var sizeSpan
= document
.createElement('span');
110 sizeSpan
.setAttribute('style', 'margin: 0; padding: 0 0 0 1em; border: 0;');
111 div
.appendChild(sizeSpan
);
112 var oneEmWidth
=sizeSpan
.offsetWidth
;
113 div
.removeChild(sizeSpan
);
117 legend
.prototype.select
= function(e
) {
118 var xValue
= e
.selectedX
;
119 var points
= e
.selectedPoints
;
121 var html
= generateLegendHTML(e
.dygraph
, xValue
, points
, this.one_em_width_
);
122 this.legend_div_
.innerHTML
= html
;
125 legend
.prototype.deselect
= function(e
) {
126 // Have to do this every time, since styles might have changed.
127 var oneEmWidth
= calculateEmWidthInDiv(this.legend_div_
);
128 this.one_em_width_
= oneEmWidth
;
130 var html
= generateLegendHTML(e
.dygraph
, undefined
, undefined
, oneEmWidth
);
131 this.legend_div_
.innerHTML
= html
;
134 legend
.prototype.didDrawChart
= function(e
) {
138 // Right edge should be flush with the right edge of the charting area (which
139 // may not be the same as the right edge of the div, if we have two y-axes.
140 // TODO(danvk): is any of this really necessary? Could just set "right" in "activate".
142 * Position the labels div so that:
143 * - its right edge is flush with the right edge of the charting area
144 * - its top edge is flush with the top edge of the charting area
147 legend
.prototype.predraw
= function(e
) {
148 // Don't touch a user-specified labelsDiv.
149 if (!this.is_generated_div_
) return;
151 // TODO(danvk): only use real APIs for this.
152 e
.dygraph
.graphDiv
.appendChild(this.legend_div_
);
153 var area
= e
.dygraph
.plotter_
.area
;
154 this.legend_div_
.style
.left
= area
.x
+ area
.w
- e
.dygraph
.getOption("labelsDivWidth") - 1 + "px";
155 this.legend_div_
.style
.top
= area
.y
+ "px";
159 * Called when dygraph.destroy() is called.
160 * You should null out any references and detach any DOM elements.
162 legend
.prototype.destroy
= function() {
163 this.legend_div_
= null;
168 * Generates HTML for the legend which is displayed when hovering over the
169 * chart. If no selected points are specified, a default legend is returned
170 * (this may just be the empty string).
171 * @param { Number } [x] The x-value of the selected points.
172 * @param { [Object] } [sel_points] List of selected points for the given
173 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
174 * @param { Number } [oneEmWidth] The pixel width for 1em in the legend. Only
175 * relevant when displaying a legend with no selection (i.e. {legend:
176 * 'always'}) and with dashed lines.
178 var generateLegendHTML
= function(g
, x
, sel_points
, oneEmWidth
) {
179 // TODO(danvk): deprecate this option in place of {legend: 'never'}
180 if (g
.getOption('showLabelsOnHighlight') !== true) return '';
182 // If no points are selected, we display a default legend. Traditionally,
183 // this has been blank. But a better default would be a conventional legend,
184 // which provides essential information for a non-interactive chart.
185 var html
, sepLines
, i
, c
, dash
, strokePattern
;
186 var labels
= g
.getLabels();
188 if (typeof(x
) === 'undefined') {
189 if (g
.getOption('legend') != 'always') {
193 sepLines
= g
.getOption('labelsSeparateLines');
195 for (i
= 1; i
< labels
.length
; i
++) {
196 var series
= g
.getPropertiesForSeries(labels
[i
]);
197 if (!series
.visible
) continue;
199 if (html
!== '') html
+= (sepLines
? '<br/>' : ' ');
200 strokePattern
= g
.getOption("strokePattern", labels
[i
]);
201 dash
= generateLegendDashHTML(strokePattern
, series
.color
, oneEmWidth
);
202 html
+= "<span style='font-weight: bold; color: " + series
.color
+ ";'>" +
203 dash
+ " " + labels
[i
] + "</span>";
208 // TODO(danvk): remove this use of a private API
209 var xOptView
= g
.optionsViewForAxis_('x');
210 var xvf
= xOptView('valueFormatter');
211 html
= xvf(x
, xOptView
, labels
[0], g
);
217 var num_axes
= g
.numAxes();
218 for (i
= 0; i
< num_axes
; i
++) {
219 // TODO(danvk): remove this use of a private API
220 yOptViews
[i
] = g
.optionsViewForAxis_('y' + (i
? 1 + i
: ''));
222 var showZeros
= g
.getOption("labelsShowZeroValues");
223 sepLines
= g
.getOption("labelsSeparateLines");
224 var highlightSeries
= g
.getHighlightSeries();
225 for (i
= 0; i
< sel_points
.length
; i
++) {
226 var pt
= sel_points
[i
];
227 if (pt
.yval
=== 0 && !showZeros
) continue;
228 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
229 if (sepLines
) html
+= "<br/>";
231 var series
= g
.getPropertiesForSeries(pt
.name
);
232 var yOptView
= yOptViews
[series
.axis
- 1];
233 var fmtFunc
= yOptView('valueFormatter');
234 var yval
= fmtFunc(pt
.yval
, yOptView
, pt
.name
, g
);
236 var cls
= (pt
.name
== highlightSeries
) ? " class='highlight'" : "";
238 // TODO(danvk): use a template string here and make it an attribute.
239 html
+= "<span" + cls
+ ">" + " <b><span style='color: " + series
.color
+ ";'>" +
240 pt
.name
+ "</span></b>:" + yval
+ "</span>";
247 * Generates html for the "dash" displayed on the legend when using "legend: always".
248 * In particular, this works for dashed lines with any stroke pattern. It will
249 * try to scale the pattern to fit in 1em width. Or if small enough repeat the
250 * pattern for 1em width.
252 * @param strokePattern The pattern
253 * @param color The color of the series.
254 * @param oneEmWidth The width in pixels of 1em in the legend.
257 var generateLegendDashHTML
= function(strokePattern
, color
, oneEmWidth
) {
258 // IE 7,8 fail at these divs, so they get boring legend, have not tested 9.
259 var isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
260 if (isIE
) return "—";
262 // Easy, common case: a solid line
263 if (!strokePattern
|| strokePattern
.length
<= 1) {
264 return "<div style=\"display: inline-block; position: relative; " +
265 "bottom: .5ex; padding-left: 1em; height: 1px; " +
266 "border-bottom: 2px solid " + color
+ ";\"></div>";
269 var i
, j
, paddingLeft
, marginRight
;
270 var strokePixelLength
= 0, segmentLoop
= 0;
271 var normalizedPattern
= [];
274 // Compute the length of the pixels including the first segment twice,
275 // since we repeat it.
276 for (i
= 0; i
<= strokePattern
.length
; i
++) {
277 strokePixelLength
+= strokePattern
[i
%strokePattern
.length
];
280 // See if we can loop the pattern by itself at least twice.
281 loop
= Math
.floor(oneEmWidth
/(strokePixelLength
-strokePattern
[0]));
283 // This pattern fits at least two times, no scaling just convert to em;
284 for (i
= 0; i
< strokePattern
.length
; i
++) {
285 normalizedPattern
[i
] = strokePattern
[i
]/oneEmWidth
;
287 // Since we are repeating the pattern, we don't worry about repeating the
288 // first segment in one draw.
289 segmentLoop
= normalizedPattern
.length
;
291 // If the pattern doesn't fit in the legend we scale it to fit.
293 for (i
= 0; i
< strokePattern
.length
; i
++) {
294 normalizedPattern
[i
] = strokePattern
[i
]/strokePixelLength
;
296 // For the scaled patterns we do redraw the first segment.
297 segmentLoop
= normalizedPattern
.length
+1;
300 // Now make the pattern.
302 for (j
= 0; j
< loop
; j
++) {
303 for (i
= 0; i
< segmentLoop
; i
+=2) {
304 // The padding is the drawn segment.
305 paddingLeft
= normalizedPattern
[i
%normalizedPattern
.length
];
306 if (i
< strokePattern
.length
) {
307 // The margin is the space segment.
308 marginRight
= normalizedPattern
[(i
+1)%normalizedPattern
.length
];
310 // The repeated first segment has no right margin.
313 dash
+= "<div style=\"display: inline-block; position: relative; " +
314 "bottom: .5ex; margin-right: " + marginRight
+ "em; padding-left: " +
315 paddingLeft
+ "em; height: 1px; border-bottom: 2px solid " + color
+