1 Dygraph
.Plugins
.Legend
= (function() {
5 Current bits of jankiness:
6 - Uses two private APIs:
7 1. Dygraph.optionsViewForAxis_
8 2. dygraph.plotter_.area
9 - Registers for a "predraw" event, which should be renamed.
10 - I call calculateEmWidthInDiv more often than needed.
18 * Creates the legend, which appears when the user hovers over the chart.
19 * The legend can be either a user-specified or generated div.
23 var legend
= function() {
24 this.legend_div_
= null;
25 this.is_generated_div_
= false; // do we own this div, or was it user-specified?
28 legend
.prototype.toString
= function() {
29 return "Legend Plugin";
33 * This is called during the dygraph constructor, after options have been set
34 * but before the data is available.
36 * Proper tasks to do here include:
37 * - Reading your own options
39 * - Registering event listeners
41 * @param {Dygraph} g Graph instance.
42 * @return {object.<string, function(ev)>} Mapping of event names to callbacks.
44 legend
.prototype.activate
= function(g
) {
46 var divWidth
= g
.getOption('labelsDivWidth');
48 var userLabelsDiv
= g
.getOption('labelsDiv');
49 if (userLabelsDiv
&& null !== userLabelsDiv
) {
50 if (typeof(userLabelsDiv
) == "string" || userLabelsDiv
instanceof String
) {
51 div
= document
.getElementById(userLabelsDiv
);
56 // Default legend styles. These can be overridden in CSS by adding
57 // "!important" after your rule, e.g. "left: 30px !important;"
59 "position": "absolute",
62 "width": divWidth
+ "px",
64 "left": (g
.size().width
- divWidth
- 2) + "px",
65 "background": "white",
66 "lineHeight": "normal",
68 "overflow": "hidden"};
70 // TODO(danvk): get rid of labelsDivStyles? CSS is better.
71 Dygraph
.update(messagestyle
, g
.getOption('labelsDivStyles'));
72 div
= document
.createElement("div");
73 div
.className
= "dygraph-legend";
74 for (var name
in messagestyle
) {
75 if (!messagestyle
.hasOwnProperty(name
)) continue;
78 div
.style
[name
] = messagestyle
[name
];
80 this.warn("You are using unsupported css properties for your " +
81 "browser in labelsDivStyles");
85 // TODO(danvk): come up with a cleaner way to expose this.
86 g
.graphDiv
.appendChild(div
);
87 this.is_generated_div_
= true;
90 this.legend_div_
= div
;
94 deselect
: this.deselect
,
95 // TODO(danvk): rethink the name "predraw" before we commit to it in any API.
96 predraw
: this.predraw
,
97 drawChart
: this.drawChart
101 // Needed for dashed lines.
102 var calculateEmWidthInDiv
= function(div
) {
103 var sizeSpan
= document
.createElement('span');
104 sizeSpan
.setAttribute('style', 'margin: 0; padding: 0 0 0 1em; border: 0;');
105 div
.appendChild(sizeSpan
);
106 var oneEmWidth
=sizeSpan
.offsetWidth
;
107 div
.removeChild(sizeSpan
);
111 legend
.prototype.select
= function(e
) {
112 var xValue
= e
.selectedX
;
113 var points
= e
.selectedPoints
;
115 // Have to do this every time, since styles might have changed.
116 // TODO(danvk): this is not necessary; dashes never used in this case.
117 var oneEmWidth
= calculateEmWidthInDiv(this.legend_div_
);
119 var html
= generateLegendHTML(e
.dygraph
, xValue
, points
, oneEmWidth
);
120 this.legend_div_
.innerHTML
= html
;
123 legend
.prototype.deselect
= function(e
) {
124 var oneEmWidth
= calculateEmWidthInDiv(this.legend_div_
);
125 var html
= generateLegendHTML(e
.dygraph
, undefined
, undefined
, oneEmWidth
);
126 this.legend_div_
.innerHTML
= html
;
129 legend
.prototype.drawChart
= function(e
) {
133 // Right edge should be flush with the right edge of the charting area (which
134 // may not be the same as the right edge of the div, if we have two y-axes.
135 // TODO(danvk): is any of this really necessary? Could just set "right" in "activate".
137 * Position the labels div so that:
138 * - its right edge is flush with the right edge of the charting area
139 * - its top edge is flush with the top edge of the charting area
142 legend
.prototype.predraw
= function(e
) {
143 // Don't touch a user-specified labelsDiv.
144 if (!this.is_generated_div_
) return;
146 // TODO(danvk): only use real APIs for this.
147 var area
= e
.dygraph
.plotter_
.area
;
148 this.legend_div_
.style
.left
= area
.x
+ area
.w
- e
.dygraph
.getOption("labelsDivWidth") - 1 + "px";
149 this.legend_div_
.style
.top
= area
.y
+ "px";
153 * Called when dygraph.destroy() is called.
154 * You should null out any references and detach any DOM elements.
156 legend
.prototype.destroy
= function() {
157 this.legend_div_
= null;
162 * Generates HTML for the legend which is displayed when hovering over the
163 * chart. If no selected points are specified, a default legend is returned
164 * (this may just be the empty string).
165 * @param { Number } [x] The x-value of the selected points.
166 * @param { [Object] } [sel_points] List of selected points for the given
167 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
168 * @param { Number } [oneEmWidth] The pixel width for 1em in the legend. Only
169 * relevant when displaying a legend with no selection (i.e. {legend:
170 * 'always'}) and with dashed lines.
172 var generateLegendHTML
= function(g
, x
, sel_points
, oneEmWidth
) {
173 // TODO(danvk): deprecate this option in place of {legend: 'never'}
174 if (g
.getOption('showLabelsOnHighlight') !== true) return '';
176 // If no points are selected, we display a default legend. Traditionally,
177 // this has been blank. But a better default would be a conventional legend,
178 // which provides essential information for a non-interactive chart.
179 var html
, sepLines
, i
, c
, dash
, strokePattern
;
180 var labels
= g
.getLabels();
182 if (typeof(x
) === 'undefined') {
183 if (g
.getOption('legend') != 'always') {
187 sepLines
= g
.getOption('labelsSeparateLines');
189 for (i
= 1; i
< labels
.length
; i
++) {
190 var series
= g
.getPropertiesForSeries(labels
[i
]);
191 if (!series
.visible
) continue;
193 if (html
!== '') html
+= (sepLines
? '<br/>' : ' ');
194 strokePattern
= g
.getOption("strokePattern", labels
[i
]);
195 dash
= generateLegendDashHTML(strokePattern
, series
.color
, oneEmWidth
);
196 html
+= "<span style='font-weight: bold; color: " + series
.color
+ ";'>" +
197 dash
+ " " + labels
[i
] + "</span>";
202 // TODO(danvk): remove this use of a private API
203 var xOptView
= g
.optionsViewForAxis_('x');
204 var xvf
= xOptView('valueFormatter');
205 html
= xvf(x
, xOptView
, labels
[0], g
) + ":";
208 var num_axes
= g
.numAxes();
209 for (i
= 0; i
< num_axes
; i
++) {
210 // TODO(danvk): remove this use of a private API
211 yOptViews
[i
] = g
.optionsViewForAxis_('y' + (i
? 1 + i
: ''));
213 var showZeros
= g
.getOption("labelsShowZeroValues");
214 sepLines
= g
.getOption("labelsSeparateLines");
215 var highlightSeries
= g
.getHighlightSeries();
216 for (i
= 0; i
< sel_points
.length
; i
++) {
217 var pt
= sel_points
[i
];
218 if (pt
.yval
=== 0 && !showZeros
) continue;
219 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
220 if (sepLines
) html
+= "<br/>";
222 var series
= g
.getPropertiesForSeries(pt
.name
);
223 var yOptView
= yOptViews
[series
.axis
- 1];
224 var fmtFunc
= yOptView('valueFormatter');
225 var yval
= fmtFunc(pt
.yval
, yOptView
, pt
.name
, g
);
227 var cls
= (pt
.name
== highlightSeries
) ? " class='highlight'" : "";
229 // TODO(danvk): use a template string here and make it an attribute.
230 html
+= "<span" + cls
+ ">" + " <b><span style='color: " + series
.color
+ ";'>" +
231 pt
.name
+ "</span></b>:" + yval
+ "</span>";
238 * Generates html for the "dash" displayed on the legend when using "legend: always".
239 * In particular, this works for dashed lines with any stroke pattern. It will
240 * try to scale the pattern to fit in 1em width. Or if small enough repeat the
241 * pattern for 1em width.
243 * @param strokePattern The pattern
244 * @param color The color of the series.
245 * @param oneEmWidth The width in pixels of 1em in the legend.
248 var generateLegendDashHTML
= function(strokePattern
, color
, oneEmWidth
) {
249 // IE 7,8 fail at these divs, so they get boring legend, have not tested 9.
250 var isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
251 if (isIE
) return "—";
253 // Easy, common case: a solid line
254 if (!strokePattern
|| strokePattern
.length
<= 1) {
255 return "<div style=\"display: inline-block; position: relative; " +
256 "bottom: .5ex; padding-left: 1em; height: 1px; " +
257 "border-bottom: 2px solid " + color
+ ";\"></div>";
260 var i
, j
, paddingLeft
, marginRight
;
261 var strokePixelLength
= 0, segmentLoop
= 0;
262 var normalizedPattern
= [];
265 // Compute the length of the pixels including the first segment twice,
266 // since we repeat it.
267 for (i
= 0; i
<= strokePattern
.length
; i
++) {
268 strokePixelLength
+= strokePattern
[i
%strokePattern
.length
];
271 // See if we can loop the pattern by itself at least twice.
272 loop
= Math
.floor(oneEmWidth
/(strokePixelLength
-strokePattern
[0]));
274 // This pattern fits at least two times, no scaling just convert to em;
275 for (i
= 0; i
< strokePattern
.length
; i
++) {
276 normalizedPattern
[i
] = strokePattern
[i
]/oneEmWidth
;
278 // Since we are repeating the pattern, we don't worry about repeating the
279 // first segment in one draw.
280 segmentLoop
= normalizedPattern
.length
;
282 // If the pattern doesn't fit in the legend we scale it to fit.
284 for (i
= 0; i
< strokePattern
.length
; i
++) {
285 normalizedPattern
[i
] = strokePattern
[i
]/strokePixelLength
;
287 // For the scaled patterns we do redraw the first segment.
288 segmentLoop
= normalizedPattern
.length
+1;
291 // Now make the pattern.
293 for (j
= 0; j
< loop
; j
++) {
294 for (i
= 0; i
< segmentLoop
; i
+=2) {
295 // The padding is the drawn segment.
296 paddingLeft
= normalizedPattern
[i
%normalizedPattern
.length
];
297 if (i
< strokePattern
.length
) {
298 // The margin is the space segment.
299 marginRight
= normalizedPattern
[(i
+1)%normalizedPattern
.length
];
301 // The repeated first segment has no right margin.
304 dash
+= "<div style=\"display: inline-block; position: relative; " +
305 "bottom: .5ex; margin-right: " + marginRight
+ "em; padding-left: " +
306 paddingLeft
+ "em; height: 1px; border-bottom: 2px solid " + color
+