2023-07-15 12:26:12 +02:00
|
|
|
import React, { useCallback, useEffect, useRef } from 'react'
|
2023-01-09 14:51:36 +01:00
|
|
|
import type { BubbleProps } from '@typebot.io/js'
|
2023-07-15 12:26:12 +02:00
|
|
|
import '@typebot.io/js/dist/web'
|
2023-01-16 12:13:21 +01:00
|
|
|
|
2023-01-25 11:27:47 +01:00
|
|
|
type Props = BubbleProps
|
2023-01-09 14:51:36 +01:00
|
|
|
|
|
|
|
|
declare global {
|
|
|
|
|
namespace JSX {
|
|
|
|
|
interface IntrinsicElements {
|
|
|
|
|
'typebot-bubble': React.DetailedHTMLProps<
|
|
|
|
|
React.HTMLAttributes<HTMLElement>,
|
|
|
|
|
HTMLElement
|
2023-03-31 08:45:42 +02:00
|
|
|
>
|
2023-01-09 14:51:36 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-01-25 11:27:47 +01:00
|
|
|
type BubbleElement = HTMLElement & Props
|
|
|
|
|
|
|
|
|
|
export const Bubble = (props: Props) => {
|
2023-07-25 09:12:53 +02:00
|
|
|
const bubbleElement = useRef<BubbleElement | null>(null)
|
2023-01-16 12:13:21 +01:00
|
|
|
|
2023-02-21 08:28:36 +01:00
|
|
|
const attachBubbleToDom = useCallback((props: Props) => {
|
2023-07-25 09:12:53 +02:00
|
|
|
const newBubbleElement = document.createElement(
|
2023-01-25 11:27:47 +01:00
|
|
|
'typebot-bubble'
|
|
|
|
|
) as BubbleElement
|
2023-07-25 09:12:53 +02:00
|
|
|
bubbleElement.current = newBubbleElement
|
|
|
|
|
injectPropsToElement(bubbleElement.current, props)
|
2023-12-13 14:47:06 +01:00
|
|
|
document.body.prepend(bubbleElement.current)
|
2023-02-21 08:28:36 +01:00
|
|
|
}, [])
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
2023-07-25 09:12:53 +02:00
|
|
|
if (!bubbleElement.current) attachBubbleToDom(props)
|
|
|
|
|
injectPropsToElement(bubbleElement.current as BubbleElement, props)
|
2023-07-15 12:26:12 +02:00
|
|
|
}, [attachBubbleToDom, props])
|
2023-02-21 08:28:36 +01:00
|
|
|
|
2023-07-25 09:12:53 +02:00
|
|
|
useEffect(() => {
|
|
|
|
|
return () => {
|
|
|
|
|
bubbleElement.current?.remove()
|
|
|
|
|
bubbleElement.current = null
|
|
|
|
|
}
|
|
|
|
|
}, [])
|
|
|
|
|
|
2023-02-21 08:28:36 +01:00
|
|
|
const injectPropsToElement = (element: BubbleElement, props: Props) => {
|
|
|
|
|
Object.assign(element, props)
|
2023-01-25 11:27:47 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return null
|
2023-01-09 14:51:36 +01:00
|
|
|
}
|
2023-07-15 12:26:12 +02:00
|
|
|
|
|
|
|
|
export default Bubble
|