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