# PivotPlugin

> _Since v0.1.1_

Pivot Table Plugin for tbw-grid

Transforms flat data into a pivot table view with grouped rows, grouped columns,
and aggregated values. Includes an interactive tool panel for configuring
row groups, column groups, and value aggregations at runtime.

## Installation

```ts
import { PivotPlugin } from '@toolbox-web/grid/plugins/pivot';
```

## Aggregation Functions

`sum`, `avg`, `count`, `min`, `max`, `first`, `last`

## CSS Custom Properties

| Property | Default | Description |
|----------|---------|-------------|
| `--tbw-pivot-group-bg` | `var(--tbw-color-row-alt)` | Group row background |
| `--tbw-pivot-grand-total-bg` | `var(--tbw-color-header-bg)` | Grand total row |

## [Configuration Options](/grid/plugins/pivot/interfaces/pivotconfig.md)

| Option | Type | Description |
| ------ | ---- | ----------- |
| `active?` | <code>boolean</code> | Whether pivot view is active on load (default: true when fields are configured) |
| `rowGroupFields?` | <code>string[]</code> | Fields to group rows by (vertical axis). Multiple fields create nested groups. |
| `columnGroupFields?` | <code>string[]</code> | Fields whose unique values become column headers (horizontal axis). |
| `valueFields?` | <code><a href="/grid/plugins/pivot/interfaces/pivotvaluefield/">PivotValueField</a>[]</code> | Value fields to aggregate at each row/column intersection. |
| `showTotals?` | <code>boolean</code> |  |
| `showGrandTotal?` | <code>boolean</code> |  |
| `defaultExpanded?` | <code><a href="/grid/plugins/pivot/types/pivotdefaultexpandedvalue/">PivotDefaultExpandedValue</a></code> | Which groups are expanded by default. - `true` — expand all (default) - `false` — collapse all - `number` — expand group at index - `string` — expand group with key - `string[]` — expand groups matching keys |
| `indentWidth?` | <code>number</code> | Indent width per depth level in pixels (default: 20) |
| `showToolPanel?` | <code>boolean</code> | Whether to show the pivot configuration tool panel (default: true) |
| `animation?` | <code><a href="/grid/api/core/types/expandcollapseanimation/">ExpandCollapseAnimation</a></code> | Animation style for expanding/collapsing groups. - `false`: No animation - `'slide'`: Slide animation (default) - `'fade'`: Fade animation |
| `sortRows?` | <code><a href="/grid/plugins/pivot/interfaces/pivotsortconfig/">PivotSortConfig</a></code> | Sort configuration for row groups. When set, groups at each level are sorted by label or aggregate value. |
| `sortColumns?` | <code><a href="/grid/plugins/pivot/types/pivotsortdir/">PivotSortDir</a></code> | Sort direction for column keys. Default: `'asc'` (alphabetical). Set to `'desc'` for reverse order. |
| `grandTotalInRowModel?` | <code>boolean</code> | Include the grand total row in the row model (so it's included in exports/copy). When `false` (default), grand total is rendered as a separate sticky footer. |
| `valueDisplayMode?` | <code><a href="/grid/plugins/pivot/types/pivotvaluedisplaymode/">PivotValueDisplayMode</a></code> | Display mode for aggregated values. |
| `showSubtotals?` | <code>boolean</code> | Whether to show subtotal rows at each group level in multi-level grouping. |

## Examples

### Basic Pivot Table

```ts
import '@toolbox-web/grid';
import { PivotPlugin } from '@toolbox-web/grid/plugins/pivot';

grid.gridConfig = {
  columns: [...],
  plugins: [
    new PivotPlugin({
      rowGroupFields: ['region', 'product'],
      columnGroupFields: ['quarter'],
      valueFields: [{ field: 'sales', aggFunc: 'sum', header: 'Total' }],
    }),
  ],
};
```

### Programmatic-Only (No Tool Panel)

```ts
new PivotPlugin({
  showToolPanel: false,
  rowGroupFields: ['category'],
  valueFields: [{ field: 'amount', aggFunc: 'sum' }],
})
```

## See Also

- [`PivotConfig`](/grid/plugins/pivot/interfaces/pivotconfig.md) for all configuration options
- [`PivotValueField`](/grid/plugins/pivot/interfaces/pivotvaluefield.md) for value field structure

> **Extends** [BaseGridPlugin](/docs/grid-api-plugin-development-classes-basegridplugin--docs)
>
> Inherited methods like `attach()`, `detach()`, `afterRender()`, etc. are documented in the base class.

## Properties

| Property | Type | Description |
| -------- | ---- | ----------- |
| `dependencies` | <code><a href="/grid/api/plugin-development/interfaces/plugindependency/">PluginDependency</a>[]</code> | Plugin dependencies. |
| `PANEL_ID` | <code>pivot</code> | Tool panel ID for shell integration |

## Methods

### toggle()

```ts
toggle(key: string): void
```

#### Parameters

| Name | Type | Description |
| ---- | ---- | ----------- |
| `key` | <code>string</code> |  |

***

### expand()

Expand a specific pivot group row, revealing its children.

```ts
expand(key: string): void
```

#### Parameters

| Name | Type | Description |
| ---- | ---- | ----------- |
| `key` | <code>string</code> | The pivot row key (hierarchical path, e.g. `'Engineering'` or `'Engineering||Frontend'`) |

***

### collapse()

Collapse a specific pivot group row, hiding its children.

```ts
collapse(key: string): void
```

#### Parameters

| Name | Type | Description |
| ---- | ---- | ----------- |
| `key` | <code>string</code> | The pivot row key to collapse |

***

### expandAll()

Expand all pivot group rows, revealing the full hierarchy.

```ts
expandAll(): void
```

***

### collapseAll()

Collapse all pivot group rows, showing only top-level groups.

```ts
collapseAll(): void
```

***

### isExpanded()

Check whether a specific pivot group row is currently expanded.

```ts
isExpanded(key: string): boolean
```

#### Parameters

| Name | Type | Description |
| ---- | ---- | ----------- |
| `key` | <code>string</code> | The pivot row key to check |

#### Returns

`boolean` - `true` if the group is expanded

***

### getExpandedGroups()

Get all currently expanded group keys.

```ts
getExpandedGroups(): string[]
```

#### Returns

`string[]` - Array of expanded pivot row keys

***

### enablePivot()

Enable pivot mode.

Captures the original column set (if not already captured) and activates
the pivot transformation. The grid will re-render with pivot columns and rows.

```ts
enablePivot(): void
```

#### Example

```ts
const pivot = grid.getPluginByName('pivot');
pivot.enablePivot();
```

***

### disablePivot()

Disable pivot mode and restore the original grid columns.

The grid reverts to its normal tabular layout with the original column definitions.

```ts
disablePivot(): void
```

***

### isPivotActive()

Check whether pivot mode is currently active.

```ts
isPivotActive(): boolean
```

#### Returns

`boolean` - `true` if the grid is in pivot mode

***

### getPivotResult()

Get the current pivot computation result.

Returns the full PivotResult with rows, column keys, totals,
and grand total. Returns `null` if pivot is inactive or not yet computed.

```ts
getPivotResult(): PivotResult | null
```

#### Returns

`PivotResult | null` - The computed pivot result, or `null`

***

### setRowGroupFields()

Set the fields used for row grouping (vertical axis).

Triggers a re-render with the new pivot structure.

```ts
setRowGroupFields(fields: string[]): void
```

#### Parameters

| Name | Type | Description |
| ---- | ---- | ----------- |
| `fields` | <code>string[]</code> | Array of field names to group rows by |

#### Example

```ts
const pivot = grid.getPluginByName('pivot');
pivot.setRowGroupFields(['region', 'department']);
```

***

### setColumnGroupFields()

Set the fields whose unique values become column headers (horizontal axis).

Triggers a re-render with the new pivot column structure.

```ts
setColumnGroupFields(fields: string[]): void
```

#### Parameters

| Name | Type | Description |
| ---- | ---- | ----------- |
| `fields` | <code>string[]</code> | Array of field names for column grouping |

#### Example

```ts
const pivot = grid.getPluginByName('pivot');
pivot.setColumnGroupFields(['quarter']);
```

***

### setValueFields()

Set the value fields and their aggregation functions.

Each value field defines which data field to aggregate and how.
Triggers a re-render with the new aggregation.

```ts
setValueFields(fields: PivotValueField[]): void
```

#### Parameters

| Name | Type | Description |
| ---- | ---- | ----------- |
| `fields` | <code><a href="/grid/plugins/pivot/interfaces/pivotvaluefield/">PivotValueField</a>[]</code> | Array of PivotValueField definitions |

#### Example

```ts
const pivot = grid.getPluginByName('pivot');
pivot.setValueFields([
  { field: 'revenue', aggFunc: 'sum', header: 'Total Revenue' },
  { field: 'orders', aggFunc: 'count', header: '# Orders' },
]);
```

***

### refresh()

Force re-computation of the pivot result.

Clears the cached pivot result and triggers a full re-render.
Call this after changing the underlying row data.

```ts
refresh(): void
```

***

### showPanel()

Show the pivot tool panel.
Opens the tool panel and ensures this section is expanded.

```ts
showPanel(): void
```

***

### hidePanel()

Hide the tool panel.

```ts
hidePanel(): void
```

***

### togglePanel()

Toggle the pivot tool panel section.

```ts
togglePanel(): void
```

***

### isPanelVisible()

Check if the pivot panel section is currently expanded.

```ts
isPanelVisible(): boolean
```

***
