{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "bar-chart",
  "title": "Bar chart",
  "author": "superzero11 <https://github.com/superzero11/uiset>",
  "description": "Categories compared: columns or horizontal bars, grouped or stacked, ranked, with thin marks and values at the tips.",
  "dependencies": [
    "@ui-sdk/core@0.1.0-beta.5",
    "@ui-sdk/react@0.1.0-beta.5"
  ],
  "registryDependencies": [
    "https://uiset.dev/r/uiset.json",
    "https://uiset.dev/r/chart.json"
  ],
  "files": [
    {
      "path": "registry/uiset/ui/bar-chart.tsx",
      "content": "\"use client\"\n\nimport type { ChartSelectChange } from \"./chart/points\"\nimport type { ReactNode } from \"react\"\nimport { ChartFrame, reactPlot } from \"./chart\"\nimport { barFrame, barHeight, barPlot, type BarOptions } from \"./chart/plots/bar\"\n\ntype BarChartProps<Datum> = BarOptions<Datum> & {\n  title: string\n  description?: ReactNode\n  height?: number\n  selected?: string | null\n  onSelect?: (key: string | null, details: ChartSelectChange) => void\n  actions?: ReactNode\n  className?: string\n}\n\n/** Grouped or stacked bars, rising or running sideways. The geometry is chart/plots/bar.ts. */\nfunction BarChart<Datum>({ title, description, height, selected, onSelect, actions, className, ...options }: BarChartProps<Datum>) {\n  const frame = barFrame(options)\n  return (\n    <ChartFrame\n      title={title}\n      description={description}\n      height={barHeight(options, height)}\n      orientation={frame.orientation}\n      className={[frame.className, className].filter(Boolean).join(\" \")}\n      series={frame.series}\n      table={frame.table}\n      rows={frame.rows}\n      selected={selected}\n      onSelect={onSelect}\n      actions={actions}\n      plot={(context) => reactPlot(barPlot(options, context))}\n    />\n  )\n}\n\nexport { BarChart }\nexport type { BarChartProps }\n",
      "type": "registry:ui",
      "target": "@ui/bar-chart.tsx"
    },
    {
      "path": "registry/uiset/ui/chart/plots/bar.ts",
      "content": "// The bar chart's geometry: grouped or stacked bars, rising or running sideways.\nimport { seriesColor, focusKey, type ChartFrameData, type ChartGeometry, type ChartPlotContext, type ChartPoint, type ChartSeries } from \"../plot\"\nimport { band, formatValue, linear, numberFormat, tickFormatter } from \"../scale\"\nimport { tooltipRow, v as node, type VChild } from \"../vnode\"\n\ntype BarOptions<Datum> = {\n  data: readonly Datum[]\n  /** The category a datum belongs to, like \"North\" or \"Mar\". */\n  x: (datum: Datum) => string\n  series: ChartSeries<Datum>[]\n  format?: (value: number) => string\n  /** Reads numbers in this locale; pass it when rendering on a server. */\n  locale?: string\n  /** Columns rise (vertical, the default); bars run sideways (horizontal, for long names). */\n  orientation?: \"vertical\" | \"horizontal\"\n  /** Several series side by side, or stacked to a total. */\n  layout?: \"grouped\" | \"stacked\"\n  /** Rank categories by their total. */\n  sort?: \"descending\" | \"ascending\"\n  /** Print each bar's value at its tip, where it fits. Defaults to one series and few bars. */\n  labels?: boolean\n}\n\nconst MAX_THICKNESS = 24\nconst GAP = 2\nconst RADIUS = 4\nconst charWidth = 6.6\n\n/** A bar with a 4px rounded data end and a square end at the baseline. */\nfunction barPath(\n  x: number,\n  y: number,\n  width: number,\n  height: number,\n  end: \"top\" | \"bottom\" | \"right\" | \"left\" | \"none\",\n) {\n  const r = Math.min(RADIUS, width / 2, height / 2)\n  if (end === \"none\" || r <= 0) return `M${x},${y}h${width}v${height}h${-width}Z`\n  if (end === \"top\")\n    return `M${x},${y + height}V${y + r}Q${x},${y} ${x + r},${y}H${x + width - r}Q${x + width},${y} ${x + width},${y + r}V${y + height}Z`\n  if (end === \"bottom\")\n    return `M${x},${y}V${y + height - r}Q${x},${y + height} ${x + r},${y + height}H${x + width - r}Q${x + width},${y + height} ${x + width},${y + height - r}V${y}Z`\n  if (end === \"right\")\n    return `M${x},${y}H${x + width - r}Q${x + width},${y} ${x + width},${y + r}V${y + height - r}Q${x + width},${y + height} ${x + width - r},${y + height}H${x}Z`\n  return `M${x + width},${y}H${x + r}Q${x},${y} ${x},${y + r}V${y + height - r}Q${x},${y + height} ${x + r},${y + height}H${x + width}Z`\n}\n\nfunction barParts<Datum>({ data, x, series, format, locale, sort, layout = \"grouped\" }: BarOptions<Datum>) {\n  const value = (s: ChartSeries<Datum>, d: Datum) => {\n    const n = s.value(d)\n    return n === null || n === undefined || !Number.isFinite(n) ? null : n\n  }\n  const total = (d: Datum) => series.reduce((sum, s) => sum + (value(s, d) ?? 0), 0)\n  const rows = sort ? [...data].sort((a, b) => (sort === \"descending\" ? total(b) - total(a) : total(a) - total(b))) : [...data]\n  const categories = rows.map(x)\n  // Positions are keyed by the datum's place in `data`, so `onSelect(\"2\")` always means\n  // data[2], however the bars are sorted.\n  const indexOf = new Map(data.map((d, i) => [d, i]))\n  const keyOf = (d: Datum) => String(indexOf.get(d))\n  const fmt = numberFormat(locale, format)\n  const stackedLayout = layout === \"stacked\" && series.length > 1\n  return { value, total, rows, categories, keyOf, fmt, stackedLayout }\n}\n\n/** The plot's height: given, or enough for every bar running sideways. */\nfunction barHeight<Datum>(options: BarOptions<Datum>, height?: number) {\n  return height ?? (options.orientation === \"horizontal\" ? Math.max(160, options.data.length * 36 + 40) : 240)\n}\n\nfunction barFrame<Datum>(options: BarOptions<Datum>): ChartFrameData {\n  const { series, orientation = \"vertical\" } = options\n  const { value, total, rows, categories, keyOf, fmt, stackedLayout } = barParts(options)\n  return {\n    className: \"bar-chart\",\n    orientation: orientation === \"horizontal\" ? \"vertical\" : \"horizontal\",\n    series: series.map((s) => ({ key: s.key, label: s.label, shape: \"rect\" })),\n    table: {\n      head: [\"\", ...series.map((s) => s.label), ...(stackedLayout ? [\"Total\"] : [])],\n      numeric: [false, ...series.map(() => true), ...(stackedLayout ? [true] : [])],\n      rows: rows.map((d, i) => ({\n        key: keyOf(d),\n        cells: [categories[i]!, ...series.map((s) => formatValue(value(s, d), fmt)), ...(stackedLayout ? [fmt(total(d))] : [])],\n      })),\n    },\n    rows: () =>\n      rows.map((d, i) => {\n        const row: Record<string, string> = { category: categories[i]! }\n        for (const s of series) row[s.label] = formatValue(value(s, d), fmt)\n        return row\n      }),\n  }\n}\n\nfunction barPlot<Datum>(options: BarOptions<Datum>, { width, height: h, shown, active, selected: pinned }: ChartPlotContext): ChartGeometry {\n  const { data, x, series, locale, layout = \"grouped\", labels } = options\n  const horizontal = options.orientation === \"horizontal\"\n  const { value, rows, categories, keyOf, fmt } = barParts(options)\n  const visible = series.filter((s) => shown(s.key))\n  const stacked = layout === \"stacked\" && visible.length > 1\n  const extents = rows.flatMap((d) => {\n    if (!stacked) return visible.map((s) => value(s, d) ?? 0)\n    let up = 0\n    let down = 0\n    for (const s of visible) {\n      const v = value(s, d) ?? 0\n      if (v >= 0) up += v\n      else down += v\n    }\n    return [up, down]\n  })\n  const top = horizontal ? 4 : 18\n  const bottom = horizontal ? 24 : 28\n  const categoryWidth = horizontal\n    ? Math.min(180, Math.max(0, ...categories.map((c) => c.length)) * charWidth + 12)\n    : 0\n  // Value axis first, so its labels can size the margin.\n  const provisional = linear(extents, [0, 1])\n  const tickLabel = tickFormatter(provisional.ticks, locale)\n  const shownTotal = (d: Datum) => visible.reduce((sum, s) => sum + (value(s, d) ?? 0), 0)\n  const tallest = (d: Datum) =>\n    stacked ? shownTotal(d) : Math.max(0, ...visible.map((s) => value(s, d) ?? 0))\n  const valueLabelWidth = Math.max(...provisional.ticks.map((t) => tickLabel(t).length)) * charWidth\n  const left = horizontal ? categoryWidth : valueLabelWidth + 12\n  const right = horizontal ? 48 : 8\n  const v = horizontal\n    ? linear(extents, [left, width - right])\n    : linear(extents, [h - bottom, top])\n  const c = horizontal\n    ? band(categories, [top, h - bottom], 0.35)\n    : band(categories, [left, width - right], 0.35)\n  const groupCount = stacked ? 1 : Math.max(1, visible.length)\n  const thickness = Math.max(\n    2,\n    Math.min(MAX_THICKNESS, (c.bandwidth - GAP * (groupCount - 1)) / groupCount),\n  )\n  const groupSpan = thickness * groupCount + GAP * (groupCount - 1)\n  const zero = v(0)\n  const focus = focusKey(active, pinned, (key) => rows.some((d) => keyOf(d) === key))\n  const showLabels =\n    labels ?? (visible.length === 1 && categories.length <= (horizontal ? 24 : 12))\n\n  type Label = { x: number; y: number; text: string; anchor: \"start\" | \"middle\" | \"end\" }\n  type Bar = { key: string; series: string; d: string; color: string; label?: Label }\n  const bars: Bar[] = []\n  rows.forEach((d, i) => {\n    const start = c(categories[i]!) + (c.bandwidth - groupSpan) / 2\n    let up = 0\n    let down = 0\n    const stackTop = stacked\n      ? visible.filter((s) => (value(s, d) ?? 0) > 0).at(-1)?.key\n      : undefined\n    const stackBottom = stacked\n      ? visible.filter((s) => (value(s, d) ?? 0) < 0).at(-1)?.key\n      : undefined\n    visible.forEach((s, j) => {\n      const raw = value(s, d)\n      if (raw === null || raw === 0) return\n      const offsetIndex = stacked ? 0 : j\n      const pos = start + offsetIndex * (thickness + GAP)\n      const from = stacked ? (raw >= 0 ? up : down) : 0\n      const to = from + raw\n      if (stacked) {\n        if (raw >= 0) up = to\n        else down = to\n      }\n      const a = v(from)\n      const b = v(to)\n      // The 2px surface gap between stacked segments.\n      const gap = stacked && from !== 0 ? GAP : 0\n      const isEnd = !stacked || s.key === (raw >= 0 ? stackTop : stackBottom)\n      let path: string\n      let label: Label | undefined\n      const text = formatValue(raw, fmt)\n      if (horizontal) {\n        const x0 = Math.min(a, b) + (raw >= 0 ? gap : 0)\n        const len = Math.max(0, Math.abs(b - a) - gap)\n        path = barPath(x0, pos, len, thickness, isEnd ? (raw >= 0 ? \"right\" : \"left\") : \"none\")\n        if (showLabels && !stacked)\n          label =\n            raw >= 0\n              ? { x: x0 + len + 6, y: pos + thickness / 2, text, anchor: \"start\" }\n              : { x: x0 - 6, y: pos + thickness / 2, text, anchor: \"end\" }\n      } else {\n        const y0 = Math.min(a, b)\n        const len = Math.max(0, Math.abs(b - a) - gap)\n        path = barPath(pos, raw >= 0 ? y0 : y0 + gap, thickness, len, isEnd ? (raw >= 0 ? \"top\" : \"bottom\") : \"none\")\n        const fits = text.length * charWidth <= c.step - 4\n        if (showLabels && !stacked && fits)\n          label = {\n            x: pos + thickness / 2,\n            y: raw >= 0 ? y0 - 6 : y0 + len + 14,\n            text,\n            anchor: \"middle\",\n          }\n      }\n      bars.push({\n        key: keyOf(d),\n        series: s.key,\n        d: path,\n        color: seriesColor(series, s.key),\n        label,\n      })\n    })\n  })\n\n  const points: ChartPoint[] = rows.map((d, i) => {\n    const start = c(categories[i]!) - (c.step - c.bandwidth) / 2\n    const readings = visible.map(\n      (s) => `${visible.length > 1 ? `${s.label} ` : \"\"}${formatValue(value(s, d), fmt)}`,\n    )\n    // A stack's total is in its reading and the table, not only the tooltip.\n    if (stacked) readings.push(`total ${fmt(shownTotal(d))}`)\n    const reading = `${categories[i]}: ${readings.join(\", \")}`\n    return horizontal\n      ? {\n          key: keyOf(d),\n          label: reading,\n          x: 0,\n          y: start,\n          width: width,\n          height: c.step,\n          anchor: { x: Math.max(zero, v(tallest(d))), y: start + c.step / 2 },\n        }\n      : {\n          key: keyOf(d),\n          label: reading,\n          x: start,\n          y: top,\n          width: c.step,\n          height: h - top - bottom + 22,\n          anchor: { x: start + c.step / 2, y: Math.min(zero, v(tallest(d))) },\n        }\n  })\n\n  const svg: VChild[] = [\n    node(\n      \"g\",\n      { key: \"grid\", className: \"chart-grid\" },\n      ...v.ticks.map((t) =>\n        horizontal\n          ? node(\"line\", { key: t, x1: v(t), x2: v(t), y1: top, y2: h - bottom, \"data-zero\": t === 0 ? \"\" : undefined })\n          : node(\"line\", { key: t, x1: left, x2: width - right, y1: v(t), y2: v(t), \"data-zero\": t === 0 ? \"\" : undefined }),\n      ),\n    ),\n    node(\n      \"g\",\n      { key: \"value\", className: \"chart-axis-labels\", \"data-axis\": \"value\" },\n      ...v.ticks.map((t) =>\n        horizontal\n          ? node(\"text\", { key: t, x: v(t), y: h - bottom + 16, textAnchor: \"middle\" }, tickLabel(t))\n          : node(\"text\", { key: t, x: left - 8, y: v(t), dy: \"0.32em\", textAnchor: \"end\" }, tickLabel(t)),\n      ),\n    ),\n    node(\n      \"g\",\n      { key: \"category\", className: \"chart-axis-labels\", \"data-axis\": \"category\" },\n      ...categories.map((name, i) => {\n        const center = c(name) + c.bandwidth / 2\n        const every = horizontal ? 1 : Math.max(1, Math.ceil((name.length * charWidth + 8) / c.step))\n        if (i % every !== 0) return null\n        return horizontal\n          ? node(\n              \"text\",\n              { key: i, x: left - 8, y: center, dy: \"0.32em\", textAnchor: \"end\" },\n              name.length * charWidth > categoryWidth - 12 ? `${name.slice(0, Math.floor((categoryWidth - 24) / charWidth))}…` : name,\n            )\n          : node(\"text\", { key: i, x: center, y: h - bottom + 18, textAnchor: \"middle\" }, name)\n      }),\n    ),\n    ...bars.map((bar) =>\n      node(\"path\", {\n        key: `${bar.key}-${bar.series}`,\n        className: \"chart-bar\",\n        d: bar.d,\n        \"data-dim\": focus !== null && focus !== bar.key ? \"\" : undefined,\n        style: { \"--series\": bar.color },\n      }),\n    ),\n    ...bars.map((bar) =>\n      bar.label\n        ? node(\n            \"text\",\n            {\n              key: `label-${bar.key}-${bar.series}`,\n              className: \"chart-value-label\",\n              x: bar.label.x,\n              y: bar.label.y,\n              dy: horizontal ? \"0.32em\" : undefined,\n              textAnchor: bar.label.anchor,\n            },\n            bar.label.text,\n          )\n        : null,\n    ),\n  ]\n\n  return {\n    svg,\n    points,\n    tooltip: (key) => {\n      const d = data[Number(key)]\n      if (d === undefined) return null\n      return [\n        node(\"span\", { key: \"title\", className: \"chart-tooltip-title\" }, x(d)),\n        ...visible.map((s) => tooltipRow(seriesColor(series, s.key), formatValue(value(s, d), fmt), s.label, \"rect\", s.key)),\n        stacked && node(\"span\", { key: \"total\", className: \"chart-tooltip-total\" }, node(\"strong\", {}, fmt(shownTotal(d))), \" total\"),\n      ]\n    },\n  }\n}\n\nexport { barFrame, barHeight, barPlot }\nexport type { BarOptions }\n",
      "type": "registry:file",
      "target": "@ui/chart/plots/bar.ts"
    }
  ],
  "type": "registry:ui"
}