{
  "title": "Dual-Handle Interactive Brush Range",
  "description": "Drag handles horizontally to select date domain window bounds.",
  "name": "tanstack-charts-brush-range-selection",
  "dependencies": [
    "@tanstack/charts",
    "@tanstack/react-charts",
    "d3-scale"
  ],
  "registryDependencies": [
    "card"
  ],
  "type": "registry:block",
  "files": [
    {
      "path": "components/blocks/tanstack-charts/line/brush-range-selection.tsx",
      "type": "registry:block",
      "content": "import { type ChartPoint, defineChart, dot, lineY } from \"@tanstack/charts\";\nimport { brushX } from \"@tanstack/charts/interaction/brush\";\nimport { controlledSignal } from \"@tanstack/charts/interaction/signal\";\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 { Sliders } from \"lucide-react\";\n\nimport { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from \"@/components/ui/card\";\n\ninterface StockDatum {\n    date: Date;\n    close: number;\n}\n\nconst motionRenderer = motion({\n    initial: \"always\",\n    transition: { type: \"spring\", stiffness: 170, damping: 18, mass: 1 },\n});\n\nfunction generateDemoData(): StockDatum[] {\n    const results: StockDatum[] = [];\n    let price = 150;\n    const baseDate = new Date(Date.UTC(2024, 0, 1)).getTime();\n\n    for (let i = 0; i < 24; i++) {\n        price += Math.sin(i * 0.4) * 6 + (Math.random() - 0.45) * 8;\n        results.push({\n            date: new Date(baseDate + i * 15 * 24 * 60 * 60 * 1000),\n            close: Number(Math.max(100, price).toFixed(2)),\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 StockDatum;\n    if (!d || !d.date) return { title: \"\", rows: [] };\n    const dateObj = d.date instanceof Date ? d.date : new Date(d.date);\n    const titleStr = isNaN(dateObj.getTime())\n        ? \"\"\n        : dateObj.toLocaleDateString(\"en-US\", { month: \"short\", day: \"numeric\", year: \"numeric\", timeZone: \"UTC\" });\n    return {\n        title: titleStr,\n        rows: [{ label: \"Close Price\", value: `$${d.close.toFixed(2)}`, color: \"var(--chart-1)\" }],\n    };\n}\n\nexport function BrushRangeSelection() {\n    const data = useMemo(() => generateDemoData(), []);\n    const dates = useMemo(() => data.map((d) => d.date), [data]);\n    const fullDomain = useMemo(() => [dates[0], dates[dates.length - 1]], [dates]);\n\n    const [range, setRange] = useState<{ start: Date; end: Date }>({\n        start: dates[4],\n        end: dates[16],\n    });\n\n    const rangeStats = useMemo(() => {\n        const startTime = range.start instanceof Date ? range.start.getTime() : new Date(range.start).getTime();\n        const endTime = range.end instanceof Date ? range.end.getTime() : new Date(range.end).getTime();\n        const sliced = data.filter((d) => {\n            const t = d.date instanceof Date ? d.date.getTime() : new Date(d.date).getTime();\n            return t >= startTime && t <= endTime;\n        });\n        if (sliced.length === 0) return { count: 0, avg: 0 };\n        const sum = sliced.reduce((acc, curr) => acc + curr.close, 0);\n        return { count: sliced.length, avg: sum / sliced.length };\n    }, [data, range]);\n\n    const definition = useMemo(\n        () =>\n            defineChart(\n                {\n                    renderer: motionRenderer,\n                    marks: [\n                        lineY(data, {\n                            id: \"brush-series-line\",\n                            x: \"date\",\n                            y: \"close\",\n                            stroke: \"var(--chart-1)\",\n                            strokeWidth: 2.5,\n                        }),\n                        dot(data, {\n                            id: \"brush-series-points\",\n                            x: \"date\",\n                            y: \"close\",\n                            fill: \"var(--chart-1)\",\n                            r: 3.5,\n                            stroke: \"var(--background)\",\n                            strokeWidth: 1,\n                        }),\n                    ],\n                    scales: {\n                        x: {\n                            scale: scaleUtc().domain(fullDomain),\n                            axis: {\n                                ticks: {\n                                    format: (v: any) => {\n                                        const dateObj = v instanceof Date ? v : new Date(v);\n                                        return isNaN(dateObj.getTime())\n                                            ? \"\"\n                                            : dateObj.toLocaleDateString(\"en-US\", { month: \"short\", timeZone: \"UTC\" });\n                                    },\n                                },\n                            },\n                        },\n                        y: {\n                            scale: scaleLinear,\n                            grid: true,\n                            axis: { label: \"Price ($)\" },\n                        },\n                    },\n                    controls: [\n                        brushX({\n                            id: \"monthly-range\",\n                            range: controlledSignal(range, (next: any) => {\n                                if (!next) return;\n                                setRange({\n                                    start: next.start instanceof Date ? next.start : new Date(next.start),\n                                    end: next.end instanceof Date ? next.end : new Date(next.end),\n                                });\n                            }),\n                            values: dates,\n                            ariaLabel: \"Time range brush handles\",\n                            selectionStyle: {\n                                fill: \"var(--chart-1)\",\n                                fillOpacity: 0.18,\n                                stroke: \"var(--chart-1)\",\n                                strokeWidth: 1.5,\n                            },\n                            handleStyle: {\n                                fill: \"var(--background)\",\n                                stroke: \"var(--chart-1)\",\n                                strokeWidth: 2,\n                            },\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                },\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, dates, fullDomain, range],\n    );\n\n    const fmtDate = (d: any) => {\n        const dateObj = d instanceof Date ? d : new Date(d);\n        return isNaN(dateObj.getTime())\n            ? \"\"\n            : dateObj.toLocaleDateString(\"en-US\", { month: \"short\", day: \"numeric\", timeZone: \"UTC\" });\n    };\n\n    return (\n        <Card className=\"w-full max-w-xl\">\n            <CardHeader>\n                <CardTitle>Dual-Handle Interactive Brush Range Selection</CardTitle>\n                <CardDescription>\n                    Drag handles horizontally to select date sub-ranges and compute window aggregations\n                </CardDescription>\n            </CardHeader>\n            <CardContent>\n                <div className=\"h-[250px] w-full\">\n                    <Chart\n                        definition={definition}\n                        renderer={motionRenderer}\n                        height={250}\n                        ariaLabel=\"Dual-Handle Interactive Brush Range Selection 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                    Selection: {fmtDate(range.start)} → {fmtDate(range.end)} ({rangeStats.count} points, Avg: $\n                    {rangeStats.avg.toFixed(2)}) <Sliders className=\"h-4 w-4 text-emerald-500\" />\n                </div>\n                <div className=\"text-muted-foreground leading-none\">\n                    `brushX` mark provides dual handles for active range selection and summary statistics\n                </div>\n            </CardFooter>\n        </Card>\n    );\n}\n\nexport default BrushRangeSelection;\n"
    }
  ],
  "mcp": {
    "description": "Renders responsive data visualization with dark mode styling and customizable tooltips. Drag handles horizontally to select date domain window bounds. Relies on card. Use when presenting data insights or analytics dashboards.",
    "tags": [
      "chart",
      "tanstack"
    ]
  }
}