blob: bb3f365000adde0a6d5760b77b2683369c8a39c9 (
plain) (
blame)
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
|
import { useState, useCallback, useRef } from "react";
const GLYPHS = "▒▓░█#@*+:-/[]{}<>_";
export function useTextScramble(originalText: string) {
const [displayText, setDisplayText] = useState(originalText);
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
const iterationRef = useRef(0);
const scramble = useCallback(() => {
// Clear any existing animation
if (timerRef.current) {
clearInterval(timerRef.current);
}
iterationRef.current = 0;
timerRef.current = setInterval(() => {
const text = originalText;
const iteration = iterationRef.current;
const display = text
.split("")
.map((char, index) => {
if (index < iteration) return char;
return GLYPHS.charAt(Math.floor(Math.random() * GLYPHS.length));
})
.join("");
setDisplayText(display);
iterationRef.current += 1;
if (iteration > text.length + 2) {
if (timerRef.current) {
clearInterval(timerRef.current);
timerRef.current = null;
}
setDisplayText(originalText);
}
}, 26);
}, [originalText]);
const reset = useCallback(() => {
if (timerRef.current) {
clearInterval(timerRef.current);
timerRef.current = null;
}
setDisplayText(originalText);
}, [originalText]);
return { displayText, scramble, reset };
}
|