{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "rich-text-editor",
  "type": "registry:ui",
  "title": "Rich Text Editor",
  "description": "Short formatted text (bold, italic, bullet lists, links) edited in place, Markdown in and out, with a one-row toolbar that floats above it while it has focus and flips below when there is no room. ProseMirror via ProseKit.",
  "dependencies": [
    "hast-util-from-dom@^5.0.1",
    "lucide-react@^1.49.0",
    "prosekit@^0.22.4",
    "rehype-remark@^10.0.1",
    "rehype-stringify@^10.0.1",
    "remark-gfm@^4.0.1",
    "remark-parse@^11.0.0",
    "remark-rehype@^11.1.2",
    "remark-stringify@^11.0.0",
    "unified@^11.0.5"
  ],
  "registryDependencies": [
    "https://ui.klarhimmel.com/r/icon-button.json",
    "https://ui.klarhimmel.com/r/theme.json",
    "https://ui.klarhimmel.com/r/utils.json"
  ],
  "files": [
    {
      "path": "src/ui/rich-text-editor.tsx",
      "type": "registry:file",
      "target": "components/klarhimmel/ui/rich-text-editor.tsx",
      "content": "/// <reference path=\"../css.d.ts\" />\nimport { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react';\nimport { createEditor, union, defineBaseCommands, defineBaseKeymap, defineHistory, definePlugin, type Editor } from 'prosekit/core';\nimport { defineDoc } from 'prosekit/extensions/doc';\nimport { defineText } from 'prosekit/extensions/text';\nimport { defineParagraph } from 'prosekit/extensions/paragraph';\nimport { defineBold } from 'prosekit/extensions/bold';\nimport { defineItalic } from 'prosekit/extensions/italic';\nimport { defineHeading } from 'prosekit/extensions/heading';\nimport { defineList, ListDOMSerializer } from 'prosekit/extensions/list';\nimport { defineLink } from 'prosekit/extensions/link';\nimport { defineHardBreak } from 'prosekit/extensions/hard-break';\nimport { Plugin } from 'prosekit/pm/state';\nimport { ProseKit, useDocChange, useEditorDerivedValue } from 'prosekit/react';\nimport { unified } from 'unified';\nimport remarkParse from 'remark-parse';\nimport remarkGfm from 'remark-gfm';\nimport remarkRehype from 'remark-rehype';\nimport rehypeStringify from 'rehype-stringify';\nimport rehypeRemark from 'rehype-remark';\nimport remarkStringify from 'remark-stringify';\nimport { fromDom } from 'hast-util-from-dom';\nimport { Bold, Heading, Italic, List, ListChecks, Redo2, Undo2 } from 'lucide-react';\nimport { cn } from '../lib/utils';\nimport { IconButton } from './icon-button';\nimport 'prosekit/basic/style.css';\n\n// A section editor for short formatted text: headings, bold, italic, bullet and task lists, links, line breaks. GFM task\n// lists ('- [ ]', '- [x]') are real checkboxes a click ticks (workspace counts a task's checklist from them). Markdown in, Markdown out;\n// saving, versions and recovery belong to the caller. Its own entry point (@klarhimmel/ui/rich-text-editor), not in the\n// barrel, so only a page that edits loads ProseMirror and the Markdown pipeline. Moved from the portal (pm 10).\n\nfunction safeHTML(html: string) {\n  const doc = new DOMParser().parseFromString(html, 'text/html');\n  doc.querySelectorAll('img,script,style,iframe,object').forEach((el) => el.remove());\n  doc.querySelectorAll('a').forEach((link) => {\n    if (!/^(https?:|mailto:|\\/|#)/i.test(link.getAttribute('href') ?? '')) link.removeAttribute('href');\n    link.setAttribute('target', '_blank');\n    link.setAttribute('rel', 'noopener noreferrer');\n  });\n  return doc.body.innerHTML;\n}\nexport const markdownToHTML = (text: string) => safeHTML(String(unified().use(remarkParse).use(remarkGfm).use(remarkRehype).use(rehypeStringify).processSync(text)));\n// HTML is read with the browser's own parser (DOMParser), not parse5, which would add 185 KB to the bundle.\n// Bullets as '-', so a task reads '- [ ]' (workspace counts a task's checklist from that).\nconst toMarkdown = unified().use(rehypeRemark).use(remarkGfm).use(remarkStringify, { bullet: '-' });\nexport function htmlToMarkdown(html: string) {\n  const template = document.createElement('template');\n  template.innerHTML = html;\n  const hast = fromDom(template.content) as Parameters<typeof toMarkdown.runSync>[0];\n  return String(toMarkdown.stringify(toMarkdown.runSync(hast))).trimEnd();\n}\n\n/** The flat-list serializer writes one <ul> for adjacent bullet and task items and marks a task only with data attributes.\n *  Give Markdown what GFM reads: a list per kind, a checkbox first in each task item, and a lone paragraph unwrapped so the\n *  list stays tight. */\nfunction nativeLists(root: HTMLElement) {\n  for (const list of [...root.querySelectorAll('ul')]) {\n    let current = list;\n    let kind: string | null = null;\n    for (const item of [...list.children] as HTMLElement[]) {\n      const k = item.dataset.listKind ?? 'bullet';\n      if (kind !== null && k !== kind) {\n        const next = document.createElement('ul');\n        current.after(next);\n        current = next;\n      }\n      kind = k;\n      if (current !== list) current.append(item);\n      if (item.children.length === 1 && item.firstElementChild!.tagName === 'P') item.firstElementChild!.replaceWith(...item.firstElementChild!.childNodes);\n      if (k === 'task') {\n        const box = document.createElement('input');\n        box.type = 'checkbox';\n        if (item.hasAttribute('data-list-checked')) box.setAttribute('checked', '');\n        item.prepend(box, ' ');\n      }\n    }\n  }\n}\n\nexport interface RichTextEditorLabels {\n  toolbar: string;\n  heading: string;\n  bold: string;\n  italic: string;\n  list: string;\n  tasks: string;\n  undo: string;\n  redo: string;\n}\nconst EN: RichTextEditorLabels = { toolbar: 'Formatting', heading: 'Heading', bold: 'Bold', italic: 'Italic', list: 'Bulleted list', tasks: 'Task list', undo: 'Undo', redo: 'Redo' };\n\nexport interface RichTextEditorProps {\n  /** Markdown. A new value from outside replaces the text; the editor's own changes come back through onChange. */\n  value: string;\n  onChange: (value: string) => void;\n  /** Required: names the text box (and, after the toolbar label, its toolbar). */\n  label: string;\n  /** Where the toolbar floats while the editor has focus. auto: above, or below when there is no room above it in the\n   *  window (the top inset is the page's scroll-padding-top, so a sticky header counts). It never takes room in the page. */\n  placement?: 'auto' | 'above' | 'below';\n  /** The longest Markdown accepted, in characters; an edit past it is undone. 0 for no limit. */\n  maxLength?: number;\n  /** The toolbar's and the buttons' names. English by default: pass them translated. */\n  labels?: Partial<RichTextEditorLabels>;\n  className?: string;\n}\n\nfunction defineExtension(label: string) {\n  return union(\n    defineDoc(), defineText(), defineParagraph(), defineHeading(), defineBold(), defineItalic(), defineList(), defineLink(), defineHardBreak(),\n    defineBaseCommands(), defineBaseKeymap(), defineHistory(),\n    definePlugin(new Plugin({ props: { attributes: { role: 'textbox', 'aria-label': label, 'aria-multiline': 'true' }, transformPastedHTML: safeHTML } })),\n  );\n}\ntype TextEditor = Editor<ReturnType<typeof defineExtension>>;\n\nconst TOOLBAR_ROOM = 52; // the toolbar's height (44 px buttons, padding, border) and a gap\n\n/** Short formatted text with a one-row floating toolbar above it (or below, see placement) while it has focus. */\nexport function RichTextEditor({ value, onChange, label, placement = 'auto', maxLength = 8000, labels, className }: RichTextEditorProps) {\n  const editor = useMemo(() => createEditor({ extension: defineExtension(label) }), [label]);\n  const applying = useRef(false);\n  const last = useRef<string | null>(null);\n  const previousEditor = useRef(editor);\n  useEffect(() => {\n    if (value === last.current && previousEditor.current === editor) return;\n    previousEditor.current = editor;\n    applying.current = true;\n    editor.setContent(markdownToHTML(value));\n    last.current = value;\n    applying.current = false;\n  }, [editor, value]);\n  useDocChange(\n    (doc) => {\n      if (applying.current) return;\n      const container = document.createElement('div');\n      container.append(ListDOMSerializer.fromSchema(editor.schema).serializeFragment(doc.content));\n      nativeLists(container);\n      const next = htmlToMarkdown(container.innerHTML);\n      if (next === last.current) return;\n      if (maxLength > 0 && next.length > maxLength) {\n        applying.current = true;\n        editor.setContent(markdownToHTML(last.current ?? value), 'end');\n        applying.current = false;\n        return;\n      }\n      last.current = next;\n      onChange(next);\n    },\n    { editor },\n  );\n\n  const [below, setBelow] = useState(placement === 'below');\n  const place = useCallback(\n    (el: HTMLElement) => {\n      if (placement !== 'auto') return setBelow(placement === 'below');\n      const inset = parseFloat(getComputedStyle(document.documentElement).scrollPaddingTop) || 0;\n      setBelow(el.getBoundingClientRect().top - TOOLBAR_ROOM < inset);\n    },\n    [placement],\n  );\n  const words = { ...EN, ...labels };\n\n  return (\n    <ProseKit editor={editor}>\n      <div\n        className={cn('group relative flex min-w-0 flex-col', className)}\n        onFocus={(e) => {\n          if (!e.currentTarget.contains(e.relatedTarget as Node | null)) place(e.currentTarget);\n        }}\n      >\n        <Toolbar editor={editor} words={words} name={`${words.toolbar}: ${label}`} below={below} />\n        <div\n          ref={editor.mount}\n          className={cn(\n            // ProseKit mounts the view on this element (it becomes .ProseMirror), so its padding and focus ring are set here, not on a child.\n            // :focus, not :focus-visible: WebKit does not match focus-visible on a tapped contenteditable, as browsers do for a text input.\n            'min-h-12 min-w-0 rounded-kh p-2 text-kh-body leading-relaxed text-kh-ink focus:outline-2 focus:outline-(--kh-focus)',\n            '[&_h2]:mb-2 [&_h2]:text-kh-lead [&_input]:accent-(--kh-accent) [&_h2]:font-semibold [&_h3]:mb-2 [&_h3]:font-semibold [&_p]:mb-2 [&_p:last-child]:mb-0 [&_ul]:list-disc [&_ul]:pl-6 [&_ol]:list-decimal [&_ol]:pl-6 [&_a]:underline',\n          )}\n        />\n      </div>\n    </ProseKit>\n  );\n}\n\nexport default RichTextEditor;\n\ntype Run = (editor: TextEditor) => unknown;\nconst TOOLS: { key: keyof RichTextEditorLabels; icon: typeof Bold; run: Run; shortcut?: string }[] = [\n  { key: 'heading', icon: Heading, run: (e) => e.commands.toggleHeading({ level: 2 }) },\n  { key: 'bold', icon: Bold, run: (e) => e.commands.toggleBold(), shortcut: 'Mod+B' },\n  { key: 'italic', icon: Italic, run: (e) => e.commands.toggleItalic(), shortcut: 'Mod+I' },\n  { key: 'list', icon: List, run: (e) => e.commands.toggleList({ kind: 'bullet' }) },\n  { key: 'tasks', icon: ListChecks, run: (e) => e.commands.toggleList({ kind: 'task' }) },\n  { key: 'undo', icon: Undo2, run: (e) => e.commands.undo(), shortcut: 'Mod+Z' },\n  { key: 'redo', icon: Redo2, run: (e) => e.commands.redo(), shortcut: 'Mod+Shift+Z' },\n];\n\n/** The WAI-ARIA toolbar: one tab stop, Left / Right / Home / End move between the buttons. */\nfunction Toolbar({ editor, words, name, below }: { editor: TextEditor; words: RichTextEditorLabels; name: string; below: boolean }) {\n  const pressed = useEditorDerivedValue(derivePressed);\n  const [current, setCurrent] = useState(0);\n  const buttons = useRef<(HTMLButtonElement | null)[]>([]);\n  const onKeyDown = (e: KeyboardEvent) => {\n    const n = TOOLS.length;\n    const to = { ArrowRight: current + 1, ArrowLeft: current - 1 + n, Home: 0, End: n - 1 }[e.key];\n    if (to === undefined) return;\n    e.preventDefault();\n    setCurrent(to % n);\n    buttons.current[to % n]?.focus();\n  };\n  return (\n    <div\n      role=\"toolbar\"\n      aria-label={name}\n      onKeyDown={onKeyDown}\n      className={cn(\n        'pointer-events-none invisible absolute left-0 z-30 flex max-w-full flex-nowrap gap-0.5 overflow-x-auto rounded-kh-lg border border-kh-line bg-kh-surface p-0.5 shadow-kh-2',\n        'group-focus-within:pointer-events-auto group-focus-within:visible',\n        below ? 'top-full mt-1' : 'bottom-full mb-1',\n      )}\n    >\n      {TOOLS.map(({ key, icon: Icon, run }, i) => (\n        <IconButton\n          key={key}\n          ref={(el) => {\n            buttons.current[i] = el;\n          }}\n          label={words[key]}\n          noTooltip\n          size=\"md\"\n          tabIndex={i === current ? 0 : -1}\n          active={key in pressed ? pressed[key as keyof typeof pressed] : undefined}\n          onMouseDown={(e) => e.preventDefault()}\n          onFocus={() => setCurrent(i)}\n          onClick={() => {\n            run(editor);\n            editor.focus();\n          }}\n        >\n          <Icon aria-hidden className=\"size-4\" />\n        </IconButton>\n      ))}\n    </div>\n  );\n}\n\nfunction derivePressed(editor: TextEditor) {\n  return { heading: editor.nodes.heading.isActive(), bold: editor.marks.bold.isActive(), italic: editor.marks.italic.isActive(), list: editor.nodes.list.isActive({ kind: 'bullet' }), tasks: editor.nodes.list.isActive({ kind: 'task' }) };\n}\n"
    }
  ]
}
