A composable Reel component that looks like Instagram Stories - a full-height, 9:16 aspect ratio container with video playback and progress indicators.
1"use client";
2
3import { useControllableState } from "@radix-ui/react-use-controllable-state";
4import {
5 ChevronLeft,
6 ChevronRight,
7 Pause,
8 Play,
9 Volume2,
10 VolumeX,
11} from "lucide-react";
12import { AnimatePresence, motion } from "motion/react";
13import type {
14 ComponentProps,
15 HTMLAttributes,
16 MouseEventHandler,
17 ReactNode,
18 VideoHTMLAttributes,
19} from "react";
20import {
21 createContext,
22 useCallback,
23 useContext,
24 useEffect,
25 useRef,
26 useState,
27} from "react";
28import { Button } from "@/components/ui/button";
29import { Progress } from "@/components/ui/progress";
30import { cn } from "@/lib/utils";
31
32// Explicit type for reel items
33export type ReelItem = {
34 id: string | number;
35 type: "video" | "image";
36 src: string;
37 duration: number; // Duration in seconds for both video and image
38 alt?: string;
39 title?: string;
40 description?: string;
41};
42
43type ReelContextType = {
44 currentIndex: number;
45 setCurrentIndex: (index: number) => void;
46 isPlaying: boolean;
47 setIsPlaying: (playing: boolean) => void;
48 isMuted: boolean;
49 setIsMuted: (muted: boolean) => void;
50 progress: number;
51 setProgress: (progress: number) => void;
52 duration: number;
53 setDuration: (duration: number) => void;
54 data: ReelItem[];
55 currentItem: ReelItem;
56 isNavigating: boolean;
57 setIsNavigating: (navigating: boolean) => void;
58 isTransitioning: boolean;
59 setIsTransitioning: (transitioning: boolean) => void;
60};
61
62const ReelContext = createContext<ReelContextType | undefined>(undefined);
63
64const useReelContext = () => {
65 const context = useContext(ReelContext);
66 if (!context) {
67 throw new Error("useReelContext must be used within a Reel");
68 }
69 return context;
70};
71
72export type ReelProps = HTMLAttributes<HTMLDivElement> & {
73 data: ReelItem[];
74 defaultIndex?: number;
75 index?: number;
76 onIndexChange?: (index: number) => void;
77 defaultPlaying?: boolean;
78 playing?: boolean;
79 onPlayingChange?: (playing: boolean) => void;
80 defaultMuted?: boolean;
81 muted?: boolean;
82 onMutedChange?: (muted: boolean) => void;
83 autoPlay?: boolean;
84};
85
86export const Reel = ({
87 className,
88 data,
89 defaultIndex = 0,
90 index: controlledIndex,
91 onIndexChange: controlledOnIndexChange,
92 defaultPlaying,
93 playing: controlledPlaying,
94 onPlayingChange: controlledOnPlayingChange,
95 defaultMuted = true,
96 muted: controlledMuted,
97 onMutedChange: controlledOnMutedChange,
98 autoPlay = true,
99 ...props
100}: ReelProps) => {
101 const [currentIndex, setCurrentIndexState] = useControllableState({
102 defaultProp: defaultIndex,
103 prop: controlledIndex,
104 onChange: controlledOnIndexChange,
105 });
106
107 const [isPlaying, setIsPlaying] = useControllableState({
108 defaultProp: defaultPlaying ?? autoPlay,
109 prop: controlledPlaying,
110 onChange: controlledOnPlayingChange,
111 });
112
113 const [isMuted, setIsMuted] = useControllableState({
114 defaultProp: defaultMuted,
115 prop: controlledMuted,
116 onChange: controlledOnMutedChange,
117 });
118
119 const [progress, setProgress] = useState(0);
120 const [duration, setDuration] = useState(0);
121 const [isNavigating, setIsNavigating] = useState(false);
122 const [isTransitioning, setIsTransitioning] = useState(false);
123
124 const setCurrentIndex = useCallback(
125 (index: number) => {
126 setIsTransitioning(true);
127 setProgress(0); // Reset progress immediately to prevent showing 100% during transition
128 setCurrentIndexState(index);
129 },
130 [setCurrentIndexState]
131 );
132
133 const currentItem = data[currentIndex];
134
135 return (
136 <ReelContext.Provider
137 value={{
138 currentIndex,
139 setCurrentIndex,
140 isPlaying,
141 setIsPlaying,
142 isMuted,
143 setIsMuted,
144 progress,
145 setProgress,
146 duration,
147 setDuration,
148 data,
149 currentItem,
150 isNavigating,
151 setIsNavigating,
152 isTransitioning,
153 setIsTransitioning,
154 }}
155 >
156 <div
157 className={cn(
158 "relative isolate h-full w-auto overflow-hidden bg-black",
159 "aspect-[9/16]",
160 className
161 )}
162 {...props}
163 />
164 </ReelContext.Provider>
165 );
166};
167
168export type ReelContentProps = Omit<
169 HTMLAttributes<HTMLDivElement>,
170 "children"
171> & {
172 children: (item: ReelItem, index: number) => ReactNode;
173};
174
175export const ReelContent = ({
176 className,
177 children,
178 ...props
179}: ReelContentProps) => {
180 const { currentIndex, currentItem, setIsTransitioning } = useReelContext();
181
182 const renderContent = () => {
183 if (typeof children === "function") {
184 return children(currentItem, currentIndex);
185 }
186 const childrenArray = Array.isArray(children) ? children : [children];
187 return childrenArray[currentIndex];
188 };
189
190 return (
191 <div
192 className={cn("relative size-full", className)}
193 data-reel-content
194 {...props}
195 >
196 <AnimatePresence mode="wait">
197 <motion.div
198 animate={{ opacity: 1 }}
199 className="absolute inset-0"
200 exit={{ opacity: 0 }}
201 initial={{ opacity: 0 }}
202 key={currentIndex}
203 onAnimationComplete={() => {
204 // Mark transition as complete when fade-in completes
205 setIsTransitioning(false);
206 }}
207 transition={{ duration: 0.3 }}
208 >
209 {renderContent()}
210 </motion.div>
211 </AnimatePresence>
212 </div>
213 );
214};
215
216export type ReelItemProps = HTMLAttributes<HTMLDivElement>;
217
218export const ReelItem = ({ className, ...props }: ReelItemProps) => (
219 <div
220 className={cn("relative size-full overflow-hidden", className)}
221 data-reel-item
222 {...props}
223 />
224);
225
226export type ReelVideoProps = VideoHTMLAttributes<HTMLVideoElement>;
227
228const MS_TO_SECONDS = 1000;
229const PERCENTAGE = 100;
230
231export const ReelVideo = ({ className, ...props }: ReelVideoProps) => {
232 const videoRef = useRef<HTMLVideoElement>(null);
233 const {
234 isPlaying,
235 isMuted,
236 setDuration,
237 setProgress,
238 currentIndex,
239 setCurrentIndex,
240 data,
241 progress,
242 currentItem,
243 isTransitioning,
244 } = useReelContext();
245 const animationFrameRef = useRef<number | undefined>(undefined);
246 const startTimeRef = useRef<number | undefined>(undefined);
247 const pausedProgressRef = useRef<number>(0);
248 const duration = currentItem.duration;
249
250 // Set duration when component mounts or currentIndex changes
251 useEffect(() => {
252 setDuration(duration);
253 // Don't reset progress here anymore - it's handled in ReelContent after transition
254 if (!isTransitioning) {
255 pausedProgressRef.current = 0;
256 }
257 }, [duration, setDuration, isTransitioning]);
258
259 // Handle muting
260 useEffect(() => {
261 const video = videoRef.current;
262 if (!video) {
263 return;
264 }
265 video.muted = isMuted;
266 }, [isMuted]);
267
268 // Store progress when pausing
269 useEffect(() => {
270 if (!isPlaying) {
271 pausedProgressRef.current = progress;
272 }
273 }, [isPlaying, progress]);
274
275 // Handle play/pause with duration-based progress
276 useEffect(() => {
277 const video = videoRef.current;
278 if (!video) {
279 return;
280 }
281
282 if (isPlaying && !isTransitioning) {
283 video.play().catch(() => {
284 // Ignore autoplay errors
285 });
286
287 // Start progress animation only when not transitioning
288 const elapsedTime = (pausedProgressRef.current * duration) / PERCENTAGE;
289 startTimeRef.current = performance.now() - elapsedTime * MS_TO_SECONDS;
290
291 const updateProgress = (currentTime: number) => {
292 const elapsed =
293 (currentTime - (startTimeRef.current || 0)) / MS_TO_SECONDS;
294 const newProgress = (elapsed / duration) * PERCENTAGE;
295
296 if (newProgress >= PERCENTAGE) {
297 const totalItems = data?.length || 0;
298 if (currentIndex < totalItems - 1) {
299 setCurrentIndex(currentIndex + 1);
300 } else {
301 setCurrentIndex(0);
302 }
303 } else {
304 setProgress(newProgress);
305 animationFrameRef.current = requestAnimationFrame(updateProgress);
306 }
307 };
308
309 animationFrameRef.current = requestAnimationFrame(updateProgress);
310 } else if (!isTransitioning) {
311 video.pause();
312 }
313
314 return () => {
315 if (animationFrameRef.current) {
316 cancelAnimationFrame(animationFrameRef.current);
317 }
318 };
319 }, [
320 isPlaying,
321 duration,
322 currentIndex,
323 setProgress,
324 setCurrentIndex,
325 data,
326 isTransitioning,
327 ]);
328
329 // biome-ignore lint/correctness/useExhaustiveDependencies: Reset video when index changes
330 useEffect(() => {
331 const video = videoRef.current;
332 if (video) {
333 video.currentTime = 0;
334 }
335 }, [currentIndex]);
336
337 return (
338 <video
339 className={cn("absolute inset-0 size-full object-cover", className)}
340 loop
341 muted={isMuted}
342 playsInline
343 ref={videoRef}
344 {...props}
345 />
346 );
347};
348
349export type ReelImageProps = Omit<ComponentProps<"img">, "alt"> & {
350 alt: string;
351 duration?: number;
352 width?: number | string;
353 height?: number | string;
354};
355
356const DEFAULT_IMAGE_DURATION = 5;
357
358export const ReelImage = ({
359 className,
360 alt,
361 duration = DEFAULT_IMAGE_DURATION,
362 width,
363 height,
364 ...props
365}: ReelImageProps) => {
366 const {
367 isPlaying,
368 setDuration,
369 setProgress,
370 currentIndex,
371 setCurrentIndex,
372 data,
373 progress,
374 isTransitioning,
375 } = useReelContext();
376 const animationFrameRef = useRef<number | undefined>(undefined);
377 const startTimeRef = useRef<number | undefined>(undefined);
378 const pausedProgressRef = useRef<number>(0);
379
380 // biome-ignore lint/correctness/useExhaustiveDependencies: Reset progress when index changes
381 useEffect(() => {
382 setDuration(duration);
383 // Don't reset progress here anymore - it's handled in ReelContent after transition
384 if (!isTransitioning) {
385 pausedProgressRef.current = 0;
386 }
387 }, [currentIndex, duration, setDuration, isTransitioning]);
388
389 // Handle play/pause
390 useEffect(() => {
391 if (isPlaying && !isTransitioning) {
392 const elapsedTime = (pausedProgressRef.current * duration) / PERCENTAGE;
393 startTimeRef.current = performance.now() - elapsedTime * MS_TO_SECONDS;
394
395 const updateProgress = (currentTime: number) => {
396 const elapsed =
397 (currentTime - (startTimeRef.current || 0)) / MS_TO_SECONDS;
398 const newProgress = (elapsed / duration) * PERCENTAGE;
399
400 if (newProgress >= PERCENTAGE) {
401 const totalItems = data?.length || 0;
402
403 if (currentIndex < totalItems - 1) {
404 setCurrentIndex(currentIndex + 1);
405 } else {
406 setCurrentIndex(0);
407 }
408 } else {
409 setProgress(newProgress);
410 pausedProgressRef.current = newProgress;
411 animationFrameRef.current = requestAnimationFrame(updateProgress);
412 }
413 };
414
415 animationFrameRef.current = requestAnimationFrame(updateProgress);
416 } else if (!isTransitioning) {
417 pausedProgressRef.current = progress;
418 }
419
420 return () => {
421 if (animationFrameRef.current) {
422 cancelAnimationFrame(animationFrameRef.current);
423 }
424 };
425 }, [
426 isPlaying,
427 duration,
428 currentIndex,
429 setProgress,
430 setCurrentIndex,
431 data,
432 progress,
433 isTransitioning,
434 ]);
435
436 return (
437 // biome-ignore lint/performance/noImgElement: "Reel is framework-agnostic"
438 <img
439 alt={alt}
440 className={cn("absolute inset-0 size-full object-cover", className)}
441 height={height}
442 width={width}
443 {...props}
444 />
445 );
446};
447
448export type ReelProgressProps = HTMLAttributes<HTMLDivElement> & {
449 children?: (
450 item: ReelItem,
451 index: number,
452 isActive: boolean,
453 progress: number
454 ) => ReactNode;
455};
456
457export const ReelProgress = ({
458 className,
459 children,
460 ...props
461}: ReelProgressProps) => {
462 const { progress, currentIndex, data } = useReelContext();
463 const FULL_PROGRESS = 100;
464
465 const calculateProgress = (index: number) => {
466 if (index < currentIndex) {
467 return FULL_PROGRESS;
468 }
469 if (index === currentIndex) {
470 return progress;
471 }
472
473 return 0;
474 };
475
476 if (typeof children === "function") {
477 return (
478 <div
479 className={cn(
480 "absolute top-0 right-0 left-0 z-40 flex gap-1 p-2",
481 className
482 )}
483 {...props}
484 >
485 {data.map((item, index) => (
486 <div className="relative flex-1" key={`${item.id}-progress`}>
487 {children(
488 item,
489 index,
490 index === currentIndex,
491 calculateProgress(index)
492 )}
493 </div>
494 ))}
495 </div>
496 );
497 }
498
499 return (
500 <div
501 className={cn(
502 "absolute top-0 right-0 left-0 z-40 flex gap-1 p-2",
503 className
504 )}
505 {...props}
506 >
507 {data.map((item, index) => (
508 <Progress
509 className="h-0.5 flex-1 bg-white/30 [&>div]:bg-white [&>div]:transition-none"
510 key={`${item.id}-progress`}
511 value={calculateProgress(index)}
512 />
513 ))}
514 </div>
515 );
516};
517
518export type ReelControlsProps = HTMLAttributes<HTMLDivElement>;
519
520export const ReelControls = ({ className, ...props }: ReelControlsProps) => (
521 <div
522 className={cn(
523 "absolute right-0 bottom-0 left-0 z-20 flex items-center justify-between p-4",
524 "bg-gradient-to-t from-black/60 to-transparent",
525 className
526 )}
527 {...props}
528 />
529);
530
531export type ReelPreviousButtonProps = ComponentProps<typeof Button>;
532
533export const ReelPreviousButton = ({
534 className,
535 children,
536 ...props
537}: ReelPreviousButtonProps) => {
538 const { currentIndex, setCurrentIndex, setIsNavigating } = useReelContext();
539 const NAVIGATION_RESET_DELAY = 50;
540
541 const handlePrevious = () => {
542 if (currentIndex > 0) {
543 setIsNavigating(true);
544 setCurrentIndex(currentIndex - 1);
545 setTimeout(() => setIsNavigating(false), NAVIGATION_RESET_DELAY);
546 }
547 };
548
549 return (
550 <Button
551 aria-label="Previous"
552 className={cn(
553 "rounded-full text-white hover:bg-white/10 hover:text-white",
554 className
555 )}
556 disabled={currentIndex === 0}
557 onClick={handlePrevious}
558 size="icon"
559 type="button"
560 variant="ghost"
561 {...props}
562 >
563 {children || <ChevronLeft className="size-4" />}
564 </Button>
565 );
566};
567
568export type ReelNextButtonProps = ComponentProps<typeof Button>;
569
570export const ReelNextButton = ({
571 className,
572 children,
573 ...props
574}: ReelNextButtonProps) => {
575 const { currentIndex, setCurrentIndex, data, setIsNavigating } =
576 useReelContext();
577 const totalItems = data?.length || 0;
578 const NAVIGATION_RESET_DELAY = 50;
579
580 const handleNext = () => {
581 if (currentIndex < totalItems - 1) {
582 setIsNavigating(true);
583 setCurrentIndex(currentIndex + 1);
584 setTimeout(() => setIsNavigating(false), NAVIGATION_RESET_DELAY);
585 }
586 };
587
588 return (
589 <Button
590 aria-label="Next"
591 className={cn(
592 "rounded-full text-white hover:bg-white/10 hover:text-white",
593 className
594 )}
595 disabled={currentIndex === totalItems - 1}
596 onClick={handleNext}
597 size="icon"
598 type="button"
599 variant="ghost"
600 {...props}
601 >
602 {children || <ChevronRight className="size-4" />}
603 </Button>
604 );
605};
606
607export type ReelPlayButtonProps = ComponentProps<typeof Button>;
608
609export const ReelPlayButton = ({
610 className,
611 children,
612 ...props
613}: ReelPlayButtonProps) => {
614 const { isPlaying, setIsPlaying } = useReelContext();
615
616 return (
617 <Button
618 aria-label={isPlaying ? "Pause" : "Play"}
619 className={cn(
620 "rounded-full text-white hover:bg-white/10 hover:text-white",
621 className
622 )}
623 onClick={() => setIsPlaying(!isPlaying)}
624 size="icon"
625 variant="ghost"
626 {...props}
627 >
628 {children ||
629 (isPlaying ? (
630 <Pause className="size-4" />
631 ) : (
632 <Play className="size-4" />
633 ))}
634 </Button>
635 );
636};
637
638export type ReelMuteButtonProps = ComponentProps<typeof Button>;
639
640export const ReelMuteButton = ({
641 className,
642 children,
643 ...props
644}: ReelMuteButtonProps) => {
645 const { isMuted, setIsMuted } = useReelContext();
646
647 return (
648 <Button
649 aria-label={isMuted ? "Unmute" : "Mute"}
650 className={cn(
651 "rounded-full text-white hover:bg-white/10 hover:text-white",
652 className
653 )}
654 onClick={() => setIsMuted(!isMuted)}
655 size="icon"
656 variant="ghost"
657 {...props}
658 >
659 {children ||
660 (isMuted ? (
661 <VolumeX className="size-4" />
662 ) : (
663 <Volume2 className="size-4" />
664 ))}
665 </Button>
666 );
667};
668
669export type ReelNavigationProps = HTMLAttributes<HTMLButtonElement>;
670
671export const ReelNavigation = ({
672 className,
673 ...props
674}: ReelNavigationProps) => {
675 const { setCurrentIndex, currentIndex, data, setIsNavigating } =
676 useReelContext();
677 const totalItems = data?.length || 0;
678 const NAVIGATION_RESET_DELAY = 50;
679 const HALF_WIDTH_DIVISOR = 2;
680
681 const handleClick: MouseEventHandler<HTMLButtonElement> = (e) => {
682 const rect = e.currentTarget.getBoundingClientRect();
683 const x = e.clientX - rect.left;
684 const width = rect.width;
685
686 if (x < width / HALF_WIDTH_DIVISOR) {
687 if (currentIndex > 0) {
688 setIsNavigating(true);
689 setCurrentIndex(currentIndex - 1);
690 setTimeout(() => setIsNavigating(false), NAVIGATION_RESET_DELAY);
691 }
692 } else if (currentIndex < totalItems - 1) {
693 setIsNavigating(true);
694 setCurrentIndex(currentIndex + 1);
695 setTimeout(() => setIsNavigating(false), NAVIGATION_RESET_DELAY);
696 }
697 };
698
699 return (
700 <button
701 className={cn("absolute inset-0 z-10 flex", className)}
702 onClick={handleClick}
703 type="button"
704 {...props}
705 >
706 <div className="flex-1 cursor-pointer" />
707 <div className="flex-1 cursor-pointer" />
708 </button>
709 );
710};
711
712export type ReelOverlayProps = HTMLAttributes<HTMLDivElement>;
713
714export const ReelOverlay = ({ className, ...props }: ReelOverlayProps) => (
715 <div
716 className={cn("pointer-events-none absolute inset-0 z-30", className)}
717 {...props}
718 />
719);
720
721export type ReelHeaderProps = HTMLAttributes<HTMLDivElement>;
722
723export const ReelHeader = ({ className, ...props }: ReelHeaderProps) => (
724 <div
725 className={cn(
726 "absolute top-0 right-0 left-0 z-20 p-4 pt-6",
727 "bg-gradient-to-b from-black/60 to-transparent",
728 className
729 )}
730 {...props}
731 />
732);
733
734export type ReelFooterProps = HTMLAttributes<HTMLDivElement>;
735
736export const ReelFooter = ({ className, ...props }: ReelFooterProps) => (
737 <div
738 className={cn(
739 "absolute right-0 bottom-0 left-0 z-20 p-4",
740 "bg-gradient-to-t from-black/60 to-transparent",
741 className
742 )}
743 {...props}
744 />
745);
746