{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "sankey-chart",
  "type": "registry:component",
  "title": "Flow diagram",
  "description": "Trace how time or budget moves from one category to the next.",
  "categories": [
    "charts"
  ],
  "dependencies": [
    "recharts-analytics@npm:recharts@3.10.1"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "src/registry/overtrue/sankey-chart.tsx",
      "type": "registry:component",
      "target": "components/overtrue/sankey-chart.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 */\n\"use client\";\n\nimport * as React from \"react\";\nimport {\n  Sankey,\n  type SankeyLinkProps,\n  type SankeyNode as RechartsSankeyNode,\n  type SankeyNodeProps,\n} from \"recharts-analytics\";\n\nimport { cn } from \"@/lib/utils\";\nimport { formatNumber } from \"./metric-format\";\nimport {\n  ChartContainer,\n  ChartTooltip,\n  type ChartConfig,\n} from \"./analytics-chart\";\n\nexport interface SankeyChartNode {\n  name: string;\n  /** Any CSS color. Sources default to the palette in order; targets inherit the color of their largest incoming link. */\n  color?: string;\n}\n\nexport interface SankeyChartLink {\n  /** Node name or index into `nodes`. */\n  source: number | string;\n  /** Node name or index into `nodes`. */\n  target: number | string;\n  value: number;\n}\n\nexport interface SankeyChartProps extends Omit<\n  React.ComponentProps<typeof ChartContainer>,\n  \"config\" | \"children\"\n> {\n  nodes: SankeyChartNode[];\n  links: SankeyChartLink[];\n  valueFormatter?: (value: number) => string;\n  /** Append each node's share of the total flow to its label, e.g. \"Writing · 18%\". */\n  showShares?: boolean;\n  showTooltip?: boolean;\n  nodeWidth?: number;\n  /** Vertical gap between nodes in the same column. */\n  nodePadding?: number;\n  /** Fill opacity of the links. Hovered links are drawn at double this, up to 1. */\n  linkOpacity?: number;\n  /** \"outside\" reserves a margin and puts labels left of sources and right of targets; \"inside\" draws them over the flow. */\n  labelPosition?: \"outside\" | \"inside\";\n  /** Palette cycled through source nodes without a color. Defaults to chart-1 through chart-5. */\n  colors?: string[];\n  /** Draw the flow in from left to right on mount. Respects reduced motion. */\n  animate?: boolean;\n}\n\nconst DEFAULT_COLORS = [\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\n/** Approximate rendered width of a text-xs string, for reserving label margins. */\nconst CHAR_WIDTH = 6.4;\nconst LABEL_GAP = 8;\n\ninterface ResolvedNode {\n  name: string;\n  color: string;\n  /** Share of the total flow, as a fraction. */\n  share: number;\n  /** Which side of the node bar the label is drawn on. */\n  side: \"left\" | \"right\";\n  /** Label text next to the node, share included. */\n  label: string;\n  shareLabel: string;\n}\n\ninterface ResolvedLink {\n  source: number;\n  target: number;\n  value: number;\n}\n\ntype Hover = { kind: \"node\"; index: number } | { kind: \"link\"; index: number };\n\nfunction round(n: number) {\n  return Math.round(n * 1000) / 1000;\n}\n\nfunction slugify(name: string) {\n  return name.toLowerCase().replace(/[^a-z0-9]+/g, \"-\");\n}\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    () => true,\n  );\n}\n\nfunction percent(share: number) {\n  return formatNumber(share, { format: \"percent\", maximumFractionDigits: 0 });\n}\n\n/**\n * A flow diagram on shadcn's chart primitives. Links blend from their source color\n * to their target color; hovering a node traces every flow through it, and hovering\n * a link isolates it.\n */\nfunction SankeyChart({\n  nodes,\n  links,\n  valueFormatter = (value) => formatNumber(value),\n  showShares = true,\n  showTooltip = true,\n  nodeWidth = 12,\n  nodePadding = 16,\n  linkOpacity = 0.25,\n  labelPosition = \"outside\",\n  colors = DEFAULT_COLORS,\n  animate = true,\n  className,\n  ...props\n}: SankeyChartProps) {\n  const palette = colors.length ? colors : DEFAULT_COLORS;\n  const hoverOpacity = Math.min(1, linkOpacity * 2);\n  const reduced = useReducedMotion();\n  const motion = animate && !reduced;\n  const uid = React.useId().replace(/[^a-zA-Z0-9_-]/g, \"\");\n  const [hover, setHover] = React.useState<Hover | null>(null);\n\n  const { data, margin, config, outgoing, total, indexByName } =\n    React.useMemo(() => {\n      const indexByName = new Map(\n        nodes.map((node, index) => [node.name, index]),\n      );\n      const resolveIndex = (ref: number | string) =>\n        typeof ref === \"number\"\n          ? Number.isInteger(ref) && ref >= 0 && ref < nodes.length\n            ? ref\n            : -1\n          : (indexByName.get(ref) ?? -1);\n\n      const resolvedLinks: ResolvedLink[] = links\n        .map((link) => ({\n          source: resolveIndex(link.source),\n          target: resolveIndex(link.target),\n          value: link.value,\n        }))\n        .filter(\n          (link) =>\n            link.source >= 0 &&\n            link.target >= 0 &&\n            link.source !== link.target &&\n            Number.isFinite(link.value) &&\n            link.value > 0,\n        );\n\n      const incoming = nodes.map(() => 0);\n      const outgoing = nodes.map(() => 0);\n      const strongestSource = nodes.map<number | null>(() => null);\n      const strongestValue = nodes.map(() => 0);\n      for (const link of resolvedLinks) {\n        outgoing[link.source]! += link.value;\n        incoming[link.target]! += link.value;\n        if (link.value > strongestValue[link.target]!) {\n          strongestValue[link.target] = link.value;\n          strongestSource[link.target] = link.source;\n        }\n      }\n\n      const isRoot = nodes.map((_, index) => incoming[index] === 0);\n      const isLeaf = nodes.map((_, index) => outgoing[index] === 0);\n      const values = nodes.map((_, index) =>\n        Math.max(incoming[index]!, outgoing[index]!),\n      );\n      const total = values.reduce(\n        (sum, value, index) => (isRoot[index] ? sum + value : sum),\n        0,\n      );\n\n      // Roots cycle through the palette; everything else inherits its strongest source.\n      const resolvedColors: (string | undefined)[] = nodes.map(() => undefined);\n      let paletteIndex = 0;\n      nodes.forEach((node, index) => {\n        if (node.color) resolvedColors[index] = node.color;\n        else if (isRoot[index])\n          resolvedColors[index] = palette[paletteIndex++ % palette.length];\n      });\n      const colorOf = (index: number, seen: Set<number>): string => {\n        const known = resolvedColors[index];\n        if (known) return known;\n        const source = strongestSource[index] ?? null;\n        if (source !== null && !seen.has(index)) {\n          seen.add(index);\n          const inherited = colorOf(source, seen);\n          resolvedColors[index] = inherited;\n          return inherited;\n        }\n        const fallback = palette[paletteIndex++ % palette.length]!;\n        resolvedColors[index] = fallback;\n        return fallback;\n      };\n\n      const resolvedNodes: ResolvedNode[] = nodes.map((node, index) => {\n        const share = total > 0 ? values[index]! / total : 0;\n        const shareLabel = showShares ? ` · ${percent(share)}` : \"\";\n        const side: ResolvedNode[\"side\"] =\n          labelPosition === \"outside\"\n            ? isRoot[index] && !isLeaf[index]\n              ? \"left\"\n              : \"right\"\n            : isLeaf[index] && !isRoot[index]\n              ? \"left\"\n              : \"right\";\n        return {\n          name: node.name,\n          color: colorOf(index, new Set()),\n          share,\n          side,\n          label: node.name,\n          shareLabel,\n        };\n      });\n\n      const labelWidth = (node: ResolvedNode) =>\n        Math.ceil((node.label.length + node.shareLabel.length) * CHAR_WIDTH) +\n        LABEL_GAP;\n      const widest = (predicate: (index: number) => boolean) =>\n        resolvedNodes.reduce(\n          (max, node, index) =>\n            predicate(index) && values[index]! > 0\n              ? Math.max(max, labelWidth(node))\n              : max,\n          0,\n        );\n      const margin =\n        labelPosition === \"outside\"\n          ? {\n              top: 4,\n              bottom: 4,\n              left: widest((index) => resolvedNodes[index]!.side === \"left\"),\n              right: widest((index) => resolvedNodes[index]!.side === \"right\"),\n            }\n          : { top: 4, bottom: 4, left: 4, right: 4 };\n\n      const config = Object.fromEntries(\n        resolvedNodes.map((node) => [\n          slugify(node.name),\n          { label: node.name, color: node.color },\n        ]),\n      ) satisfies ChartConfig;\n\n      return {\n        data: { nodes: resolvedNodes, links: resolvedLinks },\n        margin,\n        config,\n        outgoing,\n        total,\n        indexByName,\n      };\n    }, [nodes, links, palette, showShares, labelPosition]);\n\n  // Everything upstream and downstream of the hovered node, or just the hovered link.\n  const highlight = React.useMemo(() => {\n    if (!hover) return null;\n    const lit = new Set<number>();\n    const litNodes = new Set<number>();\n    const all = data.links;\n    if (hover.kind === \"link\") {\n      const link = all[hover.index];\n      if (!link) return null;\n      lit.add(hover.index);\n      litNodes.add(link.source).add(link.target);\n      return { links: lit, nodes: litNodes };\n    }\n    litNodes.add(hover.index);\n    const walk = (from: number, forward: boolean) => {\n      const queue = [from];\n      const seen = new Set([from]);\n      while (queue.length) {\n        const node = queue.shift()!;\n        all.forEach((link, index) => {\n          if ((forward ? link.source : link.target) !== node) return;\n          lit.add(index);\n          const next = forward ? link.target : link.source;\n          litNodes.add(next);\n          if (!seen.has(next)) {\n            seen.add(next);\n            queue.push(next);\n          }\n        });\n      }\n    };\n    walk(hover.index, true);\n    walk(hover.index, false);\n    return { links: lit, nodes: litNodes };\n  }, [hover, data.links]);\n\n  const nodeIndexOf = React.useCallback(\n    (node: { name?: unknown }) => indexByName.get(String(node.name)) ?? -1,\n    [indexByName],\n  );\n\n  const linkIndexOf = React.useCallback(\n    (source: number, target: number) =>\n      data.links.findIndex(\n        (link) => link.source === source && link.target === target,\n      ),\n    [data.links],\n  );\n\n  const renderNode = (nodeProps: SankeyNodeProps) => {\n    const { x, y, width, height, payload } = nodeProps;\n    const node = payload as unknown as RechartsSankeyNode & ResolvedNode;\n    if (!(node.value > 0) || !(height > 0)) return null;\n    const index = nodeIndexOf(node);\n    const radius = Math.min(3, width / 2, height / 2);\n    const labelX = node.side === \"left\" ? x - LABEL_GAP : x + width + LABEL_GAP;\n    const dimmed = highlight != null && !highlight.nodes.has(index);\n    const active = hover?.kind === \"node\" && hover.index === index;\n    return (\n      <g\n        data-slot=\"sankey-node\"\n        data-active={active || undefined}\n        onPointerEnter={() => setHover({ kind: \"node\", index })}\n        onPointerLeave={() => setHover(null)}\n        className=\"cursor-default transition-opacity duration-150 motion-reduce:transition-none\"\n        style={{ opacity: dimmed ? 0.3 : 1 }}\n      >\n        <rect\n          x={round(x)}\n          y={round(y)}\n          width={round(width)}\n          height={round(height)}\n          rx={round(radius)}\n          fill={node.color}\n          className={cn(\n            \"[transform-box:fill-box] [transform-origin:center] dark:[filter:drop-shadow(0_0_6px_color-mix(in_oklab,var(--sankey-node)_45%,transparent))]\",\n            motion &&\n              \"motion-safe:animate-[sankey-node-in_600ms_cubic-bezier(0.22,1,0.36,1)_backwards]\",\n          )}\n          style={{\n            [\"--sankey-node\" as string]: node.color,\n            animationDelay: motion ? `${Math.round(x * 0.9)}ms` : undefined,\n          }}\n        />\n        {/* A soft highlight along the leading edge gives the bar a little depth. */}\n        <rect\n          x={round(x)}\n          y={round(y)}\n          width={round(Math.min(2, width / 3))}\n          height={round(height)}\n          rx={round(Math.min(1, radius))}\n          fill=\"#fff\"\n          fillOpacity={0.18}\n          pointerEvents=\"none\"\n        />\n        <text\n          x={round(labelX)}\n          y={round(y + height / 2)}\n          textAnchor={node.side === \"left\" ? \"end\" : \"start\"}\n          dominantBaseline=\"middle\"\n          className={cn(\n            \"fill-foreground text-xs\",\n            motion &&\n              \"motion-safe:animate-[sankey-label-in_500ms_ease-out_backwards]\",\n          )}\n          style={{\n            animationDelay: motion\n              ? `${Math.round(240 + x * 0.9)}ms`\n              : undefined,\n          }}\n        >\n          <tspan className={active ? \"font-semibold\" : \"font-medium\"}>\n            {node.label}\n          </tspan>\n          {node.shareLabel ? (\n            <tspan className=\"fill-muted-foreground text-[11px] tabular-nums\">\n              {node.shareLabel}\n            </tspan>\n          ) : null}\n        </text>\n      </g>\n    );\n  };\n\n  const renderLink = (linkProps: SankeyLinkProps) => {\n    const {\n      sourceX,\n      sourceY,\n      sourceControlX,\n      targetX,\n      targetY,\n      targetControlX,\n      linkWidth,\n      payload,\n    } = linkProps;\n    const source = payload.source as RechartsSankeyNode & ResolvedNode;\n    const target = payload.target as RechartsSankeyNode & ResolvedNode;\n    const index = linkIndexOf(nodeIndexOf(source), nodeIndexOf(target));\n    const half = Math.max(linkWidth, 0.5) / 2;\n    const top = (yValue: number) => round(yValue - half);\n    const bottom = (yValue: number) => round(yValue + half);\n    const d = [\n      `M${round(sourceX)},${top(sourceY)}`,\n      `C${round(sourceControlX)},${top(sourceY)} ${round(targetControlX)},${top(targetY)} ${round(targetX)},${top(targetY)}`,\n      `L${round(targetX)},${bottom(targetY)}`,\n      `C${round(targetControlX)},${bottom(targetY)} ${round(sourceControlX)},${bottom(sourceY)} ${round(sourceX)},${bottom(sourceY)}`,\n      \"Z\",\n    ].join(\" \");\n    const gradientId = `${uid}-link-${index}`;\n    const lit = highlight?.links.has(index) ?? false;\n    const opacity =\n      highlight == null\n        ? linkOpacity\n        : lit\n          ? hoverOpacity\n          : Math.max(0.04, linkOpacity * 0.3);\n    return (\n      <g>\n        <defs>\n          <linearGradient\n            id={gradientId}\n            gradientUnits=\"userSpaceOnUse\"\n            x1={round(sourceX)}\n            x2={round(targetX)}\n            y1={0}\n            y2={0}\n          >\n            <stop offset=\"0%\" stopColor={source.color} />\n            <stop offset=\"100%\" stopColor={target.color} />\n          </linearGradient>\n        </defs>\n        <path\n          data-slot=\"sankey-link\"\n          data-active={lit || undefined}\n          d={d}\n          fill={`url(#${gradientId})`}\n          fillOpacity={opacity}\n          stroke=\"none\"\n          onPointerEnter={() => setHover({ kind: \"link\", index })}\n          onPointerLeave={() => setHover(null)}\n          className={cn(\n            \"transition-[fill-opacity] duration-150 motion-reduce:transition-none\",\n            // Dark surfaces swallow translucent fills, so resting links get a little more body there.\n            highlight == null &&\n              \"dark:[fill-opacity:min(1,calc(var(--sankey-link-opacity)*1.5))] hover:[fill-opacity:var(--sankey-link-hover-opacity)]\",\n            motion &&\n              \"motion-safe:animate-[sankey-link-in_800ms_cubic-bezier(0.22,1,0.36,1)_backwards]\",\n          )}\n          style={\n            {\n              \"--sankey-link-hover-opacity\": hoverOpacity,\n              \"--sankey-link-opacity\": linkOpacity,\n              animationDelay: motion\n                ? `${Math.round(120 + sourceX * 0.9)}ms`\n                : undefined,\n            } as React.CSSProperties\n          }\n        />\n      </g>\n    );\n  };\n\n  return (\n    <ChartContainer\n      data-slot=\"sankey-chart\"\n      data-hover={hover?.kind}\n      config={config}\n      className={cn(\"aspect-auto h-72 w-full\", className)}\n      {...props}\n    >\n      <>\n        <style href=\"overtrue-sankey-chart\" precedence=\"default\">\n          {`@keyframes sankey-link-in{from{clip-path:inset(0 100% 0 0);opacity:.4}to{clip-path:inset(0 0 0 0);opacity:1}}@keyframes sankey-node-in{from{opacity:0;transform:scaleY(.3)}}@keyframes sankey-label-in{from{opacity:0}}`}\n        </style>\n        <Sankey\n          data={data}\n          nodeWidth={nodeWidth}\n          nodePadding={nodePadding}\n          linkCurvature={0.5}\n          margin={margin}\n          node={renderNode}\n          link={renderLink}\n        >\n          {showTooltip ? (\n            <ChartTooltip\n              cursor={false}\n              isAnimationActive={false}\n              content={(tooltipProps) => {\n                const item = tooltipProps.payload?.[0];\n                if (!tooltipProps.active || !item) return null;\n                // Links carry their source and target as node indexes (or nodes); nodes carry their own meta.\n                // Recharts wraps the link or node in `{ payload, name, value }`.\n                const wrapper = item.payload as\n                  Record<string, unknown> | undefined;\n                const raw = (wrapper?.payload ?? wrapper) as\n                  Record<string, unknown> | undefined;\n                const nodeAt = (ref: unknown) =>\n                  (typeof ref === \"number\"\n                    ? data.nodes[ref]\n                    : typeof ref === \"object\" && ref !== null\n                      ? (ref as ResolvedNode)\n                      : undefined) as ResolvedNode | undefined;\n                const source = nodeAt(raw?.source);\n                const target = nodeAt(raw?.target);\n                const isLink = source !== undefined && target !== undefined;\n                const value = Number(item.value);\n                const sourceIndex = isLink ? nodeIndexOf(source) : -1;\n                const out = sourceIndex >= 0 ? outgoing[sourceIndex] : 0;\n                return (\n                  <div className=\"grid min-w-44 gap-1 rounded-xl border border-border/70 bg-popover/90 px-3 py-2.5 text-xs text-popover-foreground shadow-xl backdrop-blur-md\">\n                    <div className=\"flex items-center gap-2\">\n                      <span\n                        aria-hidden=\"true\"\n                        className=\"h-2.5 w-3.5 shrink-0 rounded-[3px]\"\n                        style={{\n                          background: isLink\n                            ? `linear-gradient(to right, ${source.color}, ${target.color})`\n                            : String(raw?.color ?? \"var(--color-foreground)\"),\n                        }}\n                      />\n                      <span className=\"font-medium text-foreground\">\n                        {isLink ? (\n                          <>\n                            {source.name}\n                            <span className=\"px-1 text-muted-foreground\">\n                              →\n                            </span>\n                            {target.name}\n                          </>\n                        ) : (\n                          String(raw?.name ?? wrapper?.name ?? item.name)\n                        )}\n                      </span>\n                      <span className=\"ml-auto pl-4 font-semibold text-foreground tabular-nums\">\n                        {valueFormatter(value)}\n                      </span>\n                    </div>\n                    <div className=\"pl-[22px] text-[11px] text-muted-foreground tabular-nums\">\n                      {isLink\n                        ? out\n                          ? `${percent(value / out)} of ${source.name}`\n                          : null\n                        : total\n                          ? `${percent(value / total)} of total flow`\n                          : null}\n                    </div>\n                  </div>\n                );\n              }}\n            />\n          ) : null}\n        </Sankey>\n      </>\n    </ChartContainer>\n  );\n}\n\nexport { SankeyChart };\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/analytics-chart.tsx",
      "type": "registry:component",
      "target": "components/overtrue/analytics-chart.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 */\n\"use client\";\n\nimport * as React from \"react\";\nimport * as RechartsPrimitive from \"recharts-analytics\";\nimport type { TooltipValueType } from \"recharts-analytics\";\n\nimport { cn } from \"@/lib/utils\";\n\n// Format: { THEME_NAME: CSS_SELECTOR }\nconst THEMES = { light: \"\", dark: \".dark\" } as const;\n\nconst INITIAL_DIMENSION = { width: 320, height: 200 } as const;\ntype TooltipNameType = number | string;\n\nexport type ChartConfig = Record<\n  string,\n  {\n    label?: React.ReactNode;\n    icon?: React.ComponentType;\n  } & (\n    | { color?: string; theme?: never }\n    | { color?: never; theme: Record<keyof typeof THEMES, string> }\n  )\n>;\n\ntype ChartContextProps = {\n  config: ChartConfig;\n};\n\nconst ChartContext = React.createContext<ChartContextProps | null>(null);\n\nfunction useChart() {\n  const context = React.useContext(ChartContext);\n\n  if (!context) {\n    throw new Error(\"useChart must be used within a <ChartContainer />\");\n  }\n\n  return context;\n}\n\nfunction ChartContainer({\n  id,\n  className,\n  children,\n  config,\n  initialDimension = INITIAL_DIMENSION,\n  ...props\n}: React.ComponentProps<\"div\"> & {\n  config: ChartConfig;\n  children: React.ComponentProps<\n    typeof RechartsPrimitive.ResponsiveContainer\n  >[\"children\"];\n  initialDimension?: {\n    width: number;\n    height: number;\n  };\n}) {\n  const uniqueId = React.useId();\n  const chartId = `chart-${id ?? uniqueId.replace(/:/g, \"\")}`;\n\n  return (\n    <ChartContext.Provider value={{ config }}>\n      <div\n        data-slot=\"chart\"\n        data-chart={chartId}\n        className={cn(\n          \"flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden\",\n          className,\n        )}\n        {...props}\n      >\n        <ChartStyle id={chartId} config={config} />\n        <RechartsPrimitive.ResponsiveContainer\n          initialDimension={initialDimension}\n        >\n          {children}\n        </RechartsPrimitive.ResponsiveContainer>\n      </div>\n    </ChartContext.Provider>\n  );\n}\n\nconst ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {\n  const colorConfig = Object.entries(config).filter(\n    ([, config]) => config.theme ?? config.color,\n  );\n\n  if (!colorConfig.length) {\n    return null;\n  }\n\n  return (\n    <style\n      dangerouslySetInnerHTML={{\n        __html: Object.entries(THEMES)\n          .map(\n            ([theme, prefix]) => `\n${prefix} [data-chart=${id}] {\n${colorConfig\n  .map(([key, itemConfig]) => {\n    const color =\n      itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ??\n      itemConfig.color;\n    return color ? `  --color-${key}: ${color};` : null;\n  })\n  .join(\"\\n\")}\n}\n`,\n          )\n          .join(\"\\n\"),\n      }}\n    />\n  );\n};\n\nconst ChartTooltip = RechartsPrimitive.Tooltip;\n\nfunction ChartTooltipContent({\n  active,\n  payload,\n  className,\n  indicator = \"dot\",\n  hideLabel = false,\n  hideIndicator = false,\n  label,\n  labelFormatter,\n  labelClassName,\n  formatter,\n  color,\n  nameKey,\n  labelKey,\n}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &\n  React.ComponentProps<\"div\"> & {\n    hideLabel?: boolean;\n    hideIndicator?: boolean;\n    indicator?: \"line\" | \"dot\" | \"dashed\";\n    nameKey?: string;\n    labelKey?: string;\n  } & Omit<\n    RechartsPrimitive.DefaultTooltipContentProps<\n      TooltipValueType,\n      TooltipNameType\n    >,\n    \"accessibilityLayer\"\n  >) {\n  const { config } = useChart();\n\n  const tooltipLabel = React.useMemo(() => {\n    if (hideLabel || !payload?.length) {\n      return null;\n    }\n\n    const [item] = payload;\n    const key = `${labelKey ?? item?.dataKey ?? item?.name ?? \"value\"}`;\n    const itemConfig = getPayloadConfigFromPayload(config, item, key);\n    const value =\n      !labelKey && typeof label === \"string\"\n        ? (config[label]?.label ?? label)\n        : itemConfig?.label;\n\n    if (labelFormatter) {\n      return (\n        <div className={cn(\"font-medium\", labelClassName)}>\n          {labelFormatter(value, payload)}\n        </div>\n      );\n    }\n\n    if (!value) {\n      return null;\n    }\n\n    return <div className={cn(\"font-medium\", labelClassName)}>{value}</div>;\n  }, [\n    label,\n    labelFormatter,\n    payload,\n    hideLabel,\n    labelClassName,\n    config,\n    labelKey,\n  ]);\n\n  if (!active || !payload?.length) {\n    return null;\n  }\n\n  const nestLabel = payload.length === 1 && indicator !== \"dot\";\n\n  return (\n    <div\n      className={cn(\n        \"grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl\",\n        className,\n      )}\n    >\n      {!nestLabel ? tooltipLabel : null}\n      <div className=\"grid gap-1.5\">\n        {payload\n          .filter((item) => item.type !== \"none\")\n          .map((item, index) => {\n            const key = `${nameKey ?? item.name ?? item.dataKey ?? \"value\"}`;\n            const itemConfig = getPayloadConfigFromPayload(config, item, key);\n            const indicatorColor = color ?? item.payload?.fill ?? item.color;\n\n            return (\n              <div\n                key={index}\n                className={cn(\n                  \"flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground\",\n                  indicator === \"dot\" && \"items-center\",\n                )}\n              >\n                {formatter && item?.value !== undefined && item.name ? (\n                  formatter(item.value, item.name, item, index, item.payload)\n                ) : (\n                  <>\n                    {itemConfig?.icon ? (\n                      <itemConfig.icon />\n                    ) : (\n                      !hideIndicator && (\n                        <div\n                          className={cn(\n                            \"shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)\",\n                            {\n                              \"h-2.5 w-2.5\": indicator === \"dot\",\n                              \"w-1\": indicator === \"line\",\n                              \"w-0 border-[1.5px] border-dashed bg-transparent\":\n                                indicator === \"dashed\",\n                              \"my-0.5\": nestLabel && indicator === \"dashed\",\n                            },\n                          )}\n                          style={\n                            {\n                              \"--color-bg\": indicatorColor,\n                              \"--color-border\": indicatorColor,\n                            } as React.CSSProperties\n                          }\n                        />\n                      )\n                    )}\n                    <div\n                      className={cn(\n                        \"flex flex-1 justify-between leading-none\",\n                        nestLabel ? \"items-end\" : \"items-center\",\n                      )}\n                    >\n                      <div className=\"grid gap-1.5\">\n                        {nestLabel ? tooltipLabel : null}\n                        <span className=\"text-muted-foreground\">\n                          {itemConfig?.label ?? item.name}\n                        </span>\n                      </div>\n                      {item.value != null && (\n                        <span className=\"font-mono font-medium text-foreground tabular-nums\">\n                          {typeof item.value === \"number\"\n                            ? item.value.toLocaleString()\n                            : String(item.value)}\n                        </span>\n                      )}\n                    </div>\n                  </>\n                )}\n              </div>\n            );\n          })}\n      </div>\n    </div>\n  );\n}\n\nconst ChartLegend = RechartsPrimitive.Legend;\n\nfunction ChartLegendContent({\n  className,\n  hideIcon = false,\n  payload,\n  verticalAlign = \"bottom\",\n  nameKey,\n}: React.ComponentProps<\"div\"> & {\n  hideIcon?: boolean;\n  nameKey?: string;\n} & RechartsPrimitive.DefaultLegendContentProps) {\n  const { config } = useChart();\n\n  if (!payload?.length) {\n    return null;\n  }\n\n  return (\n    <div\n      className={cn(\n        \"flex items-center justify-center gap-4\",\n        verticalAlign === \"top\" ? \"pb-3\" : \"pt-3\",\n        className,\n      )}\n    >\n      {payload\n        .filter((item) => item.type !== \"none\")\n        .map((item, index) => {\n          const key = `${nameKey ?? item.dataKey ?? \"value\"}`;\n          const itemConfig = getPayloadConfigFromPayload(config, item, key);\n\n          return (\n            <div\n              key={index}\n              className={cn(\n                \"flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground\",\n              )}\n            >\n              {itemConfig?.icon && !hideIcon ? (\n                <itemConfig.icon />\n              ) : (\n                <div\n                  className=\"h-2 w-2 shrink-0 rounded-[2px]\"\n                  style={{\n                    backgroundColor: item.color,\n                  }}\n                />\n              )}\n              {itemConfig?.label}\n            </div>\n          );\n        })}\n    </div>\n  );\n}\n\n// Helper to extract item config from a payload.\nfunction getPayloadConfigFromPayload(\n  config: ChartConfig,\n  payload: unknown,\n  key: string,\n) {\n  if (typeof payload !== \"object\" || payload === null) {\n    return undefined;\n  }\n\n  const payloadPayload =\n    \"payload\" in payload &&\n    typeof payload.payload === \"object\" &&\n    payload.payload !== null\n      ? payload.payload\n      : undefined;\n\n  let configLabelKey: string = key;\n\n  if (\n    key in payload &&\n    typeof payload[key as keyof typeof payload] === \"string\"\n  ) {\n    configLabelKey = payload[key as keyof typeof payload] as string;\n  } else if (\n    payloadPayload &&\n    key in payloadPayload &&\n    typeof payloadPayload[key as keyof typeof payloadPayload] === \"string\"\n  ) {\n    configLabelKey = payloadPayload[\n      key as keyof typeof payloadPayload\n    ] as string;\n  }\n\n  return configLabelKey in config ? config[configLabelKey] : config[key];\n}\n\nexport {\n  ChartContainer,\n  ChartTooltip,\n  ChartTooltipContent,\n  ChartLegend,\n  ChartLegendContent,\n  ChartStyle,\n};\n"
    }
  ],
  "docs": "Documentation: https://ui.overtrue.xyz/components/sankey-chart. Requires an initialized shadcn/ui project with Tailwind CSS v4."
}
