1"use client"
2
3import {
4 Children,
5 createContext,
6 useContext,
7 useEffect,
8 useMemo,
9 useRef,
10 useState,
11 type ComponentType,
12 type RefAttributes,
13} from "react"
14import {
15 motion,
16 useInView,
17 type DOMMotionComponents,
18 type HTMLMotionProps,
19 type MotionProps,
20} from "motion/react"
21
22import { cn } from "@/lib/utils"
23
24interface SequenceContextValue {
25 completeItem: (index: number) => void
26 activeIndex: number
27 sequenceStarted: boolean
28}
29
30const SequenceContext = createContext<SequenceContextValue | null>(null)
31
32const useSequence = () => useContext(SequenceContext)
33
34const ItemIndexContext = createContext<number | null>(null)
35const useItemIndex = () => useContext(ItemIndexContext)
36
37const motionElements = {
38 article: motion.article,
39 div: motion.div,
40 h1: motion.h1,
41 h2: motion.h2,
42 h3: motion.h3,
43 h4: motion.h4,
44 h5: motion.h5,
45 h6: motion.h6,
46 li: motion.li,
47 p: motion.p,
48 section: motion.section,
49 span: motion.span,
50} as const
51
52type MotionElementType = Extract<
53 keyof DOMMotionComponents,
54 keyof typeof motionElements
55>
56type TerminalTypingMotionComponent = ComponentType<
57 Omit<HTMLMotionProps<"span">, "ref"> & RefAttributes<HTMLElement>
58>
59
60interface AnimatedSpanProps extends MotionProps {
61 children: React.ReactNode
62 delay?: number
63 className?: string
64 startOnView?: boolean
65}
66
67export const AnimatedSpan = ({
68 children,
69 delay = 0,
70 className,
71 startOnView = false,
72 ...props
73}: AnimatedSpanProps) => {
74 const elementRef = useRef<HTMLDivElement | null>(null)
75 const isInView = useInView(elementRef as React.RefObject<Element>, {
76 amount: 0.3,
77 once: true,
78 })
79
80 const sequence = useSequence()
81 const itemIndex = useItemIndex()
82 const [hasStarted, setHasStarted] = useState(false)
83 useEffect(() => {
84 if (!sequence || itemIndex === null) return
85 if (!sequence.sequenceStarted) return
86 if (hasStarted) return
87 if (sequence.activeIndex === itemIndex) {
88 setHasStarted(true)
89 }
90 }, [sequence, hasStarted, itemIndex])
91
92 const shouldAnimate = sequence ? hasStarted : startOnView ? isInView : true
93
94 return (
95 <motion.div
96 ref={elementRef}
97 initial={{ opacity: 0, y: -5 }}
98 animate={shouldAnimate ? { opacity: 1, y: 0 } : { opacity: 0, y: -5 }}
99 transition={{ duration: 0.3, delay: sequence ? 0 : delay / 1000 }}
100 className={cn("grid text-sm font-normal tracking-tight", className)}
101 onAnimationComplete={() => {
102 if (!sequence) return
103 if (itemIndex === null) return
104 sequence.completeItem(itemIndex)
105 }}
106 {...props}
107 >
108 {children}
109 </motion.div>
110 )
111}
112
113interface TypingAnimationProps extends Omit<MotionProps, "children"> {
114 children: string
115 className?: string
116 duration?: number
117 delay?: number
118 as?: MotionElementType
119 startOnView?: boolean
120}
121
122export const TypingAnimation = ({
123 children,
124 className,
125 duration = 60,
126 delay = 0,
127 as: Component = "span",
128 startOnView = true,
129 ...props
130}: TypingAnimationProps) => {
131 if (typeof children !== "string") {
132 throw new Error("TypingAnimation: children must be a string. Received:")
133 }
134
135 const MotionComponent = motionElements[
136 Component
137 ] as TerminalTypingMotionComponent
138
139 const [displayedText, setDisplayedText] = useState<string>("")
140 const [started, setStarted] = useState(false)
141 const elementRef = useRef<HTMLElement | null>(null)
142 const isInView = useInView(elementRef as React.RefObject<Element>, {
143 amount: 0.3,
144 once: true,
145 })
146
147 const sequence = useSequence()
148 const itemIndex = useItemIndex()
149 const hasSequence = sequence !== null
150 const sequenceStarted = sequence?.sequenceStarted ?? false
151 const sequenceActiveIndex = sequence?.activeIndex ?? null
152 const sequenceCompleteItemRef = useRef<
153 SequenceContextValue["completeItem"] | null
154 >(null)
155 const sequenceItemIndexRef = useRef<number | null>(null)
156
157 useEffect(() => {
158 sequenceCompleteItemRef.current = sequence?.completeItem ?? null
159 sequenceItemIndexRef.current = itemIndex
160 }, [sequence?.completeItem, itemIndex])
161
162 useEffect(() => {
163 let startTimeout: ReturnType<typeof setTimeout> | null = null
164
165 if (hasSequence && itemIndex !== null) {
166 if (sequenceStarted && !started && sequenceActiveIndex === itemIndex) {
167 setStarted(true)
168 }
169 } else if (!startOnView || isInView) {
170 startTimeout = setTimeout(() => setStarted(true), delay)
171 }
172
173 return () => {
174 if (startTimeout !== null) {
175 clearTimeout(startTimeout)
176 }
177 }
178 }, [
179 delay,
180 startOnView,
181 isInView,
182 started,
183 hasSequence,
184 sequenceActiveIndex,
185 sequenceStarted,
186 itemIndex,
187 ])
188
189 useEffect(() => {
190 let typingEffect: ReturnType<typeof setInterval> | null = null
191
192 if (started) {
193 let i = 0
194 typingEffect = setInterval(() => {
195 if (i < children.length) {
196 setDisplayedText(children.substring(0, i + 1))
197 i++
198 } else {
199 if (typingEffect !== null) {
200 clearInterval(typingEffect)
201 }
202 const completeItem = sequenceCompleteItemRef.current
203 const currentItemIndex = sequenceItemIndexRef.current
204 if (completeItem && currentItemIndex !== null) {
205 completeItem(currentItemIndex)
206 }
207 }
208 }, duration)
209 }
210
211 return () => {
212 if (typingEffect !== null) {
213 clearInterval(typingEffect)
214 }
215 }
216 }, [children, duration, started])
217
218 return (
219 <MotionComponent
220 ref={elementRef}
221 className={cn("text-sm font-normal tracking-tight", className)}
222 {...props}
223 >
224 {displayedText}
225 </MotionComponent>
226 )
227}
228
229interface TerminalProps {
230 children: React.ReactNode
231 className?: string
232 sequence?: boolean
233 startOnView?: boolean
234}
235
236export const Terminal = ({
237 children,
238 className,
239 sequence = true,
240 startOnView = true,
241}: TerminalProps) => {
242 const containerRef = useRef<HTMLDivElement | null>(null)
243 const isInView = useInView(containerRef as React.RefObject<Element>, {
244 amount: 0.3,
245 once: true,
246 })
247
248 const [activeIndex, setActiveIndex] = useState(0)
249 const sequenceHasStarted = sequence ? !startOnView || isInView : false
250
251 const contextValue = useMemo<SequenceContextValue | null>(() => {
252 if (!sequence) return null
253 return {
254 completeItem: (index: number) => {
255 setActiveIndex((current) => (index === current ? current + 1 : current))
256 },
257 activeIndex,
258 sequenceStarted: sequenceHasStarted,
259 }
260 }, [sequence, activeIndex, sequenceHasStarted])
261
262 const wrappedChildren = useMemo(() => {
263 if (!sequence) return children
264 const array = Children.toArray(children)
265 return array.map((child, index) => (
266 <ItemIndexContext.Provider key={index} value={index}>
267 {child as React.ReactNode}
268 </ItemIndexContext.Provider>
269 ))
270 }, [children, sequence])
271
272 const content = (
273 <div
274 ref={containerRef}
275 className={cn(
276 "border-border bg-background z-0 h-full max-h-100 w-full max-w-lg rounded-xl border",
277 className
278 )}
279 >
280 <div className="border-border flex flex-col gap-y-2 border-b p-4">
281 <div className="flex flex-row gap-x-2">
282 <div className="h-2 w-2 rounded-full bg-red-500"></div>
283 <div className="h-2 w-2 rounded-full bg-yellow-500"></div>
284 <div className="h-2 w-2 rounded-full bg-green-500"></div>
285 </div>
286 </div>
287 <pre className="p-4">
288 <code className="grid gap-y-1 overflow-auto">{wrappedChildren}</code>
289 </pre>
290 </div>
291 )
292
293 if (!sequence) return content
294
295 return (
296 <SequenceContext.Provider value={contextValue}>
297 {content}
298 </SequenceContext.Provider>
299 )
300}
301