{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "chart-frame",
  "type": "registry:ui",
  "title": "Chart Frame",
  "description": "The frame a published chart sits in: a title that states the finding, a line on what is measured, the chart, and a footer with where the numbers came from and a copy of them to take away. Every chart on a page gets the same frame, so a reader learns once…",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "data",
    "chart"
  ],
  "dependencies": [],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/cn.json",
    "https://ds.interlace.tools/r/tabs.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/charts/chart-frame.tsx",
      "target": "components/ui/charts/chart-frame.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/chart-frame v1.0.1 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/chart-frame\n// What changed since: https://ds.interlace.tools/c/chart-frame#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — ChartFrame\n *\n * The frame a published chart sits in: a title that states the finding, a\n * line on what is measured, the chart, and a footer with where the numbers\n * came from and a copy of them to take away. Every chart on a page gets the\n * same frame, so a reader learns once where the source is.\n *\n * ## A chart is a claim, the footer is its receipt\n *\n * `sources` names each source, linked when it has an address; `note` says\n * what the reader must know to read the numbers right (how a question was\n * worded, what was left out); `updated` says how fresh they are. All three\n * are plain HTML in the footer, never hidden behind a click, because a\n * reader who doubts a chart should not have to hunt for its origin.\n *\n * ## Chart or table\n *\n * Pass `table` and the frame offers a Chart and a Table view (Base UI tabs,\n * arrow keys between them). Both views stay in the server HTML: the hidden\n * one is only hidden, so search engines and readers without scripts get the\n * numbers too.\n *\n * ## Take the data with you\n *\n * `download` is the data as rows. The frame writes it as CSV into a link at\n * render time (UTF-8 with a byte-order mark, so spreadsheet apps read\n * accents right), so the link works before scripts load. Cells that start\n * with `=`, `+`, `-` or `@` and are not numbers get a leading apostrophe, so\n * a spreadsheet never runs them as a formula. `toCsv()` is exported and pure.\n *\n * ## Words\n *\n * Every fixed word (\"Source\", \"Download data\") comes from `labels`, so a\n * page in another language passes its own. Dates go through\n * `Intl.DateTimeFormat` in `locale`.\n *\n * ## MIN_VIEWPORT — 320\n *\n * The header is a single column; the footer wraps; the view switch sits\n * under the subtitle and never pushes the title sideways.\n *\n * ## Anatomy\n *\n *   <figure data-slot=\"chart-frame\">\n *     <header data-slot=\"chart-frame-header\">\n *       <h3 data-slot=\"chart-frame-title\" />\n *       <p data-slot=\"chart-frame-subtitle\" />\n *     </header>\n *     <div data-slot=\"chart-frame-body\">{children}</div>        (or tabs: chart / table)\n *     <figcaption data-slot=\"chart-frame-footer\">\n *       <p data-slot=\"chart-frame-sources\" />\n *       <p data-slot=\"chart-frame-note\" />\n *       <p> <time data-slot=\"chart-frame-updated\" /> · <a data-slot=\"chart-frame-download\" download /> </p>\n *     </figcaption>\n *   </figure>\n *\n * | Rule | Concept                    | Where in this file                                     |\n * | ---- | -------------------------- | ------------------------------------------------------ |\n * | R4   | Extends native el          | `React.ComponentProps<'figure'>`                        |\n * | R6   | data-slot on every part    | `chart-frame` / `-header` / `-body` / `-footer`          |\n * | R7   | className merged + ...rest | `cn(...)` + `{...props}`                                |\n * | R10  | Composition seam           | `children` is any chart; `table` any table              |\n * | R14  | Declares min viewport      | `data-min-viewport={String(MIN_VIEWPORT)}`              |\n * | R18  | Tailwind only              | zero inline `style`                                     |\n * | R19  | Tokens only                | `--foreground`, `--muted-foreground`, `--border`, `--primary` |\n * | R26  | A11y                       | `<figure>` + footer `<figcaption>`, tabs from Base UI   |\n */\n\nimport { cn } from '@/lib/utils';\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';\n\nexport const MIN_VIEWPORT = 320 as const;\n\nexport type ChartSource = {\n  /** The source's name, such as a publisher and the title of the release. */\n  label: string;\n  /** Where to read it: an http(s), mailto or relative URL; other schemes print as plain text. */\n  href?: string;\n};\n\nexport type CsvValue = string | number | boolean | null | undefined;\nexport type CsvRow = Readonly<Record<string, CsvValue>>;\n\nexport type ChartDownload = {\n  /** The file's name. `.csv` is added when missing. */\n  filename: string;\n  /** The rows, one object per line. */\n  rows: readonly CsvRow[];\n  /** The columns, in order. @default every key, in the order first seen */\n  columns?: readonly string[];\n};\n\nexport type ChartFrameLabels = {\n  chart: string;\n  table: string;\n  source: string;\n  sources: string;\n  note: string;\n  updated: string;\n  download: string;\n  views: string;\n};\n\nconst LABELS: ChartFrameLabels = {\n  chart: 'Chart',\n  table: 'Table',\n  source: 'Source',\n  sources: 'Sources',\n  note: 'Note',\n  updated: 'Updated',\n  download: 'Download data (CSV)',\n  views: 'View',\n};\n\n// ─────────────────────────────────────────────────────────────────\n// CSV\n// ─────────────────────────────────────────────────────────────────\n\nconst FORMULA = /^[=+\\-@\\t\\r]/;\n\n/**\n * A source link keeps http(s), mailto and relative URLs and drops any other\n * scheme (`javascript:`, `data:`), so a citation passed through from user\n * input cannot run script when clicked. Such a source prints as plain text.\n */\nexport function safeHref(href: string | undefined): string | undefined {\n  if (!href) return undefined;\n  const scheme = /^\\s*([a-z][a-z\\d+.-]*):/i.exec(href);\n  return !scheme || /^(?:https?|mailto)$/i.test(scheme[1]!) ? href : undefined;\n}\n\nfunction cell(value: CsvValue): string {\n  if (value === null || value === undefined) return '';\n  if (typeof value === 'number') return Number.isFinite(value) ? String(value) : '';\n  let text = String(value);\n  if (typeof value === 'string' && FORMULA.test(text) && !Number.isFinite(Number(text))) text = `'${text}`;\n  return /[\",\\n\\r]/.test(text) ? `\"${text.replaceAll('\"', '\"\"')}\"` : text;\n}\n\n/** Rows as CSV text: a header line, then one line per row, CRLF between lines (RFC 4180). */\nexport function toCsv(rows: readonly CsvRow[], columns?: readonly string[]): string {\n  const keys = columns ?? [...new Set(rows.flatMap((row) => Object.keys(row)))];\n  const lines = [keys.map((k) => cell(k)), ...rows.map((row) => keys.map((k) => cell(row[k])))];\n  return lines.map((line) => line.join(',')).join('\\r\\n');\n}\n\n/** A `data:` address holding the CSV, with a byte-order mark so spreadsheet apps read it as UTF-8. */\nexport function csvHref(rows: readonly CsvRow[], columns?: readonly string[]): string {\n  return `data:text/csv;charset=utf-8,${encodeURIComponent(`\\uFEFF${toCsv(rows, columns)}`)}`;\n}\n\n// ─────────────────────────────────────────────────────────────────\n// Component\n// ─────────────────────────────────────────────────────────────────\n\nconst HEADING = {\n  h2: 'h2',\n  h3: 'h3',\n  h4: 'h4',\n} as const;\n\nexport interface ChartFrameProps extends Omit<React.ComponentProps<'figure'>, 'title'> {\n  /** The finding, in a sentence, such as \"Most residents walk or cycle now\". */\n  title?: React.ReactNode;\n  /** What is measured, where and when. */\n  subtitle?: React.ReactNode;\n  /** The heading level of the title, to fit the page's outline. @default 'h3' */\n  headingLevel?: keyof typeof HEADING;\n  /** Where the numbers came from. */\n  sources?: readonly ChartSource[];\n  /** What a reader must know to read the numbers right. */\n  note?: React.ReactNode;\n  /** When the data was last updated, as an ISO date (`2025-10-01`). */\n  updated?: string;\n  /** The data as rows, offered as a CSV download. */\n  download?: ChartDownload;\n  /** A table of the same numbers. When given, the frame offers a Chart and a Table view. */\n  table?: React.ReactNode;\n  /** The view shown first, when there is a table. @default 'chart' */\n  defaultView?: 'chart' | 'table';\n  /** A BCP 47 locale for the date. @default the reader's */\n  locale?: string;\n  /** Fixed words, for pages in another language. */\n  labels?: Partial<ChartFrameLabels>;\n}\n\nexport const ChartFrame = React.forwardRef<HTMLElement, ChartFrameProps>(function ChartFrame(\n  {\n    title,\n    subtitle,\n    headingLevel = 'h3',\n    sources = [],\n    note,\n    updated,\n    download,\n    table,\n    defaultView = 'chart',\n    locale,\n    labels: labelsProp,\n    className,\n    children,\n    ...props\n  },\n  ref,\n) {\n  const labels = { ...LABELS, ...labelsProp };\n  const titleId = React.useId();\n  const Heading = HEADING[headingLevel];\n\n  const href = React.useMemo(\n    () => (download ? csvHref(download.rows, download.columns) : undefined),\n    [download],\n  );\n  const filename = download\n    ? download.filename.toLowerCase().endsWith('.csv')\n      ? download.filename\n      : `${download.filename}.csv`\n    : undefined;\n\n  const date = updated ? new Date(`${updated.slice(0, 10)}T00:00:00Z`) : undefined;\n  // A free-form `updated` (\"autumn 2025\") is printed as given, with no\n  // machine-readable `datetime`, which must be a valid date string.\n  const isoDate = date && !Number.isNaN(date.getTime()) ? date.toISOString().slice(0, 10) : undefined;\n  const dateText = isoDate\n    ? new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeZone: 'UTC' }).format(new Date(isoDate))\n    : updated;\n\n  const hasFooter = sources.length > 0 || note || updated || download;\n\n  const body = table ? (\n    <Tabs defaultValue={defaultView} data-slot=\"chart-frame-views\" className=\"gap-4\">\n      <TabsList aria-label={labels.views} className=\"self-start\">\n        <TabsTrigger value=\"chart\">{labels.chart}</TabsTrigger>\n        <TabsTrigger value=\"table\">{labels.table}</TabsTrigger>\n      </TabsList>\n      <TabsContent value=\"chart\" keepMounted data-slot=\"chart-frame-body\" className=\"min-w-0\">\n        {children}\n      </TabsContent>\n      <TabsContent value=\"table\" keepMounted data-slot=\"chart-frame-table\" className=\"min-w-0 overflow-x-auto\">\n        {table}\n      </TabsContent>\n    </Tabs>\n  ) : (\n    <div data-slot=\"chart-frame-body\" className=\"min-w-0\">\n      {children}\n    </div>\n  );\n\n  return (\n    <figure\n      ref={ref}\n      data-slot=\"chart-frame\"\n      data-min-viewport={String(MIN_VIEWPORT)}\n      aria-labelledby={title ? titleId : undefined}\n      className={cn('m-0 flex w-full min-w-0 flex-col gap-4', className)}\n      {...props}\n    >\n      {title || subtitle ? (\n        <header data-slot=\"chart-frame-header\" className=\"flex max-w-prose flex-col gap-1\">\n          {title ? (\n            <Heading\n              id={titleId}\n              data-slot=\"chart-frame-title\"\n              className=\"text-foreground font-heading m-0 text-h3 font-semibold text-balance\"\n            >\n              {title}\n            </Heading>\n          ) : null}\n          {subtitle ? (\n            <p data-slot=\"chart-frame-subtitle\" className=\"text-muted-foreground m-0 text-ui\">\n              {subtitle}\n            </p>\n          ) : null}\n        </header>\n      ) : null}\n\n      {body}\n\n      {hasFooter ? (\n        <figcaption\n          data-slot=\"chart-frame-footer\"\n          className=\"text-muted-foreground border-border flex flex-col gap-1.5 border-t pt-3 text-caption\"\n        >\n          {sources.length > 0 ? (\n            <p data-slot=\"chart-frame-sources\" className=\"m-0\">\n              <span className=\"text-foreground font-medium\">\n                {sources.length === 1 ? labels.source : labels.sources}:\n              </span>{' '}\n              {sources.map((source, i) => {\n                const link = safeHref(source.href);\n                return (\n                  <React.Fragment key={`${source.label}-${i}`}>\n                    {i > 0 ? '; ' : null}\n                    {link ? (\n                      <a\n                        href={link}\n                        className=\"text-foreground underline decoration-border underline-offset-2 hover:decoration-current focus-visible:ring-ring focus-visible:ring-offset-background rounded-sm focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:outline-hidden\"\n                      >\n                        {source.label}\n                      </a>\n                    ) : (\n                      source.label\n                    )}\n                  </React.Fragment>\n                );\n              })}\n            </p>\n          ) : null}\n          {note ? (\n            <p data-slot=\"chart-frame-note\" className=\"m-0\">\n              <span className=\"text-foreground font-medium\">{labels.note}:</span> {note}\n            </p>\n          ) : null}\n          {updated || download ? (\n            <p className=\"m-0 flex flex-wrap items-center gap-x-3 gap-y-1\">\n              {updated ? (\n                <span>\n                  {labels.updated}{' '}\n                  <time data-slot=\"chart-frame-updated\" dateTime={isoDate}>\n                    {dateText}\n                  </time>\n                </span>\n              ) : null}\n              {download ? (\n                <a\n                  data-slot=\"chart-frame-download\"\n                  href={href}\n                  download={filename}\n                  className=\"text-foreground inline-flex min-h-target items-center gap-1.5 rounded-sm font-medium underline decoration-border underline-offset-2 hover:decoration-current focus-visible:ring-ring focus-visible:ring-offset-background focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:outline-hidden\"\n                >\n                  <svg aria-hidden viewBox=\"0 0 16 16\" className=\"size-3.5 fill-none stroke-current\" strokeWidth={1.5} strokeLinecap=\"round\" strokeLinejoin=\"round\">\n                    <path d=\"M8 2.5v8M4.5 7 8 10.5 11.5 7M3 13.5h10\" />\n                  </svg>\n                  {labels.download}\n                </a>\n              ) : null}\n            </p>\n          ) : null}\n        </figcaption>\n      ) : null}\n    </figure>\n  );\n});\nChartFrame.displayName = 'ChartFrame';\n"
    }
  ],
  "meta": {
    "tier": "chart",
    "client": true,
    "minViewport": 320,
    "loading": false,
    "version": "1.0.1",
    "since": "2.0.0"
  },
  "docs": "## @interlace/chart-frame\n\nInstalled to `components/ui/charts/chart-frame.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/charts/chart-frame';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/chart-frame\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
