# Column chooser

> A searchable dialog that shows and hides columns, opened from the toolbar, the column menu or the API.

Canonical: https://salmonui.dev/docs/data-grid/column-chooser

The column chooser lists the columns with a checkbox each. It
opens from the toolbar `'columnChooser'` item, anchored below the button,
from the `columnChooser` column menu item, or from
`api.openColumnChooser()`. Called with a viewport point,
`api.openColumnChooser({ x, y })` opens it there; without one it opens at
the start of the grid. `columnChooser={false}` drops the `columnChooser`
item from the column menu and disables the toolbar item.

## Search

A search box above the list narrows the columns by header text.
`columnChooser={{ searchOperator }}` picks the match: `'contains'`
(default), `'startsWith'`, `'endsWith'` or `'equal'`. `searchable: false` removes the
box (`enableSearching`), `ignoreAccents: true` folds diacritics so
`categorie` finds "Catégorie" (`ignoreAccent`), and `debounce` delays the
filtering while typing (`immediateModeDelay`; Enter applies at once).

## Applying changes

In the default `mode: 'confirm'` the checkboxes are a draft: OK applies the
changes and Cancel discards them. `mode: 'immediate'`
applies every toggle at once. Either way the grid raises the cancelable
`onBeforeColumnVisibilityChange` and then `onColumnVisibilityChange` with
the hidden and shown columns, and `onBeforeColumnChooserOpen` fires before
the chooser opens with the listed `columns` (call `preventDefault()` to
keep it closed). The chooser is a labelled `role="dialog"`: focus
moves into it, Escape closes it and returns focus to the element that
opened it.

A column with `hideable: false` is left out of the list, so the chooser can
never hide it. Under
stacked headers the list is an indented tree of the groups and their
leaves; a group checkbox toggles all of its leaves.

### Live demo: Column chooser

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

The column chooser opened from the toolbar item, from `api.openColumnChooser()` or at a viewport point, with a search box, a configurable `searchOperator`, the `confirm` and `immediate` modes, and a column kept out of the list with `hideable: false`.

`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 DataGridColumnChooser } 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(1_000, 13);

const columns: DataGridColumn<Order>[] = [
  // `hideable: false` keeps a column out of the chooser.
  { field: 'id', header: 'Order', primaryKey: true, width: 110, hideable: false },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'city', header: 'City', width: 130 },
  { field: 'product', header: 'Product', width: 150 },
  { field: 'category', header: 'Category', width: 120 },
  { field: 'quantity', header: 'Quantity', type: 'number', align: 'end', width: 100 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
  { field: 'priority', header: 'Priority', width: 100, hidden: true },
  { field: 'note', header: 'Note', width: 200, hidden: true },
];

const operators = ['contains', 'startsWith', 'endsWith', 'equal'] as const;
const OPERATOR_OPTIONS = operators.map((op) => ({ value: op, label: op }));

export default function ColumnChooserDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [operator, setOperator] = useState<(typeof operators)[number]>('contains');
  const [immediate, setApplyImmediately] = useState(false);
  const [log, push] = useEventLog();
  const columnChooser = useMemo<DataGridColumnChooser>(() => ({ searchOperator: operator, mode: immediate ? 'immediate' : 'confirm' }), [operator, immediate]);
  return (
    <>
      <div className="demo-toolbar">
        <label>
          Search operator
          <Select aria-label="Search operator" data={OPERATOR_OPTIONS} value={operator} onValueChange={(value) => value != null && setOperator(value as (typeof operators)[number])} />
        </label>
        <Checkbox checked={immediate} onCheckedChange={(checked) => setApplyImmediately(checked)}>
          Apply every toggle immediately
        </Checkbox>
        <Button variant="outline" onClick={() => api.current?.openColumnChooser()}>
          Open through the API
        </Button>
        <Button variant="outline" onClick={(event) => api.current?.openColumnChooser({ x: event.clientX, y: event.clientY })}>
          Open at the pointer
        </Button>
      </div>
      <DataGrid<Order>
        aria-label="Orders with a column chooser"
        data={orders}
        columns={columns}
        columnChooser={columnChooser}
        toolbar={['columnChooser']}
        height={380}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        ref={api}
        onBeforeColumnChooserOpen={(event) => push(`chooser open (${event.source}): ${event.columns.length} columns`)}
        onColumnVisibilityChange={(event) => push(`visibility (${event.source}): hidden ${event.hidden.join(', ') || '-'}; shown ${event.shown.join(', ') || '-'}`)}
      />
      <EventLog entries={log} />
    </>
  );
}
```

## Templates

`renderHeader` adds content above the search box and `renderFooter`
replaces the OK / Cancel buttons; `renderChooser` replaces the search box
and the list.
Each receives the listed `columns` (`field`, `header`, draft `hidden`,
`matches`, and the public `column` view), the `searchText` and
`setSearchText(text)`, `setHidden(fields, hidden)`, `apply()`, `close()`,
and `defaultContent`
(the built-in part it replaces), so a template can decorate the built-in UI
instead of rebuilding it.

### Live demo: Column chooser templates

Live demo: https://salmonui.dev/demos/data-grid/column-chooser-templates

The toolbar column chooser with stacked header groups, accent-insensitive debounced search, a header line, a custom footer action, and `openColumnChooser({ x, y })`.

`Demo.tsx`:

```tsx
'use client';

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

const orders = createOrders(1_000, 5);

const columns: DataGridColumn<Order>[] = [
  // Not listed in the chooser: the key column stays visible.
  { field: 'id', header: 'Order', primaryKey: true, width: 120, hideable: false },
  { field: 'customer', header: 'Client', width: 150 },
  {
    id: 'region',
    header: 'Région',
    columns: [
      { field: 'country', header: 'Pays', width: 120 },
      { field: 'city', header: 'Ville', width: 120 },
    ],
  },
  { field: 'product', header: 'Produit', width: 140 },
  { field: 'category', header: 'Catégorie', width: 120, hidden: true },
  { field: 'quantity', header: 'Quantité', type: 'number', align: 'end', width: 100 },
  { field: 'unitPrice', header: 'Prix unitaire', type: 'number', format: 'C2', align: 'end', width: 130, hidden: true },
  { field: 'amount', header: 'Montant', type: 'number', format: 'C2', align: 'end', width: 120 },
  { field: 'placed', header: 'Commandé', type: 'date', format: 'yMMMd', width: 130 },
  { field: 'note', header: 'Détails', width: 200, hidden: true },
];

// Search ignores accents ("categorie" finds "Catégorie") and waits 200 ms after typing; a header line
// and a footer with a "Show all" action next to the built-in OK / Cancel buttons. A constant: the
// options prop is reactive.
const chooser: DataGridColumnChooser<Order> = {
  searchable: true,
  ignoreAccents: true,
  debounce: 200,
  searchOperator: 'contains',
  renderHeader: ({ columns: items }) => (
    <p className="demo-chooser__summary" style={{ margin: '0 0 8px' }}>
      {items.filter((c) => !c.hidden).length} of {items.length} columns shown
    </p>
  ),
  renderFooter: ({ columns: items, setHidden, defaultContent }) => (
    <div className="demo-chooser__footer" style={{ display: 'flex', gap: 8, alignItems: 'center', justifyContent: 'space-between' }}>
      <button type="button" className="salmon-data-grid-button" onClick={() => setHidden(items.map((c) => c.field), false)}>
        Show all
      </button>
      {defaultContent}
    </div>
  ),
};

export default function ColumnChooserTemplatesDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [log, push] = useEventLog();
  return (
    <>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={() => api.current?.openColumnChooser({ x: 24, y: 24 })}>
          Open at the viewport corner
        </Button>
      </div>
      <DataGrid<Order>
        aria-label="Orders with a templated column chooser"
        data={orders}
        columns={columns}
        toolbar={['columnChooser']}
        columnChooser={chooser}
        onBeforeColumnChooserOpen={(e) => push(`chooser opened: ${e.columns.length} columns`)}
        onColumnVisibilityChange={(e) => push(`shown: ${e.shown.join(', ') || '-'}; hidden: ${e.hidden.join(', ') || '-'}`)}
        height={360}
        locale="fr-FR"
        currency="EUR"
        timeZone="UTC"
        ref={api}
      />
      <EventLog entries={log} label="Column visibility" />
    </>
  );
}
```

## API reference

[`DataGridColumnChooser`](https://salmonui.dev/docs/reference/data-grid/DataGridColumnChooser)
lists the `columnChooser` options and
[`DataGridColumnChooserContext`](https://salmonui.dev/docs/reference/data-grid/DataGridColumnChooserContext)
the template context;
[`DataGridColumnChooserOpenEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridColumnChooserOpenEvent)
and [`DataGridColumnVisibilityChangeEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridColumnVisibilityChangeEvent)
are the event payloads, and `openColumnChooser` is on
[`DataGridApi`](https://salmonui.dev/docs/reference/data-grid/DataGridApi).
