{
  "$schema": "https://uipkge.dev/schema/registry-item.json",
  "name": "violin-chart",
  "title": "Violin Chart",
  "type": "registry:ui",
  "files": [
    {
      "path": "packages/registry-svelte/components/violin-chart/ViolinChart.svelte",
      "content": "<script lang=\"ts\" module>\n  import type { HTMLAttributes } from 'svelte/elements'\n\n  export interface ViolinGroup {\n    group: string\n    values: number[]\n  }\n\n  export interface ViolinChartProps extends HTMLAttributes<HTMLDivElement> {\n    groups: ViolinGroup[]\n    height?: number | string\n    option?: any\n    /** Accessible name announced for the chart image. */\n    ariaLabel?: string\n  }\n</script>\n\n<script lang=\"ts\">\n  import { onDestroy } from 'svelte'\n  import { init, use, type ECharts, type EChartsCoreOption } from 'echarts/core'\n  import { CanvasRenderer } from 'echarts/renderers'\n  import { CustomChart as EChartsCustomChart } from 'echarts/charts'\n  import { GridComponent, TooltipComponent, LegendComponent } from 'echarts/components'\n  import { cn } from '$lib/utils'\n  import {\n    chartAxisColor,\n    chartColors,\n    chartSplitLineColor,\n    chartTextColor,\n    chartTooltipBg,\n    chartTooltipBorder,\n    chartTooltipText,\n    mergeOptionBlock,\n  } from './useChartTheme.svelte'\n\n  use([CanvasRenderer, EChartsCustomChart, GridComponent, TooltipComponent, LegendComponent])\n\n  let { groups, height = 340, option, class: className, ariaLabel, ...restProps }: ViolinChartProps = $props()\n\n  let chartEl: HTMLDivElement | null = $state(null)\n  let chart: ECharts | null = null\n\n  function kde(values: number[], grid: number[]): number[] {\n    const n = values.length\n    if (!n) return grid.map(() => 0)\n    const mean = values.reduce((s, v) => s + v, 0) / n\n    const sd = Math.sqrt(values.reduce((s, v) => s + (v - mean) ** 2, 0) / n) || 1\n    const h = 1.06 * sd * Math.pow(n, -0.2) || sd\n    return grid.map((x) => values.reduce((s, v) => s + Math.exp(-0.5 * ((x - v) / h) ** 2), 0) / (n * h))\n  }\n\n  function quartiles(sorted: number[]) {\n    const q = (p: number) => sorted[Math.min(sorted.length - 1, Math.floor(p * (sorted.length - 1)))]!\n    return { q1: q(0.25), med: q(0.5), q3: q(0.75), min: sorted[0]!, max: sorted[sorted.length - 1]! }\n  }\n\n  const GRID_N = 60\n\n  const mergedOption = $derived.by((): EChartsCoreOption => {\n    const colors = chartColors()\n    const textColor = chartTextColor()\n    const axisColor = chartAxisColor()\n    const splitLineColor = chartSplitLineColor()\n    const tooltipBg = chartTooltipBg()\n    const tooltipBorder = chartTooltipBorder()\n    const tooltipText = chartTooltipText()\n\n    const all = groups.flatMap((g) => g.values)\n    const lo = Math.min(...all, 0)\n    const hi = Math.max(...all, 1)\n    const grid = Array.from({ length: GRID_N }, (_, i) => lo + ((hi - lo) * i) / (GRID_N - 1))\n    const densities = groups.map((g) => kde(g.values, grid))\n    const maxD = Math.max(...densities.flat(), 1)\n    const W = 0.42\n\n    const series = [\n      {\n        type: 'custom',\n        renderItem: (params: any, api: any) => {\n          const gi: number = params.dataIndex\n          const g = groups[gi]!\n          const sorted = [...g.values].sort((a, b) => a - b)\n          const { q1, med, q3, min, max } = quartiles(sorted)\n          const dens = densities[gi]!\n          const cx = api.coord([gi, 0])[0]\n          const yOf = (v: number) => api.coord([gi, v])[1]\n          const xOf = (d: number, side: 1 | -1) =>\n            cx + side * ((d / maxD) * W * Math.abs(api.coord([gi + 1, 0])[0] - cx || 60))\n          const right = grid.map((v, i) => [xOf(dens[i]!, 1), yOf(v)] as [number, number])\n          const left = grid.map((v, i) => [xOf(dens[i]!, -1), yOf(v)] as [number, number]).reverse()\n          const color = colors[gi % colors.length]\n          return {\n            type: 'group',\n            children: [\n              { type: 'polygon', shape: { points: [...right, ...left] }, style: { fill: color, opacity: 0.45 } },\n              {\n                type: 'line',\n                shape: { x1: cx, y1: yOf(min), x2: cx, y2: yOf(max) },\n                style: { stroke: textColor, lineWidth: 1.5 },\n              },\n              {\n                type: 'line',\n                shape: { x1: cx, y1: yOf(q1), x2: cx, y2: yOf(q3) },\n                style: { stroke: color, lineWidth: 7, lineCap: 'round' },\n              },\n              {\n                type: 'circle',\n                shape: { cx, cy: yOf(med), r: 4.5 },\n                style: { fill: tooltipBg, stroke: color, lineWidth: 2 },\n              },\n            ],\n          }\n        },\n        data: groups.map((g) => g.group),\n      },\n    ]\n    const userOption: any = option ?? {}\n    const {\n      series: userSeries,\n      xAxis: userXAxis,\n      yAxis: userYAxis,\n      grid: userGrid,\n      tooltip: userTooltip,\n      ...userRest\n    } = userOption\n    const mergedSeries = Array.isArray(userSeries) ? series.map((s, i) => ({ ...s, ...(userSeries[i] ?? {}) })) : series\n    return {\n      color: colors,\n      grid: mergeOptionBlock({ left: 16, right: 16, top: 24, bottom: 24, containLabel: true }, userGrid),\n      tooltip: mergeOptionBlock(\n        {\n          trigger: 'item',\n          backgroundColor: tooltipBg,\n          borderColor: tooltipBorder,\n          textStyle: { color: tooltipText, fontSize: 12 },\n          formatter: (p: any) => {\n            const g = groups[p.dataIndex]\n            if (!g) return ''\n            const s = [...g.values].sort((a, b) => a - b)\n            const { q1, med, q3 } = quartiles(s)\n            return `${g.group}<br/>n=${g.values.length} median=${med.toFixed(2)}<br/>Q1=${q1.toFixed(2)} Q3=${q3.toFixed(2)}`\n          },\n        },\n        userTooltip,\n      ),\n      legend: { show: false },\n      xAxis: mergeOptionBlock(\n        {\n          type: 'category',\n          data: groups.map((g) => g.group),\n          axisLine: { lineStyle: { color: axisColor } },\n          axisLabel: { color: textColor, fontSize: 11 },\n          axisTick: { show: false },\n        },\n        userXAxis,\n      ),\n      yAxis: mergeOptionBlock(\n        {\n          type: 'value',\n          min: lo,\n          max: hi,\n          splitLine: { lineStyle: { color: splitLineColor } },\n          axisLabel: { color: textColor, fontSize: 11 },\n        },\n        userYAxis,\n      ),\n      series: mergedSeries,\n      ...userRest,\n    }\n  })\n\n  // Create once, then push option updates (props or theme flips) into the live chart.\n  $effect(() => {\n    const el = chartEl\n    if (!el) return\n    chart ??= init(el)\n    chart.setOption(mergedOption)\n  })\n\n  // Autoresize with the container, like VChart's autoresize.\n  $effect(() => {\n    const el = chartEl\n    if (!el || typeof ResizeObserver === 'undefined') return\n    const ro = new ResizeObserver(() => chart?.resize())\n    ro.observe(el)\n    return () => ro.disconnect()\n  })\n\n  onDestroy(() => {\n    chart?.dispose()\n    chart = null\n  })\n</script>\n\n<div\n  role=\"img\"\n  tabindex=\"0\"\n  aria-label={ariaLabel || 'Violin chart'}\n  style:height={/^\\d+$/.test(String(height)) ? `${height}px` : String(height)}\n  class={cn('focus-visible:ring-ring w-full focus-visible:ring-2 focus-visible:outline-none', className)}\n  {...restProps}\n>\n  <div bind:this={chartEl} class=\"size-full\"></div>\n</div>\n",
      "type": "registry:ui",
      "target": "~/src/lib/components/ui/violin-chart/ViolinChart.svelte"
    },
    {
      "path": "packages/registry-svelte/components/violin-chart/index.ts",
      "content": "export { default as ViolinChart, type ViolinChartProps, type ViolinGroup } from './ViolinChart.svelte'\n",
      "type": "registry:ui",
      "target": "~/src/lib/components/ui/violin-chart/index.ts"
    },
    {
      "path": "packages/registry-svelte/components/violin-chart/useChartTheme.svelte.ts",
      "content": "// Chart palette is driven by Tailwind v4 CSS variables (`--chart-1`..`--chart-5`,\n// `--muted-foreground`, `--border`, `--popover`, etc.) so dark/light flips\n// happen automatically when the consumer toggles their theme class. The\n// values resolve at runtime via `getComputedStyle`, so they pick up whatever\n// the consumer set in their own `tailwind.css` -- no fork required.\n//\n// `themeKey` bumps whenever `<html>` class/style changes (the typical\n// shadcn dark-mode pivot). Every getter below reads it, so a `$derived`\n// that calls these re-resolves and downstream ECharts options re-paint.\n//\n// NOTE: this file is intentionally duplicated per chart item (not shared)\n// so each chart stays a single self-contained install unit. Keep the copies\n// in sync with the Vue twin at `components/charts/useChartTheme.ts`.\n\nlet themeKey = $state(0)\n\nif (typeof window !== 'undefined') {\n  // Bump once on the first paint so post-hydration getComputedStyle reads\n  // the *resolved* CSS values (during SSR-built bundles the very first\n  // pass returns the fallbacks below).\n  requestAnimationFrame(() => themeKey++)\n  new MutationObserver(() => themeKey++).observe(document.documentElement, {\n    attributes: true,\n    attributeFilter: ['class', 'style', 'data-theme'],\n  })\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\n// Each getter reads `themeKey` so reactive callers re-run on theme flips.\nexport function chartColors(): string[] {\n  themeKey\n  return Array.from({ length: 5 }, (_, i) => resolveVar(`--chart-${i + 1}`, CHART_FALLBACK[i]!))\n}\n\nexport function chartTextColor(): string {\n  themeKey\n  return resolveVar('--muted-foreground', '#888888')\n}\n\nexport function chartAxisColor(): string {\n  themeKey\n  return resolveVar('--border', '#e5e5e5')\n}\n\nexport function chartSplitLineColor(): string {\n  themeKey\n  return resolveVar('--border', '#f0f0f0')\n}\n\nexport function chartTooltipBg(): string {\n  themeKey\n  return resolveVar('--popover', 'rgba(255,255,255,0.96)')\n}\n\nexport function chartTooltipBorder(): string {\n  themeKey\n  return resolveVar('--border', '#e5e5e5')\n}\n\nexport function chartTooltipText(): string {\n  themeKey\n  return resolveVar('--popover-foreground', '#333333')\n}\n\nexport function chartBgColor(): string {\n  themeKey\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  themeKey\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  themeKey\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.\n//\n// This is the merge strategy the chart wrappers use to fold `props.option`\n// onto their computed base option without forcing consumers to spell out\n// every default they want to preserve.\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 (\n      bv != null &&\n      uv != null &&\n      typeof bv === 'object' &&\n      typeof uv === 'object' &&\n      !Array.isArray(bv) &&\n      !Array.isArray(uv)\n    ) {\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// Pulled off saturated green and onto teal so the gauge ties back to the\n// dashboard palette; red is kept as the universal \"limit reached\" cue.\n// GaugeChart consumes this via its `thresholds` prop default; consumers\n// pass their own array to override. Static because gauges have semantic\n// meaning (green safe / red danger) that 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/violin-chart/useChartTheme.svelte.ts"
    }
  ],
  "dependencies": [
    "echarts"
  ],
  "devDependencies": [],
  "registryDependencies": [],
  "description": "Violin chart around Apache ECharts custom series. Gaussian-KDE density halves with quartile box, median dot, and whiskers per group. Theme-aware via registry tokens.",
  "categories": [
    "chart"
  ]
}