A compare component from Aceternity UI.
From Aceternity UI
1"use client";
2import React, { useState, useEffect, useRef, useCallback } from "react";
3import { SparklesCore } from "@/components/ui/sparkles";
4import { AnimatePresence, motion } from "motion/react";
5import { cn } from "@/lib/utils";
6import { IconDotsVertical } from "@tabler/icons-react";
7
8interface CompareProps {
9 firstImage?: string;
10 secondImage?: string;
11 className?: string;
12 firstImageClassName?: string;
13 secondImageClassname?: string;
14 initialSliderPercentage?: number;
15 slideMode?: "hover" | "drag";
16 showHandlebar?: boolean;
17 autoplay?: boolean;
18 autoplayDuration?: number;
19}
20export const Compare = ({
21 firstImage = "",
22 secondImage = "",
23 className,
24 firstImageClassName,
25 secondImageClassname,
26 initialSliderPercentage = 50,
27 slideMode = "hover",
28 showHandlebar = true,
29 autoplay = false,
30 autoplayDuration = 5000,
31}: CompareProps) => {
32 const [sliderXPercent, setSliderXPercent] = useState(initialSliderPercentage);
33 const [isDragging, setIsDragging] = useState(false);
34
35 const sliderRef = useRef<HTMLDivElement>(null);
36
37 const [isMouseOver, setIsMouseOver] = useState(false);
38
39 const autoplayRef = useRef<NodeJS.Timeout | null>(null);
40
41 const startAutoplay = useCallback(() => {
42 if (!autoplay) return;
43
44 const startTime = Date.now();
45 const animate = () => {
46 const elapsedTime = Date.now() - startTime;
47 const progress =
48 (elapsedTime % (autoplayDuration * 2)) / autoplayDuration;
49 const percentage = progress <= 1 ? progress * 100 : (2 - progress) * 100;
50
51 setSliderXPercent(percentage);
52 autoplayRef.current = setTimeout(animate, 16); // ~60fps
53 };
54
55 animate();
56 }, [autoplay, autoplayDuration]);
57
58 const stopAutoplay = useCallback(() => {
59 if (autoplayRef.current) {
60 clearTimeout(autoplayRef.current);
61 autoplayRef.current = null;
62 }
63 }, []);
64
65 useEffect(() => {
66 startAutoplay();
67 return () => stopAutoplay();
68 }, [startAutoplay, stopAutoplay]);
69
70 function mouseEnterHandler() {
71 setIsMouseOver(true);
72 stopAutoplay();
73 }
74
75 function mouseLeaveHandler() {
76 setIsMouseOver(false);
77 if (slideMode === "hover") {
78 setSliderXPercent(initialSliderPercentage);
79 }
80 if (slideMode === "drag") {
81 setIsDragging(false);
82 }
83 startAutoplay();
84 }
85
86 const handleStart = useCallback(
87 (clientX: number) => {
88 if (slideMode === "drag") {
89 setIsDragging(true);
90 }
91 },
92 [slideMode]
93 );
94
95 const handleEnd = useCallback(() => {
96 if (slideMode === "drag") {
97 setIsDragging(false);
98 }
99 }, [slideMode]);
100
101 const handleMove = useCallback(
102 (clientX: number) => {
103 if (!sliderRef.current) return;
104 if (slideMode === "hover" || (slideMode === "drag" && isDragging)) {
105 const rect = sliderRef.current.getBoundingClientRect();
106 const x = clientX - rect.left;
107 const percent = (x / rect.width) * 100;
108 requestAnimationFrame(() => {
109 setSliderXPercent(Math.max(0, Math.min(100, percent)));
110 });
111 }
112 },
113 [slideMode, isDragging]
114 );
115
116 const handleMouseDown = useCallback(
117 (e: React.MouseEvent) => handleStart(e.clientX),
118 [handleStart]
119 );
120 const handleMouseUp = useCallback(() => handleEnd(), [handleEnd]);
121 const handleMouseMove = useCallback(
122 (e: React.MouseEvent) => handleMove(e.clientX),
123 [handleMove]
124 );
125
126 const handleTouchStart = useCallback(
127 (e: React.TouchEvent) => {
128 if (!autoplay) {
129 handleStart(e.touches[0].clientX);
130 }
131 },
132 [handleStart, autoplay]
133 );
134
135 const handleTouchEnd = useCallback(() => {
136 if (!autoplay) {
137 handleEnd();
138 }
139 }, [handleEnd, autoplay]);
140
141 const handleTouchMove = useCallback(
142 (e: React.TouchEvent) => {
143 if (!autoplay) {
144 handleMove(e.touches[0].clientX);
145 }
146 },
147 [handleMove, autoplay]
148 );
149
150 return (
151 <div
152 ref={sliderRef}
153 className={cn("w-[400px] h-[400px] overflow-hidden", className)}
154 style={{
155 position: "relative",
156 cursor: slideMode === "drag" ? "grab" : "col-resize",
157 }}
158 onMouseMove={handleMouseMove}
159 onMouseLeave={mouseLeaveHandler}
160 onMouseEnter={mouseEnterHandler}
161 onMouseDown={handleMouseDown}
162 onMouseUp={handleMouseUp}
163 onTouchStart={handleTouchStart}
164 onTouchEnd={handleTouchEnd}
165 onTouchMove={handleTouchMove}
166 >
167 <AnimatePresence initial={false}>
168 <motion.div
169 className="h-full w-px absolute top-0 m-auto z-30 bg-gradient-to-b from-transparent from-[5%] to-[95%] via-indigo-500 to-transparent"
170 style={{
171 left: `${sliderXPercent}%`,
172 top: "0",
173 zIndex: 40,
174 }}
175 transition={{ duration: 0 }}
176 >
177 <div className="w-36 h-full [mask-image:radial-gradient(100px_at_left,white,transparent)] absolute top-1/2 -translate-y-1/2 left-0 bg-gradient-to-r from-indigo-400 via-transparent to-transparent z-20 opacity-50" />
178 <div className="w-10 h-1/2 [mask-image:radial-gradient(50px_at_left,white,transparent)] absolute top-1/2 -translate-y-1/2 left-0 bg-gradient-to-r from-cyan-400 via-transparent to-transparent z-10 opacity-100" />
179 <div className="w-10 h-3/4 top-1/2 -translate-y-1/2 absolute -right-10 [mask-image:radial-gradient(100px_at_left,white,transparent)]">
180 <MemoizedSparklesCore
181 background="transparent"
182 minSize={0.4}
183 maxSize={1}
184 particleDensity={1200}
185 className="w-full h-full"
186 particleColor="#FFFFFF"
187 />
188 </div>
189 {showHandlebar && (
190 <div className="h-5 w-5 rounded-md top-1/2 -translate-y-1/2 bg-white z-30 -right-2.5 absolute flex items-center justify-center shadow-[0px_-1px_0px_0px_#FFFFFF40]">
191 <IconDotsVertical className="h-4 w-4 text-black" />
192 </div>
193 )}
194 </motion.div>
195 </AnimatePresence>
196 <div className="overflow-hidden w-full h-full relative z-20 pointer-events-none">
197 <AnimatePresence initial={false}>
198 {firstImage ? (
199 <motion.div
200 className={cn(
201 "absolute inset-0 z-20 rounded-2xl shrink-0 w-full h-full select-none overflow-hidden",
202 firstImageClassName
203 )}
204 style={{
205 clipPath: `inset(0 ${100 - sliderXPercent}% 0 0)`,
206 }}
207 transition={{ duration: 0 }}
208 >
209 <img
210 alt="first image"
211 src={firstImage}
212 className={cn(
213 "absolute inset-0 z-20 rounded-2xl shrink-0 w-full h-full select-none",
214 firstImageClassName
215 )}
216 draggable={false}
217 />
218 </motion.div>
219 ) : null}
220 </AnimatePresence>
221 </div>
222
223 <AnimatePresence initial={false}>
224 {secondImage ? (
225 <motion.img
226 className={cn(
227 "absolute top-0 left-0 z-[19] rounded-2xl w-full h-full select-none",
228 secondImageClassname
229 )}
230 alt="second image"
231 src={secondImage}
232 draggable={false}
233 />
234 ) : null}
235 </AnimatePresence>
236 </div>
237 );
238};
239
240const MemoizedSparklesCore = React.memo(SparklesCore);
241