-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
73 additions
and
43 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
import { useState, useRef, useEffect } from 'react' | ||
|
||
interface StreamTextOptions { | ||
text: string | ||
isStreaming: boolean | ||
streamId?: number | null | ||
speed?: number | ||
} | ||
|
||
export function useStreamText({ | ||
text, | ||
isStreaming, | ||
streamId = null, | ||
speed = 0, | ||
}: StreamTextOptions) { | ||
const [displayedText, setDisplayedText] = useState('') | ||
const lastIndexRef = useRef(0) | ||
const [prevStreamId, setPrevStreamId] = useState<number | null>(null) | ||
|
||
// Reset on new stream | ||
useEffect(() => { | ||
if (streamId && streamId !== prevStreamId) { | ||
setDisplayedText('') | ||
lastIndexRef.current = 0 | ||
setPrevStreamId(streamId) | ||
} | ||
}, [streamId, prevStreamId]) | ||
|
||
// Append text while streaming | ||
useEffect(() => { | ||
if (!isStreaming) return | ||
|
||
const intervalId = setInterval(() => { | ||
if (lastIndexRef.current < text.length) { | ||
setDisplayedText((prev) => { | ||
const nextChar = text[lastIndexRef.current] | ||
lastIndexRef.current += 1 | ||
return prev + nextChar | ||
}) | ||
} | ||
}, speed) | ||
|
||
return () => clearInterval(intervalId) | ||
}, [isStreaming, text, speed]) | ||
|
||
// Ensure full text is displayed when streaming ends | ||
useEffect(() => { | ||
if (!isStreaming && text) { | ||
setDisplayedText(text) | ||
lastIndexRef.current = text.length | ||
} | ||
}, [isStreaming, text]) | ||
|
||
return displayedText | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters