{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "fan-chart",
  "type": "registry:component",
  "title": "Fan Chart",
  "description": "A forecast drawn honestly: what was observed as a solid line, then the median forecast with nested bands for its intervals (90 %, 50 % …) that widen as the forecast reaches further, with arrow-key reading of every point.",
  "categories": [
    "viz"
  ],
  "dependencies": [
    "d3-scale",
    "d3-shape"
  ],
  "devDependencies": [
    "@types/d3-scale",
    "@types/d3-shape"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/chart",
    "@rivier-ui/cn"
  ],
  "files": [
    {
      "path": "registry/viz/fan-chart.tsx",
      "type": "registry:component",
      "target": "components/viz/fan-chart.tsx",
      "content": "\"use client\";\n/**\n * @name fan-chart\n * @category viz\n * @description A forecast drawn honestly: what was observed as a solid line, then the median forecast with nested bands for its intervals (90 %, 50 % …) that widen as the forecast reaches further, with arrow-key reading of every point.\n * @when Showing a prediction or an estimate with its uncertainty: a forecast, a model's range, a confidence band around a trend. For a series with no uncertainty use line-chart; for the spread of measured values use box-plot.\n * @example\n * <FanChart\n *   label=\"Visitors, observed and forecast\"\n *   data={[\n *     { week: 1, observed: 120 },\n *     { week: 2, observed: 132 },\n *     { week: 3, observed: 128, median: 128, low90: 128, high90: 128, low50: 128, high50: 128 },\n *     { week: 4, median: 136, low90: 118, high90: 152, low50: 128, high50: 143 },\n *     { week: 5, median: 141, low90: 110, high90: 170, low50: 126, high50: 155 },\n *   ]}\n *   x=\"week\"\n *   observed=\"observed\"\n *   median=\"median\"\n *   intervals={[\n *     { low: \"low90\", high: \"high90\", label: \"90% interval\" },\n *     { low: \"low50\", high: \"high50\", label: \"50% interval\" },\n *   ]}\n *   forecastFrom={3}\n *   labels={{ observed: \"Observed\", median: \"Forecast (median)\", forecast: \"Forecast\" }}\n * />\n */\nimport { area, line } from \"d3-shape\";\nimport { scaleUtc } from \"d3-scale\";\nimport { useMemo, type PointerEvent } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport {\n  axisNumberFormatter,\n  ChartAxis,\n  ChartContainer,\n  ChartEmpty,\n  ChartGrid,\n  chartLinear,\n  ChartSvg,\n  ChartTooltip,\n  dateFormatter,\n  formatNumber,\n  readNumber,\n  useChartCursor,\n  widestText,\n  type ChartBaseProps,\n} from \"@/components/viz/chart\";\n\nexport type FanInterval<T> = {\n  /** The field holding the interval's lower edge. */\n  low: keyof T & string;\n  /** The field holding its upper edge. */\n  high: keyof T & string;\n  /** Its name: \"90% interval\". */\n  label: string;\n};\n\nexport type FanChartLabels = { observed: string; median: string; forecast: string };\n\nexport type FanChartProps<T extends object> = ChartBaseProps & {\n  /** One object per x position, observed and forecast rows together. */\n  data: readonly T[];\n  /** The field holding x: a number or a Date. */\n  x: keyof T & string;\n  /** The field holding what was measured, where it was. */\n  observed?: keyof T & string;\n  /** The field holding the forecast's median (or central estimate). */\n  median: keyof T & string;\n  /** The intervals from widest to narrowest. Each is drawn a step stronger than the one around it. */\n  intervals: readonly FanInterval<T>[];\n  /** The x where the forecast starts: a rule and the word \"Forecast\" mark it. */\n  forecastFrom?: number | Date;\n  /** Words for the legend, the tooltip and the table. */\n  labels?: Partial<FanChartLabels>;\n  /** The name of the x column in the table. Default: the field name. */\n  xLabel?: string;\n  /** Replaces the x format on the axis, in the tooltip and in the table. */\n  formatX?: (value: number | Date) => string;\n  /** The time zone dates are printed in. Default \"UTC\". */\n  timeZone?: string;\n  /** Start the y axis at zero. */\n  zero?: boolean;\n  showGrid?: boolean;\n  showLegend?: boolean;\n};\n\nconst LABELS: FanChartLabels = { observed: \"Observed\", median: \"Median\", forecast: \"Forecast\" };\n/** Band strengths from the outside in: each narrower band is a step stronger. */\nconst STRENGTHS = [0.16, 0.3, 0.44, 0.58];\n\ntype Row = { x: number; observed: number | null; median: number | null; bands: ({ low: number; high: number } | null)[] };\n\nexport function FanChart<T extends object>({\n  data,\n  x,\n  observed,\n  median,\n  intervals,\n  forecastFrom,\n  labels: given,\n  xLabel,\n  formatX,\n  timeZone,\n  zero = false,\n  showGrid = true,\n  showLegend = true,\n  label,\n  aspect,\n  height,\n  emptyLabel,\n  locale,\n  formatValue,\n  className,\n  ...props\n}: FanChartProps<T>) {\n  const labels = { ...LABELS, ...given };\n  const model = useMemo(() => {\n    const isTime = data.some((row) => (row as Record<string, unknown>)[x] instanceof Date);\n    const rows: Row[] = data\n      .flatMap((row) => {\n        const raw = (row as Record<string, unknown>)[x];\n        const at = raw instanceof Date ? raw.getTime() : typeof raw === \"number\" ? raw : NaN;\n        if (!Number.isFinite(at)) return [];\n        return [\n          {\n            x: at,\n            observed: observed ? readNumber(row, observed) : null,\n            median: readNumber(row, median),\n            bands: intervals.map((band) => {\n              const low = readNumber(row, band.low);\n              const high = readNumber(row, band.high);\n              return low === null || high === null ? null : { low: Math.min(low, high), high: Math.max(low, high) };\n            }),\n          },\n        ];\n      })\n      .sort((a, b) => a.x - b.x);\n    return { rows, isTime };\n  }, [data, x, observed, median, intervals]);\n\n  const { rows, isTime } = model;\n  const cursor = useChartCursor(rows.length);\n  const number = formatValue ?? ((amount: number) => formatNumber(amount, locale));\n  const span = rows.length > 1 ? (rows[rows.length - 1]?.x ?? 0) - (rows[0]?.x ?? 0) : 0;\n  const fullX = formatX ?? (isTime ? dateFormatter(span, \"full\", locale, timeZone) : (value: number | Date) => formatNumber(Number(value), locale));\n  const axisXFormat = formatX ?? (isTime ? dateFormatter(span, \"axis\", locale, timeZone) : (value: number | Date) => formatNumber(Number(value), locale));\n  const xOf = (value: number): number | Date => (isTime ? new Date(value) : value);\n  const range = (band: { low: number; high: number } | null): string => (band ? `${number(band.low)} – ${number(band.high)}` : \"\");\n  const table = {\n    caption: label,\n    columns: [xLabel ?? x, ...(observed ? [labels.observed] : []), labels.median, ...intervals.map((band) => band.label)],\n    rows: rows.map((row) => [fullX(xOf(row.x)), ...(observed ? [row.observed === null ? \"\" : number(row.observed)] : []), row.median === null ? \"\" : number(row.median), ...row.bands.map(range)]),\n  };\n  const current = cursor.active === null ? undefined : rows[cursor.active];\n  const tooltipRows = (row: Row): { label: string; value: string }[] => [\n    ...(row.observed !== null ? [{ label: labels.observed, value: number(row.observed) }] : []),\n    ...(row.median !== null ? [{ label: labels.median, value: number(row.median) }] : []),\n    ...row.bands.flatMap((band, index) => (band ? [{ label: intervals[index]?.label ?? \"\", value: range(band) }] : [])),\n  ];\n  const announcement =\n    cursor.keyboard && current\n      ? `${fullX(xOf(current.x))}: ${tooltipRows(current)\n          .map((item) => `${item.label} ${item.value}`)\n          .join(\", \")}`\n      : \"\";\n  const forecastAt = forecastFrom instanceof Date ? forecastFrom.getTime() : forecastFrom;\n\n  return (\n    <div data-slot=\"fan-chart\" className={cn(\"flex w-full min-w-0 flex-col gap-3\", className)} {...props}>\n      {showLegend ? (\n        <ul data-slot=\"fan-chart-legend\" className=\"flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground\">\n          {observed ? (\n            <li className=\"flex items-center gap-1.5\">\n              <svg aria-hidden=\"true\" width={20} height={12}>\n                <line x1={1} x2={19} y1={6} y2={6} className=\"stroke-foreground\" strokeWidth={2} strokeLinecap=\"round\" />\n              </svg>\n              {labels.observed}\n            </li>\n          ) : null}\n          <li className=\"flex items-center gap-1.5\">\n            <svg aria-hidden=\"true\" width={20} height={12}>\n              <line x1={1} x2={19} y1={6} y2={6} className=\"stroke-chart-1\" strokeWidth={2} strokeDasharray=\"5 3\" strokeLinecap=\"round\" />\n            </svg>\n            {labels.median}\n          </li>\n          {intervals.map((band, index) => (\n            <li key={band.label} className=\"flex items-center gap-1.5\">\n              <span aria-hidden=\"true\" className=\"h-3 w-5 rounded-[min(var(--radius),3px)] bg-chart-1\" style={{ opacity: STRENGTHS[Math.min(index, STRENGTHS.length - 1)] }} />\n              {band.label}\n            </li>\n          ))}\n        </ul>\n      ) : null}\n      <ChartContainer aspect={aspect} height={height} table={table} announcement={announcement}>\n        {({ width, height: plotHeight }) => {\n          if (rows.length === 0) return <ChartEmpty>{emptyLabel}</ChartEmpty>;\n          const values = rows.flatMap((row) => [row.observed, row.median, ...row.bands.flatMap((band) => (band ? [band.low, band.high] : []))].filter((v): v is number => v !== null));\n          const low = Math.min(...values, ...(zero ? [0] : []));\n          const high = Math.max(...values, ...(zero ? [0] : []));\n          const top = 18;\n          const bottom = 26;\n          const sy = chartLinear(low, high, [plotHeight - bottom, top]);\n          const axisY = formatValue ?? axisNumberFormatter(Math.max(Math.abs(low), Math.abs(high)), locale);\n          const left = widestText(sy.ticks.map(axisY)) + 12;\n          const right = 12;\n          const first = rows[0]?.x ?? 0;\n          const last = rows[rows.length - 1]?.x ?? 1;\n          const tickCount = Math.max(2, Math.floor((width - left) / 90));\n          const timeScale = scaleUtc()\n            .domain([first, last === first ? first + 1 : last])\n            .range([left, width - right]);\n          const numberScale = chartLinear(first, last, [left, width - right], 90).scale.domain([first, last === first ? first + 1 : last]);\n          const sx = (value: number): number => (isTime ? timeScale(value) : numberScale(value));\n          const xTicks = isTime ? timeScale.ticks(tickCount).map((d) => d.getTime()) : numberScale.ticks(tickCount);\n          const bandPaths = intervals.map((_, index) =>\n            area<Row>()\n              .defined((row) => row.bands[index] != null)\n              .x((row) => sx(row.x))\n              .y0((row) => sy.scale(row.bands[index]?.low ?? 0))\n              .y1((row) => sy.scale(row.bands[index]?.high ?? 0))(rows),\n          );\n          const observedPath = observed\n            ? line<Row>()\n                .defined((row) => row.observed !== null)\n                .x((row) => sx(row.x))\n                .y((row) => sy.scale(row.observed ?? 0))(rows)\n            : null;\n          const medianPath = line<Row>()\n            .defined((row) => row.median !== null)\n            .x((row) => sx(row.x))\n            .y((row) => sy.scale(row.median ?? 0))(rows);\n          const onPointerMove = (event: PointerEvent<SVGSVGElement>): void => {\n            const box = event.currentTarget.getBoundingClientRect();\n            const px = event.clientX - box.left;\n            let best = 0;\n            rows.forEach((row, index) => {\n              if (Math.abs(sx(row.x) - px) < Math.abs(sx(rows[best]?.x ?? 0) - px)) best = index;\n            });\n            cursor.point(best);\n          };\n          const shownX = current ? sx(current.x) : 0;\n          const shownY = current ? sy.scale(current.median ?? current.observed ?? 0) : 0;\n          return (\n            <>\n              <ChartSvg label={label} width={width} height={plotHeight} interactive {...cursor.svgProps} onPointerMove={onPointerMove}>\n                {showGrid ? <ChartGrid offsets={sy.ticks.map((tick) => sy.scale(tick))} from={left} to={width - right} /> : null}\n                <ChartAxis side=\"left\" at={left - 8} ticks={sy.ticks.map((tick) => ({ offset: sy.scale(tick), label: axisY(tick) }))} />\n                <ChartAxis side=\"bottom\" at={plotHeight - bottom + 6} ticks={xTicks.map((tick) => ({ offset: sx(tick), label: axisXFormat(xOf(tick)) }))} />\n                <g aria-hidden=\"true\">\n                  {bandPaths.map((d, index) => (d ? <path key={index} d={d} className=\"fill-chart-1\" fillOpacity={STRENGTHS[Math.min(index, STRENGTHS.length - 1)]} /> : null))}\n                  {forecastAt !== undefined && forecastAt >= first && forecastAt <= last ? (\n                    <g>\n                      <line x1={sx(forecastAt)} x2={sx(forecastAt)} y1={top - 6} y2={plotHeight - bottom} className=\"stroke-border-strong\" strokeDasharray=\"2 3\" />\n                      <text x={sx(forecastAt) + 4} y={top - 6} dy=\"0.32em\" className=\"fill-muted-foreground\">\n                        {labels.forecast}\n                      </text>\n                    </g>\n                  ) : null}\n                  {medianPath ? <path d={medianPath} fill=\"none\" className=\"stroke-chart-1\" strokeWidth={2} strokeDasharray=\"5 3\" strokeLinejoin=\"round\" strokeLinecap=\"round\" /> : null}\n                  {observedPath ? <path d={observedPath} fill=\"none\" className=\"stroke-foreground\" strokeWidth={2} strokeLinejoin=\"round\" strokeLinecap=\"round\" /> : null}\n                  {current ? (\n                    <g>\n                      <line x1={shownX} x2={shownX} y1={top} y2={plotHeight - bottom} className=\"stroke-border-strong\" />\n                      <circle cx={shownX} cy={shownY} r={4.5} className={cn(current.median === null ? \"fill-foreground\" : \"fill-chart-1\", \"stroke-background\")} strokeWidth={2} />\n                    </g>\n                  ) : null}\n                </g>\n              </ChartSvg>\n              {current ? <ChartTooltip x={shownX} y={shownY} side={shownX > width / 2 ? \"left\" : \"right\"} title={fullX(xOf(current.x))} rows={tooltipRows(current)} /> : null}\n            </>\n          );\n        }}\n      </ChartContainer>\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "viz",
    "when": "Showing a prediction or an estimate with its uncertainty: a forecast, a model's range, a confidence band around a trend. For a series with no uncertainty use line-chart; for the spread of measured values use box-plot.",
    "example": "<FanChart\n  label=\"Visitors, observed and forecast\"\n  data={[\n    { week: 1, observed: 120 },\n    { week: 2, observed: 132 },\n    { week: 3, observed: 128, median: 128, low90: 128, high90: 128, low50: 128, high50: 128 },\n    { week: 4, median: 136, low90: 118, high90: 152, low50: 128, high50: 143 },\n    { week: 5, median: 141, low90: 110, high90: 170, low50: 126, high50: 155 },\n  ]}\n  x=\"week\"\n  observed=\"observed\"\n  median=\"median\"\n  intervals={[\n    { low: \"low90\", high: \"high90\", label: \"90% interval\" },\n    { low: \"low50\", high: \"high50\", label: \"50% interval\" },\n  ]}\n  forecastFrom={3}\n  labels={{ observed: \"Observed\", median: \"Forecast (median)\", forecast: \"Forecast\" }}\n/>",
    "client": true
  }
}
