{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "signature-pad",
  "title": "Signature Pad",
  "description": "A signature field that draws smooth, pressure-aware ink, with undo, clear, a typed-signature option for people who can't draw, and PNG and SVG export in a paper-ready ink colour.",
  "dependencies": [
    "motion",
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/signature-pad/signature-pad.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { motion, AnimatePresence } from \"motion/react\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\nexport type SignaturePadSize = \"sm\" | \"md\" | \"lg\";\n\nexport interface SignatureResult {\n  isEmpty: boolean;\n  /** PNG data URL on a transparent background, drawn in exportColor. Null when empty. */\n  dataUrl: string | null;\n  /** Standalone SVG markup, drawn in exportColor. Null when empty. */\n  svg: string | null;\n  mode: \"draw\" | \"type\";\n  /** The typed name in type mode. */\n  typedName: string;\n}\n\nexport interface SignaturePadProps {\n  onChange?: (result: SignatureResult) => void;\n  label?: string;\n  helperText?: string;\n  placeholder?: string;\n  /** Offer a \"Type\" tab that renders the typed name in a script face. */\n  allowTyping?: boolean;\n  /** Ink colour on screen; defaults to the theme's text colour. */\n  penColor?: string;\n  /** Colour used in the exported PNG and SVG, so a signature drawn in dark mode still shows on white paper. */\n  exportColor?: string;\n  minWidth?: number;\n  maxWidth?: number;\n  height?: number;\n  size?: SignaturePadSize;\n  theme?: \"dark\" | \"light\";\n  width?: number | string;\n  disabled?: boolean;\n  className?: string;\n}\n\nconst PALETTES = {\n  dark: { text: \"#F5F4F1\", muted: \"rgba(245,244,241,0.5)\", faint: \"rgba(245,244,241,0.28)\", bg: \"rgba(255,255,255,0.03)\", border: \"rgba(255,255,255,0.12)\", borderHover: \"rgba(255,255,255,0.24)\", focus: \"rgba(245,244,241,0.85)\", line: \"rgba(245,244,241,0.22)\", hover: \"rgba(255,255,255,0.07)\", sel: \"#F5F4F1\", selText: \"#0A0A0A\", track: \"rgba(255,255,255,0.06)\" },\n  light: { text: \"#0A0A0A\", muted: \"rgba(10,10,10,0.5)\", faint: \"rgba(10,10,10,0.28)\", bg: \"#FFFFFF\", border: \"rgba(10,10,10,0.16)\", borderHover: \"rgba(10,10,10,0.3)\", focus: \"rgba(10,10,10,0.85)\", line: \"rgba(10,10,10,0.2)\", hover: \"rgba(10,10,10,0.05)\", sel: \"#0A0A0A\", selText: \"#FFFFFF\", track: \"rgba(10,10,10,0.05)\" },\n};\n\nconst SIZES: Record<SignaturePadSize, { font: number; radius: number; btn: number }> = {\n  sm: { font: 13, radius: 11, btn: 30 },\n  md: { font: 14.5, radius: 13, btn: 34 },\n  lg: { font: 16, radius: 15, btn: 38 },\n};\n\nconst SCRIPT_FONT = '\"Snell Roundhand\", \"Segoe Script\", \"Brush Script MT\", \"Apple Chancery\", cursive';\n\ninterface Point {\n  x: number;\n  y: number;\n  w: number;\n}\ntype Stroke = Point[];\n\n// Draws one stroke as a chain of quadratic curves through the midpoints, each segment at its own width.\nfunction drawStroke(ctx: CanvasRenderingContext2D, stroke: Stroke, color: string) {\n  ctx.strokeStyle = color;\n  ctx.fillStyle = color;\n  ctx.lineCap = \"round\";\n  ctx.lineJoin = \"round\";\n  if (stroke.length === 1) {\n    ctx.beginPath();\n    ctx.arc(stroke[0].x, stroke[0].y, stroke[0].w / 2, 0, Math.PI * 2);\n    ctx.fill();\n    return;\n  }\n  for (let i = 1; i < stroke.length; i++) {\n    const a = stroke[i - 1];\n    const b = stroke[i];\n    const prev = stroke[i - 2] ?? a;\n    const start = { x: (prev.x + a.x) / 2, y: (prev.y + a.y) / 2 };\n    const end = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };\n    ctx.lineWidth = (a.w + b.w) / 2;\n    ctx.beginPath();\n    ctx.moveTo(i === 1 ? a.x : start.x, i === 1 ? a.y : start.y);\n    ctx.quadraticCurveTo(a.x, a.y, end.x, end.y);\n    ctx.stroke();\n  }\n  const last = stroke[stroke.length - 1];\n  const beforeLast = stroke[stroke.length - 2];\n  ctx.lineWidth = last.w;\n  ctx.beginPath();\n  ctx.moveTo((beforeLast.x + last.x) / 2, (beforeLast.y + last.y) / 2);\n  ctx.lineTo(last.x, last.y);\n  ctx.stroke();\n}\n\nfunction strokesToSvg(strokes: Stroke[], w: number, h: number, color: string) {\n  const paths = strokes\n    .map((s) => {\n      if (s.length === 1) return `<circle cx=\"${s[0].x.toFixed(1)}\" cy=\"${s[0].y.toFixed(1)}\" r=\"${(s[0].w / 2).toFixed(2)}\" fill=\"${color}\"/>`;\n      let d = `M${s[0].x.toFixed(1)} ${s[0].y.toFixed(1)}`;\n      for (let i = 1; i < s.length; i++) {\n        const a = s[i - 1];\n        const b = s[i];\n        d += ` Q${a.x.toFixed(1)} ${a.y.toFixed(1)} ${((a.x + b.x) / 2).toFixed(1)} ${((a.y + b.y) / 2).toFixed(1)}`;\n      }\n      const avg = s.reduce((sum, p) => sum + p.w, 0) / s.length;\n      return `<path d=\"${d}\" fill=\"none\" stroke=\"${color}\" stroke-width=\"${avg.toFixed(2)}\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>`;\n    })\n    .join(\"\");\n  return `<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 ${Math.round(w)} ${Math.round(h)}\" width=\"${Math.round(w)}\" height=\"${Math.round(h)}\">${paths}</svg>`;\n}\n\nexport function SignaturePad({\n  onChange,\n  label,\n  helperText,\n  placeholder = \"Sign here\",\n  allowTyping = true,\n  penColor,\n  exportColor = \"#0A0A0A\",\n  minWidth = 1.1,\n  maxWidth = 3.4,\n  height = 200,\n  size = \"md\",\n  theme = \"dark\",\n  width = 440,\n  disabled = false,\n  className,\n}: SignaturePadProps) {\n  const p = PALETTES[theme];\n  const s = SIZES[size];\n  const ink = penColor ?? p.text;\n  const uid = React.useId();\n  const wrapRef = React.useRef<HTMLDivElement>(null);\n  const canvasRef = React.useRef<HTMLCanvasElement>(null);\n  const strokesRef = React.useRef<Stroke[]>([]);\n  const drawing = React.useRef<{ last: { x: number; y: number; t: number }; w: number } | null>(null);\n  const [strokeCount, setStrokeCount] = React.useState(0);\n  const [mode, setMode] = React.useState<\"draw\" | \"type\">(\"draw\");\n  const [typed, setTyped] = React.useState(\"\");\n  const [hovered, setHovered] = React.useState(false);\n  const [box, setBox] = React.useState({ w: 0, h: height });\n\n  const redraw = React.useCallback(() => {\n    const canvas = canvasRef.current;\n    const ctx = canvas?.getContext(\"2d\");\n    if (!canvas || !ctx) return;\n    const dpr = window.devicePixelRatio || 1;\n    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n    ctx.clearRect(0, 0, canvas.width, canvas.height);\n    strokesRef.current.forEach((st) => drawStroke(ctx, st, ink));\n  }, [ink]);\n\n  // Keep the canvas sharp and the right size; strokes are stored in CSS pixels and redrawn.\n  React.useEffect(() => {\n    const el = wrapRef.current;\n    const canvas = canvasRef.current;\n    if (!el || !canvas) return;\n    const fit = () => {\n      const w = el.clientWidth;\n      const dpr = window.devicePixelRatio || 1;\n      canvas.width = Math.round(w * dpr);\n      canvas.height = Math.round(height * dpr);\n      canvas.style.width = `${w}px`;\n      canvas.style.height = `${height}px`;\n      setBox({ w, h: height });\n      redraw();\n    };\n    fit();\n    const ro = new ResizeObserver(fit);\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, [height, redraw]);\n\n  const exportTyped = (name: string): SignatureResult => {\n    const clean = name.trim();\n    if (!clean) return { isEmpty: true, dataUrl: null, svg: null, mode: \"type\", typedName: \"\" };\n    const fontSize = Math.min(64, (box.w * 1.6) / Math.max(clean.length, 6));\n    const off = document.createElement(\"canvas\");\n    off.width = Math.round(box.w * 2);\n    off.height = Math.round(box.h * 2);\n    const ctx = off.getContext(\"2d\");\n    if (ctx) {\n      ctx.scale(2, 2);\n      ctx.fillStyle = exportColor;\n      ctx.font = `${fontSize}px ${SCRIPT_FONT}`;\n      ctx.textBaseline = \"alphabetic\";\n      ctx.fillText(clean, 36, box.h * 0.66);\n    }\n    const escaped = clean.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\");\n    const svg = `<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 ${Math.round(box.w)} ${Math.round(box.h)}\" width=\"${Math.round(box.w)}\" height=\"${Math.round(box.h)}\"><text x=\"36\" y=\"${(box.h * 0.66).toFixed(1)}\" font-family='${SCRIPT_FONT.replace(/'/g, \"\")}' font-size=\"${fontSize.toFixed(1)}\" fill=\"${exportColor}\">${escaped}</text></svg>`;\n    return { isEmpty: false, dataUrl: off.toDataURL(\"image/png\"), svg, mode: \"type\", typedName: clean };\n  };\n\n  const exportDrawn = (): SignatureResult => {\n    const strokes = strokesRef.current;\n    if (strokes.length === 0) return { isEmpty: true, dataUrl: null, svg: null, mode: \"draw\", typedName: \"\" };\n    const off = document.createElement(\"canvas\");\n    off.width = Math.round(box.w * 2);\n    off.height = Math.round(box.h * 2);\n    const ctx = off.getContext(\"2d\");\n    if (ctx) {\n      ctx.scale(2, 2);\n      strokes.forEach((st) => drawStroke(ctx, st, exportColor));\n    }\n    return { isEmpty: false, dataUrl: off.toDataURL(\"image/png\"), svg: strokesToSvg(strokes, box.w, box.h, exportColor), mode: \"draw\", typedName: \"\" };\n  };\n\n  const notify = () => onChange?.(exportDrawn());\n\n  const point = (e: React.PointerEvent<HTMLCanvasElement>) => {\n    const r = e.currentTarget.getBoundingClientRect();\n    return { x: e.clientX - r.left, y: e.clientY - r.top, t: e.timeStamp };\n  };\n\n  // Faster movement draws a thinner line, like a real pen; pen pressure scales it when available.\n  const widthFor = (from: { x: number; y: number; t: number }, to: { x: number; y: number; t: number }, prevW: number, pressure: number, pointerType: string) => {\n    const dist = Math.hypot(to.x - from.x, to.y - from.y);\n    const velocity = dist / Math.max(1, to.t - from.t);\n    const target = Math.max(minWidth, maxWidth - velocity * (maxWidth - minWidth) * 0.9);\n    const withPressure = pointerType === \"pen\" && pressure > 0 ? target * (0.5 + pressure) : target;\n    return prevW * 0.65 + withPressure * 0.35;\n  };\n\n  const onPointerDown = (e: React.PointerEvent<HTMLCanvasElement>) => {\n    if (disabled || mode !== \"draw\" || (e.pointerType === \"mouse\" && e.button !== 0)) return;\n    e.currentTarget.setPointerCapture(e.pointerId);\n    const pt = point(e);\n    const w = (minWidth + maxWidth) / 2;\n    drawing.current = { last: pt, w };\n    strokesRef.current = [...strokesRef.current, [{ x: pt.x, y: pt.y, w }]];\n    setStrokeCount(strokesRef.current.length);\n    redraw();\n  };\n\n  const onPointerMove = (e: React.PointerEvent<HTMLCanvasElement>) => {\n    const d = drawing.current;\n    if (!d) return;\n    const events = typeof e.nativeEvent.getCoalescedEvents === \"function\" ? e.nativeEvent.getCoalescedEvents() : [e.nativeEvent];\n    const r = e.currentTarget.getBoundingClientRect();\n    const stroke = strokesRef.current[strokesRef.current.length - 1];\n    for (const ev of events.length ? events : [e.nativeEvent]) {\n      const pt = { x: ev.clientX - r.left, y: ev.clientY - r.top, t: ev.timeStamp };\n      if (Math.hypot(pt.x - d.last.x, pt.y - d.last.y) < 1.2) continue;\n      d.w = widthFor(d.last, pt, d.w, ev.pressure, ev.pointerType);\n      stroke.push({ x: pt.x, y: pt.y, w: d.w });\n      d.last = pt;\n    }\n    redraw();\n  };\n\n  const endStroke = () => {\n    if (!drawing.current) return;\n    drawing.current = null;\n    notify();\n  };\n\n  const clear = () => {\n    strokesRef.current = [];\n    setStrokeCount(0);\n    setTyped(\"\");\n    redraw();\n    onChange?.({ isEmpty: true, dataUrl: null, svg: null, mode, typedName: \"\" });\n  };\n\n  const undo = () => {\n    strokesRef.current = strokesRef.current.slice(0, -1);\n    setStrokeCount(strokesRef.current.length);\n    redraw();\n    notify();\n  };\n\n  const switchMode = (next: \"draw\" | \"type\") => {\n    if (next === mode) return;\n    setMode(next);\n    onChange?.(next === \"type\" ? exportTyped(typed) : exportDrawn());\n  };\n\n  const hasInk = mode === \"draw\" ? strokeCount > 0 : typed.trim().length > 0;\n  const typedSize = Math.min(56, (box.w * 1.5) / Math.max(typed.trim().length, 6));\n\n  return (\n    <div className={cn(\"relative inline-flex flex-col gap-2\", className)} style={{ width, maxWidth: \"100%\", fontFamily: \"Inter, sans-serif\", opacity: disabled ? 0.5 : 1 }}>\n      {(label || allowTyping) && (\n        <div className=\"flex items-center justify-between\" style={{ gap: 12 }}>\n          {label ? (\n            <span id={`${uid}-label`} className=\"font-semibold tracking-[-0.01em]\" style={{ color: p.text, fontSize: s.font }}>\n              {label}\n            </span>\n          ) : (\n            <span />\n          )}\n          {allowTyping && (\n            <div role=\"tablist\" aria-label=\"Signature method\" className=\"relative flex\" style={{ padding: 3, borderRadius: 10, background: p.track }}>\n              {([\"draw\", \"type\"] as const).map((m) => (\n                <button\n                  key={m}\n                  type=\"button\"\n                  role=\"tab\"\n                  aria-selected={mode === m}\n                  disabled={disabled}\n                  onClick={() => switchMode(m)}\n                  className=\"relative cursor-pointer border-none bg-transparent font-medium capitalize outline-none focus-visible:ring-2\"\n                  style={{ height: s.btn - 8, padding: \"0 12px\", borderRadius: 8, color: mode === m ? p.selText : p.muted, fontSize: s.font - 2, [\"--tw-ring-color\" as string]: p.focus }}\n                >\n                  {mode === m && <motion.span layoutId={`${uid}-mode`} className=\"absolute inset-0\" style={{ borderRadius: 8, background: p.sel }} transition={{ type: \"spring\", stiffness: 500, damping: 36 }} />}\n                  <span className=\"relative\">{m}</span>\n                </button>\n              ))}\n            </div>\n          )}\n        </div>\n      )}\n\n      <div\n        ref={wrapRef}\n        onMouseEnter={() => setHovered(true)}\n        onMouseLeave={() => setHovered(false)}\n        className=\"relative overflow-hidden\"\n        style={{ height, borderRadius: s.radius, background: p.bg, border: `1px solid ${hovered && mode === \"draw\" && !disabled ? p.borderHover : p.border}`, transition: \"border-color 0.18s ease\" }}\n      >\n        {/* Signing line with an ×, like paper forms. */}\n        <div aria-hidden=\"true\" className=\"pointer-events-none absolute flex items-end\" style={{ left: 22, right: 22, bottom: height * 0.26, gap: 10 }}>\n          <span style={{ color: p.faint, fontSize: s.font + 2, lineHeight: 1 }}>×</span>\n          <span className=\"flex-1\" style={{ height: 1, background: p.line }} />\n        </div>\n\n        <AnimatePresence>\n          {!hasInk && (\n            <motion.span\n              aria-hidden=\"true\"\n              className=\"pointer-events-none absolute inset-x-0 text-center\"\n              style={{ top: height * 0.38, color: p.faint, fontSize: s.font }}\n              initial={{ opacity: 0 }}\n              animate={{ opacity: 1 }}\n              exit={{ opacity: 0, transition: { duration: 0.15 } }}\n            >\n              {mode === \"draw\" ? placeholder : \"Your name appears here\"}\n            </motion.span>\n          )}\n        </AnimatePresence>\n\n        <canvas\n          ref={canvasRef}\n          role=\"img\"\n          aria-label={hasInk && mode === \"draw\" ? \"Signature drawn\" : \"Signature area, draw with a mouse, finger or pen\"}\n          aria-labelledby={label ? `${uid}-label` : undefined}\n          onPointerDown={onPointerDown}\n          onPointerMove={onPointerMove}\n          onPointerUp={endStroke}\n          onPointerCancel={endStroke}\n          className=\"absolute inset-0\"\n          style={{ touchAction: \"none\", cursor: disabled ? \"default\" : \"crosshair\", visibility: mode === \"draw\" ? \"visible\" : \"hidden\" }}\n        />\n\n        {mode === \"type\" && (\n          <div aria-hidden=\"true\" className=\"pointer-events-none absolute flex items-end overflow-hidden\" style={{ left: 36, right: 22, bottom: height * 0.26 + 6, height: height * 0.6 }}>\n            <AnimatePresence mode=\"popLayout\">\n              <motion.span key={typed.trim() === \"\" ? \"empty\" : \"name\"} initial={{ opacity: 0, y: 6 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0 }} transition={{ duration: 0.2 }} className=\"whitespace-nowrap\" style={{ color: ink, fontFamily: SCRIPT_FONT, fontSize: typedSize, lineHeight: 1.1 }}>\n                {typed.trim()}\n              </motion.span>\n            </AnimatePresence>\n          </div>\n        )}\n\n        <div className=\"absolute flex items-center\" style={{ top: 8, right: 8, gap: 4 }}>\n          {mode === \"draw\" && (\n            <button\n              type=\"button\"\n              aria-label=\"Undo last stroke\"\n              disabled={disabled || strokeCount === 0}\n              onClick={undo}\n              className=\"flex cursor-pointer items-center justify-center border-none bg-transparent outline-none focus-visible:ring-2 disabled:cursor-default disabled:opacity-30\"\n              style={{ width: s.btn - 4, height: s.btn - 4, borderRadius: 8, color: p.muted, [\"--tw-ring-color\" as string]: p.focus }}\n              onMouseEnter={(e) => (e.currentTarget.style.background = p.hover)}\n              onMouseLeave={(e) => (e.currentTarget.style.background = \"transparent\")}\n            >\n              <svg width=\"15\" height=\"15\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.6\" strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">\n                <path d=\"M4.5 6.5h5.25a3.25 3.25 0 0 1 0 6.5H7M6.75 3.75 4 6.5l2.75 2.75\" />\n              </svg>\n            </button>\n          )}\n          <button\n            type=\"button\"\n            disabled={disabled || !hasInk}\n            onClick={clear}\n            className=\"cursor-pointer border-none bg-transparent font-medium outline-none focus-visible:ring-2 disabled:cursor-default disabled:opacity-30\"\n            style={{ height: s.btn - 4, padding: \"0 10px\", borderRadius: 8, color: p.muted, fontSize: s.font - 2, [\"--tw-ring-color\" as string]: p.focus }}\n            onMouseEnter={(e) => (e.currentTarget.style.background = p.hover)}\n            onMouseLeave={(e) => (e.currentTarget.style.background = \"transparent\")}\n          >\n            Clear\n          </button>\n        </div>\n      </div>\n\n      {mode === \"type\" && (\n        <input\n          type=\"text\"\n          aria-label=\"Type your full name\"\n          autoComplete=\"name\"\n          disabled={disabled}\n          value={typed}\n          placeholder=\"Type your full name\"\n          onChange={(e) => {\n            setTyped(e.target.value);\n            onChange?.(exportTyped(e.target.value));\n          }}\n          className=\"w-full border-none outline-none placeholder:text-[color:var(--sp-placeholder)] focus-visible:ring-2\"\n          style={{ height: s.btn + 8, padding: \"0 14px\", borderRadius: s.radius, background: p.bg, border: `1px solid ${p.border}`, color: p.text, fontSize: s.font, [\"--sp-placeholder\" as string]: p.faint, [\"--tw-ring-color\" as string]: p.focus }}\n        />\n      )}\n\n      {helperText && <span style={{ color: p.muted, fontSize: s.font - 1.5, lineHeight: 1.4 }}>{helperText}</span>}\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}