9e4650eb481c969ef0fe72fb16428f79873c7221
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.
11 - Why can't I call "this.deselect(e)" instead of "legend.deselect.call(this, e)"?
19 * Creates the legend, which appears when the user hovers over the chart.
20 * The legend can be either a user-specified or generated div.
24 var legend
= function() {
25 this.legend_div_
= null;
26 this.is_generated_div_
= false; // do we own this div, or was it user-specified?
29 legend
.prototype.toString
= function() {
30 return "Legend Plugin";
34 * This is called during the dygraph constructor, after options have been set
35 * but before the data is available.
37 * Proper tasks to do here include:
38 * - Reading your own options
40 * - Registering event listeners
42 legend
.prototype.activate
= function(g
, r
) {
44 var divWidth
= g
.getOption('labelsDivWidth');
46 var userLabelsDiv
= g
.getOption('labelsDiv');
47 if (userLabelsDiv
&& null !== userLabelsDiv
) {
48 if (typeof(userLabelsDiv
) == "string" || userLabelsDiv
instanceof String
) {
49 div
= document
.getElementById(userLabelsDiv
);
54 // Default legend styles. These can be overridden in CSS by adding
55 // "!important" after your rule, e.g. "left: 30px !important;"
57 "position": "absolute",
60 "width": divWidth
+ "px",
63 "background": "white",
64 "lineHeight": "normal",
66 "overflow": "hidden"};
68 // TODO(danvk): get rid of labelsDivStyles? CSS is better.
69 Dygraph
.update(messagestyle
, g
.getOption('labelsDivStyles'));
70 div
= document
.createElement("div");
71 div
.className
= "dygraph-legend";
72 for (var name
in messagestyle
) {
73 if (!messagestyle
.hasOwnProperty(name
)) continue;
76 div
.style
[name
] = messagestyle
[name
];
78 this.warn("You are using unsupported css properties for your " +
79 "browser in labelsDivStyles");
83 // TODO(danvk): come up with a cleaner way to expose this.
84 g
.graphDiv
.appendChild(div
);
85 this.is_generated_div_
= true;
88 this.legend_div_
= div
;
90 r
.addEventListener('select', legend
.select
);
91 r
.addEventListener('deselect', legend
.deselect
);
93 // TODO(danvk): rethink the name "predraw" before we commit to it in any API.
94 r
.addEventListener('predraw', legend
.predraw
);
95 r
.addEventListener('drawChart', legend
.drawChart
);
98 // Needed for dashed lines.
99 var calculateEmWidthInDiv
= function(div
) {
100 var sizeSpan
= document
.createElement('span');
101 sizeSpan
.setAttribute('style', 'margin: 0; padding: 0 0 0 1em; border: 0;');
102 div
.appendChild(sizeSpan
);
103 var oneEmWidth
=sizeSpan
.offsetWidth
;
104 div
.removeChild(sizeSpan
);
108 legend
.select
= function(e
) {
109 var xValue
= e
.selectedX
;
110 var points
= e
.selectedPoints
;
112 // Have to do this every time, since styles might have changed.
113 // TODO(danvk): this is not necessary; dashes never used in this case.
114 var oneEmWidth
= calculateEmWidthInDiv(this.legend_div_
);
116 var html
= generateLegendHTML(e
.dygraph
, xValue
, points
, oneEmWidth
);
117 this.legend_div_
.innerHTML
= html
;
120 legend
.deselect
= function(e
) {
121 var oneEmWidth
= calculateEmWidthInDiv(this.legend_div_
);
122 var html
= generateLegendHTML(e
.dygraph
, undefined
, undefined
, oneEmWidth
);
123 this.legend_div_
.innerHTML
= html
;
126 legend
.drawChart
= function(e
) {
127 // TODO(danvk): why doesn't this.deselect(e) work here?
128 legend
.deselect
.call(this, e
);
131 // Right edge should be flush with the right edge of the charting area (which
132 // may not be the same as the right edge of the div, if we have two y-axes.
133 // TODO(danvk): is any of this really necessary? Could just set "right" in "activate".
135 * Position the labels div so that:
136 * - its right edge is flush with the right edge of the charting area
137 * - its top edge is flush with the top edge of the charting area
140 legend
.predraw
= function(e
) {
141 // Don't touch a user-specified labelsDiv.
142 if (!this.is_generated_div_
) return;
144 // TODO(danvk): only use real APIs for this.
145 var area
= e
.dygraph
.plotter_
.area
;
146 this.legend_div_
.style
.left
= area
.x
+ area
.w
- e
.dygraph
.getOption("labelsDivWidth") - 1 + "px";
147 this.legend_div_
.style
.top
= area
.y
+ "px";
151 * Called when dygraph.destroy() is called.
152 * You should null out any references and detach any DOM elements.
154 legend
.prototype.destroy
= function() {
155 this.legend_div_
= null;
160 * Generates HTML for the legend which is displayed when hovering over the
161 * chart. If no selected points are specified, a default legend is returned
162 * (this may just be the empty string).
163 * @param { Number } [x] The x-value of the selected points.
164 * @param { [Object] } [sel_points] List of selected points for the given
165 * x-value. Should have properties like 'name', 'yval' and 'canvasy'.
166 * @param { Number } [oneEmWidth] The pixel width for 1em in the legend. Only
167 * relevant when displaying a legend with no selection (i.e. {legend:
168 * 'always'}) and with dashed lines.
170 var generateLegendHTML
= function(g
, x
, sel_points
, oneEmWidth
) {
171 // TODO(danvk): deprecate this option in place of {legend: 'never'}
172 if (g
.getOption('showLabelsOnHighlight') !== true) return '';
174 // If no points are selected, we display a default legend. Traditionally,
175 // this has been blank. But a better default would be a conventional legend,
176 // which provides essential information for a non-interactive chart.
177 var html
, sepLines
, i
, c
, dash
, strokePattern
;
178 var labels
= g
.getLabels();
180 if (typeof(x
) === 'undefined') {
181 if (g
.getOption('legend') != 'always') {
185 sepLines
= g
.getOption('labelsSeparateLines');
187 for (i
= 1; i
< labels
.length
; i
++) {
188 var series
= g
.getPropertiesForSeries(labels
[i
]);
189 if (!series
.visible
) continue;
191 if (html
!== '') html
+= (sepLines
? '<br/>' : ' ');
192 strokePattern
= g
.getOption("strokePattern", labels
[i
]);
193 dash
= generateLegendDashHTML(strokePattern
, series
.color
, oneEmWidth
);
194 html
+= "<span style='font-weight: bold; color: " + series
.color
+ ";'>" +
195 dash
+ " " + labels
[i
] + "</span>";
200 // TODO(danvk): remove this use of a private API
201 var xOptView
= g
.optionsViewForAxis_('x');
202 var xvf
= xOptView('valueFormatter');
203 html
= xvf(x
, xOptView
, labels
[0], g
) + ":";
206 var num_axes
= g
.numAxes();
207 for (i
= 0; i
< num_axes
; i
++) {
208 // TODO(danvk): remove this use of a private API
209 yOptViews
[i
] = g
.optionsViewForAxis_('y' + (i
? 1 + i
: ''));
211 var showZeros
= g
.getOption("labelsShowZeroValues");
212 sepLines
= g
.getOption("labelsSeparateLines");
213 var highlightSeries
= g
.getHighlightSeries();
214 for (i
= 0; i
< sel_points
.length
; i
++) {
215 var pt
= sel_points
[i
];
216 if (pt
.yval
=== 0 && !showZeros
) continue;
217 if (!Dygraph
.isOK(pt
.canvasy
)) continue;
218 if (sepLines
) html
+= "<br/>";
220 var series
= g
.getPropertiesForSeries(pt
.name
);
221 var yOptView
= yOptViews
[series
.axis
- 1];
222 var fmtFunc
= yOptView('valueFormatter');
223 var yval
= fmtFunc(pt
.yval
, yOptView
, pt
.name
, g
);
225 var cls
= (pt
.name
== highlightSeries
) ? " class='highlight'" : "";
227 // TODO(danvk): use a template string here and make it an attribute.
228 html
+= "<span" + cls
+ ">" + " <b><span style='color: " + series
.color
+ ";'>" +
229 pt
.name
+ "</span></b>:" + yval
+ "</span>";
236 * Generates html for the "dash" displayed on the legend when using "legend: always".
237 * In particular, this works for dashed lines with any stroke pattern. It will
238 * try to scale the pattern to fit in 1em width. Or if small enough repeat the
239 * pattern for 1em width.
241 * @param strokePattern The pattern
242 * @param color The color of the series.
243 * @param oneEmWidth The width in pixels of 1em in the legend.
246 var generateLegendDashHTML
= function(strokePattern
, color
, oneEmWidth
) {
247 // IE 7,8 fail at these divs, so they get boring legend, have not tested 9.
248 var isIE
= (/MSIE/.test(navigator
.userAgent
) && !window
.opera
);
249 if (isIE
) return "—";
251 // Easy, common case: a solid line
252 if (!strokePattern
|| strokePattern
.length
<= 1) {
253 return "<div style=\"display: inline-block; position: relative; " +
254 "bottom: .5ex; padding-left: 1em; height: 1px; " +
255 "border-bottom: 2px solid " + color
+ ";\"></div>";
258 var i
, j
, paddingLeft
, marginRight
;
259 var strokePixelLength
= 0, segmentLoop
= 0;
260 var normalizedPattern
= [];
263 // Compute the length of the pixels including the first segment twice,
264 // since we repeat it.
265 for (i
= 0; i
<= strokePattern
.length
; i
++) {
266 strokePixelLength
+= strokePattern
[i
%strokePattern
.length
];
269 // See if we can loop the pattern by itself at least twice.
270 loop
= Math
.floor(oneEmWidth
/(strokePixelLength
-strokePattern
[0]));
272 // This pattern fits at least two times, no scaling just convert to em;
273 for (i
= 0; i
< strokePattern
.length
; i
++) {
274 normalizedPattern
[i
] = strokePattern
[i
]/oneEmWidth
;
276 // Since we are repeating the pattern, we don't worry about repeating the
277 // first segment in one draw.
278 segmentLoop
= normalizedPattern
.length
;
280 // If the pattern doesn't fit in the legend we scale it to fit.
282 for (i
= 0; i
< strokePattern
.length
; i
++) {
283 normalizedPattern
[i
] = strokePattern
[i
]/strokePixelLength
;
285 // For the scaled patterns we do redraw the first segment.
286 segmentLoop
= normalizedPattern
.length
+1;
289 // Now make the pattern.
291 for (j
= 0; j
< loop
; j
++) {
292 for (i
= 0; i
< segmentLoop
; i
+=2) {
293 // The padding is the drawn segment.
294 paddingLeft
= normalizedPattern
[i
%normalizedPattern
.length
];
295 if (i
< strokePattern
.length
) {
296 // The margin is the space segment.
297 marginRight
= normalizedPattern
[(i
+1)%normalizedPattern
.length
];
299 // The repeated first segment has no right margin.
302 dash
+= "<div style=\"display: inline-block; position: relative; " +
303 "bottom: .5ex; margin-right: " + marginRight
+ "em; padding-left: " +
304 paddingLeft
+ "em; height: 1px; border-bottom: 2px solid " + color
+