{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "metric-tabs-chart-card",
  "title": "Metric Tabs Chart Card",
  "description": "A row of metric tabs, each with a value and delta, above a line chart of the selected metric against the previous period.",
  "dependencies": [
    "recharts",
    "lucide-react"
  ],
  "registryDependencies": [
    "card",
    "chart",
    "tooltip"
  ],
  "files": [
    {
      "path": "registry/dashboardcn/blocks/metric-tabs-chart-card.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\nimport {\n  computeDelta,\n  formatNumber,\n  type NumberFormat,\n} from \"@/registry/dashboardcn/lib/format\"\nimport { Card, CardContent } from \"@/components/ui/card\"\nimport { ComposedChart, type ComposedChartProps } from \"@/registry/dashboardcn/ui/composed-chart\"\nimport { DeltaBadge } from \"@/registry/dashboardcn/ui/delta-badge\"\nimport { MetricValue } from \"@/registry/dashboardcn/ui/metric-value\"\n\nexport interface MetricTab {\n  /** Key of this metric in each data row. */\n  key: string\n  label: string\n  /** Key of the previous-period series in each row, drawn as a dashed line. */\n  compareKey?: string\n  /** Headline value. Defaults to the aggregate of the metric's series. */\n  value?: number | string\n  /** Fractional change. Defaults to the aggregate vs the compare series. */\n  delta?: number\n  /** How to roll the series up into the headline value. */\n  aggregate?: \"sum\" | \"average\" | \"last\"\n  format?: NumberFormat\n  currency?: string\n  fractionDigits?: number\n  /** Treat a decrease as good and an increase as bad (spend, cost, churn). */\n  invertDelta?: boolean\n}\n\nexport interface MetricTabsChartCardProps extends React.ComponentProps<typeof Card> {\n  metrics: MetricTab[]\n  data: Record<string, unknown>[]\n  xKey: string\n  /** Controlled selected metric key. */\n  selected?: string\n  defaultSelected?: string\n  onSelectedChange?: (key: string) => void\n  /** Line color for the selected metric. */\n  color?: string\n  /** Line color for the previous-period series. */\n  compareColor?: string\n  /** Tooltip label for the previous-period series. */\n  compareLabel?: string\n  xFormatter?: ComposedChartProps[\"xFormatter\"]\n  chartClassName?: string\n}\n\nfunction aggregate(\n  data: Record<string, unknown>[],\n  key: string,\n  mode: MetricTab[\"aggregate\"] = \"sum\"\n) {\n  const values = data.map((row) => Number(row[key])).filter(Number.isFinite)\n  if (!values.length) return 0\n  if (mode === \"last\") return values[values.length - 1]!\n  const total = values.reduce((sum, value) => sum + value, 0)\n  return mode === \"average\" ? total / values.length : total\n}\n\n/** A card with a row of metric tabs, each with a value and delta, and a line chart of the selected metric against the previous period. */\nfunction MetricTabsChartCard({\n  metrics,\n  data,\n  xKey,\n  selected: selectedProp,\n  defaultSelected,\n  onSelectedChange,\n  color = \"var(--chart-2)\",\n  compareColor = \"var(--chart-1)\",\n  compareLabel = \"Previous period\",\n  xFormatter,\n  chartClassName,\n  className,\n  ...props\n}: MetricTabsChartCardProps) {\n  const id = React.useId()\n  const [selectedState, setSelectedState] = React.useState(\n    defaultSelected ?? metrics[0]?.key\n  )\n  const selectedKey = selectedProp ?? selectedState\n  const active = metrics.find((metric) => metric.key === selectedKey) ?? metrics[0]\n\n  const select = (key: string) => {\n    setSelectedState(key)\n    onSelectedChange?.(key)\n  }\n\n  const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    if (event.key !== \"ArrowLeft\" && event.key !== \"ArrowRight\") return\n    event.preventDefault()\n    const index = metrics.findIndex((metric) => metric.key === active?.key)\n    const step = event.key === \"ArrowRight\" ? 1 : -1\n    const next = metrics[(index + step + metrics.length) % metrics.length]\n    if (!next) return\n    select(next.key)\n    document.getElementById(`${id}-tab-${next.key}`)?.focus()\n  }\n\n  const yFormatter = React.useCallback(\n    (value: number) =>\n      formatNumber(value, {\n        format: active?.format,\n        currency: active?.currency,\n        maximumFractionDigits: active?.fractionDigits,\n      }),\n    [active?.format, active?.currency, active?.fractionDigits]\n  )\n\n  if (!active) return null\n\n  return (\n    <Card\n      data-slot=\"metric-tabs-chart-card\"\n      className={cn(\"gap-0 overflow-hidden py-0\", className)}\n      {...props}\n    >\n      <div\n        role=\"tablist\"\n        aria-label=\"Metrics\"\n        onKeyDown={onKeyDown}\n        className=\"flex divide-x overflow-x-auto border-b [scrollbar-width:thin] [scrollbar-color:color-mix(in_oklab,var(--foreground)_20%,transparent)_transparent]\"\n      >\n        {metrics.map((metric) => {\n          const isSelected = metric.key === active.key\n          const value =\n            metric.value ??\n            aggregate(data, metric.key, metric.aggregate)\n          const delta =\n            metric.delta ??\n            (metric.compareKey\n              ? computeDelta(\n                  aggregate(data, metric.key, metric.aggregate),\n                  aggregate(data, metric.compareKey, metric.aggregate)\n                )\n              : undefined)\n          return (\n            <button\n              key={metric.key}\n              id={`${id}-tab-${metric.key}`}\n              type=\"button\"\n              role=\"tab\"\n              aria-selected={isSelected}\n              aria-controls={`${id}-panel`}\n              tabIndex={isSelected ? 0 : -1}\n              data-slot=\"metric-tab\"\n              data-state={isSelected ? \"active\" : \"inactive\"}\n              onClick={() => select(metric.key)}\n              className={cn(\n                \"flex flex-[1_0_auto] flex-col gap-1.5 px-4 py-3 text-left outline-none transition-colors\",\n                \"focus-visible:ring-ring/50 focus-visible:ring-2 focus-visible:ring-inset\",\n                isSelected\n                  ? \"bg-muted\"\n                  : \"hover:bg-muted/50\"\n              )}\n            >\n              <span className=\"text-muted-foreground text-sm whitespace-nowrap\">{metric.label}</span>\n              <span className=\"flex items-center justify-between gap-3\">\n                <MetricValue\n                  value={value}\n                  format={metric.format}\n                  currency={metric.currency}\n                  maximumFractionDigits={metric.fractionDigits}\n                  className=\"text-lg font-semibold tracking-tight\"\n                />\n                {delta !== undefined ? (\n                  <DeltaBadge\n                    delta={delta}\n                    invert={metric.invertDelta}\n                    variant=\"text\"\n                    showIcon={false}\n                  />\n                ) : null}\n              </span>\n            </button>\n          )\n        })}\n      </div>\n      <CardContent id={`${id}-panel`} role=\"tabpanel\" className=\"pt-4 pb-4\">\n        <ComposedChart\n          data={data}\n          xKey={xKey}\n          series={[\n            ...(active.compareKey\n              ? [\n                  {\n                    key: active.compareKey,\n                    label: compareLabel,\n                    type: \"line\" as const,\n                    color: compareColor,\n                    dashed: true,\n                  },\n                ]\n              : []),\n            { key: active.key, label: active.label, type: \"line\" as const, color },\n          ]}\n          showGrid={false}\n          yDomain=\"auto\"\n          xFormatter={xFormatter}\n          yFormatter={yFormatter}\n          className={cn(\"h-40\", chartClassName)}\n        />\n      </CardContent>\n    </Card>\n  )\n}\n\nexport { MetricTabsChartCard }\n",
      "type": "registry:component"
    },
    {
      "path": "registry/dashboardcn/ui/composed-chart.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport {\n  Area,\n  Bar,\n  CartesianGrid,\n  ComposedChart as RechartsComposedChart,\n  Line,\n  ReferenceDot,\n  ReferenceLine,\n  XAxis,\n  YAxis,\n} from \"recharts\"\n\nimport { cn } from \"@/lib/utils\"\nimport {\n  ChartContainer,\n  ChartLegend,\n  ChartLegendContent,\n  ChartTooltip,\n  ChartTooltipContent,\n  type ChartConfig,\n} from \"@/components/ui/chart\"\n\nexport interface ComposedSeries {\n  /** Key in each data row. */\n  key: string\n  label: string\n  type?: \"area\" | \"line\" | \"bar\"\n  /** Any CSS color. Defaults to chart-1 through chart-5 in order. */\n  color?: string\n  /** Plot against the right axis. */\n  axis?: \"left\" | \"right\"\n  /** Series with the same stackId stack on top of each other. */\n  stackId?: string\n  /** Bars only: fill with a diagonal hatch instead of a solid color. */\n  pattern?: \"solid\" | \"hatched\"\n  /** Lines and areas only. */\n  dashed?: boolean\n  curve?: \"monotone\" | \"linear\" | \"step\"\n  /** Lines only: draw a dot on every point. */\n  dots?: boolean\n  /** Mark the highest point of this series with a dot. */\n  highlightMax?: boolean\n}\n\nexport interface ReferenceLineSpec {\n  /** Horizontal line at this y value. */\n  y?: number\n  /** Vertical line at this x value. */\n  x?: string | number\n  label?: string\n  /** Any CSS color. Defaults to the muted foreground. */\n  color?: string\n  dashed?: boolean\n  axis?: \"left\" | \"right\"\n}\n\nexport interface ComposedChartProps\n  extends Omit<React.ComponentProps<typeof ChartContainer>, \"config\" | \"children\"> {\n  data: Record<string, unknown>[]\n  /** Key of the x-axis value in each row. */\n  xKey: string\n  series: ComposedSeries[]\n  referenceLines?: ReferenceLineSpec[]\n  showGrid?: boolean\n  showYAxis?: boolean\n  showLegend?: boolean\n  showTooltip?: boolean\n  xFormatter?: (value: unknown) => string\n  yFormatter?: (value: number) => string\n  rightYFormatter?: (value: number) => string\n  barRadius?: number\n  /** Animate series after hydration and when their data changes. Respects reduced motion. */\n  animate?: boolean\n  animationDuration?: number\n  /** \"zero\" starts the y-axis at 0; \"auto\" fits it to the data. */\n  yDomain?: \"zero\" | \"auto\" | [number, number]\n}\n\nconst reducedMotionQuery = \"(prefers-reduced-motion: reduce)\"\n\nfunction subscribeToReducedMotion(onChange: () => void) {\n  const query = window.matchMedia(reducedMotionQuery)\n  query.addEventListener(\"change\", onChange)\n  return () => query.removeEventListener(\"change\", onChange)\n}\n\nfunction getReducedMotionSnapshot() {\n  return window.matchMedia(reducedMotionQuery).matches\n}\n\n/** The server snapshot disables motion so hydration starts from identical markup. */\nfunction getReducedMotionServerSnapshot() {\n  return true\n}\n\nfunction defaultXFormatter(value: unknown) {\n  if (typeof value === \"string\" && /^\\d{4}-\\d{2}-\\d{2}/.test(value)) {\n    const [y, m, d] = value.split(\"-\").map(Number)\n    return new Date(y!, m! - 1, d).toLocaleDateString(\"en-US\", {\n      month: \"short\",\n      day: \"numeric\",\n    })\n  }\n  return String(value)\n}\n\nfunction ComposedChart({\n  data,\n  xKey,\n  series,\n  referenceLines = [],\n  showGrid = true,\n  showYAxis = false,\n  showLegend = false,\n  showTooltip = true,\n  xFormatter = defaultXFormatter,\n  yFormatter,\n  rightYFormatter,\n  barRadius = 4,\n  animate = true,\n  animationDuration = 500,\n  yDomain = \"zero\",\n  className,\n  ...props\n}: ComposedChartProps) {\n  const id = React.useId()\n  const reducedMotion = React.useSyncExternalStore(\n    subscribeToReducedMotion,\n    getReducedMotionSnapshot,\n    getReducedMotionServerSnapshot\n  )\n  const config = Object.fromEntries(\n    series.map((s, index) => [\n      s.key,\n      { label: s.label, color: s.color ?? `var(--chart-${(index % 5) + 1})` },\n    ])\n  ) satisfies ChartConfig\n  const hasRightAxis = series.some((s) => s.axis === \"right\")\n  const domain =\n    yDomain === \"auto\" ? ([\"auto\", \"auto\"] as const) : yDomain === \"zero\" ? undefined : yDomain\n\n  const maxPoints = series\n    .filter((s) => s.highlightMax)\n    .map((s) => {\n      let best: { x: unknown; y: number } | null = null\n      for (const row of data) {\n        const y = Number(row[s.key])\n        if (Number.isFinite(y) && (!best || y > best.y)) best = { x: row[xKey], y }\n      }\n      return best ? { ...best, key: s.key, axis: s.axis ?? \"left\" } : null\n    })\n    .filter((p): p is NonNullable<typeof p> => p !== null)\n\n  return (\n    <ChartContainer\n      data-slot=\"composed-chart\"\n      config={config}\n      className={cn(\"aspect-auto h-64 w-full\", className)}\n      {...props}\n    >\n      <RechartsComposedChart\n        data={data}\n        margin={{ top: 8, right: hasRightAxis ? 0 : 8, bottom: 0, left: showYAxis ? 0 : 8 }}\n      >\n        <defs>\n          {series.map((s) => (\n            <React.Fragment key={s.key}>\n              <linearGradient id={`${id}-fill-${s.key}`} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n                <stop offset=\"5%\" stopColor={`var(--color-${s.key})`} stopOpacity={0.5} />\n                <stop offset=\"95%\" stopColor={`var(--color-${s.key})`} stopOpacity={0.05} />\n              </linearGradient>\n              <pattern\n                id={`${id}-hatch-${s.key}`}\n                patternUnits=\"userSpaceOnUse\"\n                width={6}\n                height={6}\n                patternTransform=\"rotate(45)\"\n              >\n                <rect width={6} height={6} fill={`var(--color-${s.key})`} fillOpacity={0.15} />\n                <rect width={2} height={6} fill={`var(--color-${s.key})`} />\n              </pattern>\n            </React.Fragment>\n          ))}\n        </defs>\n        {showGrid ? <CartesianGrid vertical={false} /> : null}\n        <XAxis\n          dataKey={xKey}\n          tickLine={false}\n          axisLine={false}\n          tickMargin={8}\n          minTickGap={32}\n          tickFormatter={xFormatter}\n        />\n        <YAxis\n          yAxisId=\"left\"\n          domain={domain}\n          hide={!showYAxis}\n          tickLine={false}\n          axisLine={false}\n          tickMargin={8}\n          width={44}\n          tickFormatter={yFormatter}\n        />\n        {hasRightAxis ? (\n          <YAxis\n            yAxisId=\"right\"\n            orientation=\"right\"\n            domain={domain}\n            hide={!showYAxis}\n            tickLine={false}\n            axisLine={false}\n            tickMargin={8}\n            width={44}\n            tickFormatter={rightYFormatter ?? yFormatter}\n          />\n        ) : null}\n        {showTooltip ? (\n          <ChartTooltip\n            cursor={false}\n            content={\n              <ChartTooltipContent\n                indicator=\"dot\"\n                labelFormatter={(value) => xFormatter(value)}\n                formatter={(value, name, item) => {\n                  const s = series.find((entry) => entry.key === name)\n                  const fmt = s?.axis === \"right\" ? (rightYFormatter ?? yFormatter) : yFormatter\n                  return (\n                    <div className=\"flex w-full items-center gap-2\">\n                      <span\n                        className=\"size-2 shrink-0 rounded-[2px]\"\n                        style={{ backgroundColor: item.color }}\n                      />\n                      <span className=\"text-muted-foreground flex-1\">\n                        {config[name as string]?.label ?? name}\n                      </span>\n                      <span className=\"font-mono font-medium tabular-nums\">\n                        {fmt ? fmt(Number(value)) : String(value)}\n                      </span>\n                    </div>\n                  )\n                }}\n              />\n            }\n          />\n        ) : null}\n        {showLegend ? <ChartLegend content={<ChartLegendContent />} /> : null}\n        {series.map((s) => {\n          const color = `var(--color-${s.key})`\n          const common = {\n            dataKey: s.key,\n            yAxisId: s.axis ?? \"left\",\n            stackId: s.stackId,\n            isAnimationActive: animate && !reducedMotion,\n            animationDuration,\n            animationEasing: \"ease-out\" as const,\n          }\n          if (s.type === \"bar\") {\n            return (\n              <Bar\n                key={s.key}\n                {...common}\n                fill={s.pattern === \"hatched\" ? `url(#${id}-hatch-${s.key})` : color}\n                stroke={s.pattern === \"hatched\" ? color : undefined}\n                strokeWidth={s.pattern === \"hatched\" ? 1 : 0}\n                radius={s.stackId ? 0 : barRadius}\n              />\n            )\n          }\n          if (s.type === \"line\") {\n            return (\n              <Line\n                key={s.key}\n                {...common}\n                type={s.curve ?? \"monotone\"}\n                stroke={color}\n                strokeWidth={2}\n                strokeDasharray={s.dashed ? \"4 4\" : undefined}\n                dot={s.dots ? { r: 3, fill: color, strokeWidth: 0 } : false}\n                activeDot={{ r: 4 }}\n              />\n            )\n          }\n          return (\n            <Area\n              key={s.key}\n              {...common}\n              type={s.curve ?? \"monotone\"}\n              stroke={color}\n              strokeWidth={2}\n              strokeDasharray={s.dashed ? \"4 4\" : undefined}\n              fill={`url(#${id}-fill-${s.key})`}\n              dot={false}\n            />\n          )\n        })}\n        {referenceLines.map((line, index) => (\n          <ReferenceLine\n            key={index}\n            y={line.y}\n            x={line.x}\n            yAxisId={line.axis ?? \"left\"}\n            stroke={line.color ?? \"var(--muted-foreground)\"}\n            strokeDasharray={line.dashed === false ? undefined : \"4 4\"}\n            label={\n              line.label\n                ? {\n                    value: line.label,\n                    position: line.y !== undefined ? \"insideTopRight\" : \"insideTopLeft\",\n                    fill: line.color ?? \"var(--muted-foreground)\",\n                    fontSize: 11,\n                  }\n                : undefined\n            }\n          />\n        ))}\n        {maxPoints.map((point) => (\n          <ReferenceDot\n            key={point.key}\n            x={point.x as string | number}\n            y={point.y}\n            yAxisId={point.axis}\n            r={4}\n            fill={`var(--color-${point.key})`}\n            stroke=\"var(--background)\"\n            strokeWidth={2}\n          />\n        ))}\n      </RechartsComposedChart>\n    </ChartContainer>\n  )\n}\n\nexport { ComposedChart }\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/dashboardcn/ui/delta-badge.tsx",
      "content": "import * as React from \"react\"\nimport { Minus, TrendingDown, TrendingUp } from \"lucide-react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { formatDelta } from \"@/registry/dashboardcn/lib/format\"\n\nexport type DeltaDirection = \"up\" | \"down\" | \"flat\"\n\nexport function getDeltaDirection(delta: number | undefined): DeltaDirection {\n  if (delta === undefined || delta === 0 || !Number.isFinite(delta)) return \"flat\"\n  return delta > 0 ? \"up\" : \"down\"\n}\n\nconst directionIcon: Record<DeltaDirection, React.ElementType> = {\n  up: TrendingUp,\n  down: TrendingDown,\n  flat: Minus,\n}\n\nexport interface DeltaBadgeProps extends React.ComponentProps<\"span\"> {\n  /** Fractional change, e.g. 0.124 for +12.4%. */\n  delta: number\n  /** Treat a decrease as good and an increase as bad (churn, latency, errors). */\n  invert?: boolean\n  variant?: \"outline\" | \"soft\" | \"text\"\n  showIcon?: boolean\n}\n\nfunction DeltaBadge({\n  delta,\n  invert = false,\n  variant = \"outline\",\n  showIcon = true,\n  className,\n  children,\n  ...props\n}: DeltaBadgeProps) {\n  const direction = getDeltaDirection(delta)\n  const positive = direction === \"flat\" ? null : (direction === \"up\") !== invert\n  const Icon = directionIcon[direction]\n\n  return (\n    <span\n      data-slot=\"delta-badge\"\n      data-direction={direction}\n      data-positive={positive}\n      className={cn(\n        \"inline-flex items-center gap-1 text-xs font-medium tabular-nums\",\n        variant === \"outline\" && \"rounded-md border px-1.5 py-0.5\",\n        variant === \"soft\" && \"rounded-md px-1.5 py-0.5\",\n        variant === \"soft\" && positive === true && \"bg-emerald-500/10\",\n        variant === \"soft\" && positive === false && \"bg-red-500/10\",\n        variant === \"soft\" && positive === null && \"bg-muted\",\n        positive === true && \"text-emerald-600 dark:text-emerald-400\",\n        positive === false && \"text-red-600 dark:text-red-400\",\n        positive === null && \"text-muted-foreground\",\n        className\n      )}\n      {...props}\n    >\n      {showIcon ? <Icon className=\"size-3\" aria-hidden=\"true\" /> : null}\n      {children ?? formatDelta(delta)}\n    </span>\n  )\n}\n\nexport { DeltaBadge }\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/dashboardcn/ui/metric-value.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { formatNumber, type NumberFormat } from \"@/registry/dashboardcn/lib/format\"\nimport {\n  Tooltip,\n  TooltipContent,\n  TooltipProvider,\n  TooltipTrigger,\n} from \"@/components/ui/tooltip\"\n\n/** Values at or above this are abbreviated by default. */\nexport const DEFAULT_COMPACT_FROM = 100_000\n\nexport interface MetricValueProps extends Omit<React.ComponentProps<\"span\">, \"children\"> {\n  /** Strings render as-is. */\n  value: number | string\n  format?: NumberFormat\n  currency?: string\n  maximumFractionDigits?: number\n  /** Values at or above this are abbreviated (e.g. $158K) with the full value in a tooltip. Set to Infinity to always show the full value. */\n  compactFrom?: number\n  /** Text after the number, e.g. a unit. */\n  suffix?: React.ReactNode\n}\n\n/** A formatted number. Large values are abbreviated and reveal the full value on hover. */\nfunction MetricValue({\n  value,\n  format,\n  currency,\n  maximumFractionDigits,\n  compactFrom = DEFAULT_COMPACT_FROM,\n  suffix,\n  className,\n  ...props\n}: MetricValueProps) {\n  const classes = cn(\"tabular-nums\", className)\n\n  if (typeof value !== \"number\") {\n    return (\n      <span data-slot=\"metric-value\" className={classes} {...props}>\n        {value}\n        {suffix}\n      </span>\n    )\n  }\n\n  const full = formatNumber(value, { format, currency, maximumFractionDigits })\n  const abbreviate = format !== \"percent\" && Math.abs(value) >= compactFrom\n  if (!abbreviate) {\n    return (\n      <span data-slot=\"metric-value\" className={classes} {...props}>\n        {full}\n        {suffix}\n      </span>\n    )\n  }\n\n  return (\n    <TooltipProvider>\n      <Tooltip>\n        <TooltipTrigger asChild>\n          <span\n            data-slot=\"metric-value\"\n            data-compact=\"\"\n            className={cn(classes, \"cursor-default\")}\n            {...props}\n          >\n            {formatNumber(value, { format, currency, compact: true })}\n            {suffix}\n          </span>\n        </TooltipTrigger>\n        <TooltipContent className=\"tabular-nums\">\n          {full}\n          {suffix}\n        </TooltipContent>\n      </Tooltip>\n    </TooltipProvider>\n  )\n}\n\nexport { MetricValue }\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/dashboardcn/lib/format.ts",
      "content": "export type NumberFormat = \"number\" | \"compact\" | \"currency\" | \"percent\"\n\nexport interface FormatNumberOptions {\n  format?: NumberFormat\n  /** ISO 4217 code, used when format is \"currency\". Defaults to USD. */\n  currency?: string\n  locale?: string\n  maximumFractionDigits?: number\n  /** Abbreviate large values, e.g. \"$158K\" instead of \"$158,143\". */\n  compact?: boolean\n}\n\nconst formatterCache = new Map<string, Intl.NumberFormat>()\n\nfunction getFormatter(locale: string, options: Intl.NumberFormatOptions) {\n  const key = locale + JSON.stringify(options)\n  let formatter = formatterCache.get(key)\n  if (!formatter) {\n    formatter = new Intl.NumberFormat(locale, options)\n    formatterCache.set(key, formatter)\n  }\n  return formatter\n}\n\n/**\n * Format a metric value for display.\n *\n * formatNumber(1234567)                          -> \"1,234,567\"\n * formatNumber(1234567, { format: \"compact\" })   -> \"1.2M\"\n * formatNumber(48.2, { format: \"currency\" })     -> \"$48.20\"\n * formatNumber(158143, { format: \"currency\", compact: true }) -> \"$158K\"\n * formatNumber(0.124, { format: \"percent\" })     -> \"12.4%\"\n */\nexport function formatNumber(\n  value: number,\n  {\n    format = \"number\",\n    currency = \"USD\",\n    locale = \"en-US\",\n    maximumFractionDigits,\n    compact = false,\n  }: FormatNumberOptions = {}\n): string {\n  if (!Number.isFinite(value)) return \"—\"\n\n  // Compact values keep three significant digits: $158K, $1.23M, 41.2K.\n  const compactOptions: Intl.NumberFormatOptions = compact\n    ? maximumFractionDigits === undefined\n      ? { notation: \"compact\", maximumSignificantDigits: 3 }\n      : { notation: \"compact\", maximumFractionDigits }\n    : {}\n  switch (format) {\n    case \"compact\":\n      return getFormatter(locale, {\n        notation: \"compact\",\n        maximumFractionDigits: maximumFractionDigits ?? 1,\n      }).format(value)\n    case \"currency\":\n      return getFormatter(locale, {\n        style: \"currency\",\n        currency,\n        maximumFractionDigits: maximumFractionDigits ?? 2,\n        ...compactOptions,\n      }).format(value)\n    case \"percent\":\n      return getFormatter(locale, {\n        style: \"percent\",\n        maximumFractionDigits: maximumFractionDigits ?? 1,\n      }).format(value)\n    default:\n      return getFormatter(locale, {\n        maximumFractionDigits: maximumFractionDigits ?? 0,\n        ...compactOptions,\n      }).format(value)\n  }\n}\n\n/**\n * Format a fractional change as a signed percentage.\n *\n * formatDelta(0.124)  -> \"+12.4%\"\n * formatDelta(-0.03)  -> \"-3.0%\"\n * formatDelta(0)      -> \"0.0%\"\n */\nexport function formatDelta(delta: number, locale = \"en-US\"): string {\n  if (!Number.isFinite(delta)) return \"—\"\n  return getFormatter(locale, {\n    style: \"percent\",\n    signDisplay: \"exceptZero\",\n    maximumFractionDigits: 1,\n    minimumFractionDigits: 1,\n  }).format(delta)\n}\n\n/**\n * Fractional change between two values. Returns 0 when there is no baseline.\n */\nexport function computeDelta(current: number, previous: number): number {\n  if (!previous) return 0\n  return (current - previous) / Math.abs(previous)\n}\n",
      "type": "registry:lib"
    }
  ],
  "categories": [
    "dashboard",
    "charts",
    "marketing"
  ],
  "type": "registry:block"
}