1"use client";
2
3import { useRef, useEffect, useMemo, useCallback, useState } from "react";
4import { cn } from "@/lib/utils";
5
6type Align = "left" | "center" | "right";
7
8const defaultColors = ["#8d6869", "#5a8ea6", "#b9c96e", "#c7c571", "#cb706f", "#7e5e5f"];
9
10interface GradientWaveTextProps {
11 children?: React.ReactNode;
12 align?: Align;
13 className?: string;
14
15 speed?: number;
16 paused?: boolean;
17 delay?: number;
18 repeat?: boolean;
19 inView?: boolean;
20 once?: boolean;
21
22 radial?: boolean;
23 bottomOffset?: number;
24 bandGap?: number;
25 bandCount?: number;
26 customColors?: string[];
27
28 onClick?: (e: React.MouseEvent) => void;
29 onMouseEnter?: (e: React.MouseEvent) => void;
30 onMouseLeave?: (e: React.MouseEvent) => void;
31
32 ariaLabel?: string;
33}
34
35
36export function GradientWaveText({
37 children,
38 align = "center",
39 className,
40
41 speed = 1,
42 paused = false,
43 delay = 0,
44 repeat = false,
45 inView = false,
46 once = true,
47
48 radial = true,
49 bottomOffset = 20,
50 bandGap = 4,
51 bandCount = 8,
52 customColors,
53
54 onClick,
55 onMouseEnter,
56 onMouseLeave,
57
58 ariaLabel,
59}: GradientWaveTextProps) {
60 const elRef = useRef<HTMLDivElement | null>(null);
61 const rafRef = useRef(0);
62 const tRef = useRef(0);
63 const cyclesDoneRef = useRef(0);
64 const finishedRef = useRef(false);
65 const startedRef = useRef(false);
66 const startAtRef = useRef(0);
67 const hasPlayedRef = useRef(false);
68
69 const [isInView, setIsInView] = useState(!inView);
70
71 const cycles = repeat ? 0 : 1;
72
73 useEffect(() => {
74 if (!inView) {
75 setIsInView(true);
76 return;
77 }
78
79 const node = elRef.current;
80 if (!node) return;
81
82 const observer = new IntersectionObserver(
83 (entries) => {
84 entries.forEach((entry) => {
85 if (entry.isIntersecting) {
86 if (once && hasPlayedRef.current) return;
87 setIsInView(true);
88 hasPlayedRef.current = true;
89 } else if (!once) {
90 setIsInView(false);
91 }
92 });
93 },
94 { threshold: 0.1 }
95 );
96
97 observer.observe(node);
98 return () => observer.disconnect();
99 }, [inView, once]);
100
101 const resolvedColors = useMemo(() => {
102 return customColors?.length ? customColors : defaultColors;
103 }, [customColors]);
104
105 const stops = useMemo(() => {
106 const arr: string[] = [];
107 const baseColor = "var(--gradient-wave-base, rgb(29,29,31))";
108 arr.push(`${baseColor} calc((var(--gi) + 0) * 1%)`);
109 for (let i = 0; i < bandCount && i < resolvedColors.length * 2; i++) {
110 const color = resolvedColors[i % resolvedColors.length];
111 const offset = (i + 2) * bandGap;
112 arr.push(`${color} calc((var(--gi) + ${offset}) * 1%)`);
113 }
114 const endOffset = (bandCount + 2) * bandGap;
115 arr.push(`${baseColor} calc((var(--gi) + ${endOffset}) * 1%)`);
116 return arr.join(", ");
117 }, [resolvedColors, bandGap, bandCount]);
118
119 const gradient = useMemo(() => {
120 return radial
121 ? `radial-gradient(circle at 50% bottom, ${stops})`
122 : `linear-gradient(0deg, ${stops})`;
123 }, [radial, stops]);
124
125 useEffect(() => {
126 const node = elRef.current;
127 if (node) node.style.setProperty("--gi", "-25");
128 }, []);
129
130 useEffect(() => {
131 if (!isInView) return;
132
133 const node = elRef.current;
134 if (!node) return;
135
136 tRef.current = -25;
137 cyclesDoneRef.current = 0;
138 finishedRef.current = false;
139 startedRef.current = false;
140 startAtRef.current = performance.now() + Math.max(0, (delay ?? 0) * 1000);
141 node.style.setProperty("--gi", "-25");
142 }, [isInView, delay]);
143
144 useEffect(() => {
145 const node = elRef.current;
146 if (!node || !isInView) return;
147
148 const RANGE = 200;
149 let last = performance.now();
150
151 const tick = (now: number) => {
152 if (finishedRef.current) return;
153
154 if (!startedRef.current) {
155 if (now >= startAtRef.current) {
156 startedRef.current = true;
157 last = now;
158 } else {
159 rafRef.current = requestAnimationFrame(tick);
160 return;
161 }
162 }
163
164 const dt = Math.min(64, now - last);
165 last = now;
166
167 const shouldAnimate = !paused;
168
169 if (shouldAnimate) {
170 const increment = (dt * speed) / 16.6667;
171 let next = tRef.current + increment;
172
173 if (cycles === 0) {
174 if (next >= RANGE) next = next % RANGE;
175 tRef.current = next;
176 node.style.setProperty("--gi", String(next));
177 } else {
178 while (next >= RANGE && cyclesDoneRef.current < cycles) {
179 next -= RANGE;
180 cyclesDoneRef.current += 1;
181 }
182
183 if (cyclesDoneRef.current >= cycles) {
184 tRef.current = RANGE;
185 node.style.setProperty("--gi", String(RANGE));
186 finishedRef.current = true;
187 return;
188 } else {
189 tRef.current = next;
190 node.style.setProperty("--gi", String(next));
191 }
192 }
193 }
194
195 rafRef.current = requestAnimationFrame(tick);
196 };
197
198 rafRef.current = requestAnimationFrame(tick);
199 return () => cancelAnimationFrame(rafRef.current);
200 }, [speed, paused, cycles, isInView]);
201
202 const justifyContent =
203 align === "left"
204 ? "flex-start"
205 : align === "right"
206 ? "flex-end"
207 : "center";
208
209 const handleClick = useCallback(
210 (e: React.MouseEvent) => {
211 onClick?.(e);
212 },
213 [onClick]
214 );
215
216 const handleMouseEnter = useCallback(
217 (e: React.MouseEvent) => {
218 onMouseEnter?.(e);
219 },
220 [onMouseEnter]
221 );
222
223 const handleMouseLeave = useCallback(
224 (e: React.MouseEvent) => {
225 onMouseLeave?.(e);
226 },
227 [onMouseLeave]
228 );
229
230 return (
231 <div
232 ref={elRef}
233 className={cn(
234 "flex w-full h-full items-center [--gradient-wave-base:rgb(29,29,31)] dark:[--gradient-wave-base:rgb(255,255,255)]",
235 className
236 )}
237 style={{ justifyContent, "--gi": -25 } as React.CSSProperties}
238 aria-label={ariaLabel || undefined}
239 role={ariaLabel ? "img" : undefined}
240 onClick={handleClick}
241 onMouseEnter={handleMouseEnter}
242 onMouseLeave={handleMouseLeave}
243 >
244 <span
245 style={{
246 textAlign: align,
247 backgroundImage: gradient,
248 WebkitBackgroundClip: "text",
249 backgroundClip: "text",
250 WebkitTextFillColor: "transparent",
251 color: "transparent",
252 whiteSpace: "pre-wrap",
253 wordBreak: "break-word",
254 display: "inline-block",
255 WebkitFontSmoothing: "antialiased",
256 MozOsxFontSmoothing: "grayscale",
257 WebkitBackfaceVisibility: "hidden",
258 backfaceVisibility: "hidden",
259 transform: "translateZ(0)",
260 paddingBottom: `${bottomOffset}%`,
261 marginBottom: `-${bottomOffset}%`,
262 paddingInline: 2,
263 }}
264 >
265 {children}
266 </span>
267 </div>
268 );
269}
270
271export default GradientWaveText;
272