{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"share-bar","type":"registry:component","title":"Share bar","description":"Parts of a whole as one bar that comes apart into a ranked list: each segment drops out and slides into its own row, keeping its width.","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/share-bar.tsx","type":"registry:component","content":"// Hairline UI · share-bar · 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 * SHARE BAR: parts of a whole as one bar that opens into a list\n *\n *   arrive    the segments grow out from the left edge in turn and\n *             the total rolls up\n *   point     point at a segment and the rest dim; the total becomes\n *             that part's figure and the line under it its name and\n *             share\n *   open      press the bar (or Breakdown) and the stack comes apart:\n *             each segment drops out of the bar and slides left into\n *             a row of its own, largest first, keeping exactly its\n *             width, so the list and the bar are the same picture.\n *             Each row's name and figure arrive once its bar has\n *             landed; the card grows to fit as they go\n *   close     the last row goes back first, each segment sliding\n *             right and up into its place in the stack\n *\n * One even-paced progress drives the whole move, each segment easing\n * its own phase, so pressing again mid-way turns it round from where\n * it is. Segments move by transform only.\n * ───────────────────────────────────────────────────────── */\n\nexport interface ShareBarItem {\n  key: string;\n  label: string;\n  value: number;\n  /** Any CSS colour. Defaults to your chart colours in turn. */\n  color?: string;\n}\n\nexport interface ShareBarProps extends React.HTMLAttributes<HTMLDivElement> {\n  items: ShareBarItem[];\n  title?: string;\n  /** Under the total, e.g. \"Visitors by source, last 30 days\". */\n  caption?: string;\n  expanded?: boolean;\n  defaultExpanded?: boolean;\n  onExpandedChange?: (expanded: boolean) => void;\n  format?: Intl.NumberFormatOptions;\n  locales?: string | string[];\n}\n\nconst EASE = \"cubic-bezier(0.16,1,0.3,1)\";\nconst FOCUS = \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40\";\nconst BAR = 14; // the bar's height, stacked and in each row\n/** The mark: a segment is a run of 2px upright hairlines, one every 4px. */\nconst TICKS = \"repeating-linear-gradient(to right, #000 0 2px, transparent 2px 4px)\";\nconst GAP = 3; // between stacked segments\nconst ROW = 46; // one row of the list\nconst LABEL = 18; // the name line over a row's bar\nconst STAGGER = 0.4; // how much of the move the stagger takes\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\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);\nconst out = (t: number) => 1 - (1 - t) ** 3;\n\nexport function ShareBar({\n  items,\n  title = \"Traffic\",\n  caption,\n  expanded,\n  defaultExpanded = false,\n  onExpandedChange,\n  format,\n  locales,\n  className = \"\",\n  ...props\n}: ShareBarProps) {\n  const reduced = useReducedMotion();\n  const hydrated = useHydrated();\n  const locale = locales ?? (hydrated ? undefined : \"en-US\");\n  const id = React.useId();\n  const [own, setOwn] = React.useState(defaultExpanded);\n  const open = expanded ?? own;\n  // Largest first, in the stack and in the list, so a segment's row is its rank.\n  const ranked = React.useMemo(\n    () => items.map((it, i) => ({ ...it, color: it.color ?? `var(--chart-${(i % 5) + 1}, var(--primary))` })).sort((a, b) => b.value - a.value),\n    [items],\n  );\n  const n = ranked.length;\n  const total = ranked.reduce((s, it) => s + Math.max(0, it.value), 0);\n\n  const [visible, setVisible] = React.useState(false);\n  const [active, setActive] = React.useState<string | null>(null);\n  const [width, setWidth] = React.useState(0);\n  const [legendH, setLegendH] = React.useState(20);\n\n  const rootRef = React.useRef<HTMLDivElement>(null);\n  const stageRef = React.useRef<HTMLDivElement>(null);\n  const legendRef = React.useRef<HTMLDivElement>(null);\n  const segRefs = React.useRef<(HTMLDivElement | null)[]>([]);\n  const rowRefs = React.useRef<(HTMLLIElement | null)[]>([]);\n  const trackRefs = React.useRef<(HTMLDivElement | null)[]>([]);\n  const springRef = React.useRef<Pacer | null>(null);\n  const live = React.useRef({ width: 0, n: 0, shares: [] as number[], legendH: 20 });\n\n  const shares = React.useMemo(() => ranked.map((it) => (total ? Math.max(0, it.value) / total : 0)), [ranked, total]);\n\n  // One frame: each segment between its place in the stack and its row, the card's height, and what fades.\n  const paint = React.useCallback(() => {\n    const s = springRef.current;\n    const L = live.current;\n    if (!s || !L.width) return;\n    const p = s.get();\n    let left = 0;\n    for (let i = 0; i < L.n; i++) {\n      const w = Math.max(2, L.shares[i] * (L.width - GAP * (L.n - 1)));\n      const delay = L.n > 1 ? (i / (L.n - 1)) * STAGGER : 0;\n      const t = clamp01((p * (1 + STAGGER) - delay) / 1);\n      // It drops first and slides second, so it leaves the stack on a curve rather than a diagonal.\n      const ty = ease(clamp01(t / 0.8));\n      const tx = ease(clamp01((t - 0.15) / 0.85));\n      const x = left * (1 - tx);\n      const y = (i * ROW + LABEL) * ty;\n      const seg = segRefs.current[i];\n      if (seg) {\n        seg.style.width = `${w}px`;\n        seg.style.transform = `translate3d(${x}px,${y}px,0)`;\n      }\n      const row = rowRefs.current[i];\n      const arrived = out(clamp01((t - 0.62) / 0.38));\n      if (row) {\n        row.style.opacity = String(arrived);\n        row.style.transform = `translate3d(0,${(1 - arrived) * 4}px,0)`;\n      }\n      const track = trackRefs.current[i];\n      if (track) track.style.opacity = String(arrived);\n      left += w + GAP;\n    }\n    const legend = legendRef.current;\n    if (legend) {\n      const gone = clamp01(p * 3);\n      legend.style.opacity = String(1 - gone);\n      legend.style.transform = `translate3d(0,${gone * -4}px,0)`;\n    }\n    const stage = stageRef.current;\n    if (stage) {\n      const closedH = BAR + 14 + L.legendH;\n      const openH = Math.max(1, L.n) * ROW - (ROW - LABEL - BAR);\n      stage.style.height = `${closedH + (openH - closedH) * ease(clamp01(p * 1.1))}px`;\n    }\n  }, []);\n\n  const startOpen = React.useRef(open);\n  React.useLayoutEffect(() => {\n    const s = createPacer(startOpen.current ? 1 : 0, 1100, paint);\n    springRef.current = s;\n    return () => {\n      s.stop();\n      springRef.current = null;\n    };\n  }, [paint]);\n\n  React.useLayoutEffect(() => {\n    live.current = { width, n, shares, legendH };\n    paint();\n  }, [width, n, shares, legendH, paint]);\n\n  React.useEffect(() => {\n    const s = springRef.current;\n    if (!s) return;\n    if (reduced) s.jump(open ? 1 : 0);\n    else s.set(open ? 1 : 0);\n  }, [open, reduced]);\n\n  React.useLayoutEffect(() => {\n    const stage = stageRef.current;\n    const legend = legendRef.current;\n    if (!stage || !legend) return;\n    const measure = () => {\n      setWidth((w) => (w === stage.offsetWidth ? w : stage.offsetWidth));\n      setLegendH((h) => (h === legend.offsetHeight ? h : legend.offsetHeight));\n    };\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(stage);\n    observer.observe(legend);\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    const next = !open;\n    if (expanded === undefined) setOwn(next);\n    onExpandedChange?.(next);\n  };\n\n  const fmt = (v: number) => new Intl.NumberFormat(locale, format).format(v);\n  const pct = (share: number) => new Intl.NumberFormat(locale, { style: \"percent\", maximumFractionDigits: share < 0.1 ? 1 : 0 }).format(share);\n  const shownIndex = active ? ranked.findIndex((it) => it.key === active) : -1;\n  const shown = shownIndex >= 0 ? ranked[shownIndex] : null;\n  const point = (key: string | null) => (e: React.PointerEvent) => {\n    if (e.pointerType === \"touch\" && e.type === \"pointerleave\") return;\n    setActive(key);\n  };\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, 480px)\" }} />\n      <div className=\"@container w-full\">\n      <div className=\"p-4 @md:p-5\">\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-expanded={open}\n            aria-controls={`${id}-list`}\n            onClick={toggle}\n            className={`-my-1 inline-flex h-7 shrink-0 cursor-pointer items-center gap-1.5 rounded-full pl-3 pr-2 text-[12px] font-medium text-muted-foreground shadow-[inset_0_0_0_1px_var(--border)] transition-[color,scale] duration-200 hover:text-foreground active:scale-[0.97] @md:text-[12.5px] ${FOCUS}`}\n            style={{ transitionTimingFunction: EASE }}\n          >\n            <TextMorph>{open ? \"Collapse\" : \"Breakdown\"}</TextMorph>\n            <svg\n              viewBox=\"0 0 12 12\"\n              aria-hidden=\"true\"\n              className=\"size-3\"\n              style={{ transform: open ? \"rotate(180deg)\" : \"none\", transition: reduced ? \"none\" : `transform 420ms ${EASE}` }}\n            >\n              <path d=\"M3 4.5 6 7.5l3-3\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n            </svg>\n          </button>\n        </div>\n        <p className=\"mt-0.5 text-[22px] font-medium leading-tight tracking-[-0.03em] text-foreground tabular-nums @md:text-[26px]\">\n          <NumberRoll value={visible ? (shown ? shown.value : total) : 0} format={format} locales={locale} duration={shown ? 600 : 1000} />\n        </p>\n        <p className=\"mt-0.5 truncate whitespace-nowrap text-[11.5px] text-muted-foreground @md:text-[12.5px]\">\n          <TextMorph>{shown ? `${shown.label} · ${pct(shares[shownIndex])}` : (caption ?? \"Total\")}</TextMorph>\n        </p>\n\n        <div ref={stageRef} className=\"relative mt-4 @md:mt-5\" style={{ height: BAR + 14 + legendH }} onPointerLeave={point(null)}>\n          {/* Row tracks: the whole width is 100%, so a short bar reads as a small share. */}\n          {ranked.map((it, i) => (\n            <div\n              key={`${it.key}-track`}\n              ref={(el) => {\n                trackRefs.current[i] = el;\n              }}\n              aria-hidden=\"true\"\n              className=\"absolute inset-x-0 bg-foreground/[0.1]\"\n              style={{ top: i * ROW + LABEL, height: BAR, opacity: 0, maskImage: TICKS, WebkitMaskImage: TICKS }}\n            />\n          ))}\n\n          {/* The segments: one bar when closed, the bars of the list when open. */}\n          <div\n            aria-hidden=\"true\"\n            onClick={toggle}\n            className=\"absolute inset-x-0 top-0 cursor-pointer\"\n            style={{ height: BAR, clipPath: visible || reduced ? \"inset(-200px -10px -2000px -10px)\" : \"inset(-200px 100% -2000px -10px)\", transition: reduced ? \"none\" : `clip-path 900ms ${EASE}` }}\n          >\n            {ranked.map((it, i) => (\n              <div\n                key={it.key}\n                ref={(el) => {\n                  segRefs.current[i] = el;\n                }}\n                onPointerMove={(e) => {\n                  if (e.pointerType === \"mouse\" || e.buttons) setActive(it.key);\n                }}\n                onPointerDown={() => setActive(it.key)}\n                className=\"absolute left-0 top-0\"\n                style={{\n                  height: BAR,\n                  background: it.color,\n                  maskImage: TICKS,\n                  WebkitMaskImage: TICKS,\n                  opacity: active && active !== it.key ? 0.32 : 1,\n                  transition: reduced ? \"none\" : `opacity 220ms ${EASE}`,\n                  willChange: \"transform\",\n                }}\n              />\n            ))}\n          </div>\n\n          {/* Closed: a legend under the bar. */}\n          <div ref={legendRef} aria-hidden={open} className=\"absolute inset-x-0 flex flex-wrap gap-x-4 gap-y-1\" style={{ top: BAR + 14, pointerEvents: open ? \"none\" : undefined }}>\n            {ranked.map((it, i) => (\n              <span\n                key={it.key}\n                onPointerEnter={point(it.key)}\n                className=\"inline-flex items-center gap-1.5 whitespace-nowrap text-[11.5px] text-muted-foreground transition-opacity duration-200 @md:text-[12.5px]\"\n                style={{ opacity: active && active !== it.key ? 0.45 : 1 }}\n              >\n                <span className=\"size-2 rounded-[2px]\" style={{ background: it.color }} />\n                {it.label}\n                <span className=\"tabular-nums text-foreground\">{pct(shares[i])}</span>\n              </span>\n            ))}\n          </div>\n\n          {/* Open: each row's name and figure, over the bar that landed there. */}\n          <ul id={`${id}-list`} aria-label={`${title} by share`} className=\"absolute inset-x-0 top-0\" style={{ pointerEvents: open ? undefined : \"none\" }}>\n            {ranked.map((it, i) => (\n              <li\n                key={it.key}\n                ref={(el) => {\n                  rowRefs.current[i] = el;\n                }}\n                aria-hidden={!open}\n                onPointerEnter={point(it.key)}\n                className=\"absolute inset-x-0 flex items-baseline justify-between gap-3 text-[12px] @md:text-[13px]\"\n                style={{ top: i * ROW, height: LABEL + BAR + 4, opacity: 0, transition: reduced ? \"none\" : `color 200ms ${EASE}` }}\n              >\n                <span className={`truncate transition-colors duration-200 ${active && active !== it.key ? \"text-muted-foreground\" : \"text-foreground\"}`}>{it.label}</span>\n                <span className=\"flex shrink-0 items-baseline gap-2 tabular-nums\">\n                  <span className=\"text-muted-foreground\">{fmt(it.value)}</span>\n                  <span className=\"w-[3.2em] text-right font-medium text-foreground\">{pct(shares[i])}</span>\n                </span>\n              </li>\n            ))}\n          </ul>\n        </div>\n\n        <div className=\"sr-only\"><table>\n          <caption>\n            {title}: {fmt(total)}\n          </caption>\n          <tbody>\n            {ranked.map((it, i) => (\n              <tr key={it.key}>\n                <th scope=\"row\">{it.label}</th>\n                <td>{fmt(it.value)}</td>\n                <td>{pct(shares[i])}</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/share-bar. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}