1"use client";
2
3import {
4 ChevronDownIcon,
5 ChevronLeftIcon,
6 ChevronRightIcon,
7 ChevronUpIcon,
8} from "lucide-react";
9import { Slot as SlotPrimitive } from "radix-ui";
10import * as React from "react";
11import { useComposedRefs } from "@/lib/compose-refs";
12import { cn } from "@/lib/utils";
13import { useAsRef } from "@/registry/bases/radix/hooks/use-as-ref";
14import { useIsomorphicLayoutEffect } from "@/registry/bases/radix/hooks/use-isomorphic-layout-effect";
15import { useLazyRef } from "@/registry/bases/radix/hooks/use-lazy-ref";
16
17const ROOT_NAME = "CompareSlider";
18const BEFORE_NAME = "CompareSliderBefore";
19const AFTER_NAME = "CompareSliderAfter";
20const LABEL_NAME = "CompareSliderLabel";
21const HANDLE_NAME = "CompareSliderHandle";
22
23const PAGE_KEYS = ["PageUp", "PageDown"];
24const ARROW_KEYS = ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"];
25
26type Interaction = "hover" | "drag";
27type Orientation = "horizontal" | "vertical";
28
29interface DivProps extends React.ComponentProps<"div"> {
30 asChild?: boolean;
31}
32
33type RootElement = React.ComponentRef<typeof CompareSlider>;
34
35function clamp(value: number, min: number, max: number): number {
36 return Math.min(Math.max(value, min), max);
37}
38
39interface StoreState {
40 value: number;
41 isDragging: boolean;
42}
43
44interface Store {
45 subscribe: (callback: () => void) => () => void;
46 getState: () => StoreState;
47 setState: <K extends keyof StoreState>(key: K, value: StoreState[K]) => void;
48 notify: () => void;
49}
50
51const StoreContext = React.createContext<Store | null>(null);
52
53function useStore<T>(
54 selector: (state: StoreState) => T,
55 ogStore?: Store | null,
56): T {
57 const contextStore = React.useContext(StoreContext);
58
59 const store = ogStore ?? contextStore;
60
61 if (!store) {
62 throw new Error(`\`useStore\` must be used within \`${ROOT_NAME}\``);
63 }
64
65 const getSnapshot = React.useCallback(
66 () => selector(store.getState()),
67 [store, selector],
68 );
69
70 return React.useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
71}
72
73interface CompareSliderContextValue {
74 interaction: Interaction;
75 orientation: Orientation;
76}
77
78const CompareSliderContext =
79 React.createContext<CompareSliderContextValue | null>(null);
80
81function useCompareSliderContext(consumerName: string) {
82 const context = React.useContext(CompareSliderContext);
83 if (!context) {
84 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
85 }
86 return context;
87}
88
89interface CompareSliderProps extends DivProps {
90 value?: number;
91 defaultValue?: number;
92 onValueChange?: (value: number) => void;
93 step?: number;
94 interaction?: Interaction;
95 orientation?: Orientation;
96}
97
98function CompareSlider(props: CompareSliderProps) {
99 const {
100 value: valueProp,
101 defaultValue = 50,
102 onValueChange,
103 step = 1,
104 interaction = "drag",
105 orientation = "horizontal",
106 className,
107 children,
108 ref,
109 onPointerMove: onPointerMoveProp,
110 onPointerUp: onPointerUpProp,
111 onPointerDown: onPointerDownProp,
112 onKeyDown: onKeyDownProp,
113 asChild,
114 ...rootProps
115 } = props;
116
117 const stateRef = useLazyRef<StoreState>(() => ({
118 value: clamp(valueProp ?? defaultValue, 0, 100),
119 isDragging: false,
120 }));
121 const listenersRef = useLazyRef(() => new Set<() => void>());
122 const onValueChangeRef = useAsRef(onValueChange);
123
124 const store = React.useMemo<Store>(() => {
125 return {
126 subscribe: (cb) => {
127 listenersRef.current.add(cb);
128 return () => listenersRef.current.delete(cb);
129 },
130 getState: () => stateRef.current,
131 setState: <K extends keyof StoreState>(key: K, value: StoreState[K]) => {
132 if (Object.is(stateRef.current[key], value)) return;
133 stateRef.current[key] = value;
134
135 if (key === "value") {
136 onValueChangeRef.current?.(value as number);
137 }
138
139 store.notify();
140 },
141 notify: () => {
142 for (const cb of listenersRef.current) {
143 cb();
144 }
145 },
146 };
147 }, [listenersRef, stateRef, onValueChangeRef]);
148
149 const rootRef = React.useRef<RootElement | null>(null);
150 const composedRef = useComposedRefs(ref, rootRef);
151 const isDraggingRef = React.useRef(false);
152
153 const propsRef = useAsRef({
154 onPointerMove: onPointerMoveProp,
155 onPointerUp: onPointerUpProp,
156 onPointerDown: onPointerDownProp,
157 onKeyDown: onKeyDownProp,
158 interaction,
159 orientation,
160 step,
161 });
162
163 const value = useStore((state) => state.value, store);
164
165 useIsomorphicLayoutEffect(() => {
166 if (valueProp !== undefined) {
167 store.setState("value", clamp(valueProp, 0, 100));
168 }
169 }, [valueProp]);
170
171 const onPointerMove = React.useCallback(
172 (event: React.PointerEvent<RootElement>) => {
173 if (!isDraggingRef.current && propsRef.current.interaction === "drag") {
174 return;
175 }
176 if (!rootRef.current) return;
177
178 propsRef.current.onPointerMove?.(event);
179 if (event.defaultPrevented) return;
180
181 const rootRect = rootRef.current.getBoundingClientRect();
182 const isVertical = propsRef.current.orientation === "vertical";
183 const position = isVertical
184 ? event.clientY - rootRect.top
185 : event.clientX - rootRect.left;
186 const size = isVertical ? rootRect.height : rootRect.width;
187 const percentage = clamp((position / size) * 100, 0, 100);
188
189 store.setState("value", percentage);
190 },
191 [propsRef, store],
192 );
193
194 const onPointerDown = React.useCallback(
195 (event: React.PointerEvent<RootElement>) => {
196 if (propsRef.current.interaction !== "drag") return;
197
198 propsRef.current.onPointerDown?.(event);
199 if (event.defaultPrevented) return;
200
201 event.currentTarget.setPointerCapture(event.pointerId);
202 isDraggingRef.current = true;
203 store.setState("isDragging", true);
204 },
205 [store, propsRef],
206 );
207
208 const onPointerUp = React.useCallback(
209 (event: React.PointerEvent<RootElement>) => {
210 if (propsRef.current.interaction !== "drag") return;
211
212 propsRef.current.onPointerUp?.(event);
213 if (event.defaultPrevented) return;
214
215 event.currentTarget.releasePointerCapture(event.pointerId);
216 isDraggingRef.current = false;
217 store.setState("isDragging", false);
218 },
219 [store, propsRef],
220 );
221
222 const onKeyDown = React.useCallback(
223 (event: React.KeyboardEvent<RootElement>) => {
224 propsRef.current.onKeyDown?.(event);
225 if (event.defaultPrevented) return;
226
227 const currentValue = store.getState().value;
228 const isVertical = propsRef.current.orientation === "vertical";
229
230 if (event.key === "Home") {
231 event.preventDefault();
232 store.setState("value", 0);
233 } else if (event.key === "End") {
234 event.preventDefault();
235 store.setState("value", 100);
236 } else if (PAGE_KEYS.concat(ARROW_KEYS).includes(event.key)) {
237 event.preventDefault();
238
239 const isPageKey = PAGE_KEYS.includes(event.key);
240 const isSkipKey =
241 isPageKey || (event.shiftKey && ARROW_KEYS.includes(event.key));
242 const multiplier = isSkipKey ? 10 : 1;
243
244 let direction = 0;
245 if (isVertical) {
246 const isDecreaseKey = ["ArrowUp", "PageUp"].includes(event.key);
247 direction = isDecreaseKey ? -1 : 1;
248 } else {
249 const isDecreaseKey = ["ArrowLeft", "PageUp"].includes(event.key);
250 direction = isDecreaseKey ? -1 : 1;
251 }
252
253 const stepInDirection = propsRef.current.step * multiplier * direction;
254 const newValue = clamp(currentValue + stepInDirection, 0, 100);
255 store.setState("value", newValue);
256 }
257 },
258 [store, propsRef],
259 );
260
261 const contextValue = React.useMemo<CompareSliderContextValue>(
262 () => ({
263 interaction,
264 orientation,
265 }),
266 [interaction, orientation],
267 );
268
269 const RootPrimitive = asChild ? SlotPrimitive.Slot : "div";
270
271 return (
272 <StoreContext.Provider value={store}>
273 <CompareSliderContext.Provider value={contextValue}>
274 <RootPrimitive
275 role="slider"
276 aria-orientation={orientation}
277 aria-valuemax={100}
278 aria-valuemin={0}
279 aria-valuenow={value}
280 data-slot="compare-slider"
281 data-orientation={orientation}
282 {...rootProps}
283 ref={composedRef}
284 tabIndex={0}
285 className={cn(
286 "relative isolate touch-none select-none overflow-hidden outline-none transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
287 orientation === "horizontal" ? "w-full" : "h-full",
288 className,
289 )}
290 onPointerDown={onPointerDown}
291 onPointerMove={onPointerMove}
292 onPointerUp={onPointerUp}
293 onPointerCancel={onPointerUp}
294 onKeyDown={onKeyDown}
295 >
296 {children}
297 </RootPrimitive>
298 </CompareSliderContext.Provider>
299 </StoreContext.Provider>
300 );
301}
302
303interface CompareSliderBeforeProps extends DivProps {
304 label?: string;
305}
306
307function CompareSliderBefore(props: CompareSliderBeforeProps) {
308 const { className, children, style, label, asChild, ref, ...beforeProps } =
309 props;
310
311 const value = useStore((state) => state.value);
312 const { orientation } = useCompareSliderContext(BEFORE_NAME);
313
314 const labelId = React.useId();
315
316 const isVertical = orientation === "vertical";
317 const clipPath = isVertical
318 ? `inset(${value}% 0 0 0)`
319 : `inset(0 0 0 ${value}%)`;
320
321 const BeforePrimitive = asChild ? SlotPrimitive.Slot : "div";
322
323 return (
324 <BeforePrimitive
325 role="img"
326 aria-labelledby={label ? labelId : undefined}
327 aria-hidden={label ? undefined : "true"}
328 data-slot="compare-slider-before"
329 data-orientation={orientation}
330 {...beforeProps}
331 ref={ref}
332 className={cn("absolute inset-0 h-full w-full object-cover", className)}
333 style={{
334 clipPath,
335 ...style,
336 }}
337 >
338 {children}
339 {label && (
340 <CompareSliderLabel id={labelId} side="before">
341 {label}
342 </CompareSliderLabel>
343 )}
344 </BeforePrimitive>
345 );
346}
347
348interface CompareSliderAfterProps extends DivProps {
349 label?: string;
350}
351
352function CompareSliderAfter(props: CompareSliderAfterProps) {
353 const { className, children, style, label, asChild, ref, ...afterProps } =
354 props;
355
356 const value = useStore((state) => state.value);
357 const { orientation } = useCompareSliderContext(AFTER_NAME);
358
359 const labelId = React.useId();
360
361 const isVertical = orientation === "vertical";
362 const clipPath = isVertical
363 ? `inset(0 0 ${100 - value}% 0)`
364 : `inset(0 ${100 - value}% 0 0)`;
365
366 const AfterPrimitive = asChild ? SlotPrimitive.Slot : "div";
367
368 return (
369 <AfterPrimitive
370 role="img"
371 aria-labelledby={label ? labelId : undefined}
372 aria-hidden={label ? undefined : "true"}
373 data-slot="compare-slider-after"
374 data-orientation={orientation}
375 {...afterProps}
376 ref={ref}
377 className={cn("absolute inset-0 h-full w-full object-cover", className)}
378 style={{
379 clipPath,
380 ...style,
381 }}
382 >
383 {children}
384 {label && (
385 <CompareSliderLabel id={labelId} side="after">
386 {label}
387 </CompareSliderLabel>
388 )}
389 </AfterPrimitive>
390 );
391}
392
393function CompareSliderHandle(props: DivProps) {
394 const { className, children, style, asChild, ref, ...handleProps } = props;
395
396 const value = useStore((state) => state.value);
397 const { interaction, orientation } = useCompareSliderContext(HANDLE_NAME);
398
399 const isVertical = orientation === "vertical";
400
401 const HandlePrimitive = asChild ? SlotPrimitive.Slot : "div";
402
403 return (
404 <HandlePrimitive
405 role="presentation"
406 aria-hidden="true"
407 data-slot="compare-slider-handle"
408 data-orientation={orientation}
409 {...handleProps}
410 ref={ref}
411 className={cn(
412 "absolute z-50 flex items-center justify-center",
413 isVertical
414 ? "left-0 h-10 w-full -translate-y-1/2"
415 : "top-0 h-full w-10 -translate-x-1/2",
416 interaction === "drag" && "cursor-grab active:cursor-grabbing",
417 className,
418 )}
419 style={{
420 [isVertical ? "top" : "left"]: `${value}%`,
421 ...style,
422 }}
423 >
424 {children ?? (
425 <>
426 <div
427 className={cn(
428 "absolute bg-background",
429 isVertical
430 ? "top-1/2 h-1 w-full -translate-y-1/2"
431 : "left-1/2 h-full w-1 -translate-x-1/2",
432 )}
433 />
434 {interaction === "drag" && (
435 <div className="z-50 flex aspect-square size-11 shrink-0 items-center justify-center rounded-full bg-background p-2 [&_svg]:size-4 [&_svg]:select-none [&_svg]:stroke-3 [&_svg]:text-muted-foreground">
436 {isVertical ? (
437 <div className="flex flex-col items-center">
438 <ChevronUpIcon />
439 <ChevronDownIcon />
440 </div>
441 ) : (
442 <div className="flex items-center">
443 <ChevronLeftIcon />
444 <ChevronRightIcon />
445 </div>
446 )}
447 </div>
448 )}
449 </>
450 )}
451 </HandlePrimitive>
452 );
453}
454
455interface CompareSliderLabelProps extends DivProps {
456 side?: "before" | "after";
457}
458
459function CompareSliderLabel(props: CompareSliderLabelProps) {
460 const { className, children, side, asChild, ref, ...labelProps } = props;
461
462 const { orientation } = useCompareSliderContext(LABEL_NAME);
463 const isVertical = orientation === "vertical";
464
465 const LabelPrimitive = asChild ? SlotPrimitive.Slot : "div";
466
467 return (
468 <LabelPrimitive
469 ref={ref}
470 data-slot="compare-slider-label"
471 className={cn(
472 "absolute z-20 rounded-md border border-border bg-background/80 px-3 py-1.5 font-medium text-sm backdrop-blur-sm",
473 isVertical
474 ? side === "before"
475 ? "top-2 left-2"
476 : "bottom-2 left-2"
477 : side === "before"
478 ? "top-2 left-2"
479 : "top-2 right-2",
480 className,
481 )}
482 {...labelProps}
483 >
484 {children}
485 </LabelPrimitive>
486 );
487}
488
489export {
490 CompareSlider,
491 CompareSliderAfter,
492 CompareSliderBefore,
493 CompareSliderHandle,
494 CompareSliderLabel,
495 type CompareSliderProps,
496};
497