forked from jnsahaj/tweakcn
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-stream-text.ts
More file actions
70 lines (58 loc) · 1.77 KB
/
use-stream-text.ts
File metadata and controls
70 lines (58 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { useCallback, useEffect, useRef, useState } from "react";
interface UseStreamTextProps {
speed?: number;
}
export function useStreamText({ speed = 5 }: UseStreamTextProps = {}) {
const [parts, setParts] = useState<string[]>([]);
const [stream, setStream] = useState("");
const frame = useRef<number | null>(null);
const lastTimeRef = useRef<number>(0);
const streamIndexRef = useRef<number>(0);
const isAnimatingRef = useRef(false);
const addPart = useCallback((part: string) => {
if (part) {
setParts((prev) => [...prev, part]);
}
}, []);
const reset = useCallback(() => {
setParts([]);
setStream("");
streamIndexRef.current = 0;
if (frame.current) {
cancelAnimationFrame(frame.current);
}
frame.current = null;
lastTimeRef.current = 0;
isAnimatingRef.current = false;
}, []);
useEffect(() => {
if (isAnimatingRef.current) return;
const typewriterSpeed = speed;
const fullText = parts.join("");
if (streamIndexRef.current >= fullText.length) {
setStream(fullText);
return;
}
isAnimatingRef.current = true;
const animate = (time: number) => {
if (streamIndexRef.current < fullText.length) {
if (time - lastTimeRef.current > typewriterSpeed) {
streamIndexRef.current++;
setStream(fullText.slice(0, streamIndexRef.current));
lastTimeRef.current = time;
}
frame.current = requestAnimationFrame(animate);
} else {
isAnimatingRef.current = false;
}
};
frame.current = requestAnimationFrame(animate);
return () => {
if (frame.current) {
cancelAnimationFrame(frame.current);
}
isAnimatingRef.current = false;
};
}, [parts]);
return { stream, addPart, reset };
}