{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "spring-slider",
  "title": "Spring Compare Slider",
  "description": "A before/after slider on a spring: the divider bends with its speed, the old side crumbles into pixels and sparks fly off the line.",
  "dependencies": [
    "motion"
  ],
  "files": [
    {
      "path": "src/registry/easeout/spring-slider.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { animate, type AnimationPlaybackControls } from \"motion/react\"\n\n/*\n  Spring compare slider by easeout (easeoutstudio.com). Free to use, MIT.\n  Install: npx shadcn@latest add @easeout/spring-slider\n  Drag it, click anywhere on it, or use the arrow keys (±10%, Home/End). It settles on a spring (k 400, c 40)\n  instead of stopping dead. No re-renders while it moves: everything runs on CSS variables and refs.\n\n  While it moves (turn off with effects={false}; always off for reduced motion):\n  - the divider bends: the faster it goes, the further its middle leads its ends, then it springs back straight\n  - the old side crumbles: it drains toward grey and a band of pixel blocks flickers in along the line\n  - sparks and star glints fly off the curve, and chips of the old side break away from it (or fly back in when\n    you pull the divider back)\n*/\n\nexport type SpringSliderProps = {\n  before: React.ReactNode\n  after: React.ReactNode\n  /** Start position, 0–100. */\n  initial?: number\n  label?: string\n  /** Glides between a few positions on its own until someone points at it, drags it or focuses it. */\n  autoplay?: boolean\n  /** The bend, the crumbling old side and the sparks. */\n  effects?: boolean\n  /** Corner tags for the two sides; false hides them. */\n  labels?: [string, string] | false\n  className?: string\n}\n\nconst clamp = (v: number) => (v < 0 ? 0 : v > 100 ? 100 : v)\n\n// the crumble band's pixel blocks: one 64px tile of squares at fixed random opacities\nconst BLOCKS = (() => {\n  let seed = 7\n  const rnd = () => ((seed = (seed * 16807) % 2147483647) - 1) / 2147483646\n  let rects = \"\"\n  for (let r = 0; r < 8; r++)\n    for (let c = 0; c < 8; c++) {\n      const a = rnd()\n      if (a < 0.35) continue\n      const fill = rnd() < 0.7 ? \"0B0B0D\" : \"FFFFFF\"\n      rects += `<rect x='${c * 8}' y='${r * 8}' width='7' height='7' fill='%23${fill}' fill-opacity='${(a * 0.9).toFixed(2)}'/>`\n    }\n  return `url(\"data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='64' height='64'>${rects}</svg>\")`\n})()\nconst CHIPS = [\"#0B0B0D\", \"#2A2A30\", \"#FFFFFF\", \"#9AA3B5\"]\nconst EASE = \"cubic-bezier(.16,1,.3,1)\"\nconst MAX_BITS = 90\n\nexport function SpringSlider({\n  before,\n  after,\n  initial = 50,\n  label = \"Compare before and after\",\n  autoplay = false,\n  effects = true,\n  labels = [\"Before\", \"After\"],\n  className,\n}: SpringSliderProps) {\n  const root = React.useRef<HTMLDivElement>(null)\n  const knob = React.useRef<HTMLButtonElement>(null)\n  const old = React.useRef<HTMLDivElement>(null)\n  const neu = React.useRef<HTMLDivElement>(null)\n  const crumble = React.useRef<HTMLDivElement>(null)\n  const curve = React.useRef<SVGPathElement>(null)\n  const bits = React.useRef<HTMLDivElement>(null)\n  const p = React.useRef(initial)\n  const anim = React.useRef<AnimationPlaybackControls | null>(null)\n  const dragging = React.useRef(false)\n  const fx = React.useRef<{ push: (v: number) => void; stop: () => void } | null>(null)\n\n  // the effects engine: lives outside React, set up once per mount\n  React.useEffect(() => {\n    const el = root.current\n    if (!effects || !el || window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches) return\n    let w = el.clientWidth\n    let h = el.clientHeight\n    const ro = new ResizeObserver(() => {\n      w = el.clientWidth\n      h = el.clientHeight\n    })\n    ro.observe(el)\n\n    // bend: a spring that chases the divider's speed\n    let pct = p.current\n    let lastPx = NaN\n    let lastT = 0\n    let target = 0\n    let b = 0\n    let vb = 0\n    let raf = 0\n    let bent = false\n    const maxBend = () => Math.min(40, w * 0.055)\n    const flat = () => {\n      bent = false\n      el.style.setProperty(\"--bx\", \"0px\")\n      if (old.current) old.current.style.clipPath = \"\"\n      if (neu.current) neu.current.style.clipPath = \"\"\n      el.removeAttribute(\"data-bend\")\n    }\n    const draw = () => {\n      const x = (pct / 100) * w\n      const cx = x + 2 * b // a quadratic's middle sits halfway to its control point: the bulge is exactly b\n      const m = h / 2\n      if (old.current) old.current.style.clipPath = `path(\"M0 0H${x.toFixed(1)}Q${cx.toFixed(1)} ${m} ${x.toFixed(1)} ${h}H0Z\")`\n      if (neu.current) neu.current.style.clipPath = `path(\"M${x.toFixed(1)} 0H${w}V${h}H${x.toFixed(1)}Q${cx.toFixed(1)} ${m} ${x.toFixed(1)} 0Z\")`\n      curve.current?.setAttribute(\"d\", `M${x.toFixed(1)} 0Q${cx.toFixed(1)} ${m} ${x.toFixed(1)} ${h}`)\n      el.style.setProperty(\"--bx\", `${b.toFixed(2)}px`)\n    }\n    const frame = (now: number) => {\n      if (now - lastT > 70) target *= 0.6\n      vb = (vb + (target - b) * 0.16) * 0.74\n      b += vb\n      if (Math.abs(b) < 0.15 && Math.abs(vb) < 0.05 && Math.abs(target) < 0.15) {\n        b = vb = target = 0\n        raf = 0\n        return flat()\n      }\n      if (!bent) {\n        bent = true\n        el.setAttribute(\"data-bend\", \"\")\n      }\n      draw()\n      raf = requestAnimationFrame(frame)\n    }\n\n    // the crumble band flickers through its tile while it shows\n    const flicker = crumble.current?.animate([{ backgroundPosition: \"0 0\" }, { backgroundPosition: \"-64px 24px\" }], {\n      duration: 360,\n      iterations: Infinity,\n      easing: \"steps(6)\",\n    })\n    flicker?.pause()\n\n    // sparks, glints and chips, each a tiny element animated with WAAPI and removed when done\n    let live = 0\n    const fly = (bit: HTMLElement, frames: Keyframe[], ms: number) => {\n      bits.current?.appendChild(bit)\n      live++\n      bit.animate(frames, { duration: ms, easing: EASE }).finished.then(\n        () => {\n          bit.remove()\n          live--\n        },\n        () => {},\n      )\n    }\n    const spray = (dir: number) => {\n      if (live >= MAX_BITS) return\n      const on = () => {\n        const t = Math.random()\n        return { x: (pct / 100) * w + 4 * b * t * (1 - t), y: t * h }\n      }\n      for (let i = 0; i < 3; i++) {\n        const { x, y } = on()\n        const star = Math.random() < 0.3\n        const s = star ? 6 + Math.random() * 6 : 1.5 + Math.random() * 2.5\n        const bit = document.createElement(\"i\")\n        bit.style.cssText =\n          `position:absolute;left:${x.toFixed(0)}px;top:${y.toFixed(0)}px;width:${s.toFixed(1)}px;height:${s.toFixed(1)}px;background:#fff;pointer-events:none;` +\n          (star\n            ? `clip-path:polygon(50% 0,61% 39%,100% 50%,61% 61%,50% 100%,39% 61%,0 50%,39% 39%);filter:drop-shadow(0 0 3px ${Math.random() < 0.3 ? \"rgb(255 120 60 / .9)\" : \"rgb(150 165 255 / .9)\"})`\n            : \"border-radius:999px;box-shadow:0 0 4px 1px rgb(150 165 255 / .75)\")\n        const dx = -dir * (10 + Math.random() * 48)\n        const dy = (Math.random() - 0.5) * 36\n        const spin = star ? (Math.random() - 0.5) * 180 : 0\n        fly(\n          bit,\n          [\n            { transform: \"translate(-50%,-50%) scale(1) rotate(0deg)\", opacity: 1 },\n            { transform: `translate(calc(-50% + ${dx.toFixed(0)}px),calc(-50% + ${dy.toFixed(0)}px)) scale(.2) rotate(${spin.toFixed(0)}deg)`, opacity: 0 },\n          ],\n          star ? 900 + Math.random() * 500 : 600 + Math.random() * 600,\n        )\n      }\n      for (let i = 0; i < 2; i++) {\n        const { x, y } = on()\n        const s = 3 + Math.random() * 4\n        const bit = document.createElement(\"i\")\n        bit.style.cssText = `position:absolute;left:${x.toFixed(0)}px;top:${y.toFixed(0)}px;width:${s.toFixed(1)}px;height:${s.toFixed(1)}px;border-radius:1px;pointer-events:none;background:${CHIPS[(Math.random() * CHIPS.length) | 0]}`\n        const off = `translate(calc(-50% - ${(20 + Math.random() * 60).toFixed(0)}px),calc(-50% + ${((Math.random() - 0.3) * 44).toFixed(0)}px)) rotate(${((Math.random() - 0.5) * 120).toFixed(0)}deg) scale(.4)`\n        const at = \"translate(calc(-50% - 4px),-50%) rotate(0deg) scale(1)\"\n        // the new side winning (moving left): chips break away; pulled back: they fly in and settle\n        fly(\n          bit,\n          dir < 0 ? [{ transform: at, opacity: 0.95 }, { transform: off, opacity: 0 }] : [{ transform: off, opacity: 0 }, { transform: at, opacity: 0.9, offset: 0.85 }, { transform: at, opacity: 0 }],\n          700 + Math.random() * 500,\n        )\n      }\n    }\n\n    let still = 0\n    let lastSpray = 0\n    fx.current = {\n      push(v) {\n        const now = performance.now()\n        const px = (v / 100) * w\n        const dpx = px - lastPx\n        pct = v\n        if (!Number.isNaN(lastPx) && now > lastT) {\n          const m = maxBend()\n          target = Math.max(-m, Math.min(m, (dpx / Math.max(8, now - lastT)) * 70))\n        }\n        lastPx = px\n        lastT = now\n        if (bent) draw() // now, not next frame: the divider's spring may run after this frame's bend step\n        if (!raf) raf = requestAnimationFrame(frame)\n        if (Number.isNaN(dpx) || Math.abs(dpx) < 0.4) return\n        el.setAttribute(\"data-moving\", \"\")\n        flicker?.play()\n        clearTimeout(still)\n        still = window.setTimeout(() => {\n          el.removeAttribute(\"data-moving\")\n          flicker?.pause()\n        }, 200)\n        if (now - lastSpray > 32) {\n          lastSpray = now\n          spray(Math.sign(dpx))\n        }\n      },\n      stop() {\n        cancelAnimationFrame(raf)\n        clearTimeout(still)\n        flicker?.cancel()\n        ro.disconnect()\n        el.removeAttribute(\"data-moving\")\n        bits.current?.replaceChildren()\n        flat()\n      },\n    }\n    return () => {\n      fx.current?.stop()\n      fx.current = null\n    }\n  }, [effects])\n\n  const set = React.useCallback((v: number) => {\n    p.current = clamp(v)\n    root.current?.style.setProperty(\"--p\", p.current + \"%\")\n    knob.current?.setAttribute(\"aria-valuenow\", String(Math.round(p.current)))\n    fx.current?.push(p.current)\n  }, [])\n  const to = React.useCallback(\n    (v: number, instant = false) => {\n      anim.current?.stop()\n      if (instant || window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches) return set(v)\n      anim.current = animate(p.current, clamp(v), { type: \"spring\", stiffness: 400, damping: 40, restDelta: 0.05, onUpdate: set })\n    },\n    [set],\n  )\n  React.useEffect(() => () => anim.current?.stop(), [])\n\n  const held = React.useRef(false)\n  React.useEffect(() => {\n    if (!autoplay || window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches) return\n    const stops = [78, 22, 64, 40]\n    let i = 0\n    const id = window.setInterval(() => {\n      if (held.current) return\n      to(stops[i++ % stops.length])\n    }, 1700)\n    return () => clearInterval(id)\n  }, [autoplay, to])\n\n  const at = (clientX: number) => {\n    const r = root.current!.getBoundingClientRect()\n    return ((clientX - r.left) / r.width) * 100\n  }\n\n  return (\n    <div\n      ref={root}\n      className={[\n        \"group/ss relative isolate aspect-[16/9] cursor-ew-resize touch-pan-y select-none overflow-hidden rounded-2xl bg-neutral-950 shadow-[0_0_0_1px_var(--color-border)] [--bx:0px] [--p:50%]\",\n        className,\n      ]\n        .filter(Boolean)\n        .join(\" \")}\n      style={{ \"--p\": `${initial}%` } as React.CSSProperties}\n      onPointerEnter={() => (held.current = true)}\n      onPointerLeave={() => (held.current = dragging.current)}\n      onFocus={() => (held.current = true)}\n      onBlur={() => (held.current = false)}\n      onPointerDown={(e) => {\n        held.current = true\n        dragging.current = true\n        e.currentTarget.setPointerCapture(e.pointerId)\n        to(at(e.clientX))\n        knob.current?.focus({ preventScroll: true })\n      }}\n      onPointerMove={(e) => dragging.current && to(at(e.clientX))}\n      onPointerUp={() => (dragging.current = false)}\n      onPointerCancel={() => (dragging.current = false)}\n    >\n      <div ref={neu} className=\"absolute inset-0 [clip-path:inset(0_0_0_var(--p))]\">\n        {after}\n      </div>\n      <div ref={old} className=\"absolute inset-0 [clip-path:inset(0_calc(100%-var(--p))_0_0)]\">\n        {/* the old side drains toward grey while the divider moves */}\n        <div className=\"absolute inset-0 transition-[filter] duration-[420ms] ease-[cubic-bezier(.16,1,.3,1)] group-data-moving/ss:grayscale-[.75] group-data-moving/ss:duration-150\">\n          {before}\n        </div>\n        {effects && (\n          <div\n            ref={crumble}\n            aria-hidden=\"true\"\n            className=\"pointer-events-none absolute inset-y-0 left-[calc(var(--p)-var(--cw)*.74+var(--bx)/2)] w-(--cw) opacity-0 transition-opacity duration-[380ms] [--cw:min(220px,36%)] [mask-image:linear-gradient(90deg,transparent,rgb(0_0_0/.25)_35%,#000_70%)] group-data-moving/ss:opacity-70 group-data-moving/ss:duration-100\"\n            style={{ backgroundImage: BLOCKS, backgroundSize: \"64px 64px\" }}\n          />\n        )}\n      </div>\n      {/* the divider: a straight line at rest, the SVG curve while it bends */}\n      <div className=\"pointer-events-none absolute inset-y-0 left-[var(--p)] w-px -translate-x-1/2 bg-white/90 shadow-[0_0_0_.5px_rgba(0,0,0,.1),0_0_18px_rgba(0,0,0,.22)] group-data-bend/ss:opacity-0\" />\n      <svg aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0 size-full overflow-visible opacity-0 group-data-bend/ss:opacity-100\">\n        <path ref={curve} fill=\"none\" stroke=\"rgb(255 255 255 / .9)\" strokeWidth=\"1.25\" strokeLinecap=\"round\" />\n      </svg>\n      <div ref={bits} aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0 overflow-hidden\" />\n      {labels && (\n        <>\n          <span className=\"pointer-events-none absolute top-3 left-3 rounded-full bg-black/45 px-2.5 py-1 text-[11px] font-medium text-white backdrop-blur-sm\">{labels[0]}</span>\n          <span className=\"pointer-events-none absolute top-3 right-3 rounded-full bg-black/45 px-2.5 py-1 text-[11px] font-medium text-white backdrop-blur-sm\">{labels[1]}</span>\n        </>\n      )}\n      <button\n        ref={knob}\n        type=\"button\"\n        role=\"slider\"\n        aria-label={label}\n        aria-valuemin={0}\n        aria-valuemax={100}\n        aria-valuenow={initial}\n        onKeyDown={(e) => {\n          const step = e.key === \"ArrowRight\" || e.key === \"ArrowUp\" ? 10 : e.key === \"ArrowLeft\" || e.key === \"ArrowDown\" ? -10 : 0\n          if (step) to(p.current + step)\n          else if (e.key === \"Home\") to(0)\n          else if (e.key === \"End\") to(100)\n          else return\n          e.preventDefault()\n        }}\n        className=\"absolute top-1/2 left-[calc(var(--p)+var(--bx))] grid size-10 -translate-x-1/2 -translate-y-1/2 cursor-ew-resize place-items-center rounded-full bg-white p-0 text-neutral-800 shadow-[0_0_0_1px_rgba(0,0,0,.06),0_2px_6px_rgba(0,0,0,.12),0_10px_24px_-8px_rgba(0,0,0,.3)] transition-[scale] duration-200 group-data-moving/ss:scale-95 before:pointer-events-none before:absolute before:-inset-2.5 before:rounded-full before:border before:border-white/45 focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-white\"\n      >\n        <svg viewBox=\"0 0 24 24\" width=\"18\" height=\"18\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.8\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n          <path d=\"m9 18-6-6 6-6\" />\n          <path d=\"m15 6 6 6-6 6\" />\n        </svg>\n      </button>\n    </div>\n  )\n}\n",
      "type": "registry:component"
    }
  ],
  "docs": "Import it with `import { SpringSlider } from \"@/components/spring-slider\"`. Live demo, props and a usage example: https://www.easeoutstudio.com/lab/spring-slider",
  "type": "registry:component"
}
