{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "editing",
  "type": "registry:lib",
  "title": "Editing slots",
  "description": "Text and Media slots every block renders copy and images through. Outside an editor they render plain elements.",
  "dependencies": [],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/editing.tsx",
      "type": "registry:file",
      "target": "components/klarhimmel/editing.tsx",
      "content": "// Editing slots. Blocks render every piece of editable content through these, so the same block\n// code is static in production and inline-editable in the canvas (which provides EditingContext).\nimport { createContext, createElement, useContext, type ComponentType, type ElementType, type ReactNode } from 'react';\nimport { hasInline, inline } from './lib/inline';\nimport { prose } from './lib/prose';\n\n/** Path of a prop inside the block's props: ['items', 2, 'title']. */\nexport type PropPath = (string | number)[];\n\nexport interface TextSlot {\n  path: PropPath;\n  value: string;\n  as: ElementType;\n  className?: string;\n  /** Allows line breaks (stored as \\n). */\n  multiline?: boolean;\n  placeholder?: string;\n}\n\nexport interface MediaValue {\n  /** https:// or site-relative URL. Empty = placeholder. */\n  src?: string;\n  /** The same picture for dark mode (https:// or site-relative). Both are drawn; the theme's mode attribute shows one and hides the other. */\n  srcDark?: string;\n  alt: string;\n}\n\nexport interface EditingApi {\n  /** Render an editable text slot. */\n  text(slot: TextSlot): ReactNode;\n}\n\n/** Provided by the canvas; absent in production. */\nexport const EditingContext = createContext<EditingApi | null>(null);\n\n/** A section worked on as a composition (the parts prototype, an editor): the part filling each of its slots, by the slot's path\n *  ('primary', 'title'). undefined keeps the block's own part, null empties the slot. Absent in production, where nothing changes. */\nexport interface SlotsApi { partAt(path: PropPath): string | null | undefined }\nexport const SlotsContext = createContext<SlotsApi | null>(null);\nexport const slotKey = (path: PropPath) => path.join('.');\n/** A slot's marks while its section is worked on: its path, the kind of part it holds and the version filling it (`set` when the\n *  section's data chose it rather than the block). */\nexport function slotMarks(api: SlotsApi | null, path: PropPath, tag: string, version: string | undefined, set: boolean): Record<string, string | undefined> {\n  return api ? { 'data-kh-slot': slotKey(path), 'data-kh-tag': tag, 'data-kh-v': version, 'data-kh-set': set ? version : undefined } : {};\n}\n/** An emptied slot while its section is worked on: a dotted place its part can be added back to. Nothing in production. */\nexport function EmptySlotMark({ path, tag }: { path: PropPath; tag: string }) {\n  return createElement('span', { 'data-kh-slot': slotKey(path), 'data-kh-tag': tag, 'data-kh-empty': '', className: 'kh-slot-empty' });\n}\n/** The version a heading or paragraph is drawn at, read from its type step. */\nconst STEP: Record<string, [string, string][]> = {\n  heading: [['text-kh-display', 'display'], ['text-kh-title', 'page'], ['text-kh-heading', 'section']],\n  paragraph: [['text-kh-lead', 'lead'], ['text-kh-body', 'body'], ['text-kh-small', 'small'], ['text-kh-caption', 'caption']],\n};\nconst ownVersion = (tag: string, className: string | undefined) => { const hit = STEP[tag]?.find(([c]) => className?.split(/\\s+/).includes(c)); return hit ? `${tag}/${hit[1]}` : undefined; };\n\n/**\n * The level of the block's own title when the page needs it to be the page's h1 (or not to be): a block whose title is an h2\n * can carry the page's h1 with `headingLevel: '1'`, and a hero whose title is an h1 can give it up with '2'. Only the\n * top-level `title` slot follows it; headings inside the block (card titles, steps) never change. Blocks get it from their\n * own `headingLevel` prop: every block module's default export is wrapped in `withHeadingLevel`, so it works through the BLOCKS\n * list, `<Block>` and a direct `import X from '@klarhimmel/ui/blocks/x'` alike. A parent `<HeadingLevel>` applies when the prop is absent.\n */\nexport const HeadingLevelContext = createContext<{ level: '1' | '2'; slot: string } | undefined>(undefined);\n/** `slot` is the top-level text field that follows the level ('title' unless the spec names another `headingSlot`). */\nexport function HeadingLevel({ level, slot = 'title', children }: { level: '1' | '2' | undefined; slot?: string; children?: ReactNode }) {\n  return createElement(HeadingLevelContext.Provider, { value: level ? { level, slot } : undefined }, children);\n}\n/** Wraps a block component so its own `headingLevel` prop sets the level of its title. */\nexport function withHeadingLevel<P extends { props: unknown }>(C: ComponentType<P>, slot: string = 'title'): ComponentType<P & { props: P['props'] & { headingLevel?: '1' | '2' | 1 | 2 } }> {\n  const W = (p: P & { props: P['props'] & { headingLevel?: '1' | '2' | 1 | 2 } }) => {\n    const level = normalizeHeadingLevel((p.props as { headingLevel?: unknown } | undefined)?.headingLevel);\n    return level ? createElement(HeadingLevel, { level, slot }, createElement(C, p)) : createElement(C, p);\n  };\n  W.displayName = C.displayName || C.name;\n  return W;\n}\n/** `headingLevel` as it may arrive (a number from a page file, a string from the panel) to '1' | '2', else undefined. */\nexport const normalizeHeadingLevel = (v: unknown): '1' | '2' | undefined => (v === 1 || v === '1' ? '1' : v === 2 || v === '2' ? '2' : undefined);\n\nconst LONG_RUN = /\\S{24,}/;\n\n/** `rich`: **bold**, `code` and [links](https://…) in the value are drawn as such outside the editor (the editor shows the raw text).\n *  rich=\"site\": site content, where a link to the site's own page (/studio/) is an anchor too (reports keep paths as text). */\nexport function Text({ path, value, as: asGiven = 'span', className, multiline, placeholder, rich, markdown }: Omit<TextSlot, 'as'> & { as?: ElementType; rich?: boolean | 'site'; markdown?: boolean }) {\n  const api = useContext(EditingContext);\n  const heading = useContext(HeadingLevelContext);\n  const isTitle = !!heading && path.length === 1 && path[0] === heading.slot;\n  const as: ElementType = heading && isTitle && (asGiven === 'h1' || asGiven === 'h2') ? `h${heading.level}` : asGiven;\n  const slots = useContext(SlotsContext);\n  if (api) return api.text({ path, value, as, className, multiline, placeholder });\n  // Headings and paragraphs are slots of their section; a span is part of something larger (a button's label).\n  const tag = typeof as === 'string' && /^h[1-6]$/.test(as) ? 'heading' : as === 'p' ? 'paragraph' : undefined;\n  const part = tag ? slots?.partAt(path) : undefined;\n  if (tag && part === null) return slots ? createElement(EmptySlotMark, { path, tag }) : null;\n  // Emptied text is dropped rather than rendered empty (an empty heading is announced and breaks the outline; an empty span names nothing).\n  if (!value.trim()) return null;\n  // One unbroken run (a URL, a long word) wraps instead of pushing its box wider than the page.\n  const cls = LONG_RUN.test(value) ? [className, '[overflow-wrap:anywhere]'].filter(Boolean).join(' ') : className;\n  const marks = tag ? slotMarks(slots, path, tag, part ?? ownVersion(tag, className), !!part) : {};\n  return createElement(as, { className: cls, ...marks }, markdown ? prose(value) : rich && hasInline(value) ? inline(value, { site: rich === 'site' }) : value);\n}\n\nconst SAFE_SRC = /^(https:\\/\\/|\\/(?!\\/))/;\n/** A picture embedded in the page itself (kh-report): a base64 image data address of a raster or svg type. Only where a block asks for it. */\nconst DATA_IMAGE = /^data:image\\/(png|jpeg|gif|webp|svg\\+xml);base64,[A-Za-z0-9+/=]+$/;\n\n/** Whether Media will show this address: https, or a path on the same site. Anything else renders the placeholder. */\nexport const isSafeSrc = (src: string): boolean => SAFE_SRC.test(src);\n\n/** Modern-format twins of one picture, from a host that has them (`setMediaTwins`): `<source>` entries in order of preference, and the picture's pixel size. */\nexport interface MediaTwins { sources: { type: string; srcSet: string }[]; width: number; height: number }\nlet twinsOf: ((src: string) => MediaTwins | undefined) | undefined;\n/** The directory site tells Media which pictures have AVIF/WebP twins. The same function runs on the server and in the browser, so the markup is the same. */\nexport const setMediaTwins = (fn: ((src: string) => MediaTwins | undefined) | undefined) => { twinsOf = fn; };\n\n/**\n * An image, or a themed placeholder when there is no (safe) src. The wireframe theme always shows the placeholder.\n * With `srcDark` both images are in the page and CSS picks one by the theme's `data-kh-mode` (not by the OS setting, which the mode may override):\n * a hidden `<img>` is display:none, so it is out of the accessibility tree and, being lazy, is not fetched until it is shown.\n * `allowData` lets a src be an embedded base64 image (a one-file report); everything else keeps to https and site paths.\n * `priority`: the picture is likely the largest thing on the first screen (the first cards of a grid, a page's hero picture): it loads at once and ahead of\n * the rest instead of lazily. The dark twin stays lazy.\n */\nexport function Media({ path, value, ratio = '16 / 10', className, allowData, priority }: { path: PropPath; value: MediaValue; ratio?: string; className?: string; allowData?: boolean; priority?: boolean }) {\n  const slots = useContext(SlotsContext);\n  const part = slots?.partAt(path);\n  if (part === null) return createElement(EmptySlotMark, { path, tag: 'image' });\n  const ok =(v: string | undefined) => (v && (SAFE_SRC.test(v) || (allowData && DATA_IMAGE.test(v))) ? v : undefined);\n  const src = ok(value.src);\n  const dark = src ? ok(value.srcDark) : undefined;\n  // One picture: a <picture> with its twins when the host has them (width/height are the picture's own; the CSS still sizes the box), else a plain <img>.\n  const pic = (url: string, loading: 'eager' | 'lazy', mark: Record<string, string | undefined>, fetchPriority?: 'high') => {\n    const tw = twinsOf?.(url);\n    const img = <img src={url} alt={value.alt} loading={loading} fetchPriority={fetchPriority} decoding=\"async\" width={tw?.width} height={tw?.height} {...mark} />;\n    return tw ? <picture {...mark}>{tw.sources.map((x) => <source key={x.type} type={x.type} srcSet={x.srcSet} />)}{img}</picture> : img;\n  };\n  const first = src && priority ? twinsOf?.(src) : undefined;\n  return (\n    <div className={['kh-media', className].filter(Boolean).join(' ')} data-kh-ratio={ratio.replace(/\\s/g, '')} data-kh-media={src ? 'image' : 'placeholder'} data-kh-media-dark={dark ? '' : undefined}\n      {...slotMarks(slots, path, 'image', part ?? 'image/picture', !!part)}>\n      {src ? (\n        <>\n          {/* React does not preload an <img> inside a <picture>: the priority picture's first twin is preloaded here (a browser skips a type it cannot decode). */}\n          {first && <link rel=\"preload\" as=\"image\" href={first.sources[0]!.srcSet} type={first.sources[0]!.type} fetchPriority=\"high\" />}\n          {pic(src, priority ? 'eager' : 'lazy', { 'data-kh-light': dark ? '' : undefined }, priority ? 'high' : undefined)}\n          {dark && pic(dark, 'lazy', { 'data-kh-dark': '' })}\n        </>\n      ) : <span className=\"sr-only\">{value.alt}</span>}\n    </div>\n  );\n}\n"
    },
    {
      "path": "src/lib/inline.tsx",
      "type": "registry:file",
      "target": "components/klarhimmel/lib/inline.tsx",
      "content": "// Inline markup for report text: **bold**, `code` and [label](https://link). Nothing else is interpreted, and a link\n// whose address is not safe (javascript:, data:, a file path) is drawn as its label, never as an anchor. Site content (a blog\n// post, a page's prose) passes { site: true }: a root-relative link to the site's own page (/studio/) is an anchor there too.\nimport { createElement, type ReactNode } from 'react';\n\nconst TOKEN = /`([^`\\n]+)`|\\*\\*([^*\\n]+(?:\\*(?!\\*)[^*\\n]*)*)\\*\\*|(!?)\\[([^\\]\\n]*)\\]\\(([^)\\s]+)\\)/g;\nconst SAFE = /^(https?:\\/\\/|mailto:|tel:|#)/i;\n// A page of the same site: one leading slash, never // (another host) and never a machine path.\nconst SITE = /^\\/(?!\\/)(?!(?:Users|private|tmp|var|home|etc|opt)\\/)/;\nexport const siteSafe = (href: string) => SAFE.test(href) || SITE.test(href);\n// A file beside a report (files/brief.pdf): relative, with an extension, never .. and never a scheme. Sessions stores and serves these with\n// the page (Felix 10-21: document links clickable).\nconst BESIDE = /^(?![a-z][\\w+.-]*:)(?!\\.\\.?\\/)[\\w-][\\w.-]*(?:\\/[\\w-][\\w.-]*)*\\.[a-z0-9]{1,5}$/i;\nconst reportSafe = (href: string) => SAFE.test(href) || BESIDE.test(href);\n\n/** Splits a string into text, <strong>, <code> and <a> nodes. */\nexport function inline(value: string, { site = false }: { site?: boolean } = {}): ReactNode[] {\n  const out: ReactNode[] = [];\n  let at = 0;\n  let key = 0;\n  for (const m of value.matchAll(TOKEN)) {\n    if (m.index! > at) out.push(value.slice(at, m.index));\n    if (m[1] !== undefined) out.push(createElement('code', { key: key++, className: 'rounded-kh-sm bg-kh-surface-2 px-1 py-0.5 font-kh-mono text-[0.9em] [overflow-wrap:anywhere]' }, m[1]));\n    else if (m[2] !== undefined) out.push(createElement('strong', { key: key++, className: 'font-semibold' }, inline(m[2], { site })));\n    // A picture inside a sentence is its alt text; a paragraph that is only a picture is a figure (prose.tsx).\n    else if (m[3] === '!') out.push(m[4]);\n    else if (site ? siteSafe(m[5]!) : reportSafe(m[5]!)) out.push(createElement('a', { key: key++, href: m[5], rel: 'noopener noreferrer', className: 'text-kh-ink underline [text-decoration-color:var(--kh-edge)] underline-offset-4 hover:text-kh-accent-ink hover:decoration-current [overflow-wrap:anywhere]' }, m[4]));\n    else out.push(m[4]);\n    at = m.index! + m[0].length;\n  }\n  if (at < value.length) out.push(value.slice(at));\n  return out;\n}\n\n/** True when the string has any inline markup (so plain strings keep the plain path). */\nexport const hasInline = (value: string) => /`[^`\\n]+`|\\*\\*[^*\\n]+\\*\\*|\\[[^\\]\\n]*\\]\\([^)\\s]+\\)/.test(value);\n"
    },
    {
      "path": "src/lib/prose.tsx",
      "type": "registry:file",
      "target": "components/klarhimmel/lib/prose.tsx",
      "content": "import { createElement, type ReactNode } from 'react';\nimport { inline, siteSafe } from './inline';\n\n/** Small safe Markdown renderer for site content: paragraphs, h2/h3, lists, GFM tables, links to the site's own pages, and a paragraph\n *  that is only ![alt](src) as a picture in the reading column. Raw HTML remains text. */\n\n// A GFM table (website 11-05 18:0x, WEB-28's price table; UI-35): a header row, the --- rule, then rows. Same reading as doc-page.markdown.ts.\nconst cells = (line: string) => 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);\nfunction table(lines: string[], key: number): ReactNode {\n  const head = cells(lines[0]!);\n  const rows = lines.slice(2).filter(isRow).map((l) => { const r = cells(l); return head.map((_, i) => r[i] ?? ''); });\n  // the box scrolls sideways on a phone, never the page; a keyboard reaches it (tabIndex) and a reader hears what it is\n  return createElement('div', { key, role: 'region', 'aria-label': 'Table', tabIndex: 0, className: 'mb-6 max-w-full overflow-x-auto rounded-kh-lg border border-kh-line focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--kh-focus)' },\n    createElement('table', { className: 'w-full min-w-[32rem] border-collapse text-left text-kh-small' },\n      createElement('thead', null, createElement('tr', { className: 'bg-kh-surface-2' }, head.map((h, i) => createElement('th', { key: i, scope: 'col', className: 'border-b border-kh-line px-3 py-2 font-semibold text-kh-ink' }, inline(h, { site: true }))))),\n      createElement('tbody', null, rows.map((r, j) => createElement('tr', { key: j, className: 'border-b border-kh-line last:border-0' }, r.map((c, i) => createElement('td', { key: i, className: 'px-3 py-2 align-top text-kh-ink-2' }, inline(c, { site: true }))))))));\n}\nexport function prose(value: string): ReactNode[] {\n  return value.split(/\\n\\s*\\n/).filter(p => p.trim()).map((block, key) => {\n    const heading = block.match(/^(#{2,3})\\s+([^\\n]+)$/);\n    // One scale for long reads (klarholding's manifesto, Felix 10-23 23:2x): ## a section title with room above, ### a smaller head close to\n    // its text, a picture opens its section. Blocks carry only a bottom margin, so a heading sits on the text it names.\n    if (heading) return heading[1]!.length === 2\n      ? createElement('h2', { key, className: 'mt-14 mb-4 text-[clamp(calc(var(--kh-size)*1.625),1.2rem+1.2cqi,calc(var(--kh-size)*2.125))] font-semibold leading-[1.15] tracking-[-0.02em] text-balance text-kh-ink first:mt-0 @3xl:mt-20 [figure+&]:mt-10' }, inline(heading[2]!, { site: true }))\n      : createElement('h3', { key, className: 'mt-9 mb-1.5 text-kh-lead font-semibold leading-snug text-kh-ink first:mt-0' }, inline(heading[2]!, { site: true }));\n    const picture = block.trim().match(/^!\\[([^\\]\\n]*)\\]\\(([^)\\s]+)\\)$/);\n    if (picture && siteSafe(picture[2]!) && !/^(mailto:|tel:|#)/i.test(picture[2]!)) {\n      return createElement('figure', { key, className: 'mt-16 mb-8 first:mt-0 @3xl:mt-24' }, createElement('img', { src: picture[2], alt: picture[1], loading: 'lazy', decoding: 'async', className: 'aspect-3/2 w-full rounded-kh-lg bg-kh-surface-2 object-cover' }));\n    }\n    const lines = block.split('\\n');\n    if (lines.length >= 2 && isRow(lines[0]!) && isRule(lines[1]!)) return table(lines, key);\n    if (lines.every(line => /^[-*]\\s+/.test(line))) return createElement('ul', { key, className: 'mb-5 list-disc space-y-2 ps-6' }, lines.map((line, i) => createElement('li', { key: i }, inline(line.replace(/^[-*]\\s+/, ''), { site: true }))));\n    return createElement('p', { key, className: 'mb-5 whitespace-pre-line' }, inline(block, { site: true }));\n  });\n}\n"
    }
  ]
}
