base-chart-component.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import Ember from 'ember';
  2. export default Ember.Component.extend({
  3. chart: undefined,
  4. tooltip : undefined,
  5. colors: d3.scale.category10().range(),
  6. initChart: function() {
  7. this.chart = {
  8. svg: undefined,
  9. g: undefined,
  10. h: 0,
  11. w: 0,
  12. tooltip: undefined
  13. };
  14. // Init tooltip if it is not initialized
  15. this.tooltip = d3.select("#chart-tooltip");
  16. if (!this.tooltip) {
  17. this.tooltip = d3.select("body")
  18. .append("div")
  19. .attr("class", "tooltip")
  20. .attr("id", "chart-tooltip")
  21. .style("opacity", 0);
  22. }
  23. // Init svg
  24. var svg = this.chart.svg;
  25. if (svg) {
  26. svg.remove();
  27. }
  28. var parentId = this.get("parentId");
  29. var parent = d3.select("#" + parentId);
  30. var bbox = parent.node().getBoundingClientRect();
  31. this.chart.w = bbox.width - 30;
  32. var ratio = 0.75; // 4:3 by default
  33. if (this.get("ratio")) {
  34. ratio = this.get("ratio");
  35. }
  36. this.chart.h = bbox.width * ratio;
  37. if (this.get("maxHeight")) {
  38. this.chart.h = Math.min(this.get("maxHeight"), this.chart.h);
  39. }
  40. this.chart.svg = parent.append("svg")
  41. .attr("width", this.chart.w)
  42. .attr("height", this.chart.h);
  43. this.chart.g = this.chart.svg.append("g");
  44. },
  45. renderTitleAndBG: function(g, title, layout) {
  46. var bg = g.append("g");
  47. bg.append("text")
  48. .text(title)
  49. .attr("x", (layout.x1 + layout.x2) / 2)
  50. .attr("y", layout.y1 + layout.margin + 20)
  51. .attr("class", "chart-title");
  52. bg.append("rect")
  53. .attr("x", layout.x1)
  54. .attr("y", layout.y1)
  55. .attr("width", layout.x2 - layout.x1)
  56. .attr("height", layout.y2 - layout.y1)
  57. .attr("class", "chart-frame");
  58. },
  59. bindTooltip: function(d) {
  60. d.on("mouseover", function(d) {
  61. this.tooltip
  62. .style("left", (d3.event.pageX) + "px")
  63. .style("top", (d3.event.pageY - 28) + "px");
  64. }.bind(this))
  65. .on("mousemove", function(d) {
  66. // Handle pie chart case
  67. var data = d;
  68. if (d.data) {
  69. data = d.data;
  70. }
  71. this.tooltip.style("opacity", .9);
  72. this.tooltip.html(data.label + " = " + data.value)
  73. .style("left", (d3.event.pageX) + "px")
  74. .style("top", (d3.event.pageY - 28) + "px");
  75. }.bind(this))
  76. .on("mouseout", function(d) {
  77. this.tooltip.style("opacity", 0);
  78. }.bind(this));
  79. },
  80. getLayout: function() {
  81. var x1 = 0;
  82. var y1 = 0;
  83. var x2 = this.chart.w;
  84. var y2 = this.chart.h;
  85. var layout = {
  86. x1: x1,
  87. y1: y1,
  88. x2: x2 - 10,
  89. y2: y2 - 10,
  90. margin: 10
  91. };
  92. return layout;
  93. },
  94. });