1"use client"
2
3import {
4 useEffect,
5 useMemo,
6 useRef,
7 useState,
8 type ComponentType,
9 type RefAttributes,
10 type RefObject,
11} from "react"
12import {
13 motion,
14 useInView,
15 type DOMMotionComponents,
16 type HTMLMotionProps,
17 type MotionProps,
18} from "motion/react"
19
20import { cn } from "@/lib/utils"
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 TypingAnimationMotionComponent = ComponentType<
42 Omit<HTMLMotionProps<"span">, "ref"> & RefAttributes<HTMLElement>
43>
44
45interface TypingAnimationProps extends Omit<MotionProps, "children"> {
46 children?: string
47 words?: string[]
48 className?: string
49 duration?: number
50 typeSpeed?: number
51 deleteSpeed?: number
52 delay?: number
53 pauseDelay?: number
54 loop?: boolean
55 as?: MotionElementType
56 startOnView?: boolean
57 showCursor?: boolean
58 blinkCursor?: boolean
59 cursorStyle?: "line" | "block" | "underscore"
60}
61
62export function TypingAnimation({
63 children,
64 words,
65 className,
66 duration = 100,
67 typeSpeed,
68 deleteSpeed,
69 delay = 0,
70 pauseDelay = 1000,
71 loop = false,
72 as: Component = "span",
73 startOnView = true,
74 showCursor = true,
75 blinkCursor = true,
76 cursorStyle = "line",
77 ...props
78}: TypingAnimationProps) {
79 const MotionComponent = motionElements[
80 Component
81 ] as TypingAnimationMotionComponent
82
83 const [displayedText, setDisplayedText] = useState<string>("")
84 const [currentWordIndex, setCurrentWordIndex] = useState(0)
85 const [currentCharIndex, setCurrentCharIndex] = useState(0)
86 const [phase, setPhase] = useState<"typing" | "pause" | "deleting">("typing")
87 const elementRef = useRef<HTMLElement | null>(null)
88 const isInView = useInView(elementRef as RefObject<Element>, {
89 amount: 0.3,
90 once: true,
91 })
92
93 const wordsToAnimate = useMemo(
94 () => words ?? (children ? [children] : []),
95 [words, children]
96 )
97 const hasMultipleWords = wordsToAnimate.length > 1
98
99 const typingSpeed = typeSpeed ?? duration
100 const deletingSpeed = deleteSpeed ?? typingSpeed / 2
101
102 const shouldStart = startOnView ? isInView : true
103 const animationSourceKey = useMemo(
104 () => (words ? words.join("\u0000") : (children ?? "")),
105 [words, children]
106 )
107
108 useEffect(() => {
109 setDisplayedText("")
110 setCurrentWordIndex(0)
111 setCurrentCharIndex(0)
112 setPhase("typing")
113 }, [animationSourceKey])
114
115 useEffect(() => {
116 let timeout: ReturnType<typeof setTimeout> | null = null
117
118 if (shouldStart && wordsToAnimate.length > 0) {
119 const timeoutDelay =
120 delay > 0 && displayedText === ""
121 ? delay
122 : phase === "typing"
123 ? typingSpeed
124 : phase === "deleting"
125 ? deletingSpeed
126 : pauseDelay
127
128 timeout = setTimeout(() => {
129 const currentWord = wordsToAnimate[currentWordIndex] || ""
130 const graphemes = Array.from(currentWord)
131
132 switch (phase) {
133 case "typing":
134 if (currentCharIndex < graphemes.length) {
135 setDisplayedText(
136 graphemes.slice(0, currentCharIndex + 1).join("")
137 )
138 setCurrentCharIndex(currentCharIndex + 1)
139 } else {
140 if (hasMultipleWords || loop) {
141 const isLastWord =
142 currentWordIndex === wordsToAnimate.length - 1
143 if (!isLastWord || loop) {
144 setPhase("pause")
145 }
146 }
147 }
148 break
149
150 case "pause":
151 setPhase("deleting")
152 break
153
154 case "deleting":
155 if (currentCharIndex > 0) {
156 setDisplayedText(
157 graphemes.slice(0, currentCharIndex - 1).join("")
158 )
159 setCurrentCharIndex(currentCharIndex - 1)
160 } else {
161 const nextIndex = (currentWordIndex + 1) % wordsToAnimate.length
162 setCurrentWordIndex(nextIndex)
163 setPhase("typing")
164 }
165 break
166 }
167 }, timeoutDelay)
168 }
169
170 return () => {
171 if (timeout !== null) {
172 clearTimeout(timeout)
173 }
174 }
175 }, [
176 shouldStart,
177 phase,
178 currentCharIndex,
179 currentWordIndex,
180 displayedText,
181 wordsToAnimate,
182 hasMultipleWords,
183 loop,
184 typingSpeed,
185 deletingSpeed,
186 pauseDelay,
187 delay,
188 ])
189
190 const currentWordGraphemes = Array.from(
191 wordsToAnimate[currentWordIndex] || ""
192 )
193 const isComplete =
194 !loop &&
195 currentWordIndex === wordsToAnimate.length - 1 &&
196 currentCharIndex >= currentWordGraphemes.length &&
197 phase !== "deleting"
198
199 const shouldShowCursor =
200 showCursor &&
201 !isComplete &&
202 (hasMultipleWords || loop || currentCharIndex < currentWordGraphemes.length)
203
204 const getCursorChar = () => {
205 switch (cursorStyle) {
206 case "block":
207 return "โ"
208 case "underscore":
209 return "_"
210 case "line":
211 default:
212 return "|"
213 }
214 }
215
216 return (
217 <MotionComponent
218 ref={elementRef}
219 className={cn(
220 "leading-20 tracking-[-0.02em]",
221 Component === "span" && "inline-block",
222 className
223 )}
224 {...props}
225 >
226 {displayedText}
227 {shouldShowCursor && (
228 <span
229 className={cn("inline-block", blinkCursor && "animate-blink-cursor")}
230 >
231 {getCursorChar()}
232 </span>
233 )}
234 </MotionComponent>
235 )
236}
237