Partition.js 11 KB

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