# Searching

> The toolbar search box, the search prop with its text, columns, operator and case and accent options, highlighted matches, search methods and events, and server-side search.

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

`search` turns grid search on: `true` for the defaults, or a `DataGridSearch`
object. Search keeps the rows where any searched column matches the text,
on top of the filters, and runs as a core pipeline stage.

## The search box

The toolbar item `'search'` hosts the
search box: typing searches, Escape clears it, and a search made
elsewhere is written back into the box. The box is a `role="search"`
landmark labelled by the `searchLabel` text, "Search grid" by default;
give each grid its own `aria-label` when a page has several.
Enter applies the text at once; when a search changes the rows, a live
region announces the match count ("12 rows match", `localeText.searchMatches`).
`DataGridSearchBox` renders the same box elsewhere: inside the grid's subtree
it finds the grid itself, outside it takes the grid's `api` (the grid ref).
Its `debounce` (ms, default 0) delays typed text, `aria-label` names the
landmark and `onBeforeSearch` can skip a search with `preventDefault()`.

```tsx
const [api, setApi] = useState<DataGridApi<Order> | null>(null);

<DataGridSearchBox api={api} debounce={200} aria-label="Search orders" />
<DataGrid onReady={setApi} data={orders} columns={columns} search />
```

## Options

- `search.text` is the search text. It is reactive and part of the
  server render, so a grid can render already searched.
  `onBeforeSearchChange` can cancel a change with `preventDefault()`;
  `onSearchChange` reports the `text` and the `previousText`.
- `search.fields` lists the searched columns. By default every
  searchable column except date columns is searched; a column opts out with
  `searchable: false`.
- `search.operator` is `'contains'` (the default), `'startsWith'`,
  `'endsWith'`, `'equal'`, `'notEqual'`, `'wildcard'` or `'like'`, with the
  filter operator names. `'wildcard'` matches a pattern where `*` is any run
  of characters and `?` one character (`T*o` finds "Tokyo"); `'like'` is the
  SQL form where `%` (or `*`) is any run (`%abc`, `abc%`, `%abc%`). Both
  match the whole value, and number columns match their
  digits (`1%` finds 10 and 12).
  `search.matchCase` (default `false`) makes the match case-sensitive and
  `search.ignoreAccents` folds accents, so "jose" finds "José".

`api.search(text)` searches and `api.clearSearch()` clears the search;
`api.search('')` clears it as well.

## Highlighting matches

`search.highlight: true` wraps each match of the applied search in a
`<mark class="salmon-data-grid-search-mark">` inside the displayed text of the
searched columns, without a cell template. The matches
follow the search: the operator (`contains` marks every occurrence,
`startsWith` and `endsWith` the start or the end, `equal`, `wildcard` and
`like` the whole text, `notEqual` nothing), `matchCase` and `ignoreAccents`, so with accents
ignored "jose" marks "José". Only rendered cells compute their marks, so the
cost follows the visible cells, not the row count, and with the option off
nothing is computed. `<mark>` is announced as highlighted text by screen
readers that support it; forced-colors mode uses the system `Mark` colors.
A `renderCell` template renders as given.

### Live demo: Search

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

The toolbar search box over the `search` prop, with an initial text, the operator (including `wildcard` and `like` patterns), the searched columns, case and accent switches, highlighted matches, a non-searchable column, search methods and events.

`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 DataGridSearch } from '@salmonui/data-grid';
import { Select } from '@salmonui/dropdowns/select';
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(800, 13).map((order, index) => ({ ...order, customer: NAMES[index % NAMES.length] as string }));

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'city', header: 'City', width: 130 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'product', header: 'Product', width: 150 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
  // Opted out of searching.
  { field: 'note', header: 'Note (not searchable)', width: 220, searchable: false },
];

type Operator = NonNullable<DataGridSearch['operator']>;
const FIELD_SETS: Record<string, readonly string[] | undefined> = { all: undefined, customer: ['customer'], place: ['city', 'country'] };

const OPERATOR_OPTIONS = [
  { value: 'contains', label: 'contains' },
  { value: 'startsWith', label: 'startsWith' },
  { value: 'endsWith', label: 'endsWith' },
  { value: 'equal', label: 'equal' },
  { value: 'notEqual', label: 'notEqual' },
  { value: 'wildcard', label: 'wildcard (* and ?)' },
  { value: 'like', label: 'like (%)' },
];

const COLUMNS_OPTIONS = [
  { value: 'all', label: 'Every searchable column' },
  { value: 'customer', label: 'Customer' },
  { value: 'place', label: 'City and Country' },
];

export default function SearchDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [operator, setOperator] = useState<Operator>('contains');
  const [fieldSet, setFieldSet] = useState('all');
  const [matchCase, setMatchCase] = useState(false);
  const [ignoreAccents, setIgnoreAccents] = useState(false);
  const [highlight, setHighlight] = useState(true);
  const [log, push] = useEventLog();
  const fields = FIELD_SETS[fieldSet];
  return (
    <>
      <div className="demo-toolbar">
        <label>
          Operator
          <Select aria-label="Operator" data={OPERATOR_OPTIONS} value={operator} onValueChange={(value) => value != null && setOperator(value as Operator)} />
        </label>
        <label>
          Columns
          <Select aria-label="Columns" data={COLUMNS_OPTIONS} value={fieldSet} onValueChange={(value) => value != null && setFieldSet(String(value))} />
        </label>
        <Checkbox checked={matchCase} onCheckedChange={(checked) => setMatchCase(checked)}>
          Match case
        </Checkbox>
        <Checkbox checked={ignoreAccents} onCheckedChange={(checked) => setIgnoreAccents(checked)}>
          Ignore accents
        </Checkbox>
        <Checkbox checked={highlight} onCheckedChange={(checked) => setHighlight(checked)}>
          Highlight matches
        </Checkbox>
      </div>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={() => api.current?.search('Tokyo')}>
          Search “Tokyo”
        </Button>
        <Button variant="outline" onClick={() => api.current?.clearSearch()}>
          Clear search
        </Button>
      </div>
      <DataGrid<Order>
        aria-label="Searchable orders"
        data={orders}
        columns={columns}
        toolbar={['search']}
        search={{ text: 'Lyon', operator, matchCase, ignoreAccents, highlight, ...(fields ? { fields } : {}) }}
        height={340}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        ref={api}
        onBeforeSearchChange={(event) => push(`beforeSearchChange (${event.source}): "${event.previousText}" → "${event.text}"`)}
        onSearchChange={(event) => push(`searchChange: "${event.text}"`)}
      />
      <p className="demo-status">Type in the toolbar search box; Escape clears it.</p>
      <EventLog entries={log} label="Search events" />
    </>
  );
}
```

## Server-side search

With a remote data source the search (text, fields, operator, case and
accent options) is part of every read request, next to the filters and the
page, and the server applies it. The request log of the
[server-side filtering demo](https://salmonui.dev/docs/data-grid/filtering) shows it.

## API reference

See [`DataGridSearch`](https://salmonui.dev/docs/reference/data-grid/DataGridSearch),
[`DataGridSearchBoxProps`](https://salmonui.dev/docs/reference/data-grid/DataGridSearchBoxProps)
and [`DataGridSearchChangeEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridSearchChangeEvent)
in the API reference.
