{
  "title": "Recharts Interactive Legend",
  "description": "Interactive toggleable series legend to show or hide individual series dynamically.",
  "name": "tanstack-charts-recharts-interactive-legend",
  "dependencies": [
    "@tanstack/charts",
    "@tanstack/react-charts",
    "d3-scale"
  ],
  "registryDependencies": [
    "card"
  ],
  "type": "registry:block",
  "files": [
    {
      "path": "components/blocks/tanstack-charts/line/recharts-interactive-legend.tsx",
      "type": "registry:block",
      "content": "import { type ChartPoint, defineChart, lineY } from \"@tanstack/charts\";\nimport { controlledSignal } from \"@tanstack/charts/interaction/signal\";\nimport { interactiveColorLegend } from \"@tanstack/charts/legend\";\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 { scaleLinear, scaleUtc } from \"d3-scale\";\nimport { Eye } from \"lucide-react\";\n\nimport { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from \"@/components/ui/card\";\n\ninterface IndustryDatum {\n    industry: string;\n    date: Date;\n    unemployed: number;\n}\n\ntype SeriesId = \"Manufacturing\" | \"Construction\";\n\nconst motionRenderer = motion({\n    initial: \"always\",\n    transition: { type: \"spring\", stiffness: 170, damping: 18, mass: 1 },\n});\n\nconst seriesColors: Record<SeriesId, string> = {\n    Manufacturing: \"var(--chart-1)\",\n    Construction: \"var(--chart-2)\",\n};\n\nfunction generateDemoData(): IndustryDatum[] {\n    const results: IndustryDatum[] = [];\n\n    for (let m = 0; m < 14; m++) {\n        const date = new Date(Date.UTC(2024, m, 1));\n        results.push({\n            industry: \"Manufacturing\",\n            date,\n            unemployed: Math.round(450 + Math.sin(m * 0.4) * 120 + Math.random() * 30),\n        });\n        results.push({\n            industry: \"Construction\",\n            date,\n            unemployed: Math.round(300 + Math.cos(m * 0.4) * 90 + Math.random() * 25),\n        });\n    }\n\n    return results;\n}\n\nfunction shadcnTooltipContent<TDatum>(points: readonly ChartPoint<TDatum>[]) {\n    if (points.length === 0) return { title: \"\", rows: [] };\n    const d = points[0].datum as IndustryDatum;\n    if (!d) return { title: \"\", rows: [] };\n    return {\n        title: `${d.industry} (${d.date.toLocaleDateString(\"en-US\", { month: \"short\", year: \"numeric\", timeZone: \"UTC\" })})`,\n        rows: [\n            {\n                label: \"Unemployed Count\",\n                value: `${d.unemployed}k`,\n                color: seriesColors[d.industry as SeriesId] || \"var(--chart-1)\",\n            },\n        ],\n    };\n}\n\nexport function RechartsInteractiveLegend() {\n    const [visibleSeries, setVisibleSeries] = useState<readonly SeriesId[]>([\"Manufacturing\", \"Construction\"]);\n\n    const rawData = useMemo(() => generateDemoData(), []);\n\n    const filteredData = useMemo(() => {\n        return rawData.filter((d) => visibleSeries.includes(d.industry as SeriesId));\n    }, [rawData, visibleSeries]);\n\n    const definition = useMemo(\n        () =>\n            defineChart(\n                {\n                    renderer: motionRenderer,\n                    marks: [\n                        lineY(filteredData, {\n                            id: \"industry-lines\",\n                            x: \"date\",\n                            y: \"unemployed\",\n                            color: \"industry\",\n                            strokeWidth: 2.5,\n                        }),\n                    ],\n                    scales: {\n                        x: {\n                            scale: scaleUtc,\n                            axis: {\n                                ticks: {\n                                    format: (v: Date) => v.toLocaleDateString(\"en-US\", { month: \"short\", timeZone: \"UTC\" }),\n                                },\n                            },\n                        },\n                        y: {\n                            scale: scaleLinear().domain([0, 750]),\n                            grid: true,\n                            axis: { label: \"Unemployed Count (k)\" },\n                        },\n                    },\n                    color: {\n                        domain: [\"Manufacturing\", \"Construction\"],\n                        range: [\"var(--chart-1)\", \"var(--chart-2)\"],\n                        legend: interactiveColorLegend({\n                            visible: controlledSignal(visibleSeries as readonly string[], (v) =>\n                                setVisibleSeries(v as readonly SeriesId[]),\n                            ),\n                            placement: \"bottom\",\n                            ariaLabel: \"Series visibility toggle\",\n                        }),\n                    },\n                    margin: { top: 20, right: 24, bottom: 60, left: 48 },\n                    theme: {\n                        foreground: \"var(--muted-foreground)\",\n                        grid: \"var(--border)\",\n                        background: \"transparent\",\n                    },\n                },\n                {\n                    focus: \"group-x\",\n                    keyboard: true,\n                    tooltip: {\n                        use: tooltip,\n                        className:\n                            \"font-sans shadow-none rounded-md bg-popover text-popover-foreground border p-2.5 text-xs pointer-events-none transition-all duration-75\",\n                        anchor: \"pointer\",\n                        placement: \"auto\",\n                        content: (points) => shadcnTooltipContent(points),\n                    },\n                },\n            ),\n        [filteredData, visibleSeries],\n    );\n\n    const toggleSeries = (id: SeriesId) => {\n        if (visibleSeries.includes(id)) {\n            if (visibleSeries.length > 1) {\n                setVisibleSeries(visibleSeries.filter((s) => s !== id));\n            }\n        } else {\n            setVisibleSeries([...visibleSeries, id]);\n        }\n    };\n\n    return (\n        <Card className=\"w-full max-w-xl\">\n            <CardHeader>\n                <CardTitle>Interactive Toggleable Legend</CardTitle>\n                <CardDescription>\n                    Click interactive legend items to toggle series visibility on/off dynamically\n                </CardDescription>\n            </CardHeader>\n            <CardContent className=\"space-y-4\">\n                <div className=\"flex items-center justify-center gap-3 pt-1\">\n                    {([\"Manufacturing\", \"Construction\"] as const).map((id) => {\n                        const isVisible = visibleSeries.includes(id);\n                        const color = seriesColors[id];\n                        return (\n                            <button\n                                key={id}\n                                type=\"button\"\n                                onClick={() => toggleSeries(id)}\n                                className={`inline-flex cursor-pointer items-center gap-2 rounded-full border px-3 py-1 text-xs font-medium transition-all duration-150 ${\n                                    isVisible\n                                        ? \"border-border bg-muted/60 text-foreground hover:bg-muted shadow-2xs\"\n                                        : \"text-muted-foreground border-transparent bg-transparent opacity-40 hover:opacity-70\"\n                                }`}>\n                                <span\n                                    className=\"h-2.5 w-2.5 rounded-full transition-transform\"\n                                    style={{\n                                        backgroundColor: color,\n                                        transform: isVisible ? \"scale(1)\" : \"scale(0.75)\",\n                                    }}\n                                />\n                                {id}\n                            </button>\n                        );\n                    })}\n                </div>\n\n                <div className=\"h-[250px] w-full\">\n                    <Chart\n                        definition={definition}\n                        renderer={motionRenderer}\n                        height={250}\n                        ariaLabel=\"Interactive Toggleable Legend Chart\"\n                    />\n                </div>\n            </CardContent>\n            <CardFooter className=\"flex-col items-start gap-2 text-sm\">\n                <div className=\"flex items-center gap-2 leading-none font-medium\">\n                    Controlled signal updates visible series in state reactively{\" \"}\n                    <Eye className=\"h-4 w-4 text-emerald-500\" />\n                </div>\n                <div className=\"text-muted-foreground leading-none\">\n                    `interactiveColorLegend` integrates with React state for seamless toggle interaction\n                </div>\n            </CardFooter>\n        </Card>\n    );\n}\n\nexport default RechartsInteractiveLegend;\n"
    }
  ],
  "mcp": {
    "description": "Renders responsive data visualization with dark mode styling and customizable tooltips. Interactive toggleable series legend to show or hide individual series dynamically. Relies on card. Use when presenting data insights or analytics dashboards.",
    "tags": [
      "chart",
      "tanstack"
    ]
  }
}