2
0

🐛 Improve bot libs mount in prod env

This commit is contained in:
Baptiste Arnaud
2023-02-21 08:28:36 +01:00
parent 46bf25a580
commit 907cad8050
11 changed files with 78 additions and 71 deletions

View File

@ -1,4 +1,4 @@
import { useEffect, useRef } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import type { BubbleProps } from '@typebot.io/js'
type Props = BubbleProps
@ -18,33 +18,32 @@ type BubbleElement = HTMLElement & Props
export const Bubble = (props: Props) => {
const ref = useRef<BubbleElement | null>(null)
const [isInitialized, setIsInitialized] = useState(false)
useEffect(() => {
;(async () => {
await import('@typebot.io/js/dist/web')
initBubble()
setIsInitialized(true)
})()
return () => {
ref.current?.remove()
}
}, [])
useEffect(() => {
updateProps(ref.current, props)
}, [props])
const updateProps = (element: BubbleElement | null, props: Props) => {
if (!element) return
Object.assign(element, props)
}
const initBubble = async () => {
const attachBubbleToDom = useCallback((props: Props) => {
const bubbleElement = document.createElement(
'typebot-bubble'
) as BubbleElement
if (ref.current) return
ref.current = bubbleElement
injectPropsToElement(ref.current, props)
document.body.append(ref.current)
}, [])
useEffect(() => {
if (!isInitialized) return
if (!ref.current) attachBubbleToDom(props)
injectPropsToElement(ref.current as BubbleElement, props)
}, [attachBubbleToDom, isInitialized, props])
const injectPropsToElement = (element: BubbleElement, props: Props) => {
Object.assign(element, props)
}
return null