{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "pivot",
  "type": "registry:component",
  "title": "Pivot table and designer",
  "description": "An Excel-style pivot designer (field list, filters, columns, rows and values wells, drag and drop, presets) and the pivot table it builds, with collapsible groups and totals.",
  "dependencies": [
    "rowpine",
    "lucide-react"
  ],
  "registryDependencies": [
    "table",
    "button",
    "checkbox",
    "dropdown-menu",
    "input",
    "popover"
  ],
  "files": [
    {
      "path": "registry/rowpine/pivot-table.tsx",
      "type": "registry:component",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { ChevronDown, ChevronRight } from \"lucide-react\"\nimport {\n  createPivot,\n  type PivotColumnDef,\n  type PivotConfig,\n  type PivotTable as PivotModel,\n  type PivotTreeRow,\n  type ToColumnsOptions,\n} from \"rowpine\"\n\nimport { cn } from \"@/lib/utils\"\nimport {\n  Table,\n  TableBody,\n  TableCell,\n  TableHead,\n  TableHeader,\n  TableRow,\n} from \"@/components/ui/table\"\n\n/**\n * Pivot `data` with `config`; recomputes only when either changes.\n * @param data Source rows. A new array on each render rebuilds the pivot.\n * @param config The pivot config. Keep the same object between renders (a constant or useMemo); a new one rebuilds the pivot.\n * @param options Settings for every value column, such as an Excel number format. Same rule as `config`.\n */\nexport function usePivot<TData>(\n  data: ReadonlyArray<TData>,\n  config: PivotConfig<TData>,\n  options?: ToColumnsOptions\n): PivotModel {\n  return React.useMemo(() => createPivot(data, config, options), [data, config, options])\n}\n\n/** Ids of every row that has children: pass to `collapsed` to collapse all. */\nexport function expandableIds(pivot: PivotModel): Set<string> {\n  const ids = new Set<string>()\n  const walk = (rows: PivotTreeRow[]) =>\n    rows.forEach((r) => {\n      if (r.subRows?.length) {\n        ids.add(r.__pivotId)\n        walk(r.subRows)\n      }\n    })\n  walk(pivot.data)\n  return ids\n}\n\ntype HeaderCell = { key: string; label: string; colSpan: number; rowSpan: number; isTotal: boolean; isRowHeader: boolean }\n\n/** The column tree as header rows, with spans, like a spreadsheet pivot. */\nfunction headerRows(columns: PivotColumnDef[]): HeaderCell[][] {\n  const depthOf = (c: PivotColumnDef): number => (\"columns\" in c ? 1 + Math.max(...c.columns.map(depthOf)) : 1)\n  const depth = Math.max(...columns.map(depthOf))\n  const rows: HeaderCell[][] = Array.from({ length: depth }, () => [])\n  const width = (c: PivotColumnDef): number => (\"columns\" in c ? c.columns.reduce((n, k) => n + width(k), 0) : 1)\n  const place = (c: PivotColumnDef, level: number) => {\n    const leaf = !(\"columns\" in c)\n    rows[level]!.push({\n      key: c.id,\n      label: c.header,\n      colSpan: width(c),\n      rowSpan: leaf ? depth - level : 1,\n      isTotal: c.meta.pivot.isTotal,\n      isRowHeader: c.meta.pivot.isRowHeader,\n    })\n    if (!leaf) c.columns.forEach((k) => place(k, level + 1))\n  }\n  columns.forEach((c) => place(c, 0))\n  return rows\n}\n\nfunction leafColumns(columns: PivotColumnDef[]): Extract<PivotColumnDef, { accessorFn: unknown }>[] {\n  return columns.flatMap((c) => (\"columns\" in c ? leafColumns(c.columns) : [c]))\n}\n\n/** Props of `PivotTable`. */\nexport type PivotTableProps = {\n  /** The pivot to show, from usePivot or createPivot. */\n  pivot: PivotModel\n  /** Collapsed group ids, to control expansion from outside. */\n  collapsed?: Set<string>\n  /**\n   * Called with the new set of collapsed ids when a row is expanded or\n   * collapsed. When given, the table does not keep its own state, so pass\n   * `collapsed` with it.\n   */\n  onCollapsedChange?: (collapsed: Set<string>) => void\n  /** Start with every group collapsed when uncontrolled. Default false. */\n  defaultCollapsed?: boolean\n  /** Classes added to the bordered wrapper. */\n  className?: string\n}\n\n/**\n * A pivot as a shadcn Table: header groups span their columns, rows with\n * children get an expand and collapse button, and empty value cells show '-'.\n * @param props See `PivotTableProps`.\n */\nexport function PivotTable({ pivot, collapsed, onCollapsedChange, defaultCollapsed = false, className }: PivotTableProps) {\n  const [own, setOwn] = React.useState<Set<string>>(() => (defaultCollapsed ? expandableIds(pivot) : new Set()))\n  const shut = collapsed ?? own\n  const setShut = (next: Set<string>) => (onCollapsedChange ? onCollapsedChange(next) : setOwn(next))\n  const toggle = (id: string) => {\n    const next = new Set(shut)\n    if (next.has(id)) next.delete(id)\n    else next.add(id)\n    setShut(next)\n  }\n\n  const headers = React.useMemo(() => headerRows(pivot.columns), [pivot.columns])\n  const leaves = React.useMemo(() => leafColumns(pivot.columns), [pivot.columns])\n\n  const visible: Array<{ row: PivotTreeRow; depth: number }> = []\n  const walk = (rows: PivotTreeRow[], depth: number) => {\n    for (const row of rows) {\n      visible.push({ row, depth })\n      if (row.subRows?.length && !shut.has(row.__pivotId)) walk(row.subRows, depth + 1)\n    }\n  }\n  walk(pivot.data, 0)\n\n  return (\n    <div className={cn(\"rounded-md border\", className)}>\n      <Table>\n        <TableHeader>\n          {headers.map((cells, level) => (\n            <TableRow key={level}>\n              {cells.map((h) => (\n                <TableHead\n                  key={h.key}\n                  colSpan={h.colSpan}\n                  rowSpan={h.rowSpan}\n                  className={cn(\n                    \"border-l first:border-l-0\",\n                    h.isRowHeader ? \"text-left\" : \"text-right\",\n                    h.colSpan > 1 && \"text-center\",\n                    h.isTotal && \"bg-muted/50\"\n                  )}\n                >\n                  {h.label}\n                </TableHead>\n              ))}\n            </TableRow>\n          ))}\n        </TableHeader>\n        <TableBody>\n          {visible.map(({ row, depth }) => {\n            const kind = row.__pivotKind\n            const strong = kind === \"group\" || kind === \"grandTotal\"\n            const open = !shut.has(row.__pivotId)\n            return (\n              <TableRow\n                key={row.__pivotId}\n                className={cn(kind === \"group\" && \"bg-muted/30\", kind === \"grandTotal\" && \"border-t-2 bg-muted/50\")}\n              >\n                {leaves.map((col) => {\n                  if (col.meta.pivot.isRowHeader) {\n                    return (\n                      <TableCell key={col.id} className={cn(\"whitespace-nowrap\", strong && \"font-medium\")}>\n                        <span className=\"inline-flex items-center gap-1\" style={{ paddingLeft: depth * 16 }}>\n                          {row.subRows?.length ? (\n                            <button\n                              type=\"button\"\n                              onClick={() => toggle(row.__pivotId)}\n                              className=\"-ml-1 rounded p-0.5 text-muted-foreground hover:text-foreground\"\n                              aria-expanded={open}\n                              aria-label={`${open ? \"Collapse\" : \"Expand\"} ${row.__pivotLabel}`}\n                            >\n                              {open ? <ChevronDown className=\"size-4\" /> : <ChevronRight className=\"size-4\" />}\n                            </button>\n                          ) : (\n                            depth > 0 && <span className=\"w-4\" />\n                          )}\n                          {row.__pivotLabel}\n                        </span>\n                      </TableCell>\n                    )\n                  }\n                  const value = col.accessorFn(row)\n                  const text = col.meta.rowpine.format ? col.meta.rowpine.format(value, row) : String(value ?? \"\")\n                  return (\n                    <TableCell\n                      key={col.id}\n                      className={cn(\n                        \"border-l text-right tabular-nums\",\n                        strong && \"font-medium\",\n                        col.meta.pivot.isTotal && \"bg-muted/50\",\n                        value == null && \"text-muted-foreground\"\n                      )}\n                    >\n                      {value == null ? \"-\" : text}\n                    </TableCell>\n                  )\n                })}\n              </TableRow>\n            )\n          })}\n        </TableBody>\n      </Table>\n    </div>\n  )\n}\n"
    },
    {
      "path": "registry/rowpine/pivot-designer.tsx",
      "type": "registry:component",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport {\n  Check,\n  ChevronsDownUp,\n  ChevronsUpDown,\n  Columns3,\n  Filter,\n  GripVertical,\n  MoreHorizontal,\n  RotateCcw,\n  Rows3,\n  Search,\n  Settings2,\n  Sigma,\n} from \"lucide-react\"\nimport {\n  addToWell,\n  AGG_LABEL,\n  ALL_AGGREGATORS,\n  clearWell,\n  defaultLayoutFor,\n  distinctValues,\n  isFieldInLayout,\n  KIND_WELLS,\n  pivotFromLayout,\n  removeFromWell,\n  setAggregatorAt,\n  setFilterAllowed,\n  toggleField,\n  WELL_LABEL,\n  type PivotAggregatorId,\n  type PivotField,\n  type PivotLayout,\n  type PivotPreset,\n  type PivotTable as PivotModel,\n  type ToColumnsOptions,\n  type Well,\n} from \"rowpine\"\n\nimport { cn } from \"@/lib/utils\"\nimport { buttonVariants } from \"@/components/ui/button\"\nimport { Checkbox } from \"@/components/ui/checkbox\"\nimport {\n  DropdownMenu,\n  DropdownMenuCheckboxItem,\n  DropdownMenuContent,\n  DropdownMenuGroup,\n  DropdownMenuItem,\n  DropdownMenuLabel,\n  DropdownMenuSeparator,\n  DropdownMenuSub,\n  DropdownMenuSubContent,\n  DropdownMenuSubTrigger,\n  DropdownMenuTrigger,\n} from \"@/components/ui/dropdown-menu\"\nimport { Input } from \"@/components/ui/input\"\nimport { Popover, PopoverContent, PopoverTrigger } from \"@/components/ui/popover\"\nimport { expandableIds, PivotTable } from \"@/components/pivot-table\"\n\n/** Props of `PivotDesigner`. */\nexport type PivotDesignerProps<TData> = {\n  /** Source rows. The filter value lists are read from all of them. */\n  data: ReadonlyArray<TData>\n  /** The fields offered in the field list. `kind` decides which wells take each one. */\n  fields: ReadonlyArray<PivotField<TData>>\n  /** The layout, to control it. Store it as JSON to save a user's view. */\n  layout?: PivotLayout\n  /** Called with each new layout. Without `layout` the designer also keeps the layout itself. */\n  onLayoutChange?: (layout: PivotLayout) => void\n  /** Saved layouts offered in the Presets menu. */\n  presets?: ReadonlyArray<PivotPreset>\n  /** Aggregations offered on value chips. Default all. */\n  aggregators?: ReadonlyArray<PivotAggregatorId>\n  /** Column options for the pivot, e.g. an Excel number format. */\n  pivotOptions?: ToColumnsOptions\n  /** Extra toolbar content, given the current pivot (e.g. an ExportMenu). */\n  actions?: (pivot: PivotModel) => React.ReactNode\n  /** Called with each new pivot. */\n  onPivotChange?: (pivot: PivotModel | null) => void\n  /** Classes added to the outer container. */\n  className?: string\n}\n\ntype Drag = { field: string; from: Well | \"list\"; index?: number }\n\nconst WELL_ICON: Record<Well, React.ComponentType<{ className?: string }>> = {\n  filters: Filter,\n  cols: Columns3,\n  rows: Rows3,\n  values: Sigma,\n}\n\nconst ghost = (extra?: string) => cn(buttonVariants({ variant: \"ghost\", size: \"sm\" }), extra)\nconst outline = (extra?: string) => cn(buttonVariants({ variant: \"outline\", size: \"sm\" }), extra)\n\nfunction FilterValues({\n  values,\n  allowed,\n  onChange,\n}: {\n  values: string[]\n  allowed: string[] | null\n  onChange: (allowed: string[] | null) => void\n}) {\n  const [query, setQuery] = React.useState(\"\")\n  const pass = new Set(allowed ?? values)\n  const shown = values.filter((v) => v.toLowerCase().includes(query.trim().toLowerCase()))\n  const set = (v: string, on: boolean) => {\n    const next = new Set(pass)\n    if (on) next.add(v)\n    else next.delete(v)\n    onChange(next.size === values.length ? null : values.filter((x) => next.has(x)))\n  }\n  return (\n    <div className=\"grid gap-2\">\n      <Input placeholder=\"Search values...\" value={query} onChange={(e) => setQuery(e.target.value)} className=\"h-8\" />\n      <div className=\"flex gap-2 text-xs\">\n        <button type=\"button\" className=\"text-primary hover:underline\" onClick={() => onChange(null)}>\n          Select all\n        </button>\n        <button type=\"button\" className=\"text-primary hover:underline\" onClick={() => onChange([])}>\n          Clear\n        </button>\n        <span className=\"ml-auto text-muted-foreground\">\n          {pass.size} of {values.length}\n        </span>\n      </div>\n      <div className=\"grid max-h-56 gap-1 overflow-y-auto pr-1\">\n        {shown.map((v) => (\n          <label key={v} className=\"flex cursor-pointer items-center gap-2 rounded px-1 py-0.5 text-sm hover:bg-muted\">\n            <Checkbox checked={pass.has(v)} onCheckedChange={(on) => set(v, on === true)} />\n            <span className=\"truncate\">{v}</span>\n          </label>\n        ))}\n      </div>\n    </div>\n  )\n}\n\n/**\n * An Excel-style pivot designer: field list, four wells, and the pivot it builds.\n * Uncontrolled, it starts from `defaultLayoutFor`.\n * @param props See `PivotDesignerProps`.\n */\nexport function PivotDesigner<TData>({\n  data,\n  fields,\n  layout: controlled,\n  onLayoutChange,\n  presets,\n  aggregators = ALL_AGGREGATORS,\n  pivotOptions,\n  actions,\n  onPivotChange,\n  className,\n}: PivotDesignerProps<TData>) {\n  const [own, setOwn] = React.useState<PivotLayout>(() => controlled ?? defaultLayoutFor(fields))\n  const layout = controlled ?? own\n  const emit = (next: PivotLayout) => {\n    if (!controlled) setOwn(next)\n    onLayoutChange?.(next)\n  }\n\n  const pivot = React.useMemo(() => pivotFromLayout(data, layout, fields, pivotOptions), [data, layout, fields, pivotOptions])\n  React.useEffect(() => onPivotChange?.(pivot), [pivot, onPivotChange])\n\n  const [collapsed, setCollapsed] = React.useState<Set<string>>(() => new Set())\n  const [search, setSearch] = React.useState(\"\")\n  const [drag, setDrag] = React.useState<Drag | null>(null)\n  const [over, setOver] = React.useState<Well | \"list\" | null>(null)\n  const [filterOpen, setFilterOpen] = React.useState<string | null>(null)\n\n  const labelOf = (field: string) => fields.find((f) => f.field === field)?.label ?? field\n  const kindOf = (field: string) => fields.find((f) => f.field === field)?.kind ?? \"dimension\"\n\n  const add = (field: string, well: Well, sourceIndex?: number) => {\n    emit(addToWell(layout, fields, field, well, Infinity, sourceIndex))\n    // A new filter passes everything until values are picked: open the picker.\n    if (well === \"filters\") setFilterOpen(field)\n  }\n\n  // ---- drag and drop -------------------------------------------------\n  const dragProps = (d: Drag) => ({\n    draggable: true,\n    onDragStart: (e: React.DragEvent) => {\n      setDrag(d)\n      e.dataTransfer.effectAllowed = \"move\"\n      e.dataTransfer.setData(\"text/plain\", d.field)\n    },\n    onDragEnd: () => {\n      setDrag(null)\n      setOver(null)\n    },\n  })\n  const dropProps = (target: Well | \"list\") => ({\n    onDragOver: (e: React.DragEvent) => {\n      if (!drag) return\n      if (target !== \"list\" && !KIND_WELLS[kindOf(drag.field)].includes(target)) return\n      e.preventDefault()\n      e.dataTransfer.dropEffect = \"move\"\n      setOver(target)\n    },\n    onDragLeave: () => setOver(null),\n    onDrop: (e: React.DragEvent) => {\n      e.preventDefault()\n      setOver(null)\n      if (!drag) return\n      if (target === \"list\") {\n        if (drag.from !== \"list\") emit(removeFromWell(layout, drag.field, drag.from, drag.index))\n      } else {\n        add(drag.field, target, drag.from === \"values\" ? drag.index : undefined)\n      }\n      setDrag(null)\n    },\n  })\n\n  // ---- field list ----------------------------------------------------\n  const q = search.trim().toLowerCase()\n  const groups = new Map<string, PivotField<TData>[]>()\n  for (const f of fields) {\n    if (q && !f.label.toLowerCase().includes(q)) continue\n    const g = f.group ?? \"\"\n    groups.set(g, [...(groups.get(g) ?? []), f])\n  }\n\n  const chipMenu = (well: Well, field: string, index?: number) => {\n    const targets = KIND_WELLS[kindOf(field)].filter((w) => w !== well)\n    const current = index !== undefined ? layout.values[index]?.agg : undefined\n    return (\n      <DropdownMenu>\n        <DropdownMenuTrigger className=\"rounded-sm p-0.5 text-muted-foreground hover:text-foreground\" aria-label={`Options for ${labelOf(field)}`}>\n          <MoreHorizontal className=\"size-3.5\" />\n        </DropdownMenuTrigger>\n        <DropdownMenuContent align=\"start\" className=\"w-48\">\n          {well === \"values\" && index !== undefined && (\n            <DropdownMenuSub>\n              <DropdownMenuSubTrigger>\n                <Sigma />\n                Aggregate\n              </DropdownMenuSubTrigger>\n              <DropdownMenuSubContent>\n                {aggregators\n                  .filter((a) => kindOf(field) === \"measure\" || a === \"count\" || a === \"countDistinct\")\n                  .map((a) => (\n                    // A plain item closes the menu on pick in both bases; checkbox items stay open in Base UI.\n                    <DropdownMenuItem key={a} onClick={() => emit(setAggregatorAt(layout, fields, index, a))}>\n                      <Check className={cn(a !== current && \"invisible\")} />\n                      {AGG_LABEL[a]}\n                    </DropdownMenuItem>\n                  ))}\n              </DropdownMenuSubContent>\n            </DropdownMenuSub>\n          )}\n          {targets.length > 0 && (\n            <DropdownMenuSub>\n              <DropdownMenuSubTrigger>Move to</DropdownMenuSubTrigger>\n              <DropdownMenuSubContent>\n                {targets.map((w) => (\n                  <DropdownMenuItem key={w} onClick={() => add(field, w, well === \"values\" ? index : undefined)}>\n                    {WELL_LABEL[w]}\n                  </DropdownMenuItem>\n                ))}\n              </DropdownMenuSubContent>\n            </DropdownMenuSub>\n          )}\n          {well === \"filters\" && <DropdownMenuItem onClick={() => setFilterOpen(field)}>Edit filter...</DropdownMenuItem>}\n          <DropdownMenuSeparator />\n          <DropdownMenuItem onClick={() => emit(removeFromWell(layout, field, well, index))}>Remove</DropdownMenuItem>\n          <DropdownMenuItem onClick={() => emit(clearWell(layout, well))}>Clear {WELL_LABEL[well]}</DropdownMenuItem>\n        </DropdownMenuContent>\n      </DropdownMenu>\n    )\n  }\n\n  const chip = (well: Well, field: string, index?: number) => {\n    const value = index !== undefined ? layout.values[index] : undefined\n    const filter = well === \"filters\" ? layout.filters.find((f) => f.field === field) : undefined\n    const text = value ? (value.label ?? `${AGG_LABEL[value.agg]} of ${labelOf(field)}`) : labelOf(field)\n    return (\n      <div\n        key={`${well}-${field}-${index ?? \"\"}`}\n        {...dragProps({ field, from: well, index })}\n        className=\"flex h-7 cursor-grab items-center gap-1 rounded-md border bg-background pl-1 pr-0.5 text-xs shadow-xs active:cursor-grabbing\"\n      >\n        <GripVertical className=\"size-3 text-muted-foreground\" />\n        <span className=\"max-w-40 truncate\">{text}</span>\n        {filter && (\n          <Popover open={filterOpen === field} onOpenChange={(o) => setFilterOpen(o ? field : null)}>\n            <PopoverTrigger\n              className={cn(\"rounded-sm p-0.5 hover:text-foreground\", filter.allowed ? \"text-primary\" : \"text-muted-foreground\")}\n              aria-label={`Filter ${labelOf(field)}`}\n            >\n              <Filter className=\"size-3.5\" />\n            </PopoverTrigger>\n            <PopoverContent align=\"start\" className=\"w-64\">\n              <FilterValues\n                values={distinctValues(data, field)}\n                allowed={filter.allowed}\n                onChange={(allowed) => emit(setFilterAllowed(layout, field, allowed))}\n              />\n            </PopoverContent>\n          </Popover>\n        )}\n        {chipMenu(well, field, index)}\n      </div>\n    )\n  }\n\n  const well = (w: Well) => {\n    const Icon = WELL_ICON[w]\n    const items =\n      w === \"values\"\n        ? layout.values.map((v, i) => chip(\"values\", v.field, i))\n        : w === \"filters\"\n          ? layout.filters.map((f) => chip(\"filters\", f.field))\n          : layout[w].map((f) => chip(w, f))\n    return (\n      <div\n        {...dropProps(w)}\n        data-well={w}\n        className={cn(\"grid content-start gap-1.5 rounded-md border border-dashed p-2\", over === w && \"border-primary bg-primary/5\")}\n      >\n        <div className=\"flex items-center gap-1.5 text-xs font-medium text-muted-foreground\">\n          <Icon className=\"size-3.5\" />\n          {WELL_LABEL[w]}\n        </div>\n        <div className=\"flex min-h-7 flex-wrap gap-1.5\">\n          {items.length ? items : <span className=\"self-center text-xs text-muted-foreground\">Drag fields here</span>}\n        </div>\n      </div>\n    )\n  }\n\n  return (\n    <div className={cn(\"grid gap-3 md:grid-cols-[13rem_1fr]\", className)}>\n      {/* Field list */}\n      <aside\n        {...dropProps(\"list\")}\n        className={cn(\"grid content-start gap-2 self-start rounded-md border p-2 md:sticky md:top-4\", over === \"list\" && \"border-primary bg-primary/5\")}\n        aria-label=\"Pivot fields\"\n      >\n        <div className=\"relative\">\n          <Search className=\"pointer-events-none absolute top-1/2 left-2 size-3.5 -translate-y-1/2 text-muted-foreground\" />\n          <Input placeholder=\"Search fields...\" value={search} onChange={(e) => setSearch(e.target.value)} className=\"h-8 pl-7\" />\n        </div>\n        {[...groups].map(([group, items]) => (\n          <div key={group || \"_\"} className=\"grid gap-0.5\">\n            {group && <div className=\"px-1 pt-1 text-xs font-medium text-muted-foreground\">{group}</div>}\n            {items.map((f) => (\n              <div\n                key={f.field}\n                {...dragProps({ field: f.field, from: \"list\" })}\n                className=\"group flex cursor-grab items-center gap-2 rounded px-1 py-1 text-sm hover:bg-muted active:cursor-grabbing\"\n              >\n                <Checkbox\n                  checked={isFieldInLayout(layout, f.field)}\n                  onCheckedChange={() => emit(toggleField(layout, fields, f.field))}\n                  aria-label={`Use ${f.label}`}\n                />\n                <span className=\"flex-1 truncate\">{f.label}</span>\n                {f.kind === \"measure\" && <Sigma className=\"size-3.5 text-muted-foreground\" />}\n                <DropdownMenu>\n                  <DropdownMenuTrigger\n                    className=\"rounded-sm p-0.5 text-muted-foreground opacity-0 group-hover:opacity-100 hover:text-foreground focus-visible:opacity-100\"\n                    aria-label={`Add ${f.label}`}\n                  >\n                    <MoreHorizontal className=\"size-3.5\" />\n                  </DropdownMenuTrigger>\n                  <DropdownMenuContent align=\"start\">\n                    {KIND_WELLS[f.kind].map((w) => (\n                      <DropdownMenuItem key={w} onClick={() => add(f.field, w)}>\n                        Add to {WELL_LABEL[w]}\n                      </DropdownMenuItem>\n                    ))}\n                  </DropdownMenuContent>\n                </DropdownMenu>\n              </div>\n            ))}\n          </div>\n        ))}\n      </aside>\n\n      <div className=\"grid min-w-0 content-start gap-3\">\n        {/* Toolbar */}\n        <div className=\"flex flex-wrap items-center gap-2\">\n          {presets && presets.length > 0 && (\n            <DropdownMenu>\n              <DropdownMenuTrigger className={outline()}>Presets</DropdownMenuTrigger>\n              <DropdownMenuContent align=\"start\">\n                <DropdownMenuGroup>\n                  <DropdownMenuLabel>Saved layouts</DropdownMenuLabel>\n                  {presets.map((p) => (\n                    <DropdownMenuItem key={p.name} onClick={() => emit(structuredClone(p.layout))}>\n                      {p.name}\n                    </DropdownMenuItem>\n                  ))}\n                </DropdownMenuGroup>\n              </DropdownMenuContent>\n            </DropdownMenu>\n          )}\n          <DropdownMenu>\n            <DropdownMenuTrigger className={outline()}>\n              <Settings2 />\n              Totals\n            </DropdownMenuTrigger>\n            <DropdownMenuContent align=\"start\">\n              <DropdownMenuCheckboxItem checked={!layout.hideSubtotals} onCheckedChange={(on) => emit({ ...layout, hideSubtotals: !on })}>\n                Subtotals\n              </DropdownMenuCheckboxItem>\n              <DropdownMenuCheckboxItem checked={!layout.hideGrandTotals} onCheckedChange={(on) => emit({ ...layout, hideGrandTotals: !on })}>\n                Grand totals\n              </DropdownMenuCheckboxItem>\n            </DropdownMenuContent>\n          </DropdownMenu>\n          <button type=\"button\" className={ghost()} onClick={() => setCollapsed(new Set())} disabled={!pivot}>\n            <ChevronsUpDown />\n            Expand all\n          </button>\n          <button type=\"button\" className={ghost()} onClick={() => pivot && setCollapsed(expandableIds(pivot))} disabled={!pivot}>\n            <ChevronsDownUp />\n            Collapse all\n          </button>\n          <button type=\"button\" className={ghost()} onClick={() => emit(defaultLayoutFor(fields))}>\n            <RotateCcw />\n            Reset\n          </button>\n          {pivot && actions && <div className=\"ml-auto\">{actions(pivot)}</div>}\n        </div>\n\n        {/* Wells */}\n        <div className=\"grid gap-2 sm:grid-cols-2\">\n          {well(\"filters\")}\n          {well(\"cols\")}\n          {well(\"rows\")}\n          {well(\"values\")}\n        </div>\n\n        {/* Pivot */}\n        {pivot ? (\n          <PivotTable pivot={pivot} collapsed={collapsed} onCollapsedChange={setCollapsed} className=\"overflow-x-auto\" />\n        ) : (\n          <div className=\"rounded-md border border-dashed p-8 text-center text-sm text-muted-foreground\">\n            Add a field to Values to build the pivot.\n          </div>\n        )}\n      </div>\n    </div>\n  )\n}\n"
    }
  ]
}
