{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "core",
  "type": "registry:lib",
  "title": "ChartslibraryUI core",
  "description": "Shared chart core: frame, scales, paths, formatting, data checks and theme (charts.css). Required by every chart.",
  "dependencies": [],
  "registryDependencies": [],
  "files": [
    {
      "path": "registry/charts/core/axis.tsx",
      "type": "registry:lib",
      "target": "components/charts/core/axis.tsx",
      "content": "// core/axis.tsx · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com\n\"use client\";\n\nimport type { ReactNode, SVGProps } from \"react\";\nimport { textWidth, thinLabels, truncate } from \"./text\";\n\nexport const AXIS_FONT = 11;\nexport const LABEL_FONT = 11;\n\n/** Width needed for a column of y-axis labels. */\nexport function axisWidth(labels: string[], fontSize = AXIS_FONT, pad = 8) {\n  return Math.ceil(Math.max(0, ...labels.map((l) => textWidth(l, fontSize)))) + pad;\n}\n\n/** Horizontal hairline gridlines with labels on the left. The zero line is drawn stronger. */\nexport function YGrid({\n  ticks,\n  y,\n  x0,\n  x1,\n  format,\n  labels = true,\n}: {\n  ticks: number[];\n  y: (v: number) => number;\n  x0: number;\n  x1: number;\n  format: (v: number) => string;\n  labels?: boolean;\n}) {\n  return (\n    <g className=\"clui-axis\" aria-hidden>\n      {ticks.map((t) => {\n        const py = Math.round(y(t)) + 0.5;\n        return (\n          <g key={t}>\n            <line\n              x1={x0}\n              x2={x1}\n              y1={py}\n              y2={py}\n              style={{ stroke: t === 0 ? \"var(--clui-axis)\" : \"var(--clui-grid)\" }}\n              shapeRendering=\"crispEdges\"\n            />\n            {labels && (\n              <text x={x0 - 8} y={py} dy=\"0.32em\" textAnchor=\"end\" className=\"clui-tick\">\n                {format(t)}\n              </text>\n            )}\n          </g>\n        );\n      })}\n    </g>\n  );\n}\n\n/** Vertical hairline gridlines with labels underneath (horizontal bar charts, scatter x axis). */\nexport function XGrid({\n  ticks,\n  x,\n  y0,\n  y1,\n  format,\n  labels = true,\n  labelY,\n}: {\n  ticks: number[];\n  x: (v: number) => number;\n  y0: number;\n  y1: number;\n  format: (v: number) => string;\n  labels?: boolean;\n  labelY?: number;\n}) {\n  const positions = ticks.map((t) => x(t));\n  const texts = ticks.map((t) => format(t));\n  const keep = thinLabels(positions, texts, AXIS_FONT, 8);\n  return (\n    <g className=\"clui-axis\" aria-hidden>\n      {ticks.map((t, i) => {\n        const px = Math.round(positions[i]) + 0.5;\n        return (\n          <g key={t}>\n            <line\n              x1={px}\n              x2={px}\n              y1={y0}\n              y2={y1}\n              style={{ stroke: t === 0 ? \"var(--clui-axis)\" : \"var(--clui-grid)\" }}\n              shapeRendering=\"crispEdges\"\n            />\n            {labels && keep[i] && (\n              <text x={px} y={labelY ?? y1 + 16} textAnchor=\"middle\" className=\"clui-tick\">\n                {texts[i]}\n              </text>\n            )}\n          </g>\n        );\n      })}\n    </g>\n  );\n}\n\n/**\n * Category or date labels along the bottom. Labels are thinned so they never overlap; hidden labels stay\n * available in the tooltip and the table.\n */\nexport function XLabels({\n  positions,\n  labels,\n  y,\n  maxLabelWidth = 120,\n  anchorEnds = false,\n  x0,\n  x1,\n  ticks = false,\n  tickTop,\n}: {\n  positions: number[];\n  labels: string[];\n  y: number;\n  maxLabelWidth?: number;\n  /** Align first/last label to the plot edges so they don't overflow. */\n  anchorEnds?: boolean;\n  x0?: number;\n  x1?: number;\n  ticks?: boolean;\n  tickTop?: number;\n}) {\n  const shown = labels.map((l) => truncate(l, maxLabelWidth, AXIS_FONT));\n  const widths = shown.map((l) => textWidth(l, AXIS_FONT));\n  // Where a label would overflow the plot edge, anchor it to the edge; thin using the shifted centres.\n  const anchors = positions.map((px, i): \"start\" | \"middle\" | \"end\" => {\n    if (anchorEnds && x0 !== undefined && px - widths[i] / 2 < x0) return \"start\";\n    if (anchorEnds && x1 !== undefined && px + widths[i] / 2 > x1) return \"end\";\n    return \"middle\";\n  });\n  const textX = positions.map((px, i) =>\n    anchors[i] === \"start\" ? Math.max(px - 4, x0 ?? px) : anchors[i] === \"end\" ? Math.min(px + 4, x1 ?? px) : px,\n  );\n  const centres = textX.map((tx, i) =>\n    anchors[i] === \"start\" ? tx + widths[i] / 2 : anchors[i] === \"end\" ? tx - widths[i] / 2 : tx,\n  );\n  const keep = thinLabels(centres, shown, AXIS_FONT, 12);\n  return (\n    <g className=\"clui-axis\" aria-hidden>\n      {positions.map((px, i) => {\n        if (!keep[i]) return null;\n        const anchor = anchors[i];\n        const tx = textX[i];\n        return (\n          <g key={i}>\n            {ticks && tickTop !== undefined && (\n              <line x1={px} x2={px} y1={tickTop} y2={tickTop + 4} style={{ stroke: \"var(--clui-axis)\" }} />\n            )}\n            <text x={tx} y={y} textAnchor={anchor} className=\"clui-tick\">\n              {shown[i]}\n              {shown[i] !== labels[i] && <title>{labels[i]}</title>}\n            </text>\n          </g>\n        );\n      })}\n    </g>\n  );\n}\n\n/** Shaded region marking forecast or partial periods, with a label at the top. */\nexport function PeriodShade({\n  x0,\n  x1,\n  top,\n  bottom,\n  label,\n  kind = \"forecast\",\n}: {\n  x0: number;\n  x1: number;\n  top: number;\n  bottom: number;\n  label?: string;\n  kind?: \"forecast\" | \"partial\";\n}) {\n  if (x1 <= x0) return null;\n  return (\n    <g aria-hidden>\n      <rect\n        x={x0}\n        y={top}\n        width={x1 - x0}\n        height={bottom - top}\n        style={{ fill: kind === \"forecast\" ? \"var(--clui-forecast-bg)\" : \"var(--clui-partial-bg)\" }}\n      />\n      <line x1={x0} x2={x0} y1={top} y2={bottom} style={{ stroke: \"var(--clui-axis)\" }} strokeDasharray=\"2 3\" />\n      {label && (\n        <text x={x0 + 6} y={top + 12} className=\"clui-annot\">\n          {label}\n        </text>\n      )}\n    </g>\n  );\n}\n\n/** A labelled horizontal reference line (target, average, threshold). */\nexport function RefLine({\n  y,\n  x0,\n  x1,\n  label,\n  align = \"end\",\n}: {\n  y: number;\n  x0: number;\n  x1: number;\n  label?: ReactNode;\n  align?: \"start\" | \"end\";\n}) {\n  return (\n    <g aria-hidden>\n      <line x1={x0} x2={x1} y1={y} y2={y} style={{ stroke: \"var(--clui-ink-2)\" }} strokeDasharray=\"4 3\" />\n      {label && (\n        <text\n          x={align === \"end\" ? x1 : x0}\n          y={y - 5}\n          textAnchor={align === \"end\" ? \"end\" : \"start\"}\n          className=\"clui-annot clui-halo\"\n        >\n          {label}\n        </text>\n      )}\n    </g>\n  );\n}\n\n/** Text with a surface-coloured halo so it stays readable over marks. */\nexport function HaloText(props: SVGProps<SVGTextElement>) {\n  return <text {...props} className={[\"clui-halo\", props.className].filter(Boolean).join(\" \")} />;\n}\n\n/**\n * Place end labels for lines without overlap. Returns adjusted y positions (sorted greedy spacing). If the labels\n * would need to move more than `maxShift`, returns null: fall back to the legend instead.\n */\nexport function placeEndLabels(ys: number[], minGap = 14, top = 0, bottom = Infinity, maxShift = 28): number[] | null {\n  const order = ys.map((y, i) => ({ y, i })).sort((a, b) => a.y - b.y);\n  const placed = order.map((o) => o.y);\n  for (let k = 1; k < placed.length; k++) if (placed[k] - placed[k - 1] < minGap) placed[k] = placed[k - 1] + minGap;\n  const overflow = placed[placed.length - 1] - bottom;\n  if (overflow > 0) for (let k = 0; k < placed.length; k++) placed[k] -= overflow;\n  for (let k = 0; k < placed.length; k++) placed[k] = Math.max(top, placed[k]);\n  for (let k = 1; k < placed.length; k++) if (placed[k] - placed[k - 1] < minGap) placed[k] = placed[k - 1] + minGap;\n  const out = new Array<number>(ys.length);\n  let worst = 0;\n  order.forEach((o, k) => {\n    out[o.i] = placed[k];\n    worst = Math.max(worst, Math.abs(placed[k] - o.y));\n  });\n  return worst > maxShift ? null : out;\n}\n"
    },
    {
      "path": "registry/charts/core/bars.tsx",
      "type": "registry:lib",
      "target": "components/charts/core/bars.tsx",
      "content": "// core/bars.tsx · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com\n\"use client\";\n\n/**\n * Shared engine for bar and column charts: single, grouped, stacked and 100% stacked, vertical or horizontal.\n * Bars always start at zero. Bars are at most 24px thick, with a rounded data end and a square baseline.\n */\n\nimport { useMemo, type PointerEvent } from \"react\";\nimport { AXIS_FONT, RefLine, XGrid, XLabels, YGrid, axisWidth } from \"./axis\";\nimport { PALETTE_SIZE, seriesColors, toneColor, toneOf, type Favorable } from \"./color\";\nimport { checkRows, column, type Issue, type Row } from \"./data\";\nimport { formatValue, labelFormatter, tickFormatter, type FormatInput } from \"./format\";\nimport {\n  ChartFrame,\n  ChartTooltip,\n  localPoint,\n  useActiveIndex,\n  useSeriesToggle,\n  type FrameProps,\n  type LegendItem,\n  type TooltipRow,\n} from \"./frame\";\nimport { barPath } from \"./path\";\nimport { bandScale, linearScale, valueDomain } from \"./scale\";\nimport { textWidth, truncate } from \"./text\";\nimport { normalizeSeries, type Reference, type SeriesInput } from \"./series\";\nimport type { ChartWords } from \"./words\";\nimport { useWords } from \"./words\";\n\nexport interface BarChartBaseProps extends FrameProps {\n  data: Row[];\n  /** Key of the category label in each row. */\n  x: string;\n  series: SeriesInput[];\n  format?: FormatInput;\n  /** Category values to emphasise (single series). Others are grey. */\n  highlight?: string | string[];\n  /** Sort categories by value (single series) or total (stacked). */\n  sort?: \"none\" | \"asc\" | \"desc\";\n  /** Value labels at bar ends. \"auto\" shows them when they fit. */\n  labels?: boolean | \"auto\";\n  /** First category that is an incomplete period; drawn lighter and marked. */\n  partialFrom?: string;\n  /** Categories that are forecasts; drawn hollow and marked. */\n  forecastFrom?: string;\n  references?: Reference[];\n  /** Colour bars by sign using `favorable` (diverging bars). */\n  colorBySign?: boolean;\n  favorable?: Favorable;\n  /** Show the legend. Default: on for 2+ series. */\n  legend?: boolean;\n  /** Max bar thickness in px. */\n  maxBarSize?: number;\n}\n\nexport type BarLayout = \"single\" | \"grouped\" | \"stacked\" | \"stacked100\";\n\nconst GAP = 2;\n\nexport function BarsChart(\n  props: BarChartBaseProps & { layout: BarLayout; orientation: \"vertical\" | \"horizontal\"; summaryName?: string },\n) {\n  const L = useWords(props.words);\n  const {\n    data,\n    x,\n    series: seriesInput,\n    format,\n    highlight,\n    sort = \"none\",\n    labels = \"auto\",\n    partialFrom,\n    forecastFrom,\n    references = [],\n    colorBySign = false,\n    favorable = \"up\",\n    legend,\n    maxBarSize = 24,\n    layout,\n    orientation,\n    summaryName,\n    height: heightProp,\n    ...frame\n  } = props;\n  const series = useMemo(() => normalizeSeries(seriesInput), [seriesInput]);\n  const keys = series.map((s) => s.key);\n  const toggle = useSeriesToggle(keys);\n  const visible = series.filter((s) => !toggle.hidden.has(s.key));\n  const stacked = layout === \"stacked\" || layout === \"stacked100\";\n\n  const keySig = keys.join(\"|\");\n  const prep = useMemo(() => {\n    const issues: Issue[] = checkRows(data, { xKey: x, valueKeys: keys, maxSeries: PALETTE_SIZE, allowMissing: false });\n    let rows = Array.isArray(data) ? [...data] : [];\n    if (layout === \"stacked100\") {\n      const neg = rows.some((r) => keys.some((k) => typeof r?.[k] === \"number\" && (r[k] as number) < 0));\n      if (neg)\n        issues.push({ level: \"error\", message: \"100% stacked bars can't show negative values. Use stacked or grouped bars.\" });\n    }\n    if (sort !== \"none\") {\n      const val = (r: Row) => keys.reduce((a, k) => a + (typeof r?.[k] === \"number\" ? (r[k] as number) : 0), 0);\n      rows = rows.sort((a, b) => (sort === \"asc\" ? val(a) - val(b) : val(b) - val(a)));\n    }\n    const cols = Object.fromEntries(keys.map((k) => [k, column(rows, k).values]));\n    return { issues, rows, cols };\n  }, [data, x, keySig, sort, layout]); // eslint-disable-line react-hooks/exhaustive-deps\n  const { issues, rows, cols } = prep;\n  const n = rows.length;\n  const cats = rows.map((r) => String(r?.[x] ?? \"\"));\n\n  const horizontal = orientation === \"horizontal\";\n  const rowSize = layout === \"grouped\" ? Math.min(maxBarSize, 20) * visible.length + 14 : Math.min(maxBarSize, 22) + 12;\n  const height = heightProp ?? (horizontal ? Math.max(120, n * rowSize + 30) : 280);\n\n  const colors = seriesColors(series);\n  const hl = highlight === undefined ? null : new Set(Array.isArray(highlight) ? highlight : [highlight]);\n\n  const partialIndex = partialFrom !== undefined ? cats.indexOf(String(partialFrom)) : -1;\n  const forecastIndex = forecastFrom !== undefined ? cats.indexOf(String(forecastFrom)) : -1;\n\n  // per category segments\n  const visibleSig = visible.map((s) => s.key).join(\"|\");\n  const segs = useMemo(() => {\n    return rows.map((_, i) => {\n      const total = visible.reduce((a, s) => a + Math.max(0, cols[s.key][i] ?? 0), 0);\n      let pos = 0;\n      let neg = 0;\n      return visible.map((s, j) => {\n        let v = cols[s.key][i];\n        if (v === null) return { key: s.key, j, v: null as number | null, a: 0, b: 0, raw: null as number | null };\n        const raw = v;\n        if (layout === \"stacked100\") v = total === 0 ? 0 : v / total;\n        if (!stacked) return { key: s.key, j, v, a: 0, b: v, raw };\n        if (v >= 0) {\n          const a = pos;\n          pos += v;\n          return { key: s.key, j, v, a, b: pos, raw };\n        }\n        const a = neg;\n        neg += v;\n        return { key: s.key, j, v, a, b: neg, raw };\n      });\n    });\n  }, [rows, cols, visibleSig, layout]); // eslint-disable-line react-hooks/exhaustive-deps\n\n  const values: number[] = [];\n  for (const cat of segs) for (const s of cat) if (s.v !== null) values.push(s.a, s.b);\n  for (const r of references) values.push(r.value);\n\n  const legendItems: LegendItem[] =\n    legend === false || (legend === undefined && series.length < 2)\n      ? []\n      : series.map((s) => ({ key: s.key, label: s.label!, color: colors[s.key], shape: \"square\" }));\n  if (colorBySign && legend !== false && series.length === 1) {\n    legendItems.push(\n      { key: \"__good\", label: favorable === \"down\" ? \"Decrease (favorable)\" : \"Increase (favorable)\", color: \"var(--clui-good)\" },\n      { key: \"__bad\", label: favorable === \"down\" ? \"Increase (unfavorable)\" : \"Decrease (unfavorable)\", color: \"var(--clui-bad)\" },\n    );\n  }\n\n  const fmtTable = (v: unknown) => formatValue(v as number, format, { context: \"table\" });\n  const table = {\n    columns: [\n      { key: \"__x\", label: x },\n      ...series.map((s) => ({ key: s.key, label: s.label!, align: \"right\" as const, format: fmtTable })),\n      ...(stacked && series.length > 1 ? [{ key: \"__total\", label: L.total, align: \"right\" as const, format: fmtTable }] : []),\n    ],\n    rows: rows.map((r, i) => ({\n      __x: cats[i],\n      ...Object.fromEntries(series.map((s) => [s.key, cols[s.key][i]])),\n      __total: series.reduce((a, s) => a + (cols[s.key][i] ?? 0), 0),\n    })),\n  };\n\n  const summary = (() => {\n    if (!n) return \"Bar chart with no data.\";\n    const s0 = series[0];\n    const vals = cols[s0?.key] ?? [];\n    let maxI = 0;\n    let minI = 0;\n    vals.forEach((v, i) => {\n      if ((v ?? -Infinity) > (vals[maxI] ?? -Infinity)) maxI = i;\n      if ((v ?? Infinity) < (vals[minI] ?? Infinity)) minI = i;\n    });\n    return `${summaryName ?? \"Bar chart\"} of ${series.map((s) => s.label).join(\", \")} across ${n} categories. ${\n      s0?.label\n    } is highest for ${cats[maxI]} (${formatValue(vals[maxI], format)}) and lowest for ${cats[minI]} (${formatValue(\n      vals[minI],\n      format,\n    )}). Use arrow keys to read values.`;\n  })();\n\n  return (\n    <ChartFrame\n      {...frame}\n      height={height}\n      issues={issues}\n      table={table}\n      summary={summary}\n      legend={legendItems}\n      legendHidden={toggle.hidden}\n      onLegendToggle={series.length > 1 ? toggle.toggle : undefined}\n      onLegendHover={(k) => toggle.setFocus(k && !k.startsWith(\"__\") ? k : null)}\n    >\n      {({ width }) => {\n        const p = {\n          width,\n          height,\n          n,\n          cats,\n          rows,\n          segs,\n          values,\n          visible,\n          colors,\n          hl,\n          layout,\n          stacked,\n          format,\n          labels,\n          partialIndex,\n          forecastIndex,\n          references,\n          colorBySign,\n          favorable,\n          maxBarSize,\n          focus: toggle.focus,\n          rawCols: cols,\n        };\n        return horizontal ? <HorizontalPlot {...p} /> : <VerticalPlot {...p} />;\n      }}\n    </ChartFrame>\n  );\n}\n\ntype Seg = { key: string; j: number; v: number | null; a: number; b: number; raw: number | null };\n\ninterface PlotP {\n  width: number;\n  height: number;\n  n: number;\n  cats: string[];\n  rows: Row[];\n  segs: Seg[][];\n  values: number[];\n  visible: { key: string; label?: string }[];\n  colors: Record<string, string>;\n  hl: Set<string> | null;\n  layout: BarLayout;\n  stacked: boolean;\n  format?: FormatInput;\n  labels: boolean | \"auto\";\n  partialIndex: number;\n  forecastIndex: number;\n  references: Reference[];\n  colorBySign: boolean;\n  favorable: Favorable;\n  maxBarSize: number;\n  focus: string | null;\n  rawCols: Record<string, (number | null)[]>;\n}\n\nfunction fillFor(p: PlotP, seg: Seg, cat: string) {\n  if (p.colorBySign) return toneColor(toneOf(seg.raw, p.favorable));\n  if (p.hl && p.visible.length === 1) return p.hl.has(cat) ? p.colors[seg.key] : \"var(--clui-context)\";\n  return p.colors[seg.key];\n}\n\nfunction tooltipFor(p: PlotP, i: number, L: ChartWords) {\n  const rows: TooltipRow[] = p.segs[i].map((s) => ({\n    label: p.visible[s.j].label ?? s.key,\n    value: formatValue(s.raw, p.format, { context: \"tooltip\" }),\n    note:\n      p.layout === \"stacked100\" && s.v !== null ? `(${formatValue(s.v, { kind: \"percent\", decimals: 0 })})` : undefined,\n    color: fillFor(p, s, p.cats[i]),\n    shape: \"square\",\n  }));\n  if (p.stacked && p.visible.length > 1) {\n    rows.reverse();\n    rows.push({\n      label: L.total,\n      value: formatValue(\n        p.segs[i].reduce((a, s) => a + (s.raw ?? 0), 0),\n        p.format,\n        { context: \"tooltip\" },\n      ),\n      strong: true,\n    });\n  }\n  const tags = [\n    p.partialIndex >= 0 && i >= p.partialIndex ? \"Partial period\" : null,\n    p.forecastIndex >= 0 && i >= p.forecastIndex ? L.forecast : null,\n  ].filter(Boolean);\n  return { title: p.cats[i], rows, footer: tags.length ? tags.join(\" · \") : undefined };\n}\n\n/** One label formatter per plot so every bar label shares a magnitude. */\nfunction labelFmt(p: PlotP) {\n  return labelFormatter(p.format, p.segs.map((cat) => cat.reduce((a, s) => a + (s.raw ?? 0), 0)));\n}\n\nfunction markStyle(p: PlotP, i: number, fill: string) {\n  const forecast = p.forecastIndex >= 0 && i >= p.forecastIndex;\n  const partial = p.partialIndex >= 0 && i >= p.partialIndex;\n  if (forecast) return { fill: \"transparent\", stroke: fill, strokeWidth: 1.5, strokeDasharray: \"3 2\" };\n  if (partial) return { fill, opacity: 0.45 };\n  return { fill };\n}\n\nfunction VerticalPlot(p: PlotP) {\n  const L = useWords();\n  const fmtLabel = labelFmt(p);\n  const { width, height, n, cats } = p;\n  const { active, setActive, keyProps } = useActiveIndex(n, { describe: (i) => ({ label: cats[i], row: p.rows[i] }) });\n  const tickCount = Math.max(2, Math.min(6, Math.floor(height / 50)));\n  const { domain, ticks } = valueDomain(p.values, {\n    includeZero: true,\n    ticks: tickCount,\n    domain: p.layout === \"stacked100\" ? [0, 1] : undefined,\n  });\n  const yFmt = p.layout === \"stacked100\" ? { kind: \"percent\" as const, decimals: 0 } : p.format;\n  const fmtTick = tickFormatter(yFmt, ticks);\n  const left = axisWidth(ticks.map(fmtTick));\n  const right = width - 8;\n  const hasMarkerRow = p.partialIndex >= 0 || p.forecastIndex >= 0;\n  const top = hasMarkerRow ? 22 : 16;\n  const bottom = height - 24;\n  const y = linearScale(domain, [bottom, top]);\n  const band = bandScale(n, [left, right], { paddingInner: 0.3, paddingOuter: 0.15 });\n  const groups = p.layout === \"grouped\" ? p.visible.length : 1;\n  const groupW = Math.min(band.bandwidth, p.maxBarSize * groups + GAP * (groups - 1));\n  const barW = Math.max(1, (groupW - GAP * (groups - 1)) / groups);\n  const zeroY = y(0);\n\n  const mixedSigns = p.stacked && p.segs.some((cat) => cat.some((s) => (s.v ?? 0) < 0) && cat.some((s) => (s.v ?? 0) > 0));\n  const labelFits =\n    p.labels === true ||\n    (p.labels === \"auto\" &&\n      p.layout !== \"grouped\" &&\n      p.layout !== \"stacked100\" &&\n      !mixedSigns &&\n      n <= 16 &&\n      cats.every((_, i) => {\n        const total = p.segs[i].reduce((a, s) => a + (s.raw ?? 0), 0);\n        return textWidth(fmtLabel(total), 10.5) <= band.step - 4;\n      }));\n\n  const onMove = (e: PointerEvent<SVGRectElement>) => setActive(band.indexAt(localPoint(e).x + left));\n\n  return (\n    <>\n      <svg width={width} height={height} role=\"group\" aria-roledescription=\"chart\" aria-label=\"Bar chart. Use arrow keys to read values.\" {...keyProps}>\n        <YGrid ticks={ticks} y={y} x0={left} x1={right} format={fmtTick} />\n        <XLabels\n          positions={cats.map((_, i) => band(i) + band.bandwidth / 2)}\n          labels={cats}\n          y={bottom + 17}\n          maxLabelWidth={Math.max(40, band.step * 3)}\n          anchorEnds\n          x0={left - 8}\n          x1={width}\n        />\n        {hasMarkerRow &&\n          (() => {\n            const mi = Math.min(...[p.partialIndex, p.forecastIndex].filter((v) => v >= 0));\n            return (\n              <text x={right} y={11} textAnchor=\"end\" className=\"clui-annot\">\n                {mi === p.forecastIndex ? \"Forecast (outlined)\" : \"Partial period (faded)\"}\n              </text>\n            );\n          })()}\n        {active !== null && (\n          <rect x={band(active) - (band.step - band.bandwidth) / 2} y={top} width={band.step} height={bottom - top} style={{ fill: \"var(--clui-grid)\", opacity: 0.6 }} />\n        )}\n        {p.segs.map((cat, i) => {\n          const cx = band(i) + (band.bandwidth - groupW) / 2;\n          const outer = (s: Seg) => {\n            if (!p.stacked) return true;\n            const sameSide = cat.filter((o) => o.v !== null && o.v !== 0 && Math.sign(o.v) === Math.sign(s.v ?? 0));\n            return sameSide[sameSide.length - 1] === s;\n          };\n          return (\n            <g key={i}>\n              {cat.map((s) => {\n                if (s.v === null || s.a === s.b) return null;\n                const bx = p.layout === \"grouped\" ? cx + s.j * (barW + GAP) : cx;\n                const w = p.layout === \"grouped\" ? barW : groupW;\n                const ya = y(s.a);\n                const yb = y(s.b);\n                const up = s.b > s.a || (s.b === s.a && s.v >= 0);\n                const isOuter = outer(s);\n                // 2px surface gap between stacked segments\n                const gapA = p.stacked && s.a !== 0 ? GAP / 2 : 0;\n                const gapB = p.stacked && !isOuter ? GAP / 2 : 0;\n                let y0 = Math.min(ya, yb);\n                let h = Math.abs(yb - ya);\n                if (up) {\n                  y0 += gapB;\n                  h -= gapA + gapB;\n                } else {\n                  y0 += gapA;\n                  h -= gapA + gapB;\n                }\n                h = Math.max(h, s.v !== 0 ? 1 : 0);\n                const fill = fillFor(p, s, cats[i]);\n                const style = markStyle(p, i, fill);\n                const d = isOuter ? barPath(bx, y0, w, h, 4, up ? \"up\" : \"down\") : `M${bx},${y0}h${w}v${h}h${-w}Z`;\n                const dim = p.focus !== null && p.focus !== s.key;\n                return <path key={s.key} d={d} style={style} className={`clui-mark${dim ? \" clui-dim\" : \"\"}`} />;\n              })}\n              {labelFits &&\n                (() => {\n                  const total = cat.reduce((a, s) => a + (s.raw ?? 0), 0);\n                  if (cat.every((s) => s.v === null)) return null;\n                  const end = p.stacked ? (total >= 0 ? Math.max(0, ...cat.map((s) => s.b)) : Math.min(0, ...cat.map((s) => s.b))) : total;\n                  const ly = total >= 0 ? y(end) - 5 : y(end) + 13;\n                  return (\n                    <text x={band(i) + band.bandwidth / 2} y={ly} textAnchor=\"middle\" className=\"clui-label\">\n                      {fmtLabel(total)}\n                    </text>\n                  );\n                })()}\n            </g>\n          );\n        })}\n        <line x1={left} x2={right} y1={Math.round(zeroY) + 0.5} y2={Math.round(zeroY) + 0.5} style={{ stroke: \"var(--clui-axis)\" }} />\n        {p.references.map((r, i) => (\n          <RefLine key={i} y={y(r.value)} x0={left} x1={right} label={r.label} />\n        ))}\n        <rect\n          x={left}\n          y={0}\n          width={Math.max(0, right - left)}\n          height={bottom}\n          fill=\"transparent\"\n          onPointerMove={onMove}\n          onPointerDown={onMove}\n          onPointerLeave={() => setActive(null)}\n        />\n      </svg>\n      {active !== null && (\n        <ChartTooltip\n          x={band(active) + band.bandwidth / 2}\n          y={y(Math.max(0, ...p.segs[active].map((s) => s.b)))}\n          width={width}\n          height={height}\n          data={tooltipFor(p, active, L)}\n        />\n      )}\n    </>\n  );\n}\n\nfunction HorizontalPlot(p: PlotP) {\n  const L = useWords();\n  const fmtLabel = labelFmt(p);\n  const { width, height, n, cats } = p;\n  const { active, setActive, keyProps } = useActiveIndex(n, { describe: (i) => ({ label: cats[i], row: p.rows[i] }) });\n  const labelCol = Math.min(Math.max(...cats.map((c) => textWidth(c, AXIS_FONT)), 20) + 12, Math.max(80, width * 0.38));\n  const left = labelCol;\n  const hasNeg = p.values.some((v) => v < 0);\n  const showAxis = p.labels === false || p.layout === \"grouped\" || p.layout === \"stacked100\";\n  const labelRoom = showAxis ? 10 : 56;\n  const right = width - labelRoom;\n  const top = 4;\n  const bottom = showAxis ? height - 22 : height - 4;\n  const tickCount = Math.max(2, Math.min(6, Math.floor((right - left) / 90)));\n  const { domain, ticks } = valueDomain(p.values, {\n    includeZero: true,\n    ticks: tickCount,\n    domain: p.layout === \"stacked100\" ? [0, 1] : undefined,\n  });\n  const xFmt = p.layout === \"stacked100\" ? { kind: \"percent\" as const, decimals: 0 } : p.format;\n  const fmtTick = tickFormatter(xFmt, ticks);\n  // with negative values, leave room for labels on the left of negative bars\n  const negRoom = hasNeg && !showAxis ? 52 : 0;\n  const xs = linearScale(domain, [left + negRoom, right]);\n  const band = bandScale(n, [top, bottom], { paddingInner: 0.3, paddingOuter: 0.1 });\n  const groups = p.layout === \"grouped\" ? p.visible.length : 1;\n  const groupH = Math.min(band.bandwidth, p.maxBarSize * groups + GAP * (groups - 1));\n  const barH = Math.max(1, (groupH - GAP * (groups - 1)) / groups);\n  const zeroX = xs(0);\n  const onMove = (e: PointerEvent<SVGRectElement>) => setActive(band.indexAt(localPoint(e).y));\n\n  return (\n    <>\n      <svg width={width} height={height} role=\"group\" aria-roledescription=\"chart\" aria-label=\"Bar chart. Use arrow keys to read values.\" {...keyProps}>\n        {showAxis && <XGrid ticks={ticks} x={xs} y0={top} y1={bottom} format={fmtTick} />}\n        {active !== null && (\n          <rect x={0} y={band(active) - (band.step - band.bandwidth) / 2} width={width} height={band.step} style={{ fill: \"var(--clui-grid)\", opacity: 0.6 }} />\n        )}\n        {cats.map((c, i) => (\n          <text key={i} x={left - 10} y={band(i) + band.bandwidth / 2} dy=\"0.32em\" textAnchor=\"end\" className=\"clui-tick\" style={{ fill: \"var(--clui-ink)\" }}>\n            {truncate(c, left - 14, AXIS_FONT)}\n            <title>{c}</title>\n          </text>\n        ))}\n        {p.segs.map((cat, i) => {\n          const cy = band(i) + (band.bandwidth - groupH) / 2;\n          const outer = (s: Seg) => {\n            if (!p.stacked) return true;\n            const same = cat.filter((o) => o.v !== null && o.v !== 0 && Math.sign(o.v) === Math.sign(s.v ?? 0));\n            return same[same.length - 1] === s;\n          };\n          const total = cat.reduce((a, s) => a + (s.raw ?? 0), 0);\n          const endVal = p.stacked ? (total >= 0 ? Math.max(0, ...cat.map((s) => s.b)) : Math.min(0, ...cat.map((s) => s.b))) : total;\n          return (\n            <g key={i}>\n              {cat.map((s) => {\n                if (s.v === null || s.a === s.b) return null;\n                const by = p.layout === \"grouped\" ? cy + s.j * (barH + GAP) : cy;\n                const h = p.layout === \"grouped\" ? barH : groupH;\n                const xa = xs(s.a);\n                const xb = xs(s.b);\n                const rightward = s.b >= s.a;\n                const isOuter = outer(s);\n                const gapA = p.stacked && s.a !== 0 ? GAP / 2 : 0;\n                const gapB = p.stacked && !isOuter ? GAP / 2 : 0;\n                let x0 = Math.min(xa, xb);\n                let w = Math.abs(xb - xa);\n                if (rightward) {\n                  x0 += gapA;\n                  w -= gapA + gapB;\n                } else {\n                  x0 += gapB;\n                  w -= gapA + gapB;\n                }\n                w = Math.max(w, 1);\n                const fill = fillFor(p, s, cats[i]);\n                const d = isOuter ? barPath(x0, by, w, h, 4, rightward ? \"right\" : \"left\") : `M${x0},${by}h${w}v${h}h${-w}Z`;\n                const dim = p.focus !== null && p.focus !== s.key;\n                return <path key={s.key} d={d} style={markStyle(p, i, fill)} className={`clui-mark${dim ? \" clui-dim\" : \"\"}`} />;\n              })}\n              {!showAxis && cat.some((s) => s.v !== null) && (\n                <text\n                  x={endVal >= 0 ? xs(endVal) + 6 : xs(endVal) - 6}\n                  y={band(i) + band.bandwidth / 2}\n                  dy=\"0.32em\"\n                  textAnchor={endVal >= 0 ? \"start\" : \"end\"}\n                  className=\"clui-label\"\n                >\n                  {fmtLabel(total)}\n                </text>\n              )}\n            </g>\n          );\n        })}\n        <line x1={Math.round(zeroX) + 0.5} x2={Math.round(zeroX) + 0.5} y1={top} y2={bottom} style={{ stroke: \"var(--clui-axis)\" }} />\n        {p.references.map((r, i) => (\n          <g key={i} aria-hidden>\n            <line x1={xs(r.value)} x2={xs(r.value)} y1={top} y2={bottom} style={{ stroke: \"var(--clui-ink-2)\" }} strokeDasharray=\"4 3\" />\n            {r.label && (\n              <text x={xs(r.value) + 4} y={bottom - 4} className=\"clui-annot clui-halo\">\n                {r.label}\n              </text>\n            )}\n          </g>\n        ))}\n        <rect x={0} y={top} width={width} height={bottom - top} fill=\"transparent\" onPointerMove={onMove} onPointerDown={onMove} onPointerLeave={() => setActive(null)} />\n      </svg>\n      {active !== null && (\n        <ChartTooltip\n          x={Math.min(right, xs(Math.max(0, ...p.segs[active].map((s) => s.b))))}\n          y={band(active) + band.bandwidth / 2}\n          width={width}\n          height={height}\n          data={tooltipFor(p, active, L)}\n        />\n      )}\n    </>\n  );\n}\n"
    },
    {
      "path": "registry/charts/core/charts.css",
      "type": "registry:file",
      "target": "components/charts/core/charts.css",
      "content": "/* ChartslibraryUI 1.1.0 · MIT License */\n/*\n * ChartslibraryUI chart theme. Import once, e.g. in your root layout:\n *   import \"@/components/charts/core/charts.css\";\n *\n * Everything is a CSS variable. To re-brand, override the --clui-* tokens on .clui (or a parent scope).\n * Dark mode follows `.dark` or `[data-theme=\"dark\"]` on any ancestor (next-themes, shadcn, Tailwind),\n * or set mode=\"dark\" | \"light\" | \"auto\" on a chart. Wrap a region in .clui-light / .clui-dark to force a mode.\n *\n * The categorical order (s1-s8) is validated for colour-vision deficiency on adjacent pairs in both modes.\n * Keep the order if you swap hues, and re-validate.\n */\n\n.clui,\n.clui-light {\n  --clui-font: inherit;\n  --clui-surface: #ffffff;\n  --clui-ink: #191919;\n  --clui-ink-2: #5e5e5e;\n  --clui-ink-3: #858585;\n  --clui-grid: #ececec;\n  --clui-axis: #c2c2c2;\n  --clui-border: rgba(11, 11, 11, 0.1);\n  --clui-context: #b9b9b9;\n  --clui-context-soft: #e2e2e2;\n  --clui-total: #4b4b4b;\n  --clui-neutral: #a3a3a3;\n  --clui-s1: #257de0;\n  --clui-s2: #f47230;\n  --clui-s3: #00b894;\n  --clui-s4: #f2a600;\n  --clui-s5: #ee7fac;\n  --clui-s6: #008a17;\n  --clui-s7: #6a4ce2;\n  --clui-s8: #ec4647;\n  --clui-s1-ink: #ffffff;\n  --clui-s2-ink: #191919;\n  --clui-s3-ink: #0b0b0b;\n  --clui-s4-ink: #0b0b0b;\n  --clui-s5-ink: #0b0b0b;\n  --clui-s6-ink: #ffffff;\n  --clui-s7-ink: #ffffff;\n  --clui-s8-ink: #ffffff;\n  --clui-good: #0a9b20;\n  --clui-bad: #dc3c3d;\n  --clui-good-text: #006c10;\n  --clui-bad-text: #b3261e;\n  --clui-forecast-bg: rgba(25, 25, 25, 0.035);\n  --clui-partial-bg: rgba(25, 25, 25, 0.025);\n  --clui-tooltip-bg: #ffffff;\n  --clui-tooltip-shadow: 0 1px 2px rgba(0, 0, 0, 0.06), 0 6px 20px rgba(0, 0, 0, 0.08);\n  /* sequential (blue), light -> dark */\n  --clui-seq-1: #e3effd;\n  --clui-seq-2: #b6d5f8;\n  --clui-seq-3: #84b9f3;\n  --clui-seq-4: #519ced;\n  --clui-seq-5: #257de0;\n  --clui-seq-6: #1b64be;\n  --clui-seq-7: #0e3d7e;\n  --clui-seq-ink-1: #191919;\n  --clui-seq-ink-2: #191919;\n  --clui-seq-ink-3: #191919;\n  --clui-seq-ink-4: #191919;\n  --clui-seq-ink-5: #ffffff;\n  --clui-seq-ink-6: #ffffff;\n  --clui-seq-ink-7: #ffffff;\n  /* diverging (red <- grey -> blue) */\n  --clui-div-n3: #b3262a;\n  --clui-div-n2: #e3615f;\n  --clui-div-n1: #f5b9b5;\n  --clui-div-0: #efefef;\n  --clui-div-p1: #b3d3f7;\n  --clui-div-p2: #519ced;\n  --clui-div-p3: #1b64be;\n  --clui-div-ink-n3: #ffffff;\n  --clui-div-ink-n2: #191919;\n  --clui-div-ink-n1: #191919;\n  --clui-div-ink-0: #191919;\n  --clui-div-ink-p1: #191919;\n  --clui-div-ink-p2: #191919;\n  --clui-div-ink-p3: #ffffff;\n  color-scheme: light;\n}\n\n.dark .clui,\n[data-theme=\"dark\"] .clui,\n.clui[data-mode=\"dark\"],\n.clui-dark,\n.clui-dark .clui {\n  --clui-surface: #191919;\n  --clui-ink: #efefef;\n  --clui-ink-2: #a6a6a6;\n  --clui-ink-3: #7f7f7f;\n  --clui-grid: #2b2b2b;\n  --clui-axis: #4a4a4a;\n  --clui-border: rgba(255, 255, 255, 0.1);\n  --clui-context: #5f5f5f;\n  --clui-context-soft: #363636;\n  --clui-total: #c9c9c9;\n  --clui-neutral: #6f6f6f;\n  --clui-s1: #338ced;\n  --clui-s2: #e76624;\n  --clui-s3: #00a888;\n  --clui-s4: #d28e05;\n  --clui-s5: #e24d8b;\n  --clui-s6: #0aac23;\n  --clui-s7: #9887ef;\n  --clui-s8: #eb6263;\n  --clui-s1-ink: #0b0b0b;\n  --clui-s2-ink: #0b0b0b;\n  --clui-s3-ink: #0b0b0b;\n  --clui-s4-ink: #0b0b0b;\n  --clui-s5-ink: #0b0b0b;\n  --clui-s6-ink: #0b0b0b;\n  --clui-s7-ink: #0b0b0b;\n  --clui-s8-ink: #0b0b0b;\n  --clui-good: #19b032;\n  --clui-bad: #eb6263;\n  --clui-good-text: #53c556;\n  --clui-bad-text: #f28b8b;\n  --clui-forecast-bg: rgba(255, 255, 255, 0.045);\n  --clui-partial-bg: rgba(255, 255, 255, 0.03);\n  --clui-tooltip-bg: #232323;\n  --clui-tooltip-shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.45);\n  --clui-seq-1: #1c2a3c;\n  --clui-seq-2: #1d3f6b;\n  --clui-seq-3: #1b5aa6;\n  --clui-seq-4: #2f7fd9;\n  --clui-seq-5: #5aa3ee;\n  --clui-seq-6: #93c2f5;\n  --clui-seq-7: #cfe4fb;\n  --clui-seq-ink-1: #efefef;\n  --clui-seq-ink-2: #efefef;\n  --clui-seq-ink-3: #efefef;\n  --clui-seq-ink-4: #ffffff;\n  --clui-seq-ink-5: #0b0b0b;\n  --clui-seq-ink-6: #0b0b0b;\n  --clui-seq-ink-7: #0b0b0b;\n  --clui-div-n3: #f08a89;\n  --clui-div-n2: #c2474a;\n  --clui-div-n1: #6b2c2d;\n  --clui-div-0: #333333;\n  --clui-div-p1: #1f4677;\n  --clui-div-p2: #2f7fd9;\n  --clui-div-p3: #8bbcf5;\n  --clui-div-ink-n3: #0b0b0b;\n  --clui-div-ink-n2: #ffffff;\n  --clui-div-ink-n1: #efefef;\n  --clui-div-ink-0: #efefef;\n  --clui-div-ink-p1: #efefef;\n  --clui-div-ink-p2: #ffffff;\n  --clui-div-ink-p3: #0b0b0b;\n  color-scheme: dark;\n}\n\n/* Forced light inside a dark page (declared after dark so it wins). */\n.clui-light .clui,\n.clui[data-mode=\"light\"] {\n  --clui-surface: #ffffff;\n  --clui-ink: #191919;\n  --clui-ink-2: #5e5e5e;\n  --clui-ink-3: #858585;\n  --clui-grid: #ececec;\n  --clui-axis: #c2c2c2;\n  --clui-border: rgba(11, 11, 11, 0.1);\n  --clui-context: #b9b9b9;\n  --clui-context-soft: #e2e2e2;\n  --clui-total: #4b4b4b;\n  --clui-neutral: #a3a3a3;\n  --clui-s1: #257de0;\n  --clui-s2: #f47230;\n  --clui-s3: #00b894;\n  --clui-s4: #f2a600;\n  --clui-s5: #ee7fac;\n  --clui-s6: #008a17;\n  --clui-s7: #6a4ce2;\n  --clui-s8: #ec4647;\n  --clui-s1-ink: #ffffff;\n  --clui-s2-ink: #191919;\n  --clui-s3-ink: #0b0b0b;\n  --clui-s4-ink: #0b0b0b;\n  --clui-s5-ink: #0b0b0b;\n  --clui-s6-ink: #ffffff;\n  --clui-s7-ink: #ffffff;\n  --clui-s8-ink: #ffffff;\n  --clui-good: #0a9b20;\n  --clui-bad: #dc3c3d;\n  --clui-good-text: #006c10;\n  --clui-bad-text: #b3261e;\n  --clui-forecast-bg: rgba(25, 25, 25, 0.035);\n  --clui-partial-bg: rgba(25, 25, 25, 0.025);\n  --clui-tooltip-bg: #ffffff;\n  --clui-tooltip-shadow: 0 1px 2px rgba(0, 0, 0, 0.06), 0 6px 20px rgba(0, 0, 0, 0.08);\n  --clui-seq-1: #e3effd;\n  --clui-seq-2: #b6d5f8;\n  --clui-seq-3: #84b9f3;\n  --clui-seq-4: #519ced;\n  --clui-seq-5: #257de0;\n  --clui-seq-6: #1b64be;\n  --clui-seq-7: #0e3d7e;\n  --clui-seq-ink-1: #191919;\n  --clui-seq-ink-2: #191919;\n  --clui-seq-ink-3: #191919;\n  --clui-seq-ink-4: #191919;\n  --clui-seq-ink-5: #ffffff;\n  --clui-seq-ink-6: #ffffff;\n  --clui-seq-ink-7: #ffffff;\n  --clui-div-n3: #b3262a;\n  --clui-div-n2: #e3615f;\n  --clui-div-n1: #f5b9b5;\n  --clui-div-0: #efefef;\n  --clui-div-p1: #b3d3f7;\n  --clui-div-p2: #519ced;\n  --clui-div-p3: #1b64be;\n  --clui-div-ink-n3: #ffffff;\n  --clui-div-ink-n2: #191919;\n  --clui-div-ink-n1: #191919;\n  --clui-div-ink-0: #191919;\n  --clui-div-ink-p1: #191919;\n  --clui-div-ink-p2: #191919;\n  --clui-div-ink-p3: #ffffff;\n  color-scheme: light;\n}\n\n@media (prefers-color-scheme: dark) {\n  .clui[data-mode=\"auto\"] {\n    --clui-surface: #191919;\n    --clui-ink: #efefef;\n    --clui-ink-2: #a6a6a6;\n    --clui-ink-3: #7f7f7f;\n    --clui-grid: #2b2b2b;\n    --clui-axis: #4a4a4a;\n    --clui-border: rgba(255, 255, 255, 0.1);\n    --clui-context: #5f5f5f;\n    --clui-context-soft: #363636;\n    --clui-total: #c9c9c9;\n    --clui-neutral: #6f6f6f;\n    --clui-s1: #338ced;\n    --clui-s2: #e76624;\n    --clui-s3: #00a888;\n    --clui-s4: #d28e05;\n    --clui-s5: #e24d8b;\n    --clui-s6: #0aac23;\n    --clui-s7: #9887ef;\n    --clui-s8: #eb6263;\n    --clui-s1-ink: #0b0b0b;\n    --clui-s2-ink: #0b0b0b;\n    --clui-s3-ink: #0b0b0b;\n    --clui-s4-ink: #0b0b0b;\n    --clui-s5-ink: #0b0b0b;\n    --clui-s6-ink: #0b0b0b;\n    --clui-s7-ink: #0b0b0b;\n    --clui-s8-ink: #0b0b0b;\n  --clui-s1-ink: #0b0b0b;\n  --clui-s2-ink: #0b0b0b;\n  --clui-s3-ink: #0b0b0b;\n  --clui-s4-ink: #0b0b0b;\n  --clui-s5-ink: #0b0b0b;\n  --clui-s6-ink: #0b0b0b;\n  --clui-s7-ink: #0b0b0b;\n  --clui-s8-ink: #0b0b0b;\n    --clui-good: #19b032;\n    --clui-bad: #eb6263;\n    --clui-good-text: #53c556;\n    --clui-bad-text: #f28b8b;\n    --clui-forecast-bg: rgba(255, 255, 255, 0.045);\n    --clui-partial-bg: rgba(255, 255, 255, 0.03);\n    --clui-tooltip-bg: #232323;\n    --clui-seq-1: #1c2a3c;\n    --clui-seq-2: #1d3f6b;\n    --clui-seq-3: #1b5aa6;\n    --clui-seq-4: #2f7fd9;\n    --clui-seq-5: #5aa3ee;\n    --clui-seq-6: #93c2f5;\n    --clui-seq-7: #cfe4fb;\n    --clui-seq-ink-4: #ffffff;\n    --clui-seq-ink-5: #0b0b0b;\n    --clui-seq-ink-6: #0b0b0b;\n    --clui-seq-ink-7: #0b0b0b;\n    --clui-div-n3: #f08a89;\n    --clui-div-n2: #c2474a;\n    --clui-div-n1: #6b2c2d;\n    --clui-div-0: #333333;\n    --clui-div-p1: #1f4677;\n    --clui-div-p2: #2f7fd9;\n    --clui-div-p3: #8bbcf5;\n    color-scheme: dark;\n  }\n}\n\n/* ---------- frame ---------- */\n\n.clui {\n  margin: 0;\n  font-family: var(--clui-font);\n  color: var(--clui-ink);\n  min-width: 0;\n  position: relative;\n  -webkit-font-smoothing: antialiased;\n}\n.clui *,\n.clui *::before,\n.clui *::after {\n  box-sizing: border-box;\n}\n.clui-head {\n  display: flex;\n  align-items: flex-start;\n  justify-content: space-between;\n  gap: 12px;\n  margin-bottom: 10px;\n}\n.clui-head-text {\n  min-width: 0;\n}\n.clui-title {\n  margin: 0;\n  font-size: 15px;\n  line-height: 1.3;\n  font-weight: 600;\n  letter-spacing: -0.01em;\n  color: var(--clui-ink);\n}\n.clui-subtitle {\n  margin: 2px 0 0;\n  font-size: 12.5px;\n  line-height: 1.4;\n  color: var(--clui-ink-2);\n}\n.clui-toolbar {\n  display: flex;\n  gap: 4px;\n  flex-shrink: 0;\n}\n/* Charts with an onSelect handler: marks are clickable. */\n.clui svg[data-selectable] {\n  cursor: pointer;\n}\n\n.clui-tool {\n  font: inherit;\n  font-size: 11px;\n  line-height: 1;\n  padding: 5px 8px;\n  border-radius: 6px;\n  border: 1px solid var(--clui-border);\n  background: transparent;\n  color: var(--clui-ink-2);\n  cursor: pointer;\n}\n.clui-tool:hover {\n  color: var(--clui-ink);\n  border-color: var(--clui-axis);\n}\n.clui-tool[aria-pressed=\"true\"] {\n  color: var(--clui-ink);\n  background: var(--clui-grid);\n}\n.clui-tool:focus-visible,\n.clui-legend-btn:focus-visible,\n.clui svg:focus-visible,\n.clui-table-wrap:focus-visible {\n  outline: 2px solid var(--clui-s1);\n  outline-offset: 2px;\n  border-radius: 4px;\n}\n.clui svg:focus:not(:focus-visible) {\n  outline: none;\n}\n\n.clui-legend {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 4px 14px;\n  list-style: none;\n  margin: 0 0 10px;\n  padding: 0;\n  font-size: 12px;\n  color: var(--clui-ink-2);\n}\n.clui-legend li {\n  display: flex;\n}\n.clui-legend-item,\n.clui-legend-btn {\n  display: inline-flex;\n  align-items: center;\n  gap: 6px;\n  font: inherit;\n  color: inherit;\n}\n.clui-legend-btn {\n  background: none;\n  border: 0;\n  padding: 0;\n  cursor: pointer;\n}\n.clui-legend-btn[data-off] {\n  opacity: 0.45;\n  text-decoration: line-through;\n}\n.clui-key {\n  display: inline-block;\n  width: 10px;\n  height: 10px;\n  border-radius: 2px;\n  flex-shrink: 0;\n}\n.clui-key-line {\n  width: 14px;\n  height: 2px;\n  border-radius: 1px;\n}\n.clui-key-dot {\n  border-radius: 50%;\n  width: 8px;\n  height: 8px;\n}\n.clui-key-ring {\n  border-radius: 50%;\n  width: 9px;\n  height: 9px;\n  background: transparent;\n  border: 2px solid;\n}\n.clui-key-band {\n  width: 14px;\n  height: 8px;\n  opacity: 0.35;\n}\n\n.clui-plot {\n  position: relative;\n  width: 100%;\n}\n.clui-plot svg {\n  display: block;\n  overflow: visible;\n}\n.clui-tick {\n  font-size: 11px;\n  fill: var(--clui-ink-2);\n  font-variant-numeric: tabular-nums;\n}\n.clui-annot {\n  font-size: 11px;\n  fill: var(--clui-ink-2);\n}\n.clui-label {\n  font-size: 11px;\n  fill: var(--clui-ink);\n  font-variant-numeric: tabular-nums;\n}\n.clui-label-strong {\n  font-size: 11.5px;\n  font-weight: 600;\n  fill: var(--clui-ink);\n}\n.clui-halo {\n  paint-order: stroke;\n  stroke: var(--clui-surface);\n  stroke-width: 3px;\n  stroke-linejoin: round;\n}\n.clui-mark {\n  transition: opacity 120ms ease;\n}\n.clui-dim {\n  opacity: 0.25;\n}\n\n.clui-tooltip {\n  position: absolute;\n  z-index: 10;\n  pointer-events: none;\n  min-width: 140px;\n  max-width: 280px;\n  padding: 8px 10px;\n  border-radius: 8px;\n  background: var(--clui-tooltip-bg);\n  border: 1px solid var(--clui-border);\n  box-shadow: var(--clui-tooltip-shadow);\n  font-size: 12px;\n  line-height: 1.35;\n  color: var(--clui-ink);\n}\n.clui-tooltip-title {\n  font-weight: 600;\n  margin-bottom: 4px;\n}\n.clui-tooltip table {\n  border-collapse: collapse;\n  width: 100%;\n}\n.clui-tooltip td {\n  padding: 1.5px 0;\n  vertical-align: middle;\n}\n.clui-tooltip-label {\n  color: var(--clui-ink-2);\n  padding-right: 14px !important;\n  white-space: nowrap;\n  overflow: hidden;\n  text-overflow: ellipsis;\n  max-width: 170px;\n}\n.clui-tooltip-label > span:last-child {\n  margin-left: 6px;\n}\n.clui-tooltip-value {\n  text-align: right;\n  font-variant-numeric: tabular-nums;\n  white-space: nowrap;\n}\n.clui-tooltip tr[data-strong] td {\n  font-weight: 600;\n  color: var(--clui-ink);\n}\n.clui-tooltip-note {\n  color: var(--clui-ink-2);\n  font-weight: 400;\n}\n.clui-tooltip-footer {\n  margin-top: 5px;\n  padding-top: 5px;\n  border-top: 1px solid var(--clui-border);\n  color: var(--clui-ink-2);\n  font-size: 11px;\n}\n\n.clui-foot {\n  display: flex;\n  flex-direction: column;\n  gap: 2px;\n  margin-top: 10px;\n  font-size: 11px;\n  line-height: 1.4;\n  color: var(--clui-ink-2);\n}\n.clui-note[data-level=\"warning\"] {\n  color: var(--clui-ink);\n}\n.clui-source {\n  color: var(--clui-ink-3);\n}\n\n.clui-message {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  text-align: center;\n  gap: 6px;\n  padding: 16px;\n  border: 1px dashed var(--clui-axis);\n  border-radius: 8px;\n  color: var(--clui-ink-2);\n  font-size: 12px;\n}\n.clui-message-title {\n  font-weight: 600;\n  font-size: 13px;\n  color: var(--clui-ink);\n}\n.clui-message ul {\n  margin: 0;\n  padding: 0;\n  list-style: none;\n  max-width: 520px;\n}\n\n.clui-table-wrap {\n  overflow: auto;\n  border: 1px solid var(--clui-border);\n  border-radius: 8px;\n}\n.clui-table {\n  border-collapse: collapse;\n  width: 100%;\n  font-size: 12px;\n  font-variant-numeric: tabular-nums;\n}\n.clui-table th,\n.clui-table td {\n  padding: 6px 10px;\n  border-bottom: 1px solid var(--clui-grid);\n  text-align: left;\n  white-space: nowrap;\n}\n.clui-table thead th {\n  position: sticky;\n  top: 0;\n  background: var(--clui-surface);\n  color: var(--clui-ink-2);\n  font-weight: 500;\n}\n.clui-table tbody th {\n  font-weight: 500;\n}\n.clui-table [data-align=\"right\"] {\n  text-align: right;\n}\n\n.clui-sr {\n  position: absolute;\n  width: 1px;\n  height: 1px;\n  padding: 0;\n  margin: -1px;\n  overflow: hidden;\n  clip: rect(0, 0, 0, 0);\n  white-space: nowrap;\n  border: 0;\n}\n\n/* KPI tiles */\n.clui-kpi-row {\n  display: grid;\n  gap: 12px;\n  grid-template-columns: repeat(auto-fit, minmax(var(--clui-kpi-min, 180px), 1fr));\n}\n.clui-kpi {\n  display: flex;\n  flex-direction: column;\n  gap: 4px;\n  padding: 14px 16px;\n  border: 1px solid var(--clui-border);\n  border-radius: 10px;\n  background: var(--clui-surface);\n  min-width: 0;\n  container-type: inline-size;\n}\n.clui-kpi-label {\n  font-size: 12.5px;\n  color: var(--clui-ink-2);\n  white-space: nowrap;\n  overflow: hidden;\n  text-overflow: ellipsis;\n}\n.clui-kpi-value {\n  font-size: 26px;\n  line-height: 1.15;\n  font-weight: 600;\n  letter-spacing: -0.02em;\n  white-space: nowrap;\n}\n.clui-kpi-delta {\n  font-size: 12px;\n  font-variant-numeric: tabular-nums;\n  display: flex;\n  gap: 6px;\n  flex-wrap: wrap;\n  align-items: baseline;\n}\n.clui-kpi-delta-muted {\n  color: var(--clui-ink-2);\n}\n.clui-kpi-foot {\n  display: flex;\n  align-items: flex-end;\n  justify-content: space-between;\n  gap: 8px;\n}\n.clui-kpi-delta > span:first-child {\n  white-space: nowrap;\n}\n/* Narrow tiles: the sparkline moves under the numbers instead of squeezing them. */\n@container (max-width: 260px) {\n  .clui-kpi-foot {\n    flex-direction: column;\n    align-items: stretch;\n  }\n  .clui-kpi-spark {\n    width: 100% !important;\n  }\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .clui * {\n    transition: none !important;\n    animation: none !important;\n  }\n}\n\n@media (forced-colors: active) {\n  .clui-key {\n    forced-color-adjust: none;\n  }\n}\n"
    },
    {
      "path": "registry/charts/core/color.ts",
      "type": "registry:lib",
      "target": "components/charts/core/color.ts",
      "content": "// core/color.ts · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com\n/**\n * Colour roles. Every colour is a CSS variable defined in charts.css, so light/dark and brand changes happen in CSS.\n *\n * Rules\n * - Categorical colours are assigned in a fixed order and never cycled. Past 8 series, extra series are grey.\n * - Emphasis by default: when `highlight` is given, highlighted series take accent colours and the rest are grey.\n * - Good / bad colour follows business direction (`favorable`), not the sign of the number.\n */\n\nexport const PALETTE_SIZE = 8;\n\nexport const color = {\n  series: (i: number) => (i < PALETTE_SIZE ? `var(--clui-s${i + 1})` : \"var(--clui-context)\"),\n  /** Text colour for a label placed inside a fill of series colour i. */\n  seriesInk: (i: number) => (i < PALETTE_SIZE ? `var(--clui-s${i + 1}-ink)` : \"var(--clui-ink)\"),\n  accent: \"var(--clui-s1)\",\n  context: \"var(--clui-context)\",\n  contextSoft: \"var(--clui-context-soft)\",\n  ink: \"var(--clui-ink)\",\n  ink2: \"var(--clui-ink-2)\",\n  ink3: \"var(--clui-ink-3)\",\n  grid: \"var(--clui-grid)\",\n  axis: \"var(--clui-axis)\",\n  surface: \"var(--clui-surface)\",\n  good: \"var(--clui-good)\",\n  bad: \"var(--clui-bad)\",\n  goodText: \"var(--clui-good-text)\",\n  badText: \"var(--clui-bad-text)\",\n  neutral: \"var(--clui-neutral)\",\n  total: \"var(--clui-total)\",\n  forecast: \"var(--clui-forecast-bg)\",\n  seq: (step: number) => `var(--clui-seq-${Math.max(1, Math.min(7, step))})`,\n  seqInk: (step: number) => `var(--clui-seq-ink-${Math.max(1, Math.min(7, step))})`,\n  div: (step: number) => `var(--clui-div-${step < 0 ? `n${Math.min(3, -step)}` : step > 0 ? `p${Math.min(3, step)}` : \"0\"})`,\n  divInk: (step: number) =>\n    `var(--clui-div-ink-${step < 0 ? `n${Math.min(3, -step)}` : step > 0 ? `p${Math.min(3, step)}` : \"0\"})`,\n};\n\nexport interface SeriesLike {\n  key: string;\n  color?: string;\n}\n\n/**\n * Resolve each series' colour. Colour follows the series' position in the declared list (not its rank or visibility); series with an explicit\n * colour don't use up a slot,\n * so toggling a series never repaints the others.\n */\nexport function seriesColors(series: SeriesLike[], highlight?: string | string[]): Record<string, string> {\n  const hl = highlight === undefined ? null : new Set(Array.isArray(highlight) ? highlight : [highlight]);\n  const out: Record<string, string> = {};\n  let slot = 0;\n  series.forEach((s) => {\n    if (s.color) out[s.key] = s.color;\n    else if (hl) out[s.key] = hl.has(s.key) ? color.series(slot++) : color.context;\n    else out[s.key] = color.series(slot++);\n  });\n  return out;\n}\n\n// ---------- direction ----------\n\nexport type Favorable = \"up\" | \"down\" | \"none\";\nexport type Tone = \"good\" | \"bad\" | \"neutral\";\n\n/** Is this change good? `favorable: \"down\"` for costs, churn, latency. Zero and \"none\" are neutral. */\nexport function toneOf(delta: number | null | undefined, favorable: Favorable = \"up\"): Tone {\n  if (delta === null || delta === undefined || !Number.isFinite(delta) || delta === 0 || favorable === \"none\")\n    return \"neutral\";\n  const up = delta > 0;\n  return (favorable === \"up\") === up ? \"good\" : \"bad\";\n}\n\nexport const toneColor = (tone: Tone) => (tone === \"good\" ? color.good : tone === \"bad\" ? color.bad : color.neutral);\nexport const toneText = (tone: Tone) =>\n  tone === \"good\" ? color.goodText : tone === \"bad\" ? color.badText : color.ink2;\n\n/** Arrow follows the sign; colour (applied separately) follows `favorable`. */\nexport const arrowGlyph = (delta: number | null | undefined) =>\n  delta === null || delta === undefined || !Number.isFinite(delta) || delta === 0 ? \"\" : delta > 0 ? \"▲\" : \"▼\";\n\n/** Word for screen readers and tables, so tone never depends on colour alone. */\nexport const toneWord = (tone: Tone) => (tone === \"good\" ? \"favorable\" : tone === \"bad\" ? \"unfavorable\" : \"no change\");\n"
    },
    {
      "path": "registry/charts/core/data.ts",
      "type": "registry:lib",
      "target": "components/charts/core/data.ts",
      "content": "// core/data.ts · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com\n/**\n * Data checks. Charts never silently \"fix\" data: invalid input becomes an error message drawn on the chart,\n * and questionable input (missing values, duplicates, too many series) becomes a visible footnote.\n */\n\nexport type IssueLevel = \"error\" | \"warning\" | \"note\";\n\nexport interface Issue {\n  level: IssueLevel;\n  message: string;\n}\n\nexport type Row = Record<string, unknown>;\n\nexport function isNum(v: unknown): v is number {\n  return typeof v === \"number\" && Number.isFinite(v);\n}\n\n/** Read a numeric cell: finite numbers pass, null/undefined are \"missing\", anything else is \"invalid\". */\nexport function readNum(v: unknown): { value: number | null; state: \"ok\" | \"missing\" | \"invalid\" } {\n  if (v === null || v === undefined) return { value: null, state: \"missing\" };\n  if (typeof v === \"number\") {\n    if (Number.isFinite(v)) return { value: v, state: \"ok\" };\n    if (Number.isNaN(v)) return { value: null, state: \"missing\" };\n    return { value: null, state: \"invalid\" };\n  }\n  return { value: null, state: \"invalid\" };\n}\n\nconst plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;\n\n/** Extract a numeric column with counts of missing / invalid cells. */\nexport function column(rows: Row[], key: string) {\n  let missing = 0;\n  let invalid = 0;\n  const invalidRows: number[] = [];\n  const values = rows.map((row, i) => {\n    const r = readNum(row?.[key]);\n    if (r.state === \"missing\") missing++;\n    if (r.state === \"invalid\") {\n      invalid++;\n      invalidRows.push(i);\n    }\n    return r.value;\n  });\n  return { values, missing, invalid, invalidRows };\n}\n\n/** Standard checks for row-based charts. Returns issues; callers add chart-specific ones. */\nexport function checkRows(\n  rows: unknown,\n  opts: { name?: string; xKey?: string; valueKeys: string[]; allowMissing?: boolean; maxSeries?: number },\n): Issue[] {\n  const issues: Issue[] = [];\n  if (!Array.isArray(rows)) return [{ level: \"error\", message: \"`data` must be an array of rows.\" }];\n  if (rows.length === 0) return [{ level: \"error\", message: \"No data to display.\" }];\n  if (opts.valueKeys.length === 0)\n    return [{ level: \"error\", message: \"No series to draw. Pass at least one key.\" }];\n  if (opts.xKey && !rows.some((r) => r && (r as Row)[opts.xKey!] !== undefined)) {\n    issues.push({ level: \"error\", message: `No row has the x key \"${opts.xKey}\".` });\n  }\n  for (const key of opts.valueKeys) {\n    const present = rows.some((r) => r && key in (r as Row));\n    if (!present) {\n      issues.push({ level: \"error\", message: `No row has the key \"${key}\".` });\n      continue;\n    }\n    const c = column(rows as Row[], key);\n    if (c.invalid) {\n      const sample = c.invalidRows\n        .slice(0, 3)\n        .map((i) => JSON.stringify((rows as Row[])[i][key]))\n        .join(\", \");\n      issues.push({\n        level: \"error\",\n        message: `\"${key}\" has ${plural(c.invalid, \"non-numeric value\")} (${sample}${c.invalid > 3 ? \", …\" : \"\"}). Convert to numbers before charting.`,\n      });\n    }\n    if (c.missing && c.missing === rows.length) {\n      issues.push({ level: \"warning\", message: `\"${key}\" has no values.` });\n    } else if (c.missing && opts.allowMissing !== false) {\n      issues.push({\n        level: \"note\",\n        message: `\"${key}\": ${plural(c.missing, \"missing value\")}, shown as gaps.`,\n      });\n    } else if (c.missing) {\n      issues.push({\n        level: \"warning\",\n        message: `\"${key}\": ${plural(c.missing, \"missing value\")} not drawn.`,\n      });\n    }\n  }\n  if (opts.xKey) {\n    const seen = new Map<string, number>();\n    for (const r of rows as Row[]) {\n      const k = String(r?.[opts.xKey]);\n      seen.set(k, (seen.get(k) ?? 0) + 1);\n    }\n    const dups = [...seen.entries()].filter(([, n]) => n > 1);\n    if (dups.length) {\n      issues.push({\n        level: \"warning\",\n        message: `Duplicate ${opts.xKey} values: ${dups\n          .slice(0, 3)\n          .map(([k]) => `\"${k}\"`)\n          .join(\n            \", \",\n          )}${dups.length > 3 ? \"…\" : \"\"}. Each row is drawn separately; aggregate first if that is not intended.`,\n      });\n    }\n  }\n  if (opts.maxSeries && opts.valueKeys.length > opts.maxSeries) {\n    issues.push({\n      level: \"warning\",\n      message: `${opts.valueKeys.length} series exceeds the ${opts.maxSeries}-colour palette; series after ${opts.maxSeries} are grey. Consider small multiples or grouping into \"Other\".`,\n    });\n  }\n  return issues;\n}\n\nexport const hasError = (issues: Issue[]) => issues.some((i) => i.level === \"error\");\n\n/** Parse a date-like value to UTC ms. Date-only ISO strings (\"2026-03-01\") are read as UTC midnight. */\nexport function parseDate(v: unknown): number | null {\n  if (v instanceof Date) return Number.isNaN(v.getTime()) ? null : v.getTime();\n  if (typeof v === \"number\") return Number.isFinite(v) ? v : null;\n  if (typeof v !== \"string\" || !v.trim()) return null;\n  const s = v.trim();\n  const dateOnly = /^(\\d{4})-(\\d{2})(?:-(\\d{2}))?$/.exec(s);\n  if (dateOnly) {\n    const [, y, m, d] = dateOnly;\n    return Date.UTC(Number(y), Number(m) - 1, d ? Number(d) : 1);\n  }\n  const t = Date.parse(s);\n  return Number.isNaN(t) ? null : t;\n}\n\nexport function sum(values: (number | null)[]): number {\n  let s = 0;\n  for (const v of values) if (v !== null && Number.isFinite(v)) s += v;\n  return s;\n}\n\nexport function extent(values: (number | null | undefined)[]): [number, number] | null {\n  let lo = Infinity;\n  let hi = -Infinity;\n  for (const v of values) {\n    if (v === null || v === undefined || !Number.isFinite(v)) continue;\n    if (v < lo) lo = v;\n    if (v > hi) hi = v;\n  }\n  return lo === Infinity ? null : [lo, hi];\n}\n\n/** Quantile of a sorted array (linear interpolation, R-7). */\nexport function quantile(sorted: number[], p: number): number {\n  if (!sorted.length) return NaN;\n  const h = (sorted.length - 1) * p;\n  const lo = Math.floor(h);\n  const hi = Math.ceil(h);\n  return sorted[lo] + (sorted[hi] - sorted[lo]) * (h - lo);\n}\n\n/** Convert row data to CSV (RFC 4180), guarding against spreadsheet formula injection. */\nexport function toCSV(columns: { key: string; label: string }[], rows: Row[]): string {\n  const cell = (v: unknown) => {\n    if (v === null || v === undefined) return \"\";\n    let s = v instanceof Date ? v.toISOString() : String(v);\n    // numbers (e.g. -5) are data, not formulas; anything else is checked by its text\n    if (typeof v !== \"number\" && typeof v !== \"bigint\" && /^[=+\\-@\\t\\r]/.test(s)) s = `'${s}`;\n    return /[\",\\n\\r]/.test(s) ? `\"${s.replace(/\"/g, '\"\"')}\"` : s;\n  };\n  const lines = [columns.map((c) => cell(c.label)).join(\",\")];\n  for (const r of rows) lines.push(columns.map((c) => cell(r[c.key])).join(\",\"));\n  return lines.join(\"\\r\\n\");\n}\n"
    },
    {
      "path": "registry/charts/core/format.ts",
      "type": "registry:lib",
      "target": "components/charts/core/format.ts",
      "content": "// core/format.ts · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com\n/**\n * Number and date formatting shared by every chart: axes, tooltips, labels, legends, tables and KPI tiles.\n *\n * Conventions\n * - Percent values are fractions: 0.125 -> \"12.5%\".\n * - Percentage points (\"pp\") are given in points: 2.3 -> \"+2.3 pp\".\n * - Negative numbers use a true minus sign (U+2212).\n * - Compact numbers (1.2K, $4.2M) are used from 10,000 upward in \"auto\" mode. Tables show full values.\n * - A magnitude unit (m, bn, k...) means the value is already scaled, so it is never re-compacted:\n *   { kind: \"currency\", unit: \"m\" } formats 1000 as \"$1,000m\", never \"$1.0Km\".\n */\n\nexport type FormatKind = \"number\" | \"integer\" | \"currency\" | \"percent\" | \"pp\";\n\nexport interface FormatSpec {\n  kind?: FormatKind;\n  /** \"auto\" (default) compacts from 10,000 up outside tables; true always compacts; false never. */\n  compact?: boolean | \"auto\";\n  /** Fixed number of decimals. Overrides the automatic choice. */\n  decimals?: number;\n  /** ISO 4217 code for kind \"currency\". Default \"USD\". */\n  currency?: string;\n  /** Unit written after the number, e.g. \"trips\", \"ms\", \"m\" (already in millions). */\n  unit?: string;\n  /** Always show a sign (+/−). Default true for \"pp\", false otherwise. */\n  signed?: boolean;\n  /** BCP 47 locale. Default \"en-US\". */\n  locale?: string;\n}\n\nexport type FormatPreset = FormatKind | \"compact\" | \"currency-compact\";\nexport type FormatInput = FormatPreset | FormatSpec | ((value: number) => string);\n\n/** Where a value is written. Tables show more precision and no auto-compaction. */\nexport type FormatContext = \"axis\" | \"label\" | \"tooltip\" | \"table\";\n\nconst MINUS = \"−\";\nconst MAGNITUDE_UNITS = new Set([\"k\", \"K\", \"m\", \"M\", \"mm\", \"MM\", \"bn\", \"b\", \"B\", \"tn\", \"T\"]);\nconst TIGHT_UNITS = new Set([\"x\", \"×\", \"%\", \"‰\", \"°\"]);\n\nexport function resolveFormat(input?: FormatInput): FormatSpec | ((value: number) => string) {\n  if (typeof input === \"function\") return input;\n  if (!input) return { kind: \"number\" };\n  if (typeof input === \"string\") {\n    switch (input) {\n      case \"compact\":\n        return { kind: \"number\", compact: true };\n      case \"currency-compact\":\n        return { kind: \"currency\", compact: true };\n      default:\n        return { kind: input };\n    }\n  }\n  return { kind: \"number\", ...input };\n}\n\ninterface Magnitude {\n  divisor: number;\n  suffix: string;\n}\n\nconst MAGNITUDES: Magnitude[] = [\n  { divisor: 1e12, suffix: \"T\" },\n  { divisor: 1e9, suffix: \"B\" },\n  { divisor: 1e6, suffix: \"M\" },\n  { divisor: 1e3, suffix: \"K\" },\n];\n\nfunction magnitudeFor(abs: number): Magnitude {\n  for (const m of MAGNITUDES) if (abs >= m.divisor * 0.9995) return m;\n  return { divisor: 1, suffix: \"\" };\n}\n\nfunction isMagnitudeUnit(unit?: string) {\n  return !!unit && MAGNITUDE_UNITS.has(unit);\n}\n\nfunction shouldCompact(spec: FormatSpec, abs: number, context: FormatContext) {\n  if (spec.kind === \"percent\" || spec.kind === \"pp\") return false;\n  if (isMagnitudeUnit(spec.unit)) return false;\n  const c = spec.compact ?? \"auto\";\n  if (c === true) return abs >= 1000 || context !== \"table\";\n  if (c === false) return false;\n  return context !== \"table\" && abs >= 10_000;\n}\n\nfunction defaultDecimals(spec: FormatSpec, scaledAbs: number, compacted: boolean, context: FormatContext) {\n  if (spec.decimals !== undefined) return spec.decimals;\n  switch (spec.kind) {\n    case \"integer\":\n      return compacted ? (scaledAbs < 100 ? 1 : 0) : 0;\n    case \"percent\":\n      return 1;\n    case \"pp\":\n      return 1;\n    default: {\n      if (compacted) return scaledAbs < 100 ? 1 : 0;\n      // whole numbers are written whole: \"$40\", not \"$40.0\"\n      if (Number.isInteger(scaledAbs)) return 0;\n      if (context === \"table\" || context === \"tooltip\") {\n        if (scaledAbs >= 1000) return 0;\n        if (scaledAbs >= 100) return 1;\n        return 2;\n      }\n      if (scaledAbs >= 100) return 0;\n      if (scaledAbs >= 10) return 1;\n      return 2;\n    }\n  }\n}\n\nfunction appendUnit(text: string, unit?: string) {\n  if (!unit) return text;\n  if (TIGHT_UNITS.has(unit) || isMagnitudeUnit(unit)) return text + unit;\n  return `${text} ${unit}`;\n}\n\n/** Intl formatting with our suffix inserted after the numeric part (handles \"4,2 M €\" style locales). */\nfunction intlFormat(\n  scaled: number,\n  spec: FormatSpec,\n  decimals: number,\n  suffix: string,\n  trim: boolean,\n  significant?: number,\n): string {\n  const locale = spec.locale ?? \"en-US\";\n  const opts: Intl.NumberFormatOptions = significant\n    ? { maximumSignificantDigits: significant }\n    : { minimumFractionDigits: trim ? 0 : decimals, maximumFractionDigits: decimals };\n  if (spec.kind === \"currency\") {\n    opts.style = \"currency\";\n    opts.currency = spec.currency ?? \"USD\";\n  }\n  const parts = new Intl.NumberFormat(locale, opts).formatToParts(scaled);\n  let lastNumeric = -1;\n  parts.forEach((p, i) => {\n    if (p.type === \"integer\" || p.type === \"fraction\" || p.type === \"decimal\" || p.type === \"group\") lastNumeric = i;\n  });\n  let out = \"\";\n  parts.forEach((p, i) => {\n    out += p.type === \"minusSign\" ? MINUS : p.value;\n    if (i === lastNumeric) out += suffix;\n  });\n  return out;\n}\n\nexport interface FormatOptions {\n  context?: FormatContext;\n  signed?: boolean;\n  /** Force a magnitude (used by axes so every tick shares one suffix). */\n  magnitude?: Magnitude;\n  decimals?: number;\n  /** Drop trailing zeros (axes). */\n  trim?: boolean;\n}\n\n/** Format one value. null/undefined/NaN become an en dash, never \"0\". */\nexport function formatValue(value: number | null | undefined, input?: FormatInput, options: FormatOptions = {}): string {\n  if (value === null || value === undefined || typeof value !== \"number\" || Number.isNaN(value)) return \"–\";\n  if (!Number.isFinite(value)) return value > 0 ? \"∞\" : `${MINUS}∞`;\n  const resolved = resolveFormat(input);\n  if (typeof resolved === \"function\") return resolved(value);\n  const spec = resolved;\n  const context = options.context ?? \"label\";\n  const signed = options.signed ?? spec.signed ?? spec.kind === \"pp\";\n\n  if (value === 0 && spec.decimals === undefined) {\n    // Zero is always written plainly: \"0\", \"$0\", \"0%\", never \"$0.0M\".\n    let z = intlFormat(0, spec, 0, \"\", true);\n    if (spec.kind === \"percent\") z += \"%\";\n    if (spec.kind === \"pp\") z = appendUnit(z, \"pp\");\n    return appendUnit(z, isMagnitudeUnit(spec.unit) ? undefined : spec.unit);\n  }\n\n  let scaled = value;\n  if (spec.kind === \"percent\") scaled = value * 100;\n\n  const abs = Math.abs(scaled);\n  const mag = options.magnitude ?? (shouldCompact(spec, abs, context) ? magnitudeFor(abs) : { divisor: 1, suffix: \"\" });\n  const display = scaled / mag.divisor;\n  const decimals = options.decimals ?? defaultDecimals(spec, Math.abs(display), mag.divisor > 1, context);\n\n  // Very small non-zero values must not collapse to \"0\".\n  const tiny = display !== 0 && Math.abs(display) < 0.5 * 10 ** -decimals && spec.decimals === undefined;\n  let text = tiny\n    ? intlFormat(display, spec, decimals, mag.suffix, true, 2)\n    : intlFormat(display, spec, decimals, mag.suffix, !!options.trim);\n\n  // Normalise \"−0\" / \"−0.0\"\n  if (!/[1-9]/.test(text)) text = text.replace(MINUS, \"\");\n\n  if (spec.kind === \"percent\") text += \"%\";\n  if (spec.kind === \"pp\") text = appendUnit(text, \"pp\");\n  text = appendUnit(text, spec.unit);\n  if (signed && value > 0 && /[1-9]/.test(text)) text = `+${text}`;\n  return text;\n}\n\n/**\n * Build a formatter for a set of axis ticks: one magnitude suffix for the whole axis and the fewest decimals\n * that keep every tick distinct.\n */\nexport function tickFormatter(input: FormatInput | undefined, ticks: number[]): (v: number) => string {\n  const resolved = resolveFormat(input);\n  if (typeof resolved === \"function\") return resolved;\n  const spec = resolved;\n  const scale = spec.kind === \"percent\" ? 100 : 1;\n  const maxAbs = Math.max(0, ...ticks.map((t) => Math.abs(t * scale)));\n  const mag = shouldCompact(spec, maxAbs, \"axis\") ? magnitudeFor(maxAbs) : { divisor: 1, suffix: \"\" };\n  const zeroFirst = (fn: (v: number) => string) => (v: number) => (v === 0 ? formatValue(0, { ...spec, decimals: undefined }) : fn(v));\n  // Ticks are round numbers: they always use the fewest decimals that keep them distinct, even when the\n  // format fixes decimals for labels and tooltips (\"10 h\", not \"10.0 h\").\n  for (let d = 0; d <= 4; d++) {\n    const labels = ticks.map((t) => formatValue(t, spec, { context: \"axis\", magnitude: mag, decimals: d, trim: false }));\n    const exact = ticks.every((t) => {\n      const s = (t * scale) / mag.divisor;\n      return Math.abs(Math.round(s * 10 ** d) - s * 10 ** d) < 1e-6;\n    });\n    if (new Set(labels).size === labels.length && exact) {\n      return zeroFirst((v) => formatValue(v, spec, { context: \"axis\", magnitude: mag, decimals: d, trim: false }));\n    }\n  }\n  return zeroFirst((v) => formatValue(v, spec, { context: \"axis\", magnitude: mag, decimals: 2, trim: false }));\n}\n\n/** Make a single-context formatter. */\n/**\n * Formatter for a set of data labels shown together. If the largest label compacts, every label shares its\n * magnitude (\"$17.8K, $4.5K, −$0.7K\", never \"$17.8K, $4,500, −$700\"). Percent, pp, magnitude units and\n * function formats fall back to formatting each value on its own. `delta` writes signed differences.\n */\nexport function labelFormatter(input: FormatInput | undefined, values: (number | null | undefined)[], opts: { delta?: boolean } = {}) {\n  const resolved = resolveFormat(input);\n  const single = (v: number | null | undefined) => (opts.delta ? formatDelta(v, input) : formatValue(v, input));\n  if (typeof resolved === \"function\") return single;\n  const spec = resolved;\n  if (spec.kind === \"percent\" || spec.kind === \"pp\") return single;\n  const finite = values.filter((v): v is number => typeof v === \"number\" && Number.isFinite(v));\n  const maxAbs = finite.reduce((m, v) => Math.max(m, Math.abs(v)), 0);\n  if (!maxAbs || !shouldCompact(spec, maxAbs, \"label\")) return single;\n  const magnitude = magnitudeFor(maxAbs);\n  const decimals = spec.decimals ?? (maxAbs / magnitude.divisor >= 100 ? 0 : 1);\n  return (v: number | null | undefined) =>\n    v === 0 || v === null || v === undefined || !Number.isFinite(v) ? single(v) : formatValue(v, input, { magnitude, decimals, signed: opts.delta });\n}\n\nexport function formatter(input: FormatInput | undefined, context: FormatContext = \"label\") {\n  return (v: number | null | undefined) => formatValue(v, input, { context });\n}\n\n/**\n * Format a difference between two values of the given format.\n * Percent formats express differences in percentage points.\n */\nexport function formatDelta(delta: number | null | undefined, input?: FormatInput, context: FormatContext = \"label\") {\n  const resolved = resolveFormat(input);\n  if (typeof resolved === \"function\") {\n    if (delta === null || delta === undefined || Number.isNaN(delta)) return \"–\";\n    const t = resolved(Math.abs(delta));\n    return delta > 0 ? `+${t}` : delta < 0 ? `${MINUS}${t}` : t;\n  }\n  if (resolved.kind === \"percent\") {\n    return formatValue(delta === null || delta === undefined ? delta : delta * 100, { ...resolved, kind: \"pp\" }, {\n      context,\n      signed: true,\n    });\n  }\n  return formatValue(delta, resolved, { context, signed: true });\n}\n\n/** Relative change as a signed percentage. Returns \"–\" when the base is zero or missing. */\nexport function formatChange(current: number | null | undefined, base: number | null | undefined, decimals = 1) {\n  if (current == null || base == null || !Number.isFinite(current) || !Number.isFinite(base) || base === 0) return \"–\";\n  const change = (current - base) / Math.abs(base);\n  return formatValue(change, { kind: \"percent\", decimals }, { signed: true });\n}\n\n/** A share of a whole, with \"<1%\" for tiny non-zero shares rather than a misleading \"0%\". */\nexport function formatShare(share: number | null | undefined, decimals = 0) {\n  if (share === null || share === undefined || Number.isNaN(share)) return \"–\";\n  if (share > 0 && share * 100 < 0.5 * 10 ** -decimals) return `<${(10 ** -decimals).toString()}%`;\n  return formatValue(share, { kind: \"percent\", decimals });\n}\n\nexport type DateGrain = \"day\" | \"week\" | \"month\" | \"quarter\" | \"year\";\n\nconst MONTHS = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\n\n/** Format a timestamp (ms) in UTC at the given grain. */\nexport function formatDate(ms: number, grain: DateGrain = \"day\", style: \"short\" | \"long\" = \"short\"): string {\n  const d = new Date(ms);\n  if (Number.isNaN(d.getTime())) return \"–\";\n  const y = d.getUTCFullYear();\n  const m = d.getUTCMonth();\n  switch (grain) {\n    case \"year\":\n      return String(y);\n    case \"quarter\":\n      return `Q${Math.floor(m / 3) + 1} ${y}`;\n    case \"month\":\n      return style === \"long\" ? `${MONTHS[m]} ${y}` : `${MONTHS[m]} ${String(y).slice(2)}`;\n    case \"week\":\n    case \"day\":\n    default:\n      return style === \"long\" ? `${MONTHS[m]} ${d.getUTCDate()}, ${y}` : `${MONTHS[m]} ${d.getUTCDate()}`;\n  }\n}\n"
    },
    {
      "path": "registry/charts/core/frame.tsx",
      "type": "registry:lib",
      "target": "components/charts/core/frame.tsx",
      "content": "// core/frame.tsx · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com\n\"use client\";\n\nimport {\n  Component,\n  useCallback,\n  useId,\n  useLayoutEffect,\n  useEffect,\n  useRef,\n  useState,\n  type CSSProperties,\n  type ErrorInfo,\n  type KeyboardEvent,\n  type PointerEvent,\n  type ReactNode,\n} from \"react\";\nimport { hasError, toCSV, type Issue, type Row } from \"./data\";\nimport { ChartScope, useWords, useSelectHandler, type ChartWords, type ChartSelectEvent } from \"./words\";\n\nexport { ChartWordsProvider, DEFAULT_WORDS, useWords, type ChartWords, type ChartSelectEvent } from \"./words\";\n\n// ---------- size ----------\n\nconst useIsoLayoutEffect = typeof window === \"undefined\" ? useEffect : useLayoutEffect;\n\n/** Width of an element, tracked with ResizeObserver. Falls back to `fallback` where ResizeObserver is missing. */\nexport function useWidth<T extends HTMLElement>(fixed?: number, fallback = 640) {\n  const ref = useRef<T>(null);\n  const [width, setWidth] = useState(fixed ?? 0);\n  useIsoLayoutEffect(() => {\n    if (fixed) return setWidth(fixed);\n    const el = ref.current;\n    if (!el) return;\n    if (typeof ResizeObserver === \"undefined\") return setWidth(el.clientWidth || fallback);\n    const measure = () => setWidth(Math.floor(el.clientWidth || el.getBoundingClientRect().width || 0));\n    measure();\n    const ro = new ResizeObserver(measure);\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, [fixed, fallback]);\n  return [ref, width] as const;\n}\n\n// ---------- legend ----------\n\nexport type KeyShape = \"line\" | \"dash\" | \"square\" | \"dot\" | \"ring\" | \"band\";\n\nexport interface LegendItem {\n  key: string;\n  label: string;\n  color: string;\n  shape?: KeyShape;\n}\n\nexport function KeySwatch({ color, shape = \"square\" }: { color: string; shape?: KeyShape }) {\n  const s: CSSProperties = { background: color };\n  if (shape === \"line\") return <span className=\"clui-key clui-key-line\" style={s} aria-hidden />;\n  if (shape === \"dash\")\n    return (\n      <span\n        className=\"clui-key clui-key-line\"\n        style={{ background: `repeating-linear-gradient(90deg, ${color} 0 4px, transparent 4px 7px)` }}\n        aria-hidden\n      />\n    );\n  if (shape === \"dot\") return <span className=\"clui-key clui-key-dot\" style={s} aria-hidden />;\n  if (shape === \"ring\") return <span className=\"clui-key clui-key-ring\" style={{ borderColor: color }} aria-hidden />;\n  if (shape === \"band\") return <span className=\"clui-key clui-key-band\" style={s} aria-hidden />;\n  return <span className=\"clui-key\" style={s} aria-hidden />;\n}\n\nexport function Legend({\n  items,\n  hidden,\n  onToggle,\n  onHover,\n}: {\n  items: LegendItem[];\n  hidden?: Set<string>;\n  onToggle?: (key: string) => void;\n  onHover?: (key: string | null) => void;\n}) {\n  const L = useWords();\n  if (!items.length) return null;\n  return (\n    <ul className=\"clui-legend\" aria-label={L.legend}>\n      {items.map((it) => {\n        const off = hidden?.has(it.key);\n        const content = (\n          <>\n            <KeySwatch color={it.color} shape={it.shape} />\n            <span>{it.label}</span>\n          </>\n        );\n        return (\n          <li key={it.key} onPointerEnter={() => onHover?.(it.key)} onPointerLeave={() => onHover?.(null)}>\n            {onToggle ? (\n              <button\n                type=\"button\"\n                className=\"clui-legend-btn\"\n                aria-pressed={!off}\n                data-off={off || undefined}\n                onClick={() => onToggle(it.key)}\n                onFocus={() => onHover?.(it.key)}\n                onBlur={() => onHover?.(null)}\n                title={`${off ? L.show : L.hide} ${it.label}`}\n              >\n                {content}\n              </button>\n            ) : (\n              <span className=\"clui-legend-item\">{content}</span>\n            )}\n          </li>\n        );\n      })}\n    </ul>\n  );\n}\n\n/** Legend state: hidden series and the hovered (highlighted) series. Colours never change when toggling. */\nexport function useSeriesToggle(keys: string[]) {\n  const [hidden, setHidden] = useState<Set<string>>(() => new Set());\n  const [focus, setFocus] = useState<string | null>(null);\n  const toggle = useCallback(\n    (key: string) =>\n      setHidden((prev) => {\n        const next = new Set(prev);\n        if (next.has(key)) next.delete(key);\n        else if (keys.length - next.size > 1) next.add(key); // always keep one series visible\n        return next;\n      }),\n    [keys.length],\n  );\n  return { hidden, toggle, focus, setFocus };\n}\n\n// ---------- tooltip ----------\n\nexport interface TooltipRow {\n  label: string;\n  value: string;\n  color?: string;\n  shape?: KeyShape;\n  strong?: boolean;\n  note?: string;\n}\n\nexport interface TooltipData {\n  title?: string;\n  rows: TooltipRow[];\n  footer?: string;\n}\n\n/** Tooltip positioned inside the plot. Flips to the left of the pointer on the right half. */\nexport function ChartTooltip({\n  x,\n  y,\n  width,\n  height,\n  data,\n}: {\n  x: number;\n  y: number;\n  width: number;\n  height: number;\n  data: TooltipData | null;\n}) {\n  if (!data) return null;\n  const flip = x > width * 0.55;\n  const top = Math.max(8, Math.min(height - 8, y));\n  const style: CSSProperties = {\n    left: x,\n    top,\n    transform: `translate(${flip ? \"calc(-100% - 14px)\" : \"14px\"}, ${top > height * 0.6 ? \"-100%\" : top < height * 0.3 ? \"0\" : \"-50%\"})`,\n  };\n  return (\n    <div className=\"clui-tooltip\" style={style} role=\"status\" aria-live=\"polite\">\n      {data.title && <div className=\"clui-tooltip-title\">{data.title}</div>}\n      {data.rows.length > 0 && (\n        <table>\n          <tbody>\n            {data.rows.map((r, i) => (\n              <tr key={i} data-strong={r.strong || undefined}>\n                <td className=\"clui-tooltip-label\">\n                  {r.color && <KeySwatch color={r.color} shape={r.shape} />}\n                  <span>{r.label}</span>\n                </td>\n                <td className=\"clui-tooltip-value\">\n                  {r.value}\n                  {r.note && <span className=\"clui-tooltip-note\"> {r.note}</span>}\n                </td>\n              </tr>\n            ))}\n          </tbody>\n        </table>\n      )}\n      {data.footer && <div className=\"clui-tooltip-footer\">{data.footer}</div>}\n    </div>\n  );\n}\n\n/** Pointer position relative to the element that received the event. */\nexport function localPoint(e: PointerEvent<Element>) {\n  const rect = (e.currentTarget as Element).getBoundingClientRect();\n  return { x: e.clientX - rect.left, y: e.clientY - rect.top };\n}\n\n/**\n * The active (hovered or keyboard-focused) item. Spread `keyProps` on the focusable SVG: arrow keys move,\n * Home/End jump, Escape clears.\n */\nexport function useActiveIndex(\n  count: number,\n  opts: {\n    columns?: number;\n    /** What a click on mark i reports to the chart's onSelect (label and data row). */\n    describe?: (i: number) => Omit<ChartSelectEvent, \"index\">;\n  } = {},\n) {\n  const [active, setActive] = useState<number | null>(null);\n  const onSelect = useSelectHandler();\n  const cols = opts.columns;\n  const select = (i: number | null) => {\n    if (!onSelect || i === null || i < 0 || i >= count) return;\n    onSelect({ index: i, ...opts.describe?.(i) });\n  };\n  const onKeyDown = (e: KeyboardEvent) => {\n    if (!count) return;\n    if ((e.key === \"Enter\" || e.key === \" \") && onSelect && active !== null) {\n      e.preventDefault();\n      select(active);\n      return;\n    }\n    const cur = active ?? -1;\n    let next: number | null = cur;\n    switch (e.key) {\n      case \"ArrowRight\":\n        next = Math.min(count - 1, cur + 1);\n        break;\n      case \"ArrowLeft\":\n        next = Math.max(0, cur < 0 ? 0 : cur - 1);\n        break;\n      case \"ArrowDown\":\n        next = cols ? Math.min(count - 1, cur < 0 ? 0 : cur + cols) : Math.min(count - 1, cur + 1);\n        break;\n      case \"ArrowUp\":\n        next = cols ? Math.max(0, cur - cols) : Math.max(0, cur < 0 ? 0 : cur - 1);\n        break;\n      case \"Home\":\n        next = 0;\n        break;\n      case \"End\":\n        next = count - 1;\n        break;\n      case \"Escape\":\n        next = null;\n        break;\n      default:\n        return;\n    }\n    e.preventDefault();\n    setActive(next);\n  };\n  const keyProps = {\n    tabIndex: 0,\n    onKeyDown,\n    onBlur: () => setActive(null),\n    onClick: onSelect ? () => select(active) : undefined,\n    \"data-selectable\": onSelect ? \"\" : undefined,\n  };\n  return { active, setActive, keyProps };\n}\n\n// ---------- table ----------\n\nexport interface TableColumn {\n  key: string;\n  label: string;\n  align?: \"left\" | \"right\";\n  /** Display formatter. The raw value is used for CSV. */\n  format?: (value: unknown, row: Row) => string;\n}\n\nexport interface TableData {\n  columns: TableColumn[];\n  rows: Row[];\n  caption?: string;\n}\n\nexport function DataTable({ table, maxHeight }: { table: TableData; maxHeight?: number }) {\n  return (\n    <div className=\"clui-table-wrap\" style={maxHeight ? { maxHeight } : undefined} tabIndex={0}>\n      <table className=\"clui-table\">\n        {table.caption && <caption className=\"clui-sr\">{table.caption}</caption>}\n        <thead>\n          <tr>\n            {table.columns.map((c) => (\n              <th key={c.key} scope=\"col\" data-align={c.align ?? \"left\"}>\n                {c.label}\n              </th>\n            ))}\n          </tr>\n        </thead>\n        <tbody>\n          {table.rows.map((row, i) => (\n            <tr key={i}>\n              {table.columns.map((c, j) => {\n                const v = row[c.key];\n                const text = c.format ? c.format(v, row) : v === null || v === undefined ? \"–\" : String(v);\n                return j === 0 ? (\n                  <th key={c.key} scope=\"row\" data-align={c.align ?? \"left\"}>\n                    {text}\n                  </th>\n                ) : (\n                  <td key={c.key} data-align={c.align ?? \"left\"}>\n                    {text}\n                  </td>\n                );\n              })}\n            </tr>\n          ))}\n        </tbody>\n      </table>\n    </div>\n  );\n}\n\nexport function downloadCSV(table: TableData, filename = \"chart-data.csv\") {\n  const csv = toCSV(table.columns, table.rows);\n  const blob = new Blob([\"﻿\" + csv], { type: \"text/csv;charset=utf-8\" });\n  const url = URL.createObjectURL(blob);\n  const a = document.createElement(\"a\");\n  a.href = url;\n  a.download = filename;\n  document.body.appendChild(a);\n  a.click();\n  a.remove();\n  setTimeout(() => URL.revokeObjectURL(url), 1000);\n}\n\n// ---------- messages ----------\n\nexport function ChartMessage({ issues, height }: { issues: Issue[]; height: number }) {\n  const errors = issues.filter((i) => i.level === \"error\");\n  const empty = errors.length === 1 && errors[0].message === \"No data to display.\";\n  return (\n    <div className=\"clui-message\" style={{ minHeight: height }} role=\"alert\" data-kind={empty ? \"empty\" : \"error\"}>\n      <div className=\"clui-message-title\">{empty ? \"No data to display\" : \"This chart can’t be drawn\"}</div>\n      {!empty && (\n        <ul>\n          {errors.slice(0, 4).map((e, i) => (\n            <li key={i}>{e.message}</li>\n          ))}\n        </ul>\n      )}\n    </div>\n  );\n}\n\nclass ChartBoundary extends Component<{ height: number; children: ReactNode }, { error: Error | null }> {\n  state = { error: null as Error | null };\n  static getDerivedStateFromError(error: Error) {\n    return { error };\n  }\n  componentDidCatch(error: Error, info: ErrorInfo) {\n    if (typeof console !== \"undefined\") console.error(\"[chart] render failed\", error, info.componentStack);\n  }\n  render() {\n    if (this.state.error)\n      return (\n        <ChartMessage\n          height={this.props.height}\n          issues={[{ level: \"error\", message: `Rendering failed: ${this.state.error.message}` }]}\n        />\n      );\n    return this.props.children;\n  }\n}\n\n// ---------- frame ----------\n\nexport type ChartMode = \"light\" | \"dark\" | \"auto\";\n\nexport interface FrameProps {\n  /** The takeaway, e.g. \"Revenue passed plan in Q3\". */\n  title?: ReactNode;\n  /** What is measured: metric, unit, basis, period. */\n  subtitle?: ReactNode;\n  /** Data source, shown in the footer. */\n  source?: ReactNode;\n  /** Extra footnote text. */\n  footnote?: ReactNode;\n  /** Height of the plot area in px. 0 lets the content set its own height. */\n  height?: number;\n  /** Fixed width in px. Defaults to the container width. */\n  width?: number;\n  /** Light/dark override. By default the chart follows `.dark` / `[data-theme=\"dark\"]` on an ancestor. */\n  mode?: ChartMode;\n  /** Show the table/CSV toolbar. */\n  toolbar?: boolean;\n  /** Show data notes (missing values, duplicates) under the chart. */\n  showNotes?: boolean;\n  className?: string;\n  style?: CSSProperties;\n  /** Heading element for the title. */\n  titleAs?: \"h2\" | \"h3\" | \"h4\" | \"div\";\n  /** Translate the words the chart draws itself (\"Total\", \"Forecast\", \"Table\"…). See ChartWordsProvider. */\n  words?: Partial<ChartWords>;\n  /** Called when someone clicks a mark (or presses Enter on it): its index, label and data row. */\n  onSelect?: (e: ChartSelectEvent) => void;\n}\n\nexport interface ChartFrameProps extends FrameProps {\n  legend?: LegendItem[];\n  legendHidden?: Set<string>;\n  onLegendToggle?: (key: string) => void;\n  onLegendHover?: (key: string | null) => void;\n  issues?: Issue[];\n  table?: TableData;\n  /** Screen-reader summary of what the chart shows. */\n  summary: string;\n  /** Name used for the CSV file. */\n  csvName?: string;\n  /** Minimum width before the plot scrolls horizontally instead of compressing further. */\n  minWidth?: number;\n  /** Start in table view. */\n  defaultView?: \"chart\" | \"table\";\n  children: (size: { width: number; height: number }) => ReactNode;\n}\n\nexport function ChartFrame(props: ChartFrameProps) {\n  return (\n    <ChartScope labels={props.words} onSelect={props.onSelect}>\n      <FrameBody {...props} />\n    </ChartScope>\n  );\n}\n\nfunction FrameBody(props: ChartFrameProps) {\n  const L = useWords();\n  const {\n    title,\n    subtitle,\n    source,\n    footnote,\n    height = 280,\n    width: fixedWidth,\n    mode,\n    toolbar = true,\n    showNotes = true,\n    className,\n    style,\n    titleAs: TitleTag = \"h3\",\n    legend,\n    legendHidden,\n    onLegendToggle,\n    onLegendHover,\n    issues = [],\n    table,\n    summary,\n    csvName,\n    minWidth = 0,\n    defaultView = \"chart\",\n    children,\n  } = props;\n  const [ref, measured] = useWidth<HTMLDivElement>(fixedWidth);\n  const [view, setView] = useState<\"chart\" | \"table\">(defaultView);\n  const id = useId();\n  const failed = hasError(issues);\n  const notes = issues.filter((i) => i.level !== \"error\");\n  const plotWidth = Math.max(measured, minWidth);\n\n  return (\n    <figure\n      className={[\"clui\", className].filter(Boolean).join(\" \")}\n      data-mode={mode}\n      style={{ ...(fixedWidth ? { width: fixedWidth } : null), ...style }}\n      aria-labelledby={title ? `${id}-t` : undefined}\n      aria-describedby={`${id}-s`}\n    >\n      {(title || subtitle || (toolbar && table && !failed)) && (\n        <div className=\"clui-head\">\n          <div className=\"clui-head-text\">\n            {title && (\n              <TitleTag className=\"clui-title\" id={`${id}-t`}>\n                {title}\n              </TitleTag>\n            )}\n            {subtitle && <p className=\"clui-subtitle\">{subtitle}</p>}\n          </div>\n          {toolbar && table && !failed && (\n            <div className=\"clui-toolbar\">\n              <button\n                type=\"button\"\n                className=\"clui-tool\"\n                aria-pressed={view === \"table\"}\n                onClick={() => setView((v) => (v === \"chart\" ? \"table\" : \"chart\"))}\n              >\n                {view === \"chart\" ? L.table : L.chart}\n              </button>\n              <button\n                type=\"button\"\n                className=\"clui-tool\"\n                onClick={() => downloadCSV(table, csvName ?? (typeof title === \"string\" ? slug(title) : \"chart-data\") + \".csv\")}\n                aria-label={L.downloadCsv}\n              >\n                {L.csv}\n              </button>\n            </div>\n          )}\n        </div>\n      )}\n      {legend && legend.length > 0 && !failed && view === \"chart\" && (\n        <Legend items={legend} hidden={legendHidden} onToggle={onLegendToggle} onHover={onLegendHover} />\n      )}\n      <p className=\"clui-sr\" id={`${id}-s`}>\n        {summary}\n      </p>\n      <div\n        ref={ref}\n        className=\"clui-plot\"\n        style={{ minHeight: height || 120, overflowX: minWidth && measured < minWidth ? \"auto\" : undefined }}\n      >\n        {failed ? (\n          <ChartMessage issues={issues} height={height} />\n        ) : view === \"table\" && table ? (\n          <DataTable table={table} maxHeight={Math.max(height, 200)} />\n        ) : measured > 0 ? (\n          <ChartBoundary height={height}>\n            <div style={{ position: \"relative\", width: plotWidth, height: height || undefined }}>\n              {children({ width: plotWidth, height })}\n            </div>\n          </ChartBoundary>\n        ) : (\n          <div style={{ height: height || 120 }} aria-hidden />\n        )}\n      </div>\n      {((showNotes && notes.length > 0) || source || footnote) && (\n        <figcaption className=\"clui-foot\">\n          {showNotes &&\n            notes.map((n, i) => (\n              <span key={i} className=\"clui-note\" data-level={n.level}>\n                {`${n.level === \"warning\" ? L.check : L.note}: `}\n                {n.message}\n              </span>\n            ))}\n          {footnote && <span className=\"clui-note\">{footnote}</span>}\n          {source && <span className=\"clui-source\">{L.source}: {source}</span>}\n        </figcaption>\n      )}\n    </figure>\n  );\n}\n\nfunction slug(s: string) {\n  return (\n    s\n      .toLowerCase()\n      .replace(/[^a-z0-9]+/g, \"-\")\n      .replace(/^-|-$/g, \"\")\n      .slice(0, 60) || \"chart-data\"\n  );\n}\n"
    },
    {
      "path": "registry/charts/core/path.ts",
      "type": "registry:lib",
      "target": "components/charts/core/path.ts",
      "content": "// core/path.ts · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com\n/** SVG path builders. Points that are null create gaps, so missing data is never interpolated. */\n\nexport type Point = [number, number];\nexport type MaybePoint = Point | null;\nexport type Curve = \"linear\" | \"monotone\" | \"step\" | \"step-before\";\n\nconst r = (v: number) => Math.round(v * 10) / 10;\n\n/** Split a point list into runs of consecutive non-null points. */\nexport function segments(points: MaybePoint[]): Point[][] {\n  const out: Point[][] = [];\n  let run: Point[] = [];\n  for (const p of points) {\n    if (p && Number.isFinite(p[0]) && Number.isFinite(p[1])) run.push(p);\n    else if (run.length) {\n      out.push(run);\n      run = [];\n    }\n  }\n  if (run.length) out.push(run);\n  return out;\n}\n\nfunction monotoneTangents(pts: Point[]): number[] {\n  const n = pts.length;\n  const m: number[] = [];\n  for (let i = 0; i < n - 1; i++) {\n    const dx = pts[i + 1][0] - pts[i][0];\n    m.push(dx === 0 ? 0 : (pts[i + 1][1] - pts[i][1]) / dx);\n  }\n  const t: number[] = new Array(n);\n  t[0] = m[0];\n  t[n - 1] = m[n - 2];\n  for (let i = 1; i < n - 1; i++) t[i] = m[i - 1] * m[i] <= 0 ? 0 : (m[i - 1] + m[i]) / 2;\n  for (let i = 0; i < n - 1; i++) {\n    if (m[i] === 0) {\n      t[i] = 0;\n      t[i + 1] = 0;\n      continue;\n    }\n    const a = t[i] / m[i];\n    const b = t[i + 1] / m[i];\n    const s = a * a + b * b;\n    if (s > 9) {\n      const tau = 3 / Math.sqrt(s);\n      t[i] = tau * a * m[i];\n      t[i + 1] = tau * b * m[i];\n    }\n  }\n  return t;\n}\n\n/** Path commands for one run, without the leading move. */\nfunction runCommands(pts: Point[], curve: Curve): string {\n  if (pts.length === 1) return \"\";\n  let d = \"\";\n  if (curve === \"step\") {\n    for (let i = 1; i < pts.length; i++) d += `H${r(pts[i][0])}V${r(pts[i][1])}`;\n    return d;\n  }\n  if (curve === \"step-before\") {\n    for (let i = 1; i < pts.length; i++) d += `V${r(pts[i][1])}H${r(pts[i][0])}`;\n    return d;\n  }\n  if (curve === \"monotone\" && pts.length > 2) {\n    const t = monotoneTangents(pts);\n    for (let i = 0; i < pts.length - 1; i++) {\n      const [x0, y0] = pts[i];\n      const [x1, y1] = pts[i + 1];\n      const dx = (x1 - x0) / 3;\n      d += `C${r(x0 + dx)},${r(y0 + t[i] * dx)},${r(x1 - dx)},${r(y1 - t[i + 1] * dx)},${r(x1)},${r(y1)}`;\n    }\n    return d;\n  }\n  for (let i = 1; i < pts.length; i++) d += `L${r(pts[i][0])},${r(pts[i][1])}`;\n  return d;\n}\n\n/** A line through the points; nulls break the line. Single isolated points produce no path (draw a dot). */\nexport function linePath(points: MaybePoint[], curve: Curve = \"linear\"): string {\n  return segments(points)\n    .filter((s) => s.length > 1)\n    .map((s) => `M${r(s[0][0])},${r(s[0][1])}${runCommands(s, curve)}`)\n    .join(\"\");\n}\n\n/** Points that have no neighbour on either side; they need a visible dot because a line can't show them. */\nexport function isolatedPoints(points: MaybePoint[]): Point[] {\n  return segments(points)\n    .filter((s) => s.length === 1)\n    .map((s) => s[0]);\n}\n\n/**\n * Area between a top line and a baseline. `base` is a constant y (e.g. the zero line) or a matching list of points\n * (stacked areas). Gaps in either list break the area.\n */\nexport function areaPath(top: MaybePoint[], base: number | MaybePoint[], curve: Curve = \"linear\"): string {\n  const bottom: MaybePoint[] = typeof base === \"number\" ? top.map((p) => (p ? [p[0], base] : null)) : base;\n  const ok = (p: MaybePoint | undefined): p is Point => !!p && Number.isFinite(p[0]) && Number.isFinite(p[1]);\n  const runs: number[][] = [];\n  let run: number[] = [];\n  top.forEach((p, i) => {\n    if (ok(p) && ok(bottom[i])) run.push(i);\n    else if (run.length) {\n      runs.push(run);\n      run = [];\n    }\n  });\n  if (run.length) runs.push(run);\n  const bottomCurve: Curve = curve === \"step\" ? \"step-before\" : curve === \"step-before\" ? \"step\" : curve;\n  let d = \"\";\n  for (const idx of runs) {\n    if (idx.length < 2) continue;\n    const t = idx.map((i) => top[i] as Point);\n    const b = idx.map((i) => bottom[i] as Point).reverse();\n    d += `M${r(t[0][0])},${r(t[0][1])}${runCommands(t, curve)}`;\n    d += `L${r(b[0][0])},${r(b[0][1])}${runCommands(b, bottomCurve)}Z`;\n  }\n  return d;\n}\n\nexport type BarEnd = \"up\" | \"down\" | \"left\" | \"right\";\n\n/**\n * A bar with a rounded data end and a square baseline. (x, y) is the top-left corner. `end` says which side\n * carries the value.\n */\nexport function barPath(x: number, y: number, w: number, h: number, radius = 4, end: BarEnd = \"up\"): string {\n  if (w <= 0 || h <= 0) return \"\";\n  const rad = Math.max(0, Math.min(radius, end === \"up\" || end === \"down\" ? w / 2 : h / 2, end === \"up\" || end === \"down\" ? h : w));\n  const x1 = x + w;\n  const y1 = y + h;\n  const a = (ex: number, ey: number) => `A${r(rad)},${r(rad)} 0 0 1 ${r(ex)},${r(ey)}`;\n  switch (end) {\n    case \"up\":\n      return `M${r(x)},${r(y1)}V${r(y + rad)}${a(x + rad, y)}H${r(x1 - rad)}${a(x1, y + rad)}V${r(y1)}Z`;\n    case \"down\":\n      return `M${r(x1)},${r(y)}V${r(y1 - rad)}${a(x1 - rad, y1)}H${r(x + rad)}${a(x, y1 - rad)}V${r(y)}Z`;\n    case \"right\":\n      return `M${r(x)},${r(y)}H${r(x1 - rad)}${a(x1, y + rad)}V${r(y1 - rad)}${a(x1 - rad, y1)}H${r(x)}Z`;\n    case \"left\":\n      return `M${r(x1)},${r(y1)}H${r(x + rad)}${a(x, y1 - rad)}V${r(y + rad)}${a(x + rad, y)}H${r(x1)}Z`;\n  }\n}\n\n/** Rectangle with all four corners rounded (cells, tiles, segments). */\nexport function roundedRect(x: number, y: number, w: number, h: number, radius = 2): string {\n  if (w <= 0 || h <= 0) return \"\";\n  const rad = Math.max(0, Math.min(radius, w / 2, h / 2));\n  const a = (ex: number, ey: number) => `A${r(rad)},${r(rad)} 0 0 1 ${r(ex)},${r(ey)}`;\n  return `M${r(x + rad)},${r(y)}H${r(x + w - rad)}${a(x + w, y + rad)}V${r(y + h - rad)}${a(x + w - rad, y + h)}H${r(\n    x + rad,\n  )}${a(x, y + h - rad)}V${r(y + rad)}${a(x + rad, y)}Z`;\n}\n\n/** Donut / pie sector. Angles in radians, 0 = 12 o'clock, clockwise. */\nexport function arcPath(cx: number, cy: number, inner: number, outer: number, start: number, end: number): string {\n  const sweep = end - start;\n  if (sweep <= 0) return \"\";\n  if (sweep >= Math.PI * 2 - 1e-6) {\n    // full ring: two halves\n    const mid = start + Math.PI;\n    return arcPath(cx, cy, inner, outer, start, mid) + arcPath(cx, cy, inner, outer, mid, start + Math.PI * 2 - 1e-6);\n  }\n  const p = (rad: number, a: number): Point => [cx + rad * Math.sin(a), cy - rad * Math.cos(a)];\n  const large = sweep > Math.PI ? 1 : 0;\n  const [ox0, oy0] = p(outer, start);\n  const [ox1, oy1] = p(outer, end);\n  let d = `M${r(ox0)},${r(oy0)}A${r(outer)},${r(outer)} 0 ${large} 1 ${r(ox1)},${r(oy1)}`;\n  if (inner > 0) {\n    const [ix1, iy1] = p(inner, end);\n    const [ix0, iy0] = p(inner, start);\n    d += `L${r(ix1)},${r(iy1)}A${r(inner)},${r(inner)} 0 ${large} 0 ${r(ix0)},${r(iy0)}Z`;\n  } else {\n    d += `L${r(cx)},${r(cy)}Z`;\n  }\n  return d;\n}\n"
    },
    {
      "path": "registry/charts/core/scale.ts",
      "type": "registry:lib",
      "target": "components/charts/core/scale.ts",
      "content": "// core/scale.ts · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com\n/** Minimal scales: linear, band, point and UTC time. Pure functions, no dependencies. */\nimport type { DateGrain } from \"./format\";\n\nexport interface LinearScale {\n  (value: number): number;\n  domain: [number, number];\n  range: [number, number];\n  invert(px: number): number;\n}\n\nexport function linearScale(domain: [number, number], range: [number, number]): LinearScale {\n  const [d0, d1] = domain;\n  const [r0, r1] = range;\n  const span = d1 - d0 || 1;\n  const fn = ((v: number) => r0 + ((v - d0) / span) * (r1 - r0)) as LinearScale;\n  fn.domain = domain;\n  fn.range = range;\n  fn.invert = (px: number) => d0 + ((px - r0) / (r1 - r0 || 1)) * span;\n  return fn;\n}\n\nfunction tickStep(min: number, max: number, count: number) {\n  const raw = Math.abs(max - min) / Math.max(1, count);\n  if (raw === 0 || !Number.isFinite(raw)) return 1;\n  const power = Math.floor(Math.log10(raw));\n  const base = 10 ** power;\n  const err = raw / base;\n  const mult = err >= 7.5 ? 10 : err >= 3.5 ? 5 : err >= 1.5 ? 2 : 1;\n  return mult * base;\n}\n\n/** Round numbers covering [min, max], about `count` intervals. */\nexport function niceTicks(min: number, max: number, count = 5): number[] {\n  if (!Number.isFinite(min) || !Number.isFinite(max)) return [0];\n  if (min === max) {\n    if (min === 0) return [0, 1];\n    const pad = Math.abs(min) * 0.1;\n    return niceTicks(min - pad, max + pad, count);\n  }\n  if (min > max) [min, max] = [max, min];\n  const step = tickStep(min, max, count);\n  const start = Math.floor(min / step) * step;\n  const stop = Math.ceil(max / step) * step;\n  const ticks: number[] = [];\n  const decimals = Math.max(0, -Math.floor(Math.log10(step)) + 1);\n  for (let v = start, i = 0; v <= stop + step / 2 && i < 100; v += step, i++) {\n    ticks.push(Number(v.toFixed(decimals)) + 0);\n  }\n  return ticks.map((t) => (Object.is(t, -0) ? 0 : t));\n}\n\nexport interface ValueDomainOptions {\n  /** Force zero into the domain (required for bars, columns and areas). */\n  includeZero?: boolean;\n  /** Target number of tick intervals. */\n  ticks?: number;\n  /** Explicit domain; null entries are computed. */\n  domain?: [number | null, number | null];\n}\n\n/** Compute a nice domain + ticks for a set of values (non-finite values are ignored). */\nexport function valueDomain(values: number[], opts: ValueDomainOptions = {}) {\n  const finite = values.filter((v) => Number.isFinite(v));\n  let min = finite.length ? Math.min(...finite) : 0;\n  let max = finite.length ? Math.max(...finite) : 1;\n  if (opts.includeZero) {\n    min = Math.min(0, min);\n    max = Math.max(0, max);\n  }\n  const fixedMin = opts.domain?.[0];\n  const fixedMax = opts.domain?.[1];\n  if (fixedMin != null) min = fixedMin;\n  if (fixedMax != null) max = fixedMax;\n  const ticks = niceTicks(min, max, opts.ticks ?? 5);\n  const lo = fixedMin ?? ticks[0];\n  const hi = fixedMax ?? ticks[ticks.length - 1];\n  return { domain: [lo, hi] as [number, number], ticks: ticks.filter((t) => t >= lo - 1e-9 && t <= hi + 1e-9) };\n}\n\nexport interface BandScale {\n  (index: number): number;\n  bandwidth: number;\n  step: number;\n  count: number;\n  /** index of the band that contains px, clamped. */\n  indexAt(px: number): number;\n}\n\n/** Evenly spaced bands for categorical bars. */\nexport function bandScale(\n  count: number,\n  range: [number, number],\n  opts: { paddingInner?: number; paddingOuter?: number } = {},\n): BandScale {\n  const inner = opts.paddingInner ?? 0.25;\n  const outer = opts.paddingOuter ?? 0.12;\n  const [r0, r1] = range;\n  const n = Math.max(1, count);\n  const step = (r1 - r0) / Math.max(1, n - inner + outer * 2);\n  const bandwidth = step * (1 - inner);\n  const start = r0 + step * outer;\n  const fn = ((i: number) => start + i * step) as BandScale;\n  fn.bandwidth = Math.max(0, bandwidth);\n  fn.step = step;\n  fn.count = count;\n  fn.indexAt = (px: number) => Math.max(0, Math.min(count - 1, Math.floor((px - start + (step * inner) / 2) / step)));\n  return fn;\n}\n\nexport interface PointScale {\n  (index: number): number;\n  step: number;\n  count: number;\n  indexAt(px: number): number;\n}\n\n/** Evenly spaced points for categorical lines (first and last point sit at the edges, with padding). */\nexport function pointScale(count: number, range: [number, number], padding = 0): PointScale {\n  const [r0, r1] = range;\n  const n = Math.max(1, count);\n  const step = n === 1 ? 0 : (r1 - r0 - padding * 2) / (n - 1);\n  const fn = ((i: number) => (n === 1 ? (r0 + r1) / 2 : r0 + padding + i * step)) as PointScale;\n  fn.step = step;\n  fn.count = count;\n  fn.indexAt = (px: number) =>\n    n === 1 ? 0 : Math.max(0, Math.min(n - 1, Math.round((px - r0 - padding) / (step || 1))));\n  return fn;\n}\n\n/** Index of the value in a sorted array nearest to target. */\nexport function nearestIndex(sorted: number[], target: number): number {\n  if (!sorted.length) return -1;\n  let lo = 0;\n  let hi = sorted.length - 1;\n  while (hi - lo > 1) {\n    const mid = (lo + hi) >> 1;\n    if (sorted[mid] < target) lo = mid;\n    else hi = mid;\n  }\n  return Math.abs(sorted[lo] - target) <= Math.abs(sorted[hi] - target) ? lo : hi;\n}\n\n// ---------- time ----------\n\nconst DAY = 86_400_000;\n\ninterface TimeInterval {\n  grain: DateGrain;\n  ms: number;\n  step: number;\n  unit: \"day\" | \"month\" | \"year\";\n}\n\nconst INTERVALS: TimeInterval[] = [\n  { grain: \"day\", ms: DAY, step: 1, unit: \"day\" },\n  { grain: \"day\", ms: 2 * DAY, step: 2, unit: \"day\" },\n  { grain: \"week\", ms: 7 * DAY, step: 7, unit: \"day\" },\n  { grain: \"week\", ms: 14 * DAY, step: 14, unit: \"day\" },\n  { grain: \"month\", ms: 30 * DAY, step: 1, unit: \"month\" },\n  { grain: \"month\", ms: 61 * DAY, step: 2, unit: \"month\" },\n  { grain: \"quarter\", ms: 91 * DAY, step: 3, unit: \"month\" },\n  { grain: \"month\", ms: 182 * DAY, step: 6, unit: \"month\" },\n  { grain: \"year\", ms: 365 * DAY, step: 1, unit: \"year\" },\n  { grain: \"year\", ms: 730 * DAY, step: 2, unit: \"year\" },\n  { grain: \"year\", ms: 1826 * DAY, step: 5, unit: \"year\" },\n  { grain: \"year\", ms: 3652 * DAY, step: 10, unit: \"year\" },\n];\n\n/** Calendar-aligned UTC ticks between min and max (ms). */\nexport function timeTicks(min: number, max: number, count = 6): { ticks: number[]; grain: DateGrain } {\n  if (!Number.isFinite(min) || !Number.isFinite(max) || max <= min) return { ticks: [min], grain: \"day\" };\n  const target = (max - min) / Math.max(1, count);\n  const interval = INTERVALS.find((i) => i.ms >= target) ?? INTERVALS[INTERVALS.length - 1];\n  const ticks: number[] = [];\n  const start = new Date(min);\n  let cursor: Date;\n  if (interval.unit === \"day\") {\n    cursor = new Date(Date.UTC(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate()));\n    if (interval.step === 7 || interval.step === 14) {\n      // align to Monday\n      const dow = (cursor.getUTCDay() + 6) % 7;\n      cursor = new Date(cursor.getTime() - dow * DAY);\n    }\n  } else if (interval.unit === \"month\") {\n    const m = Math.floor(start.getUTCMonth() / interval.step) * interval.step;\n    cursor = new Date(Date.UTC(start.getUTCFullYear(), m, 1));\n  } else {\n    const y = Math.floor(start.getUTCFullYear() / interval.step) * interval.step;\n    cursor = new Date(Date.UTC(y, 0, 1));\n  }\n  let guard = 0;\n  while (cursor.getTime() <= max && guard++ < 500) {\n    if (cursor.getTime() >= min) ticks.push(cursor.getTime());\n    if (interval.unit === \"day\") cursor = new Date(cursor.getTime() + interval.step * DAY);\n    else if (interval.unit === \"month\")\n      cursor = new Date(Date.UTC(cursor.getUTCFullYear(), cursor.getUTCMonth() + interval.step, 1));\n    else cursor = new Date(Date.UTC(cursor.getUTCFullYear() + interval.step, 0, 1));\n  }\n  return { ticks, grain: interval.grain };\n}\n\n// ---------- colour steps ----------\n\n/** Map a value to a sequential step 1..steps (1 = lowest). Equal-width bins between min and max. */\nexport function sequentialStep(value: number, min: number, max: number, steps = 7): number {\n  if (!Number.isFinite(value)) return 0;\n  if (max <= min) return Math.ceil(steps / 2);\n  const t = (value - min) / (max - min);\n  return Math.max(1, Math.min(steps, Math.floor(t * steps) + 1));\n}\n\n/** Map a value to a diverging step -3..3 around `center` (0 = within the neutral band). */\nexport function divergingStep(value: number, maxAbs: number, center = 0): number {\n  if (!Number.isFinite(value) || maxAbs <= 0) return 0;\n  const t = (value - center) / maxAbs;\n  const a = Math.abs(t);\n  const s = a < 1 / 7 ? 0 : a < 3 / 7 ? 1 : a < 5 / 7 ? 2 : 3;\n  return t < 0 ? -s : s;\n}\n"
    },
    {
      "path": "registry/charts/core/series.tsx",
      "type": "registry:lib",
      "target": "components/charts/core/series.tsx",
      "content": "// core/series.tsx · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com\n\"use client\";\n\n/**\n * Shared engine for line, area, stacked-area, step and index charts: one x axis (categories or time), one y axis\n * (never two), gaps for missing values, forecast/partial periods, end labels, a crosshair tooltip and keyboard\n * navigation. The public chart files (line-chart.tsx, area-chart.tsx, ...) are thin wrappers around it.\n */\n\nimport { useMemo, type PointerEvent } from \"react\";\nimport { AXIS_FONT, PeriodShade, RefLine, XLabels, YGrid, axisWidth, placeEndLabels } from \"./axis\";\nimport { seriesColors, PALETTE_SIZE } from \"./color\";\nimport { checkRows, column, parseDate, type Issue, type Row } from \"./data\";\nimport { formatDate, formatValue, tickFormatter, type DateGrain, type FormatInput } from \"./format\";\nimport {\n  ChartFrame,\n  ChartTooltip,\n  localPoint,\n  useActiveIndex,\n  useSeriesToggle,\n  type FrameProps,\n  type LegendItem,\n  type TableData,\n  type TooltipRow,\n} from \"./frame\";\nimport { areaPath, isolatedPoints, linePath, type Curve, type MaybePoint } from \"./path\";\nimport { linearScale, nearestIndex, pointScale, timeTicks, valueDomain } from \"./scale\";\nimport { textWidth } from \"./text\";\nimport { useWords } from \"./words\";\n\nexport interface SeriesDef {\n  key: string;\n  label?: string;\n  /** Any CSS colour. Defaults to the categorical order (or grey context when `highlight` is used). */\n  color?: string;\n  /** Draw this whole series dashed (e.g. a plan or target line). */\n  dashed?: boolean;\n}\n\nexport type SeriesInput = string | SeriesDef;\n\nexport interface Reference {\n  value: number;\n  label?: string;\n}\n\nexport interface SeriesChartProps extends FrameProps {\n  data: Row[];\n  /** Key of the x value in each row. */\n  x: string;\n  series: SeriesInput[];\n  /** \"category\" treats x as labels (default); \"time\" reads ISO strings, Date or ms and spaces by real time. */\n  xType?: \"category\" | \"time\";\n  /** Date grain used to label time axes and tooltips. Auto-detected if omitted. */\n  grain?: DateGrain;\n  /** Y value format, e.g. \"currency\", { kind: \"percent\" }, or a function. */\n  format?: FormatInput;\n  curve?: Curve;\n  /** Series key(s) to emphasise; others are drawn as grey context. */\n  highlight?: string | string[];\n  /** First x value that is a forecast. From there on lines are dashed and the region is shaded. */\n  forecastFrom?: string | number | Date;\n  /** First x value that is an incomplete period (e.g. month to date). */\n  partialFrom?: string | number | Date;\n  /** Include zero in the y axis. Default true; set false to zoom in on a rate (lines only). */\n  zero?: boolean;\n  /** Fixed y domain; null keeps the computed bound. */\n  yDomain?: [number | null, number | null];\n  references?: Reference[];\n  /** Dots on every point. Default: only when there are few points. */\n  markers?: boolean;\n  /** Series names at the line ends. Default: on when up to 4 series fit. */\n  endLabels?: boolean;\n  /** Show the legend. Default: on for 2+ series. */\n  legend?: boolean;\n  /** Click legend entries to hide/show series. Default true for 2+ series. */\n  toggleable?: boolean;\n}\n\nexport type SeriesKind = \"line\" | \"area\" | \"stacked\" | \"stacked100\";\n\nconst DAY = 86_400_000;\n\nfunction guessGrain(times: number[]): DateGrain {\n  if (times.length < 2) return \"day\";\n  const gaps = times\n    .slice(1)\n    .map((t, i) => t - times[i])\n    .filter((g) => g > 0)\n    .sort((a, b) => a - b);\n  const g = gaps[Math.floor(gaps.length / 2)] ?? DAY;\n  if (g >= 360 * DAY) return \"year\";\n  if (g >= 89 * DAY) return \"quarter\";\n  if (g >= 27 * DAY) return \"month\";\n  if (g >= 6.5 * DAY) return \"week\";\n  return \"day\";\n}\n\nexport function normalizeSeries(series: SeriesInput[]): SeriesDef[] {\n  return (series ?? []).map((s) => (typeof s === \"string\" ? { key: s, label: s } : { ...s, label: s.label ?? s.key }));\n}\n\n/** Index of the first x at or after `from`, or -1. */\nfunction indexFrom(xs: unknown[], times: number[] | null, from: string | number | Date | undefined): number {\n  if (from === undefined || from === null) return -1;\n  if (times) {\n    const t = parseDate(from);\n    if (t === null) return -1;\n    return times.findIndex((v) => v >= t);\n  }\n  return xs.findIndex((v) => String(v) === String(from));\n}\n\nexport function SeriesChart(props: SeriesChartProps & { kind: SeriesKind; summaryName?: string }) {\n  const {\n    data,\n    x,\n    series: seriesInput,\n    xType = \"category\",\n    format,\n    curve = \"linear\",\n    highlight,\n    forecastFrom,\n    partialFrom,\n    zero = true,\n    yDomain,\n    references = [],\n    markers,\n    endLabels,\n    legend,\n    toggleable,\n    kind,\n    summaryName,\n    height = 280,\n    ...frame\n  } = props;\n\n  const series = useMemo(() => normalizeSeries(seriesInput), [seriesInput]);\n  const keys = series.map((s) => s.key);\n  const toggle = useSeriesToggle(keys);\n  const stacked = kind === \"stacked\" || kind === \"stacked100\";\n\n  const keySig = keys.join(\"|\");\n  const prepared = useMemo(() => {\n    const issues: Issue[] = checkRows(data, {\n      xKey: x,\n      valueKeys: keys,\n      maxSeries: PALETTE_SIZE,\n      allowMissing: true,\n    });\n    const rows = Array.isArray(data) ? data : [];\n    let times: number[] | null = null;\n    let order = rows.map((_, i) => i);\n    if (xType === \"time\" && rows.length) {\n      const parsed = rows.map((r) => parseDate(r?.[x]));\n      const bad = parsed.filter((t) => t === null).length;\n      if (bad) issues.push({ level: \"error\", message: `${bad} row(s) have an unreadable date in \"${x}\".` });\n      order = order.filter((i) => parsed[i] !== null).sort((a, b) => parsed[a]! - parsed[b]!);\n      times = order.map((i) => parsed[i]!);\n    }\n    const sorted = order.map((i) => rows[i]);\n    const cols = Object.fromEntries(keys.map((k) => [k, column(sorted, k).values]));\n    if (stacked) {\n      for (const k of keys) {\n        if (cols[k].some((v) => v !== null && v < 0)) {\n          issues.push({\n            level: \"error\",\n            message: `Stacked areas can't show negative values (\"${k}\" has some). Use a line chart or stacked bars.`,\n          });\n          break;\n        }\n      }\n    }\n    return { issues, rows: sorted, times, cols };\n  }, [data, x, keySig, xType, stacked]); // eslint-disable-line react-hooks/exhaustive-deps\n\n  const { issues, rows, times, cols } = prepared;\n  const n = rows.length;\n  const grain = props.grain ?? (times ? guessGrain(times) : \"month\");\n  const xLabel = (i: number) =>\n    times ? formatDate(times[i], grain, \"long\") : String(rows[i]?.[x] ?? \"\");\n\n  const colors = seriesColors(series, highlight);\n  const visible = series.filter((s) => !toggle.hidden.has(s.key));\n\n  // stacked values: per index, cumulative bottom/top for each visible series. Any missing cell breaks the column.\n  const visibleSig = visible.map((s) => s.key).join(\"|\");\n  const stack = useMemo(() => {\n    if (!stacked) return null;\n    const bottoms: Record<string, (number | null)[]> = {};\n    const tops: Record<string, (number | null)[]> = {};\n    const totals: (number | null)[] = [];\n    for (let i = 0; i < n; i++) {\n      const vals = visible.map((s) => cols[s.key]?.[i] ?? null);\n      const broken = vals.some((v) => v === null);\n      const total = broken ? null : vals.reduce<number>((a, b) => a + (b ?? 0), 0);\n      totals.push(total);\n      let acc = 0;\n      visible.forEach((s, j) => {\n        bottoms[s.key] ??= [];\n        tops[s.key] ??= [];\n        if (broken || total === null || (kind === \"stacked100\" && total === 0)) {\n          bottoms[s.key].push(null);\n          tops[s.key].push(null);\n          return;\n        }\n        const v = kind === \"stacked100\" ? vals[j]! / total : vals[j]!;\n        bottoms[s.key].push(acc);\n        acc += v;\n        tops[s.key].push(acc);\n      });\n    }\n    return { bottoms, tops, totals };\n  }, [stacked, kind, n, cols, visibleSig]); // eslint-disable-line react-hooks/exhaustive-deps\n\n  const yFormat: FormatInput | undefined = kind === \"stacked100\" ? { kind: \"percent\", decimals: 0 } : format;\n\n  const fIndex = indexFrom(rows.map((r) => r?.[x]), times, forecastFrom);\n  const pIndex = indexFrom(rows.map((r) => r?.[x]), times, partialFrom);\n  const splitAt = fIndex > 0 ? fIndex : pIndex > 0 ? pIndex : -1;\n\n  const allValues: number[] = [];\n  if (stack) {\n    for (const k of Object.keys(stack.tops)) for (const v of stack.tops[k]) if (v !== null) allValues.push(v);\n  } else {\n    for (const s of visible) for (const v of cols[s.key] ?? []) if (v !== null) allValues.push(v);\n  }\n  for (const r of references) allValues.push(r.value);\n\n  const tableData: TableData = {\n    columns: [\n      { key: \"__x\", label: x },\n      ...series.map((s) => ({\n        key: s.key,\n        label: s.label!,\n        align: \"right\" as const,\n        format: (v: unknown) => formatValue(v as number, format, { context: \"table\" }),\n      })),\n    ],\n    rows: rows.map((r, i) => ({\n      __x: times ? new Date(times[i]).toISOString().slice(0, 10) : r?.[x],\n      ...Object.fromEntries(series.map((s) => [s.key, cols[s.key]?.[i] ?? null])),\n    })),\n  };\n\n  const legendItems: LegendItem[] =\n    legend === false || (legend === undefined && series.length < 2)\n      ? []\n      : series.map((s) => ({\n          key: s.key,\n          label: s.label!,\n          color: colors[s.key],\n          shape: stacked || kind === \"area\" ? \"square\" : s.dashed ? \"dash\" : \"line\",\n        }));\n\n  const summary = buildSummary(summaryName ?? kind, series, cols, n, xLabel, format);\n\n  return (\n    <ChartFrame\n      {...frame}\n      height={height}\n      issues={issues}\n      table={tableData}\n      summary={summary}\n      legend={legendItems}\n      legendHidden={toggle.hidden}\n      onLegendToggle={(toggleable ?? series.length > 1) ? toggle.toggle : undefined}\n      onLegendHover={toggle.setFocus}\n    >\n      {({ width }) => (\n        <SeriesPlot\n          width={width}\n          height={height}\n          n={n}\n          times={times}\n          rows={rows}\n          x={x}\n          grain={grain}\n          series={series}\n          visible={visible}\n          cols={cols}\n          stack={stack}\n          kind={kind}\n          colors={colors}\n          curve={curve}\n          yFormat={yFormat}\n          format={format}\n          allValues={allValues}\n          zero={zero || kind !== \"line\"}\n          yDomain={kind === \"stacked100\" ? [0, 1] : yDomain}\n          references={references}\n          markers={markers}\n          endLabels={endLabels}\n          fIndex={fIndex}\n          pIndex={pIndex}\n          splitAt={splitAt}\n          xLabel={xLabel}\n          focus={toggle.focus}\n          highlight={highlight}\n        />\n      )}\n    </ChartFrame>\n  );\n}\n\nfunction buildSummary(\n  name: string,\n  series: SeriesDef[],\n  cols: Record<string, (number | null)[]>,\n  n: number,\n  xLabel: (i: number) => string,\n  format?: FormatInput,\n) {\n  if (!n) return `${name} chart with no data.`;\n  const parts = series.slice(0, 4).map((s) => {\n    const vals = (cols[s.key] ?? []).filter((v): v is number => v !== null);\n    if (!vals.length) return `${s.label}: no values`;\n    const first = vals[0];\n    const last = vals[vals.length - 1];\n    return `${s.label} from ${formatValue(first, format)} to ${formatValue(last, format)} (min ${formatValue(\n      Math.min(...vals),\n      format,\n    )}, max ${formatValue(Math.max(...vals), format)})`;\n  });\n  return `${name[0].toUpperCase()}${name.slice(1)} chart, ${n} points from ${xLabel(0)} to ${xLabel(n - 1)}. ${parts.join(\n    \"; \",\n  )}.${series.length > 4 ? ` ${series.length - 4} more series in the table view.` : \"\"} Use arrow keys to read values.`;\n}\n\ninterface PlotProps {\n  width: number;\n  height: number;\n  n: number;\n  times: number[] | null;\n  rows: Row[];\n  x: string;\n  grain: DateGrain;\n  series: SeriesDef[];\n  visible: SeriesDef[];\n  cols: Record<string, (number | null)[]>;\n  stack: { bottoms: Record<string, (number | null)[]>; tops: Record<string, (number | null)[]>; totals: (number | null)[] } | null;\n  kind: SeriesKind;\n  colors: Record<string, string>;\n  curve: Curve;\n  yFormat?: FormatInput;\n  format?: FormatInput;\n  allValues: number[];\n  zero: boolean;\n  yDomain?: [number | null, number | null];\n  references: Reference[];\n  markers?: boolean;\n  endLabels?: boolean;\n  fIndex: number;\n  pIndex: number;\n  splitAt: number;\n  xLabel: (i: number) => string;\n  focus: string | null;\n  highlight?: string | string[];\n}\n\nfunction SeriesPlot(p: PlotProps) {\n  const L = useWords();\n  const { width, height, n, times, cols, stack, kind, colors, curve, visible } = p;\n  const { active, setActive, keyProps } = useActiveIndex(n, { describe: (i) => ({ label: p.xLabel(i), row: p.rows[i] }) });\n  const stacked = !!stack;\n\n  const tickCount = Math.max(2, Math.min(6, Math.floor(height / 50)));\n  const { domain, ticks } = valueDomain(p.allValues, { includeZero: p.zero, ticks: tickCount, domain: p.yDomain });\n  const fmtTick = tickFormatter(p.yFormat, ticks);\n  const tickLabels = ticks.map(fmtTick);\n\n  // end labels: names at line ends (lines only, up to 4 visible series, enough width)\n  const lastIndex = (key: string) => {\n    const vals = stacked ? stack!.tops[key] : cols[key];\n    for (let i = (vals?.length ?? 0) - 1; i >= 0; i--) if (vals[i] !== null) return i;\n    return -1;\n  };\n  const wantEnd =\n    p.endLabels ?? (kind === \"line\" && visible.length >= 2 && visible.length <= 4 && width >= 420);\n  const endLabelWidth = wantEnd\n    ? Math.min(140, Math.max(...visible.map((s) => textWidth(s.label!, AXIS_FONT))) + 14)\n    : 0;\n\n  const forecastLabel = p.fIndex > 0 || p.pIndex > 0;\n  const top = forecastLabel ? 20 : 8;\n  const bottom = height - 24;\n  const left = axisWidth(tickLabels);\n  const right = width - Math.max(10, endLabelWidth);\n\n  const y = linearScale(domain, [bottom, top]);\n  const xs: number[] = (() => {\n    if (times && times.length) {\n      const t0 = times[0];\n      const t1 = times[times.length - 1];\n      const sx = linearScale([t0, t1 === t0 ? t0 + 1 : t1], [left + 4, right - 4]);\n      return times.map((t) => (t1 === t0 ? (left + right) / 2 : sx(t)));\n    }\n    const ps = pointScale(n, [left, right], Math.min(24, (right - left) / Math.max(2, n) / 2));\n    return Array.from({ length: n }, (_, i) => ps(i));\n  })();\n\n  const pts = (vals: (number | null)[] | undefined): MaybePoint[] =>\n    (vals ?? []).map((v, i) => (v === null || v === undefined ? null : [xs[i], y(v)]));\n\n  // x axis labels\n  let xAxis;\n  if (times && times.length > 1) {\n    const { ticks: tt, grain: tg } = timeTicks(times[0], times[times.length - 1], Math.max(2, Math.floor((right - left) / 80)));\n    const sx = linearScale([times[0], times[times.length - 1]], [left + 4, right - 4]);\n    xAxis = (\n      <XLabels\n        positions={tt.map((t) => sx(t))}\n        labels={tt.map((t) => formatDate(t, tg === \"week\" ? \"day\" : tg))}\n        y={bottom + 17}\n        anchorEnds\n        x0={left - 8}\n        x1={width}\n        ticks\n        tickTop={bottom}\n      />\n    );\n  } else {\n    xAxis = (\n      <XLabels\n        positions={xs}\n        labels={p.rows.map((r, i) => (times ? formatDate(times[i], p.grain) : String(r?.[p.x] ?? \"\")))}\n        y={bottom + 17}\n        anchorEnds\n        x0={left - 8}\n        x1={width}\n      />\n    );\n  }\n\n  const splitX = (idx: number) => (idx <= 0 ? null : (xs[idx - 1] + xs[idx]) / 2);\n  const fx = splitX(p.fIndex);\n  const px = splitX(p.pIndex);\n\n  const onMove = (e: PointerEvent<SVGRectElement>) => {\n    const { x: mx } = localPoint(e);\n    const px0 = mx + left;\n    setActive(times ? nearestIndex(xs, px0) : nearestIndex(xs, px0));\n  };\n\n  const isDim = (key: string) => p.focus !== null && p.focus !== key;\n  const hl = p.highlight === undefined ? null : new Set(Array.isArray(p.highlight) ? p.highlight : [p.highlight]);\n  // context series first so highlighted ones sit on top\n  const drawOrder = [...visible].sort((a, b) => Number(hl?.has(a.key) ?? 0) - Number(hl?.has(b.key) ?? 0));\n\n  const showMarkers = p.markers ?? n <= 12;\n\n  const lines = drawOrder.map((s) => {\n    const vals = stacked ? stack!.tops[s.key] : cols[s.key];\n    const all = pts(vals);\n    const c = colors[s.key];\n    const isContext = hl !== null && !hl.has(s.key);\n    const strokeW = isContext ? 1.5 : 2;\n    const solid = p.splitAt > 0 ? all.map((pt, i) => (i < p.splitAt ? pt : null)) : all;\n    const dashed = p.splitAt > 0 ? all.map((pt, i) => (i >= p.splitAt - 1 ? pt : null)) : [];\n    const areaFill =\n      kind === \"line\"\n        ? null\n        : stacked\n          ? areaPath(all, pts(stack!.bottoms[s.key]), curve)\n          : areaPath(all, y(Math.max(domain[0], Math.min(0, domain[1]))), curve);\n    const dots = showMarkers ? all : isolatedPoints(all);\n    return (\n      <g key={s.key} className={`clui-mark${isDim(s.key) ? \" clui-dim\" : \"\"}`}>\n        {areaFill && (\n          <path d={areaFill} style={{ fill: c, opacity: stacked ? 0.85 : 0.12 }} stroke=\"none\" />\n        )}\n        {stacked && <path d={linePath(solid, curve)} style={{ stroke: \"var(--clui-surface)\" }} strokeWidth={1.5} fill=\"none\" />}\n        {!stacked && (\n          <>\n            <path\n              d={linePath(solid, curve)}\n              style={{ stroke: c }}\n              strokeWidth={strokeW}\n              fill=\"none\"\n              strokeLinejoin=\"round\"\n              strokeLinecap=\"round\"\n              strokeDasharray={s.dashed ? \"5 4\" : undefined}\n            />\n            {dashed.length > 0 && (\n              <path\n                d={linePath(dashed, curve)}\n                style={{ stroke: c }}\n                strokeWidth={strokeW}\n                fill=\"none\"\n                strokeDasharray=\"4 4\"\n                strokeLinecap=\"round\"\n              />\n            )}\n          </>\n        )}\n        {!stacked &&\n          dots.map((pt, i) =>\n            pt ? (\n              <circle\n                key={i}\n                cx={pt[0]}\n                cy={pt[1]}\n                r={3.5}\n                style={{ fill: c, stroke: \"var(--clui-surface)\" }}\n                strokeWidth={1.5}\n              />\n            ) : null,\n          )}\n      </g>\n    );\n  });\n\n  // end labels\n  let endLabelEls = null;\n  if (wantEnd && endLabelWidth) {\n    const items = visible\n      .map((s) => ({ s, i: lastIndex(s.key) }))\n      .filter((o) => o.i >= 0)\n      .map((o) => {\n        const v = stacked ? stack!.tops[o.s.key][o.i]! : cols[o.s.key][o.i]!;\n        return { ...o, y: y(v) };\n      });\n    const placed = placeEndLabels(\n      items.map((o) => o.y),\n      13,\n      top,\n      bottom,\n    );\n    if (placed) {\n      endLabelEls = items.map((o, k) => (\n        <text\n          key={o.s.key}\n          x={xs[o.i] + 8}\n          y={placed[k]}\n          dy=\"0.32em\"\n          className={`clui-label clui-halo${isDim(o.s.key) ? \" clui-dim\" : \"\"}`}\n        >\n          {o.s.label}\n        </text>\n      ));\n    }\n  }\n\n  // tooltip\n  let tip = null;\n  if (active !== null && active < n) {\n    const order = stacked ? [...visible].reverse() : visible;\n    const rows: TooltipRow[] = order.map((s) => {\n      const v = cols[s.key]?.[active] ?? null;\n      const share =\n        kind === \"stacked100\" && stack && stack.totals[active] ? (v ?? 0) / stack.totals[active]! : null;\n      return {\n        label: s.label!,\n        value: formatValue(v, p.format, { context: \"tooltip\" }),\n        note: share !== null ? `(${formatValue(share, { kind: \"percent\", decimals: 0 })})` : undefined,\n        color: colors[s.key],\n        shape: (stacked || kind === \"area\" ? \"square\" : \"line\") as \"square\" | \"line\",\n      };\n    });\n    if (stacked && visible.length > 1) {\n      rows.push({\n        label: L.total,\n        value: formatValue(stack!.totals[active], p.format, { context: \"tooltip\" }),\n        strong: true,\n      });\n    }\n    const tags = [\n      p.fIndex > 0 && active >= p.fIndex ? L.forecast : null,\n      p.pIndex > 0 && active >= p.pIndex ? \"Partial period\" : null,\n    ].filter(Boolean);\n    const anyVal = visible.map((s) => (stacked ? stack!.tops[s.key][active] : cols[s.key]?.[active])).find((v) => v !== null && v !== undefined);\n    tip = (\n      <ChartTooltip\n        x={xs[active]}\n        y={anyVal !== undefined && anyVal !== null ? y(anyVal) : (top + bottom) / 2}\n        width={width}\n        height={height}\n        data={{ title: p.xLabel(active), rows, footer: tags.length ? tags.join(\" · \") : undefined }}\n      />\n    );\n  }\n\n  return (\n    <>\n      <svg width={width} height={height} role=\"group\" aria-roledescription=\"chart\" aria-label=\"Chart. Use arrow keys to read values.\" {...keyProps}>\n        {fx !== null && <PeriodShade x0={fx} x1={right} top={top - 14} bottom={bottom} label={L.forecast} />}\n        {px !== null && (fx === null || px < fx) && (\n          <PeriodShade x0={px} x1={fx ?? right} top={top - 14} bottom={bottom} label=\"Partial\" kind=\"partial\" />\n        )}\n        <YGrid ticks={ticks} y={y} x0={left} x1={right} format={fmtTick} />\n        {xAxis}\n        {p.references.map((r, i) => (\n          <RefLine key={i} y={y(r.value)} x0={left} x1={right} label={r.label} />\n        ))}\n        {lines}\n        {endLabelEls}\n        {active !== null && active < n && (\n          <g aria-hidden>\n            <line x1={xs[active]} x2={xs[active]} y1={top} y2={bottom} style={{ stroke: \"var(--clui-axis)\" }} />\n            {visible.map((s) => {\n              const v = stacked ? stack!.tops[s.key][active] : cols[s.key]?.[active];\n              if (v === null || v === undefined) return null;\n              return (\n                <circle\n                  key={s.key}\n                  cx={xs[active]}\n                  cy={y(v)}\n                  r={4.5}\n                  style={{ fill: colors[s.key], stroke: \"var(--clui-surface)\" }}\n                  strokeWidth={2}\n                />\n              );\n            })}\n          </g>\n        )}\n        <rect\n          x={left}\n          y={0}\n          width={Math.max(0, right - left + (endLabelWidth ? 0 : 10))}\n          height={bottom}\n          fill=\"transparent\"\n          onPointerMove={onMove}\n          onPointerDown={onMove}\n          onPointerLeave={() => setActive(null)}\n        />\n      </svg>\n      {tip}\n    </>\n  );\n}\n\n"
    },
    {
      "path": "registry/charts/core/text.ts",
      "type": "registry:lib",
      "target": "components/charts/core/text.ts",
      "content": "// core/text.ts · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com\n/**\n * Deterministic text measurement. An approximation of a typical UI sans-serif, good to within a few pixels. It is\n * the same on the server, in tests and in the browser, which keeps layouts and screenshots stable.\n */\n\nconst NARROW = new Set(\"iljtfrI.,:;'|!()[]{} \".split(\"\"));\nconst WIDE = new Set(\"mwMW@%&\".split(\"\"));\n\nexport function textWidth(text: string, fontSize = 12): number {\n  let w = 0;\n  for (const ch of text) {\n    if (NARROW.has(ch)) w += 0.3;\n    else if (WIDE.has(ch)) w += 0.86;\n    else if (ch >= \"0\" && ch <= \"9\") w += 0.57;\n    else if (ch >= \"A\" && ch <= \"Z\") w += 0.66;\n    else if (ch.charCodeAt(0) > 0x2e80) w += 1; // CJK and similar full-width glyphs\n    else w += 0.53;\n  }\n  return w * fontSize;\n}\n\n/** Shorten text with an ellipsis to fit maxWidth. */\nexport function truncate(text: string, maxWidth: number, fontSize = 12): string {\n  if (textWidth(text, fontSize) <= maxWidth) return text;\n  const chars = [...text];\n  let lo = 0;\n  let hi = chars.length;\n  while (lo < hi) {\n    const mid = Math.ceil((lo + hi) / 2);\n    if (textWidth(chars.slice(0, mid).join(\"\") + \"…\", fontSize) <= maxWidth) lo = mid;\n    else hi = mid - 1;\n  }\n  return lo <= 0 ? \"…\" : chars.slice(0, lo).join(\"\").trimEnd() + \"…\";\n}\n\n/**\n * Choose which labels to show along an axis so none overlap. Keeps the first and last label where possible\n * and an even stride in between.\n */\nexport function thinLabels(positions: number[], labels: string[], fontSize = 11, gap = 10): boolean[] {\n  const n = positions.length;\n  if (n === 0) return [];\n  const widths = labels.map((l) => textWidth(l, fontSize));\n  for (let stride = 1; stride <= n; stride++) {\n    const keep = positions.map((_, i) => i % stride === 0);\n    if (stride > 1 && (n - 1) % stride !== 0) {\n      // try to keep the last label if it does not collide with the previous kept one\n      let lastKept = n - 1 - ((n - 1) % stride);\n      const fits =\n        positions[n - 1] - widths[n - 1] / 2 - (positions[lastKept] + widths[lastKept] / 2) >= gap;\n      if (fits) keep[n - 1] = true;\n      else if (lastKept > 0) {\n        keep[lastKept] = false;\n        keep[n - 1] = true;\n        lastKept = n - 1;\n      }\n    }\n    let ok = true;\n    let prev = -1;\n    for (let i = 0; i < n && ok; i++) {\n      if (!keep[i]) continue;\n      if (prev >= 0 && positions[i] - widths[i] / 2 - (positions[prev] + widths[prev] / 2) < gap) ok = false;\n      prev = i;\n    }\n    if (ok) return keep;\n  }\n  return positions.map((_, i) => i === 0);\n}\n"
    },
    {
      "path": "registry/charts/core/words.tsx",
      "type": "registry:lib",
      "target": "components/charts/core/words.tsx",
      "content": "// core/words.tsx · ChartslibraryUI 1.1.0 · MIT License · https://chartslibraryui.com\n\"use client\";\n\nimport { createContext, useContext, useMemo, type ReactNode } from \"react\";\nimport type { Row } from \"./data\";\n\n/**\n * Words the charts draw themselves (table headers, tooltips, legends, the toolbar). Translate them once for the\n * whole app with <ChartWordsProvider words={…}>, or per chart with the `words` prop. Anything you leave out\n * stays in English. Your own titles, series names and column names are never touched.\n */\nexport interface ChartWords {\n  // toolbar & legend\n  table: string;\n  chart: string;\n  csv: string;\n  downloadCsv: string;\n  legend: string;\n  /** Legend button tooltip, before the series name. */\n  show: string;\n  hide: string;\n  /** Prefix of data notes under the chart. */\n  note: string;\n  check: string;\n  /** Before the data source in the footer. */\n  source: string;\n  // values\n  value: string;\n  total: string;\n  subtotal: string;\n  change: string;\n  share: string;\n  count: string;\n  median: string;\n  mean: string;\n  range: string;\n  low: string;\n  high: string;\n  min: string;\n  max: string;\n  rank: string;\n  /** \"3 of 12\" in ranked charts. */\n  of: string;\n  other: string;\n  noData: string;\n  // business words\n  actual: string;\n  forecast: string;\n  partial: string;\n  plan: string;\n  target: string;\n  increase: string;\n  decrease: string;\n  // time & finance\n  start: string;\n  end: string;\n  progress: string;\n  today: string;\n  open: string;\n  close: string;\n  volume: string;\n}\n\nexport const DEFAULT_WORDS: ChartWords = {\n  table: \"Table\",\n  chart: \"Chart\",\n  csv: \"CSV\",\n  downloadCsv: \"Download data as CSV\",\n  legend: \"Legend\",\n  show: \"Show\",\n  hide: \"Hide\",\n  note: \"Note\",\n  check: \"Check\",\n  source: \"Source\",\n  value: \"Value\",\n  total: \"Total\",\n  subtotal: \"Subtotal\",\n  change: \"Change\",\n  share: \"Share\",\n  count: \"Count\",\n  median: \"Median\",\n  mean: \"Mean\",\n  range: \"Range\",\n  low: \"Low\",\n  high: \"High\",\n  min: \"Min\",\n  max: \"Max\",\n  rank: \"Rank\",\n  of: \"of\",\n  other: \"Other\",\n  noData: \"No data\",\n  actual: \"Actual\",\n  forecast: \"Forecast\",\n  partial: \"Partial\",\n  plan: \"Plan\",\n  target: \"Target\",\n  increase: \"Increase\",\n  decrease: \"Decrease\",\n  start: \"Start\",\n  end: \"End\",\n  progress: \"Progress\",\n  today: \"Today\",\n  open: \"Open\",\n  close: \"Close\",\n  volume: \"Volume\",\n};\n\n/** What a click (or Enter) on a mark reports. `row` is the data row behind the mark when the chart has one. */\nexport interface ChartSelectEvent {\n  /** Position of the mark in the chart's own order (bar, point, cell, slice…). */\n  index: number;\n  /** The mark's label as shown in the tooltip, when there is one. */\n  label?: string;\n  row?: Row;\n}\n\ninterface ChartContextValue {\n  labels: ChartWords;\n  onSelect?: (e: ChartSelectEvent) => void;\n}\n\nconst Ctx = createContext<ChartContextValue>({ labels: DEFAULT_WORDS });\n\n/** Translate the charts' own words for everything inside. Nest it, or use a chart's `words` prop, to override. */\nexport function ChartWordsProvider({ words, children }: { words: Partial<ChartWords>; children: ReactNode }) {\n  const parent = useContext(Ctx);\n  const value = useMemo(() => ({ ...parent, labels: { ...parent.labels, ...words } }), [parent, words]);\n  return <Ctx.Provider value={value}>{children}</Ctx.Provider>;\n}\n\n/** Used by ChartFrame: one chart's `words` and `onSelect`, on top of any app-wide provider. */\nexport function ChartScope({ labels, onSelect, children }: { labels?: Partial<ChartWords>; onSelect?: (e: ChartSelectEvent) => void; children: ReactNode }) {\n  const parent = useContext(Ctx);\n  const value = useMemo(\n    () => ({ labels: labels ? { ...parent.labels, ...labels } : parent.labels, onSelect: onSelect ?? parent.onSelect }),\n    [parent, labels, onSelect],\n  );\n  return <Ctx.Provider value={value}>{children}</Ctx.Provider>;\n}\n\n/** The labels in effect. Pass a chart's own `words` prop when calling it outside ChartFrame's children. */\nexport function useWords(override?: Partial<ChartWords>): ChartWords {\n  const { labels } = useContext(Ctx);\n  return useMemo(() => (override ? { ...labels, ...override } : labels), [labels, override]);\n}\n\n/** The chart's select handler, if any. */\nexport function useSelectHandler(): ((e: ChartSelectEvent) => void) | undefined {\n  return useContext(Ctx).onSelect;\n}\n"
    }
  ],
  "meta": {
    "version": "1.1.0",
    "tier": "free",
    "importCss": "components/charts/core/charts.css"
  }
}