{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "doc-page",
  "type": "registry:ui",
  "title": "Doc Page",
  "description": "The doc-page primitive.",
  "dependencies": [
    "lucide-react@^1.49.0",
    "prosekit@^0.22.4"
  ],
  "registryDependencies": [
    "https://ui.klarhimmel.com/r/dialog.json",
    "https://ui.klarhimmel.com/r/doc-host.json",
    "https://ui.klarhimmel.com/r/input.json",
    "https://ui.klarhimmel.com/r/sheet.json",
    "https://ui.klarhimmel.com/r/theme.json",
    "https://ui.klarhimmel.com/r/toast.json",
    "https://ui.klarhimmel.com/r/utils.json"
  ],
  "files": [
    {
      "path": "src/ui/doc-page.tsx",
      "type": "registry:file",
      "target": "components/klarhimmel/ui/doc-page.tsx",
      "content": "// DocPage: the one text-page view and editor (Felix 2026-10-21 14:50: \"standardize this as the default text page view edit\n// experience across all our projects going forward\"). Moved here from apps/operations/workspace-screens/doc.tsx.\n// Notion's interaction patterns, our tokens; Markdown in, Markdown out (doc-page.markdown.ts).\n// - Always editable in place: no tabs, no fixed toolbar. Without onChange it is read-only.\n// - A floating toolbar on a selection: text style, bold, italic, underline, strike, code, link, and Comment / Ask when given.\n// - Block handles in the left margin (+ adds a block, the grip drags it); '/' opens a menu of blocks.\n// - Links to other pages show a preview card on hover (DocHost.resolve); mod-click follows them.\n// - A slim outline on the right edge from a 48rem container, from three headings and not when bare: one line per heading; hover lists them, click jumps.\n// DocPanel wraps it in a side Sheet: close and full page on the left, copy link, star and more (…) on the right.\n// It loads ProseMirror: import it lazily, on the page that shows a document.\nimport { useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';\nimport { createEditor, union, type Editor, type NodeJSON } from 'prosekit/core';\nimport { defineBasicExtension } from 'prosekit/basic';\nimport { definePlaceholder } from 'prosekit/extensions/placeholder';\nimport { defineReadonly } from 'prosekit/extensions/readonly';\nimport { ProseKit, useDocChange, useEditor, useEditorDerivedValue } from 'prosekit/react';\nimport { InlinePopoverRoot, InlinePopoverPositioner, InlinePopoverPopup } from 'prosekit/react/inline-popover';\nimport { BlockHandleRoot, BlockHandlePositioner, BlockHandlePopup, BlockHandleAdd, BlockHandleDraggable } from 'prosekit/react/block-handle';\nimport { AutocompleteRoot, AutocompletePositioner, AutocompletePopup, AutocompleteItem, AutocompleteEmpty } from 'prosekit/react/autocomplete';\nimport 'prosekit/basic/style.css';\nimport { Bold, Italic, Underline, Strikethrough, Code, Link2, MessageSquare, Sparkles, Plus, GripVertical, ChevronsRight, Maximize2, Star, MoreHorizontal, Link as LinkIcon, Heading1, Heading2, Heading3, List, ListOrdered, ListChecks, Quote, Minus, Image as ImageIcon, FileText, Type, Table as TableIcon } from 'lucide-react';\nimport { cn } from '../lib/utils';\nimport { docToMarkdown, inlineToMarkdown, markdownToDoc, type DocJSON } from './doc-page.markdown';\nimport { Sheet } from './sheet';\nimport { Dialog } from './dialog';\nimport { Textarea } from './input';\nimport { toast } from './toast';\n\nexport { markdownToDoc, docToMarkdown } from './doc-page.markdown';\n\nimport { DocHostCtx, type DocHostValue } from './doc-host';\nexport { DocHost, type DocHostValue } from './doc-host';\n\nexport interface DocPageLabels {\n  placeholder: string; style: string; text: string; h1: string; h2: string; h3: string; bold: string; italic: string; underline: string;\n  strike: string; code: string; link: string; linkTo: string; comment: string; ask: string; addBlock: string; drag: string; nothing: string;\n  bullets: string; numbers: string; checklist: string; quote: string; divider: string; table: string; image: string; pageLink: string; findPage: string;\n  outline: string; open: string;\n  close: string; fullPage: string; copyLink: string; copied: string; star: string; more: string; source: string; sourceNote: string;\n  history: string; download: string;\n}\nconst EN: DocPageLabels = {\n  placeholder: \"Write, or type '/' for headings, lists, pictures…\", style: 'Text style', text: 'Text', h1: 'Heading 1', h2: 'Heading 2', h3: 'Heading 3',\n  bold: 'Bold', italic: 'Italic', underline: 'Underline', strike: 'Strike', code: 'Code', link: 'Link', linkTo: 'Link to (a web address)', comment: 'Comment',\n  ask: 'Ask', addBlock: 'Add a block', drag: 'Drag to move', nothing: 'Nothing matches', bullets: 'Bulleted list', numbers: 'Numbered list',\n  checklist: 'Checklist', quote: 'Quote', divider: 'Divider', table: 'Table', image: 'An image', pageLink: 'Link to a page', findPage: 'Find a page', outline: 'On this page',\n  open: 'Open', close: 'Close the panel', fullPage: 'Open as full page', copyLink: 'Copy link', copied: 'Copied', star: 'Star', more: 'More',\n  source: 'Markdown source', sourceNote: 'What is stored. Edits here change the page.', history: 'Version history', download: 'Download as .md',\n};\n\nexport interface DocPageProps {\n  /** The page's name, shown large. */\n  title: string;\n  /** Markdown (storage). A new value from outside replaces the text. */\n  value: string;\n  /** Edits come back as Markdown. Absent: the page is read-only (no handles, '/' menu or selection toolbar). */\n  onChange?: (markdown: string) => void;\n  /** One quiet line under the title: path, version, saved. */\n  meta?: string;\n  /** Above the body, under the title (a description's goal and deliverables). */\n  lead?: ReactNode;\n  /** Shows Comment on a selection: the caller files the quoted words in its thread. */\n  onComment?: (quote: string) => void;\n  /** Shows Ask on a selection with these actions; the caller runs the assistant on the quoted words. */\n  ask?: { actions: string[]; onAsk(action: string, quote: string): void };\n  /** The caller draws the title (a task card): the page is the body only. */\n  bare?: boolean;\n  labels?: Partial<DocPageLabels>;\n  className?: string;\n}\n\n// The basic extension includes tables; doc-page.markdown.ts reads and writes them as GFM (Klar Portal 10-25 09:27).\nconst makeExtension = (placeholder: string) => union(defineBasicExtension(), definePlaceholder({ placeholder }));\ntype DocExtension = ReturnType<typeof makeExtension>;\n/** Read-only: the same document, no typing. */\nconst makeReadonly = () => union(defineBasicExtension(), defineReadonly()) as unknown as DocExtension;\ntype DocEditor = Editor<DocExtension>;\n\nconst tool = 'inline-flex size-8 pointer-coarse:size-11 items-center justify-center rounded-kh text-kh-ink-2 hover:bg-kh-surface-2 hover:text-kh-ink';\nconst row = 'flex min-h-9 pointer-coarse:min-h-11 w-full cursor-pointer items-center gap-2 rounded-kh px-2 text-left text-kh-small hover:bg-kh-surface-2';\n\nfunction Tool({ label, on, onClick, children }: { label: string; on?: boolean; onClick: () => void; children: ReactNode }) {\n  return <button type=\"button\" aria-label={label} title={label} aria-pressed={on} onMouseDown={(e) => e.preventDefault()} onClick={onClick}\n    className={cn(tool, on && 'bg-kh-surface-2 text-kh-ink')}>{children}</button>;\n}\n\n/** The text page: a large title, the body at a reading width, editable in place. */\nexport function DocPage({ title, value, onChange, meta, lead, onComment, ask, bare, labels, className }: DocPageProps) {\n  const w = { ...EN, ...labels };\n  const host = useContext(DocHostCtx);\n  // Shown picture addresses map back to their stored reference when the page is saved.\n  const refs = useRef(new Map<string, string>());\n  const pictureSrc = (ref: string) => { const src = host.pictureSrc(ref); refs.current.set(src, ref); return src; };\n  const pictureRef = (src: string) => refs.current.get(src) ?? src;\n  const readOnly = !onChange;\n  const extension = useMemo(() => (readOnly ? makeReadonly() : makeExtension(w.placeholder)), []); // eslint-disable-line react-hooks/exhaustive-deps\n  const editor = useMemo(() => createEditor({ extension, defaultContent: markdownToDoc(value, pictureSrc) as NodeJSON }), [extension]); // eslint-disable-line react-hooks/exhaustive-deps\n  const last = useRef(value);\n  const [heads, setHeads] = useState<{ text: string; level: number; i: number }[]>([]);\n  const readHeads = () => setHeads(((editor.getDocJSON() as DocJSON).content ?? []).flatMap((b, i) => (b.type === 'heading' ? [{ text: inlineToMarkdown(b.content).replace(/[*_~`]/g, ''), level: Number(b.attrs?.level ?? 1), i }] : [])));\n  // In step when the caller's Markdown changes from elsewhere (a checkbox in a list, the Markdown source).\n  useEffect(() => { if (value !== last.current) { last.current = value; editor.setContent(markdownToDoc(value, pictureSrc) as NodeJSON); readHeads(); } }, [value, editor]); // eslint-disable-line react-hooks/exhaustive-deps\n  useDocChange(() => { const md = docToMarkdown(editor.getDocJSON() as DocJSON, pictureRef); last.current = md; onChange?.(md); readHeads(); }, { editor });\n  useEffect(() => { readHeads(); }, [editor]); // eslint-disable-line react-hooks/exhaustive-deps\n\n  const [preview, setPreview] = useState<{ href: string; x: number; y: number } | null>(null);\n  const [picker, setPicker] = useState<null | 'image' | 'link'>(null);\n  const body = useRef<HTMLDivElement>(null);\n\n  // Hover a page link: its preview card. Mod-click or Open follows it.\n  const onMove = (e: React.MouseEvent) => {\n    const a = (e.target as HTMLElement).closest('a'); const href = a?.getAttribute('href') ?? '';\n    if (a && host.resolve(href)) { const r = a.getBoundingClientRect(); setPreview({ href, x: r.left, y: r.bottom + 6 }); }\n  };\n  const onClick = (e: React.MouseEvent) => {\n    const a = (e.target as HTMLElement).closest('a'); const href = a?.getAttribute('href') ?? '';\n    if (a && (e.metaKey || e.ctrlKey)) { e.preventDefault(); if (host.resolve(href)) host.open(href); else window.open(href, '_blank', 'noopener'); }\n  };\n  // After a picker closes, typing goes on in the document (the dialog hands focus back to the page otherwise).\n  const refocus = () => setTimeout(() => editor.focus(), 0);\n  const jump = (i: number) => body.current?.querySelector('.ProseMirror')?.children[i]?.scrollIntoView({ behavior: 'smooth', block: 'start' });\n\n  const icon = 'size-4';\n  const slash: { label: string; icon: ReactNode; run: () => void }[] = [\n    { label: w.text, icon: <Type className={icon} />, run: () => editor.commands.setParagraph() },\n    { label: w.h1, icon: <Heading1 className={icon} />, run: () => editor.commands.setHeading({ level: 1 }) },\n    { label: w.h2, icon: <Heading2 className={icon} />, run: () => editor.commands.setHeading({ level: 2 }) },\n    { label: w.h3, icon: <Heading3 className={icon} />, run: () => editor.commands.setHeading({ level: 3 }) },\n    { label: w.bullets, icon: <List className={icon} />, run: () => editor.commands.wrapInList({ kind: 'bullet' }) },\n    { label: w.numbers, icon: <ListOrdered className={icon} />, run: () => editor.commands.wrapInList({ kind: 'ordered' }) },\n    { label: w.checklist, icon: <ListChecks className={icon} />, run: () => editor.commands.wrapInList({ kind: 'task' }) },\n    { label: w.quote, icon: <Quote className={icon} />, run: () => editor.commands.setBlockquote() },\n    { label: w.divider, icon: <Minus className={icon} />, run: () => editor.commands.insertHorizontalRule() },\n    { label: w.table, icon: <TableIcon className={icon} />, run: () => editor.commands.insertTable({ row: 3, col: 3, header: true }) },\n    ...(host.pictures.length ? [{ label: w.image, icon: <ImageIcon className={icon} />, run: () => setPicker('image') }] : []),\n    ...(host.pages.length ? [{ label: w.pageLink, icon: <FileText className={icon} />, run: () => setPicker('link') }] : []),\n  ];\n  const card = preview && host.resolve(preview.href);\n\n  return (\n    <div className={cn('@container relative min-w-0', className)}>\n      {!bare && <h1 className=\"font-kh-display text-[2rem] font-semibold leading-tight tracking-tight [overflow-wrap:anywhere]\">{title}</h1>}\n      {!bare && meta && <p className=\"mt-1 text-kh-caption text-kh-muted\">{meta}</p>}\n      {lead && <div className=\"mt-5\">{lead}</div>}\n      <ProseKit editor={editor}>\n        <div ref={body} onMouseMove={onMove} onMouseLeave={() => setPreview(null)} onClick={onClick}\n          className={cn('kh-doc relative max-w-[46rem] text-[1.0625rem] leading-[1.7] text-kh-ink', !bare && 'mt-4',\n            '[&_.ProseMirror]:outline-none [&_.ProseMirror>*+*]:mt-3 [&_h1]:mt-8 [&_h1]:text-[1.6rem] [&_h1]:font-semibold [&_h2]:mt-7 [&_h2]:text-[1.3rem] [&_h2]:font-semibold [&_h3]:mt-5 [&_h3]:text-[1.1rem] [&_h3]:font-semibold',\n            '[&_a]:text-kh-ink [&_a]:underline [&_a]:decoration-kh-line-strong [&_a]:underline-offset-4 [&_a:hover]:decoration-kh-ink [&_code]:rounded [&_code]:bg-kh-surface-2 [&_code]:px-1 [&_code]:text-[0.9em]',\n            '[&_blockquote]:border-l-2 [&_blockquote]:border-kh-line-strong [&_blockquote]:pl-4 [&_blockquote]:text-kh-ink-2 [&_hr]:border-kh-line [&_img]:rounded-kh-lg [&_img]:border [&_img]:border-kh-line',\n            '[&_table]:text-kh-small [&_td]:border-kh-line [&_th]:border-kh-line [&_th]:bg-kh-surface-2 [&_th]:text-left [&_th]:font-semibold [&_td]:py-2 [&_th]:py-2 [&_td>p]:m-0 [&_th>p]:m-0 [&_td]:[overflow-wrap:break-word] [&_th]:[overflow-wrap:break-word] [&_td]:px-2 [&_th]:px-2 @md:[&_td]:px-3 @md:[&_th]:px-3 [&_.tableWrapper]:rounded-kh [&_table]:min-w-0! [&_table]:w-full! [&_table]:table-auto!',\n            '[&_.prosemirror-flat-list]:my-0.5 [&_.ProseMirror_.is-empty]:before:text-kh-muted')}>\n          <div ref={editor.mount} aria-label={title} />\n        </div>\n        {!readOnly && <>\n          <BlockHandleRoot><BlockHandlePositioner placement=\"left\">\n            <BlockHandlePopup className=\"flex items-center text-kh-muted\">\n              <BlockHandleAdd className=\"inline-flex size-6 cursor-pointer items-center justify-center rounded-kh hover:bg-kh-surface-2 hover:text-kh-ink\" aria-label={w.addBlock}><Plus className={icon} /></BlockHandleAdd>\n              <BlockHandleDraggable className=\"inline-flex size-6 cursor-grab items-center justify-center rounded-kh hover:bg-kh-surface-2 hover:text-kh-ink\" aria-label={w.drag}><GripVertical className={icon} /></BlockHandleDraggable>\n            </BlockHandlePopup>\n          </BlockHandlePositioner></BlockHandleRoot>\n          <InlinePopoverRoot><InlinePopoverPositioner placement=\"top\">\n            <InlinePopoverPopup className=\"z-50 flex items-center gap-0.5 rounded-kh-lg border border-kh-line bg-kh-surface p-1 shadow-kh-3\">\n              <SelectionTools w={w} onComment={onComment} ask={ask} />\n            </InlinePopoverPopup>\n          </InlinePopoverPositioner></InlinePopoverRoot>\n          <AutocompleteRoot regex={/\\/([\\p{L}\\p{N} ]*)$/u}><AutocompletePositioner placement=\"bottom-start\">\n            <AutocompletePopup className=\"z-50 flex max-h-80 w-64 flex-col overflow-y-auto rounded-kh-lg border border-kh-line bg-kh-surface p-1 shadow-kh-3\">\n              <AutocompleteEmpty className=\"px-2 py-1.5 text-kh-small text-kh-muted\">{w.nothing}</AutocompleteEmpty>\n              {slash.map((s) => (\n                <AutocompleteItem key={s.label} onSelect={s.run} className={cn(row, 'hover:bg-transparent data-[highlighted]:bg-kh-surface-2')}>\n                  <span className=\"text-kh-muted\">{s.icon}</span>{s.label}\n                </AutocompleteItem>\n              ))}\n            </AutocompletePopup>\n          </AutocompletePositioner></AutocompleteRoot>\n          <Picker kind={picker} w={w} onClose={() => setPicker(null)} pictures={host.pictures} pages={host.pages}\n            onPicture={(ref) => { editor.commands.insertImage({ src: pictureSrc(ref) }); setPicker(null); refocus(); }}\n            onPage={(p) => {\n              // The title goes in already linked (addLink on an empty cursor links nothing).\n              const { state } = editor.view; const { from, to } = state.selection; const link = state.schema.marks.link;\n              if (link) editor.view.dispatch(state.tr.insertText(p.title, from, to).addMark(from, from + p.title.length, link.create({ href: p.href })));\n              setPicker(null); refocus();\n            }} />\n        </>}\n      </ProseKit>\n      {/* Not when bare (a description inside another page) or short: two dashes beside a note read as a stray drag handle (Klar Portal 21:04). */}\n      {!bare && heads.length > 2 && (\n        <nav aria-label={w.outline} className=\"group/outline absolute right-0 top-24 hidden flex-col items-end @3xl:flex\">\n          <div aria-hidden className=\"flex flex-col items-end gap-1.5 py-2 group-hover/outline:hidden group-focus-within/outline:hidden\">{heads.map((h) => <span key={h.i} className=\"block h-0.5 rounded-full bg-kh-line-strong\" style={{ width: `${18 - h.level * 4}px` }} />)}</div>\n          <ul className=\"sr-only w-52 flex-col rounded-kh-lg border border-kh-line bg-kh-surface p-1.5 shadow-kh-2 group-hover/outline:not-sr-only group-hover/outline:flex group-focus-within/outline:not-sr-only group-focus-within/outline:flex\">\n            {heads.map((h) => <li key={h.i}><button type=\"button\" onClick={() => jump(h.i)} className=\"w-full truncate rounded-kh px-2 py-1 text-left text-kh-small text-kh-ink-2 hover:bg-kh-surface-2 hover:text-kh-ink\" style={{ paddingLeft: `${0.5 + (h.level - 1) * 0.75}rem` }}>{h.text}</button></li>)}\n          </ul>\n        </nav>\n      )}\n      {preview && card && (\n        <div className=\"fixed z-50 w-72 rounded-kh-lg border border-kh-line bg-kh-surface p-3 shadow-kh-3\" style={{ left: preview.x, top: preview.y }} onMouseEnter={() => setPreview(preview)} onMouseLeave={() => setPreview(null)}>\n          <p className=\"font-medium\">{card.title}</p><p className=\"mt-0.5 line-clamp-2 text-kh-small text-kh-muted\">{card.line}</p>\n          <a href={card.href} onClick={(e) => { e.preventDefault(); host.open(preview.href); }} className=\"mt-2 inline-block text-kh-small underline underline-offset-4\">{w.open}</a>\n        </div>\n      )}\n    </div>\n  );\n}\n\nfunction SelectionTools({ w, onComment, ask }: { w: DocPageLabels; onComment?: DocPageProps['onComment']; ask?: DocPageProps['ask'] }) {\n  const [asking, setAsking] = useState(false);\n  const [linking, setLinking] = useState<string | null>(null);\n  // One stable string per state (an object per call would re-render forever: React error 185).\n  const key = useEditorDerivedValue((editor: DocEditor) => [editor.marks.bold.isActive(), editor.marks.italic.isActive(), editor.marks.underline.isActive(),\n    editor.marks.strike.isActive(), editor.marks.code.isActive(), editor.marks.link.isActive()].map(Number).join('') + ([1, 2, 3].find((l) => editor.nodes.heading.isActive({ level: l })) ?? 0));\n  const ed = useEditor<DocExtension>();\n  const s = { bold: key[0] === '1', italic: key[1] === '1', underline: key[2] === '1', strike: key[3] === '1', code: key[4] === '1', link: key[5] === '1', level: Number(key[6]) };\n  const quote = () => { const { from, to } = ed.state.selection; return ed.state.doc.textBetween(from, to, ' '); };\n\n  if (linking !== null) {\n    const done = (href: string) => { if (href.trim()) ed.commands.addLink({ href: href.trim() }); setLinking(null); };\n    return (\n      <form className=\"flex items-center gap-1\" onSubmit={(e) => { e.preventDefault(); done(linking); }}>\n        <input autoFocus type=\"url\" aria-label={w.linkTo} placeholder={w.linkTo} value={linking} onChange={(e) => setLinking(e.target.value)}\n          onKeyDown={(e) => { if (e.key === 'Escape') { e.preventDefault(); setLinking(null); ed.focus(); } }}\n          className=\"h-8 w-60 rounded-kh bg-transparent px-2 text-kh-small outline-none\" />\n        <button type=\"submit\" className=\"h-8 rounded-kh px-2 text-kh-small font-medium hover:bg-kh-surface-2\">{w.link}</button>\n      </form>\n    );\n  }\n  return (\n    <>\n      <select aria-label={w.style} value={s.level} onMouseDown={(e) => e.stopPropagation()} onChange={(e) => { const l = Number(e.target.value); if (l) ed.commands.setHeading({ level: l }); else ed.commands.setParagraph(); }}\n        className=\"h-8 rounded-kh bg-transparent px-1.5 text-kh-small text-kh-ink-2 hover:bg-kh-surface-2\">\n        <option value={0}>{w.text}</option><option value={1}>{w.h1}</option><option value={2}>{w.h2}</option><option value={3}>{w.h3}</option>\n      </select>\n      <span className=\"mx-0.5 h-5 w-px bg-kh-line\" />\n      <Tool label={w.bold} on={s.bold} onClick={() => ed.commands.toggleBold()}><Bold className=\"size-4\" /></Tool>\n      <Tool label={w.italic} on={s.italic} onClick={() => ed.commands.toggleItalic()}><Italic className=\"size-4\" /></Tool>\n      <Tool label={w.underline} on={s.underline} onClick={() => ed.commands.toggleUnderline()}><Underline className=\"size-4\" /></Tool>\n      <Tool label={w.strike} on={s.strike} onClick={() => ed.commands.toggleStrike()}><Strikethrough className=\"size-4\" /></Tool>\n      <Tool label={w.code} on={s.code} onClick={() => ed.commands.toggleCode()}><Code className=\"size-4\" /></Tool>\n      <Tool label={w.link} on={s.link} onClick={() => (s.link ? ed.commands.removeLink() : setLinking(''))}><Link2 className=\"size-4\" /></Tool>\n      {(onComment || ask) && <span className=\"mx-0.5 h-5 w-px bg-kh-line\" />}\n      {onComment && <Tool label={w.comment} onClick={() => onComment(quote())}><MessageSquare className=\"size-4\" /></Tool>}\n      {ask && (\n        <div className=\"relative\">\n          <button type=\"button\" aria-expanded={asking} onMouseDown={(e) => e.preventDefault()} onClick={() => setAsking(!asking)} className=\"inline-flex h-8 pointer-coarse:h-11 items-center gap-1 rounded-kh px-2 text-kh-small text-kh-accent-ink hover:bg-kh-surface-2\"><Sparkles className=\"size-4\" />{w.ask}</button>\n          {asking && (\n            <div className=\"absolute right-0 top-9 z-50 w-48 rounded-kh-lg border border-kh-line bg-kh-surface p-1 shadow-kh-3\">\n              {ask.actions.map((a) => <button key={a} type=\"button\" onMouseDown={(e) => e.preventDefault()} onClick={() => { setAsking(false); ask.onAsk(a, quote()); }} className={row}>{a}</button>)}\n            </div>\n          )}\n        </div>\n      )}\n    </>\n  );\n}\n\nfunction Picker({ kind, w, onClose, pictures, pages, onPicture, onPage }: { kind: null | 'image' | 'link'; w: DocPageLabels; onClose: () => void;\n  pictures: DocHostValue['pictures']; pages: DocHostValue['pages']; onPicture: (ref: string) => void; onPage: (p: DocHostValue['pages'][number]) => void }) {\n  const [q, setQ] = useState('');\n  const list = pages.filter((p) => p.title.toLowerCase().includes(q.toLowerCase())).slice(0, 12);\n  return (\n    <Dialog open={!!kind} onOpenChange={(o) => !o && onClose()} title={kind === 'image' ? w.image : w.pageLink} className=\"w-[min(36rem,calc(100vw-2rem))]\">\n      <div className=\"min-h-0 overflow-y-auto px-5 pb-5\">\n        {kind === 'image' ? (\n          <ul className=\"grid grid-cols-3 gap-2\">{pictures.map((p) => <li key={p.ref}><button type=\"button\" onClick={() => onPicture(p.ref)} className=\"block w-full overflow-hidden rounded-kh border border-kh-line hover:border-kh-accent\"><div className=\"aspect-[4/3] [&>*]:size-full\">{p.thumb}</div><p className=\"truncate px-1.5 py-1 text-left text-kh-caption\">{p.title}</p></button></li>)}</ul>\n        ) : (\n          <>\n            <input autoFocus aria-label={w.findPage} value={q} onChange={(e) => setQ(e.target.value)} placeholder={w.findPage} className=\"mb-2 h-10 pointer-coarse:h-11 w-full rounded-kh border border-kh-line bg-kh-surface px-3 text-kh-small outline-none focus:border-kh-accent\" />\n            <ul className=\"flex flex-col\">{list.map((p) => <li key={p.href}><button type=\"button\" onClick={() => onPage(p)} className={cn(row, 'justify-between')}><span className=\"truncate\">{p.title}</span><span className=\"shrink-0 text-kh-caption text-kh-muted\">{p.line}</span></button></li>)}</ul>\n          </>\n        )}\n      </div>\n    </Dialog>\n  );\n}\n\nexport interface DocPanelProps extends DocPageProps {\n  open: boolean;\n  onOpenChange: (open: boolean) => void;\n  /** Where the page opens full size: shows the full-page button. */\n  fullHref?: string;\n  /** What Copy link copies. Default: the address in the window. */\n  link?: string;\n  /** Shows Star; the caller keeps whether it is starred. */\n  star?: { on: boolean; onChange(on: boolean): void };\n  /** Extra lines at the top of the … menu (moving a file between folders). */\n  menu?: { label: string; onSelect(): void }[];\n  /** Shows Version history in the … menu. */\n  versions?: { version: number; note: string; when: string }[];\n  /** The whole stored file for Markdown source, when the page edits only part of it (under frontmatter). */\n  source?: { value: string; onChange: (markdown: string) => void };\n}\n\n/** A DocPage in a side panel, with the page's own header. */\nexport function DocPanel({ open, onOpenChange, fullHref, link, star, versions, source: src, menu = [], ...page }: DocPanelProps) {\n  const w = { ...EN, ...page.labels };\n  const [more, setMore] = useState(false);\n  const [source, setSource] = useState(false);\n  const [history, setHistory] = useState(false);\n  const download = () => {\n    const url = URL.createObjectURL(new Blob([src ? src.value : page.value], { type: 'text/markdown' }));\n    const a = document.createElement('a'); a.href = url; a.download = `${page.title.replace(/[\\\\/:*?\"<>|]+/g, '-')}.md`; a.click();\n    setTimeout(() => URL.revokeObjectURL(url), 0);\n  };\n  const header = (\n    // One padding for the page (px-6, @md px-12); the bar's is 8 px less, the inset of its icon buttons, so the icons sit on\n    // the text's left and right edges (Felix 2026-10-21 16:5x \"Gap alignment issues\").\n    <div className=\"@container shrink-0\"><div className=\"flex h-14 items-center justify-between px-4 @md:px-10\">\n      <div className=\"flex gap-0.5\">\n        <button type=\"button\" aria-label={w.close} title={w.close} className={tool} onClick={() => onOpenChange(false)}><ChevronsRight className=\"size-4\" /></button>\n        {fullHref && <a aria-label={w.fullPage} title={w.fullPage} className={tool} href={fullHref}><Maximize2 className=\"size-4\" /></a>}\n      </div>\n      <div className=\"relative flex gap-0.5\">\n        <button type=\"button\" aria-label={w.copyLink} title={w.copyLink} className={tool} onClick={() => { void navigator.clipboard?.writeText(link ?? location.href); toast(w.copied); }}><LinkIcon className=\"size-4\" /></button>\n        {star && <button type=\"button\" aria-label={w.star} title={w.star} aria-pressed={star.on} className={cn(tool, star.on && 'text-kh-ink [&_svg]:fill-current')} onClick={() => star.onChange(!star.on)}><Star className=\"size-4\" /></button>}\n        <button type=\"button\" aria-label={w.more} title={w.more} aria-expanded={more} className={tool} onClick={() => setMore(!more)}><MoreHorizontal className=\"size-4\" /></button>\n        {more && (\n          <div className=\"absolute right-0 top-9 z-30 w-52 rounded-kh-lg border border-kh-line bg-kh-surface p-1 shadow-kh-3\">\n            {menu.map((m) => <button key={m.label} type=\"button\" className={row} onClick={() => { setMore(false); m.onSelect(); }}>{m.label}</button>)}\n            <button type=\"button\" className={row} onClick={() => { setMore(false); setSource(true); }}>{w.source}</button>\n            {versions && versions.length > 0 && <button type=\"button\" className={row} onClick={() => { setMore(false); setHistory(true); }}>{w.history}</button>}\n            <button type=\"button\" className={row} onClick={() => { setMore(false); download(); }}>{w.download}</button>\n          </div>\n        )}\n      </div>\n    </div></div>\n  );\n  return (\n    <Sheet open={open} onOpenChange={onOpenChange} side=\"right\" title={page.title} header={header} flush className=\"w-[min(52rem,100vw)]\">\n      <div className=\"@container\"><div className=\"px-6 pb-10 pt-2 @md:px-12\"><DocPage {...page} /></div></div>\n      <Dialog open={source} onOpenChange={setSource} title={w.source} description={w.sourceNote} className=\"w-[min(48rem,calc(100vw-2rem))]\">\n        <div className=\"min-h-0 overflow-y-auto px-5 pb-5\"><Textarea aria-label={w.source} rows={18} className=\"font-kh-mono text-kh-small\" value={src ? src.value : page.value} readOnly={!src && !page.onChange} onChange={(e) => (src ? src.onChange(e.target.value) : page.onChange?.(e.target.value))} /></div>\n      </Dialog>\n      {versions && versions.length > 0 && (\n        <Dialog open={history} onOpenChange={setHistory} title={w.history} className=\"w-[min(32rem,calc(100vw-2rem))]\">\n          <ul className=\"min-h-0 overflow-y-auto px-5 pb-5\">\n            {versions.map((v) => (\n              <li key={v.version} className=\"flex items-baseline justify-between gap-3 py-2 text-kh-small\"><span><span className=\"font-medium\">v{v.version}</span> · {v.note}</span><span className=\"text-kh-caption text-kh-muted\">{v.when}</span></li>\n            ))}\n          </ul>\n        </Dialog>\n      )}\n    </Sheet>\n  );\n}\n\nexport default DocPage;\n"
    },
    {
      "path": "src/ui/doc-page.markdown.ts",
      "type": "registry:file",
      "target": "components/klarhimmel/ui/doc-page.markdown.ts",
      "content": "// Markdown <-> ProseMirror JSON for DocPage: the subset a page stores (headings 1-3, paragraphs, bulleted, numbered and task\n// lists with nesting, quotes, dividers, images, GFM tables with a header row, bold, italic, underline, strike, code, links). Pure: no DOM, no editor.\n// A smaller sibling of rich-text-editor's remark pipeline, kept small because DocPage loads it with every page.\n\ntype Mark = { type: string; attrs?: Record<string, unknown> };\nexport type DocJSON = { type: string; content?: DocJSON[]; marks?: Mark[]; text?: string; attrs?: Record<string, unknown> };\n\nfunction inlineToJSON(text: string): DocJSON[] {\n  const out: DocJSON[] = [];\n  const re = /(\\*\\*([^*]+)\\*\\*|~~([^~]+)~~|<u>([^<]+)<\\/u>|`([^`]+)`|\\*([^*]+)\\*|_([^_]+)_|\\[([^\\]]+)\\]\\(([^)]+)\\))/g;\n  let last = 0; let m: RegExpExecArray | null;\n  const push = (t: string, marks?: Mark[]) => { if (t) out.push({ type: 'text', text: t, ...(marks?.length ? { marks } : {}) }); };\n  while ((m = re.exec(text))) {\n    push(text.slice(last, m.index));\n    if (m[2]) push(m[2], [{ type: 'bold' }]);\n    else if (m[3]) push(m[3], [{ type: 'strike' }]);\n    else if (m[4]) push(m[4], [{ type: 'underline' }]);\n    else if (m[5]) push(m[5], [{ type: 'code' }]);\n    else if (m[6] || m[7]) push((m[6] ?? m[7])!, [{ type: 'italic' }]);\n    else if (m[8]) push(m[8], [{ type: 'link', attrs: { href: m[9] } }]);\n    last = m.index + m[0].length;\n  }\n  push(text.slice(last));\n  return out;\n}\nconst para = (text: string): DocJSON => ({ type: 'paragraph', content: inlineToJSON(text) });\n\n/** One GFM table row's cells: outer pipes dropped, an escaped \\| kept as a pipe. */\nconst cells = (line: string): string[] =>\n  line.trim().replace(/^\\|/, '').replace(/(?<!\\\\)\\|$/, '').split(/(?<!\\\\)\\|/).map((c) => c.trim().replace(/\\\\\\|/g, '|'));\nconst isRow = (line: string) => /^\\s*\\|.*\\|\\s*$/.test(line);\nconst isRule = (line: string) => /^\\s*\\|?\\s*:?-{3,}:?\\s*(\\|\\s*:?-{3,}:?\\s*)*\\|?\\s*$/.test(line);\nconst cell = (type: string, text: string): DocJSON => ({ type, attrs: { colspan: 1, rowspan: 1, colwidth: null }, content: [para(text)] });\n\n/** Markdown to the editor's document. `pictureSrc` turns a stored picture reference into an address the page can show. */\nexport function markdownToDoc(md: string, pictureSrc: (ref: string) => string = (r) => r): DocJSON {\n  const lines = md.replace(/\\r/g, '').split('\\n');\n  const blocks: DocJSON[] = [];\n  let buf: string[] = [];\n  const flush = () => { if (buf.length) { blocks.push(para(buf.join(' '))); buf = []; } };\n  // A list item: kind, checked, text, and its depth from the indent (two spaces a level).\n  const stack: { depth: number; node: DocJSON }[] = [];\n  for (let k = 0; k < lines.length; k++) {\n    const line = lines[k]!.trimEnd();\n    // A GFM table: a row of cells, the --- rule, then rows until a line that is not one; short rows are filled, long ones cut.\n    if (isRow(line) && k + 1 < lines.length && isRule(lines[k + 1]!)) {\n      flush(); stack.length = 0;\n      const head = cells(line);\n      const rows: DocJSON[] = [{ type: 'tableRow', content: head.map((t) => cell('tableHeaderCell', t)) }];\n      k += 2;\n      for (; k < lines.length && isRow(lines[k]!); k++) {\n        const r = cells(lines[k]!);\n        rows.push({ type: 'tableRow', content: head.map((_, i) => cell('tableCell', r[i] ?? '')) });\n      }\n      k--;\n      blocks.push({ type: 'table', content: rows });\n      continue;\n    }\n    const li = /^(\\s*)([-*]|\\d+\\.)\\s+(?:\\[( |x|X)\\]\\s+)?(.*)$/.exec(line);\n    if (li) {\n      flush();\n      const depth = Math.floor(li[1]!.length / 2);\n      const kind = li[3] !== undefined ? 'task' : /\\d/.test(li[2]!) ? 'ordered' : 'bullet';\n      const node: DocJSON = { type: 'list', attrs: { kind, checked: li[3] === 'x' || li[3] === 'X', order: null, collapsed: false }, content: [para(li[4]!)] };\n      while (stack.length && stack[stack.length - 1]!.depth >= depth) stack.pop();\n      if (stack.length) stack[stack.length - 1]!.node.content!.push(node); else blocks.push(node);\n      stack.push({ depth, node });\n      continue;\n    }\n    stack.length = 0;\n    if (!line.trim()) { flush(); continue; }\n    const h = /^(#{1,3})\\s+(.*)$/.exec(line);\n    const img = /^!\\[([^\\]]*)\\]\\(([^)]+)\\)$/.exec(line.trim());\n    if (h) { flush(); blocks.push({ type: 'heading', attrs: { level: h[1]!.length }, content: inlineToJSON(h[2]!) }); }\n    else if (/^(-{3,}|\\*{3,})$/.test(line.trim())) { flush(); blocks.push({ type: 'horizontalRule' }); }\n    else if (line.startsWith('> ')) { flush(); blocks.push({ type: 'blockquote', content: [para(line.slice(2))] }); }\n    else if (img) { flush(); blocks.push({ type: 'image', attrs: { src: pictureSrc(img[2]!) } }); }\n    else buf.push(line.trim());\n  }\n  flush();\n  return { type: 'doc', content: blocks.length ? blocks : [{ type: 'paragraph' }] };\n}\n\n/** One block's words as Markdown (also the outline's text, once the marks are stripped). */\nexport function inlineToMarkdown(nodes: DocJSON[] = []): string {\n  return nodes.map((n) => {\n    if (n.type === 'hardBreak') return '  \\n';\n    let t = n.text ?? '';\n    for (const m of n.marks ?? []) {\n      if (m.type === 'bold') t = `**${t}**`;\n      else if (m.type === 'italic') t = `*${t}*`;\n      else if (m.type === 'strike') t = `~~${t}~~`;\n      else if (m.type === 'underline') t = `<u>${t}</u>`;\n      else if (m.type === 'code') t = `\\`${t}\\``;\n      else if (m.type === 'link') t = `[${t}](${String(m.attrs?.href ?? '')})`;\n    }\n    return t;\n  }).join('');\n}\n\n/** The editor's document to Markdown. `pictureRef` maps a shown picture address back to its stored reference. */\nexport function docToMarkdown(doc: DocJSON, pictureRef: (src: string) => string = (s) => s): string {\n  const out: string[] = [];\n  const list = (n: DocJSON, depth: number, i: number): string[] => {\n    const a = n.attrs ?? {};\n    const pad = '  '.repeat(depth);\n    const bullet = a.kind === 'ordered' ? `${i + 1}.` : '-';\n    const box = a.kind === 'task' ? (a.checked ? '[x] ' : '[ ] ') : '';\n    const [first, ...rest] = n.content ?? [];\n    const lines = [`${pad}${bullet} ${box}${inlineToMarkdown(first?.content)}`];\n    let k = 0;\n    for (const c of rest) lines.push(...(c.type === 'list' ? list(c, depth + 1, k++) : [`${pad}  ${inlineToMarkdown(c.content)}`]));\n    return lines;\n  };\n  // A run of list items is one Markdown list; a switch between numbered and bulleted starts a new one (else it would merge).\n  let run: string[] = []; let n = 0; let ordered: boolean | null = null;\n  const end = () => { if (run.length) { out.push(run.join('\\n')); run = []; n = 0; ordered = null; } };\n  for (const b of doc.content ?? []) {\n    if (b.type === 'list') {\n      const o = b.attrs?.kind === 'ordered';\n      if (ordered !== null && o !== ordered) end();\n      ordered = o; run.push(...list(b, 0, n++)); continue;\n    }\n    end();\n    if (b.type === 'heading') out.push(`${'#'.repeat(Number(b.attrs?.level ?? 1))} ${inlineToMarkdown(b.content)}`);\n    else if (b.type === 'blockquote') out.push((b.content ?? []).map((p) => `> ${inlineToMarkdown(p.content)}`).join('\\n'));\n    else if (b.type === 'horizontalRule') out.push('---');\n    else if (b.type === 'table') {\n      const text = (c: DocJSON) => (c.content ?? []).map((p) => inlineToMarkdown(p.content)).join(' ').replace(/\\|/g, '\\\\|').replace(/\\n+/g, ' ');\n      const rows = (b.content ?? []).map((r) => `| ${(r.content ?? []).map(text).join(' | ')} |`);\n      if (rows.length) out.push([rows[0], `|${(b.content![0]!.content ?? []).map(() => ' --- ').join('|')}|`, ...rows.slice(1)].join('\\n'));\n    }\n    else if (b.type === 'image') out.push(`![](${pictureRef(String(b.attrs?.src ?? ''))})`);\n    else if (b.type === 'paragraph') { const t = inlineToMarkdown(b.content); if (t) out.push(t); }\n  }\n  end();\n  return out.join('\\n\\n') + '\\n';\n}\n"
    }
  ]
}
