{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "revenue-overview",
  "type": "registry:block",
  "title": "Revenue overview",
  "description": "A subscription revenue dashboard: rolling headline figures, the MRR bridge, plan mix, cohort retention and targets on one page.",
  "categories": [
    "blocks"
  ],
  "dependencies": [
    "@tabler/icons-react"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/registry/overtrue/revenue-overview.tsx",
      "type": "registry:component",
      "target": "components/overtrue/revenue-overview.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { IconCalendarStats } from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { NumberTicker } from \"./number-ticker\";\nimport { Sparkline } from \"./sparkline\";\nimport { DeltaBadge } from \"./delta-badge\";\nimport { WaterfallChart, type WaterfallStep } from \"./waterfall-chart\";\nimport { Treemap, type TreemapNode } from \"./treemap\";\nimport { CohortGrid, type CohortGridCohort } from \"./cohort-grid\";\nimport { BulletChart, type BulletChartItem } from \"./bullet-chart\";\n\nexport interface RevenueMetric {\n  id: string;\n  label: string;\n  /** Currency amounts in whole units; rates as fractions (0.031 for 3.1%). */\n  value: number;\n  format?: \"currency\" | \"percent\" | \"number\";\n  /** Fractional change against the previous period, e.g. 0.102 for +10.2%. */\n  change?: number;\n  /** Lower is better, e.g. churn. Flips the color of the change. */\n  invert?: boolean;\n  /** Recent values, oldest first, for the sparkline. */\n  history?: number[];\n  /** Short context under the figure, e.g. \"vs. August\". */\n  hint?: string;\n}\n\nexport interface RevenueOverviewData {\n  title: string;\n  /** The reporting period, e.g. \"September 2026\". */\n  period: string;\n  /** ISO currency code for currency metrics and charts. Defaults to USD. */\n  currency?: string;\n  /** Headline metrics. The first one is lit as the hero figure. */\n  metrics: RevenueMetric[];\n  /** The MRR bridge for the period, from opening to closing MRR. */\n  movement: WaterfallStep[];\n  /** Closing MRR by plan, optionally split further (for example by billing cycle). */\n  planMix: TreemapNode[];\n  /** Subscriber retention by signup cohort. */\n  retention: { cohorts: CohortGridCohort[]; periods?: string[] };\n  /** Targets for the period. */\n  targets: BulletChartItem[];\n}\n\nexport interface RevenueOverviewProps\n  extends Omit<React.ComponentProps<\"section\">, \"title\"> {\n  data: RevenueOverviewData;\n  /** Controls placed in the header, such as a period picker or export button. */\n  actions?: React.ReactNode;\n  locale?: string;\n}\n\n/** A subscription revenue overview: headline figures, the MRR bridge, plan mix, retention and targets. */\nexport function RevenueOverview({\n  data,\n  actions,\n  locale = \"en-US\",\n  className,\n  ...props\n}: RevenueOverviewProps) {\n  const currency = data.currency ?? \"USD\";\n  const money = React.useMemo(() => {\n    const exact = new Intl.NumberFormat(locale, {\n      style: \"currency\",\n      currency,\n      maximumFractionDigits: 0,\n    });\n    const compact = new Intl.NumberFormat(locale, {\n      style: \"currency\",\n      currency,\n      notation: \"compact\",\n      maximumFractionDigits: 1,\n    });\n    return { exact, compact };\n  }, [currency, locale]);\n  const percent = React.useMemo(\n    () =>\n      new Intl.NumberFormat(locale, {\n        style: \"percent\",\n        minimumFractionDigits: 1,\n        maximumFractionDigits: 1,\n      }),\n    [locale],\n  );\n  const formatTarget = (value: number, item: BulletChartItem) =>\n    /churn|retention|rate/i.test(item.label)\n      ? percent.format(value)\n      : money.compact.format(value);\n\n  return (\n    <section\n      data-slot=\"revenue-overview\"\n      aria-label={`${data.title}, ${data.period}`}\n      className={cn(\n        \"@container/revenue flex min-w-0 flex-col gap-3 text-foreground sm:gap-4\",\n        className,\n      )}\n      {...props}\n    >\n      <header\n        data-slot=\"revenue-overview-header\"\n        className=\"flex flex-wrap items-end justify-between gap-3\"\n      >\n        <div className=\"min-w-0\">\n          <h2 className=\"truncate text-base font-semibold tracking-tight\">\n            {data.title}\n          </h2>\n          <p className=\"flex items-center gap-1.5 text-xs text-muted-foreground\">\n            <IconCalendarStats aria-hidden=\"true\" className=\"size-3.5\" />\n            {data.period}\n          </p>\n        </div>\n        {actions && (\n          <div className=\"flex flex-wrap items-center gap-2\">{actions}</div>\n        )}\n      </header>\n\n      <div className=\"grid gap-3 sm:gap-4\">\n        <dl\n          data-slot=\"revenue-metrics\"\n          className=\"grid grid-cols-1 gap-px overflow-hidden rounded-2xl border border-border/70 bg-border/70 shadow-[0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.10)] @md/revenue:grid-cols-2 @4xl/revenue:grid-cols-4 dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.05),0_1px_2px_rgb(0_0_0/0.5)]\"\n        >\n          {data.metrics.map((metric, index) => (\n            <MetricTile\n              key={metric.id}\n              metric={metric}\n              hero={index === 0}\n              locale={locale}\n              currency={currency}\n            />\n          ))}\n        </dl>\n\n        <div className=\"grid gap-3 sm:gap-4 @4xl/revenue:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)]\">\n          <WaterfallChart\n            title=\"MRR movement\"\n            description={`Where recurring revenue came from in ${data.period}`}\n            steps={data.movement}\n            valueFormatter={(value, context) =>\n              context === \"detail\"\n                ? money.exact.format(value)\n                : money.compact.format(value)\n            }\n          />\n          <Treemap\n            title=\"Plan mix\"\n            description=\"Closing MRR by plan and billing cycle\"\n            data={data.planMix}\n            rootLabel=\"All plans\"\n            height={300}\n            maxDepth={2}\n            valueFormatter={(value) => money.compact.format(value)}\n          />\n        </div>\n\n        <div className=\"grid gap-3 sm:gap-4 @4xl/revenue:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)]\">\n          <CohortGrid\n            title=\"Subscriber retention\"\n            description=\"Share of each signup month still subscribed\"\n            cohorts={data.retention.cohorts}\n            periods={data.retention.periods}\n            showAverage\n          />\n          <BulletChart\n            title=\"Targets\"\n            description={`${data.period}, against plan`}\n            items={data.targets}\n            tone=\"status\"\n            valueFormatter={formatTarget}\n          />\n        </div>\n      </div>\n    </section>\n  );\n}\n\nfunction MetricTile({\n  metric,\n  hero,\n  locale,\n  currency,\n}: {\n  metric: RevenueMetric;\n  hero: boolean;\n  locale: string;\n  currency: string;\n}) {\n  const format = metric.format ?? \"currency\";\n  return (\n    <div\n      data-slot=\"revenue-metric\"\n      data-hero={hero || undefined}\n      className={cn(\n        \"relative flex min-w-0 flex-col gap-3 bg-card p-5\",\n        hero &&\n          \"bg-[radial-gradient(120%_90%_at_0%_0%,color-mix(in_oklab,var(--color-primary)_10%,transparent),transparent_60%)] bg-card\",\n      )}\n    >\n      <div className=\"flex items-center justify-between gap-2\">\n        <dt className=\"truncate text-xs text-muted-foreground\">\n          {metric.label}\n        </dt>\n        {metric.change !== undefined && (\n          <DeltaBadge\n            delta={metric.change}\n            invert={metric.invert}\n            variant=\"soft\"\n          />\n        )}\n      </div>\n      <dd className=\"flex min-w-0 flex-col gap-1\">\n        <NumberTicker\n          value={metric.value}\n          locale={locale}\n          currency={currency}\n          format={format}\n          formatOptions={\n            format === \"percent\"\n              ? { style: \"percent\", minimumFractionDigits: 1, maximumFractionDigits: 1 }\n              : format === \"currency\"\n                ? { style: \"currency\", currency, maximumFractionDigits: 0 }\n                : undefined\n          }\n          className={cn(\n            \"font-semibold tracking-[-0.035em] tabular-nums\",\n            hero ? \"text-3xl\" : \"text-2xl\",\n          )}\n        />\n        {metric.hint && (\n          <span className=\"text-xs text-muted-foreground\">{metric.hint}</span>\n        )}\n      </dd>\n      {metric.history && metric.history.length > 1 && (\n        <Sparkline\n          data={metric.history}\n          label={`${metric.label} over the last ${metric.history.length} months`}\n          className={cn(\n            \"h-10\",\n            metric.change === undefined\n              ? \"text-muted-foreground\"\n              : (metric.change >= 0) !== Boolean(metric.invert)\n                ? \"text-primary\"\n                : \"text-rose-500 dark:text-rose-400\",\n          )}\n          filled\n          endpoint\n        />\n      )}\n    </div>\n  );\n}\n\n/* Sample data --------------------------------------------------------------- */\n\n/** Fictional subscription revenue for Acme Studio, for demos and tests. */\nexport const sampleRevenue: RevenueOverviewData = {\n  title: \"Revenue\",\n  period: \"September 2026\",\n  currency: \"USD\",\n  metrics: [\n    {\n      id: \"mrr\",\n      label: \"Monthly recurring revenue\",\n      value: 454430,\n      change: 0.102,\n      hint: \"vs. $412,300 in August\",\n      history: [298, 311, 326, 334, 351, 362, 371, 384, 396, 404, 412.3, 454.4],\n    },\n    {\n      id: \"new\",\n      label: \"New business\",\n      value: 38400,\n      change: 0.164,\n      hint: \"41 new subscriptions\",\n      history: [21, 24, 22, 27, 25, 29, 31, 28, 30, 33, 33, 38.4],\n    },\n    {\n      id: \"nrr\",\n      label: \"Net revenue retention\",\n      value: 1.009,\n      format: \"percent\",\n      change: 0.006,\n      hint: \"Expansion net of churn\",\n      history: [0.97, 0.98, 0.975, 0.99, 0.985, 0.99, 1.0, 0.995, 1.0, 1.004, 1.003, 1.009],\n    },\n    {\n      id: \"churn\",\n      label: \"Gross churn\",\n      value: 0.031,\n      format: \"percent\",\n      change: -0.114,\n      invert: true,\n      hint: \"Share of opening MRR lost\",\n      history: [0.046, 0.044, 0.045, 0.041, 0.042, 0.039, 0.037, 0.038, 0.036, 0.035, 0.035, 0.031],\n    },\n  ],\n  movement: [\n    { id: \"open\", label: \"Aug 31 MRR\", value: 412300, kind: \"start\" },\n    { id: \"new\", label: \"New business\", value: 38400 },\n    { id: \"expansion\", label: \"Expansion\", value: 21750 },\n    { id: \"reactivation\", label: \"Reactivation\", value: 4120 },\n    { id: \"contraction\", label: \"Contraction\", value: -9260 },\n    { id: \"churn\", label: \"Churn\", value: -12880 },\n    { id: \"close\", label: \"Sep 30 MRR\", value: 0, kind: \"end\" },\n  ],\n  planMix: [\n    {\n      id: \"studio\",\n      label: \"Studio\",\n      children: [\n        { id: \"studio-annual\", label: \"Annual\", value: 168000 },\n        { id: \"studio-monthly\", label: \"Monthly\", value: 64000 },\n      ],\n    },\n    {\n      id: \"team\",\n      label: \"Team\",\n      children: [\n        { id: \"team-annual\", label: \"Annual\", value: 98000 },\n        { id: \"team-monthly\", label: \"Monthly\", value: 52000 },\n      ],\n    },\n    {\n      id: \"enterprise\",\n      label: \"Enterprise\",\n      children: [{ id: \"enterprise-annual\", label: \"Annual\", value: 52000 }],\n    },\n    {\n      id: \"starter\",\n      label: \"Starter\",\n      children: [{ id: \"starter-monthly\", label: \"Monthly\", value: 20430 }],\n    },\n  ],\n  retention: {\n    periods: [\"M0\", \"M1\", \"M2\", \"M3\", \"M4\", \"M5\"],\n    cohorts: [\n      { id: \"apr\", label: \"Apr 2026\", size: 212, values: [1, 0.91, 0.86, 0.83, 0.81, 0.8] },\n      { id: \"may\", label: \"May 2026\", size: 238, values: [1, 0.92, 0.87, 0.85, 0.83] },\n      { id: \"jun\", label: \"Jun 2026\", size: 251, values: [1, 0.93, 0.89, 0.86] },\n      { id: \"jul\", label: \"Jul 2026\", size: 274, values: [1, 0.94, 0.9] },\n      { id: \"aug\", label: \"Aug 2026\", size: 290, values: [1, 0.95] },\n      { id: \"sep\", label: \"Sep 2026\", size: 312, values: [1] },\n    ],\n  },\n  targets: [\n    {\n      id: \"mrr\",\n      label: \"Closing MRR\",\n      sublabel: \"Monthly recurring revenue\",\n      value: 454430,\n      target: 460000,\n      ranges: [400000, 440000, 500000],\n    },\n    {\n      id: \"new\",\n      label: \"New business\",\n      sublabel: \"MRR from new subscriptions\",\n      value: 38400,\n      target: 35000,\n      ranges: [25000, 32000, 45000],\n    },\n    {\n      id: \"nrr\",\n      label: \"Net revenue retention\",\n      sublabel: \"Expansion net of churn\",\n      value: 1.009,\n      target: 1.02,\n      ranges: [0.95, 1.0, 1.1],\n    },\n    {\n      id: \"churn\",\n      label: \"Gross churn rate\",\n      sublabel: \"Lower is better\",\n      value: 0.031,\n      target: 0.025,\n      ranges: [0.02, 0.035, 0.06],\n      invert: true,\n    },\n  ],\n};\n"
    },
    {
      "path": "src/registry/overtrue/number-ticker.tsx",
      "type": "registry:component",
      "target": "components/overtrue/number-ticker.tsx",
      "content": "\"use client\";\nimport {\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useState,\n  useSyncExternalStore,\n  type ComponentProps,\n  type CSSProperties,\n  type ReactNode,\n} from \"react\";\nimport { cn } from \"@/lib/utils\";\n\nexport type NumberTickerFormat = \"number\" | \"currency\" | \"percent\" | \"compact\";\n\nexport interface NumberTickerProps extends Omit<\n  ComponentProps<\"span\">,\n  \"children\" | \"prefix\"\n> {\n  value: number;\n  /** Preset Intl options. Percent expects a fraction: 0.124 renders 12.4%. */\n  format?: NumberTickerFormat;\n  /** Merged over the preset, e.g. `{ maximumFractionDigits: 0 }`. */\n  formatOptions?: Intl.NumberFormatOptions;\n  locale?: string;\n  /** ISO 4217 code used by the currency preset. */\n  currency?: string;\n  prefix?: ReactNode;\n  suffix?: ReactNode;\n  /** Roll duration in milliseconds. */\n  duration?: number;\n  /** Tint the number briefly: emerald when it rises, red when it falls. */\n  highlightChanges?: boolean;\n  /** Roll up from zero on first mount instead of rendering the value directly. */\n  animateOnMount?: boolean;\n}\n\n// Each column is a wheel of five 0–9 runs. It rests in the middle run, so two\n// rapid changes in either direction can always roll forward or backward.\nconst CELLS = 50;\nconst REST = 20;\nconst STAGGER = 32;\nconst MAX_STAGGER = 224;\nconst SLIDE_EASE = \"cubic-bezier(0.2, 1, 0.32, 1)\";\n// Overshoot scales with distance, so longer rolls get a gentler curve: every\n// wheel settles past its digit by about a tenth of a cell, whatever it travelled.\nconst SETTLE = [1.534, 1.368, 1.3, 1.262, 1.236, 1.217, 1.203, 1.191, 1.181];\nconst rollEase = (cells: number) =>\n  `cubic-bezier(0.2, ${SETTLE[Math.min(Math.max(Math.abs(cells), 1), 9) - 1]}, 0.32, 1)`;\nconst SIZE_EASE = \"cubic-bezier(0.32, 0.72, 0, 1)\";\nconst REDUCED_QUERY = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribeReducedMotion(callback: () => void) {\n  const query = window.matchMedia(REDUCED_QUERY);\n  query.addEventListener(\"change\", callback);\n  return () => query.removeEventListener(\"change\", callback);\n}\n\nfunction usePrefersReducedMotion() {\n  return useSyncExternalStore(\n    subscribeReducedMotion,\n    () => window.matchMedia(REDUCED_QUERY).matches,\n    () => false,\n  );\n}\n\nconst presets: Record<\n  NumberTickerFormat,\n  (currency: string) => Intl.NumberFormatOptions\n> = {\n  number: () => ({}),\n  currency: (currency) => ({ style: \"currency\", currency }),\n  percent: () => ({\n    style: \"percent\",\n    minimumFractionDigits: 1,\n    maximumFractionDigits: 1,\n  }),\n  compact: () => ({ notation: \"compact\", maximumSignificantDigits: 3 }),\n};\n\ninterface TickerFormatter {\n  format: Intl.NumberFormat;\n  /** The locale's digit glyphs, so Arabic-Indic or Devanagari numerals roll too. */\n  glyphs: string[];\n  /** One padded cell per wheel position, created once and shared by every column. */\n  cells: ReactNode[];\n}\n\nconst formatterCache = new Map<string, TickerFormatter>();\n\nfunction resolveOptions(\n  format: NumberTickerFormat,\n  currency: string,\n  overrides: Intl.NumberFormatOptions | undefined,\n): Intl.NumberFormatOptions {\n  const options = { ...presets[format](currency), ...overrides };\n  // Keep a preset's fixed precision from conflicting with a partial override.\n  const { minimumFractionDigits: min, maximumFractionDigits: max } = options;\n  if (min !== undefined && max !== undefined && min > max) {\n    if (overrides?.maximumFractionDigits !== undefined)\n      options.minimumFractionDigits = max;\n    else options.maximumFractionDigits = min;\n  }\n  return options;\n}\n\nfunction getFormatter(\n  locale: string,\n  options: Intl.NumberFormatOptions,\n): TickerFormatter {\n  const key = `${locale}|${JSON.stringify(options)}`;\n  let entry = formatterCache.get(key);\n  if (!entry) {\n    let format: Intl.NumberFormat;\n    try {\n      format = new Intl.NumberFormat(locale, options);\n    } catch {\n      format = new Intl.NumberFormat(\"en-US\");\n    }\n    const digits = new Intl.NumberFormat(format.resolvedOptions().locale, {\n      useGrouping: false,\n      numberingSystem: format.resolvedOptions().numberingSystem,\n    } as Intl.NumberFormatOptions);\n    const glyphs = Array.from({ length: 10 }, (_, digit) =>\n      digits.format(digit),\n    );\n    const cells = Array.from({ length: CELLS }, (_, cell) => (\n      <span key={cell} className=\"block py-(--ticker-gap)\">\n        {glyphs[cell % 10]}\n      </span>\n    ));\n    entry = { format, glyphs, cells };\n    formatterCache.set(key, entry);\n  }\n  return entry;\n}\n\ntype Slot =\n  | { key: string; kind: \"digit\"; digit: number; order: number }\n  | { key: string; kind: \"char\"; char: string };\n\ntype Item = Slot & { phase: \"idle\" | \"enter\" | \"exit\" };\n\n/**\n * Split a formatted number into keyed slots. Integer digits are keyed by place\n * value and fraction digits by position, so the ones column stays the ones\n * column when 999 becomes 1,000 and only the new leading columns enter.\n */\nfunction toSlots(value: number, formatter: TickerFormatter) {\n  if (!Number.isFinite(value)) {\n    return {\n      text: \"—\",\n      slots: [{ key: \"missing\", kind: \"char\", char: \"—\" }] as Slot[],\n    };\n  }\n  const parts = formatter.format.formatToParts(value);\n  const isDigit = (char: string) => formatter.glyphs.includes(char);\n  let integerDigits = 0;\n  for (const part of parts)\n    if (part.type === \"integer\")\n      for (const char of part.value) if (isDigit(char)) integerDigits++;\n\n  const slots: Slot[] = [];\n  const seen = new Map<string, number>();\n  let integerIndex = 0;\n  let fractionIndex = 0;\n  const pushChar = (type: string, char: string) => {\n    const count = seen.get(type) ?? 0;\n    seen.set(type, count + 1);\n    slots.push({ key: `${type}${count}:${char}`, kind: \"char\", char });\n  };\n  for (const part of parts) {\n    if (part.type === \"integer\" || part.type === \"fraction\") {\n      for (const char of part.value) {\n        const digit = formatter.glyphs.indexOf(char);\n        if (digit < 0) pushChar(part.type, char);\n        else if (part.type === \"integer\")\n          slots.push({\n            key: `i${integerDigits - 1 - integerIndex++}`,\n            kind: \"digit\",\n            digit,\n            order: 0,\n          });\n        else\n          slots.push({\n            key: `f${fractionIndex++}`,\n            kind: \"digit\",\n            digit,\n            order: 0,\n          });\n      }\n    } else if (part.type === \"group\") {\n      slots.push({\n        key: `g${integerDigits - integerIndex}:${part.value}`,\n        kind: \"char\",\n        char: part.value,\n      });\n    } else {\n      pushChar(part.type, part.value);\n    }\n  }\n  // Stagger from the rightmost digit outward, like a carry moving left.\n  let order = 0;\n  for (let i = slots.length - 1; i >= 0; i--) {\n    const slot = slots[i];\n    if (slot.kind === \"digit\") slots[i] = { ...slot, order: order++ };\n  }\n  return { text: parts.map((part) => part.value).join(\"\"), slots };\n}\n\n/** Keep removed slots in place for one transition so they can collapse out. */\nfunction mergeSlots(previous: Item[], next: Slot[], animate: boolean): Item[] {\n  const previousKeys = new Set(previous.map((item) => item.key));\n  const live: Item[] = next.map((slot) => ({\n    ...slot,\n    phase: animate && !previousKeys.has(slot.key) ? \"enter\" : \"idle\",\n  }));\n  if (!animate) return live;\n  const nextKeys = new Set(next.map((slot) => slot.key));\n  const leadingExits = new Map<string, Item[]>();\n  let pending: Item[] = [];\n  for (const item of previous) {\n    if (nextKeys.has(item.key)) {\n      if (pending.length) leadingExits.set(item.key, pending);\n      pending = [];\n    } else if (item.phase !== \"exit\") {\n      pending.push({ ...item, phase: \"exit\" });\n    }\n  }\n  const merged: Item[] = [];\n  for (const item of live) {\n    const exits = leadingExits.get(item.key);\n    if (exits) merged.push(...exits);\n    merged.push(item);\n  }\n  return merged.concat(pending);\n}\n\nfunction zeroed(slots: Slot[]): Slot[] {\n  return slots.map((slot) =>\n    slot.kind === \"digit\" ? { ...slot, digit: 0 } : slot,\n  );\n}\n\ninterface TickerState {\n  signature: string;\n  value: number;\n  items: Item[];\n  direction: number;\n  flash: \"up\" | \"down\" | null;\n  version: number;\n}\n\n/** An odometer-style number: each digit rolls on its own wheel when `value` changes. */\nexport function NumberTicker({\n  value,\n  format = \"number\",\n  formatOptions,\n  locale = \"en-US\",\n  currency = \"USD\",\n  prefix,\n  suffix,\n  duration = 800,\n  highlightChanges = false,\n  animateOnMount = false,\n  className,\n  ...props\n}: NumberTickerProps) {\n  const reduced = usePrefersReducedMotion();\n  const optionsKey = JSON.stringify(formatOptions ?? null);\n  const formatter = useMemo(\n    () => getFormatter(locale, resolveOptions(format, currency, formatOptions)),\n    // formatOptions is compared by content so inline objects stay cheap.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [locale, format, currency, optionsKey],\n  );\n  const { text, slots } = useMemo(\n    () => toSlots(value, formatter),\n    [value, formatter],\n  );\n\n  const [armed, setArmed] = useState(!animateOnMount);\n  const shown = armed ? slots : zeroed(slots);\n  const signature = (armed ? \"\" : \"0|\") + shown.map(slotKey).join(\"|\");\n  const shownValue = armed ? value : 0;\n\n  const [state, setState] = useState<TickerState>(() => ({\n    signature,\n    value: shownValue,\n    items: shown.map((slot) => ({ ...slot, phase: \"idle\" })),\n    direction: 0,\n    flash: null,\n    version: 0,\n  }));\n  if (state.signature !== signature) {\n    const direction = Math.sign(shownValue - state.value);\n    // The first roll up from zero is an entrance, not a change worth tinting.\n    const entrance = state.signature.startsWith(\"0|\");\n    setState({\n      signature,\n      value: shownValue,\n      items: mergeSlots(state.items, shown, !reduced),\n      direction,\n      flash:\n        highlightChanges && !entrance && direction !== 0\n          ? direction > 0\n            ? \"up\"\n            : \"down\"\n          : null,\n      version: state.version + 1,\n    });\n  }\n\n  // Roll up from zero after the first paint (or settle at once without motion).\n  useLayoutEffect(() => {\n    if (armed) return;\n    if (reduced) {\n      setArmed(true);\n      return;\n    }\n    let inner = 0;\n    const outer = requestAnimationFrame(() => {\n      inner = requestAnimationFrame(() => setArmed(true));\n    });\n    return () => {\n      cancelAnimationFrame(outer);\n      cancelAnimationFrame(inner);\n    };\n  }, [armed, reduced]);\n\n  // Drop collapsed slots and fade the tint once the roll has settled.\n  const { version } = state;\n  const hasExits = state.items.some((item) => item.phase === \"exit\");\n  useEffect(() => {\n    if (!hasExits) return;\n    const timer = window.setTimeout(\n      () =>\n        setState((current) =>\n          current.version === version\n            ? {\n                ...current,\n                items: current.items.filter((item) => item.phase !== \"exit\"),\n              }\n            : current,\n        ),\n      duration + MAX_STAGGER,\n    );\n    return () => window.clearTimeout(timer);\n  }, [version, hasExits, duration]);\n  const flashing = state.flash !== null;\n  useEffect(() => {\n    if (!flashing) return;\n    const timer = window.setTimeout(\n      () =>\n        setState((current) =>\n          current.version === version ? { ...current, flash: null } : current,\n        ),\n      Math.max(360, duration * 0.75),\n    );\n    return () => window.clearTimeout(timer);\n  }, [version, flashing, duration]);\n\n  const animate = !reduced;\n  return (\n    <span\n      data-slot=\"number-ticker\"\n      data-direction={\n        state.direction > 0 ? \"up\" : state.direction < 0 ? \"down\" : undefined\n      }\n      className={cn(\"inline-block whitespace-nowrap tabular-nums\", className)}\n      {...props}\n    >\n      {prefix}\n      <span className=\"sr-only\">{text}</span>\n      {/* Digits always run left to right, even inside right-to-left text. */}\n      <span\n        aria-hidden=\"true\"\n        dir=\"ltr\"\n        data-slot=\"number-ticker-value\"\n        className={cn(\n          \"transition-colors motion-reduce:transition-none\",\n          state.flash === \"up\" && \"text-emerald-700 dark:text-emerald-400\",\n          state.flash === \"down\" && \"text-red-600 dark:text-red-400\",\n        )}\n        style={{ transitionDuration: state.flash ? \"140ms\" : \"900ms\" }}\n      >\n        {state.items.map((item) => (\n          <TickerSlot\n            key={item.key}\n            item={item}\n            direction={state.direction}\n            formatter={formatter}\n            duration={duration}\n            animate={animate}\n          />\n        ))}\n      </span>\n      {suffix}\n    </span>\n  );\n}\n\nfunction slotKey(slot: Slot) {\n  return slot.kind === \"digit\" ? `${slot.key}=${slot.digit}` : slot.key;\n}\n\nfunction TickerSlot({\n  item,\n  direction,\n  formatter,\n  duration,\n  animate,\n}: {\n  item: Item;\n  direction: number;\n  formatter: TickerFormatter;\n  duration: number;\n  animate: boolean;\n}) {\n  // New slots mount collapsed, then open on the next frame so the change transitions.\n  const [open, setOpen] = useState(item.phase !== \"enter\" || !animate);\n  useEffect(() => {\n    if (open) return;\n    let inner = 0;\n    const outer = requestAnimationFrame(() => {\n      inner = requestAnimationFrame(() => setOpen(true));\n    });\n    return () => {\n      cancelAnimationFrame(outer);\n      cancelAnimationFrame(inner);\n    };\n  }, [open]);\n\n  const collapsed = !open || item.phase === \"exit\";\n  const travel = direction < 0 ? -1 : 1;\n  const offset = item.phase === \"exit\" ? -travel : travel;\n  const delay =\n    item.kind === \"digit\" ? Math.min(item.order * STAGGER, MAX_STAGGER) : 0;\n  const style: CSSProperties = {\n    gridTemplateColumns: collapsed ? \"0fr\" : \"1fr\",\n    opacity: collapsed ? 0 : 1,\n    transform: collapsed ? `translateY(${offset * 0.42}em)` : undefined,\n    transition: animate\n      ? `grid-template-columns ${duration * 0.7}ms ${SIZE_EASE}, opacity ${duration * 0.5}ms ease, transform ${duration}ms ${SLIDE_EASE}`\n      : \"none\",\n  };\n  return (\n    <span className=\"inline-grid\" style={style} data-phase={item.phase}>\n      <span className=\"min-w-0 [clip-path:inset(-50%_0)]\">\n        {item.kind === \"digit\" ? (\n          <DigitWheel\n            digit={item.digit}\n            direction={direction}\n            formatter={formatter}\n            duration={duration}\n            delay={delay}\n            animate={animate}\n          />\n        ) : (\n          <span className=\"whitespace-pre\">{item.char}</span>\n        )}\n      </span>\n    </span>\n  );\n}\n\nfunction DigitWheel({\n  digit,\n  direction,\n  formatter,\n  duration,\n  delay,\n  animate,\n}: {\n  digit: number;\n  direction: number;\n  formatter: TickerFormatter;\n  duration: number;\n  delay: number;\n  animate: boolean;\n}) {\n  const [wheel, setWheel] = useState({\n    digit,\n    cell: REST + digit,\n    travel: 0,\n    rolling: false,\n  });\n  if (wheel.digit !== digit) {\n    // Roll forward when the value rises and backward when it falls, wrapping\n    // through 9 → 0 the way a mechanical counter carries.\n    const forward = (digit - wheel.digit + 10) % 10;\n    const backward = (wheel.digit - digit + 10) % 10;\n    const step =\n      direction > 0\n        ? forward\n        : direction < 0\n          ? -backward\n          : forward <= backward\n            ? forward\n            : -backward;\n    let cell = wheel.cell + step;\n    if (cell < 0 || cell >= CELLS) cell = REST + digit;\n    setWheel(\n      animate\n        ? { digit, cell, travel: cell - wheel.cell, rolling: true }\n        : { digit, cell: REST + digit, travel: 0, rolling: false },\n    );\n  }\n\n  // Once settled, jump back to the matching cell in the middle run (same glyph).\n  useEffect(() => {\n    if (!wheel.rolling) return;\n    const timer = window.setTimeout(\n      () =>\n        setWheel((current) => ({\n          digit: current.digit,\n          cell: REST + current.digit,\n          travel: 0,\n          rolling: false,\n        })),\n      duration + delay + 40,\n    );\n    return () => window.clearTimeout(timer);\n  }, [wheel, duration, delay]);\n\n  // Cells carry --ticker-gap of padding above and below, and the clipping window\n  // reaches that far past the line box. At rest only padding shows in the\n  // overhang; while rolling, neighbors fade through it like a real wheel.\n  return (\n    <span className=\"relative inline-block [--ticker-gap:0.2em]\">\n      <span className=\"invisible\">{formatter.glyphs[digit]}</span>\n      <span className=\"absolute inset-x-0 -inset-y-(--ticker-gap) overflow-hidden [mask-image:linear-gradient(to_bottom,transparent,#000_var(--ticker-gap),#000_calc(100%_-_var(--ticker-gap)),transparent)]\">\n        <span\n          className=\"absolute inset-x-0 top-0 flex flex-col text-center\"\n          style={{\n            transform: `translateY(${(-wheel.cell * 100) / CELLS}%)`,\n            transition: wheel.rolling\n              ? `transform ${duration}ms ${rollEase(wheel.travel)} ${delay}ms`\n              : \"none\",\n            willChange: wheel.rolling ? \"transform\" : undefined,\n          }}\n        >\n          {formatter.cells}\n        </span>\n      </span>\n    </span>\n  );\n}\n"
    },
    {
      "path": "src/registry/overtrue/sparkline.tsx",
      "type": "registry:component",
      "target": "components/overtrue/sparkline.tsx",
      "content": "\"use client\";\nimport { useId, type CSSProperties } from \"react\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface SparklineProps {\n  data: number[];\n  label: string;\n  className?: string;\n  filled?: boolean;\n  /** Mark the most recent value. */\n  endpoint?: boolean;\n  /** Any CSS color. Defaults to the current text color, which is primary. */\n  color?: string;\n  /** Draw the line in and raise the area when the sparkline mounts. Skipped under reduced motion. */\n  animate?: boolean;\n}\n\nconst WIDTH = 240;\nconst HEIGHT = 48;\nconst PAD_X = 3;\nconst PAD_Y = 5;\nconst EASE = \"ease-[cubic-bezier(0.22,1,0.36,1)]\";\n\n/** Monotone cubic path: smooth, but never overshoots the data. */\nfunction monotonePath(points: [number, number][]) {\n  const n = points.length;\n  if (n < 2) return \"\";\n  const dx: number[] = [];\n  const slope: number[] = [];\n  for (let i = 0; i < n - 1; i++) {\n    dx.push(points[i + 1][0] - points[i][0]);\n    slope.push((points[i + 1][1] - points[i][1]) / dx[i]);\n  }\n  const tangent = [slope[0]];\n  for (let i = 1; i < n - 1; i++) {\n    tangent.push(\n      slope[i - 1] * slope[i] <= 0 ? 0 : (slope[i - 1] + slope[i]) / 2,\n    );\n  }\n  tangent.push(slope[n - 2]);\n  for (let i = 0; i < n - 1; i++) {\n    if (slope[i] === 0) {\n      tangent[i] = tangent[i + 1] = 0;\n      continue;\n    }\n    const a = tangent[i] / slope[i];\n    const b = tangent[i + 1] / slope[i];\n    const h = a * a + b * b;\n    if (h > 9) {\n      const t = 3 / Math.sqrt(h);\n      tangent[i] = t * a * slope[i];\n      tangent[i + 1] = t * b * slope[i];\n    }\n  }\n  const r = (value: number) => Math.round(value * 100) / 100;\n  let d = `M${r(points[0][0])},${r(points[0][1])}`;\n  for (let i = 0; i < n - 1; i++) {\n    const [x0, y0] = points[i];\n    const [x1, y1] = points[i + 1];\n    const h = dx[i] / 3;\n    d += `C${r(x0 + h)},${r(y0 + tangent[i] * h)} ${r(x1 - h)},${r(y1 - tangent[i + 1] * h)} ${r(x1)},${r(y1)}`;\n  }\n  return d;\n}\n\n/** A compact overview. Use a full chart when individual values need inspection. */\nexport function Sparkline({\n  data,\n  label,\n  className,\n  filled = true,\n  endpoint = true,\n  color,\n  animate = true,\n}: SparklineProps) {\n  const gradient = `sparkline-${useId().replace(/:/g, \"\")}`;\n  const values = data.filter(Number.isFinite);\n  let low = Infinity,\n    high = -Infinity;\n  for (const value of values) {\n    low = Math.min(low, value);\n    high = Math.max(high, value);\n  }\n  const points = values.map((value, i): [number, number] => [\n    values.length > 1\n      ? PAD_X + (i / (values.length - 1)) * (WIDTH - PAD_X * 2)\n      : WIDTH / 2,\n    high === low\n      ? HEIGHT / 2\n      : HEIGHT - PAD_Y - ((value - low) / (high - low)) * (HEIGHT - PAD_Y * 2),\n  ]);\n  const line = monotonePath(points);\n  const last = points[points.length - 1];\n  const lastValue = values[values.length - 1];\n  const motion = animate ? \"motion-reduce:transition-none\" : \"transition-none\";\n  return (\n    <div\n      data-slot=\"sparkline\"\n      role=\"img\"\n      aria-label={`${label}: ${values.length ? values.join(\", \") : \"No data\"}`}\n      className={cn(\"relative h-12 w-full text-primary\", className)}\n      style={color ? { color } : undefined}\n    >\n      {values.length > 1 && filled && (\n        <svg\n          viewBox={`0 0 ${WIDTH} ${HEIGHT}`}\n          preserveAspectRatio=\"none\"\n          aria-hidden=\"true\"\n          data-slot=\"sparkline-area\"\n          className={cn(\n            \"absolute inset-0 size-full origin-bottom overflow-visible transition-[opacity,scale] delay-75 duration-700\",\n            EASE,\n            animate && \"starting:scale-y-0 starting:opacity-0\",\n            motion,\n          )}\n        >\n          <defs>\n            <linearGradient id={gradient} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n              <stop offset=\"0%\" stopColor=\"currentColor\" stopOpacity=\"0.28\" />\n              <stop offset=\"100%\" stopColor=\"currentColor\" stopOpacity=\"0\" />\n            </linearGradient>\n          </defs>\n          <path\n            d={`${line}L${last[0]},${HEIGHT}L${points[0][0]},${HEIGHT}Z`}\n            fill={`url(#${gradient})`}\n            className={cn(\"transition-[d] duration-500\", EASE, motion)}\n          />\n        </svg>\n      )}\n      <svg\n        viewBox={`0 0 ${WIDTH} ${HEIGHT}`}\n        preserveAspectRatio=\"none\"\n        aria-hidden=\"true\"\n        data-slot=\"sparkline-line\"\n        className={cn(\n          // The line wipes in from the left; the inset leaves room for its glow.\n          \"absolute inset-0 size-full overflow-visible [clip-path:inset(-60%_-8%_-60%_-8%)] transition-[clip-path] duration-700\",\n          EASE,\n          animate &&\n            values.length > 1 &&\n            \"starting:[clip-path:inset(-60%_100%_-60%_-8%)]\",\n          motion,\n        )}\n      >\n        {values.length > 1 ? (\n          <path\n            d={line}\n            fill=\"none\"\n            stroke=\"currentColor\"\n            strokeWidth=\"2\"\n            strokeLinejoin=\"round\"\n            strokeLinecap=\"round\"\n            vectorEffect=\"non-scaling-stroke\"\n            className={cn(\n              \"transition-[d] duration-500 dark:[filter:drop-shadow(0_0_6px_color-mix(in_oklab,currentColor_50%,transparent))]\",\n              EASE,\n              motion,\n            )}\n          />\n        ) : values.length === 0 ? (\n          <path\n            d={`M${PAD_X} ${HEIGHT / 2}H${WIDTH - PAD_X}`}\n            stroke=\"currentColor\"\n            strokeDasharray=\"2 5\"\n            strokeLinecap=\"round\"\n            opacity=\"0.3\"\n            vectorEffect=\"non-scaling-stroke\"\n          />\n        ) : null}\n      </svg>\n      {/* Drawn in HTML so the marker stays round when the line stretches. */}\n      {endpoint && last && (\n        <span\n          aria-hidden=\"true\"\n          data-slot=\"sparkline-endpoint\"\n          className={cn(\n            // Moves with the line, and on mount appears once the line has drawn in.\n            \"absolute -translate-x-1/2 -translate-y-1/2 [transition:left_500ms_cubic-bezier(0.22,1,0.36,1),top_500ms_cubic-bezier(0.22,1,0.36,1),opacity_300ms_ease-out_550ms,scale_500ms_cubic-bezier(0.22,1,0.36,1)_550ms]\",\n            animate && \"starting:scale-0 starting:opacity-0\",\n            motion,\n          )}\n          style={\n            {\n              left: `${(last[0] / WIDTH) * 100}%`,\n              top: `${(last[1] / HEIGHT) * 100}%`,\n            } as CSSProperties\n          }\n        >\n          {/* Pulses once whenever the latest value changes. */}\n          <span\n            key={lastValue}\n            className={cn(\n              \"absolute inset-0 scale-[3.2] rounded-full bg-current opacity-0 transition-[opacity,scale] duration-1000 ease-out starting:scale-100 starting:opacity-40 motion-reduce:hidden\",\n              !animate && \"hidden\",\n            )}\n          />\n          <span className=\"relative block size-2 rounded-full border-[1.5px] border-card bg-current shadow-[0_0_0_3px_color-mix(in_oklab,currentColor_18%,transparent)] dark:shadow-[0_0_0_3px_color-mix(in_oklab,currentColor_24%,transparent),0_0_12px_1px_color-mix(in_oklab,currentColor_70%,transparent)]\" />\n        </span>\n      )}\n    </div>\n  );\n}\n"
    },
    {
      "path": "src/registry/overtrue/delta-badge.tsx",
      "type": "registry:component",
      "target": "components/overtrue/delta-badge.tsx",
      "content": "/** Adapted from dashboardcn (MIT), copyright 2026 dashboardcn contributors.\n * Source: https://github.com/NoahGdev/dashboardcn/tree/b1ffacbca0f7a0be60135c8665b9e8c267205c48\n *\n * MIT License\n *\n * Copyright (c) 2026 dashboardcn contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * ---\n *\n * Portions of this project are derived from shadcn/ui and shadcn/registry-template\n * (https://github.com/shadcn-ui/ui), Copyright (c) 2023 shadcn, licensed under the\n * MIT License. The notice above applies to those portions as well.\n */\nimport * as React from \"react\";\nimport {\n  IconArrowDownRight as ArrowDownRight,\n  IconArrowUpRight as ArrowUpRight,\n  IconMinus as Minus,\n} from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\nimport { formatDelta } from \"./metric-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))\n    return \"flat\";\n  return delta > 0 ? \"up\" : \"down\";\n}\n\nconst directionIcon: Record<DeltaDirection, React.ElementType> = {\n  up: ArrowUpRight,\n  down: ArrowDownRight,\n  flat: Minus,\n};\n\ntype Tone = \"positive\" | \"negative\" | \"neutral\";\n\nconst toneText: Record<Tone, string> = {\n  positive: \"text-emerald-700 dark:text-emerald-400\",\n  negative: \"text-rose-700 dark:text-rose-400\",\n  neutral: \"text-muted-foreground\",\n};\n\nconst toneSoft: Record<Tone, string> = {\n  positive: \"bg-emerald-500/10 dark:bg-emerald-400/10\",\n  negative: \"bg-rose-500/10 dark:bg-rose-400/10\",\n  neutral: \"bg-muted dark:bg-muted/70\",\n};\n\nconst toneOutline: Record<Tone, string> = {\n  positive:\n    \"bg-emerald-500/[0.06] ring-emerald-600/20 dark:bg-emerald-400/[0.07] dark:ring-emerald-400/25\",\n  negative:\n    \"bg-rose-500/[0.06] ring-rose-600/20 dark:bg-rose-400/[0.07] dark:ring-rose-400/25\",\n  neutral: \"bg-muted/40 ring-border\",\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\n/** A change chip: the arrow shows direction, the color shows whether it helps. */\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 =\n    direction === \"flat\" ? null : (direction === \"up\") !== invert;\n  const tone: Tone =\n    positive === true\n      ? \"positive\"\n      : positive === false\n        ? \"negative\"\n        : \"neutral\";\n  const Icon = directionIcon[direction];\n  const pill = variant !== \"text\";\n\n  return (\n    <span\n      data-slot=\"delta-badge\"\n      data-direction={direction}\n      data-positive={positive}\n      data-variant={variant}\n      className={cn(\n        \"inline-flex shrink-0 items-center gap-0.5 text-xs leading-none font-medium tracking-[-0.01em] whitespace-nowrap tabular-nums\",\n        pill && \"h-5 rounded-full\",\n        pill && (showIcon ? \"pr-1.5 pl-1\" : \"px-1.5\"),\n        variant === \"outline\" && [\"ring-1 ring-inset\", toneOutline[tone]],\n        variant === \"soft\" && toneSoft[tone],\n        toneText[tone],\n        className,\n      )}\n      {...props}\n    >\n      {showIcon ? (\n        <Icon\n          data-slot=\"delta-badge-icon\"\n          className=\"size-3 shrink-0\"\n          stroke={2.5}\n          aria-hidden=\"true\"\n        />\n      ) : null}\n      {children ?? formatDelta(delta)}\n    </span>\n  );\n}\n\nexport { DeltaBadge };\n"
    },
    {
      "path": "src/registry/overtrue/metric-format.tsx",
      "type": "registry:component",
      "target": "components/overtrue/metric-format.tsx",
      "content": "/** Adapted from dashboardcn (MIT), copyright 2026 dashboardcn contributors.\n * Source: https://github.com/NoahGdev/dashboardcn/tree/b1ffacbca0f7a0be60135c8665b9e8c267205c48\n *\n * MIT License\n *\n * Copyright (c) 2026 dashboardcn contributors\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * ---\n *\n * Portions of this project are derived from shadcn/ui and shadcn/registry-template\n * (https://github.com/shadcn-ui/ui), Copyright (c) 2023 shadcn, licensed under the\n * MIT License. The notice above applies to those portions as well.\n */\nexport 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"
    },
    {
      "path": "src/registry/overtrue/waterfall-chart.tsx",
      "type": "registry:component",
      "target": "components/overtrue/waterfall-chart.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/**\n * start sets the running total, delta moves it, subtotal and end show it.\n * Defaults to \"delta\".\n */\nexport type WaterfallStepKind = \"start\" | \"delta\" | \"subtotal\" | \"end\";\n\nexport interface WaterfallStep {\n  id: string;\n  label: string;\n  /**\n   * The opening amount for a start step, or the signed change for a delta.\n   * Subtotal and end steps always show the running total, so the bridge balances.\n   */\n  value: number;\n  kind?: WaterfallStepKind;\n}\n\nexport type WaterfallDirection = \"increase\" | \"decrease\" | \"total\";\n\n/** Where a value is shown: bar labels, axis ticks, or the tooltip and table. */\nexport type WaterfallFormatContext = \"label\" | \"axis\" | \"detail\";\n\nexport interface WaterfallStepInfo {\n  index: number;\n  kind: WaterfallStepKind;\n  direction: WaterfallDirection;\n  /** Signed change for a delta; the total for start, subtotal and end. */\n  change: number;\n  /** Running total before and after the step. Totals run from 0. */\n  from: number;\n  to: number;\n  /** The change with its sign, or the total, formatted for the tooltip. */\n  formattedChange: string;\n  /** The running total after the step, formatted for the tooltip. */\n  formattedTotal: string;\n  /** Change relative to the opening total, when there is one. */\n  shareOfStart: number | null;\n  /** The bar color. */\n  color: string;\n}\n\nexport interface WaterfallChartColors {\n  /** Any CSS color. Defaults to emerald. */\n  increase?: string;\n  /** Any CSS color. Defaults to the destructive color. */\n  decrease?: string;\n  /** Any CSS color for start, subtotal and end bars. Defaults to the primary color. */\n  total?: string;\n}\n\nexport type WaterfallOrientation = \"vertical\" | \"horizontal\" | \"auto\";\n\n/** The figures behind the summary line, passed to `renderSummary`. */\nexport interface WaterfallTotals {\n  /** The first start step's value, or null when the bridge has no start. */\n  opening: number | null;\n  /** The running total after the last step. */\n  closing: number;\n  /** closing − opening, or null without an opening total. */\n  net: number | null;\n  /** net as a share of the opening total, or null. */\n  netShare: number | null;\n  /** The chart's formatter, with a leading − for negative values. */\n  format: (value: number, context: WaterfallFormatContext) => string;\n}\n\nexport interface WaterfallChartProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"title\" | \"onSelect\" | \"children\"\n> {\n  steps: WaterfallStep[];\n  /**\n   * Columns, rows, or \"auto\": columns when the card is wide enough for every step\n   * and rows below that, switched with a container query. Defaults to \"auto\".\n   */\n  orientation?: WaterfallOrientation;\n  /**\n   * Formats an amount. It always receives a non-negative number; the chart adds\n   * + and − itself. Defaults to compact numbers, and grouped digits in the tooltip.\n   */\n  valueFormatter?: (value: number, context: WaterfallFormatContext) => string;\n  title?: React.ReactNode;\n  description?: React.ReactNode;\n  /** Controls placed at the top right. */\n  actions?: React.ReactNode;\n  /** Plot height in pixels for columns. Rows size themselves. Defaults to 280. */\n  height?: number;\n  colors?: WaterfallChartColors;\n  /**\n   * \"auto\" starts the value axis just below the lowest running total when every\n   * total is far from zero, and marks the cut on total bars. \"zero\" always starts at 0.\n   */\n  baseline?: \"auto\" | \"zero\";\n  /** Show the closing total and net change under the title. Defaults to true. */\n  showSummary?: boolean;\n  /** Replace the summary line, e.g. to show a margin instead of the net change. */\n  renderSummary?: (totals: WaterfallTotals) => React.ReactNode;\n  /** Show the increase, decrease and total key. Defaults to true. */\n  showLegend?: boolean;\n  /** Replace the tooltip content for a hovered or focused step. */\n  renderTooltip?: (\n    step: WaterfallStep,\n    info: WaterfallStepInfo,\n  ) => React.ReactNode;\n  /** Called when a step is clicked or activated with Enter. */\n  onSelect?: (step: WaterfallStep, info: WaterfallStepInfo) => void;\n}\n\ninterface Row {\n  step: WaterfallStep;\n  info: WaterfallStepInfo;\n  /** Ends of the bar in data units, low to high. */\n  low: number;\n  high: number;\n  /** Whether the bar is cut by a raised baseline. */\n  cut: boolean;\n  /** Whether a connector runs from this bar to the next one. */\n  connects: boolean;\n}\n\nconst MINUS = \"−\";\nconst compactNumber = new Intl.NumberFormat(\"en-US\", {\n  notation: \"compact\",\n  maximumFractionDigits: 1,\n});\nconst exactNumber = new Intl.NumberFormat(\"en-US\", {\n  maximumFractionDigits: 2,\n});\nconst sharePercent = new Intl.NumberFormat(\"en-US\", {\n  style: \"percent\",\n  maximumFractionDigits: 1,\n  signDisplay: \"exceptZero\",\n});\n\nfunction defaultFormatter(value: number, context: WaterfallFormatContext) {\n  return context === \"detail\"\n    ? exactNumber.format(value)\n    : compactNumber.format(value);\n}\n\nconst DEFAULT_INCREASE = \"var(--color-emerald-500, oklch(69.6% 0.17 162.48))\";\nconst DEFAULT_DECREASE = \"var(--color-destructive)\";\nconst DEFAULT_TOTAL = \"var(--color-primary)\";\n\n/** Container widths where columns take over from rows, by step count. */\nconst AUTO_SWITCH = [\n  {\n    upTo: 4,\n    columns: \"hidden @min-[20rem]/waterfall:block\",\n    rows: \"@min-[20rem]/waterfall:hidden\",\n  },\n  {\n    upTo: 5,\n    columns: \"hidden @min-[24rem]/waterfall:block\",\n    rows: \"@min-[24rem]/waterfall:hidden\",\n  },\n  {\n    upTo: 6,\n    columns: \"hidden @min-[28rem]/waterfall:block\",\n    rows: \"@min-[28rem]/waterfall:hidden\",\n  },\n  {\n    upTo: 7,\n    columns: \"hidden @min-[32rem]/waterfall:block\",\n    rows: \"@min-[32rem]/waterfall:hidden\",\n  },\n  {\n    upTo: 8,\n    columns: \"hidden @min-[36rem]/waterfall:block\",\n    rows: \"@min-[36rem]/waterfall:hidden\",\n  },\n  {\n    upTo: 10,\n    columns: \"hidden @min-[44rem]/waterfall:block\",\n    rows: \"@min-[44rem]/waterfall:hidden\",\n  },\n  {\n    upTo: Infinity,\n    columns: \"hidden @min-[54rem]/waterfall:block\",\n    rows: \"@min-[54rem]/waterfall:hidden\",\n  },\n];\n\nconst kindLabel: Record<WaterfallStepKind, string> = {\n  start: \"Opening total\",\n  delta: \"Change\",\n  subtotal: \"Subtotal\",\n  end: \"Closing total\",\n};\n\nconst finite = (value: number) => (Number.isFinite(value) ? value : 0);\n\nfunction niceStep(span: number, count: number) {\n  const raw = span / Math.max(1, count);\n  if (!(raw > 0)) return 1;\n  const magnitude = 10 ** Math.floor(Math.log10(raw));\n  const step = [1, 2, 2.5, 5, 10].find((n) => raw <= n * magnitude) ?? 10;\n  return step * magnitude;\n}\n\n/**\n * The visible range and its ticks. With a raised baseline the range starts a little\n * below the lowest running total so the changes, not the totals, fill the plot.\n */\nfunction scaleFor(\n  rows: Omit<Row, \"cut\" | \"connects\">[],\n  baseline: \"auto\" | \"zero\",\n) {\n  let low = Infinity;\n  let high = -Infinity;\n  let totalLow = Infinity;\n  for (const row of rows) {\n    if (row.info.direction === \"total\") {\n      totalLow = Math.min(totalLow, row.info.to);\n      low = Math.min(low, row.info.to);\n      high = Math.max(high, row.info.to);\n    } else {\n      low = Math.min(low, row.low);\n      high = Math.max(high, row.high);\n    }\n  }\n  if (!Number.isFinite(low))\n    return { min: 0, max: 1, ticks: [0, 1], raised: false };\n  let min = Math.min(0, low);\n  let max = Math.max(0, high);\n  let raised = false;\n  if (baseline === \"auto\" && low > 0 && totalLow > 0 && low / high > 0.35) {\n    // Leave room under the lowest total so short bars still read as bars.\n    min = Math.max(0, low - (high - low) * 0.55);\n    raised = true;\n  }\n  const step = niceStep(max - min, 4);\n  const start = Math.floor(min / step) * step;\n  const end = Math.ceil(max / step) * step || step;\n  const ticks: number[] = [];\n  for (let tick = start; tick <= end + step / 2; tick += step)\n    ticks.push(Math.round(tick / step) * step);\n  return { min: start, max: end, ticks, raised: raised && start > 0 };\n}\n\nconst reveal =\n  \"motion-safe:animate-[waterfall-rise_620ms_cubic-bezier(0.22,1,0.36,1)_backwards]\";\nconst fadeUp =\n  \"motion-safe:animate-[waterfall-fade_420ms_cubic-bezier(0.22,1,0.36,1)_backwards]\";\nconst draw =\n  \"motion-safe:animate-[waterfall-draw_360ms_cubic-bezier(0.22,1,0.36,1)_backwards]\";\n\n/** Two short card-colored strokes across a bar whose bottom is cut by a raised axis. */\nfunction CutMark({ horizontal }: { horizontal?: boolean }) {\n  return (\n    <svg\n      aria-hidden=\"true\"\n      viewBox=\"0 0 10 10\"\n      preserveAspectRatio=\"none\"\n      className={cn(\n        \"pointer-events-none absolute\",\n        horizontal\n          ? \"inset-y-0 left-1.5 h-full w-2\"\n          : \"inset-x-0 bottom-1.5 h-2 w-full\",\n      )}\n    >\n      {horizontal ? (\n        <>\n          <path\n            d=\"M3 0 L1 10\"\n            stroke=\"var(--color-card)\"\n            strokeWidth=\"1.5\"\n            vectorEffect=\"non-scaling-stroke\"\n          />\n          <path\n            d=\"M8 0 L6 10\"\n            stroke=\"var(--color-card)\"\n            strokeWidth=\"1.5\"\n            vectorEffect=\"non-scaling-stroke\"\n          />\n        </>\n      ) : (\n        <>\n          <path\n            d=\"M0 4 L10 2\"\n            stroke=\"var(--color-card)\"\n            strokeWidth=\"1.5\"\n            vectorEffect=\"non-scaling-stroke\"\n          />\n          <path\n            d=\"M0 9 L10 7\"\n            stroke=\"var(--color-card)\"\n            strokeWidth=\"1.5\"\n            vectorEffect=\"non-scaling-stroke\"\n          />\n        </>\n      )}\n    </svg>\n  );\n}\n\n/**\n * A waterfall (bridge) chart: an opening total, the changes that move it, optional\n * subtotals, and the closing total. Bars rise in sequence on mount; hover or focus a\n * step for a crosshair at its running total and a readout of the change.\n */\nfunction WaterfallChart({\n  steps,\n  orientation = \"auto\",\n  valueFormatter = defaultFormatter,\n  title,\n  description,\n  actions,\n  height = 280,\n  colors,\n  baseline = \"auto\",\n  showSummary = true,\n  showLegend = true,\n  renderSummary,\n  renderTooltip,\n  onSelect,\n  className,\n  ...props\n}: WaterfallChartProps) {\n  const [hovered, setHovered] = React.useState<number | null>(null);\n  const [focused, setFocused] = React.useState<number | null>(null);\n  const [cursor, setCursor] = React.useState(0);\n\n  const increase = colors?.increase ?? DEFAULT_INCREASE;\n  const decrease = colors?.decrease ?? DEFAULT_DECREASE;\n  const total = colors?.total ?? DEFAULT_TOTAL;\n  const subtotalFill = `color-mix(in oklab, ${total} 52%, var(--color-card))`;\n\n  const format = React.useCallback(\n    (value: number, context: WaterfallFormatContext) =>\n      `${value < 0 ? MINUS : \"\"}${valueFormatter(Math.abs(value), context)}`,\n    [valueFormatter],\n  );\n  const signed = React.useCallback(\n    (value: number, context: WaterfallFormatContext) =>\n      `${value < 0 ? MINUS : \"+\"}${valueFormatter(Math.abs(value), context)}`,\n    [valueFormatter],\n  );\n\n  const { rows, scale, opening, closing } = React.useMemo(() => {\n    let running = 0;\n    let opening: number | null = null;\n    const base = steps.map((step, index) => {\n      const kind = step.kind ?? \"delta\";\n      const value = finite(step.value);\n      let from = 0;\n      let to = 0;\n      if (kind === \"start\") {\n        to = value;\n        running = value;\n        if (opening == null) opening = value;\n      } else if (kind === \"delta\") {\n        from = running;\n        to = running + value;\n        running = to;\n      } else {\n        to = running;\n      }\n      const direction: WaterfallDirection =\n        kind === \"delta\" ? (value < 0 ? \"decrease\" : \"increase\") : \"total\";\n      const change = kind === \"delta\" ? value : to;\n      const color =\n        direction === \"increase\"\n          ? increase\n          : direction === \"decrease\"\n            ? decrease\n            : kind === \"subtotal\"\n              ? subtotalFill\n              : total;\n      const info: WaterfallStepInfo = {\n        index,\n        kind,\n        direction,\n        change,\n        from,\n        to,\n        formattedChange:\n          kind === \"delta\"\n            ? signed(change, \"detail\")\n            : format(change, \"detail\"),\n        formattedTotal: format(to, \"detail\"),\n        shareOfStart:\n          opening && kind === \"delta\"\n            ? change / opening\n            : opening && kind !== \"start\"\n              ? (to - opening) / opening\n              : null,\n        color,\n      };\n      return {\n        step,\n        info,\n        low: Math.min(from, to),\n        high: Math.max(from, to),\n      };\n    });\n    const scale = scaleFor(base, baseline);\n    const rows: Row[] = base.map((row, index) => {\n      const next = base[index + 1];\n      return {\n        ...row,\n        cut: row.info.direction === \"total\" && scale.raised,\n        connects: next != null && next.info.kind !== \"start\",\n      };\n    });\n    const closing = base.length ? base[base.length - 1].info.to : 0;\n    return { rows, scale, opening, closing };\n  }, [\n    steps,\n    baseline,\n    increase,\n    decrease,\n    total,\n    subtotalFill,\n    format,\n    signed,\n  ]);\n\n  const span = scale.max - scale.min || 1;\n  /** Distance from the low end of the axis, as a percentage. */\n  const position = (value: number) =>\n    ((Math.min(scale.max, Math.max(scale.min, value)) - scale.min) / span) *\n    100;\n\n  const active = hovered ?? focused;\n  const activeRow = active != null ? rows[active] : null;\n  const count = rows.length;\n  const auto = AUTO_SWITCH.find((entry) => count <= entry.upTo)!;\n  const net = opening != null ? closing - opening : null;\n\n  const largest = (direction: WaterfallDirection) =>\n    rows\n      .filter((row) => row.info.direction === direction)\n      .sort((a, b) => Math.abs(b.info.change) - Math.abs(a.info.change))[0];\n  const topIncrease = largest(\"increase\");\n  const topDecrease = largest(\"decrease\");\n  const titleText = typeof title === \"string\" ? title : \"Waterfall chart\";\n  const summary = [\n    `${titleText}.`,\n    opening != null ? `Starts at ${format(opening, \"detail\")}` : null,\n    count ? `ends at ${format(closing, \"detail\")}` : null,\n    net != null && opening\n      ? `(${signed(net, \"detail\")}, ${sharePercent.format(net / opening)}).`\n      : null,\n    topIncrease\n      ? `Largest increase: ${topIncrease.step.label}, ${topIncrease.info.formattedChange}.`\n      : null,\n    topDecrease\n      ? `Largest decrease: ${topDecrease.step.label}, ${topDecrease.info.formattedChange}.`\n      : null,\n  ]\n    .filter(Boolean)\n    .join(\" \");\n\n  const select = (index: number) => {\n    const row = rows[index];\n    if (row && onSelect) onSelect(row.step, row.info);\n  };\n\n  const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    const keys: Record<string, number> = {\n      ArrowRight: 1,\n      ArrowDown: 1,\n      ArrowLeft: -1,\n      ArrowUp: -1,\n    };\n    let next: number | null = null;\n    if (event.key in keys) next = (focused ?? cursor) + keys[event.key];\n    else if (event.key === \"Home\") next = 0;\n    else if (event.key === \"End\") next = count - 1;\n    else if ((event.key === \"Enter\" || event.key === \" \") && focused != null) {\n      event.preventDefault();\n      select(focused);\n      return;\n    } else if (event.key === \"Escape\") {\n      setFocused(null);\n      return;\n    }\n    if (next == null || !count) return;\n    event.preventDefault();\n    const clamped = Math.min(count - 1, Math.max(0, next));\n    setCursor(clamped);\n    setFocused(clamped);\n    setHovered(null);\n  };\n\n  const plotProps = (label: string) => ({\n    role: \"img\" as const,\n    tabIndex: count ? 0 : -1,\n    \"aria-label\": `${label} Use the arrow keys to read each step.`,\n    \"aria-roledescription\": \"waterfall chart\",\n    onKeyDown,\n    onFocus: (event: React.FocusEvent<HTMLDivElement>) => {\n      if (\n        event.target === event.currentTarget &&\n        event.currentTarget.matches(\":focus-visible\")\n      )\n        setFocused(cursor);\n    },\n    onBlur: () => setFocused(null),\n    onPointerLeave: () => setHovered(null),\n  });\n\n  const valueText = (row: Row) =>\n    row.info.kind === \"delta\"\n      ? signed(row.info.change, \"label\")\n      : format(row.info.to, \"label\");\n\n  const valueTone = (row: Row) => {\n    if (row.info.direction === \"total\") return \"text-foreground font-semibold\";\n    if (row.info.direction === \"increase\")\n      return colors?.increase ? \"\" : \"text-emerald-700 dark:text-emerald-400\";\n    return colors?.decrease ? \"\" : \"text-rose-600 dark:text-rose-400\";\n  };\n  const valueStyle = (row: Row): React.CSSProperties | undefined =>\n    row.info.direction === \"increase\" && colors?.increase\n      ? { color: colors.increase }\n      : row.info.direction === \"decrease\" && colors?.decrease\n        ? { color: colors.decrease }\n        : undefined;\n\n  const tooltip = (row: Row) =>\n    renderTooltip ? (\n      renderTooltip(row.step, row.info)\n    ) : (\n      <div className=\"flex min-w-36 flex-col gap-1.5\">\n        <div className=\"flex items-center gap-1.5 text-muted-foreground\">\n          <span\n            className=\"h-2.5 w-[3px] shrink-0 rounded-full\"\n            style={{ backgroundColor: row.info.color }}\n          />\n          <span className=\"truncate\">{row.step.label}</span>\n        </div>\n        <div className=\"text-sm leading-none font-semibold tracking-tight whitespace-nowrap tabular-nums\">\n          {row.info.formattedChange}\n          {row.info.shareOfStart != null ? (\n            <span className=\"ml-1.5 font-mono text-[10.5px] font-normal text-muted-foreground\">\n              {sharePercent.format(row.info.shareOfStart)}\n            </span>\n          ) : null}\n        </div>\n        {row.info.kind === \"delta\" ? (\n          <div className=\"flex items-baseline justify-between gap-4 border-t pt-1.5 whitespace-nowrap text-muted-foreground tabular-nums\">\n            <span>Running total</span>\n            <span className=\"font-medium text-foreground\">\n              {row.info.formattedTotal}\n            </span>\n          </div>\n        ) : null}\n      </div>\n    );\n\n  const crosshairValue = activeRow ? activeRow.info.to : null;\n\n  const columns = (\n    <div\n      data-slot=\"waterfall-chart-columns\"\n      className={cn(\n        \"px-4 pt-3 pb-3\",\n        orientation === \"auto\"\n          ? auto.columns\n          : orientation === \"vertical\"\n            ? \"block\"\n            : \"hidden\",\n      )}\n    >\n      <div\n        {...plotProps(summary)}\n        data-slot=\"waterfall-chart-plot\"\n        className=\"group/plot relative rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-4 focus-visible:ring-offset-card\"\n      >\n        <div className=\"relative\" style={{ height }}>\n          {/* Axis and gridlines. */}\n          <div\n            aria-hidden=\"true\"\n            data-slot=\"waterfall-chart-axis\"\n            className=\"absolute inset-x-0 top-6 bottom-6\"\n          >\n            {scale.ticks.map((tick) => (\n              <div\n                key={tick}\n                className=\"absolute inset-x-0 flex items-center\"\n                style={{\n                  bottom: `${position(tick)}%`,\n                  transform: \"translateY(50%)\",\n                }}\n              >\n                <span className=\"w-11 shrink-0 pr-2 text-right font-mono text-[10.5px] leading-none text-muted-foreground tabular-nums\">\n                  {format(tick, \"axis\")}\n                </span>\n                <span\n                  className={cn(\n                    \"h-px flex-1\",\n                    tick === 0 ? \"bg-foreground/25\" : \"bg-border\",\n                  )}\n                />\n              </div>\n            ))}\n            {crosshairValue != null ? (\n              <div\n                data-slot=\"waterfall-chart-crosshair\"\n                className=\"pointer-events-none absolute inset-x-0 z-10 flex items-center\"\n                style={{\n                  bottom: `${position(crosshairValue)}%`,\n                  transform: \"translateY(50%)\",\n                }}\n              >\n                <span className=\"flex w-11 shrink-0 justify-end pr-1\">\n                  <span className=\"rounded-[4px] bg-foreground px-1 py-0.5 font-mono text-[10px] leading-none text-background tabular-nums\">\n                    {format(crosshairValue, \"axis\")}\n                  </span>\n                </span>\n                <span className=\"h-px flex-1 bg-foreground/45\" />\n              </div>\n            ) : null}\n          </div>\n\n          {/* Bars. */}\n          <div\n            className=\"absolute inset-y-0 right-0 left-11 grid\"\n            style={{\n              gridTemplateColumns: `repeat(${Math.max(1, count)}, minmax(0, 1fr))`,\n            }}\n          >\n            {rows.map((row, index) => {\n              const isActive = active === index;\n              const dimmed = active != null && !isActive;\n              const bottom = position(row.low);\n              const top = position(row.high);\n              const delay = 120 + index * 85;\n              // Decreases and negative totals hang from their top edge.\n              const falling =\n                row.info.direction === \"decrease\" ||\n                (row.info.direction === \"total\" && row.info.to < 0);\n              return (\n                <div\n                  key={row.step.id}\n                  data-slot=\"waterfall-chart-step\"\n                  data-direction={row.info.direction}\n                  data-active={isActive || undefined}\n                  className={cn(\"relative\", onSelect && \"cursor-pointer\")}\n                  onPointerEnter={() => setHovered(index)}\n                  onClick={onSelect ? () => select(index) : undefined}\n                >\n                  <div\n                    aria-hidden=\"true\"\n                    className={cn(\n                      \"absolute inset-x-[8%] inset-y-0 rounded-md bg-foreground/[0.045] opacity-0 transition-opacity duration-150 motion-reduce:transition-none\",\n                      isActive && \"opacity-100\",\n                    )}\n                  />\n                  <div className=\"absolute inset-x-0 top-6 bottom-6\">\n                    <div\n                      data-slot=\"waterfall-chart-bar\"\n                      className={cn(\n                        \"absolute left-1/2 w-[min(34px,58%)] -translate-x-1/2 transition-[opacity,bottom,height] duration-300 motion-reduce:transition-none\",\n                        row.info.direction === \"total\"\n                          ? \"rounded-t-[4px]\"\n                          : \"rounded-[3px]\",\n                        row.info.direction === \"total\" &&\n                          row.low < 0 &&\n                          \"rounded-t-none rounded-b-[4px]\",\n                        dimmed && \"opacity-45\",\n                      )}\n                      style={{\n                        bottom: `${bottom}%`,\n                        height: `max(2px, ${top - bottom}%)`,\n                      }}\n                    >\n                      <div\n                        className={cn(\n                          \"absolute inset-0 rounded-[inherit]\",\n                          reveal,\n                        )}\n                        style={{\n                          backgroundColor: row.info.color,\n                          transformOrigin: falling ? \"top\" : \"bottom\",\n                          animationDelay: `${delay}ms`,\n                        }}\n                      />\n                      {row.cut ? <CutMark /> : null}\n                    </div>\n                    <span\n                      data-slot=\"waterfall-chart-value\"\n                      className={cn(\n                        \"absolute inset-x-0 text-center text-[11px] leading-none whitespace-nowrap tabular-nums transition-opacity duration-150 motion-reduce:transition-none\",\n                        valueTone(row),\n                        fadeUp,\n                        dimmed && \"opacity-50\",\n                      )}\n                      style={{\n                        ...valueStyle(row),\n                        ...(falling\n                          ? { top: `calc(${100 - bottom}% + 6px)` }\n                          : { bottom: `calc(${top}% + 6px)` }),\n                        animationDelay: `${delay + 300}ms`,\n                      }}\n                    >\n                      {valueText(row)}\n                    </span>\n                    {row.connects ? (\n                      <span\n                        aria-hidden=\"true\"\n                        data-slot=\"waterfall-chart-connector\"\n                        className={cn(\n                          \"absolute left-[calc(50%+min(17px,29%))] h-px w-[calc(100%-min(34px,58%))] origin-left bg-foreground/35\",\n                          draw,\n                        )}\n                        style={{\n                          bottom: `${position(row.info.to)}%`,\n                          animationDelay: `${delay + 380}ms`,\n                        }}\n                      />\n                    ) : null}\n                  </div>\n                  {isActive ? (\n                    <div\n                      data-slot=\"waterfall-chart-tooltip\"\n                      className=\"pointer-events-none absolute z-30 rounded-lg border bg-popover px-3 py-2 text-xs whitespace-nowrap text-popover-foreground shadow-lg shadow-black/5\"\n                      style={{\n                        // Beside the bar, level with its top, kept inside the plot.\n                        top: Math.max(\n                          0,\n                          Math.min(\n                            24 + ((100 - top) / 100) * (height - 48) - 6,\n                            height - 88,\n                          ),\n                        ),\n                        [index < count / 2 ? \"left\" : \"right\"]:\n                          \"calc(50% + min(17px, 29%) + 10px)\",\n                      }}\n                    >\n                      {tooltip(row)}\n                    </div>\n                  ) : null}\n                </div>\n              );\n            })}\n          </div>\n        </div>\n\n        {/* Step labels. */}\n        <div\n          aria-hidden=\"true\"\n          className=\"grid pl-11\"\n          style={{\n            gridTemplateColumns: `repeat(${Math.max(1, count)}, minmax(0, 1fr))`,\n          }}\n        >\n          {rows.map((row, index) => (\n            <span\n              key={row.step.id}\n              data-slot=\"waterfall-chart-label\"\n              className={cn(\n                \"line-clamp-2 px-0.5 pt-1 text-center text-[11px] leading-[14px] transition-colors motion-reduce:transition-none\",\n                row.info.direction === \"total\"\n                  ? \"font-medium text-foreground\"\n                  : \"text-muted-foreground\",\n                active === index && \"text-foreground\",\n              )}\n            >\n              {row.step.label}\n            </span>\n          ))}\n        </div>\n      </div>\n    </div>\n  );\n\n  // Below 26rem the value moves under its label so the track keeps most of the width.\n  const rowsView = (\n    <div\n      data-slot=\"waterfall-chart-rows\"\n      className={cn(\n        \"px-4 pt-3 pb-3\",\n        \"[--wf-label:6.25rem] [--wf-value:0px] @min-[26rem]/waterfall:[--wf-label:6.5rem] @min-[26rem]/waterfall:[--wf-value:calc(4.75rem+0.75rem)] @md/waterfall:[--wf-label:9rem]\",\n        orientation === \"auto\"\n          ? auto.rows\n          : orientation === \"horizontal\"\n            ? \"block\"\n            : \"hidden\",\n      )}\n    >\n      <div\n        {...plotProps(summary)}\n        data-slot=\"waterfall-chart-plot\"\n        className=\"group/plot relative rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-4 focus-visible:ring-offset-card\"\n      >\n        <div className=\"relative\">\n          {/* Gridlines span the track column only. */}\n          <div\n            aria-hidden=\"true\"\n            data-slot=\"waterfall-chart-axis\"\n            className=\"pointer-events-none absolute inset-y-0 right-(--wf-value) left-[calc(var(--wf-label)+0.75rem)]\"\n          >\n            {scale.ticks.map((tick) => (\n              <span\n                key={tick}\n                className={cn(\n                  \"absolute inset-y-0 w-px\",\n                  tick === 0 ? \"bg-foreground/25\" : \"bg-border\",\n                )}\n                style={{ left: `${position(tick)}%` }}\n              />\n            ))}\n            {crosshairValue != null ? (\n              <span\n                data-slot=\"waterfall-chart-crosshair\"\n                className=\"absolute inset-y-0 z-10 w-px bg-foreground/45\"\n                style={{ left: `${position(crosshairValue)}%` }}\n              />\n            ) : null}\n          </div>\n\n          <ul role=\"presentation\" className=\"relative\">\n            {rows.map((row, index) => {\n              const isActive = active === index;\n              const dimmed = active != null && !isActive;\n              const left = position(row.low);\n              const right = position(row.high);\n              const delay = 120 + index * 85;\n              // Decreases and negative totals hang from their top edge.\n              const falling =\n                row.info.direction === \"decrease\" ||\n                (row.info.direction === \"total\" && row.info.to < 0);\n              const center = (left + right) / 2;\n              return (\n                <li\n                  key={row.step.id}\n                  role=\"presentation\"\n                  data-slot=\"waterfall-chart-step\"\n                  data-direction={row.info.direction}\n                  data-active={isActive || undefined}\n                  onPointerEnter={() => setHovered(index)}\n                  onClick={onSelect ? () => select(index) : undefined}\n                  className={cn(\n                    \"relative grid h-10 grid-cols-[var(--wf-label)_minmax(0,1fr)] items-center gap-x-3\",\n                    \"@min-[26rem]/waterfall:h-9 @min-[26rem]/waterfall:grid-cols-[var(--wf-label)_minmax(0,1fr)_4.75rem]\",\n                    onSelect && \"cursor-pointer\",\n                    row.info.kind === \"subtotal\" || row.info.kind === \"end\"\n                      ? \"border-t border-dashed border-border\"\n                      : \"\",\n                  )}\n                >\n                  <span\n                    aria-hidden=\"true\"\n                    className={cn(\n                      \"absolute -inset-x-2 inset-y-0.5 rounded-md bg-foreground/[0.045] opacity-0 transition-opacity duration-150 motion-reduce:transition-none\",\n                      isActive && \"opacity-100\",\n                    )}\n                  />\n                  <span className=\"relative min-w-0\">\n                    <span\n                      data-slot=\"waterfall-chart-label\"\n                      className={cn(\n                        \"block truncate text-xs leading-4\",\n                        row.info.direction === \"total\"\n                          ? \"font-medium text-foreground\"\n                          : \"text-muted-foreground\",\n                        isActive && \"text-foreground\",\n                      )}\n                    >\n                      {row.step.label}\n                    </span>\n                    <span\n                      className={cn(\n                        \"block text-[11px] leading-4 whitespace-nowrap tabular-nums @min-[26rem]/waterfall:hidden\",\n                        valueTone(row),\n                        dimmed && \"opacity-50\",\n                      )}\n                      style={valueStyle(row)}\n                    >\n                      {valueText(row)}\n                    </span>\n                  </span>\n                  <span className=\"relative h-full\">\n                    <span\n                      data-slot=\"waterfall-chart-bar\"\n                      className={cn(\n                        \"absolute top-1/2 h-3.5 -translate-y-1/2 transition-[opacity,left,width] duration-300 motion-reduce:transition-none\",\n                        row.info.direction === \"total\"\n                          ? row.info.to < 0\n                            ? \"rounded-l-[4px]\"\n                            : \"rounded-r-[4px]\"\n                          : \"rounded-[3px]\",\n                        dimmed && \"opacity-45\",\n                      )}\n                      style={{\n                        left: `${left}%`,\n                        width: `max(2px, ${right - left}%)`,\n                      }}\n                    >\n                      <span\n                        className=\"absolute inset-0 rounded-[inherit] motion-safe:animate-[waterfall-grow_620ms_cubic-bezier(0.22,1,0.36,1)_backwards]\"\n                        style={{\n                          backgroundColor: row.info.color,\n                          transformOrigin: falling ? \"right\" : \"left\",\n                          animationDelay: `${delay}ms`,\n                        }}\n                      />\n                      {row.cut ? <CutMark horizontal /> : null}\n                    </span>\n                    {row.connects ? (\n                      <span\n                        aria-hidden=\"true\"\n                        data-slot=\"waterfall-chart-connector\"\n                        className=\"absolute top-[calc(50%+7px)] h-[calc(100%-14px)] w-px origin-top bg-foreground/35 motion-safe:animate-[waterfall-drop_300ms_cubic-bezier(0.22,1,0.36,1)_backwards]\"\n                        style={{\n                          left: `${position(row.info.to)}%`,\n                          animationDelay: `${delay + 380}ms`,\n                        }}\n                      />\n                    ) : null}\n                    {isActive ? (\n                      <span\n                        data-slot=\"waterfall-chart-tooltip\"\n                        className=\"pointer-events-none absolute bottom-[calc(50%+14px)] z-30 rounded-lg border bg-popover px-3 py-2 text-xs whitespace-nowrap text-popover-foreground shadow-lg shadow-black/5\"\n                        style={{\n                          left: `${center}%`,\n                          transform: `translateX(-${Math.min(100, Math.max(0, center))}%)`,\n                        }}\n                      >\n                        {tooltip(row)}\n                      </span>\n                    ) : null}\n                  </span>\n                  <span\n                    data-slot=\"waterfall-chart-value\"\n                    className={cn(\n                      \"relative hidden text-right text-xs whitespace-nowrap tabular-nums transition-opacity duration-150 motion-reduce:transition-none @min-[26rem]/waterfall:block\",\n                      valueTone(row),\n                      fadeUp,\n                      dimmed && \"opacity-50\",\n                    )}\n                    style={{\n                      ...valueStyle(row),\n                      animationDelay: `${delay + 260}ms`,\n                    }}\n                  >\n                    {valueText(row)}\n                  </span>\n                </li>\n              );\n            })}\n          </ul>\n        </div>\n        <div\n          aria-hidden=\"true\"\n          className=\"relative mt-1 mr-(--wf-value) ml-[calc(var(--wf-label)+0.75rem)] h-4\"\n        >\n          {scale.ticks.map((tick, index) => {\n            const first = index === 0;\n            const last = index === scale.ticks.length - 1;\n            return (\n              <span\n                key={tick}\n                className={cn(\n                  \"absolute top-0 font-mono text-[10.5px] leading-4 text-muted-foreground tabular-nums\",\n                  first ? \"\" : last ? \"-translate-x-full\" : \"-translate-x-1/2\",\n                  // Narrow tracks only label the ends of the axis.\n                  !first && !last && \"hidden @min-[26rem]/waterfall:block\",\n                )}\n                style={{ left: `${position(tick)}%` }}\n              >\n                {format(tick, \"axis\")}\n              </span>\n            );\n          })}\n        </div>\n      </div>\n    </div>\n  );\n\n  const legend = (className: string) => (\n    <ul\n      data-slot=\"waterfall-chart-legend\"\n      aria-hidden=\"true\"\n      className={cn(\n        \"flex flex-wrap items-center gap-x-3.5 gap-y-1 text-[11px] text-muted-foreground\",\n        className,\n      )}\n    >\n      {(\n        [\n          [\"Increase\", increase],\n          [\"Decrease\", decrease],\n          [\"Total\", total],\n          ...(hasSubtotal ? [[\"Subtotal\", subtotalFill]] : []),\n        ] as [string, string][]\n      ).map(([label, color]) => (\n        <li key={label} className=\"flex items-center gap-1.5\">\n          <span\n            className=\"size-2.5 rounded-[3px]\"\n            style={{ backgroundColor: color }}\n          />\n          {label}\n        </li>\n      ))}\n    </ul>\n  );\n\n  const hasHeader =\n    title != null ||\n    description != null ||\n    actions != null ||\n    showSummary ||\n    showLegend;\n  const hasSubtotal = rows.some((row) => row.info.kind === \"subtotal\");\n\n  return (\n    <div\n      data-slot=\"waterfall-chart\"\n      data-orientation={orientation}\n      className={cn(\n        \"@container/waterfall flex min-w-0 flex-col rounded-xl border bg-card text-card-foreground shadow-xs\",\n        className,\n      )}\n      {...props}\n    >\n      <style href=\"overtrue-waterfall-chart\" precedence=\"default\">\n        {`@keyframes waterfall-rise{from{transform:scaleY(0)}}@keyframes waterfall-grow{from{transform:scaleX(0)}}@keyframes waterfall-drop{from{transform:scaleY(0)}}@keyframes waterfall-draw{from{transform:scaleX(0)}}@keyframes waterfall-fade{from{opacity:0;transform:translateY(3px)}}`}\n      </style>\n\n      {hasHeader ? (\n        <div className=\"flex flex-col gap-3 px-4 pt-4\">\n          {title != null || description != null || actions != null ? (\n            <div className=\"flex flex-wrap items-start justify-between gap-x-6 gap-y-3\">\n              <div className=\"min-w-0 space-y-1\">\n                {title != null ? (\n                  <h3 className=\"text-sm leading-5 font-semibold tracking-tight\">\n                    {title}\n                  </h3>\n                ) : null}\n                {description != null ? (\n                  <p className=\"text-xs text-muted-foreground\">{description}</p>\n                ) : null}\n              </div>\n              {actions != null ? (\n                <div className=\"flex shrink-0 items-center gap-2\">\n                  {actions}\n                </div>\n              ) : null}\n            </div>\n          ) : null}\n          {showSummary || showLegend ? (\n            <div className=\"flex flex-wrap items-end justify-between gap-x-6 gap-y-2\">\n              {showSummary && count ? (\n                renderSummary ? (\n                  <div data-slot=\"waterfall-chart-summary\" className=\"min-w-0\">\n                    {renderSummary({\n                      opening,\n                      closing,\n                      net,\n                      netShare: net != null && opening ? net / opening : null,\n                      format,\n                    })}\n                  </div>\n                ) : (\n                  <p\n                    data-slot=\"waterfall-chart-summary\"\n                    className=\"flex flex-wrap items-baseline gap-x-2 gap-y-1\"\n                  >\n                    <span className=\"text-2xl leading-none font-semibold tracking-tight\">\n                      {format(closing, \"detail\")}\n                    </span>\n                    {net != null && opening ? (\n                      <span\n                        className={cn(\n                          \"text-xs font-medium tabular-nums\",\n                          net > 0\n                            ? \"text-emerald-700 dark:text-emerald-400\"\n                            : net < 0\n                              ? \"text-rose-600 dark:text-rose-400\"\n                              : \"text-muted-foreground\",\n                        )}\n                      >\n                        {signed(net, \"label\")}\n                        <span className=\"ml-1 font-mono text-[10.5px] font-normal\">\n                          {sharePercent.format(net / opening)}\n                        </span>\n                      </span>\n                    ) : null}\n                    {opening != null ? (\n                      <span className=\"text-xs text-muted-foreground\">\n                        from {format(opening, \"label\")}\n                      </span>\n                    ) : null}\n                  </p>\n                )\n              ) : (\n                <span />\n              )}\n              {showLegend && count ? legend(\"hidden @md/waterfall:flex\") : null}\n            </div>\n          ) : null}\n        </div>\n      ) : null}\n\n      {count === 0 ? (\n        <p className=\"m-4 grid h-32 place-items-center rounded-md border border-dashed text-xs text-muted-foreground\">\n          No steps to show.\n        </p>\n      ) : (\n        <>\n          {orientation !== \"horizontal\" ? columns : null}\n          {orientation !== \"vertical\" ? rowsView : null}\n          {showLegend && count\n            ? legend(\"border-t px-4 py-2.5 @md/waterfall:hidden\")\n            : null}\n        </>\n      )}\n\n      <p className=\"sr-only\" aria-live=\"polite\">\n        {focused != null && rows[focused]\n          ? `${rows[focused].step.label}: ${rows[focused].info.formattedChange}${\n              rows[focused].info.kind === \"delta\"\n                ? `, running total ${rows[focused].info.formattedTotal}`\n                : \"\"\n            }`\n          : \"\"}\n      </p>\n\n      <div className=\"sr-only\">\n        <table>\n          <caption>{titleText}</caption>\n          <thead>\n            <tr>\n              <th scope=\"col\">Step</th>\n              <th scope=\"col\">Change</th>\n              <th scope=\"col\">Running total</th>\n            </tr>\n          </thead>\n          <tbody>\n            {rows.map((row) => (\n              <tr key={row.step.id}>\n                <th scope=\"row\">{row.step.label}</th>\n                <td>\n                  {row.info.kind === \"delta\"\n                    ? row.info.formattedChange\n                    : kindLabel[row.info.kind]}\n                </td>\n                <td>{row.info.formattedTotal}</td>\n              </tr>\n            ))}\n          </tbody>\n        </table>\n      </div>\n    </div>\n  );\n}\n\nexport { WaterfallChart };\n"
    },
    {
      "path": "src/registry/overtrue/treemap.tsx",
      "type": "registry:component",
      "target": "components/overtrue/treemap.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { IconArrowUp, IconChevronRight } from \"@tabler/icons-react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport interface TreemapNode<TMeta = unknown> {\n  /** Unique across the whole tree. Used for the path, keys and transitions. */\n  id: string;\n  label: string;\n  /** Amount for a leaf. Nodes with children always show the sum of their children. */\n  value?: number;\n  children?: TreemapNode<TMeta>[];\n  /** Any CSS color. Applies to this node and everything under it. */\n  color?: string;\n  /** Anything else your labels or handlers need, such as a file count or an owner. */\n  meta?: TMeta;\n}\n\n/** Label tier picked from the tile's size: lg shows label, value and share; xs shows nothing. */\nexport type TreemapLabelSize = \"lg\" | \"md\" | \"sm\" | \"xs\";\n\n/** Where a formatted value is shown: dense tile labels, or the breadcrumb, readout and labels for assistive tech. */\nexport type TreemapFormatContext = \"tile\" | \"detail\";\n\n/** Everything known about a tile, passed to `renderLabel`. */\nexport interface TreemapTileInfo<TMeta = unknown> {\n  value: number;\n  /** The value run through `valueFormatter` for a tile. */\n  formattedValue: string;\n  /** Share of the parent node, 0–1. */\n  share: number;\n  /** Share of the whole map, 0–1. */\n  shareOfTotal: number;\n  /** Depth below the top level: 0 for a top-level node. */\n  depth: number;\n  /** Nodes from the top level down to and including this one. */\n  path: TreemapNode<TMeta>[];\n  /** Tile size in CSS pixels, and the label tier picked for it. */\n  width: number;\n  height: number;\n  size: TreemapLabelSize;\n  /** Resolved fill and a readable text color for it. */\n  fill: string;\n  ink: string;\n  /** Leaves under this node, or 1 for a leaf. */\n  leafCount: number;\n  /** Whether activating the tile zooms into it. */\n  drillable: boolean;\n  /** Whether the tile is hovered or focused. */\n  active: boolean;\n}\n\nexport interface TreemapProps<TMeta = unknown> extends Omit<\n  React.ComponentProps<\"div\">,\n  \"title\" | \"onSelect\" | \"children\"\n> {\n  /** Top-level nodes. Leaves carry values; parents sum their children. */\n  data: TreemapNode<TMeta>[];\n  /**\n   * Formats values. `context` is \"tile\" for tile labels and \"detail\" for the\n   * breadcrumb, readout and accessible labels. Defaults to compact numbers on tiles\n   * and grouped digits elsewhere.\n   */\n  valueFormatter?: (value: number, context: TreemapFormatContext) => string;\n  title?: React.ReactNode;\n  description?: React.ReactNode;\n  /** Controls placed at the top right, such as a period picker. */\n  actions?: React.ReactNode;\n  /**\n   * Height of the map: pixels, or any CSS length. The card is a size container, so\n   * container units work, e.g. \"clamp(240px, 56cqw, 420px)\". Defaults to 360.\n   */\n  height?: number | string;\n  /** Levels drawn at once. Deeper levels appear as outlined groups. Defaults to 1. */\n  maxDepth?: number;\n  /** Colors for top-level groups, cycled in data order. Defaults to chart-1 … chart-5. */\n  colors?: string[];\n  /** Name of the top of the hierarchy in the breadcrumb. Defaults to \"All\". */\n  rootLabel?: string;\n  /** Controlled drill-down path: ids from the top level to the node being shown. */\n  path?: string[];\n  /** Initial path when uncontrolled. */\n  defaultPath?: string[];\n  /** Called with the new path and its nodes whenever the view zooms in or out. */\n  onPathChange?: (path: string[], nodes: TreemapNode<TMeta>[]) => void;\n  /** Called when a tile is clicked or activated with Enter, before any zoom. */\n  onSelect?: (node: TreemapNode<TMeta>, path: TreemapNode<TMeta>[]) => void;\n  /** Replace the content of every tile. Return null to leave a tile blank. */\n  renderLabel?: (\n    node: TreemapNode<TMeta>,\n    info: TreemapTileInfo<TMeta>,\n  ) => React.ReactNode;\n}\n\ntype Rect = { x: number; y: number; w: number; h: number };\n\ninterface Item<TMeta> {\n  id: string;\n  node: TreemapNode<TMeta> | null;\n  label: string;\n  value: number;\n  /** -1 for the root, 0 for top-level nodes. */\n  depth: number;\n  color: string;\n  parent: Item<TMeta> | null;\n  children: Item<TMeta>[];\n  leafCount: number;\n  /** Value relative to the largest sibling, 0–1. */\n  rank: number;\n}\n\ninterface Placement<TMeta> {\n  key: string;\n  item: Item<TMeta>;\n  rect: Rect;\n  kind: \"tile\" | \"group\" | \"hidden\";\n  header: number;\n}\n\ninterface Frame {\n  rect: Rect;\n  opacity: number;\n}\n\ninterface Zoom {\n  key: number;\n  from: string;\n  phase: \"start\" | \"run\";\n}\n\nconst ROOT_ID = \"\\u0000treemap-root\";\nconst GAP = 2;\nconst GROUP_HEADER = 22;\nconst GROUP_PAD = 3;\nconst DURATION = 560;\nconst EASE = \"cubic-bezier(0.22, 1, 0.36, 1)\";\nconst FALLBACK_WIDTH = 640;\n\nconst defaultColors = [\n  \"var(--color-chart-1)\",\n  \"var(--color-chart-2)\",\n  \"var(--color-chart-3)\",\n  \"var(--color-chart-4)\",\n  \"var(--color-chart-5)\",\n];\n\nconst compactNumber = new Intl.NumberFormat(\"en-US\", {\n  notation: \"compact\",\n  maximumFractionDigits: 1,\n});\nconst exactNumber = new Intl.NumberFormat(\"en-US\", {\n  maximumFractionDigits: 2,\n});\n\nfunction defaultFormatter(value: number, context: TreemapFormatContext) {\n  return context === \"tile\"\n    ? compactNumber.format(value)\n    : exactNumber.format(value);\n}\n\nfunction percent(share: number) {\n  const pct = share * 100;\n  if (!(pct > 0)) return \"0%\";\n  if (pct < 0.1) return \"<0.1%\";\n  if (pct >= 99.95) return \"100%\";\n  return `${pct.toFixed(1)}%`;\n}\n\nconst useIsomorphicLayoutEffect =\n  typeof window === \"undefined\" ? React.useEffect : React.useLayoutEffect;\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (onChange) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", onChange);\n      return () => query.removeEventListener(\"change\", onChange);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\n/** Normalise the data: sum parents, drop empty nodes, sort by size and resolve colors. */\nfunction buildTree<TMeta>(\n  data: TreemapNode<TMeta>[],\n  colors: string[],\n  rootLabel: string,\n) {\n  const palette = colors.length ? colors : defaultColors;\n  const index = new Map<string, Item<TMeta>>();\n  const root: Item<TMeta> = {\n    id: ROOT_ID,\n    node: null,\n    label: rootLabel,\n    value: 0,\n    depth: -1,\n    color: \"var(--color-muted-foreground)\",\n    parent: null,\n    children: [],\n    leafCount: 0,\n    rank: 1,\n  };\n  index.set(ROOT_ID, root);\n\n  const visit = (\n    nodes: TreemapNode<TMeta>[],\n    parent: Item<TMeta>,\n    depth: number,\n  ): Item<TMeta>[] => {\n    const items: Item<TMeta>[] = [];\n    nodes.forEach((node, position) => {\n      const item: Item<TMeta> = {\n        id: node.id,\n        node,\n        label: node.label,\n        value: 0,\n        depth,\n        // Colors follow data order, so they stay put when values change.\n        color:\n          node.color ??\n          (depth === 0 ? palette[position % palette.length] : parent.color),\n        parent,\n        children: [],\n        leafCount: 1,\n        rank: 1,\n      };\n      if (node.children?.length) {\n        item.children = visit(node.children, item, depth + 1);\n        item.value = item.children.reduce((sum, child) => sum + child.value, 0);\n        item.leafCount = item.children.reduce(\n          (sum, child) => sum + child.leafCount,\n          0,\n        );\n      } else {\n        const value = Number(node.value);\n        item.value = Number.isFinite(value) && value > 0 ? value : 0;\n      }\n      if (item.value > 0) {\n        items.push(item);\n        index.set(item.id, item);\n      }\n    });\n    items.sort((a, b) => b.value - a.value);\n    const largest = items[0]?.value || 1;\n    for (const item of items) item.rank = item.value / largest;\n    return items;\n  };\n\n  root.children = visit(data, root, 0);\n  root.value = root.children.reduce((sum, child) => sum + child.value, 0);\n  root.leafCount = root.children.reduce(\n    (sum, child) => sum + child.leafCount,\n    0,\n  );\n  return { root, index };\n}\n\n/** Bruls, Huizing and van Wijk's squarified layout. Values must be sorted, largest first. */\nfunction squarify(values: number[], area: Rect): Rect[] {\n  const total = values.reduce((sum, value) => sum + value, 0);\n  if (!(total > 0) || area.w <= 0 || area.h <= 0)\n    return values.map(() => ({ x: area.x, y: area.y, w: 0, h: 0 }));\n  const scale = (area.w * area.h) / total;\n  const sizes = values.map((value) => value * scale);\n  const out: Rect[] = new Array(values.length);\n  let { x, y, w, h } = area;\n  let start = 0;\n  while (start < sizes.length) {\n    const side = Math.min(w, h);\n    let end = start;\n    let sum = 0;\n    let min = Infinity;\n    let max = 0;\n    let worst = Infinity;\n    while (end < sizes.length) {\n      const size = sizes[end];\n      const nextSum = sum + size;\n      const nextMin = Math.min(min, size);\n      const nextMax = Math.max(max, size);\n      const ratio = Math.max(\n        (side * side * nextMax) / (nextSum * nextSum),\n        (nextSum * nextSum) / (side * side * nextMin),\n      );\n      if (end > start && ratio > worst) break;\n      worst = ratio;\n      sum = nextSum;\n      min = nextMin;\n      max = nextMax;\n      end++;\n    }\n    const last = end >= sizes.length;\n    if (w >= h) {\n      // A column along the left edge.\n      const columnWidth = last ? w : sum / h;\n      let cursor = y;\n      for (let i = start; i < end; i++) {\n        const tall = i === end - 1 ? y + h - cursor : sizes[i] / columnWidth;\n        out[i] = { x, y: cursor, w: columnWidth, h: tall };\n        cursor += tall;\n      }\n      x += columnWidth;\n      w -= columnWidth;\n    } else {\n      // A row along the top edge.\n      const rowHeight = last ? h : sum / w;\n      let cursor = x;\n      for (let i = start; i < end; i++) {\n        const wide = i === end - 1 ? x + w - cursor : sizes[i] / rowHeight;\n        out[i] = { x: cursor, y, w: wide, h: rowHeight };\n        cursor += wide;\n      }\n      y += rowHeight;\n      h -= rowHeight;\n    }\n    start = end;\n  }\n  return out;\n}\n\n/**\n * Lay out everything under `focus` in a width × height frame. Levels within\n * `maxDepth` are drawn; deeper levels are still placed (hidden) so zooms can start\n * from where a node would sit.\n */\nfunction layoutView<TMeta>(\n  focus: Item<TMeta>,\n  width: number,\n  height: number,\n  maxDepth: number,\n) {\n  const map = new Map<string, Placement<TMeta>>();\n  const place = (\n    parent: Item<TMeta>,\n    area: Rect,\n    level: number,\n    visible: boolean,\n  ) => {\n    if (!parent.children.length) return;\n    const rects = squarify(\n      parent.children.map((child) => child.value),\n      area,\n    );\n    parent.children.forEach((child, i) => {\n      const rect = rects[i];\n      let kind: Placement<TMeta>[\"kind\"] = \"hidden\";\n      let header = 0;\n      if (visible) {\n        const group =\n          child.children.length > 0 &&\n          level < maxDepth &&\n          rect.w >= 48 &&\n          rect.h >= 40;\n        kind = group ? \"group\" : \"tile\";\n        if (group && rect.w >= 72 && rect.h >= 64) header = GROUP_HEADER;\n      }\n      map.set(child.id, {\n        key: kind === \"group\" ? `${child.id}\\u0000group` : child.id,\n        item: child,\n        rect,\n        kind,\n        header,\n      });\n      if (!child.children.length) return;\n      const inner =\n        kind === \"group\"\n          ? {\n              x: rect.x + GROUP_PAD,\n              y: rect.y + (header || GROUP_PAD),\n              w: Math.max(0, rect.w - GROUP_PAD * 2),\n              h: Math.max(0, rect.h - (header || GROUP_PAD) - GROUP_PAD),\n            }\n          : rect;\n      place(child, inner, level + 1, kind === \"group\");\n    });\n  };\n  place(focus, { x: 0, y: 0, w: width, h: height }, 1, true);\n  return map;\n}\n\n/** Map a rect so that `frame` fills the whole view: the geometry of a camera zoom. */\nfunction zoomRect(\n  rect: Rect,\n  frame: Rect,\n  width: number,\n  height: number,\n): Rect {\n  const sx = width / (frame.w || 1);\n  const sy = height / (frame.h || 1);\n  return {\n    x: (rect.x - frame.x) * sx,\n    y: (rect.y - frame.y) * sy,\n    w: rect.w * sx,\n    h: rect.h * sy,\n  };\n}\n\n/** The inverse of zoomRect: squeeze a full-view rect into `frame`. */\nfunction unzoomRect(\n  rect: Rect,\n  frame: Rect,\n  width: number,\n  height: number,\n): Rect {\n  const sx = frame.w / (width || 1);\n  const sy = frame.h / (height || 1);\n  return {\n    x: frame.x + rect.x * sx,\n    y: frame.y + rect.y * sy,\n    w: rect.w * sx,\n    h: rect.h * sy,\n  };\n}\n\nfunction isWithin<TMeta>(item: Item<TMeta>, ancestor: Item<TMeta>) {\n  for (\n    let current: Item<TMeta> | null = item;\n    current;\n    current = current.parent\n  )\n    if (current === ancestor) return true;\n  return false;\n}\n\nfunction lineage<TMeta>(item: Item<TMeta>) {\n  const chain: Item<TMeta>[] = [];\n  for (\n    let current: Item<TMeta> | null = item;\n    current && current.depth >= 0;\n    current = current.parent\n  )\n    chain.unshift(current);\n  return chain;\n}\n\n/** Deeper levels and smaller siblings get lighter, so neighbors of one hue stay distinct. */\nfunction fillFor<TMeta>(item: Item<TMeta>) {\n  const base = [0.9, 0.82, 0.72, 0.64][Math.min(Math.max(item.depth, 0), 3)];\n  const strength = base * (0.42 + 0.58 * Math.pow(item.rank, 0.7));\n  return `color-mix(in oklab, ${item.color} ${Math.round(strength * 100)}%, var(--color-card))`;\n}\n\n/**\n * Light or dark text picked from the fill's own lightness and tinted with its hue.\n * Browsers without relative color syntax keep the inherited foreground.\n */\nfunction inkFor(fill: string) {\n  return `oklch(from ${fill} clamp(0.2, (0.64 - l) * 1000, 0.985) min(c, 0.04) h)`;\n}\n\nfunction labelSize(width: number, height: number): TreemapLabelSize {\n  if (width >= 104 && height >= 70) return \"lg\";\n  if (width >= 64 && height >= 38) return \"md\";\n  if (width >= 34 && height >= 20) return \"sm\";\n  return \"xs\";\n}\n\nfunction boxStyle(rect: Rect, width: number, height: number, inset: number) {\n  const ix = rect.w > inset * 2 ? inset : 0;\n  const iy = rect.h > inset * 2 ? inset : 0;\n  return {\n    left: `calc(${(rect.x / width) * 100}% + ${ix}px)`,\n    top: `calc(${(rect.y / height) * 100}% + ${iy}px)`,\n    width: `calc(${(rect.w / width) * 100}% - ${ix * 2}px)`,\n    height: `calc(${(rect.h / height) * 100}% - ${iy * 2}px)`,\n  };\n}\n\nfunction DefaultLabel({\n  label,\n  info,\n  childCount,\n}: {\n  label: string;\n  info: TreemapTileInfo;\n  childCount: number;\n}) {\n  if (info.size === \"xs\") return null;\n  // A label cut to a couple of letters is noise; drop it and let the readout name the tile.\n  const fits = (font: number) =>\n    label.length <= Math.floor((info.width - 16) / (font * 0.56)) ||\n    (info.width - 16) / (font * 0.56) >= 6;\n  if (info.size === \"sm\")\n    return fits(11) ? (\n      <span className=\"block truncate px-1.5 pt-1 text-[11px] leading-4 font-medium\">\n        {label}\n      </span>\n    ) : null;\n  if (info.size === \"md\")\n    return (\n      <span className=\"flex min-w-0 flex-col px-2 pt-1.5\">\n        {fits(12) ? (\n          <span className=\"truncate text-xs leading-4 font-medium\">\n            {label}\n          </span>\n        ) : null}\n        <span className=\"truncate text-[11px] leading-4 tabular-nums opacity-80\">\n          {info.formattedValue}\n        </span>\n      </span>\n    );\n  const big = info.width >= 176 && info.height >= 120;\n  return (\n    <span className=\"flex h-full min-w-0 flex-col justify-between gap-1 p-2.5\">\n      <span\n        className={cn(\n          \"min-w-0 text-xs leading-4 font-medium\",\n          info.height >= 84 ? \"line-clamp-2 break-words\" : \"truncate\",\n        )}\n      >\n        {label}\n      </span>\n      <span className=\"flex min-w-0 items-end justify-between gap-2\">\n        <span className=\"flex min-w-0 items-baseline gap-1.5\">\n          <span\n            className={cn(\n              \"truncate leading-none font-semibold tracking-tight\",\n              big ? \"text-[22px]\" : \"text-[15px]\",\n            )}\n          >\n            {info.formattedValue}\n          </span>\n          {info.width >= 132 ? (\n            <span className=\"shrink-0 font-mono text-[10.5px] leading-none tabular-nums opacity-70\">\n              {percent(info.share)}\n            </span>\n          ) : null}\n        </span>\n        {info.drillable && info.width >= 150 ? (\n          <span className=\"flex shrink-0 items-center gap-0.5 font-mono text-[10.5px] leading-none tabular-nums opacity-70\">\n            {childCount}\n            <IconChevronRight aria-hidden=\"true\" size={11} stroke={2.25} />\n          </span>\n        ) : null}\n      </span>\n    </span>\n  );\n}\n\n/** Pick the tile whose center lies closest in the arrow's direction. */\nfunction neighborIn<TMeta>(\n  tiles: Placement<TMeta>[],\n  from: Placement<TMeta>,\n  key: string,\n) {\n  const cx = from.rect.x + from.rect.w / 2;\n  const cy = from.rect.y + from.rect.h / 2;\n  let best: Placement<TMeta> | null = null;\n  let bestScore = Infinity;\n  for (const tile of tiles) {\n    if (tile === from) continue;\n    const r = tile.rect;\n    const tx = r.x + r.w / 2;\n    const ty = r.y + r.h / 2;\n    let along: number;\n    let across: number;\n    if (key === \"ArrowRight\") {\n      if (r.x < from.rect.x + from.rect.w - 1) continue;\n      along = r.x - (from.rect.x + from.rect.w);\n      across = Math.abs(ty - cy);\n    } else if (key === \"ArrowLeft\") {\n      if (r.x + r.w > from.rect.x + 1) continue;\n      along = from.rect.x - (r.x + r.w);\n      across = Math.abs(ty - cy);\n    } else if (key === \"ArrowDown\") {\n      if (r.y < from.rect.y + from.rect.h - 1) continue;\n      along = r.y - (from.rect.y + from.rect.h);\n      across = Math.abs(tx - cx);\n    } else {\n      if (r.y + r.h > from.rect.y + 1) continue;\n      along = from.rect.y - (r.y + r.h);\n      across = Math.abs(tx - cx);\n    }\n    const score = Math.max(0, along) + across * 2;\n    if (score < bestScore) {\n      best = tile;\n      bestScore = score;\n    }\n  }\n  return best;\n}\n\n/**\n * A squarified treemap for hierarchical totals. Click or press Enter on a tile to\n * zoom into it with an animated layout tween; the breadcrumb, Backspace or Escape\n * zoom back out. Hover or focus a tile to read its share of the parent and the total.\n */\nfunction Treemap<TMeta = unknown>({\n  data,\n  valueFormatter = defaultFormatter,\n  title,\n  description,\n  actions,\n  height = 360,\n  maxDepth = 1,\n  colors = defaultColors,\n  rootLabel = \"All\",\n  path: pathProp,\n  defaultPath,\n  onPathChange,\n  onSelect,\n  renderLabel,\n  className,\n  ...props\n}: TreemapProps<TMeta>) {\n  const id = React.useId();\n  const reduced = useReducedMotion();\n  const canvasRef = React.useRef<HTMLDivElement>(null);\n  const pendingFocus = React.useRef<string | null>(null);\n  const [measured, setMeasured] = React.useState<{\n    w: number;\n    h: number;\n  } | null>(null);\n  const [instant, setInstant] = React.useState(true);\n  const [revealed, setRevealed] = React.useState(false);\n  const [internalPath, setInternalPath] = React.useState<string[]>(\n    defaultPath ?? [],\n  );\n  const [hoveredId, setHoveredId] = React.useState<string | null>(null);\n  const [focusedId, setFocusedId] = React.useState<string | null>(null);\n  const [tabStopId, setTabStopId] = React.useState<string | null>(null);\n  const [zoom, setZoom] = React.useState<Zoom | null>(null);\n\n  const colorKey = colors.join(\"|\");\n  const tree = React.useMemo(\n    () => buildTree(data, colorKey ? colorKey.split(\"|\") : [], rootLabel),\n    // colorKey stands in for `colors`, so inline arrays do not rebuild the tree.\n    [data, colorKey, rootLabel],\n  );\n  const { root, index } = tree;\n  const depthLimit = Math.max(1, Math.floor(maxDepth));\n\n  const requestedPath = pathProp ?? internalPath;\n  const chain = React.useMemo(() => {\n    const result = [root];\n    let current = root;\n    for (const step of requestedPath) {\n      const next = current.children.find((child) => child.id === step);\n      if (!next || !next.children.length) break;\n      result.push(next);\n      current = next;\n    }\n    return result;\n  }, [root, requestedPath]);\n  const focus = chain[chain.length - 1];\n\n  const width = measured?.w ?? FALLBACK_WIDTH;\n  const frameHeight =\n    measured?.h ??\n    (typeof height === \"number\" ? height : FALLBACK_WIDTH * 0.5625);\n  const layout = React.useMemo(\n    () => layoutView(focus, width, frameHeight, depthLimit),\n    [focus, width, frameHeight, depthLimit],\n  );\n  const placements = React.useMemo(\n    () => [...layout.values()].filter((p) => p.kind !== \"hidden\"),\n    [layout],\n  );\n  const tiles = React.useMemo(\n    () => placements.filter((p) => p.kind === \"tile\"),\n    [placements],\n  );\n\n  // Start a zoom whenever the focused node changes; the previous layout is derived\n  // from the node we are leaving, so nothing has to be cached between renders.\n  const [shownFocus, setShownFocus] = React.useState(focus.id);\n  if (shownFocus !== focus.id) {\n    setShownFocus(focus.id);\n    setHoveredId(null);\n    setFocusedId(null);\n    setZoom(\n      reduced || !measured\n        ? null\n        : { key: (zoom?.key ?? 0) + 1, from: shownFocus, phase: \"start\" },\n    );\n  }\n\n  // Every tile moves under one camera transform, so nothing crosses paths: the old\n  // arrangement zooms away and fades while the new one zooms in from the same place.\n  const transition = React.useMemo(() => {\n    if (!zoom) return null;\n    const previous = index.get(zoom.from);\n    if (!previous || !(previous.children.length > 0)) return null;\n    const before = layoutView(previous, width, frameHeight, depthLimit);\n    const frameIn = isWithin(focus, previous)\n      ? before.get(focus.id)?.rect\n      : undefined;\n    const frameOut =\n      !frameIn && isWithin(previous, focus)\n        ? layout.get(previous.id)?.rect\n        : undefined;\n    const start = new Map<string, Frame>();\n    for (const p of placements) {\n      start.set(p.key, {\n        rect: frameIn\n          ? unzoomRect(p.rect, frameIn, width, frameHeight)\n          : frameOut\n            ? zoomRect(p.rect, frameOut, width, frameHeight)\n            : p.rect,\n        opacity: 0,\n      });\n    }\n    const exits: { placement: Placement<TMeta>; to: Rect }[] = [];\n    for (const p of before.values()) {\n      if (p.kind === \"hidden\") continue;\n      exits.push({\n        placement: p,\n        to: frameIn\n          ? zoomRect(p.rect, frameIn, width, frameHeight)\n          : frameOut\n            ? unzoomRect(p.rect, frameOut, width, frameHeight)\n            : p.rect,\n      });\n    }\n    return { start, exits };\n    // Recompute per zoom, not per phase.\n  }, [\n    zoom?.key,\n    zoom?.from,\n    layout,\n    placements,\n    index,\n    width,\n    frameHeight,\n    depthLimit,\n  ]);\n\n  useIsomorphicLayoutEffect(() => {\n    const element = canvasRef.current;\n    if (!element) return;\n    let frame = 0;\n    let last: { w: number; h: number } | null = null;\n    const measure = () => {\n      const w = element.clientWidth;\n      const h = element.clientHeight;\n      if (!w || !h) return;\n      if (last && last.w === w && last.h === h) return;\n      last = { w, h };\n      // Re-layout on resize without tweening every tile after the pointer.\n      setInstant(true);\n      setMeasured({ w, h });\n      cancelAnimationFrame(frame);\n      frame = requestAnimationFrame(() => {\n        frame = requestAnimationFrame(() => setInstant(false));\n      });\n    };\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(element);\n    return () => {\n      observer.disconnect();\n      cancelAnimationFrame(frame);\n    };\n  }, []);\n\n  useIsomorphicLayoutEffect(() => {\n    if (zoom?.phase !== \"start\") return;\n    // Commit the start frame so moving to the end frame is a CSS transition.\n    canvasRef.current?.getBoundingClientRect();\n    const key = zoom.key;\n    const frame = requestAnimationFrame(() =>\n      setZoom((current) =>\n        current && current.key === key ? { ...current, phase: \"run\" } : current,\n      ),\n    );\n    return () => cancelAnimationFrame(frame);\n  }, [zoom?.key, zoom?.phase]);\n\n  React.useEffect(() => {\n    if (zoom?.phase !== \"run\") return;\n    const key = zoom.key;\n    const timer = window.setTimeout(\n      () =>\n        setZoom((current) => (current && current.key === key ? null : current)),\n      DURATION + 40,\n    );\n    return () => window.clearTimeout(timer);\n  }, [zoom?.key, zoom?.phase]);\n\n  React.useEffect(() => {\n    const timer = window.setTimeout(() => setRevealed(true), 1200);\n    return () => window.clearTimeout(timer);\n  }, []);\n\n  // After a keyboard zoom, keep focus in the map.\n  React.useEffect(() => {\n    const target = pendingFocus.current;\n    const canvas = canvasRef.current;\n    if (!target || !canvas) return;\n    pendingFocus.current = null;\n    const live = Array.from(\n      canvas.querySelectorAll<HTMLElement>(\n        '[data-slot=\"treemap-tile\"]:not([data-exiting])',\n      ),\n    );\n    const previous = index.get(target);\n    const match =\n      live.find((element) => element.dataset.id === target) ??\n      (previous\n        ? live.find((element) => {\n            const item = index.get(element.dataset.id ?? \"\");\n            return item ? isWithin(item, previous) : false;\n          })\n        : undefined) ??\n      live[0];\n    match?.focus({ preventScroll: true });\n  }, [focus.id, index]);\n\n  const format = valueFormatter;\n  const activeId = zoom ? null : (hoveredId ?? focusedId);\n  const activeItem = activeId ? (index.get(activeId) ?? null) : null;\n  const stopId =\n    tabStopId && tiles.some((p) => p.item.id === tabStopId)\n      ? tabStopId\n      : (tiles[0]?.item.id ?? null);\n\n  const commitPath = (target: Item<TMeta>) => {\n    const nodes = lineage(target);\n    const next = nodes.map((item) => item.id);\n    if (pathProp === undefined) setInternalPath(next);\n    onPathChange?.(\n      next,\n      nodes.map((item) => item.node!),\n    );\n  };\n\n  const activate = (item: Item<TMeta>, fromKeyboard: boolean) => {\n    const nodes = lineage(item);\n    onSelect?.(\n      item.node!,\n      nodes.map((entry) => entry.node!),\n    );\n    // Zoom into the tile, or into its group when it is a leaf drawn inside one.\n    const target = item.children.length\n      ? item\n      : item.parent && item.parent !== focus\n        ? item.parent\n        : null;\n    if (!target || target === focus) return;\n    if (fromKeyboard) pendingFocus.current = \"first\";\n    commitPath(target);\n  };\n\n  const goUp = (fromKeyboard: boolean) => {\n    if (!focus.parent) return;\n    if (fromKeyboard) pendingFocus.current = focus.id;\n    commitPath(focus.parent);\n  };\n\n  const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n    const target = event.target as HTMLElement;\n    if (target.dataset.slot !== \"treemap-tile\") return;\n    const current = tiles.find((p) => p.item.id === target.dataset.id);\n    if (!current) return;\n    if (event.key === \"Enter\" || event.key === \" \") {\n      event.preventDefault();\n      activate(current.item, true);\n      return;\n    }\n    if (event.key === \"Backspace\" || event.key === \"Escape\") {\n      if (!focus.parent) return;\n      event.preventDefault();\n      goUp(true);\n      return;\n    }\n    let next: Placement<TMeta> | null | undefined = null;\n    if (event.key.startsWith(\"Arrow\"))\n      next = neighborIn(tiles, current, event.key);\n    else if (event.key === \"Home\") next = tiles[0];\n    else if (event.key === \"End\") next = tiles[tiles.length - 1];\n    else return;\n    event.preventDefault();\n    if (!next) return;\n    setTabStopId(next.item.id);\n    canvasRef.current\n      ?.querySelector<HTMLElement>(\n        `[data-slot=\"treemap-tile\"][data-id=\"${CSS.escape(next.item.id)}\"]:not([data-exiting])`,\n      )\n      ?.focus({ preventScroll: true });\n  };\n\n  const hasHeader = title != null || description != null || actions != null;\n  const mapLabel = typeof title === \"string\" ? title : \"Treemap\";\n  const shareOfParent = (item: Item<TMeta>) =>\n    item.parent && item.parent.value > 0 ? item.value / item.parent.value : 1;\n  const shareOfTotal = (item: Item<TMeta>) =>\n    root.value > 0 ? item.value / root.value : 0;\n\n  const describe = (item: Item<TMeta>) => {\n    const parts = [\n      item.label,\n      format(item.value, \"detail\"),\n      `${percent(shareOfParent(item))} of ${item.parent?.label ?? rootLabel}`,\n    ];\n    if (item.depth > 0) parts.push(`${percent(shareOfTotal(item))} of total`);\n    if (item.children.length)\n      parts.push(`${item.children.length} items, press Enter to zoom in`);\n    return parts.join(\", \");\n  };\n\n  const phase = zoom && transition ? zoom.phase : null;\n  const labelsHidden = zoom != null;\n  const motion = !reduced && !instant;\n  const moveTransition = (fade: number, fadeDelay = 0) =>\n    [\n      `left ${DURATION}ms ${EASE}`,\n      `top ${DURATION}ms ${EASE}`,\n      `width ${DURATION}ms ${EASE}`,\n      `height ${DURATION}ms ${EASE}`,\n      `opacity ${fade}ms ${fadeDelay}ms ease-out`,\n    ].join(\", \");\n\n  const frameFor = (\n    p: Placement<TMeta>,\n    exitTo: Rect | null,\n  ): { style: React.CSSProperties; exiting: boolean } => {\n    let rect = p.rect;\n    let opacity: number | undefined;\n    if (transition && phase === \"start\") {\n      const from = exitTo ? null : transition.start.get(p.key);\n      rect = from?.rect ?? p.rect;\n      opacity = from ? from.opacity : 1;\n    } else if (transition && phase === \"run\") {\n      rect = exitTo ?? p.rect;\n      opacity = exitTo ? 0 : 1;\n    }\n    let css = \"none\";\n    if (motion && phase !== \"start\")\n      css =\n        phase === \"run\"\n          ? exitTo\n            ? moveTransition(\n                Math.round(DURATION * 0.5),\n                Math.round(DURATION * 0.1),\n              )\n            : moveTransition(Math.round(DURATION * 0.55))\n          : moveTransition(240);\n    return {\n      exiting: exitTo != null,\n      style: {\n        ...boxStyle(rect, width, frameHeight, GAP / 2),\n        opacity,\n        transition: css,\n      },\n    };\n  };\n\n  const revealDelay = (rect: Rect) =>\n    `${Math.round(((rect.x + rect.w / 2) / width + (rect.y + rect.h / 2) / frameHeight) * 210)}ms`;\n\n  const renderGroup = (p: Placement<TMeta>, exitTo: Rect | null) => {\n    const { style, exiting } = frameFor(p, exitTo);\n    const { item } = p;\n    const groupActive = activeItem != null && isWithin(activeItem, item);\n    return (\n      <div\n        key={exiting ? `${p.key}\\u0000exit` : p.key}\n        data-slot=\"treemap-group\"\n        data-id={item.id}\n        data-depth={item.depth}\n        data-active={groupActive || undefined}\n        data-exiting={exiting || undefined}\n        aria-hidden=\"true\"\n        className={cn(\n          \"absolute overflow-hidden rounded-[5px] border\",\n          exiting && \"pointer-events-none\",\n          !revealed &&\n            \"motion-safe:animate-[treemap-tile-in_600ms_cubic-bezier(0.22,1,0.36,1)_backwards]\",\n        )}\n        style={{\n          ...style,\n          borderColor: `color-mix(in oklab, ${item.color} ${groupActive ? 55 : 30}%, var(--color-border))`,\n          backgroundColor: `color-mix(in oklab, ${item.color} 7%, var(--color-card))`,\n          animationDelay: revealed ? undefined : revealDelay(p.rect),\n        }}\n      >\n        {p.header ? (\n          <div\n            className=\"flex h-[19px] w-full cursor-pointer items-center gap-1.5 px-1.5 text-[11px] leading-none transition-opacity duration-200 motion-reduce:transition-none\"\n            style={{ opacity: labelsHidden ? 0 : 1 }}\n            onPointerEnter={() => setHoveredId(item.id)}\n            onClick={exiting ? undefined : () => activate(item, false)}\n          >\n            <span\n              aria-hidden=\"true\"\n              className=\"size-1.5 shrink-0 rounded-full\"\n              style={{ backgroundColor: item.color }}\n            />\n            <span className=\"min-w-0 truncate font-medium text-foreground\">\n              {item.label}\n            </span>\n            {p.rect.w >= 128 ? (\n              <span className=\"ml-auto shrink-0 text-muted-foreground tabular-nums\">\n                {format(item.value, \"tile\")}\n              </span>\n            ) : null}\n          </div>\n        ) : null}\n      </div>\n    );\n  };\n\n  const renderTile = (p: Placement<TMeta>, exitTo: Rect | null) => {\n    const { style, exiting } = frameFor(p, exitTo);\n    const { item } = p;\n    const fill = fillFor(item);\n    const ink = inkFor(fill);\n    const tileWidth = Math.max(0, p.rect.w - GAP);\n    const tileHeight = Math.max(0, p.rect.h - GAP);\n    const active = !exiting && activeItem === item;\n    const dimmed =\n      !exiting &&\n      activeItem != null &&\n      activeItem !== root &&\n      !isWithin(item, activeItem);\n    const drillable = item.children.length > 0;\n    const info: TreemapTileInfo<TMeta> = {\n      value: item.value,\n      formattedValue: format(item.value, \"tile\"),\n      share: shareOfParent(item),\n      shareOfTotal: shareOfTotal(item),\n      depth: item.depth,\n      path: lineage(item).map((entry) => entry.node!),\n      width: tileWidth,\n      height: tileHeight,\n      size: labelSize(tileWidth, tileHeight),\n      fill,\n      ink,\n      leafCount: item.leafCount,\n      drillable,\n      active,\n    };\n    const content = renderLabel ? (\n      renderLabel(item.node!, info)\n    ) : (\n      <DefaultLabel\n        label={item.label}\n        info={info as TreemapTileInfo}\n        childCount={item.children.length}\n      />\n    );\n    return (\n      <button\n        key={exiting ? `${p.key}\\u0000exit` : p.key}\n        type=\"button\"\n        data-slot=\"treemap-tile\"\n        data-id={item.id}\n        data-depth={item.depth}\n        data-size={info.size}\n        data-active={active || undefined}\n        data-exiting={exiting || undefined}\n        aria-hidden={exiting || undefined}\n        aria-label={exiting ? undefined : describe(item)}\n        tabIndex={!exiting && item.id === stopId ? 0 : -1}\n        onPointerEnter={exiting ? undefined : () => setHoveredId(item.id)}\n        onFocus={\n          exiting\n            ? undefined\n            : () => {\n                setFocusedId(item.id);\n                setTabStopId(item.id);\n              }\n        }\n        onClick={exiting ? undefined : () => activate(item, false)}\n        className={cn(\n          \"absolute overflow-hidden rounded-[4px] p-0 text-left outline-none select-none\",\n          drillable\n            ? \"cursor-zoom-in\"\n            : onSelect\n              ? \"cursor-pointer\"\n              : \"cursor-default\",\n          exiting && \"pointer-events-none\",\n          \"data-[active]:z-10 focus-visible:z-20\",\n          // Inset rings so they are not clipped at the edge of the map.\n          \"after:pointer-events-none after:absolute after:inset-0 after:rounded-[inherit] after:opacity-0 after:transition-opacity after:duration-150 motion-reduce:after:transition-none\",\n          \"after:shadow-[inset_0_0_0_1.5px_color-mix(in_oklab,var(--color-foreground)_78%,transparent)] data-[active]:after:opacity-100\",\n          \"focus-visible:after:opacity-100 focus-visible:after:shadow-[inset_0_0_0_2px_var(--color-ring),inset_0_0_0_3.5px_var(--color-card)]\",\n          !revealed &&\n            \"motion-safe:animate-[treemap-tile-in_600ms_cubic-bezier(0.22,1,0.36,1)_backwards]\",\n        )}\n        style={{\n          ...style,\n          animationDelay: revealed ? undefined : revealDelay(p.rect),\n        }}\n      >\n        <span\n          aria-hidden=\"true\"\n          data-slot=\"treemap-tile-fill\"\n          className=\"absolute inset-0 transition-opacity duration-200 motion-reduce:transition-none\"\n          style={{\n            backgroundColor: fill,\n            opacity: dimmed ? 0.42 : 1,\n          }}\n        />\n        <span\n          aria-hidden=\"true\"\n          data-slot=\"treemap-tile-label\"\n          className=\"relative block h-full min-w-0\"\n          style={{\n            color: ink,\n            opacity: labelsHidden ? 0 : dimmed ? 0.55 : 1,\n            transition: reduced\n              ? \"none\"\n              : `opacity ${labelsHidden ? 100 : 260}ms ${EASE}`,\n          }}\n        >\n          {content}\n        </span>\n      </button>\n    );\n  };\n\n  const renderPlacement = (p: Placement<TMeta>, exitTo: Rect | null) =>\n    p.kind === \"group\" ? renderGroup(p, exitTo) : renderTile(p, exitTo);\n\n  const atRoot = focus === root;\n  const activePath = activeItem ? lineage(activeItem) : [];\n\n  return (\n    <div\n      data-slot=\"treemap\"\n      data-depth={chain.length - 1}\n      className={cn(\n        \"@container/treemap flex min-w-0 flex-col rounded-xl border bg-card text-card-foreground shadow-xs\",\n        className,\n      )}\n      {...props}\n    >\n      <style href=\"overtrue-treemap\" precedence=\"default\">\n        {`@keyframes treemap-tile-in{from{opacity:0;transform:scale(.92)}}`}\n      </style>\n\n      {hasHeader ? (\n        <div className=\"flex flex-wrap items-start justify-between gap-x-6 gap-y-3 px-4 pt-4\">\n          <div className=\"min-w-0 space-y-1\">\n            {title != null ? (\n              <h3 className=\"text-sm leading-5 font-semibold tracking-tight\">\n                {title}\n              </h3>\n            ) : null}\n            {description != null ? (\n              <p\n                id={`${id}-description`}\n                className=\"text-xs text-muted-foreground\"\n              >\n                {description}\n              </p>\n            ) : null}\n          </div>\n          {actions != null ? (\n            <div className=\"flex shrink-0 items-center gap-2\">{actions}</div>\n          ) : null}\n        </div>\n      ) : null}\n\n      <div\n        className={cn(\n          \"flex min-w-0 items-center gap-2 px-4 pb-2.5\",\n          hasHeader ? \"pt-3\" : \"pt-4\",\n        )}\n      >\n        {!atRoot ? (\n          <button\n            type=\"button\"\n            data-slot=\"treemap-up\"\n            aria-label={`Zoom out to ${focus.parent?.label}`}\n            onClick={() => goUp(false)}\n            className=\"grid size-6 shrink-0 place-items-center rounded-md border text-muted-foreground outline-none transition-[color,background-color,opacity,scale] hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 motion-reduce:transition-none motion-safe:starting:scale-75 motion-safe:starting:opacity-0\"\n          >\n            <IconArrowUp aria-hidden=\"true\" size={13} stroke={2} />\n          </button>\n        ) : null}\n        <nav\n          aria-label=\"Treemap level\"\n          data-slot=\"treemap-breadcrumb\"\n          className=\"min-w-0 flex-1\"\n        >\n          <ol className=\"flex min-w-0 items-center gap-0.5 text-xs\">\n            {chain.map((item, position) => {\n              const last = position === chain.length - 1;\n              return (\n                <li\n                  key={item.id}\n                  className={cn(\n                    \"flex min-w-0 items-center gap-0.5\",\n                    last ? \"shrink-0\" : \"shrink\",\n                  )}\n                >\n                  {position > 0 ? (\n                    <IconChevronRight\n                      aria-hidden=\"true\"\n                      size={12}\n                      className=\"shrink-0 text-muted-foreground/60\"\n                    />\n                  ) : null}\n                  {last ? (\n                    <span\n                      aria-current=\"location\"\n                      className=\"flex min-w-0 items-center gap-1.5 px-1 font-medium text-foreground motion-safe:transition-[opacity,translate] motion-safe:duration-300 motion-safe:starting:-translate-x-1 motion-safe:starting:opacity-0\"\n                    >\n                      {item.depth >= 0 ? (\n                        <span\n                          aria-hidden=\"true\"\n                          className=\"size-2 shrink-0 rounded-[2px]\"\n                          style={{ backgroundColor: fillFor(item) }}\n                        />\n                      ) : null}\n                      <span className=\"max-w-[14rem] truncate\">\n                        {item.label}\n                      </span>\n                    </span>\n                  ) : (\n                    <button\n                      type=\"button\"\n                      onClick={() => commitPath(item)}\n                      className=\"max-w-[9rem] truncate rounded-sm px-1 text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 motion-reduce:transition-none\"\n                    >\n                      {item.label}\n                    </button>\n                  )}\n                </li>\n              );\n            })}\n          </ol>\n        </nav>\n        <p className=\"flex shrink-0 items-baseline gap-1.5 tabular-nums\">\n          {!atRoot ? (\n            <span className=\"font-mono text-[10.5px] text-muted-foreground\">\n              {percent(shareOfTotal(focus))}\n            </span>\n          ) : null}\n          <span className=\"text-sm font-semibold tracking-tight\">\n            {format(focus.value, \"detail\")}\n          </span>\n        </p>\n      </div>\n\n      <div className=\"px-4\">\n        <div\n          ref={canvasRef}\n          role=\"group\"\n          aria-roledescription=\"treemap\"\n          aria-label={`${mapLabel}: ${focus.label}, ${focus.children.length} items. Arrow keys move between tiles, Enter zooms in, Backspace zooms out.`}\n          aria-describedby={\n            description != null ? `${id}-description` : undefined\n          }\n          data-slot=\"treemap-canvas\"\n          data-zooming={zoom ? zoom.phase : undefined}\n          onKeyDown={onKeyDown}\n          onPointerLeave={() => setHoveredId(null)}\n          onBlur={(event) => {\n            if (!event.currentTarget.contains(event.relatedTarget as Node))\n              setFocusedId(null);\n          }}\n          className=\"relative w-full overflow-hidden rounded-md\"\n          style={{ height }}\n        >\n          {root.value <= 0 ? (\n            <p className=\"grid h-full place-items-center rounded-md border border-dashed text-xs text-muted-foreground\">\n              Nothing to show.\n            </p>\n          ) : null}\n          {transition && phase\n            ? transition.exits.map(({ placement, to }) =>\n                renderPlacement(placement, to),\n              )\n            : null}\n          {placements.map((p) => renderPlacement(p, null))}\n        </div>\n      </div>\n\n      <div\n        aria-hidden=\"true\"\n        data-slot=\"treemap-readout\"\n        className=\"mt-3 flex min-h-11 min-w-0 flex-wrap items-center gap-x-3 gap-y-1 border-t px-4 py-2.5 text-xs\"\n      >\n        {activeItem && activeItem !== root ? (\n          <>\n            <span className=\"flex min-w-0 items-center gap-1.5\">\n              <span\n                className=\"size-2.5 shrink-0 rounded-[3px]\"\n                style={{ backgroundColor: fillFor(activeItem) }}\n              />\n              {activePath.map((item, position) => (\n                <React.Fragment key={item.id}>\n                  {position > 0 ? (\n                    <IconChevronRight\n                      size={11}\n                      className=\"shrink-0 text-muted-foreground/60\"\n                    />\n                  ) : null}\n                  <span\n                    className={cn(\n                      \"truncate\",\n                      position === activePath.length - 1\n                        ? \"font-medium text-foreground\"\n                        : \"text-muted-foreground\",\n                    )}\n                  >\n                    {item.label}\n                  </span>\n                </React.Fragment>\n              ))}\n            </span>\n            <span className=\"ml-auto flex flex-wrap items-baseline gap-x-3 gap-y-0.5 tabular-nums\">\n              <span className=\"text-sm font-semibold tracking-tight\">\n                {format(activeItem.value, \"detail\")}\n              </span>\n              <span className=\"text-muted-foreground\">\n                <span className=\"font-medium text-foreground\">\n                  {percent(shareOfParent(activeItem))}\n                </span>{\" \"}\n                of {activeItem.parent?.label ?? rootLabel}\n              </span>\n              {activeItem.depth > 0 ? (\n                <span className=\"text-muted-foreground\">\n                  <span className=\"font-medium text-foreground\">\n                    {percent(shareOfTotal(activeItem))}\n                  </span>{\" \"}\n                  of total\n                </span>\n              ) : null}\n            </span>\n          </>\n        ) : (\n          <span className=\"text-muted-foreground\">\n            <span className=\"font-medium text-foreground tabular-nums\">\n              {focus.children.length}\n            </span>{\" \"}\n            {focus.children.length === 1 ? \"item\" : \"items\"}\n            {focus.leafCount !== focus.children.length ? (\n              <>\n                {\" · \"}\n                <span className=\"font-medium text-foreground tabular-nums\">\n                  {focus.leafCount}\n                </span>{\" \"}\n                leaves\n              </>\n            ) : null}\n            <span\n              className={cn(\"hidden\", focus.children.length > 0 && \"sm:inline\")}\n            >\n              {\" · \"}\n              {atRoot\n                ? \"Select a tile to zoom in\"\n                : \"Esc or Backspace to zoom out\"}\n            </span>\n          </span>\n        )}\n      </div>\n\n      <p className=\"sr-only\" aria-live=\"polite\">\n        {atRoot\n          ? \"\"\n          : `${focus.label}: ${format(focus.value, \"detail\")}, ${focus.children.length} items`}\n      </p>\n    </div>\n  );\n}\n\nexport { Treemap };\n"
    },
    {
      "path": "src/registry/overtrue/cohort-grid.tsx",
      "type": "registry:component",
      "target": "components/overtrue/cohort-grid.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\nexport interface CohortGridCohort {\n  id: string;\n  /** Row label, e.g. \"Jan 2026\" or \"Week of Sep 29\". */\n  label: string;\n  /** People who entered the cohort. Retained counts are derived from it. */\n  size: number;\n  /**\n   * Retention per period as a 0–1 fraction, in period order.\n   * Use `null` (or leave the entry out) for periods that have not happened yet.\n   */\n  values: (number | null)[];\n}\n\nexport type CohortGridMode = \"percent\" | \"count\";\n\n/** Everything known about one cell, passed to `onCellSelect`. */\nexport interface CohortGridCell {\n  /** The cohort row, or `null` for the weighted average row. */\n  cohort: CohortGridCohort | null;\n  label: string;\n  period: string;\n  periodIndex: number;\n  /** Retention fraction, or `null` when the period has not happened yet. */\n  value: number | null;\n  /** People still active in this period, or `null` when there is no data yet. */\n  retained: number | null;\n  /** People the retention is measured against. */\n  base: number;\n}\n\nexport interface CohortGridProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"title\"\n> {\n  /** One row per cohort, oldest first so the matrix forms a triangle. */\n  cohorts: CohortGridCohort[];\n  /** Column labels. Defaults to M0, M1, … for the longest cohort. */\n  periods?: string[];\n  /** Show retention as a percentage or as retained people. Color always follows retention. */\n  mode?: CohortGridMode;\n  /** Add a size-weighted average row under the cohorts. */\n  showAverage?: boolean;\n  /** Show the color scale and the pending-period key. */\n  showLegend?: boolean;\n  title?: React.ReactNode;\n  description?: React.ReactNode;\n  /** Controls placed at the top right, such as a percent/count toggle. */\n  actions?: React.ReactNode;\n  /**\n   * Formats a 0–1 retention fraction everywhere. By default cells show whole\n   * percentages and the readout shows one decimal.\n   */\n  valueFormatter?: (value: number) => string;\n  /**\n   * Formats people counts everywhere. By default cells go compact from 1,000 and the\n   * size column from 10,000, while the readout and cell labels stay exact.\n   */\n  countFormatter?: (count: number) => string;\n  /** Any CSS color. Cells mix it with transparency by retention. Defaults to chart-1. */\n  color?: string;\n  /**\n   * Retention mapped to the lightest and strongest fill. Defaults to the range of\n   * the periods after period 0, which is usually 100% by definition.\n   */\n  domain?: [number, number];\n  /** Heading for the label column. */\n  cohortLabel?: string;\n  /** Heading for the cohort size column. */\n  sizeLabel?: string;\n  /** Noun used in the readout and cell labels, e.g. \"subscribers\". */\n  unit?: string;\n  /** Label for the average row. Defaults to \"Weighted avg\", or \"Total retained\" in count mode. */\n  averageLabel?: string;\n  /** Called when a cell with data is clicked or activated with Enter or Space. */\n  onCellSelect?: (cell: CohortGridCell) => void;\n}\n\ntype Position = { row: number; col: number };\n\n/** Precise percent for the readout and cell labels. */\nfunction detailPercent(value: number) {\n  const pct = value * 100;\n  if (pct === 0) return \"0%\";\n  if (pct >= 99.95) return \"100%\";\n  if (pct > 0 && pct < 0.05) return \"<0.1%\";\n  return `${pct.toFixed(1)}%`;\n}\n\n/** Whole percent keeps dense cells quiet; the readout carries the decimals. */\nfunction cellPercent(value: number) {\n  const pct = value * 100;\n  if (pct > 0 && pct < 1) return \"<1%\";\n  return `${Math.round(pct)}%`;\n}\n\nconst compact = new Intl.NumberFormat(\"en-US\", {\n  notation: \"compact\",\n  maximumFractionDigits: 1,\n});\n\nfunction exactCount(count: number) {\n  return count.toLocaleString(\"en-US\");\n}\n\n/** Size column: exact until five digits. */\nfunction sizeCount(count: number) {\n  return Math.abs(count) >= 10_000\n    ? compact.format(count)\n    : count.toLocaleString(\"en-US\");\n}\n\n/** Cells are narrow, so counts go compact from four digits. */\nfunction cellCount(count: number) {\n  return Math.abs(count) >= 1_000\n    ? compact.format(count)\n    : count.toLocaleString(\"en-US\");\n}\n\nfunction clamp(value: number, min: number, max: number) {\n  return Math.min(max, Math.max(min, value));\n}\n\n/** Mix the accent into the card surface so every theme gets its own ramp. */\nfunction fillFor(color: string, t: number) {\n  const pct = Math.round(8 + clamp(t, 0, 1) * 92);\n  return `color-mix(in oklab, ${color} ${pct}%, var(--color-card))`;\n}\n\n/**\n * Pick light or dark text from the fill's own lightness, tinted with its hue, so\n * strong cells stay readable whether the theme's chart color is deep or pale.\n * Browsers without relative color syntax keep the inherited foreground.\n */\nfunction inkFor(fill: string) {\n  return `oklch(from ${fill} clamp(0.2, (0.6 - l) * 1000, 0.985) min(c, 0.035) h)`;\n}\n\n// A short fade on the sticky column's edge, shown once the matrix scrolls under it.\nconst stickyFade =\n  \"after:pointer-events-none after:absolute after:inset-y-0 after:-right-3 after:w-3 after:bg-gradient-to-r after:from-card after:to-transparent after:opacity-0 after:transition-opacity group-data-[scrolled=true]/scroll:after:opacity-100 motion-reduce:after:transition-none\";\n\nconst hatch =\n  \"repeating-linear-gradient(-45deg, color-mix(in oklab, var(--color-muted-foreground) 26%, transparent) 0 1px, transparent 1px 5px)\";\n\n/**\n * A retention cohort matrix. Rows are cohorts, columns are periods since the cohort\n * started, and cell color follows retention. Hover or focus a cell to light up its\n * row and column and read the exact numbers; arrow keys move between cells.\n */\nfunction CohortGrid({\n  cohorts,\n  periods: periodsProp,\n  mode = \"percent\",\n  showAverage = false,\n  showLegend = false,\n  title,\n  description,\n  actions,\n  valueFormatter,\n  countFormatter,\n  color = \"var(--color-chart-1)\",\n  domain,\n  cohortLabel = \"Cohort\",\n  sizeLabel = \"Users\",\n  unit = \"users\",\n  averageLabel,\n  onCellSelect,\n  className,\n  ...props\n}: CohortGridProps) {\n  const formatCell = valueFormatter ?? cellPercent;\n  // Dense spots (cells, the size column) go compact; the readout and labels stay exact.\n  const formatCellCount = countFormatter ?? cellCount;\n  const formatSize = countFormatter ?? sizeCount;\n  const formatExact = countFormatter ?? exactCount;\n  const formatDetail = valueFormatter ?? detailPercent;\n  const id = React.useId();\n  const tableRef = React.useRef<HTMLTableElement>(null);\n  const scrollRef = React.useRef<HTMLDivElement>(null);\n  const [hovered, setHovered] = React.useState<Position | null>(null);\n  const [focused, setFocused] = React.useState<Position | null>(null);\n  const [tabStop, setTabStop] = React.useState<Position>({ row: 0, col: 0 });\n  const [scrolled, setScrolled] = React.useState(false);\n\n  const periodCount =\n    periodsProp?.length ??\n    cohorts.reduce((max, cohort) => Math.max(max, cohort.values.length), 0);\n  const periods = React.useMemo(\n    () =>\n      periodsProp ?? Array.from({ length: periodCount }, (_, i) => `M${i}`),\n    [periodsProp, periodCount],\n  );\n\n  const [low, high] = React.useMemo(() => {\n    if (domain) return domain;\n    // Period 0 is usually 100% by definition, so spend the ramp on the periods after it.\n    const range = (from: number) => {\n      let min = Infinity;\n      let max = -Infinity;\n      for (const cohort of cohorts)\n        for (let i = from; i < cohort.values.length; i++) {\n          const value = cohort.values[i];\n          if (value == null || !Number.isFinite(value)) continue;\n          min = Math.min(min, value);\n          max = Math.max(max, value);\n        }\n      return [min, max] as [number, number];\n    };\n    let [min, max] = range(1);\n    if (!Number.isFinite(min) || min === max) [min, max] = range(0);\n    if (!Number.isFinite(min)) return [0, 1] as [number, number];\n    return [min === max ? 0 : min, max || 1] as [number, number];\n  }, [cohorts, domain]);\n  const span = high - low || 1;\n  const position = (value: number) => clamp((value - low) / span, 0, 1);\n\n  const totalSize = cohorts.reduce((sum, cohort) => sum + cohort.size, 0);\n\n  const average = React.useMemo(\n    () =>\n      periods.map((_, c) => {\n        let base = 0;\n        let retained = 0;\n        let weighted = 0;\n        for (const cohort of cohorts) {\n          const value = cohort.values[c];\n          if (value == null || !Number.isFinite(value)) continue;\n          base += cohort.size;\n          weighted += cohort.size * value;\n          retained += Math.round(cohort.size * value);\n        }\n        return base > 0\n          ? { value: weighted / base, retained, base }\n          : { value: null, retained: null, base: 0 };\n      }),\n    [cohorts, periods],\n  );\n\n  const rowCount = cohorts.length + (showAverage ? 1 : 0);\n  const averageRow = showAverage ? cohorts.length : -1;\n\n  const cellAt = React.useCallback(\n    (row: number, col: number): CohortGridCell => {\n      const period = periods[col] ?? \"\";\n      if (row === averageRow) {\n        const entry = average[col];\n        return {\n          cohort: null,\n          label:\n            averageLabel ??\n            (mode === \"count\" ? \"Total retained\" : \"Weighted avg\"),\n          period,\n          periodIndex: col,\n          value: entry?.value ?? null,\n          retained: entry?.retained ?? null,\n          base: entry?.base ?? 0,\n        };\n      }\n      const cohort = cohorts[row];\n      const raw = cohort?.values[col];\n      const value = raw == null || !Number.isFinite(raw) ? null : raw;\n      return {\n        cohort: cohort ?? null,\n        label: cohort?.label ?? \"\",\n        period,\n        periodIndex: col,\n        value,\n        retained: value == null ? null : Math.round((cohort?.size ?? 0) * value),\n        base: cohort?.size ?? 0,\n      };\n    },\n    [average, averageLabel, averageRow, cohorts, mode, periods],\n  );\n\n  // Keep the roving tab stop inside the matrix when the data shrinks.\n  const stop = {\n    row: clamp(tabStop.row, 0, Math.max(0, rowCount - 1)),\n    col: clamp(tabStop.col, 0, Math.max(0, periods.length - 1)),\n  };\n  const active = hovered ?? focused;\n  const activeCell = active ? cellAt(active.row, active.col) : null;\n\n  const move = (next: Position) => {\n    const row = clamp(next.row, 0, rowCount - 1);\n    const col = clamp(next.col, 0, periods.length - 1);\n    setTabStop({ row, col });\n    const element = tableRef.current?.querySelector<HTMLElement>(\n      `[data-row=\"${row}\"][data-col=\"${col}\"]`,\n    );\n    if (!element) return;\n    element.focus({ preventScroll: true });\n    // Keep the cell clear of the sticky label column while scrolling sideways.\n    const scroller = scrollRef.current;\n    const sticky =\n      tableRef.current?.querySelector<HTMLElement>(\"th\")?.offsetWidth ?? 0;\n    if (scroller) {\n      const left = element.offsetLeft;\n      const right = left + element.offsetWidth;\n      if (left - scroller.scrollLeft < sticky)\n        scroller.scrollLeft = left - sticky;\n      else if (right - scroller.scrollLeft > scroller.clientWidth)\n        scroller.scrollLeft = right - scroller.clientWidth;\n    }\n    element.scrollIntoView({ block: \"nearest\", inline: \"nearest\" });\n  };\n\n  const onKeyDown = (event: React.KeyboardEvent<HTMLTableElement>) => {\n    const target = event.target as HTMLElement;\n    if (target.dataset.slot !== \"cohort-grid-cell\") return;\n    const row = Number(target.dataset.row);\n    const col = Number(target.dataset.col);\n    const last = { row: rowCount - 1, col: periods.length - 1 };\n    const keys: Record<string, Position | undefined> = {\n      ArrowRight: { row, col: col + 1 },\n      ArrowLeft: { row, col: col - 1 },\n      ArrowDown: { row: row + 1, col },\n      ArrowUp: { row: row - 1, col },\n      Home: event.ctrlKey ? { row: 0, col: 0 } : { row, col: 0 },\n      End: event.ctrlKey ? last : { row, col: last.col },\n      PageUp: { row: 0, col },\n      PageDown: { row: last.row, col },\n    };\n    const next = keys[event.key];\n    if (next) {\n      event.preventDefault();\n      move(next);\n      return;\n    }\n    if ((event.key === \"Enter\" || event.key === \" \") && onCellSelect) {\n      const cell = cellAt(row, col);\n      if (cell.value == null) return;\n      event.preventDefault();\n      onCellSelect(cell);\n    }\n  };\n\n  const hasHeader = title != null || description != null || actions != null;\n  const tableLabel =\n    typeof title === \"string\" ? title : \"Cohort retention by period\";\n  const resolvedAverageLabel =\n    averageLabel ?? (mode === \"count\" ? \"Total retained\" : \"Weighted avg\");\n\n  const display = (cell: CohortGridCell) =>\n    cell.value == null\n      ? \"\"\n      : mode === \"count\"\n        ? formatCellCount(cell.retained ?? 0)\n        : formatCell(cell.value);\n\n  const describe = (cell: CohortGridCell) =>\n    cell.value == null\n      ? `${cell.label}, ${cell.period}: no data yet`\n      : `${cell.label}, ${cell.period}: ${formatDetail(cell.value)} retained, ${formatExact(cell.retained ?? 0)} of ${formatExact(cell.base)} ${unit}`;\n\n  const renderCell = (row: number, col: number) => {\n    const cell = cellAt(row, col);\n    const isAverage = row === averageRow;\n    const isActive = active?.row === row && active?.col === col;\n    const inCrosshair =\n      active != null && (active.row === row || active.col === col);\n    const t = cell.value == null ? null : position(cell.value);\n    const fill = t == null ? null : fillFor(color, t);\n    const selectable = onCellSelect != null && cell.value != null;\n\n    return (\n      <td\n        key={col}\n        role=\"gridcell\"\n        data-slot=\"cohort-grid-cell\"\n        data-row={row}\n        data-col={col}\n        data-empty={cell.value == null || undefined}\n        aria-label={describe(cell)}\n        tabIndex={stop.row === row && stop.col === col ? 0 : -1}\n        onPointerEnter={() => setHovered({ row, col })}\n        onFocus={() => {\n          setFocused({ row, col });\n          setTabStop({ row, col });\n        }}\n        onClick={selectable ? () => onCellSelect(cell) : undefined}\n        className={cn(\n          \"group/cell p-[1.5px] outline-none\",\n          isAverage && \"border-t border-dashed pt-2\",\n          col === periods.length - 1 && \"pr-4\",\n          selectable && \"cursor-pointer\",\n        )}\n      >\n        <div\n          data-active={isActive || undefined}\n          className={cn(\n            \"relative flex h-8 min-w-[2.125rem] items-center justify-center rounded-[4px] px-0.5 text-xs tabular-nums transition-[opacity,box-shadow] duration-150 motion-reduce:transition-none\",\n            fill == null ? \"bg-muted/40\" : \"text-foreground\",\n            isAverage ? \"font-semibold\" : \"font-medium\",\n            active != null && !inCrosshair && \"opacity-50\",\n            \"data-[active]:z-10 data-[active]:ring-2 data-[active]:ring-foreground/80 data-[active]:ring-offset-1 data-[active]:ring-offset-card\",\n            \"group-focus-visible/cell:z-10 group-focus-visible/cell:ring-2 group-focus-visible/cell:ring-ring group-focus-visible/cell:ring-offset-1 group-focus-visible/cell:ring-offset-card\",\n          )}\n          style={\n            fill == null\n              ? { backgroundImage: hatch }\n              : { backgroundColor: fill, color: inkFor(fill) }\n          }\n        >\n          <span aria-hidden=\"true\">{display(cell)}</span>\n        </div>\n      </td>\n    );\n  };\n\n  const rowHeader = (row: number, label: string, size: number) => {\n    const isActive = active?.row === row;\n    return (\n      <th\n        scope=\"row\"\n        data-active={isActive || undefined}\n        onPointerEnter={() => setHovered(null)}\n        className={cn(\n          \"sticky left-0 z-20 bg-card py-0 pr-2.5 pl-4 text-left font-normal whitespace-nowrap\",\n          \"before:absolute before:inset-y-2 before:left-1.5 before:w-0.5 before:rounded-full before:bg-foreground before:opacity-0 before:transition-opacity data-[active]:before:opacity-100 motion-reduce:before:transition-none\",\n          stickyFade,\n          row === averageRow && \"border-t border-dashed pt-2\",\n        )}\n      >\n        <span className=\"flex items-baseline justify-between gap-3\">\n          <span\n            className={cn(\n              \"text-xs transition-colors motion-reduce:transition-none\",\n              row === averageRow\n                ? \"font-semibold text-foreground\"\n                : \"font-medium text-foreground/80\",\n              isActive && \"text-foreground\",\n            )}\n          >\n            {label}\n          </span>\n          <span className=\"text-[11px] text-muted-foreground tabular-nums\">\n            {formatSize(size)}\n          </span>\n        </span>\n      </th>\n    );\n  };\n\n  return (\n    <div\n      data-slot=\"cohort-grid\"\n      data-mode={mode}\n      className={cn(\n        \"flex min-w-0 flex-col rounded-xl border bg-card text-card-foreground shadow-xs\",\n        className,\n      )}\n      {...props}\n    >\n      {hasHeader ? (\n        <div className=\"flex flex-wrap items-start justify-between gap-x-6 gap-y-3 px-4 pt-4\">\n          <div className=\"min-w-0 space-y-1\">\n            {title != null ? (\n              <h3 className=\"text-sm leading-5 font-semibold tracking-tight\">\n                {title}\n              </h3>\n            ) : null}\n            {description != null ? (\n              <p id={`${id}-description`} className=\"text-xs text-muted-foreground\">\n                {description}\n              </p>\n            ) : null}\n          </div>\n          {actions != null ? (\n            <div className=\"flex shrink-0 items-center gap-2\">{actions}</div>\n          ) : null}\n        </div>\n      ) : null}\n\n      <div\n        ref={scrollRef}\n        data-scrolled={scrolled}\n        className={cn(\n          \"group/scroll relative overflow-x-auto overscroll-x-contain pb-1\",\n          hasHeader ? \"mt-4\" : \"mt-3\",\n        )}\n        onScroll={(event) => setScrolled(event.currentTarget.scrollLeft > 0)}\n      >\n        <table\n          ref={tableRef}\n          role=\"grid\"\n          aria-label={tableLabel}\n          aria-describedby={description != null ? `${id}-description` : undefined}\n          aria-rowcount={rowCount + 1}\n          aria-colcount={periods.length + 1}\n          onKeyDown={onKeyDown}\n          onPointerLeave={() => setHovered(null)}\n          onBlur={(event) => {\n            if (!event.currentTarget.contains(event.relatedTarget as Node))\n              setFocused(null);\n          }}\n          className=\"w-full border-separate border-spacing-0 text-xs\"\n        >\n          <thead onPointerEnter={() => setHovered(null)}>\n            <tr>\n              <th\n                scope=\"col\"\n                className={cn(\n                  \"sticky left-0 z-20 bg-card pr-2.5 pb-1.5 pl-4 text-left align-bottom font-normal whitespace-nowrap\",\n                  stickyFade,\n                )}\n              >\n                <span className=\"flex items-baseline justify-between gap-3 text-[11px] font-medium text-muted-foreground\">\n                  <span>{cohortLabel}</span>\n                  <span>{sizeLabel}</span>\n                </span>\n              </th>\n              {periods.map((period, col) => {\n                const isActive = active?.col === col;\n                return (\n                  <th\n                    key={col}\n                    scope=\"col\"\n                    data-active={isActive || undefined}\n                    style={{ width: `${100 / Math.max(1, periods.length)}%` }}\n                    className={cn(\n                      \"group/col px-0 pb-1.5 text-center align-bottom text-[11px] font-medium whitespace-nowrap text-muted-foreground tabular-nums transition-colors motion-reduce:transition-none\",\n                      \"data-[active]:text-foreground\",\n                      col === periods.length - 1 && \"pr-4\",\n                    )}\n                  >\n                    <span className=\"relative inline-block px-0.5 after:absolute after:inset-x-0.5 after:-bottom-1 after:h-0.5 after:rounded-full after:bg-foreground after:opacity-0 after:transition-opacity group-data-[active]/col:after:opacity-100 motion-reduce:after:transition-none\">\n                      {period}\n                    </span>\n                  </th>\n                );\n              })}\n            </tr>\n          </thead>\n          <tbody>\n            {cohorts.map((cohort, row) => (\n              <tr key={cohort.id}>\n                {rowHeader(row, cohort.label, cohort.size)}\n                {periods.map((_, col) => renderCell(row, col))}\n              </tr>\n            ))}\n          </tbody>\n          {showAverage ? (\n            <tfoot>\n              <tr>\n                {rowHeader(averageRow, resolvedAverageLabel, totalSize)}\n                {periods.map((_, col) => renderCell(averageRow, col))}\n              </tr>\n            </tfoot>\n          ) : null}\n        </table>\n      </div>\n\n      <div className=\"flex flex-wrap items-center justify-between gap-x-6 gap-y-3 border-t px-4 py-3\">\n        <div\n          aria-hidden=\"true\"\n          data-slot=\"cohort-grid-readout\"\n          className=\"flex min-h-8 min-w-0 flex-wrap items-center gap-x-2.5 gap-y-1 text-xs\"\n        >\n          {activeCell ? (\n            <>\n              <span className=\"font-medium text-foreground\">\n                {activeCell.label}\n              </span>\n              <span className=\"rounded-[4px] border px-1.5 py-px font-mono text-[10.5px] text-muted-foreground\">\n                {activeCell.period}\n              </span>\n              {activeCell.value == null ? (\n                <span className=\"text-muted-foreground\">No data yet</span>\n              ) : (\n                <>\n                  <span className=\"text-sm font-semibold tabular-nums\">\n                    {formatDetail(activeCell.value)}\n                  </span>\n                  <span className=\"text-muted-foreground tabular-nums\">\n                    {formatExact(activeCell.retained ?? 0)} of{\" \"}\n                    {formatExact(activeCell.base)} {unit}\n                  </span>\n                </>\n              )}\n            </>\n          ) : (\n            <span className=\"text-muted-foreground\">\n              <span className=\"font-medium text-foreground tabular-nums\">\n                {cohorts.length}\n              </span>{\" \"}\n              cohorts ·{\" \"}\n              <span className=\"font-medium text-foreground tabular-nums\">\n                {formatExact(totalSize)}\n              </span>{\" \"}\n              {unit}\n              <span className=\"hidden sm:inline\"> · hover a cell for detail</span>\n            </span>\n          )}\n        </div>\n\n        {showLegend ? (\n          <div\n            data-slot=\"cohort-grid-legend\"\n            className=\"flex items-center gap-4 text-[10.5px] text-muted-foreground\"\n          >\n            <span className=\"flex items-center gap-1.5\">\n              <span\n                aria-hidden=\"true\"\n                className=\"size-3 rounded-[3px] bg-muted/40 inset-ring inset-ring-foreground/5\"\n                style={{ backgroundImage: hatch }}\n              />\n              Pending\n            </span>\n            <span className=\"flex flex-col gap-1\">\n              <span\n                aria-hidden=\"true\"\n                className=\"block h-2 w-32 rounded-full inset-ring inset-ring-foreground/5\"\n                style={{\n                  backgroundImage: `linear-gradient(to right, ${fillFor(color, 0)}, ${fillFor(color, 0.5)}, ${fillFor(color, 1)})`,\n                }}\n              />\n              <span className=\"flex justify-between font-mono tabular-nums\">\n                <span>{formatCell(low)}</span>\n                <span className=\"sr-only\"> to </span>\n                <span>{formatCell(high)}</span>\n              </span>\n            </span>\n          </div>\n        ) : null}\n      </div>\n    </div>\n  );\n}\n\nexport { CohortGrid };\n"
    },
    {
      "path": "src/registry/overtrue/bullet-chart.tsx",
      "type": "registry:component",
      "target": "components/overtrue/bullet-chart.tsx",
      "content": "\"use client\";\nimport { useId, type ComponentProps, type ReactNode } from \"react\";\nimport { cn } from \"@/lib/utils\";\n\n/** Ascending thresholds that split the scale into three qualitative ranges. */\nexport type BulletChartRanges = [number, number, number];\nexport type BulletChartQuality = \"poor\" | \"satisfactory\" | \"good\";\n\nexport interface BulletChartItem {\n  id: string;\n  label: string;\n  sublabel?: string;\n  value: number;\n  target: number;\n  /**\n   * Upper bounds of the poor, satisfactory and good ranges, e.g. [600, 800, 1000].\n   * With `invert` the same bounds read good, satisfactory, poor.\n   */\n  ranges?: BulletChartRanges;\n  /** End of the scale. Defaults to the last range, or a rounded value above the data. */\n  max?: number;\n  /** Lower is better, e.g. response time, churn or cost. */\n  invert?: boolean;\n  /** Formats this row's value, target and gap. Overrides the chart's formatter. */\n  valueFormatter?: (value: number) => string;\n}\n\nexport interface BulletChartProps extends Omit<\n  ComponentProps<\"section\">,\n  \"title\" | \"children\"\n> {\n  items: BulletChartItem[];\n  title?: ReactNode;\n  description?: ReactNode;\n  valueFormatter?: (value: number, item: BulletChartItem) => string;\n  size?: \"default\" | \"compact\";\n  /** Paint the measure in the primary color, or by whether it meets its target. */\n  tone?: \"primary\" | \"status\";\n  showLegend?: boolean;\n}\n\nconst numberFormat = new Intl.NumberFormat(\"en-US\", {\n  maximumFractionDigits: 1,\n});\nconst wholePercent = new Intl.NumberFormat(\"en-US\", {\n  style: \"percent\",\n  maximumFractionDigits: 0,\n});\nconst precisePercent = new Intl.NumberFormat(\"en-US\", {\n  style: \"percent\",\n  maximumFractionDigits: 1,\n});\n\nconst bandShade: Record<BulletChartQuality, string> = {\n  poor: \"bg-foreground/[0.15]\",\n  satisfactory: \"bg-foreground/[0.085]\",\n  good: \"bg-foreground/[0.04]\",\n};\n\ntype Status = \"met\" | \"behind\" | \"at-risk\";\n\nconst statusFill: Record<Status, string> = {\n  met: \"bg-emerald-700 dark:bg-emerald-500\",\n  behind: \"bg-amber-700 dark:bg-amber-400\",\n  \"at-risk\": \"bg-red-600 dark:bg-red-400\",\n};\n\nfunction niceCeil(value: number) {\n  if (!(value > 0)) return 1;\n  const magnitude = 10 ** Math.floor(Math.log10(value));\n  const step = [1, 2, 2.5, 5, 10].find((n) => value <= n * magnitude) ?? 10;\n  return step * magnitude;\n}\n\nconst finite = (value: number) => (Number.isFinite(value) ? value : 0);\nconst clampPercent = (value: number, max: number) =>\n  Math.min(100, Math.max(0, (value / max) * 100));\n\nfunction measure(item: BulletChartItem, format: (value: number) => string) {\n  const value = finite(item.value);\n  const target = finite(item.target);\n  const ranges = item.ranges\n    ? ([...item.ranges].map(finite).sort((a, b) => a - b) as BulletChartRanges)\n    : undefined;\n  const peak = Math.max(value, target);\n  const max =\n    item.max && item.max > 0\n      ? item.max\n      : ranges && ranges[2] >= peak && ranges[2] > 0\n        ? ranges[2]\n        : niceCeil(Math.max(peak, ranges?.[2] ?? 0) * 1.1);\n\n  const order: BulletChartQuality[] = item.invert\n    ? [\"good\", \"satisfactory\", \"poor\"]\n    : [\"poor\", \"satisfactory\", \"good\"];\n  const bands = ranges\n    ? ranges.map((end, index) => ({\n        quality: order[index],\n        from: clampPercent(index ? ranges[index - 1] : 0, max),\n        to: clampPercent(end, max),\n      }))\n    : [];\n  const quality = ranges\n    ? order[value < ranges[0] ? 0 : value < ranges[1] ? 1 : 2]\n    : undefined;\n\n  const met = item.invert ? value <= target : value >= target;\n  const status: Status = met\n    ? \"met\"\n    : quality === \"poor\"\n      ? \"at-risk\"\n      : \"behind\";\n  const ratio = target ? value / target : undefined;\n  const gap = value - target;\n  const gapShort =\n    gap === 0\n      ? \"on target\"\n      : `${format(Math.abs(gap))} ${gap > 0 ? \"above\" : \"below\"}`;\n\n  const formattedValue = format(value);\n  const formattedTarget = format(target);\n  const summary = [\n    `${item.label}: ${formattedValue} of ${formattedTarget} target`,\n    ratio !== undefined ? ` (${wholePercent.format(ratio)})` : \"\",\n    item.invert ? \", lower is better\" : \"\",\n    quality ? `, ${quality} range` : \"\",\n    gap === 0 ? \". On target.\" : `. ${gapShort} target.`,\n  ].join(\"\");\n\n  return {\n    value,\n    target,\n    bands,\n    status,\n    ratio,\n    gapShort,\n    formattedValue,\n    formattedTarget,\n    summary,\n    valuePercent: clampPercent(value, max),\n    targetPercent: clampPercent(target, max),\n  };\n}\n\n/** Stephen Few's bullet graph: a measure against its target over qualitative ranges. */\nexport function BulletChart({\n  items,\n  title,\n  description,\n  valueFormatter,\n  size = \"default\",\n  tone = \"primary\",\n  showLegend = true,\n  className,\n  ...props\n}: BulletChartProps) {\n  const titleId = useId();\n  const compact = size === \"compact\";\n  const hasHeader = Boolean(title || description || showLegend);\n\n  return (\n    <section\n      data-slot=\"bullet-chart\"\n      data-size={size}\n      aria-labelledby={title ? titleId : undefined}\n      className={cn(\n        \"@container/bullet rounded-xl border bg-card text-card-foreground shadow-xs\",\n        compact ? \"p-4\" : \"p-5 @lg/bullet:p-6\",\n        className,\n      )}\n      {...props}\n    >\n      {hasHeader && (\n        <header\n          className={cn(\n            \"flex flex-wrap items-start justify-between gap-x-6 gap-y-3\",\n            compact ? \"mb-3\" : \"mb-5\",\n          )}\n        >\n          {(title || description) && (\n            <div className=\"min-w-0\">\n              {title && (\n                <h3\n                  id={titleId}\n                  className={cn(\n                    \"leading-tight font-semibold tracking-tight\",\n                    compact ? \"text-sm\" : \"text-base\",\n                  )}\n                >\n                  {title}\n                </h3>\n              )}\n              {description && (\n                <p\n                  className={cn(\n                    \"mt-1 text-muted-foreground\",\n                    compact ? \"text-xs\" : \"text-sm\",\n                  )}\n                >\n                  {description}\n                </p>\n              )}\n            </div>\n          )}\n          {showLegend && <Legend tone={tone} />}\n        </header>\n      )}\n\n      <ul\n        role=\"list\"\n        className={cn(\n          \"grid grid-cols-[minmax(0,1fr)_auto] gap-x-4\",\n          \"@min-[25rem]/bullet:grid-cols-[fit-content(11rem)_minmax(0,1fr)_auto] @lg/bullet:gap-x-5\",\n          compact ? \"gap-y-0.5\" : \"gap-y-1\",\n        )}\n      >\n        {items.map((item, index) => {\n          const format = item.valueFormatter\n            ? item.valueFormatter\n            : valueFormatter\n              ? (value: number) => valueFormatter(value, item)\n              : (value: number) => numberFormat.format(value);\n          const row = measure(item, format);\n          return (\n            <li\n              key={item.id}\n              tabIndex={0}\n              data-status={row.status}\n              className={cn(\n                \"group relative col-span-2 -mx-3 grid grid-cols-subgrid items-center gap-y-2 rounded-lg px-3 outline-none\",\n                \"transition-colors hover:bg-muted/60 focus-visible:bg-muted/60 focus-visible:ring-2 focus-visible:ring-ring/50\",\n                \"@min-[25rem]/bullet:col-span-3\",\n                compact ? \"py-2\" : \"py-2.5\",\n              )}\n            >\n              <span className=\"sr-only\">{row.summary}</span>\n\n              <div\n                aria-hidden=\"true\"\n                className=\"col-start-1 row-start-1 min-w-0\"\n              >\n                {compact ? (\n                  <p className=\"truncate text-[13px] leading-5\">\n                    <span className=\"font-medium\">{item.label}</span>\n                    {item.sublabel && (\n                      <span className=\"ml-1.5 text-xs text-muted-foreground\">\n                        {item.sublabel}\n                      </span>\n                    )}\n                  </p>\n                ) : (\n                  <>\n                    <p className=\"truncate text-sm leading-5 font-medium\">\n                      {item.label}\n                    </p>\n                    {item.sublabel && (\n                      <p className=\"truncate text-xs leading-4 text-muted-foreground\">\n                        {item.sublabel}\n                      </p>\n                    )}\n                  </>\n                )}\n              </div>\n\n              <div\n                aria-hidden=\"true\"\n                className=\"col-start-2 row-start-1 text-right tabular-nums @min-[25rem]/bullet:col-start-3\"\n              >\n                {compact ? (\n                  <p className=\"text-[13px] leading-5 whitespace-nowrap\">\n                    <span className=\"font-semibold\">{row.formattedValue}</span>\n                    <span className=\"text-muted-foreground\">\n                      {\" \"}\n                      / {row.formattedTarget}\n                    </span>\n                  </p>\n                ) : (\n                  <>\n                    <p className=\"text-sm leading-5 font-semibold whitespace-nowrap\">\n                      {row.formattedValue}\n                    </p>\n                    <p className=\"text-xs leading-4 whitespace-nowrap text-muted-foreground\">\n                      of {row.formattedTarget}\n                    </p>\n                  </>\n                )}\n              </div>\n\n              <div\n                aria-hidden=\"true\"\n                className={cn(\n                  \"relative col-span-2 row-start-2 @min-[25rem]/bullet:col-span-1 @min-[25rem]/bullet:col-start-2 @min-[25rem]/bullet:row-start-1\",\n                  compact ? \"h-4\" : \"h-6\",\n                )}\n              >\n                <div\n                  className={cn(\n                    \"absolute inset-0 overflow-hidden rounded-[3px]\",\n                    row.bands.length ? \"bg-foreground/[0.02]\" : \"bg-muted\",\n                  )}\n                >\n                  {row.bands.map((band) => (\n                    <div\n                      key={band.quality}\n                      className={cn(\n                        \"absolute inset-y-0\",\n                        bandShade[band.quality],\n                      )}\n                      style={{\n                        left: `${band.from}%`,\n                        width: `${band.to - band.from}%`,\n                      }}\n                    />\n                  ))}\n                </div>\n                <div\n                  className={cn(\n                    \"absolute left-0 origin-left rounded-[2px] transition-[width,transform,background-color] duration-700 ease-[cubic-bezier(0.22,1,0.36,1)] starting:[transform:scaleX(0)] motion-reduce:transition-none\",\n                    compact ? \"top-[5px] h-1.5\" : \"top-2 h-2\",\n                    tone === \"status\" ? statusFill[row.status] : \"bg-primary\",\n                  )}\n                  style={{\n                    width: `${row.valuePercent}%`,\n                    transitionDelay: `${80 + index * 70}ms`,\n                  }}\n                />\n                <div\n                  className={cn(\n                    \"absolute w-0.5 -translate-x-1/2 rounded-full bg-foreground transition-[left,opacity] duration-500 starting:opacity-0 motion-reduce:transition-none\",\n                    compact ? \"inset-y-0.5\" : \"inset-y-1\",\n                  )}\n                  style={{\n                    left: `${row.targetPercent}%`,\n                    transitionDelay: `${360 + index * 70}ms`,\n                  }}\n                />\n\n                {/* The readout slides along with the measure: at X% it is shifted\n                    by X% of its own width, so it never leaves the track and its\n                    caret always points at the end of the bar. */}\n                <div\n                  className={cn(\n                    \"pointer-events-none absolute bottom-full z-10 mb-2.5 translate-y-1 rounded-md bg-foreground px-2.5 py-1.5 font-mono text-[11px] leading-4 whitespace-nowrap text-background tabular-nums opacity-0 shadow-lg shadow-black/10 transition-[opacity,translate] duration-150\",\n                    \"group-hover:translate-y-0 group-hover:opacity-100 group-focus-visible:translate-y-0 group-focus-visible:opacity-100 motion-reduce:transition-none\",\n                  )}\n                  style={{\n                    left: `${row.valuePercent}%`,\n                    transform: `translateX(-${row.valuePercent}%)`,\n                  }}\n                >\n                  <p>\n                    <span className=\"font-semibold\">{row.formattedValue}</span>\n                    <span className=\"opacity-60\"> / {row.formattedTarget}</span>\n                  </p>\n                  <p>\n                    <span>\n                      {row.ratio !== undefined\n                        ? precisePercent.format(row.ratio)\n                        : \"—\"}\n                    </span>\n                    <span className=\"opacity-40\"> · </span>\n                    <span\n                      className={\n                        row.status === \"met\"\n                          ? \"text-emerald-400 dark:text-emerald-700\"\n                          : row.status === \"behind\"\n                            ? \"text-amber-300 dark:text-amber-800\"\n                            : \"text-red-400 dark:text-red-700\"\n                      }\n                    >\n                      {row.gapShort}\n                    </span>\n                  </p>\n                  <span\n                    className=\"absolute top-full size-2 -translate-x-1/2 -translate-y-1/2 rotate-45 rounded-[1px] bg-foreground\"\n                    style={{\n                      left: `clamp(8px, ${row.valuePercent}%, calc(100% - 8px))`,\n                    }}\n                  />\n                </div>\n              </div>\n            </li>\n          );\n        })}\n      </ul>\n    </section>\n  );\n}\n\nfunction Legend({ tone }: { tone: \"primary\" | \"status\" }) {\n  return (\n    <ul className=\"flex flex-wrap items-center gap-x-4 gap-y-1.5 text-xs text-muted-foreground\">\n      <li className=\"flex items-center gap-1.5\">\n        <span\n          aria-hidden=\"true\"\n          className=\"flex h-2.5 w-9 overflow-hidden rounded-[2px]\"\n        >\n          <span className={cn(\"flex-1\", bandShade.poor)} />\n          <span className={cn(\"flex-1\", bandShade.satisfactory)} />\n          <span className={cn(\"flex-1\", bandShade.good)} />\n        </span>\n        Poor → good\n      </li>\n      {tone === \"status\" ? (\n        (\n          [\n            [\"met\", \"Met\"],\n            [\"behind\", \"Behind\"],\n            [\"at-risk\", \"At risk\"],\n          ] as const\n        ).map(([status, label]) => (\n          <li key={status} className=\"flex items-center gap-1.5\">\n            <span\n              aria-hidden=\"true\"\n              className={cn(\"h-1.5 w-3 rounded-[1px]\", statusFill[status])}\n            />\n            {label}\n          </li>\n        ))\n      ) : (\n        <li className=\"flex items-center gap-1.5\">\n          <span\n            aria-hidden=\"true\"\n            className=\"h-1.5 w-3 rounded-[1px] bg-primary\"\n          />\n          Actual\n        </li>\n      )}\n      <li className=\"flex items-center gap-1.5\">\n        <span\n          aria-hidden=\"true\"\n          className=\"h-3 w-0.5 rounded-full bg-foreground\"\n        />\n        Target\n      </li>\n    </ul>\n  );\n}\n"
    }
  ],
  "docs": "Documentation: https://ui.overtrue.xyz/blocks/revenue-overview. Requires an initialized shadcn/ui project with Tailwind CSS v4."
}
