# Filtering

> The filter row, menu, checklist and Excel filter UIs, operators, initial and nested filters, case and accent matching, filter methods and server-side filtering.

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

`filtering` turns filtering on: `true` for the defaults, or a
`DataGridFiltering` object. Filtering is a core pipeline stage, so the
filter state lives in the engine and survives virtual scrolling, sorting and
grouping. A column opts out with `filterable: false`.

## Filter row

The default UI, `filtering.ui: 'row'`, is a row of labelled inputs under the
header. A plain value uses the column's default operator
(`contains` for strings, `equal` otherwise). An operator prefix picks
another one: `>=`, `<=`, `>`, `<`, `=`, `!=` or `<>`; `*` and `%` in string
text are wildcards, so `Lyo*` is a `like` condition. Escape clears
the cell. Invalid text, for example letters in a number column, marks the
input `aria-invalid` and keeps the previous filter. A filter set elsewhere
(the initial `filtering.filters`, a menu or a method) is written into the
cell with its operator prefix (`>=50`), a `between` range as `100..500`, and
the cell is marked `data-filtered`; Enter on that text keeps the condition,
also for operators without a prefix such as `startsWith`.

`filtering.showOperators` adds an operator dropdown to each cell, which
replaces the prefixes; with `between` the cell is a text input
that takes `from..to`. `filtering.trigger` decides when a cell
applies: `'enter'` (the default) on Enter, `'input'` while typing, after
`filtering.debounce` milliseconds (default 1500). A column's
`renderFilterCell(ctx)` replaces its cell, for example with a select; the
context carries the column, the applied value and operator, and `apply`,
`setValue` and `clear`.

With the filter row and paging, the pager shows the applied filters on a
line under its controls, for example "Filtered by Country: Equal Japan;
Amount: Greater than or equal 200". It lists every condition, whatever set it, flattens nested groups
and shortens an `in` list after five values; the initial filters are part
of the server render. `filtering.showStatus: false` hides it. The message
belongs to the pager: a grid without paging, a
`renderPager` template or the menu UIs show none. The text comes from the
`localeText` keys `filterStatus` (`{conditions}`), `filterStatusCondition`
(`{column}`, `{operator}`, `{value}`) and `filterStatusSeparator`.

### Live demo: Filter row

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

A filter row with operator prefixes and wildcards, an operator dropdown, Enter or while-typing triggers, case and accent switches, a cell template, a lookup column filtered by its display text, initial and nested AND/OR filters, filter methods and a non-filterable column.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Select } from '@salmonui/dropdowns/select';
import { DataGrid, type DataGridApi, type DataGridColumn, type DataGridFilter, type DataGridFilterContext } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

// Customer names with accents and case variants, to show `matchCase` and `ignoreAccents`.
const NAMES = ['José Álvarez', 'Zoë Laurent', 'Chloé Dubois', 'jose alvarez', 'Renée Roy', 'André Silva', 'Noël Martin', 'Ana Muñoz'];
const orders: Order[] = createOrders(600, 5).map((order, index) => ({ ...order, customer: NAMES[index % NAMES.length] as string }));

const COUNTRIES = ['France', 'Germany', 'Japan', 'Malaysia', 'Portugal'];
// `all` stands for "no filter"; every other option is a country.
const COUNTRY_OPTIONS = [{ value: 'all', label: 'All' }, ...COUNTRIES.map((country) => ({ value: country, label: country }))];

/** Filter row cell template (`renderFilterCell`): a select instead of the text input. */
function CountryFilterCell(ctx: DataGridFilterContext<Order>) {
  return (
    <Select
      aria-label="Filter Country"
      data={COUNTRY_OPTIONS}
      value={typeof ctx.value === 'string' ? ctx.value : 'all'}
      onValueChange={(value) => (value == null || value === 'all' ? ctx.clear() : ctx.apply(String(value)))}
      style={{ inlineSize: '100%' }}
    />
  );
}

// Lookup column: rows hold the category key; the grid shows, and filters by, the name.
const CATEGORIES = [
  { id: 'Coffee', name: 'Coffee beans' },
  { id: 'Tea', name: 'Loose tea' },
  { id: 'Equipment', name: 'Brewing equipment' },
];

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 150 },
  // Filters are keyed by column id: this column's id is `place`, its field `city`.
  { id: 'place', field: 'city', header: 'City', width: 130 },
  { field: 'country', header: 'Country', width: 130, filter: { operator: 'equal' }, renderFilterCell: CountryFilterCell },
  { field: 'category', header: 'Category', width: 150, lookup: { data: CATEGORIES, keyField: 'id', displayField: 'name' } },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
  { field: 'shipped', header: 'Shipped', type: 'boolean', displayAsCheckbox: true, align: 'center', width: 100 },
  { field: 'note', header: 'Note (not filterable)', width: 200, filterable: false },
];

const initialFilters: readonly DataGridFilter[] = [{ field: 'amount', operator: 'greaterThanOrEqual', value: 50 }];
// Nested group: (Japan OR amount > 1,000) AND not shipped. The group's `logic`
// combines its members.
const nested: readonly DataGridFilter[] = [
  {
    logic: 'or',
    filters: [
      { field: 'country', operator: 'equal', value: 'Japan' },
      { field: 'amount', operator: 'greaterThan', value: 1000 },
    ],
  },
  { field: 'shipped', operator: 'equal', value: false },
];

const describe = (filters: readonly DataGridFilter[]): string =>
  filters.length === 0
    ? 'none'
    : filters.map((f) => ('filters' in f ? `(${f.filters.map((m) => describe([m])).join(` ${f.logic} `)})` : `${f.logic === 'or' ? 'or ' : ''}${f.field} ${f.operator} ${JSON.stringify(f.value)}`)).join('; ');

export default function FilterRowDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [filters, setFilters] = useState<readonly DataGridFilter[]>(initialFilters);
  const [matchCase, setMatchCase] = useState(false);
  const [ignoreAccents, setIgnoreAccents] = useState(false);
  const [showOperators, setShowOperators] = useState(false);
  const [typing, setTyping] = useState(false);
  const [log, push] = useEventLog();
  return (
    <>
      <div className="demo-toolbar">
        <Checkbox checked={matchCase} onCheckedChange={(checked) => setMatchCase(checked)}>
          Match case
        </Checkbox>
        <Checkbox checked={ignoreAccents} onCheckedChange={(checked) => setIgnoreAccents(checked)}>
          Ignore accents
        </Checkbox>
        <Checkbox checked={showOperators} onCheckedChange={(checked) => setShowOperators(checked)}>
          Show operators
        </Checkbox>
        <Checkbox checked={typing} onCheckedChange={(checked) => setTyping(checked)}>
          Filter while typing (300 ms)
        </Checkbox>
      </div>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={() => api.current?.filterColumn('amount', 'between', [100, 500])}>
          Amount between 100 and 500
        </Button>
        <Button variant="outline" onClick={() => api.current?.filterColumn('place', 'in', ['Lyon', 'Osaka'])}>
          City in Lyon, Osaka
        </Button>
        <Button variant="outline" onClick={() => setFilters(nested)}>
          (Japan or over 1,000) and not shipped
        </Button>
        <Button variant="outline" onClick={() => api.current?.removeFilter('amount')}>
          Remove Amount filter
        </Button>
        <Button variant="outline" onClick={() => api.current?.clearFiltering()}>
          Clear filters
        </Button>
      </div>
      <DataGrid<Order>
        aria-label="Orders with a filter row"
        data={orders}
        columns={columns}
        filtering={{ ui: 'row', filters, matchCase, ignoreAccents, showOperators, trigger: typing ? 'input' : 'enter', debounce: 300 }}
        sorting
        height={360}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        ref={api}
        onFilterChange={(event) => {
          setFilters(event.filters);
          push(`filterChange (${event.source}${event.field ? `, ${event.field}` : ''}): ${describe(event.filters)}`);
        }}
      />
      <p className="demo-status">Type in the filter row and press Enter: <code>&gt;=500</code>, <code>!=France</code> and <code>Lyo*</code> pick other operators.</p>
      <EventLog entries={log} label="Filter changes" />
    </>
  );
}
```

## Filter menus

`filtering.ui: 'menu'` puts a filter button in each header that opens a
filter dialog with an operator and a typed value.
`'checklist'` lists the column's distinct values with checkboxes,
and `'excel'` combines the checklist with a custom filter of up to two
conditions joined by And or Or. Alt+↓ on a focused header opens
the dialog; Escape closes it and returns focus to the header. A column's
`filter.ui` overrides the grid-wide UI, and
`filtering.headerButton: false` hides the header buttons when the dialogs
are opened only from the column menu or `api.openFilterMenu(field)`.

```tsx
<DataGrid
  data={orders}
  columns={[
    { field: 'customer', header: 'Customer' },
    { field: 'country', header: 'Country', filter: { ui: 'checklist' } },
    { field: 'amount', header: 'Amount', type: 'number', filter: { operator: 'greaterThanOrEqual' } },
  ]}
  filtering={{ ui: 'excel', filters: [{ field: 'country', operator: 'in', value: ['Japan', 'France'] }] }}
  onFilterChange={(event) => console.log(event.filters)}
/>
```

The value editors follow the column type: text, number (with From and To
for `between`), date, date and time, and a true/false select for booleans.
A column's `filter.editorProps` passes attributes such as `min`,
`max` and `placeholder` to the built-in editors, and `renderFilter(ctx)`
replaces the value editor with your own, for example a dropdown.

The checklist has a search box that narrows the list, a Select All
checkbox with a mixed state, one Blanks entry for empty and missing values,
and the row count of each value. The counts exclude the column's own filter,
so unchecked values stay listed. The list requests
`filtering.checklistPageSize` values at a time (default 100) and the next
batch as it scrolls to its end; `filtering.checklistInfiniteScroll:
false` requests every value at once. The list is virtualized either
way, and Select All or a single toggle applies to values that are not loaded
yet. Custom filter UIs read the same distinct values and counts with
`getColumnFacet(field, options)`.

### Live demo: Filter menus

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

Menu, checklist and Excel filter UIs with typed value editors, a per-column UI and operator list, a custom menu editor, a custom filter comparer, checklist search, Select All, blanks and counts, and a checklist that loads 50 values at a time, plus the filter menu open events with a cancellable before-event.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, type DataGridColumn, type DataGridFilterContext, type DataGridFilterUi, type DataGridFiltering } from '@salmonui/data-grid';
import { Select } from '@salmonui/dropdowns/select';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(600, 8);

const FILTER_UIS = [
  { value: 'menu', label: 'Menu' },
  { value: 'checklist', label: 'Checklist' },
  { value: 'excel', label: 'Excel' },
];

/** Menu value editor template (`renderFilter`): a dropdown of the categories. */
function CategoryFilter(ctx: DataGridFilterContext<Order>) {
  return (
    <select className="salmon-data-grid-input" style={{ inlineSize: '100%' }} aria-label="Category value" value={typeof ctx.value === 'string' ? ctx.value : ''} onChange={(event) => ctx.setValue(event.target.value)}>
      <option value="">Any category</option>
      <option value="Coffee">Coffee</option>
      <option value="Tea">Tea</option>
      <option value="Equipment">Equipment</option>
    </select>
  );
}

/** Lower case without spaces or hyphens: "bao-nguyen" and "Bao Nguyen" compare equal. */
const squash = (value: unknown): string => String(value ?? '').toLowerCase().replace(/[\s-]+/g, '');

/**
 * Custom filter comparer (`filterComparator`): decides each built-in
 * operator on the squashed text. It runs once per distinct name, not per row.
 */
const nameComparator: NonNullable<DataGridColumn<Order>['filterComparator']> = (value, filterValue, operator) => {
  const cell = squash(value);
  // The checklist sends `in` / `notIn` with the checked values.
  if (operator === 'in' || operator === 'notIn') {
    const hit = (Array.isArray(filterValue) ? filterValue : [filterValue]).some((v) => squash(v) === cell);
    return operator === 'in' ? hit : !hit;
  }
  const text = squash(filterValue);
  switch (operator) {
    case 'contains':
      return cell.includes(text);
    case 'doesNotContain':
      return !cell.includes(text);
    case 'startsWith':
      return cell.startsWith(text);
    case 'endsWith':
      return cell.endsWith(text);
    case 'notEqual':
      return cell !== text;
    case 'isEmpty':
      return cell === '';
    case 'isNotEmpty':
      return cell !== '';
    default:
      return cell === text;
  }
};

const columns: DataGridColumn<Order>[] = [
  // 600 distinct values: the checklist loads 50 at a time as it scrolls.
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  // Custom comparer: "baonguyen" or "bao-nguyen" finds "Bao Nguyen".
  { field: 'customer', header: 'Customer', width: 140, filterComparator: nameComparator },
  // Per-column UI: always a checklist, whatever `filtering.ui` says.
  { field: 'country', header: 'Country', width: 120, filter: { ui: 'checklist' } },
  { field: 'category', header: 'Category', width: 120, filter: { operator: 'equal' }, renderFilter: CategoryFilter },
  // Per-column operators and editor attributes.
  { field: 'quantity', header: 'Qty', type: 'number', align: 'end', width: 80, filter: { operators: ['equal', 'greaterThan', 'lessThan', 'between'], editorProps: { min: 1, max: 12, step: 1 } } },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
  { field: 'placed', header: 'Placed', type: 'date', format: 'yMMMd', width: 130 },
  { id: 'placedAt', field: 'placed', header: 'Placed at', type: 'datetime', format: 'yMMMdHm', width: 190 },
  { field: 'shipped', header: 'Shipped', type: 'boolean', displayAsCheckbox: true, align: 'center', width: 120 },
  // Most notes are empty: the checklist lists them as one Blanks entry.
  { field: 'note', header: 'Note', width: 200 },
];

// String columns offer these operators, in this order (the first is the default).
const operators: NonNullable<DataGridFiltering['operators']> = { string: ['contains', 'startsWith', 'endsWith', 'equal', 'notEqual', 'like', 'isEmpty', 'isNotEmpty'] };

export default function FilterMenusDemo() {
  const [ui, setUi] = useState<DataGridFilterUi>('excel');
  const [blockNote, setBlockNote] = useState(false);
  const [log, push] = useEventLog();
  return (
    <>
      <div className="demo-toolbar">
        <label>
          Filter UI{' '}
          <Select aria-label="Filter UI" data={FILTER_UIS} value={ui} onValueChange={(value) => value != null && setUi(value as DataGridFilterUi)} />
        </label>
        <Checkbox checked={blockNote} onCheckedChange={(checked) => setBlockNote(checked)}>
          Cancel the Note filter menu
        </Checkbox>
      </div>
      <DataGrid<Order>
        aria-label="Orders with filter menus"
        data={orders}
        columns={columns}
        filtering={{ ui, operators, checklistPageSize: 50 }}
        height={380}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        // Menu open events: the before-event can cancel the opening.
        onBeforeFilterMenuOpen={(event) => {
          if (blockNote && event.field === 'note') {
            event.preventDefault();
            push(`beforeFilterMenuOpen (${event.field}, ${event.ui}, ${event.dialog}): prevented`);
            return;
          }
          push(`beforeFilterMenuOpen (${event.field}, ${event.ui}, ${event.dialog})`);
        }}
        onFilterMenuOpen={(event) => push(`filterMenuOpen (${event.field}, ${event.ui}, ${event.dialog})`)}
        onFilterChange={(event) => push(`filterChange (${event.field ?? 'all'}): ${JSON.stringify(event.filters)}`)}
      />
      <p className="demo-status">Open a header&apos;s filter button, or focus a header and press Alt+↓.</p>
      <EventLog entries={log} label="Filter events" />
    </>
  );
}
```

## Operators

String columns offer `contains`, `startsWith`, `endsWith`,
`doesNotContain`, `doesNotStartWith`, `doesNotEndWith`, `isEmpty` and
`isNotEmpty`. Every type has `equal` and `notEqual`;
numbers and dates add `greaterThan`, `greaterThanOrEqual`, `lessThan`,
`lessThanOrEqual` and `between` with a `[from, to]` value. `isNull`,
`isNotNull`, `in` and `notIn` (with an array value) work on every type,
and `like` (with `%` and `*`) and `wildcard` match patterns.
The core also accepts the lowercase spellings (`startswith`).

`filtering.operators` sets the operators offered per column type, in order,
with the first as the default; a column's `filter.operators` overrides it
for that column and `filter.operator` sets its default.

## Custom comparer

A column's `filterComparator(value, filterValue, operator)` replaces the
built-in test for every built-in operator on that column. It
receives the raw cell value, the condition's value
(an array for `between`, `in` and `notIn`) and the operator in its camelCase
name, and returns `true` when the cell matches. The comparator owns the
comparison, so `matchCase` and `ignoreAccents` are not applied to its
inputs. It runs once per distinct cell value, not once per row, so it must
not read other fields of the row; a longer value never narrows the previous
result. Columns without a comparator keep the built-in path. The comparator
runs on local data only: a remote source receives the condition as usual.
Custom operators registered with the filter module keep their own function.

```tsx
const squash = (v: unknown) => String(v ?? '').toLowerCase().replace(/[\s-]+/g, '');
const columns: DataGridColumn<Order>[] = [
  {
    field: 'customer',
    filterComparator: (value, filterValue, operator) =>
      operator === 'contains' ? squash(value).includes(squash(filterValue)) : squash(value) === squash(filterValue),
  },
];
```

## Filter state and methods

`filtering.filters` holds the active filters as `DataGridFilter[]`: conditions
`{ field, operator, value, logic, matchCase, ignoreAccents }` and nested
groups `{ logic, filters }`. A group's `logic` combines its
members: `(A OR B) AND C` is
`[{ logic: 'or', filters: [A, B] }, C]`, and groups nest; `not: true`
negates a group. A condition's
`logic` (default `'and'`) joins it to the previous condition on the same
column at the top level; inside a group it is ignored. Top-level columns
and groups are ANDed. The prop is reactive: a new value replaces the filters, and the
initial value is part of the server render. `onBeforeFilterChange` can
cancel a change with `preventDefault()`; `onFilterChange` reports the
applied `filters`, the `previousFilters` and the `field`.

`field` in a condition is the column id (its `id`, else its `field`), so two
columns over the same field filter independently.

`api.filterColumn(field, operator, value, { logic, matchCase, ignoreAccents })`
replaces a column's conditions; an array value with a single-value operator
ORs one condition per value. `clearFiltering(fields?)` removes the
filters of the given columns or all of them, and `removeFilter(field)`
removes one column's filters.
`getFilteredRows()` returns the rows that pass the search and every filter,
in sort order and across every page. It is synchronous and returns the same array while the rows,
filters and sort are unchanged. With a remote source that filters, the
server holds the filtered rows, so `getFilteredRows()` returns the rows the
grid loaded: the current page when the server pages, every filtered row
when it does not. To get every filtered row of a server-paged source,
read them from your data source with the current query.

### Live demo: Filter status and filtered rows

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

The pager's filter status message for the filter row (on by default, switchable with filtering.showStatus) and getFilteredRows() reading the filtered rows across every page.

`Demo.tsx`:

```tsx
'use client';

import { useMemo, useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, type DataGridApi, type DataGridColumn, type DataGridFilter, type DataGridFiltering } from '@salmonui/data-grid';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(500, 11);

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

// Initial filters: part of the server render, so the pager status is too.
const initialFilters: readonly DataGridFilter[] = [
  { field: 'country', operator: 'equal', value: 'Japan' },
  { field: 'amount', operator: 'greaterThanOrEqual', value: 200 },
];
const paging = { pageSize: 10 };

export default function FilterStatusDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [filters, setFilters] = useState<readonly DataGridFilter[]>(initialFilters);
  const [showStatus, setShowStatus] = useState(true);
  const [summary, setSummary] = useState('');
  const filtering = useMemo<DataGridFiltering>(() => ({ ui: 'row', filters, showStatus }), [filters, showStatus]);
  // getFilteredRows: every row passing the filters, in sort order, across every page.
  const readFilteredRows = (): void => {
    const rows = api.current?.getFilteredRows() ?? [];
    const total = rows.reduce((sum, row) => sum + row.amount, 0);
    const first = rows.slice(0, 3).map((row) => row.id).join(', ') || 'none';
    setSummary(`getFilteredRows(): ${rows.length} rows, total amount ${total.toFixed(2)}, first ${first}`);
  };
  return (
    <>
      <div className="demo-toolbar">
        <Checkbox checked={showStatus} onCheckedChange={(checked) => setShowStatus(checked)}>
          Show filter status
        </Checkbox>
        <Button variant="outline" onClick={readFilteredRows}>
          Read filtered rows
        </Button>
        <Button variant="outline" onClick={() => api.current?.clearFiltering()}>
          Clear filters
        </Button>
      </div>
      <DataGrid<Order>
        aria-label="Orders with a filter status in the pager"
        data={orders}
        columns={columns}
        filtering={filtering}
        paging={paging}
        sorting
        height={360}
        locale="en-US"
        currency="USD"
        ref={api}
        onFilterChange={(event) => setFilters(event.filters)}
      />
      <p className="demo-status" data-testid="filtered-rows">
        {summary || 'Filter in the row (press Enter), then read the filtered rows.'}
      </p>
    </>
  );
}
```

## Filter builder

`filtering.builder` adds an advanced filter builder: a dialog that edits the whole filter tree as
nested AND/OR groups of conditions. Each group has an And / Or choice,
Add condition, Add group and (below the root) Remove group buttons; each
condition picks a field, an operator from the column's list and a typed
value. OK applies the tree as one filter change, Clear empties the draft
and Cancel or Escape closes the dialog without applying. The dialog is
modal: Tab stays inside it, and focus returns to the toolbar button or the
grid on close.

There is no second rule model: the builder reads and writes
`filtering.filters`, so the groups it builds are the `DataGridFilter` groups
above and the filter row or menus keep working on the same state. Open it
with the `'filterBuilder'` toolbar item or `api.openFilterBuilder()`, and
close it with `api.closeFilterBuilder()`. The field list offers the
filterable visible columns; `builder: { includeHidden: true }` adds the
hidden ones.
`onBeforeFilterBuilderOpen` receives the applied `filters` and cancels the
opening with `preventDefault()`; the applied change reports through
`onBeforeFilterChange` / `onFilterChange` with `ui: 'builder'`.

The dialog code is a lazy chunk: a grid without `filtering.builder` never
downloads it, and one with it preloads the chunk after mount.

The builder edits the same `filtering.filters` tree (`DataGridFilter[]`)
as every other filter UI, so there is no separate rule API: read the
applied tree from `onFilterChange`, `onBeforeFilterBuilderOpen` or
`getState().filters`, clear it with `clearFiltering()`, and open or close
the dialog with `openFilterBuilder()` / `closeFilterBuilder()`.
| `advancedFilterComplete` | `onFilterChange` with `ui: 'builder'` |

### Live demo: Filter builder

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

The advanced filter builder dialog over nested AND/OR filter groups, opened from the toolbar item or `api.openFilterBuilder()`, with hidden columns offered through `includeHidden`, a cancellable `onBeforeFilterBuilderOpen` and filter events reporting `ui: 'builder'`.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, type DataGridApi, type DataGridColumn, type DataGridFilter } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(800, 21);

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 140 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'category', header: 'Category', width: 120 },
  { field: 'quantity', header: 'Qty', type: 'number', align: 'end', width: 80 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
  { field: 'placed', header: 'Placed', type: 'date', format: 'yMMMd', width: 130 },
  { field: 'shipped', header: 'Shipped', type: 'boolean', displayAsCheckbox: true, align: 'center', width: 120 },
  // Hidden: offered by the builder only with `includeHidden`.
  { field: 'priority', header: 'Priority', width: 100, hidden: true },
];

// The rule is the nested `DataGridFilter` groups: (Country = Japan OR Country = Malaysia) AND Amount > 100.
const initial: readonly DataGridFilter[] = [
  { logic: 'or', filters: [{ field: 'country', operator: 'equal', value: 'Japan' }, { field: 'country', operator: 'equal', value: 'Malaysia' }] },
  { field: 'amount', operator: 'greaterThan', value: 100 },
];

/** Compact text of a filter tree for the log. */
function describe(filters: readonly DataGridFilter[]): string {
  const one = (f: DataGridFilter): string =>
    'filters' in f ? `(${f.filters.map(one).join(` ${f.logic.toUpperCase()} `)})` : `${f.field} ${f.operator} ${JSON.stringify(f.value ?? null)}`;
  return filters.length ? filters.map(one).join(' AND ') : 'no filters';
}

export default function FilterBuilderDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [includeHidden, setIncludeHidden] = useState(false);
  const [cancelOpen, setCancelOpen] = useState(false);
  const [rows, setRows] = useState<number | null>(null);
  const [log, push] = useEventLog();
  return (
    <>
      <div className="demo-toolbar">
        <Button variant="outline" type="button" onClick={() => api.current?.openFilterBuilder()}>
          Open through the API
        </Button>
        <Checkbox checked={includeHidden} onCheckedChange={(checked) => setIncludeHidden(checked)}>
          Offer hidden columns
        </Checkbox>
        <Checkbox checked={cancelOpen} onCheckedChange={(checked) => setCancelOpen(checked)}>
          Cancel opening
        </Checkbox>
        <Button variant="outline" type="button" onClick={() => api.current?.clearFiltering()}>
          Clear filters
        </Button>
        <output aria-label="Filtered rows">{rows === null ? '' : `${rows} rows`}</output>
      </div>
      <DataGrid<Order>
        aria-label="Orders with a filter builder"
        data={orders}
        columns={columns}
        filtering={{ ui: 'menu', builder: { includeHidden }, filters: initial }}
        toolbar={['filterBuilder']}
        height={380}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        ref={api}
        onBeforeFilterBuilderOpen={(event) => {
          push(`builder open (${event.source}): ${describe(event.filters)}${cancelOpen ? ' - cancelled' : ''}`);
          if (cancelOpen) event.preventDefault();
        }}
        onFilterChange={(event) => {
          push(`filter change (${event.ui ?? 'other'}, ${event.source}): ${describe(event.filters)}`);
          setRows(api.current?.getFilteredRows().length ?? null);
        }}
      />
      <EventLog entries={log} />
    </>
  );
}
```

## Lookup columns

A lookup column filters by its display text, not by the key stored in the
row: typing "loose" in the demo's Category cell finds the rows whose
key is `Tea`, and the checklist lists the names. See
[Lookup columns](https://salmonui.dev/docs/data-grid/lookup-columns).

## Case and accents

Matching ignores case by default; `filtering.matchCase` makes it
case-sensitive and a condition's `matchCase` overrides it.
`filtering.ignoreAccents` folds accents before comparing, so "jose" matches
"José"; a condition's `ignoreAccents` overrides it.

## Server-side filtering

With a remote data source the filters, including nested groups, are part of
every read request; the server applies them, and the grid shows its
result. The demo's request log shows the wire query as the filter
row, the toolbar search and the pager change.

The `checklist` and `excel` UIs read their values from the server too.
The core computes facets over local rows only, so
`getColumnFacet` answers `status: 'unavailable'` for a remote source that
filters; the filter dialog then asks the data source with
`read({ facet: { columnId, search, limit } })`. The request carries the
current query, the server counts each value over the rows that pass the
search and every other column's filter, and answers `facet` with the
entries sorted by label and `complete: false` when `limit` cut the list.
The dialog requests `filtering.checklistPageSize` values first and raises
the limit by a page as the list scrolls to its end; typing in its search box
sends a narrowed request after 250 ms, each request aborts the previous one,
and closing the dialog aborts the last. OK with values that are not loaded
yet sends one more facet request for every value before applying. A source
without `capabilities.facets` shows "Filter is not available".
While the first values load, the dialog shows placeholder value rows;
`filtering.loadingIndicator: 'spinner'` shows a spinner instead.
Both are one
`role="status"` element with the "Loading…" text for assistive technology.
`createJsonDataSource` and the reference handler support facets; the
demo's Customer column uses an Excel filter over the remote source.

### Live demo: Server-side filtering and search

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

A remote JSON source receiving the filter row (with an initial nested AND/OR group), the toolbar search and the page in one request, and an Excel filter whose values come from paged, searchable facet requests (with a skeleton or spinner while they load); the request log shows the wire query.

`Demo.tsx`:

```tsx
'use client';

import { useMemo, useState } from 'react';
import { createJsonDataSource, type WireReadRequest } from '@salmonui/data';
import { DataGrid, type DataGridColumn, type DataGridFiltering } from '@salmonui/data-grid';
import { Select } from '@salmonui/dropdowns/select';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { demoFetch, type RemoteOrder } from '../../lib/remote';

const columns: DataGridColumn<RemoteOrder>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  // An Excel filter over a remote source: its values come from facet requests.
  { field: 'customer', header: 'Customer', width: 150, filter: { ui: 'excel' } },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'product', header: 'Product', width: 140 },
  { field: 'quantity', header: 'Qty', type: 'number', align: 'end', width: 80 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
];

// Initial filters with a nested OR group: (Japan OR Malaysia) AND amount >= 100.
// They are part of the first request; constants (the options props are reactive).
const filtering: DataGridFiltering = {
  ui: 'row',
  // Checklist values load 4 at a time (the next 4 as the list scrolls).
  checklistPageSize: 4,
  filters: [
    {
      logic: 'or',
      filters: [
        { field: 'country', operator: 'equal', value: 'Japan' },
        { field: 'country', operator: 'equal', value: 'Malaysia' },
      ],
    },
    { field: 'amount', operator: 'greaterThanOrEqual', value: 100 },
  ],
};
const paging = { pageSize: 20 };
type LoadingIndicator = NonNullable<DataGridFiltering['loadingIndicator']>;
const INDICATORS = [
  { value: 'skeleton', label: 'Skeleton' },
  { value: 'spinner', label: 'Spinner' },
];

/** The query part of a read request, as sent on the wire. */
function describe(request: WireReadRequest): string {
  const { where, search, page } = request.query;
  return JSON.stringify({ where, search, page });
}

export default function RemoteQueryDemo() {
  const [log, push] = useEventLog();
  // filtering.loadingIndicator: what the Excel filter shows while its values load.
  const [indicator, setIndicator] = useState<LoadingIndicator>('skeleton');
  // Same `filters` array: a new indicator does not re-apply the filters.
  const options = useMemo<DataGridFiltering>(() => ({ ...filtering, loadingIndicator: indicator }), [indicator]);
  // Created once per mounted grid (data sources are initial-only).
  const [source] = useState(() =>
    createJsonDataSource<RemoteOrder>({
      url: '/api/orders?delay=120',
      fetch: demoFetch,
      key: 'id',
      onRequest: (event) => {
        if (event.kind === 'facet') push(`facet: ${JSON.stringify((event.request as WireReadRequest).facet)}`);
        else if ('query' in event.request) push(`${event.kind}: ${describe(event.request)}`);
      },
    }),
  );
  return (
    <>
      <div className="demo-toolbar">
        <label>
          Filter values loading{' '}
          <Select aria-label="Filter values loading" data={INDICATORS} value={indicator} onValueChange={(value) => value != null && setIndicator(value as LoadingIndicator)} />
        </label>
      </div>
      <DataGrid<RemoteOrder>
        aria-label="Remote orders filtered and searched on the server"
        data={source}
        columns={columns}
        filtering={options}
        search
        toolbar={['search']}
        paging={paging}
        height={360}
        locale="en-US"
        currency="USD"
      />
      <p className="demo-status">Filter, search or page: each change is one request carrying the whole query.</p>
      <EventLog entries={log} label="Requests" />
    </>
  );
}
```

## Filter events

`onBeforeFilterChange` / `onFilterChange` report every filter change, from
the UI or a method (see above). The filter dialogs have their own pair:
`onBeforeFilterMenuOpen` fires before a menu, checklist or Excel dialog
opens and cancels the opening with `preventDefault()`; `onFilterMenuOpen`
fires once the dialog rendered. Both receive `{ field, ui, dialog }`: `ui`
is the dialog's filter UI (`'menu'`, `'checklist'` or `'excel'`) and
`dialog` is `'menu'` for the dialog itself or `'custom'` when the Excel
filter's custom-condition section opens. The filter menus demo above logs both
events and can cancel the Note column's menu.

## API reference

See [`DataGridFiltering`](https://salmonui.dev/docs/reference/data-grid/DataGridFiltering),
[`DataGridColumnFilter`](https://salmonui.dev/docs/reference/data-grid/DataGridColumnFilter),
[`DataGridFilterCondition`](https://salmonui.dev/docs/reference/data-grid/DataGridFilterCondition),
[`DataGridFilterGroup`](https://salmonui.dev/docs/reference/data-grid/DataGridFilterGroup),
[`DataGridFilterContext`](https://salmonui.dev/docs/reference/data-grid/DataGridFilterContext)
and [`DataGridFilterChangeEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridFilterChangeEvent)
in the API reference.
