{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"composition-chart","type":"registry:component","title":"Share of Total Chart","description":"100% stacked bars or areas showing each series' share per period; toggling between them re-stacks with springs, with a period tooltip and a legend that hides series.","author":"GetUrUI <hello@geturui.dev>","dependencies":["motion","lucide-react"],"registryDependencies":["@geturui/tabs"],"files":[{"path":"registry/geturui/charts/composition-chart.tsx","type":"registry:component","target":"components/charts/composition-chart.tsx","content":"\"use client\";\n\nimport * as React from \"react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { AreaChart, BarChart3 } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\nimport { Tabs } from \"@/components/ui/tabs\";\n\nexport interface CompositionSeries {\n  key: string;\n  label: string;\n  /** Any CSS colour; defaults to the token palette. */\n  color?: string;\n}\n\nexport interface CompositionDatum {\n  /** Period label, e.g. \"Mar\". */\n  label: string;\n  values: Record<string, number>;\n}\n\nexport interface CompositionChartProps {\n  data: CompositionDatum[];\n  series: CompositionSeries[];\n  mode?: \"bar\" | \"area\";\n  defaultMode?: \"bar\" | \"area\";\n  onModeChange?: (mode: \"bar\" | \"area\") => void;\n  /** Plot height in px (excluding legend and axis). */\n  height?: number;\n  /** Formats raw values in the tooltip. */\n  valueFormatter?: (n: number) => string;\n  title?: string;\n  className?: string;\n}\n\nconst PALETTE = [\"var(--volt)\", \"var(--info)\", \"var(--ember)\", \"var(--success)\", \"var(--warning)\", \"var(--ink-subtle)\"];\nconst M = { top: 8, right: 8, bottom: 26, left: 38 };\n\nfunction useWidth<T extends HTMLElement>(fallback = 640) {\n  const ref = React.useRef<T>(null);\n  const [w, setW] = React.useState(fallback);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([e]) => setW(Math.max(200, e.contentRect.width)));\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, []);\n  return [ref, w] as const;\n}\n\nconst pct = (n: number) => `${(n * 100).toFixed(n > 0 && n < 0.1 ? 1 : 0)}%`;\n\n/** 100% stacked bars or areas showing each series' share per period; toggles between the two, with a per-period tooltip and a legend that hides series. */\nexport function CompositionChart({\n  data,\n  series,\n  mode,\n  defaultMode = \"bar\",\n  onModeChange,\n  height = 240,\n  valueFormatter = (n) => n.toLocaleString(\"en-US\"),\n  title,\n  className,\n}: CompositionChartProps) {\n  const reduce = useReducedMotion();\n  const [innerMode, setInnerMode] = React.useState(defaultMode);\n  const view = mode ?? innerMode;\n  const [hidden, setHidden] = React.useState<Set<string>>(new Set());\n  const [active, setActive] = React.useState<number | null>(null);\n  const [wrapRef, width] = useWidth<HTMLDivElement>();\n  const gid = React.useId().replace(/[^a-zA-Z0-9_-]/g, \"\");\n\n  const colored = series.map((s, i) => ({ ...s, color: s.color ?? PALETTE[i % PALETTE.length] }));\n  const visible = colored.filter((s) => !hidden.has(s.key));\n\n  const iw = width - M.left - M.right;\n  const ih = height;\n  const n = data.length;\n  const band = iw / Math.max(1, n);\n  const barW = Math.min(44, band * 0.62);\n\n  // stacked shares per period: stacks[period][seriesKey] = [y0, y1] in 0..1\n  const stacks = data.map((d) => {\n    const total = visible.reduce((a, s) => a + Math.max(0, d.values[s.key] ?? 0), 0) || 1;\n    let acc = 0;\n    const out: Record<string, [number, number]> = {};\n    for (const s of colored) {\n      const v = hidden.has(s.key) ? 0 : Math.max(0, d.values[s.key] ?? 0) / total;\n      out[s.key] = [acc, acc + v];\n      acc += v;\n    }\n    return { total, out };\n  });\n\n  const y = (v: number) => ih - v * ih;\n  const cx = (i: number) => band * i + band / 2;\n\n  const areaPath = (key: string) => {\n    if (!n) return \"\";\n    const top = data.map((_, i) => `${i === 0 ? \"M\" : \"L\"}${cx(i).toFixed(2)},${y(stacks[i].out[key][1]).toFixed(2)}`);\n    const bottom = data\n      .map((_, i) => n - 1 - i)\n      .map((i) => `L${cx(i).toFixed(2)},${y(stacks[i].out[key][0]).toFixed(2)}`);\n    return `${top.join(\"\")}${bottom.join(\"\")}Z`;\n  };\n\n  const setView = (v: string) => {\n    const m = v as \"bar\" | \"area\";\n    if (mode === undefined) setInnerMode(m);\n    onModeChange?.(m);\n  };\n\n  const toggle = (key: string) =>\n    setHidden((prev) => {\n      const next = new Set(prev);\n      if (next.has(key)) next.delete(key);\n      else if (series.length - next.size > 1) next.add(key);\n      return next;\n    });\n\n  const springT = reduce ? { duration: 0 } : { type: \"spring\" as const, stiffness: 180, damping: 26 };\n  const tip = active !== null ? data[active] : null;\n  const tipLeft = active !== null ? M.left + cx(active) : 0;\n\n  return (\n    <figure className={cn(\"w-full rounded-lg border border-border bg-surface-raised p-4 shadow-sm sm:p-5\", className)}>\n      <div className=\"mb-3 flex flex-wrap items-center gap-3\">\n        {title && <figcaption className=\"mr-auto text-[14.5px] font-semibold text-ink\">{title}</figcaption>}\n        <Tabs\n          size=\"sm\"\n          aria-label=\"Chart type\"\n          value={view}\n          onValueChange={setView}\n          className={cn(!title && \"mr-auto\")}\n          items={[\n            { value: \"bar\", label: \"Bars\", icon: <BarChart3 aria-hidden className=\"size-3.5\" /> },\n            { value: \"area\", label: \"Area\", icon: <AreaChart aria-hidden className=\"size-3.5\" /> },\n          ]}\n        />\n      </div>\n\n      <div ref={wrapRef} className=\"relative\" onPointerLeave={() => setActive(null)}>\n        <svg width={width} height={ih + M.top + M.bottom} className=\"block overflow-visible\" role=\"group\" aria-label={title ?? \"Composition chart\"}>\n          <defs>\n            <clipPath id={`${gid}-reveal`}>\n              <motion.rect\n                x={0}\n                y={-10}\n                height={ih + 20}\n                initial={{ width: reduce ? iw + 20 : 0 }}\n                animate={{ width: iw + 20 }}\n                transition={{ duration: reduce ? 0 : 0.9, ease: [0.22, 1, 0.36, 1] }}\n              />\n            </clipPath>\n          </defs>\n          <g transform={`translate(${M.left},${M.top})`}>\n            {[0, 0.25, 0.5, 0.75, 1].map((t) => (\n              <g key={t}>\n                <line x1={0} x2={iw} y1={y(t)} y2={y(t)} className=\"stroke-border\" strokeDasharray={t === 0 ? undefined : \"3 4\"} />\n                <text x={-8} y={y(t)} dy=\"0.32em\" textAnchor=\"end\" className=\"fill-ink-subtle text-[10.5px] tabular-nums\">\n                  {t * 100}%\n                </text>\n              </g>\n            ))}\n\n            {active !== null && (\n              <rect x={band * active} y={0} width={band} height={ih} className=\"fill-surface-hover\" rx={6} pointerEvents=\"none\" />\n            )}\n\n            <AnimatePresence mode=\"wait\" initial={false}>\n              {view === \"bar\" ? (\n                <motion.g key=\"bars\" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={{ duration: 0.18 }}>\n                  {data.map((d, i) =>\n                    colored.map((s, k) => {\n                      const [a, b] = stacks[i].out[s.key];\n                      const h = Math.max(0, (b - a) * ih);\n                      return (\n                        <motion.rect\n                          key={`${d.label}-${s.key}`}\n                          x={cx(i) - barW / 2}\n                          width={barW}\n                          rx={h > 4 ? 3 : 0}\n                          style={{ fill: s.color }}\n                          stroke=\"var(--surface-raised)\"\n                          strokeWidth={h > 2 ? 1.5 : 0}\n                          initial={{ y: ih, height: 0 }}\n                          animate={{ y: y(b), height: h, opacity: active === null || active === i ? 1 : 0.45 }}\n                          transition={reduce ? { duration: 0 } : { ...springT, delay: (i * 0.04 + k * 0.03) }}\n                        />\n                      );\n                    }),\n                  )}\n                </motion.g>\n              ) : (\n                <motion.g\n                  key=\"area\"\n                  clipPath={`url(#${gid}-reveal)`}\n                  initial={{ opacity: 0 }}\n                  animate={{ opacity: 1 }}\n                  exit={{ opacity: 0 }}\n                  transition={{ duration: 0.18 }}\n                >\n                  {colored.map((s) => (\n                    <motion.path\n                      key={s.key}\n                      initial={false}\n                      animate={{ d: areaPath(s.key) }}\n                      transition={springT}\n                      style={{ fill: s.color }}\n                      fillOpacity={0.88}\n                      stroke=\"var(--surface-raised)\"\n                      strokeWidth={1.25}\n                    />\n                  ))}\n                  {active !== null && <line x1={cx(active)} x2={cx(active)} y1={0} y2={ih} className=\"stroke-ink\" strokeOpacity={0.5} />}\n                </motion.g>\n              )}\n            </AnimatePresence>\n\n            {data.map((d, i) => (\n              <text key={d.label} x={cx(i)} y={ih + 18} textAnchor=\"middle\" className={cn(\"text-[11px]\", active === i ? \"fill-ink\" : \"fill-ink-subtle\")}>\n                {d.label}\n              </text>\n            ))}\n\n            {data.map((d, i) => (\n              <rect\n                key={`hit-${d.label}`}\n                x={band * i}\n                y={0}\n                width={band}\n                height={ih}\n                fill=\"transparent\"\n                tabIndex={0}\n                role=\"img\"\n                aria-label={`${d.label}: ${visible.map((s) => `${s.label} ${pct(stacks[i].out[s.key][1] - stacks[i].out[s.key][0])}`).join(\", \")}`}\n                onPointerEnter={() => setActive(i)}\n                onFocus={() => setActive(i)}\n                onBlur={() => setActive(null)}\n                onKeyDown={(e) => {\n                  if (e.key === \"ArrowRight\" || e.key === \"ArrowLeft\") {\n                    e.preventDefault();\n                    const next = (e.currentTarget.parentNode?.querySelectorAll<SVGRectElement>(\"rect[tabindex]\") ?? [])[\n                      (i + (e.key === \"ArrowRight\" ? 1 : -1) + n) % n\n                    ];\n                    next?.focus();\n                  } else if (e.key === \"Escape\") {\n                    (e.currentTarget as SVGRectElement).blur();\n                  }\n                }}\n                className=\"cursor-crosshair outline-none\"\n              />\n            ))}\n          </g>\n        </svg>\n\n        <AnimatePresence>\n          {tip && active !== null && (\n            <motion.div\n              key=\"tip\"\n              aria-hidden\n              initial={{ opacity: 0, scale: 0.96, left: tipLeft }}\n              animate={{ opacity: 1, scale: 1, left: tipLeft }}\n              exit={{ opacity: 0, scale: 0.96, transition: { duration: 0.1 } }}\n              transition={{ type: \"spring\", stiffness: 500, damping: 36 }}\n              style={{ x: tipLeft > width * 0.6 ? \"calc(-100% - 14px)\" : \"14px\" }}\n              className=\"pointer-events-none absolute top-1 z-10 min-w-44 rounded-sm border border-border bg-surface-raised px-3 py-2 text-xs shadow-md\"\n            >\n              <p className=\"mb-1.5 font-semibold text-ink\">{tip.label}</p>\n              <ul className=\"space-y-1\">\n                {[...visible].reverse().map((s) => {\n                  const [a, b] = stacks[active].out[s.key];\n                  return (\n                    <li key={s.key} className=\"flex items-center gap-2\">\n                      <span className=\"size-2 rounded-[3px]\" style={{ background: s.color }} />\n                      <span className=\"flex-1 text-ink-muted\">{s.label}</span>\n                      <span className=\"font-mono tabular-nums text-ink-subtle\">{valueFormatter(tip.values[s.key] ?? 0)}</span>\n                      <span className=\"w-10 text-right font-mono font-medium tabular-nums text-ink\">{pct(b - a)}</span>\n                    </li>\n                  );\n                })}\n              </ul>\n            </motion.div>\n          )}\n        </AnimatePresence>\n      </div>\n\n      <ul className=\"mt-3 flex flex-wrap gap-1.5\" aria-label=\"Series\">\n        {colored.map((s) => {\n          const on = !hidden.has(s.key);\n          return (\n            <li key={s.key}>\n              <button\n                type=\"button\"\n                aria-pressed={on}\n                onClick={() => toggle(s.key)}\n                className={cn(\n                  \"inline-flex h-7 items-center gap-1.5 rounded-full border px-2.5 text-[12px] font-medium outline-none transition-[color,border-color,opacity] focus-visible:shadow-[var(--focus-ring)]\",\n                  on ? \"border-border text-ink\" : \"border-dashed border-border text-ink-subtle opacity-70\",\n                )}\n              >\n                <span\n                  aria-hidden\n                  className=\"size-2.5 rounded-[3px] transition-transform duration-300 ease-[var(--ease-spring)]\"\n                  style={{ background: s.color, transform: on ? \"scale(1)\" : \"scale(0.5)\" }}\n                />\n                {s.label}\n              </button>\n            </li>\n          );\n        })}\n      </ul>\n    </figure>\n  );\n}\n"},{"path":"LICENSE-geturui.md","type":"registry:file","target":"LICENSE-geturui.md","content":"MIT License\n\nCopyright (c) 2026 geturui.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"}],"categories":["charts","chart","stacked bar","stacked area","composition","share","svg"],"meta":{"tier":"free","license":"MIT","docs":"https://geturui.com/docs/composition-chart"}}