{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "marching-ants-line-chart",
  "title": "Marching Ants Line Chart",
  "description": "A line chart you measure by dragging: the range gets a marching ants outline, the stats follow it, and the forecast part of the line marches too.",
  "dependencies": [],
  "files": [
    {
      "path": "registry/new-york/marching-ants-line-chart/marching-ants-line-chart.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\n\nexport interface AntsPoint {\n  /** ISO date, YYYY-MM-DD. */\n  date: string;\n  value: number;\n}\n\nexport interface MarchingAntsLineChartProps extends Omit<\n  React.ComponentPropsWithoutRef<\"section\">,\n  \"title\"\n> {\n  theme?: \"dark\" | \"light\";\n  title?: string;\n  subtitle?: string;\n  data?: AntsPoint[];\n  /** How many of the last points are a forecast, drawn as a marching line. */\n  forecast?: number;\n  /** Range selected at the start, as first and last index. Pass null for none. */\n  defaultRange?: [number, number] | null;\n  /** Colour of the line, selection and cells. */\n  color?: string;\n  /** Height of the plot, in px. */\n  height?: number;\n  formatValue?: (value: number) => string;\n  /** Called when the selection changes, with the selected points. */\n  onRangeChange?: (points: AntsPoint[]) => void;\n}\n\nconst PALETTES = {\n  dark: {\n    card: \"#08090A\",\n    border: \"rgba(255,255,255,0.08)\",\n    grid: \"rgba(255,255,255,0.05)\",\n    text: \"#F7F8F8\",\n    sub: \"#8A8F98\",\n    faint: \"#62666D\",\n    empty: \"#16171A\",\n    tip: \"#161718\",\n    tipShadow: \"0 4px 24px rgba(0,0,0,0.4)\",\n    chip: \"rgba(255,255,255,0.05)\",\n    chipOn: \"rgba(255,255,255,0.1)\",\n    ring: \"#F7F8F8\",\n    accent: \"#2EE6A8\",\n    glow: 0.8,\n  },\n  light: {\n    card: \"#FFFFFF\",\n    border: \"rgba(8,9,10,0.08)\",\n    grid: \"rgba(8,9,10,0.06)\",\n    text: \"#08090A\",\n    sub: \"#62666D\",\n    faint: \"#8A8F98\",\n    empty: \"#EEEFF1\",\n    tip: \"#FFFFFF\",\n    tipShadow: \"0 3px 12px rgba(8,9,10,0.09)\",\n    chip: \"rgba(8,9,10,0.04)\",\n    chipOn: \"#FFFFFF\",\n    ring: \"#08090A\",\n    accent: \"#0E9F6E\",\n    glow: 0.35,\n  },\n};\n\ntype Palette = (typeof PALETTES)[\"dark\"];\n\nconst DAYS = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\nconst MONTHS = [\n  \"Jan\",\n  \"Feb\",\n  \"Mar\",\n  \"Apr\",\n  \"May\",\n  \"Jun\",\n  \"Jul\",\n  \"Aug\",\n  \"Sep\",\n  \"Oct\",\n  \"Nov\",\n  \"Dec\",\n];\n\nconst LEFT = 40;\nconst RIGHT = 8;\nconst TOP = 10;\n\nfunction parse(date: string) {\n  const [y, m, d] = date.split(\"-\").map(Number);\n  return new Date(Date.UTC(y, m - 1, d));\n}\n\n/** \"Dec 3\" */\nfunction shortDate(date: string) {\n  const d = parse(date);\n  return `${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}`;\n}\n\n/** \"Wed, Dec 3\" */\nfunction longDate(date: string) {\n  return `${DAYS[parse(date).getUTCDay()]}, ${shortDate(date)}`;\n}\n\n/** A fixed, believable daily series: a trend, a weekly rhythm and integer noise, so server and client agree. */\nfunction makeSeries(seed: number, length: number, base: number, rise: number) {\n  const week = [0, 12, 18, 16, 10, -24, -30];\n  const end = Date.UTC(2025, 11, 31);\n  let state = seed;\n  return Array.from({ length }, (_, i) => {\n    state = (state * 9301 + 49297) % 233280;\n    const noise = Math.round((state / 233280 - 0.5) * 34);\n    const when = new Date(end - (length - 1 - i) * 86400000);\n    return {\n      date: when.toISOString().slice(0, 10),\n      value: Math.round(\n        (base + (rise * i) / length) *\n          (1 + (week[when.getUTCDay()] + noise) / 100),\n      ),\n    };\n  });\n}\n\nfunction mix(a: string, b: string, t: number) {\n  const channels = (hex: string) =>\n    [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16));\n  const [x, y] = [channels(a), channels(b)];\n  return `rgb(${x.map((v, i) => Math.round(v + (y[i] - v) * t)).join(\",\")})`;\n}\n\n/** Five levels from the quartiles, so one huge day does not wash out the rest. */\nfunction levels(values: number[]) {\n  const sorted = [...values].sort((a, b) => a - b);\n  const at = (p: number) => sorted[Math.floor(p * (sorted.length - 1))] ?? 0;\n  const cuts = [at(0.2), at(0.45), at(0.7), at(0.9)];\n  return values.map((v) => cuts.filter((c) => v > c).length);\n}\n\nconst LEVEL_MIX = [0.12, 0.3, 0.52, 0.76, 1];\n\n// Monotone cubic interpolation preserves local extrema and never overshoots the data.\nfunction curve(points: [number, number][]) {\n  if (points.length < 2) return \"\";\n  const slopes = points\n    .slice(1)\n    .map((p, i) => (p[1] - points[i][1]) / (p[0] - points[i][0]));\n  const tangents = points.map((_, i) =>\n    i === 0\n      ? slopes[0]\n      : i === points.length - 1\n        ? slopes[i - 1]\n        : slopes[i - 1] * slopes[i] <= 0\n          ? 0\n          : (slopes[i - 1] + slopes[i]) / 2,\n  );\n  return (\n    `M${points[0][0].toFixed(1)},${points[0][1].toFixed(1)}` +\n    points\n      .slice(1)\n      .map((p, i) => {\n        const prev = points[i];\n        const dx = (p[0] - prev[0]) / 3;\n        return `C${(prev[0] + dx).toFixed(1)},${(prev[1] + dx * tangents[i]).toFixed(1)} ${(p[0] - dx).toFixed(1)},${(p[1] - dx * tangents[i + 1]).toFixed(1)} ${p[0].toFixed(1)},${p[1].toFixed(1)}`;\n      })\n      .join(\"\")\n  );\n}\n\nfunction useReducedMotion() {\n  return React.useSyncExternalStore(\n    (callback) => {\n      const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n      query.addEventListener(\"change\", callback);\n      return () => query.removeEventListener(\"change\", callback);\n    },\n    () => window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches,\n    () => false,\n  );\n}\n\n/** The chart is drawn at its real width, so its text stays the same size on a phone. */\nfunction useWidth(ref: React.RefObject<HTMLElement | null>) {\n  const [width, setWidth] = React.useState(700);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const ro = new ResizeObserver(([entry]) =>\n      setWidth(Math.max(240, Math.round(entry.contentRect.width))),\n    );\n    ro.observe(el);\n    return () => ro.disconnect();\n  }, [ref]);\n  return width;\n}\n\nfunction Stat({\n  value,\n  label,\n  pal,\n}: {\n  value: string;\n  label: string;\n  pal: Palette;\n}) {\n  return (\n    <div className=\"text-left sm:text-right\">\n      <p className=\"m-0 text-[18px] leading-[1.2] font-[510] tracking-[-0.018em] tabular-nums\">\n        {value}\n      </p>\n      <p\n        className=\"m-0 mt-0.5 text-[12px] tracking-[-0.011em]\"\n        style={{ color: pal.sub }}\n      >\n        {label}\n      </p>\n    </div>\n  );\n}\n\nfunction Legend({ pal, accent }: { pal: Palette; accent: string }) {\n  return (\n    <div\n      className=\"flex items-center gap-1 text-[12px]\"\n      style={{ color: pal.sub }}\n    >\n      <span className=\"mr-1\">Less</span>\n      {LEVEL_MIX.map((t) => (\n        <span\n          key={t}\n          className=\"size-2.5 rounded-[3px]\"\n          style={{ background: mix(pal.empty, accent, t) }}\n        />\n      ))}\n      <span className=\"ml-1\">More</span>\n    </div>\n  );\n}\n\nfunction Tip({\n  x,\n  y,\n  width,\n  pal,\n  children,\n}: {\n  x: number;\n  y: number;\n  width: number;\n  pal: Palette;\n  children: React.ReactNode;\n}) {\n  return (\n    <div\n      aria-hidden=\"true\"\n      className=\"pointer-events-none absolute z-10 -translate-x-1/2 rounded-lg px-2.5 py-1.5 text-[12px] tracking-[-0.011em] whitespace-nowrap\"\n      style={{\n        left: Math.max(92, Math.min(width - 92, x)),\n        top: Math.max(0, y - 42),\n        background: pal.tip,\n        color: pal.sub,\n        boxShadow: `inset 0 0 0 1px ${pal.border}, ${pal.tipShadow}`,\n      }}\n    >\n      {children}\n    </div>\n  );\n}\n\nconst CARD_FONT =\n  '\"Inter Variable\", Inter, \"SF Pro Display\", -apple-system, BlinkMacSystemFont, sans-serif';\n\nconst DEFAULT_DATA: AntsPoint[] = makeSeries(29, 60, 180, 150);\nconst FORMAT = (n: number) => Math.round(n).toLocaleString(\"en-US\");\n\nexport function MarchingAntsLineChart({\n  theme = \"dark\",\n  title = \"Signups\",\n  subtitle = \"Drag across the chart to measure a range.\",\n  data = DEFAULT_DATA,\n  forecast = 12,\n  defaultRange = [20, 36],\n  color,\n  height = 200,\n  formatValue = FORMAT,\n  onRangeChange,\n  className,\n  style,\n  ...props\n}: MarchingAntsLineChartProps) {\n  const pal = PALETTES[theme];\n  const accent = color ?? pal.accent;\n  const reduce = useReducedMotion();\n  const boxRef = React.useRef<HTMLDivElement>(null);\n  const width = useWidth(boxRef);\n  const antsRef = React.useRef<SVGRectElement>(null);\n  const trailRef = React.useRef<SVGPathElement>(null);\n  const anchor = React.useRef<number | null>(null);\n  const [range, setRange] = React.useState<[number, number] | null>(\n    defaultRange,\n  );\n  const [hover, setHover] = React.useState<number | null>(null);\n\n  const count = data.length;\n  const values = data.map((d) => d.value);\n  const max = Math.max(1, ...values) * 1.08;\n  const span = width - LEFT - RIGHT;\n  const cell = span / Math.max(1, count);\n  const x = (i: number) => LEFT + (i + 0.5) * cell;\n  const y = (v: number) => height - 2 - (v / max) * (height - TOP - 2);\n  const split = Math.max(1, count - 1 - Math.max(0, forecast));\n  const points = data.map((d, i) => [x(i), y(d.value)] as [number, number]);\n  const actual = curve(points.slice(0, split + 1));\n  const ahead = curve(points.slice(split));\n  const level = levels(values);\n  const every = Math.max(1, Math.ceil(count / Math.floor(width / 96)));\n\n  const lo = range ? Math.min(range[0], range[1]) : 0;\n  const hi = range ? Math.max(range[0], range[1]) : count - 1;\n  const picked = data.slice(lo, hi + 1);\n  const total = picked.reduce((n, d) => n + d.value, 0);\n  const first = picked[0]?.value ?? 0;\n  const last = picked[picked.length - 1]?.value ?? 0;\n  const change = first ? ((last - first) / first) * 100 : 0;\n  const point = hover === null ? null : data[hover];\n\n  // Both marching lines run as compositor-friendly animations, with nothing re-rendering.\n  React.useEffect(() => {\n    if (reduce) return;\n    const runs = [antsRef.current, trailRef.current].map((el) =>\n      el?.animate([{ strokeDashoffset: 0 }, { strokeDashoffset: -12 }], {\n        duration: 600,\n        iterations: Infinity,\n      }),\n    );\n    return () => runs.forEach((run) => run?.cancel());\n  }, [reduce]);\n\n  const indexAt = (clientX: number, el: Element) => {\n    const r = el.getBoundingClientRect();\n    const i = Math.floor((clientX - r.left - LEFT) / cell);\n    return Math.max(0, Math.min(count - 1, i));\n  };\n  const commit = (next: [number, number] | null) => {\n    setRange(next);\n    if (!onRangeChange) return;\n    if (!next) onRangeChange([]);\n    else {\n      const [a, b] = [Math.min(...next), Math.max(...next)];\n      onRangeChange(data.slice(a, b + 1));\n    }\n  };\n\n  return (\n    <section\n      className={`w-full rounded-2xl p-5 sm:p-6 ${className ?? \"\"}`}\n      style={{\n        background: pal.card,\n        boxShadow: `inset 0 0 0 1px ${pal.border}`,\n        color: pal.text,\n        fontFamily: CARD_FONT,\n        ...style,\n      }}\n      {...props}\n    >\n      <div className=\"flex flex-wrap items-start justify-between gap-x-8 gap-y-3\">\n        <div>\n          <h3 className=\"m-0 text-[17px] leading-[1.33] font-[590] tracking-[-0.012em]\">\n            {title}\n          </h3>\n          <p\n            className=\"m-0 mt-0.5 text-[13px] tracking-[-0.011em]\"\n            style={{ color: pal.sub }}\n          >\n            {subtitle}\n          </p>\n        </div>\n        <div className=\"flex gap-7\">\n          <Stat value={formatValue(total)} label=\"Total\" pal={pal} />\n          <Stat\n            value={formatValue(total / Math.max(1, picked.length))}\n            label=\"Daily average\"\n            pal={pal}\n          />\n          <Stat\n            value={`${change >= 0 ? \"+\" : \"−\"}${Math.abs(change).toFixed(1)}%`}\n            label=\"Change\"\n            pal={pal}\n          />\n        </div>\n      </div>\n\n      {count < 2 ? (\n        <p className=\"py-16 text-center text-sm\" style={{ color: pal.sub }}>\n          No data available.\n        </p>\n      ) : (\n        <div\n          ref={boxRef}\n          className=\"relative mt-5 cursor-crosshair touch-pan-y rounded-lg outline-none select-none focus-visible:ring-2\"\n          tabIndex={0}\n          role=\"group\"\n          aria-label={`${title}. Use the arrow keys to move the range, with Shift to resize it, and Escape to clear it.`}\n          onPointerDown={(e) => {\n            e.currentTarget.setPointerCapture(e.pointerId);\n            const i = indexAt(e.clientX, e.currentTarget);\n            anchor.current = i;\n            commit([i, i]);\n          }}\n          onPointerMove={(e) => {\n            const i = indexAt(e.clientX, e.currentTarget);\n            if (anchor.current === null) setHover(i);\n            else {\n              setHover(null);\n              commit([anchor.current, i]);\n            }\n          }}\n          onPointerUp={() => {\n            // A plain click clears the range rather than leaving one day picked.\n            if (range && range[0] === range[1]) commit(null);\n            anchor.current = null;\n          }}\n          onPointerCancel={() => {\n            anchor.current = null;\n          }}\n          onPointerLeave={() => setHover(null)}\n          onKeyDown={(e) => {\n            if (e.key === \"Escape\") {\n              commit(null);\n              return;\n            }\n            if (e.key !== \"ArrowLeft\" && e.key !== \"ArrowRight\") return;\n            e.preventDefault();\n            const dir = e.key === \"ArrowRight\" ? 1 : -1;\n            const a = range ? lo : Math.floor(count / 3);\n            const b = range ? hi : Math.floor(count / 2);\n            if (e.shiftKey) {\n              commit([a, Math.max(a + 1, Math.min(count - 1, b + dir))]);\n            } else if (a + dir >= 0 && b + dir < count) {\n              commit([a + dir, b + dir]);\n            }\n          }}\n        >\n          <svg\n            viewBox={`0 0 ${width} ${height}`}\n            className=\"block w-full\"\n            style={{ height }}\n            role=\"img\"\n            aria-label={`${shortDate(data[lo].date)} to ${shortDate(data[hi].date)}: ${formatValue(total)} in total`}\n          >\n            {[0, 0.5, 1].map((t) => (\n              <g key={t}>\n                <line\n                  x1={LEFT}\n                  x2={width - RIGHT}\n                  y1={y(max * t)}\n                  y2={y(max * t)}\n                  stroke={pal.grid}\n                />\n                <text\n                  x={LEFT - 8}\n                  y={y(max * t) + 4}\n                  textAnchor=\"end\"\n                  fontSize=\"11\"\n                  fill={pal.faint}\n                >\n                  {formatValue(max * t)}\n                </text>\n              </g>\n            ))}\n            {/* Always mounted, so the marching animation keeps its element. */}\n            <rect\n              x={lo * cell + LEFT}\n              y={TOP}\n              width={(hi - lo + 1) * cell}\n              height={height - TOP}\n              fill={accent}\n              fillOpacity={range ? 0.07 : 0}\n            />\n            <path\n              d={actual}\n              fill=\"none\"\n              stroke={accent}\n              strokeWidth=\"1.75\"\n              strokeLinecap=\"round\"\n            />\n            <path\n              ref={trailRef}\n              d={ahead}\n              fill=\"none\"\n              stroke={accent}\n              strokeWidth=\"1.75\"\n              strokeDasharray=\"6 6\"\n            />\n            <line\n              x1={x(split)}\n              x2={x(split)}\n              y1={TOP}\n              y2={height}\n              stroke={pal.border}\n            />\n            <text x={x(split) + 6} y={TOP + 10} fontSize=\"11\" fill={pal.faint}>\n              Forecast\n            </text>\n            <rect\n              ref={antsRef}\n              x={lo * cell + LEFT + 0.5}\n              y={TOP + 0.5}\n              width={Math.max(0, (hi - lo + 1) * cell - 1)}\n              height={height - TOP - 1}\n              rx=\"4\"\n              fill=\"none\"\n              stroke={pal.text}\n              strokeWidth=\"1\"\n              strokeDasharray=\"6 6\"\n              opacity={range ? 0.9 : 0}\n            />\n            {point && hover !== null && (\n              <circle\n                cx={x(hover)}\n                cy={y(point.value)}\n                r=\"3.5\"\n                fill={accent}\n                stroke={pal.card}\n                strokeWidth=\"2\"\n              />\n            )}\n          </svg>\n\n          <div\n            aria-hidden=\"true\"\n            className=\"mt-2 flex gap-[3px]\"\n            style={{ marginLeft: LEFT, marginRight: RIGHT }}\n          >\n            {data.map((d, i) => (\n              <span\n                key={d.date}\n                className=\"h-3.5 min-w-0 flex-1 rounded-[3px] transition-opacity duration-150\"\n                style={{\n                  background: mix(pal.empty, accent, LEVEL_MIX[level[i]]),\n                  opacity: !range || (i >= lo && i <= hi) ? 1 : 0.3,\n                  boxShadow: hover === i ? `0 0 0 1px ${pal.ring}` : undefined,\n                }}\n              />\n            ))}\n          </div>\n          <div\n            aria-hidden=\"true\"\n            className=\"relative mt-1.5 h-4 text-[11px]\"\n            style={{ color: pal.faint, marginLeft: LEFT, marginRight: RIGHT }}\n          >\n            {data\n              .map((d) => d.date)\n              .map(\n                (date, i) =>\n                  i % every === 0 && (\n                    <span\n                      key={date}\n                      className=\"absolute top-0 whitespace-nowrap\"\n                      style={{ left: `${(i / count) * 100}%` }}\n                    >\n                      {shortDate(date)}\n                    </span>\n                  ),\n              )}\n          </div>\n\n          {point && hover !== null && (\n            <Tip x={x(hover)} y={y(point.value)} width={width} pal={pal}>\n              <span className=\"font-[510]\" style={{ color: pal.text }}>\n                {formatValue(point.value)}\n              </span>{\" \"}\n              on {longDate(point.date)}\n              {hover > split ? \", forecast\" : \"\"}\n            </Tip>\n          )}\n        </div>\n      )}\n\n      <div\n        className=\"mt-3 flex flex-wrap items-center justify-between gap-2 text-[12px]\"\n        style={{ color: pal.sub }}\n      >\n        <span className=\"flex items-center gap-2\">\n          {count > 0 &&\n            `${shortDate(data[lo].date)} – ${shortDate(data[hi].date)}, ${picked.length} days`}\n          {/* Hidden rather than removed, so the row keeps its height. */}\n          <button\n            type=\"button\"\n            onClick={() => commit(null)}\n            tabIndex={range ? 0 : -1}\n            className={`h-6 cursor-pointer rounded-full px-2.5 text-[12px] font-[510] ${range ? \"\" : \"invisible\"}`}\n            style={{ background: pal.chip, color: pal.text }}\n          >\n            Clear\n          </button>\n        </span>\n        <Legend pal={pal} accent={accent} />\n      </div>\n    </section>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}