Image Compare
SaveA before and after comparison split by a divider you drag, click, flick, or move with the keyboard, with labels that fade as the divider covers them.
- Category
- Data display
- Version
- 0.1.0
- Frameworks
- Next.js, Vite + React
- Styling
- Tailwind CSS v4
Preview
Image Compare preview
RawGraded
Installation
npx @shakenui/cli add image-compareReview the plan first. A dry run lists every file and package without changing anything:
npx @shakenui/cli add image-compare --dry-runUsage
image-compare-example.tsx
"use client";
import { useId } from "react";
import { ImageCompare } from "@/components/shaken/ui/image-compare";
type Palette = { skyTop: string; skyHorizon: string; sun: string; far: string; mid: string; near: string; water: string; glint: string };
// The same frame twice: as the flat, cool raw capture and after a warm evening grade.
const raw: Palette = {
skyTop: "#8b93a1",
skyHorizon: "#c3c0ba",
sun: "#e9e5dd",
far: "#8a8d95",
mid: "#6f737c",
near: "#52565f",
water: "#9a9fa7",
glint: "#d9d6d0",
};
const graded: Palette = {
skyTop: "#1d2747",
skyHorizon: "#f39a6a",
sun: "#ffd7a1",
far: "#7a5f8f",
mid: "#463d6b",
near: "#1d1f3d",
water: "#3a3560",
glint: "#ffc58f",
};
function Landscape({ palette, label }: { palette: Palette; label: string }) {
const id = useId();
return (
<svg role="img" aria-label={label} viewBox="0 0 400 300" preserveAspectRatio="xMidYMid slice">
<defs>
<linearGradient id={`${id}-sky`} x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stopColor={palette.skyTop} />
<stop offset="1" stopColor={palette.skyHorizon} />
</linearGradient>
<radialGradient id={`${id}-sun`}>
<stop offset="0" stopColor={palette.sun} />
<stop offset="0.35" stopColor={palette.sun} stopOpacity="0.9" />
<stop offset="1" stopColor={palette.sun} stopOpacity="0" />
</radialGradient>
<linearGradient id={`${id}-water`} x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stopColor={palette.glint} stopOpacity="0.55" />
<stop offset="0.4" stopColor={palette.water} />
<stop offset="1" stopColor={palette.near} />
</linearGradient>
</defs>
<rect width="400" height="300" fill={`url(#${id}-sky)`} />
<circle cx="250" cy="176" r="70" fill={`url(#${id}-sun)`} />
<path d="M0 178 C 60 150 110 160 160 146 S 260 132 300 150 S 370 150 400 140 V 200 H 0 Z" fill={palette.far} />
<path d="M0 196 C 50 176 90 186 140 170 S 230 168 270 182 S 350 178 400 168 V 210 H 0 Z" fill={palette.mid} />
<rect y="206" width="400" height="94" fill={`url(#${id}-water)`} />
<g stroke={palette.glint} strokeLinecap="round" strokeOpacity="0.7">
<path d="M222 220h56M232 232h36M240 244h20M244 256h12" strokeWidth="2" />
</g>
<path d="M0 236 C 40 220 70 214 110 222 S 150 240 170 300 H 0 Z" fill={palette.near} />
<path d="M400 228 C 360 218 330 222 300 234 S 268 270 262 300 H 400 Z" fill={palette.near} />
</svg>
);
}
export default function ImageCompareExample() {
return (
<figure className="grid w-full max-w-lg gap-2.5">
<ImageCompare
before={<Landscape palette={raw} label="Lake at dusk, raw capture" />}
after={<Landscape palette={graded} label="Lake at dusk, with the evening grade" />}
beforeLabel="Raw"
afterLabel="Graded"
defaultPosition={42}
/>
<figcaption className="text-xs text-zinc-500">Drag or flick the divider. Evening grade, exposure +0.4, warmth +18.</figcaption>
</figure>
);
}States
Every state, rendered from local fixture data.
Image Compare states
Vertical
DraftUpscaled 4x
No labels, no flick
API
| Prop | Type | Default | Description |
|---|---|---|---|
| before / after | ReactNode | — | The two layers. An img, picture, svg or canvas fills the frame; before is on the left, or on top when vertical. |
| beforeLabel / afterLabel | ReactNode | "Before" / "After" | Labels over each side. Pass null to hide one. |
| position / defaultPosition | number | 50 | Divider position from 0 (all after) to 100 (all before), controlled or starting. |
| onPositionChange | (position: number) => void | — | Called as the divider moves. |
| orientation | "horizontal" | "vertical" | "horizontal" | vertical stacks before over after with a horizontal divider. |
| flick | boolean | true | A quick release sends the divider gliding to the edge with the speed it was given. |
| aria-label | string | "Divider position" | Accessible name of the divider. |
| className | string | — | Classes for the frame. Set the aspect ratio here; the default is 4:3. |
Accessibility
- The divider grip is role="slider" with aria-valuenow from 0 to 100, aria-orientation, and a value text such as "42% before, 58% after".
- Arrow keys move it by 1, Shift with an arrow or Page Up and Page Down by 10, Home and End to the edges; keyboard moves are instant.
- Pressing anywhere in the frame glides the divider there and keeps following the pointer; the grip never leaves the frame, so its focus ring is always visible.
- Touch scrolling still works across the divider's axis (touch-action pan-y, or pan-x when vertical).
- With reduced motion preferred, clicks and flicks move the divider without gliding.
Files
Installed into src/components/shaken, or components/shaken when the project has no src directory.
src/components/shaken/ui/image-compare.tsximage-compare- npm packages: motion@^14.14.0React and Tailwind CSS v4 required
Source
The exact source the CLI installs, from /r/items/react/image-compare/0.1.0.json.
ui/image-compare.tsxShowHide
ui/image-compare.tsx
"use client";
import {
animate,
motion,
useMotionValue,
useMotionValueEvent,
useReducedMotion,
useTransform,
type AnimationPlaybackControls,
} from "motion/react";
import { type ComponentProps, type KeyboardEvent, type PointerEvent, type ReactNode, useEffect, useRef, useState } from "react";
function cx(...classes: (string | false | null | undefined)[]) {
return classes.filter(Boolean).join(" ");
}
export interface ImageCompareProps extends Omit<ComponentProps<"div">, "children" | "defaultValue" | "onChange"> {
/** Shown on the left, or on top when vertical. An `<img>`, `<picture>`, `<svg>` or `<canvas>` fills the frame. */
before: ReactNode;
/** Shown on the right, or at the bottom when vertical. */
after: ReactNode;
/** Label over the before side. Pass `null` to hide it. */
beforeLabel?: ReactNode;
/** Label over the after side. Pass `null` to hide it. */
afterLabel?: ReactNode;
/** Divider position from 0 (all after) to 100 (all before). Pass with `onPositionChange` to control it. */
position?: number;
/** Starting position when uncontrolled. */
defaultPosition?: number;
/** Called as the divider moves, with the new position from 0 to 100. */
onPositionChange?: (position: number) => void;
/** `vertical` stacks before over after with a horizontal divider. */
orientation?: "horizontal" | "vertical";
/** Lets a quick flick send the divider gliding to the edge. */
flick?: boolean;
/** Accessible name of the divider. */
"aria-label"?: string;
}
const clamp = (value: number) => Math.min(100, Math.max(0, value));
// A release faster than this, in percent of the frame per second, counts as a flick.
const FLICK_SPEED = 140;
/**
* Before and after, split by a divider you drag, click, or move with the keyboard. Flick the
* divider and it glides on to the edge with the speed you gave it. The labels fade as the
* divider covers them.
*/
export function ImageCompare({
before,
after,
beforeLabel = "Before",
afterLabel = "After",
position: positionProp,
defaultPosition = 50,
onPositionChange,
orientation = "horizontal",
flick = true,
className,
"aria-label": ariaLabel = "Divider position",
...props
}: ImageCompareProps) {
const vertical = orientation === "vertical";
const reduceMotion = useReducedMotion();
const frameRef = useRef<HTMLDivElement>(null);
const position = useMotionValue(clamp(positionProp ?? defaultPosition));
const glide = useRef<AnimationPlaybackControls | null>(null);
const drag = useRef<{ pointerId: number; offset: number; samples: { t: number; p: number }[] } | null>(null);
const [dragging, setDragging] = useState(false);
const [rounded, setRounded] = useState(Math.round(position.get()));
// Follow a controlled position unless the user is dragging.
useEffect(() => {
if (positionProp == null || drag.current) return;
glide.current?.stop();
position.set(clamp(positionProp));
}, [positionProp, position]);
const lastReported = useRef(position.get());
useMotionValueEvent(position, "change", (value) => {
const next = Math.round(value);
setRounded((current) => (current === next ? current : next));
if (Math.abs(value - lastReported.current) >= 0.1) {
lastReported.current = value;
onPositionChange?.(value);
}
});
const clip = useTransform(position, (value) => (vertical ? `inset(0 0 ${100 - value}% 0)` : `inset(0 ${100 - value}% 0 0)`));
const lineTransform = useTransform(position, (value) => (vertical ? `translateY(${value}%)` : `translateX(${value}%)`));
// The grip stops 18px short of each edge so it is never cut off; the hairline goes all the way.
const gripTransform = useTransform(position, (value) => {
const at = `clamp(18px, ${value}%, calc(100% - 18px))`;
return vertical ? `translateY(${at})` : `translateX(${at})`;
});
const beforeLabelOpacity = useTransform(position, [8, 18], [0, 1]);
const afterLabelOpacity = useTransform(position, [82, 92], [1, 0]);
function pointToPercent(event: PointerEvent<HTMLElement>) {
const rect = frameRef.current?.getBoundingClientRect();
if (!rect) return position.get();
return vertical ? ((event.clientY - rect.top) / rect.height) * 100 : ((event.clientX - rect.left) / rect.width) * 100;
}
function moveTo(target: number, velocity = 0) {
glide.current?.stop();
if (reduceMotion) {
position.set(target);
return;
}
glide.current = animate(position, target, { type: "spring", visualDuration: 0.42, bounce: 0, velocity });
}
function onPointerDown(event: PointerEvent<HTMLDivElement>) {
if (event.button !== 0 || !event.isPrimary) return;
const point = pointToPercent(event);
const onHandle = (event.target as HTMLElement).closest("[data-compare-handle]") !== null;
event.currentTarget.setPointerCapture(event.pointerId);
glide.current?.stop();
// Grabbing the handle keeps the grab point under the pointer; pressing elsewhere glides there.
const offset = onHandle ? point - position.get() : 0;
if (!onHandle) moveTo(clamp(point));
drag.current = { pointerId: event.pointerId, offset, samples: [{ t: event.timeStamp, p: point }] };
setDragging(true);
}
function onPointerMove(event: PointerEvent<HTMLDivElement>) {
const state = drag.current;
if (!state || state.pointerId !== event.pointerId) return;
const point = pointToPercent(event);
glide.current?.stop();
position.set(clamp(point - state.offset));
state.samples.push({ t: event.timeStamp, p: point });
if (state.samples.length > 6) state.samples.shift();
}
function onPointerEnd(event: PointerEvent<HTMLDivElement>) {
const state = drag.current;
if (!state || state.pointerId !== event.pointerId) return;
drag.current = null;
setDragging(false);
if (!flick) return;
// Speed over the last ~100ms of movement, in percent per second.
const recent = state.samples.filter((sample) => event.timeStamp - sample.t < 100);
const first = recent[0];
const last = recent[recent.length - 1];
if (!first || !last || last.t - first.t < 8) return;
const velocity = ((last.p - first.p) / (last.t - first.t)) * 1000;
if (Math.abs(velocity) < FLICK_SPEED) return;
moveTo(velocity > 0 ? 100 : 0, velocity);
}
// Keyboard moves are instant: arrows by 1, Shift or Page keys by 10, Home and End to the edges.
function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {
const big = event.shiftKey ? 10 : 1;
const steps: Record<string, number> = vertical
? { ArrowUp: -big, ArrowDown: big, ArrowLeft: -big, ArrowRight: big, PageUp: -10, PageDown: 10 }
: { ArrowLeft: -big, ArrowRight: big, ArrowDown: -big, ArrowUp: big, PageDown: -10, PageUp: 10 };
let next: number | null = null;
if (event.key === "Home") next = 0;
else if (event.key === "End") next = 100;
else if (event.key in steps) next = Math.round(position.get()) + (steps[event.key] ?? 0);
if (next == null) return;
event.preventDefault();
glide.current?.stop();
position.set(clamp(next));
}
const labelClass =
"pointer-events-none absolute rounded-md bg-black/55 px-2 py-0.5 text-xs font-medium text-white shadow-[0_1px_2px_rgb(0_0_0/0.2)] select-none";
const fill =
"absolute inset-0 [&>canvas]:size-full [&>img]:size-full [&>img]:object-cover [&>picture>img]:size-full [&>picture>img]:object-cover [&>svg]:size-full";
return (
<div
ref={frameRef}
data-orientation={orientation}
data-dragging={dragging || undefined}
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={onPointerEnd}
onPointerCancel={onPointerEnd}
className={cx(
"group/compare relative isolate aspect-[4/3] w-full cursor-default overflow-hidden rounded-xl border border-zinc-950/10 bg-zinc-100 select-none dark:border-white/10 dark:bg-black",
"[&_img]:pointer-events-none [&_img]:select-none",
vertical ? "touch-pan-x" : "touch-pan-y",
className,
)}
{...props}
>
<div className={fill}>{after}</div>
<motion.div className={fill} style={{ clipPath: clip }}>
{before}
</motion.div>
{beforeLabel != null ? (
<motion.span style={{ opacity: beforeLabelOpacity }} className={cx(labelClass, "top-3 left-3")}>
{beforeLabel}
</motion.span>
) : null}
{afterLabel != null ? (
<motion.span style={{ opacity: afterLabelOpacity }} className={cx(labelClass, vertical ? "bottom-3 left-3" : "top-3 right-3")}>
{afterLabel}
</motion.span>
) : null}
{/* Full-frame layers translated by the position, so the divider moves with transforms only. */}
<motion.div style={{ transform: lineTransform }} className="pointer-events-none absolute inset-0">
<span
className={cx(
"absolute bg-white shadow-[0_0_0_0.5px_rgb(0_0_0/0.25),0_0_8px_rgb(0_0_0/0.2)]",
vertical ? "inset-x-0 top-0 h-px -translate-y-1/2" : "inset-y-0 left-0 w-px -translate-x-1/2",
)}
/>
</motion.div>
<motion.div style={{ transform: gripTransform }} className="pointer-events-none absolute inset-0">
<div
data-compare-handle=""
role="slider"
tabIndex={0}
aria-label={ariaLabel}
aria-orientation={orientation}
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={rounded}
aria-valuetext={`${rounded}% before, ${100 - rounded}% after`}
onKeyDown={onKeyDown}
className={cx(
"pointer-events-auto absolute flex items-center justify-center gap-[3px] rounded-full bg-white text-zinc-500",
"shadow-[0_0_0_1px_rgb(0_0_0/0.08),0_2px_8px_-2px_rgb(0_0_0/0.35)] dark:bg-black dark:text-zinc-400 dark:shadow-[0_0_0_1px_rgb(255_255_255/0.2),0_2px_8px_-2px_rgb(0_0_0/0.6)]",
"cursor-grab group-data-[dragging]/compare:cursor-grabbing",
"transition-[scale,color] duration-150 ease-out motion-reduce:transition-none",
"hover:scale-[1.06] hover:text-zinc-950 group-data-[dragging]/compare:scale-[1.06] group-data-[dragging]/compare:text-zinc-950 dark:hover:text-white dark:group-data-[dragging]/compare:text-white",
"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
vertical
? "top-0 left-1/2 h-6 w-9 -translate-x-1/2 -translate-y-1/2 flex-col"
: "top-1/2 left-0 h-9 w-6 -translate-x-1/2 -translate-y-1/2",
)}
>
{/* Two chevrons that open apart while dragging. */}
<svg
aria-hidden="true"
viewBox="0 0 6 10"
fill="none"
className={cx(
"h-2.5 w-1.5 transition-transform duration-150 ease-out motion-reduce:transition-none",
vertical ? "rotate-90 group-data-[dragging]/compare:-translate-y-px" : "group-data-[dragging]/compare:-translate-x-px",
)}
>
<path d="M5 1 1 5l4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
</svg>
<svg
aria-hidden="true"
viewBox="0 0 6 10"
fill="none"
className={cx(
"h-2.5 w-1.5 transition-transform duration-150 ease-out motion-reduce:transition-none",
vertical ? "rotate-90 group-data-[dragging]/compare:translate-y-px" : "group-data-[dragging]/compare:translate-x-px",
)}
>
<path d="m1 1 4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</div>
</motion.div>
</div>
);
}