{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "signature-pad",
  "type": "registry:ui",
  "title": "SignaturePad",
  "description": "امضا",
  "dependencies": [
    "@kashi-ui/persian@^2.26.0"
  ],
  "registryDependencies": [
    "https://kashi.sepantapouya.com/r/cx.json",
    "https://kashi.sepantapouya.com/r/kashi-provider.json"
  ],
  "files": [
    {
      "path": "registry/kashi/SignaturePad.tsx",
      "type": "registry:ui",
      "target": "components/kashi/SignaturePad.tsx",
      "content": "\"use client\";\n\nimport { forwardRef, useCallback, useEffect, useId, useImperativeHandle, useRef, useState, type ReactNode } from \"react\";\nimport { cx } from \"./cx\";\nimport { useMessages } from \"./KashiProvider\";\nimport { faCommon, faSignature } from \"@kashi-ui/persian\";\n\n/** یک خط امضا: نقطه‌ها به نسبت کادر (۰ تا ۱) و فشار قلم، تا با تغییر اندازه دوباره کشیده شود */\nexport type SignatureStroke = Array<[x: number, y: number, pressure: number]>;\n\nexport interface SignaturePadHandle {\n  clear: () => void;\n  undo: () => void;\n  isEmpty: () => boolean;\n  /** تصویر PNG با پس‌زمینهٔ شفاف و جوهر exportColor؛ اگر امضا خالی باشد null */\n  toDataURL: (type?: string) => string | null;\n  strokes: () => SignatureStroke[];\n}\n\nexport interface SignaturePadProps {\n  label?: ReactNode;\n  hint?: ReactNode;\n  error?: ReactNode;\n  /** تصویر امضا (data URL) که بعد از هر خط ساخته می‌شود */\n  onChange?: (dataUrl: string | null) => void;\n  /** خط‌های اولیه (برای بازگرداندن امضای ذخیره‌شده) */\n  defaultStrokes?: SignatureStroke[];\n  /** نام فیلد فرم؛ data URL در ورودی پنهان می‌رود */\n  name?: string;\n  required?: boolean;\n  disabled?: boolean;\n  readOnly?: boolean;\n  /** امکان تایپ نام به‌جای رسم (برای کیبورد و صفحه‌خوان) @default true */\n  allowTyped?: boolean;\n  /** پهنای پایهٔ قلم به پیکسل CSS @default 2.5 */\n  penWidth?: number;\n  /** رنگ جوهر در تصویر خروجی، مستقل از تم @default \"#0b0c0f\" */\n  exportColor?: string;\n  id?: string;\n  className?: string;\n}\n\nconst dist = (a: number[], b: number[]) => Math.hypot(a[0] - b[0], a[1] - b[1]);\n\n/**\n * کادر امضا با ماوس، قلم و لمس: خط‌ها نرم (منحنی درجهٔ دو) و پهنایشان با فشار و سرعت قلم تغییر می‌کند.\n * برگرداندن آخرین خط، پاک کردن، و حالت «تایپ امضا» برای کسی که نمی‌تواند رسم کند.\n */\nexport const SignaturePad = forwardRef<SignaturePadHandle, SignaturePadProps>(function SignaturePad(\n  { label, hint, error, onChange, defaultStrokes = [], name, required, disabled, readOnly, allowTyped = true, penWidth = 2.5, exportColor = \"#0b0c0f\", id, className },\n  ref,\n) {\n  const M = useMessages({ common: faCommon, signature: faSignature });\n  const S = M.signature;\n  const autoId = useId();\n  const fieldId = id ?? autoId;\n  const canvas = useRef<HTMLCanvasElement>(null);\n  const strokes = useRef<SignatureStroke[]>(defaultStrokes);\n  const current = useRef<SignatureStroke | null>(null);\n  const [count, setCount] = useState(defaultStrokes.length);\n  const [mode, setMode] = useState<\"draw\" | \"type\">(\"draw\");\n  const [typed, setTyped] = useState(\"\");\n  const [data, setData] = useState<string | null>(null);\n  const [live, setLive] = useState(\"\");\n  const locked = disabled || readOnly;\n\n  const paint = useCallback((ctx: CanvasRenderingContext2D, w: number, h: number, list: SignatureStroke[], color: string, scale = 1) => {\n    ctx.clearRect(0, 0, w, h);\n    ctx.strokeStyle = color;\n    ctx.fillStyle = color;\n    ctx.lineCap = \"round\";\n    ctx.lineJoin = \"round\";\n    for (const s of list) {\n      if (s.length === 1) {\n        ctx.beginPath();\n        ctx.arc(s[0][0] * w, s[0][1] * h, (penWidth * scale * (0.6 + s[0][2])) / 2, 0, Math.PI * 2);\n        ctx.fill();\n        continue;\n      }\n      for (let i = 1; i < s.length; i++) {\n        const p0 = s[i - 1], p1 = s[i];\n        const m0 = i > 1 ? [(s[i - 2][0] + p0[0]) / 2, (s[i - 2][1] + p0[1]) / 2] : p0;\n        const m1 = [(p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2];\n        ctx.lineWidth = penWidth * scale * (0.6 + (p0[2] + p1[2]) / 2);\n        ctx.beginPath();\n        ctx.moveTo(m0[0] * w, m0[1] * h);\n        ctx.quadraticCurveTo(p0[0] * w, p0[1] * h, m1[0] * w, m1[1] * h);\n        if (i === s.length - 1) ctx.lineTo(p1[0] * w, p1[1] * h);\n        ctx.stroke();\n      }\n    }\n  }, [penWidth]);\n\n  const redraw = useCallback(() => {\n    const c = canvas.current;\n    if (!c) return;\n    const r = c.getBoundingClientRect();\n    const dpr = window.devicePixelRatio || 1;\n    if (c.width !== Math.round(r.width * dpr) || c.height !== Math.round(r.height * dpr)) {\n      c.width = Math.round(r.width * dpr);\n      c.height = Math.round(r.height * dpr);\n    }\n    const ctx = c.getContext(\"2d\");\n    if (!ctx) return;\n    ctx.setTransform(1, 0, 0, 1, 0, 0);\n    paint(ctx, c.width, c.height, current.current ? [...strokes.current, current.current] : strokes.current, getComputedStyle(c).color, dpr);\n  }, [paint]);\n\n  useEffect(() => {\n    redraw();\n    const c = canvas.current;\n    if (!c || typeof ResizeObserver === \"undefined\") return;\n    const ro = new ResizeObserver(() => redraw());\n    ro.observe(c);\n    // رنگ جوهر از تم می‌آید؛ با عوض شدن تم دوباره بکش\n    const mq = window.matchMedia?.(\"(prefers-color-scheme: dark)\");\n    mq?.addEventListener?.(\"change\", redraw);\n    return () => { ro.disconnect(); mq?.removeEventListener?.(\"change\", redraw); };\n  }, [redraw, mode]);\n\n  const exportImage = useCallback((type = \"image/png\"): string | null => {\n    const c = canvas.current;\n    if (typeof document === \"undefined\") return null;\n    const w = c?.width || 600, h = c?.height || 200;\n    const out = document.createElement(\"canvas\");\n    out.width = w;\n    out.height = h;\n    const ctx = out.getContext(\"2d\");\n    if (!ctx) return null;\n    if (mode === \"type\") {\n      if (!typed.trim()) return null;\n      ctx.fillStyle = exportColor;\n      ctx.textAlign = \"center\";\n      ctx.textBaseline = \"middle\";\n      const family = getComputedStyle(c ?? document.body).getPropertyValue(\"--k-font-display\") || \"sans-serif\";\n      ctx.font = `700 ${Math.round(h * 0.34)}px ${family}`;\n      ctx.direction = \"rtl\";\n      ctx.fillText(typed.trim(), w / 2, h / 2, w * 0.9);\n      return out.toDataURL(type);\n    }\n    if (!strokes.current.length) return null;\n    paint(ctx, w, h, strokes.current, exportColor, w / (c?.getBoundingClientRect().width || w));\n    return out.toDataURL(type);\n  }, [mode, typed, exportColor, paint]);\n\n  const commit = useCallback((announce?: string) => {\n    const url = exportImage();\n    setData(url);\n    setCount(strokes.current.length);\n    onChange?.(url);\n    if (announce) setLive(announce);\n  }, [exportImage, onChange]);\n\n  useEffect(() => {\n    if (mode === \"type\") commit();\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [typed, mode]);\n\n  const clear = () => { strokes.current = []; current.current = null; setTyped(\"\"); redraw(); commit(S.cleared); };\n  const undo = () => { strokes.current = strokes.current.slice(0, -1); redraw(); commit(); };\n\n  useImperativeHandle(ref, () => ({\n    clear, undo,\n    isEmpty: () => (mode === \"type\" ? !typed.trim() : strokes.current.length === 0),\n    toDataURL: exportImage,\n    strokes: () => strokes.current,\n  }));\n\n  const point = (e: React.PointerEvent<HTMLCanvasElement>): [number, number, number] => {\n    const r = e.currentTarget.getBoundingClientRect();\n    const pressure = e.pointerType === \"pen\" && e.pressure > 0 ? e.pressure : 0.5;\n    return [(e.clientX - r.left) / r.width, (e.clientY - r.top) / r.height, pressure];\n  };\n\n  const empty = mode === \"type\" ? !typed.trim() : count === 0;\n  const hintId = `${fieldId}-hint`;\n  const errId = `${fieldId}-err`;\n\n  return (\n    <div className={cx(\"k-field k-signature\", className)} data-disabled={disabled || undefined} data-empty={empty || undefined} data-invalid={error ? \"\" : undefined}>\n      {label && <span className=\"k-label\" id={`${fieldId}-label`}>{label}{required && <span className=\"k-label__required\" aria-hidden=\"true\">*</span>}</span>}\n      {allowTyped && !locked && (\n        <div className=\"k-signature__modes\" role=\"radiogroup\" aria-label={typeof label === \"string\" ? label : S.label}>\n          {([\"draw\", \"type\"] as const).map((m) => (\n            <button key={m} type=\"button\" role=\"radio\" aria-checked={mode === m} className=\"k-signature__mode\" onClick={() => setMode(m)}>\n              {S[m]}\n            </button>\n          ))}\n        </div>\n      )}\n      <div className=\"k-signature__pad\">\n        {mode === \"draw\" ? (\n          <canvas\n            ref={canvas}\n            className=\"k-signature__canvas\"\n            role=\"img\"\n            aria-label={`${S.area}${empty ? `${M.common.comma}${S.empty}` : \"\"}`}\n            aria-describedby={[hint || !locked ? hintId : \"\", error ? errId : \"\"].filter(Boolean).join(\" \") || undefined}\n            onPointerDown={(e) => {\n              if (locked || (e.pointerType === \"mouse\" && e.button !== 0)) return;\n              e.currentTarget.setPointerCapture(e.pointerId);\n              current.current = [point(e)];\n              redraw();\n            }}\n            onPointerMove={(e) => {\n              const s = current.current;\n              if (!s) return;\n              const coalesced = e.nativeEvent.getCoalescedEvents?.();\n              const events = coalesced && coalesced.length ? coalesced : [e.nativeEvent];\n              const r = e.currentTarget.getBoundingClientRect();\n              for (const ev of events) {\n                const p: [number, number, number] = [(ev.clientX - r.left) / r.width, (ev.clientY - r.top) / r.height, ev.pointerType === \"pen\" && ev.pressure > 0 ? ev.pressure : 0.5];\n                const last = s[s.length - 1];\n                const d = dist(last, p) * r.width;\n                if (d < 1.2) continue;\n                // قلم بی‌فشار: هرچه تندتر، نازک‌تر (مثل جوهر واقعی)\n                if (ev.pointerType !== \"pen\") p[2] = Math.max(0.15, Math.min(0.75, 0.75 - d / 60));\n                s.push(p);\n              }\n              redraw();\n            }}\n            onPointerUp={() => {\n              if (!current.current) return;\n              strokes.current = [...strokes.current, current.current];\n              current.current = null;\n              commit(strokes.current.length === 1 ? S.signed : undefined);\n            }}\n            onPointerCancel={() => { current.current = null; redraw(); }}\n          />\n        ) : (\n          <label className=\"k-signature__typed\">\n            <span className=\"k-sr-only\">{S.typedLabel}</span>\n            <input className=\"k-signature__typed-input\" value={typed} onChange={(e) => setTyped(e.target.value)} placeholder={S.typedLabel} disabled={disabled} readOnly={readOnly} autoComplete=\"name\" />\n          </label>\n        )}\n        <span className=\"k-signature__line\" aria-hidden=\"true\">×</span>\n        {!locked && (\n          <div className=\"k-signature__tools\">\n            {mode === \"draw\" && (\n              <button type=\"button\" className=\"k-signature__tool\" onClick={undo} disabled={count === 0} aria-label={S.undo} title={S.undo}>\n                <svg viewBox=\"0 0 20 20\" aria-hidden=\"true\"><path d=\"M7.5 5 4 8.5 7.5 12M4.5 8.5h7a4 4 0 0 1 0 8H9\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.6\" strokeLinecap=\"round\" strokeLinejoin=\"round\" /></svg>\n              </button>\n            )}\n            <button type=\"button\" className=\"k-signature__tool\" onClick={clear} disabled={empty}>{S.clear}</button>\n          </div>\n        )}\n      </div>\n      {(hint || !locked) && !error && <span className=\"k-hint\" id={hintId}>{hint ?? (mode === \"draw\" ? S.hint : null)}</span>}\n      {error && <span className=\"k-hint k-hint--error\" id={errId} role=\"alert\">{error}</span>}\n      {name && <input type=\"hidden\" name={name} value={data ?? \"\"} required={required} />}\n      <span className=\"k-sr-only\" aria-live=\"polite\">{live}</span>\n    </div>\n  );\n});\n"
    }
  ]
}