Skip to content
Shaken UI
Sign in

Bar List

Save

Ranked rows whose background bar shows each value against the largest, with tabs that switch lists, bars that resize and re-rank in place, a Show more that grows the card, and a loading state.

Category
Data display
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Bar List preview

Visitors

Last 30 days
  • /docs/quickstart8,412, 34.3% of total
  • /pricing5,207, 21.2% of total
  • /docs/agents/tool-calls3,981, 16.2% of total
  • /changelog2,466, 10.1% of total
  • /docs/api/rate-limits1,903, 7.8% of total

Installation

npx @shakenui/cli add bar-list

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add bar-list --dry-run

Usage

bar-list-example.tsx
import { BarListCard } from "@/components/shaken/ui/bar-list";

const range = (values: number[]) =>
  ["search_docs", "read_file", "edit_file", "run_tests", "fetch_url", "query_db", "open_pull_request", "send_slack_message"].map(
    (name, i) => ({ name, value: values[i]! }),
  );

const tabs = [
  { value: "24h", label: "24 hours", data: range([412, 388, 241, 197, 133, 96, 31, 12]) },
  { value: "7d", label: "7 days", data: range([2_604, 2_871, 1_932, 1_655, 702, 811, 214, 97]) },
  { value: "30d", label: "30 days", data: range([10_284, 11_903, 8_115, 7_342, 2_516, 3_870, 902, 455]) },
];

export default function BarListExample() {
  return (
    <BarListCard
      className="max-w-md"
      title="Tool calls"
      meta="Production agents"
      columns={["Tool", "Calls"]}
      tabs={tabs}
      limit={5}
    />
  );
}

API

PropTypeDefaultDescription
data{ name, value, icon?, href? }[]—BarList: the rows. Rows with the same name keep their identity across updates, so their bars resize and they glide to their new rank.
tabs{ value, label, data }[]—BarListCard: the lists to switch between.
tab / defaultTab / onTabChangestring—BarListCard: the active tab.
title / meta / columnsReactNode / ReactNode / [ReactNode, ReactNode]—BarListCard: the heading, text at the right of the header, and column headings above the rows.
valueFormatter(value: number) => stringIntl.NumberFormatFormats values on the right.
show"value" | "share" | "both""value"Right column: the value, the share of the total, or both.
sortOrder"descending" | "ascending" | "none""descending"Ranks rows by value, or keeps the given order.
limitnumber5Rows shown before Show more.
expanded / defaultExpanded / onExpandedChangeboolean—Whether the rows past limit are shown.
loadingbooleanfalseShows static placeholder rows; bars grow in when data arrives.
onSelect(item) => void—Makes rows buttons. Rows with href are links.
emptyReactNode"No data for this period."Shown when data is empty.

Accessibility

  • Rows are a list; each reads as its label and value, with the share of the total added as screen reader text. Bars are decorative.
  • BarListCard tabs are a Base UI tablist with arrow-key navigation.
  • Show more is a button with aria-expanded and aria-controls; folded rows are inert and hidden from assistive technology until expanded.
  • Loading sets aria-busy on the placeholder.
  • Under reduced motion bars render at their final width, rows re-rank and expand without animating.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/bar-list.tsxbar-list
  • npm packages: @base-ui/react@^1.9.0, motion@^14.14.0React and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/bar-list/0.1.0.json.

ui/bar-list.tsxShow
ui/bar-list.tsx
"use client";

import { Tabs as BaseTabs } from "@base-ui/react/tabs";
import { AnimatePresence, MotionConfig, motion, useReducedMotion, type Transition } from "motion/react";
import { useId, useMemo, useRef, useState, type ReactNode } from "react";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

const ease = [0.23, 1, 0.32, 1] as const;
const ROW = 32;
const GAP = 4;

export interface BarListItem {
  /** Row label. Rows with the same name keep their identity when the data changes, so their bars resize and re-rank instead of re-entering. */
  name: string;
  value: number;
  /** A 16px icon, flag or favicon before the label. */
  icon?: ReactNode;
  /** Makes the row a link. */
  href?: string;
}

export interface BarListProps {
  data: BarListItem[];
  /** Formats values on the right. Defaults to `Intl.NumberFormat`. */
  valueFormatter?: (value: number) => string;
  /** Ranks rows by value. `none` keeps the given order. */
  sortOrder?: "descending" | "ascending" | "none";
  /** What the right column shows: the value, the row's share of the total, or both. */
  show?: "value" | "share" | "both";
  /** Rows shown before "Show more". Pass `Infinity` to show every row. */
  limit?: number;
  /** Controlled expanded state of a list longer than `limit`. */
  expanded?: boolean;
  defaultExpanded?: boolean;
  onExpandedChange?: (expanded: boolean) => void;
  /** Shows placeholder rows while the data loads. */
  loading?: boolean;
  /** Called when a row is pressed. Makes rows buttons. */
  onSelect?: (item: BarListItem) => void;
  /** Names the list for screen readers. */
  label?: string;
  /** Shown when `data` is empty. */
  empty?: ReactNode;
  className?: string;
}

/**
 * Ranked rows whose background bar shows each value against the largest one. Bars grow in on
 * mount, resize and re-rank in place when the data changes, and rows past `limit` fold behind a
 * "Show more" that grows the list. Under reduced motion everything renders in its final state.
 */
export function BarList({
  data,
  valueFormatter,
  sortOrder = "descending",
  show = "value",
  limit = 5,
  expanded: expandedProp,
  defaultExpanded = false,
  onExpandedChange,
  loading = false,
  onSelect,
  label,
  empty = "No data for this period.",
  className,
}: BarListProps) {
  const reduce = useReducedMotion();
  const listId = useId();
  const [expandedState, setExpandedState] = useState(defaultExpanded);
  const expanded = expandedProp ?? expandedState;
  const setExpanded = (next: boolean) => {
    if (expandedProp === undefined) setExpandedState(next);
    onExpandedChange?.(next);
  };

  const rows = useMemo(() => {
    const copy = data.slice();
    if (sortOrder !== "none") copy.sort((a, b) => (sortOrder === "descending" ? b.value - a.value : a.value - b.value));
    return copy;
  }, [data, sortOrder]);

  const max = rows.reduce((m, r) => Math.max(m, r.value), 0);
  const total = rows.reduce((s, r) => s + r.value, 0);
  const format = valueFormatter ?? ((n: number) => new Intl.NumberFormat().format(n));
  const percent = new Intl.NumberFormat(undefined, { style: "percent", maximumFractionDigits: 1 });
  const hidden = Math.max(0, rows.length - limit);
  const folded = hidden > 0 && !expanded;
  const collapsedHeight = Math.min(rows.length, limit) * ROW + Math.max(0, Math.min(rows.length, limit) - 1) * GAP;

  // Bars stagger in only the first time rows appear; later changes resize them together.
  const seen = useRef(new Set<string>());
  const firstPaint = useRef(true);

  if (loading) {
    // Bars stagger in again once the data arrives.
    seen.current.clear();
    firstPaint.current = true;
    const widths = [92, 71, 54, 38, 27, 19];
    return (
      <div aria-busy="true" aria-label={label ? `${label}, loading` : "Loading"} className={cx("grid gap-1", className)}>
        {widths.slice(0, Number.isFinite(limit) ? Math.max(1, limit) : 5).map((w, i) => (
          <div key={i} className="flex h-8 items-center justify-between gap-4">
            <div style={{ width: `${w}%` }} className="h-8 rounded-md bg-zinc-950/[0.04] dark:bg-white/[0.06]" />
            <div className="h-2.5 w-10 shrink-0 rounded-full bg-zinc-950/[0.06] dark:bg-white/[0.08]" />
          </div>
        ))}
      </div>
    );
  }

  if (rows.length === 0) {
    return <p className={cx("py-6 text-center text-sm text-zinc-500", className)}>{empty}</p>;
  }

  const barTransition = (index: number, isNew: boolean, revealIndex: number): Transition =>
    reduce
      ? { duration: 0 }
      : {
          duration: 0.5,
          ease,
          delay: revealIndex >= 0 ? revealIndex * 0.03 : isNew && firstPaint.current ? index * 0.04 : 0,
        };

  const list = (
    <motion.div
      initial={false}
      animate={{ height: folded ? collapsedHeight : "auto" }}
      transition={reduce ? { duration: 0 } : { duration: 0.32, ease }}
      className={cx(
        "relative overflow-hidden",
        folded && "[mask-image:linear-gradient(to_bottom,black_55%,transparent)]",
      )}
    >
      <ul id={listId} aria-label={label} className="relative grid gap-1">
        <AnimatePresence initial={false} mode="popLayout">
          {rows.map((row, index) => {
            const isNew = !seen.current.has(row.name);
            const visible = !folded || index < limit;
            const pct = max > 0 ? (row.value / max) * 100 : 0;
            const share = total > 0 ? row.value / total : 0;
            const right =
              show === "share" ? percent.format(share) : format(row.value);
            const revealIndex = expanded && index >= limit ? index - limit : -1;
            const content = (
              <>
                <span className="relative flex h-full min-w-0 flex-1 items-center">
                  <motion.span
                    aria-hidden="true"
                    initial={{ clipPath: "inset(0 100% 0 0 round 6px)" }}
                    animate={{ clipPath: `inset(0 ${visible ? 100 - pct : 100}% 0 0 round 6px)` }}
                    transition={barTransition(index, isNew, revealIndex)}
                    className={cx(
                      "absolute inset-0 rounded-md bg-zinc-950/[0.07] dark:bg-white/[0.1]",
                      "transition-[background-color] duration-150 ease-out motion-reduce:transition-none",
                      (onSelect || row.href) && "group-hover/row:bg-zinc-950/[0.11] dark:group-hover/row:bg-white/[0.15]",
                    )}
                  />
                  <span className="relative flex min-w-0 items-center gap-2 px-2.5">
                    {row.icon ? (
                      <span aria-hidden="true" className="flex size-4 shrink-0 items-center justify-center text-zinc-500 [&_svg]:size-4 [&>img]:size-4 [&>img]:rounded-sm">
                        {row.icon}
                      </span>
                    ) : null}
                    <span className="truncate text-zinc-950 dark:text-white">{row.name}</span>
                  </span>
                </span>
                <span className="flex min-w-12 shrink-0 items-baseline justify-end gap-2 font-mono text-xs tabular-nums">
                  {show === "both" ? <span className="text-zinc-500">{percent.format(share)}</span> : null}
                  <span className="text-zinc-700 dark:text-zinc-300">{right}</span>
                  {show === "value" ? <span className="sr-only">, {percent.format(share)} of total</span> : null}
                </span>
              </>
            );
            const rowClass = cx(
              "group/row relative flex h-8 w-full items-center justify-between gap-3 rounded-md text-left text-sm",
            );
            const interactiveClass =
              "cursor-pointer outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500";
            return (
              <motion.li
                key={row.name}
                layout={reduce ? false : "position"}
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0, transition: { duration: reduce ? 0 : 0.12, ease: "easeOut" } }}
                transition={reduce ? { duration: 0 } : { layout: { type: "spring", bounce: 0, duration: 0.45 }, opacity: { duration: 0.2 } }}
                onAnimationComplete={() => {
                  seen.current.add(row.name);
                  firstPaint.current = false;
                }}
                inert={!visible || undefined}
                aria-hidden={!visible || undefined}
              >
                {row.href ? (
                  <a href={row.href} className={cx(rowClass, interactiveClass)} onClick={onSelect ? () => onSelect(row) : undefined}>
                    {content}
                  </a>
                ) : onSelect ? (
                  <button type="button" className={cx(rowClass, interactiveClass)} onClick={() => onSelect(row)}>
                    {content}
                  </button>
                ) : (
                  <div className={rowClass}>{content}</div>
                )}
              </motion.li>
            );
          })}
        </AnimatePresence>
      </ul>
    </motion.div>
  );

  return (
    <MotionConfig reducedMotion="user">
      <div className={cx("grid", className)}>
        {list}
        {hidden > 0 ? (
          <div className={cx("relative flex justify-center", folded ? "-mt-3" : "mt-2")}>
            <button
              type="button"
              aria-expanded={expanded}
              aria-controls={listId}
              onClick={() => setExpanded(!expanded)}
              className={cx(
                "inline-flex h-7 items-center gap-1.5 rounded-lg border px-2.5 text-xs font-medium select-none",
                "border-zinc-950/10 bg-white text-zinc-600 hover:border-zinc-950/20 hover:text-zinc-950",
                "dark:border-white/15 dark:bg-black dark:text-zinc-400 dark:hover:border-white/25 dark:hover:text-white",
                "transition-[color,border-color,scale] duration-150 ease-out motion-safe:active:scale-[0.97] motion-reduce:transition-none",
                "outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
              )}
            >
              {expanded ? "Show less" : `Show ${hidden} more`}
              <svg
                aria-hidden="true"
                viewBox="0 0 16 16"
                fill="none"
                stroke="currentColor"
                strokeWidth="1.5"
                strokeLinecap="round"
                strokeLinejoin="round"
                className={cx("size-3.5 transition-transform duration-200 motion-reduce:transition-none", expanded && "rotate-180")}
              >
                <path d="m4.5 6.5 3.5 3.5 3.5-3.5" />
              </svg>
            </button>
          </div>
        ) : null}
      </div>
    </MotionConfig>
  );
}

export interface BarListTab {
  value: string;
  label: ReactNode;
  data: BarListItem[];
}

export interface BarListCardProps extends Omit<BarListProps, "data" | "label"> {
  /** Card heading. */
  title: ReactNode;
  /** Lists to switch between. Rows that share a name across lists resize and re-rank in place. */
  tabs: BarListTab[];
  /** Controlled active tab. */
  tab?: string;
  defaultTab?: string;
  onTabChange?: (value: string) => void;
  /** Column headings above the rows, such as `["Page", "Visitors"]`. */
  columns?: [ReactNode, ReactNode];
  /** Meta text at the right of the header, such as a total or a date range. */
  meta?: ReactNode;
}

/**
 * A card with a heading, tabs that switch between ranked lists, and a Bar List.
 * The list instance persists across tabs, so shared rows animate between values.
 */
export function BarListCard({
  title,
  tabs,
  tab: tabProp,
  defaultTab,
  onTabChange,
  columns,
  meta,
  className,
  ...listProps
}: BarListCardProps) {
  const [tabState, setTabState] = useState(defaultTab ?? tabs[0]?.value ?? "");
  const active = tabProp ?? tabState;
  const current = tabs.find((t) => t.value === active) ?? tabs[0];
  const indicatorId = `bar-list-tab-${useId()}`;
  const titleId = useId();

  return (
    <MotionConfig reducedMotion="user">
      <section
        aria-labelledby={titleId}
        className={cx(
          "grid w-full rounded-xl border border-zinc-950/10 bg-white text-sm shadow-[0_1px_2px_rgb(0_0_0/0.04)]",
          "dark:border-white/10 dark:bg-black dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]",
          className,
        )}
      >
        <header className="flex items-baseline justify-between gap-4 px-4 pt-4">
          <h3 id={titleId} className="text-sm font-semibold text-zinc-950 dark:text-white">
            {title}
          </h3>
          {meta ? <span className="font-mono text-xs text-zinc-500 tabular-nums">{meta}</span> : null}
        </header>
        <BaseTabs.Root
          value={active}
          onValueChange={(value) => {
            if (tabProp === undefined) setTabState(value as string);
            onTabChange?.(value as string);
          }}
        >
          <BaseTabs.List className="relative mt-2 flex gap-1 border-b border-zinc-950/[0.07] px-2 dark:border-white/[0.08]">
            {tabs.map((t) => (
              <BaseTabs.Tab
                key={t.value}
                value={t.value}
                className={cx(
                  "relative h-9 shrink-0 cursor-pointer px-2 text-sm whitespace-nowrap select-none",
                  "text-zinc-500 hover:text-zinc-950 data-[active]:text-zinc-950 dark:hover:text-white dark:data-[active]:text-white",
                  "transition-colors duration-150 ease-out motion-reduce:transition-none",
                  "rounded-md outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500",
                )}
              >
                {t.label}
                {t.value === active ? (
                  <motion.span
                    aria-hidden="true"
                    layoutId={indicatorId}
                    transition={{ type: "spring", bounce: 0, duration: 0.35 }}
                    className="absolute inset-x-2 -bottom-px h-px bg-zinc-950 dark:bg-white"
                  />
                ) : null}
              </BaseTabs.Tab>
            ))}
          </BaseTabs.List>
          {/* One panel whose value follows the active tab, so the list inside persists and can morph. */}
          <BaseTabs.Panel value={active} className="grid gap-2 px-4 pt-3 pb-4 outline-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500">
            {columns ? (
              <div aria-hidden="true" className="flex justify-between px-2.5 text-xs font-medium text-zinc-500">
                <span>{columns[0]}</span>
                <span>{columns[1]}</span>
              </div>
            ) : null}
            <BarList {...listProps} data={current?.data ?? []} label={typeof current?.label === "string" ? current.label : undefined} />
          </BaseTabs.Panel>
        </BaseTabs.Root>
      </section>
    </MotionConfig>
  );
}