{
  "$schema": "https://uipkge.dev/schema/registry-item.json",
  "name": "treemap-chart",
  "title": "Treemap Chart",
  "type": "registry:ui",
  "files": [
    {
      "path": "packages/registry-svelte/components/treemap-chart/TreemapChart.svelte",
      "content": "<script lang=\"ts\" module>\n  import type { HTMLAttributes } from 'svelte/elements'\n\n  export interface TreemapNode {\n    name: string\n    value?: number\n    children?: TreemapNode[]\n  }\n\n  export interface TreemapChartProps extends HTMLAttributes<HTMLDivElement> {\n    data: TreemapNode[]\n    height?: number | string\n    /** Show breadcrumb at top when drilling into a sub-tree. Default false. */\n    showBreadcrumb?: boolean\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 { onMount } from 'svelte'\n  import { init, use, type ECharts } from 'echarts/core'\n  import { CanvasRenderer } from 'echarts/renderers'\n  import { TreemapChart as EChartsTreemapChart } from 'echarts/charts'\n  // VisualMapComponent registered alongside Tooltip so consumers can hand a\n  // `visualMap` config via the option escape hatch (color-by-value variant).\n  import { TooltipComponent, VisualMapComponent } from 'echarts/components'\n  import { cn } from '$lib/utils'\n  import {\n    getChartColors,\n    getChartTextColor,\n    getChartTooltipBg,\n    getChartTooltipBorder,\n    getChartTooltipText,\n    toRgba,\n  } from './chart-theme'\n\n  use([CanvasRenderer, EChartsTreemapChart, TooltipComponent, VisualMapComponent])\n\n  let {\n    data,\n    height = 320,\n    showBreadcrumb = false,\n    option,\n    class: className,\n    ariaLabel,\n    ref = $bindable(null),\n    ...restProps\n  }: TreemapChartProps = $props()\n\n  // Theme version: bumped on mount and whenever `<html>` class/style changes\n  // (the typical dark-mode pivot) so the derived option re-resolves\n  // CSS-driven colors and the chart re-paints.\n  let themeKey = $state(0)\n  onMount(() => {\n    themeKey++\n    const mo = new MutationObserver(() => themeKey++)\n    mo.observe(document.documentElement, {\n      attributes: true,\n      attributeFilter: ['class', 'style', 'data-theme'],\n    })\n    return () => mo.disconnect()\n  })\n\n  const mergedOption = $derived.by(() => {\n    void themeKey\n    const textColor = getChartTextColor()\n    const series = [\n      {\n        type: 'treemap',\n        // Explicit left/top/right/bottom anchor the layout at 0,0 of the\n        // container. Without these, ECharts centres the treemap and the\n        // (invisible) breadcrumb still reserves ~22px at the top -- shows\n        // up as a phantom gap above the first rect.\n        left: 0,\n        top: 0,\n        right: 0,\n        bottom: 0,\n        width: 'auto',\n        height: 'auto',\n        roam: false,\n        nodeClick: false,\n        breadcrumb: { show: showBreadcrumb, height: 0 },\n        label: {\n          show: true,\n          formatter: ({ name, value }: any) => (value ? `{b|${name}}\\n{v|${value}}` : name),\n          rich: {\n            b: { color: textColor, fontSize: 11, fontWeight: 600, lineHeight: 14 },\n            v: { color: toRgba(textColor, 0.85), fontSize: 10, fontWeight: 500, lineHeight: 12 },\n          },\n          overflow: 'truncate',\n          ellipsis: '…',\n        },\n        labelLayout: { hideOverlap: false },\n        upperLabel: { show: false },\n        // gapWidth carves out the tile separators; an explicit borderColor\n        // would render as a contrasting stripe on the consumer's theme\n        // (white in dark mode, etc.). The gap reads as separation already.\n        itemStyle: { borderWidth: 0, gapWidth: 2 },\n        // The earlier `levels` config carried `colorSaturation` per depth\n        // for nested trees, but it also implicitly cleared the series\n        // `label` config at each level -- which meant flat data (the\n        // common case) rendered as untitled coloured rectangles. Apply\n        // saturation directly on the series so a single level config\n        // doesn't blow away the labels.\n        colorSaturation: [0.45, 0.7],\n        data,\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)\n      ? series.map((s, i) => ({ ...s, ...(userSeries[i] ?? {}) }))\n      : series\n\n    return {\n      color: getChartColors(),\n      tooltip: {\n        formatter: (info: any) => {\n          const parts = info.treePathInfo.map((n: any) => n.name).filter(Boolean)\n          return `<strong>${parts.join(' / ')}</strong><br>${info.value?.toLocaleString?.() ?? info.value}`\n        },\n        backgroundColor: getChartTooltipBg(),\n        borderColor: getChartTooltipBorder(),\n        textStyle: { color: getChartTooltipText(), fontSize: 12 },\n      },\n      series: mergedSeries,\n      ...userRest,\n    }\n  })\n\n  const heightStyle = $derived(/^\\d+$/.test(String(height)) ? `${height}px` : String(height))\n\n  let container = $state<HTMLDivElement | null>(null)\n  let chart: ECharts | null = null\n\n  onMount(() => {\n    if (!container) return\n    const c = init(container)\n    chart = c\n    c.setOption(mergedOption)\n    const ro = new ResizeObserver(() => c.resize())\n    ro.observe(container)\n    return () => {\n      ro.disconnect()\n      c.dispose()\n      chart = null\n    }\n  })\n\n  $effect(() => {\n    const opt = mergedOption\n    chart?.setOption(opt)\n  })\n</script>\n\n<div\n  bind:this={ref}\n  data-uipkge\n  data-slot=\"treemap-chart\"\n  role=\"img\"\n  tabindex=\"0\"\n  aria-label={ariaLabel || 'Chart'}\n  style=\"height: {heightStyle}\"\n  class={cn('w-full focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none', className)}\n  {...restProps}\n>\n  <div bind:this={container} class=\"size-full\"></div>\n</div>\n",
      "type": "registry:ui",
      "target": "~/src/lib/components/ui/treemap-chart/TreemapChart.svelte"
    },
    {
      "path": "packages/registry-svelte/components/treemap-chart/chart-theme.ts",
      "content": "// Self-contained chart theme helpers (the Vue twin reads these from the shared\n// `components/ui/charts/useChartTheme.ts`; each Svelte chart ships its own copy\n// so the install unit stays dependency-free apart from `echarts`).\n//\n// The palette is driven by Tailwind v4 CSS variables (`--chart-1..5`,\n// `--muted-foreground`, `--border`, `--popover`, etc.) so dark/light flips\n// happen automatically when the consumer toggles their theme class. Values\n// resolve at runtime via `getComputedStyle`. The component bumps a local\n// `themeKey` whenever `<html>` class/style changes so its derived option\n// re-resolves and the chart re-paints.\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 getChartColors(): string[] {\n  return Array.from({ length: 5 }, (_, i) => resolveVar(`--chart-${i + 1}`, CHART_FALLBACK[i]!))\n}\n\nexport function getChartTextColor(): string {\n  return resolveVar('--muted-foreground', '#888888')\n}\n\nexport function getChartAxisColor(): string {\n  return resolveVar('--border', '#e5e5e5')\n}\n\nexport function getChartTooltipBg(): string {\n  return resolveVar('--popover', 'rgba(255,255,255,0.96)')\n}\n\nexport function getChartTooltipBorder(): string {\n  return resolveVar('--border', '#e5e5e5')\n}\n\nexport function getChartTooltipText(): string {\n  return resolveVar('--popover-foreground', '#333333')\n}\n",
      "type": "registry:ui",
      "target": "~/src/lib/components/ui/treemap-chart/chart-theme.ts"
    },
    {
      "path": "packages/registry-svelte/components/treemap-chart/index.ts",
      "content": "export { default as TreemapChart, type TreemapChartProps, type TreemapNode } from './TreemapChart.svelte'\n",
      "type": "registry:ui",
      "target": "~/src/lib/components/ui/treemap-chart/index.ts"
    }
  ],
  "dependencies": [
    "echarts"
  ],
  "devDependencies": [],
  "registryDependencies": [],
  "description": "Treemap wrapper around Apache ECharts. Hierarchical area-by-value visualization with nested and color-by-value variants. Theme-aware via registry tokens.",
  "categories": [
    "chart"
  ]
}