1"use client"
2
3import {
4 useEffect,
5 useRef,
6 useState,
7 type ComponentType,
8 type RefAttributes,
9} from "react"
10import {
11 AnimatePresence,
12 motion,
13 type DOMMotionComponents,
14 type HTMLMotionProps,
15 type MotionProps,
16} from "motion/react"
17
18import { cn } from "@/lib/utils"
19
20type CharacterSet = string[] | readonly string[]
21
22const motionElements = {
23 article: motion.article,
24 div: motion.div,
25 h1: motion.h1,
26 h2: motion.h2,
27 h3: motion.h3,
28 h4: motion.h4,
29 h5: motion.h5,
30 h6: motion.h6,
31 li: motion.li,
32 p: motion.p,
33 section: motion.section,
34 span: motion.span,
35} as const
36
37type MotionElementType = Extract<
38 keyof DOMMotionComponents,
39 keyof typeof motionElements
40>
41type HyperTextMotionComponent = ComponentType<
42 Omit<HTMLMotionProps<"div">, "ref"> & RefAttributes<HTMLElement>
43>
44
45interface HyperTextProps extends Omit<MotionProps, "children"> {
46 /** The text content to be animated */
47 children: string
48 /** Optional className for styling */
49 className?: string
50 /** Duration of the animation in milliseconds */
51 duration?: number
52 /** Delay before animation starts in milliseconds */
53 delay?: number
54 /** Component to render as - defaults to div */
55 as?: MotionElementType
56 /** Whether to start animation when element comes into view */
57 startOnView?: boolean
58 /** Whether to trigger animation on hover */
59 animateOnHover?: boolean
60 /** Custom character set for scramble effect. Defaults to uppercase alphabet */
61 characterSet?: CharacterSet
62}
63
64const DEFAULT_CHARACTER_SET = Object.freeze(
65 "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")
66) as readonly string[]
67
68const getRandomInt = (max: number): number => Math.floor(Math.random() * max)
69
70export function HyperText({
71 children,
72 className,
73 duration = 800,
74 delay = 0,
75 as: Component = "div",
76 startOnView = false,
77 animateOnHover = true,
78 characterSet = DEFAULT_CHARACTER_SET,
79 ...props
80}: HyperTextProps) {
81 const MotionComponent = motionElements[Component] as HyperTextMotionComponent
82
83 const [displayText, setDisplayText] = useState<string[]>(() =>
84 children.split("")
85 )
86 const [isAnimating, setIsAnimating] = useState(false)
87 const iterationCount = useRef(0)
88 const elementRef = useRef<HTMLElement | null>(null)
89
90 const handleAnimationTrigger = () => {
91 if (animateOnHover && !isAnimating) {
92 iterationCount.current = 0
93 setIsAnimating(true)
94 }
95 }
96
97 // Handle animation start based on view or delay
98 useEffect(() => {
99 if (!startOnView) {
100 const startTimeout = setTimeout(() => {
101 setIsAnimating(true)
102 }, delay)
103 return () => clearTimeout(startTimeout)
104 }
105
106 const observer = new IntersectionObserver(
107 ([entry]) => {
108 if (entry.isIntersecting) {
109 setTimeout(() => {
110 setIsAnimating(true)
111 }, delay)
112 observer.disconnect()
113 }
114 },
115 { threshold: 0.1, rootMargin: "-30% 0px -30% 0px" }
116 )
117
118 if (elementRef.current) {
119 observer.observe(elementRef.current)
120 }
121
122 return () => observer.disconnect()
123 }, [delay, startOnView])
124
125 // Handle scramble animation
126 useEffect(() => {
127 let animationFrameId: number | null = null
128
129 if (isAnimating) {
130 const maxIterations = children.length
131 const startTime = performance.now()
132
133 const animate = (currentTime: number) => {
134 const elapsed = currentTime - startTime
135 const progress = Math.min(elapsed / duration, 1)
136
137 iterationCount.current = progress * maxIterations
138
139 setDisplayText((currentText) =>
140 currentText.map((letter, index) =>
141 letter === " "
142 ? letter
143 : index <= iterationCount.current
144 ? children[index]
145 : characterSet[getRandomInt(characterSet.length)]
146 )
147 )
148
149 if (progress < 1) {
150 animationFrameId = requestAnimationFrame(animate)
151 } else {
152 setIsAnimating(false)
153 }
154 }
155
156 animationFrameId = requestAnimationFrame(animate)
157 }
158
159 return () => {
160 if (animationFrameId !== null) {
161 cancelAnimationFrame(animationFrameId)
162 }
163 }
164 }, [children, duration, isAnimating, characterSet])
165
166 return (
167 <MotionComponent
168 ref={elementRef}
169 className={cn("overflow-hidden py-2 text-4xl font-bold", className)}
170 onMouseEnter={handleAnimationTrigger}
171 {...props}
172 >
173 <AnimatePresence>
174 {displayText.map((letter, index) => (
175 <motion.span
176 key={index}
177 className={cn("font-mono", letter === " " ? "w-3" : "")}
178 >
179 {letter.toUpperCase()}
180 </motion.span>
181 ))}
182 </AnimatePresence>
183 </MotionComponent>
184 )
185}
186