{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"before-after","type":"registry:ui","title":"Before / After","description":"A before and after comparison with a divider you drag, tap or move with the arrow keys, side by side or stacked.","dependencies":[],"registryDependencies":["https://ui.mekaigames.com/r/theme.json"],"files":[{"path":"components/ui/before-after.tsx","type":"registry:ui","content":"\"use client\";\n\nimport { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type PointerEvent, type ReactNode } from \"react\";\n\nexport type BeforeAfterSide = {\n  /** Image URL, shown as a cover. */\n  src?: string;\n  alt?: string;\n  /** Any content, such as a video or a drawn scene. Takes priority over src. */\n  content?: ReactNode;\n  /** Text on the corner tag. */\n  label?: string;\n};\n\nexport type BeforeAfterProps = {\n  before: BeforeAfterSide;\n  after: BeforeAfterSide;\n  /** \"horizontal\" puts before on the left, \"vertical\" puts it on top. */\n  orientation?: \"horizontal\" | \"vertical\";\n  /** Controlled divider position, 0 to 100. */\n  value?: number;\n  /** Starting position when uncontrolled, 0 to 100. */\n  defaultValue?: number;\n  onValueChange?: (value: number) => void;\n  /** CSS aspect ratio of the frame. */\n  aspectRatio?: string;\n  /** Percent moved by one arrow key press. Page Up and Page Down move four times that. */\n  step?: number;\n  /** The divider follows a mouse without pressing. Touch still drags. */\n  followPointer?: boolean;\n  /** Nudges the divider once when it first scrolls into view. Uncontrolled only. */\n  hint?: boolean;\n  /** Show the corner tags. */\n  showLabels?: boolean;\n  /** Color of the divider and its grip. */\n  color?: string;\n  /** Accessible name of the slider. */\n  label?: string;\n  className?: string;\n};\n\nconst clamp = (v: number) => Math.min(100, Math.max(0, v));\n\nfunction Layer({ side }: { side: BeforeAfterSide }) {\n  if (side.content !== undefined) return <>{side.content}</>;\n  if (side.src) {\n    return <span role=\"img\" aria-label={side.alt ?? \"\"} className=\"block size-full bg-cover bg-center\" style={{ backgroundImage: `url(\"${side.src}\")` }} />;\n  }\n  return null;\n}\n\n/** A before/after comparison with a divider you drag, tap or move with the arrow keys. */\nexport function BeforeAfter({\n  before,\n  after,\n  orientation = \"horizontal\",\n  value,\n  defaultValue = 50,\n  onValueChange,\n  aspectRatio = \"16 / 10\",\n  step = 4,\n  followPointer = false,\n  hint = false,\n  showLabels = true,\n  color = \"#ff784f\",\n  label = \"Compare before and after\",\n  className = \"\",\n}: BeforeAfterProps) {\n  const vertical = orientation === \"vertical\";\n  const [internal, setInternal] = useState(() => clamp(defaultValue));\n  const [dragging, setDragging] = useState(false);\n  const pos = clamp(value ?? internal);\n\n  const frame = useRef<HTMLDivElement>(null);\n  const handle = useRef<HTMLDivElement>(null);\n  const latest = useRef(pos);\n  const target = useRef<number | null>(null);\n  const raf = useRef(0);\n  const notify = useRef(onValueChange);\n  const gesture = useRef<{ id: number; x: number; y: number; grab: number; active: boolean; touch: boolean } | null>(null);\n\n  useEffect(() => {\n    latest.current = pos;\n    notify.current = onValueChange;\n  }, [pos, onValueChange]);\n\n  useEffect(() => () => cancelAnimationFrame(raf.current), []);\n\n  function commit(next: number) {\n    const v = Math.round(clamp(next) * 100) / 100;\n    if (v === latest.current) return;\n    latest.current = v;\n    setInternal(v);\n    notify.current?.(v);\n  }\n\n  function stop() {\n    cancelAnimationFrame(raf.current);\n    raf.current = 0;\n    target.current = null;\n  }\n\n  // Eases toward a target. New targets just replace the old one, so quick key presses and pointer moves stay smooth.\n  function glide(to: number) {\n    const dest = clamp(to);\n    if (window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches) {\n      stop();\n      commit(dest);\n      return;\n    }\n    target.current = dest;\n    if (raf.current) return;\n    let last = performance.now();\n    const tick = (now: number) => {\n      const goal = target.current;\n      if (goal === null) return;\n      const dt = Math.min(48, now - last);\n      last = now;\n      const next = latest.current + (goal - latest.current) * (1 - Math.exp(-dt * 0.016));\n      if (Math.abs(goal - next) < 0.05) {\n        commit(goal);\n        stop();\n        return;\n      }\n      commit(next);\n      raf.current = requestAnimationFrame(tick);\n    };\n    raf.current = requestAnimationFrame(tick);\n  }\n\n  // One soft swing that fades out, so people see the divider moves before they touch it.\n  const uncontrolled = value === undefined;\n  useEffect(() => {\n    const el = frame.current;\n    if (!hint || !uncontrolled || !el) return;\n    if (window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches) return;\n    let id = 0;\n    const seen = new IntersectionObserver(\n      ([entry]) => {\n        if (!entry.isIntersecting) return;\n        seen.disconnect();\n        const base = latest.current;\n        const start = performance.now() + 250;\n        const tick = (now: number) => {\n          // Any real interaction cancels this through gesture or target.\n          if (gesture.current || target.current !== null) return;\n          const t = (now - start) / 1500;\n          if (t >= 1) {\n            setInternal(base);\n            latest.current = base;\n            return;\n          }\n          if (t > 0) {\n            const v = clamp(base + Math.sin(t * Math.PI * 2) * 14 * (1 - t));\n            latest.current = v;\n            setInternal(v);\n          }\n          id = requestAnimationFrame(tick);\n        };\n        id = requestAnimationFrame(tick);\n      },\n      { threshold: 0.5 },\n    );\n    seen.observe(el);\n    return () => {\n      seen.disconnect();\n      cancelAnimationFrame(id);\n    };\n  }, [hint, uncontrolled]);\n\n  function percentAt(e: PointerEvent<HTMLElement>) {\n    const box = frame.current?.getBoundingClientRect();\n    if (!box) return latest.current;\n    const ratio = vertical ? (e.clientY - box.top) / box.height : (e.clientX - box.left) / box.width;\n    return clamp(ratio * 100);\n  }\n\n  function onPointerDown(e: PointerEvent<HTMLDivElement>) {\n    if (e.button !== 0) return;\n    const onHandle = Boolean(handle.current?.contains(e.target as Node));\n    const touch = e.pointerType !== \"mouse\";\n    const at = percentAt(e);\n    gesture.current = { id: e.pointerId, x: e.clientX, y: e.clientY, grab: onHandle ? latest.current - at : 0, active: false, touch };\n    // A mouse or the grip takes hold at once. A finger on the image waits, because it might be scrolling the page.\n    if (!touch || onHandle) {\n      gesture.current.active = true;\n      e.currentTarget.setPointerCapture(e.pointerId);\n      setDragging(true);\n      if (!onHandle) glide(at);\n    }\n  }\n\n  function onPointerMove(e: PointerEvent<HTMLDivElement>) {\n    const g = gesture.current;\n    if (!g) {\n      if (followPointer && e.pointerType === \"mouse\") glide(percentAt(e));\n      return;\n    }\n    if (g.id !== e.pointerId) return;\n    if (!g.active) {\n      const dx = e.clientX - g.x;\n      const dy = e.clientY - g.y;\n      // Vertical mode keeps swipes for page scrolling, so only the grip strip drags on touch.\n      if (vertical || Math.abs(dx) < 5 || Math.abs(dx) < Math.abs(dy)) return;\n      g.active = true;\n      e.currentTarget.setPointerCapture(e.pointerId);\n      setDragging(true);\n    }\n    stop();\n    commit(percentAt(e) + g.grab);\n  }\n\n  function onPointerUp(e: PointerEvent<HTMLDivElement>) {\n    const g = gesture.current;\n    if (!g || g.id !== e.pointerId) return;\n    gesture.current = null;\n    setDragging(false);\n    // A tap on the image moves the divider there.\n    if (!g.active) glide(percentAt(e));\n  }\n\n  function onPointerCancel() {\n    gesture.current = null;\n    setDragging(false);\n  }\n\n  function onKeyDown(e: KeyboardEvent<HTMLDivElement>) {\n    const from = target.current ?? latest.current;\n    const forward = vertical ? [\"ArrowDown\", \"ArrowRight\"] : [\"ArrowRight\", \"ArrowUp\"];\n    const backward = vertical ? [\"ArrowUp\", \"ArrowLeft\"] : [\"ArrowLeft\", \"ArrowDown\"];\n    let next: number | null = null;\n    if (forward.includes(e.key)) next = from + step;\n    else if (backward.includes(e.key)) next = from - step;\n    else if (e.key === \"PageUp\") next = from + step * 4;\n    else if (e.key === \"PageDown\") next = from - step * 4;\n    else if (e.key === \"Home\") next = 0;\n    else if (e.key === \"End\") next = 100;\n    if (next === null) return;\n    e.preventDefault();\n    glide(next);\n  }\n\n  const beforeName = before.label ?? \"Before\";\n  const afterName = after.label ?? \"After\";\n  const shown = Math.round(pos);\n  const tag =\n    \"pointer-events-none absolute rounded-full bg-ink-950/70 px-3 py-1 text-[0.68rem] font-bold uppercase tracking-[0.2em] text-bone backdrop-blur transition-opacity duration-200\";\n\n  return (\n    <div\n      ref={frame}\n      onPointerDown={onPointerDown}\n      onPointerMove={onPointerMove}\n      onPointerUp={onPointerUp}\n      onPointerCancel={onPointerCancel}\n      onDragStart={(e) => e.preventDefault()}\n      // Stops the browser from dropping focus on the page, so the arrow keys work right after a click.\n      onMouseDown={(e) => {\n        e.preventDefault();\n        handle.current?.focus({ preventScroll: true });\n      }}\n      className={`group/frame relative w-full touch-pan-y select-none overflow-hidden rounded-3xl bg-ink-800 shadow-[0_30px_80px_-30px_rgb(0_0_0/0.9)] ${\n        vertical ? \"cursor-ns-resize\" : \"cursor-ew-resize\"\n      } ${className}`}\n      style={{ aspectRatio }}\n    >\n      <div className=\"absolute inset-0\">\n        <Layer side={after} />\n        {showLabels ? (\n          <span aria-hidden=\"true\" className={`${tag} ${vertical ? \"bottom-3 left-3\" : \"right-3 top-3\"}`} style={{ opacity: pos > 84 ? 0 : 1 }}>\n            {afterName}\n          </span>\n        ) : null}\n      </div>\n\n      <div\n        className=\"absolute inset-0\"\n        style={{ clipPath: vertical ? `inset(0 0 ${100 - pos}% 0)` : `inset(0 ${100 - pos}% 0 0)` }}\n      >\n        <Layer side={before} />\n        {showLabels ? (\n          <span aria-hidden=\"true\" className={`${tag} left-3 top-3`} style={{ opacity: pos < 16 ? 0 : 1 }}>\n            {beforeName}\n          </span>\n        ) : null}\n      </div>\n\n      <div aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0 rounded-3xl ring-1 ring-inset ring-white/10\" />\n\n      {/* The strip is the slider: wide enough to grab, and it holds the line and the grip. */}\n      <div\n        ref={handle}\n        role=\"slider\"\n        tabIndex={0}\n        aria-label={label}\n        aria-orientation={orientation}\n        aria-valuemin={0}\n        aria-valuemax={100}\n        aria-valuenow={shown}\n        aria-valuetext={`${shown}% ${beforeName}, ${100 - shown}% ${afterName}`}\n        onKeyDown={onKeyDown}\n        className={`group/handle absolute flex items-center justify-center outline-none ${\n          vertical ? \"inset-x-0 h-11 -translate-y-1/2 touch-none\" : \"inset-y-0 w-11 -translate-x-1/2 touch-pan-y\"\n        }`}\n        style={vertical ? { top: `${pos}%` } : { left: `${pos}%` }}\n      >\n        <span\n          aria-hidden=\"true\"\n          className={`absolute ${vertical ? \"inset-x-0 h-0.5\" : \"inset-y-0 w-0.5\"}`}\n          style={{\n            background: color,\n            boxShadow: `0 0 ${dragging ? 22 : 12}px color-mix(in srgb, ${color} 75%, transparent)`,\n            transition: \"box-shadow 200ms ease-out\",\n          }}\n        />\n        <span\n          aria-hidden=\"true\"\n          className={`relative grid size-11 place-items-center rounded-full text-ink-950 shadow-[0_8px_24px_-6px_rgb(0_0_0/0.8)] ring-4 transition-transform duration-200 ease-out group-hover/frame:scale-105 group-focus-visible/handle:outline-2 group-focus-visible/handle:outline-offset-4 group-focus-visible/handle:outline-bone motion-reduce:transition-none ${\n            dragging ? \"!scale-110\" : \"\"\n          }`}\n          style={{ background: color, \"--tw-ring-color\": `color-mix(in srgb, ${color} 30%, transparent)` } as CSSProperties}\n        >\n          <svg\n            viewBox=\"0 0 20 20\"\n            fill=\"none\"\n            stroke=\"currentColor\"\n            strokeWidth={2.2}\n            strokeLinecap=\"round\"\n            strokeLinejoin=\"round\"\n            className={`size-5 ${vertical ? \"rotate-90\" : \"\"}`}\n          >\n            <path d=\"M7.5 5.5 3 10l4.5 4.5M12.5 5.5 17 10l-4.5 4.5\" />\n          </svg>\n        </span>\n      </div>\n    </div>\n  );\n}\n"}]}