{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"signature-pad","type":"registry:component","title":"Signature pad","description":"Ink that swells where you slow down, and wipes away the way you wrote it.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/signature-pad.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useImperativeHandle, useRef, useState } from \"react\";\nimport { AnimatePresence, motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { usePreviewPlay } from \"@/lib/preview-play\";\nimport { SIGNATURE, SIGNATURE_VIEWBOX } from \"@/lib/signature\";\nimport { cn } from \"@/lib/utils\";\n\ntype Point = { x: number; y: number; w: number };\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n// Ink width in px: fast strokes thin out to MIN, slow ones swell to MAX,\n// the way a pen leaves more ink where it lingers.\nconst MIN = 1.1;\nconst MAX = 3.6;\n\nexport type PadActions = {\n  begin: (x: number, y: number) => void;\n  move: (x: number, y: number, t: number, pressure?: number) => void;\n  end: () => void;\n  clear: () => void;\n};\n\nexport function SignaturePad({\n  ref,\n  onSignedChange,\n  className,\n}: {\n  // Lets a script sign the pad through the same path a hand takes.\n  ref?: React.Ref<PadActions>;\n  onSignedChange?: (signed: boolean) => void;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const canvas = useRef<HTMLCanvasElement>(null);\n  const strokes = useRef<Point[][]>([]);\n  const last = useRef<{ x: number; y: number; t: number; w: number } | null>(null);\n  const [hasInk, setHasInk] = useState(false);\n  const [done, setDone] = useState(false);\n  const [wiping, setWiping] = useState(false);\n\n  const ctx = () => canvas.current?.getContext(\"2d\") ?? null;\n  const ink = () =>\n    canvas.current ? getComputedStyle(canvas.current).color : \"#171717\";\n\n  // Draws one smoothed piece of a stroke: a curve through the previous\n  // point, from midpoint to midpoint, so corners come out round.\n  const segment = (c: CanvasRenderingContext2D, a: Point, b: Point, d: Point) => {\n    c.beginPath();\n    c.moveTo((a.x + b.x) / 2, (a.y + b.y) / 2);\n    c.quadraticCurveTo(b.x, b.y, (b.x + d.x) / 2, (b.y + d.y) / 2);\n    c.lineWidth = d.w;\n    c.stroke();\n  };\n\n  const redraw = () => {\n    const el = canvas.current;\n    const c = ctx();\n    if (!el || !c) return;\n    c.clearRect(0, 0, el.width, el.height);\n    c.strokeStyle = c.fillStyle = ink();\n    c.lineCap = c.lineJoin = \"round\";\n    for (const s of strokes.current) {\n      if (s.length === 1) {\n        c.beginPath();\n        c.arc(s[0].x, s[0].y, s[0].w / 2, 0, Math.PI * 2);\n        c.fill();\n      }\n      for (let i = 1; i < s.length; i++) segment(c, s[Math.max(0, i - 2)], s[i - 1], s[i]);\n    }\n  };\n\n  // Sharp at any pixel density, redrawn from the points on resize and when\n  // the theme flips the ink colour.\n  useEffect(() => {\n    const el = canvas.current;\n    if (!el) return;\n    const fit = () => {\n      const dpr = window.devicePixelRatio || 1;\n      el.width = el.offsetWidth * dpr;\n      el.height = el.offsetHeight * dpr;\n      el.getContext(\"2d\")?.setTransform(dpr, 0, 0, dpr, 0, 0);\n      redraw();\n    };\n    fit();\n    const ro = new ResizeObserver(fit);\n    ro.observe(el);\n    const mo = new MutationObserver(redraw);\n    mo.observe(document.documentElement, { attributes: true, attributeFilter: [\"data-theme\"] });\n    const media = matchMedia(\"(prefers-color-scheme: dark)\");\n    media.addEventListener(\"change\", redraw);\n    return () => {\n      ro.disconnect();\n      mo.disconnect();\n      media.removeEventListener(\"change\", redraw);\n    };\n    // redraw only reads refs; running this once is enough.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  const begin = (x: number, y: number) => {\n    if (wiping) return;\n    const p = { x, y, w: (MIN + MAX) / 2 };\n    strokes.current.push([p]);\n    last.current = { x, y, t: performance.now(), w: p.w };\n    if (!hasInk) setHasInk(true);\n    if (done) {\n      setDone(false);\n      onSignedChange?.(false);\n    }\n    const c = ctx();\n    if (c) {\n      c.fillStyle = ink();\n      c.beginPath();\n      c.arc(x, y, p.w / 2, 0, Math.PI * 2);\n      c.fill();\n    }\n  };\n\n  const move = (x: number, y: number, t: number, pressure?: number) => {\n    const prev = last.current;\n    const stroke = strokes.current.at(-1);\n    if (!prev || !stroke) return;\n    const dist = Math.hypot(x - prev.x, y - prev.y);\n    if (dist < 1) return;\n    const speed = dist / Math.max(1, t - prev.t); // px per ms\n    const target =\n      pressure !== undefined && pressure > 0 && pressure !== 0.5\n        ? MIN + (MAX - MIN) * Math.min(1, pressure * 1.2)\n        : Math.max(MIN, Math.min(MAX, MAX - speed * 1.4));\n    // Eases toward the new width, so the line swells and thins smoothly.\n    const w = prev.w * 0.72 + target * 0.28;\n    const point = { x, y, w };\n    stroke.push(point);\n    last.current = { x, y, t, w };\n    const c = ctx();\n    if (c && stroke.length > 1) {\n      c.strokeStyle = ink();\n      c.lineCap = c.lineJoin = \"round\";\n      segment(c, stroke[Math.max(0, stroke.length - 3)], stroke[stroke.length - 2], point);\n    }\n  };\n\n  const end = () => {\n    last.current = null;\n  };\n\n  // Wipes the ink away left to right, the way it was written.\n  const clear = () => {\n    const el = canvas.current;\n    if (!el || !strokes.current.length || wiping) return;\n    const finish = () => {\n      strokes.current = [];\n      redraw();\n      setWiping(false);\n      setHasInk(false);\n      setDone(false);\n      onSignedChange?.(false);\n    };\n    if (reduceMotion) return finish();\n    setWiping(true);\n    // The browser's own animation, held at its end until the ink is gone,\n    // then cancelled so the canvas is left with no clip at all. (A library\n    // animation that writes its final value back would leave the canvas\n    // clipped away, and new ink would draw invisibly.)\n    const wipe = el.animate(\n      [{ clipPath: \"inset(0 0 0 0%)\" }, { clipPath: \"inset(0 0 0 100%)\" }],\n      { duration: 450, easing: \"cubic-bezier(0.77, 0, 0.175, 1)\", fill: \"forwards\" },\n    );\n    wipe.onfinish = () => {\n      finish();\n      wipe.cancel();\n    };\n  };\n\n  useImperativeHandle(ref, () => ({ begin, move, end, clear }));\n\n  // Pointer positions in the canvas's own pixels, even inside a scaled card.\n  const at = (e: React.PointerEvent<HTMLCanvasElement>) => {\n    const el = e.currentTarget;\n    const r = el.getBoundingClientRect();\n    const scale = r.width / el.offsetWidth || 1;\n    return { x: (e.clientX - r.left) / scale, y: (e.clientY - r.top) / scale };\n  };\n  const pressureOf = (e: React.PointerEvent) =>\n    e.pointerType === \"pen\" ? e.pressure : undefined;\n\n  return (\n    <div\n      className={cn(\n        \"w-[min(440px,100%)] rounded-2xl bg-background p-5 shadow-raised\",\n        className,\n      )}\n    >\n      <div className=\"flex items-center justify-between\">\n        <p className=\"text-[14px] font-medium text-foreground\">Sign below</p>\n        <button\n          type=\"button\"\n          onClick={clear}\n          disabled={!hasInk || wiping}\n          className=\"h-8 rounded-full px-3 text-[13px] text-muted-foreground outline-hidden transition-[color,background-color,opacity,scale] duration-150 ease-out hover:bg-muted hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid active:scale-[0.96] disabled:pointer-events-none disabled:opacity-40\"\n        >\n          Clear\n        </button>\n      </div>\n\n      <div className=\"relative mt-3 h-44 overflow-hidden rounded-xl bg-muted shadow-[inset_0_0_0_1px_var(--border)]\">\n        {/* The line you sign on, with its little cross, like paper. */}\n        <div aria-hidden className=\"pointer-events-none absolute inset-x-6 bottom-10 flex items-end gap-2\">\n          <span className=\"-mb-0.5 text-[15px] leading-none text-muted-foreground\">×</span>\n          <span className=\"h-px flex-1 border-b border-dashed border-muted-foreground/50\" />\n        </div>\n        {!hasInk && (\n          <p className=\"pointer-events-none absolute inset-x-0 top-1/2 -translate-y-6 text-center text-[13px] text-muted-foreground\">\n            Sign with your mouse, pen or finger\n          </p>\n        )}\n        <canvas\n          ref={canvas}\n          role=\"img\"\n          aria-label={hasInk ? \"Your signature\" : \"Signature area, empty\"}\n          onPointerDown={(e) => {\n            if (e.button !== 0) return;\n            e.currentTarget.setPointerCapture(e.pointerId);\n            const p = at(e);\n            begin(p.x, p.y);\n          }}\n          onPointerMove={(e) => {\n            if (!last.current) return;\n            // Coalesced events keep fast strokes smooth instead of angular.\n            const events = e.nativeEvent.getCoalescedEvents?.() ?? [e.nativeEvent];\n            const r = e.currentTarget.getBoundingClientRect();\n            const scale = r.width / e.currentTarget.offsetWidth || 1;\n            for (const ev of events.length ? events : [e.nativeEvent]) {\n              move(\n                (ev.clientX - r.left) / scale,\n                (ev.clientY - r.top) / scale,\n                ev.timeStamp,\n                pressureOf(e),\n              );\n            }\n          }}\n          onPointerUp={end}\n          onPointerCancel={end}\n          className=\"absolute inset-0 size-full cursor-crosshair touch-none text-foreground\"\n        />\n        <AnimatePresence>\n          {done && (\n            <motion.p\n              initial={{ opacity: 0, y: -4, filter: \"blur(4px)\" }}\n              animate={{ opacity: 1, y: 0, filter: \"blur(0px)\" }}\n              exit={{ opacity: 0, transition: { duration: 0.12 } }}\n              transition={{ duration: 0.25, ease: EASE_OUT }}\n              className=\"pointer-events-none absolute top-3 right-3 flex items-center gap-1.5 rounded-full bg-background px-2.5 py-1 text-[12px] font-medium text-foreground shadow-[inset_0_0_0_1px_var(--border)]\"\n            >\n              <svg viewBox=\"0 0 16 16\" className=\"size-3.5\" fill=\"none\" stroke=\"currentColor\" strokeWidth={1.6} strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden>\n                <path d=\"M3.5 8.25l3 3 6-6.5\" />\n              </svg>\n              Signed\n            </motion.p>\n          )}\n        </AnimatePresence>\n      </div>\n\n      <div className=\"mt-4 flex items-center justify-between gap-3\">\n        <p className=\"text-[12px] text-muted-foreground\">Your signature stays on this page.</p>\n        <button\n          type=\"button\"\n          disabled={!hasInk || done || wiping}\n          onClick={() => {\n            setDone(true);\n            onSignedChange?.(true);\n          }}\n          className=\"h-9 shrink-0 rounded-full bg-foreground px-4 text-[13px] font-medium text-background outline-hidden transition-[opacity,scale] duration-150 ease-out hover:opacity-90 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-solid active:scale-[0.96] disabled:pointer-events-none disabled:opacity-30\"\n        >\n          Done\n        </button>\n      </div>\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {done ? \"Signature saved\" : \"\"}\n      </span>\n    </div>\n  );\n}\n\n// The card's hover show signs the lab's own name: the path is walked in\n// small steps, faster on the straights and slower round the bends, so the\n// ink swells and thins as a hand's would.\nfunction useSignatureReplay(actions: React.RefObject<PadActions | null>, play: boolean | null) {\n  useEffect(() => {\n    if (play !== true) return;\n    const svg = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\n    svg.setAttribute(\"style\", \"position:absolute;width:0;height:0;visibility:hidden\");\n    document.body.append(svg);\n    const [vx, vy, vw, vh] = SIGNATURE_VIEWBOX.split(\" \").map(Number);\n    const parts = SIGNATURE.split(/(?=M)/).map((d) => {\n      const path = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n      path.setAttribute(\"d\", d);\n      svg.append(path);\n      return path;\n    });\n    // Fits the signature into the pad: 400 by 176, sitting on the line.\n    const scale = Math.min(300 / vw, 110 / vh);\n    const ox = (400 - vw * scale) / 2 - vx * scale;\n    const oy = 24 - vy * scale;\n\n    let raf = 0;\n    let timer: ReturnType<typeof setTimeout>;\n    let stopped = false;\n    const sign = () => {\n      let part = 0;\n      let dist = 0;\n      let clock = performance.now();\n      let began = false;\n      const step = () => {\n        if (stopped) return;\n        const path = parts[part];\n        const len = path.getTotalLength();\n        // Covers ~10px of the path per frame, slower where it curves.\n        for (let k = 0; k < 3 && dist <= len; k++) {\n          const a = path.getPointAtLength(dist);\n          const b = path.getPointAtLength(Math.min(len, dist + 4));\n          const bend = Math.abs(Math.atan2(b.y - a.y, b.x - a.x));\n          clock += 4 + (bend > 1 ? 5 : 0);\n          const x = ox + a.x * scale;\n          const y = oy + a.y * scale;\n          if (!began) {\n            actions.current?.begin(x, y);\n            began = true;\n          } else actions.current?.move(x, y, clock);\n          dist += 3.5;\n        }\n        if (dist > len) {\n          actions.current?.end();\n          part++;\n          dist = 0;\n          began = false;\n          if (part >= parts.length) {\n            timer = setTimeout(() => {\n              actions.current?.clear();\n              timer = setTimeout(sign, 1100);\n            }, 1400);\n            return;\n          }\n        }\n        raf = requestAnimationFrame(step);\n      };\n      raf = requestAnimationFrame(step);\n    };\n    timer = setTimeout(sign, 300);\n    return () => {\n      stopped = true;\n      cancelAnimationFrame(raf);\n      clearTimeout(timer);\n      svg.remove();\n      // Whichever pad is showing when the show stops gets wiped.\n      // eslint-disable-next-line react-hooks/exhaustive-deps\n      actions.current?.clear();\n    };\n  }, [play, actions]);\n}\n\nexport default function SignaturePadDemo() {\n  const play = usePreviewPlay();\n  const actions = useRef<PadActions>(null);\n  useSignatureReplay(actions, play);\n  return <SignaturePad ref={actions} />;\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"},{"path":"lib/preview-play.ts","type":"registry:lib","target":"lib/preview-play.ts","content":"\"use client\";\n\nimport { createContext, useContext } from \"react\";\n\n// Lets a demo know whether it's showing in an index card, and whether that\n// card is hovered or focused. Demos use it to act themselves out on hover:\n// a star button stars itself, a checkbox scribbles, and so on.\n//\n// null: not in a preview (the component's own page, or real use).\n// false: in a preview, at rest.\n// true: in a preview, being hovered or focused: play the show.\nexport const PreviewPlayContext = createContext<boolean | null>(null);\n\nexport function usePreviewPlay() {\n  return useContext(PreviewPlayContext);\n}\n"},{"path":"lib/signature.ts","type":"registry:lib","target":"lib/signature.ts","content":"// Yash's handwritten \"xevrion\", one stroke plus the dot of the i. The same\n// path the footer-signature component draws; kept here too because that\n// component stays self-contained.\nexport const SIGNATURE_VIEWBOX = \"12 30 282 86\";\n\nexport const SIGNATURE =\n  \"M 24 60 C 31 50 47 50 46 60 C 46 70 40 80 30 80 C 22 80 22 72 28 72 C 38 70 54 60 70 54 \" +\n  \"C 62 52 50 60 50 70 C 50 80 60 82 68 78 C 77 74 89 66 90 60 C 92 54 84 54 80 62 \" +\n  \"C 76 72 80 82 92 78 C 100 72 104 60 108 54 C 108 64 107 74 110 80 C 116 72 124 60 130 54 \" +\n  \"C 133 50 127 50 126 56 C 126 60 132 60 139 58 C 141 56 143 52 145 47 C 146 52 146 56 150 55 \" +\n  \"C 153 54 154 52 157 52 C 153 62 151 72 151 80 C 156 74 163 62 167 54 C 164 64 160 76 165 80 \" +\n  \"C 173 76 191 58 202 54 C 193 50 182 62 182 72 C 182 82 194 82 200 72 C 205 64 204 54 200 54 \" +\n  \"C 205 58 211 58 217 56 C 222 54 220 64 214 80 C 221 66 232 54 237 56 C 243 58 238 72 238 80 \" +\n  \"C 241 86 254 80 264 70 C 286 52 268 100 206 100 C 156 100 105 102 54 108 \" +\n  \"M 171 41 C 172 40 174 39 175 39\";\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":["inputs"],"docs":"From ui lab: https://lab.xevrion.dev/lab/signature-pad"}