2
0
Files
bot/apps/builder/components/shared/Graph/Graph.tsx

261 lines
7.7 KiB
TypeScript
Raw Normal View History

2022-01-03 17:39:59 +01:00
import { Flex, FlexProps, useEventListener } from '@chakra-ui/react'
import React, { useRef, useMemo, useEffect, useState } from 'react'
import {
blockWidth,
2022-04-08 14:30:46 -05:00
Coordinates,
graphPositionDefaultValue,
useGraph,
} from 'contexts/GraphContext'
import { useStepDnd } from 'contexts/GraphDndContext'
2022-01-06 09:40:56 +01:00
import { useTypebot } from 'contexts/TypebotContext/TypebotContext'
import { DraggableStepType, PublicTypebot, Typebot } from 'models'
import { AnswersCount } from 'services/analytics'
import { useDebounce } from 'use-debounce'
import { DraggableCore, DraggableData, DraggableEvent } from 'react-draggable'
import GraphContent from './GraphContent'
import cuid from 'cuid'
2022-04-08 14:30:46 -05:00
import { headerHeight } from '../TypebotHeader'
import { useUser } from 'contexts/UserContext'
import { GraphNavigation } from 'db'
import { ZoomButtons } from './ZoomButtons'
2021-12-16 10:43:49 +01:00
2022-04-08 14:30:46 -05:00
const maxScale = 1.5
const minScale = 0.1
const zoomButtonsScaleStep = 0.2
export const Graph = ({
2022-02-11 18:06:59 +01:00
typebot,
answersCounts,
2022-02-13 06:53:48 +01:00
onUnlockProPlanClick,
...props
2022-02-11 18:06:59 +01:00
}: {
typebot?: Typebot | PublicTypebot
answersCounts?: AnswersCount[]
2022-02-13 06:53:48 +01:00
onUnlockProPlanClick?: () => void
2022-02-11 18:06:59 +01:00
} & FlexProps) => {
const {
draggedStepType,
setDraggedStepType,
draggedStep,
setDraggedStep,
draggedItem,
setDraggedItem,
} = useStepDnd()
2021-12-16 10:43:49 +01:00
const graphContainerRef = useRef<HTMLDivElement | null>(null)
const editorContainerRef = useRef<HTMLDivElement | null>(null)
2022-02-11 18:06:59 +01:00
const { createBlock } = useTypebot()
const {
setGraphPosition: setGlobalGraphPosition,
setOpenedStepId,
updateBlockCoordinates,
setPreviewingEdge,
connectingIds,
} = useGraph()
const [graphPosition, setGraphPosition] = useState(graphPositionDefaultValue)
const [debouncedGraphPosition] = useDebounce(graphPosition, 200)
2021-12-16 10:43:49 +01:00
const transform = useMemo(
() =>
`translate(${graphPosition.x}px, ${graphPosition.y}px) scale(${graphPosition.scale})`,
[graphPosition]
)
2022-04-08 14:30:46 -05:00
const { user } = useUser()
2021-12-16 10:43:49 +01:00
const [autoMoveDirection, setAutoMoveDirection] = useState<
'top' | 'right' | 'bottom' | 'left' | undefined
>()
useAutoMoveBoard(autoMoveDirection, setGraphPosition)
useEffect(() => {
editorContainerRef.current = document.getElementById(
'editor-container'
) as HTMLDivElement
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
useEffect(() => {
if (!graphContainerRef.current) return
const { top, left } = graphContainerRef.current.getBoundingClientRect()
setGlobalGraphPosition({
x: left + debouncedGraphPosition.x,
y: top + debouncedGraphPosition.y,
2022-04-08 14:30:46 -05:00
scale: debouncedGraphPosition.scale,
})
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [debouncedGraphPosition])
2021-12-16 10:43:49 +01:00
const handleMouseWheel = (e: WheelEvent) => {
e.preventDefault()
const isPinchingTrackpad = e.ctrlKey
2022-04-08 14:30:46 -05:00
user?.graphNavigation === GraphNavigation.MOUSE
? zoom(-e.deltaY * 0.001, { x: e.clientX, y: e.clientY })
2022-04-08 14:30:46 -05:00
: isPinchingTrackpad
? zoom(-e.deltaY * 0.01, { x: e.clientX, y: e.clientY })
: setGraphPosition({
...graphPosition,
x: graphPosition.x - e.deltaX,
y: graphPosition.y - e.deltaY,
})
2021-12-16 10:43:49 +01:00
}
const handleMouseUp = (e: MouseEvent) => {
if (!typebot) return
if (draggedItem) setDraggedItem(undefined)
2021-12-16 10:43:49 +01:00
if (!draggedStep && !draggedStepType) return
2022-04-08 14:30:46 -05:00
const coordinates = projectMouse(
{ x: e.clientX, y: e.clientY },
graphPosition
)
const id = cuid()
updateBlockCoordinates(id, coordinates)
createBlock({
id,
...coordinates,
2022-01-08 07:40:55 +01:00
step: draggedStep ?? (draggedStepType as DraggableStepType),
indices: { blockIndex: typebot.blocks.length, stepIndex: 0 },
2021-12-16 10:43:49 +01:00
})
setDraggedStep(undefined)
setDraggedStepType(undefined)
}
const handleCaptureMouseDown = (e: MouseEvent) => {
const isRightClick = e.button === 2
if (isRightClick) e.stopPropagation()
}
const handleClick = () => {
setOpenedStepId(undefined)
setPreviewingEdge(undefined)
}
const onDrag = (_: DraggableEvent, draggableData: DraggableData) => {
const { deltaX, deltaY } = draggableData
setGraphPosition({
2022-04-08 14:30:46 -05:00
...graphPosition,
x: graphPosition.x + deltaX,
y: graphPosition.y + deltaY,
2022-04-08 14:30:46 -05:00
})
}
const zoom = (delta = zoomButtonsScaleStep, mousePosition?: Coordinates) => {
const { x: mouseX, y } = mousePosition ?? { x: 0, y: 0 }
const mouseY = y - headerHeight
let scale = graphPosition.scale + delta
if (
(scale >= maxScale && graphPosition.scale === maxScale) ||
(scale <= minScale && graphPosition.scale === minScale)
)
return
scale = scale >= maxScale ? maxScale : scale <= minScale ? minScale : scale
const xs = (mouseX - graphPosition.x) / graphPosition.scale
const ys = (mouseY - graphPosition.y) / graphPosition.scale
setGraphPosition({
...graphPosition,
x: mouseX - xs * scale,
y: mouseY - ys * scale,
scale,
})
}
const handleMouseMove = (e: MouseEvent) => {
if (!connectingIds)
return autoMoveDirection ? setAutoMoveDirection(undefined) : undefined
if (e.clientX <= 50) return setAutoMoveDirection('left')
if (e.clientY <= 50 + headerHeight) return setAutoMoveDirection('top')
if (e.clientX >= window.innerWidth - 50)
return setAutoMoveDirection('right')
if (e.clientY >= window.innerHeight - 50)
return setAutoMoveDirection('bottom')
setAutoMoveDirection(undefined)
}
useEventListener('wheel', handleMouseWheel, graphContainerRef.current)
useEventListener('mousedown', handleCaptureMouseDown, undefined, {
capture: true,
})
useEventListener('mouseup', handleMouseUp, graphContainerRef.current)
useEventListener('click', handleClick, editorContainerRef.current)
useEventListener('mousemove', handleMouseMove)
2021-12-16 10:43:49 +01:00
return (
<DraggableCore onDrag={onDrag} enableUserSelectHack={false}>
<Flex ref={graphContainerRef} position="relative" {...props}>
2022-04-08 14:30:46 -05:00
<ZoomButtons
onZoomIn={() => zoom(zoomButtonsScaleStep)}
onZoomOut={() => zoom(-zoomButtonsScaleStep)}
/>
<Flex
flex="1"
w="full"
h="full"
position="absolute"
style={{
transform,
}}
willChange="transform"
transformOrigin="0px 0px 0px"
>
<GraphContent
answersCounts={answersCounts}
onUnlockProPlanClick={onUnlockProPlanClick}
/>
</Flex>
2021-12-16 10:43:49 +01:00
</Flex>
</DraggableCore>
2021-12-16 10:43:49 +01:00
)
}
2022-04-08 14:30:46 -05:00
const projectMouse = (
mouseCoordinates: Coordinates,
graphPosition: Coordinates & { scale: number }
) => {
return {
x:
(mouseCoordinates.x -
graphPosition.x -
blockWidth / (3 / graphPosition.scale)) /
graphPosition.scale,
y:
(mouseCoordinates.y -
graphPosition.y -
(headerHeight + 20 * graphPosition.scale)) /
graphPosition.scale,
}
}
const useAutoMoveBoard = (
autoMoveDirection: 'top' | 'right' | 'bottom' | 'left' | undefined,
setGraphPosition: React.Dispatch<
React.SetStateAction<{
x: number
y: number
scale: number
}>
>
) =>
useEffect(() => {
if (!autoMoveDirection) return
const interval = setInterval(() => {
setGraphPosition((prev) => ({
...prev,
x:
autoMoveDirection === 'right'
? prev.x - 5
: autoMoveDirection === 'left'
? prev.x + 5
: prev.x,
y:
autoMoveDirection === 'bottom'
? prev.y - 5
: autoMoveDirection === 'top'
? prev.y + 5
: prev.y,
}))
}, 5)
return () => {
clearInterval(interval)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [autoMoveDirection])