2023-10-03 12:25:16 +03:00
|
|
|
import { useEffect, useState } from "react";
|
|
|
|
|
2023-10-03 19:26:40 +03:00
|
|
|
type UseStreamTextProps = {
|
|
|
|
text: string;
|
|
|
|
enabled?: boolean;
|
2023-10-04 17:26:56 +03:00
|
|
|
shouldStream?: boolean;
|
2023-10-03 19:26:40 +03:00
|
|
|
};
|
2023-10-03 12:25:16 +03:00
|
|
|
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
|
2023-10-04 17:26:56 +03:00
|
|
|
export const useStreamText = ({
|
|
|
|
text,
|
|
|
|
enabled = true,
|
|
|
|
shouldStream = true,
|
|
|
|
}: UseStreamTextProps) => {
|
2023-10-03 12:25:16 +03:00
|
|
|
const [streamingText, setStreamingText] = useState<string>("");
|
2023-10-12 10:39:56 +03:00
|
|
|
const [lastStreamIndex, setLastStreamIndex] = useState(0);
|
2023-10-03 12:25:16 +03:00
|
|
|
|
2023-10-12 10:39:56 +03:00
|
|
|
const isDone = lastStreamIndex === text.length;
|
|
|
|
|
|
|
|
const lastStream = !isDone ? text[lastStreamIndex] : "";
|
2023-10-03 12:25:16 +03:00
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (!enabled) {
|
|
|
|
setStreamingText("");
|
|
|
|
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-10-04 17:26:56 +03:00
|
|
|
if (!shouldStream) {
|
|
|
|
setStreamingText(text);
|
2023-10-12 10:39:56 +03:00
|
|
|
setLastStreamIndex(text.length);
|
2023-10-04 17:26:56 +03:00
|
|
|
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-10-03 12:25:16 +03:00
|
|
|
const messageInterval = setInterval(() => {
|
2023-10-12 10:39:56 +03:00
|
|
|
if (lastStreamIndex < text.length) {
|
|
|
|
setStreamingText(
|
|
|
|
(prevText) => prevText + (text[lastStreamIndex] ?? "")
|
|
|
|
);
|
|
|
|
setLastStreamIndex((prevIndex) => prevIndex + 1);
|
2023-10-03 12:25:16 +03:00
|
|
|
} else {
|
|
|
|
clearInterval(messageInterval);
|
|
|
|
}
|
|
|
|
}, 30);
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
clearInterval(messageInterval);
|
|
|
|
};
|
2023-10-12 10:39:56 +03:00
|
|
|
}, [text, lastStreamIndex, enabled, shouldStream]);
|
2023-10-03 12:25:16 +03:00
|
|
|
|
2023-10-12 10:39:56 +03:00
|
|
|
return { streamingText, isDone, lastStream };
|
2023-10-03 12:25:16 +03:00
|
|
|
};
|