{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"compare-bars","type":"registry:component","title":"Compare bars","description":"This period, and with one press the one before: every bar splits in two, then what was gained turns green and what fell short shows in red.","author":"Hairline UI","dependencies":[],"registryDependencies":["https://hairlineui.com/r/number-roll.json?as=dependency","https://hairlineui.com/r/text-morph.json?as=dependency"],"files":[{"path":"registry/compare-bars.tsx","type":"registry:component","content":"// Hairline UI · compare-bars · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { NumberRoll } from \"./number-roll\";\nimport { TextMorph } from \"./text-morph\";\n\n/* ─────────────────────────────────────────────────────────\n * COMPARE BARS: this period, and with one press, the one before\n *\n *   arrive    the bars grow out of the baseline one after another\n *   compare   press the period chip and each bar splits in two: it\n *             narrows and steps right while last period's bar slides\n *             out from behind it to the left. The split runs out\n *             from where you were (the bar you last pointed at, or\n *             the chip's end of the chart). Once a pair has split,\n *             what changed fills in: the part of this period over\n *             last period turns green; a shortfall shows as a pale\n *             red block up to where last period reached. The change\n *             chip unfolds beside the total and rolls to its figure\n *   point     a readout rides the top of the plot over the day you\n *             point at: this period, and when comparing, the one\n *             before and the change\n *   back      press again and it plays backwards: the change drains,\n *             then last period slides back behind\n *\n * The split is one even-paced progress, each pair easing its own\n * phase, so pressing again mid-way turns it round from where it is. Bars move by transform only.\n * ───────────────────────────────────────────────────────── */\n\nexport interface CompareBarsDatum {\n  key: string;\n  /** Under the bar, e.g. \"Mon\". */\n  label: string;\n  /** In the readout, e.g. \"Monday 3 Nov\". Defaults to label. */\n  title?: string;\n  current: number;\n  previous: number;\n}\n\nexport interface CompareBarsProps extends React.HTMLAttributes<HTMLDivElement> {\n  data: CompareBarsDatum[];\n  title?: string;\n  /** e.g. \"This week\". */\n  currentLabel?: string;\n  /** e.g. \"Last week\": the chip that turns comparing on. */\n  previousLabel?: string;\n  compared?: boolean;\n  defaultCompared?: boolean;\n  onComparedChange?: (compared: boolean) => void;\n  format?: Intl.NumberFormatOptions;\n  locales?: string | string[];\n}\n\nconst EASE = \"cubic-bezier(0.16,1,0.3,1)\";\nconst THROW = \"cubic-bezier(0.34,1.36,0.64,1)\";\nconst FOCUS = \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40\";\n/** The mark: 2px hairlines every 4px, counted up from the baseline. */\nconst RULE = \"repeating-linear-gradient(to top, #000 0 2px, transparent 2px 4px)\";\nconst SPREAD = 0.55; // how much of the move the stagger takes\nconst HEADROOM = 34;\n\nconst reducedQuery = \"(prefers-reduced-motion: reduce)\";\nconst subscribeReduced = (onChange: () => void) => {\n  const query = window.matchMedia(reducedQuery);\n  query.addEventListener(\"change\", onChange);\n  return () => query.removeEventListener(\"change\", onChange);\n};\nconst useReducedMotion = () =>\n  React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);\n\n// Formatting waits for hydration: the server and the hydrating render share one fixed locale, then the visitor's takes over.\nconst subscribeNothing = () => () => {};\nconst useHydrated = () => React.useSyncExternalStore(subscribeNothing, () => true, () => false);\n\nfunction niceMax(value: number) {\n  if (value <= 0) return 1;\n  const step = 10 ** Math.floor(Math.log10(value));\n  for (const m of [1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10]) if (m * step >= value) return m * step;\n  return 10 * step;\n}\n\n/**\n * Progress that moves at an even pace toward its target (0 or 1) and turns round from wherever it is, so a second\n * press mid-way reverses the move without a jump. Each piece eases its own phase of it; a spring would front-load it.\n */\nfunction createPacer(initial: number, duration: number, onFrame: () => void) {\n  let value = initial;\n  let target = initial;\n  let frame = 0;\n  let last = 0;\n  const tick = (now: number) => {\n    const dt = last ? (now - last) / duration : 0;\n    last = now;\n    value = target > value ? Math.min(target, value + dt) : Math.max(target, value - dt);\n    onFrame();\n    if (value !== target) frame = requestAnimationFrame(tick);\n    else frame = last = 0;\n  };\n  return {\n    get: () => value,\n    set(next: number) {\n      target = next;\n      if (!frame && value !== target) frame = requestAnimationFrame(tick);\n    },\n    jump(next: number) {\n      value = target = next;\n      if (frame) cancelAnimationFrame(frame);\n      frame = last = 0;\n      onFrame();\n    },\n    stop() {\n      if (frame) cancelAnimationFrame(frame);\n      frame = last = 0;\n    },\n  };\n}\ntype Pacer = ReturnType<typeof createPacer>;\n\nconst clamp01 = (t: number) => (t < 0 ? 0 : t > 1 ? 1 : t);\nconst ease = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2);\n\nexport function CompareBars({\n  data,\n  title = \"Revenue\",\n  currentLabel = \"This week\",\n  previousLabel = \"Last week\",\n  compared,\n  defaultCompared = false,\n  onComparedChange,\n  format,\n  locales,\n  className = \"\",\n  ...props\n}: CompareBarsProps) {\n  const reduced = useReducedMotion();\n  const hydrated = useHydrated();\n  const locale = locales ?? (hydrated ? undefined : \"en-US\");\n  const [own, setOwn] = React.useState(defaultCompared);\n  const on = compared ?? own;\n  const n = data.length;\n  const max = niceMax(Math.max(0, ...data.map((d) => Math.max(d.current, d.previous))));\n  const total = data.reduce((s, d) => s + d.current, 0);\n  const before = data.reduce((s, d) => s + d.previous, 0);\n  const change = before ? (total - before) / before : 0;\n  const up = change >= 0;\n\n  const [visible, setVisible] = React.useState(false);\n  const [active, setActive] = React.useState<number | null>(null);\n  const [keyboard, setKeyboard] = React.useState(false);\n  const [box, setBox] = React.useState({ width: 0, height: 0 });\n  const plotH = Math.max(0, box.height - HEADROOM);\n\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const plotRef = React.useRef<HTMLDivElement>(null);\n  const prevRefs = React.useRef<(HTMLDivElement | null)[]>([]);\n  const curRefs = React.useRef<(HTMLDivElement | null)[]>([]);\n  const gainRefs = React.useRef<(HTMLDivElement | null)[]>([]);\n  const lossRefs = React.useRef<(HTMLDivElement | null)[]>([]);\n  const springRef = React.useRef<Pacer | null>(null);\n  const origin = React.useRef(n - 1);\n  const live = React.useRef({ n, slot: 0, origin: n - 1 });\n\n  // One frame: every pair at its own point of the split, staggered out from where you were.\n  const paint = React.useCallback(() => {\n    const s = springRef.current;\n    if (!s) return;\n    const { n: count, slot, origin: from } = live.current;\n    if (!slot) return;\n    const p = s.get();\n    const single = Math.min(22, slot * 0.6);\n    const half = Math.min(14, slot * 0.36);\n    const gap = 2;\n    const far = Math.max(from, count - 1 - from, 1);\n    for (let i = 0; i < count; i++) {\n      const delay = (Math.abs(i - from) / far) * SPREAD;\n      const t = clamp01(p * (1 + SPREAD) - delay);\n      const split = ease(clamp01(t / 0.7));\n      const fill = ease(clamp01((t - 0.5) / 0.5));\n      const width = single + (half - single) * split;\n      const sx = width / single;\n      const dx = (split * (half + gap)) / 2;\n      const prev = prevRefs.current[i];\n      const cur = curRefs.current[i];\n      if (prev) {\n        prev.style.transform = `translate3d(${-dx}px,0,0) scaleX(${sx})`;\n        prev.style.opacity = String(clamp01(split * 1.6));\n      }\n      if (cur) cur.style.transform = `translate3d(${dx}px,0,0) scaleX(${sx})`;\n      const gain = gainRefs.current[i];\n      if (gain) gain.style.opacity = String(fill);\n      const loss = lossRefs.current[i];\n      if (loss) loss.style.opacity = String(fill);\n    }\n  }, []);\n\n  // The spring is made once, where the chart starts; changes are aimed below.\n  const startOn = React.useRef(on);\n  React.useLayoutEffect(() => {\n    const s = createPacer(startOn.current ? 1 : 0, 950, paint);\n    springRef.current = s;\n    paint();\n    return () => {\n      s.stop();\n      springRef.current = null;\n    };\n  }, [paint]);\n\n  React.useLayoutEffect(() => {\n    live.current = { n, slot: n ? box.width / n : 0, origin: origin.current };\n    paint();\n  }, [n, box.width, paint, data]);\n\n  React.useEffect(() => {\n    const s = springRef.current;\n    if (!s) return;\n    live.current.origin = origin.current;\n    if (reduced) s.jump(on ? 1 : 0);\n    else s.set(on ? 1 : 0);\n  }, [on, reduced]);\n\n  React.useLayoutEffect(() => {\n    const el = plotRef.current;\n    if (!el) return;\n    const measure = () => setBox((b) => (b.width === el.offsetWidth && b.height === el.offsetHeight ? b : { width: el.offsetWidth, height: el.offsetHeight }));\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, []);\n\n  React.useEffect(() => {\n    const el = rootRef.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(\n      ([entry]) => {\n        if (entry.isIntersecting) {\n          setVisible(true);\n          observer.disconnect();\n        }\n      },\n      { rootMargin: \"0px 0px -10% 0px\" },\n    );\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, []);\n\n  const toggle = () => {\n    // The split starts from the bar you last read, or from the chip's end of the chart.\n    origin.current = active ?? n - 1;\n    const next = !on;\n    if (compared === undefined) setOwn(next);\n    onComparedChange?.(next);\n  };\n\n  const pointAt = (clientX: number) => {\n    const r = plotRef.current?.getBoundingClientRect();\n    if (!r || !n) return null;\n    return Math.min(n - 1, Math.max(0, Math.floor(((clientX - r.left) / r.width) * n)));\n  };\n\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    if (!n) return;\n    const from = active ?? n - 1;\n    const moves: Record<string, number> = { ArrowLeft: from - 1, ArrowRight: from + 1, Home: 0, End: n - 1 };\n    if (e.key === \"Escape\") return setActive(null);\n    if (!(e.key in moves)) return;\n    e.preventDefault();\n    setKeyboard(true);\n    setActive(Math.min(n - 1, Math.max(0, active === null ? from : moves[e.key])));\n  };\n\n  const fmt = (v: number) => new Intl.NumberFormat(locale, format).format(v);\n  const pct = (v: number) => new Intl.NumberFormat(locale, { style: \"percent\", maximumFractionDigits: 1, signDisplay: \"exceptZero\" }).format(v);\n  const shown = active !== null ? data[active] : null;\n  const shownChange = shown && shown.previous ? (shown.current - shown.previous) / shown.previous : 0;\n  const slotPct = n ? 100 / n : 100;\n  const single = Math.min(22, (box.width / Math.max(1, n)) * 0.6);\n  const every = box.width && n ? Math.max(1, Math.ceil(34 / (box.width / n))) : 1;\n\n  return (\n    <div ref={rootRef} className={`w-full rounded-[22px] bg-background shadow-[0_0_0_1px_var(--border)] ${className}`} {...props}>\n      {/* Its natural width where the parent sizes to its content (a centred flex column), without forcing it on narrow screens. */}\n      <div aria-hidden=\"true\" data-natural-width className=\"grid h-0\" style={{ gridTemplateColumns: \"minmax(0, 600px)\" }} />\n      <div className=\"@container w-full\">\n      <div className=\"p-4 @md:p-5 [--plot:150px] @md:[--plot:180px]\">\n        <div className=\"flex items-center justify-between gap-3\">\n          <p className=\"text-[12px] text-muted-foreground @md:text-[13px]\">{title}</p>\n          <button\n            type=\"button\"\n            aria-pressed={on}\n            onClick={toggle}\n            className={`-my-1 inline-flex h-7 shrink-0 cursor-pointer items-center gap-2 rounded-full pl-2.5 pr-3 text-[12px] font-medium transition-[background-color,color,box-shadow,scale] duration-200 active:scale-[0.97] @md:text-[12.5px] ${FOCUS} ${\n              on\n                ? \"bg-foreground/[0.06] text-foreground shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--foreground)_18%,var(--border))]\"\n                : \"text-muted-foreground shadow-[inset_0_0_0_1px_var(--border)] hover:text-foreground\"\n            }`}\n            style={{ transitionTimingFunction: EASE }}\n          >\n            {/* Two bars that split when it's on: the chip is a small picture of what it does. */}\n            <span aria-hidden=\"true\" className=\"relative h-3 w-3\">\n              <span\n                className=\"absolute bottom-0 left-1/2 h-2 w-[5px] rounded-t-[1.5px] bg-foreground/30\"\n                style={{ transform: on ? \"translateX(-5px)\" : \"translateX(-50%)\", opacity: on ? 1 : 0, transition: reduced ? \"none\" : `transform 380ms ${THROW}, opacity 200ms ${EASE}` }}\n              />\n              <span\n                className=\"absolute bottom-0 left-1/2 h-3 w-[5px] rounded-t-[1.5px]\"\n                style={{\n                  background: \"var(--chart-1, var(--primary))\",\n                  transform: on ? \"translateX(0px)\" : \"translateX(-50%)\",\n                  transition: reduced ? \"none\" : `transform 380ms ${THROW}`,\n                }}\n              />\n            </span>\n            vs {previousLabel.toLowerCase()}\n          </button>\n        </div>\n        <div className=\"mt-0.5 flex flex-wrap items-baseline gap-x-2\">\n          <p className=\"text-[22px] font-medium leading-tight tracking-[-0.03em] text-foreground tabular-nums @md:text-[26px]\">\n            <NumberRoll value={visible ? total : 0} format={format} locales={locale} duration={1000} />\n          </p>\n          {/* The change folds open beside the total while comparing. */}\n          <span\n            className=\"grid self-center\"\n            style={{ gridTemplateColumns: on ? \"1fr\" : \"0fr\", opacity: on ? 1 : 0, transition: reduced ? \"none\" : `grid-template-columns 460ms ${EASE} ${on ? 120 : 0}ms, opacity 260ms ${EASE} ${on ? 200 : 0}ms` }}\n          >\n            <span className=\"min-w-0 [clip-path:inset(-4px_-2px)]\">\n              <span\n                className={`inline-flex items-center gap-1 whitespace-nowrap rounded-full px-1.5 py-px text-[11.5px] font-medium tabular-nums @md:text-[12.5px] ${\n                  up ? \"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400\" : \"bg-red-500/10 text-red-600 dark:text-red-400\"\n                }`}\n              >\n                <svg viewBox=\"0 0 12 12\" aria-hidden=\"true\" className=\"size-3\" style={{ transform: up ? \"none\" : \"rotate(180deg)\" }}>\n                  <path d=\"M6 9.5V2.5M2.8 5.6 6 2.5l3.2 3.1\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n                </svg>\n                <NumberRoll value={on ? Math.abs(change) : 0} format={{ style: \"percent\", maximumFractionDigits: 1 }} locales={locale} duration={900} />\n              </span>\n            </span>\n          </span>\n        </div>\n        <p className=\"mt-0.5 text-[11.5px] text-muted-foreground @md:text-[12.5px]\">\n          <TextMorph>{on ? `${currentLabel} against ${previousLabel.toLowerCase()}` : currentLabel}</TextMorph>\n        </p>\n\n        <div\n          ref={plotRef}\n          role=\"group\"\n          tabIndex={0}\n          aria-label={`${title}, ${currentLabel}${on ? ` against ${previousLabel}` : \"\"}. Use the arrow keys to read each bar.`}\n          onKeyDown={onKeyDown}\n          onBlur={() => keyboard && (setActive(null), setKeyboard(false))}\n          onPointerMove={(e) => {\n            if (e.pointerType === \"touch\" && e.buttons === 0) return;\n            setKeyboard(false);\n            setActive(pointAt(e.clientX));\n          }}\n          onPointerDown={(e) => setActive(pointAt(e.clientX))}\n          onPointerLeave={(e) => e.pointerType === \"mouse\" && setActive(null)}\n          className={`relative mt-4 touch-pan-y select-none rounded-lg @md:mt-5 ${FOCUS}`}\n          style={{ height: `calc(var(--plot) + ${HEADROOM}px)` }}\n        >\n          <div aria-hidden=\"true\" className=\"absolute inset-x-0 border-t border-dashed border-border\" style={{ top: HEADROOM }} />\n          <div aria-hidden=\"true\" className=\"absolute inset-x-0 border-t border-dashed border-border\" style={{ top: HEADROOM + plotH / 2 }} />\n          {data.map((d, i) => {\n            const hc = (Math.max(0, d.current) / max) * plotH;\n            const hp = (Math.max(0, d.previous) / max) * plotH;\n            const gained = d.current > d.previous;\n            const dim = active !== null && active !== i;\n            return (\n              <div\n                key={d.key}\n                aria-hidden=\"true\"\n                className=\"absolute inset-y-0\"\n                style={{ left: `${i * slotPct}%`, width: `${slotPct}%`, opacity: dim ? 0.55 : 1, transition: reduced ? \"none\" : `opacity 200ms ${EASE}` }}\n              >\n                <div className=\"absolute inset-x-0 bottom-0 overflow-clip\" style={{ height: visible ? plotH : 0, transition: reduced ? \"none\" : `height 640ms ${EASE} ${Math.min(i, 14) * 30}ms` }}>\n                  {/* The mark: each bar is a full-height column of 2px hairlines (a mask counted up from the baseline),\n                      faint where it's empty and lit as far as its value. Last period waits behind this one. */}\n                  <div\n                    ref={(el) => {\n                      prevRefs.current[i] = el;\n                    }}\n                    className=\"absolute bottom-0 left-1/2 origin-bottom\"\n                    style={{ width: single, marginLeft: -single / 2, height: plotH, maskImage: RULE, WebkitMaskImage: RULE, willChange: \"transform\" }}\n                  >\n                    <div className=\"absolute inset-0 bg-foreground/[0.06]\" />\n                    <div className=\"absolute inset-x-0 bottom-0 bg-foreground/[0.28]\" style={{ height: Math.max(2, hp) }} />\n                  </div>\n                  {/* This period: the part over last period lights green; a shortfall lights the lines up to where last period reached, in red. */}\n                  <div\n                    ref={(el) => {\n                      curRefs.current[i] = el;\n                    }}\n                    className=\"absolute bottom-0 left-1/2\"\n                    style={{ width: single, marginLeft: -single / 2, height: plotH, maskImage: RULE, WebkitMaskImage: RULE, willChange: \"transform\" }}\n                  >\n                    <div className=\"absolute inset-0 bg-foreground/[0.06]\" />\n                    {!gained && hp - hc > 0.5 && (\n                      <div\n                        ref={(el) => {\n                          lossRefs.current[i] = el;\n                        }}\n                        className=\"absolute inset-x-0 bg-red-500/45 dark:bg-red-400/50\"\n                        style={{ bottom: hc, height: hp - hc, opacity: 0 }}\n                      />\n                    )}\n                    <div className=\"absolute inset-x-0 bottom-0 overflow-clip\" style={{ height: Math.max(2, hc), background: \"var(--chart-1, var(--primary))\" }}>\n                      {gained && (\n                        <div\n                          ref={(el) => {\n                            gainRefs.current[i] = el;\n                          }}\n                          className=\"absolute inset-x-0 top-0 bg-emerald-500 dark:bg-emerald-400\"\n                          style={{ height: Math.max(0, hc - hp), opacity: 0 }}\n                        />\n                      )}\n                    </div>\n                  </div>\n                </div>\n                <span\n                  className=\"absolute -bottom-5 left-1/2 -translate-x-1/2 whitespace-nowrap text-[10.5px] leading-4 text-muted-foreground\"\n                  style={{ opacity: (n - 1 - i) % every === 0 ? 1 : 0 }}\n                >\n                  {d.label}\n                </span>\n              </div>\n            );\n          })}\n          <div aria-hidden=\"true\" className=\"absolute inset-x-0 bottom-0 border-t border-border\" />\n\n          {/* The readout: this period, and when comparing, the one before and the change. */}\n          <div\n            aria-hidden=\"true\"\n            className=\"pointer-events-none absolute top-0 flex h-[24px] -translate-x-1/2 items-center gap-1.5 whitespace-nowrap rounded-full bg-background px-2.5 text-[11.5px] shadow-[0_0_0_1px_var(--border)]\"\n            style={{\n              left: active !== null ? `clamp(90px, ${(active + 0.5) * slotPct}%, calc(100% - 90px))` : \"50%\",\n              opacity: shown ? 1 : 0,\n              scale: shown ? \"1\" : \"0.94\",\n              transition: reduced ? \"none\" : `left 380ms ${THROW}, opacity 200ms ${EASE}, scale 260ms ${EASE}`,\n            }}\n          >\n            <span className=\"text-muted-foreground\">\n              {shown ? (shown.title ?? shown.label) : \" \"}\n            </span>\n            <span className=\"font-medium tabular-nums text-foreground\">\n              {shown ? fmt(shown.current) : \" \"}\n            </span>\n            <span\n              className=\"grid\"\n              style={{ gridTemplateColumns: on ? \"1fr\" : \"0fr\", opacity: on ? 1 : 0, transition: reduced ? \"none\" : `grid-template-columns 380ms ${EASE}, opacity 220ms ${EASE}` }}\n            >\n              <span className=\"flex min-w-0 items-center gap-1.5 [clip-path:inset(-4px_-2px)]\">\n                <span className=\"pl-0.5 text-muted-foreground\">vs</span>\n                <span className=\"tabular-nums text-muted-foreground\">\n                  {shown ? fmt(shown.previous) : \" \"}\n                </span>\n                <span className={`font-medium tabular-nums ${shownChange >= 0 ? \"text-emerald-600 dark:text-emerald-400\" : \"text-red-600 dark:text-red-400\"}`}>\n                  {pct(shownChange)}\n                </span>\n              </span>\n            </span>\n          </div>\n        </div>\n        <div aria-hidden=\"true\" className=\"h-5\" />\n\n        <p aria-live=\"polite\" className=\"sr-only\">\n          {keyboard && shown ? `${shown.title ?? shown.label}: ${fmt(shown.current)}${on ? `, ${previousLabel} ${fmt(shown.previous)}, ${pct(shownChange)}` : \"\"}` : \"\"}\n        </p>\n        <div className=\"sr-only\"><table>\n          <caption>\n            {title}: {currentLabel} {fmt(total)}, {previousLabel} {fmt(before)}, {pct(change)}\n          </caption>\n          <thead>\n            <tr>\n              <th scope=\"col\">Day</th>\n              <th scope=\"col\">{currentLabel}</th>\n              <th scope=\"col\">{previousLabel}</th>\n            </tr>\n          </thead>\n          <tbody>\n            {data.map((d) => (\n              <tr key={d.key}>\n                <th scope=\"row\">{d.title ?? d.label}</th>\n                <td>{fmt(d.current)}</td>\n                <td>{fmt(d.previous)}</td>\n              </tr>\n            ))}\n          </tbody>\n        </table></div>\n      </div>\n      </div>\n    </div>\n  );\n}\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/compare-bars. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}