♻️ (bot) Change to features-centric folder structure
This commit is contained in:
committed by
Baptiste Arnaud
parent
a5c8a8a95c
commit
972094425a
@@ -0,0 +1,77 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { EmbedBubbleBlock } from 'models'
|
||||
import { TypingBubble } from '../../../../../components/TypingBubble'
|
||||
import { parseVariables } from '@/features/variables'
|
||||
import { useTypebot } from '@/providers/TypebotProvider'
|
||||
|
||||
type Props = {
|
||||
block: EmbedBubbleBlock
|
||||
onTransitionEnd: () => void
|
||||
}
|
||||
|
||||
export const showAnimationDuration = 400
|
||||
|
||||
export const EmbedBubble = ({ block, onTransitionEnd }: Props) => {
|
||||
const { typebot, isLoading } = useTypebot()
|
||||
const messageContainer = useRef<HTMLDivElement | null>(null)
|
||||
const [isTyping, setIsTyping] = useState(true)
|
||||
|
||||
const url = useMemo(
|
||||
() => parseVariables(typebot.variables)(block.content?.url),
|
||||
[block.content?.url, typebot.variables]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!isTyping || isLoading) return
|
||||
showContentAfterMediaLoad()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isLoading])
|
||||
|
||||
const showContentAfterMediaLoad = () => {
|
||||
setTimeout(() => {
|
||||
setIsTyping(false)
|
||||
onTypingEnd()
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
const onTypingEnd = () => {
|
||||
setIsTyping(false)
|
||||
setTimeout(() => {
|
||||
onTransitionEnd()
|
||||
}, showAnimationDuration)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full" ref={messageContainer}>
|
||||
<div className="flex mb-2 w-full lg:w-11/12 items-center">
|
||||
<div
|
||||
className={
|
||||
'flex relative z-10 items-start typebot-host-bubble w-full'
|
||||
}
|
||||
>
|
||||
<div
|
||||
className="flex items-center absolute px-4 py-2 rounded-lg bubble-typing z-10 "
|
||||
style={{
|
||||
width: isTyping ? '4rem' : '100%',
|
||||
height: isTyping ? '2rem' : '100%',
|
||||
}}
|
||||
>
|
||||
{isTyping ? <TypingBubble /> : <></>}
|
||||
</div>
|
||||
<iframe
|
||||
id="embed-bubble-content"
|
||||
src={url}
|
||||
className={
|
||||
'w-full z-20 p-4 content-opacity ' +
|
||||
(isTyping ? 'opacity-0' : 'opacity-100')
|
||||
}
|
||||
style={{
|
||||
height: isTyping ? '2rem' : block.content.height,
|
||||
borderRadius: '15px',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { EmbedBubble } from './components/EmbedBubble'
|
||||
@@ -0,0 +1,84 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useTypebot } from '@/providers/TypebotProvider'
|
||||
import { ImageBubbleBlock } from 'models'
|
||||
import { TypingBubble } from '@/components/TypingBubble'
|
||||
import { parseVariables } from '@/features/variables'
|
||||
|
||||
type Props = {
|
||||
block: ImageBubbleBlock
|
||||
onTransitionEnd: () => void
|
||||
}
|
||||
|
||||
export const showAnimationDuration = 400
|
||||
|
||||
export const mediaLoadingFallbackTimeout = 5000
|
||||
|
||||
export const ImageBubble = ({ block, onTransitionEnd }: Props) => {
|
||||
const { typebot, isLoading } = useTypebot()
|
||||
const messageContainer = useRef<HTMLDivElement | null>(null)
|
||||
const image = useRef<HTMLImageElement | null>(null)
|
||||
const [isTyping, setIsTyping] = useState(true)
|
||||
|
||||
const url = useMemo(
|
||||
() => parseVariables(typebot.variables)(block.content?.url),
|
||||
[block.content?.url, typebot.variables]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!isTyping || isLoading) return
|
||||
showContentAfterMediaLoad()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isLoading])
|
||||
|
||||
const showContentAfterMediaLoad = () => {
|
||||
if (!image.current) return
|
||||
const timeout = setTimeout(() => {
|
||||
setIsTyping(false)
|
||||
onTypingEnd()
|
||||
}, mediaLoadingFallbackTimeout)
|
||||
image.current.onload = () => {
|
||||
clearTimeout(timeout)
|
||||
setIsTyping(false)
|
||||
onTypingEnd()
|
||||
}
|
||||
}
|
||||
|
||||
const onTypingEnd = () => {
|
||||
setIsTyping(false)
|
||||
setTimeout(() => {
|
||||
onTransitionEnd()
|
||||
}, showAnimationDuration)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col" ref={messageContainer}>
|
||||
<div className="flex mb-2 w-full lg:w-11/12 items-center">
|
||||
<div className={'flex relative z-10 items-start typebot-host-bubble'}>
|
||||
<div
|
||||
className="flex items-center absolute px-4 py-2 rounded-lg bubble-typing z-10 "
|
||||
style={{
|
||||
width: isTyping ? '4rem' : '100%',
|
||||
height: isTyping ? '2rem' : '100%',
|
||||
}}
|
||||
>
|
||||
{isTyping ? <TypingBubble /> : null}
|
||||
</div>
|
||||
<img
|
||||
ref={image}
|
||||
src={url}
|
||||
className={
|
||||
'p-4 content-opacity z-10 w-auto rounded-lg ' +
|
||||
(isTyping ? 'opacity-0' : 'opacity-100')
|
||||
}
|
||||
style={{
|
||||
maxHeight: '32rem',
|
||||
height: isTyping ? '2rem' : 'auto',
|
||||
maxWidth: '100%',
|
||||
}}
|
||||
alt="Bubble image"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { ImageBubble } from './components/ImageBubble'
|
||||
@@ -0,0 +1,81 @@
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { useTypebot } from '@/providers/TypebotProvider'
|
||||
import { BubbleBlockType, TextBubbleBlock } from 'models'
|
||||
import { computeTypingDuration } from '../utils/computeTypingDuration'
|
||||
import { parseVariables } from '@/features/variables'
|
||||
import { TypingBubble } from '@/components/TypingBubble'
|
||||
|
||||
type Props = {
|
||||
block: TextBubbleBlock
|
||||
onTransitionEnd: () => void
|
||||
}
|
||||
|
||||
export const showAnimationDuration = 400
|
||||
|
||||
const defaultTypingEmulation = {
|
||||
enabled: true,
|
||||
speed: 300,
|
||||
maxDelay: 1.5,
|
||||
}
|
||||
|
||||
export const TextBubble = ({ block, onTransitionEnd }: Props) => {
|
||||
const { typebot, isLoading } = useTypebot()
|
||||
const messageContainer = useRef<HTMLDivElement | null>(null)
|
||||
const [isTyping, setIsTyping] = useState(true)
|
||||
|
||||
const [content] = useState(
|
||||
parseVariables(typebot.variables)(block.content.html)
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!isTyping || isLoading) return
|
||||
const typingTimeout = computeTypingDuration(
|
||||
block.content.plainText,
|
||||
typebot.settings?.typingEmulation ?? defaultTypingEmulation
|
||||
)
|
||||
setTimeout(() => {
|
||||
onTypingEnd()
|
||||
}, typingTimeout)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isLoading])
|
||||
|
||||
const onTypingEnd = () => {
|
||||
setIsTyping(false)
|
||||
setTimeout(() => {
|
||||
onTransitionEnd()
|
||||
}, showAnimationDuration)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col" ref={messageContainer}>
|
||||
<div className="flex mb-2 w-full items-center">
|
||||
<div className={'flex relative items-start typebot-host-bubble'}>
|
||||
<div
|
||||
className="flex items-center absolute px-4 py-2 rounded-lg bubble-typing "
|
||||
style={{
|
||||
width: isTyping ? '4rem' : '100%',
|
||||
height: isTyping ? '2rem' : '100%',
|
||||
}}
|
||||
data-testid="host-bubble"
|
||||
>
|
||||
{isTyping ? <TypingBubble /> : null}
|
||||
</div>
|
||||
{block.type === BubbleBlockType.TEXT && (
|
||||
<p
|
||||
style={{
|
||||
textOverflow: 'ellipsis',
|
||||
}}
|
||||
className={
|
||||
'overflow-hidden content-opacity mx-4 my-2 whitespace-pre-wrap slate-html-container relative ' +
|
||||
(isTyping ? 'opacity-0 h-6' : 'opacity-100 h-full')
|
||||
}
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: content,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { TextBubble } from './components/TextBubble'
|
||||
@@ -0,0 +1,16 @@
|
||||
import { TypingEmulation } from 'models'
|
||||
|
||||
export const computeTypingDuration = (
|
||||
bubbleContent: string,
|
||||
typingSettings: TypingEmulation
|
||||
) => {
|
||||
let wordCount = bubbleContent.match(/(\w+)/g)?.length ?? 0
|
||||
if (wordCount === 0) wordCount = bubbleContent.length
|
||||
const typedWordsPerMinute = typingSettings.speed
|
||||
let typingTimeout = typingSettings.enabled
|
||||
? (wordCount / typedWordsPerMinute) * 60000
|
||||
: 0
|
||||
if (typingTimeout > typingSettings.maxDelay * 1000)
|
||||
typingTimeout = typingSettings.maxDelay * 1000
|
||||
return typingTimeout
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useTypebot } from '@/providers/TypebotProvider'
|
||||
import {
|
||||
Variable,
|
||||
VideoBubbleContent,
|
||||
VideoBubbleContentType,
|
||||
VideoBubbleBlock,
|
||||
} from 'models'
|
||||
import { TypingBubble } from '@/components/TypingBubble'
|
||||
import { parseVariables } from '@/features/variables'
|
||||
|
||||
type Props = {
|
||||
block: VideoBubbleBlock
|
||||
onTransitionEnd: () => void
|
||||
}
|
||||
|
||||
export const showAnimationDuration = 400
|
||||
|
||||
export const mediaLoadingFallbackTimeout = 5000
|
||||
|
||||
export const VideoBubble = ({ block, onTransitionEnd }: Props) => {
|
||||
const { typebot, isLoading } = useTypebot()
|
||||
const messageContainer = useRef<HTMLDivElement | null>(null)
|
||||
const [isTyping, setIsTyping] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
if (!isTyping || isLoading) return
|
||||
showContentAfterMediaLoad()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [isLoading])
|
||||
|
||||
const showContentAfterMediaLoad = () => {
|
||||
setTimeout(() => {
|
||||
setIsTyping(false)
|
||||
onTypingEnd()
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
const onTypingEnd = () => {
|
||||
setIsTyping(false)
|
||||
setTimeout(() => {
|
||||
onTransitionEnd()
|
||||
}, showAnimationDuration)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col" ref={messageContainer}>
|
||||
<div className="flex mb-2 w-full lg:w-11/12 items-center">
|
||||
<div className={'flex relative z-10 items-start typebot-host-bubble'}>
|
||||
<div
|
||||
className="flex items-center absolute px-4 py-2 rounded-lg bubble-typing z-10 "
|
||||
style={{
|
||||
width: isTyping ? '4rem' : '100%',
|
||||
height: isTyping ? '2rem' : '100%',
|
||||
}}
|
||||
>
|
||||
{isTyping ? <TypingBubble /> : <></>}
|
||||
</div>
|
||||
<VideoContent
|
||||
content={block.content}
|
||||
isTyping={isTyping}
|
||||
variables={typebot.variables}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const VideoContent = ({
|
||||
content,
|
||||
isTyping,
|
||||
variables,
|
||||
}: {
|
||||
content?: VideoBubbleContent
|
||||
isTyping: boolean
|
||||
variables: Variable[]
|
||||
}) => {
|
||||
const url = useMemo(
|
||||
() => parseVariables(variables)(content?.url),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[variables]
|
||||
)
|
||||
if (!content?.type) return <></>
|
||||
switch (content.type) {
|
||||
case VideoBubbleContentType.URL:
|
||||
const isSafariBrowser = window.navigator.vendor.match(/apple/i)
|
||||
return (
|
||||
<video
|
||||
controls
|
||||
className={
|
||||
'p-4 focus:outline-none w-full z-10 content-opacity rounded-md ' +
|
||||
(isTyping ? 'opacity-0' : 'opacity-100')
|
||||
}
|
||||
style={{
|
||||
height: isTyping ? '2rem' : 'auto',
|
||||
maxHeight: isSafariBrowser ? '40vh' : '',
|
||||
}}
|
||||
autoPlay
|
||||
>
|
||||
<source src={url} type="video/mp4" />
|
||||
Sorry, your browser doesn't support embedded videos.
|
||||
</video>
|
||||
)
|
||||
case VideoBubbleContentType.VIMEO:
|
||||
case VideoBubbleContentType.YOUTUBE: {
|
||||
const baseUrl =
|
||||
content.type === VideoBubbleContentType.VIMEO
|
||||
? 'https://player.vimeo.com/video'
|
||||
: 'https://www.youtube.com/embed'
|
||||
return (
|
||||
<iframe
|
||||
src={`${baseUrl}/${content.id}`}
|
||||
className={
|
||||
'w-full p-4 content-opacity z-10 rounded-md ' +
|
||||
(isTyping ? 'opacity-0' : 'opacity-100')
|
||||
}
|
||||
height={isTyping ? '2rem' : '200px'}
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
||||
allowFullScreen
|
||||
/>
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { VideoBubble } from './components/VideoBubble'
|
||||
@@ -0,0 +1,94 @@
|
||||
import { parseVariables } from '@/features/variables'
|
||||
import { useAnswers } from '@/providers/AnswersProvider'
|
||||
import { useTypebot } from '@/providers/TypebotProvider'
|
||||
import { InputSubmitContent } from '@/types'
|
||||
import { ChoiceInputBlock } from 'models'
|
||||
import React, { useState } from 'react'
|
||||
import { SendButton } from '../../../../../components/SendButton'
|
||||
|
||||
type ChoiceFormProps = {
|
||||
block: ChoiceInputBlock
|
||||
onSubmit: (value: InputSubmitContent) => void
|
||||
}
|
||||
|
||||
export const ChoiceForm = ({ block, onSubmit }: ChoiceFormProps) => {
|
||||
const {
|
||||
typebot: { variables },
|
||||
} = useTypebot()
|
||||
const { resultValues } = useAnswers()
|
||||
const [selectedIndices, setSelectedIndices] = useState<number[]>([])
|
||||
|
||||
const handleClick = (itemIndex: number) => (e: React.MouseEvent) => {
|
||||
e.preventDefault()
|
||||
if (block.options?.isMultipleChoice) toggleSelectedItemIndex(itemIndex)
|
||||
else
|
||||
onSubmit({
|
||||
value: parseVariables(variables)(block.items[itemIndex].content),
|
||||
itemId: block.items[itemIndex].id,
|
||||
})
|
||||
}
|
||||
|
||||
const toggleSelectedItemIndex = (itemIndex: number) => {
|
||||
const existingIndex = selectedIndices.indexOf(itemIndex)
|
||||
if (existingIndex !== -1) {
|
||||
selectedIndices.splice(existingIndex, 1)
|
||||
setSelectedIndices([...selectedIndices])
|
||||
} else {
|
||||
setSelectedIndices([...selectedIndices, itemIndex])
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = () =>
|
||||
onSubmit({
|
||||
value: selectedIndices
|
||||
.map((itemIndex) =>
|
||||
parseVariables(variables)(block.items[itemIndex].content)
|
||||
)
|
||||
.join(', '),
|
||||
})
|
||||
|
||||
const isUniqueFirstButton =
|
||||
resultValues &&
|
||||
resultValues.answers.length === 0 &&
|
||||
block.items.length === 1
|
||||
|
||||
return (
|
||||
<form className="flex flex-col items-end" onSubmit={handleSubmit}>
|
||||
<div className="flex flex-wrap justify-end">
|
||||
{block.items.map((item, idx) => (
|
||||
<span key={item.id} className="relative inline-flex ml-2 mb-2">
|
||||
<button
|
||||
role={block.options?.isMultipleChoice ? 'checkbox' : 'button'}
|
||||
onClick={handleClick(idx)}
|
||||
className={
|
||||
'py-2 px-4 text-left font-semibold rounded-md transition-all filter hover:brightness-90 active:brightness-75 duration-100 focus:outline-none typebot-button ' +
|
||||
(selectedIndices.includes(idx) ||
|
||||
!block.options?.isMultipleChoice
|
||||
? ''
|
||||
: 'selectable')
|
||||
}
|
||||
data-testid="button"
|
||||
data-itemid={item.id}
|
||||
>
|
||||
{parseVariables(variables)(item.content)}
|
||||
</button>
|
||||
{isUniqueFirstButton && (
|
||||
<span className="flex h-3 w-3 absolute top-0 right-0 -mt-1 -mr-1 ping">
|
||||
<span className="animate-ping absolute inline-flex h-full w-full rounded-full brightness-225 opacity-75" />
|
||||
<span className="relative inline-flex rounded-full h-3 w-3 brightness-200" />
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex">
|
||||
{selectedIndices.length > 0 && (
|
||||
<SendButton
|
||||
label={block.options?.buttonLabel ?? 'Send'}
|
||||
disableIcon
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { ChoiceForm } from './components/ChoiceForm'
|
||||
@@ -0,0 +1,86 @@
|
||||
import { SendButton } from '@/components/SendButton'
|
||||
import { InputSubmitContent } from '@/types'
|
||||
import { DateInputOptions } from 'models'
|
||||
import React, { useState } from 'react'
|
||||
import { parseReadableDate } from '../utils/parseReadableDate'
|
||||
|
||||
type DateInputProps = {
|
||||
onSubmit: (inputValue: InputSubmitContent) => void
|
||||
options?: DateInputOptions
|
||||
}
|
||||
|
||||
export const DateForm = ({
|
||||
onSubmit,
|
||||
options,
|
||||
}: DateInputProps): JSX.Element => {
|
||||
const { hasTime, isRange, labels } = options ?? {}
|
||||
const [inputValues, setInputValues] = useState({ from: '', to: '' })
|
||||
return (
|
||||
<div className="flex flex-col w-full lg:w-4/6">
|
||||
<div className="flex items-center">
|
||||
<form
|
||||
className={
|
||||
'flex justify-between rounded-lg typebot-input pr-2 items-end'
|
||||
}
|
||||
onSubmit={(e) => {
|
||||
if (inputValues.from === '' && inputValues.to === '') return
|
||||
e.preventDefault()
|
||||
onSubmit({
|
||||
value: `${inputValues.from}${
|
||||
isRange ? ` to ${inputValues.to}` : ''
|
||||
}`,
|
||||
label: parseReadableDate({ ...inputValues, hasTime, isRange }),
|
||||
})
|
||||
}}
|
||||
>
|
||||
<div className="flex flex-col">
|
||||
<div className={'flex items-center p-4 ' + (isRange ? 'pb-0' : '')}>
|
||||
{isRange && (
|
||||
<p className="font-semibold mr-2">{labels?.from ?? 'From:'}</p>
|
||||
)}
|
||||
<input
|
||||
className="focus:outline-none flex-1 w-full text-input"
|
||||
style={{
|
||||
minHeight: '2rem',
|
||||
minWidth: '100px',
|
||||
fontSize: '16px',
|
||||
}}
|
||||
type={hasTime ? 'datetime-local' : 'date'}
|
||||
onChange={(e) =>
|
||||
setInputValues({ ...inputValues, from: e.target.value })
|
||||
}
|
||||
data-testid="from-date"
|
||||
/>
|
||||
</div>
|
||||
{isRange && (
|
||||
<div className="flex items-center p-4">
|
||||
{isRange && (
|
||||
<p className="font-semibold">{labels?.to ?? 'To:'}</p>
|
||||
)}
|
||||
<input
|
||||
className="focus:outline-none flex-1 w-full text-input ml-2"
|
||||
style={{
|
||||
minHeight: '2rem',
|
||||
minWidth: '100px',
|
||||
fontSize: '16px',
|
||||
}}
|
||||
type={hasTime ? 'datetime-local' : 'date'}
|
||||
onChange={(e) =>
|
||||
setInputValues({ ...inputValues, to: e.target.value })
|
||||
}
|
||||
data-testid="to-date"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<SendButton
|
||||
label={labels?.button ?? 'Send'}
|
||||
isDisabled={inputValues.to === '' && inputValues.from === ''}
|
||||
className="my-2 ml-2"
|
||||
/>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { DateForm } from './components/DateForm'
|
||||
export { parseReadableDate } from './utils/parseReadableDate'
|
||||
@@ -0,0 +1,26 @@
|
||||
export const parseReadableDate = ({
|
||||
from,
|
||||
to,
|
||||
hasTime,
|
||||
isRange,
|
||||
}: {
|
||||
from: string
|
||||
to: string
|
||||
hasTime?: boolean
|
||||
isRange?: boolean
|
||||
}) => {
|
||||
const currentLocale = window.navigator.language
|
||||
const formatOptions: Intl.DateTimeFormatOptions = {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
hour: hasTime ? '2-digit' : undefined,
|
||||
minute: hasTime ? '2-digit' : undefined,
|
||||
}
|
||||
const fromReadable = new Date(from).toLocaleString(
|
||||
currentLocale,
|
||||
formatOptions
|
||||
)
|
||||
const toReadable = new Date(to).toLocaleString(currentLocale, formatOptions)
|
||||
return `${fromReadable}${isRange ? ` to ${toReadable}` : ''}`
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { ShortTextInput } from '@/components/inputs/ShortTextInput'
|
||||
import { SendButton } from '@/components/SendButton'
|
||||
import { InputSubmitContent } from '@/types'
|
||||
import { EmailInputBlock } from 'models'
|
||||
import React, { MutableRefObject, useRef, useState } from 'react'
|
||||
|
||||
type EmailInputProps = {
|
||||
block: EmailInputBlock
|
||||
onSubmit: (value: InputSubmitContent) => void
|
||||
defaultValue?: string
|
||||
hasGuestAvatar: boolean
|
||||
}
|
||||
|
||||
export const EmailInput = ({
|
||||
block,
|
||||
onSubmit,
|
||||
defaultValue,
|
||||
hasGuestAvatar,
|
||||
}: EmailInputProps) => {
|
||||
const [inputValue, setInputValue] = useState(defaultValue ?? '')
|
||||
const inputRef = useRef<HTMLInputElement | HTMLTextAreaElement | null>(null)
|
||||
|
||||
const handleChange = (inputValue: string) => setInputValue(inputValue)
|
||||
|
||||
const checkIfInputIsValid = () =>
|
||||
inputValue !== '' && inputRef.current?.reportValidity()
|
||||
|
||||
const submit = () => {
|
||||
if (checkIfInputIsValid()) onSubmit({ value: inputValue })
|
||||
}
|
||||
|
||||
const submitWhenEnter = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') submit()
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={
|
||||
'flex items-end justify-between rounded-lg pr-2 typebot-input w-full'
|
||||
}
|
||||
data-testid="input"
|
||||
style={{
|
||||
marginRight: hasGuestAvatar ? '50px' : '0.5rem',
|
||||
maxWidth: '350px',
|
||||
}}
|
||||
onKeyDown={submitWhenEnter}
|
||||
>
|
||||
<ShortTextInput
|
||||
ref={inputRef as MutableRefObject<HTMLInputElement>}
|
||||
value={inputValue}
|
||||
placeholder={block.options?.labels?.placeholder ?? 'Type your email...'}
|
||||
onChange={handleChange}
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
/>
|
||||
<SendButton
|
||||
type="button"
|
||||
label={block.options?.labels?.button ?? 'Send'}
|
||||
isDisabled={inputValue === ''}
|
||||
className="my-2 ml-2"
|
||||
onClick={submit}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { EmailInput } from './components/EmailInput'
|
||||
export { validateEmail } from './utils/validateEmail'
|
||||
@@ -0,0 +1,4 @@
|
||||
const emailRegex =
|
||||
/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
|
||||
|
||||
export const validateEmail = (email: string) => emailRegex.test(email)
|
||||
@@ -0,0 +1,256 @@
|
||||
import { Spinner, SendButton } from '@/components/SendButton'
|
||||
import { useAnswers } from '@/providers/AnswersProvider'
|
||||
import { useTypebot } from '@/providers/TypebotProvider'
|
||||
import { InputSubmitContent } from '@/types'
|
||||
import { FileInputBlock } from 'models'
|
||||
import React, { ChangeEvent, FormEvent, useState, DragEvent } from 'react'
|
||||
import { uploadFiles } from 'utils'
|
||||
|
||||
type Props = {
|
||||
block: FileInputBlock
|
||||
onSubmit: (url: InputSubmitContent) => void
|
||||
onSkip: () => void
|
||||
}
|
||||
|
||||
export const FileUploadForm = ({
|
||||
block: {
|
||||
id,
|
||||
options: { isMultipleAllowed, labels, sizeLimit, isRequired },
|
||||
},
|
||||
onSubmit,
|
||||
onSkip,
|
||||
}: Props) => {
|
||||
const { isPreview, currentTypebotId } = useTypebot()
|
||||
const { resultId } = useAnswers()
|
||||
const [selectedFiles, setSelectedFiles] = useState<File[]>([])
|
||||
const [isUploading, setIsUploading] = useState(false)
|
||||
const [uploadProgressPercent, setUploadProgressPercent] = useState(0)
|
||||
const [isDraggingOver, setIsDraggingOver] = useState(false)
|
||||
const [errorMessage, setErrorMessage] = useState<string>()
|
||||
|
||||
const handleFileChange = async (e: ChangeEvent<HTMLInputElement>) => {
|
||||
if (!e.target.files) return
|
||||
onNewFiles(e.target.files)
|
||||
}
|
||||
|
||||
const onNewFiles = (files: FileList) => {
|
||||
setErrorMessage(undefined)
|
||||
const newFiles = Array.from(files)
|
||||
if (newFiles.some((file) => file.size > (sizeLimit ?? 10) * 1024 * 1024))
|
||||
return setErrorMessage(`A file is larger than ${sizeLimit ?? 10}MB`)
|
||||
if (!isMultipleAllowed && files) return startSingleFileUpload(newFiles[0])
|
||||
setSelectedFiles([...selectedFiles, ...newFiles])
|
||||
}
|
||||
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (selectedFiles.length === 0) return
|
||||
startFilesUpload(selectedFiles)
|
||||
}
|
||||
|
||||
const startSingleFileUpload = async (file: File) => {
|
||||
if (isPreview)
|
||||
return onSubmit({
|
||||
label: `File uploaded`,
|
||||
value: 'http://fake-upload-url.com',
|
||||
})
|
||||
setIsUploading(true)
|
||||
const urls = await uploadFiles({
|
||||
basePath: `/api/typebots/${currentTypebotId}/blocks/${id}`,
|
||||
files: [
|
||||
{
|
||||
file,
|
||||
path: `public/results/${resultId}/${id}/${file.name}`,
|
||||
},
|
||||
],
|
||||
})
|
||||
setIsUploading(false)
|
||||
if (urls.length)
|
||||
return onSubmit({ label: `File uploaded`, value: urls[0] ?? '' })
|
||||
setErrorMessage('An error occured while uploading the file')
|
||||
}
|
||||
const startFilesUpload = async (files: File[]) => {
|
||||
if (isPreview)
|
||||
return onSubmit({
|
||||
label: `${files.length} file${files.length > 1 ? 's' : ''} uploaded`,
|
||||
value: files
|
||||
.map((_, idx) => `http://fake-upload-url.com/${idx}`)
|
||||
.join(', '),
|
||||
})
|
||||
setIsUploading(true)
|
||||
const urls = await uploadFiles({
|
||||
basePath: `/api/typebots/${currentTypebotId}/blocks/${id}`,
|
||||
files: files.map((file) => ({
|
||||
file: file,
|
||||
path: `public/results/${resultId}/${id}/${file.name}`,
|
||||
})),
|
||||
onUploadProgress: setUploadProgressPercent,
|
||||
})
|
||||
setIsUploading(false)
|
||||
setUploadProgressPercent(0)
|
||||
if (urls.length !== files.length)
|
||||
return setErrorMessage('An error occured while uploading the files')
|
||||
onSubmit({
|
||||
label: `${urls.length} file${urls.length > 1 ? 's' : ''} uploaded`,
|
||||
value: urls.join(', '),
|
||||
})
|
||||
}
|
||||
|
||||
const handleDragOver = (e: DragEvent) => {
|
||||
e.preventDefault()
|
||||
setIsDraggingOver(true)
|
||||
}
|
||||
|
||||
const handleDragLeave = () => setIsDraggingOver(false)
|
||||
|
||||
const handleDropFile = (e: DragEvent<HTMLLabelElement>) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
if (!e.dataTransfer.files) return
|
||||
onNewFiles(e.dataTransfer.files)
|
||||
}
|
||||
|
||||
const clearFiles = () => setSelectedFiles([])
|
||||
|
||||
return (
|
||||
<form className="flex flex-col w-full" onSubmit={handleSubmit}>
|
||||
<label
|
||||
htmlFor="dropzone-file"
|
||||
className={
|
||||
'typebot-upload-input py-6 flex flex-col justify-center items-center w-full bg-gray-50 rounded-lg border-2 border-gray-300 border-dashed cursor-pointer hover:bg-gray-100 px-8 mb-2 ' +
|
||||
(isDraggingOver ? 'dragging-over' : '')
|
||||
}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDropFile}
|
||||
>
|
||||
{isUploading ? (
|
||||
<>
|
||||
{selectedFiles.length === 1 ? (
|
||||
<Spinner />
|
||||
) : (
|
||||
<div className="w-full bg-gray-200 rounded-full h-2.5">
|
||||
<div
|
||||
className="upload-progress-bar h-2.5 rounded-full"
|
||||
style={{
|
||||
width: `${
|
||||
uploadProgressPercent > 0 ? uploadProgressPercent : 10
|
||||
}%`,
|
||||
transition: 'width 150ms cubic-bezier(0.4, 0, 0.2, 1)',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex flex-col justify-center items-center">
|
||||
{selectedFiles.length ? (
|
||||
<span className="relative">
|
||||
<FileIcon />
|
||||
<div
|
||||
className="total-files-indicator flex items-center justify-center absolute -right-1 rounded-full px-1 h-4"
|
||||
style={{ bottom: '5px' }}
|
||||
>
|
||||
{selectedFiles.length}
|
||||
</div>
|
||||
</span>
|
||||
) : (
|
||||
<UploadIcon />
|
||||
)}
|
||||
<p
|
||||
className="text-sm text-gray-500 text-center"
|
||||
dangerouslySetInnerHTML={{ __html: labels.placeholder }}
|
||||
/>
|
||||
</div>
|
||||
<input
|
||||
id="dropzone-file"
|
||||
type="file"
|
||||
className="hidden"
|
||||
multiple={isMultipleAllowed}
|
||||
onChange={handleFileChange}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</label>
|
||||
{selectedFiles.length === 0 && isRequired === false && (
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
className={
|
||||
'py-2 px-4 justify-center font-semibold rounded-md text-white focus:outline-none flex items-center disabled:opacity-50 disabled:cursor-not-allowed disabled:brightness-100 transition-all filter hover:brightness-90 active:brightness-75 typebot-button '
|
||||
}
|
||||
onClick={onSkip}
|
||||
>
|
||||
Skip
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{isMultipleAllowed && selectedFiles.length > 0 && !isUploading && (
|
||||
<div className="flex justify-end">
|
||||
<div className="flex">
|
||||
{selectedFiles.length && (
|
||||
<button
|
||||
className={
|
||||
'secondary-button py-2 px-4 justify-center font-semibold rounded-md text-white focus:outline-none flex items-center disabled:opacity-50 disabled:cursor-not-allowed disabled:brightness-100 transition-all filter hover:brightness-90 active:brightness-75 mr-2'
|
||||
}
|
||||
onClick={clearFiles}
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
)}
|
||||
<SendButton
|
||||
type="submit"
|
||||
label={
|
||||
labels.button
|
||||
? `${labels.button} ${selectedFiles.length} file${
|
||||
selectedFiles.length > 1 ? 's' : ''
|
||||
}`
|
||||
: 'Upload'
|
||||
}
|
||||
disableIcon
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{errorMessage && <p className="text-red-500 text-sm">{errorMessage}</p>}
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
const UploadIcon = () => (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className="mb-3"
|
||||
>
|
||||
<polyline points="16 16 12 12 8 16"></polyline>
|
||||
<line x1="12" y1="12" x2="12" y2="21"></line>
|
||||
<path d="M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.3"></path>
|
||||
<polyline points="16 16 12 12 8 16"></polyline>
|
||||
</svg>
|
||||
)
|
||||
|
||||
const FileIcon = () => (
|
||||
<svg
|
||||
className="mb-3"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path>
|
||||
<polyline points="13 2 13 9 20 9"></polyline>
|
||||
</svg>
|
||||
)
|
||||
@@ -0,0 +1 @@
|
||||
export { FileUploadForm } from './components/FileUploadForm'
|
||||
@@ -0,0 +1,70 @@
|
||||
import { ShortTextInput } from '@/components/inputs/ShortTextInput'
|
||||
import { SendButton } from '@/components/SendButton'
|
||||
import { InputSubmitContent } from '@/types'
|
||||
import { NumberInputBlock } from 'models'
|
||||
import React, { MutableRefObject, useRef, useState } from 'react'
|
||||
|
||||
type NumberInputProps = {
|
||||
block: NumberInputBlock
|
||||
onSubmit: (value: InputSubmitContent) => void
|
||||
defaultValue?: string
|
||||
hasGuestAvatar: boolean
|
||||
}
|
||||
|
||||
export const NumberInput = ({
|
||||
block,
|
||||
onSubmit,
|
||||
defaultValue,
|
||||
hasGuestAvatar,
|
||||
}: NumberInputProps) => {
|
||||
const [inputValue, setInputValue] = useState(defaultValue ?? '')
|
||||
const inputRef = useRef<HTMLInputElement | HTMLTextAreaElement | null>(null)
|
||||
|
||||
const handleChange = (inputValue: string) => setInputValue(inputValue)
|
||||
|
||||
const checkIfInputIsValid = () =>
|
||||
inputValue !== '' && inputRef.current?.reportValidity()
|
||||
|
||||
const submit = () => {
|
||||
if (checkIfInputIsValid()) onSubmit({ value: inputValue })
|
||||
}
|
||||
|
||||
const submitWhenEnter = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') submit()
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={
|
||||
'flex items-end justify-between rounded-lg pr-2 typebot-input w-full'
|
||||
}
|
||||
data-testid="input"
|
||||
style={{
|
||||
marginRight: hasGuestAvatar ? '50px' : '0.5rem',
|
||||
maxWidth: '350px',
|
||||
}}
|
||||
onKeyDown={submitWhenEnter}
|
||||
>
|
||||
<ShortTextInput
|
||||
ref={inputRef as MutableRefObject<HTMLInputElement>}
|
||||
value={inputValue}
|
||||
placeholder={
|
||||
block.options?.labels?.placeholder ?? 'Type your answer...'
|
||||
}
|
||||
onChange={handleChange}
|
||||
type="number"
|
||||
style={{ appearance: 'auto' }}
|
||||
min={block.options?.min}
|
||||
max={block.options?.max}
|
||||
step={block.options?.step ?? 'any'}
|
||||
/>
|
||||
<SendButton
|
||||
type="button"
|
||||
label={block.options?.labels?.button ?? 'Send'}
|
||||
isDisabled={inputValue === ''}
|
||||
className="my-2 ml-2"
|
||||
onClick={submit}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { NumberInput } from './components/NumberInput'
|
||||
@@ -0,0 +1,15 @@
|
||||
import { PaymentInputOptions, PaymentProvider } from 'models'
|
||||
import React from 'react'
|
||||
import { StripePaymentForm } from './StripePaymentForm'
|
||||
|
||||
type Props = {
|
||||
onSuccess: () => void
|
||||
options: PaymentInputOptions
|
||||
}
|
||||
|
||||
export const PaymentForm = ({ onSuccess, options }: Props): JSX.Element => {
|
||||
switch (options.provider) {
|
||||
case PaymentProvider.STRIPE:
|
||||
return <StripePaymentForm onSuccess={onSuccess} options={options} />
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
import React, { FormEvent, useEffect, useState } from 'react'
|
||||
import { useStripe, useElements, PaymentElement } from '@stripe/react-stripe-js'
|
||||
import { Elements } from '@stripe/react-stripe-js'
|
||||
import { PaymentInputOptions, Variable } from 'models'
|
||||
import { SendButton, Spinner } from '@/components/SendButton'
|
||||
import { useFrame } from 'react-frame-component'
|
||||
import { initStripe } from '@/lib/stripe'
|
||||
import { parseVariables } from '@/features/variables'
|
||||
import { useChat } from '@/providers/ChatProvider'
|
||||
import { useTypebot } from '@/providers/TypebotProvider'
|
||||
import { createPaymentIntentQuery } from '../../queries/createPaymentIntentQuery'
|
||||
|
||||
type Props = {
|
||||
options: PaymentInputOptions
|
||||
onSuccess: () => void
|
||||
}
|
||||
|
||||
export const StripePaymentForm = ({ options, onSuccess }: Props) => {
|
||||
const {
|
||||
apiHost,
|
||||
isPreview,
|
||||
typebot: { variables },
|
||||
onNewLog,
|
||||
} = useTypebot()
|
||||
const { window: frameWindow, document: frameDocument } = useFrame()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const [stripe, setStripe] = useState<any>(null)
|
||||
const [clientSecret, setClientSecret] = useState('')
|
||||
const [amountLabel, setAmountLabel] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
;(async () => {
|
||||
const { data, error } = await createPaymentIntentQuery({
|
||||
apiHost,
|
||||
isPreview,
|
||||
variables,
|
||||
inputOptions: options,
|
||||
})
|
||||
if (error)
|
||||
return onNewLog({
|
||||
status: 'error',
|
||||
description: error.name + ' ' + error.message,
|
||||
details: error.message,
|
||||
})
|
||||
if (!data || !frameDocument) return
|
||||
await initStripe(frameDocument)
|
||||
if (!frameWindow?.Stripe) return
|
||||
setStripe(frameWindow.Stripe(data.publicKey))
|
||||
setClientSecret(data.clientSecret)
|
||||
setAmountLabel(data.amountLabel)
|
||||
})()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
if (!stripe || !clientSecret) return <Spinner className="text-blue-500" />
|
||||
return (
|
||||
<Elements stripe={stripe} options={{ clientSecret }}>
|
||||
<CheckoutForm
|
||||
onSuccess={onSuccess}
|
||||
clientSecret={clientSecret}
|
||||
amountLabel={amountLabel}
|
||||
options={options}
|
||||
variables={variables}
|
||||
viewerHost={apiHost}
|
||||
/>
|
||||
</Elements>
|
||||
)
|
||||
}
|
||||
|
||||
const CheckoutForm = ({
|
||||
onSuccess,
|
||||
clientSecret,
|
||||
amountLabel,
|
||||
options,
|
||||
variables,
|
||||
viewerHost,
|
||||
}: {
|
||||
onSuccess: () => void
|
||||
clientSecret: string
|
||||
amountLabel: string
|
||||
options: PaymentInputOptions
|
||||
variables: Variable[]
|
||||
viewerHost: string
|
||||
}) => {
|
||||
const { scroll } = useChat()
|
||||
const [ignoreFirstPaymentIntentCall, setIgnoreFirstPaymentIntentCall] =
|
||||
useState(true)
|
||||
|
||||
const stripe = useStripe()
|
||||
const elements = useElements()
|
||||
|
||||
const [message, setMessage] = useState<string>()
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const [isPayButtonVisible, setIsPayButtonVisible] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!stripe || !clientSecret) return
|
||||
|
||||
if (ignoreFirstPaymentIntentCall)
|
||||
return setIgnoreFirstPaymentIntentCall(false)
|
||||
|
||||
stripe.retrievePaymentIntent(clientSecret).then(({ paymentIntent }) => {
|
||||
switch (paymentIntent?.status) {
|
||||
case 'succeeded':
|
||||
setMessage('Payment succeeded!')
|
||||
break
|
||||
case 'processing':
|
||||
setMessage('Your payment is processing.')
|
||||
break
|
||||
case 'requires_payment_method':
|
||||
setMessage('Your payment was not successful, please try again.')
|
||||
break
|
||||
default:
|
||||
setMessage('Something went wrong.')
|
||||
break
|
||||
}
|
||||
})
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [stripe, clientSecret])
|
||||
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
|
||||
if (!stripe || !elements) return
|
||||
|
||||
setIsLoading(true)
|
||||
|
||||
const { error, paymentIntent } = await stripe.confirmPayment({
|
||||
elements,
|
||||
confirmParams: {
|
||||
// TO-DO: Handle redirection correctly.
|
||||
return_url: viewerHost,
|
||||
payment_method_data: {
|
||||
billing_details: {
|
||||
name: options.additionalInformation?.name
|
||||
? parseVariables(variables)(options.additionalInformation?.name)
|
||||
: undefined,
|
||||
email: options.additionalInformation?.email
|
||||
? parseVariables(variables)(options.additionalInformation?.email)
|
||||
: undefined,
|
||||
phone: options.additionalInformation?.phoneNumber
|
||||
? parseVariables(variables)(
|
||||
options.additionalInformation?.phoneNumber
|
||||
)
|
||||
: undefined,
|
||||
},
|
||||
},
|
||||
},
|
||||
redirect: 'if_required',
|
||||
})
|
||||
|
||||
setIsLoading(false)
|
||||
if (error?.type === 'validation_error') return
|
||||
if (error?.type === 'card_error') return setMessage(error.message)
|
||||
if (!error && paymentIntent.status === 'succeeded') return onSuccess()
|
||||
}
|
||||
|
||||
const showPayButton = () => {
|
||||
setIsPayButtonVisible(true)
|
||||
scroll()
|
||||
}
|
||||
|
||||
return (
|
||||
<form
|
||||
id="payment-form"
|
||||
onSubmit={handleSubmit}
|
||||
className="flex flex-col rounded-lg p-4 typebot-input w-full items-center"
|
||||
>
|
||||
<PaymentElement
|
||||
id="payment-element"
|
||||
className="w-full"
|
||||
onReady={showPayButton}
|
||||
/>
|
||||
{isPayButtonVisible && (
|
||||
<SendButton
|
||||
label={`${options.labels.button} ${amountLabel}`}
|
||||
isDisabled={isLoading || !stripe || !elements}
|
||||
isLoading={isLoading}
|
||||
className="mt-4 w-full max-w-lg"
|
||||
disableIcon
|
||||
/>
|
||||
)}
|
||||
|
||||
{message && (
|
||||
<div
|
||||
id="payment-message"
|
||||
className="typebot-input-error-message mt-4 text-center"
|
||||
>
|
||||
{message}
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { PaymentForm } from './PaymentForm'
|
||||
@@ -0,0 +1 @@
|
||||
export { PaymentForm } from './components/PaymentForm/'
|
||||
@@ -0,0 +1,21 @@
|
||||
import { PaymentInputOptions, Variable } from 'models'
|
||||
import { sendRequest } from 'utils'
|
||||
|
||||
export const createPaymentIntentQuery = ({
|
||||
apiHost,
|
||||
isPreview,
|
||||
inputOptions,
|
||||
variables,
|
||||
}: {
|
||||
inputOptions: PaymentInputOptions
|
||||
apiHost: string
|
||||
variables: Variable[]
|
||||
isPreview: boolean
|
||||
}) =>
|
||||
sendRequest<{ clientSecret: string; publicKey: string; amountLabel: string }>(
|
||||
{
|
||||
url: `${apiHost}/api/integrations/stripe/createPaymentIntent`,
|
||||
method: 'POST',
|
||||
body: { inputOptions, isPreview, variables },
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,68 @@
|
||||
import { SendButton } from '@/components/SendButton'
|
||||
import { InputSubmitContent } from '@/types'
|
||||
import { isMobile } from '@/utils/helpers'
|
||||
import { PhoneNumberInputBlock } from 'models'
|
||||
import React, { useRef, useState } from 'react'
|
||||
import ReactPhoneNumberInput, { Value, Country } from 'react-phone-number-input'
|
||||
|
||||
type PhoneInputProps = {
|
||||
block: PhoneNumberInputBlock
|
||||
onSubmit: (value: InputSubmitContent) => void
|
||||
defaultValue?: string
|
||||
hasGuestAvatar: boolean
|
||||
}
|
||||
|
||||
export const PhoneInput = ({
|
||||
block,
|
||||
onSubmit,
|
||||
defaultValue,
|
||||
hasGuestAvatar,
|
||||
}: PhoneInputProps) => {
|
||||
const [inputValue, setInputValue] = useState(defaultValue ?? '')
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const inputRef = useRef<any>(null)
|
||||
|
||||
const handleChange = (inputValue: Value | undefined) =>
|
||||
setInputValue(inputValue as string)
|
||||
|
||||
const checkIfInputIsValid = () =>
|
||||
inputValue !== '' && inputRef.current?.reportValidity()
|
||||
|
||||
const submit = () => {
|
||||
if (checkIfInputIsValid()) onSubmit({ value: inputValue })
|
||||
}
|
||||
|
||||
const submitWhenEnter = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') submit()
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={
|
||||
'flex items-end justify-between rounded-lg pr-2 typebot-input w-full'
|
||||
}
|
||||
data-testid="input"
|
||||
style={{
|
||||
marginRight: hasGuestAvatar ? '50px' : '0.5rem',
|
||||
maxWidth: '350px',
|
||||
}}
|
||||
onKeyDown={submitWhenEnter}
|
||||
>
|
||||
<ReactPhoneNumberInput
|
||||
ref={inputRef}
|
||||
value={inputValue}
|
||||
onChange={handleChange}
|
||||
placeholder={block.options.labels.placeholder ?? 'Your phone number...'}
|
||||
defaultCountry={block.options.defaultCountryCode as Country}
|
||||
autoFocus={!isMobile}
|
||||
/>
|
||||
<SendButton
|
||||
type="button"
|
||||
label={block.options?.labels?.button ?? 'Send'}
|
||||
isDisabled={inputValue === ''}
|
||||
className="my-2 ml-2"
|
||||
onClick={submit}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { PhoneInput } from './components/PhoneInput'
|
||||
export { validatePhoneNumber } from './utils/validatePhoneNumber'
|
||||
@@ -0,0 +1,4 @@
|
||||
import { isPossiblePhoneNumber } from 'react-phone-number-input'
|
||||
|
||||
export const validatePhoneNumber = (phoneNumber: string) =>
|
||||
isPossiblePhoneNumber(phoneNumber)
|
||||
@@ -0,0 +1,107 @@
|
||||
import { InputSubmitContent } from '@/types'
|
||||
import { RatingInputOptions, RatingInputBlock } from 'models'
|
||||
import React, { FormEvent, useState } from 'react'
|
||||
import { isDefined, isEmpty, isNotDefined } from 'utils'
|
||||
import { SendButton } from '../../../../../components/SendButton'
|
||||
|
||||
type Props = {
|
||||
block: RatingInputBlock
|
||||
onSubmit: (value: InputSubmitContent) => void
|
||||
}
|
||||
|
||||
export const RatingForm = ({ block, onSubmit }: Props) => {
|
||||
const [rating, setRating] = useState<number>()
|
||||
|
||||
const handleSubmit = (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (isNotDefined(rating)) return
|
||||
onSubmit({ value: rating.toString() })
|
||||
}
|
||||
|
||||
const handleClick = (rating: number) => setRating(rating)
|
||||
|
||||
return (
|
||||
<form className="flex flex-col" onSubmit={handleSubmit}>
|
||||
{block.options.labels.left && (
|
||||
<span className="text-sm w-full mb-2 rating-label">
|
||||
{block.options.labels.left}
|
||||
</span>
|
||||
)}
|
||||
<div className="flex flex-wrap justify-center">
|
||||
{Array.from(
|
||||
Array(
|
||||
block.options.length +
|
||||
(block.options.buttonType === 'Numbers' ? 1 : 0)
|
||||
)
|
||||
).map((_, idx) => (
|
||||
<RatingButton
|
||||
{...block.options}
|
||||
key={idx}
|
||||
rating={rating}
|
||||
idx={idx + (block.options.buttonType === 'Numbers' ? 0 : 1)}
|
||||
onClick={handleClick}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{block.options.labels.right && (
|
||||
<span className="text-sm w-full text-right mb-2 pr-2 rating-label">
|
||||
{block.options.labels.right}
|
||||
</span>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end mr-2">
|
||||
{isDefined(rating) && (
|
||||
<SendButton
|
||||
label={block.options?.labels.button ?? 'Send'}
|
||||
disableIcon
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
const RatingButton = ({
|
||||
rating,
|
||||
idx,
|
||||
buttonType,
|
||||
customIcon,
|
||||
onClick,
|
||||
}: Pick<RatingInputOptions, 'buttonType' | 'customIcon'> & {
|
||||
rating: number | undefined
|
||||
idx: number
|
||||
onClick: (idx: number) => void
|
||||
}) => {
|
||||
if (buttonType === 'Numbers')
|
||||
return (
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
onClick(idx)
|
||||
}}
|
||||
className={
|
||||
'py-2 px-4 mr-2 mb-2 text-left font-semibold rounded-md transition-all filter hover:brightness-90 active:brightness-75 duration-100 focus:outline-none typebot-button ' +
|
||||
(isDefined(rating) && idx <= rating ? '' : 'selectable')
|
||||
}
|
||||
>
|
||||
{idx}
|
||||
</button>
|
||||
)
|
||||
return (
|
||||
<div
|
||||
className={
|
||||
'flex justify-center items-center rating-icon-container cursor-pointer mr-2 mb-2 ' +
|
||||
(isDefined(rating) && idx <= rating ? 'selected' : '')
|
||||
}
|
||||
onClick={() => onClick(idx)}
|
||||
dangerouslySetInnerHTML={{
|
||||
__html:
|
||||
customIcon.isEnabled && !isEmpty(customIcon.svg)
|
||||
? customIcon.svg
|
||||
: defaultIcon,
|
||||
}}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const defaultIcon = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-star"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon></svg>`
|
||||
@@ -0,0 +1 @@
|
||||
export { RatingForm } from './components/RatingForm'
|
||||
@@ -0,0 +1,80 @@
|
||||
import { ShortTextInput } from '@/components/inputs/ShortTextInput'
|
||||
import { Textarea } from '@/components/inputs/Textarea'
|
||||
import { SendButton } from '@/components/SendButton'
|
||||
import { InputSubmitContent } from '@/types'
|
||||
import { TextInputBlock } from 'models'
|
||||
import React, { MutableRefObject, useRef, useState } from 'react'
|
||||
|
||||
type TextInputProps = {
|
||||
block: TextInputBlock
|
||||
onSubmit: (value: InputSubmitContent) => void
|
||||
defaultValue: string | undefined
|
||||
hasGuestAvatar: boolean
|
||||
}
|
||||
|
||||
export const TextInput = ({
|
||||
block,
|
||||
onSubmit,
|
||||
defaultValue,
|
||||
hasGuestAvatar,
|
||||
}: TextInputProps) => {
|
||||
const [inputValue, setInputValue] = useState(defaultValue ?? '')
|
||||
const inputRef = useRef<HTMLInputElement | HTMLTextAreaElement | null>(null)
|
||||
|
||||
const isLongText = block.options?.isLong
|
||||
|
||||
const handleChange = (inputValue: string) => setInputValue(inputValue)
|
||||
|
||||
const checkIfInputIsValid = () =>
|
||||
inputValue !== '' && inputRef.current?.reportValidity()
|
||||
|
||||
const submit = () => {
|
||||
if (checkIfInputIsValid()) onSubmit({ value: inputValue })
|
||||
}
|
||||
|
||||
const submitWhenEnter = (e: React.KeyboardEvent) => {
|
||||
if (isLongText) return
|
||||
if (e.key === 'Enter') submit()
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={
|
||||
'flex items-end justify-between rounded-lg pr-2 typebot-input w-full'
|
||||
}
|
||||
data-testid="input"
|
||||
style={{
|
||||
marginRight: hasGuestAvatar ? '50px' : '0.5rem',
|
||||
maxWidth: isLongText ? undefined : '350px',
|
||||
}}
|
||||
onKeyDown={submitWhenEnter}
|
||||
>
|
||||
{isLongText ? (
|
||||
<Textarea
|
||||
ref={inputRef as MutableRefObject<HTMLTextAreaElement>}
|
||||
onChange={handleChange}
|
||||
value={inputValue}
|
||||
placeholder={
|
||||
block.options?.labels?.placeholder ?? 'Type your answer...'
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<ShortTextInput
|
||||
ref={inputRef as MutableRefObject<HTMLInputElement>}
|
||||
onChange={handleChange}
|
||||
value={inputValue}
|
||||
placeholder={
|
||||
block.options?.labels?.placeholder ?? 'Type your answer...'
|
||||
}
|
||||
/>
|
||||
)}
|
||||
<SendButton
|
||||
type="button"
|
||||
label={block.options?.labels?.button ?? 'Send'}
|
||||
isDisabled={inputValue === ''}
|
||||
className="my-2 ml-2"
|
||||
onClick={submit}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { TextInput } from './components/TextInput'
|
||||
@@ -0,0 +1,71 @@
|
||||
import { ShortTextInput } from '@/components/inputs/ShortTextInput'
|
||||
import { SendButton } from '@/components/SendButton'
|
||||
import { InputSubmitContent } from '@/types'
|
||||
import { UrlInputBlock } from 'models'
|
||||
import React, { MutableRefObject, useRef, useState } from 'react'
|
||||
|
||||
type UrlInputProps = {
|
||||
block: UrlInputBlock
|
||||
onSubmit: (value: InputSubmitContent) => void
|
||||
defaultValue?: string
|
||||
hasGuestAvatar: boolean
|
||||
}
|
||||
|
||||
export const UrlInput = ({
|
||||
block,
|
||||
onSubmit,
|
||||
defaultValue,
|
||||
hasGuestAvatar,
|
||||
}: UrlInputProps) => {
|
||||
const [inputValue, setInputValue] = useState(defaultValue ?? '')
|
||||
const inputRef = useRef<HTMLInputElement | HTMLTextAreaElement | null>(null)
|
||||
|
||||
const handleChange = (inputValue: string) => {
|
||||
if (!inputValue.startsWith('https://'))
|
||||
return inputValue === 'https:/'
|
||||
? undefined
|
||||
: setInputValue(`https://${inputValue}`)
|
||||
setInputValue(inputValue)
|
||||
}
|
||||
|
||||
const checkIfInputIsValid = () =>
|
||||
inputValue !== '' && inputRef.current?.reportValidity()
|
||||
|
||||
const submit = () => {
|
||||
if (checkIfInputIsValid()) onSubmit({ value: inputValue })
|
||||
}
|
||||
|
||||
const submitWhenEnter = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter') submit()
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={
|
||||
'flex items-end justify-between rounded-lg pr-2 typebot-input w-full'
|
||||
}
|
||||
data-testid="input"
|
||||
style={{
|
||||
marginRight: hasGuestAvatar ? '50px' : '0.5rem',
|
||||
maxWidth: '350px',
|
||||
}}
|
||||
onKeyDown={submitWhenEnter}
|
||||
>
|
||||
<ShortTextInput
|
||||
ref={inputRef as MutableRefObject<HTMLInputElement>}
|
||||
value={inputValue}
|
||||
placeholder={block.options?.labels?.placeholder ?? 'Type your URL...'}
|
||||
onChange={handleChange}
|
||||
type="url"
|
||||
autoComplete="url"
|
||||
/>
|
||||
<SendButton
|
||||
type="button"
|
||||
label={block.options?.labels?.button ?? 'Send'}
|
||||
isDisabled={inputValue === ''}
|
||||
className="my-2 ml-2"
|
||||
onClick={submit}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { UrlInput } from './components/UrlInput'
|
||||
export { validateUrl } from './utils/validateUrl'
|
||||
@@ -0,0 +1,4 @@
|
||||
const urlRegex =
|
||||
/^(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})$/
|
||||
|
||||
export const validateUrl = (url: string) => urlRegex.test(url)
|
||||
@@ -0,0 +1 @@
|
||||
export * from './utils/executeChatwootBlock'
|
||||
@@ -1,8 +1,8 @@
|
||||
import { parseVariables, parseCorrectValueType } from '@/features/variables'
|
||||
import { IntegrationState } from '@/types'
|
||||
import { sendEventToParent } from '@/utils/chat'
|
||||
import { isEmbedded } from '@/utils/helpers'
|
||||
import { ChatwootBlock, ChatwootOptions } from 'models'
|
||||
import { sendEventToParent } from 'services/chat'
|
||||
import { IntegrationContext } from 'services/integration'
|
||||
import { isEmbedded } from 'services/utils'
|
||||
import { parseCorrectValueType, parseVariables } from 'services/variable'
|
||||
|
||||
const parseSetUserCode = (user: ChatwootOptions['user']) => `
|
||||
window.$chatwoot.setUser("${user?.id ?? ''}", {
|
||||
@@ -47,9 +47,9 @@ if (window.$chatwoot) {
|
||||
})(document, "script");
|
||||
}`
|
||||
|
||||
export const openChatwootWidget = async (
|
||||
export const executeChatwootBlock = async (
|
||||
block: ChatwootBlock,
|
||||
{ variables, isPreview, onNewLog }: IntegrationContext
|
||||
{ variables, isPreview, onNewLog }: IntegrationState
|
||||
) => {
|
||||
if (isPreview) {
|
||||
onNewLog({
|
||||
@@ -0,0 +1 @@
|
||||
export { executeGoogleAnalyticsBlock } from './utils/executeGoogleAnalyticsBlock'
|
||||
@@ -0,0 +1,15 @@
|
||||
import { parseVariablesInObject } from '@/features/variables'
|
||||
import { sendGaEvent } from '@/lib/gtag'
|
||||
import { IntegrationState } from '@/types'
|
||||
import { GoogleAnalyticsBlock } from 'models'
|
||||
|
||||
export const executeGoogleAnalyticsBlock = async (
|
||||
block: GoogleAnalyticsBlock,
|
||||
{ variables }: IntegrationState
|
||||
) => {
|
||||
if (!block.options?.trackingId) return block.outgoingEdgeId
|
||||
const { default: initGoogleAnalytics } = await import('@/lib/gtag')
|
||||
await initGoogleAnalytics(block.options.trackingId)
|
||||
sendGaEvent(parseVariablesInObject(block.options, variables))
|
||||
return block.outgoingEdgeId
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { executeGoogleSheetBlock } from './utils/executeGoogleSheetBlock'
|
||||
@@ -0,0 +1,159 @@
|
||||
import { parseVariables } from '@/features/variables'
|
||||
import { IntegrationState } from '@/types'
|
||||
import { parseLog } from '@/utils/helpers'
|
||||
import {
|
||||
GoogleSheetsBlock,
|
||||
GoogleSheetsAction,
|
||||
GoogleSheetsInsertRowOptions,
|
||||
GoogleSheetsUpdateRowOptions,
|
||||
GoogleSheetsGetOptions,
|
||||
VariableWithValue,
|
||||
Cell,
|
||||
Variable,
|
||||
} from 'models'
|
||||
import { stringify } from 'qs'
|
||||
import { sendRequest, byId } from 'utils'
|
||||
|
||||
export const executeGoogleSheetBlock = async (
|
||||
block: GoogleSheetsBlock,
|
||||
context: IntegrationState
|
||||
) => {
|
||||
if (!('action' in block.options)) return block.outgoingEdgeId
|
||||
switch (block.options.action) {
|
||||
case GoogleSheetsAction.INSERT_ROW:
|
||||
await insertRowInGoogleSheets(block.options, context)
|
||||
break
|
||||
case GoogleSheetsAction.UPDATE_ROW:
|
||||
await updateRowInGoogleSheets(block.options, context)
|
||||
break
|
||||
case GoogleSheetsAction.GET:
|
||||
await getRowFromGoogleSheets(block.options, context)
|
||||
break
|
||||
}
|
||||
return block.outgoingEdgeId
|
||||
}
|
||||
|
||||
const insertRowInGoogleSheets = async (
|
||||
options: GoogleSheetsInsertRowOptions,
|
||||
{ variables, apiHost, onNewLog, resultId }: IntegrationState
|
||||
) => {
|
||||
if (!options.cellsToInsert) {
|
||||
onNewLog({
|
||||
status: 'warning',
|
||||
description: 'Cells to insert are undefined',
|
||||
details: null,
|
||||
})
|
||||
return
|
||||
}
|
||||
const params = stringify({ resultId })
|
||||
const { error } = await sendRequest({
|
||||
url: `${apiHost}/api/integrations/google-sheets/spreadsheets/${options.spreadsheetId}/sheets/${options.sheetId}?${params}`,
|
||||
method: 'POST',
|
||||
body: {
|
||||
credentialsId: options.credentialsId,
|
||||
values: parseCellValues(options.cellsToInsert, variables),
|
||||
},
|
||||
})
|
||||
onNewLog(
|
||||
parseLog(
|
||||
error,
|
||||
'Succesfully inserted a row in the sheet',
|
||||
'Failed to insert a row in the sheet'
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
const updateRowInGoogleSheets = async (
|
||||
options: GoogleSheetsUpdateRowOptions,
|
||||
{ variables, apiHost, onNewLog, resultId }: IntegrationState
|
||||
) => {
|
||||
if (!options.cellsToUpsert || !options.referenceCell) return
|
||||
const params = stringify({ resultId })
|
||||
const { error } = await sendRequest({
|
||||
url: `${apiHost}/api/integrations/google-sheets/spreadsheets/${options.spreadsheetId}/sheets/${options.sheetId}?${params}`,
|
||||
method: 'PATCH',
|
||||
body: {
|
||||
credentialsId: options.credentialsId,
|
||||
values: parseCellValues(options.cellsToUpsert, variables),
|
||||
referenceCell: {
|
||||
column: options.referenceCell.column,
|
||||
value: parseVariables(variables)(options.referenceCell.value ?? ''),
|
||||
},
|
||||
},
|
||||
})
|
||||
onNewLog(
|
||||
parseLog(
|
||||
error,
|
||||
'Succesfully updated a row in the sheet',
|
||||
'Failed to update a row in the sheet'
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
const getRowFromGoogleSheets = async (
|
||||
options: GoogleSheetsGetOptions,
|
||||
{
|
||||
variables,
|
||||
updateVariableValue,
|
||||
updateVariables,
|
||||
apiHost,
|
||||
onNewLog,
|
||||
resultId,
|
||||
}: IntegrationState
|
||||
) => {
|
||||
if (!options.referenceCell || !options.cellsToExtract) return
|
||||
const queryParams = stringify(
|
||||
{
|
||||
credentialsId: options.credentialsId,
|
||||
referenceCell: {
|
||||
column: options.referenceCell.column,
|
||||
value: parseVariables(variables)(options.referenceCell.value ?? ''),
|
||||
},
|
||||
columns: options.cellsToExtract.map((cell) => cell.column),
|
||||
resultId,
|
||||
},
|
||||
{ indices: false }
|
||||
)
|
||||
const { data, error } = await sendRequest<{ [key: string]: string }>({
|
||||
url: `${apiHost}/api/integrations/google-sheets/spreadsheets/${options.spreadsheetId}/sheets/${options.sheetId}?${queryParams}`,
|
||||
method: 'GET',
|
||||
})
|
||||
onNewLog(
|
||||
parseLog(
|
||||
error,
|
||||
'Succesfully fetched data from sheet',
|
||||
'Failed to fetch data from sheet'
|
||||
)
|
||||
)
|
||||
if (!data) return
|
||||
const newVariables = options.cellsToExtract.reduce<VariableWithValue[]>(
|
||||
(newVariables, cell) => {
|
||||
const existingVariable = variables.find(byId(cell.variableId))
|
||||
const value = data[cell.column ?? ''] ?? null
|
||||
if (!existingVariable) return newVariables
|
||||
updateVariableValue(existingVariable.id, value)
|
||||
return [
|
||||
...newVariables,
|
||||
{
|
||||
...existingVariable,
|
||||
value,
|
||||
},
|
||||
]
|
||||
},
|
||||
[]
|
||||
)
|
||||
updateVariables(newVariables)
|
||||
}
|
||||
|
||||
const parseCellValues = (
|
||||
cells: Cell[],
|
||||
variables: Variable[]
|
||||
): { [key: string]: string } =>
|
||||
cells.reduce((row, cell) => {
|
||||
return !cell.column || !cell.value
|
||||
? row
|
||||
: {
|
||||
...row,
|
||||
[cell.column]: parseVariables(variables)(cell.value),
|
||||
}
|
||||
}, {})
|
||||
@@ -0,0 +1 @@
|
||||
export { executeSendEmailBlock } from './utils/executeSendEmailBlock'
|
||||
@@ -0,0 +1,51 @@
|
||||
import { parseVariables } from '@/features/variables'
|
||||
import { IntegrationState } from '@/types'
|
||||
import { parseLog } from '@/utils/helpers'
|
||||
import { SendEmailBlock } from 'models'
|
||||
import { sendRequest, byId } from 'utils'
|
||||
|
||||
export const executeSendEmailBlock = async (
|
||||
block: SendEmailBlock,
|
||||
{
|
||||
variables,
|
||||
apiHost,
|
||||
isPreview,
|
||||
onNewLog,
|
||||
resultId,
|
||||
typebotId,
|
||||
resultValues,
|
||||
}: IntegrationState
|
||||
) => {
|
||||
if (isPreview) {
|
||||
onNewLog({
|
||||
status: 'info',
|
||||
description: 'Emails are not sent in preview mode',
|
||||
details: null,
|
||||
})
|
||||
return block.outgoingEdgeId
|
||||
}
|
||||
const { options } = block
|
||||
const { error } = await sendRequest({
|
||||
url: `${apiHost}/api/typebots/${typebotId}/integrations/email?resultId=${resultId}`,
|
||||
method: 'POST',
|
||||
body: {
|
||||
credentialsId: options.credentialsId,
|
||||
recipients: options.recipients.map(parseVariables(variables)),
|
||||
subject: parseVariables(variables)(options.subject ?? ''),
|
||||
body: parseVariables(variables)(options.body ?? ''),
|
||||
cc: (options.cc ?? []).map(parseVariables(variables)),
|
||||
bcc: (options.bcc ?? []).map(parseVariables(variables)),
|
||||
replyTo: options.replyTo
|
||||
? parseVariables(variables)(options.replyTo)
|
||||
: undefined,
|
||||
fileUrls: variables.find(byId(options.attachmentsVariableId))?.value,
|
||||
isCustomBody: options.isCustomBody,
|
||||
isBodyCode: options.isBodyCode,
|
||||
resultValues,
|
||||
},
|
||||
})
|
||||
onNewLog(
|
||||
parseLog(error, 'Succesfully sent an email', 'Failed to send an email')
|
||||
)
|
||||
return block.outgoingEdgeId
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { executeWebhook } from './utils/executeWebhookBlock'
|
||||
@@ -0,0 +1,69 @@
|
||||
import { parseVariables } from '@/features/variables'
|
||||
import { IntegrationState } from '@/types'
|
||||
import {
|
||||
WebhookBlock,
|
||||
ZapierBlock,
|
||||
MakeComBlock,
|
||||
PabblyConnectBlock,
|
||||
VariableWithUnknowValue,
|
||||
} from 'models'
|
||||
import { stringify } from 'qs'
|
||||
import { sendRequest, byId } from 'utils'
|
||||
|
||||
export const executeWebhook = async (
|
||||
block: WebhookBlock | ZapierBlock | MakeComBlock | PabblyConnectBlock,
|
||||
{
|
||||
blockId,
|
||||
variables,
|
||||
updateVariableValue,
|
||||
updateVariables,
|
||||
typebotId,
|
||||
apiHost,
|
||||
resultValues,
|
||||
onNewLog,
|
||||
resultId,
|
||||
}: IntegrationState
|
||||
) => {
|
||||
const params = stringify({ resultId })
|
||||
const { data, error } = await sendRequest({
|
||||
url: `${apiHost}/api/typebots/${typebotId}/blocks/${blockId}/executeWebhook?${params}`,
|
||||
method: 'POST',
|
||||
body: {
|
||||
variables,
|
||||
resultValues,
|
||||
},
|
||||
})
|
||||
const statusCode = (
|
||||
data as Record<string, string> | undefined
|
||||
)?.statusCode.toString()
|
||||
const isError = statusCode
|
||||
? statusCode?.startsWith('4') || statusCode?.startsWith('5')
|
||||
: true
|
||||
onNewLog({
|
||||
status: error ? 'error' : isError ? 'warning' : 'success',
|
||||
description: isError
|
||||
? 'Webhook returned an error'
|
||||
: 'Webhook successfuly executed',
|
||||
details: JSON.stringify(error ?? data, null, 2).substring(0, 1000),
|
||||
})
|
||||
const newVariables = block.options.responseVariableMapping.reduce<
|
||||
VariableWithUnknowValue[]
|
||||
>((newVariables, varMapping) => {
|
||||
if (!varMapping?.bodyPath || !varMapping.variableId) return newVariables
|
||||
const existingVariable = variables.find(byId(varMapping.variableId))
|
||||
if (!existingVariable) return newVariables
|
||||
const func = Function(
|
||||
'data',
|
||||
`return data.${parseVariables(variables)(varMapping?.bodyPath)}`
|
||||
)
|
||||
try {
|
||||
const value: unknown = func(data)
|
||||
updateVariableValue(existingVariable?.id, value)
|
||||
return [...newVariables, { ...existingVariable, value }]
|
||||
} catch (err) {
|
||||
return newVariables
|
||||
}
|
||||
}, [])
|
||||
updateVariables(newVariables)
|
||||
return block.outgoingEdgeId
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { executeCode } from './utils/executeCode'
|
||||
@@ -0,0 +1,29 @@
|
||||
import { parseVariables, parseCorrectValueType } from '@/features/variables'
|
||||
import { LogicState } from '@/types'
|
||||
import { sendEventToParent } from '@/utils/chat'
|
||||
import { isEmbedded } from '@/utils/helpers'
|
||||
import { CodeBlock } from 'models'
|
||||
|
||||
export const executeCode = async (
|
||||
block: CodeBlock,
|
||||
{ typebot: { variables } }: LogicState
|
||||
) => {
|
||||
if (!block.options.content) return
|
||||
if (block.options.shouldExecuteInParentContext && isEmbedded) {
|
||||
sendEventToParent({
|
||||
codeToExecute: parseVariables(variables)(block.options.content),
|
||||
})
|
||||
} else {
|
||||
const func = Function(
|
||||
...variables.map((v) => v.id),
|
||||
parseVariables(variables, { fieldToParse: 'id' })(block.options.content)
|
||||
)
|
||||
try {
|
||||
await func(...variables.map((v) => parseCorrectValueType(v.value)))
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
}
|
||||
}
|
||||
|
||||
return block.outgoingEdgeId
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { executeCondition } from './utils/executeCondition'
|
||||
@@ -0,0 +1,54 @@
|
||||
import { parseVariables } from '@/features/variables'
|
||||
import { EdgeId, LogicState } from '@/types'
|
||||
import {
|
||||
Comparison,
|
||||
ComparisonOperators,
|
||||
ConditionBlock,
|
||||
LogicalOperator,
|
||||
Variable,
|
||||
} from 'models'
|
||||
import { isNotDefined, isDefined } from 'utils'
|
||||
|
||||
export const executeCondition = (
|
||||
block: ConditionBlock,
|
||||
{ typebot: { variables } }: LogicState
|
||||
): EdgeId | undefined => {
|
||||
const { content } = block.items[0]
|
||||
const isConditionPassed =
|
||||
content.logicalOperator === LogicalOperator.AND
|
||||
? content.comparisons.every(executeComparison(variables))
|
||||
: content.comparisons.some(executeComparison(variables))
|
||||
return isConditionPassed
|
||||
? block.items[0].outgoingEdgeId
|
||||
: block.outgoingEdgeId
|
||||
}
|
||||
|
||||
const executeComparison =
|
||||
(variables: Variable[]) => (comparison: Comparison) => {
|
||||
if (!comparison?.variableId) return false
|
||||
const inputValue = (
|
||||
variables.find((v) => v.id === comparison.variableId)?.value ?? ''
|
||||
).trim()
|
||||
const value = parseVariables(variables)(comparison.value).trim()
|
||||
if (isNotDefined(value)) return false
|
||||
switch (comparison.comparisonOperator) {
|
||||
case ComparisonOperators.CONTAINS: {
|
||||
return inputValue.toLowerCase().includes(value.toLowerCase())
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { executeRedirect } from './utils/executeRedirect'
|
||||
@@ -0,0 +1,27 @@
|
||||
import { parseVariables } from '@/features/variables'
|
||||
import { EdgeId, LogicState } from '@/types'
|
||||
import { sendEventToParent } from '@/utils/chat'
|
||||
import { RedirectBlock } from 'models'
|
||||
import { sanitizeUrl } from 'utils'
|
||||
|
||||
export const executeRedirect = (
|
||||
block: RedirectBlock,
|
||||
{ typebot: { variables } }: LogicState
|
||||
): EdgeId | undefined => {
|
||||
if (!block.options?.url) return block.outgoingEdgeId
|
||||
const formattedUrl = sanitizeUrl(parseVariables(variables)(block.options.url))
|
||||
const isEmbedded = window.parent && window.location !== window.top?.location
|
||||
if (isEmbedded) {
|
||||
if (!block.options.isNewTab)
|
||||
return ((window.top as Window).location.href = formattedUrl)
|
||||
|
||||
try {
|
||||
window.open(formattedUrl)
|
||||
} catch (err) {
|
||||
sendEventToParent({ redirectUrl: formattedUrl })
|
||||
}
|
||||
} else {
|
||||
window.open(formattedUrl, block.options.isNewTab ? '_blank' : '_self')
|
||||
}
|
||||
return block.outgoingEdgeId
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { executeSetVariable } from './utils/executeSetVariable'
|
||||
@@ -0,0 +1,36 @@
|
||||
import { SetVariableBlock, Variable } from 'models'
|
||||
import { byId } from 'utils'
|
||||
import { EdgeId, LogicState } from '@/types'
|
||||
import { parseVariables, parseCorrectValueType } from '@/features/variables'
|
||||
|
||||
export const executeSetVariable = (
|
||||
block: SetVariableBlock,
|
||||
{ typebot: { variables }, updateVariableValue, updateVariables }: LogicState
|
||||
): EdgeId | undefined => {
|
||||
if (!block.options?.variableId) return block.outgoingEdgeId
|
||||
const evaluatedExpression = block.options.expressionToEvaluate
|
||||
? evaluateSetVariableExpression(variables)(
|
||||
block.options.expressionToEvaluate
|
||||
)
|
||||
: undefined
|
||||
const existingVariable = variables.find(byId(block.options.variableId))
|
||||
if (!existingVariable) return block.outgoingEdgeId
|
||||
updateVariableValue(existingVariable.id, evaluatedExpression)
|
||||
updateVariables([{ ...existingVariable, value: evaluatedExpression }])
|
||||
return block.outgoingEdgeId
|
||||
}
|
||||
|
||||
const evaluateSetVariableExpression =
|
||||
(variables: Variable[]) =>
|
||||
(str: string): unknown => {
|
||||
const evaluating = parseVariables(variables, { fieldToParse: 'id' })(
|
||||
str.includes('return ') ? str : `return ${str}`
|
||||
)
|
||||
try {
|
||||
const func = Function(...variables.map((v) => v.id), evaluating)
|
||||
return func(...variables.map((v) => parseCorrectValueType(v.value)))
|
||||
} catch (err) {
|
||||
console.log(`Evaluating: ${evaluating}`, err)
|
||||
return str
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { executeTypebotLink } from './utils/executeTypebotLink'
|
||||
@@ -0,0 +1,19 @@
|
||||
import { LinkedTypebot } from '@/providers/TypebotProvider'
|
||||
import { LogicState } from '@/types'
|
||||
import { TypebotLinkBlock, Typebot, PublicTypebot } from 'models'
|
||||
import { sendRequest } from 'utils'
|
||||
|
||||
export const fetchAndInjectTypebot = async (
|
||||
block: TypebotLinkBlock,
|
||||
{ apiHost, injectLinkedTypebot, isPreview }: LogicState
|
||||
): Promise<LinkedTypebot | undefined> => {
|
||||
const { data, error } = isPreview
|
||||
? await sendRequest<{ typebot: Typebot }>(
|
||||
`/api/typebots/${block.options.typebotId}`
|
||||
)
|
||||
: await sendRequest<{ typebot: PublicTypebot }>(
|
||||
`${apiHost}/api/publicTypebots/${block.options.typebotId}`
|
||||
)
|
||||
if (!data || error) return
|
||||
return injectLinkedTypebot(data.typebot)
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { LinkedTypebot } from '@/providers/TypebotProvider'
|
||||
import { EdgeId, LogicState } from '@/types'
|
||||
import { TypebotLinkBlock, Edge, PublicTypebot } from 'models'
|
||||
import { byId } from 'utils'
|
||||
import { fetchAndInjectTypebot } from '../queries/fetchAndInjectTypebotQuery'
|
||||
|
||||
export const executeTypebotLink = async (
|
||||
block: TypebotLinkBlock,
|
||||
context: LogicState
|
||||
): Promise<{
|
||||
nextEdgeId?: EdgeId
|
||||
linkedTypebot?: PublicTypebot | LinkedTypebot
|
||||
}> => {
|
||||
const {
|
||||
typebot,
|
||||
linkedTypebots,
|
||||
onNewLog,
|
||||
createEdge,
|
||||
setCurrentTypebotId,
|
||||
pushEdgeIdInLinkedTypebotQueue,
|
||||
currentTypebotId,
|
||||
} = context
|
||||
const linkedTypebot = (
|
||||
block.options.typebotId === 'current'
|
||||
? typebot
|
||||
: [typebot, ...linkedTypebots].find(byId(block.options.typebotId)) ??
|
||||
(await fetchAndInjectTypebot(block, context))
|
||||
) as PublicTypebot | LinkedTypebot | undefined
|
||||
if (!linkedTypebot) {
|
||||
onNewLog({
|
||||
status: 'error',
|
||||
description: 'Failed to link typebot',
|
||||
details: '',
|
||||
})
|
||||
return { nextEdgeId: block.outgoingEdgeId }
|
||||
}
|
||||
if (block.outgoingEdgeId)
|
||||
pushEdgeIdInLinkedTypebotQueue({
|
||||
edgeId: block.outgoingEdgeId,
|
||||
typebotId: currentTypebotId,
|
||||
})
|
||||
setCurrentTypebotId(
|
||||
'typebotId' in linkedTypebot ? linkedTypebot.typebotId : linkedTypebot.id
|
||||
)
|
||||
const nextGroupId =
|
||||
block.options.groupId ??
|
||||
linkedTypebot.groups.find((b) => b.blocks.some((s) => s.type === 'start'))
|
||||
?.id
|
||||
if (!nextGroupId) return { nextEdgeId: block.outgoingEdgeId }
|
||||
const newEdge: Edge = {
|
||||
id: (Math.random() * 1000).toString(),
|
||||
from: { blockId: '', groupId: '' },
|
||||
to: {
|
||||
groupId: nextGroupId,
|
||||
},
|
||||
}
|
||||
createEdge(newEdge)
|
||||
return {
|
||||
nextEdgeId: newEdge.id,
|
||||
linkedTypebot: {
|
||||
...linkedTypebot,
|
||||
edges: [...linkedTypebot.edges, newEdge],
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
export { openChatwootWidget } from './utils/openChatwootWidget'
|
||||
1
packages/bot-engine/src/features/theme/index.ts
Normal file
1
packages/bot-engine/src/features/theme/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from './utils/setCssVariablesValue'
|
||||
@@ -0,0 +1,142 @@
|
||||
import {
|
||||
Background,
|
||||
BackgroundType,
|
||||
ChatTheme,
|
||||
ContainerColors,
|
||||
GeneralTheme,
|
||||
InputColors,
|
||||
Theme,
|
||||
} from 'models'
|
||||
|
||||
const cssVariableNames = {
|
||||
general: {
|
||||
bgImage: '--typebot-container-bg-image',
|
||||
bgColor: '--typebot-container-bg-color',
|
||||
fontFamily: '--typebot-container-font-family',
|
||||
},
|
||||
chat: {
|
||||
hostBubbles: {
|
||||
bgColor: '--typebot-host-bubble-bg-color',
|
||||
color: '--typebot-host-bubble-color',
|
||||
},
|
||||
guestBubbles: {
|
||||
bgColor: '--typebot-guest-bubble-bg-color',
|
||||
color: '--typebot-guest-bubble-color',
|
||||
},
|
||||
inputs: {
|
||||
bgColor: '--typebot-input-bg-color',
|
||||
color: '--typebot-input-color',
|
||||
placeholderColor: '--typebot-input-placeholder-color',
|
||||
},
|
||||
buttons: {
|
||||
bgColor: '--typebot-button-bg-color',
|
||||
color: '--typebot-button-color',
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
export const setCssVariablesValue = (
|
||||
theme: Theme | undefined,
|
||||
documentStyle: CSSStyleDeclaration
|
||||
) => {
|
||||
if (!theme) return
|
||||
if (theme.general) setGeneralTheme(theme.general, documentStyle)
|
||||
if (theme.chat) setChatTheme(theme.chat, documentStyle)
|
||||
}
|
||||
|
||||
const setGeneralTheme = (
|
||||
generalTheme: GeneralTheme,
|
||||
documentStyle: CSSStyleDeclaration
|
||||
) => {
|
||||
const { background, font } = generalTheme
|
||||
if (background) setTypebotBackground
|
||||
if (font) documentStyle.setProperty(cssVariableNames.general.fontFamily, font)
|
||||
}
|
||||
|
||||
const setChatTheme = (
|
||||
chatTheme: ChatTheme,
|
||||
documentStyle: CSSStyleDeclaration
|
||||
) => {
|
||||
const { hostBubbles, guestBubbles, buttons, inputs } = chatTheme
|
||||
if (hostBubbles) setHostBubbles(hostBubbles, documentStyle)
|
||||
if (guestBubbles) setGuestBubbles(guestBubbles, documentStyle)
|
||||
if (buttons) setButtons(buttons, documentStyle)
|
||||
if (inputs) setInputs(inputs, documentStyle)
|
||||
}
|
||||
|
||||
const setHostBubbles = (
|
||||
hostBubbles: ContainerColors,
|
||||
documentStyle: CSSStyleDeclaration
|
||||
) => {
|
||||
if (hostBubbles.backgroundColor)
|
||||
documentStyle.setProperty(
|
||||
cssVariableNames.chat.hostBubbles.bgColor,
|
||||
hostBubbles.backgroundColor
|
||||
)
|
||||
if (hostBubbles.color)
|
||||
documentStyle.setProperty(
|
||||
cssVariableNames.chat.hostBubbles.color,
|
||||
hostBubbles.color
|
||||
)
|
||||
}
|
||||
|
||||
const setGuestBubbles = (
|
||||
guestBubbles: ContainerColors,
|
||||
documentStyle: CSSStyleDeclaration
|
||||
) => {
|
||||
if (guestBubbles.backgroundColor)
|
||||
documentStyle.setProperty(
|
||||
cssVariableNames.chat.guestBubbles.bgColor,
|
||||
guestBubbles.backgroundColor
|
||||
)
|
||||
if (guestBubbles.color)
|
||||
documentStyle.setProperty(
|
||||
cssVariableNames.chat.guestBubbles.color,
|
||||
guestBubbles.color
|
||||
)
|
||||
}
|
||||
|
||||
const setButtons = (
|
||||
buttons: ContainerColors,
|
||||
documentStyle: CSSStyleDeclaration
|
||||
) => {
|
||||
if (buttons.backgroundColor)
|
||||
documentStyle.setProperty(
|
||||
cssVariableNames.chat.buttons.bgColor,
|
||||
buttons.backgroundColor
|
||||
)
|
||||
if (buttons.color)
|
||||
documentStyle.setProperty(
|
||||
cssVariableNames.chat.buttons.color,
|
||||
buttons.color
|
||||
)
|
||||
}
|
||||
|
||||
const setInputs = (inputs: InputColors, documentStyle: CSSStyleDeclaration) => {
|
||||
if (inputs.backgroundColor)
|
||||
documentStyle.setProperty(
|
||||
cssVariableNames.chat.inputs.bgColor,
|
||||
inputs.backgroundColor
|
||||
)
|
||||
if (inputs.color)
|
||||
documentStyle.setProperty(cssVariableNames.chat.inputs.color, inputs.color)
|
||||
if (inputs.placeholderColor)
|
||||
documentStyle.setProperty(
|
||||
cssVariableNames.chat.inputs.placeholderColor,
|
||||
inputs.placeholderColor
|
||||
)
|
||||
}
|
||||
|
||||
const setTypebotBackground = (
|
||||
background: Background,
|
||||
documentStyle: CSSStyleDeclaration
|
||||
) => {
|
||||
documentStyle.setProperty(
|
||||
background?.type === BackgroundType.IMAGE
|
||||
? cssVariableNames.general.bgImage
|
||||
: cssVariableNames.general.bgColor,
|
||||
background.type === BackgroundType.NONE
|
||||
? 'transparent'
|
||||
: background.content ?? '#ffffff'
|
||||
)
|
||||
}
|
||||
1
packages/bot-engine/src/features/variables/index.ts
Normal file
1
packages/bot-engine/src/features/variables/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from './utils'
|
||||
80
packages/bot-engine/src/features/variables/utils.ts
Normal file
80
packages/bot-engine/src/features/variables/utils.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import { Variable, VariableWithValue } from 'models'
|
||||
import { isDefined, isNotDefined } from 'utils'
|
||||
|
||||
export const stringContainsVariable = (str: string): boolean =>
|
||||
/\{\{(.*?)\}\}/g.test(str)
|
||||
|
||||
export const parseVariables =
|
||||
(
|
||||
variables: Variable[],
|
||||
options: { fieldToParse?: 'value' | 'id'; escapeForJson?: boolean } = {
|
||||
fieldToParse: 'value',
|
||||
escapeForJson: false,
|
||||
}
|
||||
) =>
|
||||
(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)
|
||||
}) as VariableWithValue | undefined
|
||||
if (!variable) return ''
|
||||
if (options.fieldToParse === 'id') return variable.id
|
||||
const { value } = variable
|
||||
if (options.escapeForJson) return jsonParse(value)
|
||||
const parsedValue = safeStringify(value)
|
||||
if (!parsedValue) return ''
|
||||
return parsedValue
|
||||
})
|
||||
}
|
||||
|
||||
export const safeStringify = (val: unknown): string | null => {
|
||||
if (isNotDefined(val)) return null
|
||||
if (typeof val === 'string') return val
|
||||
try {
|
||||
return JSON.stringify(val)
|
||||
} catch {
|
||||
console.warn('Failed to safely stringify variable value', val)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const parseCorrectValueType = (
|
||||
value: Variable['value']
|
||||
): string | boolean | number | null | undefined => {
|
||||
if (value === null) return null
|
||||
if (value === undefined) return undefined
|
||||
const isNumberStartingWithZero =
|
||||
value.startsWith('0') && !value.startsWith('0.') && value.length > 1
|
||||
if (typeof value === 'string' && isNumberStartingWithZero) return value
|
||||
if (typeof value === 'number') return value
|
||||
if (value === 'true') return true
|
||||
if (value === 'false') return false
|
||||
if (value === 'null') return null
|
||||
if (value === 'undefined') return undefined
|
||||
// isNaN works with strings
|
||||
if (isNaN(value as unknown as number)) return value
|
||||
return Number(value)
|
||||
}
|
||||
|
||||
const jsonParse = (str: string) =>
|
||||
str
|
||||
.replace(/\n/g, `\\n`)
|
||||
.replace(/"/g, `\\"`)
|
||||
.replace(/\\[^n"]/g, `\\\\ `)
|
||||
|
||||
export const parseVariablesInObject = (
|
||||
object: { [key: string]: string | number },
|
||||
variables: Variable[]
|
||||
) =>
|
||||
Object.keys(object).reduce((newObj, key) => {
|
||||
const currentValue = object[key]
|
||||
return {
|
||||
...newObj,
|
||||
[key]:
|
||||
typeof currentValue === 'string'
|
||||
? parseVariables(variables)(currentValue)
|
||||
: currentValue,
|
||||
}
|
||||
}, {})
|
||||
Reference in New Issue
Block a user