feat(inputs): ✨ Add Condition step
This commit is contained in:
@@ -237,3 +237,9 @@ export const CheckSquareIcon = (props: IconProps) => (
|
|||||||
<path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"></path>
|
<path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"></path>
|
||||||
</Icon>
|
</Icon>
|
||||||
)
|
)
|
||||||
|
|
||||||
|
export const FilterIcon = (props: IconProps) => (
|
||||||
|
<Icon viewBox="0 0 24 24" {...featherIconsBaseProps} {...props}>
|
||||||
|
<polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"></polygon>
|
||||||
|
</Icon>
|
||||||
|
)
|
||||||
|
|||||||
@@ -1,41 +1,76 @@
|
|||||||
import { useAnalyticsGraph } from 'contexts/AnalyticsGraphProvider'
|
import { useAnalyticsGraph } from 'contexts/AnalyticsGraphProvider'
|
||||||
import React, { useMemo } from 'react'
|
import { useGraph } from 'contexts/GraphContext'
|
||||||
|
import React, { useEffect, useMemo, useState } from 'react'
|
||||||
import {
|
import {
|
||||||
getAnchorsPosition,
|
getAnchorsPosition,
|
||||||
computeFlowChartConnectorPath,
|
computeEdgePath,
|
||||||
|
getEndpointTopOffset,
|
||||||
} from 'services/graph'
|
} from 'services/graph'
|
||||||
|
|
||||||
type Props = { stepId: string }
|
type Props = { stepId: string }
|
||||||
|
|
||||||
export const Edge = ({ stepId }: Props) => {
|
export const Edge = ({ stepId }: Props) => {
|
||||||
const { typebot } = useAnalyticsGraph()
|
const { typebot } = useAnalyticsGraph()
|
||||||
|
const step = typebot?.steps.byId[stepId]
|
||||||
|
const { sourceEndpoints, targetEndpoints, graphPosition } = useGraph()
|
||||||
|
const [sourceTop, setSourceTop] = useState(
|
||||||
|
getEndpointTopOffset(graphPosition, sourceEndpoints, stepId)
|
||||||
|
)
|
||||||
|
const [targetTop, setTargetTop] = useState(
|
||||||
|
getEndpointTopOffset(graphPosition, sourceEndpoints, step?.target?.stepId)
|
||||||
|
)
|
||||||
|
|
||||||
const { sourceBlock, targetBlock, targetStepIndex } = useMemo(() => {
|
useEffect(() => {
|
||||||
|
const newSourceTop = getEndpointTopOffset(
|
||||||
|
graphPosition,
|
||||||
|
sourceEndpoints,
|
||||||
|
stepId
|
||||||
|
)
|
||||||
|
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,
|
||||||
|
step?.target?.stepId
|
||||||
|
)
|
||||||
|
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])
|
||||||
|
|
||||||
|
const { sourceBlock, targetBlock } = useMemo(() => {
|
||||||
if (!typebot) return {}
|
if (!typebot) return {}
|
||||||
const step = typebot.steps.byId[stepId]
|
if (!step?.target) return {}
|
||||||
if (!step.target) return {}
|
|
||||||
const targetBlock = typebot.blocks.byId[step.target.blockId]
|
const targetBlock = typebot.blocks.byId[step.target.blockId]
|
||||||
const targetStepIndex = step.target.stepId
|
|
||||||
? targetBlock.stepIds.indexOf(step.target.stepId)
|
|
||||||
: undefined
|
|
||||||
const sourceBlock = typebot.blocks.byId[step.blockId]
|
const sourceBlock = typebot.blocks.byId[step.blockId]
|
||||||
return {
|
return {
|
||||||
sourceBlock,
|
sourceBlock,
|
||||||
targetBlock,
|
targetBlock,
|
||||||
targetStepIndex,
|
|
||||||
}
|
}
|
||||||
}, [stepId, typebot])
|
}, [step?.blockId, step?.target, typebot])
|
||||||
|
|
||||||
const path = useMemo(() => {
|
const path = useMemo(() => {
|
||||||
if (!sourceBlock || !targetBlock) return ``
|
if (!sourceBlock || !targetBlock) return ``
|
||||||
const anchorsPosition = getAnchorsPosition({
|
const anchorsPosition = getAnchorsPosition({
|
||||||
sourceBlock,
|
sourceBlock,
|
||||||
targetBlock,
|
targetBlock,
|
||||||
sourceStepIndex: sourceBlock.stepIds.indexOf(stepId),
|
sourceTop,
|
||||||
sourceChoiceItemIndex: targetStepIndex,
|
targetTop,
|
||||||
})
|
})
|
||||||
return computeFlowChartConnectorPath(anchorsPosition)
|
return computeEdgePath(anchorsPosition)
|
||||||
}, [sourceBlock, stepId, targetBlock, targetStepIndex])
|
}, [sourceBlock, sourceTop, targetBlock, targetTop])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<path
|
<path
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
CheckSquareIcon,
|
CheckSquareIcon,
|
||||||
EditIcon,
|
EditIcon,
|
||||||
EmailIcon,
|
EmailIcon,
|
||||||
|
FilterIcon,
|
||||||
FlagIcon,
|
FlagIcon,
|
||||||
GlobeIcon,
|
GlobeIcon,
|
||||||
NumberIcon,
|
NumberIcon,
|
||||||
@@ -45,6 +46,9 @@ export const StepIcon = ({ type, ...props }: StepIconProps) => {
|
|||||||
case LogicStepType.SET_VARIABLE: {
|
case LogicStepType.SET_VARIABLE: {
|
||||||
return <EditIcon {...props} />
|
return <EditIcon {...props} />
|
||||||
}
|
}
|
||||||
|
case LogicStepType.CONDITION: {
|
||||||
|
return <FilterIcon {...props} />
|
||||||
|
}
|
||||||
case 'start': {
|
case 'start': {
|
||||||
return <FlagIcon {...props} />
|
return <FlagIcon {...props} />
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,6 +31,9 @@ export const StepTypeLabel = ({ type }: Props) => {
|
|||||||
case LogicStepType.SET_VARIABLE: {
|
case LogicStepType.SET_VARIABLE: {
|
||||||
return <Text>Set variable</Text>
|
return <Text>Set variable</Text>
|
||||||
}
|
}
|
||||||
|
case LogicStepType.CONDITION: {
|
||||||
|
return <Text>Condition</Text>
|
||||||
|
}
|
||||||
default: {
|
default: {
|
||||||
return <></>
|
return <></>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,13 @@
|
|||||||
import { PopoverContent, PopoverArrow, PopoverBody } from '@chakra-ui/react'
|
import {
|
||||||
|
PopoverContent,
|
||||||
|
PopoverArrow,
|
||||||
|
PopoverBody,
|
||||||
|
useEventListener,
|
||||||
|
} from '@chakra-ui/react'
|
||||||
import { useTypebot } from 'contexts/TypebotContext/TypebotContext'
|
import { useTypebot } from 'contexts/TypebotContext/TypebotContext'
|
||||||
import {
|
import {
|
||||||
ChoiceInputOptions,
|
ChoiceInputOptions,
|
||||||
|
ConditionOptions,
|
||||||
InputStep,
|
InputStep,
|
||||||
InputStepType,
|
InputStepType,
|
||||||
LogicStepType,
|
LogicStepType,
|
||||||
@@ -9,6 +15,7 @@ import {
|
|||||||
Step,
|
Step,
|
||||||
TextInputOptions,
|
TextInputOptions,
|
||||||
} from 'models'
|
} from 'models'
|
||||||
|
import { useRef } from 'react'
|
||||||
import {
|
import {
|
||||||
TextInputSettingsBody,
|
TextInputSettingsBody,
|
||||||
NumberInputSettingsBody,
|
NumberInputSettingsBody,
|
||||||
@@ -17,6 +24,7 @@ import {
|
|||||||
DateInputSettingsBody,
|
DateInputSettingsBody,
|
||||||
} from './bodies'
|
} from './bodies'
|
||||||
import { ChoiceInputSettingsBody } from './bodies/ChoiceInputSettingsBody'
|
import { ChoiceInputSettingsBody } from './bodies/ChoiceInputSettingsBody'
|
||||||
|
import { ConditionSettingsBody } from './bodies/ConditionSettingsBody'
|
||||||
import { PhoneNumberSettingsBody } from './bodies/PhoneNumberSettingsBody'
|
import { PhoneNumberSettingsBody } from './bodies/PhoneNumberSettingsBody'
|
||||||
import { SetVariableSettingsBody } from './bodies/SetVariableSettingsBody'
|
import { SetVariableSettingsBody } from './bodies/SetVariableSettingsBody'
|
||||||
|
|
||||||
@@ -25,12 +33,17 @@ type Props = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const SettingsPopoverContent = ({ step }: Props) => {
|
export const SettingsPopoverContent = ({ step }: Props) => {
|
||||||
|
const ref = useRef<HTMLDivElement | null>(null)
|
||||||
const handleMouseDown = (e: React.MouseEvent) => e.stopPropagation()
|
const handleMouseDown = (e: React.MouseEvent) => e.stopPropagation()
|
||||||
|
|
||||||
|
const handleMouseWheel = (e: WheelEvent) => {
|
||||||
|
e.stopPropagation()
|
||||||
|
}
|
||||||
|
useEventListener('wheel', handleMouseWheel, ref.current)
|
||||||
return (
|
return (
|
||||||
<PopoverContent onMouseDown={handleMouseDown}>
|
<PopoverContent onMouseDown={handleMouseDown}>
|
||||||
<PopoverArrow />
|
<PopoverArrow />
|
||||||
<PopoverBody p="6">
|
<PopoverBody p="6" overflowY="scroll" maxH="400px" ref={ref}>
|
||||||
<SettingsPopoverBodyContent step={step} />
|
<SettingsPopoverBodyContent step={step} />
|
||||||
</PopoverBody>
|
</PopoverBody>
|
||||||
</PopoverContent>
|
</PopoverContent>
|
||||||
@@ -40,7 +53,11 @@ export const SettingsPopoverContent = ({ step }: Props) => {
|
|||||||
const SettingsPopoverBodyContent = ({ step }: Props) => {
|
const SettingsPopoverBodyContent = ({ step }: Props) => {
|
||||||
const { updateStep } = useTypebot()
|
const { updateStep } = useTypebot()
|
||||||
const handleOptionsChange = (
|
const handleOptionsChange = (
|
||||||
options: TextInputOptions | ChoiceInputOptions | SetVariableOptions
|
options:
|
||||||
|
| TextInputOptions
|
||||||
|
| ChoiceInputOptions
|
||||||
|
| SetVariableOptions
|
||||||
|
| ConditionOptions
|
||||||
) => updateStep(step.id, { options } as Partial<InputStep>)
|
) => updateStep(step.id, { options } as Partial<InputStep>)
|
||||||
|
|
||||||
switch (step.type) {
|
switch (step.type) {
|
||||||
@@ -108,6 +125,14 @@ const SettingsPopoverBodyContent = ({ step }: Props) => {
|
|||||||
/>
|
/>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
case LogicStepType.CONDITION: {
|
||||||
|
return (
|
||||||
|
<ConditionSettingsBody
|
||||||
|
options={step.options}
|
||||||
|
onOptionsChange={handleOptionsChange}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
default: {
|
default: {
|
||||||
return <></>
|
return <></>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,157 @@
|
|||||||
|
import { Button, Fade, Flex, IconButton, Stack } from '@chakra-ui/react'
|
||||||
|
import { PlusIcon, TrashIcon } from 'assets/icons'
|
||||||
|
import { DebouncedInput } from 'components/shared/DebouncedInput'
|
||||||
|
import { DropdownList } from 'components/shared/DropdownList'
|
||||||
|
import { VariableSearchInput } from 'components/shared/VariableSearchInput'
|
||||||
|
import {
|
||||||
|
Comparison,
|
||||||
|
ComparisonOperators,
|
||||||
|
LogicalOperator,
|
||||||
|
Table,
|
||||||
|
Variable,
|
||||||
|
} from 'models'
|
||||||
|
import React, { useEffect, useState } from 'react'
|
||||||
|
import { generate } from 'short-uuid'
|
||||||
|
import { useImmer } from 'use-immer'
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
initialComparisons: Table<Comparison>
|
||||||
|
logicalOperator: LogicalOperator
|
||||||
|
onLogicalOperatorChange: (logicalOperator: LogicalOperator) => void
|
||||||
|
onComparisonsChange: (comparisons: Table<Comparison>) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ComparisonsList = ({
|
||||||
|
initialComparisons,
|
||||||
|
logicalOperator,
|
||||||
|
onLogicalOperatorChange,
|
||||||
|
onComparisonsChange,
|
||||||
|
}: Props) => {
|
||||||
|
const [comparisons, setComparisons] = useImmer(initialComparisons)
|
||||||
|
const [showDeleteId, setShowDeleteId] = useState<string | undefined>()
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
onComparisonsChange(comparisons)
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [comparisons])
|
||||||
|
|
||||||
|
const createComparison = () => {
|
||||||
|
setComparisons((comparisons) => {
|
||||||
|
const id = generate()
|
||||||
|
comparisons.byId[id] = {
|
||||||
|
id,
|
||||||
|
comparisonOperator: ComparisonOperators.EQUAL,
|
||||||
|
}
|
||||||
|
comparisons.allIds.push(id)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const updateComparison = (
|
||||||
|
comparisonId: string,
|
||||||
|
updates: Partial<Omit<Comparison, 'id'>>
|
||||||
|
) =>
|
||||||
|
setComparisons((comparisons) => {
|
||||||
|
comparisons.byId[comparisonId] = {
|
||||||
|
...comparisons.byId[comparisonId],
|
||||||
|
...updates,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const deleteComparison = (comparisonId: string) => () => {
|
||||||
|
setComparisons((comparisons) => {
|
||||||
|
delete comparisons.byId[comparisonId]
|
||||||
|
const index = comparisons.allIds.indexOf(comparisonId)
|
||||||
|
if (index !== -1) comparisons.allIds.splice(index, 1)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleVariableSelected =
|
||||||
|
(comparisonId: string) => (variable: Variable) => {
|
||||||
|
updateComparison(comparisonId, { variableId: variable.id })
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleComparisonOperatorSelected =
|
||||||
|
(comparisonId: string) => (dropdownItem: ComparisonOperators) =>
|
||||||
|
updateComparison(comparisonId, {
|
||||||
|
comparisonOperator: dropdownItem,
|
||||||
|
})
|
||||||
|
const handleLogicalOperatorSelected = (dropdownItem: LogicalOperator) =>
|
||||||
|
onLogicalOperatorChange(dropdownItem)
|
||||||
|
|
||||||
|
const handleValueChange = (comparisonId: string) => (value: string) =>
|
||||||
|
updateComparison(comparisonId, { value })
|
||||||
|
|
||||||
|
const handleMouseEnter = (comparisonId: string) => () => {
|
||||||
|
setShowDeleteId(comparisonId)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleMouseLeave = () => setShowDeleteId(undefined)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Stack spacing="4" py="4">
|
||||||
|
{comparisons.allIds.map((comparisonId, idx) => (
|
||||||
|
<>
|
||||||
|
{idx > 0 && (
|
||||||
|
<Flex justify="center">
|
||||||
|
<DropdownList<LogicalOperator>
|
||||||
|
currentItem={logicalOperator}
|
||||||
|
onItemSelect={handleLogicalOperatorSelected}
|
||||||
|
items={Object.values(LogicalOperator)}
|
||||||
|
/>
|
||||||
|
</Flex>
|
||||||
|
)}
|
||||||
|
<Flex
|
||||||
|
pos="relative"
|
||||||
|
onMouseEnter={handleMouseEnter(comparisonId)}
|
||||||
|
onMouseLeave={handleMouseLeave}
|
||||||
|
>
|
||||||
|
<Stack
|
||||||
|
key={comparisonId}
|
||||||
|
bgColor="blue.50"
|
||||||
|
p="4"
|
||||||
|
rounded="md"
|
||||||
|
flex="1"
|
||||||
|
>
|
||||||
|
<VariableSearchInput
|
||||||
|
initialVariableId={comparisons.byId[comparisonId].variableId}
|
||||||
|
onSelectVariable={handleVariableSelected(comparisonId)}
|
||||||
|
bgColor="white"
|
||||||
|
placeholder="Search for a variable"
|
||||||
|
/>
|
||||||
|
<DropdownList<ComparisonOperators>
|
||||||
|
currentItem={comparisons.byId[comparisonId].comparisonOperator}
|
||||||
|
onItemSelect={handleComparisonOperatorSelected(comparisonId)}
|
||||||
|
items={Object.values(ComparisonOperators)}
|
||||||
|
bgColor="white"
|
||||||
|
/>
|
||||||
|
{comparisons.byId[comparisonId].comparisonOperator !==
|
||||||
|
ComparisonOperators.IS_SET && (
|
||||||
|
<DebouncedInput
|
||||||
|
delay={100}
|
||||||
|
initialValue={comparisons.byId[comparisonId].value ?? ''}
|
||||||
|
onChange={handleValueChange(comparisonId)}
|
||||||
|
bgColor="white"
|
||||||
|
placeholder="Type a value..."
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
<Fade in={showDeleteId === comparisonId}>
|
||||||
|
<IconButton
|
||||||
|
icon={<TrashIcon />}
|
||||||
|
aria-label="Remove comparison"
|
||||||
|
onClick={deleteComparison(comparisonId)}
|
||||||
|
pos="absolute"
|
||||||
|
left="-10px"
|
||||||
|
top="-10px"
|
||||||
|
size="sm"
|
||||||
|
/>
|
||||||
|
</Fade>
|
||||||
|
</Flex>
|
||||||
|
</>
|
||||||
|
))}
|
||||||
|
<Button leftIcon={<PlusIcon />} onClick={createComparison} flexShrink={0}>
|
||||||
|
Add
|
||||||
|
</Button>
|
||||||
|
</Stack>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { Comparison, ConditionOptions, LogicalOperator, Table } from 'models'
|
||||||
|
import React from 'react'
|
||||||
|
import { ComparisonsList } from './ComparisonsList'
|
||||||
|
|
||||||
|
type ConditionSettingsBodyProps = {
|
||||||
|
options: ConditionOptions
|
||||||
|
onOptionsChange: (options: ConditionOptions) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ConditionSettingsBody = ({
|
||||||
|
options,
|
||||||
|
onOptionsChange,
|
||||||
|
}: ConditionSettingsBodyProps) => {
|
||||||
|
const handleComparisonsChange = (comparisons: Table<Comparison>) =>
|
||||||
|
onOptionsChange({ ...options, comparisons })
|
||||||
|
const handleLogicalOperatorChange = (logicalOperator: LogicalOperator) =>
|
||||||
|
onOptionsChange({ ...options, logicalOperator })
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ComparisonsList
|
||||||
|
initialComparisons={options.comparisons}
|
||||||
|
logicalOperator={options.logicalOperator ?? LogicalOperator.AND}
|
||||||
|
onLogicalOperatorChange={handleLogicalOperatorChange}
|
||||||
|
onComparisonsChange={handleComparisonsChange}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export { ConditionSettingsBody } from './ConditonSettingsBody'
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Box, BoxProps } from '@chakra-ui/react'
|
import { Box, BoxProps } from '@chakra-ui/react'
|
||||||
import { ConnectingSourceIds, useGraph } from 'contexts/GraphContext'
|
import { ConnectingSourceIds, useGraph } from 'contexts/GraphContext'
|
||||||
import React, { MouseEvent } from 'react'
|
import React, { MouseEvent, useEffect, useRef } from 'react'
|
||||||
|
|
||||||
export const SourceEndpoint = ({
|
export const SourceEndpoint = ({
|
||||||
source,
|
source,
|
||||||
@@ -8,15 +8,28 @@ export const SourceEndpoint = ({
|
|||||||
}: BoxProps & {
|
}: BoxProps & {
|
||||||
source: ConnectingSourceIds
|
source: ConnectingSourceIds
|
||||||
}) => {
|
}) => {
|
||||||
const { setConnectingIds } = useGraph()
|
const { setConnectingIds, addSourceEndpoint: addEndpoint } = useGraph()
|
||||||
|
const ref = useRef<HTMLDivElement | null>(null)
|
||||||
|
|
||||||
const handleMouseDown = (e: MouseEvent<HTMLDivElement>) => {
|
const handleMouseDown = (e: MouseEvent<HTMLDivElement>) => {
|
||||||
e.stopPropagation()
|
e.stopPropagation()
|
||||||
setConnectingIds({ source })
|
setConnectingIds({ source })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!ref.current) return
|
||||||
|
const id =
|
||||||
|
source.choiceItemId ?? source.stepId + (source.conditionType ?? '')
|
||||||
|
addEndpoint({
|
||||||
|
id,
|
||||||
|
ref,
|
||||||
|
})
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [ref])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box
|
<Box
|
||||||
|
ref={ref}
|
||||||
boxSize="15px"
|
boxSize="15px"
|
||||||
rounded="full"
|
rounded="full"
|
||||||
bgColor="gray.500"
|
bgColor="gray.500"
|
||||||
|
|||||||
@@ -10,13 +10,7 @@ import React, { useEffect, useMemo, useState } from 'react'
|
|||||||
import { Block, Step } from 'models'
|
import { Block, Step } from 'models'
|
||||||
import { useGraph } from 'contexts/GraphContext'
|
import { useGraph } from 'contexts/GraphContext'
|
||||||
import { StepIcon } from 'components/board/StepTypesList/StepIcon'
|
import { StepIcon } from 'components/board/StepTypesList/StepIcon'
|
||||||
import {
|
import { isDefined, isInputStep, isLogicStep, isTextBubbleStep } from 'utils'
|
||||||
isChoiceInput,
|
|
||||||
isDefined,
|
|
||||||
isInputStep,
|
|
||||||
isLogicStep,
|
|
||||||
isTextBubbleStep,
|
|
||||||
} from 'utils'
|
|
||||||
import { Coordinates } from '@dnd-kit/core/dist/types'
|
import { Coordinates } from '@dnd-kit/core/dist/types'
|
||||||
import { TextEditor } from './TextEditor/TextEditor'
|
import { TextEditor } from './TextEditor/TextEditor'
|
||||||
import { StepNodeContent } from './StepNodeContent'
|
import { StepNodeContent } from './StepNodeContent'
|
||||||
@@ -26,6 +20,8 @@ import { SettingsPopoverContent } from './SettingsPopoverContent'
|
|||||||
import { DraggableStep } from 'contexts/DndContext'
|
import { DraggableStep } from 'contexts/DndContext'
|
||||||
import { StepNodeContextMenu } from './StepNodeContextMenu'
|
import { StepNodeContextMenu } from './StepNodeContextMenu'
|
||||||
import { SourceEndpoint } from './SourceEndpoint'
|
import { SourceEndpoint } from './SourceEndpoint'
|
||||||
|
import { hasDefaultConnector } from 'services/typebots'
|
||||||
|
import { TargetEndpoint } from './TargetEndpoint'
|
||||||
|
|
||||||
export const StepNode = ({
|
export const StepNode = ({
|
||||||
step,
|
step,
|
||||||
@@ -192,7 +188,13 @@ export const StepNode = ({
|
|||||||
>
|
>
|
||||||
<StepIcon type={step.type} mt="1" />
|
<StepIcon type={step.type} mt="1" />
|
||||||
<StepNodeContent step={step} />
|
<StepNodeContent step={step} />
|
||||||
{isConnectable && !isChoiceInput(step) && (
|
<TargetEndpoint
|
||||||
|
pos="absolute"
|
||||||
|
left="-32px"
|
||||||
|
top="19px"
|
||||||
|
stepId={step.id}
|
||||||
|
/>
|
||||||
|
{isConnectable && hasDefaultConnector(step) && (
|
||||||
<SourceEndpoint
|
<SourceEndpoint
|
||||||
source={{
|
source={{
|
||||||
blockId: step.blockId,
|
blockId: step.blockId,
|
||||||
@@ -205,17 +207,23 @@ export const StepNode = ({
|
|||||||
)}
|
)}
|
||||||
</HStack>
|
</HStack>
|
||||||
|
|
||||||
{isDefined(connectedStubPosition) && !isChoiceInput(step) && (
|
{isDefined(connectedStubPosition) &&
|
||||||
<Box
|
hasDefaultConnector(step) &&
|
||||||
h="2px"
|
isConnectable && (
|
||||||
pos="absolute"
|
<Box
|
||||||
right={connectedStubPosition === 'left' ? undefined : '-18px'}
|
h="2px"
|
||||||
left={connectedStubPosition === 'left' ? '-18px' : undefined}
|
pos="absolute"
|
||||||
top="25px"
|
right={
|
||||||
w="18px"
|
connectedStubPosition === 'left' ? undefined : '-18px'
|
||||||
bgColor="gray.500"
|
}
|
||||||
/>
|
left={
|
||||||
)}
|
connectedStubPosition === 'left' ? '-18px' : undefined
|
||||||
|
}
|
||||||
|
top="25px"
|
||||||
|
w="18px"
|
||||||
|
bgColor="gray.500"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</Flex>
|
</Flex>
|
||||||
</PopoverTrigger>
|
</PopoverTrigger>
|
||||||
{(isInputStep(step) || isLogicStep(step)) && (
|
{(isInputStep(step) || isLogicStep(step)) && (
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Flex, Text } from '@chakra-ui/react'
|
import { Flex, HStack, Stack, Tag, Text } from '@chakra-ui/react'
|
||||||
import { useTypebot } from 'contexts/TypebotContext'
|
import { useTypebot } from 'contexts/TypebotContext'
|
||||||
import {
|
import {
|
||||||
Step,
|
Step,
|
||||||
@@ -7,8 +7,10 @@ import {
|
|||||||
InputStepType,
|
InputStepType,
|
||||||
LogicStepType,
|
LogicStepType,
|
||||||
SetVariableStep,
|
SetVariableStep,
|
||||||
|
ConditionStep,
|
||||||
} from 'models'
|
} from 'models'
|
||||||
import { ChoiceItemsList } from './ChoiceInputStepNode/ChoiceItemsList'
|
import { ChoiceItemsList } from './ChoiceInputStepNode/ChoiceItemsList'
|
||||||
|
import { SourceEndpoint } from './SourceEndpoint'
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
step: Step | StartStep
|
step: Step | StartStep
|
||||||
@@ -79,6 +81,9 @@ export const StepNodeContent = ({ step }: Props) => {
|
|||||||
case LogicStepType.SET_VARIABLE: {
|
case LogicStepType.SET_VARIABLE: {
|
||||||
return <SetVariableNodeContent step={step} />
|
return <SetVariableNodeContent step={step} />
|
||||||
}
|
}
|
||||||
|
case LogicStepType.CONDITION: {
|
||||||
|
return <ConditionNodeContent step={step} />
|
||||||
|
}
|
||||||
case 'start': {
|
case 'start': {
|
||||||
return <Text>{step.label}</Text>
|
return <Text>{step.label}</Text>
|
||||||
}
|
}
|
||||||
@@ -101,3 +106,51 @@ const SetVariableNodeContent = ({ step }: { step: SetVariableStep }) => {
|
|||||||
</Text>
|
</Text>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const ConditionNodeContent = ({ step }: { step: ConditionStep }) => {
|
||||||
|
const { typebot } = useTypebot()
|
||||||
|
return (
|
||||||
|
<Flex>
|
||||||
|
<Stack color={'gray.500'}>
|
||||||
|
{step.options?.comparisons.allIds.map((comparisonId, idx) => {
|
||||||
|
const comparison = step.options?.comparisons.byId[comparisonId]
|
||||||
|
const variable = typebot?.variables.byId[comparison?.variableId ?? '']
|
||||||
|
return (
|
||||||
|
<HStack key={comparisonId} spacing={1}>
|
||||||
|
{idx > 0 && <Text>{step.options?.logicalOperator ?? ''}</Text>}
|
||||||
|
{variable?.name && (
|
||||||
|
<Tag bgColor="orange.400">{variable.name}</Tag>
|
||||||
|
)}
|
||||||
|
{comparison.comparisonOperator && (
|
||||||
|
<Text>{comparison?.comparisonOperator}</Text>
|
||||||
|
)}
|
||||||
|
{comparison?.value && (
|
||||||
|
<Tag bgColor={'green.400'}>{comparison.value}</Tag>
|
||||||
|
)}
|
||||||
|
</HStack>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</Stack>
|
||||||
|
<SourceEndpoint
|
||||||
|
source={{
|
||||||
|
blockId: step.blockId,
|
||||||
|
stepId: step.id,
|
||||||
|
conditionType: 'true',
|
||||||
|
}}
|
||||||
|
pos="absolute"
|
||||||
|
top="7px"
|
||||||
|
right="15px"
|
||||||
|
/>
|
||||||
|
<SourceEndpoint
|
||||||
|
source={{
|
||||||
|
blockId: step.blockId,
|
||||||
|
stepId: step.id,
|
||||||
|
conditionType: 'false',
|
||||||
|
}}
|
||||||
|
pos="absolute"
|
||||||
|
bottom="7px"
|
||||||
|
right="15px"
|
||||||
|
/>
|
||||||
|
</Flex>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { Box, BoxProps } from '@chakra-ui/react'
|
||||||
|
import { useGraph } from 'contexts/GraphContext'
|
||||||
|
import React, { useEffect, useRef } from 'react'
|
||||||
|
|
||||||
|
export const TargetEndpoint = ({
|
||||||
|
stepId,
|
||||||
|
isVisible,
|
||||||
|
...props
|
||||||
|
}: BoxProps & {
|
||||||
|
stepId: string
|
||||||
|
isVisible?: boolean
|
||||||
|
}) => {
|
||||||
|
const { addTargetEndpoint } = useGraph()
|
||||||
|
const ref = useRef<HTMLDivElement | null>(null)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!ref.current) return
|
||||||
|
addTargetEndpoint({
|
||||||
|
id: stepId,
|
||||||
|
ref,
|
||||||
|
})
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [ref])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
ref={ref}
|
||||||
|
boxSize="15px"
|
||||||
|
rounded="full"
|
||||||
|
bgColor="blue.500"
|
||||||
|
cursor="pointer"
|
||||||
|
visibility={isVisible ? 'visible' : 'hidden'}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -8,7 +8,6 @@ import {
|
|||||||
withPlate,
|
withPlate,
|
||||||
} from '@udecode/plate-core'
|
} from '@udecode/plate-core'
|
||||||
import { editorStyle, platePlugins } from 'libs/plate'
|
import { editorStyle, platePlugins } from 'libs/plate'
|
||||||
import { useDebounce } from 'use-debounce'
|
|
||||||
import { useTypebot } from 'contexts/TypebotContext/TypebotContext'
|
import { useTypebot } from 'contexts/TypebotContext/TypebotContext'
|
||||||
import { BaseSelection, createEditor, Transforms } from 'slate'
|
import { BaseSelection, createEditor, Transforms } from 'slate'
|
||||||
import { ToolBar } from './ToolBar'
|
import { ToolBar } from './ToolBar'
|
||||||
@@ -37,7 +36,6 @@ export const TextEditor = ({
|
|||||||
)
|
)
|
||||||
const { updateStep } = useTypebot()
|
const { updateStep } = useTypebot()
|
||||||
const [value, setValue] = useState(initialValue)
|
const [value, setValue] = useState(initialValue)
|
||||||
const [debouncedValue] = useDebounce(value, 500)
|
|
||||||
const varDropdownRef = useRef<HTMLDivElement | null>(null)
|
const varDropdownRef = useRef<HTMLDivElement | null>(null)
|
||||||
const rememberedSelection = useRef<BaseSelection | null>(null)
|
const rememberedSelection = useRef<BaseSelection | null>(null)
|
||||||
const [isVariableDropdownOpen, setIsVariableDropdownOpen] = useState(false)
|
const [isVariableDropdownOpen, setIsVariableDropdownOpen] = useState(false)
|
||||||
@@ -45,16 +43,15 @@ export const TextEditor = ({
|
|||||||
const textEditorRef = useRef<HTMLDivElement>(null)
|
const textEditorRef = useRef<HTMLDivElement>(null)
|
||||||
useOutsideClick({
|
useOutsideClick({
|
||||||
ref: textEditorRef,
|
ref: textEditorRef,
|
||||||
handler: () => {
|
handler: onClose,
|
||||||
save(value)
|
|
||||||
onClose()
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
save(debouncedValue)
|
return () => {
|
||||||
|
save(value)
|
||||||
|
}
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [debouncedValue])
|
}, [value])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isVariableDropdownOpen) return
|
if (!isVariableDropdownOpen) return
|
||||||
@@ -107,6 +104,7 @@ export const TextEditor = ({
|
|||||||
|
|
||||||
const handleChangeEditorContent = (val: unknown[]) => {
|
const handleChangeEditorContent = (val: unknown[]) => {
|
||||||
setValue(val)
|
setValue(val)
|
||||||
|
save(val)
|
||||||
setIsVariableDropdownOpen(false)
|
setIsVariableDropdownOpen(false)
|
||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -2,15 +2,22 @@ import { useEventListener } from '@chakra-ui/hooks'
|
|||||||
import { headerHeight } from 'components/shared/TypebotHeader/TypebotHeader'
|
import { headerHeight } from 'components/shared/TypebotHeader/TypebotHeader'
|
||||||
import { useGraph, ConnectingIds } from 'contexts/GraphContext'
|
import { useGraph, ConnectingIds } from 'contexts/GraphContext'
|
||||||
import { useTypebot } from 'contexts/TypebotContext/TypebotContext'
|
import { useTypebot } from 'contexts/TypebotContext/TypebotContext'
|
||||||
import { Target } from 'models'
|
import { Step, Target } from 'models'
|
||||||
import React, { useMemo, useState } from 'react'
|
import React, { useMemo, useState } from 'react'
|
||||||
import {
|
import {
|
||||||
computeDrawingConnectedPath,
|
computeConnectingEdgePath,
|
||||||
computeDrawingPathToMouse,
|
computeEdgePathToMouse,
|
||||||
|
getEndpointTopOffset,
|
||||||
} from 'services/graph'
|
} from 'services/graph'
|
||||||
|
|
||||||
export const DrawingEdge = () => {
|
export const DrawingEdge = () => {
|
||||||
const { graphPosition, setConnectingIds, connectingIds } = useGraph()
|
const {
|
||||||
|
graphPosition,
|
||||||
|
setConnectingIds,
|
||||||
|
connectingIds,
|
||||||
|
sourceEndpoints,
|
||||||
|
targetEndpoints,
|
||||||
|
} = useGraph()
|
||||||
const { typebot, updateStep, updateChoiceItem } = useTypebot()
|
const { typebot, updateStep, updateChoiceItem } = useTypebot()
|
||||||
const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 })
|
const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 })
|
||||||
|
|
||||||
@@ -20,22 +27,44 @@ export const DrawingEdge = () => {
|
|||||||
[connectingIds]
|
[connectingIds]
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const sourceTop = useMemo(() => {
|
||||||
|
if (!sourceBlock || !connectingIds) return 0
|
||||||
|
return getEndpointTopOffset(
|
||||||
|
graphPosition,
|
||||||
|
sourceEndpoints,
|
||||||
|
connectingIds.source.choiceItemId ??
|
||||||
|
connectingIds.source.stepId + (connectingIds.source.conditionType ?? '')
|
||||||
|
)
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [graphPosition, sourceEndpoints, connectingIds])
|
||||||
|
|
||||||
|
const targetTop = useMemo(() => {
|
||||||
|
if (!sourceBlock || !connectingIds) return 0
|
||||||
|
return getEndpointTopOffset(
|
||||||
|
graphPosition,
|
||||||
|
targetEndpoints,
|
||||||
|
connectingIds.target?.stepId
|
||||||
|
)
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [graphPosition, targetEndpoints, connectingIds])
|
||||||
|
|
||||||
const path = useMemo(() => {
|
const path = useMemo(() => {
|
||||||
if (!sourceBlock || !typebot || !connectingIds) return ``
|
if (!sourceBlock || !typebot || !connectingIds) return ``
|
||||||
|
|
||||||
return connectingIds?.target
|
return connectingIds?.target
|
||||||
? computeDrawingConnectedPath(
|
? computeConnectingEdgePath(
|
||||||
connectingIds as Omit<ConnectingIds, 'target'> & { target: Target },
|
connectingIds as Omit<ConnectingIds, 'target'> & { target: Target },
|
||||||
sourceBlock,
|
sourceBlock,
|
||||||
|
sourceTop,
|
||||||
|
targetTop,
|
||||||
typebot
|
typebot
|
||||||
)
|
)
|
||||||
: computeDrawingPathToMouse(
|
: computeEdgePathToMouse({
|
||||||
sourceBlock,
|
blockPosition: sourceBlock.graphCoordinates,
|
||||||
connectingIds,
|
|
||||||
mousePosition,
|
mousePosition,
|
||||||
typebot.steps
|
sourceTop,
|
||||||
)
|
})
|
||||||
}, [sourceBlock, typebot, connectingIds, mousePosition])
|
}, [sourceBlock, typebot, connectingIds, sourceTop, targetTop, mousePosition])
|
||||||
|
|
||||||
const handleMouseMove = (e: MouseEvent) => {
|
const handleMouseMove = (e: MouseEvent) => {
|
||||||
setMousePosition({
|
setMousePosition({
|
||||||
@@ -49,14 +78,25 @@ export const DrawingEdge = () => {
|
|||||||
setConnectingIds(null)
|
setConnectingIds(null)
|
||||||
})
|
})
|
||||||
|
|
||||||
const createNewEdge = (connectingIds: ConnectingIds) =>
|
const createNewEdge = (connectingIds: ConnectingIds) => {
|
||||||
connectingIds.source.choiceItemId
|
if (connectingIds.source.choiceItemId) {
|
||||||
? updateChoiceItem(connectingIds.source.choiceItemId, {
|
updateChoiceItem(connectingIds.source.choiceItemId, {
|
||||||
target: connectingIds.target,
|
target: connectingIds.target,
|
||||||
})
|
})
|
||||||
: updateStep(connectingIds.source.stepId, {
|
} else if (connectingIds.source.conditionType === 'true') {
|
||||||
target: connectingIds.target,
|
updateStep(connectingIds.source.stepId, {
|
||||||
})
|
trueTarget: connectingIds.target,
|
||||||
|
} as Step)
|
||||||
|
} else if (connectingIds.source.conditionType === 'false') {
|
||||||
|
updateStep(connectingIds.source.stepId, {
|
||||||
|
falseTarget: connectingIds.target,
|
||||||
|
} as Step)
|
||||||
|
} else {
|
||||||
|
updateStep(connectingIds.source.stepId, {
|
||||||
|
target: connectingIds.target,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if ((mousePosition.x === 0 && mousePosition.y === 0) || !connectingIds)
|
if ((mousePosition.x === 0 && mousePosition.y === 0) || !connectingIds)
|
||||||
return <></>
|
return <></>
|
||||||
|
|||||||
@@ -3,13 +3,13 @@ import assert from 'assert'
|
|||||||
import { Coordinates, useGraph } from 'contexts/GraphContext'
|
import { Coordinates, useGraph } from 'contexts/GraphContext'
|
||||||
import { useTypebot } from 'contexts/TypebotContext/TypebotContext'
|
import { useTypebot } from 'contexts/TypebotContext/TypebotContext'
|
||||||
import { ChoiceItem } from 'models'
|
import { ChoiceItem } from 'models'
|
||||||
import React, { useMemo } from 'react'
|
import React, { useEffect, useMemo, useState } from 'react'
|
||||||
import {
|
import {
|
||||||
getAnchorsPosition,
|
getAnchorsPosition,
|
||||||
computeFlowChartConnectorPath,
|
computeEdgePath,
|
||||||
getSourceChoiceItemIndex,
|
getEndpointTopOffset,
|
||||||
|
getTarget,
|
||||||
} from 'services/graph'
|
} from 'services/graph'
|
||||||
import { isChoiceInput } from 'utils'
|
|
||||||
|
|
||||||
export type AnchorsPositionProps = {
|
export type AnchorsPositionProps = {
|
||||||
sourcePosition: Coordinates
|
sourcePosition: Coordinates
|
||||||
@@ -18,15 +18,25 @@ export type AnchorsPositionProps = {
|
|||||||
totalSegments: number
|
totalSegments: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export enum EdgeType {
|
||||||
|
STEP,
|
||||||
|
CHOICE_ITEM,
|
||||||
|
CONDITION_TRUE,
|
||||||
|
CONDITION_FALSE,
|
||||||
|
}
|
||||||
|
|
||||||
export const Edge = ({
|
export const Edge = ({
|
||||||
|
type,
|
||||||
stepId,
|
stepId,
|
||||||
item,
|
item,
|
||||||
}: {
|
}: {
|
||||||
|
type: EdgeType
|
||||||
stepId: string
|
stepId: string
|
||||||
item?: ChoiceItem
|
item?: ChoiceItem
|
||||||
}) => {
|
}) => {
|
||||||
const { typebot } = useTypebot()
|
const { typebot } = useTypebot()
|
||||||
const { previewingIds } = useGraph()
|
const { previewingIds, sourceEndpoints, targetEndpoints, graphPosition } =
|
||||||
|
useGraph()
|
||||||
const step = typebot?.steps.byId[stepId]
|
const step = typebot?.steps.byId[stepId]
|
||||||
const isPreviewing = useMemo(
|
const isPreviewing = useMemo(
|
||||||
() =>
|
() =>
|
||||||
@@ -34,40 +44,83 @@ export const Edge = ({
|
|||||||
previewingIds.targetId === step?.target?.blockId,
|
previewingIds.targetId === step?.target?.blockId,
|
||||||
[previewingIds.sourceId, previewingIds.targetId, step]
|
[previewingIds.sourceId, previewingIds.targetId, step]
|
||||||
)
|
)
|
||||||
|
const [sourceTop, setSourceTop] = useState(
|
||||||
|
getEndpointTopOffset(graphPosition, sourceEndpoints, item?.id ?? step?.id)
|
||||||
|
)
|
||||||
|
const [targetTop, setTargetTop] = useState(
|
||||||
|
getEndpointTopOffset(graphPosition, targetEndpoints, step?.id)
|
||||||
|
)
|
||||||
|
|
||||||
const { sourceBlock, targetBlock, targetStepIndex } = useMemo(() => {
|
useEffect(() => {
|
||||||
|
const newSourceTop = getEndpointTopOffset(
|
||||||
|
graphPosition,
|
||||||
|
sourceEndpoints,
|
||||||
|
getSourceEndpointId()
|
||||||
|
)
|
||||||
|
const sensibilityThreshold = 10
|
||||||
|
const newSourceTopIsTooClose =
|
||||||
|
sourceTop < newSourceTop + sensibilityThreshold &&
|
||||||
|
sourceTop > newSourceTop - sensibilityThreshold
|
||||||
|
if (newSourceTopIsTooClose) return
|
||||||
|
setSourceTop(newSourceTop)
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [typebot?.blocks, typebot?.steps, graphPosition, sourceEndpoints])
|
||||||
|
|
||||||
|
const getSourceEndpointId = () => {
|
||||||
|
switch (type) {
|
||||||
|
case EdgeType.STEP:
|
||||||
|
return step?.id
|
||||||
|
case EdgeType.CHOICE_ITEM:
|
||||||
|
return item?.id
|
||||||
|
case EdgeType.CONDITION_TRUE:
|
||||||
|
return step?.id + 'true'
|
||||||
|
case EdgeType.CONDITION_FALSE:
|
||||||
|
return step?.id + 'false'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!step) return
|
||||||
|
const target = getTarget(step, type)
|
||||||
|
const newTargetTop = getEndpointTopOffset(
|
||||||
|
graphPosition,
|
||||||
|
targetEndpoints,
|
||||||
|
target?.blockId ?? target?.stepId
|
||||||
|
)
|
||||||
|
const sensibilityThreshold = 10
|
||||||
|
const newSourceTopIsTooClose =
|
||||||
|
targetTop < newTargetTop + sensibilityThreshold &&
|
||||||
|
targetTop > newTargetTop - sensibilityThreshold
|
||||||
|
if (newSourceTopIsTooClose) return
|
||||||
|
setTargetTop(newTargetTop)
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [typebot?.blocks, typebot?.steps, graphPosition, targetEndpoints])
|
||||||
|
|
||||||
|
const { sourceBlock, targetBlock } = useMemo(() => {
|
||||||
if (!typebot) return {}
|
if (!typebot) return {}
|
||||||
const step = typebot.steps.byId[stepId]
|
const step = typebot.steps.byId[stepId]
|
||||||
const sourceBlock = typebot.blocks.byId[step.blockId]
|
const sourceBlock = typebot.blocks.byId[step.blockId]
|
||||||
const targetBlockId = item?.target?.blockId ?? step.target?.blockId
|
const targetBlockId = getTarget(step, type)?.blockId
|
||||||
assert(isDefined(targetBlockId))
|
assert(isDefined(targetBlockId))
|
||||||
const targetBlock = typebot.blocks.byId[targetBlockId]
|
const targetBlock = typebot.blocks.byId[targetBlockId]
|
||||||
const targetStepId = item?.target?.stepId ?? step.target?.stepId
|
|
||||||
const targetStepIndex = targetStepId
|
|
||||||
? targetBlock.stepIds.indexOf(targetStepId)
|
|
||||||
: undefined
|
|
||||||
return {
|
return {
|
||||||
sourceBlock,
|
sourceBlock,
|
||||||
targetBlock,
|
targetBlock,
|
||||||
targetStepIndex,
|
|
||||||
}
|
}
|
||||||
}, [item?.target?.blockId, item?.target?.stepId, stepId, typebot])
|
}, [stepId, type, typebot])
|
||||||
|
|
||||||
const path = useMemo(() => {
|
const path = useMemo(() => {
|
||||||
if (!sourceBlock || !targetBlock || !step) return ``
|
if (!sourceBlock || !targetBlock || !step) return ``
|
||||||
const sourceChoiceItemIndex = isChoiceInput(step)
|
|
||||||
? getSourceChoiceItemIndex(step, item?.id)
|
|
||||||
: undefined
|
|
||||||
const anchorsPosition = getAnchorsPosition({
|
const anchorsPosition = getAnchorsPosition({
|
||||||
sourceBlock,
|
sourceBlock,
|
||||||
targetBlock,
|
targetBlock,
|
||||||
sourceStepIndex: sourceBlock.stepIds.indexOf(stepId),
|
sourceTop,
|
||||||
targetStepIndex,
|
targetTop,
|
||||||
sourceChoiceItemIndex,
|
|
||||||
})
|
})
|
||||||
return computeFlowChartConnectorPath(anchorsPosition)
|
return computeEdgePath(anchorsPosition)
|
||||||
}, [item, sourceBlock, step, stepId, targetBlock, targetStepIndex])
|
}, [sourceBlock, sourceTop, step, targetBlock, targetTop])
|
||||||
|
|
||||||
|
if (sourceTop === 0) return <></>
|
||||||
return (
|
return (
|
||||||
<path
|
<path
|
||||||
d={path}
|
d={path}
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { chakra } from '@chakra-ui/system'
|
import { chakra } from '@chakra-ui/system'
|
||||||
import { useTypebot } from 'contexts/TypebotContext/TypebotContext'
|
import { useTypebot } from 'contexts/TypebotContext/TypebotContext'
|
||||||
import { ChoiceItem } from 'models'
|
import { ChoiceItem, ConditionStep } from 'models'
|
||||||
import React, { useMemo } from 'react'
|
import React, { useMemo } from 'react'
|
||||||
import { isDefined, isSingleChoiceInput } from 'utils'
|
import { isConditionStep, isDefined, isSingleChoiceInput } from 'utils'
|
||||||
import { DrawingEdge } from './DrawingEdge'
|
import { DrawingEdge } from './DrawingEdge'
|
||||||
import { Edge } from './Edge'
|
import { Edge, EdgeType } from './Edge'
|
||||||
|
|
||||||
export const Edges = () => {
|
export const Edges = () => {
|
||||||
const { typebot } = useTypebot()
|
const { typebot } = useTypebot()
|
||||||
@@ -26,6 +26,14 @@ export const Edges = () => {
|
|||||||
)
|
)
|
||||||
.map((itemId) => typebot.choiceItems.byId[itemId])
|
.map((itemId) => typebot.choiceItems.byId[itemId])
|
||||||
}, [typebot])
|
}, [typebot])
|
||||||
|
const conditionStepIdsWithTarget = useMemo(
|
||||||
|
() =>
|
||||||
|
typebot?.steps.allIds.filter((stepId) => {
|
||||||
|
const step = typebot.steps.byId[stepId]
|
||||||
|
return isConditionStep(step) && (step.trueTarget || step.falseTarget)
|
||||||
|
}),
|
||||||
|
[typebot?.steps.allIds, typebot?.steps.byId]
|
||||||
|
)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<chakra.svg
|
<chakra.svg
|
||||||
@@ -38,10 +46,18 @@ export const Edges = () => {
|
|||||||
>
|
>
|
||||||
<DrawingEdge />
|
<DrawingEdge />
|
||||||
{stepIdsWithTarget.map((stepId) => (
|
{stepIdsWithTarget.map((stepId) => (
|
||||||
<Edge key={stepId} stepId={stepId} />
|
<Edge key={stepId} stepId={stepId} type={EdgeType.STEP} />
|
||||||
))}
|
))}
|
||||||
{singleChoiceItemsWithTarget.map((item) => (
|
{singleChoiceItemsWithTarget.map((item) => (
|
||||||
<Edge key={item.id} stepId={item.stepId} item={item} />
|
<Edge
|
||||||
|
key={item.id}
|
||||||
|
stepId={item.stepId}
|
||||||
|
item={item}
|
||||||
|
type={EdgeType.CHOICE_ITEM}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
{conditionStepIdsWithTarget?.map((stepId) => (
|
||||||
|
<ConditionStepEdges key={stepId} stepId={stepId} />
|
||||||
))}
|
))}
|
||||||
<marker
|
<marker
|
||||||
id={'arrow'}
|
id={'arrow'}
|
||||||
@@ -61,3 +77,18 @@ export const Edges = () => {
|
|||||||
</chakra.svg>
|
</chakra.svg>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const ConditionStepEdges = ({ stepId }: { stepId: string }) => {
|
||||||
|
const { typebot } = useTypebot()
|
||||||
|
const step = typebot?.steps.byId[stepId] as ConditionStep
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{step.trueTarget && (
|
||||||
|
<Edge type={EdgeType.CONDITION_TRUE} stepId={stepId} />
|
||||||
|
)}
|
||||||
|
{step.falseTarget && (
|
||||||
|
<Edge type={EdgeType.CONDITION_FALSE} stepId={stepId} />
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|||||||
61
apps/builder/components/shared/DropdownList.tsx
Normal file
61
apps/builder/components/shared/DropdownList.tsx
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Menu,
|
||||||
|
MenuButton,
|
||||||
|
MenuButtonProps,
|
||||||
|
MenuItem,
|
||||||
|
MenuList,
|
||||||
|
Stack,
|
||||||
|
} from '@chakra-ui/react'
|
||||||
|
import { ChevronLeftIcon } from 'assets/icons'
|
||||||
|
import React from 'react'
|
||||||
|
|
||||||
|
type Props<T> = {
|
||||||
|
currentItem: T
|
||||||
|
onItemSelect: (item: T) => void
|
||||||
|
items: T[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DropdownList = <T,>({
|
||||||
|
currentItem,
|
||||||
|
onItemSelect,
|
||||||
|
items,
|
||||||
|
...props
|
||||||
|
}: Props<T> & MenuButtonProps) => {
|
||||||
|
const handleMenuItemClick = (operator: T) => () => {
|
||||||
|
onItemSelect(operator)
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Menu isLazy placement="bottom-end">
|
||||||
|
<MenuButton
|
||||||
|
as={Button}
|
||||||
|
rightIcon={<ChevronLeftIcon transform={'rotate(-90deg)'} />}
|
||||||
|
colorScheme="gray"
|
||||||
|
isTruncated
|
||||||
|
justifyContent="space-between"
|
||||||
|
textAlign="left"
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{currentItem}
|
||||||
|
</MenuButton>
|
||||||
|
<MenuList maxW="500px">
|
||||||
|
<Stack maxH={'35vh'} overflowY="scroll" spacing="0">
|
||||||
|
{items.map((item) => (
|
||||||
|
<MenuItem
|
||||||
|
key={item as unknown as string}
|
||||||
|
maxW="500px"
|
||||||
|
overflow="hidden"
|
||||||
|
whiteSpace="nowrap"
|
||||||
|
textOverflow="ellipsis"
|
||||||
|
onClick={handleMenuItemClick(item)}
|
||||||
|
>
|
||||||
|
{item}
|
||||||
|
</MenuItem>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
</MenuList>
|
||||||
|
</Menu>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -13,7 +13,7 @@ export const headerHeight = 56
|
|||||||
|
|
||||||
export const TypebotHeader = () => {
|
export const TypebotHeader = () => {
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const { typebot } = useTypebot()
|
const { typebot, updateTypebot } = useTypebot()
|
||||||
const { setRightPanel } = useEditor()
|
const { setRightPanel } = useEditor()
|
||||||
|
|
||||||
const handleBackClick = () => {
|
const handleBackClick = () => {
|
||||||
@@ -23,6 +23,7 @@ export const TypebotHeader = () => {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const handleNameSubmit = (name: string) => updateTypebot({ name })
|
||||||
return (
|
return (
|
||||||
<Flex
|
<Flex
|
||||||
w="full"
|
w="full"
|
||||||
@@ -87,7 +88,7 @@ export const TypebotHeader = () => {
|
|||||||
/>
|
/>
|
||||||
<EditableTypebotName
|
<EditableTypebotName
|
||||||
name={typebot?.name}
|
name={typebot?.name}
|
||||||
onNewName={(newName) => console.log(newName)}
|
onNewName={handleNameSubmit}
|
||||||
/>
|
/>
|
||||||
</Flex>
|
</Flex>
|
||||||
</Flex>
|
</Flex>
|
||||||
|
|||||||
@@ -13,9 +13,9 @@ export enum RightPanel {
|
|||||||
const editorContext = createContext<{
|
const editorContext = createContext<{
|
||||||
rightPanel?: RightPanel
|
rightPanel?: RightPanel
|
||||||
setRightPanel: Dispatch<SetStateAction<RightPanel | undefined>>
|
setRightPanel: Dispatch<SetStateAction<RightPanel | undefined>>
|
||||||
}>({
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||||
setRightPanel: () => console.log("I'm not instantiated"),
|
//@ts-ignore
|
||||||
})
|
}>({})
|
||||||
|
|
||||||
export const EditorContext = ({ children }: { children: ReactNode }) => {
|
export const EditorContext = ({ children }: { children: ReactNode }) => {
|
||||||
const [rightPanel, setRightPanel] = useState<RightPanel>()
|
const [rightPanel, setRightPanel] = useState<RightPanel>()
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { Block, Step, Target } from 'models'
|
import { Block, Step, Table, Target } from 'models'
|
||||||
import {
|
import {
|
||||||
createContext,
|
createContext,
|
||||||
Dispatch,
|
Dispatch,
|
||||||
|
MutableRefObject,
|
||||||
ReactNode,
|
ReactNode,
|
||||||
SetStateAction,
|
SetStateAction,
|
||||||
useContext,
|
useContext,
|
||||||
@@ -24,10 +25,6 @@ export const blockAnchorsOffset = {
|
|||||||
y: 20,
|
y: 20,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
export const firstStepOffsetY = 88
|
|
||||||
export const spaceBetweenSteps = 62
|
|
||||||
|
|
||||||
export const firstChoiceItemOffsetY = 20
|
|
||||||
|
|
||||||
export type Coordinates = { x: number; y: number }
|
export type Coordinates = { x: number; y: number }
|
||||||
|
|
||||||
@@ -54,10 +51,18 @@ export type ConnectingSourceIds = {
|
|||||||
blockId: string
|
blockId: string
|
||||||
stepId: string
|
stepId: string
|
||||||
choiceItemId?: string
|
choiceItemId?: string
|
||||||
|
conditionType?: 'true' | 'false'
|
||||||
}
|
}
|
||||||
|
|
||||||
type PreviewingIdsProps = { sourceId?: string; targetId?: string }
|
type PreviewingIdsProps = { sourceId?: string; targetId?: string }
|
||||||
|
|
||||||
|
type StepId = string
|
||||||
|
type NodeId = string
|
||||||
|
export type Endpoint = {
|
||||||
|
id: StepId | NodeId
|
||||||
|
ref: MutableRefObject<HTMLDivElement | null>
|
||||||
|
}
|
||||||
|
|
||||||
const graphContext = createContext<{
|
const graphContext = createContext<{
|
||||||
graphPosition: Position
|
graphPosition: Position
|
||||||
setGraphPosition: Dispatch<SetStateAction<Position>>
|
setGraphPosition: Dispatch<SetStateAction<Position>>
|
||||||
@@ -65,6 +70,10 @@ const graphContext = createContext<{
|
|||||||
setConnectingIds: Dispatch<SetStateAction<ConnectingIds | null>>
|
setConnectingIds: Dispatch<SetStateAction<ConnectingIds | null>>
|
||||||
previewingIds: PreviewingIdsProps
|
previewingIds: PreviewingIdsProps
|
||||||
setPreviewingIds: Dispatch<SetStateAction<PreviewingIdsProps>>
|
setPreviewingIds: Dispatch<SetStateAction<PreviewingIdsProps>>
|
||||||
|
sourceEndpoints: Table<Endpoint>
|
||||||
|
addSourceEndpoint: (endpoint: Endpoint) => void
|
||||||
|
targetEndpoints: Table<Endpoint>
|
||||||
|
addTargetEndpoint: (endpoint: Endpoint) => void
|
||||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||||
//@ts-ignore
|
//@ts-ignore
|
||||||
}>({
|
}>({
|
||||||
@@ -76,6 +85,28 @@ export const GraphProvider = ({ children }: { children: ReactNode }) => {
|
|||||||
const [graphPosition, setGraphPosition] = useState(graphPositionDefaultValue)
|
const [graphPosition, setGraphPosition] = useState(graphPositionDefaultValue)
|
||||||
const [connectingIds, setConnectingIds] = useState<ConnectingIds | null>(null)
|
const [connectingIds, setConnectingIds] = useState<ConnectingIds | null>(null)
|
||||||
const [previewingIds, setPreviewingIds] = useState<PreviewingIdsProps>({})
|
const [previewingIds, setPreviewingIds] = useState<PreviewingIdsProps>({})
|
||||||
|
const [sourceEndpoints, setSourceEndpoints] = useState<Table<Endpoint>>({
|
||||||
|
byId: {},
|
||||||
|
allIds: [],
|
||||||
|
})
|
||||||
|
const [targetEndpoints, setTargetEndpoints] = useState<Table<Endpoint>>({
|
||||||
|
byId: {},
|
||||||
|
allIds: [],
|
||||||
|
})
|
||||||
|
|
||||||
|
const addSourceEndpoint = (endpoint: Endpoint) => {
|
||||||
|
setSourceEndpoints((endpoints) => ({
|
||||||
|
byId: { ...endpoints.byId, [endpoint.id]: endpoint },
|
||||||
|
allIds: [...endpoints.allIds, endpoint.id],
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
const addTargetEndpoint = (endpoint: Endpoint) => {
|
||||||
|
setTargetEndpoints((endpoints) => ({
|
||||||
|
byId: { ...endpoints.byId, [endpoint.id]: endpoint },
|
||||||
|
allIds: [...endpoints.allIds, endpoint.id],
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<graphContext.Provider
|
<graphContext.Provider
|
||||||
@@ -86,6 +117,10 @@ export const GraphProvider = ({ children }: { children: ReactNode }) => {
|
|||||||
setConnectingIds,
|
setConnectingIds,
|
||||||
previewingIds,
|
previewingIds,
|
||||||
setPreviewingIds,
|
setPreviewingIds,
|
||||||
|
sourceEndpoints,
|
||||||
|
targetEndpoints,
|
||||||
|
addSourceEndpoint,
|
||||||
|
addTargetEndpoint,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{children}
|
{children}
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ type UpdateTypebotPayload = Partial<{
|
|||||||
theme: Theme
|
theme: Theme
|
||||||
settings: Settings
|
settings: Settings
|
||||||
publicId: string
|
publicId: string
|
||||||
|
name: string
|
||||||
}>
|
}>
|
||||||
const typebotContext = createContext<
|
const typebotContext = createContext<
|
||||||
{
|
{
|
||||||
@@ -150,12 +151,14 @@ export const TypebotContext = ({
|
|||||||
publicId,
|
publicId,
|
||||||
settings,
|
settings,
|
||||||
theme,
|
theme,
|
||||||
|
name,
|
||||||
}: UpdateTypebotPayload) => {
|
}: UpdateTypebotPayload) => {
|
||||||
setLocalTypebot((typebot) => {
|
setLocalTypebot((typebot) => {
|
||||||
if (!typebot) return
|
if (!typebot) return
|
||||||
if (publicId) typebot.publicId = publicId
|
if (publicId) typebot.publicId = publicId
|
||||||
if (settings) typebot.settings = settings
|
if (settings) typebot.settings = settings
|
||||||
if (theme) typebot.theme = theme
|
if (theme) typebot.theme = theme
|
||||||
|
if (name) typebot.name = name
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
191
apps/builder/cypress/fixtures/typebots/logic/condition.json
Normal file
191
apps/builder/cypress/fixtures/typebots/logic/condition.json
Normal file
@@ -0,0 +1,191 @@
|
|||||||
|
{
|
||||||
|
"id": "typebot4",
|
||||||
|
"createdAt": "2022-01-14T14:23:36.576Z",
|
||||||
|
"updatedAt": "2022-01-14T14:23:36.576Z",
|
||||||
|
"name": "My typebot",
|
||||||
|
"ownerId": "ckye5hs3e1801em1a0eodjj3f",
|
||||||
|
"publishedTypebotId": null,
|
||||||
|
"folderId": null,
|
||||||
|
"blocks": {
|
||||||
|
"byId": {
|
||||||
|
"1YV9MuAa6dd6eNxC5BipDZ": {
|
||||||
|
"id": "1YV9MuAa6dd6eNxC5BipDZ",
|
||||||
|
"title": "Start",
|
||||||
|
"stepIds": ["3EzaqYRLFqFQFbCj2gQP3q"],
|
||||||
|
"graphCoordinates": { "x": 0, "y": 0 }
|
||||||
|
},
|
||||||
|
"bnmeD9SVeGPhF4qvwKfxE8R": {
|
||||||
|
"id": "bnmeD9SVeGPhF4qvwKfxE8R",
|
||||||
|
"title": "Block #2",
|
||||||
|
"stepIds": ["condition1", "condition2"],
|
||||||
|
"graphCoordinates": { "x": 194, "y": 228 }
|
||||||
|
},
|
||||||
|
"b3EaF53FGbQH5MhbBPUjDjb": {
|
||||||
|
"id": "b3EaF53FGbQH5MhbBPUjDjb",
|
||||||
|
"title": "Block #4",
|
||||||
|
"graphCoordinates": { "x": 375, "y": -39 },
|
||||||
|
"stepIds": ["siBqadjM6AJXf25Ct4413dM", "sqTSo2heZ5vdfzJjNZfYUK5"]
|
||||||
|
},
|
||||||
|
"b2Wjyg4MsqB5xhQYQPbPYkc": {
|
||||||
|
"id": "b2Wjyg4MsqB5xhQYQPbPYkc",
|
||||||
|
"title": "Block #4",
|
||||||
|
"graphCoordinates": { "x": 712, "y": 186 },
|
||||||
|
"stepIds": ["srFH8bxpJZuShgr2hmz4uhx"]
|
||||||
|
},
|
||||||
|
"b4KB24EywCVt3zX3opqMvYS": {
|
||||||
|
"id": "b4KB24EywCVt3zX3opqMvYS",
|
||||||
|
"title": "Block #5",
|
||||||
|
"graphCoordinates": { "x": 700, "y": 340 },
|
||||||
|
"stepIds": ["ssBZF1FgMDYZJTbmTzb8Uks"]
|
||||||
|
},
|
||||||
|
"bppe1zzyayc8ub14ozqJEXb": {
|
||||||
|
"id": "bppe1zzyayc8ub14ozqJEXb",
|
||||||
|
"title": "Block #6",
|
||||||
|
"graphCoordinates": { "x": 713, "y": 491 },
|
||||||
|
"stepIds": ["scQmWL2qGp1oXnEYdqjLcDv"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"allIds": [
|
||||||
|
"1YV9MuAa6dd6eNxC5BipDZ",
|
||||||
|
"bnmeD9SVeGPhF4qvwKfxE8R",
|
||||||
|
"b3EaF53FGbQH5MhbBPUjDjb",
|
||||||
|
"b2Wjyg4MsqB5xhQYQPbPYkc",
|
||||||
|
"b4KB24EywCVt3zX3opqMvYS",
|
||||||
|
"bppe1zzyayc8ub14ozqJEXb"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"steps": {
|
||||||
|
"byId": {
|
||||||
|
"3EzaqYRLFqFQFbCj2gQP3q": {
|
||||||
|
"id": "3EzaqYRLFqFQFbCj2gQP3q",
|
||||||
|
"type": "start",
|
||||||
|
"label": "Start",
|
||||||
|
"target": { "blockId": "b3EaF53FGbQH5MhbBPUjDjb" },
|
||||||
|
"blockId": "1YV9MuAa6dd6eNxC5BipDZ"
|
||||||
|
},
|
||||||
|
"condition1": {
|
||||||
|
"id": "condition1",
|
||||||
|
"type": "Condition",
|
||||||
|
"blockId": "bnmeD9SVeGPhF4qvwKfxE8R",
|
||||||
|
"trueTarget": { "blockId": "b2Wjyg4MsqB5xhQYQPbPYkc" },
|
||||||
|
"options": {
|
||||||
|
"comparisons": {
|
||||||
|
"byId": { "comparison1": { "comparisonOperator": "Equal to" } },
|
||||||
|
"allIds": ["comparison1"]
|
||||||
|
},
|
||||||
|
"logicalOperator": "AND"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"condition2": {
|
||||||
|
"id": "condition2",
|
||||||
|
"blockId": "bnmeD9SVeGPhF4qvwKfxE8R",
|
||||||
|
"type": "Condition",
|
||||||
|
"trueTarget": { "blockId": "b4KB24EywCVt3zX3opqMvYS" },
|
||||||
|
"falseTarget": { "blockId": "bppe1zzyayc8ub14ozqJEXb" },
|
||||||
|
"options": {
|
||||||
|
"comparisons": {
|
||||||
|
"byId": { "comparison1": { "comparisonOperator": "Equal to" } },
|
||||||
|
"allIds": ["comparison1"]
|
||||||
|
},
|
||||||
|
"logicalOperator": "AND"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"sqTSo2heZ5vdfzJjNZfYUK5": {
|
||||||
|
"id": "sqTSo2heZ5vdfzJjNZfYUK5",
|
||||||
|
"blockId": "b3EaF53FGbQH5MhbBPUjDjb",
|
||||||
|
"type": "number input",
|
||||||
|
"options": {
|
||||||
|
"variableId": "icVxLRv1sQnPyNwRX9cjK9",
|
||||||
|
"min": 0,
|
||||||
|
"max": 150,
|
||||||
|
"labels": { "placeholder": "Type your age..." }
|
||||||
|
},
|
||||||
|
"target": { "blockId": "bnmeD9SVeGPhF4qvwKfxE8R" }
|
||||||
|
},
|
||||||
|
"siBqadjM6AJXf25Ct4413dM": {
|
||||||
|
"id": "siBqadjM6AJXf25Ct4413dM",
|
||||||
|
"blockId": "b3EaF53FGbQH5MhbBPUjDjb",
|
||||||
|
"type": "text",
|
||||||
|
"content": {
|
||||||
|
"html": "<div>How old are you?</div>",
|
||||||
|
"richText": [
|
||||||
|
{ "type": "p", "children": [{ "text": "How old are you?" }] }
|
||||||
|
],
|
||||||
|
"plainText": "How old are you?"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"srFH8bxpJZuShgr2hmz4uhx": {
|
||||||
|
"id": "srFH8bxpJZuShgr2hmz4uhx",
|
||||||
|
"blockId": "b2Wjyg4MsqB5xhQYQPbPYkc",
|
||||||
|
"type": "text",
|
||||||
|
"content": {
|
||||||
|
"html": "<div>Wow you are older than 80</div>",
|
||||||
|
"richText": [
|
||||||
|
{
|
||||||
|
"type": "p",
|
||||||
|
"children": [{ "text": "Wow you are older than 80" }]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"plainText": "Wow you are older than 80"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"ssBZF1FgMDYZJTbmTzb8Uks": {
|
||||||
|
"id": "ssBZF1FgMDYZJTbmTzb8Uks",
|
||||||
|
"blockId": "b4KB24EywCVt3zX3opqMvYS",
|
||||||
|
"type": "text",
|
||||||
|
"content": {
|
||||||
|
"html": "<div>Wow you are older than 20</div>",
|
||||||
|
"richText": [
|
||||||
|
{
|
||||||
|
"type": "p",
|
||||||
|
"children": [{ "text": "Wow you are older than 20" }]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"plainText": "Wow you are older than 20"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"scQmWL2qGp1oXnEYdqjLcDv": {
|
||||||
|
"id": "scQmWL2qGp1oXnEYdqjLcDv",
|
||||||
|
"blockId": "bppe1zzyayc8ub14ozqJEXb",
|
||||||
|
"type": "text",
|
||||||
|
"content": {
|
||||||
|
"html": "<div>You are younger than 20</div>",
|
||||||
|
"richText": [
|
||||||
|
{ "type": "p", "children": [{ "text": "You are younger than 20" }] }
|
||||||
|
],
|
||||||
|
"plainText": "You are younger than 20"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"allIds": [
|
||||||
|
"3EzaqYRLFqFQFbCj2gQP3q",
|
||||||
|
"condition1",
|
||||||
|
"condition2",
|
||||||
|
"sqTSo2heZ5vdfzJjNZfYUK5",
|
||||||
|
"siBqadjM6AJXf25Ct4413dM",
|
||||||
|
"srFH8bxpJZuShgr2hmz4uhx",
|
||||||
|
"ssBZF1FgMDYZJTbmTzb8Uks",
|
||||||
|
"scQmWL2qGp1oXnEYdqjLcDv"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"choiceItems": { "byId": {}, "allIds": [] },
|
||||||
|
"variables": {
|
||||||
|
"byId": {
|
||||||
|
"icVxLRv1sQnPyNwRX9cjK9": {
|
||||||
|
"id": "icVxLRv1sQnPyNwRX9cjK9",
|
||||||
|
"name": "Age"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"allIds": ["icVxLRv1sQnPyNwRX9cjK9"]
|
||||||
|
},
|
||||||
|
"theme": {
|
||||||
|
"general": {
|
||||||
|
"font": "Open Sans",
|
||||||
|
"background": { "type": "None", "content": "#ffffff" }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"typingEmulation": { "speed": 300, "enabled": true, "maxDelay": 1.5 }
|
||||||
|
},
|
||||||
|
"publicId": null
|
||||||
|
}
|
||||||
@@ -276,11 +276,11 @@ const createTypebotWithStep = (step: Omit<InputStep, 'id' | 'blockId'>) => {
|
|||||||
...step,
|
...step,
|
||||||
id: 'step1',
|
id: 'step1',
|
||||||
blockId: 'block1',
|
blockId: 'block1',
|
||||||
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||||
|
//@ts-ignore
|
||||||
options:
|
options:
|
||||||
step.type === InputStepType.CHOICE
|
step.type === InputStepType.CHOICE
|
||||||
? // eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
? { itemIds: ['item1'] }
|
||||||
//@ts-ignore
|
|
||||||
{ itemIds: ['item1'] }
|
|
||||||
: undefined,
|
: undefined,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -39,6 +39,60 @@ describe('Set variables', () => {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('Condition step', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
cy.task('seed')
|
||||||
|
cy.signOut()
|
||||||
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cy.window().then((win) => {
|
||||||
|
win.removeEventListener('beforeunload', preventUserFromRefreshing)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
it('options should work', () => {
|
||||||
|
cy.loadTypebotFixtureInDatabase('typebots/logic/condition.json')
|
||||||
|
cy.signIn('test2@gmail.com')
|
||||||
|
cy.visit('/typebots/typebot4/edit')
|
||||||
|
|
||||||
|
cy.findByTestId('step-condition1').click()
|
||||||
|
|
||||||
|
cy.findByTestId('variables-input').click()
|
||||||
|
cy.findByRole('menuitem', { name: 'Age' }).click()
|
||||||
|
cy.findByRole('button', { name: 'Equal to' }).click()
|
||||||
|
cy.findByRole('menuitem', { name: 'Greater than' }).click()
|
||||||
|
cy.findByPlaceholderText('Type a value...').type('80')
|
||||||
|
|
||||||
|
cy.findByRole('button', { name: 'Add' }).click()
|
||||||
|
cy.findAllByTestId('variables-input').last().click()
|
||||||
|
cy.findByRole('menuitem', { name: 'Age' }).click()
|
||||||
|
cy.findByRole('button', { name: 'Equal to' }).click()
|
||||||
|
cy.findByRole('menuitem', { name: 'Less than' }).click()
|
||||||
|
cy.findAllByPlaceholderText('Type a value...').last().type('100')
|
||||||
|
|
||||||
|
cy.findByTestId('step-condition2').click()
|
||||||
|
|
||||||
|
cy.findByTestId('variables-input').click()
|
||||||
|
cy.findByRole('menuitem', { name: 'Age' }).click()
|
||||||
|
cy.findByRole('button', { name: 'Equal to' }).click()
|
||||||
|
cy.findByRole('menuitem', { name: 'Greater than' }).click()
|
||||||
|
cy.findByPlaceholderText('Type a value...').type('20')
|
||||||
|
|
||||||
|
cy.findByRole('button', { name: 'Preview' }).click()
|
||||||
|
getIframeBody().findByPlaceholderText('Type your age...').type('15{enter}')
|
||||||
|
getIframeBody().findByText('You are younger than 20').should('exist')
|
||||||
|
|
||||||
|
cy.findByRole('button', { name: 'Restart' }).click()
|
||||||
|
getIframeBody().findByPlaceholderText('Type your age...').type('45{enter}')
|
||||||
|
getIframeBody().findByText('Wow you are older than 20').should('exist')
|
||||||
|
|
||||||
|
cy.findByRole('button', { name: 'Restart' }).click()
|
||||||
|
getIframeBody().findByPlaceholderText('Type your age...').type('90{enter}')
|
||||||
|
getIframeBody().findByText('Wow you are older than 80').should('exist')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
const createNewVar = (name: string) => {
|
const createNewVar = (name: string) => {
|
||||||
cy.findByTestId('variables-input').type(name)
|
cy.findByTestId('variables-input').type(name)
|
||||||
cy.findByRole('menuitem', { name: `Create "${name}"` }).click()
|
cy.findByRole('menuitem', { name: `Create "${name}"` }).click()
|
||||||
|
|||||||
@@ -1,17 +1,19 @@
|
|||||||
import { Coordinates } from '@dnd-kit/core/dist/types'
|
import { Coordinates } from '@dnd-kit/core/dist/types'
|
||||||
import { Block, ChoiceInputStep, Step, Table, Target, Typebot } from 'models'
|
import { Block, Step, Table, Target, Typebot } from 'models'
|
||||||
import { AnchorsPositionProps } from 'components/board/graph/Edges/Edge'
|
import {
|
||||||
|
AnchorsPositionProps,
|
||||||
|
EdgeType,
|
||||||
|
} from 'components/board/graph/Edges/Edge'
|
||||||
import {
|
import {
|
||||||
stubLength,
|
stubLength,
|
||||||
blockWidth,
|
blockWidth,
|
||||||
blockAnchorsOffset,
|
blockAnchorsOffset,
|
||||||
spaceBetweenSteps,
|
|
||||||
firstStepOffsetY,
|
|
||||||
firstChoiceItemOffsetY,
|
|
||||||
ConnectingIds,
|
ConnectingIds,
|
||||||
|
Endpoint,
|
||||||
} from 'contexts/GraphContext'
|
} from 'contexts/GraphContext'
|
||||||
import { roundCorners } from 'svg-round-corners'
|
import { roundCorners } from 'svg-round-corners'
|
||||||
import { isChoiceInput, isDefined } from 'utils'
|
import { headerHeight } from 'components/shared/TypebotHeader'
|
||||||
|
import { isConditionStep } from 'utils'
|
||||||
|
|
||||||
export const computeDropOffPath = (
|
export const computeDropOffPath = (
|
||||||
sourcePosition: Coordinates,
|
sourcePosition: Coordinates,
|
||||||
@@ -27,38 +29,12 @@ export const computeDropOffPath = (
|
|||||||
|
|
||||||
export const computeSourceCoordinates = (
|
export const computeSourceCoordinates = (
|
||||||
sourcePosition: Coordinates,
|
sourcePosition: Coordinates,
|
||||||
sourceStepIndex: number,
|
sourceTop: number
|
||||||
sourceChoiceItemIndex?: number
|
|
||||||
) => ({
|
) => ({
|
||||||
x: sourcePosition.x + blockWidth,
|
x: sourcePosition.x + blockWidth,
|
||||||
y:
|
y: sourceTop,
|
||||||
(sourcePosition.y ?? 0) +
|
|
||||||
firstStepOffsetY +
|
|
||||||
spaceBetweenSteps * sourceStepIndex +
|
|
||||||
(isDefined(sourceChoiceItemIndex)
|
|
||||||
? firstChoiceItemOffsetY +
|
|
||||||
(sourceChoiceItemIndex ?? 0) * spaceBetweenSteps
|
|
||||||
: 0),
|
|
||||||
})
|
})
|
||||||
|
|
||||||
export const computeFlowChartConnectorPath = ({
|
|
||||||
sourcePosition,
|
|
||||||
targetPosition,
|
|
||||||
sourceType,
|
|
||||||
totalSegments,
|
|
||||||
}: AnchorsPositionProps) => {
|
|
||||||
const segments = getSegments({
|
|
||||||
sourcePosition,
|
|
||||||
targetPosition,
|
|
||||||
sourceType,
|
|
||||||
totalSegments,
|
|
||||||
})
|
|
||||||
return roundCorners(
|
|
||||||
`M${sourcePosition.x},${sourcePosition.y} ${segments}`,
|
|
||||||
10
|
|
||||||
).path
|
|
||||||
}
|
|
||||||
|
|
||||||
const getSegments = ({
|
const getSegments = ({
|
||||||
sourcePosition,
|
sourcePosition,
|
||||||
targetPosition,
|
targetPosition,
|
||||||
@@ -152,27 +128,20 @@ const computeFiveSegments = (
|
|||||||
type GetAnchorsPositionParams = {
|
type GetAnchorsPositionParams = {
|
||||||
sourceBlock: Block
|
sourceBlock: Block
|
||||||
targetBlock: Block
|
targetBlock: Block
|
||||||
sourceStepIndex: number
|
sourceTop: number
|
||||||
sourceChoiceItemIndex?: number
|
targetTop: number
|
||||||
targetStepIndex?: number
|
|
||||||
}
|
}
|
||||||
export const getAnchorsPosition = ({
|
export const getAnchorsPosition = ({
|
||||||
sourceBlock,
|
sourceBlock,
|
||||||
targetBlock,
|
targetBlock,
|
||||||
sourceStepIndex,
|
sourceTop,
|
||||||
sourceChoiceItemIndex,
|
targetTop,
|
||||||
targetStepIndex,
|
|
||||||
}: GetAnchorsPositionParams): AnchorsPositionProps => {
|
}: GetAnchorsPositionParams): AnchorsPositionProps => {
|
||||||
const targetOffsetY = isDefined(targetStepIndex)
|
const targetOffsetY = targetTop > 0 ? targetTop : undefined
|
||||||
? (targetBlock.graphCoordinates.y ?? 0) +
|
|
||||||
firstStepOffsetY +
|
|
||||||
spaceBetweenSteps * targetStepIndex
|
|
||||||
: undefined
|
|
||||||
|
|
||||||
const sourcePosition = computeSourceCoordinates(
|
const sourcePosition = computeSourceCoordinates(
|
||||||
sourceBlock.graphCoordinates,
|
sourceBlock.graphCoordinates,
|
||||||
sourceStepIndex,
|
sourceTop
|
||||||
sourceChoiceItemIndex
|
|
||||||
)
|
)
|
||||||
let sourceType: 'right' | 'left' = 'right'
|
let sourceType: 'right' | 'left' = 'right'
|
||||||
if (sourceBlock.graphCoordinates.x > targetBlock.graphCoordinates.x) {
|
if (sourceBlock.graphCoordinates.x > targetBlock.graphCoordinates.x) {
|
||||||
@@ -247,78 +216,58 @@ const parseBlockAnchorPosition = (
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const computeDrawingConnectedPath = (
|
export const computeEdgePath = ({
|
||||||
|
sourcePosition,
|
||||||
|
targetPosition,
|
||||||
|
sourceType,
|
||||||
|
totalSegments,
|
||||||
|
}: AnchorsPositionProps) => {
|
||||||
|
const segments = getSegments({
|
||||||
|
sourcePosition,
|
||||||
|
targetPosition,
|
||||||
|
sourceType,
|
||||||
|
totalSegments,
|
||||||
|
})
|
||||||
|
return roundCorners(
|
||||||
|
`M${sourcePosition.x},${sourcePosition.y} ${segments}`,
|
||||||
|
10
|
||||||
|
).path
|
||||||
|
}
|
||||||
|
|
||||||
|
export const computeConnectingEdgePath = (
|
||||||
connectingIds: Omit<ConnectingIds, 'target'> & { target: Target },
|
connectingIds: Omit<ConnectingIds, 'target'> & { target: Target },
|
||||||
sourceBlock: Block,
|
sourceBlock: Block,
|
||||||
|
sourceTop: number,
|
||||||
|
targetTop: number,
|
||||||
typebot: Typebot
|
typebot: Typebot
|
||||||
) => {
|
) => {
|
||||||
if (!sourceBlock) return ``
|
if (!sourceBlock) return ``
|
||||||
const targetBlock = typebot.blocks.byId[connectingIds.target.blockId]
|
const targetBlock = typebot.blocks.byId[connectingIds.target.blockId]
|
||||||
const targetStepIndex = connectingIds.target.stepId
|
|
||||||
? targetBlock.stepIds.findIndex(
|
|
||||||
(stepId) => stepId === connectingIds.target?.stepId
|
|
||||||
)
|
|
||||||
: undefined
|
|
||||||
|
|
||||||
const sourceStepIndex = sourceBlock?.stepIds.indexOf(
|
|
||||||
connectingIds?.source.stepId
|
|
||||||
)
|
|
||||||
const sourceStep = typebot.steps.byId[connectingIds?.source.stepId]
|
|
||||||
const sourceChoiceItemIndex = isChoiceInput(sourceStep)
|
|
||||||
? getSourceChoiceItemIndex(sourceStep, connectingIds.source.choiceItemId)
|
|
||||||
: undefined
|
|
||||||
const anchorsPosition = getAnchorsPosition({
|
const anchorsPosition = getAnchorsPosition({
|
||||||
sourceBlock,
|
sourceBlock,
|
||||||
targetBlock,
|
targetBlock,
|
||||||
sourceStepIndex,
|
sourceTop,
|
||||||
sourceChoiceItemIndex,
|
targetTop,
|
||||||
targetStepIndex,
|
|
||||||
})
|
})
|
||||||
return computeFlowChartConnectorPath(anchorsPosition)
|
return computeEdgePath(anchorsPosition)
|
||||||
}
|
}
|
||||||
|
|
||||||
export const computeDrawingPathToMouse = (
|
export const computeEdgePathToMouse = ({
|
||||||
sourceBlock: Block,
|
|
||||||
connectingIds: ConnectingIds,
|
|
||||||
mousePosition: Coordinates,
|
|
||||||
steps: Table<Step>
|
|
||||||
) => {
|
|
||||||
const sourceStep = steps.byId[connectingIds?.source.stepId ?? '']
|
|
||||||
return computeConnectingEdgePath({
|
|
||||||
blockPosition: sourceBlock?.graphCoordinates,
|
|
||||||
mousePosition,
|
|
||||||
stepIndex: sourceBlock.stepIds.findIndex(
|
|
||||||
(stepId) => stepId === connectingIds?.source.stepId
|
|
||||||
),
|
|
||||||
choiceItemIndex: isChoiceInput(sourceStep)
|
|
||||||
? getSourceChoiceItemIndex(sourceStep, connectingIds?.source.choiceItemId)
|
|
||||||
: undefined,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const computeConnectingEdgePath = ({
|
|
||||||
blockPosition,
|
blockPosition,
|
||||||
mousePosition,
|
mousePosition,
|
||||||
stepIndex,
|
sourceTop,
|
||||||
choiceItemIndex,
|
|
||||||
}: {
|
}: {
|
||||||
blockPosition: Coordinates
|
blockPosition: Coordinates
|
||||||
mousePosition: Coordinates
|
mousePosition: Coordinates
|
||||||
stepIndex: number
|
sourceTop: number
|
||||||
choiceItemIndex?: number
|
|
||||||
}): string => {
|
}): string => {
|
||||||
const sourcePosition = {
|
const sourcePosition = {
|
||||||
x:
|
x:
|
||||||
mousePosition.x - blockPosition.x > blockWidth / 2
|
mousePosition.x - blockPosition.x > blockWidth / 2
|
||||||
? blockPosition.x + blockWidth - 40
|
? blockPosition.x + blockWidth - 40
|
||||||
: blockPosition.x + 40,
|
: blockPosition.x + 40,
|
||||||
y:
|
y: sourceTop,
|
||||||
blockPosition.y +
|
|
||||||
firstStepOffsetY +
|
|
||||||
stepIndex * spaceBetweenSteps +
|
|
||||||
(isDefined(choiceItemIndex)
|
|
||||||
? firstChoiceItemOffsetY + (choiceItemIndex ?? 0) * spaceBetweenSteps
|
|
||||||
: 0),
|
|
||||||
}
|
}
|
||||||
const sourceType =
|
const sourceType =
|
||||||
mousePosition.x - blockPosition.x > blockWidth / 2 ? 'right' : 'left'
|
mousePosition.x - blockPosition.x > blockWidth / 2 ? 'right' : 'left'
|
||||||
@@ -333,8 +282,33 @@ const computeConnectingEdgePath = ({
|
|||||||
).path
|
).path
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getSourceChoiceItemIndex = (
|
export const getEndpointTopOffset = (
|
||||||
step: ChoiceInputStep,
|
graphPosition: Coordinates,
|
||||||
itemId?: string
|
endpoints: Table<Endpoint>,
|
||||||
) =>
|
id?: string
|
||||||
itemId ? step.options.itemIds.indexOf(itemId) : step.options.itemIds.length
|
): number => {
|
||||||
|
if (!id) return 0
|
||||||
|
const endpointRef = endpoints.byId[id]?.ref
|
||||||
|
if (!endpointRef) return 0
|
||||||
|
return (
|
||||||
|
7 +
|
||||||
|
(endpointRef.current?.getBoundingClientRect().top ?? 0) -
|
||||||
|
graphPosition.y -
|
||||||
|
headerHeight
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getTarget = (step: Step, edgeType: EdgeType) => {
|
||||||
|
if (!step) return
|
||||||
|
switch (edgeType) {
|
||||||
|
case EdgeType.STEP:
|
||||||
|
case EdgeType.CHOICE_ITEM:
|
||||||
|
return step.target
|
||||||
|
case EdgeType.CONDITION_TRUE:
|
||||||
|
if (!isConditionStep(step)) return
|
||||||
|
return step.trueTarget
|
||||||
|
case EdgeType.CONDITION_FALSE:
|
||||||
|
if (!isConditionStep(step)) return
|
||||||
|
return step.falseTarget
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -13,13 +13,18 @@ import {
|
|||||||
ChoiceInputStep,
|
ChoiceInputStep,
|
||||||
LogicStepType,
|
LogicStepType,
|
||||||
LogicStep,
|
LogicStep,
|
||||||
|
Step,
|
||||||
|
ConditionStep,
|
||||||
|
ComparisonOperators,
|
||||||
|
LogicalOperator,
|
||||||
} from 'models'
|
} from 'models'
|
||||||
import shortId from 'short-uuid'
|
import shortId, { generate } from 'short-uuid'
|
||||||
import { Typebot } from 'models'
|
import { Typebot } from 'models'
|
||||||
import useSWR from 'swr'
|
import useSWR from 'swr'
|
||||||
import { fetcher, sendRequest, toKebabCase } from './utils'
|
import { fetcher, sendRequest, toKebabCase } from './utils'
|
||||||
import { deepEqual } from 'fast-equals'
|
import { deepEqual } from 'fast-equals'
|
||||||
import { stringify } from 'qs'
|
import { stringify } from 'qs'
|
||||||
|
import { isChoiceInput, isConditionStep } from 'utils'
|
||||||
|
|
||||||
export const useTypebots = ({
|
export const useTypebots = ({
|
||||||
folderId,
|
folderId,
|
||||||
@@ -136,6 +141,26 @@ export const parseNewStep = (
|
|||||||
...choiceInput,
|
...choiceInput,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
case LogicStepType.CONDITION: {
|
||||||
|
const id = generate()
|
||||||
|
const conditionStep: Pick<ConditionStep, 'type' | 'options'> = {
|
||||||
|
type,
|
||||||
|
options: {
|
||||||
|
comparisons: {
|
||||||
|
byId: {
|
||||||
|
[id]: { id, comparisonOperator: ComparisonOperators.EQUAL },
|
||||||
|
},
|
||||||
|
allIds: [id],
|
||||||
|
},
|
||||||
|
logicalOperator: LogicalOperator.AND,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
blockId,
|
||||||
|
...conditionStep,
|
||||||
|
}
|
||||||
|
}
|
||||||
default: {
|
default: {
|
||||||
return {
|
return {
|
||||||
id,
|
id,
|
||||||
@@ -214,3 +239,6 @@ export const parseNewTypebot = ({
|
|||||||
settings,
|
settings,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const hasDefaultConnector = (step: Step) =>
|
||||||
|
!isChoiceInput(step) && !isConditionStep(step)
|
||||||
|
|||||||
@@ -4,10 +4,20 @@ import { TransitionGroup, CSSTransition } from 'react-transition-group'
|
|||||||
import { ChatStep } from './ChatStep'
|
import { ChatStep } from './ChatStep'
|
||||||
import { AvatarSideContainer } from './AvatarSideContainer'
|
import { AvatarSideContainer } from './AvatarSideContainer'
|
||||||
import { HostAvatarsContext } from '../../contexts/HostAvatarsContext'
|
import { HostAvatarsContext } from '../../contexts/HostAvatarsContext'
|
||||||
import { ChoiceInputStep, LogicStep, Step } from 'models'
|
import {
|
||||||
|
ChoiceInputStep,
|
||||||
|
ComparisonOperators,
|
||||||
|
ConditionStep,
|
||||||
|
LogicalOperator,
|
||||||
|
LogicStep,
|
||||||
|
LogicStepType,
|
||||||
|
Step,
|
||||||
|
Target,
|
||||||
|
} from 'models'
|
||||||
import { useTypebot } from '../../contexts/TypebotContext'
|
import { useTypebot } from '../../contexts/TypebotContext'
|
||||||
import {
|
import {
|
||||||
isChoiceInput,
|
isChoiceInput,
|
||||||
|
isDefined,
|
||||||
isInputStep,
|
isInputStep,
|
||||||
isLogicStep,
|
isLogicStep,
|
||||||
isTextBubbleStep,
|
isTextBubbleStep,
|
||||||
@@ -20,23 +30,30 @@ import {
|
|||||||
|
|
||||||
type ChatBlockProps = {
|
type ChatBlockProps = {
|
||||||
stepIds: string[]
|
stepIds: string[]
|
||||||
onBlockEnd: (nextBlockId?: string) => void
|
startStepId?: string
|
||||||
|
onBlockEnd: (target?: Target) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ChatBlock = ({ stepIds, onBlockEnd }: ChatBlockProps) => {
|
export const ChatBlock = ({
|
||||||
|
stepIds,
|
||||||
|
startStepId,
|
||||||
|
onBlockEnd,
|
||||||
|
}: ChatBlockProps) => {
|
||||||
const { typebot, updateVariableValue } = useTypebot()
|
const { typebot, updateVariableValue } = useTypebot()
|
||||||
const [displayedSteps, setDisplayedSteps] = useState<Step[]>([])
|
const [displayedSteps, setDisplayedSteps] = useState<Step[]>([])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
displayNextStep()
|
const nextStep =
|
||||||
|
typebot.steps.byId[startStepId ?? stepIds[displayedSteps.length]]
|
||||||
|
if (nextStep) setDisplayedSteps([...displayedSteps, nextStep])
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
autoScrollToBottom()
|
autoScrollToBottom()
|
||||||
const currentStep = [...displayedSteps].pop()
|
const currentStep = [...displayedSteps].pop()
|
||||||
if (currentStep && isLogicStep(currentStep)) {
|
if (currentStep && isLogicStep(currentStep)) {
|
||||||
executeLogic(currentStep)
|
const target = executeLogic(currentStep)
|
||||||
displayNextStep()
|
target ? onBlockEnd(target) : displayNextStep()
|
||||||
}
|
}
|
||||||
}, [displayedSteps])
|
}, [displayedSteps])
|
||||||
|
|
||||||
@@ -65,33 +82,71 @@ export const ChatBlock = ({ stepIds, onBlockEnd }: ChatBlockProps) => {
|
|||||||
currentStep?.target?.blockId ||
|
currentStep?.target?.blockId ||
|
||||||
displayedSteps.length === stepIds.length
|
displayedSteps.length === stepIds.length
|
||||||
)
|
)
|
||||||
return onBlockEnd(currentStep?.target?.blockId)
|
return onBlockEnd(currentStep?.target)
|
||||||
}
|
}
|
||||||
const nextStep = typebot.steps.byId[stepIds[displayedSteps.length]]
|
const nextStep = typebot.steps.byId[stepIds[displayedSteps.length]]
|
||||||
if (nextStep) setDisplayedSteps([...displayedSteps, nextStep])
|
if (nextStep) setDisplayedSteps([...displayedSteps, nextStep])
|
||||||
}
|
}
|
||||||
|
|
||||||
const executeLogic = (step: LogicStep) => {
|
const executeLogic = (step: LogicStep): Target | undefined => {
|
||||||
if (!step.options?.variableId || !step.options.expressionToEvaluate) return
|
switch (step.type) {
|
||||||
const expression = step.options.expressionToEvaluate
|
case LogicStepType.SET_VARIABLE: {
|
||||||
const evaluatedExpression = isMathFormula(expression)
|
if (!step.options?.variableId || !step.options.expressionToEvaluate)
|
||||||
? evaluateExpression(parseVariables(expression, typebot.variables))
|
return
|
||||||
: expression
|
const expression = step.options.expressionToEvaluate
|
||||||
updateVariableValue(step.options.variableId, evaluatedExpression)
|
const evaluatedExpression = isMathFormula(expression)
|
||||||
|
? evaluateExpression(parseVariables(expression, typebot.variables))
|
||||||
|
: expression
|
||||||
|
updateVariableValue(step.options.variableId, evaluatedExpression)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case LogicStepType.CONDITION: {
|
||||||
|
const isConditionPassed =
|
||||||
|
step.options?.logicalOperator === LogicalOperator.AND
|
||||||
|
? step.options?.comparisons.allIds.every(executeComparison(step))
|
||||||
|
: step.options?.comparisons.allIds.some(executeComparison(step))
|
||||||
|
return isConditionPassed ? step.trueTarget : step.falseTarget
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const executeComparison = (step: ConditionStep) => (comparisonId: string) => {
|
||||||
|
const comparison = step.options?.comparisons.byId[comparisonId]
|
||||||
|
if (!comparison?.variableId) return false
|
||||||
|
const inputValue = typebot.variables.byId[comparison.variableId].value ?? ''
|
||||||
|
const { value } = comparison
|
||||||
|
if (!isDefined(value)) return false
|
||||||
|
switch (comparison.comparisonOperator) {
|
||||||
|
case ComparisonOperators.CONTAINS: {
|
||||||
|
return inputValue.includes(value)
|
||||||
|
}
|
||||||
|
case ComparisonOperators.EQUAL: {
|
||||||
|
return inputValue === value
|
||||||
|
}
|
||||||
|
case ComparisonOperators.NOT_EQUAL: {
|
||||||
|
return inputValue !== value
|
||||||
|
}
|
||||||
|
case ComparisonOperators.GREATER: {
|
||||||
|
return parseFloat(inputValue) >= parseFloat(value)
|
||||||
|
}
|
||||||
|
case ComparisonOperators.LESS: {
|
||||||
|
return parseFloat(inputValue) <= parseFloat(value)
|
||||||
|
}
|
||||||
|
case ComparisonOperators.IS_SET: {
|
||||||
|
return isDefined(inputValue) && inputValue.length > 0
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const getSingleChoiceTargetId = (
|
const getSingleChoiceTargetId = (
|
||||||
currentStep: ChoiceInputStep,
|
currentStep: ChoiceInputStep,
|
||||||
answerContent?: string
|
answerContent?: string
|
||||||
) => {
|
): Target | undefined => {
|
||||||
const itemId = currentStep.options.itemIds.find(
|
const itemId = currentStep.options.itemIds.find(
|
||||||
(itemId) => typebot.choiceItems.byId[itemId].content === answerContent
|
(itemId) => typebot.choiceItems.byId[itemId].content === answerContent
|
||||||
)
|
)
|
||||||
if (!itemId) throw new Error('itemId should exist')
|
if (!itemId) throw new Error('itemId should exist')
|
||||||
const targetId =
|
return typebot.choiceItems.byId[itemId].target ?? currentStep.target
|
||||||
typebot.choiceItems.byId[itemId].target?.blockId ??
|
|
||||||
currentStep.target?.blockId
|
|
||||||
return targetId
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -5,8 +5,7 @@ import { useFrame } from 'react-frame-component'
|
|||||||
import { setCssVariablesValue } from '../services/theme'
|
import { setCssVariablesValue } from '../services/theme'
|
||||||
import { useAnswers } from '../contexts/AnswersContext'
|
import { useAnswers } from '../contexts/AnswersContext'
|
||||||
import { deepEqual } from 'fast-equals'
|
import { deepEqual } from 'fast-equals'
|
||||||
import { Answer, Block, PublicTypebot } from 'models'
|
import { Answer, Block, PublicTypebot, Target } from 'models'
|
||||||
import { filterTable } from 'utils'
|
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
typebot: PublicTypebot
|
typebot: PublicTypebot
|
||||||
@@ -21,25 +20,29 @@ export const ConversationContainer = ({
|
|||||||
onCompleted,
|
onCompleted,
|
||||||
}: Props) => {
|
}: Props) => {
|
||||||
const { document: frameDocument } = useFrame()
|
const { document: frameDocument } = useFrame()
|
||||||
const [displayedBlocks, setDisplayedBlocks] = useState<Block[]>([])
|
const [displayedBlocks, setDisplayedBlocks] = useState<
|
||||||
|
{ block: Block; startStepId?: string }[]
|
||||||
|
>([])
|
||||||
const [localAnswer, setLocalAnswer] = useState<Answer | undefined>()
|
const [localAnswer, setLocalAnswer] = useState<Answer | undefined>()
|
||||||
const { answers } = useAnswers()
|
const { answers } = useAnswers()
|
||||||
const bottomAnchor = useRef<HTMLDivElement | null>(null)
|
const bottomAnchor = useRef<HTMLDivElement | null>(null)
|
||||||
|
|
||||||
const displayNextBlock = (blockId?: string) => {
|
const displayNextBlock = (target?: Target) => {
|
||||||
if (!blockId) return onCompleted()
|
if (!target) return onCompleted()
|
||||||
const nextBlock = typebot.blocks.byId[blockId]
|
const nextBlock = {
|
||||||
|
block: typebot.blocks.byId[target.blockId],
|
||||||
|
startStepId: target.stepId,
|
||||||
|
}
|
||||||
if (!nextBlock) return onCompleted()
|
if (!nextBlock) return onCompleted()
|
||||||
onNewBlockVisible(blockId)
|
onNewBlockVisible(target.blockId)
|
||||||
setDisplayedBlocks([...displayedBlocks, nextBlock])
|
setDisplayedBlocks([...displayedBlocks, nextBlock])
|
||||||
}
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const blocks = typebot.blocks
|
const blocks = typebot.blocks
|
||||||
const firstBlockId =
|
const firstTarget =
|
||||||
typebot.steps.byId[blocks.byId[blocks.allIds[0]].stepIds[0]].target
|
typebot.steps.byId[blocks.byId[blocks.allIds[0]].stepIds[0]].target
|
||||||
?.blockId
|
if (firstTarget) displayNextBlock(firstTarget)
|
||||||
if (firstBlockId) displayNextBlock(firstBlockId)
|
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -58,10 +61,11 @@ export const ConversationContainer = ({
|
|||||||
className="overflow-y-scroll w-full lg:w-3/4 min-h-full rounded lg:px-5 px-3 pt-10 relative scrollable-container typebot-chat-view"
|
className="overflow-y-scroll w-full lg:w-3/4 min-h-full rounded lg:px-5 px-3 pt-10 relative scrollable-container typebot-chat-view"
|
||||||
id="scrollable-container"
|
id="scrollable-container"
|
||||||
>
|
>
|
||||||
{displayedBlocks.map((block, idx) => (
|
{displayedBlocks.map((displayedBlock, idx) => (
|
||||||
<ChatBlock
|
<ChatBlock
|
||||||
key={block.id + idx}
|
key={displayedBlock.block.id + idx}
|
||||||
stepIds={block.stepIds}
|
stepIds={displayedBlock.block.stepIds}
|
||||||
|
startStepId={displayedBlock.startStepId}
|
||||||
onBlockEnd={displayNextBlock}
|
onBlockEnd={displayNextBlock}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
import { StepBase } from '.'
|
import { StepBase, Target } from '.'
|
||||||
|
import { Table } from '../..'
|
||||||
|
|
||||||
export type LogicStep = SetVariableStep
|
export type LogicStep = SetVariableStep | ConditionStep
|
||||||
|
|
||||||
export enum LogicStepType {
|
export enum LogicStepType {
|
||||||
SET_VARIABLE = 'Set variable',
|
SET_VARIABLE = 'Set variable',
|
||||||
|
CONDITION = 'Condition',
|
||||||
}
|
}
|
||||||
|
|
||||||
export type SetVariableStep = StepBase & {
|
export type SetVariableStep = StepBase & {
|
||||||
@@ -11,6 +13,39 @@ export type SetVariableStep = StepBase & {
|
|||||||
options?: SetVariableOptions
|
options?: SetVariableOptions
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export enum LogicalOperator {
|
||||||
|
OR = 'OR',
|
||||||
|
AND = 'AND',
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum ComparisonOperators {
|
||||||
|
EQUAL = 'Equal to',
|
||||||
|
NOT_EQUAL = 'Not equal',
|
||||||
|
CONTAINS = 'Contains',
|
||||||
|
GREATER = 'Greater than',
|
||||||
|
LESS = 'Less than',
|
||||||
|
IS_SET = 'Is set',
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ConditionStep = StepBase & {
|
||||||
|
type: LogicStepType.CONDITION
|
||||||
|
options: ConditionOptions
|
||||||
|
trueTarget?: Target
|
||||||
|
falseTarget?: Target
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ConditionOptions = {
|
||||||
|
comparisons: Table<Comparison>
|
||||||
|
logicalOperator?: LogicalOperator
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Comparison = {
|
||||||
|
id: string
|
||||||
|
variableId?: string
|
||||||
|
comparisonOperator: ComparisonOperators
|
||||||
|
value?: string
|
||||||
|
}
|
||||||
|
|
||||||
export type SetVariableOptions = {
|
export type SetVariableOptions = {
|
||||||
variableId?: string
|
variableId?: string
|
||||||
expressionToEvaluate?: string
|
expressionToEvaluate?: string
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import {
|
|||||||
BubbleStep,
|
BubbleStep,
|
||||||
BubbleStepType,
|
BubbleStepType,
|
||||||
ChoiceInputStep,
|
ChoiceInputStep,
|
||||||
|
ConditionStep,
|
||||||
InputStep,
|
InputStep,
|
||||||
InputStepType,
|
InputStepType,
|
||||||
LogicStep,
|
LogicStep,
|
||||||
@@ -36,9 +37,9 @@ export const sendRequest = async <ResponseData>({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const isDefined = <T>(value: T | undefined | null): value is T => {
|
export const isDefined = <T>(
|
||||||
return <T>value !== undefined && <T>value !== null
|
value: T | undefined | null
|
||||||
}
|
): value is NonNullable<T> => value !== undefined && value !== null
|
||||||
|
|
||||||
export const filterTable = <T>(ids: string[], table: Table<T>): Table<T> => ({
|
export const filterTable = <T>(ids: string[], table: Table<T>): Table<T> => ({
|
||||||
byId: ids.reduce((acc, id) => ({ ...acc, [id]: table.byId[id] }), {}),
|
byId: ids.reduce((acc, id) => ({ ...acc, [id]: table.byId[id] }), {}),
|
||||||
@@ -65,3 +66,6 @@ export const isChoiceInput = (step: Step): step is ChoiceInputStep =>
|
|||||||
|
|
||||||
export const isSingleChoiceInput = (step: Step): step is ChoiceInputStep =>
|
export const isSingleChoiceInput = (step: Step): step is ChoiceInputStep =>
|
||||||
step.type === InputStepType.CHOICE && !step.options.isMultipleChoice
|
step.type === InputStepType.CHOICE && !step.options.isMultipleChoice
|
||||||
|
|
||||||
|
export const isConditionStep = (step: Step): step is ConditionStep =>
|
||||||
|
step.type === LogicStepType.CONDITION
|
||||||
|
|||||||
Reference in New Issue
Block a user