import React, {memo, useCallback} from 'react';
import {BaseEdge, EdgeProps, getStraightPath, Position, ReactFlowState, useStore} from 'reactflow';
import {getEdgeParams} from "../../../utils/mathUtils";
export type GetSpecialPathParams = {
sourceX: number;
sourceY: number;
targetX: number;
targetY: number;
};
const FloatingEdge = memo(({ id, source, target, markerEnd, style } : EdgeProps) => {
const sourceNode = useStore(useCallback((store) => store.nodeInternals.get(source), [source]));
const targetNode = useStore(useCallback((store) => store.nodeInternals.get(target), [target]));
if (!sourceNode || !targetNode) {
return null;
}
const isBiDirectionEdge = useStore((s: ReactFlowState) => {
const edgeExists = s.edges.some(
(e) =>
(e.source === target && e.target === source) || (e.target === source && e.source === target)
);
return edgeExists;
});
const getSpecialPath = ({ sourceX, sourceY, targetX, targetY }: GetSpecialPathParams, offset: number) => {
return `M ${sourceX} ${sourceY + offset} L ${targetX} ${targetY + offset}`;
};
const { sx, sy, tx, ty, sourcePos, targetPos } = getEdgeParams(sourceNode, targetNode);
let path = "";
if (isBiDirectionEdge) {
path = getSpecialPath({
sourceX: sx,
sourceY: sy,
targetX: tx,
targetY: ty,
}, sourcePos == Position.Left ? 20 : 0
);
} else {
[path] = getStraightPath({
sourceX: sx,
sourceY: sy,
targetX: tx,
targetY: ty,
});
}
return (
<BaseEdge
id={id}
path={path}
markerEnd={markerEnd}
style={style}
/>
);
})
export default FloatingEdge;