refactor: update title generation logic to improve user experience by generating titles in parallel with assistant responses

This commit is contained in:
Anish Sarkar 2026-03-09 01:28:53 +05:30
parent bd91b0bef2
commit e8cf677b25
5 changed files with 120 additions and 61 deletions

View file

@ -0,0 +1,49 @@
import { useEffect, useRef, useState } from "react";
/**
* Animates text changes with a typewriter reveal effect, but only when
* transitioning away from the `skipFor` placeholder (default "New Chat").
* All other text values are shown instantly without animation.
*/
export function useTypewriter(text: string, speed = 35, skipFor = "New Chat"): string {
const [displayed, setDisplayed] = useState(text);
const prevTextRef = useRef(text);
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
useEffect(() => {
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
const prevText = prevTextRef.current;
prevTextRef.current = text;
const shouldAnimate = prevText === skipFor && text !== skipFor && !!text;
if (!shouldAnimate) {
setDisplayed(text);
return;
}
let i = 0;
setDisplayed("");
intervalRef.current = setInterval(() => {
i++;
setDisplayed(text.slice(0, i));
if (i >= text.length) {
if (intervalRef.current) clearInterval(intervalRef.current);
intervalRef.current = null;
}
}, speed);
return () => {
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
};
}, [text, speed, skipFor]);
return displayed;
}