{
  "schemaVersion": 1,
  "target": "react",
  "name": "image-compare",
  "version": "0.1.0",
  "category": "data",
  "title": "Image Compare",
  "description": "A 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.",
  "tags": [
    "image",
    "compare",
    "before-after",
    "slider",
    "media",
    "motion"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {
    "motion": "^14.14.0"
  },
  "registryDependencies": [],
  "docsPath": "/components/image-compare",
  "props": [
    {
      "name": "before / after",
      "type": "ReactNode",
      "description": "The two layers. An img, picture, svg or canvas fills the frame; before is on the left, or on top when vertical."
    },
    {
      "name": "beforeLabel / afterLabel",
      "type": "ReactNode",
      "default": "\"Before\" / \"After\"",
      "description": "Labels over each side. Pass null to hide one."
    },
    {
      "name": "position / defaultPosition",
      "type": "number",
      "default": "50",
      "description": "Divider position from 0 (all after) to 100 (all before), controlled or starting."
    },
    {
      "name": "onPositionChange",
      "type": "(position: number) => void",
      "description": "Called as the divider moves."
    },
    {
      "name": "orientation",
      "type": "\"horizontal\" | \"vertical\"",
      "default": "\"horizontal\"",
      "description": "vertical stacks before over after with a horizontal divider."
    },
    {
      "name": "flick",
      "type": "boolean",
      "default": "true",
      "description": "A quick release sends the divider gliding to the edge with the speed it was given."
    },
    {
      "name": "aria-label",
      "type": "string",
      "default": "\"Divider position\"",
      "description": "Accessible name of the divider."
    },
    {
      "name": "className",
      "type": "string",
      "description": "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."
  ],
  "states": [
    "default",
    "dragging",
    "flicked to edge",
    "vertical",
    "no labels"
  ],
  "files": [
    {
      "path": "ui/image-compare.tsx",
      "content": "\"use client\";\n\nimport {\n  animate,\n  motion,\n  useMotionValue,\n  useMotionValueEvent,\n  useReducedMotion,\n  useTransform,\n  type AnimationPlaybackControls,\n} from \"motion/react\";\nimport { type ComponentProps, type KeyboardEvent, type PointerEvent, type ReactNode, useEffect, useRef, useState } from \"react\";\n\nfunction cx(...classes: (string | false | null | undefined)[]) {\n  return classes.filter(Boolean).join(\" \");\n}\n\nexport interface ImageCompareProps extends Omit<ComponentProps<\"div\">, \"children\" | \"defaultValue\" | \"onChange\"> {\n  /** Shown on the left, or on top when vertical. An `<img>`, `<picture>`, `<svg>` or `<canvas>` fills the frame. */\n  before: ReactNode;\n  /** Shown on the right, or at the bottom when vertical. */\n  after: ReactNode;\n  /** Label over the before side. Pass `null` to hide it. */\n  beforeLabel?: ReactNode;\n  /** Label over the after side. Pass `null` to hide it. */\n  afterLabel?: ReactNode;\n  /** Divider position from 0 (all after) to 100 (all before). Pass with `onPositionChange` to control it. */\n  position?: number;\n  /** Starting position when uncontrolled. */\n  defaultPosition?: number;\n  /** Called as the divider moves, with the new position from 0 to 100. */\n  onPositionChange?: (position: number) => void;\n  /** `vertical` stacks before over after with a horizontal divider. */\n  orientation?: \"horizontal\" | \"vertical\";\n  /** Lets a quick flick send the divider gliding to the edge. */\n  flick?: boolean;\n  /** Accessible name of the divider. */\n  \"aria-label\"?: string;\n}\n\nconst clamp = (value: number) => Math.min(100, Math.max(0, value));\n\n// A release faster than this, in percent of the frame per second, counts as a flick.\nconst FLICK_SPEED = 140;\n\n/**\n * Before and after, split by a divider you drag, click, or move with the keyboard. Flick the\n * divider and it glides on to the edge with the speed you gave it. The labels fade as the\n * divider covers them.\n */\nexport function ImageCompare({\n  before,\n  after,\n  beforeLabel = \"Before\",\n  afterLabel = \"After\",\n  position: positionProp,\n  defaultPosition = 50,\n  onPositionChange,\n  orientation = \"horizontal\",\n  flick = true,\n  className,\n  \"aria-label\": ariaLabel = \"Divider position\",\n  ...props\n}: ImageCompareProps) {\n  const vertical = orientation === \"vertical\";\n  const reduceMotion = useReducedMotion();\n  const frameRef = useRef<HTMLDivElement>(null);\n  const position = useMotionValue(clamp(positionProp ?? defaultPosition));\n  const glide = useRef<AnimationPlaybackControls | null>(null);\n  const drag = useRef<{ pointerId: number; offset: number; samples: { t: number; p: number }[] } | null>(null);\n  const [dragging, setDragging] = useState(false);\n  const [rounded, setRounded] = useState(Math.round(position.get()));\n\n  // Follow a controlled position unless the user is dragging.\n  useEffect(() => {\n    if (positionProp == null || drag.current) return;\n    glide.current?.stop();\n    position.set(clamp(positionProp));\n  }, [positionProp, position]);\n\n  const lastReported = useRef(position.get());\n  useMotionValueEvent(position, \"change\", (value) => {\n    const next = Math.round(value);\n    setRounded((current) => (current === next ? current : next));\n    if (Math.abs(value - lastReported.current) >= 0.1) {\n      lastReported.current = value;\n      onPositionChange?.(value);\n    }\n  });\n\n  const clip = useTransform(position, (value) => (vertical ? `inset(0 0 ${100 - value}% 0)` : `inset(0 ${100 - value}% 0 0)`));\n  const lineTransform = useTransform(position, (value) => (vertical ? `translateY(${value}%)` : `translateX(${value}%)`));\n  // The grip stops 18px short of each edge so it is never cut off; the hairline goes all the way.\n  const gripTransform = useTransform(position, (value) => {\n    const at = `clamp(18px, ${value}%, calc(100% - 18px))`;\n    return vertical ? `translateY(${at})` : `translateX(${at})`;\n  });\n  const beforeLabelOpacity = useTransform(position, [8, 18], [0, 1]);\n  const afterLabelOpacity = useTransform(position, [82, 92], [1, 0]);\n\n  function pointToPercent(event: PointerEvent<HTMLElement>) {\n    const rect = frameRef.current?.getBoundingClientRect();\n    if (!rect) return position.get();\n    return vertical ? ((event.clientY - rect.top) / rect.height) * 100 : ((event.clientX - rect.left) / rect.width) * 100;\n  }\n\n  function moveTo(target: number, velocity = 0) {\n    glide.current?.stop();\n    if (reduceMotion) {\n      position.set(target);\n      return;\n    }\n    glide.current = animate(position, target, { type: \"spring\", visualDuration: 0.42, bounce: 0, velocity });\n  }\n\n  function onPointerDown(event: PointerEvent<HTMLDivElement>) {\n    if (event.button !== 0 || !event.isPrimary) return;\n    const point = pointToPercent(event);\n    const onHandle = (event.target as HTMLElement).closest(\"[data-compare-handle]\") !== null;\n    event.currentTarget.setPointerCapture(event.pointerId);\n    glide.current?.stop();\n    // Grabbing the handle keeps the grab point under the pointer; pressing elsewhere glides there.\n    const offset = onHandle ? point - position.get() : 0;\n    if (!onHandle) moveTo(clamp(point));\n    drag.current = { pointerId: event.pointerId, offset, samples: [{ t: event.timeStamp, p: point }] };\n    setDragging(true);\n  }\n\n  function onPointerMove(event: PointerEvent<HTMLDivElement>) {\n    const state = drag.current;\n    if (!state || state.pointerId !== event.pointerId) return;\n    const point = pointToPercent(event);\n    glide.current?.stop();\n    position.set(clamp(point - state.offset));\n    state.samples.push({ t: event.timeStamp, p: point });\n    if (state.samples.length > 6) state.samples.shift();\n  }\n\n  function onPointerEnd(event: PointerEvent<HTMLDivElement>) {\n    const state = drag.current;\n    if (!state || state.pointerId !== event.pointerId) return;\n    drag.current = null;\n    setDragging(false);\n    if (!flick) return;\n    // Speed over the last ~100ms of movement, in percent per second.\n    const recent = state.samples.filter((sample) => event.timeStamp - sample.t < 100);\n    const first = recent[0];\n    const last = recent[recent.length - 1];\n    if (!first || !last || last.t - first.t < 8) return;\n    const velocity = ((last.p - first.p) / (last.t - first.t)) * 1000;\n    if (Math.abs(velocity) < FLICK_SPEED) return;\n    moveTo(velocity > 0 ? 100 : 0, velocity);\n  }\n\n  // Keyboard moves are instant: arrows by 1, Shift or Page keys by 10, Home and End to the edges.\n  function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {\n    const big = event.shiftKey ? 10 : 1;\n    const steps: Record<string, number> = vertical\n      ? { ArrowUp: -big, ArrowDown: big, ArrowLeft: -big, ArrowRight: big, PageUp: -10, PageDown: 10 }\n      : { ArrowLeft: -big, ArrowRight: big, ArrowDown: -big, ArrowUp: big, PageDown: -10, PageUp: 10 };\n    let next: number | null = null;\n    if (event.key === \"Home\") next = 0;\n    else if (event.key === \"End\") next = 100;\n    else if (event.key in steps) next = Math.round(position.get()) + (steps[event.key] ?? 0);\n    if (next == null) return;\n    event.preventDefault();\n    glide.current?.stop();\n    position.set(clamp(next));\n  }\n\n  const labelClass =\n    \"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\";\n  const fill =\n    \"absolute inset-0 [&>canvas]:size-full [&>img]:size-full [&>img]:object-cover [&>picture>img]:size-full [&>picture>img]:object-cover [&>svg]:size-full\";\n\n  return (\n    <div\n      ref={frameRef}\n      data-orientation={orientation}\n      data-dragging={dragging || undefined}\n      onPointerDown={onPointerDown}\n      onPointerMove={onPointerMove}\n      onPointerUp={onPointerEnd}\n      onPointerCancel={onPointerEnd}\n      className={cx(\n        \"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\",\n        \"[&_img]:pointer-events-none [&_img]:select-none\",\n        vertical ? \"touch-pan-x\" : \"touch-pan-y\",\n        className,\n      )}\n      {...props}\n    >\n      <div className={fill}>{after}</div>\n      <motion.div className={fill} style={{ clipPath: clip }}>\n        {before}\n      </motion.div>\n\n      {beforeLabel != null ? (\n        <motion.span style={{ opacity: beforeLabelOpacity }} className={cx(labelClass, \"top-3 left-3\")}>\n          {beforeLabel}\n        </motion.span>\n      ) : null}\n      {afterLabel != null ? (\n        <motion.span style={{ opacity: afterLabelOpacity }} className={cx(labelClass, vertical ? \"bottom-3 left-3\" : \"top-3 right-3\")}>\n          {afterLabel}\n        </motion.span>\n      ) : null}\n\n      {/* Full-frame layers translated by the position, so the divider moves with transforms only. */}\n      <motion.div style={{ transform: lineTransform }} className=\"pointer-events-none absolute inset-0\">\n        <span\n          className={cx(\n            \"absolute bg-white shadow-[0_0_0_0.5px_rgb(0_0_0/0.25),0_0_8px_rgb(0_0_0/0.2)]\",\n            vertical ? \"inset-x-0 top-0 h-px -translate-y-1/2\" : \"inset-y-0 left-0 w-px -translate-x-1/2\",\n          )}\n        />\n      </motion.div>\n      <motion.div style={{ transform: gripTransform }} className=\"pointer-events-none absolute inset-0\">\n        <div\n          data-compare-handle=\"\"\n          role=\"slider\"\n          tabIndex={0}\n          aria-label={ariaLabel}\n          aria-orientation={orientation}\n          aria-valuemin={0}\n          aria-valuemax={100}\n          aria-valuenow={rounded}\n          aria-valuetext={`${rounded}% before, ${100 - rounded}% after`}\n          onKeyDown={onKeyDown}\n          className={cx(\n            \"pointer-events-auto absolute flex items-center justify-center gap-[3px] rounded-full bg-white text-zinc-500\",\n            \"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)]\",\n            \"cursor-grab group-data-[dragging]/compare:cursor-grabbing\",\n            \"transition-[scale,color] duration-150 ease-out motion-reduce:transition-none\",\n            \"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\",\n            \"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500\",\n            vertical\n              ? \"top-0 left-1/2 h-6 w-9 -translate-x-1/2 -translate-y-1/2 flex-col\"\n              : \"top-1/2 left-0 h-9 w-6 -translate-x-1/2 -translate-y-1/2\",\n          )}\n        >\n          {/* Two chevrons that open apart while dragging. */}\n          <svg\n            aria-hidden=\"true\"\n            viewBox=\"0 0 6 10\"\n            fill=\"none\"\n            className={cx(\n              \"h-2.5 w-1.5 transition-transform duration-150 ease-out motion-reduce:transition-none\",\n              vertical ? \"rotate-90 group-data-[dragging]/compare:-translate-y-px\" : \"group-data-[dragging]/compare:-translate-x-px\",\n            )}\n          >\n            <path d=\"M5 1 1 5l4 4\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n          </svg>\n          <svg\n            aria-hidden=\"true\"\n            viewBox=\"0 0 6 10\"\n            fill=\"none\"\n            className={cx(\n              \"h-2.5 w-1.5 transition-transform duration-150 ease-out motion-reduce:transition-none\",\n              vertical ? \"rotate-90 group-data-[dragging]/compare:translate-y-px\" : \"group-data-[dragging]/compare:translate-x-px\",\n            )}\n          >\n            <path d=\"m1 1 4 4-4 4\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n          </svg>\n        </div>\n      </motion.div>\n    </div>\n  );\n}\n"
    }
  ],
  "example": {
    "content": "\"use client\";\n\nimport { useId } from \"react\";\nimport { ImageCompare } from \"@/components/shaken/ui/image-compare\";\n\ntype Palette = { skyTop: string; skyHorizon: string; sun: string; far: string; mid: string; near: string; water: string; glint: string };\n\n// The same frame twice: as the flat, cool raw capture and after a warm evening grade.\nconst raw: Palette = {\n  skyTop: \"#8b93a1\",\n  skyHorizon: \"#c3c0ba\",\n  sun: \"#e9e5dd\",\n  far: \"#8a8d95\",\n  mid: \"#6f737c\",\n  near: \"#52565f\",\n  water: \"#9a9fa7\",\n  glint: \"#d9d6d0\",\n};\n\nconst graded: Palette = {\n  skyTop: \"#1d2747\",\n  skyHorizon: \"#f39a6a\",\n  sun: \"#ffd7a1\",\n  far: \"#7a5f8f\",\n  mid: \"#463d6b\",\n  near: \"#1d1f3d\",\n  water: \"#3a3560\",\n  glint: \"#ffc58f\",\n};\n\nfunction Landscape({ palette, label }: { palette: Palette; label: string }) {\n  const id = useId();\n  return (\n    <svg role=\"img\" aria-label={label} viewBox=\"0 0 400 300\" preserveAspectRatio=\"xMidYMid slice\">\n      <defs>\n        <linearGradient id={`${id}-sky`} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n          <stop offset=\"0\" stopColor={palette.skyTop} />\n          <stop offset=\"1\" stopColor={palette.skyHorizon} />\n        </linearGradient>\n        <radialGradient id={`${id}-sun`}>\n          <stop offset=\"0\" stopColor={palette.sun} />\n          <stop offset=\"0.35\" stopColor={palette.sun} stopOpacity=\"0.9\" />\n          <stop offset=\"1\" stopColor={palette.sun} stopOpacity=\"0\" />\n        </radialGradient>\n        <linearGradient id={`${id}-water`} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n          <stop offset=\"0\" stopColor={palette.glint} stopOpacity=\"0.55\" />\n          <stop offset=\"0.4\" stopColor={palette.water} />\n          <stop offset=\"1\" stopColor={palette.near} />\n        </linearGradient>\n      </defs>\n      <rect width=\"400\" height=\"300\" fill={`url(#${id}-sky)`} />\n      <circle cx=\"250\" cy=\"176\" r=\"70\" fill={`url(#${id}-sun)`} />\n      <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} />\n      <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} />\n      <rect y=\"206\" width=\"400\" height=\"94\" fill={`url(#${id}-water)`} />\n      <g stroke={palette.glint} strokeLinecap=\"round\" strokeOpacity=\"0.7\">\n        <path d=\"M222 220h56M232 232h36M240 244h20M244 256h12\" strokeWidth=\"2\" />\n      </g>\n      <path d=\"M0 236 C 40 220 70 214 110 222 S 150 240 170 300 H 0 Z\" fill={palette.near} />\n      <path d=\"M400 228 C 360 218 330 222 300 234 S 268 270 262 300 H 400 Z\" fill={palette.near} />\n    </svg>\n  );\n}\n\nexport default function ImageCompareExample() {\n  return (\n    <figure className=\"grid w-full max-w-lg gap-2.5\">\n      <ImageCompare\n        before={<Landscape palette={raw} label=\"Lake at dusk, raw capture\" />}\n        after={<Landscape palette={graded} label=\"Lake at dusk, with the evening grade\" />}\n        beforeLabel=\"Raw\"\n        afterLabel=\"Graded\"\n        defaultPosition={42}\n      />\n      <figcaption className=\"text-xs text-zinc-500\">Drag or flick the divider. Evening grade, exposure +0.4, warmth +18.</figcaption>\n    </figure>\n  );\n}\n"
  }
}
