import { Fragment, useEffect, useRef, useState } from '@wordpress/element' import { __ } from '@wordpress/i18n' import { Icon } from '@wordpress/icons' import { Error } from '@chat/components/dialog/Error' import { useAnswer } from '@chat/hooks/useAnswer' import { robot, send } from '@chat/svg' import classnames from 'classnames' export const Answer = ({ question, reset, answerId, questionLoading, questionError, }) => { const [status, setStatus] = useState(null) const [displayedAnswer, setDisplayedAnswer] = useState('') const { data, error } = useAnswer(answerId ?? null, status) const { answer, loading, status: answerStatus } = data ?? {} const scrollRef = useRef(null) useEffect(() => setStatus(answerStatus), [answerStatus]) useEffect(() => { if (!answer) return const words = answer.slice(displayedAnswer.length).trim().split(' ') const nextWord = words[0] if (!nextWord) return const retryTime = [75, 75, 75, 150, 300].at( Math.floor(Math.random() * 5), ) const timer = setTimeout(() => { setDisplayedAnswer((prev) => prev + (prev ? ' ' : '') + nextWord) if (scrollRef.current) { scrollRef.current.scrollTo({ top: scrollRef.current.scrollHeight, behavior: 'smooth', }) } }, retryTime) return () => clearTimeout(timer) }, [answer, status, displayedAnswer]) return ( <>
{questionError ? ( ) : (

{question}

)}
{(status || loading || error) && (
{error ? ( ) : (

{displayedAnswer ? ( displayedAnswer .split('\n') .map((line, index) => ( {line}
)) ) : ( ... )}

)}
)}
) }