| 1 | /** |
| 2 | * @license |
| 3 | * Copyright 2012 Dan Vanderkam (danvdk@gmail.com) |
| 4 | * MIT-licensed (http://opensource.org/licenses/MIT) |
| 5 | */ |
| 6 | |
| 7 | Dygraph.Plugins.Legend = (function() { |
| 8 | /* |
| 9 | |
| 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. |
| 16 | |
| 17 | */ |
| 18 | |
| 19 | /*jshint globalstrict: true */ |
| 20 | /*global Dygraph:false */ |
| 21 | "use strict"; |
| 22 | |
| 23 | |
| 24 | /** |
| 25 | * Creates the legend, which appears when the user hovers over the chart. |
| 26 | * The legend can be either a user-specified or generated div. |
| 27 | * |
| 28 | * @constructor |
| 29 | */ |
| 30 | var legend = function() { |
| 31 | this.legend_div_ = null; |
| 32 | this.is_generated_div_ = false; // do we own this div, or was it user-specified? |
| 33 | }; |
| 34 | |
| 35 | legend.prototype.toString = function() { |
| 36 | return "Legend Plugin"; |
| 37 | }; |
| 38 | |
| 39 | // (defined below) |
| 40 | var generateLegendHTML, generateLegendDashHTML; |
| 41 | |
| 42 | /** |
| 43 | * This is called during the dygraph constructor, after options have been set |
| 44 | * but before the data is available. |
| 45 | * |
| 46 | * Proper tasks to do here include: |
| 47 | * - Reading your own options |
| 48 | * - DOM manipulation |
| 49 | * - Registering event listeners |
| 50 | * |
| 51 | * @param {Dygraph} g Graph instance. |
| 52 | * @return {object.<string, function(ev)>} Mapping of event names to callbacks. |
| 53 | */ |
| 54 | legend.prototype.activate = function(g) { |
| 55 | var div; |
| 56 | var divWidth = g.getOption('labelsDivWidth'); |
| 57 | |
| 58 | var userLabelsDiv = g.getOption('labelsDiv'); |
| 59 | if (userLabelsDiv && null !== userLabelsDiv) { |
| 60 | if (typeof(userLabelsDiv) == "string" || userLabelsDiv instanceof String) { |
| 61 | div = document.getElementById(userLabelsDiv); |
| 62 | } else { |
| 63 | div = userLabelsDiv; |
| 64 | } |
| 65 | } else { |
| 66 | // Default legend styles. These can be overridden in CSS by adding |
| 67 | // "!important" after your rule, e.g. "left: 30px !important;" |
| 68 | var messagestyle = { |
| 69 | "position": "absolute", |
| 70 | "fontSize": "14px", |
| 71 | "zIndex": 10, |
| 72 | "width": divWidth + "px", |
| 73 | "top": "0px", |
| 74 | "left": (g.size().width - divWidth - 2) + "px", |
| 75 | "background": "white", |
| 76 | "lineHeight": "normal", |
| 77 | "textAlign": "left", |
| 78 | "overflow": "hidden"}; |
| 79 | |
| 80 | // TODO(danvk): get rid of labelsDivStyles? CSS is better. |
| 81 | Dygraph.update(messagestyle, g.getOption('labelsDivStyles')); |
| 82 | div = document.createElement("div"); |
| 83 | div.className = "dygraph-legend"; |
| 84 | for (var name in messagestyle) { |
| 85 | if (!messagestyle.hasOwnProperty(name)) continue; |
| 86 | |
| 87 | try { |
| 88 | div.style[name] = messagestyle[name]; |
| 89 | } catch (e) { |
| 90 | this.warn("You are using unsupported css properties for your " + |
| 91 | "browser in labelsDivStyles"); |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | // TODO(danvk): come up with a cleaner way to expose this. |
| 96 | g.graphDiv.appendChild(div); |
| 97 | this.is_generated_div_ = true; |
| 98 | } |
| 99 | |
| 100 | this.legend_div_ = div; |
| 101 | this.one_em_width_ = 10; // just a guess, will be updated. |
| 102 | |
| 103 | return { |
| 104 | select: this.select, |
| 105 | deselect: this.deselect, |
| 106 | // TODO(danvk): rethink the name "predraw" before we commit to it in any API. |
| 107 | predraw: this.predraw, |
| 108 | didDrawChart: this.didDrawChart |
| 109 | }; |
| 110 | }; |
| 111 | |
| 112 | // Needed for dashed lines. |
| 113 | var calculateEmWidthInDiv = function(div) { |
| 114 | var sizeSpan = document.createElement('span'); |
| 115 | sizeSpan.setAttribute('style', 'margin: 0; padding: 0 0 0 1em; border: 0;'); |
| 116 | div.appendChild(sizeSpan); |
| 117 | var oneEmWidth=sizeSpan.offsetWidth; |
| 118 | div.removeChild(sizeSpan); |
| 119 | return oneEmWidth; |
| 120 | }; |
| 121 | |
| 122 | legend.prototype.select = function(e) { |
| 123 | var xValue = e.selectedX; |
| 124 | var points = e.selectedPoints; |
| 125 | |
| 126 | var html = generateLegendHTML(e.dygraph, xValue, points, this.one_em_width_); |
| 127 | this.legend_div_.innerHTML = html; |
| 128 | }; |
| 129 | |
| 130 | legend.prototype.deselect = function(e) { |
| 131 | // Have to do this every time, since styles might have changed. |
| 132 | var oneEmWidth = calculateEmWidthInDiv(this.legend_div_); |
| 133 | this.one_em_width_ = oneEmWidth; |
| 134 | |
| 135 | var html = generateLegendHTML(e.dygraph, undefined, undefined, oneEmWidth); |
| 136 | this.legend_div_.innerHTML = html; |
| 137 | }; |
| 138 | |
| 139 | legend.prototype.didDrawChart = function(e) { |
| 140 | this.deselect(e); |
| 141 | }; |
| 142 | |
| 143 | // Right edge should be flush with the right edge of the charting area (which |
| 144 | // may not be the same as the right edge of the div, if we have two y-axes. |
| 145 | // TODO(danvk): is any of this really necessary? Could just set "right" in "activate". |
| 146 | /** |
| 147 | * Position the labels div so that: |
| 148 | * - its right edge is flush with the right edge of the charting area |
| 149 | * - its top edge is flush with the top edge of the charting area |
| 150 | * @private |
| 151 | */ |
| 152 | legend.prototype.predraw = function(e) { |
| 153 | // Don't touch a user-specified labelsDiv. |
| 154 | if (!this.is_generated_div_) return; |
| 155 | |
| 156 | // TODO(danvk): only use real APIs for this. |
| 157 | e.dygraph.graphDiv.appendChild(this.legend_div_); |
| 158 | var area = e.dygraph.plotter_.area; |
| 159 | var labelsDivWidth = e.dygraph.getOption("labelsDivWidth"); |
| 160 | this.legend_div_.style.left = area.x + area.w - labelsDivWidth - 1 + "px"; |
| 161 | this.legend_div_.style.top = area.y + "px"; |
| 162 | this.legend_div_.style.width = labelsDivWidth + "px"; |
| 163 | }; |
| 164 | |
| 165 | /** |
| 166 | * Called when dygraph.destroy() is called. |
| 167 | * You should null out any references and detach any DOM elements. |
| 168 | */ |
| 169 | legend.prototype.destroy = function() { |
| 170 | this.legend_div_ = null; |
| 171 | }; |
| 172 | |
| 173 | /** |
| 174 | * @private |
| 175 | * Generates HTML for the legend which is displayed when hovering over the |
| 176 | * chart. If no selected points are specified, a default legend is returned |
| 177 | * (this may just be the empty string). |
| 178 | * @param { Number } [x] The x-value of the selected points. |
| 179 | * @param { [Object] } [sel_points] List of selected points for the given |
| 180 | * x-value. Should have properties like 'name', 'yval' and 'canvasy'. |
| 181 | * @param { Number } [oneEmWidth] The pixel width for 1em in the legend. Only |
| 182 | * relevant when displaying a legend with no selection (i.e. {legend: |
| 183 | * 'always'}) and with dashed lines. |
| 184 | */ |
| 185 | generateLegendHTML = function(g, x, sel_points, oneEmWidth) { |
| 186 | // TODO(danvk): deprecate this option in place of {legend: 'never'} |
| 187 | if (g.getOption('showLabelsOnHighlight') !== true) return ''; |
| 188 | |
| 189 | // If no points are selected, we display a default legend. Traditionally, |
| 190 | // this has been blank. But a better default would be a conventional legend, |
| 191 | // which provides essential information for a non-interactive chart. |
| 192 | var html, sepLines, i, c, dash, strokePattern; |
| 193 | var labels = g.getLabels(); |
| 194 | |
| 195 | if (typeof(x) === 'undefined') { |
| 196 | if (g.getOption('legend') != 'always') { |
| 197 | return ''; |
| 198 | } |
| 199 | |
| 200 | sepLines = g.getOption('labelsSeparateLines'); |
| 201 | html = ''; |
| 202 | for (i = 1; i < labels.length; i++) { |
| 203 | var series = g.getPropertiesForSeries(labels[i]); |
| 204 | if (!series.visible) continue; |
| 205 | |
| 206 | if (html !== '') html += (sepLines ? '<br/>' : ' '); |
| 207 | strokePattern = g.getOption("strokePattern", labels[i]); |
| 208 | dash = generateLegendDashHTML(strokePattern, series.color, oneEmWidth); |
| 209 | html += "<span style='font-weight: bold; color: " + series.color + ";'>" + |
| 210 | dash + " " + labels[i] + "</span>"; |
| 211 | } |
| 212 | return html; |
| 213 | } |
| 214 | |
| 215 | // TODO(danvk): remove this use of a private API |
| 216 | var xOptView = g.optionsViewForAxis_('x'); |
| 217 | var xvf = xOptView('valueFormatter'); |
| 218 | html = xvf(x, xOptView, labels[0], g); |
| 219 | if (html !== '') { |
| 220 | html += ':'; |
| 221 | } |
| 222 | |
| 223 | var yOptViews = []; |
| 224 | var num_axes = g.numAxes(); |
| 225 | for (i = 0; i < num_axes; i++) { |
| 226 | // TODO(danvk): remove this use of a private API |
| 227 | yOptViews[i] = g.optionsViewForAxis_('y' + (i ? 1 + i : '')); |
| 228 | } |
| 229 | var showZeros = g.getOption("labelsShowZeroValues"); |
| 230 | sepLines = g.getOption("labelsSeparateLines"); |
| 231 | var highlightSeries = g.getHighlightSeries(); |
| 232 | for (i = 0; i < sel_points.length; i++) { |
| 233 | var pt = sel_points[i]; |
| 234 | if (pt.yval === 0 && !showZeros) continue; |
| 235 | if (!Dygraph.isOK(pt.canvasy)) continue; |
| 236 | if (sepLines) html += "<br/>"; |
| 237 | |
| 238 | var series = g.getPropertiesForSeries(pt.name); |
| 239 | var yOptView = yOptViews[series.axis - 1]; |
| 240 | var fmtFunc = yOptView('valueFormatter'); |
| 241 | var yval = fmtFunc(pt.yval, yOptView, pt.name, g); |
| 242 | |
| 243 | var cls = (pt.name == highlightSeries) ? " class='highlight'" : ""; |
| 244 | |
| 245 | // TODO(danvk): use a template string here and make it an attribute. |
| 246 | html += "<span" + cls + ">" + " <b><span style='color: " + series.color + ";'>" + |
| 247 | pt.name + "</span></b>:" + yval + "</span>"; |
| 248 | } |
| 249 | return html; |
| 250 | }; |
| 251 | |
| 252 | |
| 253 | /** |
| 254 | * Generates html for the "dash" displayed on the legend when using "legend: always". |
| 255 | * In particular, this works for dashed lines with any stroke pattern. It will |
| 256 | * try to scale the pattern to fit in 1em width. Or if small enough repeat the |
| 257 | * pattern for 1em width. |
| 258 | * |
| 259 | * @param strokePattern The pattern |
| 260 | * @param color The color of the series. |
| 261 | * @param oneEmWidth The width in pixels of 1em in the legend. |
| 262 | * @private |
| 263 | */ |
| 264 | generateLegendDashHTML = function(strokePattern, color, oneEmWidth) { |
| 265 | // IE 7,8 fail at these divs, so they get boring legend, have not tested 9. |
| 266 | var isIE = (/MSIE/.test(navigator.userAgent) && !window.opera); |
| 267 | if (isIE) return "—"; |
| 268 | |
| 269 | // Easy, common case: a solid line |
| 270 | if (!strokePattern || strokePattern.length <= 1) { |
| 271 | return "<div style=\"display: inline-block; position: relative; " + |
| 272 | "bottom: .5ex; padding-left: 1em; height: 1px; " + |
| 273 | "border-bottom: 2px solid " + color + ";\"></div>"; |
| 274 | } |
| 275 | |
| 276 | var i, j, paddingLeft, marginRight; |
| 277 | var strokePixelLength = 0, segmentLoop = 0; |
| 278 | var normalizedPattern = []; |
| 279 | var loop; |
| 280 | |
| 281 | // Compute the length of the pixels including the first segment twice, |
| 282 | // since we repeat it. |
| 283 | for (i = 0; i <= strokePattern.length; i++) { |
| 284 | strokePixelLength += strokePattern[i%strokePattern.length]; |
| 285 | } |
| 286 | |
| 287 | // See if we can loop the pattern by itself at least twice. |
| 288 | loop = Math.floor(oneEmWidth/(strokePixelLength-strokePattern[0])); |
| 289 | if (loop > 1) { |
| 290 | // This pattern fits at least two times, no scaling just convert to em; |
| 291 | for (i = 0; i < strokePattern.length; i++) { |
| 292 | normalizedPattern[i] = strokePattern[i]/oneEmWidth; |
| 293 | } |
| 294 | // Since we are repeating the pattern, we don't worry about repeating the |
| 295 | // first segment in one draw. |
| 296 | segmentLoop = normalizedPattern.length; |
| 297 | } else { |
| 298 | // If the pattern doesn't fit in the legend we scale it to fit. |
| 299 | loop = 1; |
| 300 | for (i = 0; i < strokePattern.length; i++) { |
| 301 | normalizedPattern[i] = strokePattern[i]/strokePixelLength; |
| 302 | } |
| 303 | // For the scaled patterns we do redraw the first segment. |
| 304 | segmentLoop = normalizedPattern.length+1; |
| 305 | } |
| 306 | |
| 307 | // Now make the pattern. |
| 308 | var dash = ""; |
| 309 | for (j = 0; j < loop; j++) { |
| 310 | for (i = 0; i < segmentLoop; i+=2) { |
| 311 | // The padding is the drawn segment. |
| 312 | paddingLeft = normalizedPattern[i%normalizedPattern.length]; |
| 313 | if (i < strokePattern.length) { |
| 314 | // The margin is the space segment. |
| 315 | marginRight = normalizedPattern[(i+1)%normalizedPattern.length]; |
| 316 | } else { |
| 317 | // The repeated first segment has no right margin. |
| 318 | marginRight = 0; |
| 319 | } |
| 320 | dash += "<div style=\"display: inline-block; position: relative; " + |
| 321 | "bottom: .5ex; margin-right: " + marginRight + "em; padding-left: " + |
| 322 | paddingLeft + "em; height: 1px; border-bottom: 2px solid " + color + |
| 323 | ";\"></div>"; |
| 324 | } |
| 325 | } |
| 326 | return dash; |
| 327 | }; |
| 328 | |
| 329 | |
| 330 | return legend; |
| 331 | })(); |