<!-- generated by scripts/gen-docs.mjs from docs/system/composition-bar.md. Edit the source and rerun. -->
# CompositionBar

## Description
Shows the parts of one whole in a single bar, each part as wide as its share, with every part's amount and share written under it, so a person reads what the whole is made of at a glance and the exact figures beside it.

`import { CompositionBar } from "@/components/cobalt/ui/composition-bar"`, source `registry/cobalt/ui/composition-bar.tsx`, status `ready-with-gaps`.
Foundation: `hand-rolled`. Traps checked: `trap/loading-layout-shift`, `trap/color-only-status`, `trap/live-region-double`, `trap/reduced-motion-ignored`, `trap/motion-transition-all`, `trap/motion-layout-property`, `trap/numbers-shift`, `trap/tooltip-essential`, `trap/tooltip-interactive`, `trap/touch-hover-flash`, `trap/hover-unguarded` (n/a: no CSS hover reveals anything; the list rows and the bar follow the hover store and pointer events), `trap/demo-on-timers` (n/a: every example holds fixed data), `trap/illustration-announced` (n/a: the bar is `aria-hidden` and the list and the table carry the data), `trap/loop-offscreen` (n/a: nothing loops).

### Foundation
Not applicable: hand-rolled.

| Given by the foundation | Added by the team |
|---|---|
| The Chart frame from `chart.tsx` for the line the bar sits in: the hover store, the tooltip, the keys, the live line, the summary and the hidden table; `barPath` for the rounded ends; `ChartSwatch`, `seriesColor` and `formatValue` from `chart-math.ts`; `Empty` and `Skeleton` for the states | The bar: one line, `h-6` with the list and `h-5` alone, so it sits level with one line of text in a table row; parts 2px of surface apart, the outer ends rounded and the joins square, no part narrower than 2px; parts in the order of `data`, coloured `--chart-1` to `--chart-6` by place or by `config`; past `max` parts, six by default, the smallest folded into one grey "Other", last; zero, negative and missing parts left out of the whole. The list: a row per part with its swatch, its name, its amount and its share to one decimal, so a column of shares lines up; hovering a part lights its row and hovering a row lights its part, the others dim. The tooltip shows only with `legend="none"`, since the list already writes every figure. Its own empty, pending and failure states, held at the line and `placeholder` rows, since a 20px line cannot hold the frame's own |

## Examples
A fund's assets by strategy in one bar, each part as wide as its share, with every amount and share written under it.

Real uses, 0 call sites (`rg -n "<CompositionBar\b" app registry docs/system/examples --glob '!docs/system/examples/composition-bar/*'`): no showcase page draws one outside its examples yet, and the examples folder does not count.

Uses inside the registry: none. `registry/cobalt/ui/composition-bar.test.tsx` renders it for the tests.

### Example files
| File | Covers | Caption |
|---|---|---|
| `docs/system/examples/composition-bar/default.tsx` | default | A fund's assets by strategy in one bar, each part as wide as its share, with every amount and share written under it |
| Not applicable: list is the default, the list in default.tsx | legend=list | Every part's name, amount and share under the bar |
| `docs/system/examples/composition-bar/legend-none.tsx` | legend=none | The bar alone in each row of a table of funds, one legend above; `config` gives each asset class its colour in every row |
| `docs/system/examples/composition-bar/in-card.tsx` | composition:ChartCard | Who invests in a fund, in a chart card: nine kinds of investor, the five largest shown and the rest folded into Other |

Example: A fund's assets by strategy in one bar, each part as wide as its share, with every amount and share written under it (`docs/system/examples/composition-bar/default.tsx`)

```tsx
import { CompositionBar } from "@/components/cobalt/ui/composition-bar";

// Gross assets by strategy at the latest filing, in dollars, largest first.
const strategies = [
  { strategy: "Private equity", assets: 2.32e9 },
  { strategy: "Credit", assets: 1.26e9 },
  { strategy: "Real assets", assets: 5.3e8 },
  { strategy: "Infrastructure", assets: 3.1e8 },
];

export default function Example() {
  return (
    <CompositionBar
      className="w-full max-w-md"
      label="Assets by strategy"
      data={strategies}
      name="strategy"
      value="assets"
      format="money"
    />
  );
}
```

Example: Who invests in a fund, in a chart card: nine kinds of investor, the five largest shown and the rest folded into Other (`docs/system/examples/composition-bar/in-card.tsx`)

```tsx
import { ChartCard } from "@/components/cobalt/ui/chart-card";
import { CompositionBar } from "@/components/cobalt/ui/composition-bar";
import { compactMoney } from "@/lib/cobalt/format";

// Commitments to the fund by kind of investor, in dollars, largest first.
const investors = [
  { kind: "Pension plans", committed: 1.42e9 },
  { kind: "Endowments", committed: 6.8e8 },
  { kind: "Insurance companies", committed: 5.9e8 },
  { kind: "Sovereign wealth funds", committed: 4.4e8 },
  { kind: "Funds of funds", committed: 3.1e8 },
  { kind: "Family offices", committed: 1.9e8 },
  { kind: "Individuals", committed: 1.2e8 },
  { kind: "Banks", committed: 7.0e7 },
  { kind: "Foundations", committed: 4.0e7 },
];
const total = investors.reduce((sum, investor) => sum + investor.committed, 0);

export default function Example() {
  return (
    <ChartCard
      className="w-full max-w-md"
      title="Who invests"
      value={compactMoney(total)}
      note={`Committed by ${investors.length} kinds of investor`}
    >
      <CompositionBar label="Commitments by kind of investor" data={investors} name="kind" value="committed" format="money" />
    </ChartCard>
  );
}
```

## Variants

### legend
- `list`: the default, a row per part under the bar with its name, amount and share; a name too long for its row breaks onto a second line, with the swatch and the figures on its first, instead of losing its end; hovering a part lights its row, and the list is where the figures are read, so the bar shows no tooltip. Used at 0 call sites.
- `none`: the bar alone in a 20px line, for a table cell or beside a figure; the tooltip carries the part's amount and share, and a legend of the parts sits once above the table. Used at 0 call sites.

Example: The bar alone in each row of a table of funds, one legend above; `config` gives each asset class its colour in every row (`docs/system/examples/composition-bar/legend-none.tsx`)

```tsx
import { type ChartConfig, ChartLegend } from "@/components/cobalt/ui/chart";
import { CompositionBar } from "@/components/cobalt/ui/composition-bar";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/cobalt/ui/table";

// What each fund held at its latest filing, by asset class, in dollars.
const funds = [
  { fund: "Northwind Growth", holdings: [["Stocks", 3.1e9], ["Bonds", 1.2e9], ["Cash", 2.1e8]] },
  { fund: "Harbor Point Income", holdings: [["Stocks", 4.2e8], ["Bonds", 1.5e9], ["Cash", 1.8e8]] },
  { fund: "Juniper Balanced", holdings: [["Stocks", 4.6e8], ["Bonds", 3.9e8], ["Cash", 3.0e7]] },
  { fund: "Saltmarsh Cash Reserve", holdings: [["Bonds", 9.0e7], ["Cash", 6.2e8]] },
].map(({ fund, holdings }) => ({
  fund,
  holdings: holdings.map(([kind, amount]) => ({ kind: String(kind), amount: Number(amount) })),
}));

// A part keeps its colour in every row, though a fund that holds no stocks starts with bonds.
const config = {
  Stocks: { color: "var(--chart-1)" },
  Bonds: { color: "var(--chart-2)" },
  Cash: { color: "var(--chart-3)" },
} satisfies ChartConfig;

export default function Example() {
  return (
    <div className="flex w-full max-w-lg flex-col gap-3">
      <ChartLegend items={Object.entries(config).map(([key, { color }]) => ({ key, label: key, color }))} />
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>Fund</TableHead>
            <TableHead className="w-1/2">Holdings</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {funds.map((row) => (
            <TableRow key={row.fund}>
              <TableCell>{row.fund}</TableCell>
              <TableCell>
                <CompositionBar
                  label={`${row.fund} holdings`}
                  data={row.holdings}
                  name="kind"
                  value="amount"
                  format="money"
                  config={config}
                  legend="none"
                />
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </div>
  );
}
```

## States
| State | Trigger | What the user can do | Shown by, besides color | Checked by |
|---|---|---|---|---|
| idle | `data` with at least one part above zero | read the bar and the list, hover, tab in | each part's width, its row's name, amount and share | test |
| hover | the pointer over a part, or over its row | read the part's figures | the other parts dim to 40% and the other rows to 50%; with `legend="none"` the tooltip above the bar | screenshot |
| focus | Tab reaches the bar | step with the arrow keys | the system focus outline on the line, the last part shown, the live line read aloud | by hand |
| folded | more parts than `max` | read the sum of the smallest | an "Other" part last, in `--chart-previous`, its row last; with `legend="none"` its tooltip names the parts it holds | test |
| pending | `status="pending"` with no parts yet | wait | `aria-busy`; nothing for 250ms, then a Skeleton bar and `placeholder` Skeleton rows at their own heights | test |
| refreshing | `status="pending"` with parts on screen | read the old parts | after 250ms the bar and the list dim to 55% and the hover stops; the new parts fade in when they arrive | by hand |
| empty | no part above zero, and not pending | read why | the sentence "Nothing to show for this period." at the line's height | test |
| failure | `status="failure"` | press Retry, with the list | the title "Could not load the chart" announced once as an alert, and Retry when `onRetry` is passed; with `legend="none"` one line of text, no Retry | test |

### State precedence
- Failure and pending: failure wins. The line shows the failure.
- Pending and empty: pending wins. The line stays blank, then shows the Skeleton after the slow wait; the empty sentence never flashes.
- Pending and idle: both show. The parts stay, dimmed after the slow wait, until the new ones arrive.
- Hover on the bar and hover on a row: the last one wins. One part is lit at a time.

### Motion
| Trigger | Kind | Preset | Properties | Reduced motion |
|---|---|---|---|---|
| a part is hovered, by the pointer, the keys or its row | input | `duration-press`, `--t-press` 140ms on `--curve` | opacity | the same fade |
| the parts change while on screen | announce | the system's crossfade, `--t-crossfade` 320ms on `--curve-sheet`, the new bar fading in | opacity | none: the new bar is drawn at once |
| the parts first arrive after the Skeleton | announce | `--t-fade` 150ms on `--curve` | opacity | none |
| a refresh passes the slow wait | announce | `duration-fade` on `--curve` | opacity, to 55% | the same fade |

## Props

<!-- Props generated from registry/cobalt/ui/composition-bar.tsx with TypeScript by scripts/props-table.mjs -->
| Prop | Type | Default | Purpose |
|---|---|---|---|
| `data` | `readonly T[]` |  |  |
| `label` | `string` |  |  |
| `name` | `Accessor<T, string>` |  | The part's name: "Credit". |
| `value` | `Accessor<T, number>` |  | The part's amount. |
| `active?` | `number` |  | The hovered part, as its row in `data`, for a headline that follows the pointer. |
| `className?` | `string` |  |  |
| `config?` | `ChartConfig` |  | Names and colours by part name, as shadcn's `ChartConfig`. |
| `format?` | `ValueFormat` | `"number"` | How amounts read in the list, the tooltip and the table. |
| `labels?` | `Partial<ChartLabels>` |  |  |
| `legend?` | `"none" \| "list"` | `"list"` | "list" writes each part's name, amount and share under the bar, and the row is what hovering a part lights; "none" leaves the bar alone, for a table cell or beside a figure, and the tooltip carries the figures. |
| `locale?` | `string` |  |  |
| `max?` | `number` | `6` | Past this many parts the smallest fold into one grey "Other", last. |
| `onActiveChange?` | `((row: number) => void)` |  | Called with the hovered part's row in `data`, or null; the folded "Other" reports null. |
| `onRetry?` | `(() => void)` |  |  |
| `placeholder?` | `number` | `4` | How many parts the loading state holds, the count you expect. |
| `status?` | `Status` | `"idle"` |  |
| `summary?` | `string` |  | Your own sentence for screen readers; one is written from the data otherwise. |
| `tooltip?` | `boolean` |  |  |
| `words?` | `{ value: string; share: string; }` | `WORDS` | The words for the tooltip's rows and the table's columns. |

`data` holds the parts; `name` reads a part's name, which keys its colour, its `config` entry and its row, and `value` its amount. `format` shapes the amounts. `config` names and colours parts by name, as shadcn's `ChartConfig`; a colour there wins over the part's place. `max` is how many parts show before the smallest fold into "Other", 6 by default. `legend` is `list` or `none`. `words` replaces the tooltip rows and the table columns, `{ value: "Amount", share: "Share" }` by default. `placeholder` is the count of Skeleton rows, 4 by default, and every state holds the line and that many 28px rows. `active` and `onActiveChange` speak in rows of `data`; the folded "Other" reports null. `label`, `summary`, `status`, `onRetry`, `labels`, `tooltip`, `className` and `locale` work as on every chart; `Chart` documents them. It takes no `height`: the line is one height.

## Usage

### When to use
- The parts of one whole that a person reads as shares, such as a fund's assets by strategy, its investors by kind or the forms filed this month.
- The make-up of each row of a table, such as each fund's holdings by asset class, with `legend="none"` and one legend above.

### When not to use
- Parts that a person ranks and compares by length, or more than a dozen of them. Use BarList instead.
- Parts of a whole over time. Use AreaChart with `stacked`, or BarChart with `layout="stacked"`, instead.
- Amounts that are not parts of one whole, such as figures that overlap or do not add up. Use BarChart instead.
- One value against a limit. Use Meter instead.

### Rules
- `rule/composition-bar-config-in-tables`: When a table draws a `CompositionBar` in each row, give each part its colour in `config` instead of relying on its place, because a row that lacks a part would shift every colour after it, and the one legend above the table would no longer match. Evidence: principle heuristic: consistency and standards; person D13. Check: review of every `CompositionBar` with `legend="none"` inside a `TableCell`.
  - Don't: `<CompositionBar data={row.holdings} name="kind" value="amount" legend="none" label="Holdings" />`
  - Do: `<CompositionBar data={row.holdings} name="kind" value="amount" config={config} legend="none" label="Holdings" />`
- `rule/composition-bar-status-not-conditionals`: When the parts are loading or failed, pass `status` and `onRetry` instead of swapping the bar for a spinner or a message, because the bar holds its line and its rows, waits 250ms before the Skeleton, and announces a failure once. Evidence: person D39; person D37; principle heuristic: visibility of system status. Check: test `composition-bar.test.tsx` expects the held height, `aria-busy` with no Skeleton before the wait, and `role="alert"`.
  - Don't: `{loading ? <Spinner /> : <CompositionBar data={parts} name="kind" value="amount" label="Assets" />}`
  - Do: `<CompositionBar data={parts} name="kind" value="amount" label="Assets" status={query.status} onRetry={query.retry} />`

### Content
- Follows `rule/writing-no-invented-numbers`.
- Follows `rule/chart-label-names-the-data`.
- `rule/composition-bar-largest-first`: When the parts have no order of their own, sort `data` largest first instead of passing the rows in the order they came, because the bar and the list keep the order of `data`, and largest first puts the colours a reader meets first on the parts that matter most. Evidence: principle heuristic: recognition rather than recall; single use docs/system/examples/composition-bar/default.tsx:4-10. Check: review of every `data` passed to `CompositionBar` whose names are not ordered bands.
  - Don't: `data={[{ kind: "Cash", amount: 2e8 }, { kind: "Stocks", amount: 3.1e9 }]}`
  - Do: `data={[{ kind: "Stocks", amount: 3.1e9 }, { kind: "Cash", amount: 2e8 }]}`

### Anti-slop
- `rule/composition-bar-not-a-donut`: When the parts of one whole are shown, draw them as a `CompositionBar` instead of a donut or a pie, because lengths along one line are read more exactly than angles, and the bar fits a table row or a card's header where a circle does not. Evidence: principle heuristic: match between system and real world, lengths along one line are compared more exactly than angles; person D13. Check: review of every page that sets out the parts of a whole.
  - Don't: `<PieChart data={parts} />`
  - Do: `<CompositionBar data={parts} name="kind" value="amount" label="Assets by strategy" />`

### Limits
- `rule/composition-bar-six-parts`: When a whole has more than 6 parts, let the bar fold the smallest into "Other", which it does by itself, instead of raising `max` past 6, because past six the series colours repeat and two parts would look the same. Evidence: measured 9 kinds of investor folded to 5 and Other in docs/system/examples/composition-bar/in-card.tsx; person D13. Check: test `composition-bar.test.tsx` expects six rows, the last "Other", and the folded parts in the table.
  - Don't: `<CompositionBar data={nineKinds} name="kind" value="amount" max={9} label="Investors" />`
  - Do: `<CompositionBar data={nineKinds} name="kind" value="amount" label="Investors" />`

## Accessibility
Rests on the Chart frame for the bar: a focusable `div` with `role="group"` and `aria-roledescription="chart"`, one tab stop. The bar is `aria-hidden`; the data is a visually hidden sentence (`aria-describedby`) that says how many parts, the whole and the largest part's share, and a visually hidden `table` with a row per part, the folded ones too, and a last row for the whole. The list under the bar is plain text that a screen reader reads as a list. Parts are told apart by their row's name as well as colour. Screen reader pass with VoiceOver: NEEDS REVIEW.

### Keyboard
| Key | Where focus is | Effect | Focus after | Checked by |
|---|---|---|---|---|
| Tab | before the bar | focuses the bar and shows the last part | the bar | by hand |
| Right, Left | the bar | the next or previous part, its row lit | the bar | by hand |
| Home, End | the bar | the first or the last part | the bar | by hand |
| Escape | the bar, or the pointer over it | clears the lit part | stays | by hand |
| Tab | the bar | leaves it | the next control | by hand |

### ARIA
| Part | Role | Accessible name from | States and properties | Announced | Checked by |
|---|---|---|---|---|---|
| bar | group | `label`, through `aria-label`; `aria-roledescription` from `labels.chart` | `aria-describedby` the summary; `aria-busy` while pending | the name, "chart" and the summary when it is reached | test |
| live line | none, `aria-live="polite"` | nothing | none | the part, its amount and its share as the keys move | by hand |
| list | list | nothing; name it with a heading above | none | "list, 4 items", then each row's name, amount and share | test |
| table | table | its caption, the `label` | a row header per part and the whole | read on request from the table list | test |
| failure | alert | its title | none | "Could not load the chart" once | test |

## Tokens
| Part | State | Token |
|---|---|---|
| parts | all | `--chart-1`, `--chart-2`, `--chart-3`, `--chart-4`, `--chart-5`, `--chart-6` |
| Other | all | `--chart-previous` |
| part's name and amount | all | `--foreground` |
| share | all | `--muted-foreground` |
| swatch | all | `--r-xs` |
| tooltip | hover, with `legend="none"` | `--tip`, `--tip-foreground`, `--r-md`, `--t-press`, `--curve` |
| pending bar and rows | pending | `--muted` through Skeleton |

## Related
- BarList: names ranked by value, each row filled to its share of the largest.
- AreaChart: parts of a whole over time, stacked.
- BarChart: amounts per period or group, stacked or side by side.
- ChartCard: a card with the chart's title and headline figure.
- Chart: the frame every chart draws in, with the shared states, keys and table.
- Meter: one value against a fixed limit.
