{
  "title": "Area Interactive",
  "description": "An interactive network bandwidth and throughput area chart with time range select built with TanStack Charts.",
  "name": "tanstack-charts-area-interactive",
  "dependencies": [
    "@tanstack/charts",
    "@tanstack/react-charts",
    "d3-array",
    "d3-scale",
    "d3-shape"
  ],
  "registryDependencies": [
    "card",
    "select",
    "chart"
  ],
  "type": "registry:block",
  "files": [
    {
      "path": "components/blocks/tanstack-charts/area/area-interactive.tsx",
      "type": "registry:block",
      "content": "import { areaY, defineChart, lineY } from \"@tanstack/charts\";\nimport { d3Curve } from \"@tanstack/charts/d3/shape\";\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\";\nimport { curveMonotoneX } from \"d3-shape\";\n\nimport { Card, CardContent, CardDescription, CardHeader, CardTitle } from \"@/components/ui/card\";\nimport type { ChartConfig } from \"@/components/ui/chart\";\n\nconst startTime = new Date(2026, 6, 1, 0, 0, 0).getTime();\nconst HOUR_MS = 60 * 60 * 1000;\n\nconst chartData = Array.from({ length: 72 }, (_, i) => {\n    const date = new Date(startTime + i * HOUR_MS);\n    const hour = date.getHours();\n\n    const diurnalCycle = Math.sin(((hour - 6) / 24) * 2 * Math.PI) * 0.3 + 0.7;\n\n    const microNoise = Math.sin(i * 0.7) * 4 + Math.cos(i * 1.3) * 6;\n    const periodicSpike = i % 12 === 0 ? 15 : 0;\n\n    const desktop = Math.round((250 + microNoise * 10 + periodicSpike * 5) * diurnalCycle + 120);\n    const mobile = Math.round((180 + microNoise * 8 + periodicSpike * 3) * diurnalCycle + 90);\n\n    return {\n        date,\n        desktop,\n        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 formatTooltipDate = (date: unknown) => {\n    if (!(date instanceof Date)) return \"\";\n    return date.toLocaleDateString(\"en-US\", {\n        month: \"short\",\n        day: \"numeric\",\n        hour: \"numeric\",\n        minute: \"2-digit\",\n    });\n};\n\ntype MetricTab = \"combined\" | \"desktop\" | \"mobile\";\n\nconst motionRenderer = motion({\n    initial: \"always\",\n    transition: { type: \"spring\", stiffness: 140, damping: 16, mass: 0.8 },\n});\n\nexport const Demo = () => {\n    const [activeTab, setActiveTab] = useState<MetricTab>(\"combined\");\n\n    const stats = 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            combined: Math.round((totalDesktop + totalMobile) / chartData.length),\n            desktop: Math.round(totalDesktop / chartData.length),\n            mobile: Math.round(totalMobile / chartData.length),\n        };\n    }, []);\n\n    const xDomain = useMemo(() => extent(chartData, (d) => d.date) as [Date, Date], []);\n    const fixedYMax = useMemo(() => {\n        const peak = max(chartData, (d) => Math.max(d.desktop, d.mobile)) ?? 350;\n        return Math.ceil(peak / 50) * 50;\n    }, []);\n\n    const definition = useMemo(() => {\n        const getDesktopY = (d: (typeof chartData)[number]) => {\n            if (activeTab === \"mobile\") return d.mobile;\n            return d.desktop;\n        };\n\n        const getMobileY = (d: (typeof chartData)[number]) => {\n            if (activeTab === \"desktop\") return d.desktop;\n            return d.mobile;\n        };\n\n        const getDesktopColor = () => {\n            if (activeTab === \"mobile\") return chartConfig.mobile.color;\n            return chartConfig.desktop.color;\n        };\n\n        const getMobileColor = () => {\n            if (activeTab === \"desktop\") return chartConfig.desktop.color;\n            return chartConfig.mobile.color;\n        };\n\n        const marks = [\n            // Desktop Area\n            areaY(chartData, {\n                id: \"desktop-area\",\n                key: (d) => d.date.toISOString(),\n                x: (d) => d.date,\n                y: getDesktopY,\n                fill: getDesktopColor(),\n                fillOpacity: 0.35,\n                curve: d3Curve(curveMonotoneX),\n            }),\n            // Desktop Line\n            lineY(chartData, {\n                id: \"desktop-line\",\n                key: (d) => d.date.toISOString(),\n                x: (d) => d.date,\n                y: getDesktopY,\n                stroke: getDesktopColor(),\n                strokeWidth: 2,\n                curve: d3Curve(curveMonotoneX),\n                points: false,\n            }),\n\n            // Mobile Area\n            areaY(chartData, {\n                id: \"mobile-area\",\n                key: (d) => d.date.toISOString(),\n                x: (d) => d.date,\n                y: getMobileY,\n                fill: getMobileColor(),\n                fillOpacity: 0.35,\n                curve: d3Curve(curveMonotoneX),\n            }),\n            // Mobile Line\n            lineY(chartData, {\n                id: \"mobile-line\",\n                key: (d) => d.date.toISOString(),\n                x: (d) => d.date,\n                y: getMobileY,\n                stroke: getMobileColor(),\n                strokeWidth: 2,\n                curve: d3Curve(curveMonotoneX),\n                points: false,\n            }),\n        ];\n\n        return defineChart(\n            {\n                marks,\n                renderer: motionRenderer,\n                motion: {\n                    transition: { type: \"spring\", stiffness: 170, damping: 18, mass: 1 },\n                },\n                scales: {\n                    x: {\n                        scale: scaleTime().domain(xDomain),\n                    },\n                    y: {\n                        scale: scaleLinear().domain([0, fixedYMax]).nice(),\n                        grid: true,\n                    },\n                },\n            },\n            {\n                focus: \"group-x\",\n                tooltip: {\n                    use: tooltip,\n                    motion: { type: \"spring\", stiffness: 170, damping: 18 },\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                        const activeMetrics = activeTab === \"combined\" ? ([\"desktop\", \"mobile\"] as const) : [activeTab];\n\n                        return {\n                            title: formatTooltipDate(points[0].xValue),\n                            rows: activeMetrics.map((key) => ({\n                                label: chartConfig[key].label,\n                                value: `${datum[key].toLocaleString(\"en-US\")} visitors`,\n                                color: chartConfig[key].color,\n                            })),\n                        };\n                    },\n                },\n            },\n        );\n    }, [activeTab, xDomain, fixedYMax]);\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\">Live Server Throughput</CardTitle>\n                    <CardDescription>\n                        {activeTab === \"combined\"\n                            ? \"Interactive visitor traffic across desktop and mobile devices (Last 72 Hours)\"\n                            : `Isolated traffic trend for ${chartConfig[activeTab].label}`}\n                    </CardDescription>\n                </div>\n\n                {/* Tab Controls */}\n                <div className=\"flex\">\n                    {([\"combined\", \"desktop\", \"mobile\"] as const).map((key) => {\n                        const label = key === \"combined\" ? \"Combined Avg\" : chartConfig[key].label;\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-4 py-4 text-left transition-colors even:border-l sm:border-t-0 sm:border-l sm:px-6 sm:py-6\"\n                                onClick={() => setActiveTab(key)}>\n                                <span className=\"text-muted-foreground text-xs lg:text-nowrap\">{label}</span>\n                                <span className=\"text-lg leading-none font-bold sm:text-2xl\">\n                                    {stats[key].toLocaleString(\"en-US\")}\n                                    <span className=\"text-muted-foreground ml-1 text-xs font-normal\">/hr</span>\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                {/* Dynamic Legend */}\n                <div className=\"text-muted-foreground mb-4 flex items-center justify-end gap-5 text-xs font-medium\">\n                    {(activeTab === \"combined\" || activeTab === \"desktop\") && (\n                        <div className=\"flex items-center gap-2\">\n                            <span\n                                className=\"h-2.5 w-2.5 rounded-full\"\n                                style={{ backgroundColor: chartConfig.desktop.color }}\n                            />\n                            <span>Desktop</span>\n                        </div>\n                    )}\n                    {(activeTab === \"combined\" || activeTab === \"mobile\") && (\n                        <div className=\"flex items-center gap-2\">\n                            <span\n                                className=\"h-2.5 w-2.5 rounded-full\"\n                                style={{ backgroundColor: chartConfig.mobile.color }}\n                            />\n                            <span>Mobile</span>\n                        </div>\n                    )}\n                </div>\n\n                <div className=\"h-[300px] w-full\">\n                    <Chart\n                        definition={definition}\n                        renderer={motionRenderer}\n                        height={300}\n                        ariaLabel={`Live server throughput chart displaying ${activeTab} data`}\n                    />\n                </div>\n            </CardContent>\n        </Card>\n    );\n};\n\nexport default Demo;\n"
    }
  ],
  "mcp": {
    "description": "Renders responsive data visualization with dark mode styling and customizable tooltips. An interactive network bandwidth and throughput area chart with time range select built with TanStack Charts. Relies on card, select. Use when presenting data insights or analytics dashboards.",
    "tags": [
      "chart",
      "tanstack",
      "area"
    ]
  }
}