1"use client";
2
3import { AnimationOptions, motion } from "motion/react";
4import {
5 forwardRef,
6 useCallback,
7 useEffect,
8 useImperativeHandle,
9 useMemo,
10 useState,
11} from "react";
12
13import { cn } from "@/lib/utils";
14
15interface SlideUpTextProps {
16 children: React.ReactNode;
17 split?: "words" | "characters" | "lines";
18 delay?: number;
19 stagger?: number;
20 from?: "first" | "last" | "center";
21 transition?: AnimationOptions;
22 className?: string;
23 wordClass?: string;
24 charClass?: string;
25 autoStart?: boolean;
26 onStart?: () => void;
27 onComplete?: () => void;
28 inView?: boolean;
29 once?: boolean;
30}
31
32export interface SlideUpTextRef {
33 startAnimation: () => void;
34 reset: () => void;
35}
36
37interface WordObject {
38 characters: string[];
39 needsSpace: boolean;
40}
41
42const SlideUpText = forwardRef<SlideUpTextRef, SlideUpTextProps>(
43 (
44 {
45 children,
46 split = "words",
47 delay = 0,
48 stagger = 0.1,
49 from = "first",
50 transition = {
51 type: "tween",
52 ease: [0.625, 0.05, 0, 1],
53 duration: 0.5,
54 },
55 className,
56 wordClass,
57 charClass,
58 autoStart = true,
59 onStart,
60 onComplete,
61 inView = false,
62 once = true,
63 ...props
64 },
65 ref,
66 ) => {
67 const text = typeof children === "string"
68 ? children
69 : children?.toString() || "";
70 const [isAnimating, setIsAnimating] = useState(false);
71
72 const splitIntoCharacters = (text: string): string[] => {
73 if (typeof Intl !== "undefined" && "Segmenter" in Intl) {
74 const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
75 return Array.from(segmenter.segment(text), ({ segment }) => segment);
76 }
77 return Array.from(text);
78 };
79
80 const elements = useMemo(() => {
81 const words = text.split(" ");
82 if (split === "characters") {
83 return words.map((word, i) => ({
84 characters: splitIntoCharacters(word),
85 needsSpace: i !== words.length - 1,
86 }));
87 }
88 return split === "words" ? text.split(" ") : text.split("\n");
89 }, [text, split]);
90
91 const getStaggerDelay = useCallback(
92 (index: number) => {
93 const total = split === "characters"
94 ? elements.reduce(
95 (acc, word) =>
96 acc +
97 (typeof word === "string"
98 ? 1
99 : word.characters.length + (word.needsSpace ? 1 : 0)),
100 0,
101 )
102 : elements.length;
103
104 if (from === "first") return index * stagger;
105 if (from === "last") return (total - 1 - index) * stagger;
106 if (from === "center") {
107 const center = Math.floor(total / 2);
108 return Math.abs(center - index) * stagger;
109 }
110 return index * stagger;
111 },
112 [elements, from, stagger, split],
113 );
114
115 const startAnimation = useCallback(() => {
116 setIsAnimating(true);
117 onStart?.();
118 }, [onStart]);
119
120 useImperativeHandle(ref, () => ({
121 startAnimation,
122 reset: () => setIsAnimating(false),
123 }));
124
125 useEffect(() => {
126 if (autoStart && !inView) {
127 startAnimation();
128 }
129 }, [autoStart, inView, startAnimation]);
130
131 const variants = {
132 hidden: { y: "100%" },
133 visible: (i: number) => ({
134 y: 0,
135 transition: {
136 ...transition,
137 delay: delay + ((transition?.delay as number) || 0) + getStaggerDelay(i),
138 },
139 }),
140 };
141
142 return (
143 <motion.span
144 className={cn(
145 className,
146 "flex flex-wrap whitespace-pre-wrap",
147 split === "lines" && "flex-col",
148 )}
149 initial="hidden"
150 whileInView={inView ? "visible" : undefined}
151 animate={inView ? undefined : isAnimating ? "visible" : "hidden"}
152 viewport={{ once }}
153 onAnimationStart={() => {
154 if (inView) {
155 setIsAnimating(true);
156 onStart?.();
157 }
158 }}
159 {...props}
160 >
161 <span className="sr-only">{text}</span>
162
163 {(split === "characters"
164 ? (elements as WordObject[])
165 : (elements as string[]).map((el, i, arr) => ({
166 characters: [el],
167 needsSpace: split === "words" && i !== arr.length - 1,
168 }))).map((wordObj, wordIndex, array) => {
169 const previousCharsCount = array
170 .slice(0, wordIndex)
171 .reduce((sum, word) => sum + word.characters.length, 0);
172
173 return (
174 <span
175 key={wordIndex}
176 aria-hidden="true"
177 className={cn("inline-flex overflow-hidden", wordClass)}
178 >
179 {wordObj.characters.map((char, charIndex) => (
180 <span
181 className={cn(
182 charClass,
183 "whitespace-pre-wrap relative overflow-hidden",
184 )}
185 key={charIndex}
186 >
187 <motion.span
188 custom={previousCharsCount + charIndex}
189 initial="hidden"
190 animate={isAnimating ? "visible" : "hidden"}
191 variants={variants}
192 onAnimationComplete={wordIndex === array.length - 1 &&
193 charIndex === wordObj.characters.length - 1
194 ? onComplete
195 : undefined}
196 className="inline-block"
197 >
198 {char}
199 </motion.span>
200 </span>
201 ))}
202 {wordObj.needsSpace && (
203 <span className="relative overflow-hidden">
204 <motion.span
205 custom={previousCharsCount + wordObj.characters.length}
206 initial="hidden"
207 animate={isAnimating ? "visible" : "hidden"}
208 variants={variants}
209 className="inline-block"
210 >
211 {" "}
212 </motion.span>
213 </span>
214 )}
215 </span>
216 );
217 })}
218 </motion.span>
219 );
220 },
221);
222
223SlideUpText.displayName = "SlideUpText";
224
225export { SlideUpText };
226export type { SlideUpTextProps };
227