2
0
Files
bot/apps/builder/contexts/AnalyticsGraphProvider.tsx

63 lines
1.5 KiB
TypeScript
Raw Normal View History

2022-01-06 09:40:56 +01:00
import { PublicTypebot } from 'models'
2022-01-03 17:39:59 +01:00
import {
createContext,
Dispatch,
ReactNode,
SetStateAction,
useContext,
useState,
} from 'react'
import { Coordinates } from './GraphContext'
2022-01-06 09:40:56 +01:00
import produce from 'immer'
2022-01-03 17:39:59 +01:00
type Position = Coordinates & { scale: number }
const graphPositionDefaultValue = { x: 400, y: 100, scale: 1 }
const graphContext = createContext<{
typebot?: PublicTypebot
updateBlockPosition: (blockId: string, newPositon: Coordinates) => void
graphPosition: Position
setGraphPosition: Dispatch<SetStateAction<Position>>
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
}>({
graphPosition: graphPositionDefaultValue,
})
export const AnalyticsGraphProvider = ({
children,
initialTypebot,
}: {
children: ReactNode
initialTypebot: PublicTypebot
}) => {
const [typebot, setTypebot] = useState(initialTypebot)
const [graphPosition, setGraphPosition] = useState(graphPositionDefaultValue)
const updateBlockPosition = (blockId: string, newPosition: Coordinates) => {
if (!typebot) return
2022-01-06 09:40:56 +01:00
setTypebot(
produce(typebot, (nextTypebot) => {
nextTypebot.blocks.byId[blockId].graphCoordinates = newPosition
})
)
2022-01-03 17:39:59 +01:00
}
return (
<graphContext.Provider
value={{
typebot,
graphPosition,
setGraphPosition,
updateBlockPosition,
}}
>
{children}
</graphContext.Provider>
)
}
export const useAnalyticsGraph = () => useContext(graphContext)