{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "period-bar-chart-card",
  "title": "Period Bar Chart Card",
  "description": "A card with a total for the selected period, a range switcher, and a bar chart that highlights that period.",
  "dependencies": [
    "recharts",
    "lucide-react"
  ],
  "registryDependencies": [
    "card",
    "chart",
    "tabs"
  ],
  "files": [
    {
      "path": "registry/dashboardcn/blocks/period-bar-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 {\n  Card,\n  CardAction,\n  CardContent,\n  CardDescription,\n  CardHeader,\n  CardTitle,\n} from \"@/components/ui/card\"\nimport { BarChart, type BarChartProps, type BarRow } from \"@/registry/dashboardcn/ui/bar-chart\"\nimport { DeltaBadge } from \"@/registry/dashboardcn/ui/delta-badge\"\nimport { PeriodTabs } from \"@/registry/dashboardcn/ui/period-tabs\"\n\nexport interface RangeOption {\n  value: string\n  label: string\n  /** How many trailing rows of data this range shows. */\n  points: number\n}\n\nexport interface PeriodBarChartCardProps extends React.ComponentProps<typeof Card> {\n  title: string\n  data: BarRow[]\n  xKey: string\n  yKey: string\n  /** Key that groups bars into selectable periods, e.g. \"month\" for weekly rows. Defaults to xKey. */\n  groupKey?: string\n  /** Range options for the switcher. Omit to show every row and hide the switcher. */\n  ranges?: RangeOption[]\n  defaultRange?: string\n  /** Group value drawn in color. Defaults to the last group in view. */\n  selected?: string\n  defaultSelected?: string\n  onSelectedChange?: (group: string) => void\n  /** Words after the period in the subtitle, e.g. \"spending\" renders \"March spending\". */\n  valueLabel?: string\n  format?: NumberFormat\n  currency?: string\n  variant?: BarChartProps[\"variant\"]\n  color?: string\n  mutedColor?: string\n  grid?: BarChartProps[\"grid\"]\n  xFormatter?: BarChartProps[\"xFormatter\"]\n  tooltipLabel?: BarChartProps[\"tooltipLabel\"]\n  chartClassName?: string\n}\n\nfunction sum(rows: BarRow[], key: string) {\n  return rows.reduce((total, row) => total + (Number(row[key]) || 0), 0)\n}\n\n/** A card with a total for the selected period, a range switcher, and a bar chart. Click a bar to select its period. */\nfunction PeriodBarChartCard({\n  title,\n  data,\n  xKey,\n  yKey,\n  groupKey = xKey,\n  ranges,\n  defaultRange,\n  selected: selectedProp,\n  defaultSelected,\n  onSelectedChange,\n  valueLabel,\n  format = \"currency\",\n  currency,\n  variant,\n  color,\n  mutedColor,\n  grid,\n  xFormatter,\n  tooltipLabel,\n  chartClassName,\n  className,\n  ...props\n}: PeriodBarChartCardProps) {\n  const [range, setRange] = React.useState(defaultRange ?? ranges?.[0]?.value)\n  const points = ranges?.find((option) => option.value === range)?.points\n  const rows = React.useMemo(\n    () => (points ? data.slice(Math.max(0, data.length - points)) : data),\n    [data, points]\n  )\n\n  const groups = React.useMemo(() => {\n    const order: string[] = []\n    for (const row of rows) {\n      const group = String(row[groupKey])\n      if (order[order.length - 1] !== group) order.push(group)\n    }\n    return order\n  }, [rows, groupKey])\n\n  const [selectedState, setSelectedState] = React.useState(defaultSelected)\n  const selected =\n    selectedProp ?? (selectedState && groups.includes(selectedState) ? selectedState : groups.at(-1))\n  const setSelected = (group: string) => {\n    setSelectedState(group)\n    onSelectedChange?.(group)\n  }\n\n  const selectedRows = rows.filter((row) => String(row[groupKey]) === selected)\n  const previousGroup = groups[groups.indexOf(selected ?? \"\") - 1]\n  const previousRows = previousGroup\n    ? rows.filter((row) => String(row[groupKey]) === previousGroup)\n    : []\n  const total = sum(selectedRows, yKey)\n  const delta = previousRows.length ? computeDelta(total, sum(previousRows, yKey)) : undefined\n\n  const yFormatter = React.useCallback(\n    (value: number) => formatNumber(value, { format, currency }),\n    [format, currency]\n  )\n\n  return (\n    <Card data-slot=\"period-bar-chart-card\" className={cn(\"@container/card gap-4\", className)} {...props}>\n      <CardHeader className=\"@max-sm/card:[grid-template-columns:minmax(0,1fr)]!\">\n        <CardDescription>{title}</CardDescription>\n        <CardTitle className=\"text-3xl font-semibold tabular-nums tracking-tight\">\n          {yFormatter(total)}\n        </CardTitle>\n        <div className=\"flex items-center gap-1.5 text-sm\">\n          {delta !== undefined ? <DeltaBadge delta={delta} variant=\"text\" /> : null}\n          <span className=\"text-muted-foreground\">\n            {selected}\n            {valueLabel ? ` ${valueLabel}` : null}\n            {previousGroup ? ` vs ${previousGroup}` : null}\n          </span>\n        </div>\n        {ranges?.length ? (\n          <CardAction className=\"@max-sm/card:[grid-area:auto]! @max-sm/card:justify-self-start!\">\n            <PeriodTabs options={ranges} value={range} onValueChange={setRange} />\n          </CardAction>\n        ) : null}\n      </CardHeader>\n      <CardContent>\n        <BarChart\n          data={rows}\n          xKey={xKey}\n          yKey={yKey}\n          groupKey={groupKey === xKey ? undefined : groupKey}\n          variant={variant}\n          color={color}\n          mutedColor={mutedColor}\n          grid={grid}\n          highlight={(row) => String(row[groupKey]) === selected}\n          yFormatter={yFormatter}\n          xFormatter={xFormatter}\n          tooltipLabel={tooltipLabel}\n          onBarClick={(row) => setSelected(String(row[groupKey]))}\n          className={cn(\"h-56\", chartClassName)}\n        />\n      </CardContent>\n    </Card>\n  )\n}\n\nexport { PeriodBarChartCard }\n",
      "type": "registry:component"
    },
    {
      "path": "registry/dashboardcn/ui/bar-chart.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport {\n  Bar,\n  BarChart as RechartsBarChart,\n  CartesianGrid,\n  Cell,\n  Rectangle,\n  ReferenceLine,\n  XAxis,\n  YAxis,\n} from \"recharts\"\n\nimport { cn } from \"@/lib/utils\"\nimport { ChartContainer, ChartTooltip } from \"@/components/ui/chart\"\n\nexport type BarRow = Record<string, unknown>\n\nexport interface BarReferenceLine {\n  /** Horizontal line at this y value. */\n  y: number\n  label?: string\n  /** Any CSS color. Defaults to the muted foreground. */\n  color?: string\n  /** Defaults to dashed. */\n  dashed?: boolean\n}\n\nexport interface BarChartProps\n  extends Omit<React.ComponentProps<typeof ChartContainer>, \"config\" | \"children\"> {\n  data: BarRow[]\n  /** Key of the x-axis value in each row. */\n  xKey: string\n  /** Key of the bar value in each row. */\n  yKey: string\n  /**\n   * Key of a coarser label, e.g. \"month\" for weekly rows. When set, the x-axis\n   * shows one tick per group centered under its bars instead of a tick per bar.\n   */\n  groupKey?: string\n  /** \"gradient\" fades each bar toward the bottom; \"striped\" fills it with diagonal bands. */\n  variant?: \"gradient\" | \"striped\" | \"solid\"\n  /** Any CSS color for highlighted bars. Defaults to chart-1. */\n  color?: string\n  /** Any CSS color for bars that are not highlighted. Defaults to the muted foreground. */\n  mutedColor?: string\n  /** Return true for bars drawn in color. Every bar is highlighted when omitted. */\n  highlight?: (row: BarRow, index: number) => boolean\n  grid?: \"dashed\" | \"solid\" | \"none\"\n  showYAxis?: boolean\n  showTooltip?: boolean\n  /** Draw a hollow ring on top of the hovered bar. */\n  showActiveMarker?: boolean\n  barRadius?: number\n  /** Animate bars after hydration and when data changes. Respects reduced motion. */\n  animate?: boolean\n  animationDuration?: number\n  /** Horizontal lines, e.g. a goal or an average. The y-axis extends to fit them. */\n  referenceLines?: BarReferenceLine[]\n  xFormatter?: (value: unknown) => string\n  yFormatter?: (value: number) => string\n  /** Secondary line of the tooltip. Defaults to the formatted x value. */\n  tooltipLabel?: (row: BarRow, index: number) => React.ReactNode\n  onBarClick?: (row: BarRow, index: number) => void\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\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\n/** One tick per group, placed under the middle bar of the group. */\nfunction groupTicks(data: BarRow[], groupKey: string) {\n  const labels: string[] = Array.from({ length: data.length }, () => \"\")\n  let start = 0\n  for (let i = 1; i <= data.length; i++) {\n    if (i === data.length || data[i]![groupKey] !== data[start]![groupKey]) {\n      labels[Math.floor((start + i - 1) / 2)] = String(data[start]![groupKey] ?? \"\")\n      start = i\n    }\n  }\n  return labels\n}\n\ninterface ShapeProps {\n  x?: number\n  y?: number\n  width?: number\n  height?: number\n  index?: number\n}\n\n/** A single-series bar chart with gradient or striped fills, highlighted bars, and a hover marker. */\nfunction BarChart({\n  data,\n  xKey,\n  yKey,\n  groupKey,\n  variant = \"gradient\",\n  color = \"var(--chart-1)\",\n  mutedColor = \"var(--muted-foreground)\",\n  highlight,\n  grid = \"dashed\",\n  showYAxis = false,\n  showTooltip = true,\n  showActiveMarker = true,\n  barRadius = 6,\n  animate = true,\n  animationDuration = 500,\n  referenceLines = [],\n  xFormatter = defaultXFormatter,\n  yFormatter,\n  tooltipLabel,\n  onBarClick,\n  className,\n  ...props\n}: BarChartProps) {\n  const id = React.useId()\n  const reducedMotion = React.useSyncExternalStore(\n    subscribeToReducedMotion,\n    getReducedMotionSnapshot,\n    getReducedMotionServerSnapshot\n  )\n  const isHighlighted = React.useCallback(\n    (index: number) => (highlight ? highlight(data[index]!, index) : true),\n    [data, highlight]\n  )\n  const tickLabels = React.useMemo(\n    () => (groupKey ? groupTicks(data, groupKey) : null),\n    [data, groupKey]\n  )\n  const fillFor = (index: number) =>\n    `url(#${id}-${isHighlighted(index) ? \"on\" : \"off\"})`\n\n  const activeBar = (shape: ShapeProps) => {\n    const { x = 0, y = 0, width = 0, height = 0, index = 0 } = shape\n    const on = isHighlighted(index)\n    return (\n      <g>\n        <Rectangle {...shape} fill={fillFor(index)} />\n        {showActiveMarker && height > 0 ? (\n          <circle\n            cx={x + width / 2}\n            cy={y}\n            r={4}\n            fill=\"var(--background)\"\n            stroke={on ? color : mutedColor}\n            strokeWidth={2}\n          />\n        ) : null}\n      </g>\n    )\n  }\n\n  return (\n    <ChartContainer\n      data-slot=\"bar-chart\"\n      config={{ [yKey]: { label: yKey, color } }}\n      className={cn(\"aspect-auto h-64 w-full\", className)}\n      {...props}\n    >\n      <RechartsBarChart\n        data={data}\n        margin={{ top: 12, right: 8, bottom: 0, left: showYAxis ? 0 : 8 }}\n        barCategoryGap=\"28%\"\n      >\n        <defs>\n          {variant === \"gradient\" ? (\n            <>\n              <linearGradient id={`${id}-on`} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n                <stop offset=\"0%\" stopColor={color} stopOpacity={1} />\n                <stop offset=\"100%\" stopColor={color} stopOpacity={0.6} />\n              </linearGradient>\n              <linearGradient id={`${id}-off`} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n                <stop offset=\"0%\" stopColor={mutedColor} stopOpacity={0.35} />\n                <stop offset=\"100%\" stopColor={mutedColor} stopOpacity={0.18} />\n              </linearGradient>\n            </>\n          ) : variant === \"striped\" ? (\n            <>\n              {([\"on\", \"off\"] as const).map((state) => {\n                const fill = state === \"on\" ? color : mutedColor\n                const opacity = state === \"on\" ? 1 : 0.3\n                return (\n                  <pattern\n                    key={state}\n                    id={`${id}-${state}`}\n                    patternUnits=\"userSpaceOnUse\"\n                    width={10}\n                    height={10}\n                    patternTransform=\"rotate(45)\"\n                  >\n                    <rect width={10} height={10} fill={fill} fillOpacity={opacity} />\n                    <rect\n                      width={5}\n                      height={10}\n                      fill=\"var(--background)\"\n                      fillOpacity={0.25}\n                    />\n                  </pattern>\n                )\n              })}\n            </>\n          ) : (\n            <>\n              <linearGradient id={`${id}-on`}>\n                <stop stopColor={color} />\n              </linearGradient>\n              <linearGradient id={`${id}-off`}>\n                <stop stopColor={mutedColor} stopOpacity={0.3} />\n              </linearGradient>\n            </>\n          )}\n        </defs>\n        {grid !== \"none\" ? (\n          <CartesianGrid\n            vertical={false}\n            strokeDasharray={grid === \"dashed\" ? \"6 6\" : undefined}\n          />\n        ) : null}\n        <XAxis\n          dataKey={xKey}\n          tickLine={false}\n          axisLine={false}\n          tickMargin={10}\n          interval={tickLabels ? 0 : \"preserveStartEnd\"}\n          minTickGap={tickLabels ? 0 : 24}\n          tickFormatter={\n            tickLabels ? (_, index) => tickLabels[index] ?? \"\" : (v) => xFormatter(v)\n          }\n        />\n        <YAxis\n          hide={!showYAxis}\n          tickLine={false}\n          axisLine={false}\n          tickMargin={8}\n          width={44}\n          tickFormatter={yFormatter}\n        />\n        {showTooltip ? (\n          <ChartTooltip\n            cursor={false}\n            isAnimationActive={false}\n            content={({ active, payload }) => {\n              const entry = payload?.[0]\n              if (!active || !entry) return null\n              const row = entry.payload as BarRow\n              const index = data.indexOf(row)\n              const value = Number(row[yKey])\n              return (\n                <div className=\"bg-background rounded-lg border px-3 py-2 text-xs shadow-md\">\n                  <div className=\"text-sm font-semibold tabular-nums\">\n                    {yFormatter ? yFormatter(value) : String(value)}\n                  </div>\n                  <div className=\"text-muted-foreground\">\n                    {tooltipLabel ? tooltipLabel(row, index) : xFormatter(row[xKey])}\n                  </div>\n                </div>\n              )\n            }}\n          />\n        ) : null}\n        <Bar\n          dataKey={yKey}\n          radius={barRadius}\n          isAnimationActive={animate && !reducedMotion}\n          animationDuration={animationDuration}\n          animationEasing=\"ease-out\"\n          activeBar={activeBar}\n          onClick={\n            onBarClick\n              ? (_, index) => onBarClick(data[index]!, index)\n              : undefined\n          }\n          className={onBarClick ? \"cursor-pointer\" : undefined}\n        >\n          {data.map((_, index) => (\n            <Cell key={index} fill={fillFor(index)} />\n          ))}\n        </Bar>\n        {referenceLines.map((line, index) => (\n          <ReferenceLine\n            key={index}\n            y={line.y}\n            ifOverflow=\"extendDomain\"\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: \"insideTopRight\",\n                    fill: line.color ?? \"var(--muted-foreground)\",\n                    fontSize: 11,\n                  }\n                : undefined\n            }\n          />\n        ))}\n      </RechartsBarChart>\n    </ChartContainer>\n  )\n}\n\nexport { BarChart }\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/period-tabs.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Tabs, TabsList, TabsTrigger } from \"@/components/ui/tabs\"\n\nexport interface PeriodOption {\n  value: string\n  label: string\n}\n\nexport const defaultPeriods: PeriodOption[] = [\n  { value: \"week\", label: \"Week\" },\n  { value: \"month\", label: \"Month\" },\n  { value: \"year\", label: \"Year\" },\n]\n\nexport interface PeriodTabsProps\n  extends Omit<React.ComponentProps<typeof Tabs>, \"children\"> {\n  options?: PeriodOption[]\n  size?: \"sm\" | \"default\"\n  /** Slide a single pill between tabs instead of swapping backgrounds. */\n  animated?: boolean\n}\n\ninterface IndicatorRect {\n  left: number\n  top: number\n  width: number\n  height: number\n}\n\n/** Small segmented control for switching a chart's time range. */\nfunction PeriodTabs({\n  options = defaultPeriods,\n  size = \"sm\",\n  animated = false,\n  className,\n  value,\n  defaultValue,\n  onValueChange,\n  ...props\n}: PeriodTabsProps) {\n  const listRef = React.useRef<HTMLDivElement>(null)\n  const [internalValue, setInternalValue] = React.useState(\n    defaultValue ?? options[0]?.value\n  )\n  const active = value ?? internalValue\n  const [rect, setRect] = React.useState<IndicatorRect | null>(null)\n\n  const measure = React.useCallback(() => {\n    const list = listRef.current\n    if (!list) return\n    const trigger = list.querySelector<HTMLElement>('[data-state=\"active\"]')\n    if (!trigger) return\n    setRect({\n      left: trigger.offsetLeft,\n      top: trigger.offsetTop,\n      width: trigger.offsetWidth,\n      height: trigger.offsetHeight,\n    })\n  }, [])\n\n  React.useLayoutEffect(() => {\n    if (!animated) return\n    measure()\n  }, [animated, active, options, size, measure])\n\n  React.useEffect(() => {\n    if (!animated || !listRef.current) return\n    const observer = new ResizeObserver(measure)\n    observer.observe(listRef.current)\n    return () => observer.disconnect()\n  }, [animated, measure])\n\n  return (\n    <Tabs\n      data-slot=\"period-tabs\"\n      className={cn(\"w-fit\", className)}\n      value={value}\n      defaultValue={defaultValue}\n      onValueChange={(next) => {\n        setInternalValue(next)\n        onValueChange?.(next)\n      }}\n      {...props}\n    >\n      <TabsList\n        ref={listRef}\n        className={cn(\n          \"relative\",\n          size === \"sm\" && \"group-data-[orientation=horizontal]/tabs:h-8 p-1\"\n        )}\n      >\n        {animated && rect ? (\n          <span\n            aria-hidden\n            data-slot=\"period-tabs-indicator\"\n            className=\"pointer-events-none absolute rounded-md bg-background shadow-sm transition-[left,top,width,height] duration-300 ease-[cubic-bezier(0.25,1,0.5,1)] motion-reduce:transition-none dark:border dark:border-input dark:bg-input/30\"\n            style={rect}\n          />\n        ) : null}\n        {options.map((option) => (\n          <TabsTrigger\n            key={option.value}\n            value={option.value}\n            className={cn(\n              size === \"sm\" && \"h-6 px-2.5 text-xs\",\n              animated &&\n                \"relative z-10 data-[state=active]:bg-transparent group-data-[variant=default]/tabs-list:data-[state=active]:shadow-none dark:data-[state=active]:border-transparent dark:data-[state=active]:bg-transparent\"\n            )}\n          >\n            {option.label}\n          </TabsTrigger>\n        ))}\n      </TabsList>\n    </Tabs>\n  )\n}\n\nexport { PeriodTabs }\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",
    "finance"
  ],
  "type": "registry:block"
}