1"use client";
2
3import { GripVerticalIcon } from "lucide-react";
4import {
5 type MotionValue,
6 motion,
7 useMotionValue,
8 useSpring,
9 useTransform,
10} from "motion/react";
11import {
12 type ComponentProps,
13 createContext,
14 type HTMLAttributes,
15 type MouseEventHandler,
16 type ReactNode,
17 type TouchEventHandler,
18 useContext,
19 useState,
20} from "react";
21import { cn } from "@/lib/utils";
22
23type ImageComparisonContextType = {
24 sliderPosition: number;
25 setSliderPosition: (pos: number) => void;
26 motionSliderPosition: MotionValue<number>;
27 mode: "hover" | "drag";
28};
29
30const ImageComparisonContext = createContext<
31 ImageComparisonContextType | undefined
32>(undefined);
33
34const useImageComparisonContext = () => {
35 const context = useContext(ImageComparisonContext);
36
37 if (!context) {
38 throw new Error(
39 "useImageComparisonContext must be used within a ImageComparison"
40 );
41 }
42
43 return context;
44};
45
46export type ComparisonProps = HTMLAttributes<HTMLDivElement> & {
47 mode?: "hover" | "drag";
48 onDragStart?: () => void;
49 onDragEnd?: () => void;
50};
51
52export const Comparison = ({
53 className,
54 mode = "drag",
55 onDragStart,
56 onDragEnd,
57 ...props
58}: ComparisonProps) => {
59 const [isDragging, setIsDragging] = useState(false);
60 const motionValue = useMotionValue(50);
61 const motionSliderPosition = useSpring(motionValue, {
62 bounce: 0,
63 duration: 0,
64 });
65 const [sliderPosition, setSliderPosition] = useState(50);
66
67 const handleDrag = (domRect: DOMRect, clientX: number) => {
68 if (!isDragging && mode === "drag") {
69 return;
70 }
71
72 const x = clientX - domRect.left;
73 const percentage = Math.min(Math.max((x / domRect.width) * 100, 0), 100);
74 motionValue.set(percentage);
75 setSliderPosition(percentage);
76 };
77
78 const handleMouseDrag: MouseEventHandler<HTMLDivElement> = (event) => {
79 if (!event) {
80 return;
81 }
82
83 const containerRect = event.currentTarget.getBoundingClientRect();
84
85 handleDrag(containerRect, event.clientX);
86 };
87
88 const handleTouchDrag: TouchEventHandler<HTMLDivElement> = (event) => {
89 if (!event) {
90 return;
91 }
92
93 const containerRect = event.currentTarget.getBoundingClientRect();
94 const touches = Array.from(event.touches);
95
96 handleDrag(containerRect, touches.at(0)?.clientX ?? 0);
97 };
98
99 const handleDragStart = () => {
100 if (mode === "drag") {
101 setIsDragging(true);
102 onDragStart?.();
103 }
104 };
105
106 const handleDragEnd = () => {
107 if (mode === "drag") {
108 setIsDragging(false);
109 onDragEnd?.();
110 }
111 };
112
113 return (
114 <ImageComparisonContext.Provider
115 value={{ sliderPosition, setSliderPosition, motionSliderPosition, mode }}
116 >
117 <div
118 aria-label="Comparison slider"
119 aria-valuemax={100}
120 aria-valuemin={0}
121 aria-valuenow={sliderPosition}
122 className={cn(
123 "relative isolate w-full select-none overflow-hidden",
124 className
125 )}
126 onMouseDown={handleDragStart}
127 onMouseLeave={handleDragEnd}
128 onMouseMove={handleMouseDrag}
129 onMouseUp={handleDragEnd}
130 onTouchEnd={handleDragEnd}
131 onTouchMove={handleTouchDrag}
132 onTouchStart={handleDragStart}
133 role="slider"
134 tabIndex={0}
135 {...props}
136 />
137 </ImageComparisonContext.Provider>
138 );
139};
140
141export type ComparisonItemProps = ComponentProps<typeof motion.div> & {
142 position: "left" | "right";
143};
144
145export const ComparisonItem = ({
146 className,
147 position,
148 ...props
149}: ComparisonItemProps) => {
150 const { motionSliderPosition } = useImageComparisonContext();
151 const leftClipPath = useTransform(
152 motionSliderPosition,
153 (value) => `inset(0 0 0 ${value}%)`
154 );
155 const rightClipPath = useTransform(
156 motionSliderPosition,
157 (value) => `inset(0 ${100 - value}% 0 0)`
158 );
159
160 return (
161 <motion.div
162 aria-hidden="true"
163 className={cn("absolute inset-0 h-full w-full object-cover", className)}
164 role="img"
165 style={{
166 clipPath: position === "left" ? leftClipPath : rightClipPath,
167 }}
168 {...props}
169 />
170 );
171};
172
173export type ComparisonHandleProps = ComponentProps<typeof motion.div> & {
174 children?: ReactNode;
175};
176
177export const ComparisonHandle = ({
178 className,
179 children,
180 ...props
181}: ComparisonHandleProps) => {
182 const { motionSliderPosition, mode } = useImageComparisonContext();
183 const left = useTransform(motionSliderPosition, (value) => `${value}%`);
184
185 return (
186 <motion.div
187 aria-hidden="true"
188 className={cn(
189 "-translate-x-1/2 absolute top-0 z-50 flex h-full w-10 items-center justify-center",
190 mode === "drag" && "cursor-grab active:cursor-grabbing",
191 className
192 )}
193 role="presentation"
194 style={{ left }}
195 {...props}
196 >
197 {children ?? (
198 <>
199 <div className="-translate-x-1/2 absolute left-1/2 h-full w-1 bg-background" />
200 {mode === "drag" && (
201 <div className="z-50 flex items-center justify-center rounded-sm bg-background px-0.5 py-1">
202 <GripVerticalIcon className="h-4 w-4 select-none text-muted-foreground" />
203 </div>
204 )}
205 </>
206 )}
207 </motion.div>
208 );
209};
210