{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "markdown-editor",
  "type": "registry:ui",
  "title": "Markdown Editor",
  "description": "A field for writing Markdown with a toolbar that wraps the chosen words (bold, italic, code, link) or starts a line (heading, list, quote), the same as Ctrl/⌘ with B, I and K, and a tab that shows the project's own preview.",
  "categories": [
    "ui"
  ],
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/cn",
    "@rivier-ui/use-controllable-state"
  ],
  "files": [
    {
      "path": "registry/ui/markdown-editor.tsx",
      "type": "registry:ui",
      "target": "components/ui/markdown-editor.tsx",
      "content": "\"use client\";\n/**\n * @name markdown-editor\n * @category ui\n * @description A field for writing Markdown with a toolbar that wraps the chosen words (bold, italic, code, link) or starts a line (heading, list, quote), the same as Ctrl/⌘ with B, I and K, and a tab that shows the project's own preview.\n * @when Comments, notes and descriptions where people write a little formatting. The preview is the project's (its Markdown renderer and its sanitiser); without one, leave `renderPreview` out and there is no preview tab. For rich text without markup bring an editor (Tiptap, Lexical); for plain text use textarea.\n * @example\n * <MarkdownEditor aria-label=\"Comment\" defaultValue=\"**Hello**\" renderPreview={(text) => <MyMarkdown source={text} />} name=\"comment\" />\n */\nimport { Bold, Code, Heading2, Italic, Link, List, Quote } from \"lucide-react\";\nimport { useId, useRef, useState, type ComponentProps, type KeyboardEvent, type ReactNode } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport { useControllableState } from \"@/lib/use-controllable-state\";\n\nexport type MarkdownEditorLabels = { toolbar: string; write: string; preview: string; bold: string; italic: string; code: string; link: string; heading: string; list: string; quote: string; linkText: string };\n\nconst LABELS: MarkdownEditorLabels = {\n  toolbar: \"Formatting\",\n  write: \"Write\",\n  preview: \"Preview\",\n  bold: \"Bold\",\n  italic: \"Italic\",\n  code: \"Code\",\n  link: \"Link\",\n  heading: \"Heading\",\n  list: \"List\",\n  quote: \"Quote\",\n  linkText: \"text\",\n};\n\nexport type MarkdownEditorProps = Omit<ComponentProps<\"textarea\">, \"value\" | \"defaultValue\"> & {\n  value?: string;\n  defaultValue?: string;\n  onValueChange?: (value: string) => void;\n  /** Draws the preview: the project's Markdown renderer. Left out, there is no preview tab. */\n  renderPreview?: (markdown: string) => ReactNode;\n  labels?: Partial<MarkdownEditorLabels>;\n};\n\ntype Action = \"bold\" | \"italic\" | \"code\" | \"link\" | \"heading\" | \"list\" | \"quote\";\n\nexport function MarkdownEditor({ value, defaultValue = \"\", onValueChange, renderPreview, labels: given, className, onKeyDown, rows = 8, ...props }: MarkdownEditorProps) {\n  const labels = { ...LABELS, ...given };\n  const [text, setText] = useControllableState<string>({ value, defaultValue, onChange: onValueChange });\n  const [tab, setTab] = useState<\"write\" | \"preview\">(\"write\");\n  const area = useRef<HTMLTextAreaElement>(null);\n  const id = useId();\n\n  const apply = (action: Action): void => {\n    const node = area.current;\n    if (!node) return;\n    const start = node.selectionStart;\n    const end = node.selectionEnd;\n    const chosen = text.slice(start, end);\n    let next = text;\n    let from = start;\n    let to = end;\n    const wrapWith = (before: string, after = before, placeholder = \"\"): void => {\n      const inner = chosen || placeholder;\n      next = text.slice(0, start) + before + inner + after + text.slice(end);\n      from = start + before.length;\n      to = from + inner.length;\n    };\n    const prefixLines = (prefix: string): void => {\n      const lineStart = text.lastIndexOf(\"\\n\", start - 1) + 1;\n      const block = text.slice(lineStart, end);\n      const changed = block\n        .split(\"\\n\")\n        .map((line) => (line.startsWith(prefix) ? line.slice(prefix.length) : prefix + line))\n        .join(\"\\n\");\n      next = text.slice(0, lineStart) + changed + text.slice(end);\n      from = lineStart;\n      to = lineStart + changed.length;\n    };\n    if (action === \"bold\") wrapWith(\"**\");\n    else if (action === \"italic\") wrapWith(\"_\");\n    else if (action === \"code\") wrapWith(chosen.includes(\"\\n\") ? \"```\\n\" : \"`\", chosen.includes(\"\\n\") ? \"\\n```\" : \"`\");\n    else if (action === \"link\") {\n      wrapWith(\"[\", \"](https://)\", labels.linkText);\n    } else if (action === \"heading\") prefixLines(\"## \");\n    else if (action === \"list\") prefixLines(\"- \");\n    else prefixLines(\"> \");\n    setText(next);\n    requestAnimationFrame(() => {\n      node.focus();\n      node.setSelectionRange(from, to);\n    });\n  };\n  const tools: { action: Action; label: string; icon: ReactNode }[] = [\n    { action: \"bold\", label: labels.bold, icon: <Bold /> },\n    { action: \"italic\", label: labels.italic, icon: <Italic /> },\n    { action: \"heading\", label: labels.heading, icon: <Heading2 /> },\n    { action: \"link\", label: labels.link, icon: <Link /> },\n    { action: \"code\", label: labels.code, icon: <Code /> },\n    { action: \"list\", label: labels.list, icon: <List /> },\n    { action: \"quote\", label: labels.quote, icon: <Quote /> },\n  ];\n\n  return (\n    <div data-slot=\"markdown-editor\" className={cn(\"flex w-full min-w-0 flex-col overflow-hidden rounded-surface border border-input bg-background focus-within:outline-2 focus-within:outline-offset-2 focus-within:outline-ring\", className)}>\n      <div className=\"flex flex-wrap items-center gap-1 border-b bg-card p-1\">\n        {renderPreview ? (\n          <div role=\"tablist\" aria-label={labels.preview} className=\"me-2 flex gap-1\">\n            {([\"write\", \"preview\"] as const).map((name) => (\n              <button\n                key={name}\n                type=\"button\"\n                role=\"tab\"\n                id={`${id}-${name}-tab`}\n                aria-selected={tab === name}\n                aria-controls={`${id}-${name}`}\n                tabIndex={tab === name ? 0 : -1}\n                onClick={() => setTab(name)}\n                onKeyDown={(event) => {\n                  if (event.key === \"ArrowRight\" || event.key === \"ArrowLeft\") {\n                    event.preventDefault();\n                    setTab(name === \"write\" ? \"preview\" : \"write\");\n                    document.getElementById(`${id}-${name === \"write\" ? \"preview\" : \"write\"}-tab`)?.focus();\n                  }\n                }}\n                className=\"h-control-sm rounded-control px-3 text-sm aria-selected:bg-highlight-soft aria-selected:font-medium hover:bg-accent\"\n              >\n                {name === \"write\" ? labels.write : labels.preview}\n              </button>\n            ))}\n          </div>\n        ) : null}\n        {tab === \"write\" ? (\n          <div role=\"toolbar\" aria-label={labels.toolbar} aria-controls={`${id}-write`} className=\"flex flex-wrap gap-0.5\">\n            {tools.map((tool) => (\n              <button\n                key={tool.action}\n                type=\"button\"\n                aria-label={tool.label}\n                onClick={() => apply(tool.action)}\n                className=\"flex size-8 items-center justify-center rounded-control text-muted-foreground hover:bg-accent hover:text-foreground pointer-coarse:size-10 [&_svg]:size-4\"\n              >\n                {tool.icon}\n              </button>\n            ))}\n          </div>\n        ) : null}\n      </div>\n      <div id={`${id}-write`} role={renderPreview ? \"tabpanel\" : undefined} aria-labelledby={renderPreview ? `${id}-write-tab` : undefined} hidden={tab !== \"write\"}>\n        <textarea\n          ref={area}\n          value={text}\n          rows={rows}\n          onChange={(event) => setText(event.target.value)}\n          onKeyDown={(event: KeyboardEvent<HTMLTextAreaElement>) => {\n            onKeyDown?.(event);\n            if (!(event.ctrlKey || event.metaKey) || event.altKey) return;\n            const keys: Record<string, Action> = { KeyB: \"bold\", KeyI: \"italic\", KeyK: \"link\" };\n            const action = keys[event.code];\n            if (action) {\n              event.preventDefault();\n              apply(action);\n            }\n          }}\n          className=\"block w-full resize-y bg-transparent p-3 font-mono text-sm outline-none\"\n          {...props}\n        />\n      </div>\n      {renderPreview ? (\n        <div id={`${id}-preview`} role=\"tabpanel\" aria-labelledby={`${id}-preview-tab`} hidden={tab !== \"preview\"} tabIndex={0} className=\"min-h-40 p-3 text-base\">\n          {tab === \"preview\" ? renderPreview(text) : null}\n        </div>\n      ) : null}\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "Comments, notes and descriptions where people write a little formatting. The preview is the project's (its Markdown renderer and its sanitiser); without one, leave `renderPreview` out and there is no preview tab. For rich text without markup bring an editor (Tiptap, Lexical); for plain text use textarea.",
    "example": "<MarkdownEditor aria-label=\"Comment\" defaultValue=\"**Hello**\" renderPreview={(text) => <MyMarkdown source={text} />} name=\"comment\" />",
    "client": true
  }
}
