1// npm i embla-carousel-autoplay framer-motion lucide-react
2// npx shadcn@latest add carousel
3"use client"
4
5import React, { useCallback, useEffect, useState, type JSX } from "react"
6import Image from "next/image"
7import Autoplay from "embla-carousel-autoplay"
8import { ChevronRight } from "lucide-react"
9import {
10 AnimatePresence,
11 motion,
12 MotionProps,
13 useAnimation,
14 Variants,
15} from "motion/react"
16
17import { cn } from "@/lib/utils"
18import {
19 Carousel,
20 CarouselContent,
21 CarouselItem,
22 CarouselNext,
23 CarouselPrevious,
24 type CarouselApi,
25} from "@/components/ui/carousel"
26
27interface Tip {
28 text: string
29 image: string
30 url?: string
31}
32
33interface LoadingCarouselProps {
34 tips?: Tip[]
35 className?: string
36 autoplayInterval?: number
37 showNavigation?: boolean
38 showIndicators?: boolean
39 showProgress?: boolean
40 aspectRatio?: "video" | "square" | "wide"
41 textPosition?: "top" | "bottom"
42 onTipChange?: (index: number) => void
43 backgroundTips?: boolean
44 backgroundGradient?: boolean
45 shuffleTips?: boolean
46 animateText?: boolean
47}
48
49const defaultTips: Tip[] = [
50 {
51 text: "Backend snippets. Shadcn style headless components.. but for your backend.",
52 image: "/placeholders/cult-snips.png",
53 url: "https://www.newcult.co/backend",
54 },
55 {
56 text: "Create your first directory app today. AI batch scripts to process 100s of urls in seconds.",
57 image: "/placeholders/cult-dir.png",
58 url: "https://www.newcult.co/templates/cult-seo",
59 },
60 {
61 text: "Cult landing page template. Framer motion, shadcn, and tailwind.",
62 image: "/placeholders/cult-rune.png",
63 url: "https://www.newcult.co/templates/cult-landing-page",
64 },
65 {
66 text: "Vector embeddings, semantic search, and chat based vector retrieval on easy mode.",
67 image: "/placeholders/cult-manifest.png",
68 url: "https://www.newcult.co/templates/manifest",
69 },
70 {
71 text: "SEO analysis app. Scraping, analysis, insights, and AI recommendations.",
72 image: "/placeholders/cult-seo.png",
73 url: "https://www.newcult.co/templates/cult-seo",
74 },
75]
76
77function shuffleArray<T>(array: T[]): T[] {
78 const shuffled = [...array]
79 for (let i = shuffled.length - 1; i > 0; i--) {
80 const j = Math.floor(Math.random() * (i + 1))
81 ;[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]
82 }
83 return shuffled
84}
85
86const carouselVariants: Variants = {
87 enter: (direction: number) => ({
88 x: direction > 0 ? "100%" : "-100%",
89 opacity: 0,
90 }),
91 center: {
92 x: 0,
93 opacity: 1,
94 },
95 exit: (direction: number) => ({
96 x: direction < 0 ? "100%" : "-100%",
97 opacity: 0,
98 }),
99}
100
101const textVariants: Variants = {
102 hidden: { opacity: 0, y: 20 },
103 visible: { opacity: 1, y: 0, transition: { delay: 0.3, duration: 0.5 } },
104}
105
106const aspectRatioClasses = {
107 video: "aspect-video",
108 square: "aspect-square",
109 wide: "aspect-[2/1]",
110}
111
112export function LoadingCarousel({
113 onTipChange,
114 className,
115 tips = defaultTips,
116 showProgress = true,
117 aspectRatio = "video",
118 showNavigation = false,
119 showIndicators = true,
120 backgroundTips = false,
121 textPosition = "bottom",
122 autoplayInterval = 4500,
123 backgroundGradient = false,
124 shuffleTips = false,
125 animateText = true,
126}: LoadingCarouselProps) {
127 const [progress, setProgress] = useState(0)
128 const [api, setApi] = useState<CarouselApi>()
129 const [current, setCurrent] = useState(0)
130 const [direction, setDirection] = useState(0)
131 const controls = useAnimation()
132 const [displayTips] = useState(() =>
133 shuffleTips ? shuffleArray(tips) : tips
134 )
135
136 const autoplay = Autoplay({
137 delay: autoplayInterval,
138 stopOnInteraction: false,
139 })
140
141 useEffect(() => {
142 if (!api) {
143 return
144 }
145
146 setCurrent(api.selectedScrollSnap())
147 setDirection(
148 api.scrollSnapList().indexOf(api.selectedScrollSnap()) - current
149 )
150
151 const onSelect = () => {
152 const newIndex = api.selectedScrollSnap()
153 setCurrent(newIndex)
154 setDirection(api.scrollSnapList().indexOf(newIndex) - current)
155 onTipChange?.(newIndex)
156 }
157
158 api.on("select", onSelect)
159
160 return () => {
161 api.off("select", onSelect)
162 }
163 }, [api, current, onTipChange])
164
165 useEffect(() => {
166 if (!showProgress) return
167
168 const timer = setInterval(() => {
169 setProgress((oldProgress) => {
170 if (oldProgress === 100) {
171 return 0
172 }
173 const diff = 2 // Constant increment for smoother progress
174 return Math.min(oldProgress + diff, 100)
175 })
176 }, autoplayInterval / 50)
177
178 return () => {
179 clearInterval(timer)
180 }
181 }, [showProgress, autoplayInterval])
182
183 useEffect(() => {
184 if (progress === 100) {
185 controls.start({ scaleX: 0 }).then(() => {
186 setProgress(0)
187 controls.set({ scaleX: 1 })
188 })
189 } else {
190 controls.start({ scaleX: progress / 100 })
191 }
192 }, [progress, controls])
193
194 const handleSelect = useCallback(
195 (index: number) => {
196 api?.scrollTo(index)
197 },
198 [api]
199 )
200
201 return (
202 <motion.div
203 initial={{ opacity: 0, y: 20 }}
204 animate={{ opacity: 1, y: 0 }}
205 transition={{ duration: 0.8, ease: "easeOut" }}
206 className={cn(
207 "w-full max-w-6xl mx-auto rounded-lg bg-muted shadow-[0px_1px_1px_0px_rgba(0,0,0,0.05),0px_1px_1px_0px_rgba(255,252,240,0.5)_inset,0px_0px_0px_1px_hsla(0,0%,100%,0.1)_inset,0px_0px_1px_0px_rgba(28,27,26,0.5)]",
208 className
209 )}
210 >
211 <div className="w-full overflow-hidden rounded-lg">
212 <Carousel
213 setApi={setApi}
214 plugins={[autoplay]}
215 className="w-full relative"
216 opts={{
217 loop: true,
218 }}
219 >
220 <CarouselContent>
221 <AnimatePresence initial={false} custom={direction}>
222 {(displayTips || []).map((tip, index) => (
223 <CarouselItem key={index}>
224 <motion.div
225 variants={carouselVariants}
226 initial="enter"
227 animate="center"
228 exit="exit"
229 custom={direction}
230 transition={{ duration: 0.8, ease: "easeInOut" }}
231 className={`relative ${aspectRatioClasses[aspectRatio]} w-full overflow-hidden`}
232 >
233 <Image
234 src={tip.image}
235 alt={`Visual representation for tip: ${tip.text}`}
236 fill
237 className="object-cover"
238 priority
239 />
240 {backgroundGradient && (
241 <div className="absolute inset-0 bg-gradient-to-t from-black/90 via-black/20 to-transparent" />
242 )}
243
244 {backgroundTips ? (
245 <motion.div
246 variants={textVariants}
247 initial="hidden"
248 animate="visible"
249 className={`absolute ${
250 textPosition === "top" ? "top-0" : "bottom-0"
251 } left-0 right-0 p-4 sm:p-6 md:p-8`}
252 >
253 {displayTips[current]?.url ? (
254 <a
255 href={displayTips[current]?.url}
256 target="_blank"
257 rel="noopener noreferrer"
258 >
259 <p className="text-white text-center md:text-left text-base sm:text-lg md:text-xl lg:text-2xl lg:font-bold tracking-tight font-medium leading-relaxed">
260 {tip.text}
261 </p>
262 </a>
263 ) : (
264 <p className="text-white text-center md:text-left text-base sm:text-lg md:text-xl lg:text-2xl lg:font-bold tracking-tight font-medium leading-relaxed">
265 {tip.text}
266 </p>
267 )}
268 </motion.div>
269 ) : null}
270 </motion.div>
271 </CarouselItem>
272 ))}
273 </AnimatePresence>
274 </CarouselContent>
275 {showNavigation && (
276 <>
277 <CarouselPrevious className="absolute left-2 top-1/2 -translate-y-1/2" />
278 <CarouselNext className="absolute right-2 top-1/2 -translate-y-1/2" />
279 </>
280 )}
281 </Carousel>
282 <div
283 className={cn(
284 "bg-muted p-4 ",
285 showIndicators && !backgroundTips ? "lg:py-2 lg:px-4 " : ""
286 )}
287 >
288 <div
289 className={cn(
290 "flex flex-col sm:flex-row items-center justify-between space-y-2 sm:space-y-0",
291 showIndicators && !backgroundTips
292 ? "sm:flex-col space-y-2 items-start gap-3"
293 : ""
294 )}
295 >
296 {showIndicators && (
297 <div className="flex space-x-2 overflow-x-auto pb-2 sm:pb-0 w-full sm:w-auto">
298 {(displayTips || []).map((_, index) => (
299 <motion.button
300 key={index}
301 className={`h-1 w-8 flex-shrink-0 rounded-full ${
302 index === current ? "bg-muted" : "bg-primary"
303 }`}
304 initial={false}
305 animate={{
306 backgroundColor:
307 index === current ? "#3D3D3E" : "#E6E6E4",
308 }}
309 transition={{ duration: 0.5 }}
310 onClick={() => handleSelect(index)}
311 aria-label={`Go to tip ${index + 1}`}
312 />
313 ))}
314 </div>
315 )}
316 <div className="flex items-center space-x-2 text-primary whitespace-nowrap">
317 {backgroundTips ? (
318 <span className="text-sm font-medium">
319 Tip {current + 1}/{displayTips?.length || 0}
320 </span>
321 ) : (
322 <div className="flex flex-col">
323 {displayTips[current]?.url ? (
324 <a
325 href={displayTips[current]?.url}
326 target="_blank"
327 rel="noopener noreferrer"
328 className="text-base lg:text-2xl xl:font-semibold tracking-tight font-medium"
329 >
330 {animateText ? (
331 <TextScramble
332 key={displayTips[current]?.text}
333 duration={1.2}
334 characterSet=". "
335 >
336 {displayTips[current]?.text}
337 </TextScramble>
338 ) : (
339 displayTips[current]?.text
340 )}
341 </a>
342 ) : (
343 <span className="text-base lg:text-2xl xl:font-semibold tracking-tight font-medium">
344 {animateText ? (
345 <TextScramble
346 key={displayTips[current]?.text}
347 duration={1.2}
348 characterSet=". "
349 >
350 {displayTips[current]?.text}
351 </TextScramble>
352 ) : (
353 displayTips[current]?.text
354 )}
355 </span>
356 )}
357 </div>
358 )}
359 {backgroundTips && <ChevronRight className="w-4 h-4" />}
360 </div>
361 </div>
362 {showProgress && (
363 <motion.div
364 initial={{ scaleX: 0 }}
365 animate={controls}
366 transition={{ duration: 0.5, ease: "linear" }}
367 className="h-1 bg-muted origin-left mt-2"
368 />
369 )}
370 </div>
371 </div>
372 </motion.div>
373 )
374}
375
376// Credit -> https://motion-primitives.com/docs/text-scramble
377// https://x.com/Ibelick
378type TextScrambleProps = {
379 children: string
380 duration?: number
381 speed?: number
382 characterSet?: string
383 as?: React.ElementType
384 className?: string
385 trigger?: boolean
386 onScrambleComplete?: () => void
387} & MotionProps
388
389const defaultChars =
390 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
391
392function TextScramble({
393 children,
394 duration = 0.8,
395 speed = 0.04,
396 characterSet = defaultChars,
397 className,
398 as: Component = "p",
399 trigger = true,
400 onScrambleComplete,
401 ...props
402}: TextScrambleProps) {
403 const MotionComponent = motion.create(
404 Component as keyof JSX.IntrinsicElements
405 )
406 const [displayText, setDisplayText] = useState(children)
407 const [isAnimating, setIsAnimating] = useState(false)
408 const text = children
409
410 const scramble = async () => {
411 if (isAnimating) return
412 setIsAnimating(true)
413
414 const steps = duration / speed
415 let step = 0
416
417 const interval = setInterval(() => {
418 let scrambled = ""
419 const progress = step / steps
420
421 for (let i = 0; i < text.length; i++) {
422 if (text[i] === " ") {
423 scrambled += " "
424 continue
425 }
426
427 if (progress * text.length > i) {
428 scrambled += text[i]
429 } else {
430 scrambled +=
431 characterSet[Math.floor(Math.random() * characterSet.length)]
432 }
433 }
434
435 setDisplayText(scrambled)
436 step++
437
438 if (step > steps) {
439 clearInterval(interval)
440 setDisplayText(text)
441 setIsAnimating(false)
442 onScrambleComplete?.()
443 }
444 }, speed * 1000)
445 }
446
447 useEffect(() => {
448 if (!trigger) return
449
450 scramble()
451 }, [trigger])
452
453 return (
454 <MotionComponent className={className} {...props}>
455 {displayText}
456 </MotionComponent>
457 )
458}
459
460export default LoadingCarousel
461