|
| 1 | +import { useCallback, useEffect, useRef, useState } from 'react' |
| 2 | +import type { BubbleProps } from 'flowise-embed' |
| 3 | + |
| 4 | +type Props = BubbleProps |
| 5 | + |
| 6 | +declare global { |
| 7 | + namespace JSX { |
| 8 | + interface IntrinsicElements { |
| 9 | + 'flowise-bubble': React.DetailedHTMLProps< |
| 10 | + React.HTMLAttributes<HTMLElement>, |
| 11 | + HTMLElement |
| 12 | + > |
| 13 | + } |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +type BubbleElement = HTMLElement & Props |
| 18 | + |
| 19 | +export const BubbleChat = (props: Props) => { |
| 20 | + const ref = useRef<BubbleElement | null>(null) |
| 21 | + const [isInitialized, setIsInitialized] = useState(false) |
| 22 | + |
| 23 | + useEffect(() => { |
| 24 | + ;(async () => { |
| 25 | + await import('flowise-embed/dist/web') |
| 26 | + setIsInitialized(true) |
| 27 | + })() |
| 28 | + return () => { |
| 29 | + ref.current?.remove() |
| 30 | + } |
| 31 | + }, []) |
| 32 | + |
| 33 | + const attachBubbleToDom = useCallback((props: Props) => { |
| 34 | + const bubbleElement = document.createElement( |
| 35 | + 'flowise-bubble' |
| 36 | + ) as BubbleElement |
| 37 | + ref.current = bubbleElement |
| 38 | + injectPropsToElement(ref.current, props) |
| 39 | + document.body.append(ref.current) |
| 40 | + }, []) |
| 41 | + |
| 42 | + useEffect(() => { |
| 43 | + if (!isInitialized) return |
| 44 | + if (!ref.current) attachBubbleToDom(props) |
| 45 | + injectPropsToElement(ref.current as BubbleElement, props) |
| 46 | + }, [attachBubbleToDom, isInitialized, props]) |
| 47 | + |
| 48 | + const injectPropsToElement = (element: BubbleElement, props: Props) => { |
| 49 | + Object.assign(element, props) |
| 50 | + } |
| 51 | + |
| 52 | + return null |
| 53 | +} |
0 commit comments