{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "distribution",
  "title": "Distribution",
  "description": "Primitives for distributions: quantiles from raw values or from binned counts, binning, a five-number summary, the share above a limit, round ticks, a histogram with labelled percentile and threshold lines and a line for an earlier period, box plots and legend keys.",
  "dependencies": [
    "recharts"
  ],
  "registryDependencies": [
    "https://www.dashboardblocks.com/r/radix/chart.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/distribution.tsx",
      "content": "'use client'\n\nimport { useBlockState } from '@/registry/components/dashboardblocks/block-state'\nimport {\n  ChartPlaceholder,\n  chartActiveDot,\n  chartAxisProps,\n  chartBarCursor,\n  chartGridProps,\n  chartReferenceProps,\n  ChartTooltipFrame,\n  ChartTooltipItem,\n  chartValueAxisWidth,\n} from '@/registry/components/dashboardblocks/chart'\nimport { formatNumber, formatPercent } from '@/registry/lib/dashboardblocks/format'\nimport { type CSSProperties, useState } from 'react'\nimport {\n  Bar,\n  BarChart,\n  CartesianGrid,\n  Cell,\n  ComposedChart,\n  Line,\n  ReferenceLine,\n  ResponsiveContainer,\n  Tooltip,\n  XAxis,\n  YAxis,\n  type YAxisTickContentProps,\n} from 'recharts'\n\nimport { cn } from '@/lib/utils'\n\ninterface DistributionBin {\n  /** Lower edge, inclusive. */\n  x0: number\n  /** Upper edge, exclusive. */\n  x1: number\n  count: number\n}\n\ninterface DistributionSummary {\n  count: number\n  max: number\n  mean: number\n  median: number\n  min: number\n  q1: number\n  q3: number\n}\n\n/** The `p` (0–1) quantile of sorted values, interpolating between neighbours. */\nfunction quantile(sorted: number[], p: number) {\n  if (sorted.length === 0) return 0\n  const index = (sorted.length - 1) * Math.min(1, Math.max(0, p))\n  const lower = Math.floor(index)\n  const upper = Math.ceil(index)\n  return sorted[lower] + (sorted[upper] - sorted[lower]) * (index - lower)\n}\n\nfunction summarize(values: number[]): DistributionSummary {\n  const sorted = [...values].sort((a, b) => a - b)\n  const count = sorted.length\n  return {\n    count,\n    max: sorted[count - 1] ?? 0,\n    mean: count > 0 ? sorted.reduce((sum, value) => sum + value, 0) / count : 0,\n    median: quantile(sorted, 0.5),\n    min: sorted[0] ?? 0,\n    q1: quantile(sorted, 0.25),\n    q3: quantile(sorted, 0.75),\n  }\n}\n\nfunction binValues(values: number[], edges: number[]): DistributionBin[] {\n  const bins = edges\n    .slice(0, -1)\n    .map((x0, index) => ({ count: 0, x0, x1: edges[index + 1] }))\n  if (bins.length === 0) return bins\n  for (const value of values) {\n    let index = bins.findIndex((bin) => value < bin.x1)\n    if (index === -1) index = bins.length - 1\n    bins[index].count++\n  }\n  return bins\n}\n\n/** The `p` (0–1) quantile from binned counts, such as histogram buckets from a metrics backend, assuming values are spread evenly within each bin. */\nfunction quantileFromBins(bins: DistributionBin[], p: number) {\n  const total = bins.reduce((sum, bin) => sum + bin.count, 0)\n  if (total === 0) return bins[0]?.x0 ?? 0\n  const target = Math.min(1, Math.max(0, p)) * total\n  let before = 0\n  for (const bin of bins) {\n    if (bin.count > 0 && before + bin.count >= target) {\n      return bin.x0 + ((target - before) / bin.count) * (bin.x1 - bin.x0)\n    }\n    before += bin.count\n  }\n  return bins[bins.length - 1].x1\n}\n\nfunction meanFromBins(bins: DistributionBin[]) {\n  const total = bins.reduce((sum, bin) => sum + bin.count, 0)\n  if (total === 0) return 0\n  return bins.reduce((sum, bin) => sum + ((bin.x0 + bin.x1) / 2) * bin.count, 0) / total\n}\n\n/** The share (0–1) of binned counts at or above `limit`, interpolating within its bin. */\nfunction getShareAbove(bins: DistributionBin[], limit: number) {\n  const total = bins.reduce((sum, bin) => sum + bin.count, 0)\n  if (total === 0) return 0\n  let above = 0\n  for (const bin of bins) {\n    if (bin.x0 >= limit) above += bin.count\n    else if (bin.x1 > limit) above += (bin.count * (bin.x1 - limit)) / (bin.x1 - bin.x0)\n  }\n  return above / total\n}\n\nfunction getNiceTicks(min: number, max: number, count = 5) {\n  const span = max - min || Math.abs(max) || 1\n  const rough = span / Math.max(1, count - 1)\n  const power = 10 ** Math.floor(Math.log10(rough))\n  const step = [1, 2, 5, 10].map((m) => m * power).find((s) => s >= rough) ?? power * 10\n  const start = Math.floor(min / step) * step\n  const end = Math.ceil(max / step) * step\n  const ticks: number[] = []\n  for (let tick = start; tick <= end + step / 2; tick += step) {\n    ticks.push(Math.round(tick / power) * power)\n  }\n  return ticks\n}\n\n/** Where `value` falls across bins drawn at equal widths, 0–1. */\nfunction getBinPosition(bins: DistributionBin[], value: number) {\n  if (bins.length === 0) return 0\n  let index = bins.findIndex((bin) => value < bin.x1)\n  if (index === -1) index = bins.length - 1\n  const bin = bins[index]\n  const within = bin.x1 > bin.x0 ? (value - bin.x0) / (bin.x1 - bin.x0) : 0\n  return Math.min(\n    1,\n    Math.max(0, (index + Math.min(1, Math.max(0, within))) / bins.length),\n  )\n}\n\n/** A share (0–1) as a whole percent, with one decimal below 1%. */\nfunction formatDistributionShare(share: number) {\n  return formatPercent(share, {\n    maximumFractionDigits: share > 0 && share < 0.01 ? 1 : 0,\n  })\n}\n\ninterface HistogramMarker {\n  label: string\n  value: number\n}\n\ninterface HistogramProps {\n  bins: DistributionBin[]\n  className?: string\n  /** @default 'var(--color-chart-2)' */\n  color?: string\n  /** Earlier counts in the same bins, drawn as a dashed line of shares. */\n  compare?: number[]\n  /** @default 'Before' */\n  compareLabel?: string\n  formatEdge?: (value: number) => string\n  /** Names the bars in the tooltip, such as `This week`. @default 'Share' */\n  label?: string\n  markers?: HistogramMarker[]\n  /** Shows every nth bin edge on the axis. */\n  tickEvery?: number\n  threshold?: HistogramMarker\n  /** @default DISTRIBUTION_THRESHOLD_COLOR */\n  thresholdColor?: string\n  /** Counts the bars in the tooltip, such as `requests`. Leave out to show shares only. */\n  unit?: string\n  /** Names the chart for screen readers; leave it out to hide it, such as beside a table of the same data. */\n  'aria-label'?: string\n}\n\nconst LABEL_ROW_PX = 16\n\nfunction estimateLabelWidth(text: string) {\n  return text.length * 6.5 + 8\n}\n\nconst DISTRIBUTION_THRESHOLD_COLOR =\n  'color-mix(in oklab, var(--color-destructive) 70%, var(--color-background))'\n\nfunction chartLabelProps(ariaLabel: string | undefined) {\n  return ariaLabel\n    ? ({ 'aria-label': ariaLabel, role: 'img' } as const)\n    : ({ 'aria-hidden': true } as const)\n}\n\nfunction Histogram({\n  'aria-label': ariaLabel,\n  bins,\n  className,\n  color = 'var(--color-chart-2)',\n  compare,\n  compareLabel = 'Before',\n  formatEdge = (value) => formatNumber(value),\n  label = 'Share',\n  markers = [],\n  threshold,\n  thresholdColor = DISTRIBUTION_THRESHOLD_COLOR,\n  tickEvery = 1,\n  unit,\n}: HistogramProps) {\n  const [width, setWidth] = useState(0)\n  const state = useBlockState()\n  const total = bins.reduce((sum, bin) => sum + bin.count, 0) || 1\n  const compareTotal = compare?.reduce((sum, count) => sum + count, 0) || 1\n  const data = bins.map((bin, index) => ({\n    ...bin,\n    compareShare: compare ? (compare[index] ?? 0) / compareTotal : undefined,\n    over: threshold !== undefined && bin.x0 >= threshold.value,\n    position: index + 0.5,\n    share: bin.count / total,\n  }))\n\n  const shareTicks = getNiceTicks(\n    0,\n    Math.max(...data.map((bin) => Math.max(bin.share, bin.compareShare ?? 0)), 0.01),\n    4,\n  )\n\n  const lines = [\n    ...markers.map((marker) => ({ ...marker, kind: 'marker' as const })),\n    ...(threshold ? [{ ...threshold, kind: 'threshold' as const }] : []),\n  ]\n    .map((line) => ({ ...line, position: getBinPosition(bins, line.value) }))\n    .sort((a, b) => a.position - b.position)\n  const rowEnds: number[] = []\n  const rows = lines.map((line) => {\n    const half = estimateLabelWidth(line.label) / 2\n    const center = line.position * width\n    let row = rowEnds.findIndex((end) => end + 4 <= center - half)\n    if (row === -1) row = rowEnds.push(0) - 1\n    rowEnds[row] = center + half\n    return row\n  })\n  const widestTick = Math.max(\n    0,\n    ...bins.map((bin) => estimateLabelWidth(formatEdge(bin.x0))),\n  )\n  const tickStep = Math.max(\n    tickEvery,\n    Math.ceil((widestTick + 8) / Math.max(1, width / Math.max(1, bins.length))),\n  )\n  const ticks = bins\n    .map((_, index) => index)\n    .filter((index) => index % tickStep === 0 && bins.length - index >= tickStep)\n    .concat(bins.length)\n  const edgeAt = (index: number) =>\n    index >= bins.length ? (bins[bins.length - 1]?.x1 ?? 0) : (bins[index]?.x0 ?? 0)\n\n  if (state) {\n    return (\n      <div className={cn('w-full', className)}>\n        <ChartPlaceholder height='100%' />\n      </div>\n    )\n  }\n\n  return (\n    <div {...chartLabelProps(ariaLabel)} className={cn('w-full', className)}>\n      <ResponsiveContainer\n        height='100%'\n        onResize={(nextWidth) => setWidth(nextWidth)}\n        width='100%'\n      >\n        <ComposedChart\n          accessibilityLayer={false}\n          barCategoryGap={2}\n          data={data}\n          margin={{\n            bottom: 0,\n            left: 0,\n            right: 16,\n            top: rowEnds.length * LABEL_ROW_PX + 4,\n          }}\n        >\n          <CartesianGrid {...chartGridProps} />\n          <XAxis dataKey='position' height={0} hide />\n          <XAxis\n            {...chartAxisProps}\n            dataKey='position'\n            domain={[0, bins.length]}\n            interval={0}\n            tickFormatter={(index: number) => formatEdge(edgeAt(index))}\n            ticks={ticks}\n            type='number'\n            xAxisId='edges'\n          />\n          <YAxis\n            {...chartAxisProps}\n            domain={[0, shareTicks[shareTicks.length - 1]]}\n            tickFormatter={formatDistributionShare}\n            ticks={shareTicks}\n            width={chartValueAxisWidth}\n          />\n          <Tooltip\n            content={({ active, payload }) => {\n              const bin = payload?.[0]?.payload as (typeof data)[number] | undefined\n              if (!active || !bin) return null\n              return (\n                <ChartTooltipFrame>\n                  <span className='font-medium tabular-nums'>\n                    {formatEdge(bin.x0)}–{formatEdge(bin.x1)}\n                  </span>\n                  <ChartTooltipItem\n                    color={bin.over ? thresholdColor : color}\n                    name={label}\n                    value={formatDistributionShare(bin.share)}\n                  />\n                  {bin.compareShare !== undefined && (\n                    <ChartTooltipItem\n                      color='var(--color-muted-foreground)'\n                      name={compareLabel}\n                      value={formatDistributionShare(bin.compareShare)}\n                    />\n                  )}\n                  {unit && (\n                    <ChartTooltipItem\n                      name={unit.charAt(0).toUpperCase() + unit.slice(1)}\n                      value={formatNumber(bin.count)}\n                    />\n                  )}\n                </ChartTooltipFrame>\n              )\n            }}\n            cursor={chartBarCursor}\n          />\n          <Bar dataKey='share' name={label} radius={[4, 4, 0, 0]}>\n            {data.map((bin, index) => (\n              <Cell key={index} fill={bin.over ? thresholdColor : color} />\n            ))}\n          </Bar>\n          {compare && (\n            <Line\n              activeDot={chartActiveDot}\n              dataKey='compareShare'\n              dot={false}\n              name={compareLabel}\n              stroke='var(--color-muted-foreground)'\n              strokeDasharray='3 3'\n              strokeWidth={1.5}\n              type='monotone'\n            />\n          )}\n          {lines.map((line, index) => (\n            <ReferenceLine\n              key={`${line.kind}-${line.label}`}\n              {...(line.kind === 'marker'\n                ? { stroke: 'var(--color-foreground)', strokeWidth: 1.5 }\n                : chartReferenceProps)}\n              ifOverflow='visible'\n              label={({ viewBox }: { viewBox?: { x?: number; y?: number } }) => (\n                <text\n                  x={viewBox?.x ?? 0}\n                  y={(viewBox?.y ?? 0) - 6 - rows[index] * LABEL_ROW_PX}\n                  textAnchor='middle'\n                  fontSize={11}\n                  fontWeight={500}\n                  fill={\n                    line.kind === 'marker'\n                      ? 'var(--color-foreground)'\n                      : 'var(--color-muted-foreground)'\n                  }\n                >\n                  {line.label}\n                </text>\n              )}\n              x={line.position * bins.length}\n              xAxisId='edges'\n            />\n          ))}\n        </ComposedChart>\n      </ResponsiveContainer>\n    </div>\n  )\n}\n\ninterface BoxPlotRow {\n  count?: number\n  high: number\n  label: string\n  low: number\n  mean?: number\n  median: number\n  q1: number\n  q3: number\n}\n\ninterface BoxPlotProps {\n  className?: string\n  /** @default 'var(--color-chart-2)' */\n  color?: string\n  domain: [number, number]\n  format?: (value: number) => string\n  /** Shows each row's label on the left. @default true when there is more than one row */\n  labels?: boolean\n  /** Shows each row's median on the right. @default true when there is more than one row */\n  medians?: boolean\n  /** How many rows to sketch while loading, when `rows` is empty. @default 4 */\n  placeholderRows?: number\n  /** @default 44 */\n  rowHeight?: number\n  rows: BoxPlotRow[]\n  tickFormat?: (value: number) => string\n  ticks?: number[]\n  /** Counts each row in the tooltip, such as `tickets`. */\n  unit?: string\n  /** @default '5th–95th percentile' */\n  whiskerLabel?: string\n  /** Names the chart for screen readers; leave it out to hide it, such as beside a table of the same data. */\n  'aria-label'?: string\n}\n\nconst BOX_AXIS_PX = 24\nconst LABEL_AXIS_PX = 100\nconst BOX_MAX_PX = 24\n\ninterface BoxShapeProps {\n  color: string\n  height?: number\n  payload?: BoxPlotRow\n  width?: number\n  x?: number\n  y?: number\n}\n\nfunction BoxShape({\n  color,\n  height = 0,\n  payload,\n  width = 0,\n  x = 0,\n  y = 0,\n}: BoxShapeProps) {\n  if (!payload) return null\n  const at = (value: number) =>\n    payload.high > payload.low\n      ? x + ((value - payload.low) / (payload.high - payload.low)) * width\n      : x\n  const middle = y + height / 2\n  const box = Math.min(BOX_MAX_PX, height * 0.55)\n  return (\n    <g>\n      <line\n        x1={x}\n        x2={x + width}\n        y1={middle}\n        y2={middle}\n        stroke='var(--color-muted-foreground)'\n      />\n      <line\n        x1={x}\n        x2={x}\n        y1={middle - box / 3}\n        y2={middle + box / 3}\n        stroke='var(--color-muted-foreground)'\n      />\n      <line\n        x1={x + width}\n        x2={x + width}\n        y1={middle - box / 3}\n        y2={middle + box / 3}\n        stroke='var(--color-muted-foreground)'\n      />\n      <rect\n        x={at(payload.q1)}\n        y={middle - box / 2}\n        width={Math.max(1, at(payload.q3) - at(payload.q1))}\n        height={box}\n        rx={3}\n        fill={`color-mix(in oklab, ${color} 30%, var(--color-background))`}\n        stroke={color}\n      />\n      <line\n        x1={at(payload.median)}\n        x2={at(payload.median)}\n        y1={middle - box / 2 - 2}\n        y2={middle + box / 2 + 2}\n        stroke='var(--color-foreground)'\n        strokeLinecap='round'\n        strokeWidth={2}\n      />\n      {payload.mean !== undefined && (\n        <circle\n          cx={at(payload.mean)}\n          cy={middle}\n          r={4}\n          fill='var(--color-background)'\n          stroke='var(--color-foreground)'\n          strokeWidth={1.5}\n        />\n      )}\n    </g>\n  )\n}\n\nfunction BoxPlot({\n  'aria-label': ariaLabel,\n  className,\n  color = 'var(--color-chart-2)',\n  domain,\n  format = (value) => formatNumber(value),\n  labels,\n  medians,\n  placeholderRows = 4,\n  rowHeight = 44,\n  rows,\n  tickFormat = format,\n  ticks,\n  unit,\n  whiskerLabel = '5th–95th percentile',\n}: BoxPlotProps) {\n  const state = useBlockState()\n  const several = rows.length > 1\n  const showLabels = labels ?? several\n  const showMedians = medians ?? several\n  const data = rows.map((row) => ({ ...row, range: [row.low, row.high] }))\n\n  if (state) {\n    return (\n      <ChartPlaceholder\n        className={className}\n        height={(rows.length || placeholderRows) * rowHeight + BOX_AXIS_PX}\n      />\n    )\n  }\n\n  return (\n    <div\n      {...chartLabelProps(ariaLabel)}\n      className={cn('w-full', className)}\n      style={{ height: rows.length * rowHeight + BOX_AXIS_PX }}\n    >\n      <ResponsiveContainer height='100%' width='100%'>\n        <BarChart\n          accessibilityLayer={false}\n          barCategoryGap={0}\n          data={data}\n          layout='vertical'\n          margin={{ bottom: 0, left: 0, right: showMedians ? 0 : 20, top: 0 }}\n        >\n          <XAxis\n            {...chartAxisProps}\n            allowDataOverflow\n            domain={domain}\n            height={BOX_AXIS_PX}\n            interval={0}\n            tickFormatter={tickFormat}\n            ticks={ticks}\n            type='number'\n          />\n          <YAxis\n            axisLine={false}\n            dataKey='label'\n            hide={!showLabels}\n            tick={{\n              dx: -LABEL_AXIS_PX + 8,\n              fill: 'var(--color-foreground)',\n              fontSize: 14,\n              textAnchor: 'start',\n            }}\n            tickLine={false}\n            type='category'\n            width={showLabels ? LABEL_AXIS_PX : 0}\n          />\n          {showMedians && (\n            <YAxis\n              axisLine={false}\n              dataKey='label'\n              orientation='right'\n              tick={({ payload, x, y }: YAxisTickContentProps) => {\n                const row = rows.find((item) => item.label === payload?.value)\n                return row ? (\n                  <text\n                    x={Number(x) + 8}\n                    y={Number(y)}\n                    dominantBaseline='middle'\n                    fill='var(--color-foreground)'\n                    fontSize={14}\n                  >\n                    {format(row.median)}\n                  </text>\n                ) : (\n                  <g />\n                )\n              }}\n              tickLine={false}\n              type='category'\n              width={64}\n              yAxisId='medians'\n            />\n          )}\n          <Tooltip\n            content={({ active, payload }) => {\n              const row = payload?.[0]?.payload as BoxPlotRow | undefined\n              if (!active || !row) return null\n              return (\n                <ChartTooltipFrame>\n                  <span className='font-medium'>{row.label}</span>\n                  <ChartTooltipItem name='Median' value={format(row.median)} />\n                  {row.mean !== undefined && (\n                    <ChartTooltipItem name='Mean' value={format(row.mean)} />\n                  )}\n                  <ChartTooltipItem\n                    name='Middle half'\n                    value={`${format(row.q1)}–${format(row.q3)}`}\n                  />\n                  <ChartTooltipItem\n                    name={whiskerLabel}\n                    value={`${format(row.low)}–${format(row.high)}`}\n                  />\n                  {unit && row.count !== undefined && (\n                    <ChartTooltipItem\n                      name={unit.charAt(0).toUpperCase() + unit.slice(1)}\n                      value={formatNumber(row.count)}\n                    />\n                  )}\n                </ChartTooltipFrame>\n              )\n            }}\n            cursor={chartBarCursor}\n          />\n          <Bar\n            dataKey='range'\n            shape={(shape: Omit<BoxShapeProps, 'color'>) => (\n              <BoxShape {...shape} color={color} />\n            )}\n          />\n        </BarChart>\n      </ResponsiveContainer>\n    </div>\n  )\n}\n\ntype DistributionKeyShape =\n  | 'bar'\n  | 'box'\n  | 'line'\n  | 'mean'\n  | 'median'\n  | 'threshold'\n  | 'whisker'\n\ninterface DistributionKeyProps {\n  className?: string\n  /** @default 'var(--color-chart-2)' */\n  color?: string\n  shape: DistributionKeyShape\n}\n\nfunction DistributionKey({\n  className,\n  color = 'var(--color-chart-2)',\n  shape,\n}: DistributionKeyProps) {\n  const base = cn('inline-block shrink-0', className)\n  switch (shape) {\n    case 'bar':\n      return (\n        <span\n          aria-hidden\n          className={cn(base, 'size-2.5 rounded-[3px]')}\n          style={{ backgroundColor: color }}\n        />\n      )\n    case 'box':\n      return (\n        <span\n          aria-hidden\n          className={cn(\n            base,\n            'h-2.5 w-3.5 rounded-[3px] border border-[var(--box-color)]',\n          )}\n          style={\n            {\n              '--box-color': color,\n              backgroundColor: `color-mix(in oklab, ${color} 30%, var(--color-background))`,\n            } as CSSProperties\n          }\n        />\n      )\n    case 'line':\n      return (\n        <span\n          aria-hidden\n          className={cn(base, 'h-0.5 w-3 rounded-full')}\n          style={{ backgroundColor: color }}\n        />\n      )\n    case 'mean':\n      return (\n        <span\n          aria-hidden\n          className={cn(base, 'border-foreground size-2 rounded-full border-[1.5px]')}\n        />\n      )\n    case 'median':\n      return (\n        <span aria-hidden className={cn(base, 'bg-foreground h-3 w-0.5 rounded-full')} />\n      )\n    case 'threshold':\n      return (\n        <span\n          aria-hidden\n          className={cn(\n            base,\n            'border-muted-foreground h-3 w-0 border-l-[1.5px] border-dashed',\n          )}\n        />\n      )\n    case 'whisker':\n      return (\n        <span aria-hidden className={cn(base, 'relative h-2.5 w-3.5')}>\n          <span className='bg-muted-foreground absolute inset-x-0 top-1/2 h-px' />\n          <span className='bg-muted-foreground absolute inset-y-0 left-0 w-px' />\n          <span className='bg-muted-foreground absolute inset-y-0 right-0 w-px' />\n        </span>\n      )\n  }\n}\n\nexport {\n  BoxPlot,\n  DISTRIBUTION_THRESHOLD_COLOR,\n  DistributionKey,\n  Histogram,\n  binValues,\n  formatDistributionShare,\n  getBinPosition,\n  getNiceTicks,\n  getShareAbove,\n  meanFromBins,\n  quantile,\n  quantileFromBins,\n  summarize,\n}\n\nexport type {\n  BoxPlotProps,\n  BoxPlotRow,\n  DistributionBin,\n  DistributionKeyProps,\n  DistributionKeyShape,\n  DistributionSummary,\n  HistogramMarker,\n  HistogramProps,\n}\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/distribution.tsx"
    }
  ],
  "type": "registry:component"
}
