{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "share-image",
  "type": "registry:ui",
  "title": "Share Image",
  "description": "The picture a link unfurls into on X, LinkedIn, Facebook, WhatsApp, iMessage and Slack: a kicker, the page's title, a line of description, and one optional piece of evidence (a big number, a few bars, or anything you draw), with your mark at the top and…",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "marketing",
    "pattern"
  ],
  "dependencies": [],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/patterns/share-image.tsx",
      "target": "components/ui/patterns/share-image.tsx",
      "type": "registry:ui",
      "content": "import type { CSSProperties, ReactNode } from 'react';\n\n// @interlace/share-image v1.0.0 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/share-image\n// What changed since: https://ds.interlace.tools/c/share-image#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — ShareImage\n *\n * The picture a link unfurls into on X, LinkedIn, Facebook, WhatsApp,\n * iMessage and Slack: a kicker, the page's title, a line of description, and\n * one optional piece of evidence (a big number, a few bars, or anything you\n * draw), with your mark at the top and your address at the foot.\n *\n * ## Painted by an image renderer\n *\n * The tree uses only what Satori (Next's `ImageResponse`, `@vercel/og`)\n * paints: flex boxes and inline styles, no classes and no CSS variables. So\n * the theme arrives as a value, built once from your own theme file:\n *\n *   ```tsx\n *   // app/opengraph-image.tsx\n *   import { ImageResponse } from 'next/og';\n *   import { ShareImage } from '@/components/ui/patterns/share-image';\n *   import { SHARE_IMAGE_SIZES, themeFromCss } from '@/components/ui/patterns/share-image-model';\n *\n *   const theme = themeFromCss(await readFile('app/theme.css', 'utf8'), {\n *     fontHeading: 'Newsreader',\n *     fontBody: 'Inter',\n *   });\n *   export const size = SHARE_IMAGE_SIZES.og;\n *   export default function Image() {\n *     return new ImageResponse(\n *       <ShareImage theme={theme} kicker=\"Guide\" title=\"How the tide tables work\" site=\"example.com\" />,\n *       { ...size, fonts },\n *     );\n *   }\n *   ```\n *\n * It renders in a browser too, which is how Storybook shows it.\n *\n * ## Two sizes\n *\n * `size=\"og\"` (1200 × 630) puts the evidence beside the words; `size=\"square\"`\n * (1200 × 1200) stacks it below them. The title's size steps down with its\n * length and the room left (`planWords`), and the description is cut at a word.\n *\n * ## Right to left\n *\n * `dir=\"auto\"` (the default) reads the title's first strong letter. In a\n * right-to-left image the rows mirror and the text sets from the right.\n * Satori has no bidi algorithm: it draws every line left to right. So\n * right-to-left text is broken into lines here (`breakLines`, planned wide so\n * none wraps again), each line is put in drawing order (`visualRtlLine`:\n * words reversed, Hebrew letters reversed, Arabic left to the font engine,\n * which orders an Arabic word's letters itself, Latin runs and numbers kept),\n * and each is set as its own box against the right edge.\n *\n * Satori shapes Arabic, but reads only some fonts' Arabic tables: Cairo\n * works; Noto Naskh Arabic, Noto Sans Arabic, Noto Kufi Arabic and Amiri\n * throw. Register an Arabic face that renders after your Latin faces, and\n * the renderer falls back to it glyph by glyph.\n *\n * ## No motion\n *\n * A share image is a still: nothing here animates.\n *\n * ## MIN_VIEWPORT — 1200\n *\n * ## Anatomy\n *\n *   <div data-slot=\"share-image\" data-size=\"og|square\" dir>\n *     <div data-slot=\"share-image-edge\" />                         (the accent rule)\n *     <div data-slot=\"share-image-head\"> {brand} {label} </div>\n *     <div data-slot=\"share-image-body\">\n *       <div data-slot=\"share-image-words\"> kicker · title · description </div>\n *       <div data-slot=\"share-image-visual\"> {stat | bars | visual} </div>\n *     </div>\n *     <div data-slot=\"share-image-foot\"> {site} {footnote} </div>\n *   </div>\n */\n\nimport {\n  NEUTRAL_SHARE_THEME,\n  SHARE_IMAGE_SIZES,\n  breakLines,\n  visualRtlLine,\n  clampText,\n  planWords,\n  textDirection,\n  type ShareImageSize,\n  type ShareImageTheme,\n} from '@/components/ui/patterns/share-image-model';\n\nexport interface ShareImageBar {\n  label: string;\n  /** Zero or more: bars are scaled to the largest, and a negative value draws like zero, at the minimum width. */\n  value: number;\n  /** What is printed at the bar's end; defaults to the value. */\n  display?: string;\n}\n\nexport interface ShareImageProps {\n  /** The page's title, the one thing everyone reads. */\n  title: string;\n  /** A word or two above the title: the section, the kind of page. */\n  kicker?: string;\n  /** One sentence under the title. Cut at a word to fit. */\n  description?: string;\n  /** Your mark, top start. A string is set in the heading face. */\n  brand?: ReactNode;\n  /** A quiet tag, top end: \"Answer\", \"Dataset\", \"Daily game\". */\n  label?: string;\n  /** The address readers will see, foot start. */\n  site?: string;\n  /** Foot end: \"6 sources\", \"Updated 24 Nov 2026\". */\n  footnote?: string;\n  /** A big number and what it counts. */\n  stat?: { value: string; label: string };\n  /** Up to five bars; largest first reads best. */\n  bars?: ShareImageBar[];\n  /** Your own drawing in the evidence slot. Wins over `stat` and `bars`. */\n  visual?: ReactNode;\n  size?: ShareImageSize;\n  theme?: ShareImageTheme;\n  dir?: 'ltr' | 'rtl' | 'auto';\n}\n\nconst flex = (style: CSSProperties): CSSProperties => ({ display: 'flex', ...style });\n\n/** A one-line string in drawing order. */\nconst line = (text: string, rtl: boolean) => (rtl ? visualRtlLine(text) : text);\n\n/**\n * A run of text. Left to right it is one box that wraps. Right to left it is\n * one box per planned line (`breakLines`), each already in drawing order\n * (`visualRtlLine`), set against the right edge.\n */\nfunction Words({ text, rtl, width, style }: { text: string; rtl: boolean; width: number; style: CSSProperties }) {\n  if (!rtl) return <div style={style}>{text}</div>;\n  const fontSize = Number(style.fontSize);\n  return (\n    <div style={{ ...style, display: 'flex', flexDirection: 'column', alignItems: 'flex-end' }}>\n      {breakLines(text, fontSize, width).map((lineText, i) => (\n        <div key={`${i}-${lineText}`} style={{ letterSpacing: 0, textTransform: 'none' }}>\n          {visualRtlLine(lineText)}\n        </div>\n      ))}\n    </div>\n  );\n}\n\nfunction Bars({\n  bars,\n  theme,\n  rtl,\n  width,\n  compact,\n}: {\n  bars: ShareImageBar[];\n  theme: ShareImageTheme;\n  rtl: boolean;\n  width: number;\n  /** Beside the words in a wide image: smaller type, tighter rows. */\n  compact: boolean;\n}) {\n  const top = Math.max(...bars.map((b) => b.value), 1e-9);\n  const row = rtl ? 'row-reverse' : 'row';\n  const fontSize = compact ? 22 : 26;\n  const thick = compact ? 14 : 18;\n  // One line per label, leaving room for the value at its end.\n  const labelChars = Math.floor((width - 4 * fontSize) / (fontSize * 0.5));\n  return (\n    <div data-slot=\"share-image-bars\" style={flex({ flexDirection: 'column', gap: compact ? 16 : 22, width: '100%' })}>\n      {bars.slice(0, 5).map((bar, i) => (\n        <div key={bar.label} style={flex({ flexDirection: 'column', gap: compact ? 6 : 8 })}>\n          <div style={flex({ flexDirection: row, justifyContent: 'space-between', gap: 16, fontSize })}>\n            <span style={{ color: theme.foreground }}>{line(clampText(bar.label, labelChars), rtl)}</span>\n            <span style={{ fontWeight: 700, color: theme.foreground }}>\n              {line(bar.display ?? String(bar.value), rtl)}\n            </span>\n          </div>\n          <div style={flex({ flexDirection: row, height: thick, borderRadius: thick / 2, background: theme.border })}>\n            <div\n              style={{\n                width: `${Math.max(2, (bar.value / top) * 100)}%`,\n                height: thick,\n                borderRadius: thick / 2,\n                background: theme.chart[i % theme.chart.length],\n              }}\n            />\n          </div>\n        </div>\n      ))}\n    </div>\n  );\n}\n\nconst PAD = 72;\n\n/** Where things go and how big, from the size and whether there is evidence. */\nfunction geometry(size: ShareImageSize, hasEvidence: boolean) {\n  const { width, height } = SHARE_IMAGE_SIZES[size];\n  const beside = size === 'og' && hasEvidence;\n  const inner = width - PAD * 2;\n  const wordsWidth = beside ? Math.round(inner * 0.56) : inner;\n  return {\n    width,\n    height,\n    beside,\n    wordsWidth,\n    // The evidence panel's content box: beside the words, or the full width under them.\n    panelWidth: (beside ? inner - wordsWidth - 56 : inner) - 84,\n    // The height the words may take: the image less its padding, head, foot and,\n    // in a square image with evidence, the evidence under them.\n    wordsHeight: size === 'og' ? 340 : hasEvidence ? 470 : 880,\n    titleMax: size === 'square' ? 96 : beside ? 64 : 76,\n    titleLines: beside || size === 'square' ? 4 : 3,\n  };\n}\n\ninterface Frame {\n  theme: ShareImageTheme;\n  rtl: boolean;\n}\n\nfunction Stat({\n  stat,\n  theme,\n  rtl,\n  big,\n  width,\n}: Frame & { stat: NonNullable<ShareImageProps['stat']>; big: boolean; width: number }) {\n  return (\n    <div style={flex({ flexDirection: 'column', alignItems: rtl ? 'flex-end' : 'flex-start', gap: 12 })}>\n      <span\n        style={{\n          fontFamily: theme.fontHeading,\n          fontSize: big ? 180 : 132,\n          fontWeight: 600,\n          lineHeight: 1,\n          letterSpacing: '-0.03em',\n          color: theme.accent,\n        }}\n      >\n        {line(stat.value, rtl)}\n      </span>\n      <Words\n        text={stat.label}\n        rtl={rtl}\n        width={width}\n        style={{ fontSize: 28, color: theme.muted, textAlign: rtl ? 'right' : 'left' }}\n      />\n    </div>\n  );\n}\n\nfunction Head({ brand, label, theme, rtl }: Frame & Pick<ShareImageProps, 'brand' | 'label'>) {\n  return (\n    <div\n      data-slot=\"share-image-head\"\n      style={flex({\n        flexDirection: rtl ? 'row-reverse' : 'row',\n        alignItems: 'center',\n        justifyContent: 'space-between',\n      })}\n    >\n      <div style={flex({ alignItems: 'center', fontFamily: theme.fontHeading, fontSize: 34, fontWeight: 600 })}>\n        {typeof brand === 'string' ? line(brand, rtl) : brand}\n      </div>\n      {label ? (\n        <div\n          style={flex({\n            padding: '6px 20px',\n            borderRadius: 999,\n            border: `2px solid ${theme.border}`,\n            fontSize: 24,\n            color: theme.muted,\n          })}\n        >\n          {line(label, rtl)}\n        </div>\n      ) : null}\n    </div>\n  );\n}\n\nfunction Foot({ site, footnote, theme, rtl }: Frame & Pick<ShareImageProps, 'site' | 'footnote'>) {\n  return (\n    <div\n      data-slot=\"share-image-foot\"\n      style={flex({\n        flexDirection: rtl ? 'row-reverse' : 'row',\n        justifyContent: 'space-between',\n        alignItems: 'center',\n        paddingTop: 22,\n        borderTop: `2px solid ${theme.border}`,\n        fontSize: 24,\n        color: theme.muted,\n      })}\n    >\n      <span>{line(site ?? '', rtl)}</span>\n      <span>{line(footnote ?? '', rtl)}</span>\n    </div>\n  );\n}\n\nfunction WordsBlock({\n  kicker,\n  title,\n  description,\n  theme,\n  rtl,\n  width,\n  titleSize,\n  descriptionChars,\n}: Frame &\n  Pick<ShareImageProps, 'kicker' | 'title' | 'description'> & {\n    width: number;\n    titleSize: number;\n    descriptionChars: number;\n  }) {\n  const textAlign = rtl ? 'right' : 'left';\n  return (\n    <div\n      data-slot=\"share-image-words\"\n      style={flex({ flexDirection: 'column', alignItems: rtl ? 'flex-end' : 'flex-start', width, gap: 18 })}\n    >\n      {kicker ? (\n        <Words\n          text={kicker}\n          rtl={rtl}\n          width={width}\n          style={{\n            fontSize: 24,\n            fontWeight: 700,\n            letterSpacing: '0.08em',\n            textTransform: 'uppercase',\n            color: theme.accent,\n            textAlign,\n          }}\n        />\n      ) : null}\n      <Words\n        text={title}\n        rtl={rtl}\n        width={width}\n        style={{\n          fontFamily: theme.fontHeading,\n          fontSize: titleSize,\n          fontWeight: 600,\n          lineHeight: 1.1,\n          letterSpacing: '-0.015em',\n          textAlign,\n        }}\n      />\n      {description && descriptionChars > 0 ? (\n        <Words\n          text={clampText(description, descriptionChars)}\n          rtl={rtl}\n          width={width}\n          style={{ fontSize: 28, lineHeight: 1.4, color: theme.muted, textAlign }}\n        />\n      ) : null}\n    </div>\n  );\n}\n\n/** The one piece of evidence: your drawing, else the stat, else the bars, else nothing. */\nfunction pickEvidence({\n  visual,\n  stat,\n  bars,\n  big,\n  width,\n  ...frame\n}: Frame & Pick<ShareImageProps, 'visual' | 'stat' | 'bars'> & { big: boolean; width: number }): ReactNode {\n  if (visual) return visual;\n  if (stat) return <Stat {...frame} stat={stat} big={big} width={width} />;\n  if (bars && bars.length > 0) return <Bars {...frame} bars={bars} width={width} compact={!big} />;\n  return null;\n}\n\nexport function ShareImage({\n  title,\n  kicker,\n  description,\n  brand,\n  label,\n  site,\n  footnote,\n  stat,\n  bars,\n  visual,\n  size = 'og',\n  theme = NEUTRAL_SHARE_THEME,\n  dir = 'auto',\n}: ShareImageProps) {\n  const rtl = (dir === 'auto' ? textDirection(title) : dir) === 'rtl';\n  const frame = { theme, rtl };\n  const g = geometry(size, Boolean(visual ?? stat ?? bars?.length));\n  const plan = planWords({\n    title,\n    kicker,\n    description,\n    width: g.wordsWidth,\n    height: g.wordsHeight,\n    max: g.titleMax,\n    maxLines: g.titleLines,\n  });\n  const evidence = pickEvidence({ ...frame, visual, stat, bars, big: size === 'square', width: g.panelWidth });\n\n  return (\n    <div\n      data-slot=\"share-image\"\n      data-size={size}\n      dir={rtl ? 'rtl' : 'ltr'}\n      style={flex({\n        position: 'relative',\n        flexDirection: 'column',\n        width: g.width,\n        height: g.height,\n        padding: `${PAD + 4}px ${PAD}px ${PAD - 12}px`,\n        background: theme.background,\n        color: theme.foreground,\n        fontFamily: theme.fontBody,\n      })}\n    >\n      <div\n        data-slot=\"share-image-edge\"\n        style={{ position: 'absolute', top: 0, left: 0, width: g.width, height: 10, background: theme.accent }}\n      />\n      <Head {...frame} brand={brand} label={label} />\n      <div\n        data-slot=\"share-image-body\"\n        style={flex({\n          flex: 1,\n          flexDirection: g.beside ? (rtl ? 'row-reverse' : 'row') : 'column',\n          alignItems: g.beside ? 'center' : 'stretch',\n          justifyContent: g.beside ? 'space-between' : 'center',\n          gap: 56,\n          padding: '24px 0',\n        })}\n      >\n        <WordsBlock\n          {...frame}\n          kicker={kicker}\n          title={title}\n          description={description}\n          width={g.wordsWidth}\n          titleSize={plan.titleSize}\n          descriptionChars={plan.descriptionChars}\n        />\n        {evidence !== null ? (\n          <div\n            data-slot=\"share-image-visual\"\n            style={flex({\n              ...(g.beside ? { flex: 1 } : {}),\n              justifyContent: rtl ? 'flex-end' : 'flex-start',\n              padding: 40,\n              borderRadius: 24,\n              background: theme.surface,\n              border: `2px solid ${theme.border}`,\n            })}\n          >\n            {evidence}\n          </div>\n        ) : null}\n      </div>\n      <Foot {...frame} site={site} footnote={footnote} />\n    </div>\n  );\n}\n"
    },
    {
      "path": "registry/interlace-ui/patterns/share-image-model.ts",
      "target": "components/ui/patterns/share-image-model.ts",
      "type": "registry:ui",
      "content": "export type ShareImageSize = 'og' | 'square';\n\nexport const SHARE_IMAGE_SIZES: Record<ShareImageSize, { width: number; height: number }> = {\n  og: { width: 1200, height: 630 },\n  square: { width: 1200, height: 1200 },\n};\n\n/** Every colour and face a share image paints with. Colours are CSS colours Satori can parse. */\nexport interface ShareImageTheme {\n  /** The page colour. */\n  background: string;\n  /** Body text and the title. */\n  foreground: string;\n  /** The description, the footer and quiet labels. */\n  muted: string;\n  /** The one accent: the kicker, the rule, the stat. */\n  accent: string;\n  /** Text set on the accent. */\n  accentForeground: string;\n  /** Panels inside the image (the chart, a stat box). */\n  surface: string;\n  /** Hairlines. */\n  border: string;\n  /** Chart series, in order. */\n  chart: string[];\n  /** Font family names as registered with the renderer. */\n  fontHeading: string;\n  fontBody: string;\n}\n\n/** Interlace's neutral look, for an image with no theme of its own. */\nexport const NEUTRAL_SHARE_THEME: ShareImageTheme = {\n  background: oklchToHex(0.985, 0, 0),\n  foreground: oklchToHex(0.145, 0, 0),\n  muted: oklchToHex(0.44, 0, 0),\n  accent: oklchToHex(0.205, 0, 0),\n  accentForeground: oklchToHex(0.985, 0, 0),\n  surface: oklchToHex(1, 0, 0),\n  border: oklchToHex(0.922, 0, 0),\n  chart: [\n    oklchToHex(0.55, 0.15, 250),\n    oklchToHex(0.6, 0.13, 70),\n    oklchToHex(0.55, 0.14, 155),\n    oklchToHex(0.55, 0.16, 300),\n    oklchToHex(0.55, 0, 0),\n  ],\n  fontHeading: 'serif',\n  fontBody: 'sans-serif',\n};\n\n// ─── Colour ──────────────────────────────────────────────────────────────────\n\nfunction clamp01(n: number): number {\n  return Math.min(1, Math.max(0, n));\n}\n\nfunction hex2(n: number): string {\n  return Math.round(clamp01(n) * 255)\n    .toString(16)\n    .padStart(2, '0');\n}\n\nfunction gammaEncode(c: number): number {\n  return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;\n}\n\n/** OKLCH (lightness 0 to 1, chroma, hue in degrees) to `#rrggbb`, clipped to sRGB. */\nexport function oklchToHex(l: number, c: number, h: number): string {\n  const rad = (h * Math.PI) / 180;\n  const a = c * Math.cos(rad);\n  const b = c * Math.sin(rad);\n  const l_ = Math.pow(l + 0.3963377774 * a + 0.2158037573 * b, 3);\n  const m_ = Math.pow(l - 0.1055613458 * a - 0.0638541728 * b, 3);\n  const s_ = Math.pow(l - 0.0894841775 * a - 1.291485548 * b, 3);\n  const r = 4.0767416621 * l_ - 3.3077115913 * m_ + 0.2309699292 * s_;\n  const g = -1.2684380046 * l_ + 2.6097574011 * m_ - 0.3413193965 * s_;\n  const bl = -0.0041960863 * l_ - 0.7034186147 * m_ + 1.707614701 * s_;\n  return `#${hex2(gammaEncode(r))}${hex2(gammaEncode(g))}${hex2(gammaEncode(bl))}`;\n}\n\nconst OKLCH_RE = /^oklch\\(\\s*([\\d.]+)(%?)\\s+([\\d.]+)\\s+([\\d.]+)(?:deg)?\\s*(?:\\/\\s*[\\d.%]+\\s*)?\\)$/i;\n\n/**\n * A theme colour in a form Satori can paint: `oklch()` becomes hex, and hex,\n * `rgb()`, `hsl()` and names pass through. Anything else (`color-mix()`, a\n * leftover `var()`) gives `undefined`, so the caller falls back.\n */\nexport function toPaintableColor(value: string | undefined): string | undefined {\n  if (!value) return undefined;\n  const v = value.trim();\n  const m = OKLCH_RE.exec(v);\n  if (m) {\n    const l = Number(m[1]) / (m[2] ? 100 : 1);\n    return oklchToHex(l, Number(m[3]), Number(m[4]));\n  }\n  if (/^#[\\da-f]{3,8}$/i.test(v) || /^(rgb|rgba|hsl|hsla)\\(/i.test(v) || /^[a-z]+$/i.test(v)) {\n    return v;\n  }\n  return undefined;\n}\n\n// ─── Theme from the consumer's CSS ───────────────────────────────────────────\n\n/** Strip comments, then find each `selector { … }` block that is not inside an at-rule. */\nfunction topLevelBlocks(css: string, selector: string): string[] {\n  const src = css.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '');\n  const blocks: string[] = [];\n  let depth = 0;\n  let start = 0;\n  let head = '';\n  for (let i = 0; i < src.length; i++) {\n    const ch = src[i];\n    if (ch === '{') {\n      if (depth === 0) {\n        head = src.slice(start, i).trim();\n        start = i + 1;\n      }\n      depth++;\n    } else if (ch === '}') {\n      depth--;\n      if (depth === 0) {\n        if (head.split(',').some((s) => s.trim() === selector)) blocks.push(src.slice(start, i));\n        start = i + 1;\n      }\n    }\n  }\n  return blocks;\n}\n\n/** The index of the `)` that closes the `(` just before `from`, or -1. */\nfunction closingParen(value: string, from: number): number {\n  let depth = 1;\n  for (let i = from; i < value.length; i++) {\n    if (value[i] === '(') depth++;\n    else if (value[i] === ')' && --depth === 0) return i;\n  }\n  return -1;\n}\n\n/** Resolve `var(--name)` and `var(--name, fallback)`, a few levels deep. */\nfunction resolveVars(value: string, tokens: Record<string, string>, depth = 0): string {\n  const at = value.indexOf('var(');\n  if (at === -1 || depth > 8) return value;\n  const end = closingParen(value, at + 4);\n  if (end === -1) return value;\n  const inner = value.slice(at + 4, end);\n  const comma = inner.indexOf(',');\n  const name = (comma === -1 ? inner : inner.slice(0, comma)).trim().replace(/^--/, '');\n  const fallback = comma === -1 ? '' : inner.slice(comma + 1).trim();\n  const next = `${value.slice(0, at)}${tokens[name] ?? fallback}${value.slice(end + 1)}`;\n  return resolveVars(next, tokens, depth + 1);\n}\n\n/**\n * The custom properties a theme file sets on `selector` (default `:root`),\n * outside any media query, keyed without the leading `--`, with `var()`\n * references resolved. Pass `selector: '.dark'` for the dark scheme.\n */\nexport function readThemeTokens(css: string, selector = ':root'): Record<string, string> {\n  const raw: Record<string, string> = {};\n  for (const block of topLevelBlocks(css, selector)) {\n    for (const decl of block.split(';')) {\n      const colon = decl.indexOf(':');\n      const name = decl.slice(0, colon).trim();\n      if (colon > 0 && name.startsWith('--')) raw[name.slice(2)] = decl.slice(colon + 1).trim();\n    }\n  }\n  const out: Record<string, string> = {};\n  for (const [name, value] of Object.entries(raw)) out[name] = resolveVars(value, raw);\n  return out;\n}\n\n/**\n * A share theme from shadcn token names (`background`, `foreground`,\n * `muted-foreground`, `primary`, `primary-foreground`, `card`, `border`,\n * `chart-1`…`chart-5`). Missing or unpaintable tokens keep the neutral value;\n * `overrides` wins over both (fonts are named here).\n */\nexport function shareThemeFromTokens(\n  tokens: Record<string, string>,\n  overrides: Partial<ShareImageTheme> = {},\n): ShareImageTheme {\n  const pick = (name: string, fallback: string) => toPaintableColor(tokens[name]) ?? fallback;\n  const n = NEUTRAL_SHARE_THEME;\n  return {\n    background: pick('background', n.background),\n    foreground: pick('foreground', n.foreground),\n    muted: pick('muted-foreground', n.muted),\n    accent: pick('primary', n.accent),\n    accentForeground: pick('primary-foreground', n.accentForeground),\n    surface: pick('card', n.surface),\n    border: pick('border', n.border),\n    chart: n.chart.map((fallback, i) => pick(`chart-${i + 1}`, fallback)),\n    fontHeading: n.fontHeading,\n    fontBody: n.fontBody,\n    ...overrides,\n  };\n}\n\n/** `shareThemeFromTokens(readThemeTokens(css, selector), overrides)`. */\nexport function themeFromCss(\n  css: string,\n  overrides: Partial<ShareImageTheme> = {},\n  selector = ':root',\n): ShareImageTheme {\n  return shareThemeFromTokens(readThemeTokens(css, selector), overrides);\n}\n\n// ─── Text ────────────────────────────────────────────────────────────────────\n\nconst RTL_RE = /[\\u0590-\\u08FF\\uFB1D-\\uFDFF\\uFE70-\\uFEFF]/;\nconst LTR_RE = /[A-Za-z\\u00C0-\\u024F\\u0370-\\u03FF\\u0400-\\u04FF]/;\n\n/** The direction of the first strong character, as the Unicode bidi algorithm reads a paragraph. */\nexport function textDirection(text: string): 'ltr' | 'rtl' {\n  for (const ch of text) {\n    if (RTL_RE.test(ch)) return 'rtl';\n    if (LTR_RE.test(ch)) return 'ltr';\n  }\n  return 'ltr';\n}\n\n/**\n * About how many lines `text` wraps to at `size` pixels in a box `width`\n * wide. Average glyph width is taken as 0.5em (a fair middle for a book serif\n * or a grotesque), and wrapping wastes about a word a line, so each line is\n * planned at 85%.\n */\nexport function estimateLines(text: string, size: number, width: number): number {\n  const chars = Math.max(1, [...text].length);\n  return Math.max(1, Math.ceil((chars * 0.5 * size) / (width * 0.85)));\n}\n\n/** What `planWords` decided: the title's size and how much description fits. */\nexport interface WordsPlan {\n  titleSize: number;\n  /** Characters of description to keep (0 drops it). */\n  descriptionChars: number;\n}\n\n/**\n * Size a title block to a box: the largest title (from `max` down by 2px,\n * never under `min`, at most `maxLines` lines) that still leaves room for\n * most of the description (60% of it, up to two lines), and as much of it as\n * then fits. When no size leaves that much room, the description is dropped\n * and the title keeps its largest size that fits. Line heights match `ShareImage`: title 1.1, description 28px at 1.4,\n * kicker 34px plus an 18px gap.\n */\nexport function planWords({\n  title,\n  kicker,\n  description,\n  width,\n  height,\n  max,\n  min = 40,\n  maxLines = 3,\n}: {\n  title: string;\n  kicker?: string;\n  description?: string;\n  width: number;\n  height: number;\n  max: number;\n  min?: number;\n  maxLines?: number;\n}): WordsPlan {\n  const kickerH = kicker ? 52 : 0;\n  const descLine = 28 * 1.4;\n  const perDescLine = Math.floor((width * 0.85) / (28 * 0.5));\n  // A description cut to a stub reads worse than none: keep at least 60% of it, or drop it.\n  const enough = description ? Math.ceil([...description].length * 0.6) : 0;\n  let fallback = min;\n  for (let size = max; size >= min; size -= 2) {\n    const lines = estimateLines(title, size, width);\n    if (lines > maxLines && size > min) continue;\n    if (fallback === min) fallback = size;\n    if (!description) return { titleSize: size, descriptionChars: 0 };\n    const room = height - kickerH - lines * size * 1.1 - 18;\n    const chars = Math.max(0, Math.min(2, Math.floor(room / descLine))) * perDescLine;\n    if (chars >= enough) return { titleSize: size, descriptionChars: chars };\n  }\n  return { titleSize: fallback, descriptionChars: 0 };\n}\n\n/**\n * `text` broken into lines that fit a box `width` pixels wide at `size`,\n * greedily by word, planning each character at `em` of the size (0.55 by\n * default: on the wide side, so a planned line never wraps again).\n *\n * Satori cannot wrap right-to-left text (see `visualRtlLine`), so\n * `ShareImage` plans the lines here and draws each as its own box.\n */\nexport function breakLines(text: string, size: number, width: number, em = 0.55): string[] {\n  const perLine = Math.max(1, Math.floor(width / (size * em)));\n  const lines: string[] = [];\n  let line = '';\n  for (const word of text.split(/\\s+/).filter(Boolean)) {\n    const next = line ? `${line} ${word}` : word;\n    if (line && [...next].length > perLine) {\n      lines.push(line);\n      line = word;\n    } else {\n      line = next;\n    }\n  }\n  if (line) lines.push(line);\n  return lines;\n}\n\nconst HEBREW_RE = /[\\u0590-\\u05FF\\uFB1D-\\uFB4F]/;\nconst LTR_PIECE_RE = /[A-Za-z0-9\\u00C0-\\u024F\\u0370-\\u03FF\\u0400-\\u04FF]+/g;\nconst MIRROR: Record<string, string> = {\n  '(': ')',\n  ')': '(',\n  '[': ']',\n  ']': '[',\n  '{': '}',\n  '}': '{',\n  '<': '>',\n  '>': '<',\n};\n\n/**\n * `text` cut into bidi runs, in reading order: each right-to-left word on\n * its own, and each run of left-to-right words and numbers kept together\n * (`World War II`, `+972 3 555`). A word with no strong letters (a dash, a\n * symbol) stays with the left-to-right run it follows.\n */\nexport function bidiRuns(text: string): string[] {\n  const runs: string[] = [];\n  let ltr: string[] = [];\n  const flush = () => {\n    if (ltr.length) runs.push(ltr.join(' '));\n    ltr = [];\n  };\n  for (const word of text.split(/\\s+/).filter(Boolean)) {\n    const isRtl = RTL_RE.test(word);\n    if (!isRtl && (LTR_RE.test(word) || /\\d/.test(word) || ltr.length)) {\n      ltr.push(word);\n    } else {\n      flush();\n      runs.push(word);\n    }\n  }\n  flush();\n  return runs;\n}\n\nfunction graphemes(text: string): string[] {\n  if (typeof Intl !== 'undefined' && 'Segmenter' in Intl) {\n    return [...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(text)].map((g) => g.segment);\n  }\n  return [...text];\n}\n\n/** A Hebrew word drawn left to right: letters reversed (points kept on their letter), digits kept, brackets mirrored. */\nfunction hebrewVisual(word: string): string {\n  const pieces: string[] = [];\n  let last = 0;\n  for (const m of word.matchAll(LTR_PIECE_RE)) {\n    if (m.index > last) pieces.push(...graphemes(word.slice(last, m.index)).map((g) => MIRROR[g] ?? g));\n    pieces.push(m[0]);\n    last = m.index + m[0].length;\n  }\n  if (last < word.length) pieces.push(...graphemes(word.slice(last)).map((g) => MIRROR[g] ?? g));\n  return pieces.reverse().join('');\n}\n\n/** A left-to-right run inside right-to-left text: its closing punctuation belongs to the sentence, on the left. */\nfunction ltrVisual(run: string): string {\n  let cut = run.length;\n  while (cut > 0 && '.,!?:;'.includes(run[cut - 1])) cut--;\n  return `${run.slice(cut)}${run.slice(0, cut)}`;\n}\n\n/**\n * One right-to-left line in the order a left-to-right renderer must draw it.\n *\n * Satori, under Next's `ImageResponse`, has no bidi algorithm: it draws text\n * left to right. Its font engine shapes Arabic and orders the letters of an\n * Arabic word itself, but leaves Hebrew letters and the order of words as\n * given. So the runs are reversed, Hebrew words are reversed letter by letter\n * (numbers and brackets kept readable), and Arabic words are left to the\n * engine. Left-to-right runs keep their order.\n */\nexport function visualRtlLine(line: string): string {\n  return bidiRuns(line)\n    .reverse()\n    .map((run) => {\n      if (!RTL_RE.test(run)) return ltrVisual(run);\n      return HEBREW_RE.test(run) || !/[\\u0600-\\u06FF]/.test(run) ? hebrewVisual(run) : run;\n    })\n    .join(' ');\n}\n\n/** Cut `text` at a word boundary to at most `max` characters, with an ellipsis. */\nexport function clampText(text: string, max: number): string {\n  const chars = [...text];\n  if (chars.length <= max) return text;\n  const cut = chars.slice(0, max - 1).join('');\n  const space = cut.lastIndexOf(' ');\n  return `${(space > max * 0.6 ? cut.slice(0, space) : cut).trimEnd()}…`;\n}\n\n// ─── Meta tags ───────────────────────────────────────────────────────────────\n\nexport interface ShareImageRef {\n  /** Absolute, or relative to the site's base URL. */\n  url: string;\n  size?: ShareImageSize;\n  /** What the image shows, for readers who cannot see it. */\n  alt: string;\n}\n\nexport interface ShareMetaInput {\n  title: string;\n  description?: string;\n  /** The page's canonical URL. */\n  url?: string;\n  siteName?: string;\n  /** e.g. `en_US`, `he_IL`. */\n  locale?: string;\n  type?: 'website' | 'article';\n  images: ShareImageRef[];\n}\n\n/**\n * The `openGraph` and `twitter` fields of a Next.js `Metadata` object (the\n * shape every framework's head tags follow), with each image's width,\n * height, type and alt written out, so a network never has to fetch the\n * image to lay out the preview. X gets the large card.\n */\nexport function shareMeta(input: ShareMetaInput) {\n  const images = input.images.map((img) => ({\n    url: img.url,\n    ...SHARE_IMAGE_SIZES[img.size ?? 'og'],\n    type: 'image/png',\n    alt: img.alt,\n  }));\n  return {\n    openGraph: {\n      title: input.title,\n      ...(input.description ? { description: input.description } : {}),\n      ...(input.url ? { url: input.url } : {}),\n      ...(input.siteName ? { siteName: input.siteName } : {}),\n      ...(input.locale ? { locale: input.locale } : {}),\n      type: input.type ?? 'website',\n      images,\n    },\n    twitter: {\n      card: 'summary_large_image' as const,\n      title: input.title,\n      ...(input.description ? { description: input.description } : {}),\n      images: images.slice(0, 1).map(({ url, alt }) => ({ url, alt })),\n    },\n  };\n}\n\n/**\n * @interlace/ui — share-image-model\n *\n * The pure half of `ShareImage`: the sizes the networks crop to, the theme an\n * image is painted with, which way its text runs, how big its title can be,\n * and the `og:` and `twitter:` tags that point at it.\n *\n * A share image is painted by an image renderer (Next's `ImageResponse`,\n * Satori, a headless browser), not by the page, so it cannot read CSS\n * variables. `themeFromCss()` reads the consumer's own theme file instead:\n * the same `:root { --background: …; --primary: … }` block the site is\n * styled with, `var()` references resolved and `oklch()` turned into hex.\n * The brand stays in one place.\n *\n * | Size     | Pixels      | Where it shows                                           |\n * | -------- | ----------- | -------------------------------------------------------- |\n * | `og`     | 1200 × 630  | X, LinkedIn, Facebook, Slack, iMessage, WhatsApp links    |\n * | `square` | 1200 × 1200 | WhatsApp and iMessage thumbnails, Instagram, a saved card |\n */\n"
    }
  ],
  "meta": {
    "tier": "pattern",
    "client": false,
    "minViewport": null,
    "loading": false,
    "version": "1.0.0",
    "since": "2.0.0"
  },
  "docs": "## @interlace/share-image\n\nInstalled to `components/ui/patterns/share-image.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/patterns/share-image';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/share-image\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
