Skip to content

Commit

Permalink
🚸 (js) Display last input if send message errored
Browse files Browse the repository at this point in the history
  • Loading branch information
baptisteArno committed Apr 3, 2023
1 parent a5d3f83 commit 9f8398b
Show file tree
Hide file tree
Showing 7 changed files with 38 additions and 18 deletions.
8 changes: 7 additions & 1 deletion packages/embeds/js/src/components/Bot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,17 @@ export const Bot = (props: BotProps & { class?: string }) => {
},
})
if (error && 'code' in error && typeof error.code === 'string') {
if (typeof props.typebot !== 'string' || (props.isPreview ?? false)) {
setError(
new Error('An error occurred while loading the bot.', {
cause: error.message,
})
)
}
if (['BAD_REQUEST', 'FORBIDDEN'].includes(error.code))
setError(new Error('This bot is now closed.'))
if (error.code === 'NOT_FOUND')
setError(new Error("The bot you're looking for doesn't exist."))
return
}

if (!data) return setError(new Error("Error! Couldn't initiate the chat."))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ type Props = Pick<ChatReply, 'messages' | 'input'> & {
inputIndex: number
context: BotContext
isLoadingBubbleDisplayed: boolean
hasError: boolean
onNewBubbleDisplayed: (blockId: string) => Promise<void>
onScrollToBottom: () => void
onSubmit: (input: string) => void
Expand Down Expand Up @@ -90,6 +91,7 @@ export const ChatChunk = (props: Props) => {
isInputPrefillEnabled={
props.settings.general.isInputPrefillEnabled ?? true
}
hasError={props.hasError}
/>
)}
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ export const ConversationContainer = (props: Props) => {
const [theme, setTheme] = createSignal(props.initialChatReply.typebot.theme)
const [isSending, setIsSending] = createSignal(false)
const [blockedPopupUrl, setBlockedPopupUrl] = createSignal<string>()
const [hasError, setHasError] = createSignal(false)

onMount(() => {
;(async () => {
Expand All @@ -82,19 +83,30 @@ export const ConversationContainer = (props: Props) => {
})

const sendMessage = async (message: string | undefined) => {
setHasError(false)
const currentBlockId = [...chatChunks()].pop()?.input?.id
if (currentBlockId && props.onAnswer && message)
props.onAnswer({ message, blockId: currentBlockId })
const longRequest = setTimeout(() => {
setIsSending(true)
}, 1000)
const data = await sendMessageQuery({
const { data, error } = await sendMessageQuery({
apiHost: props.context.apiHost,
sessionId: props.initialChatReply.sessionId,
message,
})
clearTimeout(longRequest)
setIsSending(false)
if (error) {
setHasError(true)
props.onNewLogs?.([
{
description: 'Error while sending message',
details: error,
status: 'error',
},
])
}
if (!data) return
if (data.logs) props.onNewLogs?.(data.logs)
if (data.dynamicTheme) setDynamicTheme(data.dynamicTheme)
Expand Down Expand Up @@ -174,6 +186,7 @@ export const ConversationContainer = (props: Props) => {
onScrollToBottom={autoScrollToBottom}
onSkip={handleSkip}
context={props.context}
hasError={hasError() && index() === chatChunks().length - 1}
/>
)}
</For>
Expand Down
1 change: 1 addition & 0 deletions packages/embeds/js/src/components/ErrorMessage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export const ErrorMessage = (props: Props) => {
return (
<div class="h-full flex justify-center items-center flex-col">
<p class="text-2xl text-center">{props.error.message}</p>
<p class="text-center">{props.error.cause as string}</p>
</div>
)
}
17 changes: 8 additions & 9 deletions packages/embeds/js/src/components/InputChatBlock.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ type Props = {
inputIndex: number
context: BotContext
isInputPrefillEnabled: boolean
hasError: boolean
onSubmit: (answer: string) => void
onSkip: () => void
}
Expand All @@ -56,16 +57,14 @@ export const InputChatBlock = (props: Props) => {

return (
<Switch>
<Match when={answer()} keyed>
{(answer) => (
<GuestBubble
message={answer}
showAvatar={props.guestAvatar?.isEnabled ?? false}
avatarSrc={props.guestAvatar?.url && props.guestAvatar.url}
/>
)}
<Match when={answer() && !props.hasError}>
<GuestBubble
message={answer() as string}
showAvatar={props.guestAvatar?.isEnabled ?? false}
avatarSrc={props.guestAvatar?.url && props.guestAvatar.url}
/>
</Match>
<Match when={isNotDefined(answer())}>
<Match when={isNotDefined(answer()) || props.hasError}>
<div
class="flex justify-end animate-fade-in"
data-blockid={props.block.id}
Expand Down
9 changes: 3 additions & 6 deletions packages/embeds/js/src/queries/sendMessageQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,12 @@ import { guessApiHost } from '@/utils/guessApiHost'
import type { ChatReply, SendMessageInput } from '@typebot.io/schemas'
import { isNotEmpty, sendRequest } from '@typebot.io/lib'

export async function sendMessageQuery({
export const sendMessageQuery = ({
apiHost,
...body
}: SendMessageInput & { apiHost?: string }) {
const response = await sendRequest<ChatReply>({
}: SendMessageInput & { apiHost?: string }) =>
sendRequest<ChatReply>({
method: 'POST',
url: `${isNotEmpty(apiHost) ? apiHost : guessApiHost()}/api/v1/sendMessage`,
body,
})

return response.data
}
4 changes: 3 additions & 1 deletion packages/embeds/js/src/utils/guessApiHost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@ import { env } from '@typebot.io/lib'
const cloudViewerUrl = 'https://viewer.typebot.io'

export const guessApiHost = () =>
env('VIEWER_URL')?.split(',')[0] ?? cloudViewerUrl
env('VIEWER_INTERNAL_URL') ??
env('VIEWER_URL')?.split(',')[0] ??
cloudViewerUrl

4 comments on commit 9f8398b

@vercel
Copy link

@vercel vercel bot commented on 9f8398b Apr 3, 2023

Choose a reason for hiding this comment

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

Successfully deployed to the following URLs:

docs – ./apps/docs

docs-typebot-io.vercel.app
docs.typebot.io
docs-git-main-typebot-io.vercel.app

@vercel
Copy link

@vercel vercel bot commented on 9f8398b Apr 3, 2023

Choose a reason for hiding this comment

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

Successfully deployed to the following URLs:

viewer-v2 – ./apps/viewer

pantherview.cr8.ai
positivobra.com.br
rollingball.cr8.ai
survey.digienge.io
this-is-a-test.com
zap.techadviser.in
ai.digitaldaftar.in
bot.boston-voip.com
bot.cabinpromos.com
bot.carnaval.studio
bot.digitalbled.com
bot.dsignagency.com
bolsamaisbrasil.app.br
bot.ilmuseoaiborghi.it
bot.louismarcondes.com
bot.pratikmandalia.com
bot.t20worldcup.com.au
bot2.mycompany.reviews
bot3.mycompany.reviews
bot4.mycompany.reviews
c23111azqw.nigerias.io
chat.footballmeetup.ie
dieta.barrettamario.it
felipewelington.com.br
form.bridesquadapp.com
form.searchcube.com.sg
gcase.barrettamario.it
help.giversforgood.com
info.clickasuransi.com
kodawariab736.skeep.it
michaeljackson.riku.ai
premium.kandabrand.com
report.gratirabbit.com
resume.gratirabbit.com
83242573.actualizar.xyz
87656003.actualizar.xyz
88152257.actualizar.xyz
91375310.actualizar.xyz
arrivalx2.wpwakanda.com
bot.blackboxtips.com.br
bot.hotelplayarimini.it
bot.upgradesolutions.eu
bots.baptiste-arnaud.fr
help.comebackreward.com
link.venturasuceder.com
mainmenu.diddancing.com
manualhandlingcourse.ie
primitive-shapes.cr8.ai
register.kandabrand.com
signup.hypemarketing.in
subfooter.wpwakanda.com
survey.hypemarketing.in
testbot.afterorigin.com
typebot.influencer.love
www.chatgpt-biliran.com
91181264.your-access.one
abg-assistent.m-vogel.de
ai.chromebookstoreph.com
contextone.wpwakanda.com
bot.polychromes-project.com
bot.seidinembroseanchetu.it
chat.semanalimpanome.com.br
designguide.techyscouts.com
liveconvert2.kandalearn.com
presente.empresarias.com.mx
register.algorithmpress.com
sell.sellthemotorhome.co.uk
anamnese.odontopavani.com.br
austin.channelautomation.com
bot.marketingplusmindset.com
bot.seidibergamoseanchetu.it
desabafe.sergiolimajr.com.br
download.venturemarketing.in
piazzatorre.barrettamario.it
type.cookieacademyonline.com
upload.atlasoutfittersk9.com
bot.brigadeirosemdrama.com.br
forms.escoladeautomacao.com.br
onboarding.libertydreamcare.ie
type.talitasouzamarques.com.br
agendamento.sergiolimajr.com.br
anamnese.clinicamegasjdr.com.br
bookings.littlepartymonkeys.com
bot.comercializadoraomicron.com
elevateyourmind.groovepages.com
viewer-v2-typebot-io.vercel.app
yourfeedback.comebackreward.com
bot.cabin-rentals-of-georgia.net
gerador.verificadordehospedes.com
personal-trainer.barrettamario.it
preagendamento.sergiolimajr.com.br
studiotecnicoimmobiliaremerelli.it
download.thailandmicespecialist.com
register.thailandmicespecialist.com
bot.studiotecnicoimmobiliaremerelli.it
pesquisa.escolamodacomproposito.com.br
anamnese.clinicaramosodontologia.com.br
chrome-os-inquiry-system.itschromeos.com
viewer-v2-git-main-typebot-io.vercel.app
main-menu-for-itschromeos.itschromeos.com

@vercel
Copy link

@vercel vercel bot commented on 9f8398b Apr 3, 2023

Choose a reason for hiding this comment

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

Successfully deployed to the following URLs:

builder-v2 – ./apps/builder

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

@vercel
Copy link

@vercel vercel bot commented on 9f8398b Apr 3, 2023

Choose a reason for hiding this comment

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

Please sign in to comment.