sankey.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.Sankey = void 0;
  4. const d3_sankey_1 = require("./utils/d3-sankey");
  5. const DEFAULT_OPTIONS = {
  6. nodeAlign: 'justify',
  7. nodeWidth: 0.008,
  8. nodePadding: 0.03,
  9. nodes: (graph) => graph.nodes,
  10. links: (graph) => graph.links,
  11. nodeSort: undefined,
  12. linkSort: undefined,
  13. iterations: 6,
  14. };
  15. const ALIGN_METHOD = {
  16. left: d3_sankey_1.left,
  17. right: d3_sankey_1.right,
  18. center: d3_sankey_1.center,
  19. justify: d3_sankey_1.justify,
  20. };
  21. function getNodeAlignFunction(nodeAlign) {
  22. const type = typeof nodeAlign;
  23. if (type === 'string')
  24. return ALIGN_METHOD[nodeAlign] || d3_sankey_1.justify;
  25. if (type === 'function')
  26. return nodeAlign;
  27. return d3_sankey_1.justify;
  28. }
  29. /**
  30. * Compute the node and edge position, return a graph representing the Sankey layout. All will be normalized to [[0, 0], [1, 1]]
  31. * Required graph data (nodes, edges)
  32. */
  33. const Sankey = (options) => {
  34. return (data) => {
  35. const { nodeId, nodeSort, nodeAlign, nodeWidth, nodePadding, nodeDepth, nodes: nodeNodes, links: nodeLinks, linkSort, iterations, } = Object.assign({}, DEFAULT_OPTIONS, options);
  36. const sankeyProcessor = (0, d3_sankey_1.sankey)()
  37. .nodeSort(nodeSort)
  38. .linkSort(linkSort)
  39. .links(nodeLinks)
  40. .nodes(nodeNodes)
  41. .nodeWidth(nodeWidth)
  42. .nodePadding(nodePadding)
  43. .nodeDepth(nodeDepth)
  44. .nodeAlign(getNodeAlignFunction(nodeAlign))
  45. .iterations(iterations)
  46. .extent([
  47. [0, 0],
  48. [1, 1],
  49. ]);
  50. if (typeof nodeId === 'function') {
  51. sankeyProcessor.nodeId(nodeId);
  52. }
  53. const layoutData = sankeyProcessor(data);
  54. const { nodes: N, links: L } = layoutData;
  55. const nodes = N.map((node) => {
  56. const { x0, x1, y0, y1 } = node;
  57. /* points
  58. * 3---2
  59. * | |
  60. * 0---1
  61. */
  62. return Object.assign(Object.assign({}, node), { x: [x0, x1, x1, x0], y: [y0, y0, y1, y1] });
  63. });
  64. const links = L.map((edge) => {
  65. const { source, target } = edge;
  66. const sx = source.x1;
  67. const tx = target.x0;
  68. const offset = edge.width / 2;
  69. return Object.assign(Object.assign({}, edge), { x: [sx, sx, tx, tx], y: [
  70. edge.y0 + offset,
  71. edge.y0 - offset,
  72. edge.y1 + offset,
  73. edge.y1 - offset,
  74. ] });
  75. });
  76. return { nodes, links };
  77. };
  78. };
  79. exports.Sankey = Sankey;
  80. exports.Sankey.props = {};
  81. //# sourceMappingURL=sankey.js.map