Skip to content

Commit

Permalink
fix: smooth streaming does not work when reloading (#403)
Browse files Browse the repository at this point in the history
  • Loading branch information
Yonom authored Jul 5, 2024
1 parent 1a8919b commit e4890aa
Showing 1 changed file with 9 additions and 11 deletions.
20 changes: 9 additions & 11 deletions packages/react/src/utils/hooks/useSmooth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,17 @@ class TextStreamAnimator {
private lastUpdateTime: number = Date.now();
private decayFactor: number = 0.99;

private _targetText: string = "";
get targetText() {
return this._targetText;
}
set targetText(targetText: string) {
this._targetText = targetText;
if (this.animationFrameId === null) {
this.animate();
}
}
public targetText: string = "";

constructor(
private setText: (callback: (prevText: string) => string) => void,
) {}

start() {
if (this.animationFrameId !== null) return;
this.animate();
}

stop() {
if (this.animationFrameId !== null) {
cancelAnimationFrame(this.animationFrameId);
Expand All @@ -33,7 +29,7 @@ class TextStreamAnimator {
this.lastUpdateTime = currentTime;

this.setText((currentText) => {
const targetText = this._targetText;
const targetText = this.targetText;

if (currentText === targetText) {
this.animationFrameId = null;
Expand Down Expand Up @@ -68,11 +64,13 @@ export const useSmooth = (text: string, smooth: boolean = false) => {

if (!text.startsWith(animatorRef.targetText)) {
setDisplayedText(text);
animatorRef.targetText = text;
animatorRef.stop();
return;
}

animatorRef.targetText = text;
animatorRef.start();
}, [animatorRef, smooth, text]);

useEffect(() => {
Expand Down

0 comments on commit e4890aa

Please sign in to comment.