{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "image-cropper",
  "type": "registry:ui",
  "title": "ImageCropper",
  "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/ImageCropper.tsx",
      "type": "registry:ui",
      "target": "components/kashi/ImageCropper.tsx",
      "content": "\"use client\";\n\nimport { forwardRef, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState, type ReactNode } from \"react\";\nimport { cx } from \"./cx\";\nimport { useKashiLocale, useMessages } from \"./KashiProvider\";\nimport { faCommon, faCropper } from \"@kashi-ui/persian\";\n\n/** ناحیهٔ برش به پیکسل تصویر اصلی (بعد از چرخش) */\nexport interface CropArea {\n  x: number;\n  y: number;\n  width: number;\n  height: number;\n}\n\nexport interface CropState {\n  /** جابه‌جایی مرکز تصویر از مرکز کادر، به نسبت اندازهٔ کادر */\n  x: number;\n  y: number;\n  /** ۱ = تصویر کادر را تازه پر کرده است */\n  zoom: number;\n  /** ۰، ۹۰، ۱۸۰ یا ۲۷۰ */\n  rotation: number;\n}\n\nexport interface ImageCropperHandle {\n  /** تصویر بریده‌شده به Blob (پیش‌فرض WebP، اگر مرورگر بخواهد PNG) */\n  crop: (options?: CropImageOptions) => Promise<Blob | null>;\n  reset: () => void;\n}\n\nexport interface CropImageOptions {\n  /** پهنای خروجی به پیکسل؛ پیش‌فرض اندازهٔ واقعی ناحیه */\n  width?: number;\n  type?: string;\n  quality?: number;\n  /** برش دایره‌ای (گوشه‌ها شفاف) */\n  circle?: boolean;\n}\n\nexport interface ImageCropperProps {\n  src: string;\n  alt?: string;\n  /** نسبت پهنا به ارتفاع کادر @default 1 */\n  aspect?: number;\n  /** کادر دایره‌ای برای عکس پروفایل */\n  shape?: \"rect\" | \"circle\";\n  /** بیشترین بزرگ‌نمایی @default 4 */\n  maxZoom?: number;\n  value?: CropState;\n  defaultValue?: Partial<CropState>;\n  onChange?: (state: CropState) => void;\n  /** بعد از هر تغییر، ناحیهٔ برش به پیکسل تصویر */\n  onCropComplete?: (area: CropArea, state: CropState) => void;\n  /** دکمهٔ چرخش @default true */\n  rotatable?: boolean;\n  label?: ReactNode;\n  className?: string;\n}\n\nconst START: CropState = { x: 0, y: 0, zoom: 1, rotation: 0 };\nconst clampN = (v: number, a: number, b: number) => Math.min(b, Math.max(a, v));\n\n/** تصویر را با ناحیه و چرخش داده‌شده می‌بُرد؛ برای سرور هم قابل استفاده است (در مرورگر) */\nexport async function cropImage(src: string, area: CropArea, rotation = 0, { width, type = \"image/webp\", quality = 0.92, circle }: CropImageOptions = {}): Promise<Blob | null> {\n  const img = new Image();\n  img.crossOrigin = \"anonymous\";\n  img.src = src;\n  await img.decode();\n  const rad = (rotation * Math.PI) / 180;\n  const side = rotation % 180 !== 0;\n  const rw = side ? img.naturalHeight : img.naturalWidth;\n  const rh = side ? img.naturalWidth : img.naturalHeight;\n  const outW = Math.round(width ?? area.width);\n  const outH = Math.round((outW * area.height) / area.width);\n  const c = document.createElement(\"canvas\");\n  c.width = outW;\n  c.height = outH;\n  const ctx = c.getContext(\"2d\");\n  if (!ctx) return null;\n  const k = outW / area.width;\n  if (circle) {\n    ctx.beginPath();\n    ctx.ellipse(outW / 2, outH / 2, outW / 2, outH / 2, 0, 0, Math.PI * 2);\n    ctx.clip();\n  }\n  ctx.scale(k, k);\n  ctx.translate(-area.x + rw / 2, -area.y + rh / 2);\n  ctx.rotate(rad);\n  ctx.drawImage(img, -img.naturalWidth / 2, -img.naturalHeight / 2);\n  return new Promise((done) => c.toBlob((b) => done(b), type, quality));\n}\n\n/**\n * برش تصویر برای عکس پروفایل و کاور: تصویر زیر کادر ثابت جابه‌جا و بزرگ می‌شود (کشیدن، چرخ ماوس، دو انگشت یا کیبورد)\n * و همیشه کادر را پر نگه می‌دارد. خروجی با ref.crop() یا تابع cropImage.\n */\nexport const ImageCropper = forwardRef<ImageCropperHandle, ImageCropperProps>(function ImageCropper(\n  { src, alt = \"\", aspect = 1, shape = \"rect\", maxZoom = 4, value, defaultValue, onChange, onCropComplete, rotatable = true, label, className },\n  ref,\n) {\n  const M = useMessages({ common: faCommon, cropper: faCropper });\n  const { n } = useKashiLocale();\n  const C = M.cropper;\n  const stage = useRef<HTMLDivElement>(null);\n  const imgRef = useRef<HTMLImageElement>(null);\n  const [inner, setInner] = useState<CropState>({ ...START, ...defaultValue });\n  const state = value ?? inner;\n  // آخرین حالت، تا کلیدها و رویدادهای پشت‌سرهم (پیش از رندر بعدی) روی حالت کهنه حساب نشوند\n  const latest = useRef(state);\n  latest.current = state;\n  const [nat, setNat] = useState<{ w: number; h: number } | null>(null);\n  const [box, setBox] = useState({ w: 0, h: 0 });\n  const [live, setLive] = useState(\"\");\n  const drag = useRef<{ id: number; x: number; y: number; start: CropState } | null>(null);\n  const pinch = useRef<{ d: number; zoom: number } | null>(null);\n  const pointers = useRef(new Map<number, { x: number; y: number }>());\n\n  const useIso = typeof window === \"undefined\" ? useEffect : useLayoutEffect;\n  useIso(() => {\n    const el = stage.current;\n    if (!el) return;\n    const read = () => setBox({ w: el.clientWidth, h: el.clientHeight });\n    read();\n    if (typeof ResizeObserver === \"undefined\") return;\n    const ro = new ResizeObserver(read);\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, []);\n\n  // تصویری که پیش از hydrate شدن (یا از حافظهٔ مرورگر) بارگذاری شده، رویداد load را دوباره نمی‌فرستد\n  useEffect(() => {\n    const img = imgRef.current;\n    if (img?.complete && img.naturalWidth) setNat({ w: img.naturalWidth, h: img.naturalHeight });\n  }, [src]);\n\n  // کادر: بزرگ‌ترین مستطیل با نسبت aspect با ۱۶px فاصله از لبه‌ها\n  const pad = 16;\n  const fw = Math.max(1, Math.min(box.w - pad * 2, (box.h - pad * 2) * aspect));\n  const fh = fw / aspect;\n  const side = state.rotation % 180 !== 0;\n  const iw = nat ? (side ? nat.h : nat.w) : 1;\n  const ih = nat ? (side ? nat.w : nat.h) : 1;\n  const base = Math.max(fw / iw, fh / ih);\n  const scale = base * state.zoom;\n\n  const clampState = useCallback((s: CropState): CropState => {\n    const zoom = clampN(s.zoom, 1, maxZoom);\n    const sc = base * zoom;\n    const mx = Math.max(0, (iw * sc - fw) / 2) / fw;\n    const my = Math.max(0, (ih * sc - fh) / 2) / fh;\n    return { ...s, zoom, x: clampN(s.x, -mx, mx), y: clampN(s.y, -my, my) };\n  }, [base, iw, ih, fw, fh, maxZoom]);\n\n  const area = useCallback((s: CropState): CropArea => {\n    const sc = base * s.zoom;\n    return {\n      x: Math.max(0, (iw * sc) / 2 - s.x * fw - fw / 2) / sc,\n      y: Math.max(0, (ih * sc) / 2 - s.y * fh - fh / 2) / sc,\n      width: fw / sc,\n      height: fh / sc,\n    };\n  }, [base, iw, ih, fw, fh]);\n\n  const set = useCallback((next: CropState, announce?: string) => {\n    const s = clampState(next);\n    latest.current = s;\n    if (value === undefined) setInner(s);\n    onChange?.(s);\n    if (nat) onCropComplete?.(area(s), s);\n    if (announce) setLive(announce);\n  }, [clampState, value, onChange, onCropComplete, area, nat]);\n\n  // وقتی اندازه یا تصویر عوض شد، حالت را دوباره در محدوده بیاور\n  useEffect(() => {\n    if (nat && box.w) set(state);\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [nat, box.w, box.h, aspect]);\n\n  useImperativeHandle(ref, () => ({\n    crop: (o) => cropImage(src, area(state), state.rotation, { circle: shape === \"circle\", ...o }),\n    reset: () => set(START),\n  }));\n\n  const zoomBy = (f: number) => { const z = latest.current.zoom * f; set({ ...latest.current, zoom: z }, C.zoomed(n(Math.round(clampN(z, 1, maxZoom) * 100)))); };\n\n  const tx = box.w / 2 + state.x * fw - (iw * scale) / 2;\n  const ty = box.h / 2 + state.y * fh - (ih * scale) / 2;\n\n  return (\n    <div className={cx(\"k-cropper\", className)} data-shape={shape}>\n      {label && <span className=\"k-label\">{label}</span>}\n      <div\n        ref={stage}\n        className=\"k-cropper__stage\"\n        dir=\"ltr\"\n        tabIndex={0}\n        role=\"application\"\n        aria-roledescription={C.label}\n        aria-label={C.area}\n        onPointerDown={(e) => {\n          e.currentTarget.setPointerCapture(e.pointerId);\n          pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });\n          if (pointers.current.size === 2) {\n            const [a, b] = [...pointers.current.values()];\n            pinch.current = { d: Math.hypot(a.x - b.x, a.y - b.y), zoom: latest.current.zoom };\n            drag.current = null;\n          } else drag.current = { id: e.pointerId, x: e.clientX, y: e.clientY, start: latest.current };\n        }}\n        onPointerMove={(e) => {\n          if (!pointers.current.has(e.pointerId)) return;\n          pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });\n          if (pinch.current && pointers.current.size === 2) {\n            const [a, b] = [...pointers.current.values()];\n            set({ ...latest.current, zoom: (pinch.current.zoom * Math.hypot(a.x - b.x, a.y - b.y)) / pinch.current.d });\n          } else if (drag.current?.id === e.pointerId) {\n            const d = drag.current;\n            set({ ...d.start, x: d.start.x + (e.clientX - d.x) / fw, y: d.start.y + (e.clientY - d.y) / fh });\n          }\n        }}\n        onPointerUp={(e) => {\n          pointers.current.delete(e.pointerId);\n          if (pointers.current.size < 2) pinch.current = null;\n          if (drag.current?.id === e.pointerId) drag.current = null;\n        }}\n        onPointerCancel={(e) => { pointers.current.delete(e.pointerId); drag.current = null; pinch.current = null; }}\n        onWheel={(e) => {\n          if (!e.ctrlKey && Math.abs(e.deltaY) < 1) return;\n          e.preventDefault();\n          set({ ...latest.current, zoom: latest.current.zoom * Math.exp(-e.deltaY / 400) });\n        }}\n        onKeyDown={(e) => {\n          const step = e.shiftKey ? 0.1 : 0.02;\n          const moves: Record<string, [number, number]> = { ArrowLeft: [step, 0], ArrowRight: [-step, 0], ArrowUp: [0, step], ArrowDown: [0, -step] };\n          if (moves[e.key]) {\n            e.preventDefault();\n            const [dx, dy] = moves[e.key];\n            const next = clampState({ ...latest.current, x: latest.current.x + dx, y: latest.current.y + dy });\n            set(next, C.moved(n(Math.round((0.5 - next.x) * 100)), n(Math.round((0.5 - next.y) * 100))));\n          } else if (e.key === \"+\" || e.key === \"=\") { e.preventDefault(); zoomBy(1.1); }\n          else if (e.key === \"-\" || e.key === \"_\") { e.preventDefault(); zoomBy(1 / 1.1); }\n          else if (e.key === \"0\") { e.preventDefault(); set(START, C.reset); }\n        }}\n      >\n        <img\n          ref={imgRef}\n          className=\"k-cropper__img\"\n          src={src}\n          alt={alt}\n          draggable={false}\n          onLoad={(e) => setNat({ w: e.currentTarget.naturalWidth, h: e.currentTarget.naturalHeight })}\n          style={nat ? {\n            inlineSize: (side ? ih : iw) * scale,\n            blockSize: (side ? iw : ih) * scale,\n            transform: `translate(${tx + (side ? (iw * scale - ih * scale) / 2 : 0)}px, ${ty + (side ? (ih * scale - iw * scale) / 2 : 0)}px) rotate(${state.rotation}deg)`,\n          } : { opacity: 0 }}\n        />\n        <div className=\"k-cropper__frame\" aria-hidden=\"true\" style={{ inlineSize: fw, blockSize: fh }}>\n          <span className=\"k-cropper__grid\" />\n        </div>\n      </div>\n      <div className=\"k-cropper__controls\">\n        <button type=\"button\" className=\"k-cropper__btn\" onClick={() => zoomBy(1 / 1.2)} aria-label={`${C.zoom} −`} disabled={state.zoom <= 1}>\n          <svg viewBox=\"0 0 20 20\" aria-hidden=\"true\"><path d=\"M5 10h10\" stroke=\"currentColor\" strokeWidth=\"1.6\" strokeLinecap=\"round\" /></svg>\n        </button>\n        <input\n          type=\"range\"\n          className=\"k-slider k-cropper__zoom\"\n          min={1}\n          max={maxZoom}\n          step={0.01}\n          value={state.zoom}\n          aria-label={C.zoom}\n          aria-valuetext={M.common.percent(n(Math.round(state.zoom * 100)))}\n          onChange={(e) => set({ ...latest.current, zoom: Number(e.target.value) })}\n        />\n        <button type=\"button\" className=\"k-cropper__btn\" onClick={() => zoomBy(1.2)} aria-label={`${C.zoom} +`} disabled={state.zoom >= maxZoom}>\n          <svg viewBox=\"0 0 20 20\" aria-hidden=\"true\"><path d=\"M5 10h10M10 5v10\" stroke=\"currentColor\" strokeWidth=\"1.6\" strokeLinecap=\"round\" /></svg>\n        </button>\n        {rotatable && (\n          <button type=\"button\" className=\"k-cropper__btn\" onClick={() => set({ ...latest.current, rotation: (latest.current.rotation + 90) % 360, x: 0, y: 0 })} aria-label={C.rotate} title={C.rotate}>\n            <svg viewBox=\"0 0 20 20\" aria-hidden=\"true\"><path d=\"M15.5 9A5.5 5.5 0 1 0 14 13.3M15.5 4.5V9H11\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.6\" strokeLinecap=\"round\" strokeLinejoin=\"round\" /></svg>\n          </button>\n        )}\n      </div>\n      <span className=\"k-sr-only\" aria-live=\"polite\">{live}</span>\n    </div>\n  );\n});\n"
    }
  ]
}