nv.d3.legend.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. // Licensed to Cloudera, Inc. under one
  2. // or more contributor license agreements. See the NOTICE file
  3. // distributed with this work for additional information
  4. // regarding copyright ownership. Cloudera, Inc. licenses this file
  5. // to you under the Apache License, Version 2.0 (the
  6. // "License"); you may not use this file except in compliance
  7. // with the License. You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. nv.models.legend = function() {
  17. "use strict";
  18. //============================================================
  19. // Public Variables with Default Settings
  20. //------------------------------------------------------------
  21. var margin = {top: 5, right: 0, bottom: 5, left: 0}
  22. , width = 400
  23. , height = 20
  24. , getKey = function(d) { return d.key }
  25. , color = nv.utils.defaultColor()
  26. , align = true
  27. , rightAlign = true
  28. , updateState = true //If true, legend will update data.disabled and trigger a 'stateChange' dispatch.
  29. , radioButtonMode = false //If true, clicking legend items will cause it to behave like a radio button. (only one can be selected at a time)
  30. , dispatch = d3.dispatch('legendClick', 'legendDblclick', 'legendMouseover', 'legendMouseout', 'stateChange')
  31. ;
  32. //============================================================
  33. function chart(selection) {
  34. selection.each(function(data) {
  35. var availableWidth = width - margin.left - margin.right,
  36. container = d3.select(this);
  37. //------------------------------------------------------------
  38. // Setup containers and skeleton of chart
  39. var wrap = container.selectAll('g.nv-legend').data([data]);
  40. var gEnter = wrap.enter().append('g').attr('class', 'nvd3 nv-legend').append('g');
  41. var g = wrap.select('g');
  42. wrap.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
  43. //------------------------------------------------------------
  44. var series = g.selectAll('.nv-series')
  45. .data(function(d) { return d });
  46. var seriesEnter = series.enter().append('g').attr('class', 'nv-series')
  47. .on('mouseover', function(d,i) {
  48. dispatch.legendMouseover(d,i); //TODO: Make consistent with other event objects
  49. })
  50. .on('mouseout', function(d,i) {
  51. dispatch.legendMouseout(d,i);
  52. })
  53. .on('click', function(d,i) {
  54. dispatch.legendClick(d,i);
  55. if (updateState) {
  56. if (radioButtonMode) {
  57. //Radio button mode: set every series to disabled,
  58. // and enable the clicked series.
  59. data.forEach(function(series) { series.disabled = true});
  60. d.disabled = false;
  61. }
  62. else {
  63. d.disabled = !d.disabled;
  64. if (data.every(function(series) { return series.disabled})) {
  65. //the default behavior of NVD3 legends is, if every single series
  66. // is disabled, turn all series' back on.
  67. data.forEach(function(series) { series.disabled = false});
  68. }
  69. }
  70. dispatch.stateChange({
  71. disabled: data.map(function(d) { return !!d.disabled })
  72. });
  73. }
  74. })
  75. .on('dblclick', function(d,i) {
  76. dispatch.legendDblclick(d,i);
  77. if (updateState) {
  78. //the default behavior of NVD3 legends, when double clicking one,
  79. // is to set all other series' to false, and make the double clicked series enabled.
  80. data.forEach(function(series) {
  81. series.disabled = true;
  82. });
  83. d.disabled = false;
  84. dispatch.stateChange({
  85. disabled: data.map(function(d) { return !!d.disabled })
  86. });
  87. }
  88. });
  89. seriesEnter.append('circle')
  90. .style('stroke-width', 2)
  91. .attr('class','nv-legend-symbol')
  92. .attr('r', 5)
  93. .style('display', function(d){return d.checkbox?'none':'inline'});
  94. seriesEnter.append('rect')
  95. .style('stroke-width', 2)
  96. .attr('class','nv-legend-symbol')
  97. .attr('width', 10)
  98. .attr('height', 10)
  99. .attr('transform', 'translate(-5,-5)')
  100. .style('display', function(d){return d.checkbox?'inline':'none'});
  101. seriesEnter.append('text')
  102. .attr('text-anchor', 'start')
  103. .attr('class','nv-legend-text')
  104. .attr('dy', '.32em')
  105. .attr('dx', '8');
  106. series.classed('disabled', function(d) { return d.disabled });
  107. series.exit().remove();
  108. series.select('circle')
  109. .style('fill', function(d,i) { return d.color || color(d,i)})
  110. .style('stroke', function(d,i) { return d.color || color(d, i) });
  111. series.select('rect')
  112. .style('fill', function(d,i) { return d.color || color(d,i)})
  113. .style('stroke', function(d,i) { return d.color || color(d, i) });
  114. series.select('text').text(getKey);
  115. //TODO: implement fixed-width and max-width options (max-width is especially useful with the align option)
  116. // NEW ALIGNING CODE, TODO: clean up
  117. if (align) {
  118. var seriesWidths = [];
  119. series.each(function(d,i) {
  120. var legendText = d3.select(this).select('text');
  121. var nodeTextLength;
  122. try {
  123. nodeTextLength = legendText.getComputedTextLength();
  124. // If the legendText is display:none'd (nodeTextLength == 0), simulate an error so we approximate, instead
  125. if(nodeTextLength <= 0) throw Error();
  126. }
  127. catch(e) {
  128. nodeTextLength = nv.utils.calcApproxTextWidth(legendText);
  129. }
  130. seriesWidths.push(nodeTextLength + 28); // 28 is ~ the width of the circle plus some padding
  131. });
  132. var seriesPerRow = 0;
  133. var legendWidth = 0;
  134. var columnWidths = [];
  135. while ( legendWidth < availableWidth && seriesPerRow < seriesWidths.length) {
  136. columnWidths[seriesPerRow] = seriesWidths[seriesPerRow];
  137. legendWidth += seriesWidths[seriesPerRow++];
  138. }
  139. if (seriesPerRow === 0) seriesPerRow = 1; //minimum of one series per row
  140. while ( legendWidth > availableWidth && seriesPerRow > 1 ) {
  141. columnWidths = [];
  142. seriesPerRow--;
  143. for (var k = 0; k < seriesWidths.length; k++) {
  144. if (seriesWidths[k] > (columnWidths[k % seriesPerRow] || 0) )
  145. columnWidths[k % seriesPerRow] = seriesWidths[k];
  146. }
  147. legendWidth = columnWidths.reduce(function(prev, cur, index, array) {
  148. return prev + cur;
  149. });
  150. }
  151. var xPositions = [];
  152. for (var i = 0, curX = 0; i < seriesPerRow; i++) {
  153. xPositions[i] = curX;
  154. curX += columnWidths[i];
  155. }
  156. series
  157. .attr('transform', function(d, i) {
  158. return 'translate(' + xPositions[i % seriesPerRow] + ',' + (5 + Math.floor(i / seriesPerRow) * 20) + ')';
  159. });
  160. //position legend as far right as possible within the total width
  161. if (rightAlign) {
  162. g.attr('transform', 'translate(' + (width - margin.right - legendWidth) + ',' + margin.top + ')');
  163. }
  164. else {
  165. g.attr('transform', 'translate(0' + ',' + margin.top + ')');
  166. }
  167. height = margin.top + margin.bottom + (Math.ceil(seriesWidths.length / seriesPerRow) * 20);
  168. } else {
  169. var ypos = 5,
  170. newxpos = 5,
  171. maxwidth = 0,
  172. xpos;
  173. series
  174. .attr('transform', function(d, i) {
  175. var length = d3.select(this).select('text').node().getComputedTextLength() + 28;
  176. xpos = newxpos;
  177. if (width < margin.left + margin.right + xpos + length) {
  178. newxpos = xpos = 5;
  179. ypos += 20;
  180. }
  181. newxpos += length;
  182. if (newxpos > maxwidth) maxwidth = newxpos;
  183. return 'translate(' + xpos + ',' + ypos + ')';
  184. });
  185. //position legend as far right as possible within the total width
  186. g.attr('transform', 'translate(' + (width - margin.right - maxwidth) + ',' + margin.top + ')');
  187. height = margin.top + margin.bottom + ypos + 15;
  188. }
  189. });
  190. return chart;
  191. }
  192. //============================================================
  193. // Expose Public Variables
  194. //------------------------------------------------------------
  195. chart.dispatch = dispatch;
  196. chart.options = nv.utils.optionsFunc.bind(chart);
  197. chart.margin = function(_) {
  198. if (!arguments.length) return margin;
  199. margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
  200. margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
  201. margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
  202. margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
  203. return chart;
  204. };
  205. chart.width = function(_) {
  206. if (!arguments.length) return width;
  207. width = _;
  208. return chart;
  209. };
  210. chart.height = function(_) {
  211. if (!arguments.length) return height;
  212. height = _;
  213. return chart;
  214. };
  215. chart.key = function(_) {
  216. if (!arguments.length) return getKey;
  217. getKey = _;
  218. return chart;
  219. };
  220. chart.color = function(_) {
  221. if (!arguments.length) return color;
  222. color = nv.utils.getColor(_);
  223. return chart;
  224. };
  225. chart.align = function(_) {
  226. if (!arguments.length) return align;
  227. align = _;
  228. return chart;
  229. };
  230. chart.rightAlign = function(_) {
  231. if (!arguments.length) return rightAlign;
  232. rightAlign = _;
  233. return chart;
  234. };
  235. chart.updateState = function(_) {
  236. if (!arguments.length) return updateState;
  237. updateState = _;
  238. return chart;
  239. };
  240. chart.radioButtonMode = function(_) {
  241. if (!arguments.length) return radioButtonMode;
  242. radioButtonMode = _;
  243. return chart;
  244. };
  245. //============================================================
  246. return chart;
  247. }