Skip to content
Thrum

Chart legend

A legend whose items switch the series of a chart on and off. It holds no chart of its own: pass its hidden keys to any chart that takes them, as the demo does with the line chart. For a legend that only names the colours, a plain list is enough.

Install

npx shadcn@latest add https://thrumui.dev/r/chart-legend.json

Adds components/ui/chart-legend.tsx and installs motion. Nothing else in your project changes.

import { ChartLegend } from "@/components/ui/chart-legend";

Data shape

Type
type ChartLegendItem = {
  key: string;            // stable id, listed in hidden
  name: string;
  color?: string;         // default: var(--chart-n) by position
  value?: number | null;  // shown beside the name
  mark?: "line" | "bar" | "dot";
};
Sample
[
  { key: "checkout", name: "Checkout", value: 412 },
  { key: "search", name: "Search", value: 268 },
  { key: "sign-in", name: "Sign-in", value: null },
]

Props

PropTypeDefaultDescription
itemsreadonly ChartLegendItem[]RequiredOne item per series, in the chart's order.
labelstringRequiredWhat the chart shows. Names the group of buttons for screen readers.
mark"line" | "bar" | "dot"Default "bar"Swatch shape: a short line, a square or a dot, to match the chart's marks. An item's own mark wins.
orientation"horizontal" | "vertical"Default "horizontal"A row that wraps onto more lines, or a column.
hiddenreadonly string[]–Keys of the hidden series, when the parent controls them. Use it with onHiddenChange.
defaultHiddenreadonly string[]–Keys of the series hidden at first, when the legend keeps the state itself.
onHiddenChange(hidden: string[]) => void–Called with the new list of hidden keys after every toggle or isolate.
formatIntl.NumberFormatOptionsDefault compactHow item values are written.
localestringDefault "en-US"Locale for number formatting.
soundbooleanDefault truePlay a soft click when a series is shown or hidden, if the visitor has sound on.
classNamestring–Merged onto the group.

Motion and sound

Motion

  • Hover and the switch between shown and hidden fade the colours in 150 ms. Nothing else moves.
  • Reduced motion: the colours change at once.

Sound

  • A rising click when a series is shown and a falling click when one is hidden, if the visitor has sound on.
  • A double-click plays one sound, for its first click. Alt+click and Alt+Enter play the rising click.

Sound is off until the visitor turns it on. Pass sound={false} to keep this component silent. How sound works

Accessibility

  • Each item is a toggle button: a native button with aria-pressed, named by the series name and its value.
  • The buttons sit in a group named after the chart, for example “Latency. Show or hide a series.”
  • A hidden series keeps its colour as an outlined swatch, and its name is muted and struck through, so the state is never colour alone.
  • The last visible series is aria-disabled and says why in its title: a chart with nothing on it answers no question.
  • Alt+click and double-click are shortcuts. Every series can also be shown or hidden one at a time.
KeysAction
TabMove to the next item. Every item is a tab stop.
Enter / SpaceShow or hide the focused series.
Alt + EnterShow only the focused series. Again shows every series.

Source

components/ui/chart-legend.tsx
"use client";

import { useState, type KeyboardEvent, type MouseEvent } from "react";
import { motion } from "motion/react";

import { cn } from "@/lib/utils";
import { formatValue, seriesColor } from "@/lib/thrum-chart";
import { INSTANT, SPRING, useReducedMotion } from "@/lib/thrum-motion";
import { play } from "@/lib/thrum-sound";

export type ChartLegendMark = "line" | "bar" | "dot";

export type ChartLegendItem = {
  /** Stable id of the series. `hidden` lists these. */
  key: string;
  /** Name of the series. */
  name: string;
  /** Any CSS colour. Defaults to the theme's chart colour for this position in `items`, the same rule the charts use. */
  color?: string;
  /** A number shown beside the name, such as the series total. `null` prints a dash. */
  value?: number | null;
  /** Swatch shape for this item, when it differs from the legend's `mark`. */
  mark?: ChartLegendMark;
};

export type ChartLegendProps = {
  /** One item per series, in the chart's order. */
  items: readonly ChartLegendItem[];
  /** What the chart shows. Names the group of buttons for screen readers. Example: "Sign-ups by channel". */
  label: string;
  /** Swatch shape: a short line, a square or a dot, to match the chart's marks. */
  mark?: ChartLegendMark;
  /** A row that wraps, or a column. */
  orientation?: "horizontal" | "vertical";
  /** Keys of the hidden series, when the parent controls them. Use it with `onHiddenChange`. */
  hidden?: readonly string[];
  /** Keys of the series hidden at first, when the legend keeps the state itself. */
  defaultHidden?: readonly string[];
  /** Called with the new list of hidden keys. */
  onHiddenChange?: (hidden: string[]) => void;
  /** How values are written. */
  format?: Intl.NumberFormatOptions;
  locale?: string;
  /** Play a soft click when a series is shown or hidden, if the visitor has sound on. */
  sound?: boolean;
  className?: string;
};

/** The swatch: drawn when the series is shown, an outline when it is hidden, so state is never colour alone. */
function Swatch({ mark, color, shown, reduced }: { mark: ChartLegendMark; color: string; shown: boolean; reduced: boolean }) {
  const fill = shown ? color : "transparent";
  const transition = reduced ? INSTANT : SPRING.control;
  if (mark === "line") {
    return (
      <motion.span
        aria-hidden="true"
        className="h-1 w-3 flex-none"
        style={{ backgroundColor: fill, boxShadow: `inset 0 0 0 1px ${color}` }}
        initial={false}
        animate={{ scale: shown ? 1 : 0.88, opacity: shown ? 1 : 0.65 }}
        transition={transition}
      />
    );
  }
  return (
    <motion.span
      aria-hidden="true"
      className={cn("size-2.5 flex-none", mark === "dot" ? "rounded-full" : "rounded-[min(var(--radius),2px)]")}
      style={{ backgroundColor: fill, boxShadow: `inset 0 0 0 1.5px ${color}` }}
      initial={false}
      animate={{ scale: shown ? 1 : 0.85, opacity: shown ? 1 : 0.65 }}
      transition={transition}
    />
  );
}

/**
 * A chart legend whose items switch series on and off. Each item is a toggle button.
 * Alt+click, Alt+Enter or a double-click shows that series alone; the same again shows every series.
 * The last visible series cannot be hidden. Colours follow the position in `items`, so hiding one never recolours the rest.
 */
export function ChartLegend({
  items,
  label,
  mark = "bar",
  orientation = "horizontal",
  hidden,
  defaultHidden,
  onHiddenChange,
  format,
  locale,
  sound = true,
  className,
}: ChartLegendProps) {
  const reduced = useReducedMotion();
  const [own, setOwn] = useState<readonly string[]>(defaultHidden ?? []);
  const hiddenKeys = hidden ?? own;
  const shownCount = items.filter((item) => !hiddenKeys.includes(item.key)).length;

  const commit = (next: string[], on: boolean, quiet = false) => {
    setOwn(next);
    onHiddenChange?.(next);
    if (sound && !quiet) play(on ? "toggleOn" : "toggleOff");
  };

  const toggle = (key: string) => {
    const on = hiddenKeys.includes(key);
    const next = on ? hiddenKeys.filter((k) => k !== key) : [...hiddenKeys, key];
    // An empty chart answers no question: the last visible series stays.
    if (items.every((item) => next.includes(item.key))) return;
    commit(next, on);
  };

  // Show one series alone. When it already is alone, show them all again.
  // A double-click is quiet here: its first click already made the one sound of the gesture.
  const isolate = (key: string, quiet = false) => {
    const alone = shownCount === 1 && !hiddenKeys.includes(key);
    commit(alone ? [] : items.filter((item) => item.key !== key).map((item) => item.key), true, quiet);
  };

  const onClick = (event: MouseEvent, key: string) => {
    // The second click of a double-click is taken by `onDoubleClick`.
    if (event.detail > 1) return;
    if (event.altKey) isolate(key);
    else toggle(key);
  };

  const onKeyDown = (event: KeyboardEvent, key: string) => {
    if (event.altKey && (event.key === "Enter" || event.key === " ")) {
      event.preventDefault();
      isolate(key);
    }
  };

  return (
    <div
      data-slot="chart-legend"
      role="group"
      aria-label={`${label}. Show or hide a series.`}
      className={cn("-mx-1.5 flex text-xs tabular-nums", orientation === "vertical" ? "flex-col items-start" : "flex-wrap gap-x-1 gap-y-0.5", className)}
    >
      {items.map((item, i) => {
        const shown = !hiddenKeys.includes(item.key);
        const last = shown && shownCount === 1;
        return (
          <button
            key={item.key}
            type="button"
            data-slot="chart-legend-item"
            aria-pressed={shown}
            aria-disabled={last || undefined}
            title={last ? "The last visible series stays" : undefined}
            onClick={(event) => onClick(event, item.key)}
            onDoubleClick={() => isolate(item.key, true)}
            onKeyDown={(event) => onKeyDown(event, item.key)}
            className={cn(
              "inline-flex h-6 max-w-full min-w-0 items-center gap-1.5 rounded-sm px-1.5 select-none transition-[background-color,color] duration-150 ease-out motion-reduce:transition-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring",
              last ? "cursor-default" : "cursor-pointer hover:bg-muted",
              !shown && "text-muted-foreground",
            )}
          >
            <Swatch mark={item.mark ?? mark} color={item.color ?? seriesColor(i)} shown={shown} reduced={reduced} />
            <span className={cn("truncate", !shown && "line-through")}>{item.name}</span>
            {item.value !== undefined && <span className="text-muted-foreground">{formatValue(item.value, format, locale)}</span>}
          </button>
        );
      })}
    </div>
  );
}

Files and dependencies

Adds
components/ui/chart-legend.tsx
Packages
motion
Brings along
Chart foundationsMotion tokensSound engine

Changelog

  1. 1.0.0 · 2026-12-03First release.

Loading index…

Keyboard shortcuts

/Ctrl KSearch components, docs and actions
?Show this list
AAppearance studio
SSound on or off
MFull or reduced motion
TTheme: auto, light, dark
GSurface: solid or frosted
BBackdrop photograph (under glass)
CCorner radius: square to round
RReplay the demo, on a component page
DDraw new data, on a component page
←→HomeEndMove the cursor in a focused chart
EscClose a dialog, or leave a chart cursor