{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"bar-chart","type":"registry:block","title":"Bar chart","description":"A grouped monthly bar chart (this year vs last year) with toggleable legend series, a hovered-month tooltip, and a lens glint on the active bar.","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"registry/prequel/bar-chart/bar-chart.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n  AnimatePresence,\n  MotionConfig,\n  motion,\n  useInView,\n  useReducedMotion,\n} from \"motion/react\";\nimport { cn } from \"@/lib/utils\";\n\nconst EASE: [number, number, number, number] = [0.22, 1, 0.36, 1];\n\nexport type BarChartSeries = {\n  key: string;\n  label: string;\n  /** Chart colour token 1–5. Defaults to the series index + 1. */\n  tone?: number;\n  /** One value per month, aligned with `months`. */\n  values: number[];\n};\n\nexport type BarChartProps = {\n  className?: string;\n  title?: string;\n  description?: string;\n  months?: string[];\n  series?: BarChartSeries[];\n  valuePrefix?: string;\n  formatValue?: (value: number) => string;\n};\n\n/* ------------------------------------------------------------------ */\n/* deterministic demo data                                             */\n/* ------------------------------------------------------------------ */\n\nconst DEFAULT_MONTHS: string[] = [\n  \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\",\n  \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\",\n];\n\nconst DEFAULT_SERIES: BarChartSeries[] = [\n  {\n    key: \"this-year\",\n    label: \"This year\",\n    tone: 1,\n    values: [42000, 51000, 48000, 60000, 66000, 72000, 69000, 78000, 84000, 79000, 88000, 96000],\n  },\n  {\n    key: \"last-year\",\n    label: \"Last year\",\n    tone: 3,\n    values: [34000, 40000, 44000, 46000, 50000, 54000, 58000, 60000, 63000, 67000, 70000, 74000],\n  },\n];\n\n/* ------------------------------------------------------------------ */\n/* helpers                                                             */\n/* ------------------------------------------------------------------ */\n\nfunction clamp(v: number, min: number, max: number) {\n  return Math.min(max, Math.max(min, v));\n}\n\nfunction niceMax(value: number) {\n  const padded = value * 1.08;\n  const magnitude = Math.pow(10, Math.floor(Math.log10(padded)));\n  const normalized = padded / magnitude;\n  const steps = [1, 1.2, 1.6, 2, 2.4, 3, 4, 5, 6, 8, 10];\n  const factor = steps.find((k) => k >= normalized) ?? 10;\n  return factor * magnitude;\n}\n\nfunction trimZero(n: number) {\n  const s = n.toFixed(1);\n  return s.endsWith(\".0\") ? s.slice(0, -2) : s;\n}\n\nfunction formatCompact(value: number, prefix: string) {\n  const abs = Math.abs(value);\n  if (abs >= 1_000_000) return `${prefix}${trimZero(abs / 1_000_000)}M`;\n  if (abs >= 1000) return `${prefix}${trimZero(abs / 1000)}k`;\n  return `${prefix}${abs}`;\n}\n\ntype Geometry = {\n  W: number;\n  H: number;\n  L: number;\n  R: number;\n  T: number;\n  B: number;\n  n: number;\n  plotW: number;\n  plotH: number;\n  baseline: number;\n  slot: number;\n  barW: number;\n  yTicks: Array<{ value: number; y: number }>;\n  xTicks: Array<{ index: number; x: number; label: string }>;\n  xForBar: (monthIndex: number, seriesIndex: number) => number;\n  yFor: (value: number) => number;\n};\n\nfunction buildGeometry(\n  width: number,\n  height: number,\n  n: number,\n  s: number,\n  max: number,\n  months: string[]\n): Geometry {\n  const W = width;\n  const H = height;\n  const L = 48;\n  const R = 8;\n  const T = 14;\n  const B = 28;\n  const plotW = W - L - R;\n  const plotH = H - T - B;\n  const baseline = T + plotH;\n  const slot = plotW / n;\n  const gap = 3;\n  const barW = clamp(slot * 0.3, 2, 22);\n  const groupW = s * barW + (s - 1) * gap;\n\n  const xForBar = (monthIndex: number, seriesIndex: number) => {\n    const center = L + slot * (monthIndex + 0.5);\n    return center - groupW / 2 + seriesIndex * (barW + gap);\n  };\n\n  const yFor = (value: number) => T + plotH * (1 - value / max);\n\n  const yTicks = [0, 1, 2, 3, 4].map((k) => ({\n    value: (max * k) / 4,\n    y: T + plotH * (1 - k / 4),\n  }));\n\n  const step = Math.max(1, Math.ceil(n / Math.max(2, Math.floor(plotW / 44))));\n  const xTicks: Array<{ index: number; x: number; label: string }> = [];\n  for (let i = 0; i < n; i += step) {\n    xTicks.push({ index: i, x: L + slot * (i + 0.5), label: months[i] });\n  }\n\n  return {\n    W, H, L, R, T, B, n, plotW, plotH, baseline, slot, barW,\n    yTicks, xTicks, xForBar, yFor,\n  };\n}\n\n/* ------------------------------------------------------------------ */\n/* component                                                           */\n/* ------------------------------------------------------------------ */\n\nexport function BarChart({\n  className,\n  title = \"Revenue\",\n  description = \"This year vs last year, by month.\",\n  months = DEFAULT_MONTHS,\n  series = DEFAULT_SERIES,\n  valuePrefix = \"$\",\n  formatValue,\n}: BarChartProps) {\n  const cardRef = useRef<HTMLDivElement>(null);\n  const chartRef = useRef<HTMLDivElement>(null);\n\n  const inView = useInView(cardRef, { once: true, margin: \"-10% 0px\" });\n  const reduce = Boolean(useReducedMotion());\n  const show = inView;\n\n  const [size, setSize] = useState<{ width: number; height: number } | null>(\n    null\n  );\n  const [hovered, setHovered] = useState<number | null>(null);\n  const [entered, setEntered] = useState(false);\n  const [visible, setVisible] = useState<Record<string, boolean>>(() =>\n    Object.fromEntries(series.map((s) => [s.key, true]))\n  );\n\n  const format =\n    formatValue ??\n    ((n: number) => valuePrefix + Math.round(n).toLocaleString(\"en-US\"));\n\n  /* measure the chart container so the SVG matches its pixel size */\n  useEffect(() => {\n    const el = chartRef.current;\n    if (!el) return;\n    const update = () => {\n      const rect = el.getBoundingClientRect();\n      setSize((prev) =>\n        prev && prev.width === rect.width && prev.height === rect.height\n          ? prev\n          : { width: rect.width, height: rect.height }\n      );\n    };\n    update();\n    const observer = new ResizeObserver(update);\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, []);\n\n  /* once the staggered entrance has played, toggles animate without the delay */\n  useEffect(() => {\n    if (!show || reduce) {\n      setEntered(true);\n      return;\n    }\n    const t = window.setTimeout(() => setEntered(true), 1300);\n    return () => window.clearTimeout(t);\n  }, [show, reduce]);\n\n  const rawMax = useMemo(\n    () => Math.max(0, ...series.flatMap((s) => s.values)),\n    [series]\n  );\n  const max = rawMax > 0 ? niceMax(rawMax) : 1;\n\n  const geometry = useMemo<Geometry | null>(() => {\n    if (!size) return null;\n    return buildGeometry(\n      size.width,\n      size.height,\n      months.length,\n      series.length,\n      max,\n      months\n    );\n  }, [size, months, series.length, max]);\n\n  const resolved = series.map((s, i) => ({\n    ...s,\n    color: `var(--chart-${clamp(s.tone ?? i + 1, 1, 5)})`,\n  }));\n\n  const toggleSeries = (key: string) => {\n    setVisible((prev) => {\n      const next = { ...prev, [key]: !prev[key] };\n      const anyVisible = series.some((s) => next[s.key]);\n      return anyVisible ? next : prev;\n    });\n  };\n\n  /* data + geometry for the hovered month (used by band, lens and tooltip) */\n  const hov = hovered;\n  const hoverMonth = hov != null ? months[hov] : \"\";\n  const hoverRows =\n    hov != null\n      ? resolved\n          .filter((s) => visible[s.key] ?? true)\n          .map((s) => ({\n            key: s.key,\n            label: s.label,\n            color: s.color,\n            value: s.values[hov],\n          }))\n      : [];\n\n  let lens: { cx: number; cy: number; color: string } | null = null;\n  if (geometry && hov != null) {\n    const idx = resolved.findIndex((s) => visible[s.key] ?? true);\n    if (idx !== -1) {\n      const s = resolved[idx];\n      lens = {\n        cx: geometry.xForBar(hov, idx) + geometry.barW / 2,\n        cy: geometry.yFor(s.values[hov] ?? 0),\n        color: s.color,\n      };\n    }\n  }\n\n  let tipLeft = 4;\n  let tipTop = 8;\n  if (geometry && hov != null) {\n    const center = geometry.L + geometry.slot * (hov + 0.5);\n    tipLeft = clamp(center - 80, 4, geometry.W - 164);\n\n    const tops = hoverRows.map((r) => geometry.yFor(r.value));\n    const minTop = tops.length ? Math.min(...tops) : geometry.T;\n    tipTop = clamp(minTop - 72, 4, geometry.H - 72);\n  }\n\n  const ariaLabel = `${title}. Monthly bar chart comparing ${resolved\n    .map((s) => s.label)\n    .join(\" and \")}. ${resolved\n    .map(\n      (s) =>\n        `${s.label}: ${s.values\n          .map((v, i) => `${months[i]} ${format(v)}`)\n          .join(\", \")}`\n    )\n    .join(\". \")}.`;\n\n  return (\n    <MotionConfig reducedMotion=\"user\">\n      <motion.div\n        ref={cardRef}\n        initial={{ opacity: 0, y: 20 }}\n        animate={show ? { opacity: 1, y: 0 } : { opacity: 0, y: 20 }}\n        transition={{ duration: 0.6, ease: EASE }}\n        className={cn(\n          \"rounded-xl border border-border bg-card text-card-foreground shadow-sm\",\n          className\n        )}\n      >\n        <div className=\"p-5 sm:p-6\">\n          <div className=\"flex flex-wrap items-start justify-between gap-3\">\n            <div>\n              <h2 className=\"text-[15px] font-semibold tracking-tight\">\n                {title}\n              </h2>\n              {description ? (\n                <p className=\"mt-0.5 text-[13px] text-muted-foreground\">\n                  {description}\n                </p>\n              ) : null}\n            </div>\n\n            <div\n              role=\"group\"\n              aria-label=\"Toggle series\"\n              className=\"flex flex-wrap items-center gap-1.5\"\n            >\n              {resolved.map((s) => {\n                const active = visible[s.key] ?? true;\n                return (\n                  <button\n                    key={s.key}\n                    type=\"button\"\n                    aria-pressed={active}\n                    onClick={() => toggleSeries(s.key)}\n                    className={cn(\n                      \"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-[12.5px] font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\",\n                      active\n                        ? \"text-foreground hover:bg-muted\"\n                        : \"text-muted-foreground hover:bg-muted\"\n                    )}\n                  >\n                    <span\n                      aria-hidden=\"true\"\n                      className=\"h-2.5 w-2.5 rounded-full transition-opacity\"\n                      style={{\n                        background: active ? s.color : \"var(--muted-foreground)\",\n                        opacity: active ? 1 : 0.35,\n                      }}\n                    />\n                    {s.label}\n                  </button>\n                );\n              })}\n            </div>\n          </div>\n\n          <div ref={chartRef} className=\"relative mt-4 h-72 w-full sm:h-80\">\n            {geometry && (\n              <svg\n                viewBox={`0 0 ${geometry.W} ${geometry.H}`}\n                role=\"img\"\n                aria-label={ariaLabel}\n                tabIndex={0}\n                onKeyDown={(e) => {\n                  if (!geometry) return;\n                  if (e.key === \"ArrowLeft\" || e.key === \"ArrowRight\") {\n                    e.preventDefault();\n                    const dir = e.key === \"ArrowRight\" ? 1 : -1;\n                    setHovered((h) =>\n                      h == null\n                        ? dir === 1\n                          ? 0\n                          : geometry.n - 1\n                        : clamp(h + dir, 0, geometry.n - 1)\n                    );\n                  } else if (e.key === \"Home\") {\n                    e.preventDefault();\n                    setHovered(0);\n                  } else if (e.key === \"End\") {\n                    e.preventDefault();\n                    setHovered(geometry.n - 1);\n                  }\n                }}\n                onFocus={() => {\n                  if (geometry) {\n                    setHovered((h) => h ?? Math.floor(geometry.n / 2));\n                  }\n                }}\n                onBlur={() => setHovered(null)}\n                className=\"block h-full w-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n              >\n                {geometry.yTicks.map((tick, i) => (\n                  <line\n                    key={`gl-${i}`}\n                    x1={geometry.L}\n                    x2={geometry.W - geometry.R}\n                    y1={tick.y}\n                    y2={tick.y}\n                    stroke=\"var(--border)\"\n                    strokeDasharray=\"3 3\"\n                  />\n                ))}\n\n                <motion.g\n                  initial={{ opacity: 0 }}\n                  animate={{ opacity: show ? 1 : 0 }}\n                  transition={{ duration: 0.4, delay: 0.15 }}\n                >\n                  {geometry.yTicks.map((tick, i) => (\n                    <text\n                      key={`y-${i}`}\n                      x={geometry.L - 10}\n                      y={tick.y + 4}\n                      textAnchor=\"end\"\n                      className=\"fill-muted-foreground text-[11px]\"\n                    >\n                      {formatCompact(tick.value, valuePrefix)}\n                    </text>\n                  ))}\n                </motion.g>\n\n                <motion.g\n                  initial={{ opacity: 0 }}\n                  animate={{ opacity: show ? 1 : 0 }}\n                  transition={{ duration: 0.4, delay: 0.15 }}\n                >\n                  {geometry.xTicks.map((tick) => (\n                    <text\n                      key={`x-${tick.index}`}\n                      x={tick.x}\n                      y={geometry.H - 8}\n                      textAnchor=\"middle\"\n                      className=\"fill-muted-foreground text-[11px]\"\n                    >\n                      {tick.label}\n                    </text>\n                  ))}\n                </motion.g>\n\n                {resolved.map((ser, si) => {\n                  const isVisible = visible[ser.key] ?? true;\n                  return (\n                    <g key={ser.key}>\n                      {ser.values.map((v, mi) => {\n                        const h = (v / max) * geometry.plotH;\n                        const yTop = geometry.baseline - h;\n                        const delay = reduce\n                          ? 0\n                          : entered\n                            ? 0\n                            : mi * 0.04 + si * 0.07;\n                        const duration = reduce ? 0 : entered ? 0.4 : 0.72;\n                        return (\n                          <motion.rect\n                            key={mi}\n                            x={geometry.xForBar(mi, si)}\n                            width={geometry.barW}\n                            rx={Math.min(2, geometry.barW / 2)}\n                            fill={ser.color}\n                            initial={false}\n                            animate={{\n                              height: show && isVisible ? h : 0,\n                              y: show && isVisible ? yTop : geometry.baseline,\n                              opacity: show && isVisible ? 1 : 0,\n                            }}\n                            transition={{ duration, delay, ease: EASE }}\n                          />\n                        );\n                      })}\n                    </g>\n                  );\n                })}\n\n                {hov != null && (\n                  <motion.rect\n                    initial={{ opacity: 0 }}\n                    animate={{ opacity: 0.06 }}\n                    transition={{ duration: 0.2 }}\n                    x={geometry.L + geometry.slot * hov}\n                    y={geometry.T}\n                    width={geometry.slot}\n                    height={geometry.plotH}\n                    fill=\"var(--muted-foreground)\"\n                  />\n                )}\n\n                {lens && hov != null && (\n                  <motion.g\n                    initial={{ opacity: 0 }}\n                    animate={{ opacity: 1 }}\n                    transition={{ duration: 0.2 }}\n                  >\n                    <circle\n                      cx={lens.cx}\n                      cy={lens.cy}\n                      r={5}\n                      fill=\"none\"\n                      stroke={lens.color}\n                      strokeWidth={1}\n                      opacity={0.4}\n                    />\n                    <circle\n                      cx={lens.cx}\n                      cy={lens.cy}\n                      r={2.25}\n                      fill=\"var(--card)\"\n                      stroke={lens.color}\n                      strokeWidth={1.5}\n                    />\n                    <motion.g\n                      initial={{ rotate: -120 }}\n                      animate={{ rotate: 40 }}\n                      transition={{\n                        type: \"spring\",\n                        stiffness: 140,\n                        damping: 16,\n                        delay: 0.05,\n                      }}\n                      style={{\n                        transformOrigin: `${lens.cx}px ${lens.cy}px`,\n                      }}\n                    >\n                      <circle\n                        cx={lens.cx}\n                        cy={lens.cy - 5}\n                        r={1.5}\n                        fill={lens.color}\n                      />\n                    </motion.g>\n                  </motion.g>\n                )}\n\n                <rect\n                  x={geometry.L}\n                  y={0}\n                  width={geometry.plotW}\n                  height={geometry.H}\n                  fill=\"transparent\"\n                  style={{ cursor: \"crosshair\" }}\n                  onPointerMove={(e) => {\n                    const el = chartRef.current;\n                    if (!el || !geometry) return;\n                    const px = e.clientX - el.getBoundingClientRect().left;\n                    const index = Math.floor(\n                      ((px - geometry.L) / geometry.plotW) * geometry.n\n                    );\n                    setHovered(clamp(index, 0, geometry.n - 1));\n                  }}\n                  onPointerLeave={() => setHovered(null)}\n                />\n              </svg>\n            )}\n\n            <AnimatePresence>\n              {hov != null && (\n                <motion.div\n                  key=\"tooltip\"\n                  initial={{ opacity: 0, scale: 0.96, y: 4 }}\n                  animate={{ opacity: 1, scale: 1, y: 0 }}\n                  exit={{ opacity: 0, scale: 0.96, y: 4 }}\n                  transition={{ duration: 0.16, ease: \"easeOut\" }}\n                  className=\"pointer-events-none absolute z-10 min-w-[150px] rounded-lg border border-border bg-card px-3 py-2 shadow-lg\"\n                  style={{ left: tipLeft, top: tipTop }}\n                >\n                  <div className=\"text-[12px] text-muted-foreground\">\n                    {hoverMonth}\n                  </div>\n                  {hoverRows.map((r) => (\n                    <div key={r.key} className=\"mt-1.5 flex items-center gap-2\">\n                      <span\n                        className=\"h-2 w-2 rounded-full\"\n                        style={{ background: r.color }}\n                      />\n                      <span className=\"text-[12.5px] text-muted-foreground\">\n                        {r.label}\n                      </span>\n                      <span className=\"ml-auto text-[13px] font-medium tabular-nums\">\n                        {format(r.value)}\n                      </span>\n                    </div>\n                  ))}\n                </motion.div>\n              )}\n            </AnimatePresence>\n          </div>\n        </div>\n      </motion.div>\n    </MotionConfig>\n  );\n}\n\nexport default BarChart;\n"}]}