1"use client"
2
3import {
4 useRef,
5 type ComponentPropsWithoutRef,
6 type FC,
7 type ReactNode,
8} from "react"
9import { motion, MotionValue, useScroll, useTransform } from "motion/react"
10
11import { cn } from "@/lib/utils"
12
13export interface TextRevealProps extends ComponentPropsWithoutRef<"div"> {
14 children: string
15}
16
17export const TextReveal: FC<TextRevealProps> = ({ children, className }) => {
18 const sectionRef = useRef<HTMLDivElement | null>(null)
19 const { scrollYProgress } = useScroll({
20 target: sectionRef,
21 })
22
23 if (typeof children !== "string") {
24 throw new Error("TextReveal: children must be a string")
25 }
26
27 const words = children.split(" ")
28
29 return (
30 <div ref={sectionRef} className={cn("relative z-0 h-[200vh]", className)}>
31 <div
32 className={
33 "sticky top-0 mx-auto flex h-[50%] max-w-4xl items-center bg-transparent px-4 py-20"
34 }
35 >
36 <span
37 className={
38 "flex flex-wrap p-5 text-2xl font-bold text-black/20 md:p-8 md:text-3xl lg:p-10 lg:text-4xl xl:text-5xl dark:text-white/20"
39 }
40 >
41 {words.map((word, i) => {
42 const start = i / words.length
43 const end = start + 1 / words.length
44 return (
45 <Word key={i} progress={scrollYProgress} range={[start, end]}>
46 {word}
47 </Word>
48 )
49 })}
50 </span>
51 </div>
52 </div>
53 )
54}
55
56interface WordProps {
57 children: ReactNode
58 progress: MotionValue<number>
59 range: [number, number]
60}
61
62const Word: FC<WordProps> = ({ children, progress, range }) => {
63 const opacity = useTransform(progress, range, [0, 1])
64 return (
65 <span className="xl:lg-3 relative mx-1 lg:mx-1.5">
66 <span className="absolute opacity-30">{children}</span>
67 <motion.span
68 style={{ opacity: opacity }}
69 className={"text-black dark:text-white"}
70 >
71 {children}
72 </motion.span>
73 </span>
74 )
75}
76