{
  "$schema": "https://uipkge.dev/schema/registry-item.json",
  "name": "stacked-bar-chart",
  "title": "Stacked Bar Chart",
  "type": "registry:ui",
  "files": [
    {
      "path": "packages/registry-svelte/components/stacked-bar-chart/StackedBarChart.svelte",
      "content": "<script lang=\"ts\" module>\n  import type { HTMLAttributes } from 'svelte/elements'\n\n  export interface StackedBarChartProps extends HTMLAttributes<HTMLDivElement> {\n    data: Record<string, any>[]\n    xField?: string\n    yFields: string[]\n    /** Render as 100% shares instead of absolute values. Default false. */\n    percent?: boolean\n    /** Corner rounding in px. Default 6. */\n    radius?: number\n    /** Gap in px between stacked bar segments. Default 1. Set to 0 to disable. */\n    stackGap?: number\n    /** Color of the gap between stacked bar segments. Defaults to card background. */\n    stackGapColor?: string\n    height?: number | string\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 { BarChart as EChartsBarChart } from 'echarts/charts'\n  import { GridComponent, LegendComponent, TooltipComponent } from 'echarts/components'\n  import { init, use, type ECharts } from 'echarts/core'\n  import { CanvasRenderer } from 'echarts/renderers'\n  import { cn } from '$lib/utils'\n  import {\n    chartAxisColor,\n    chartBgColor,\n    chartColors,\n    chartSplitLineColor,\n    chartTextColor,\n    chartTooltipBg,\n    chartTooltipBorder,\n    chartTooltipText,\n    mergeOptionBlock,\n  } from './useChartTheme'\n\n  use([CanvasRenderer, EChartsBarChart, GridComponent, TooltipComponent, LegendComponent])\n\n  let {\n    class: className,\n    data,\n    xField = 'x',\n    yFields,\n    percent = false,\n    radius = 6,\n    stackGap = 1,\n    stackGapColor,\n    height = 320,\n    option,\n    ariaLabel,\n    children,\n    ref = $bindable(null),\n    ...restProps\n  }: StackedBarChartProps = $props()\n\n  const mergedOption = $derived.by(() => {\n    const totals = data.map((d) => yFields.reduce((s, f) => s + Math.abs(d[f] ?? 0), 0) || 1)\n    const series = yFields.map((f, i) => ({\n      name: f,\n      type: 'bar',\n      stack: 'total',\n      barMaxWidth: 34,\n      itemStyle: {\n        color: $chartColors[i % $chartColors.length],\n        borderRadius: [radius, radius, radius, radius],\n        ...(stackGap > 0\n          ? {\n              borderColor: stackGapColor ?? $chartBgColor,\n              borderWidth: stackGap,\n            }\n          : {}),\n      },\n      label: percent ? { show: true, color: '#fff', fontSize: 10, formatter: (p: any) => `${Math.round(p.value)}%` } : undefined,\n      data: data.map((d, r) => (percent ? (Math.abs(d[f] ?? 0) / totals[r]!) * 100 : d[f])),\n    }))\n    const userOption: any = option ?? {}\n    const {\n      series: userSeries,\n      xAxis: userXAxis,\n      yAxis: userYAxis,\n      grid: userGrid,\n      tooltip: userTooltip,\n      legend: userLegend,\n      ...userRest\n    } = userOption\n\n    const count = Math.max(yFields.length, Array.isArray(userSeries) ? userSeries.length : 0)\n    const gap = stackGap\n    const gapColor = stackGapColor ?? $chartBgColor\n\n    const mergedSeries = Array.isArray(userSeries)\n      ? Array.from({ length: count }, (_, i) => {\n          const s = series[i] ?? {\n            name: `series-${i}`,\n            type: 'bar',\n            stack: 'total',\n            barMaxWidth: 34,\n            itemStyle: {\n              color: $chartColors[i % $chartColors.length],\n            },\n          }\n          const u = userSeries[i] ?? {}\n          return {\n            ...s,\n            ...u,\n            itemStyle: {\n              ...s.itemStyle,\n              borderRadius: [radius, radius, radius, radius],\n              ...(gap > 0\n                ? {\n                    borderColor: gapColor,\n                    borderWidth: gap,\n                  }\n                : {}),\n              ...(u.itemStyle ?? {}),\n            },\n          }\n        })\n      : series\n    return {\n      color: $chartColors,\n      grid: mergeOptionBlock({ left: 16, right: 16, top: 24, bottom: 32, containLabel: true }, userGrid),\n      tooltip: mergeOptionBlock(\n        {\n          trigger: 'axis',\n          axisPointer: { type: 'shadow' },\n          backgroundColor: $chartTooltipBg,\n          borderColor: $chartTooltipBorder,\n          textStyle: { color: $chartTooltipText, fontSize: 12 },\n          valueFormatter: (v: any) => (percent ? `${(+v).toFixed(1)}%` : v),\n        },\n        userTooltip,\n      ),\n      legend: mergeOptionBlock(\n        {\n          bottom: 0,\n          icon: 'circle',\n          itemWidth: 8,\n          itemHeight: 8,\n          textStyle: { fontSize: 11, color: $chartTextColor },\n        },\n        userLegend,\n      ),\n      xAxis: mergeOptionBlock(\n        {\n          type: 'category',\n          data: data.map((d) => d[xField]),\n          axisLine: { lineStyle: { color: $chartAxisColor } },\n          axisLabel: { color: $chartTextColor, fontSize: 11 },\n          axisTick: { show: false },\n        },\n        userXAxis,\n      ),\n      yAxis: mergeOptionBlock(\n        percent\n          ? {\n              type: 'value',\n              max: 100,\n              splitLine: { lineStyle: { color: $chartSplitLineColor } },\n              axisLabel: { color: $chartTextColor, fontSize: 11, formatter: '{value}%' },\n            }\n          : {\n              type: 'value',\n              splitLine: { lineStyle: { color: $chartSplitLineColor } },\n              axisLabel: { color: $chartTextColor, fontSize: 11 },\n            },\n        userYAxis,\n      ),\n      series: mergedSeries,\n      ...userRest,\n    }\n  })\n\n  let container = $state<HTMLDivElement | null>(null)\n  let chart = $state<ECharts | null>(null)\n  let rootEl = $state<HTMLDivElement | null>(null)\n\n  $effect(() => {\n    ref = rootEl\n  })\n\n  $effect(() => {\n    const el = container\n    if (!el) return\n    const instance = init(el)\n    chart = instance\n    const ro = new ResizeObserver(() => instance.resize())\n    ro.observe(el)\n    return () => {\n      ro.disconnect()\n      instance.dispose()\n      if (chart === instance) chart = null\n    }\n  })\n\n  $effect(() => {\n    chart?.setOption(mergedOption, { notMerge: true })\n  })\n\n  const heightStyle = $derived(/^\\d+$/.test(String(height)) ? `${height}px` : String(height))\n</script>\n\n<!-- Focusable chart region with an accessible name (mirrors the Vue twin). -->\n<!-- svelte-ignore a11y_no_noninteractive_tabindex -->\n<div\n  bind:this={rootEl}\n  role=\"img\"\n  tabindex=\"0\"\n  aria-label={ariaLabel || 'Chart'}\n  style=\"height: {heightStyle}\"\n  data-uipkge=\"\"\n  data-slot=\"stacked-bar-chart\"\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={container} class=\"size-full\"></div>\n  {@render children?.()}\n</div>\n",
      "type": "registry:ui",
      "target": "~/src/lib/components/ui/charts/stacked-bar-chart/StackedBarChart.svelte"
    },
    {
      "path": "packages/registry-svelte/components/stacked-bar-chart/index.ts",
      "content": "export { default as StackedBarChart, type StackedBarChartProps } from './StackedBarChart.svelte'\n",
      "type": "registry:ui",
      "target": "~/src/lib/components/ui/charts/stacked-bar-chart/index.ts"
    },
    {
      "path": "packages/registry-svelte/components/stacked-bar-chart/useChartTheme.ts",
      "content": "import { derived, readable } from 'svelte/store'\n\n// 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 CSS -- no fork required.\n//\n// We bump `themeKey` whenever `<html>` class/style changes (the typical\n// shadcn dark-mode pivot) so every consuming store re-resolves and\n// downstream ECharts options re-paint. Subscribe with `$chartColors` etc.\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 const themeKey = readable(0, (set) => {\n  if (typeof window === 'undefined') return\n  let n = 0\n  // Bump once on the first paint so post-hydration getComputedStyle reads\n  // the *resolved* CSS values (during SSR the very first pass returns the\n  // fallbacks below).\n  const raf = requestAnimationFrame(() => set(++n))\n  const mo = new MutationObserver(() => set(++n))\n  mo.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'style', 'data-theme'] })\n  return () => {\n    cancelAnimationFrame(raf)\n    mo.disconnect()\n  }\n})\n\nexport const chartColors = derived(themeKey, () =>\n  Array.from({ length: 5 }, (_, i) => resolveVar(`--chart-${i + 1}`, CHART_FALLBACK[i]!)),\n)\n\nexport const chartTextColor = derived(themeKey, () => resolveVar('--muted-foreground', '#888888'))\n\nexport const chartAxisColor = derived(themeKey, () => resolveVar('--border', '#e5e5e5'))\n\nexport const chartSplitLineColor = derived(themeKey, () => resolveVar('--border', '#f0f0f0'))\n\nexport const chartTooltipBg = derived(themeKey, () => resolveVar('--popover', 'rgba(255,255,255,0.96)'))\n\nexport const chartTooltipBorder = derived(themeKey, () => resolveVar('--border', '#e5e5e5'))\n\nexport const chartTooltipText = derived(themeKey, () => resolveVar('--popover-foreground', '#333333'))\n\nexport const chartBgColor = derived(themeKey, () => resolveVar('--card', resolveVar('--background', '#ffffff')))\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 const chartAccentColor = derived(themeKey, () => resolveVar('--primary', '#38bdf8'))\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 const chartDangerColor = derived(themeKey, () => resolveVar('--destructive', '#dc2626'))\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/charts/stacked-bar-chart/useChartTheme.ts"
    }
  ],
  "dependencies": [
    "echarts"
  ],
  "devDependencies": [],
  "registryDependencies": [],
  "description": "Stacked bar chart around Apache ECharts. Absolute or 100% share stacking with legend; negative stacks diverge for Likert scales. Theme-aware via registry tokens.",
  "categories": [
    "chart"
  ]
}