{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"compare-slider","type":"registry:component","title":"Compare slider","description":"Drag the line to see what polish actually changes.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/compare-slider.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, type ReactNode } from \"react\";\nimport { animate, useMotionValue } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\n// A click glides rather than teleports, so you see which way the divider\n// went; short enough that it never feels like waiting.\nconst GLIDE_MS = 200;\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\nconst STEP = 0.05;\n// Horizontal travel before a touch counts as a drag; anything less stays a\n// tap, and vertical movement is left to the page via pan-y.\nconst SLOP = 4;\n// Tags sit in the outer ~20% of the frame. They start fading at 35% visible\n// and are gone by 20%, before the divider can reach them.\nconst TAG_FADE_START = 0.35;\nconst TAG_FADE_END = 0.2;\n\nconst clamp = (v: number) => Math.min(Math.max(v, 0), 1);\nconst tagOpacity = (visible: number) =>\n  clamp((visible - TAG_FADE_END) / (TAG_FADE_START - TAG_FADE_END));\nconst percent = (v: number) => Math.round(v * 100);\nconst valueText = (v: number) =>\n  `${percent(v)}% before, ${100 - percent(v)}% after`;\n\ntype Drag = {\n  id: number;\n  startX: number;\n  // Where on the handle it was grabbed, so the handle doesn't jump to\n  // center itself under the pointer.\n  offset: number;\n  rect: DOMRect;\n  active: boolean;\n};\n\nexport function CompareSlider({\n  before,\n  after,\n  initial = 0.5,\n  label = \"Comparison position\",\n  className,\n}: {\n  before: ReactNode;\n  after: ReactNode;\n  initial?: number;\n  label?: string;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const pos = useMotionValue(initial);\n  const target = useRef(initial);\n  const glideEnd = useRef(0);\n  const drag = useRef<Drag | null>(null);\n\n  const rootRef = useRef<HTMLDivElement>(null);\n  const afterRef = useRef<HTMLDivElement>(null);\n  const dividerRef = useRef<HTMLDivElement>(null);\n  const handleRef = useRef<HTMLDivElement>(null);\n  const beforeTagRef = useRef<HTMLSpanElement>(null);\n  const afterTagRef = useRef<HTMLSpanElement>(null);\n\n  // Writes straight to the DOM so dragging never re-renders React.\n  useEffect(\n    () =>\n      pos.on(\"change\", (v) => {\n        afterRef.current?.style.setProperty(\n          \"clip-path\",\n          `inset(0 0 0 ${v * 100}%)`,\n        );\n        dividerRef.current?.style.setProperty(\n          \"transform\",\n          `translateX(${v * 100}%)`,\n        );\n        beforeTagRef.current?.style.setProperty(\"opacity\", `${tagOpacity(v)}`);\n        afterTagRef.current?.style.setProperty(\n          \"opacity\",\n          `${tagOpacity(1 - v)}`,\n        );\n        handleRef.current?.setAttribute(\"aria-valuenow\", `${percent(v)}`);\n        handleRef.current?.setAttribute(\"aria-valuetext\", valueText(v));\n      }),\n    [pos],\n  );\n\n  const moveTo = (next: number, glide: boolean) => {\n    target.current = next;\n    if (reduceMotion) return pos.jump(next);\n    const now = performance.now();\n    if (glide) {\n      glideEnd.current = now + GLIDE_MS;\n      animate(pos, next, { duration: GLIDE_MS / 1000, ease: EASE_OUT });\n      return;\n    }\n    // Dragging during a glide retargets it to land on the pointer when the\n    // glide would have ended, instead of snapping mid-flight. One frame or\n    // less left is not worth animating.\n    const remaining = glideEnd.current - now;\n    if (remaining > 16) {\n      animate(pos, next, { duration: remaining / 1000, ease: EASE_OUT });\n    } else {\n      pos.jump(next);\n    }\n  };\n\n  const at = (clientX: number, d: Drag) =>\n    clamp((clientX - d.offset - d.rect.left) / d.rect.width);\n\n  const start = (d: Drag) => {\n    d.active = true;\n    rootRef.current?.setAttribute(\"data-dragging\", \"\");\n  };\n\n  const end = () => {\n    drag.current = null;\n    rootRef.current?.removeAttribute(\"data-dragging\");\n  };\n\n  const tag =\n    \"pointer-events-none absolute top-4 rounded-full bg-background px-3 py-1 text-[13px] font-medium text-muted-foreground shadow-raised\";\n\n  return (\n    <div\n      ref={rootRef}\n      className={cn(\n        \"group relative h-[320px] w-[520px] max-w-full cursor-ew-resize touch-pan-y overflow-hidden rounded-3xl bg-muted select-none\",\n        className,\n      )}\n      onPointerDown={(e) => {\n        // Ignore a second finger while one is already dragging.\n        if (e.button !== 0 || drag.current) return;\n        // Skips the mouse's default focus handling so the handle can take\n        // focus below, and keeps text from being selected.\n        e.preventDefault();\n        const rect = e.currentTarget.getBoundingClientRect();\n        const onHandle = !!handleRef.current?.contains(e.target as Node);\n        const d: Drag = {\n          id: e.pointerId,\n          startX: e.clientX,\n          offset: onHandle\n            ? e.clientX - (rect.left + pos.get() * rect.width)\n            : 0,\n          rect,\n          active: false,\n        };\n        drag.current = d;\n        e.currentTarget.setPointerCapture(e.pointerId);\n        handleRef.current?.focus({ preventScroll: true });\n        if (onHandle) {\n          start(d);\n        } else if (e.pointerType !== \"touch\") {\n          // A mouse press is intent, so glide right away. A touch waits to\n          // see whether it is a tap, a drag or a scroll.\n          start(d);\n          moveTo(at(e.clientX, d), true);\n        }\n      }}\n      onPointerMove={(e) => {\n        const d = drag.current;\n        if (!d || e.pointerId !== d.id) return;\n        if (!d.active) {\n          if (Math.abs(e.clientX - d.startX) < SLOP) return;\n          start(d);\n          moveTo(at(e.clientX, d), true);\n          return;\n        }\n        moveTo(at(e.clientX, d), false);\n      }}\n      onPointerUp={(e) => {\n        const d = drag.current;\n        if (!d || e.pointerId !== d.id) return;\n        // A tap that never became a drag.\n        if (!d.active) moveTo(at(e.clientX, d), true);\n        end();\n      }}\n      onPointerCancel={(e) => {\n        if (drag.current?.id === e.pointerId) end();\n      }}\n    >\n      <div aria-hidden className=\"absolute inset-0\">\n        {before}\n      </div>\n      <div\n        ref={afterRef}\n        aria-hidden\n        className=\"absolute inset-0\"\n        style={{ clipPath: `inset(0 0 0 ${initial * 100}%)` }}\n      >\n        {after}\n      </div>\n\n      <span\n        ref={beforeTagRef}\n        aria-hidden\n        className={cn(tag, \"left-4\")}\n        style={{ opacity: tagOpacity(initial) }}\n      >\n        Before\n      </span>\n      <span\n        ref={afterTagRef}\n        aria-hidden\n        className={cn(tag, \"right-4\")}\n        style={{ opacity: tagOpacity(1 - initial) }}\n      >\n        After\n      </span>\n\n      {/* Full width so its translateX percentage matches the clip inset. */}\n      <div\n        ref={dividerRef}\n        className=\"pointer-events-none absolute inset-0\"\n        style={{ transform: `translateX(${initial * 100}%)` }}\n      >\n        <div className=\"absolute inset-y-0 left-0 w-px -translate-x-1/2 bg-foreground\" />\n        <div\n          ref={handleRef}\n          role=\"slider\"\n          tabIndex={0}\n          aria-label={label}\n          aria-orientation=\"horizontal\"\n          aria-valuemin={0}\n          aria-valuemax={100}\n          aria-valuenow={percent(initial)}\n          aria-valuetext={valueText(initial)}\n          className=\"pointer-events-auto absolute top-1/2 left-0 flex size-10 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full bg-background text-foreground shadow-raised outline-hidden transition-[scale] duration-150 ease-out group-data-[dragging]:scale-[0.96] focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground motion-reduce:transition-none\"\n          onKeyDown={(e) => {\n            const next = {\n              ArrowLeft: target.current - STEP,\n              ArrowDown: target.current - STEP,\n              ArrowRight: target.current + STEP,\n              ArrowUp: target.current + STEP,\n              Home: 0,\n              End: 1,\n            }[e.key];\n            if (next === undefined) return;\n            e.preventDefault();\n            // Occasional, so it glides exactly like a click.\n            moveTo(clamp(next), true);\n          }}\n        >\n          <svg\n            viewBox=\"0 0 16 16\"\n            className=\"size-5\"\n            fill=\"none\"\n            stroke=\"currentColor\"\n            strokeWidth={1.5}\n            strokeLinecap=\"round\"\n            strokeLinejoin=\"round\"\n            aria-hidden\n          >\n            <path d=\"M6 5 3 8l3 3M10 5l3 3-3 3\" />\n          </svg>\n        </div>\n      </div>\n    </div>\n  );\n}\n\nconst ICON = {\n  viewBox: \"0 0 16 16\",\n  fill: \"none\",\n  stroke: \"currentColor\",\n  strokeLinecap: \"round\",\n  strokeLinejoin: \"round\",\n} as const;\n\n// The same file card twice. Before: square corners, a border faking depth,\n// one flat text style, cramped spacing. After: concentric radii (28px outer\n// = 12px inner + 16px padding), a layered shadow instead of a border, a muted\n// secondary line with tabular numbers, and room to breathe.\nfunction FileCard({ polished }: { polished: boolean }) {\n  return (\n    <div className=\"absolute inset-0 flex items-center justify-center bg-muted\">\n      <div\n        className={cn(\n          \"flex w-[380px] max-w-[calc(100%-2.5rem)] flex-col bg-background text-foreground\",\n          polished\n            ? \"gap-4 rounded-[28px] p-4 shadow-raised\"\n            : \"gap-1.5 border border-foreground/25 p-2\",\n        )}\n      >\n        <div className={cn(\"flex items-center\", polished ? \"gap-4\" : \"gap-2\")}>\n          <div\n            className={cn(\n              \"flex size-14 shrink-0 items-center justify-center\",\n              polished ? \"rounded-xl bg-muted text-muted-foreground\" : \"bg-foreground/15\",\n            )}\n          >\n            {polished && (\n              <svg className=\"size-6\" strokeWidth={1.5} {...ICON}>\n                <path d=\"M9 2H4.5a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h7a1 1 0 0 0 1-1V5.5L9 2ZM9 2v3.5h3.5\" />\n              </svg>\n            )}\n          </div>\n          <div className=\"min-w-0\">\n            <p className={cn(\"truncate text-[15px]\", polished && \"font-medium\")}>\n              Brand guidelines.pdf\n            </p>\n            <p\n              className={cn(\n                \"truncate\",\n                polished ? \"mt-0.5 text-[13px] text-muted-foreground tabular-nums\" : \"text-[15px]\",\n              )}\n            >\n              2.4 MB · Updated 3h ago\n            </p>\n          </div>\n        </div>\n        <div\n          className={cn(\n            \"flex h-11 items-center justify-center gap-2 text-[15px]\",\n            polished\n              ? \"rounded-xl bg-foreground font-medium text-background\"\n              : \"border border-foreground/40\",\n          )}\n        >\n          {polished && (\n            // 2px stroke to match the medium-weight label beside it.\n            <svg className=\"size-4\" strokeWidth={2} {...ICON}>\n              <path d=\"M8 2.5v8M4.5 7 8 10.5 11.5 7M3 13.5h10\" />\n            </svg>\n          )}\n          Download\n        </div>\n      </div>\n    </div>\n  );\n}\n\nexport default function CompareSliderDemo() {\n  return (\n    <CompareSlider\n      before={<FileCard polished={false} />}\n      after={<FileCard polished />}\n    />\n  );\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["cards"],"docs":"From ui lab: https://lab.xevrion.dev/lab/compare-slider"}