{
  "title": "Bar Chart Interactive",
  "description": "An interactive bar chart with tabbed metric selection built with TanStack Charts.",
  "name": "tanstack-charts-bar-interactive",
  "dependencies": [
    "@tanstack/charts",
    "@tanstack/react-charts",
    "d3-array",
    "d3-scale"
  ],
  "registryDependencies": [
    "card",
    "chart"
  ],
  "type": "registry:block",
  "files": [
    {
      "path": "components/blocks/tanstack-charts/bar/bar-chart-interactive.tsx",
      "type": "registry:block",
      "content": "import { barY, defineChart } from \"@tanstack/charts\";\nimport { motion } from \"@tanstack/charts/motion\";\nimport { tooltip } from \"@tanstack/charts/tooltip\";\nimport { Chart } from \"@tanstack/react-charts/core\";\nimport { useMemo, useState } from \"react\";\n\nimport { extent, max } from \"d3-array\";\nimport { scaleLinear, scaleTime } from \"d3-scale\";\n\nimport { Card, CardContent, CardDescription, CardHeader, CardTitle } from \"@/components/ui/card\";\nimport type { ChartConfig } from \"@/components/ui/chart\";\n\n// Generate 3 months of daily visitor data (April 1 to June 30, 2024)\nconst startTime = new Date(2024, 3, 1).getTime();\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\nconst chartData = Array.from({ length: 91 }, (_, i) => {\n    const date = new Date(startTime + i * DAY_MS);\n    const dayOfWeek = date.getDay();\n    const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;\n    const baseFactor = isWeekend ? 0.65 : 1.0;\n\n    const desktop = Math.round((180 + Math.sin(i * 0.15) * 70 + Math.cos(i * 0.05) * 50) * baseFactor + (i % 7) * 12);\n    const mobile = Math.round(\n        (130 + Math.cos(i * 0.12) * 55 + Math.sin(i * 0.08) * 35) * (isWeekend ? 1.15 : 0.85) + (i % 5) * 10,\n    );\n\n    return {\n        date,\n        desktop: Math.max(50, desktop),\n        mobile: Math.max(40, mobile),\n    };\n});\n\nconst chartConfig = {\n    desktop: {\n        label: \"Desktop\",\n        color: \"var(--chart-1)\",\n    },\n    mobile: {\n        label: \"Mobile\",\n        color: \"var(--chart-2)\",\n    },\n} satisfies ChartConfig;\n\nconst motionRenderer = motion({\n    initial: \"always\",\n    transition: { type: \"spring\", stiffness: 140, damping: 16, mass: 0.8 },\n});\n\nconst formatTooltipDate = (date: unknown) => {\n    if (!(date instanceof Date)) return \"\";\n    return date.toLocaleDateString(\"en-US\", {\n        month: \"short\",\n        day: \"numeric\",\n        year: \"numeric\",\n    });\n};\n\ntype MetricTab = \"desktop\" | \"mobile\";\n\nexport const BarChartInteractive = () => {\n    const [activeTab, setActiveTab] = useState<MetricTab>(\"desktop\");\n\n    const totals = useMemo(() => {\n        const totalDesktop = chartData.reduce((acc, curr) => acc + curr.desktop, 0);\n        const totalMobile = chartData.reduce((acc, curr) => acc + curr.mobile, 0);\n\n        return {\n            desktop: totalDesktop,\n            mobile: totalMobile,\n        };\n    }, []);\n\n    const definition = useMemo(() => {\n        const xDomain = extent(chartData, (d) => d.date) as [Date, Date];\n        const activeColor = chartConfig[activeTab].color;\n        const yMax = max(chartData, (d) => d[activeTab]) ?? 0;\n\n        const marks = [\n            barY(chartData, {\n                id: \"visitor-bar\", // Stable mark ID for morph animations\n                key: (d) => d.date.toISOString(), // Stable item keys\n                x: (d) => d.date,\n                y: (d) => d[activeTab],\n                fill: activeColor,\n                radius: 2,\n            }),\n        ];\n\n        return defineChart(\n            {\n                renderer: motionRenderer,\n                motion: {\n                    transition: { type: \"spring\", stiffness: 140, damping: 16, mass: 0.8 },\n                },\n                marks,\n                scales: {\n                    x: {\n                        scale: scaleTime().domain(xDomain),\n                    },\n                    y: {\n                        scale: scaleLinear()\n                            .domain([0, Math.ceil(yMax / 50) * 50])\n                            .nice(),\n                        grid: true,\n                    },\n                },\n            },\n            {\n                focus: \"group-x\",\n                tooltip: {\n                    use: tooltip,\n                    motion: { type: \"spring\", stiffness: 140, damping: 16 },\n                    className: \"font-sans! shadow-none! capitalize!\",\n                    content: (points) => {\n                        const datum = points[0]?.datum as (typeof chartData)[number];\n                        if (!datum) return { rows: [] };\n\n                        return {\n                            title: formatTooltipDate(points[0].xValue),\n                            rows: [\n                                {\n                                    label: chartConfig[activeTab].label,\n                                    value: Number(datum[activeTab]).toLocaleString(\"en-US\"),\n                                    color: activeColor,\n                                },\n                            ],\n                        };\n                    },\n                },\n            },\n        );\n    }, [activeTab]);\n\n    return (\n        <Card className=\"gap-0 py-4 sm:py-0\">\n            <CardHeader className=\"flex flex-col items-stretch border-b p-0! sm:flex-row\">\n                {/* Title Context */}\n                <div className=\"flex flex-1 flex-col justify-center gap-1 px-6 pt-4 pb-3 sm:pt-6 sm:pb-6\">\n                    <CardTitle className=\"text-lg\">User Activity Highlights</CardTitle>\n                    <CardDescription>Showing total visitors for the last 3 months</CardDescription>\n                </div>\n\n                {/* Tab Controls */}\n                <div className=\"flex\">\n                    {([\"desktop\", \"mobile\"] as const).map((key) => {\n                        return (\n                            <button\n                                key={key}\n                                data-active={activeTab === key}\n                                className=\"data-[active=true]:bg-muted/50 hover:bg-muted/30 flex flex-1 flex-col justify-center gap-1 border-t px-6 py-4 text-left transition-colors even:border-l sm:border-t-0 sm:border-l sm:px-8 sm:py-6\"\n                                onClick={() => setActiveTab(key)}>\n                                <span className=\"text-muted-foreground text-xs tracking-wider uppercase\">\n                                    {chartConfig[key].label}\n                                </span>\n                                <span className=\"text-lg leading-none font-bold sm:text-2xl\">\n                                    {totals[key].toLocaleString(\"en-US\")}\n                                </span>\n                            </button>\n                        );\n                    })}\n                </div>\n            </CardHeader>\n\n            <CardContent className=\"px-2 pt-4 sm:p-6 sm:pt-8\">\n                {/* Active Legend Indicator */}\n                <div className=\"text-muted-foreground mb-4 flex items-center justify-end gap-2 text-xs font-medium\">\n                    <span\n                        className=\"h-2.5 w-2.5 rounded-full transition-colors duration-300\"\n                        style={{ backgroundColor: chartConfig[activeTab].color }}\n                    />\n                    <span>{chartConfig[activeTab].label} Visitors</span>\n                </div>\n\n                <div className=\"h-[280px] w-full\">\n                    <Chart\n                        definition={definition}\n                        renderer={motionRenderer}\n                        height={280}\n                        ariaLabel={`User activity bar chart displaying ${activeTab} data`}\n                    />\n                </div>\n            </CardContent>\n        </Card>\n    );\n};\n\nexport default BarChartInteractive;\n"
    }
  ],
  "mcp": {
    "description": "Renders responsive data visualization with dark mode styling and customizable tooltips. An interactive bar chart with tabbed metric selection built with TanStack Charts. Relies on card. Use when presenting data insights or analytics dashboards.",
    "tags": [
      "chart",
      "tanstack",
      "bar"
    ]
  }
}