{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"bar-chart","type":"registry:component","title":"Bar chart","description":"Grows its bars from the baseline and springs them between two weeks.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/bar-chart.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useRef, useState } from \"react\";\nimport {\n  animate,\n  motion,\n  useInView,\n  useMotionValue,\n  useTransform,\n  type AnimationPlaybackControls,\n  type MotionValue,\n} from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\ntype Datum = { label: string; value: number };\n\nconst PLOT_H = 190;\n// The 6px rounded cap rides on top of a square body. Scaling one rounded\n// rect would squash its corners, so only the body scales.\nconst CAP = 6;\n// Mount: a quick cascade reads as one gesture across the week.\nconst STAGGER = 0.04;\n// No bounce: an overshooting bar briefly claims a value that isn't true.\nconst GROW = { type: \"spring\", visualDuration: 0.45, bounce: 0 } as const;\nconst EASE = \"ease-[cubic-bezier(0.23,1,0.32,1)]\";\n\nexport function BarChart({\n  data,\n  max,\n  ticks,\n  unit,\n  suffix,\n  label,\n  className,\n}: {\n  data: Datum[];\n  max: number;\n  ticks: number[];\n  /** Spoken after each value, e.g. \"hours\". */\n  unit: string;\n  /** Shown after each value in the tooltip, e.g. \"h\". */\n  suffix: string;\n  label: string;\n  className?: string;\n}) {\n  const plotRef = useRef<HTMLDivElement>(null);\n  const barRefs = useRef<(HTMLDivElement | null)[]>([]);\n  const inView = useInView(plotRef, { once: true });\n  const [active, setActive] = useState<number | null>(null);\n  // Roving tabindex: one stop for the whole chart, arrows move within it.\n  const [focusIndex, setFocusIndex] = useState(0);\n\n  const move = (i: number) => {\n    const next = Math.min(Math.max(i, 0), data.length - 1);\n    setFocusIndex(next);\n    barRefs.current[next]?.focus();\n  };\n\n  return (\n    <div className={cn(\"flex w-[520px] max-w-full\", className)}>\n      {/* Tick labels sit in their own gutter so gridlines can span the plot. */}\n      <div\n        aria-hidden\n        className=\"relative mr-3 w-6 shrink-0 text-right text-xs text-muted-foreground tabular-nums\"\n        style={{ height: PLOT_H }}\n      >\n        {ticks.map((t) => (\n          <span\n            key={t}\n            className=\"absolute right-0 -translate-y-1/2 leading-none\"\n            style={{ top: PLOT_H - (t / max) * PLOT_H }}\n          >\n            {t}\n          </span>\n        ))}\n      </div>\n\n      <div className=\"flex-1\">\n        <div\n          ref={plotRef}\n          role=\"group\"\n          aria-label={label}\n          className=\"relative flex\"\n          style={{ height: PLOT_H }}\n          onPointerLeave={(e) => {\n            if (e.pointerType !== \"touch\") setActive(null);\n          }}\n        >\n          {ticks.map((t) => (\n            <div\n              key={t}\n              aria-hidden\n              className=\"absolute inset-x-0 h-px bg-border\"\n              style={{ top: PLOT_H - (t / max) * PLOT_H }}\n            />\n          ))}\n          {data.map((d, i) => (\n            <Bar\n              key={d.label}\n              ref={(el) => {\n                barRefs.current[i] = el;\n              }}\n              datum={d}\n              fraction={d.value / max}\n              index={i}\n              started={inView}\n              unit={unit}\n              suffix={suffix}\n              active={active === i}\n              dimmed={active !== null && active !== i}\n              tabIndex={i === focusIndex ? 0 : -1}\n              onActivate={() => setActive(i)}\n              onFocus={() => {\n                setFocusIndex(i);\n                setActive(i);\n              }}\n              onBlur={(e) => {\n                if (!plotRef.current?.contains(e.relatedTarget as Node)) setActive(null);\n              }}\n              onKeyDown={(e) => {\n                const next = {\n                  ArrowLeft: i - 1,\n                  ArrowRight: i + 1,\n                  Home: 0,\n                  End: data.length - 1,\n                }[e.key];\n                if (next === undefined) return;\n                e.preventDefault();\n                move(next);\n              }}\n            />\n          ))}\n        </div>\n        <div aria-hidden className=\"mt-3 flex\">\n          {data.map((d, i) => (\n            <span\n              key={d.label}\n              className={cn(\n                \"flex-1 text-center text-sm transition-colors duration-150 ease-out\",\n                active === i ? \"text-foreground\" : \"text-muted-foreground\",\n              )}\n            >\n              {d.label}\n            </span>\n          ))}\n        </div>\n      </div>\n    </div>\n  );\n}\n\nfunction Bar({\n  ref,\n  datum,\n  fraction,\n  index,\n  started,\n  unit,\n  suffix,\n  active,\n  dimmed,\n  tabIndex,\n  onActivate,\n  onFocus,\n  onBlur,\n  onKeyDown,\n}: {\n  ref: (el: HTMLDivElement | null) => void;\n  datum: Datum;\n  fraction: number;\n  index: number;\n  started: boolean;\n  unit: string;\n  suffix: string;\n  active: boolean;\n  dimmed: boolean;\n  tabIndex: number;\n  onActivate: () => void;\n  onFocus: () => void;\n  onBlur: (e: React.FocusEvent) => void;\n  onKeyDown: (e: React.KeyboardEvent) => void;\n}) {\n  const reduceMotion = useReducedMotion();\n  const height = useMotionValue(0);\n  const grown = useRef(false);\n  const controls = useRef<AnimationPlaybackControls>(undefined);\n\n  useEffect(() => {\n    if (!started) return;\n    const target = fraction * PLOT_H;\n    if (reduceMotion) {\n      height.jump(target);\n    } else {\n      // Only the first growth staggers; a dataset switch moves every bar\n      // at once so the comparison lands together. animate() retargets from\n      // the current value and velocity, so rapid toggles stay smooth.\n      controls.current = animate(height, target, {\n        ...GROW,\n        delay: grown.current ? 0 : index * STAGGER,\n      });\n    }\n    grown.current = true;\n  }, [started, fraction, index, reduceMotion, height]);\n\n  useEffect(() => () => controls.current?.stop(), []);\n\n  return (\n    <div\n      ref={ref}\n      role=\"img\"\n      tabIndex={tabIndex}\n      aria-label={`${datum.label}, ${datum.value} ${unit}`}\n      // The whole column is the hit target, not just the 40px bar.\n      className=\"relative flex-1 rounded-sm outline-hidden focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-foreground\"\n      onPointerEnter={(e) => {\n        if (e.pointerType !== \"touch\") onActivate();\n      }}\n      onPointerDown={(e) => {\n        if (e.pointerType === \"touch\") onActivate();\n      }}\n      onFocus={onFocus}\n      onBlur={onBlur}\n      onKeyDown={onKeyDown}\n    >\n      <BarShape height={height} dimmed={dimmed} />\n      <Tooltip height={height} visible={active}>\n        <span className=\"font-semibold tabular-nums\">{datum.value}</span> {suffix}\n      </Tooltip>\n    </div>\n  );\n}\n\nfunction BarShape({ height, dimmed }: { height: MotionValue<number>; dimmed: boolean }) {\n  const body = useTransform(height, (h) => `scaleY(${Math.max(h - CAP, 0) / (PLOT_H - CAP)})`);\n  // Overlaps the body by 1px so no hairline seam shows at fractional heights.\n  const cap = useTransform(height, (h) => `translateY(${-Math.max(h - CAP - 1, 0)}px)`);\n  // Keeps an empty bar from showing a stub before it grows.\n  const capOpacity = useTransform(height, (h) => (h < 0.5 ? 0 : 1));\n\n  return (\n    <div\n      aria-hidden\n      className={cn(\n        \"absolute bottom-0 left-1/2 w-10 -translate-x-1/2 transition-opacity duration-150 ease-out\",\n        dimmed ? \"opacity-40\" : \"opacity-100\",\n      )}\n      style={{ height: PLOT_H }}\n    >\n      <motion.div\n        className=\"absolute inset-x-0 bottom-0 origin-bottom bg-foreground\"\n        style={{ height: PLOT_H - CAP, transform: body }}\n      />\n      <motion.div\n        className=\"absolute inset-x-0 bottom-0 rounded-t-[6px] bg-foreground\"\n        style={{ height: CAP + 1, transform: cap, opacity: capOpacity }}\n      />\n    </div>\n  );\n}\n\nfunction Tooltip({\n  height,\n  visible,\n  children,\n}: {\n  height: MotionValue<number>;\n  visible: boolean;\n  children: React.ReactNode;\n}) {\n  // Rides 8px above the bar's top, following it while the bar animates.\n  const transform = useTransform(height, (h) => `translate(-50%, ${-h - 8}px)`);\n\n  return (\n    <div aria-hidden className=\"pointer-events-none absolute bottom-0 left-1/2\">\n      <motion.div style={{ transform }}>\n        <div\n          className={cn(\n            \"rounded-full bg-foreground px-3 py-1.5 text-sm whitespace-nowrap text-background transition-[opacity,translate] ease-out motion-reduce:transition-opacity\",\n            visible\n              ? \"translate-y-0 opacity-100 duration-100\"\n              : \"translate-y-1 opacity-0 duration-75 motion-reduce:translate-y-0\",\n          )}\n        >\n          {children}\n        </div>\n      </motion.div>\n    </div>\n  );\n}\n\nconst DAYS = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"];\nconst DATASETS = {\n  \"This week\": [6.5, 7.2, 5.1, 8.4, 6, 2.3, 1.2],\n  \"Last week\": [5.2, 6.1, 7.4, 4.8, 5.5, 3.1, 0.8],\n};\ntype Week = keyof typeof DATASETS;\nconst WEEKS = Object.keys(DATASETS) as Week[];\n\nexport default function BarChartDemo() {\n  const [week, setWeek] = useState<Week>(\"This week\");\n  const values = DATASETS[week];\n  const data = DAYS.map((label, i) => ({ label, value: values[i] }));\n  const total = values.reduce((a, b) => a + b, 0);\n\n  return (\n    <div className=\"flex w-[520px] max-w-full flex-col gap-6\">\n      <div className=\"flex items-end justify-between\">\n        <div>\n          <p className=\"text-[15px] text-muted-foreground\">Focus hours</p>\n          <p className=\"text-3xl font-semibold tracking-tight text-foreground tabular-nums\">\n            {total.toFixed(1)} h\n          </p>\n        </div>\n        <div className=\"relative flex rounded-full bg-muted p-1\">\n          {/* One indicator slides between the options instead of two\n              backgrounds fading, so the switch reads as a single motion. */}\n          <span\n            aria-hidden\n            className={cn(\n              \"absolute top-1 bottom-1 left-1 w-[96px] rounded-full bg-background shadow-raised transition-transform duration-200 motion-reduce:transition-none\",\n              EASE,\n              week === WEEKS[1] && \"translate-x-full\",\n            )}\n          />\n          {WEEKS.map((w) => (\n            <button\n              key={w}\n              type=\"button\"\n              aria-pressed={week === w}\n              onClick={() => setWeek(w)}\n              className={cn(\n                \"relative h-9 w-[96px] touch-manipulation rounded-full text-sm font-medium outline-hidden transition-[scale,color] duration-150 ease-out select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-[color]\",\n                week === w ? \"text-foreground\" : \"text-muted-foreground hover:text-foreground\",\n              )}\n            >\n              {w}\n            </button>\n          ))}\n        </div>\n      </div>\n      <BarChart\n        data={data}\n        max={10}\n        ticks={[0, 5, 10]}\n        unit=\"hours\"\n        suffix=\"h\"\n        label={`Focus hours per day, ${week.toLowerCase()}`}\n      />\n    </div>\n  );\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["data"],"docs":"From ui lab: https://lab.xevrion.dev/lab/bar-chart"}