{
  "$schema": "https://uipkge.dev/schema/registry-item.json",
  "name": "sankey-chart",
  "title": "Sankey Chart",
  "type": "registry:ui",
  "files": [
    {
      "path": "packages/registry-svelte/components/sankey-chart/SankeyChart.svelte",
      "content": "<script lang=\"ts\" module>\n  import type { HTMLAttributes } from 'svelte/elements'\n\n  export interface SankeyLink {\n    source: string\n    target: string\n    value: number\n  }\n\n  export interface SankeyChartProps extends HTMLAttributes<HTMLDivElement> {\n    /** Node names. If omitted, derived from the union of link sources + targets. */\n    nodes?: string[]\n    /** `{ source, target, value }` edges between nodes. */\n    links: SankeyLink[]\n    height?: number | string\n    /** Curvature of the link ribbons. 0 = straight, 1 = max curve. */\n    curveness?: number\n    option?: any\n    /** Accessible name announced for the chart image. Defaults to \"Chart\". */\n    ariaLabel?: string\n    ref?: HTMLDivElement | null\n  }\n</script>\n\n<script lang=\"ts\">\n  import { use, init } from 'echarts/core'\n  import { CanvasRenderer } from 'echarts/renderers'\n  import { SankeyChart as EChartsSankeyChart } from 'echarts/charts'\n  import { TooltipComponent, LegendComponent } from 'echarts/components'\n  import { cn } from '$lib/utils'\n  import { chartTooltipBg, chartTooltipBorder, chartTooltipText } from './chart-theme'\n\n  use([CanvasRenderer, EChartsSankeyChart, TooltipComponent, LegendComponent])\n\n  // Sankey nodes keep a fixed categorical palette so the same flow retains its\n  // visual identity across light and dark themes. Labels and tooltip chrome\n  // still use theme tokens for contrast against the current surface.\n  const SANKEY_COLORS = ['#3b82f6', '#f59e0b', '#10b981', '#ef4444', '#8b5cf6', '#06b6d4', '#ec4899', '#84cc16']\n\n  let {\n    class: className,\n    nodes,\n    links,\n    height = 360,\n    curveness = 0.5,\n    option,\n    ariaLabel,\n    ref = $bindable(null),\n    ...restProps\n  }: SankeyChartProps = $props()\n\n  let chartEl: HTMLDivElement | null = $state(null)\n  let themeTick = $state(0)\n\n  // Bump whenever <html> class/style changes (the typical shadcn dark-mode\n  // pivot) so the option below re-resolves and the chart re-paints.\n  $effect(() => {\n    if (typeof window === 'undefined') return\n    const raf = requestAnimationFrame(() => themeTick++)\n    const mo = new MutationObserver(() => themeTick++)\n    mo.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'style', 'data-theme'] })\n    return () => {\n      cancelAnimationFrame(raf)\n      mo.disconnect()\n    }\n  })\n\n  const mergedOption = $derived.by(() => {\n    void themeTick\n    const nodeNames = nodes ?? Array.from(new Set(links.flatMap((l) => [l.source, l.target])))\n\n    const series = [\n      {\n        type: 'sankey',\n        left: 16,\n        right: 72,\n        top: 12,\n        bottom: 12,\n        data: nodeNames.map((name) => ({ name })),\n        links,\n        lineStyle: { color: 'gradient', curveness },\n        label: { fontSize: 11, color: chartTooltipText() },\n        emphasis: { focus: 'adjacency' },\n        itemStyle: { borderWidth: 0 },\n      },\n    ]\n\n    // Per-index series merge — partial overrides keep computed `type`/`data`.\n    const userOption: any = option ?? {}\n    const { series: userSeries, ...userRest } = userOption\n    const mergedSeries = Array.isArray(userSeries) ? series.map((s, i) => ({ ...s, ...(userSeries[i] ?? {}) })) : series\n\n    return {\n      color: SANKEY_COLORS,\n      tooltip: {\n        trigger: 'item',\n        triggerOn: 'mousemove',\n        backgroundColor: chartTooltipBg(),\n        borderColor: chartTooltipBorder(),\n        textStyle: { color: chartTooltipText(), fontSize: 12 },\n      },\n      series: mergedSeries,\n      ...userRest,\n    }\n  })\n\n  // ECharts instance owned by the mount effect below; the option effect only\n  // ever calls setOption on it (never init twice — that logs a console warning).\n  let chartInstance: { setOption: (opt: any, opts?: any) => void; resize: () => void; dispose: () => void } | null =\n    null\n\n  $effect(() => {\n    if (!chartEl || typeof window === 'undefined') return\n    const chart = init(chartEl)\n    chartInstance = chart\n    const ro = new ResizeObserver(() => chart.resize())\n    ro.observe(chartEl)\n    return () => {\n      ro.disconnect()\n      chart.dispose()\n      chartInstance = null\n    }\n  })\n\n  $effect(() => {\n    chartInstance?.setOption(mergedOption, { notMerge: false })\n  })\n</script>\n\n<div\n  bind:this={ref}\n  role=\"img\"\n  aria-label={ariaLabel || 'Chart'}\n  style=\"height: {/^\\d+$/.test(String(height)) ? `${height}px` : String(height)};\"\n  class={cn('w-full', className)}\n  {...restProps}\n>\n  <div bind:this={chartEl} class=\"size-full\"></div>\n</div>\n",
      "type": "registry:ui",
      "target": "~/src/lib/components/ui/sankey-chart/SankeyChart.svelte"
    },
    {
      "path": "packages/registry-svelte/components/sankey-chart/index.ts",
      "content": "export { default as SankeyChart, type SankeyChartProps, type SankeyLink } from './SankeyChart.svelte'\nexport {\n  chartColors,\n  chartTextColor,\n  chartAxisColor,\n  chartSplitLineColor,\n  chartTooltipBg,\n  chartTooltipBorder,\n  chartTooltipText,\n  chartBgColor,\n  chartAccentColor,\n  chartDangerColor,\n  mergeOptionBlock,\n  toCanvasColor,\n  toRgba,\n  gaugeThresholds,\n} from './chart-theme'\n",
      "type": "registry:ui",
      "target": "~/src/lib/components/ui/sankey-chart/index.ts"
    },
    {
      "path": "packages/registry-svelte/components/sankey-chart/chart-theme.ts",
      "content": "/**\n * Chart palette driven by Tailwind v4 CSS variables (`--chart-1`..`--chart-5`,\n * `--muted-foreground`, `--border`, `--popover`, etc.) so dark/light flips happen\n * automatically when the consumer toggles their theme class. Values resolve at\n * runtime via `getComputedStyle`, so they pick up whatever the consumer set in\n * their own `tailwind.css` -- no fork required.\n *\n * Svelte port of the Vue `useChartTheme.ts`. Plain functions (no runes) so the\n * component can re-read them whenever its own MutationObserver tick fires.\n */\n\n// ECharts' canvas renderer does not accept OKLCH in every browser. Assigning\n// one of our Tailwind tokens to `fillStyle` can silently leave the sentinel\n// colour in place, turning a whole chart black. Convert OKLCH ourselves and\n// let the canvas normalize older CSS colour formats.\nlet _hexCanvas: CanvasRenderingContext2D | null = null\n\nexport function toCanvasColor(cssColor: string): string {\n  const value = cssColor.trim()\n  const match = value.match(\n    /^oklch\\(\\s*([+-]?(?:\\d+\\.?\\d*|\\.\\d+))(%?)\\s+([+-]?(?:\\d+\\.?\\d*|\\.\\d+))\\s+([+-]?(?:\\d+\\.?\\d*|\\.\\d+))(?:deg)?(?:\\s*\\/\\s*([+-]?(?:\\d+\\.?\\d*|\\.\\d+))(%?))?\\s*\\)$/i,\n  )\n\n  if (match) {\n    const lightness = Number(match[1]) / (match[2] === '%' ? 100 : 1)\n    const chroma = Number(match[3])\n    const hue = (Number(match[4]) * Math.PI) / 180\n    const alpha = match[5] == null ? 1 : Number(match[5]) / (match[6] === '%' ? 100 : 1)\n    const a = chroma * Math.cos(hue)\n    const b = chroma * Math.sin(hue)\n\n    const l = Math.pow(lightness + 0.3963377774 * a + 0.2158037573 * b, 3)\n    const m = Math.pow(lightness - 0.1055613458 * a - 0.0638541728 * b, 3)\n    const s = Math.pow(lightness - 0.0894841775 * a - 1.291485548 * b, 3)\n    const linear = [\n      4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,\n      -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,\n      -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,\n    ]\n    const rgb = linear.map((channel) => {\n      const encoded = channel <= 0.0031308 ? 12.92 * channel : 1.055 * Math.pow(channel, 1 / 2.4) - 0.055\n      return Math.round(Math.min(1, Math.max(0, encoded)) * 255)\n    })\n\n    return alpha < 1 ? `rgba(${rgb.join(', ')}, ${alpha})` : `rgb(${rgb.join(', ')})`\n  }\n\n  if (typeof document === 'undefined') return cssColor\n  if (!_hexCanvas) {\n    _hexCanvas = document.createElement('canvas').getContext('2d')\n  }\n  if (!_hexCanvas) return cssColor\n  _hexCanvas.fillStyle = '#010203'\n  _hexCanvas.fillStyle = value\n  const normalized = _hexCanvas.fillStyle as string\n  return normalized === '#010203' && value.toLowerCase() !== '#010203' ? value : normalized\n}\n\n// Convert any CSS color (hex, rgb, oklch, color()) + alpha 0..1 to a\n// canvas-safe rgba(r,g,b,a). `colorString + '40'` (8-digit hex alpha)\n// only works when `colorString` is `#rrggbb`; once tokens resolve to\n// oklch() post-hydration the gradient stops break and the canvas paint\n// throws every frame. Stay defensive and always return rgba.\nexport function toRgba(cssColor: string, alpha: number): string {\n  const normalized = toCanvasColor(cssColor)\n  if (normalized.startsWith('#') && normalized.length === 7) {\n    const r = parseInt(normalized.slice(1, 3), 16)\n    const g = parseInt(normalized.slice(3, 5), 16)\n    const b = parseInt(normalized.slice(5, 7), 16)\n    return `rgba(${r},${g},${b},${alpha})`\n  }\n  if (normalized.startsWith('rgba(')) {\n    return normalized.replace(/,\\s*[\\d.]+\\s*\\)$/, `,${alpha})`)\n  }\n  if (normalized.startsWith('rgb(')) {\n    return normalized.replace(/^rgb\\(/, 'rgba(').replace(/\\)$/, `,${alpha})`)\n  }\n  // Canvas refused to parse this color -- ship the original string and\n  // let ECharts complain (better than crashing the paint loop).\n  return cssColor\n}\n\nfunction resolveVar(name: string, fallback: string): string {\n  if (typeof window === 'undefined') return fallback\n  const v = getComputedStyle(document.documentElement).getPropertyValue(name).trim()\n  if (!v) return fallback\n  return toCanvasColor(v)\n}\n\n// SSR / pre-hydration fallback palette. Hex values picked to roughly\n// match the shadcn Neutral defaults in `tailwind.css` so the first paint\n// doesn't flicker.\nconst CHART_FALLBACK = ['#f59e0b', '#14b8a6', '#3b82f6', '#f97316', '#eab308']\n\nexport function chartColors(): string[] {\n  return Array.from({ length: 5 }, (_, i) => resolveVar(`--chart-${i + 1}`, CHART_FALLBACK[i]!))\n}\n\nexport function chartTextColor(): string {\n  return resolveVar('--muted-foreground', '#888888')\n}\n\nexport function chartAxisColor(): string {\n  return resolveVar('--border', '#e5e5e5')\n}\n\nexport function chartSplitLineColor(): string {\n  return resolveVar('--border', '#f0f0f0')\n}\n\nexport function chartTooltipBg(): string {\n  return resolveVar('--popover', 'rgba(255,255,255,0.96)')\n}\n\nexport function chartTooltipBorder(): string {\n  return resolveVar('--border', '#e5e5e5')\n}\n\nexport function chartTooltipText(): string {\n  return resolveVar('--popover-foreground', '#333333')\n}\n\nexport function chartBgColor(): string {\n  return resolveVar('--card', resolveVar('--background', '#ffffff'))\n}\n\n// The app's accent, for the one highlighted element on a chart or map — a\n// selected route, a focused bar. Category series keep using chartColors.\nexport function chartAccentColor(): string {\n  return resolveVar('--primary', '#38bdf8')\n}\n\n// Out-of-bounds / failure colour for charts that encode good vs bad rather\n// than a category — control limits, error series. CSS-level marks can use\n// `var(--destructive)` directly; this exists because ECharts needs a resolved\n// colour string on the canvas.\nexport function chartDangerColor(): string {\n  return resolveVar('--destructive', '#dc2626')\n}\n\n// Two-level deep merge for ECharts option blocks (xAxis, yAxis, grid,\n// tooltip, legend, singleAxis, parallel, etc.). The top-level keys merge\n// shallowly, but one nested level (axisLabel, axisLine, splitLine, etc.)\n// merges shallowly too so a consumer passing `xAxis: { axisLabel: { fontSize: 9 } }`\n// doesn't blow away the wrapper's `color` + base font defaults on the same\n// axisLabel block. Arrays + primitives replace outright.\nexport function mergeOptionBlock<T extends Record<string, any>>(base: T, user: Partial<T> | undefined): T {\n  if (!user) return base\n  const out: any = { ...base }\n  for (const k of Object.keys(user)) {\n    const bv = (base as any)[k]\n    const uv = (user as any)[k]\n    if (bv != null && uv != null && typeof bv === 'object' && typeof uv === 'object' && !Array.isArray(bv) && !Array.isArray(uv)) {\n      out[k] = { ...bv, ...uv }\n    } else {\n      out[k] = uv\n    }\n  }\n  return out\n}\n\n// Default gauge stoplight: teal (safe) -> amber (warning) -> red (danger).\n// Static because gauges have semantic meaning (green safe / red danger) that\n// we deliberately don't theme-flip.\nexport const gaugeThresholds: [number, string][] = [\n  [0.6, '#14b8a6'],\n  [0.85, '#f59e0b'],\n  [1, '#dc2626'],\n]\n",
      "type": "registry:ui",
      "target": "~/src/lib/components/ui/sankey-chart/chart-theme.ts"
    }
  ],
  "dependencies": [
    "echarts"
  ],
  "devDependencies": [],
  "registryDependencies": [],
  "description": "Sankey flow diagram wrapper around Apache ECharts. Visualizes value flows between named nodes (channels, stages, sources). Gradient links + theme-aware tokens.",
  "categories": [
    "chart"
  ]
}