{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "forecast",
  "title": "Forecast",
  "description": "Primitives for forecasts: a straight-line fit with a prediction interval that widens with the horizon, run-rate projection, date-to-target solving, a striped projection bar, legend keys, a tooltip and a status label.",
  "dependencies": [
    "recharts"
  ],
  "registryDependencies": [
    "https://www.dashboardblocks.com/r/radix/chart.json",
    "https://www.dashboardblocks.com/r/radix/format.json",
    "https://www.dashboardblocks.com/r/radix/status-label.json",
    "https://www.dashboardblocks.com/r/radix/use-reveal.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/forecast.tsx",
      "content": "'use client'\n\nimport { useBlockState } from '@/registry/components/dashboardblocks/block-state'\nimport {\n  ChartTooltipFrame,\n  ChartTooltipItem,\n  type ChartValueFormatter,\n  chartReferenceColor,\n  chartReferenceProps,\n  chartHatchFill,\n} from '@/registry/components/dashboardblocks/chart'\nimport {\n  StatusLabel,\n  type StatusLabelProps,\n  type StatusTone,\n} from '@/registry/components/dashboardblocks/status-label'\nimport { useReveal } from '@/registry/hooks/use-reveal'\nimport { formatNumber } from '@/registry/lib/dashboardblocks/format'\nimport type { TooltipContentProps } from 'recharts'\nimport type { NameType, ValueType } from 'recharts/types/component/DefaultTooltipContent'\n\nimport { cn } from '@/lib/utils'\n\ntype ConfidenceLevel = 0.8 | 0.9 | 0.95\n\nconst zScores: Record<ConfidenceLevel, number> = { 0.8: 1.2816, 0.9: 1.6449, 0.95: 1.96 }\n\ninterface LinearFit {\n  intercept: number\n  meanX: number\n  n: number\n  residualSd: number\n  slope: number\n  sxx: number\n}\n\nfunction fitLinear(values: number[]): LinearFit {\n  const n = values.length\n  const meanX = (n - 1) / 2\n  const meanY = n > 0 ? values.reduce((sum, value) => sum + value, 0) / n : 0\n  let sxx = 0\n  let sxy = 0\n  values.forEach((value, x) => {\n    sxx += (x - meanX) ** 2\n    sxy += (x - meanX) * (value - meanY)\n  })\n  const slope = sxx > 0 ? sxy / sxx : 0\n  const intercept = meanY - slope * meanX\n  const squaredError = values.reduce(\n    (sum, value, x) => sum + (value - (intercept + slope * x)) ** 2,\n    0,\n  )\n  const residualSd = n > 2 ? Math.sqrt(squaredError / (n - 2)) : 0\n  return { intercept, meanX, n, residualSd, slope, sxx }\n}\n\ninterface Prediction {\n  high: number\n  low: number\n  value: number\n}\n\nfunction predictLinear(fit: LinearFit, x: number, level: ConfidenceLevel = 0.8) {\n  const value = fit.intercept + fit.slope * x\n  const leverage = fit.sxx > 0 ? (x - fit.meanX) ** 2 / fit.sxx : 0\n  const margin =\n    fit.n > 0 ? zScores[level] * fit.residualSd * Math.sqrt(1 + 1 / fit.n + leverage) : 0\n  return { high: value + margin, low: value - margin, value } satisfies Prediction\n}\n\ninterface ForecastRow {\n  actual: number | null\n  /** Low and high together, for a Recharts range area. */\n  band: [number, number] | null\n  forecast: number | null\n  high: number | null\n  low: number | null\n}\n\nfunction buildForecast(values: number[], horizon: number, level: ConfidenceLevel = 0.8) {\n  const fit = fitLinear(values)\n  const last = values.length - 1\n  const rows: ForecastRow[] = values.map((value, index) =>\n    index === last\n      ? { actual: value, band: [value, value], forecast: value, high: value, low: value }\n      : { actual: value, band: null, forecast: null, high: null, low: null },\n  )\n  for (let step = 1; step <= horizon; step++) {\n    const { high, low, value } = predictLinear(fit, last + step, level)\n    rows.push({ actual: null, band: [low, high], forecast: value, high, low })\n  }\n  return { fit, rows }\n}\n\ninterface TargetForecast {\n  /** Steps after the last actual when the interval first reaches the target. */\n  earliest: number | null\n  /** Steps after the last actual when the fitted line reaches the target. */\n  expected: number | null\n  /** Steps after the last actual when the whole interval has reached the target. */\n  latest: number | null\n  reached: boolean\n}\n\ninterface SolveForTargetOptions {\n  /** @default 'up' */\n  direction?: 'up' | 'down'\n  /** @default 0.8 */\n  level?: ConfidenceLevel\n  /** How far ahead to look for the interval, in steps. */\n  maxSteps?: number\n  /** The precision of `earliest` and `latest`, in steps. */\n  resolution?: number\n}\n\nfunction solveForTarget(\n  values: number[],\n  target: number,\n  {\n    direction = 'up',\n    level = 0.8,\n    maxSteps = 104,\n    resolution = 0.1,\n  }: SolveForTargetOptions = {},\n): TargetForecast {\n  const current = values[values.length - 1] ?? 0\n  const reaches = (value: number) =>\n    direction === 'up' ? value >= target : value <= target\n  if (reaches(current)) return { earliest: 0, expected: 0, latest: 0, reached: true }\n\n  const fit = fitLinear(values)\n  const last = values.length - 1\n  const heading = direction === 'up' ? fit.slope > 0 : fit.slope < 0\n  const expected = heading\n    ? Math.max(0, (target - fit.intercept) / fit.slope - last)\n    : null\n\n  let earliest: number | null = null\n  let latest: number | null = null\n  for (let index = 1; index * resolution <= maxSteps; index++) {\n    const step = index * resolution\n    const { high, low } = predictLinear(fit, last + step, level)\n    if (earliest === null && reaches(direction === 'up' ? high : low)) earliest = step\n    if (reaches(direction === 'up' ? low : high)) {\n      latest = step\n      break\n    }\n  }\n  return { earliest, expected, latest, reached: false }\n}\n\ninterface RunRate {\n  projected: number\n  rate: number\n  remaining: number\n  required: number | null\n}\n\ninterface RunRateInput {\n  current: number\n  elapsed: number\n  target?: number\n  total: number\n}\n\nfunction getRunRate({ current, elapsed, target, total }: RunRateInput): RunRate {\n  const rate = elapsed > 0 ? current / elapsed : 0\n  const remaining = Math.max(0, total - elapsed)\n  return {\n    projected: current + rate * remaining,\n    rate,\n    remaining,\n    required:\n      target !== undefined && remaining > 0\n        ? Math.max(0, (target - current) / remaining)\n        : null,\n  }\n}\n\nfunction projectGrowth(start: number, rate: number, steps: number) {\n  return Array.from({ length: steps }, (_, index) => start * (1 + rate) ** (index + 1))\n}\n\nfunction getForecastAxis(values: (number | null)[], tickCount = 5) {\n  const numbers = values.filter((value): value is number => value !== null)\n  const min = numbers.length > 0 ? Math.min(...numbers) : 0\n  const max = numbers.length > 0 ? Math.max(...numbers) : 1\n  const rough = Math.max(max - min, Math.abs(max) / 10, 1) / (tickCount - 1)\n  const magnitude = 10 ** Math.floor(Math.log10(rough))\n  const step =\n    ([1, 2, 2.5, 5, 10].find((multiple) => multiple * magnitude >= rough) ?? 10) *\n    magnitude\n  const low = Math.floor(min / step) * step\n  const count = Math.max(1, Math.ceil((max - low) / step))\n  const ticks = Array.from({ length: count + 1 }, (_, index) => low + index * step)\n  return { domain: [low, ticks[count]] as [number, number], ticks }\n}\n\ntype ForecastStatus = 'reached' | 'on-track' | 'at-risk' | 'off-track'\n\nfunction getDeadlineStatus(forecast: TargetForecast, deadline: number): ForecastStatus {\n  if (forecast.reached) return 'reached'\n  if (forecast.latest !== null && forecast.latest <= deadline) return 'on-track'\n  if (forecast.expected !== null && forecast.expected <= deadline) return 'at-risk'\n  return 'off-track'\n}\n\nfunction getProjectionStatus(projected: number, target: number, tolerance = 0.05) {\n  const status: ForecastStatus =\n    projected >= target\n      ? 'on-track'\n      : projected >= target * (1 - tolerance)\n        ? 'at-risk'\n        : 'off-track'\n  return status\n}\n\nconst forecastStatusConfig: Record<ForecastStatus, { label: string; tone: StatusTone }> =\n  {\n    'at-risk': { label: 'At risk', tone: 'warning' },\n    'off-track': { label: 'Off track', tone: 'bad' },\n    'on-track': { label: 'On track', tone: 'good' },\n    reached: { label: 'Target reached', tone: 'good' },\n  }\n\nfunction ForecastStatusLabel({\n  className,\n  label,\n  status,\n  variant,\n}: {\n  className?: string\n  label?: string\n  status: ForecastStatus\n  variant?: StatusLabelProps['variant']\n}) {\n  const state = useBlockState()\n  if (state) return null\n  const config = forecastStatusConfig[status]\n  return (\n    <StatusLabel className={className} tone={config.tone} variant={variant}>\n      {label ?? config.label}\n    </StatusLabel>\n  )\n}\n\nconst forecastColors = {\n  actual: 'var(--color-chart-2)',\n  band: 'color-mix(in oklab, var(--color-chart-2) 20%, transparent)',\n  forecast: 'var(--color-chart-2)',\n  marker: 'var(--color-foreground)',\n  target: chartReferenceColor,\n} as const\n\nconst forecastDash = {\n  forecast: '5 4',\n  target: chartReferenceProps.strokeDasharray,\n} as const\n\ntype ForecastKeyShape =\n  | 'line'\n  | 'dashed'\n  | 'dotted'\n  | 'band'\n  | 'marker'\n  | 'dot'\n  | 'bar'\n  | 'striped'\n\nfunction ForecastKey({\n  className,\n  color,\n  shape,\n}: {\n  className?: string\n  color?: string\n  shape: ForecastKeyShape\n}) {\n  if (shape === 'bar' || shape === 'striped') {\n    const fill = color ?? forecastColors.actual\n    return (\n      <span\n        aria-hidden\n        className={cn('inline-block size-2.5 shrink-0 rounded-[3px]', className)}\n        style={\n          shape === 'bar'\n            ? { backgroundColor: fill }\n            : { backgroundImage: chartHatchFill(fill) }\n        }\n      />\n    )\n  }\n  const stroke =\n    color ??\n    (shape === 'dotted'\n      ? forecastColors.target\n      : shape === 'marker'\n        ? forecastColors.marker\n        : forecastColors.actual)\n  return (\n    <svg\n      aria-hidden\n      width='16'\n      height='10'\n      className={cn('shrink-0 overflow-visible', className)}\n    >\n      {shape === 'band' ? (\n        <rect width='16' height='10' rx='2' fill={color ?? forecastColors.band} />\n      ) : shape === 'dot' ? (\n        <circle cx='8' cy='5' r='4' fill={stroke} />\n      ) : shape === 'marker' ? (\n        <line x1='8' y1='0' x2='8' y2='10' stroke={stroke} strokeWidth='1.5' />\n      ) : (\n        <line\n          x1='0'\n          y1='5'\n          x2='16'\n          y2='5'\n          stroke={stroke}\n          strokeDasharray={\n            shape === 'dashed'\n              ? forecastDash.forecast\n              : shape === 'dotted'\n                ? forecastDash.target\n                : undefined\n          }\n          strokeWidth='2'\n        />\n      )}\n    </svg>\n  )\n}\n\ninterface ForecastLegendItem {\n  color?: string\n  label: string\n  shape: ForecastKeyShape\n}\n\nfunction ForecastLegend({\n  className,\n  items,\n}: {\n  className?: string\n  items: ForecastLegendItem[]\n}) {\n  const state = useBlockState()\n  if (state === 'empty' || state === 'error') return null\n  return (\n    <ul\n      className={cn(\n        'text-muted-foreground flex flex-wrap items-center gap-x-4 gap-y-1 text-xs',\n        className,\n      )}\n    >\n      {items.map((item) => (\n        <li key={item.label} className='flex items-center gap-1.5'>\n          <ForecastKey color={item.color} shape={item.shape} />\n          {item.label}\n        </li>\n      ))}\n    </ul>\n  )\n}\n\nconst rangeKeyColor = 'color-mix(in oklab, var(--color-chart-2) 40%, transparent)'\n\ntype ForecastTooltipProps = Partial<\n  Pick<TooltipContentProps<ValueType, NameType>, 'active' | 'label' | 'payload'>\n> & {\n  formatLabel?: (label: string) => string\n  /** @default 0.8 */\n  level?: ConfidenceLevel\n  valueFormatter?: ChartValueFormatter\n}\n\nfunction ForecastTooltip({\n  active,\n  formatLabel,\n  label,\n  level = 0.8,\n  payload,\n  valueFormatter = formatNumber,\n}: ForecastTooltipProps) {\n  const row = payload?.[0]?.payload as ForecastRow | undefined\n  if (!active || !row) return null\n  const percent = `${level * 100}%`\n  const heading = label !== undefined && label !== '' ? String(label) : undefined\n  return (\n    <ChartTooltipFrame>\n      {heading && (\n        <span className='font-medium'>\n          {formatLabel ? formatLabel(heading) : heading}\n        </span>\n      )}\n      {row.actual !== null ? (\n        <ChartTooltipItem\n          color={forecastColors.actual}\n          value={valueFormatter(row.actual)}\n        />\n      ) : (\n        <>\n          <ChartTooltipItem\n            color={forecastColors.forecast}\n            name='Forecast'\n            value={valueFormatter(row.forecast ?? 0)}\n          />\n          <ChartTooltipItem\n            color={rangeKeyColor}\n            name={`High (${percent})`}\n            value={valueFormatter(row.high ?? 0)}\n          />\n          <ChartTooltipItem\n            color={rangeKeyColor}\n            name={`Low (${percent})`}\n            value={valueFormatter(row.low ?? 0)}\n          />\n        </>\n      )}\n    </ChartTooltipFrame>\n  )\n}\n\ninterface ProjectionBarProps {\n  animated?: boolean\n  className?: string\n  /** @default 'var(--color-chart-2)' */\n  color?: string\n  current: number\n  max?: number\n  projected: number\n  target?: number\n}\n\nfunction ProjectionBar({\n  animated = true,\n  className,\n  color = forecastColors.actual,\n  current,\n  max,\n  projected,\n  target,\n}: ProjectionBarProps) {\n  const { ref, revealed } = useReveal(animated)\n  const state = useBlockState()\n\n  if (state) {\n    return (\n      <div\n        aria-hidden\n        className={cn(\n          'bg-muted h-3 w-full rounded-full',\n          state === 'loading' && 'animate-pulse motion-reduce:animate-none',\n          className,\n        )}\n      />\n    )\n  }\n\n  const scale = max ?? Math.max(current, projected, target ?? 0)\n  const share = (value: number) =>\n    scale > 0 ? Math.min(1, Math.max(0, value / scale)) * 100 : 0\n  const actualWidth = share(current)\n  const projectedWidth = Math.max(0, share(projected) - actualWidth)\n\n  return (\n    <div ref={ref} aria-hidden className={cn('relative h-3 w-full', className)}>\n      <div className='bg-muted flex h-full w-full overflow-hidden rounded-full'>\n        <div\n          className='h-full transition-[width] duration-1000 ease-[cubic-bezier(0.33,1,0.68,1)] motion-reduce:transition-none'\n          style={{ backgroundColor: color, width: `${revealed ? actualWidth : 0}%` }}\n        />\n        <div\n          className='h-full transition-[width] delay-300 duration-700 ease-[cubic-bezier(0.33,1,0.68,1)] motion-reduce:transition-none motion-reduce:delay-0'\n          style={{\n            backgroundImage: chartHatchFill(color),\n            width: `${revealed ? projectedWidth : 0}%`,\n          }}\n        />\n      </div>\n      {target !== undefined && (\n        <span\n          className='bg-foreground ring-background absolute top-1/2 h-[calc(100%+8px)] w-0.5 -translate-x-1/2 -translate-y-1/2 rounded-full ring-2'\n          style={{ left: `${share(target)}%` }}\n        />\n      )}\n    </div>\n  )\n}\n\nexport {\n  ForecastStatusLabel,\n  ForecastKey,\n  ForecastLegend,\n  ForecastTooltip,\n  ProjectionBar,\n  buildForecast,\n  fitLinear,\n  forecastColors,\n  forecastDash,\n  forecastStatusConfig,\n  getDeadlineStatus,\n  getForecastAxis,\n  getProjectionStatus,\n  getRunRate,\n  predictLinear,\n  projectGrowth,\n  solveForTarget,\n  zScores,\n}\n\nexport type {\n  ConfidenceLevel,\n  ForecastKeyShape,\n  ForecastLegendItem,\n  ForecastRow,\n  ForecastStatus,\n  ForecastTooltipProps,\n  LinearFit,\n  Prediction,\n  ProjectionBarProps,\n  RunRate,\n  RunRateInput,\n  SolveForTargetOptions,\n  TargetForecast,\n}\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/forecast.tsx"
    }
  ],
  "type": "registry:component"
}
