{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "histogram",
  "type": "registry:component",
  "title": "Histogram",
  "description": "How the values of one measure are spread: the range cut into equal bins, each bar as tall as the number of values that fall in it, with arrow-key reading of each bin.",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-array"
  ],
  "devDependencies": [
    "@types/d3-array"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/viz/histogram.tsx",
      "type": "registry:component",
      "target": "components/viz/histogram.tsx",
      "content": "\"use client\";\n/**\n * @name histogram\n * @category viz\n * @description How the values of one measure are spread: the range cut into equal bins, each bar as tall as the number of values that fall in it, with arrow-key reading of each bin.\n * @when Seeing the shape of a distribution: where most values are, how wide, whether there are two humps or a long tail. To compare the spread of several groups use box-plot; to compare totals across categories use bar-chart.\n * @example\n * <Histogram\n *   label=\"Delivery times\"\n *   data={[{ minutes: 22 }, { minutes: 31 }, { minutes: 28 }, { minutes: 45 }, { minutes: 26 }, { minutes: 33 }]}\n *   value=\"minutes\"\n *   valueLabel=\"Minutes\"\n *   bins={8}\n * />\n */\nimport { bin } from \"d3-array\";\nimport { useMemo } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport {\n  axisNumberFormatter,\n  ChartAxis,\n  ChartContainer,\n  ChartEmpty,\n  ChartGrid,\n  chartLinear,\n  chartSeries,\n  ChartSvg,\n  ChartTooltip,\n  formatNumber,\n  readNumber,\n  useChartCursor,\n  widestText,\n  type ChartBaseProps,\n} from \"@/components/viz/chart\";\n\nexport type HistogramProps<T extends object> = ChartBaseProps & {\n  /** One object per observation. */\n  data: readonly T[];\n  /** The field that holds the measured number. */\n  value: keyof T & string;\n  /** About how many bins. The edges are rounded to nice numbers, so the count can differ a little. Default 10. */\n  bins?: number;\n  /** The range to bin over. Default: the data's own. */\n  domain?: readonly [number, number];\n  /** Bars as a share of all observations instead of a count. */\n  share?: boolean;\n  /** The measure's name, under the axis and in the table. Default: the field name. */\n  valueLabel?: string;\n  /** The name of the bar heights. Default \"Count\", or \"Share\" with `share`. */\n  countLabel?: string;\n  showGrid?: boolean;\n};\n\nconst GAP = 2;\nconst ROUND = \"[rx:min(var(--radius),4px)] [ry:min(var(--radius),4px)]\";\n\nexport function Histogram<T extends object>({\n  data,\n  value,\n  bins = 10,\n  domain,\n  share = false,\n  valueLabel,\n  countLabel,\n  showGrid = true,\n  label,\n  aspect,\n  height,\n  emptyLabel,\n  locale,\n  formatValue,\n  className,\n  ...props\n}: HistogramProps<T>) {\n  const groups = useMemo(() => {\n    const values = data.flatMap((row) => {\n      const number = readNumber(row, value);\n      return number === null ? [] : [number];\n    });\n    if (values.length === 0)\n      return {\n        total: 0,\n        cells: [] as { x0: number; x1: number; count: number }[],\n      };\n    const binner = bin().thresholds(bins);\n    if (domain) binner.domain([domain[0], domain[1]]);\n    const cells = binner(values).map((cell) => ({\n      x0: cell.x0 ?? 0,\n      x1: cell.x1 ?? 0,\n      count: cell.length,\n    }));\n    return { total: values.length, cells };\n  }, [data, value, bins, domain]);\n\n  const { cells, total } = groups;\n  const cursor = useChartCursor(cells.length);\n  const number = formatValue ?? ((amount: number) => formatNumber(amount, locale));\n  const percent = (amount: number): string =>\n    formatNumber(amount, locale, {\n      style: \"percent\",\n      maximumFractionDigits: 1,\n    });\n  const height_ = (count: number): number => (share ? count / Math.max(1, total) : count);\n  const heightText = (count: number): string => (share ? percent(count / Math.max(1, total)) : formatNumber(count, locale));\n  const names = {\n    value: valueLabel ?? value,\n    count: countLabel ?? (share ? \"Share\" : \"Count\"),\n  };\n  const range = (cell: { x0: number; x1: number }): string => `${number(cell.x0)} – ${number(cell.x1)}`;\n  const table = {\n    caption: label,\n    columns: [names.value, names.count],\n    rows: cells.map((cell) => [range(cell), heightText(cell.count)]),\n  };\n  const current = cursor.active === null ? undefined : cells[cursor.active];\n\n  return (\n    <div data-slot=\"histogram\" className={cn(\"flex w-full min-w-0 flex-col gap-3\", className)} {...props}>\n      <ChartContainer aspect={aspect} height={height} table={table} announcement={cursor.keyboard && current ? `${range(current)}: ${heightText(current.count)}` : \"\"}>\n        {({ width, height: plotHeight }) => {\n          if (cells.length === 0) return <ChartEmpty>{emptyLabel}</ChartEmpty>;\n          const top = 10;\n          const bottom = 44;\n          const highest = Math.max(...cells.map((cell) => height_(cell.count)));\n          const sy = chartLinear(0, highest || 1, [plotHeight - bottom, top]);\n          const axisY = share ? percent : axisNumberFormatter(highest);\n          const left = widestText(sy.ticks.map(axisY)) + 12;\n          const first = cells[0]?.x0 ?? 0;\n          const last = cells[cells.length - 1]?.x1 ?? 1;\n          const sx = chartLinear(first, last, [left, width - 8], 70);\n          sx.scale.domain([first, last]);\n          const ticks = sx.scale.ticks(Math.max(2, Math.floor((width - left) / 70)));\n          const axisX = formatValue ?? axisNumberFormatter(Math.max(Math.abs(first), Math.abs(last)), locale);\n          const zero = sy.scale(0);\n          const shown = current\n            ? {\n                x: (sx.scale(current.x0) + sx.scale(current.x1)) / 2,\n                y: sy.scale(height_(current.count)),\n              }\n            : undefined;\n          return (\n            <>\n              <ChartSvg label={label} width={width} height={plotHeight} interactive {...cursor.svgProps}>\n                {showGrid ? <ChartGrid offsets={sy.ticks.map((tick) => sy.scale(tick))} from={left} to={width - 8} /> : null}\n                <ChartAxis\n                  side=\"left\"\n                  at={left - 8}\n                  ticks={sy.ticks.map((tick) => ({\n                    offset: sy.scale(tick),\n                    label: axisY(tick),\n                  }))}\n                />\n                <ChartAxis\n                  side=\"bottom\"\n                  at={plotHeight - bottom + 6}\n                  ticks={ticks.map((tick) => ({\n                    offset: sx.scale(tick),\n                    label: axisX(tick),\n                  }))}\n                />\n                <text aria-hidden=\"true\" x={(left + width) / 2} y={plotHeight - 4} textAnchor=\"middle\" className=\"fill-muted-foreground\">\n                  {names.value}\n                </text>\n                <g aria-hidden=\"true\">\n                  {cells.map((cell, index) => {\n                    const x0 = sx.scale(cell.x0) + GAP / 2;\n                    const w = Math.max(1, sx.scale(cell.x1) - sx.scale(cell.x0) - GAP);\n                    const y = sy.scale(height_(cell.count));\n                    const h = zero - y;\n                    return (\n                      <g key={index} className={cn(\"transition-opacity duration-instant motion-reduce:transition-none\", cursor.active !== null && cursor.active !== index && \"opacity-45\")}>\n                        {h > 0 ? (\n                          <>\n                            <rect x={x0} y={y} width={w} height={h} className={cn(chartSeries(0).fill, ROUND)} />\n                            <rect x={x0} y={y + h / 2} width={w} height={h / 2} className={chartSeries(0).fill} />\n                          </>\n                        ) : null}\n                        <rect\n                          x={sx.scale(cell.x0)}\n                          y={top}\n                          width={Math.max(1, sx.scale(cell.x1) - sx.scale(cell.x0))}\n                          height={zero - top}\n                          fill=\"transparent\"\n                          onPointerEnter={() => cursor.point(index)}\n                        />\n                      </g>\n                    );\n                  })}\n                  <line x1={left} x2={width - 8} y1={zero} y2={zero} className=\"stroke-border-strong\" shapeRendering=\"crispEdges\" />\n                </g>\n              </ChartSvg>\n              {shown && current ? (\n                <ChartTooltip\n                  x={shown.x}\n                  y={shown.y}\n                  align=\"center\"\n                  side={shown.x > width / 2 ? \"left\" : \"right\"}\n                  title={range(current)}\n                  rows={[\n                    {\n                      label: names.count,\n                      value: heightText(current.count),\n                      index: 0,\n                      mark: \"rect\",\n                    },\n                  ]}\n                />\n              ) : null}\n            </>\n          );\n        }}\n      </ChartContainer>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Seeing the shape of a distribution: where most values are, how wide, whether there are two humps or a long tail. To compare the spread of several groups use box-plot; to compare totals across categories use bar-chart.",
    "example": "<Histogram\n  label=\"Delivery times\"\n  data={[{ minutes: 22 }, { minutes: 31 }, { minutes: 28 }, { minutes: 45 }, { minutes: 26 }, { minutes: 33 }]}\n  value=\"minutes\"\n  valueLabel=\"Minutes\"\n  bins={8}\n/>",
    "client": true
  }
}
