{
  "title": "Chart Table Selection",
  "description": "Bidirectional state synchronization connecting scatter plot points and interactive table rows.",
  "name": "tanstack-charts-chart-table-selection",
  "dependencies": [
    "@tanstack/charts",
    "@tanstack/react-charts",
    "d3-scale"
  ],
  "registryDependencies": [
    "card",
    "button"
  ],
  "type": "registry:block",
  "files": [
    {
      "path": "components/blocks/tanstack-charts/line/chart-table-selection.tsx",
      "type": "registry:block",
      "content": "import { type ChartPoint, defineChart, dot } from \"@tanstack/charts\";\nimport { controlledSignal } from \"@tanstack/charts/interaction/signal\";\nimport { motion } from \"@tanstack/charts/motion\";\nimport { keyedSelection, whenSelected } from \"@tanstack/charts/selection\";\nimport { tooltip } from \"@tanstack/charts/tooltip\";\nimport { Chart } from \"@tanstack/react-charts/core\";\nimport { useMemo, useState } from \"react\";\n\nimport { scaleLinear } from \"d3-scale\";\nimport { Table as TableIcon, X } from \"lucide-react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from \"@/components/ui/card\";\n\ninterface PointDatum {\n    id: string;\n    label: string;\n    flipper_length_mm: number;\n    body_mass_g: number;\n    island: string;\n}\n\nconst motionRenderer = motion({\n    initial: \"always\",\n    transition: { type: \"spring\", stiffness: 170, damping: 18, mass: 1 },\n});\n\nfunction generateDemoData(): PointDatum[] {\n    const islands = [\"Biscoe\", \"Dream\", \"Torgersen\"];\n    const results: PointDatum[] = [];\n\n    for (let i = 0; i < 15; i++) {\n        const flipper = 180 + Math.floor(i * 3 + Math.random() * 8);\n        const mass = 2800 + Math.floor(i * 200 + Math.random() * 300);\n        const island = islands[i % islands.length];\n        results.push({\n            id: `p-${i + 1}`,\n            label: `Observation #${i + 1}`,\n            flipper_length_mm: flipper,\n            body_mass_g: mass,\n            island,\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 PointDatum;\n    if (!d) return { title: \"\", rows: [] };\n    return {\n        title: `${d.label} (${d.island})`,\n        rows: [\n            { label: \"Flipper Length\", value: `${d.flipper_length_mm} mm`, color: \"var(--chart-1)\" },\n            { label: \"Body Mass\", value: `${d.body_mass_g} g`, color: \"var(--chart-2)\" },\n        ],\n    };\n}\n\nexport function ChartTableSelection() {\n    const [selectedId, setSelectedId] = useState<string | null>(\"p-5\");\n    const data = useMemo(() => generateDemoData(), []);\n\n    const selection = useMemo(\n        () =>\n            keyedSelection<PointDatum, string, number, number>({\n                selected: controlledSignal<string | null, unknown>(selectedId, (next) => setSelectedId(next)),\n                key: (datum) => datum.id,\n            }),\n        [selectedId],\n    );\n\n    const definition = useMemo(\n        () =>\n            defineChart(\n                {\n                    renderer: motionRenderer,\n                    marks: [\n                        dot(data, {\n                            id: \"observations\",\n                            x: \"flipper_length_mm\",\n                            y: \"body_mass_g\",\n                            key: \"id\",\n                            r: 4.5,\n                            fill: \"var(--chart-1)\",\n                        }),\n                        whenSelected(\n                            dot(data, {\n                                id: \"selected-observation\",\n                                x: \"flipper_length_mm\",\n                                y: \"body_mass_g\",\n                                key: \"id\",\n                                r: 7.5,\n                                fill: \"var(--chart-2)\",\n                                stroke: \"var(--background)\",\n                                strokeWidth: 2,\n                            }),\n                            selection,\n                        ),\n                    ],\n                    scales: {\n                        x: { scale: scaleLinear, axis: { label: \"Flipper Length (mm)\" } },\n                        y: {\n                            scale: scaleLinear,\n                            grid: true,\n                            axis: { label: \"Body Mass (g)\" },\n                        },\n                    },\n                    margin: { top: 24, right: 24, bottom: 32, left: 45 },\n                    theme: {\n                        foreground: \"var(--muted-foreground)\",\n                        grid: \"var(--border)\",\n                        background: \"transparent\",\n                    },\n                    selection,\n                },\n                {\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 text-xs\",\n                        anchor: \"pointer\",\n                        placement: \"auto\",\n                        content: (points) => shadcnTooltipContent(points),\n                    },\n                },\n            ),\n        [data, selection],\n    );\n\n    const selectedDatum = data.find((d) => d.id === selectedId);\n\n    return (\n        <Card className=\"w-full max-w-xl\">\n            <CardHeader>\n                <CardTitle>Chart & Data Table Bidirectional Selection</CardTitle>\n                <CardDescription>\n                    2-way state synchronization connecting scatter chart points to interactive table rows\n                </CardDescription>\n            </CardHeader>\n            <CardContent className=\"space-y-4\">\n                <div className=\"h-[200px] w-full\">\n                    <Chart\n                        definition={definition}\n                        renderer={motionRenderer}\n                        height={200}\n                        ariaLabel=\"Chart & Data Table Bidirectional Selection\"\n                    />\n                </div>\n\n                <div className=\"text-muted-foreground flex items-center justify-between border-t pt-2 text-xs font-medium\">\n                    <div>\n                        {selectedDatum ? (\n                            <span>\n                                Selected: <strong className=\"text-foreground\">{selectedDatum.label}</strong> (\n                                {selectedDatum.island}, {selectedDatum.body_mass_g}g)\n                            </span>\n                        ) : (\n                            <span>No item selected</span>\n                        )}\n                    </div>\n                    {selectedId && (\n                        <Button\n                            variant=\"ghost\"\n                            size=\"sm\"\n                            className=\"h-7 px-2 text-xs\"\n                            onClick={() => setSelectedId(null)}>\n                            <X className=\"mr-1 h-3 w-3\" /> Clear\n                        </Button>\n                    )}\n                </div>\n\n                <div className=\"max-h-[220px] overflow-auto rounded-lg border text-xs shadow-xs\">\n                    <table className=\"w-full border-collapse text-left\">\n                        <thead className=\"bg-muted text-foreground sticky top-0 z-10 border-b font-semibold\">\n                            <tr>\n                                <th className=\"p-2.5\">Label</th>\n                                <th className=\"p-2.5\">Island</th>\n                                <th className=\"p-2.5 text-right\">Flipper (mm)</th>\n                                <th className=\"p-2.5 text-right\">Mass (g)</th>\n                            </tr>\n                        </thead>\n                        <tbody className=\"divide-y\">\n                            {data.map((row) => {\n                                const isSelected = row.id === selectedId;\n                                return (\n                                    <tr\n                                        key={row.id}\n                                        onClick={() => setSelectedId(row.id)}\n                                        className={`hover:bg-muted/60 cursor-pointer transition-colors ${\n                                            isSelected ? \"bg-primary/15 text-primary font-semibold\" : \"\"\n                                        }`}>\n                                        <td className=\"p-2.5\">{row.label}</td>\n                                        <td className=\"p-2.5\">{row.island}</td>\n                                        <td className=\"p-2.5 text-right font-mono\">{row.flipper_length_mm}</td>\n                                        <td className=\"p-2.5 text-right font-mono\">{row.body_mass_g}</td>\n                                    </tr>\n                                );\n                            })}\n                        </tbody>\n                    </table>\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                    Selecting a row in the table highlights the point on chart instantly{\" \"}\n                    <TableIcon className=\"h-4 w-4 text-emerald-500\" />\n                </div>\n                <div className=\"text-muted-foreground leading-none\">\n                    `keyedSelection` provides bidirectional binding between visual marks and tabular HTML elements\n                </div>\n            </CardFooter>\n        </Card>\n    );\n}\n\nexport default ChartTableSelection;\n"
    }
  ],
  "mcp": {
    "description": "Renders responsive data visualization with dark mode styling and customizable tooltips. Bidirectional state synchronization connecting scatter plot points and interactive table rows. Relies on card. Use when presenting data insights or analytics dashboards.",
    "tags": [
      "chart",
      "tanstack"
    ]
  }
}