Skip to content

Commit

Permalink
feat(engine): ✨ Improve variables in executed codes
Browse files Browse the repository at this point in the history
  • Loading branch information
baptisteArno committed Mar 31, 2022
1 parent 82f7bf0 commit db10f1e
Show file tree
Hide file tree
Showing 11 changed files with 155 additions and 60 deletions.
41 changes: 39 additions & 2 deletions apps/builder/components/shared/CodeEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Box, BoxProps } from '@chakra-ui/react'
import { Box, BoxProps, HStack } from '@chakra-ui/react'
import { EditorState, EditorView, basicSetup } from '@codemirror/basic-setup'
import { json, jsonParseLinter } from '@codemirror/lang-json'
import { css } from '@codemirror/lang-css'
Expand All @@ -7,6 +7,8 @@ import { html } from '@codemirror/lang-html'
import { useEffect, useRef, useState } from 'react'
import { useDebouncedCallback } from 'use-debounce'
import { linter } from '@codemirror/lint'
import { VariablesButton } from './buttons/VariablesButton'
import { Variable } from 'models'

const linterExtension = linter(jsonParseLinter())

Expand All @@ -15,19 +17,24 @@ type Props = {
lang?: 'css' | 'json' | 'js' | 'html'
isReadOnly?: boolean
debounceTimeout?: number
withVariableButton?: boolean
onChange?: (value: string) => void
}
export const CodeEditor = ({
value,
lang,
onChange,
withVariableButton = true,
isReadOnly = false,
debounceTimeout = 1000,
...props
}: Props & Omit<BoxProps, 'onChange'>) => {
const editorContainer = useRef<HTMLDivElement | null>(null)
const editorView = useRef<EditorView | null>(null)
const [, setPlainTextValue] = useState(value)
const [carretPosition, setCarretPosition] = useState<number>(0)
const isVariableButtonDisplayed = withVariableButton && !isReadOnly

const debounced = useDebouncedCallback(
(value) => {
setPlainTextValue(value)
Expand Down Expand Up @@ -101,5 +108,35 @@ export const CodeEditor = ({
return editor
}

return <Box ref={editorContainer} data-testid="code-editor" {...props} />
const handleVariableSelected = (variable?: Pick<Variable, 'id' | 'name'>) => {
editorView.current?.focus()
const insert = `{{${variable?.name}}}`
editorView.current?.dispatch({
changes: {
from: carretPosition,
insert,
},
selection: { anchor: carretPosition + insert.length },
})
}

const handleKeyUp = () => {
if (!editorContainer.current) return
setCarretPosition(editorView.current?.state.selection.main.from ?? 0)
}

return (
<HStack align="flex-end" spacing={0}>
<Box
w={isVariableButtonDisplayed ? 'calc(100% - 32px)' : '100%'}
ref={editorContainer}
data-testid="code-editor"
{...props}
onKeyUp={handleKeyUp}
/>
{isVariableButtonDisplayed && (
<VariablesButton onSelectVariable={handleVariableSelected} size="sm" />
)}
</HStack>
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ export const BlockNode = ({ block, blockIndex }: Props) => {
pointerEvents={isReadOnly || isStartBlock ? 'none' : 'auto'}
>
<EditablePreview
_hover={{ bgColor: 'gray.300' }}
_hover={{ bgColor: 'gray.200' }}
px="1"
userSelect={'none'}
/>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { FormLabel, Stack } from '@chakra-ui/react'
import { FormLabel, HStack, Stack, Switch, Text } from '@chakra-ui/react'
import { CodeEditor } from 'components/shared/CodeEditor'
import { Textarea } from 'components/shared/Textbox'
import { VariableSearchInput } from 'components/shared/VariableSearchInput'
import { SetVariableOptions, Variable } from 'models'
Expand All @@ -14,6 +15,11 @@ export const SetVariableSettings = ({ options, onOptionsChange }: Props) => {
onOptionsChange({ ...options, variableId: variable?.id })
const handleExpressionChange = (expressionToEvaluate: string) =>
onOptionsChange({ ...options, expressionToEvaluate })
const handleValueTypeChange = () =>
onOptionsChange({
...options,
isCode: options.isCode ? !options.isCode : true,
})

return (
<Stack spacing={4}>
Expand All @@ -28,14 +34,34 @@ export const SetVariableSettings = ({ options, onOptionsChange }: Props) => {
/>
</Stack>
<Stack>
<FormLabel mb="0" htmlFor="expression">
Value / Expression:
</FormLabel>
<Textarea
id="expression"
defaultValue={options.expressionToEvaluate ?? ''}
onChange={handleExpressionChange}
/>
<HStack justify="space-between">
<FormLabel mb="0" htmlFor="expression">
Value:
</FormLabel>
<HStack>
<Text fontSize="sm">Text</Text>
<Switch
size="sm"
isChecked={options.isCode ?? false}
onChange={handleValueTypeChange}
/>
<Text fontSize="sm">Code</Text>
</HStack>
</HStack>

{options.isCode ?? false ? (
<CodeEditor
value={options.expressionToEvaluate ?? ''}
onChange={handleExpressionChange}
lang="js"
/>
) : (
<Textarea
id="expression"
defaultValue={options.expressionToEvaluate ?? ''}
onChange={handleExpressionChange}
/>
)}
</Stack>
</Stack>
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ export const BlocksDropdown = ({
)

const handleBlockSelect = (title: string) => {
console.log(title)
const id = blocks?.find((b) => b.title === title)?.id
if (id) onBlockIdSelected(id)
}
Expand Down
31 changes: 2 additions & 29 deletions apps/builder/components/shared/Textbox/TextBox.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,13 @@
import {
ComponentWithAs,
Flex,
HStack,
IconButton,
InputProps,
Popover,
PopoverContent,
PopoverTrigger,
TextareaProps,
Tooltip,
} from '@chakra-ui/react'
import { UserIcon } from 'assets/icons'
import { Variable } from 'models'
import React, { ChangeEvent, useEffect, useRef, useState } from 'react'
import { useDebouncedCallback } from 'use-debounce'
import { VariableSearchInput } from '../VariableSearchInput'
import { VariablesButton } from '../buttons/VariablesButton'

export type TextBoxProps = {
onChange: (value: string) => void
Expand Down Expand Up @@ -120,27 +113,7 @@ export const TextBox = ({
bgColor={'white'}
{...props}
/>
<Popover matchWidth isLazy>
<PopoverTrigger>
<Flex>
<Tooltip label="Insert a variable">
<IconButton
aria-label="Insert a variable"
icon={<UserIcon />}
pos="relative"
/>
</Tooltip>
</Flex>
</PopoverTrigger>
<PopoverContent w="full">
<VariableSearchInput
onSelectVariable={handleVariableSelected}
placeholder="Search for a variable"
shadow="lg"
isDefaultOpen
/>
</PopoverContent>
</Popover>
<VariablesButton onSelectVariable={handleVariableSelected} />
</HStack>
)
}
46 changes: 46 additions & 0 deletions apps/builder/components/shared/buttons/VariablesButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import {
Popover,
PopoverTrigger,
Flex,
Tooltip,
IconButton,
PopoverContent,
IconButtonProps,
} from '@chakra-ui/react'
import { UserIcon } from 'assets/icons'
import { Variable } from 'models'
import React from 'react'
import { VariableSearchInput } from '../VariableSearchInput'

type Props = {
onSelectVariable: (
variable: Pick<Variable, 'name' | 'id'> | undefined
) => void
} & Omit<IconButtonProps, 'aria-label'>

export const VariablesButton = ({ onSelectVariable, ...props }: Props) => {
return (
<Popover matchWidth isLazy>
<PopoverTrigger>
<Flex>
<Tooltip label="Insert a variable">
<IconButton
aria-label={'Insert a variable'}
icon={<UserIcon />}
pos="relative"
{...props}
/>
</Tooltip>
</Flex>
</PopoverTrigger>
<PopoverContent w="full">
<VariableSearchInput
onSelectVariable={onSelectVariable}
placeholder="Search for a variable"
shadow="lg"
isDefaultOpen
/>
</PopoverContent>
</Popover>
)
}
8 changes: 4 additions & 4 deletions apps/builder/public/bots/onboarding.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@
"blockId": "cl1267q1z000d2e6d949f2ge4",
"options": {
"name": "Store Name in DB",
"content": "postMessage({from: \"typebot\", action: \"storeName\", content: \"{{Name}}\"}, \"*\")"
"content": "postMessage({from: \"typebot\", action: \"storeName\", content: {{Name}}}, \"*\")"
},
"outgoingEdgeId": "cl12bk56s000d2e69oll3nqxm"
}
Expand Down Expand Up @@ -239,7 +239,7 @@
"blockId": "cl126jioj000u2e6dqssno3hv",
"options": {
"name": "Store company in DB",
"content": "postMessage({from: \"typebot\", action: \"storeCompany\", content: \"{{Company}}\"}, \"*\")"
"content": "postMessage({from: \"typebot\", action: \"storeCompany\", content: {{Company}}}, \"*\")"
},
"outgoingEdgeId": "cl128ag8i00162e6dufv3tgo0"
}
Expand Down Expand Up @@ -335,7 +335,7 @@
"blockId": "cl126krbp00102e6dnjelmfa1",
"options": {
"name": "Store categories in DB",
"content": "postMessage({from: \"typebot\", action: \"storeCategories\", content: \"{{Categories}}\"}, \"*\")"
"content": "postMessage({from: \"typebot\", action: \"storeCategories\", content: {{Categories}}}, \"*\")"
},
"outgoingEdgeId": "cl128azam00182e6dct61k7v5"
}
Expand Down Expand Up @@ -458,7 +458,7 @@
"blockId": "cl126pv6w001n2e6dp0qkvthu",
"options": {
"name": "Store Other categories in DB",
"content": "postMessage({from: \"typebot\", action: \"storeOtherCategories\", content: \"{{Other categories}}\"}, \"*\")"
"content": "postMessage({from: \"typebot\", action: \"storeOtherCategories\", content: {{Other categories}}}, \"*\")"
},
"outgoingEdgeId": "cl128c0fu001a2e6droq69g6z"
}
Expand Down
5 changes: 2 additions & 3 deletions packages/bot-engine/src/services/integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,9 +247,8 @@ const executeWebhook = async (
if (!varMapping?.bodyPath || !varMapping.variableId) return newVariables
const existingVariable = variables.find(byId(varMapping.variableId))
if (!existingVariable) return newVariables
const value = Function(
`return (${JSON.stringify(data)}).${varMapping?.bodyPath}`
)()
const func = Function('data', `return data.${varMapping?.bodyPath}`)
const value = func(JSON.stringify(data))
updateVariableValue(existingVariable?.id, value)
return [...newVariables, { ...existingVariable, value }]
}, [])
Expand Down
11 changes: 7 additions & 4 deletions packages/bot-engine/src/services/logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,8 @@ const executeSetVariable = (
): EdgeId | undefined => {
if (!step.options?.variableId || !step.options.expressionToEvaluate)
return step.outgoingEdgeId
const expression = step.options.expressionToEvaluate
const evaluatedExpression = evaluateExpression(
parseVariables(variables)(expression)
const evaluatedExpression = evaluateExpression(variables)(
step.options.expressionToEvaluate
)
const existingVariable = variables.find(byId(step.options.variableId))
if (!existingVariable) return step.outgoingEdgeId
Expand Down Expand Up @@ -132,7 +131,11 @@ const executeCode = async (
{ typebot: { variables } }: LogicContext
) => {
if (!step.options.content) return
await Function(parseVariables(variables)(step.options.content))()
const func = Function(
...variables.map((v) => v.id),
parseVariables(variables, { fieldToParse: 'id' })(step.options.content)
)
await func(...variables.map((v) => v.value))
return step.outgoingEdgeId
}

Expand Down
25 changes: 18 additions & 7 deletions packages/bot-engine/src/services/variable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,33 @@ export const stringContainsVariable = (str: string): boolean =>
/\{\{(.*?)\}\}/g.test(str)

export const parseVariables =
(variables: Variable[]) =>
(text?: string): string => {
(
variables: Variable[],
options: { fieldToParse: 'value' | 'id' } = { fieldToParse: 'value' }
) =>
(text: string | undefined): string => {
if (!text || text === '') return ''
return text.replace(/\{\{(.*?)\}\}/g, (_, fullVariableString) => {
const matchedVarName = fullVariableString.replace(/{{|}}/g, '')
const variable = variables.find((v) => {
return matchedVarName === v.name && isDefined(v.value)
})
if (!variable) return ''
return (
variables.find((v) => {
return matchedVarName === v.name && isDefined(v.value)
})?.value ?? ''
(options.fieldToParse === 'value' ? variable.value : variable.id) || ''
)
})
}

export const evaluateExpression = (str: string) => {
export const evaluateExpression = (variables: Variable[]) => (str: string) => {
try {
const evaluatedResult = Function('return ' + str)()
const func = Function(
...variables.map((v) => v.id),
parseVariables(variables, { fieldToParse: 'id' })(
str.includes('return ') ? str : `return ${str}`
)
)
const evaluatedResult = func(...variables.map((v) => v.value))
return isNotDefined(evaluatedResult) ? '' : evaluatedResult.toString()
} catch (err) {
console.log(err)
Expand Down
1 change: 1 addition & 0 deletions packages/models/src/typebot/steps/logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ export type Comparison = {
export type SetVariableOptions = {
variableId?: string
expressionToEvaluate?: string
isCode?: boolean
}

export type RedirectOptions = {
Expand Down

3 comments on commit db10f1e

@vercel
Copy link

@vercel vercel bot commented on db10f1e Mar 31, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vercel
Copy link

@vercel vercel bot commented on db10f1e Mar 31, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vercel
Copy link

@vercel vercel bot commented on db10f1e Mar 31, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

builder-v2 – ./apps/builder

builder-v2-git-main-typebot-io.vercel.app
builder-v2-typebot-io.vercel.app
app.typebot.io

Please sign in to comment.