|
| 1 | +import { useEffect, useRef, useState } from 'react'; |
| 2 | + |
| 3 | +import type { DefaultStreamChatGenerics } from '../../../types/types'; |
| 4 | +import type { StreamedMessageTextProps } from '../StreamedMessageText'; |
| 5 | + |
| 6 | +export type UseMessageTextStreamingProps< |
| 7 | + StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics |
| 8 | +> = Pick< |
| 9 | + StreamedMessageTextProps<StreamChatGenerics>, |
| 10 | + 'streamingLetterIntervalMs' | 'renderingLetterCount' |
| 11 | +> & { text: string }; |
| 12 | + |
| 13 | +const DEFAULT_LETTER_INTERVAL = 30; |
| 14 | +const DEFAULT_RENDERING_LETTER_COUNT = 2; |
| 15 | + |
| 16 | +/** |
| 17 | + * A hook that returns text in a streamed, typewriter fashion. The speed of streaming is |
| 18 | + * configurable. |
| 19 | + * @param {number} [streamingLetterIntervalMs=30] - The timeout between each typing animation in milliseconds. |
| 20 | + * @param {number} [renderingLetterCount=2] - The number of letters to be rendered each time we update. |
| 21 | + * @param {string} text - The text that we want to render in a typewriter fashion. |
| 22 | + * @returns {{ streamedMessageText: string }} - A substring of the text property, up until we've finished rendering the typewriter animation. |
| 23 | + */ |
| 24 | +export const useMessageTextStreaming = < |
| 25 | + StreamChatGenerics extends DefaultStreamChatGenerics = DefaultStreamChatGenerics |
| 26 | +>({ |
| 27 | + streamingLetterIntervalMs = DEFAULT_LETTER_INTERVAL, |
| 28 | + renderingLetterCount = DEFAULT_RENDERING_LETTER_COUNT, |
| 29 | + text, |
| 30 | +}: UseMessageTextStreamingProps<StreamChatGenerics>): { streamedMessageText: string } => { |
| 31 | + const [streamedMessageText, setStreamedMessageText] = useState<string>(text); |
| 32 | + const textCursor = useRef<number>(text.length); |
| 33 | + |
| 34 | + useEffect(() => { |
| 35 | + const textLength = text.length; |
| 36 | + const interval = setInterval(() => { |
| 37 | + if (!text || textCursor.current >= textLength) { |
| 38 | + clearInterval(interval); |
| 39 | + } |
| 40 | + const newCursorValue = textCursor.current + renderingLetterCount; |
| 41 | + const newText = text.substring(0, newCursorValue); |
| 42 | + textCursor.current += newText.length - textCursor.current; |
| 43 | + setStreamedMessageText(newText); |
| 44 | + }, streamingLetterIntervalMs); |
| 45 | + |
| 46 | + return () => { |
| 47 | + clearInterval(interval); |
| 48 | + }; |
| 49 | + }, [streamingLetterIntervalMs, renderingLetterCount, text]); |
| 50 | + |
| 51 | + return { streamedMessageText }; |
| 52 | +}; |
0 commit comments