{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "code-block",
  "type": "registry:ui",
  "title": "CodeBlock",
  "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/CodeBlock.tsx",
      "type": "registry:ui",
      "target": "components/kashi/CodeBlock.tsx",
      "content": "\"use client\";\n\nimport { useEffect, useRef, useState, type ReactNode } from \"react\";\nimport { cx } from \"./cx\";\nimport { useKashiLocale, useMessages } from \"./KashiProvider\";\nimport { faCodeBlock } from \"@kashi-ui/persian\";\n\nexport interface CodeBlockProps {\n  code: string;\n  /** نام زبان؛ برچسب بالای کد و رنگ‌آمیزی ساده */\n  language?: string;\n  /** نام فایل به‌جای نام زبان */\n  filename?: string;\n  /** شمارهٔ خط‌ها @default false */\n  lineNumbers?: boolean;\n  /** خط‌هایی که برجسته می‌شوند (از ۱) */\n  highlightLines?: number[];\n  /** شکستن خط‌های بلند به‌جای اسکرول افقی؛ کاربر هم می‌تواند عوضش کند @default false */\n  wrap?: boolean;\n  /** رنگ‌آمیزی کلمه‌های کلیدی، رشته‌ها، عددها و توضیح‌ها @default true */\n  highlight?: boolean;\n  /** بیشترین ارتفاع پیش از اسکرول، مثل \"20rem\" */\n  maxHeight?: string;\n  className?: string;\n}\n\nconst KEYWORDS = new Set(\n  (\"import export from default const let var function return if else for while do switch case break continue new class extends \" +\n    \"async await try catch finally throw typeof instanceof in of interface type enum implements public private protected static readonly \" +\n    \"def lambda pass elif with as yield None True False self print fn pub use mod impl struct match mut package func go defer select \" +\n    \"true false null undefined void this super echo SELECT FROM WHERE INSERT INTO VALUES UPDATE SET DELETE JOIN ON AND OR NOT ORDER BY GROUP LIMIT\").split(\" \"),\n);\nconst TOKEN = /(\\/\\/[^\\n]*|#(?![{\\[])[^\\n]*|\\/\\*[\\s\\S]*?\\*\\/|<!--[\\s\\S]*?-->)|(\"(?:\\\\.|[^\"\\\\\\n])*\"|'(?:\\\\.|[^'\\\\\\n])*'|`(?:\\\\.|[^`\\\\])*`)|(\\b\\d[\\d_.]*(?:e[+-]?\\d+)?\\b)|([A-Za-z_$][\\w$]*)/g;\n\n/** رنگ‌آمیزی سبک و بی‌وابستگی؛ برای کد کامل‌تر خروجی Shiki یا Prism را به children بدهید */\nexport function highlightCode(code: string, language = \"\"): ReactNode[] {\n  const out: ReactNode[] = [];\n  const hashComments = /^(py|python|sh|bash|shell|zsh|yaml|yml|toml|rb|ruby|r)$/i.test(language);\n  let last = 0;\n  let k = 0;\n  for (const m of code.matchAll(TOKEN)) {\n    const [t, comment, str, num, word] = m;\n    const i = m.index ?? 0;\n    if (comment && comment.startsWith(\"#\") && !hashComments) continue;\n    if (i > last) out.push(code.slice(last, i));\n    const cls = comment ? \"comment\" : str ? \"string\" : num ? \"number\" : word && KEYWORDS.has(word) ? \"keyword\" : word && code[i + t.length] === \"(\" ? \"fn\" : \"\";\n    out.push(cls ? <span key={k++} className={`k-code__t-${cls}`}>{t}</span> : t);\n    last = i + t.length;\n  }\n  if (last < code.length) out.push(code.slice(last));\n  return out;\n}\n\nconst Copy = () => (\n  <svg viewBox=\"0 0 20 20\" fill=\"none\" stroke=\"currentColor\" strokeWidth={1.7} strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><rect x=\"7\" y=\"7\" width=\"10\" height=\"10\" rx=\"2\" /><path d=\"M13 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2\" /></svg>\n);\nconst Check = () => <svg viewBox=\"0 0 20 20\" fill=\"none\" stroke=\"currentColor\" strokeWidth={2} strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><path d=\"m5 10.5 3.2 3L15 7\" /></svg>;\nconst Wrap = () => (\n  <svg viewBox=\"0 0 20 20\" fill=\"none\" stroke=\"currentColor\" strokeWidth={1.7} strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\"><path d=\"M3 5h14M3 10h11a3 3 0 0 1 0 6h-3m0 0 2-2m-2 2 2 2M3 15h4\" /></svg>\n);\n\n/** نمایش کد در پاسخ دستیار یا مستندات: همیشه چپ‌به‌راست، با برچسب زبان، دکمهٔ کپی و شکستن خط */\nexport function CodeBlock({ code, language, filename, lineNumbers, highlightLines = [], wrap: wrapDefault = false, highlight = true, maxHeight, className }: CodeBlockProps) {\n  const M = useMessages({ codeBlock: faCodeBlock });\n  const { n } = useKashiLocale();\n  const B = M.codeBlock;\n  const [copied, setCopied] = useState(false);\n  const [wrap, setWrap] = useState(wrapDefault);\n  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n  useEffect(() => () => clearTimeout(timer.current), []);\n  const text = code.replace(/\\n$/, \"\");\n  const lines = text.split(\"\\n\");\n  const title = filename ?? language;\n  const mark = new Set(highlightLines);\n  const body = highlight ? highlightCode(text, language) : [text];\n\n  // خط‌ها جدا رندر می‌شوند تا شماره و برجسته‌سازی ممکن باشد؛ رنگ‌آمیزی روی کل متن است و بعد به خط‌ها تقسیم می‌شود\n  const perLine: ReactNode[][] = [[]];\n  for (const part of body) {\n    if (typeof part !== \"string\") {\n      const s = String((part as { props: { children: string } }).props.children);\n      if (!s.includes(\"\\n\")) {\n        perLine[perLine.length - 1].push(part);\n        continue;\n      }\n      const cls = (part as { props: { className: string } }).props.className;\n      s.split(\"\\n\").forEach((seg, j) => {\n        if (j) perLine.push([]);\n        if (seg) perLine[perLine.length - 1].push(<span key={`${perLine.length}-${j}`} className={cls}>{seg}</span>);\n      });\n      continue;\n    }\n    part.split(\"\\n\").forEach((seg, j) => {\n      if (j) perLine.push([]);\n      if (seg) perLine[perLine.length - 1].push(seg);\n    });\n  }\n\n  return (\n    <figure className={cx(\"k-code\", className)} data-wrap={wrap ? \"\" : undefined}>\n      <figcaption className=\"k-code__head\">\n        <span className=\"k-code__lang\" dir=\"ltr\">{title ?? B.lines(n(lines.length))}</span>\n        <span className=\"k-code__tools\">\n          <button type=\"button\" className=\"k-code__btn\" aria-label={B.wrap} aria-pressed={wrap} onClick={() => setWrap((w) => !w)}><Wrap /></button>\n          <button\n            type=\"button\"\n            className=\"k-code__btn\"\n            data-done={copied ? \"\" : undefined}\n            onClick={async () => {\n              try {\n                await navigator.clipboard.writeText(text);\n                setCopied(true);\n                clearTimeout(timer.current);\n                timer.current = setTimeout(() => setCopied(false), 2000);\n              } catch {\n                /* کلیپ‌بورد در دسترس نیست */\n              }\n            }}\n          >\n            {copied ? <Check /> : <Copy />}\n            <span>{copied ? B.copied : B.copy}</span>\n          </button>\n          <span className=\"k-sr-only\" aria-live=\"polite\">{copied ? B.copied : \"\"}</span>\n        </span>\n      </figcaption>\n      <pre className=\"k-code__pre\" dir=\"ltr\" tabIndex={0} aria-label={language ? B.code(language) : undefined} style={maxHeight ? { maxBlockSize: maxHeight } : undefined}>\n        <code>\n          {perLine.map((parts, i) => (\n            <span key={i} className=\"k-code__line\" data-marked={mark.has(i + 1) ? \"\" : undefined}>\n              {lineNumbers && <span className=\"k-code__num\" aria-hidden=\"true\">{i + 1}</span>}\n              <span className=\"k-code__text\">{parts.length ? parts : \" \"}</span>\n            </span>\n          ))}\n        </code>\n      </pre>\n    </figure>\n  );\n}\n"
    }
  ]
}