2
0

♻️ (bot) Change to features-centric folder structure

This commit is contained in:
Baptiste Arnaud
2022-11-15 14:59:34 +01:00
committed by Baptiste Arnaud
parent a5c8a8a95c
commit 972094425a
92 changed files with 1245 additions and 943 deletions

View File

@@ -1,23 +1,22 @@
import React, { useState } from 'react'
import { useAnswers } from '../../../contexts/AnswersContext'
import { useAnswers } from '../../../providers/AnswersProvider'
import { InputBlock, InputBlockType } from 'models'
import { GuestBubble } from './bubbles/GuestBubble'
import { TextForm } from './inputs/TextForm'
import { byId } from 'utils'
import { DateForm } from './inputs/DateForm'
import { ChoiceForm } from './inputs/ChoiceForm'
import { useTypebot } from 'contexts/TypebotContext'
import { parseVariables } from '../../../services/variable'
import { isInputValid } from 'services/inputs'
import { PaymentForm } from './inputs/PaymentForm'
import { RatingForm } from './inputs/RatingForm'
import { FileUploadForm } from './inputs/FileUploadForm'
export type InputSubmitContent = {
label?: string
value: string
itemId?: string
}
import { InputSubmitContent } from '@/types'
import { useTypebot } from '@/providers/TypebotProvider'
import { isInputValid } from '@/utils/inputs'
import { parseVariables } from '@/features/variables'
import { TextInput } from '@/features/blocks/inputs/textInput'
import { NumberInput } from '@/features/blocks/inputs/number'
import { EmailInput } from '@/features/blocks/inputs/email'
import { UrlInput } from '@/features/blocks/inputs/url'
import { PhoneInput } from '@/features/blocks/inputs/phone'
import { DateForm } from '@/features/blocks/inputs/date'
import { ChoiceForm } from '@/features/blocks/inputs/buttons'
import { PaymentForm } from '@/features/blocks/inputs/payment'
import { RatingForm } from '@/features/blocks/inputs/rating'
import { FileUploadForm } from '@/features/blocks/inputs/fileUpload'
export const InputChatBlock = ({
block,
@@ -111,12 +110,44 @@ const Input = ({
}) => {
switch (block.type) {
case InputBlockType.TEXT:
return (
<TextInput
block={block}
onSubmit={onSubmit}
defaultValue={defaultValue}
hasGuestAvatar={hasGuestAvatar}
/>
)
case InputBlockType.NUMBER:
return (
<NumberInput
block={block}
onSubmit={onSubmit}
defaultValue={defaultValue}
hasGuestAvatar={hasGuestAvatar}
/>
)
case InputBlockType.EMAIL:
return (
<EmailInput
block={block}
onSubmit={onSubmit}
defaultValue={defaultValue}
hasGuestAvatar={hasGuestAvatar}
/>
)
case InputBlockType.URL:
return (
<UrlInput
block={block}
onSubmit={onSubmit}
defaultValue={defaultValue}
hasGuestAvatar={hasGuestAvatar}
/>
)
case InputBlockType.PHONE:
return (
<TextForm
<PhoneInput
block={block}
onSubmit={onSubmit}
defaultValue={defaultValue}

View File

@@ -1,77 +0,0 @@
import React, { useEffect, useMemo, useRef, useState } from 'react'
import { EmbedBubbleBlock } from 'models'
import { TypingContent } from './TypingContent'
import { parseVariables } from 'services/variable'
import { useTypebot } from 'contexts/TypebotContext'
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 ? <TypingContent /> : <></>}
</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>
)
}

View File

@@ -1,4 +1,4 @@
import { Avatar } from 'components/avatars/Avatar'
import { Avatar } from '@/components/avatars/Avatar'
import React, { useState } from 'react'
import { CSSTransition } from 'react-transition-group'

View File

@@ -1,9 +1,9 @@
import { EmbedBubble } from '@/features/blocks/bubbles/embed'
import { ImageBubble } from '@/features/blocks/bubbles/image'
import { TextBubble } from '@/features/blocks/bubbles/textBubble'
import { VideoBubble } from '@/features/blocks/bubbles/video'
import { BubbleBlock, BubbleBlockType } from 'models'
import React from 'react'
import { EmbedBubble } from './EmbedBubble'
import { ImageBubble } from './ImageBubble'
import { TextBubble } from './TextBubble'
import { VideoBubble } from './VideoBubble'
type Props = {
block: BubbleBlock

View File

@@ -1,84 +0,0 @@
import React, { useEffect, useMemo, useRef, useState } from 'react'
import { useTypebot } from 'contexts/TypebotContext'
import { ImageBubbleBlock } from 'models'
import { TypingContent } from './TypingContent'
import { parseVariables } from 'services/variable'
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 ? <TypingContent /> : <></>}
</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>
)
}

View File

@@ -1,81 +0,0 @@
import React, { useEffect, useRef, useState } from 'react'
import { useTypebot } from 'contexts/TypebotContext'
import { BubbleBlockType, TextBubbleBlock } from 'models'
import { computeTypingTimeout } from 'services/chat'
import { TypingContent } from './TypingContent'
import { parseVariables } from 'services/variable'
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 = computeTypingTimeout(
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 ? <TypingContent /> : <></>}
</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>
)
}

View File

@@ -1,125 +0,0 @@
import React, { useEffect, useMemo, useRef, useState } from 'react'
import { useTypebot } from 'contexts/TypebotContext'
import {
Variable,
VideoBubbleContent,
VideoBubbleContentType,
VideoBubbleBlock,
} from 'models'
import { TypingContent } from './TypingContent'
import { parseVariables } from 'services/variable'
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 ? <TypingContent /> : <></>}
</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&apos;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
/>
)
}
}
}

View File

@@ -1,94 +0,0 @@
import { useAnswers } from 'contexts/AnswersContext'
import { useTypebot } from 'contexts/TypebotContext'
import { ChoiceInputBlock } from 'models'
import React, { useState } from 'react'
import { parseVariables } from 'services/variable'
import { InputSubmitContent } from '../InputChatBlock'
import { SendButton } from './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>
)
}

View File

@@ -1,86 +0,0 @@
import { DateInputOptions } from 'models'
import React, { useState } from 'react'
import { parseReadableDate } from 'services/inputs'
import { InputSubmitContent } from '../InputChatBlock'
import { SendButton } from './SendButton'
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>
)
}

View File

@@ -1,256 +0,0 @@
import { useAnswers } from 'contexts/AnswersContext'
import { useTypebot } from 'contexts/TypebotContext'
import { FileInputBlock } from 'models'
import React, { ChangeEvent, FormEvent, useState, DragEvent } from 'react'
import { uploadFiles } from 'utils'
import { InputSubmitContent } from '../InputChatBlock'
import { SendButton, Spinner } from './SendButton'
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>
)

View File

@@ -1,15 +0,0 @@
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} />
}
}

View File

@@ -1,195 +0,0 @@
import React, { FormEvent, useEffect, useState } from 'react'
import { useStripe, useElements, PaymentElement } from '@stripe/react-stripe-js'
import { Elements } from '@stripe/react-stripe-js'
import { createPaymentIntent } from 'services/stripe'
import { useTypebot } from 'contexts/TypebotContext'
import { PaymentInputOptions, Variable } from 'models'
import { SendButton, Spinner } from '../SendButton'
import { useFrame } from 'react-frame-component'
import { initStripe } from '../../../../../../lib/stripe'
import { parseVariables } from 'services/variable'
import { useChat } from 'contexts/ChatContext'
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 createPaymentIntent({
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>
)
}

View File

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

View File

@@ -1,107 +0,0 @@
import { RatingInputOptions, RatingInputBlock } from 'models'
import React, { FormEvent, useState } from 'react'
import { isDefined, isEmpty, isNotDefined } from 'utils'
import { InputSubmitContent } from '../InputChatBlock'
import { SendButton } from './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>`

View File

@@ -1,85 +0,0 @@
import {
EmailInputBlock,
InputBlockType,
NumberInputBlock,
PhoneNumberInputBlock,
TextInputBlock,
UrlInputBlock,
} from 'models'
import React, { useRef, useState } from 'react'
import { InputSubmitContent } from '../../InputChatBlock'
import { SendButton } from '../SendButton'
import { TextInput } from './TextInput'
type TextFormProps = {
block:
| TextInputBlock
| EmailInputBlock
| NumberInputBlock
| UrlInputBlock
| PhoneNumberInputBlock
onSubmit: (value: InputSubmitContent) => void
defaultValue?: string
hasGuestAvatar: boolean
}
export const TextForm = ({
block,
onSubmit,
defaultValue,
hasGuestAvatar,
}: TextFormProps) => {
const [inputValue, setInputValue] = useState(defaultValue ?? '')
const inputRef = useRef<HTMLInputElement | null>(null)
const isLongText = block.type === InputBlockType.TEXT && block.options?.isLong
const handleChange = (inputValue: string) => {
if (block.type === InputBlockType.URL && !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 (block.type === InputBlockType.TEXT && block.options.isLong) 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}
>
<TextInput
inputRef={inputRef}
block={block}
onChange={handleChange}
value={inputValue}
/>
<SendButton
type="button"
label={block.options?.labels?.button ?? 'Send'}
isDisabled={inputValue === ''}
className="my-2 ml-2"
onClick={submit}
/>
</div>
)
}

View File

@@ -1,159 +0,0 @@
import {
TextInputBlock,
EmailInputBlock,
NumberInputBlock,
InputBlockType,
UrlInputBlock,
PhoneNumberInputBlock,
} from 'models'
import React, { ChangeEvent, ChangeEventHandler } from 'react'
import PhoneInput, { Value, Country } from 'react-phone-number-input'
import { isMobile } from 'services/utils'
type TextInputProps = {
inputRef: React.RefObject<any>
block:
| TextInputBlock
| EmailInputBlock
| NumberInputBlock
| UrlInputBlock
| PhoneNumberInputBlock
value: string
onChange: (value: string) => void
}
export const TextInput = ({
inputRef,
block,
value,
onChange,
}: TextInputProps) => {
const handleInputChange = (
e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
) => onChange(e.target.value)
const handlePhoneNumberChange = (value?: Value | undefined) => {
onChange(value as string)
}
switch (block.type) {
case InputBlockType.TEXT: {
return block.options?.isLong ? (
<LongTextInput
ref={inputRef}
value={value}
placeholder={
block.options?.labels?.placeholder ?? 'Type your answer...'
}
onChange={handleInputChange}
/>
) : (
<ShortTextInput
ref={inputRef}
value={value}
placeholder={
block.options?.labels?.placeholder ?? 'Type your answer...'
}
onChange={handleInputChange}
// Hack to disable Chrome autocomplete
name="no-name"
/>
)
}
case InputBlockType.EMAIL: {
return (
<ShortTextInput
ref={inputRef}
value={value}
placeholder={
block.options?.labels?.placeholder ?? 'Type your email...'
}
onChange={handleInputChange}
type="email"
autoComplete="email"
/>
)
}
case InputBlockType.NUMBER: {
return (
<ShortTextInput
ref={inputRef}
value={value}
placeholder={
block.options?.labels?.placeholder ?? 'Type your answer...'
}
onChange={handleInputChange}
type="number"
style={{ appearance: 'auto' }}
min={block.options?.min}
max={block.options?.max}
step={block.options?.step ?? 'any'}
/>
)
}
case InputBlockType.URL: {
return (
<ShortTextInput
ref={inputRef}
value={value}
placeholder={block.options?.labels?.placeholder ?? 'Type your URL...'}
onChange={handleInputChange}
type="url"
autoComplete="url"
/>
)
}
case InputBlockType.PHONE: {
return (
<PhoneInput
ref={inputRef}
value={value}
onChange={handlePhoneNumberChange}
placeholder={
block.options.labels.placeholder ?? 'Your phone number...'
}
defaultCountry={block.options.defaultCountryCode as Country}
autoFocus={!isMobile}
/>
)
}
}
}
const ShortTextInput = React.forwardRef(
(
props: React.InputHTMLAttributes<HTMLInputElement>,
ref: React.ForwardedRef<HTMLInputElement>
) => (
<input
ref={ref}
className="focus:outline-none bg-transparent px-4 py-4 flex-1 w-full text-input"
type="text"
style={{ fontSize: '16px' }}
autoFocus={!isMobile}
{...props}
/>
)
)
const LongTextInput = React.forwardRef(
(
props: {
placeholder: string
value: string
onChange: ChangeEventHandler
},
ref: React.ForwardedRef<HTMLTextAreaElement>
) => (
<textarea
ref={ref}
className="focus:outline-none bg-transparent px-4 py-4 flex-1 w-full text-input"
rows={6}
data-testid="textarea"
required
style={{ fontSize: '16px' }}
autoFocus={!isMobile}
{...props}
/>
)
)

View File

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

View File

@@ -1,7 +1,7 @@
import React, { useEffect, useRef, useState } from 'react'
import { TransitionGroup, CSSTransition } from 'react-transition-group'
import { AvatarSideContainer } from './AvatarSideContainer'
import { LinkedTypebot, useTypebot } from '../../contexts/TypebotContext'
import { LinkedTypebot, useTypebot } from '../../providers/TypebotProvider'
import {
isBubbleBlock,
isBubbleBlockType,
@@ -12,11 +12,6 @@ import {
isLogicBlock,
byId,
} from 'utils'
import { executeLogic } from 'services/logic'
import { executeIntegration } from 'services/integration'
import { parseRetryBlock, blockCanBeRetried } from 'services/inputs'
import { parseVariables } from '../../services/variable'
import { useAnswers } from 'contexts/AnswersContext'
import {
BubbleBlock,
InputBlock,
@@ -24,10 +19,16 @@ import {
PublicTypebot,
Block,
} from 'models'
import { useChat } from 'contexts/ChatContext'
import { getLastChatBlockType } from 'services/chat'
import { HostBubble } from './ChatBlock/bubbles/HostBubble'
import { InputChatBlock, InputSubmitContent } from './ChatBlock/InputChatBlock'
import { InputChatBlock } from './ChatBlock/InputChatBlock'
import { parseVariables } from '@/features/variables'
import { useAnswers } from '@/providers/AnswersProvider'
import { useChat } from '@/providers/ChatProvider'
import { InputSubmitContent } from '@/types'
import { getLastChatBlockType } from '@/utils/chat'
import { executeIntegration } from '@/utils/executeIntegration'
import { executeLogic } from '@/utils/executeLogic'
import { blockCanBeRetried, parseRetryBlock } from '@/utils/inputs'
type ChatGroupProps = {
blocks: Block[]

View File

@@ -1,14 +1,13 @@
import React, { useEffect, useRef, useState } from 'react'
import { ChatGroup } from './ChatGroup'
import { useFrame } from 'react-frame-component'
import { setCssVariablesValue } from '../services/theme'
import { useAnswers } from '../contexts/AnswersContext'
import { useAnswers } from '../providers/AnswersProvider'
import { Group, Edge, PublicTypebot, Theme, VariableWithValue } from 'models'
import { byId, isDefined, isInputBlock, isNotDefined } from 'utils'
import { animateScroll as scroll } from 'react-scroll'
import { LinkedTypebot, useTypebot } from 'contexts/TypebotContext'
import { ChatContext } from 'contexts/ChatContext'
import { LinkedTypebot, useTypebot } from '@/providers/TypebotProvider'
import { setCssVariablesValue } from '@/features/theme'
import { ChatProvider } from '@/providers/ChatProvider'
type Props = {
theme: Theme
@@ -139,7 +138,7 @@ export const ConversationContainer = ({
ref={scrollableContainer}
className="overflow-y-scroll w-full lg:w-3/4 min-h-full rounded lg:px-5 px-3 pt-10 relative scrollable-container typebot-chat-view"
>
<ChatContext onScroll={autoScrollToBottom}>
<ChatProvider onScroll={autoScrollToBottom}>
{displayedGroups.map((displayedGroup, idx) => {
const groupAfter = displayedGroups[idx + 1]
const groupAfterStartsWithInput =
@@ -158,7 +157,7 @@ export const ConversationContainer = ({
/>
)
})}
</ChatContext>
</ChatProvider>
{/* We use a block to simulate padding because it makes iOS scroll flicker */}
<div className="w-full h-32" ref={bottomAnchor} />

View File

@@ -1,5 +1,5 @@
import React, { SVGProps } from 'react'
import { SendIcon } from '../../../../assets/icons'
import { SendIcon } from './icons'
type SendButtonProps = {
label: string

View File

@@ -1,11 +1,11 @@
import React, { CSSProperties, useMemo } from 'react'
import { TypebotContext } from '../contexts/TypebotContext'
import { TypebotProvider } from '../providers/TypebotProvider'
import Frame from 'react-frame-component'
import styles from '../assets/style.css'
import importantStyles from '../assets/importantStyles.css'
import phoneSyle from '../assets/phone.css'
import { ConversationContainer } from './ConversationContainer'
import { AnswersContext } from '../contexts/AnswersContext'
import { AnswersProvider } from '../providers/AnswersProvider'
import {
Answer,
BackgroundType,
@@ -89,14 +89,14 @@ export const TypebotViewer = ({
}:wght@300;400;600&display=swap');`,
}}
/>
<TypebotContext
<TypebotProvider
typebot={typebot}
apiHost={apiHost}
isPreview={isPreview}
onNewLog={handleNewLog}
isLoading={isLoading}
>
<AnswersContext
<AnswersProvider
resultId={resultId}
onNewAnswer={handleNewAnswer}
onVariablesUpdated={onVariablesUpdated}
@@ -120,8 +120,8 @@ export const TypebotViewer = ({
</div>
{typebot.settings.general.isBrandingEnabled && <LiteBadge />}
</div>
</AnswersContext>
</TypebotContext>
</AnswersProvider>
</TypebotProvider>
</Frame>
)
}

View File

@@ -1,6 +1,6 @@
import React from 'react'
export const TypingContent = (): JSX.Element => (
export const TypingBubble = (): JSX.Element => (
<div className="flex items-center">
<div className="w-2 h-2 mr-1 rounded-full bubble1" />
<div className="w-2 h-2 mr-1 rounded-full bubble2" />

View File

@@ -0,0 +1,13 @@
import React from 'react'
export const SendIcon = (props: React.SVGProps<SVGSVGElement>) => (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 512 512"
width="19px"
color="white"
{...props}
>
<path d="M476.59 227.05l-.16-.07L49.35 49.84A23.56 23.56 0 0027.14 52 24.65 24.65 0 0016 72.59v113.29a24 24 0 0019.52 23.57l232.93 43.07a4 4 0 010 7.86L35.53 303.45A24 24 0 0016 327v113.31A23.57 23.57 0 0026.59 460a23.94 23.94 0 0013.22 4 24.55 24.55 0 009.52-1.93L476.4 285.94l.19-.09a32 32 0 000-58.8z" />
</svg>
)

View File

@@ -0,0 +1,25 @@
import { isMobile } from '@/utils/helpers'
import React from 'react'
type ShortTextInputProps = {
onChange: (value: string) => void
} & Omit<React.InputHTMLAttributes<HTMLInputElement>, 'onChange'>
export const ShortTextInput = React.forwardRef(
(
{ onChange, ...props }: ShortTextInputProps,
ref: React.ForwardedRef<HTMLInputElement>
) => {
return (
<input
ref={ref}
className="focus:outline-none bg-transparent px-4 py-4 flex-1 w-full text-input"
type="text"
style={{ fontSize: '16px' }}
autoFocus={!isMobile}
onChange={(e) => onChange(e.target.value)}
{...props}
/>
)
}
)

View File

@@ -0,0 +1,25 @@
import { isMobile } from '@/utils/helpers'
import React from 'react'
type TextareaProps = {
onChange: (value: string) => void
} & Omit<React.TextareaHTMLAttributes<HTMLTextAreaElement>, 'onChange'>
export const Textarea = React.forwardRef(
(
{ onChange, ...props }: TextareaProps,
ref: React.ForwardedRef<HTMLTextAreaElement>
) => (
<textarea
ref={ref}
className="focus:outline-none bg-transparent px-4 py-4 flex-1 w-full text-input"
rows={6}
data-testid="textarea"
required
style={{ fontSize: '16px' }}
autoFocus={!isMobile}
onChange={(e) => onChange(e.target.value)}
{...props}
/>
)
)