# Filtering UI

> The member editor dialog with search, select all and a virtualized member list without a node limit, the label and value filter forms, and the onBeforeFilterChange, onFilterChange and onBeforeMemberEditorOpen events.

Canonical: https://salmonui.dev/docs/pivot-table/filtering-ui

Filters are model data: `pivotModel.filterBy[field]` holds one filter per
field, a member filter (`{ include }` or `{ exclude }`), a label filter or
a value filter. Their semantics are in
[Filtering and sorting](https://salmonui.dev/docs/pivot-table/filtering-and-sorting); this page
covers the dialog that edits them.

## Member editor

"Filter…" in a field menu (field list, axis bar) opens the member editor
for that field, a modal `dialog`:

- Include (member filter): a search box, "Select all" (indeterminate when
  some members are checked; with a search it toggles only the matching
  members) and a checkbox list of every member with its row count.
- Label filter: an operator (`equal`, `notEqual`, `contains`,
  `doesNotContain`, `startsWith`, `endsWith`, `greaterThan`, `lessThan`,
  `between`, ...) and one or two values.
- Value filter: a measure (its measure id: `field`, or `field#aggregate`
  when one field is summarized twice), an operator (`greaterThan`,
  `between`, `top`, `bottom`, ...) and one or two numbers.

OK writes the filter; an empty label or value input clears it. Checking
every member writes no filter; unchecking a few writes an `exclude` filter
so members that appear later stay visible. OK is disabled with no member
checked. Escape or Cancel closes without a change, and focus returns to the
field button. "Clear filter" in the field menu removes the filter.

```ts
pivot.setFilter('country', { include: ['Japan', 'France'] });
pivot.setFilter('product', { label: { operator: 'startsWith', value: 'B' } });
pivot.setFilter('country', { value: { measure: 'amount', operator: 'top', value: 3 } });
pivot.setFilter('country', null); // clear
```

### Large member lists

The member list is virtualized (only the visible checkboxes are mounted),
so a field with 100,000 members opens as fast as one with ten. There is no
`maxNodeLimitInMemberEditor` and no load-on-demand mode: members come from
the engine's field index, or from one `facet` request for a
[remote pivot](https://salmonui.dev/docs/pivot-table/remote-pivot).

The list is a multi-select `listbox`: ArrowUp / ArrowDown, Home / End and
PageUp / PageDown move through the members and Space checks the active one.
The three filter kinds are a radio group above it.

## Events

| Event | Payload |
| --- | --- |
| `onBeforeMemberEditorOpen` | `{ field, source }`; `preventDefault()` keeps the dialog closed |
| `onBeforeFilterChange` | `{ field, filter, previousFilter, source }`; `preventDefault()` cancels |
| `onFilterChange` | the same, after the change |

```tsx
const pivot = usePivot({
  data,
  defaultPivotModel: model,
  onBeforeMemberEditorOpen: (event) => {
    if (event.field === 'internalCode') event.preventDefault();
  },
  onBeforeFilterChange: (event) => {
    // Keep at least one region visible.
    if (event.field === 'region' && event.filter && 'include' in event.filter && event.filter.include.length === 0) event.preventDefault();
  },
});
```

A filter also fires `onBeforePivotModelChange` / `onPivotModelChange` with
`action: 'filter'` ([State and events](https://salmonui.dev/docs/pivot-table/state)).

### Live demo: Member, label and value filters

Live demo: https://salmonui.dev/demos/pivot-table/pivot-table-filtering

Include and exclude member filters, label and value (top N) filters from code and the member editor, a 2,500-member virtualized list, and the cancellable filter and member editor events.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { PivotAxisBar, PivotTable, usePivot, type PivotFilter, type PivotModelInput, type PivotFieldDefinition } from '@salmonui/pivot-table';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { NumberField } from '@salmonui/inputs/number-field';
import { TextField } from '@salmonui/inputs/text-field';

type Sale = { country: string; customer: string; product: string; year: string; amount: number };

const COUNTRIES = ['Brazil', 'Canada', 'France', 'Germany', 'India', 'Japan', 'Kenya', 'Mexico', 'Norway', 'Spain'];
const PRODUCTS = ['Bikes', 'Helmets', 'Gloves', 'Lights'];

/** 6,000 sales over 2,500 customers: a member list long enough to need virtualization. */
function makeSales(): Sale[] {
  const rows: Sale[] = [];
  for (let n = 0; n < 6000; n++) {
    rows.push({
      country: COUNTRIES[(n * 7) % COUNTRIES.length]!,
      customer: `Customer ${String((n * 37) % 2500).padStart(4, '0')}`,
      product: PRODUCTS[(n * 3) % PRODUCTS.length]!,
      year: String(2024 + (n % 3)),
      amount: ((n * 571) % 1900) + 50,
    });
  }
  return rows;
}

const SALES = makeSales();

// Captions for the headers, the axis bar and the field list (the raw field names otherwise).
const FIELDS: PivotFieldDefinition<Sale>[] = [
  { field: 'country', caption: 'Country', type: 'string' },
  { field: 'customer', caption: 'Customer', type: 'string' },
  { field: 'product', caption: 'Product', type: 'string' },
  { field: 'year', caption: 'Year', type: 'string' },
  { field: 'amount', caption: 'Amount', type: 'number' },
];

const MODEL: PivotModelInput = {
  rows: [{ field: 'country' }],
  columns: [{ field: 'year' }],
  values: [{ field: 'amount', aggregate: 'sum' }],
  filters: [{ field: 'customer' }, { field: 'product' }],
  formats: { amount: { number: { style: 'currency', currency: 'USD', maximumFractionDigits: 0 } } },
};

const describe = (filter: PivotFilter | null): string => (filter ? JSON.stringify(filter) : 'cleared');

/** Member, label and value filters from code and from the member editor, with their events. */
export default function PivotTableFilteringDemo() {
  const [text, setText] = useState('an');
  const [top, setTop] = useState(3);
  const [blockProduct, setBlockProduct] = useState(false);
  const [log, setLog] = useState<string[]>([]);
  const push = (line: string) => setLog((items) => [line, ...items].slice(0, 6));
  const pivot = usePivot<Sale>({
    data: SALES,
    fields: FIELDS,
    defaultPivotModel: MODEL,
    locale: 'en-US',
    onBeforeMemberEditorOpen: (event) => {
      if (blockProduct && event.field === 'product') {
        event.preventDefault();
        push('member editor of product refused');
      }
    },
    onBeforeFilterChange: (event) => push(`before ${event.field}: ${describe(event.filter)}`),
    onFilterChange: (event) => push(`${event.field}: ${describe(event.filter)} (${event.source})`),
  });

  return (
    <div>
      <div className="demo-toolbar" role="group" aria-label="Country filters">
        <Button variant="outline" onClick={() => pivot.setFilter('country', { include: ['France', 'Germany', 'Spain'] })}>
          Include Europe
        </Button>
        <Button variant="outline" onClick={() => pivot.setFilter('country', { exclude: ['Japan', 'India'] })}>
          Exclude Asia
        </Button>
        <label>
          Country contains
          <TextField aria-label="Country contains" value={text} onValueChange={(next) => setText(next)} style={{ inlineSize: '8em' }} />
        </label>
        <Button variant="outline" onClick={() => pivot.setFilter('country', { label: { operator: 'contains', value: text } })}>
          Label filter
        </Button>
        <label>
          Top
          <NumberField aria-label="Top" min={1} max={10} value={top} onValueChange={(next) => setTop(next || 1)} style={{ inlineSize: '6em' }} />
        </label>
        <Button variant="outline" onClick={() => pivot.setFilter('country', { value: { measure: 'amount', operator: 'top', value: top } })}>
          Top countries by amount
        </Button>
        <Button variant="outline" onClick={() => pivot.setFilter('country', { value: { measure: 'amount', operator: 'greaterThan', value: 700_000 } })}>
          Amount over 700,000
        </Button>
        <Button variant="outline" onClick={() => pivot.setFilter('country', null)}>
          Clear
        </Button>
        <Checkbox checked={blockProduct} onCheckedChange={(checked) => setBlockProduct(checked)}>
          Refuse the Product member editor
        </Checkbox>
      </div>
      <PivotAxisBar pivot={pivot} />
      <PivotTable pivot={pivot} height={300} aria-label="Sales by country with filters" />
      <div className="demo-log" aria-label="Filter events">
        {log.length ? (
          <ol>
            {log.map((line, i) => (
              <li key={`${i}-${line}`}>{line}</li>
            ))}
          </ol>
        ) : (
          'Use a button, or the filter icon of Customer, Product or Country on the axis bar.'
        )}
      </div>
    </div>
  );
}
```
