1"use client";
2
3import { motion } from "motion/react";
4import { useMemo } from "react";
5
6type SplitType = "words" | "chars";
7
8interface RandomizedTextProps {
9 children: string;
10 className?: string;
11 split?: SplitType;
12 delay?: number;
13 inView?: boolean;
14 once?: boolean;
15}
16
17export function RandomizedText({
18 children,
19 className = "",
20 split = "words",
21 delay = 0.2,
22 inView = false,
23 once = true,
24}: RandomizedTextProps) {
25
26 const expoOut = (t: number): number => {
27 return t === 1 ? 1 : 1 - Math.pow(2, -10 * t);
28 };
29
30 const elements = useMemo(() => {
31 if (split === "chars") {
32 return children.split("").map((char, i) => ({
33 content: char === " " ? "\u00A0" : char,
34 key: `char-${i}`,
35 }));
36 }
37 return children.split(" ").map((word, i) => ({
38 content: word,
39 key: `word-${i}`,
40 }));
41 }, [children, split]);
42
43 const randomizedDelays = useMemo(() => {
44 return elements.map(() =>
45 delay + Math.random() * 0.2 + Math.random() * 0.03
46 );
47 }, [elements.length, delay]);
48
49 const variants = {
50 hidden: { opacity: 0 },
51 visible: { opacity: 1 },
52 };
53
54 return (
55 <motion.span
56 className={className}
57 aria-label={children}
58 style={{ display: "inline-block", wordBreak: "break-word" }}
59 initial="hidden"
60 whileInView={inView ? "visible" : undefined}
61 animate={inView ? undefined : "visible"}
62 viewport={{ once }}
63 >
64 {elements.map((element, i) => (
65 <motion.span
66 key={element.key}
67 variants={variants}
68 transition={{
69 duration: 1.2,
70 delay: randomizedDelays[i],
71 ease: expoOut,
72 }}
73 style={{ display: split === "words" ? "inline-block" : "inline" }}
74 className={split === "words" ? "mr-[0.25em]" : ""}
75 >
76 {element.content}
77 </motion.span>
78 ))}
79 </motion.span>
80 );
81}
82