{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "rich-text-editor",
  "type": "registry:ui",
  "title": "RichTextEditor",
  "description": "ویرایشگر متن غنی سبک و فارسی: جهت هر بند جدا، نیم‌فاصله با Shift+Space، چسباندن پاک‌شده و نوار ابزار با کیبورد",
  "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/RichTextEditor.tsx",
      "type": "registry:ui",
      "target": "components/kashi/RichTextEditor.tsx",
      "content": "\"use client\";\n\nimport { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from \"react\";\nimport { cx } from \"./cx\";\nimport { useKashiLocale, useMessages } from \"./KashiProvider\";\nimport { faRichText } from \"@kashi-ui/persian\";\n\nexport type RichTextTool =\n  | \"bold\" | \"italic\" | \"underline\" | \"strike\" | \"heading\" | \"quote\" | \"bullet\" | \"ordered\" | \"link\" | \"direction\" | \"undo\" | \"clear\" | \"|\";\n\nexport interface RichTextEditorProps {\n  /** HTML کنترل‌شده؛ پیش از نمایش پاک‌سازی می‌شود */\n  value?: string;\n  defaultValue?: string;\n  /** با هر تغییر: HTML پاک‌شده و متن ساده */\n  onChange?: (html: string, text: string) => void;\n  /** @default \"ویرایشگر متن\" */\n  label?: string;\n  /** نام دسترس‌پذیر وقتی برچسب دیداری ندارد */\n  \"aria-label\"?: string;\n  placeholder?: string;\n  /** ابزارهای نوار و ترتیبشان؛ \"|\" جداکننده است */\n  tools?: RichTextTool[];\n  /** کمترین ارتفاع ناحیهٔ نوشتن @default \"8rem\" */\n  minHeight?: string;\n  /** شمارش کلمه و نویسه پایین ویرایشگر @default true */\n  showCount?: boolean;\n  /** با name، HTML در فرم ارسال می‌شود */\n  name?: string;\n  hint?: ReactNode;\n  error?: ReactNode;\n  disabled?: boolean;\n  className?: string;\n}\n\nconst DEFAULT_TOOLS: RichTextTool[] = [\"bold\", \"italic\", \"underline\", \"strike\", \"|\", \"heading\", \"quote\", \"bullet\", \"ordered\", \"|\", \"link\", \"direction\", \"|\", \"undo\", \"clear\"];\nconst ALLOWED = new Set([\"P\", \"BR\", \"B\", \"STRONG\", \"I\", \"EM\", \"U\", \"S\", \"STRIKE\", \"DEL\", \"A\", \"UL\", \"OL\", \"LI\", \"H2\", \"H3\", \"BLOCKQUOTE\", \"DIV\", \"SPAN\", \"CODE\"]);\nconst BLOCKS = \"p, li, h2, h3, blockquote, div\";\n\n/** پاک‌سازی HTML: فقط برچسب‌های متنی مجاز، پیوندهای http، https و mailto، و ویژگی dir؛ بقیه حذف می‌شود */\nexport function sanitizeRichText(html: string): string {\n  if (typeof document === \"undefined\") {\n    // رندر سرور: همان قاعده‌ها با عبارت باقاعده؛ مرورگر دوباره با DOM پاک می‌کند\n    return html\n      .replace(/<(script|style|iframe|object|embed|template|svg|math|head|title)\\b[\\s\\S]*?<\\/\\1\\s*>/gi, \"\")\n      .replace(/<!--[\\s\\S]*?-->/g, \"\")\n      .replace(/<\\/?([a-z][a-z0-9]*)\\b([^>]*)>/gi, (tag, name: string, attrs: string) => {\n        const t = name.toUpperCase();\n        if (!ALLOWED.has(t)) return \"\";\n        if (tag.startsWith(\"</\")) return `</${name.toLowerCase()}>`;\n        const keep: string[] = [];\n        const dir = attrs.match(/\\sdir\\s*=\\s*[\"']?(rtl|ltr|auto)\\b/i);\n        if (dir) keep.push(`dir=\"${dir[1].toLowerCase()}\"`);\n        if (t === \"A\") {\n          const href = attrs.match(/\\shref\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/i);\n          const url = (href?.[1] ?? href?.[2] ?? href?.[3] ?? \"\").trim();\n          if (/^(https?:|mailto:)/i.test(url)) keep.push(`href=\"${url.replace(/\"/g, \"&quot;\")}\"`, 'rel=\"noopener noreferrer nofollow\"');\n        }\n        return `<${name.toLowerCase()}${keep.length ? \" \" + keep.join(\" \") : \"\"}>`;\n      });\n  }\n  const tpl = document.createElement(\"template\");\n  tpl.innerHTML = html;\n  const walk = (node: Node) => {\n    for (const child of Array.from(node.childNodes)) {\n      if (child.nodeType === 8) {\n        child.remove();\n        continue;\n      }\n      if (child.nodeType !== 1) continue;\n      const el = child as HTMLElement;\n      if (!ALLOWED.has(el.tagName)) {\n        if (/^(SCRIPT|STYLE|IFRAME|OBJECT|EMBED|TEMPLATE|SVG|MATH|HEAD|TITLE|META|LINK)$/.test(el.tagName)) el.remove();\n        else {\n          walk(el);\n          el.replaceWith(...Array.from(el.childNodes));\n        }\n        continue;\n      }\n      for (const attr of Array.from(el.attributes)) {\n        const keep = (attr.name === \"dir\" && /^(rtl|ltr|auto)$/.test(attr.value)) || (el.tagName === \"A\" && attr.name === \"href\" && /^(https?:|mailto:)/i.test(attr.value.trim()));\n        if (!keep) el.removeAttribute(attr.name);\n      }\n      if (el.tagName === \"A\") {\n        if (!el.hasAttribute(\"href\")) {\n          el.replaceWith(...Array.from(el.childNodes));\n          continue;\n        }\n        el.setAttribute(\"rel\", \"noopener noreferrer nofollow\");\n      }\n      walk(el);\n    }\n  };\n  walk(tpl.content);\n  return tpl.innerHTML;\n}\n\nconst I = (d: ReactNode) => <svg viewBox=\"0 0 20 20\" fill=\"none\" stroke=\"currentColor\" strokeWidth={1.8} strokeLinecap=\"round\" strokeLinejoin=\"round\" aria-hidden=\"true\">{d}</svg>;\nconst ICONS: Record<Exclude<RichTextTool, \"|\" | \"direction\">, ReactNode> = {\n  bold: I(<path d=\"M6 4h5a3 3 0 0 1 0 6H6zm0 6h6a3 3 0 0 1 0 6H6z\" />),\n  italic: I(<path d=\"M12 4H8.5M11.5 16H8M11 4 9 16\" />),\n  underline: I(<path d=\"M6 4v5a4 4 0 0 0 8 0V4M5 17h10\" />),\n  strike: I(<path d=\"M4 10h12M13.5 6.5c-.5-1.5-2-2.5-3.7-2.5C7.9 4 6.5 5.1 6.5 6.6c0 3.4 7 2 7 6.3 0 1.7-1.6 3.1-3.6 3.1-1.9 0-3.4-1-3.9-2.6\" />),\n  heading: I(<path d=\"M5 4v12M13 4v12M5 10h8M15.5 16v-5l-1.5 1\" />),\n  quote: I(<path d=\"M8 8H5v3h2.5c0 2-1 3-2.5 3.5M15 8h-3v3h2.5c0 2-1 3-2.5 3.5\" />),\n  bullet: I(<path d=\"M8 5.5h8M8 10h8M8 14.5h8M4.5 5.5h.01M4.5 10h.01M4.5 14.5h.01\" />),\n  ordered: I(<path d=\"M8 5.5h8M8 10h8M8 14.5h8M4 4.5l1-.5v3M4 12.5c0-.6.5-1 1-1s1 .4 1 1c0 .7-2 1.5-2 2.5h2\" />),\n  link: I(<path d=\"M8.5 11.5a3 3 0 0 0 4.2 0l2.6-2.6a3 3 0 0 0-4.2-4.2L10 5.8M11.5 8.5a3 3 0 0 0-4.2 0l-2.6 2.6a3 3 0 0 0 4.2 4.2l1.1-1.1\" />),\n  undo: I(<path d=\"M7 5 4 8l3 3M4 8h8a4 4 0 0 1 0 8H9\" />),\n  clear: I(<path d=\"M5 4h10M10 4l-2.5 12M4 16l12-12\" />),\n};\nconst DIR_ICON = I(<path d=\"M9 4h6M13 4v12M9 4v8a3 3 0 0 1-3-3 3 3 0 0 1 3-3M4 14l2 2 2-2\" />);\n\n/** ویرایشگر متن غنی سبک و فارسی: جهت هر بند جدا، نیم‌فاصله با Shift+Space، چسباندن پاک‌شده و نوار ابزار با کیبورد */\nexport function RichTextEditor({\n  value, defaultValue = \"\", onChange, label, \"aria-label\": ariaLabel, placeholder, tools = DEFAULT_TOOLS, minHeight = \"8rem\", showCount = true, name, hint, error, disabled, className,\n}: RichTextEditorProps) {\n  const M = useMessages({ richText: faRichText });\n  const { n } = useKashiLocale();\n  const R = M.richText;\n  const area = useRef<HTMLDivElement>(null);\n  const bar = useRef<HTMLDivElement>(null);\n  const saved = useRef<Range | null>(null);\n  const [html, setHtml] = useState(() => sanitizeRichText(value ?? defaultValue));\n  // محتوای اولیه یک بار (و در رندر سرور) نوشته می‌شود؛ بعد از آن DOM دست خود کاربر است\n  const initial = useRef(html);\n  const [text, setText] = useState(\"\");\n  const [state, setState] = useState<Record<string, boolean>>({});\n  const [linkOpen, setLinkOpen] = useState(false);\n  const [url, setUrl] = useState(\"https://\");\n  const [focusTool, setFocusTool] = useState(0);\n  const id = useId();\n\n  // مقدار اولیه یا کنترل‌شده در DOM؛ اگر همان چیزی است که کاربر نوشته، دست نمی‌خورد تا مکان‌نما نپرد\n  useEffect(() => {\n    const el = area.current;\n    if (!el) return;\n    const next = sanitizeRichText(value ?? html);\n    if (el.innerHTML !== next) el.innerHTML = next;\n    setText(el.innerText ?? el.textContent ?? \"\");\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [value]);\n\n  useEffect(() => {\n    if (!area.current) return;\n    try {\n      document.execCommand(\"defaultParagraphSeparator\", false, \"p\");\n    } catch {\n      /* مرورگر پشتیبانی نمی‌کند */\n    }\n    const update = () => {\n      const sel = document.getSelection();\n      if (!sel || !area.current?.contains(sel.anchorNode)) return;\n      const block = (sel.anchorNode instanceof Element ? sel.anchorNode : sel.anchorNode?.parentElement)?.closest(BLOCKS);\n      const q = (c: string) => {\n        try {\n          return document.queryCommandState(c);\n        } catch {\n          return false;\n        }\n      };\n      setState({\n        bold: q(\"bold\"), italic: q(\"italic\"), underline: q(\"underline\"), strike: q(\"strikeThrough\"),\n        bullet: q(\"insertUnorderedList\"), ordered: q(\"insertOrderedList\"),\n        heading: !!block?.closest(\"h2, h3\"), quote: !!block?.closest(\"blockquote\"),\n        link: !!(sel.anchorNode instanceof Element ? sel.anchorNode : sel.anchorNode?.parentElement)?.closest(\"a\"),\n        ltr: (block as HTMLElement | null)?.dir === \"ltr\",\n      });\n    };\n    document.addEventListener(\"selectionchange\", update);\n    return () => document.removeEventListener(\"selectionchange\", update);\n  }, []);\n\n  const emit = () => {\n    const el = area.current;\n    if (!el) return;\n    const out = sanitizeRichText(el.innerHTML === \"<p><br></p>\" || el.innerHTML === \"<br>\" ? \"\" : el.innerHTML);\n    const plain = el.innerText ?? el.textContent ?? \"\";\n    setHtml(out);\n    setText(plain);\n    onChange?.(out, plain.trim());\n  };\n\n  const exec = (cmd: string, arg?: string) => {\n    area.current?.focus();\n    if (saved.current) {\n      const sel = document.getSelection();\n      sel?.removeAllRanges();\n      sel?.addRange(saved.current);\n      saved.current = null;\n    }\n    document.execCommand(cmd, false, arg);\n    emit();\n  };\n\n  const currentBlock = () => {\n    const sel = document.getSelection();\n    const node = sel?.anchorNode;\n    return (node instanceof Element ? node : node?.parentElement)?.closest<HTMLElement>(BLOCKS) ?? null;\n  };\n\n  const run = (tool: RichTextTool) => {\n    switch (tool) {\n      case \"bold\": return exec(\"bold\");\n      case \"italic\": return exec(\"italic\");\n      case \"underline\": return exec(\"underline\");\n      case \"strike\": return exec(\"strikeThrough\");\n      case \"heading\": return exec(\"formatBlock\", state.heading ? \"<p>\" : \"<h2>\");\n      case \"quote\": return exec(\"formatBlock\", state.quote ? \"<p>\" : \"<blockquote>\");\n      case \"bullet\": return exec(\"insertUnorderedList\");\n      case \"ordered\": return exec(\"insertOrderedList\");\n      case \"undo\": return exec(\"undo\");\n      case \"clear\": return exec(\"removeFormat\");\n      case \"direction\": {\n        const b = currentBlock();\n        if (b && area.current?.contains(b) && b !== area.current) {\n          b.dir = b.dir === \"ltr\" ? \"rtl\" : \"ltr\";\n          setState((s) => ({ ...s, ltr: b.dir === \"ltr\" }));\n          emit();\n        }\n        return;\n      }\n      case \"link\": {\n        if (state.link) return exec(\"unlink\");\n        const sel = document.getSelection();\n        if (sel && sel.rangeCount && area.current?.contains(sel.anchorNode)) saved.current = sel.getRangeAt(0).cloneRange();\n        setLinkOpen(true);\n        return;\n      }\n    }\n  };\n\n  const buttons = tools.filter((t) => t !== \"|\");\n  const onBarKey = (e: KeyboardEvent<HTMLDivElement>) => {\n    const keys = [\"ArrowRight\", \"ArrowLeft\", \"Home\", \"End\"];\n    if (!keys.includes(e.key)) return;\n    e.preventDefault();\n    const rtl = getComputedStyle(e.currentTarget).direction === \"rtl\";\n    const step = e.key === \"Home\" ? -Infinity : e.key === \"End\" ? Infinity : (e.key === \"ArrowLeft\") === rtl ? 1 : -1;\n    const next = Math.max(0, Math.min(buttons.length - 1, step === Infinity ? buttons.length - 1 : step === -Infinity ? 0 : focusTool + step));\n    setFocusTool(next);\n    bar.current?.querySelectorAll<HTMLButtonElement>(\".k-rte__tool\")[next]?.focus();\n  };\n\n  const label_ = (t: Exclude<RichTextTool, \"|\">) => (t === \"direction\" ? (state.ltr ? R.rtl : R.ltr) : t === \"link\" && state.link ? R.unlink : R[t]);\n  const words = text.trim() ? text.trim().split(/\\s+/).length : 0;\n  const empty = !text.trim() && !/<(img|li|blockquote)/.test(html);\n  const helpId = `${id}-help`;\n  let b = -1;\n\n  return (\n    <div className={cx(\"k-rte\", className)} data-disabled={disabled ? \"\" : undefined} data-invalid={error ? \"\" : undefined}>\n      {label && <label className=\"k-label k-rte__label\" id={`${id}-label`} onClick={() => area.current?.focus()}>{label}</label>}\n      <div className=\"k-rte__box\">\n        <div ref={bar} className=\"k-rte__bar\" role=\"toolbar\" aria-label={R.toolbar} aria-controls={id} onKeyDown={onBarKey}>\n          {tools.map((t, k) => {\n            if (t === \"|\") return <span key={k} className=\"k-rte__sep\" aria-hidden=\"true\" />;\n            b++;\n            const pressed = t === \"direction\" ? state.ltr : t === \"link\" || t === \"undo\" || t === \"clear\" ? undefined : !!state[t];\n            const idx = b;\n            return (\n              <button\n                key={k}\n                type=\"button\"\n                className=\"k-rte__tool\"\n                tabIndex={idx === focusTool ? 0 : -1}\n                aria-label={label_(t)}\n                title={label_(t)}\n                aria-pressed={pressed}\n                disabled={disabled}\n                onMouseDown={(e) => e.preventDefault()}\n                onClick={() => {\n                  setFocusTool(idx);\n                  run(t);\n                }}\n              >\n                {t === \"direction\" ? DIR_ICON : ICONS[t]}\n              </button>\n            );\n          })}\n        </div>\n        {linkOpen && (\n          <form\n            className=\"k-rte__link\"\n            onSubmit={(e) => {\n              e.preventDefault();\n              setLinkOpen(false);\n              if (/^(https?:\\/\\/|mailto:)\\S+$/i.test(url.trim())) exec(\"createLink\", url.trim());\n            }}\n          >\n            <input\n              className=\"k-rte__link-input\"\n              type=\"url\"\n              dir=\"ltr\"\n              aria-label={R.linkUrl}\n              value={url}\n              autoFocus\n              onChange={(e) => setUrl(e.target.value)}\n              onKeyDown={(e) => {\n                if (e.key === \"Escape\") {\n                  e.preventDefault();\n                  setLinkOpen(false);\n                  area.current?.focus();\n                }\n              }}\n            />\n            <button type=\"submit\" className=\"k-btn k-btn--primary k-btn--xs\">{R.apply}</button>\n          </form>\n        )}\n        <div\n          ref={area}\n          id={id}\n          className=\"k-rte__area\"\n          role=\"textbox\"\n          aria-multiline=\"true\"\n          aria-label={label ? undefined : ariaLabel ?? R.label}\n          aria-labelledby={label ? `${id}-label` : undefined}\n          aria-describedby={helpId}\n          aria-invalid={error ? true : undefined}\n          aria-disabled={disabled || undefined}\n          contentEditable={!disabled}\n          suppressContentEditableWarning\n          dangerouslySetInnerHTML={{ __html: initial.current }}\n          dir=\"rtl\"\n          data-empty={empty ? \"\" : undefined}\n          data-placeholder={placeholder ?? R.placeholder}\n          style={{ minBlockSize: minHeight }}\n          onInput={emit}\n          onBlur={emit}\n          onKeyDown={(e) => {\n            // نیم‌فاصله\n            if (e.key === \" \" && e.shiftKey) {\n              e.preventDefault();\n              document.execCommand(\"insertText\", false, \"‌\");\n            }\n            if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === \"k\") {\n              e.preventDefault();\n              run(\"link\");\n            }\n          }}\n          onPaste={(e) => {\n            e.preventDefault();\n            const rich = e.clipboardData.getData(\"text/html\");\n            if (rich) document.execCommand(\"insertHTML\", false, sanitizeRichText(rich));\n            else document.execCommand(\"insertText\", false, e.clipboardData.getData(\"text/plain\"));\n            emit();\n          }}\n        />\n        {showCount && (\n          <div className=\"k-rte__foot\">\n            <span>{R.words(n(words))}</span>\n            <span aria-hidden=\"true\">·</span>\n            <span>{R.chars(n(text.replace(/\\n/g, \"\").length))}</span>\n            <span className=\"k-rte__tip\">{R.zwnj}</span>\n          </div>\n        )}\n      </div>\n      <div id={helpId} className=\"k-rte__help\">\n        {error ? <p className=\"k-hint k-hint--error\">{error}</p> : hint ? <p className=\"k-hint\">{hint}</p> : <span className=\"k-sr-only\">{R.zwnj}</span>}\n      </div>\n      {name && <input type=\"hidden\" name={name} value={html} />}\n    </div>\n  );\n}\n"
    }
  ]
}