UNPKG

recharts

Version:
1,465 lines • 57.1 kB
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Sankey = Sankey;
exports.sankeyPayloadSearcher = exports.sankeyDefaultProps = exports.computeData = exports.THEMED_LINK_STROKE_OPACITY = void 0;
var _react = _interopRequireWildcard(require("react"));
var React = _react;
var _maxBy2 = _interopRequireDefault(require("es-toolkit/compat/maxBy"));
var _sumBy = _interopRequireDefault(require("es-toolkit/compat/sumBy"));
var _get = _interopRequireDefault(require("es-toolkit/compat/get"));
var _clsx = require("../util/clsx");
var _Surface = require("../container/Surface");
var _ZIndexPortal = require("../zIndex/ZIndexPortal");
var _Layer = require("../container/Layer");
var _Rectangle = require("../shape/Rectangle");
var _ChartUtils = require("../util/ChartUtils");
var _chartLayoutContext = require("../context/chartLayoutContext");
var _tooltipPortalContext = require("../context/tooltipPortalContext");
var _RechartsWrapper = require("./RechartsWrapper");
var _LabelList = require("../component/LabelList");
var _RechartsStoreProvider = require("../state/RechartsStoreProvider");
var _hooks = require("../state/hooks");
var _tooltipSlice = require("../state/tooltipSlice");
var _SetTooltipEntrySettings = require("../state/SetTooltipEntrySettings");
var _ReportEventSettings = require("../state/ReportEventSettings");
var _chartDataContext = require("../context/chartDataContext");
var _svgPropertiesNoEvents = require("../util/svgPropertiesNoEvents");
var _resolveDefaultProps = require("../util/resolveDefaultProps");
var _isWellBehavedNumber = require("../util/isWellBehavedNumber");
var _DataUtils = require("../util/DataUtils");
var _RegisterGraphicalItemId = require("../context/RegisterGraphicalItemId");
var _eventSettingsSlice = require("../state/eventSettingsSlice");
var _themeFill = require("../theme/themeFill");
var _RechartsThemeContext = require("../theme/RechartsThemeContext");
var _dataEntryStyles = require("../theme/dataEntryStyles");
var _fillDefinitions = require("../fill/fillDefinitions");
var _excluded = ["sourceX", "sourceY", "sourceControlX", "targetX", "targetY", "targetControlX", "linkWidth", "className"],
  _excluded2 = ["id", "target", "d"],
  _excluded3 = ["className", "style", "children", "id"];
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var interpolationGenerator = (a, b) => {
  var ka = +a;
  var kb = b - ka;
  return animationElapsedTime => ka + kb * animationElapsedTime;
};
var centerY = node => node.y + node.dy / 2;
var cubicValue = (start, control1, control2, end, t) => {
  var inverseT = 1 - t;
  return inverseT ** 3 * start + 3 * inverseT ** 2 * t * control1 + 3 * inverseT * t ** 2 * control2 + t ** 3 * end;
};

// TODO why is this not reading dataKey?
var getValue = entry => entry && entry.value || 0;
var getSumOfIds = (links, ids) => ids.reduce((result, id) => result + getValue(links[id]), 0);
var getSumWithWeightedSource = (tree, links, ids) => ids.reduce((result, id) => {
  var link = links[id];
  if (link == null) {
    return result;
  }
  var sourceNode = tree[link.source];
  if (sourceNode == null) {
    return result;
  }
  return result + centerY(sourceNode) * getValue(links[id]);
}, 0);
var getSumWithWeightedTarget = (tree, links, ids) => ids.reduce((result, id) => {
  var link = links[id];
  if (link == null) {
    return result;
  }
  var targetNode = tree[link.target];
  if (targetNode == null) {
    return result;
  }
  return result + centerY(targetNode) * getValue(links[id]);
}, 0);
var ascendingY = (a, b) => a.y - b.y;
/**
 * For every node, finds the links that point to it and the links that leave it, in one pass over the links.
 * The indexes in each list are in the same order as the links. Links with a missing or out of range end are skipped.
 *
 * @param links all links
 * @param nodeCount number of nodes
 * @returns adjacency of each node, by node index
 */
var getAdjacencyOfNodes = (links, nodeCount) => {
  var result = [];
  for (var id = 0; id < nodeCount; id++) {
    result.push({
      sourceNodes: [],
      sourceLinks: [],
      targetNodes: [],
      targetLinks: []
    });
  }
  var isNodeIndex = value => typeof value === 'number' && Number.isInteger(value) && value >= 0 && value < nodeCount;
  for (var i = 0, len = links.length; i < len; i++) {
    var link = links[i];
    if (link == null) {
      continue;
    }
    var source = link.source,
      target = link.target;
    /*
     * A link with one end outside the nodes is skipped on both ends. Recording the valid end alone
     * would give that node a phantom source, so it would no longer count as a root of the layout.
     */
    if (!isNodeIndex(source) || !isNodeIndex(target)) {
      continue;
    }
    var sourceAdjacency = result[source];
    sourceAdjacency === null || sourceAdjacency === void 0 || sourceAdjacency.targetNodes.push(target);
    sourceAdjacency === null || sourceAdjacency === void 0 || sourceAdjacency.targetLinks.push(i);
    var targetAdjacency = result[target];
    targetAdjacency === null || targetAdjacency === void 0 || targetAdjacency.sourceNodes.push(source);
    targetAdjacency === null || targetAdjacency === void 0 || targetAdjacency.sourceLinks.push(i);
  }
  return result;
};
var _updateDepthOfTargets = function updateDepthOfTargets(tree, curNode) {
  var onPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Set();
  var targetNodes = curNode.targetNodes;

  /*
   * `onPath` holds the nodes on the current recursion path, so a link that points back to one of them
   * is skipped instead of followed. Depth is the longest path to a node, so it grows on every trip
   * around a cycle and the `newDepth > target.depth` guard below stays true forever: without this the
   * recursion has no fixed point and exhausts the call stack.
   *
   * This tracks the current path and not every node already seen, because a node in a directed acyclic
   * graph is legitimately reached again by a longer route, and that is the route whose depth wins.
   */
  onPath.add(curNode);
  for (var i = 0, len = targetNodes.length; i < len; i++) {
    var targetNode = targetNodes[i];
    if (targetNode == null) {
      continue;
    }
    var target = tree[targetNode];
    if (target && !onPath.has(target)) {
      var newDepth = curNode.depth + 1;
      /*
       * Only recurse when the depth grows. Depth is the longest path to a node, so once it stops increasing
       * the subtree is already up to date; without this guard every path through the graph is walked
       * separately, which explodes combinatorially on dense graphs.
       */
      if (newDepth > target.depth) {
        target.depth = newDepth;
        _updateDepthOfTargets(tree, target, onPath);
      }
    }
  }
  onPath.delete(curNode);
};
var getNodesTree = (_ref, width, nodeWidth, align) => {
  var _maxBy$depth, _maxBy;
  var nodes = _ref.nodes,
    links = _ref.links;
  var adjacencyOfNodes = getAdjacencyOfNodes(links, nodes.length);
  var tree = nodes.map((entry, index) => {
    var _adjacencyOfNodes$ind;
    var result = (_adjacencyOfNodes$ind = adjacencyOfNodes[index]) !== null && _adjacencyOfNodes$ind !== void 0 ? _adjacencyOfNodes$ind : {
      sourceNodes: [],
      sourceLinks: [],
      targetNodes: [],
      targetLinks: []
    };
    return _objectSpread(_objectSpread(_objectSpread({}, entry), result), {}, {
      value: Math.max(getSumOfIds(links, result.sourceLinks), getSumOfIds(links, result.targetLinks)),
      depth: 0
    });
  });
  for (var i = 0, len = tree.length; i < len; i++) {
    var node = tree[i];
    if (node != null && !node.sourceNodes.length) {
      _updateDepthOfTargets(tree, node);
    }
  }
  var maxDepth = (_maxBy$depth = (_maxBy = (0, _maxBy2.default)(tree, entry => entry.depth)) === null || _maxBy === void 0 ? void 0 : _maxBy.depth) !== null && _maxBy$depth !== void 0 ? _maxBy$depth : 0;
  if (maxDepth >= 1) {
    var childWidth = (width - nodeWidth) / maxDepth;
    for (var _i = 0, _len = tree.length; _i < _len; _i++) {
      var _node = tree[_i];
      if (_node == null) {
        continue;
      }
      if (!_node.targetNodes.length) {
        if (align === 'justify') {
          _node.depth = maxDepth;
        }
      }
      _node.x = _node.depth * childWidth;
      _node.dx = nodeWidth;
    }
  }
  return {
    tree,
    maxDepth
  };
};
var getDepthTree = tree => {
  var result = [];
  for (var i = 0, len = tree.length; i < len; i++) {
    var _result$node$depth;
    var node = tree[i];
    if (node == null) {
      continue;
    }
    if (!result[node.depth]) {
      result[node.depth] = [];
    }
    (_result$node$depth = result[node.depth]) === null || _result$node$depth === void 0 || _result$node$depth.push(node);
  }
  return result;
};

/**
 * @public
 */

var updateYOfTree = (depthTree, height, nodePadding, links, verticalAlign) => {
  var yRatio = Math.min(...depthTree.map(nodes => {
    var value = (0, _sumBy.default)(nodes, getValue);
    return value === 0 ? Infinity : (height - (nodes.length - 1) * nodePadding) / value;
  }));
  if (yRatio === Infinity) {
    yRatio = 0;
  }
  for (var d = 0, maxDepth = depthTree.length; d < maxDepth; d++) {
    var nodes = depthTree[d];
    if (nodes == null) {
      continue;
    }
    if (verticalAlign === 'top') {
      var currentY = 0;
      for (var i = 0, len = nodes.length; i < len; i++) {
        var node = nodes[i];
        if (node == null) {
          continue;
        }
        node.dy = node.value * yRatio;
        node.y = currentY;
        currentY += node.dy + nodePadding;
      }
    } else {
      for (var _i2 = 0, _len2 = nodes.length; _i2 < _len2; _i2++) {
        var _node2 = nodes[_i2];
        if (_node2 == null) {
          continue;
        }
        _node2.y = _i2;
        _node2.dy = _node2.value * yRatio;
      }
    }
  }
  return links.map(link => _objectSpread(_objectSpread({}, link), {}, {
    dy: getValue(link) * yRatio
  }));
};
var resolveCollisions = function resolveCollisions(depthTree, height, nodePadding) {
  var sort = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  for (var i = 0, len = depthTree.length; i < len; i++) {
    var nodes = depthTree[i];
    if (nodes == null) {
      continue;
    }
    var n = nodes.length;

    // Sort by the value of y
    if (sort) {
      nodes.sort(ascendingY);
    }
    var y0 = 0;
    for (var j = 0; j < n; j++) {
      var node = nodes[j];
      if (node == null) {
        continue;
      }
      var dy = y0 - node.y;
      if (dy > 0) {
        node.y += dy;
      }
      y0 = node.y + node.dy + nodePadding;
    }
    y0 = height + nodePadding;
    for (var _j = n - 1; _j >= 0; _j--) {
      var _node3 = nodes[_j];
      if (_node3 == null) {
        continue;
      }
      var _dy = _node3.y + _node3.dy + nodePadding - y0;
      if (_dy > 0) {
        _node3.y -= _dy;
        y0 = _node3.y;
      } else {
        break;
      }
    }
  }
};
var relaxLeftToRight = (tree, depthTree, links, alpha) => {
  for (var i = 0, maxDepth = depthTree.length; i < maxDepth; i++) {
    var nodes = depthTree[i];
    if (nodes == null) {
      continue;
    }
    for (var j = 0, len = nodes.length; j < len; j++) {
      var node = nodes[j];
      if (node == null) {
        continue;
      }
      if (node.sourceLinks.length) {
        var sourceSum = getSumOfIds(links, node.sourceLinks);
        var weightedSum = getSumWithWeightedSource(tree, links, node.sourceLinks);
        var y = sourceSum === 0 ? centerY(node) : weightedSum / sourceSum;
        node.y += (y - centerY(node)) * alpha;
      }
    }
  }
};
var relaxRightToLeft = (tree, depthTree, links, alpha) => {
  for (var i = depthTree.length - 1; i >= 0; i--) {
    var nodes = depthTree[i];
    if (nodes == null) {
      continue;
    }
    for (var j = 0, len = nodes.length; j < len; j++) {
      var node = nodes[j];
      if (node == null) {
        continue;
      }
      if (node.targetLinks.length) {
        var targetSum = getSumOfIds(links, node.targetLinks);
        var weightedSum = getSumWithWeightedTarget(tree, links, node.targetLinks);
        var y = targetSum === 0 ? centerY(node) : weightedSum / targetSum;
        node.y += (y - centerY(node)) * alpha;
      }
    }
  }
};
var updateYOfLinks = (tree, links) => {
  for (var i = 0, len = tree.length; i < len; i++) {
    var node = tree[i];
    if (node == null) {
      continue;
    }
    var sy = 0;
    var ty = 0;
    node.targetLinks.sort((a, b) => {
      var _links$a, _links$b, _tree$targetA, _tree$targetB;
      var targetA = (_links$a = links[a]) === null || _links$a === void 0 ? void 0 : _links$a.target;
      var targetB = (_links$b = links[b]) === null || _links$b === void 0 ? void 0 : _links$b.target;
      if (targetA == null || targetB == null) {
        return 0;
      }
      var yA = (_tree$targetA = tree[targetA]) === null || _tree$targetA === void 0 ? void 0 : _tree$targetA.y;
      var yB = (_tree$targetB = tree[targetB]) === null || _tree$targetB === void 0 ? void 0 : _tree$targetB.y;
      if (yA == null || yB == null) {
        return 0;
      }
      return yA - yB;
    });
    node.sourceLinks.sort((a, b) => {
      var _links$a2, _links$b2, _tree$sourceA, _tree$sourceB;
      var sourceA = (_links$a2 = links[a]) === null || _links$a2 === void 0 ? void 0 : _links$a2.source;
      var sourceB = (_links$b2 = links[b]) === null || _links$b2 === void 0 ? void 0 : _links$b2.source;
      if (sourceA == null || sourceB == null) {
        return 0;
      }
      var yA = (_tree$sourceA = tree[sourceA]) === null || _tree$sourceA === void 0 ? void 0 : _tree$sourceA.y;
      var yB = (_tree$sourceB = tree[sourceB]) === null || _tree$sourceB === void 0 ? void 0 : _tree$sourceB.y;
      if (yA == null || yB == null) {
        return 0;
      }
      return yA - yB;
    });
    for (var j = 0, tLen = node.targetLinks.length; j < tLen; j++) {
      var targetLink = node.targetLinks[j];
      if (targetLink == null) {
        continue;
      }
      var link = links[targetLink];
      if (link) {
        link.sy = sy;
        sy += link.dy;
      }
    }
    for (var _j2 = 0, sLen = node.sourceLinks.length; _j2 < sLen; _j2++) {
      var sourceLink = node.sourceLinks[_j2];
      if (sourceLink == null) {
        continue;
      }
      var _link = links[sourceLink];
      if (_link) {
        _link.ty = ty;
        ty += _link.dy;
      }
    }
  }
};
var getLinkYAtX = (sourceNode, targetNode, link, x) => {
  var _link$sy, _link$ty;
  var sourceX = sourceNode.x + sourceNode.dx;
  var targetX = targetNode.x;
  var progress = targetX === sourceX ? 0 : (x - sourceX) / (targetX - sourceX);
  var boundedProgress = Math.min(Math.max(progress, 0), 1);
  var sourceY = sourceNode.y + ((_link$sy = link.sy) !== null && _link$sy !== void 0 ? _link$sy : 0) + link.dy / 2;
  var targetY = targetNode.y + ((_link$ty = link.ty) !== null && _link$ty !== void 0 ? _link$ty : 0) + link.dy / 2;
  return cubicValue(sourceY, sourceY, targetY, targetY, boundedProgress);
};
var resolveNodeLinkCollisions = (tree, depthTree, links, height, nodePadding) => {
  var depthByNode = new Map();
  for (var depth = 0; depth < depthTree.length; depth++) {
    var nodes = depthTree[depth];
    if (nodes == null) {
      continue;
    }
    for (var node of nodes) {
      depthByNode.set(node, depth);
    }
  }
  var _loop = function _loop(_depth) {
      var nodes = depthTree[_depth];
      if (nodes == null || nodes.length === 0) {
        return 0; // continue
      }
      var depthX = nodes[0] == null ? undefined : nodes[0].x + nodes[0].dx / 2;
      if (depthX == null) {
        return 0; // continue
      }
      var fixedObstacles = links.flatMap(link => {
        var sourceNode = tree[link.source];
        var targetNode = tree[link.target];
        if (sourceNode == null || targetNode == null) {
          return [];
        }
        var sourceDepth = depthByNode.get(sourceNode);
        var targetDepth = depthByNode.get(targetNode);
        if (sourceDepth == null || targetDepth == null) {
          return [];
        }
        if (_depth <= Math.min(sourceDepth, targetDepth) || _depth >= Math.max(sourceDepth, targetDepth)) {
          return [];
        }
        var y = getLinkYAtX(sourceNode, targetNode, link, depthX) - link.dy / 2;
        return [{
          y,
          dy: link.dy,
          fixed: true
        }];
      });
      var containedNodeObstacles = fixedObstacles.filter(obstacle => nodes.some(node => node.y >= obstacle.y && node.y + node.dy <= obstacle.y + obstacle.dy));
      if (containedNodeObstacles.length === 0) {
        return 0; // continue
      }
      var getItemY = item => item.fixed ? item.y : item.node.y;
      var getItemHeight = item => item.fixed ? item.dy : item.node.dy;
      var items = [...nodes.map(node => ({
        node,
        fixed: false
      })), ...containedNodeObstacles].sort((a, b) => getItemY(a) - getItemY(b));
      var nextY = 0;
      for (var item of items) {
        if (item.fixed) {
          nextY = Math.max(nextY, item.y + item.dy + nodePadding);
          continue;
        }
        if (item.node.y < nextY) {
          item.node.y = nextY;
        }
        nextY = item.node.y + item.node.dy + nodePadding;
      }
      items = items.sort((a, b) => getItemY(a) - getItemY(b));
      var previousY = height + nodePadding;
      for (var i = items.length - 1; i >= 0; i--) {
        var _item = items[i];
        if (_item == null) {
          continue;
        }
        if (_item.fixed) {
          previousY = Math.min(previousY, _item.y - nodePadding);
          continue;
        }

        // This backward pass only keeps moved nodes within the chart bounds.
        // It intentionally does not iterate again against fixed obstacles above,
        // because this fix is scoped to the fully-contained skipped-depth case.
        var dy = _item.node.y + getItemHeight(_item) + nodePadding - previousY;
        if (dy > 0) {
          _item.node.y -= dy;
        }
        previousY = _item.node.y;
      }
    },
    _ret;
  for (var _depth = 0; _depth < depthTree.length; _depth++) {
    _ret = _loop(_depth);
    if (_ret === 0) continue;
  }
};
var computeData = _ref2 => {
  var data = _ref2.data,
    width = _ref2.width,
    height = _ref2.height,
    iterations = _ref2.iterations,
    nodeWidth = _ref2.nodeWidth,
    nodePadding = _ref2.nodePadding,
    sort = _ref2.sort,
    verticalAlign = _ref2.verticalAlign,
    align = _ref2.align;
  var links = data.links;
  var _getNodesTree = getNodesTree(data, width, nodeWidth, align),
    tree = _getNodesTree.tree;
  var depthTree = getDepthTree(tree);
  var linksWithDy = updateYOfTree(depthTree, height, nodePadding, links, verticalAlign);
  resolveCollisions(depthTree, height, nodePadding, sort);
  if (verticalAlign === 'justify') {
    var alpha = 1;
    for (var i = 1; i <= iterations; i++) {
      relaxRightToLeft(tree, depthTree, linksWithDy, alpha *= 0.99);
      resolveCollisions(depthTree, height, nodePadding, sort);
      relaxLeftToRight(tree, depthTree, linksWithDy, alpha);
      resolveCollisions(depthTree, height, nodePadding, sort);
    }
  }
  updateYOfLinks(tree, linksWithDy);
  resolveNodeLinkCollisions(tree, depthTree, linksWithDy, height, nodePadding);
  updateYOfLinks(tree, linksWithDy);

  // @ts-expect-error updateYOfLinks modifies the links array to add sy and ty in place
  var newLinks = linksWithDy;
  return {
    nodes: tree,
    links: newLinks
  };
};
exports.computeData = computeData;
var getNodeCoordinateOfTooltip = item => {
  return {
    x: +item.x + +item.width / 2,
    y: +item.y + +item.height / 2
  };
};
var getLinkCoordinateOfTooltip = item => {
  return 'sourceX' in item ? {
    x: (item.sourceX + item.targetX) / 2,
    y: (item.sourceY + item.targetY) / 2
  } : undefined;
};
/**
 * Returns true if the value is a color that paints something, as opposed to a missing color or `none`.
 * @param value fill or stroke
 */
function isPaint(value) {
  return typeof value === 'string' && value !== 'none';
}
/**
 * Returns the color that a node or link is actually painted with.
 * Inline `style` wins over the presentation attribute, same as in the browser.
 * @param props resolved props of a node or link
 * @param key which paint to read
 * @returns the color, or undefined if the shape is not painted with a color
 */
function getRenderedPaint(props, key) {
  if (props == null) {
    return undefined;
  }
  var style = props.style;
  var fromStyle = style != null && typeof style === 'object' ? Reflect.get(style, key) : undefined;
  if (fromStyle != null) {
    return isPaint(fromStyle) ? fromStyle : undefined;
  }
  var fromAttribute = props[key];
  return isPaint(fromAttribute) ? fromAttribute : undefined;
}
var getPayloadOfTooltip = (item, type, nameKey) => {
  var payload = item.payload;
  if (type === 'node') {
    return {
      payload,
      name: (0, _ChartUtils.getValueByDataKey)(payload, nameKey, ''),
      value: (0, _ChartUtils.getValueByDataKey)(payload, 'value'),
      color: getRenderedPaint(item, 'fill')
    };
  }
  if ('source' in payload && payload.source && payload.target) {
    // @ts-expect-error we're sending number indexes as source and target, but getValueByDataKey expects objects
    var sourceName = (0, _ChartUtils.getValueByDataKey)(payload.source, nameKey, '');
    // @ts-expect-error we're sending number indexes as source and target, but getValueByDataKey expects objects
    var targetName = (0, _ChartUtils.getValueByDataKey)(payload.target, nameKey, '');
    return {
      payload,
      name: "".concat(sourceName, " - ").concat(targetName),
      value: (0, _ChartUtils.getValueByDataKey)(payload, 'value'),
      color: getRenderedPaint(item, 'stroke')
    };
  }
  return undefined;
};
var sankeyPayloadSearcher = (_, activeIndex, computedData, nameKey) => {
  if (activeIndex == null || typeof activeIndex !== 'string') {
    return undefined;
  }
  if (computedData == null || typeof computedData !== 'object') {
    return undefined;
  }
  var splitIndex = activeIndex.split('-');
  var _splitIndex = _slicedToArray(splitIndex, 2),
    targetType = _splitIndex[0],
    index = _splitIndex[1];
  var item = (0, _get.default)(computedData, "".concat(targetType, "s[").concat(index, "]"));
  if (item) {
    // @ts-expect-error nameKey type does not match SankeyElementType
    var payload = getPayloadOfTooltip(item, targetType, nameKey);
    return payload;
  }
  return undefined;
};
exports.sankeyPayloadSearcher = sankeyPayloadSearcher;
var options = {
  chartName: 'Sankey',
  defaultTooltipEventType: 'item',
  validateTooltipEventTypes: ['item'],
  tooltipPayloadSearcher: sankeyPayloadSearcher,
  eventEmitter: undefined
};
var SetSankeyTooltipEntrySettings = /*#__PURE__*/React.memo(_ref3 => {
  var dataKey = _ref3.dataKey,
    nameKey = _ref3.nameKey,
    stroke = _ref3.stroke,
    strokeWidth = _ref3.strokeWidth,
    fill = _ref3.fill,
    name = _ref3.name,
    data = _ref3.data,
    id = _ref3.id;
  var tooltipEntrySettings = {
    dataDefinedOnItem: data,
    getPosition: _DataUtils.noop,
    settings: {
      stroke,
      strokeWidth,
      fill,
      dataKey,
      name,
      nameKey,
      hide: false,
      type: undefined,
      color: fill,
      unit: '',
      graphicalItemId: id
    }
  };
  return /*#__PURE__*/React.createElement(_SetTooltipEntrySettings.SetTooltipEntrySettings, {
    tooltipEntrySettings: tooltipEntrySettings
  });
});

/**
 * A link in the Sankey data.
 *
 * Valid SVG properties such as `stroke`, `strokeDasharray`, `opacity` or `className` are spread on the link path.
 * `id` and `d` are not, because ids must be unique and Sankey computes the path itself.
 * With a theme, a link that defines its own `fill` or `stroke` ignores the theme colors.
 */

/**
 * @public
 */

/**
 * @public
 */

/**
 * @public
 */

// TODO: improve types - NodeOptions uses SankeyNode, LinkOptions uses LinkProps. Standardize.
/**
 * @public
 */

/**
 * @public
 */

/**
 * @public
 */

/**
 * @public
 */

/**
 * Link styles used when there is no theme. A themed Sankey does not use these at all.
 */
var legacyLinkStyles = {
  stroke: '#333',
  strokeOpacity: '0.2'
};

/**
 * Node styles used when there is no theme. A themed Sankey does not use these at all.
 */
var legacyNodeStyles = {
  fill: '#0088fe',
  fillOpacity: '0.8'
};

/**
 * @param option the `link` prop
 * @param props resolved props of the link
 * @param hasTheme true if a theme is active, in which case the legacy styles are not applied
 */
function renderLinkItem(option, props, hasTheme) {
  if (/*#__PURE__*/React.isValidElement(option)) {
    return /*#__PURE__*/React.cloneElement(option, props);
  }
  if (typeof option === 'function') {
    return option(props);
  }
  var sourceX = props.sourceX,
    sourceY = props.sourceY,
    sourceControlX = props.sourceControlX,
    targetX = props.targetX,
    targetY = props.targetY,
    targetControlX = props.targetControlX,
    linkWidth = props.linkWidth,
    className = props.className,
    others = _objectWithoutProperties(props, _excluded);
  return /*#__PURE__*/React.createElement("path", _extends({
    d: "\n          M".concat(sourceX, ",").concat(sourceY, "\n          C").concat(sourceControlX, ",").concat(sourceY, " ").concat(targetControlX, ",").concat(targetY, " ").concat(targetX, ",").concat(targetY, "\n        "),
    fill: "none"
  }, hasTheme ? undefined : legacyLinkStyles, {
    strokeWidth: linkWidth
  }, (0, _svgPropertiesNoEvents.svgPropertiesNoEvents)(others), {
    className: (0, _clsx.clsx)('recharts-sankey-link', className)
  }));
}
var buildLinkProps = _ref4 => {
  var link = _ref4.link,
    nodes = _ref4.nodes,
    left = _ref4.left,
    top = _ref4.top,
    i = _ref4.i,
    linkContent = _ref4.linkContent,
    linkCurvature = _ref4.linkCurvature,
    themeStyles = _ref4.themeStyles,
    ownStyles = _ref4.ownStyles;
  var sourceRelativeY = link.sy,
    targetRelativeY = link.ty,
    linkWidth = link.dy;
  var sourceNode = nodes[link.source];
  var targetNode = nodes[link.target];
  if (sourceNode == null || targetNode == null) {
    return undefined;
  }
  var sourceX = sourceNode.x + sourceNode.dx + left;
  var targetX = targetNode.x + left;
  var interpolationFunc = interpolationGenerator(sourceX, targetX);
  var sourceControlX = interpolationFunc(linkCurvature);
  var targetControlX = interpolationFunc(1 - linkCurvature);
  var sourceY = sourceNode.y + sourceRelativeY + linkWidth / 2 + top;
  var targetY = targetNode.y + targetRelativeY + linkWidth / 2 + top;

  // The geometry comes last, so that `targetX` and `targetY`, which are also valid SVG attributes, can't move the link.
  // @ts-expect-error linkContent is passing in unknown props
  var linkProps = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, themeStyles), (0, _svgPropertiesNoEvents.svgPropertiesNoEventsFromUnknown)(linkContent)), ownStyles), {}, {
    sourceX,
    targetX,
    sourceY,
    targetY,
    sourceControlX,
    targetControlX,
    sourceRelativeY,
    targetRelativeY,
    linkWidth,
    index: i,
    payload: _objectSpread(_objectSpread({}, link), {}, {
      source: sourceNode,
      target: targetNode
    })
  });
  return linkProps;
};
function SankeyLinkElement(_ref5) {
  var graphicalItemId = _ref5.graphicalItemId,
    props = _ref5.props,
    i = _ref5.i,
    linkContent = _ref5.linkContent,
    _onMouseEnter = _ref5.onMouseEnter,
    _onMouseLeave = _ref5.onMouseLeave,
    _onClick = _ref5.onClick,
    dataKey = _ref5.dataKey;
  var activeCoordinate = getLinkCoordinateOfTooltip(props);
  var activeIndex = "link-".concat(i);
  var hasTheme = (0, _RechartsThemeContext.useRechartsTheme)() != null;
  var dispatch = (0, _hooks.useAppDispatch)();
  var events = {
    onMouseEnter: e => {
      dispatch((0, _tooltipSlice.setActiveMouseOverItemIndex)({
        activeIndex,
        activeDataKey: dataKey,
        activeCoordinate,
        activeGraphicalItemId: graphicalItemId
      }));
      _onMouseEnter(props, e);
    },
    onMouseLeave: e => {
      dispatch((0, _tooltipSlice.mouseLeaveItem)());
      _onMouseLeave(props, e);
    },
    onClick: e => {
      dispatch((0, _tooltipSlice.setActiveClickItemIndex)({
        activeIndex,
        activeDataKey: dataKey,
        activeCoordinate,
        activeGraphicalItemId: graphicalItemId
      }));
      _onClick(props, e);
    }
  };
  return /*#__PURE__*/React.createElement(_Layer.Layer, events, renderLinkItem(linkContent, props, hasTheme));
}
function AllSankeyLinkElements(_ref6) {
  var graphicalItemId = _ref6.graphicalItemId,
    modifiedLinks = _ref6.modifiedLinks,
    links = _ref6.links,
    linkContent = _ref6.linkContent,
    onMouseEnter = _ref6.onMouseEnter,
    onMouseLeave = _ref6.onMouseLeave,
    onClick = _ref6.onClick,
    dataKey = _ref6.dataKey;
  return /*#__PURE__*/React.createElement(_Layer.Layer, {
    className: "recharts-sankey-links",
    key: "recharts-sankey-links"
  }, links.map((link, i) => {
    var linkProps = modifiedLinks[i];
    if (linkProps == null) {
      return null;
    }
    return /*#__PURE__*/React.createElement(SankeyLinkElement, {
      graphicalItemId: graphicalItemId,
      key: "link-".concat(link.source, "-").concat(link.target, "-").concat(link.value),
      props: linkProps,
      linkContent: linkContent,
      i: i,
      onMouseEnter: onMouseEnter,
      onMouseLeave: onMouseLeave,
      onClick: onClick,
      dataKey: dataKey
    });
  }));
}

/**
 * The fill the node is actually rendered with.
 *
 * `renderNodeItem` puts the legacy default fill on the rectangle first and spreads the node props over
 * it, so an explicit `fill` wins over the default. An inline `style.fill` wins over the `fill`
 * attribute in the CSS cascade, so it wins over both.
 *
 * @param nodeProps resolved props of the node
 * @param hasTheme true if a theme is active, in which case the legacy styles are not applied
 * @returns the fill of the rendered node, undefined when the node has no fill of its own
 */
function getRenderedNodeFill(nodeProps, hasTheme) {
  var _nodeProps$style;
  var styleFill = (_nodeProps$style = nodeProps.style) === null || _nodeProps$style === void 0 ? void 0 : _nodeProps$style.fill;
  if (typeof styleFill === 'string') {
    return styleFill;
  }
  if (typeof nodeProps.fill === 'string') {
    return nodeProps.fill;
  }
  if (!hasTheme) {
    return legacyNodeStyles.fill;
  }
  return undefined;
}

/**
 * @param option the `node` prop
 * @param props resolved props of the node
 * @param hasTheme true if a theme is active, in which case the legacy styles are not applied
 */
/**
 * @param option the `node` prop
 * @param props resolved props of the node
 * @param hasTheme true if a theme is active, in which case the legacy styles are not applied
 * @param fillDefinition the fill definition of the node, if it paints with one. It gets the color of the node.
 */
function renderNodeItem(option, props, hasTheme, fillDefinition) {
  if (/*#__PURE__*/React.isValidElement(option)) {
    return /*#__PURE__*/React.cloneElement(option, props);
  }
  if (typeof option === 'function') {
    return option(props);
  }
  return (
    /*#__PURE__*/
    // @ts-expect-error recharts radius is not compatible with SVG radius
    React.createElement(_Rectangle.Rectangle, _extends({}, hasTheme ? undefined : legacyNodeStyles, (0, _svgPropertiesNoEvents.svgPropertiesNoEvents)(props), fillDefinition == null ? undefined : {
      fill: {
        color: getRenderedNodeFill(props, hasTheme),
        definition: fillDefinition
      }
    }, {
      className: (0, _clsx.clsx)('recharts-sankey-node', props.className)
    }))
  );
}
var buildNodeProps = _ref7 => {
  var node = _ref7.node,
    nodeContent = _ref7.nodeContent,
    top = _ref7.top,
    left = _ref7.left,
    i = _ref7.i,
    themeStyles = _ref7.themeStyles,
    ownStyles = _ref7.ownStyles;
  var x = node.x,
    y = node.y,
    dx = node.dx,
    dy = node.dy;
  // @ts-expect-error nodeContent is passing in unknown props
  var nodeProps = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, themeStyles), (0, _svgPropertiesNoEvents.svgPropertiesNoEventsFromUnknown)(nodeContent)), ownStyles), {}, {
    x: x + left,
    y: y + top,
    width: dx,
    height: dy,
    index: i,
    payload: node
  });
  return nodeProps;
};
function NodeElement(_ref8) {
  var graphicalItemId = _ref8.graphicalItemId,
    props = _ref8.props,
    fillDefinition = _ref8.fillDefinition,
    nodeContent = _ref8.nodeContent,
    i = _ref8.i,
    _onMouseEnter2 = _ref8.onMouseEnter,
    _onMouseLeave2 = _ref8.onMouseLeave,
    _onClick2 = _ref8.onClick,
    dataKey = _ref8.dataKey;
  var dispatch = (0, _hooks.useAppDispatch)();
  var activeCoordinate = getNodeCoordinateOfTooltip(props);
  var activeIndex = "node-".concat(i);
  var hasTheme = (0, _RechartsThemeContext.useRechartsTheme)() != null;
  var events = {
    onMouseEnter: e => {
      dispatch((0, _tooltipSlice.setActiveMouseOverItemIndex)({
        activeIndex,
        activeDataKey: dataKey,
        activeCoordinate,
        activeGraphicalItemId: graphicalItemId
      }));
      _onMouseEnter2(props, e);
    },
    onMouseLeave: e => {
      dispatch((0, _tooltipSlice.mouseLeaveItem)());
      _onMouseLeave2(props, e);
    },
    onClick: e => {
      dispatch((0, _tooltipSlice.setActiveClickItemIndex)({
        activeIndex,
        activeDataKey: dataKey,
        activeCoordinate,
        activeGraphicalItemId: graphicalItemId
      }));
      _onClick2(props, e);
    }
  };
  return /*#__PURE__*/React.createElement(_Layer.Layer, events, renderNodeItem(nodeContent, props, hasTheme, fillDefinition));
}

/**
 * Publishes one cartesian label-list entry per node so that `LabelList`,
 * and the implicit `label` prop, can draw node labels like in other charts.
 *
 * The entry value is the node name read through `nameKey`, so labels honor the
 * same accessor as the tooltip. The entry fill is the fill the node renders with,
 * so a label without an explicit fill inherits the color of its node.
 */
function SankeyLabelListProvider(_ref9) {
  var nodes = _ref9.nodes,
    nameKey = _ref9.nameKey,
    children = _ref9.children;
  var hasTheme = (0, _RechartsThemeContext.useRechartsTheme)() != null;
  /*
   * A label that is drawn on top of a node swallows the hover and the click of that node, so the labels
   * of a Sankey do not take pointer events. A user that sets `pointerEvents` on a `LabelList` keeps
   * their own value.
   */
  var childrenWithPointerEvents = React.Children.map(children, child => {
    var _child$props$pointerE;
    if (! /*#__PURE__*/React.isValidElement(child) || child.type !== _LabelList.LabelList) {
      return child;
    }
    return /*#__PURE__*/React.cloneElement(child, {
      pointerEvents: (_child$props$pointerE = child.props.pointerEvents) !== null && _child$props$pointerE !== void 0 ? _child$props$pointerE : 'none'
    });
  });
  var labelListEntries = (0, _react.useMemo)(() => nodes.map(nodeProps => {
    var viewBox = {
      x: nodeProps.x,
      y: nodeProps.y,
      width: nodeProps.width,
      lowerWidth: nodeProps.width,
      upperWidth: nodeProps.width,
      height: nodeProps.height
    };
    return _objectSpread(_objectSpread({}, viewBox), {}, {
      // @ts-expect-error the same accessor the tooltip reads, but the node union does not accept a plain string dataKey
      value: (0, _ChartUtils.getValueByDataKey)(nodeProps.payload, nameKey, ''),
      payload: nodeProps.payload,
      parentViewBox: undefined,
      viewBox,
      fill: getRenderedNodeFill(nodeProps, hasTheme)
    });
  }), [nodes, nameKey, hasTheme]);
  return /*#__PURE__*/React.createElement(_LabelList.CartesianLabelListContextProvider, {
    value: labelListEntries
  }, childrenWithPointerEvents);
}
function AllNodeElements(_ref0) {
  var graphicalItemId = _ref0.graphicalItemId,
    modifiedNodes = _ref0.modifiedNodes,
    nodeFillDefinitions = _ref0.nodeFillDefinitions,
    nodeContent = _ref0.nodeContent,
    onMouseEnter = _ref0.onMouseEnter,
    onMouseLeave = _ref0.onMouseLeave,
    onClick = _ref0.onClick,
    dataKey = _ref0.dataKey;
  return /*#__PURE__*/React.createElement(_Layer.Layer, {
    className: "recharts-sankey-nodes",
    key: "recharts-sankey-nodes"
  }, modifiedNodes.map((modifiedNode, i) => {
    return /*#__PURE__*/React.createElement(NodeElement, {
      graphicalItemId: graphicalItemId,
      key: "node-".concat(modifiedNode.index, "-").concat(modifiedNode.x, "-").concat(modifiedNode.y),
      props: modifiedNode,
      fillDefinition: nodeFillDefinitions[i],
      nodeContent: nodeContent,
      i: i,
      onMouseEnter: onMouseEnter,
      onMouseLeave: onMouseLeave,
      onClick: onClick,
      dataKey: dataKey
    });
  }));
}

/**
 * Stroke opacity of links that take their color from the theme.
 *
 * Links are painted in the color of their source node, so that a flow keeps its color
 * from one end to the other. They are drawn with reduced opacity so that the nodes stand out,
 * and so that overlapping links stay see-through.
 */
var THEMED_LINK_STROKE_OPACITY = exports.THEMED_LINK_STROKE_OPACITY = 0.4;

/**
 * SVG props read from a node or link data entry.
 */

/**
 * Reads the SVG props that a node or link data entry applies to its shape.
 *
 * - `id` is removed, because ids must be unique on the page and the data entry is not the only place they could come from.
 * - `target` is removed, because in a link it is the index of the target node, not the SVG `target` attribute.
 * - `d` is removed, because Sankey computes the link path. Node position and size are set after these props for the same reason.
 * @param entry entry from `data.nodes` or `data.links`
 */
function getEntrySvgProps(entry) {
  var _svgPropertiesNoEvent;
  var _ref1 = (_svgPropertiesNoEvent = (0, _svgPropertiesNoEvents.svgPropertiesNoEventsFromUnknown)(entry)) !== null && _svgPropertiesNoEvent !== void 0 ? _svgPropertiesNoEvent : {},
    id = _ref1.id,
    target = _ref1.target,
    d = _ref1.d,
    svgProps = _objectWithoutProperties(_ref1, _excluded2);
  var result = {};
  // Skip null and undefined, so that `{ stroke: undefined }` keeps the stroke from props, the theme or the defaults.
  for (var key in svgProps) {
    if (Object.prototype.hasOwnProperty.call(svgProps, key)) {
      var value = key === 'fill' ? (0, _fillDefinitions.readEntryFill)(entry).color : Reflect.get(svgProps, key);
      // a fill object counts by its color; it paints through its definition
      if (value != null) {
        result[key] = value;
      }
    }
  }
  return result;
}

/**
 * Resolves the theme and data styles of a single node.
 *
 * Valid SVG props from the data entry are always spread on the node, with or without a theme.
 *
 * With a theme, nodes take the theme colors by their index in `data.nodes`,
 * so that a node keeps its color when the layout or sorting changes.
 * A node whose data entry or `node` prop defines its own `fill` or `stroke` drops the theme fill and stroke together,
 * and keeps the other theme styles.
 * @param themeGraphicalItems graphicalItems of the active theme, or undefined if there is no theme
 * @param themeFillObjects the fill object of each theme entry, from {@link useThemeFillObjects}
 * @param dataNode entry from `data.nodes`
 * @param index index of the node in `data.nodes`
 * @param nodeContent the `node` prop
 */
function resolveNodeStyles(themeGraphicalItems, themeFillObjects, dataNode, index, nodeContent) {
  var _readEntryFill$fillOb, _readEntryFill$fillOb2, _readEntryFill$fillOb3, _themeFillObjects;
  var ownStyles = getEntrySvgProps(dataNode);
  var ownFillDefinition = (_readEntryFill$fillOb = (_readEntryFill$fillOb2 = (0, _fillDefinitions.readEntryFill)(dataNode).fillObject) === null || _readEntryFill$fillOb2 === void 0 ? void 0 : _readEntryFill$fillOb2.definition) !== null && _readEntryFill$fillOb !== void 0 ? _readEntryFill$fillOb : (_readEntryFill$fillOb3 = (0, _fillDefinitions.readEntryFill)(nodeContent).fillObject) === null || _readEntryFill$fillOb3 === void 0 ? void 0 : _readEntryFill$fillOb3.definition;
  if (themeGraphicalItems == null) {
    return {
      themeStyles: {},
      ownStyles,
      fillDefinition: ownFillDefinition
    };
  }
  var themeItem = themeGraphicalItems.length === 0 ? undefined : themeGraphicalItems[index % themeGraphicalItems.length];
  var hasExplicitColors = (0, _dataEntryStyles.hasOwnColors)(ownStyles) || (0, _dataEntryStyles.hasOwnColors)((0, _svgPropertiesNoEvents.svgPropertiesNoEventsFromUnknown)(nodeContent));
  // Styles without a color of their own merge with the theme.
  return {
    themeStyles: (0, _dataEntryStyles.getOwnStyles)(hasExplicitColors ? (0, _dataEntryStyles.withoutColors)(themeItem) : themeItem),
    ownStyles,
    fillDefinition: ownFillDefinition !== null && ownFillDefinition !== void 0 ? ownFillDefinition : hasExplicitColors || themeFillObjects.length === 0 ? undefined : (_themeFillObjects = themeFillObjects[index % themeFillObjects.length]) === null || _themeFillObjects === void 0 ? void 0 : _themeFillObjects.definition
  };
}

/**
 * Resolves the theme and data styles of a single link.
 *
 * Valid SVG props from the data entry are always spread on the link, with or without a theme.
 *
 * With a theme, links take the color of their source node, including colors from explicit props and from data,
 * and draw it with {@link THEMED_LINK_STROKE_OPACITY}. Explicit `link` props override these field by field,
 * so `link={{ stroke: 'red' }}` keeps the see-through links.
 * A link whose data entry defines its own `fill` or `stroke` drops the theme color, and keeps the theme opacity.
 * @param themeGraphicalItems graphicalItems of the active theme, or undefined if there is no theme
 * @param dataLink entry from `data.links`
 * @param sourceNodeProps resolved props of the source node
 */
function resolveLinkStyles(themeGraphicalItems, dataLink, sourceNodeProps) {
  var _getRenderedPaint;
  var ownStyles = getEntrySvgProps(dataLink);
  if (themeGraphicalItems == null) {
    return {
      themeStyles: {},
      ownStyles
    };
  }
  if ((0, _dataEntryStyles.hasOwnColors)(ownStyles)) {
    return {
      themeStyles: {
        strokeOpacity: THEMED_LINK_STROKE_OPACITY
      },
      ownStyles
    };
  }
  var sourceColor = (_getRenderedPaint = getRenderedPaint(sourceNodeProps, 'fill')) !== null && _getRenderedPaint !== void 0 ? _getRenderedPaint : getRenderedPaint(sourceNodeProps, 'stroke');
  if (sourceColor == null) {
    return {
      themeStyles: {},
      ownStyles
    };
  }
  return {
    themeStyles: {
      stroke: sourceColor,
      strokeOpacity: THEMED_LINK_STROKE_OPACITY
    },
    ownStyles
  };
}
var sankeyDefaultProps = exports.sankeyDefaultProps = _objectSpread({
  accessibilityLayer: true,
  align: 'justify',
  dataKey: 'value',
  iterations: 32,
  label: false,
  linkCurvature: 0.5,
  margin: {
    top: 5,
    right: 5,
    bottom: 5,
    left: 5
  },
  nameKey: 'name',
  nodePadding: 10,
  nodeWidth: 10,
  sort: true,
  verticalAlign: 'justify'
}, _eventSettingsSlice.initialEventSettingsState);
function SankeyImpl(props) {
  var _useRechartsTheme;
  var className = props.className,
    style = props.style,
    children = props.children,
    id = props.id,
    others = _objectWithoutProperties(props, _excluded3);
  var link = props.link,
    dataKey = props.dataKey,
    node = props.node,
    label = props.label,
    nameKey = props.nameKey,
    onMouseEnter = props.onMouseEnter,
    onMouseLeave = props.onMouseLeave,
    onClick = props.onClick,
    data = props.data,
    iterations = props.iterations,
    nodeWidth = props.nodeWidth,
    nodePadding = props.nodePadding,
    sort = props.sort,
    linkCurvature = props.linkCurvature,
    margin = props.margin,
    verticalAlign = props.verticalAlign,
    align = props.align,
    accessibilityLayer = props.accessibilityLayer,
    title = props.title,
    desc = props.desc;
  var attrs = (0, _svgPropertiesNoEvents.svgPropertiesNoEvents)(others);
  var tabIndex, role;
  if (typeof attrs.tabIndex === 'number') {
    tabIndex = attrs.tabIndex;
  } else {
    tabIndex = accessibilityLayer ? 0 : undefined;
  }
  if (typeof attrs.role === 'string') {
    role = attrs.role;
  } else {
    role = accessibilityLayer ? 'application' : undefined;
  }
  var width = (0, _chartLayoutContext.useChartWidth)();
  var height = (0, _chartLayoutContext.useChartHeight)();
  var themeGraphicalItems = (0, _themeFill.getColorGraphicalItems)((_useRechartsTheme = (0, _RechartsThemeContext.useRechartsTheme)()) === null || _useRechartsTheme === void 0 ? void 0 : _useRechartsTheme.graphicalItems);
  var themeFillObjects = (0, _fillDefinitions.useThemeFillObjects)();
  var _useMemo = (0, _react.useMemo)(() => {
      var _margin$left, _margin$right, _margin$top, _margin$bottom;
      if (!data || !width || !height || width <= 0 || height <= 0) {
        return {
          nodes: [],
          links: [],
          modifiedLinks: [],
          modifiedNodes: [],
          nodeFillDefinitions: []
        };
      }
      var contentWidth = width - ((_margin$left = margin.left) !== null && _margin$left !== void 0 ? _margin$left : 0) - ((_margin$right = margin.right) !== null && _margin$right !== void 0 ? _margin$right : 0);
      var contentHeight = height - ((_margin$top = margin.top) !== null && _margin$top !== void 0 ? _margin$top : 0) - ((_margin$bottom = margin.bottom) !== null && _margin$bottom !== void 0 ? _margin$bottom : 0);
      var computed = computeData({
        data,
        width: contentWidth,
        height: contentHeight,
        iterations,
        nodeWidth,
        nodePadding,
        sort,
        verticalAlign,
        align
      });
      var top = margin.top || 0;
      var left = margin.left || 0;
      var newNodeFillDefinitions = [];
      var newModifiedNodes = computed.nodes.map((n, i) => {
        var _resolveNodeStyles = resolveNodeStyles(themeGraphicalItems, themeFillObjects, data.nodes[i], i, node),
          themeStyles = _resolveNodeStyles.themeStyles,
          ownStyles = _resolveNodeStyles.ownStyles,
          fillDefinition = _resolveNodeStyles.fillDefinition;
        newNodeFillDefinitions.push(fillDefinition);
        return buildNodeProps({
          node: n,
          nodeContent: node,
          i,
          top,
          left,
          themeStyles,
          ownStyles
        });
      });
      var newModifiedLinks = computed.links.map((l, i) => {
        var _resolveLinkStyles = resolveLinkStyles(themeGraphicalItems, data.links[i], newModifiedNodes[l.source]),
          themeStyles = _resolveLinkStyles.themeStyles,
          ownStyles = _resolveLinkStyles.ownStyles;
        return buildLinkProps({
          link: l,
          nodes: computed.nodes,
          i,
          top,
          left,
          linkContent: link,
          linkCurvature,
          themeStyles,
          ownStyles
        });
      }).filter(_DataUtils.isNotNil);
      return {
        nodes: computed.nodes,
        links: computed.links,
        modifiedLinks: newModifiedLinks,
        modifiedNodes: newModifiedNodes,
        nodeFillDefinitions: newNodeFillDefinitions
      };
    }, [data, width, height, margin, iterations, nodeWidth, nodePadding, sort, link, node, linkCurvature, align, verticalAlign, themeGraphicalItems, themeFillObjects]),
    links = _useMemo.links,
    modifiedLinks = _useMemo.modifiedLinks,
    modifiedNodes = _useMemo.modifiedNodes,
    nodeFillDefinitions = _useMemo.nodeFillDefinitions;
  var handleMouseEnter = (0, _react.useCallback)((item, type, e) => {
    if (onMouseEnter) {
      onMouseEnter(item, type, e);
    }
  }, [onMouseEnter]);
  var handleMouseLeave = (0, _react.useCallback)((item, type, e) => {
    if (onMouseLeave) {
      onMouseLeave(item, type, e);
    }
  }, [onMouseLeave]);
  var handleClick = (0, _react.useCallback)((item, type, e) => {
    if (onClick) {
      onClick(item, type, e);
    }
  }, [onClick]);
  if (!(0, _isWellBehavedNumber.isPositiveNumber)(width) || !(0, _isWellBehavedNumber.isPositiveNumber)(height) || !data || !data.links || !data.nodes) {
    return null;
  }
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(_chartDataContext.SetComputedData, {
    computedData: {
      links: modifiedLinks,
      nodes: modifiedNodes
    }
  }), /*#__PURE__*/React.createElement(_Surface.Surface, _extends({}, attrs, {
    title: title,
    desc: desc,
    role: role,
    tabIndex: tabIndex,
    width: width,
    height: height
  }), /*#__PURE__*/React.createElement(_ZIndexPortal.AllZIndexPortals, {
    isPanorama: false
  }, /*#__PURE__*/React.createElement(SankeyLabelListProvider, {
    nodes: modifiedNodes,
    nameKey: nameKey
  }, children, /*#__PURE__*/React.createElement(AllSankeyLinkElements, {
    graphicalItemId: id,
    links: links,
    modifiedLinks: modifiedLinks,
    linkContent: link,
    dataKey: dataKey,
    onMouseEnter: (linkProps, e) => handleMouseEnter(linkProps, 'link', e),
    onMouseLeave: (linkProps, e) => handleMouseLeave(linkProps, 'link', e),
    onClick: (linkProps, e) => handleClick(linkProps, 'link', e)
  }), /*#__PURE__*/React.createElement(AllNodeElements, {
    graphicalItemId: id,
    modifiedNodes: modifiedNodes,
    nodeFillDefinitions: nodeFillDefinitions,
    nodeContent: node,
    dataKey: dataKey,
    onMouseEnter: (nodeProps, e) => handleMouseEnter(nodeProps, 'node', e),
    onMouseLeave: (nodeProps, e) => handleMouseLeave(nodeProps, 'node', e),
    onClick: (nodeProps, e) => handleClick(nodeProps, 'node', e)
  }), /*#__PURE__*/React.createElement(_LabelList.LabelListFromLabelProp, {
    label: label,
    pointerEvents: "none"
  })))));
}

/**
 * Flow diagram in which the width of the arrows is proportional to the flow rate.
 * It is typically used to visualize energy or material or cost transfers between processes.
 *
 * @consumes ResponsiveContainerContext
 * @provides TooltipEntrySettings
 * @public
 */
function Sankey(outsideProps) {
  var props = (0, _resolveDefaultProps.resolveDefaultProps)(outsideProps, sankeyDefaultProps);
  var width = props.width,
    height = props.height,
    style = props.style,
    className = props.className,
    externalId = props.id,
    throttleDelay = props.throttleDelay,
    throttledEvents = props.throttledEvents;
  var _useState = (0, _react.useState)(null),
    _useState2 = _slicedToArray(_useState, 2),
    tooltipPortal = _useState2[0],
    setTooltipPortal = _useState2[1];
  return /*#__PURE__*/React.createElement(_RechartsStoreProvider.RechartsStoreProvider, {
    preloadedState: {
      options
    },
    reduxStoreName: className !== null && className !== void 0 ? className : 'Sankey'
  }, /*#__PURE__*/React.createElement(_chartLayoutContext.ReportChartSize, {
    width: width,
    height: height
  }), /*#__PURE__*/React.createElement(_chartLayoutContext.ReportChartMargin, {
    margin: props.margin
  }), /*#__PURE__*/React.createElement(_ReportEventSettings.ReportEventSettings, {
    throttleDelay: throttleDelay,
    throttledEvents: throttledEvents
  }), /*#__PURE__*/React.createElement(_RechartsWrapper.RechartsWrapper, {
    className: className,
    style: style,
    width: width,
    height: height
    /*
     * Sankey, same as Treemap, suffers from overfilling the container
     * and causing infinite render loops where the chart keeps growing.
     */,
    responsive: false,
    ref: node => {
      if (node && !tooltipPortal) {
        setTooltipPortal(node);
      }
    },
    onMouseEnter: undefined,
    onMouseLeave: undefined,
    onClick: undefined,
    onMouseMove: undefined,
    onMouseDown: undefined,
    onMouseUp: undefined,
    onContextMenu: undefined,
    onDoubleClick: undefined,
    onTouchStart: undefined,
    onTouchMove: undefined,
    onTouchEnd: undefined
  }, /*#__PURE__*/React.createElement(_tooltipPortalContext.TooltipPortalContext.Provider, {
    value: tooltipPortal
  }, /*#__PURE__*/React.createElement(_RegisterGraphicalItemId.RegisterGraphicalItemId, {
    id: externalId,
    type: "sankey"
  }, id => /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(SetSankeyTooltipEntrySettings, {
    dataKey: props.dataKey,
    nameKey: props.nameKey,
    stroke: props.stroke,
    strokeWidth: props.strokeWidth,
    fill: props.fill,
    name: props.name,
    data: props.data,
    id: id
  }), /*#__PURE__*/React.createElement(SankeyImpl, _extends({}, props, {
    id: id
  })))))));
}
Sankey.displayName = 'Sankey';