# Aggregates

> Footer, group footer and group caption summaries with built-in and custom aggregate types.

Canonical: https://salmonui.dev/docs/data-grid/aggregates

Aggregates are a core module declared as data: one or more
aggregate rows, each listing fields with one or several types,
as the `aggregates` prop or as `<DataGridAggregateRow>` and
`<DataGridAggregate>` children. The built-in types are sum, average, min, max, count, true count
and false count; a custom type receives the rows of the grid or
group. Values use number and date formats.

```tsx
<DataGrid
  data={orders}
  columns={columns}
  grouping={{ groupBy: ['country'] }}
  aggregates={[
    {
      columns: [
        { field: 'amount', type: ['sum', 'average'], format: 'C2',
          renderFooter: ({ formatted }) => <>Total {formatted.sum}</>,
          renderGroupCaption: ({ formatted }) => <>Avg {formatted.average}</> },
        { field: 'shipped', type: 'trueCount', renderGroupFooter: ({ values }) => <>{String(values.trueCount)} shipped</> },
        { field: 'customer', type: 'custom', custom: (rows) => new Set(rows.map((row) => row.customer)).size },
      ],
    },
  ]}
/>
```

Each `DataGridAggregate` names the `field`, the `type` (one or an array:
`'sum'`, `'average'`, `'min'`, `'max'`, `'count'`, `'trueCount'`,
`'falseCount'`, `'custom'`), an optional `displayField` for the column the
value shows under, a `format` and the templates. The JSX form is
`<DataGridAggregateRow><DataGridAggregate field="amount" type="sum" /></DataGridAggregateRow>`
inside the grid. `api.getAggregates()` returns the footer values and
`api.getAggregates(groupId)` those of one group.

## Placement and templates

Each aggregate shows in the grid footer, in group footers, in group
captions, or several of these: the templates it defines decide where, and
without any template it shows in the footer with the default rendering. Footer, group footer and group caption
templates are functions that receive the raw and formatted values, the
group, its count and its rows.

String templates such as `${Sum}` are not supported (as for column
templates): templates are functions, so no string
evaluation runs on the footer render path and they are type-checked.
For a footer that reads "Sum: ...", use
`renderFooter: ({ formatted }) => <>Sum: {formatted.sum}</>`; the context
carries the values (`values`) and formatted text (`formatted`) by type.

The footer stays pinned to the bottom of the scroll container.

## Correctness

Aggregates are computed over the whole filtered data set, not over the rows
that happen to be rendered, so they are correct under virtualization.
They recompute when the
query or the data changes.

With a remote data source that aggregates on the server, the result lists
`'aggregate'` in `performed` and carries the totals in `aggregates`: the
footer and `api.getAggregates()` then show those server totals instead of
summarizing the received page. Group footers and captions
still summarize the received rows, except in lazy grouping, where captions
come with server aggregates.

### Live demo: Aggregates

Live demo: https://salmonui.dev/demos/data-grid/aggregates

Footer, group footer and group caption aggregates over 20,000 virtualized rows; several types per column, two aggregate rows, a custom aggregate, formats, function templates, and recomputation on filter.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, DataGridAggregate, DataGridAggregateRow, type DataGridAggregateContext, type DataGridApi, type DataGridColumn } from '@salmonui/data-grid';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(20_000, 33);

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 120 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'category', header: 'Category', width: 120 },
  { field: 'quantity', header: 'Qty', type: 'number', align: 'end', width: 140 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 260 },
  { field: 'shipped', header: 'Shipped', type: 'boolean', displayAsCheckbox: true, align: 'center', width: 130 },
];

// Templates are module-level so the aggregate definitions stay stable across renders.
// A template decides where the value shows: footer, group footer, group caption.
type Ctx = DataGridAggregateContext<Order>;
const amountFooter = ({ formatted }: Ctx) => <span>Σ {formatted['sum']} · avg {formatted['average']}</span>;
const amountGroupFooter = ({ formatted, count }: Ctx) => <span>{count.toLocaleString('en-US')} orders · Σ {formatted['sum']}</span>;
const amountCaption = ({ formatted }: Ctx) => <span>Σ {formatted['sum']}</span>;
// Counts are numbers: format them like the rest of the grid (20,000, not 20000).
const formatCount = (value: unknown) => Number(value).toLocaleString('en-US');
const shippedFooter = ({ values }: Ctx) => <span>{formatCount(values['trueCount'])} shipped</span>;
const shippedGroupFooter = ({ values }: Ctx) => <span>{formatCount(values['falseCount'])} open</span>;
const rowCountFooter = ({ values }: Ctx) => <span>{formatCount(values['count'])} rows</span>;
const largest = (rows: readonly Order[]) => rows.reduce((max, row) => Math.max(max, row.amount), 0);
const largestFooter = ({ formatted }: Ctx) => <span>largest {formatted['custom']}</span>;
const sumTypes = ['sum', 'average'] as const;
const minMax = ['min', 'max'] as const;
const shippedTypes = ['trueCount', 'falseCount'] as const;

export default function AggregatesDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [grouped, setGrouped] = useState(true);
  const [onlyShipped, setOnlyShipped] = useState(false);
  return (
    <>
      <div className="demo-toolbar">
        <Checkbox checked={grouped} onCheckedChange={(checked) => setGrouped(checked)}>
          Group by Country
        </Checkbox>
        <Checkbox
          checked={onlyShipped}
          onCheckedChange={(checked) => {
            setOnlyShipped(checked);
            if (checked) api.current?.filterColumn('shipped', 'equal', true);
            else api.current?.clearFiltering();
          }}
        >
          Only shipped (aggregates follow the filter)
        </Checkbox>
      </div>
      <DataGrid<Order>
        aria-label="Orders with footer, group footer and group caption aggregates"
        data={orders}
        columns={columns}
        filtering
        height={420}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        ref={api}
        grouping={{ groupBy: grouped ? ['country'] : [], showGroupedColumns: true }}
        onGroupChange={(event) => setGrouped(event.groupBy.length > 0)}
      >
        {/* Two aggregate rows; several types on one column; a custom aggregate. */}
        <DataGridAggregateRow>
          <DataGridAggregate<Order> field="amount" type={sumTypes} format="C2" renderFooter={amountFooter} renderGroupFooter={amountGroupFooter} renderGroupCaption={amountCaption} />
          <DataGridAggregate<Order> field="quantity" type={minMax} format="N0" />
          <DataGridAggregate<Order> field="shipped" type={shippedTypes} renderFooter={shippedFooter} renderGroupFooter={shippedGroupFooter} />
        </DataGridAggregateRow>
        <DataGridAggregateRow>
          <DataGridAggregate<Order> field="id" type="count" renderFooter={rowCountFooter} />
          <DataGridAggregate<Order> field="amount" type="custom" custom={largest} format="C2" renderFooter={largestFooter} />
        </DataGridAggregateRow>
      </DataGrid>
    </>
  );
}
```

## Aggregates with paging

With `paging`, the grid prop `aggregateScope` picks what the footer and the
group footers and captions summarize: `'page'` (the default)
aggregates the rows of the current page, `'all'` every row that matches the
filters. With grouping, pages count data rows and a group that spans two
pages shows its caption on both; with `'page'` its aggregates cover only the
rows on the current page.

### Live demo: Paged groups and aggregate scope

Live demo: https://salmonui.dev/demos/data-grid/paged-groups

400 orders grouped by country and paged 25 data rows at a time; `aggregateScope` switches the footer and group footers between the current page and every row.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { DataGrid, type DataGridAggregateContext, type DataGridAggregateRow, type DataGridColumn } from '@salmonui/data-grid';
import { Radio, RadioGroup } from '@salmonui/inputs/radio-group';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(400, 17);

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'product', header: 'Product', width: 150 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 230 },
];

// Module-level templates and definitions: stable across renders.
const amountFooter = ({ formatted, values }: DataGridAggregateContext<Order>) => (
  <span data-testid="amount-footer">
    {String(values['count'])} orders · Σ {formatted['sum']}
  </span>
);
const amountGroupFooter = ({ formatted, values }: DataGridAggregateContext<Order>) => (
  <span>
    {String(values['count'])} orders · Σ {formatted['sum']}
  </span>
);
const amountTypes = ['sum', 'count'] as const;
const aggregates: DataGridAggregateRow<Order>[] = [{ columns: [{ field: 'amount', type: amountTypes, format: 'C2', renderFooter: amountFooter, renderGroupFooter: amountGroupFooter }] }];
const grouping = { groupBy: ['country'], showGroupedColumns: true };
const paging = { pageSize: 25 };

export default function PagedGroupsDemo() {
  const [scope, setScope] = useState<'page' | 'all'>('page');
  return (
    <>
      <div className="demo-toolbar">
        <RadioGroup label="Aggregate scope" name="aggregate-scope" orientation="horizontal" value={scope} onValueChange={(value) => setScope(value as 'page' | 'all')}>
          <Radio value="page">Aggregate the current page</Radio>
          <Radio value="all">Aggregate every row</Radio>
        </RadioGroup>
      </div>
      <DataGrid<Order>
        aria-label="Grouped orders, 25 per page, with page-wise or whole aggregates"
        data={orders}
        columns={columns}
        grouping={grouping}
        paging={paging}
        aggregates={aggregates}
        aggregateScope={scope}
        height={420}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
      />
      <p className="demo-status">Pages count data rows; captions and footers of the groups on a page come along. Change the page and watch the footer.</p>
    </>
  );
}
```

## API reference

See [`DataGridAggregate`](https://salmonui.dev/docs/reference/data-grid/DataGridAggregate),
[`DataGridAggregateRow`](https://salmonui.dev/docs/reference/data-grid/DataGridAggregateRow)
and [`DataGridAggregateContext`](https://salmonui.dev/docs/reference/data-grid/DataGridAggregateContext)
in the API reference.
