{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"slide-to-confirm","type":"registry:component","title":"Slide to confirm","description":"Drag the knob all the way across to confirm.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/slide-to-confirm.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport {\n  animate,\n  motion,\n  useMotionTemplate,\n  useMotionValue,\n  useTransform,\n} from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\nconst KNOB = 56;\nconst INSET = 4;\n// Past this share of the track, a fast enough release finishes the slide\n// even though the knob never touched the end.\nconst FLICK_PROGRESS = 0.7;\nconst FLICK_VELOCITY = 500;\n// How far the knob gives when pulled back past the start, in px. Small, so\n// it never pokes far outside the track.\nconst MAX_STRETCH = 6;\n// Carries the release velocity home; the slight bounce is earned by the\n// throw, and only ever happens after a drag.\nconst SNAP_BACK = { type: \"spring\", visualDuration: 0.4, bounce: 0.15 } as const;\nconst COMPLETE = { type: \"spring\", visualDuration: 0.3, bounce: 0 } as const;\n// Slower than the snap back: nobody is waiting on the reset, so it can glide.\nconst RESET = { type: \"spring\", visualDuration: 0.5, bounce: 0 } as const;\nconst ICON_SWAP = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\n// Long enough to read \"Confirmed\", short enough to try again.\nconst CONFIRMED_FOR = 2000;\n\n// A narrow highlight sweeps across in the first 70% of each loop, then\n// rests off the edge, so it reads as an invitation rather than a warning.\nconst CSS = `\n.slide-shimmer {\n  background: linear-gradient(90deg, var(--muted-foreground) 0%, var(--muted-foreground) 45%, var(--foreground) 50%, var(--muted-foreground) 55%, var(--muted-foreground) 100%);\n  background-size: 250% 100%;\n  background-position: 100% 0;\n  -webkit-background-clip: text;\n  background-clip: text;\n  color: transparent;\n  animation: slide-shimmer 2.6s cubic-bezier(0.45, 0, 0.55, 1) infinite;\n}\n[data-done=\"true\"] .slide-shimmer { animation-play-state: paused; }\n@keyframes slide-shimmer {\n  70%, 100% { background-position: 0 0; }\n}\n@media (prefers-reduced-motion: reduce) {\n  .slide-shimmer { animation: none; background: none; color: var(--muted-foreground); }\n}\n`;\n\ntype Anim = ReturnType<typeof animate>;\n\nexport function SlideToConfirm({\n  label = \"Slide to confirm\",\n  confirmedLabel = \"Confirmed\",\n  onConfirm,\n  className,\n}: {\n  label?: string;\n  confirmedLabel?: string;\n  onConfirm?: () => void;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const hintId = useId();\n  const trackRef = useRef<HTMLDivElement>(null);\n  const [done, setDone] = useState(false);\n  const x = useMotionValue(0);\n  const anim = useRef<Anim | null>(null);\n  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);\n  const drag = useRef<{\n    id: number;\n    offset: number;\n    max: number;\n    samples: { x: number; t: number }[];\n  } | null>(null);\n\n  useEffect(\n    () => () => {\n      clearTimeout(timer.current);\n      anim.current?.stop();\n    },\n    [],\n  );\n\n  const maxX = () =>\n    Math.max((trackRef.current?.clientWidth ?? 0) - KNOB - INSET * 2, 1);\n\n  // The label is gone by 60% of the way, so it never sits under the knob.\n  const labelOpacity = useTransform(x, (v) =>\n    Math.min(Math.max(1 - v / (maxX() * 0.6), 0), 1),\n  );\n  // A track-wide pill whose right end rides just behind the knob. Moving it\n  // is a transform, where growing a width would relayout every frame.\n  const fill = useMotionTemplate`translateX(calc(${x}px - 100% + ${KNOB}px))`;\n\n  const moveTo = (target: number, transition: object) => {\n    anim.current?.stop();\n    if (reduceMotion) {\n      anim.current = null;\n      x.jump(target);\n    } else {\n      anim.current = animate(x, target, transition);\n    }\n  };\n\n  const confirm = (velocity = 0) => {\n    drag.current = null;\n    setDone(true);\n    moveTo(maxX(), { ...COMPLETE, velocity });\n    onConfirm?.();\n    navigator.vibrate?.(10);\n    clearTimeout(timer.current);\n    timer.current = setTimeout(() => {\n      setDone(false);\n      moveTo(0, RESET);\n    }, CONFIRMED_FOR);\n  };\n\n  const release = (e: React.PointerEvent) => {\n    const d = drag.current;\n    if (!d || e.pointerId !== d.id) return;\n    drag.current = null;\n    const first = d.samples[0];\n    const end = d.samples[d.samples.length - 1];\n    const dt = (end.t - first.t) / 1000;\n    const velocity = dt > 0 ? (end.x - first.x) / dt : 0;\n    if (x.get() / d.max >= FLICK_PROGRESS && velocity > FLICK_VELOCITY) {\n      confirm(velocity);\n    } else {\n      moveTo(0, { ...SNAP_BACK, velocity });\n    }\n  };\n\n  return (\n    <div\n      ref={trackRef}\n      data-done={done}\n      className={cn(\n        \"relative h-16 w-[min(360px,100%)] rounded-full bg-muted shadow-wheel select-none\",\n        className,\n      )}\n    >\n      <style href=\"slide-to-confirm\" precedence=\"default\">\n        {CSS}\n      </style>\n\n      <div aria-hidden className=\"absolute inset-1 overflow-hidden rounded-full\">\n        <motion.div\n          style={{ transform: fill }}\n          className={cn(\n            \"h-full w-full rounded-full bg-foreground transition-[opacity] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)]\",\n            done ? \"opacity-100\" : \"opacity-[0.08]\",\n          )}\n        />\n      </div>\n\n      <motion.span\n        aria-hidden\n        style={{ opacity: labelOpacity }}\n        className=\"absolute inset-y-0 right-0 left-16 flex items-center justify-center pr-4 text-[15px] font-medium\"\n      >\n        <span className=\"slide-shimmer\">{label}</span>\n      </motion.span>\n\n      {/* Enters in 200ms, leaves in 150ms: the exit should never hold the eye. */}\n      <span\n        aria-hidden\n        className={cn(\n          \"absolute inset-y-0 right-16 left-0 flex items-center justify-center gap-2 pl-4 text-[15px] font-medium text-background\",\n          \"transition-[opacity,filter] ease-[cubic-bezier(0.23,1,0.32,1)]\",\n          done ? \"duration-200\" : \"opacity-0 blur-[4px] duration-150\",\n        )}\n      >\n        <motion.svg\n          viewBox=\"0 0 16 16\"\n          className=\"size-4 shrink-0\"\n          fill=\"none\"\n          stroke=\"currentColor\"\n          strokeWidth={2}\n          strokeLinecap=\"round\"\n          strokeLinejoin=\"round\"\n          initial={false}\n          animate={\n            done\n              ? { scale: 1, opacity: 1, filter: \"blur(0px)\" }\n              : reduceMotion\n                ? { scale: 1, opacity: 0, filter: \"blur(0px)\" }\n                : { scale: 0.25, opacity: 0, filter: \"blur(4px)\" }\n          }\n          transition={ICON_SWAP}\n        >\n          <path d=\"m3.5 8.5 3 3 6-7\" />\n        </motion.svg>\n        {confirmedLabel}\n      </span>\n\n      <motion.button\n        type=\"button\"\n        aria-label={label}\n        aria-describedby={hintId}\n        aria-disabled={done}\n        style={{ x }}\n        className={cn(\n          \"absolute top-1 left-1 flex size-14 touch-none items-center justify-center rounded-full bg-background text-foreground shadow-raised outline-hidden\",\n          \"transition-[scale] duration-150 ease-out focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground motion-reduce:transition-none\",\n          done ? \"cursor-default\" : \"cursor-grab active:scale-[0.96] active:cursor-grabbing\",\n        )}\n        onPointerDown={(e) => {\n          if (done || (e.pointerType === \"mouse\" && e.button !== 0)) return;\n          // Only the first finger drives; a second one mid-drag is ignored.\n          if (drag.current) return;\n          anim.current?.stop();\n          e.currentTarget.setPointerCapture(e.pointerId);\n          drag.current = {\n            id: e.pointerId,\n            // Keeps the knob under the exact point it was grabbed, even if\n            // caught mid-spring.\n            offset: e.clientX - x.get(),\n            max: maxX(),\n            samples: [{ x: e.clientX, t: e.timeStamp }],\n          };\n        }}\n        onPointerMove={(e) => {\n          const d = drag.current;\n          if (!d || e.pointerId !== d.id) return;\n          d.samples.push({ x: e.clientX, t: e.timeStamp });\n          // Only the last 100ms say how fast the hand is moving now.\n          while (d.samples.length > 2 && e.timeStamp - d.samples[0].t > 100)\n            d.samples.shift();\n          const raw = e.clientX - d.offset;\n          if (raw >= d.max) {\n            const first = d.samples[0];\n            const dt = (e.timeStamp - first.t) / 1000;\n            confirm(dt > 0 ? (e.clientX - first.x) / dt : 0);\n            return;\n          }\n          // Gives a little past the start, then stiffens.\n          x.set(raw < 0 ? MAX_STRETCH * Math.tanh(raw / (MAX_STRETCH * 4)) : raw);\n        }}\n        onPointerUp={release}\n        onPointerCancel={release}\n        // Enter and Space, and screen reader activation, arrive as clicks\n        // with no pointer detail. They slide exactly as a drag would.\n        onClick={(e) => {\n          if (e.detail === 0 && !done) confirm();\n        }}\n        onKeyDown={(e) => {\n          if ((e.key === \"ArrowRight\" || e.key === \"End\") && !done) {\n            e.preventDefault();\n            confirm();\n          }\n        }}\n      >\n        <svg\n          viewBox=\"0 0 16 16\"\n          className=\"size-5 translate-x-px\"\n          fill=\"none\"\n          stroke=\"currentColor\"\n          strokeWidth={2}\n          strokeLinecap=\"round\"\n          strokeLinejoin=\"round\"\n          aria-hidden\n        >\n          <path d=\"m6 3.5 4.5 4.5L6 12.5\" />\n        </svg>\n      </motion.button>\n\n      <span id={hintId} className=\"sr-only\">\n        Drag to the end, or press Enter\n      </span>\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {done ? confirmedLabel : \"\"}\n      </span>\n    </div>\n  );\n}\n\nexport default function SlideToConfirmDemo() {\n  return <SlideToConfirm />;\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)","shadow-wheel":"inset 0 1px 2px oklch(0 0 0 / 0.08), inset 0 0 0 1px oklch(0 0 0 / 0.04)"},"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)","shadow-wheel":"inset 0 1px 2px oklch(0 0 0 / 0.5), inset 0 0 0 1px oklch(1 0 0 / 0.04)"},"theme":{"shadow-raised":"var(--shadow-raised)","shadow-wheel":"var(--shadow-wheel)"}},"categories":["buttons"],"docs":"From ui lab: https://lab.xevrion.dev/lab/slide-to-confirm"}