# Pivot builder

> A pivot table builder where you drag dimensions and measures into Rows, Columns, Values and Filters wells, with a live preview while you hover, per value aggregation, subtotals, a grand total, heat shading, collapsible row groups, swap and CSV export.

- Type: Block
- Page: https://uiarc.dev/components/blocks/pivot-builder
- Markdown: https://uiarc.dev/components/blocks/pivot-builder/markdown

- Access: Arc Pro
- Registry id: `pivot-builder`
- Source file: `registry/blocks/pivot-builder/pivot-builder.tsx`
- Built from: Button, Empty state
- Keywords: pivot table, pivot, crosstab, olap, aggregation, group by, subtotal, grand total, heatmap, drag and drop, report builder, analytics, csv export, spreadsheet

Render <PivotBuilder /> for the Ridgeline Coffee demo, or pass records, fields (dimensions and measures) and a defaultLayout of { filters, columns, rows, values } chips. Use onLayoutChange to save views and fileName to name the export.

## When to use

- Self-serve analysis where the viewer picks the rows, columns and measures.
- Internal reporting screens that replace a spreadsheet pivot table.
- Exploring a flat export before deciding which fixed chart or report to build.

## When not to use

- Use data-grid or sortable-data-table to browse, edit or select individual records; the pivot only shows aggregates.
- Use tree-table for a hierarchy that already exists in the data, such as folders or an org chart.
- Use cohort-retention or metric-explorer when the question is fixed and a chart answers it faster.

## Installation

Pivot builder is part of Arc Pro. The live preview is public; the source and install command need Pro.

### CLI with a Pro token

1. Create a token in your account and set it in the environment (or `.env.local`). Never commit it.

```bash
export ARC_PRO_TOKEN=arc_pro_...
```

2. Add the Pro registry to `components.json`:

```json
{
  "registries": {
    "@uiarc": "https://uiarc.dev/r/{name}.json",
    "@uiarc-pro": {
      "url": "https://uiarc.dev/r/pro/{name}.json",
      "headers": {
        "Authorization": "Bearer ${ARC_PRO_TOKEN}"
      }
    }
  }
}
```

3. Install:

```bash
npx shadcn@latest add @uiarc-pro/pivot-builder
```

### Manual

Signed-in Pro members can copy the source from the Manual tab on the docs page.

- Plans: https://uiarc.dev/pricing
- Create a Pro token: https://uiarc.dev/account#pro-access
- Setup guide: https://uiarc.dev/docs/ai#pro-access

## Usage

```tsx
import { PivotBuilder, type PivotField } from "@/components/arc/blocks/pivot-builder/pivot-builder";

const fields: PivotField[] = [
  { id: "team", label: "Team", kind: "dimension" },
  { id: "month", label: "Month", kind: "dimension", values: ["Jan", "Feb", "Mar"] },
  { id: "hours", label: "Hours", kind: "measure", format: "number", aggs: ["sum", "average", "percent"] },
];

export function TimeReport({ rows }: { rows: { team: string; month: string; hours: number }[] }) {
  return (
    <PivotBuilder
      title="Logged hours"
      description="Q1 2026, all teams"
      records={rows}
      fields={fields}
      defaultLayout={{
        filters: [],
        columns: [{ id: "c-month", field: "month" }],
        rows: [{ id: "r-team", field: "team" }],
        values: [{ id: "v-hours", field: "hours", agg: "sum", heat: true }],
      }}
      fileName="logged-hours.csv"
      onLayoutChange={layout => saveView(layout)}
    />
  );
}
```

## API reference

### PivotBuilder

A pivot table builder. Drag dimensions and measures from the field list into Rows, Columns, Values and Filters, and the pivot recomputes as you hover, with subtotals, a grand total, per value aggregation, heat shading, row groups that expand and collapse, a swap for rows and columns, and CSV export.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `records` | `PivotRecord[]` | `pivotOrders` | Flat records to aggregate, one object per row keyed by field id. Defaults to 1,184 Ridgeline Coffee orders from 2025, generated from a fixed seed. |
| `fields` | `PivotField[]` | `pivotFields` | Fields in the list: { id, label, kind: "dimension" \| "measure", values?, format?, aggs? }. values sets the display order of a dimension; format is currency, number, percent or text; aggs lists the aggregations a measure offers, first is the default. |
| `defaultLayout` | `PivotLayout` | `starterLayout` | Lanes the pivot opens with: { filters, columns, rows, values }, each a list of { id, field, agg?, heat? }. Pass empty lists to open on the empty state. |
| `defaultExclusions` | `PivotExclusions` | `{}` | Values hidden by the filters lane, keyed by field id, such as { channel: ["Retail"] }. Only fields placed in Filters apply. |
| `title` | `string` | `"Sales pivot"` | Heading of the screen. |
| `description` | `string` | `"Ridgeline Coffee orders, January to December 2025"` | Line under the heading. Pass an empty string to hide it. |
| `fileName` | `string` | `"ridgeline-sales-pivot.csv"` | Name of the file Export CSV downloads. |
| `onLayoutChange` | `(layout: PivotLayout) => void` | – | Called after every committed change to the lanes, an aggregation or heat shading. Hover previews during a drag do not call it. |
| `className` | `string` | – | Class on the root element. |

### Aggregations

Set per value chip from its menu. The same measure can sit in Values twice with different aggregations.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `sum` | `Agg` | – | Adds the measure across the records in a cell. |
| `average` | `Agg` | – | Mean of the measure across the records in a cell. |
| `count` | `Agg` | – | Number of records in a cell. |
| `distinct` | `Agg` | – | Number of different values, such as unique customers. Offered for text measures. |
| `percent` | `Agg` | – | Share of the filtered grand total, shown as % of total. Text measures use the share of records. |

## Keyboard interactions

| Keys | Action |
| --- | --- |
| Enter / Space on a field | Opens the field menu: add a dimension to rows, columns or filters, or add a measure to values with a chosen aggregation. |
| Enter / Space on a chip | Opens the chip menu: aggregation and heat shading for values, shown values for filters, move, reorder and remove. |
| Alt + Arrow left / Arrow right | Moves the focused chip one place within its well. |
| Delete / Backspace | Removes the focused chip from the pivot. |
| Arrow keys in a menu, Escape | Move through menu items and close the menu, returning focus to the chip. |
| Enter / Space on a row group | Expands or collapses that group. The corner button expands or collapses all groups. |

## Accessibility

- The result is a table with role="table", row, rowheader, columnheader and cell roles, and aria-colspan on grouped column headers, so screen readers read each value with its row and column.
- Every drag has a menu path: fields and chips are real buttons with menus, so the whole pivot can be built without a pointer.
- Row groups are buttons with aria-expanded. The scroll area is focusable and named, so keyboard users can scroll wide pivots.
- Changes are announced in a polite live region, such as "Country moved to columns" or "Exported ridgeline-sales-pivot.csv".
- Heat shading is never the only signal: every shaded cell prints its value, and the footer names the shaded measure with a low to high key.
- Pointer focus draws no ring; keyboard focus shows Arc's shared focus ring. Keyboard position shows as a filled chip, field or row header.

## Motion

- The dragged chip follows the pointer on motion values, with no React render per frame. React only hears when the target well or insert position changes.
- Chips in the wells glide aside to open a dashed slot where the chip will land, on the smooth spring with no overshoot. On release the chip flies into that slot, or home if nothing changed, or fades out when dropped outside to remove.
- The table previews the drop while you hover: a new structure crossfades in, rows that appear or leave slide the rest into place, and a changed number rises into its cell.
- Group chevrons rotate on the spring token, heat shading fades by opacity, and the swap icon turns half a turn per swap.
- Reduced motion removes the fly, lift and slide; chips and rows land at once and numbers change in place.

## Responsive behavior

- From 880px the field list sits beside the wells as a column; below it becomes wrapped field pills above the wells.
- Wells sit in a two by two grid from 640px and stack below it, with the well name above its chips on phones.
- The table scrolls inside its card with the header row and first column pinned, and the grand total pinned to the bottom.
- On touch screens chips, fields, row groups and menu items grow to 44px. A tap opens the menu; a drag moves the chip.

## Performance

- The pivot recomputes in one pass per layout change and memoizes on layout and filters; 1,200 records with nested rows and columns compute in well under a frame.
- Drag hit testing reads layout offsets, not animated rects, so the insert position never oscillates while neighbours move.
- Row and cell animations use transform and opacity only. Very large pivots (hundreds of rows) stay correct but should collapse groups by default.

## Notes for AI

- Choose it when people need to slice one flat dataset their own way: sales by region and quarter, hours by team and month, tickets by queue and priority.
- Feed records as flat objects keyed by field id. Give dimensions an explicit values order when the natural order is not alphabetical (quarters, months, sizes).
- Start with a meaningful defaultLayout so the first view already answers a question. Use the empty layout only where building from scratch is the point.
- Persist views with onLayoutChange and pass the saved layout back as defaultLayout with a key to restore it.
- The engine is synchronous and client side. Aggregate on the server first for datasets beyond tens of thousands of records.

## Related

- [Data grid](https://uiarc.dev/components/data-grid/markdown): A spreadsheet grid with range selection, inline editing, a fill handle, and animated sorting.
- [Tree table](https://uiarc.dev/components/tree-table/markdown): A table with nested rows, tri-state selection, hierarchy-preserving sort, and lazy-loaded children.
- [Cohort retention](https://uiarc.dev/components/blocks/cohort-retention/markdown): A cohort retention triangle that morphs into retention curves and rewashes by segment.
- [Metric explorer](https://uiarc.dev/components/blocks/metric-explorer/markdown): KPI cards that open into a scrubbable chart and morph between metrics and ranges.
- [Sortable data table](https://uiarc.dev/components/sortable-data-table/markdown): Compare structured records with sortable columns.

## Guidance for AI tools

Blocks are complete, self-contained screens with sample data. Replace the sample data and connect the callbacks described above. Follow the declared prop types and do not invent props. Keep keyboard access, reduced motion support, and both light and dark themes intact when adapting it.

Full library index: https://uiarc.dev/llms.txt
