2021-12-16 10:43:49 +01:00
|
|
|
import { Block, StartStep, Step, Target } from 'bot-engine'
|
|
|
|
import { Coordinates, useGraph } from 'contexts/GraphContext'
|
2021-12-22 14:59:07 +01:00
|
|
|
import { useTypebot } from 'contexts/TypebotContext'
|
2021-12-16 10:43:49 +01:00
|
|
|
import React, { useMemo } from 'react'
|
|
|
|
import {
|
|
|
|
getAnchorsPosition,
|
|
|
|
computeFlowChartConnectorPath,
|
|
|
|
} from 'services/graph'
|
|
|
|
|
|
|
|
export type AnchorsPositionProps = {
|
|
|
|
sourcePosition: Coordinates
|
|
|
|
targetPosition: Coordinates
|
|
|
|
sourceType: 'right' | 'left'
|
|
|
|
totalSegments: number
|
|
|
|
}
|
|
|
|
|
|
|
|
export type StepWithTarget = Omit<Step | StartStep, 'target'> & {
|
|
|
|
target: Target
|
|
|
|
}
|
|
|
|
|
|
|
|
export const Edge = ({ step }: { step: StepWithTarget }) => {
|
2021-12-22 14:59:07 +01:00
|
|
|
const { typebot } = useTypebot()
|
|
|
|
const { previewingIds } = useGraph()
|
|
|
|
const isPreviewing = useMemo(
|
|
|
|
() =>
|
|
|
|
previewingIds.sourceId === step.blockId &&
|
|
|
|
previewingIds.targetId === step.target.blockId,
|
|
|
|
[
|
|
|
|
previewingIds.sourceId,
|
|
|
|
previewingIds.targetId,
|
|
|
|
step.blockId,
|
|
|
|
step.target.blockId,
|
|
|
|
]
|
|
|
|
)
|
|
|
|
const { blocks, startBlock } = typebot ?? {}
|
2021-12-16 10:43:49 +01:00
|
|
|
|
|
|
|
const { sourceBlock, targetBlock, targetStepIndex } = useMemo(() => {
|
2021-12-22 14:59:07 +01:00
|
|
|
const targetBlock = blocks?.find(
|
2021-12-16 10:43:49 +01:00
|
|
|
(b) => b?.id === step.target.blockId
|
|
|
|
) as Block
|
|
|
|
const targetStepIndex = step.target.stepId
|
|
|
|
? targetBlock.steps.findIndex((s) => s.id === step.target.stepId)
|
|
|
|
: undefined
|
|
|
|
return {
|
2021-12-22 14:59:07 +01:00
|
|
|
sourceBlock: [startBlock, ...(blocks ?? [])].find(
|
|
|
|
(b) => b?.id === step.blockId
|
|
|
|
),
|
2021-12-16 10:43:49 +01:00
|
|
|
targetBlock,
|
|
|
|
targetStepIndex,
|
|
|
|
}
|
|
|
|
}, [
|
|
|
|
blocks,
|
|
|
|
startBlock,
|
|
|
|
step.blockId,
|
|
|
|
step.target.blockId,
|
|
|
|
step.target.stepId,
|
|
|
|
])
|
|
|
|
|
|
|
|
const path = useMemo(() => {
|
|
|
|
if (!sourceBlock || !targetBlock) return ``
|
|
|
|
const anchorsPosition = getAnchorsPosition(
|
|
|
|
sourceBlock,
|
|
|
|
targetBlock,
|
|
|
|
sourceBlock.steps.findIndex((s) => s.id === step.id),
|
|
|
|
targetStepIndex
|
|
|
|
)
|
|
|
|
return computeFlowChartConnectorPath(anchorsPosition)
|
|
|
|
}, [sourceBlock, step.id, targetBlock, targetStepIndex])
|
|
|
|
|
|
|
|
return (
|
|
|
|
<path
|
|
|
|
d={path}
|
2021-12-22 14:59:07 +01:00
|
|
|
stroke={isPreviewing ? '#1a5fff' : '#718096'}
|
2021-12-16 10:43:49 +01:00
|
|
|
strokeWidth="2px"
|
|
|
|
markerEnd="url(#arrow)"
|
|
|
|
fill="none"
|
|
|
|
/>
|
|
|
|
)
|
|
|
|
}
|