2
0
Files
bot/apps/builder/components/analytics/graph/Edges/Edge.tsx

89 lines
2.5 KiB
TypeScript
Raw Normal View History

2022-01-03 17:39:59 +01:00
import { useAnalyticsGraph } from 'contexts/AnalyticsGraphProvider'
2022-01-15 17:30:20 +01:00
import { useGraph } from 'contexts/GraphContext'
import React, { useEffect, useMemo, useState } from 'react'
2022-01-03 17:39:59 +01:00
import {
getAnchorsPosition,
2022-01-15 17:30:20 +01:00
computeEdgePath,
getEndpointTopOffset,
getSourceEndpointId,
2022-01-03 17:39:59 +01:00
} from 'services/graph'
type Props = { edgeId: string }
2022-01-06 09:40:56 +01:00
export const Edge = ({ edgeId }: Props) => {
2022-01-03 17:39:59 +01:00
const { typebot } = useAnalyticsGraph()
const edge = typebot?.edges.byId[edgeId]
2022-01-15 17:30:20 +01:00
const { sourceEndpoints, targetEndpoints, graphPosition } = useGraph()
const [sourceTop, setSourceTop] = useState(
getEndpointTopOffset(
graphPosition,
sourceEndpoints,
getSourceEndpointId(edge)
)
2022-01-15 17:30:20 +01:00
)
const [targetTop, setTargetTop] = useState(
getEndpointTopOffset(graphPosition, sourceEndpoints, edge?.to.stepId)
2022-01-15 17:30:20 +01:00
)
useEffect(() => {
const newSourceTop = getEndpointTopOffset(
graphPosition,
sourceEndpoints,
getSourceEndpointId(edge)
2022-01-15 17:30:20 +01:00
)
const sensibilityThreshold = 10
const newSourceTopIsTooClose =
sourceTop < newSourceTop + sensibilityThreshold &&
sourceTop > newSourceTop - sensibilityThreshold
if (newSourceTopIsTooClose) return
setSourceTop(newSourceTop)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [graphPosition])
useEffect(() => {
const newTargetTop = getEndpointTopOffset(
graphPosition,
targetEndpoints,
edge?.to.stepId
2022-01-15 17:30:20 +01:00
)
const sensibilityThreshold = 10
const newSourceTopIsTooClose =
targetTop < newTargetTop + sensibilityThreshold &&
targetTop > newTargetTop - sensibilityThreshold
if (newSourceTopIsTooClose) return
setTargetTop(newTargetTop)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [graphPosition])
2022-01-03 17:39:59 +01:00
2022-01-15 17:30:20 +01:00
const { sourceBlock, targetBlock } = useMemo(() => {
if (!typebot || !edge) return {}
const targetBlock = typebot.blocks.byId[edge.to.blockId]
const sourceBlock = typebot.blocks.byId[edge.from.blockId]
2022-01-03 17:39:59 +01:00
return {
2022-01-06 09:40:56 +01:00
sourceBlock,
2022-01-03 17:39:59 +01:00
targetBlock,
}
}, [edge, typebot])
2022-01-03 17:39:59 +01:00
const path = useMemo(() => {
if (!sourceBlock || !targetBlock) return ``
2022-01-12 09:10:59 +01:00
const anchorsPosition = getAnchorsPosition({
2022-01-03 17:39:59 +01:00
sourceBlock,
targetBlock,
2022-01-15 17:30:20 +01:00
sourceTop,
targetTop,
2022-01-12 09:10:59 +01:00
})
2022-01-15 17:30:20 +01:00
return computeEdgePath(anchorsPosition)
}, [sourceBlock, sourceTop, targetBlock, targetTop])
2022-01-03 17:39:59 +01:00
return (
<path
d={path}
stroke={'#718096'}
strokeWidth="2px"
markerEnd="url(#arrow)"
fill="none"
/>
)
}