sankey.js 2.5 KB

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