All files / src/components GraphEdge.tsx

87.88% Statements 29/33
50% Branches 6/12
75% Functions 3/4
86.21% Lines 25/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 941x 1x 1x   1x                           1x 10595x 10595x 50120466x 10595x   10595x 4x     10591x               50130906x   10583x       10583x               10583x 10583x 10583x 10583x   10583x 10583x   10583x       10583x       10583x                         10583x                            
import * as React from "react";
import { GraphConfigContext, IGraphConfig } from "../contexts";
import { getPortPositionByPortId, updateEdge } from "../utils";
import { IGraphProps } from "./Graph";
import {
  GraphEdgeState,
  ICanvasEdge,
  ICanvasNode,
  TSetData
} from "./Graph.interface";
 
interface IProps {
  edge: ICanvasEdge;
  nodes: ICanvasNode[];
  graphProps: IGraphProps;
  setData: TSetData;
}
 
export const GraphEdge: React.FunctionComponent<IProps> = props => {
  const { edge, nodes, graphProps } = props;
  const setData = props.setData.bind(null);
  const sourceNode = nodes.find(node => node.id === edge.source);
  const graphConfig = React.useContext<IGraphConfig>(GraphConfigContext);
 
  if (!sourceNode) {
    throw new Error(`invalid source ${JSON.stringify(edge)}`);
  }
 
  const sourcePosition = getPortPositionByPortId(
    sourceNode,
    edge.sourcePortId,
    graphConfig,
    graphProps,
    setData
  );
 
  const targetNode = nodes.find(node => node.id === edge.target);
 
  Iif (!targetNode) {
    throw new Error("invalid target");
  }
 
  const targetPosition = getPortPositionByPortId(
    targetNode,
    edge.targetPortId,
    graphConfig,
    graphProps,
    setData
  );
 
  const x1 = sourcePosition.x;
  const y1 = sourcePosition.y;
  const x2 = targetPosition.x;
  const y2 = targetPosition.y;
 
  const shape = edge.shape ? edge.shape : "line";
  const edgeConfig = graphConfig.getEdgeConfigByName(shape);
 
  Iif (!edgeConfig) {
    throw new Error(`invalid shape in edge ${edge.id}`);
  }
 
  Iif (!edgeConfig.render) {
    throw new Error(`Missing "render" method in edge config ${shape}`);
  }
 
  const onClick: React.MouseEventHandler<SVGGElement> = () => {
    updateEdge(
      edge.id,
      {
        state:
          edge.state === GraphEdgeState.selected
            ? GraphEdgeState.default
            : GraphEdgeState.selected
      },
      setData
    );
  };
 
  return (
    <g onClick={onClick}>
      {edgeConfig.render({
        model: edge,
        graphProps,
        x1,
        y1,
        x2,
        y2,
        setData
      })}
    </g>
  );
};