Add a loading indicator at the end of a streamed message string while it types
Unanswered
Black-throated Gray Warbler posted this in #help-forum
Black-throated Gray WarblerOP
The following code works great for animating the streamed message that arrives from the Open AI:s API, but I want to add a loading indicator that has the same function as a cursor at the end of the message while it's typing, just like ChatGPT has. Does anyone know how to achieve this?
const MemoizedContent = React.memo(({ role, htmlContent, isStreaming, messageId }) => {
const [displayContent, setDisplayContent] = useState('');
const contentRef = useRef(null);
const lastUpdateRef = useRef(0);
const animationFrameRef = useRef(null);
useEffect(() => {
if (!isStreaming) {
setDisplayContent(htmlContent);
return;
}
const updateContent = (timestamp) => {
if (timestamp - lastUpdateRef.current > 1) { // Increased speed
const charsToAdd = Math.min(1, htmlContent.length - displayContent.length); // Add up to 5 chars at once
const newContent = htmlContent.slice(0, displayContent.length + charsToAdd);
setDisplayContent(newContent);
lastUpdateRef.current = timestamp;
}
if (displayContent.length < htmlContent.length) {
animationFrameRef.current = requestAnimationFrame(updateContent);
}
};
animationFrameRef.current = requestAnimationFrame(updateContent);
return () => {
if (animationFrameRef.current) {
cancelAnimationFrame(animationFrameRef.current);
}
};
}, [htmlContent, isStreaming, displayContent]);
useEffect(() => {
if (contentRef.current) {
contentRef.current.scrollTop = contentRef.current.scrollHeight;
}
}, [displayContent]);
return (
<Paper
ref={contentRef}
>
<Typography
variant="body1" >
<span dangerouslySetInnerHTML={{ __html: displayContent }} />
{isStreaming && displayContent.length < htmlContent.length}
</Typography>
</Paper>
);
});