2
0

🚀 Init preview and typebot cotext in editor

This commit is contained in:
Baptiste Arnaud
2021-12-22 14:59:07 +01:00
parent a54e42f255
commit b7cdc0d14a
87 changed files with 4431 additions and 735 deletions

View File

@ -5,27 +5,31 @@ import {
Stack,
useEventListener,
} from '@chakra-ui/react'
import React, { useEffect, useRef, useState } from 'react'
import React, { useEffect, useMemo, useState } from 'react'
import { Block, StartBlock } from 'bot-engine'
import { useGraph } from 'contexts/GraphContext'
import { useDnd } from 'contexts/DndContext'
import { StepsList } from './StepsList'
import { isNotDefined } from 'services/utils'
import { useTypebot } from 'contexts/TypebotContext'
import { ContextMenu } from 'components/shared/ContextMenu'
import { BlockNodeContextMenu } from './BlockNodeContextMenu'
export const BlockNode = ({ block }: { block: Block | StartBlock }) => {
const {
updateBlockPosition,
addNewStepToBlock,
connectingIds,
setConnectingIds,
} = useGraph()
const { connectingIds, setConnectingIds, previewingIds } = useGraph()
const { updateBlockPosition, addStepToBlock } = useTypebot()
const { draggedStep, draggedStepType, setDraggedStepType, setDraggedStep } =
useDnd()
const blockRef = useRef<HTMLDivElement | null>(null)
const [isMouseDown, setIsMouseDown] = useState(false)
const [titleValue, setTitleValue] = useState(block.title)
const [showSortPlaceholders, setShowSortPlaceholders] = useState(false)
const [isConnecting, setIsConnecting] = useState(false)
const isPreviewing = useMemo(
() =>
previewingIds.sourceId === block.id ||
previewingIds.targetId === block.id,
[block.id, previewingIds.sourceId, previewingIds.targetId]
)
useEffect(() => {
setIsConnecting(
@ -69,44 +73,56 @@ export const BlockNode = ({ block }: { block: Block | StartBlock }) => {
const handleStepDrop = (index: number) => {
setShowSortPlaceholders(false)
if (draggedStepType) {
addNewStepToBlock(block.id, draggedStepType, index)
addStepToBlock(block.id, draggedStepType, index)
setDraggedStepType(undefined)
}
if (draggedStep) {
addNewStepToBlock(block.id, draggedStep, index)
addStepToBlock(block.id, draggedStep, index)
setDraggedStep(undefined)
}
}
return (
<Stack
p="4"
rounded="lg"
bgColor="blue.50"
borderWidth="2px"
borderColor={isConnecting ? 'blue.400' : 'gray.400'}
minW="300px"
transition="border 300ms"
pos="absolute"
style={{
transform: `translate(${block.graphCoordinates.x}px, ${block.graphCoordinates.y}px)`,
}}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
ref={blockRef}
<ContextMenu<HTMLDivElement>
renderMenu={() => <BlockNodeContextMenu blockId={block.id} />}
>
<Editable value={titleValue} onChange={handleTitleChange}>
<EditablePreview _hover={{ bgColor: 'blue.100' }} px="1" />
<EditableInput minW="0" px="1" />
</Editable>
<StepsList
blockId={block.id}
steps={block.steps}
showSortPlaceholders={showSortPlaceholders}
onMouseUp={handleStepDrop}
/>
</Stack>
{(ref, isOpened) => (
<Stack
ref={ref}
p="4"
rounded="lg"
bgColor="blue.50"
borderWidth="2px"
borderColor={
isConnecting || isOpened || isPreviewing ? 'blue.400' : 'gray.400'
}
minW="300px"
transition="border 300ms"
pos="absolute"
style={{
transform: `translate(${block.graphCoordinates.x}px, ${block.graphCoordinates.y}px)`,
}}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
<Editable value={titleValue} onChange={handleTitleChange}>
<EditablePreview
_hover={{ bgColor: 'blue.100' }}
px="1"
userSelect={'none'}
/>
<EditableInput minW="0" px="1" />
</Editable>
<StepsList
blockId={block.id}
steps={block.steps}
showSortPlaceholders={showSortPlaceholders}
onMouseUp={handleStepDrop}
/>
</Stack>
)}
</ContextMenu>
)
}

View File

@ -0,0 +1,18 @@
import { MenuList, MenuItem } from '@chakra-ui/react'
import { TrashIcon } from 'assets/icons'
import { useTypebot } from 'contexts/TypebotContext'
export const BlockNodeContextMenu = ({ blockId }: { blockId: string }) => {
const { removeBlock } = useTypebot()
const handleDeleteClick = () => {
removeBlock(blockId)
}
return (
<MenuList>
<MenuItem icon={<TrashIcon />} onClick={handleDeleteClick}>
Delete
</MenuItem>
</MenuList>
)
}

View File

@ -5,15 +5,21 @@ import {
Stack,
useEventListener,
} from '@chakra-ui/react'
import React, { useState } from 'react'
import React, { useMemo, useState } from 'react'
import { StartBlock } from 'bot-engine'
import { useGraph } from 'contexts/GraphContext'
import { StepNode } from './StepNode'
import { useTypebot } from 'contexts/TypebotContext'
import { useGraph } from 'contexts/GraphContext'
export const StartBlockNode = ({ block }: { block: StartBlock }) => {
const { setStartBlock } = useGraph()
const { previewingIds } = useGraph()
const [isMouseDown, setIsMouseDown] = useState(false)
const [titleValue, setTitleValue] = useState(block.title)
const { updateBlockPosition } = useTypebot()
const isPreviewing = useMemo(
() => previewingIds.sourceId === block.id,
[block.id, previewingIds.sourceId]
)
const handleTitleChange = (title: string) => setTitleValue(title)
@ -28,15 +34,11 @@ export const StartBlockNode = ({ block }: { block: StartBlock }) => {
if (!isMouseDown) return
const { movementX, movementY } = event
setStartBlock({
...block,
graphCoordinates: {
x: block.graphCoordinates.x + movementX,
y: block.graphCoordinates.y + movementY,
},
updateBlockPosition(block.id, {
x: block.graphCoordinates.x + movementX,
y: block.graphCoordinates.y + movementY,
})
}
useEventListener('mousemove', handleMouseMove)
return (
@ -45,7 +47,7 @@ export const StartBlockNode = ({ block }: { block: StartBlock }) => {
rounded="lg"
bgColor="blue.50"
borderWidth="2px"
borderColor="gray.400"
borderColor={isPreviewing ? 'blue.400' : 'gray.400'}
minW="300px"
transition="border 300ms"
pos="absolute"
@ -57,7 +59,11 @@ export const StartBlockNode = ({ block }: { block: StartBlock }) => {
spacing="14px"
>
<Editable value={titleValue} onChange={handleTitleChange}>
<EditablePreview _hover={{ bgColor: 'blue.100' }} px="1" />
<EditablePreview
_hover={{ bgColor: 'blue.100' }}
px="1"
userSelect={'none'}
/>
<EditableInput minW="0" px="1" />
</Editable>
<StepNode step={block.steps[0]} isConnectable={true} />

View File

@ -0,0 +1,24 @@
import { MenuList, MenuItem } from '@chakra-ui/react'
import { TrashIcon } from 'assets/icons'
import { useTypebot } from 'contexts/TypebotContext'
export const StepNodeContextMenu = ({
blockId,
stepId,
}: {
blockId: string
stepId: string
}) => {
const { removeStepFromBlock } = useTypebot()
const handleDeleteClick = () => {
removeStepFromBlock(blockId, stepId)
}
return (
<MenuList>
<MenuItem icon={<TrashIcon />} onClick={handleDeleteClick}>
Delete
</MenuItem>
</MenuList>
)
}

View File

@ -0,0 +1,31 @@
import { Flex, Text } from '@chakra-ui/react'
import { Step, StartStep, StepType } from 'bot-engine'
export const StepContent = (props: Step | StartStep) => {
switch (props.type) {
case StepType.TEXT: {
return (
<Flex
flexDir={'column'}
opacity={props.content.html === '' ? '0.5' : '1'}
className="slate-html-container"
dangerouslySetInnerHTML={{
__html:
props.content.html === ''
? `<p>Click to edit...</p>`
: props.content.html,
}}
></Flex>
)
}
case StepType.TEXT_INPUT: {
return <Text color={'gray.500'}>Type your answer...</Text>
}
case StepType.START: {
return <Text>{props.label}</Text>
}
default: {
return <Text>No input</Text>
}
}
}

View File

@ -1,10 +1,16 @@
import { Box, Flex, HStack, StackProps, Text } from '@chakra-ui/react'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import { Box, Flex, HStack, useEventListener } from '@chakra-ui/react'
import React, { useEffect, useMemo, useState } from 'react'
import { Block, StartStep, Step, StepType } from 'bot-engine'
import { SourceEndpoint } from './SourceEndpoint'
import { useGraph } from 'contexts/GraphContext'
import { StepIcon } from 'components/board/StepTypesList/StepIcon'
import { isDefined } from 'services/utils'
import { Coordinates } from '@dnd-kit/core/dist/types'
import { TextEditor } from './TextEditor/TextEditor'
import { StepContent } from './StepContent'
import { useTypebot } from 'contexts/TypebotContext'
import { ContextMenu } from 'components/shared/ContextMenu'
import { StepNodeContextMenu } from './RightClickMenu'
export const StepNode = ({
step,
@ -17,17 +23,18 @@ export const StepNode = ({
isConnectable: boolean
onMouseMoveBottomOfElement?: () => void
onMouseMoveTopOfElement?: () => void
onMouseDown?: (e: React.MouseEvent, step: Step) => void
onMouseDown?: (
stepNodePosition: { absolute: Coordinates; relative: Coordinates },
step: Step
) => void
}) => {
const stepRef = useRef<HTMLDivElement | null>(null)
const {
setConnectingIds,
removeStepFromBlock,
blocks,
connectingIds,
startBlock,
} = useGraph()
const { setConnectingIds, connectingIds } = useGraph()
const { removeStepFromBlock, typebot } = useTypebot()
const { blocks, startBlock } = typebot ?? {}
const [isConnecting, setIsConnecting] = useState(false)
const [mouseDownEvent, setMouseDownEvent] =
useState<{ absolute: Coordinates; relative: Coordinates }>()
const [isEditing, setIsEditing] = useState<boolean | undefined>(undefined)
useEffect(() => {
setIsConnecting(
@ -59,12 +66,38 @@ export const StepNode = ({
const handleMouseDown = (e: React.MouseEvent) => {
if (!onMouseDown) return
e.stopPropagation()
onMouseDown(e, step as Step)
removeStepFromBlock(step.blockId, step.id)
const element = e.currentTarget as HTMLDivElement
const rect = element.getBoundingClientRect()
const relativeX = e.clientX - rect.left
const relativeY = e.clientY - rect.top
setMouseDownEvent({
absolute: { x: e.clientX + relativeX, y: e.clientY + relativeY },
relative: { x: relativeX, y: relativeY },
})
}
const handleGlobalMouseUp = () => {
setMouseDownEvent(undefined)
}
useEventListener('mouseup', handleGlobalMouseUp)
const handleMouseUp = () => {
if (mouseDownEvent) {
setIsEditing(true)
}
}
const handleMouseMove = (event: React.MouseEvent<HTMLDivElement>) => {
if (!onMouseMoveBottomOfElement || !onMouseMoveTopOfElement) return
const isMovingAndIsMouseDown =
mouseDownEvent &&
onMouseDown &&
(event.movementX > 0 || event.movementY > 0)
if (isMovingAndIsMouseDown) {
onMouseDown(mouseDownEvent, step as Step)
removeStepFromBlock(step.blockId, step.id)
setMouseDownEvent(undefined)
}
const element = event.currentTarget as HTMLDivElement
const rect = element.getBoundingClientRect()
const y = event.clientY - rect.top
@ -72,8 +105,12 @@ export const StepNode = ({
else onMouseMoveTopOfElement()
}
const handleCloseEditor = () => {
setIsEditing(false)
}
const connectedStubPosition: 'right' | 'left' | undefined = useMemo(() => {
const currentBlock = [startBlock, ...blocks].find(
const currentBlock = [startBlock, ...(blocks ?? [])].find(
(b) => b?.id === step.blockId
)
const isDragginConnectorFromCurrentBlock =
@ -83,7 +120,7 @@ export const StepNode = ({
? connectingIds.target?.blockId
: step.target?.blockId
const targetedBlock = targetBlockId
? blocks.find((b) => b.id === targetBlockId)
? (blocks ?? []).find((b) => b.id === targetBlockId)
: undefined
return targetedBlock
? targetedBlock.graphCoordinates.x <
@ -100,106 +137,74 @@ export const StepNode = ({
startBlock,
])
return (
<Flex
pos="relative"
ref={stepRef}
onMouseMove={handleMouseMove}
onMouseDown={handleMouseDown}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
return step.type === StepType.TEXT &&
(isEditing ||
(isEditing === undefined && step.content.plainText === '')) ? (
<TextEditor
ids={{ stepId: step.id, blockId: step.blockId }}
initialValue={step.content.richText}
onClose={handleCloseEditor}
/>
) : (
<ContextMenu<HTMLDivElement>
renderMenu={() => (
<StepNodeContextMenu blockId={step.blockId} stepId={step.id} />
)}
>
{connectedStubPosition === 'left' && (
<Box
h="2px"
pos="absolute"
left="-18px"
top="25px"
w="18px"
bgColor="blue.500"
/>
)}
<HStack
flex="1"
userSelect="none"
p="3"
borderWidth="2px"
borderColor={isConnecting ? 'blue.400' : 'gray.400'}
rounded="lg"
cursor={'grab'}
bgColor="white"
>
<StepIcon type={step.type} />
<StepContent {...step} />
{isConnectable && (
<SourceEndpoint
onConnectionDragStart={handleConnectionDragStart}
pos="absolute"
right="20px"
/>
)}
</HStack>
{(ref, isOpened) => (
<Flex
pos="relative"
ref={ref}
onMouseMove={handleMouseMove}
onMouseDown={handleMouseDown}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
onMouseUp={handleMouseUp}
>
{connectedStubPosition === 'left' && (
<Box
h="2px"
pos="absolute"
left="-18px"
top="25px"
w="18px"
bgColor="blue.500"
/>
)}
<HStack
flex="1"
userSelect="none"
p="3"
borderWidth="2px"
borderColor={isConnecting || isOpened ? 'blue.400' : 'gray.400'}
rounded="lg"
cursor={'pointer'}
bgColor="white"
>
<StepIcon type={step.type} />
<StepContent {...step} />
{isConnectable && (
<SourceEndpoint
onConnectionDragStart={handleConnectionDragStart}
pos="absolute"
right="20px"
/>
)}
</HStack>
{isDefined(connectedStubPosition) && (
<Box
h="2px"
pos="absolute"
right={connectedStubPosition === 'left' ? undefined : '-18px'}
left={connectedStubPosition === 'left' ? '-18px' : undefined}
top="25px"
w="18px"
bgColor="gray.500"
/>
{isDefined(connectedStubPosition) && (
<Box
h="2px"
pos="absolute"
right={connectedStubPosition === 'left' ? undefined : '-18px'}
left={connectedStubPosition === 'left' ? '-18px' : undefined}
top="25px"
w="18px"
bgColor="gray.500"
/>
)}
</Flex>
)}
</Flex>
)
}
export const StepContent = (props: Step | StartStep) => {
switch (props.type) {
case StepType.TEXT: {
return (
<Text opacity={props.content === '' ? '0.5' : '1'}>
{props.content === '' ? 'Type text...' : props.content}
</Text>
)
}
case StepType.DATE_PICKER: {
return (
<Text opacity={props.content === '' ? '0.5' : '1'}>
{props.content === '' ? 'Pick a date...' : props.content}
</Text>
)
}
case StepType.START: {
return <Text>{props.label}</Text>
}
default: {
return <Text>No input</Text>
}
}
}
export const StepNodeOverlay = ({
step,
...props
}: { step: Step } & StackProps) => {
return (
<HStack
p="3"
borderWidth="1px"
rounded="lg"
bgColor="white"
cursor={'grab'}
pos="fixed"
top="0"
left="0"
w="264px"
pointerEvents="none"
{...props}
>
<StepIcon type={step.type} />
<StepContent {...step} />
</HStack>
</ContextMenu>
)
}

View File

@ -0,0 +1,28 @@
import { StackProps, HStack } from '@chakra-ui/react'
import { Step } from 'bot-engine'
import { StepIcon } from 'components/board/StepTypesList/StepIcon'
import { StepContent } from './StepContent'
export const StepNodeOverlay = ({
step,
...props
}: { step: Step } & StackProps) => {
return (
<HStack
p="3"
borderWidth="1px"
rounded="lg"
bgColor="white"
cursor={'grab'}
pos="fixed"
top="0"
left="0"
w="264px"
pointerEvents="none"
{...props}
>
<StepIcon type={step.type} />
<StepContent {...step} />
</HStack>
)
}

View File

@ -0,0 +1,97 @@
import { Stack, useOutsideClick } from '@chakra-ui/react'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import {
Plate,
selectEditor,
serializeHtml,
TDescendant,
withPlate,
} from '@udecode/plate-core'
import { editorStyle, platePlugins } from 'libs/plate'
import { useDebounce } from 'use-debounce'
import { useTypebot } from 'contexts/TypebotContext'
import { createEditor } from 'slate'
import { ToolBar } from './ToolBar'
import { parseHtmlStringToPlainText } from 'services/utils'
type TextEditorProps = {
ids: { stepId: string; blockId: string }
initialValue: TDescendant[]
onClose: () => void
}
export const TextEditor = ({ initialValue, ids, onClose }: TextEditorProps) => {
const editor = useMemo(
() => withPlate(createEditor(), { id: ids.stepId, plugins: platePlugins }),
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
)
const { updateStep } = useTypebot()
const [value, setValue] = useState(initialValue)
const [debouncedValue] = useDebounce(value, 500)
const textEditorRef = useRef<HTMLDivElement>(null)
useOutsideClick({
ref: textEditorRef,
handler: () => {
save(value)
onClose()
},
})
useEffect(() => {
save(debouncedValue)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [debouncedValue])
const save = (value: unknown[]) => {
console.log('SAVE', value)
if (value.length === 0) return
const html = serializeHtml(editor, {
nodes: value,
})
updateStep(ids, {
content: {
html,
richText: value,
plainText: parseHtmlStringToPlainText(html),
},
})
}
const handleMouseDown = (e: React.MouseEvent) => {
e.stopPropagation()
}
return (
<Stack
flex="1"
ref={textEditorRef}
borderWidth="2px"
borderColor="blue.500"
rounded="md"
onMouseDown={handleMouseDown}
spacing={0}
>
<ToolBar />
<Plate
id={ids.stepId}
editableProps={{
style: editorStyle,
autoFocus: true,
onFocus: () => {
if (editor.children.length === 0) return
selectEditor(editor, {
edge: 'end',
})
},
}}
initialValue={
initialValue.length === 0
? [{ type: 'p', children: [{ text: '' }] }]
: initialValue
}
onChange={setValue}
editor={editor}
/>
</Stack>
)
}

View File

@ -0,0 +1,40 @@
import { StackProps, HStack, Button } from '@chakra-ui/react'
import {
MARK_BOLD,
MARK_ITALIC,
MARK_UNDERLINE,
} from '@udecode/plate-basic-marks'
import { usePlateEditorRef, getPluginType } from '@udecode/plate-core'
import { LinkToolbarButton } from '@udecode/plate-ui-link'
import { MarkToolbarButton } from '@udecode/plate-ui-toolbar'
import { BoldIcon, ItalicIcon, UnderlineIcon, LinkIcon } from 'assets/icons'
export const ToolBar = (props: StackProps) => {
const editor = usePlateEditorRef()
return (
<HStack
bgColor={'white'}
borderTopRadius="md"
p={2}
w="full"
boxSizing="border-box"
borderBottomWidth={1}
{...props}
>
<Button size="sm">Variables</Button>
<MarkToolbarButton
type={getPluginType(editor, MARK_BOLD)}
icon={<BoldIcon />}
/>
<MarkToolbarButton
type={getPluginType(editor, MARK_ITALIC)}
icon={<ItalicIcon />}
/>
<MarkToolbarButton
type={getPluginType(editor, MARK_UNDERLINE)}
icon={<UnderlineIcon />}
/>
<LinkToolbarButton icon={<LinkIcon />} />
</HStack>
)
}

View File

@ -0,0 +1 @@
export { TextEditor } from './TextEditor'

View File

@ -1 +1,2 @@
export { StepNode, StepNodeOverlay } from './StepNode'
export { StepNode } from './StepNode'
export { StepNodeOverlay } from './StepNodeOverlay'

View File

@ -1,6 +1,7 @@
import { useEventListener, Stack, Flex, Portal } from '@chakra-ui/react'
import { StartStep, Step } from 'bot-engine'
import { useDnd } from 'contexts/DndContext'
import { Coordinates } from 'contexts/GraphContext'
import { useState } from 'react'
import { StepNode, StepNodeOverlay } from './StepNode'
@ -51,13 +52,12 @@ export const StepsList = ({
onMouseUp(expandedPlaceholderIndex)
}
const handleStepMouseDown = (e: React.MouseEvent, step: Step) => {
const element = e.currentTarget as HTMLDivElement
const rect = element.getBoundingClientRect()
const relativeX = e.clientX - rect.left
const relativeY = e.clientY - rect.top
setPosition({ x: e.clientX - relativeX, y: e.clientY - relativeY })
setRelativeCoordinates({ x: relativeX, y: relativeY })
const handleStepMouseDown = (
{ absolute, relative }: { absolute: Coordinates; relative: Coordinates },
step: Step
) => {
setPosition(absolute)
setRelativeCoordinates(relative)
setDraggedStep(step)
}