Partition.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /* eslint-disable react/sort-prop-types */
  2. /**
  3. * Licensed to the Apache Software Foundation (ASF) under one
  4. * or more contributor license agreements. See the NOTICE file
  5. * distributed with this work for additional information
  6. * regarding copyright ownership. The ASF licenses this file
  7. * to you under the Apache License, Version 2.0 (the
  8. * "License"); you may not use this file except in compliance
  9. * with the License. You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing,
  14. * software distributed under the License is distributed on an
  15. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16. * KIND, either express or implied. See the License for the
  17. * specific language governing permissions and limitations
  18. * under the License.
  19. */
  20. /* eslint no-param-reassign: [2, {"props": false}] */
  21. /* eslint-disable no-plusplus */
  22. import d3 from 'd3';
  23. import PropTypes from 'prop-types';
  24. import { hierarchy } from 'd3-hierarchy';
  25. import { CategoricalColorNamespace } from '@superset-ui/color';
  26. import { getNumberFormatter } from '@superset-ui/number-format';
  27. import { getTimeFormatter } from '@superset-ui/time-format';
  28. import './Partition.css'; // Compute dx, dy, x, y for each node and
  29. // return an array of nodes in breadth-first order
  30. function init(root) {
  31. const flat = [];
  32. const dy = 1 / (root.height + 1);
  33. let prev = null;
  34. root.each(n => {
  35. n.y = dy * n.depth;
  36. n.dy = dy;
  37. if (n.parent) {
  38. n.x = prev.depth === n.parent.depth ? 0 : prev.x + prev.dx;
  39. n.dx = n.weight / n.parent.sum * n.parent.dx;
  40. } else {
  41. n.x = 0;
  42. n.dx = 1;
  43. }
  44. prev = n;
  45. flat.push(n);
  46. });
  47. return flat;
  48. } // Declare PropTypes for recursive data structures
  49. // https://github.com/facebook/react/issues/5676
  50. /* eslint-disable-next-line no-undef */
  51. const lazyFunction = f => () => f().apply(this, arguments);
  52. const leafType = PropTypes.shape({
  53. name: PropTypes.string,
  54. val: PropTypes.number.isRequired
  55. });
  56. const parentShape = {
  57. name: PropTypes.string,
  58. val: PropTypes.number.isRequired,
  59. children: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape(lazyFunction(() => parentShape)), leafType]))
  60. };
  61. const nodeType = PropTypes.oneOfType([PropTypes.shape(parentShape), leafType]);
  62. const propTypes = {
  63. data: PropTypes.arrayOf(nodeType),
  64. // array of rootNode
  65. width: PropTypes.number,
  66. height: PropTypes.number,
  67. colorScheme: PropTypes.string,
  68. dateTimeFormat: PropTypes.string,
  69. equalDateSize: PropTypes.bool,
  70. levels: PropTypes.arrayOf(PropTypes.string),
  71. metrics: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.object])),
  72. numberFormat: PropTypes.string,
  73. partitionLimit: PropTypes.number,
  74. partitionThreshold: PropTypes.number,
  75. timeSeriesOption: PropTypes.string,
  76. useLogScale: PropTypes.bool,
  77. useRichTooltip: PropTypes.bool
  78. }; // This vis is based on
  79. // http://mbostock.github.io/d3/talk/20111018/partition.html
  80. function Icicle(element, props) {
  81. const {
  82. width,
  83. height,
  84. data,
  85. colorScheme,
  86. dateTimeFormat,
  87. equalDateSize,
  88. levels,
  89. useLogScale = false,
  90. metrics = [],
  91. numberFormat,
  92. partitionLimit,
  93. partitionThreshold,
  94. useRichTooltip,
  95. timeSeriesOption = 'not_time'
  96. } = props;
  97. const div = d3.select(element);
  98. div.classed('superset-legacy-chart-partition', true); // Chart options
  99. const chartType = timeSeriesOption;
  100. const hasTime = ['adv_anal', 'time_series'].includes(chartType);
  101. const format = getNumberFormatter(numberFormat);
  102. const timeFormat = getTimeFormatter(dateTimeFormat);
  103. const colorFn = CategoricalColorNamespace.getScale(colorScheme);
  104. div.selectAll('*').remove();
  105. const tooltip = div.append('div').classed('partition-tooltip', true);
  106. function drawVis(i, dat) {
  107. const datum = dat[i];
  108. const w = width;
  109. const h = height / data.length;
  110. const x = d3.scale.linear().range([0, w]);
  111. const y = d3.scale.linear().range([0, h]);
  112. const viz = div.append('div').attr('class', 'chart').style('width', w + "px").style('height', h + "px").append('svg:svg').attr('width', w).attr('height', h); // Add padding between multiple visualizations
  113. if (i !== data.length - 1 && data.length > 1) {
  114. viz.style('padding-bottom', '3px');
  115. }
  116. if (i !== 0 && data.length > 1) {
  117. viz.style('padding-top', '3px');
  118. }
  119. const root = hierarchy(datum);
  120. function hasDateNode(n) {
  121. return metrics.includes(n.data.name) && hasTime;
  122. } // node.name is the metric/group name
  123. // node.disp is the display value
  124. // node.value determines sorting order
  125. // node.weight determines partition height
  126. // node.sum is the sum of children weights
  127. root.eachAfter(n => {
  128. n.disp = n.data.val;
  129. n.value = n.disp < 0 ? -n.disp : n.disp;
  130. n.weight = n.value;
  131. n.name = n.data.name; // If the parent is a metric and we still have
  132. // the time column, perform a date-time format
  133. if (n.parent && hasDateNode(n.parent)) {
  134. // Format timestamp values
  135. n.weight = equalDateSize ? 1 : n.value;
  136. n.value = n.name;
  137. n.name = timeFormat(n.name);
  138. }
  139. if (useLogScale) n.weight = Math.log(n.weight + 1);
  140. n.disp = n.disp && !Number.isNaN(n.disp) && Number.isFinite(n.disp) ? format(n.disp) : '';
  141. }); // Perform sort by weight
  142. root.sort((a, b) => {
  143. const v = b.value - a.value;
  144. if (v === 0) {
  145. return b.name > a.name ? 1 : -1;
  146. }
  147. return v;
  148. }); // Prune data based on partition limit and threshold
  149. // both are applied at the same time
  150. if (partitionThreshold && partitionThreshold >= 0) {
  151. // Compute weight sums as we go
  152. root.each(n => {
  153. n.sum = n.children ? n.children.reduce((a, v) => a + v.weight, 0) || 1 : 1;
  154. if (n.children) {
  155. // Dates are not ordered by weight
  156. if (hasDateNode(n)) {
  157. if (equalDateSize) {
  158. return;
  159. }
  160. const removeIndices = []; // Keep at least one child
  161. for (let j = 1; j < n.children.length; j++) {
  162. if (n.children[j].weight / n.sum < partitionThreshold) {
  163. removeIndices.push(j);
  164. }
  165. }
  166. for (let j = removeIndices.length - 1; j >= 0; j--) {
  167. n.children.splice(removeIndices[j], 1);
  168. }
  169. } else {
  170. // Find first child that falls below the threshold
  171. let j;
  172. for (j = 1; j < n.children.length; j++) {
  173. if (n.children[j].weight / n.sum < partitionThreshold) {
  174. break;
  175. }
  176. }
  177. n.children = n.children.slice(0, j);
  178. }
  179. }
  180. });
  181. }
  182. if (partitionLimit && partitionLimit >= 0) {
  183. root.each(n => {
  184. if (n.children && n.children.length > partitionLimit) {
  185. if (!hasDateNode(n)) {
  186. n.children = n.children.slice(0, partitionLimit);
  187. }
  188. }
  189. });
  190. } // Compute final weight sums
  191. root.eachAfter(n => {
  192. n.sum = n.children ? n.children.reduce((a, v) => a + v.weight, 0) || 1 : 1;
  193. });
  194. function getCategory(depth) {
  195. if (!depth) {
  196. return 'Metric';
  197. }
  198. if (hasTime && depth === 1) {
  199. return 'Date';
  200. }
  201. return levels[depth - (hasTime ? 2 : 1)];
  202. }
  203. function getAncestors(d) {
  204. const ancestors = [d];
  205. let node = d;
  206. while (node.parent) {
  207. ancestors.push(node.parent);
  208. node = node.parent;
  209. }
  210. return ancestors;
  211. }
  212. function positionAndPopulate(tip, d) {
  213. let t = '<table>';
  214. if (useRichTooltip) {
  215. const nodes = getAncestors(d);
  216. nodes.reverse().forEach(n => {
  217. const atNode = n.depth === d.depth;
  218. t += '<tbody>';
  219. t += '<tr>' + '<td>' + '<div ' + ("style='border: 2px solid " + (atNode ? 'black' : 'transparent') + ";") + ("background-color: " + n.color + ";'") + '></div>' + '</td>' + ("<td>" + getCategory(n.depth) + "</td>") + ("<td>" + n.name + "</td>") + ("<td>" + n.disp + "</td>") + '</tr>';
  220. });
  221. } else {
  222. t += '<thead><tr><td colspan="3">' + ("<strong>" + getCategory(d.depth) + "</strong>") + '</td></tr></thead><tbody>';
  223. t += '<tr>' + '<td>' + ("<div style='border: thin solid grey; background-color: " + d.color + ";'") + '></div>' + '</td>' + ("<td>" + d.name + "</td>") + ("<td>" + d.disp + "</td>") + '</tr>';
  224. }
  225. t += '</tbody></table>';
  226. const [tipX, tipY] = d3.mouse(element);
  227. tip.html(t).style('left', tipX + 15 + "px").style('top', tipY + "px");
  228. }
  229. const nodes = init(root);
  230. let zoomX = w / root.dx;
  231. let zoomY = h / 1; // Keep text centered in its division
  232. function transform(d) {
  233. return "translate(8," + d.dx * zoomY / 2 + ")";
  234. }
  235. const g = viz.selectAll('g').data(nodes).enter().append('svg:g').attr('transform', d => "translate(" + x(d.y) + "," + y(d.x) + ")").on('mouseover', d => {
  236. tooltip.interrupt().transition().duration(100).style('opacity', 0.9);
  237. positionAndPopulate(tooltip, d);
  238. }).on('mousemove', d => {
  239. positionAndPopulate(tooltip, d);
  240. }).on('mouseout', () => {
  241. tooltip.interrupt().transition().duration(250).style('opacity', 0);
  242. }); // When clicking a subdivision, the vis will zoom in to it
  243. function click(d) {
  244. if (!d.children) {
  245. if (d.parent) {
  246. // Clicking on the rightmost level should zoom in
  247. return click(d.parent);
  248. }
  249. return false;
  250. }
  251. zoomX = (d.y ? w - 40 : w) / (1 - d.y);
  252. zoomY = h / d.dx;
  253. x.domain([d.y, 1]).range([d.y ? 40 : 0, w]);
  254. y.domain([d.x, d.x + d.dx]);
  255. const t = g.transition().duration(d3.event.altKey ? 7500 : 750).attr('transform', nd => "translate(" + x(nd.y) + "," + y(nd.x) + ")");
  256. t.select('rect').attr('width', d.dy * zoomX).attr('height', nd => nd.dx * zoomY);
  257. t.select('text').attr('transform', transform).style('opacity', nd => nd.dx * zoomY > 12 ? 1 : 0);
  258. d3.event.stopPropagation();
  259. return true;
  260. }
  261. g.on('click', click);
  262. g.append('svg:rect').attr('width', root.dy * zoomX).attr('height', d => d.dx * zoomY);
  263. g.append('svg:text').attr('transform', transform).attr('dy', '0.35em').style('opacity', d => d.dx * zoomY > 12 ? 1 : 0).text(d => {
  264. if (!d.disp) {
  265. return d.name;
  266. }
  267. return d.name + ": " + d.disp;
  268. }); // Apply color scheme
  269. g.selectAll('rect').style('fill', d => {
  270. d.color = colorFn(d.name);
  271. return d.color;
  272. });
  273. }
  274. for (let i = 0; i < data.length; i++) {
  275. drawVis(i, data);
  276. }
  277. }
  278. Icicle.displayName = 'Icicle';
  279. Icicle.propTypes = propTypes;
  280. export default Icicle;