# DataTable

Table for server data, with a toolbar (search, `Filters`, the buttons of the app, "Columns"), a bar of actions on the selected rows and a footer with the pagination. Every change of page, page size, sorting, search or filters makes a new query, `{ page, pageSize, sort, search, filterValue, builder }`, where `builder` is the whole `FilterBuilder` for the backend (filters, the search word by word on `searchColumns`, the sorting of the columns). Changing filters, search, sorting or page size goes back to page 1; changing filters or search also clears the selection, which instead stays across pages. Rows come in one of two ways: a `loader({ ...query, signal })` that returns `{ rows, total }` (the table shows the loading, aborts outdated requests, shows an error with "Retry", and `reload()` runs it again; pass `rows` and `total` from the `load` of SvelteKit to skip the first request), or `rows` and `total` managed by the app, which loads them in `onquerychange` (and appends the next batch in `onloadmore` with `pagination="infinite"`). `pagination` is `pages` (a page size selector, the range and a `Paginator`), `infinite` (the next batch loads when the last rows come into view) or `none`; a new query brings a table that scrolls on its own (`--table-max-height`) back to the top. With `selectable="multiple"` a floating bar at the bottom shows how many rows are selected, offers to select every row of the result (`selectedAll`, with the rows unchecked afterwards in `excluded`) and holds `selectionActionsSnippet`. `columnManager` adds a "Columns" button that opens a `ColumnManager` on `columnState`; `oncolumnstatechange` is called when the user saves the view or resizes a column. Every prop of `Table` works as there, other attributes go to the root of the `Table`. Below the `cardBreakpoint` of the table the frame goes away and the rows become cards; below 640px of width the toolbar is one row ("Filters" and "Columns" as icons, `toolbarSnippet` receives `narrow` for icon-only buttons) and, when it does not fit in one row (below about 480px), the selection bar puts its actions on a second row.

```ts
import { DataTable } from '@likable-hair/svelte';
```

Category: composed. Source: `src/lib/components/composed/tables/DataTable.svelte`.

## Examples

### Rows from a loader

`loader` receives the query (page, page size, sorting, search, filters and the `builder` for the backend) and returns `{ rows, total }`; the table shows the loading and keeps only the newest answer. The first page comes from the `load` of the page (`rows` and `total`), so it is not loaded twice. `searchColumns` adds the search field: the text reaches the query as an `ilike` on those columns.

```svelte
<script lang="ts">
	import { DataTable, type TableColumn } from '@likable-hair/svelte';
	import { fetchBookings, queryBookings, searchColumns, type Booking } from './bookings.js';

	const first = queryBookings({ page: 1, pageSize: 20 });

	const columns: TableColumn<Booking>[] = [
		{ key: 'client', label: 'Client', sortable: true },
		{ key: 'service', label: 'Service', sortable: true },
		{ key: 'start', label: 'Date', type: 'datetime', sortable: true },
		{ key: 'amount', label: 'Amount', type: 'number', numberFormat: { style: 'currency', currency: 'EUR' }, sortable: true }
	];
</script>

<DataTable
	caption="Bookings"
	{columns}
	rows={first.rows}
	total={first.total}
	loader={fetchBookings}
	{searchColumns}
/>
```

### Filters, columns and selection

`filterFields` adds the `Filters` to the toolbar and `filterValue` holds their tree; `toolbarSnippet` puts the buttons of the page at the end (icon-only when the table is `narrow`) and `columnManager` adds "Columns". With `selectable="multiple"` the selected rows show a floating bar with the `selectionActions`, drawn by the table (a promise returned by `onclick` shows a spinner, `info` and `disabledInfo` a tooltip, the actions that do not fit go in a menu): once every row of the page is checked it offers to select the whole result. "New" adds a booking and calls `reload()`.

```svelte
<script lang="ts">
	import {
		mdiDeleteOutline,
		mdiDotsVertical,
		mdiDownload,
		mdiEmailOutline,
		mdiPencilOutline,
		mdiPlus,
		mdiTagOutline
	} from '@mdi/js';
	import {
		Button,
		Chip,
		DataTable,
		createFilters,
		filterCondition,
		type DataTableAction,
		type FilterGroup,
		type TableColumn
	} from '@likable-hair/svelte';
	import {
		bookingFields,
		bookings,
		fetchBookings,
		queryBookings,
		searchColumns,
		statuses,
		type Booking
	} from './bookings.js';

	const confirmed = createFilters([filterCondition('status', 'in', [{ value: 'confirmed', label: 'Confirmed' }])]);
	const first = queryBookings({ page: 1, pageSize: 20, filterValue: confirmed });
	let filterValue = $state<FilterGroup>(confirmed);

	const columns: TableColumn<Booking>[] = [
		{ key: 'client', label: 'Client', sortable: true, pinned: true, cell: client },
		{ key: 'service', label: 'Service' },
		{ key: 'start', label: 'Date', type: 'datetime', sortable: true },
		{ key: 'status', label: 'Status', cell: status },
		{ key: 'staff', label: 'Staff', hidden: true },
		{ key: 'paid', label: 'Paid', type: 'boolean', hidden: true },
		{ key: 'amount', label: 'Amount', type: 'number', numberFormat: { style: 'currency', currency: 'EUR' }, sortable: true }
	];

	const selectionActions: DataTableAction<Booking>[] = [
		{
			label: 'Send reminder',
			icon: mdiEmailOutline,
			info: 'Sends an email to every selected client',
			onclick: () => new Promise((resolve) => setTimeout(resolve, 1200))
		},
		{ label: 'Export', icon: mdiDownload, onclick: () => undefined },
		{ label: 'Add tag', icon: mdiTagOutline, onclick: () => undefined },
		{
			label: 'Cancel bookings',
			icon: mdiDeleteOutline,
			variant: 'danger',
			onclick: ({ clear }) => clear()
		},
		{
			label: 'Archive',
			disabled: true,
			disabledInfo: 'Only past bookings can be archived',
			onclick: () => undefined
		}
	];

	let table = $state<ReturnType<typeof DataTable>>();
	let selected = $state<Booking[]>([]);

	function add() {
		bookings.unshift({ ...bookings[0], id: bookings.length + 1, client: 'New client', initials: 'NC', status: 'confirmed' });
		table?.reload();
	}
</script>

{#snippet client({ row }: { row: Booking })}
	<span class="who"><span class="avatar">{row.initials}</span>{row.client}</span>
{/snippet}

{#snippet status({ row }: { row: Booking })}
	<Chip size="sm" variant={statuses[row.status].variant}>{statuses[row.status].label}</Chip>
{/snippet}

<DataTable
	bind:this={table}
	caption="Bookings"
	{columns}
	rows={first.rows}
	total={first.total}
	loader={fetchBookings}
	{searchColumns}
	filterFields={bookingFields}
	bind:filterValue
	columnManager
	selectable="multiple"
	bind:selected
	actionsVisibility="hover"
	{selectionActions}
>
	{#snippet toolbarSnippet({ narrow })}
		<Button size="sm" icon={mdiPlus} aria-label={narrow ? 'New' : undefined} onclick={add}>
			{#if !narrow}New{/if}
		</Button>
	{/snippet}
	{#snippet actionsSnippet({ row })}
		<Button buttonType="icon" variant="secondary" size="sm" icon={mdiPencilOutline} aria-label="Edit {row.client}" />
		<Button buttonType="icon" variant="secondary" size="sm" icon={mdiDotsVertical} aria-label="More for {row.client}" />
	{/snippet}
</DataTable>

<style>
	.who {
		display: inline-flex;
		align-items: center;
		gap: 10px;
	}

	.avatar {
		display: inline-grid;
		place-items: center;
		width: 28px;
		height: 28px;
		border-radius: 50%;
		background: var(--global-color-primary-soft);
		color: var(--global-color-primary);
		font-size: 11px;
		font-weight: 600;
	}
</style>
```

### The query for the backend

Without `loader` the app loads the rows: `onquerychange` receives `{ page, pageSize, sort, search, filterValue, builder }` at every change (not on mount), and the app passes back `rows`, `total` and `loading`. `builder.toJson()` is what the backend replays: the filters, the search as an OR group of `ilike` and the sorting (here the `sort` of the Client column orders by last and first name).

```svelte
<script lang="ts">
	import { DataTable, type DataTableQuery, type TableColumn } from '@likable-hair/svelte';
	import { bookingFields, fetchBookings, queryBookings, searchColumns, type Booking } from './bookings.js';

	const columns: TableColumn<Booking>[] = [
		{
			key: 'client',
			label: 'Client',
			sortable: true,
			sort: ({ builder, direction }) =>
				builder.orderBy('clients.lastName', direction).orderBy('clients.firstName', direction)
		},
		{ key: 'service', label: 'Service' },
		{ key: 'amount', label: 'Amount', type: 'number', numberFormat: { style: 'currency', currency: 'EUR' }, sortable: true }
	];

	const first = queryBookings({ page: 1, pageSize: 5 });
	let rows = $state(first.rows);
	let total = $state(first.total);
	let loading = $state(false);
	let sent = $state('{ "modifiers": [] }');
	let request = 0;

	async function load(query: DataTableQuery) {
		sent = JSON.stringify(query.builder.toJson());
		const own = ++request;
		loading = true;
		const result = await fetchBookings(query);
		if (own !== request) return;
		rows = result.rows;
		total = result.total;
		loading = false;
	}
</script>

<div class="stack">
	<DataTable
		caption="Bookings"
		{columns}
		{rows}
		{total}
		{loading}
		pageSize={5}
		pageSizes={[5, 10, 20]}
		{searchColumns}
		filterFields={bookingFields}
		onquerychange={load}
	/>
	<code>{sent}</code>
</div>

<style>
	.stack {
		display: flex;
		width: 100%;
		flex-direction: column;
		gap: 12px;
	}

	code {
		color: var(--global-color-text-2);
		font-family: var(--global-font-family-mono);
		font-size: 12px;
		overflow-wrap: anywhere;
	}
</style>
```

### Infinite scroll

`pagination="infinite"` loads the next batch of `pageSize` rows when the last rows come into view, inside the table when it scrolls on its own (`--table-max-height`) or in the page; the footer counts the loaded rows. Without `loader`, `onloadmore` receives the query of the next batch and the app appends its rows.

```svelte
<script lang="ts">
	import { DataTable, type TableColumn } from '@likable-hair/svelte';
	import { fetchBookings, queryBookings, searchColumns, type Booking } from './bookings.js';

	const first = queryBookings({ page: 1, pageSize: 25 });

	const columns: TableColumn<Booking>[] = [
		{ key: 'client', label: 'Client' },
		{ key: 'service', label: 'Service' },
		{ key: 'start', label: 'Date', type: 'datetime' },
		{ key: 'amount', label: 'Amount', type: 'number', numberFormat: { style: 'currency', currency: 'EUR' } }
	];
</script>

<DataTable
	--table-max-height="360px"
	caption="Bookings"
	{columns}
	rows={first.rows}
	total={first.total}
	loader={fetchBookings}
	pagination="infinite"
	pageSize={25}
	{searchColumns}
/>
```

### Loading errors

When the `loader` fails the table shows the error with "Retry" (in place of the rows, or under them when the rows of another page are on screen) and calls `onerror`; `errorSnippet` replaces it. Here the server is down until the switch is turned on.

```svelte
<script lang="ts">
	import { DataTable, Switch, type DataTableQuery, type TableColumn } from '@likable-hair/svelte';
	import { fetchBookings, type Booking } from './bookings.js';

	const columns: TableColumn<Booking>[] = [
		{ key: 'client', label: 'Client' },
		{ key: 'service', label: 'Service' },
		{ key: 'amount', label: 'Amount', type: 'number', numberFormat: { style: 'currency', currency: 'EUR' } }
	];

	let online = $state(false);

	function loader(query: DataTableQuery & { signal: AbortSignal }) {
		if (!online) return Promise.reject(new Error('Service unavailable'));
		return fetchBookings(query);
	}
</script>

<div class="stack">
	<Switch bind:checked={online} label="Server online" />
	<DataTable caption="Bookings" {columns} {loader} pageSize={5} pageSizes={[5]} />
</div>

<style>
	.stack {
		display: flex;
		width: 100%;
		flex-direction: column;
		align-items: flex-start;
		gap: 12px;
	}
</style>
```

### Texts and style

`locale` sets the language of every text and of the numbers (here Italian); `labels` changes single texts and `rangeSnippet` the range in the footer. The `--data-table-*` variables restyle the frame, the toolbar, the footer and the selection bar, and the `--table-*` ones the table inside.

```svelte
<script lang="ts">
	import { DataTable, type TableColumn } from '@likable-hair/svelte';
	import { fetchBookings, queryBookings, searchColumns, type Booking } from './bookings.js';

	const first = queryBookings({ page: 1, pageSize: 5 });

	const columns: TableColumn<Booking>[] = [
		{ key: 'client', label: 'Cliente', sortable: true },
		{ key: 'service', label: 'Servizio' },
		{ key: 'amount', label: 'Importo', type: 'number', numberFormat: { style: 'currency', currency: 'EUR' }, sortable: true }
	];
</script>

<DataTable
	--data-table-border-radius="4px"
	--data-table-toolbar-background="var(--global-color-surface-2)"
	--data-table-footer-color="var(--global-color-text-2)"
	--table-header-background="transparent"
	locale="it"
	caption="Prenotazioni"
	{columns}
	rows={first.rows}
	total={first.total}
	loader={fetchBookings}
	pageSize={5}
	pageSizes={[5, 10]}
	{searchColumns}
	labels={{ search: 'Cerca un cliente…' }}
>
	{#snippet rangeSnippet({ page, pageCount, total })}
		Pagina <strong>{page}</strong> di {pageCount} · {total} prenotazioni
	{/snippet}
</DataTable>
```

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `rows` | `Row[]` |  | Rows of the current page, or of the batches loaded so far with `pagination="infinite"`. With `loader`, the rows of the first query (for example from the `load` of SvelteKit): the table shows them instead of loading them again. |
| `loader` | `(query: DataTableQuery & { signal: AbortSignal }) => Promise<DataTableLoadResult<Row>>` |  | Loads the rows of a query. Called when the table mounts without `rows`, at every change of the query, for the next batch with `pagination="infinite"` and by `reload()`; a newer call aborts the older one through `signal`. Return the rows and the `total` of the result (or `pageCount`). |
| `pagination` | `'pages' \| 'infinite' \| 'none'` | `'pages'` | `pages`: one page at a time, with a page size selector, the range and a `Paginator`. `infinite`: the next batch loads when the last rows come into view. `none`: every row at once. |
| `page` (bindable) | `number` |  | Current page, from 1 (the last batch loaded with `pagination="infinite"`). |
| `pageSize` (bindable) | `number` |  | Rows per page, or per batch. Defaults to the first of `pageSizes`. |
| `pageSizes` | `number[]` | `[20, 50, 100]` | Choices of the page size selector. With fewer than two the selector is hidden. |
| `total` | `number` |  | Number of rows of the whole result, on every page. Without it and without `pageCount` the `Paginator` only goes forward page by page. |
| `pageCount` | `number` |  | Number of pages, when the app knows it instead of `total`. |
| `search` (bindable) | `string` |  | Text of the search field. |
| `searchColumns` | `string[]` |  | Columns of the backend searched by the search field: the text goes in the query word by word, so "mario rossi" finds Mario Rossi across first and last name: one group per word, joined with AND, each an `ilike` on every column joined with OR. Shows the search field. |
| `searchable` | `boolean` |  | Shows the search field. Defaults to `true` when `searchColumns` is set; without them the text only reaches `query.search`. |
| `filterFields` | `FilterField[]` |  | Fields of the `Filters` in the toolbar. Without them there are no filters. |
| `filterValue` (bindable) | `FilterGroup` |  | Tree of the filters, as the `value` of `Filters`. |
| `columnManager` | `boolean` | `false` | Shows a "Columns" button that opens a `ColumnManager` on `columnState`. |
| `selectionBar` | `boolean` | `true` | Shows the bar of the selected rows while at least one is selected. |
| `selectionActions` | `DataTableAction<Row>[]` | `[]` | Actions on the selected rows, drawn as buttons of the selection bar with the same look in every app. Those that do not fit (more than 4, or 2 below 640px) go in a "More actions" `MenuOrDrawerOptions`: a menu, or a bottom sheet on screens up to 1024px wide. |
| `selectionDisabled` | `boolean` | `false` | Disables every action of the selection bar, for example while one of them is running. |
| `filtersProps` | `Omit< ComponentProps<typeof Filters>, 'fields' \| 'value' \| 'locale' \| 'prependSnippet' \| 'actionsSnippet' >` |  | Props of the `Filters` in the toolbar, except those the table sets. |
| `searchBarProps` | `Omit<ComponentProps<typeof SearchBar>, 'value' \| 'locale' \| 'onsearch'>` |  | Props of the `SearchBar` in the toolbar, except those the table sets. |
| `paginatorProps` | `Omit< ComponentProps<typeof Paginator>, 'page' \| 'pageCount' \| 'locale' \| 'onchange' >` |  | Props of the `Paginator` in the footer, except those the table sets. |
| `columnManagerProps` | `Omit< ComponentProps<typeof ColumnManager<Row>>, 'columns' \| 'columnState' \| 'open' \| 'locale' >` |  | Props of the `ColumnManager`, except those the table sets. |
| `labels` | `{ search?: string; columns?: string; rowsPerPage?: string; range?: string; rangeOpen?: string; loaded?: string; results?: string; result?: string; selected?: string; selectedOne?: string; allSelected?: string; selectAll?: string; clearSelection?: string; selectionActions?: string; moreActions?: string; loadError?: string; retry?: string; loadingMore?: string; selectRow?: string; selectAllShort?: string; row?: string; expand?: string; collapse?: string; actions?: string; resize?: string; info?: string; open?: string; loading?: string; yes?: string; no?: string; sortBy?: string; unsorted?: string; moreFields?: string; fewerFields?: string; ascending?: string; descending?: string; }` |  | Texts to change, on top of those of `locale`: those of `Table` and those of the toolbar, the footer and the selection bar. `{from}`, `{to}`, `{total}` and `{count}` are replaced by the numbers. |
| `class` | `{ container?: ClassValue; toolbar?: ClassValue; footer?: ClassValue; selectionBar?: ClassValue; table?: ClassValue; header?: ClassValue; row?: ClassValue; cell?: ClassValue; }` | `{}` | Classes of the parts: `container` the root, `toolbar`, `footer`, `selectionBar`, and those of `Table`: `table` the `<table>`, `header` the header cells, `row` the rows (and cards), `cell` the body cells. |

### From Table

It accepts the props, snippets and events of Table (`/components/table.md`), listed in the tables "From Table". Except `sorting`, `onendreached`, `onload`.

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `columns` (required) | `TableColumn<Row>[]` |  | The columns, in their default order (see `TableColumn`). |
| `rowKey` | `string \| ((row: Row) => string \| number)` | `'id'` | Identity of a row: the name of a property or a function. Used as the key of the list, of the selection and of the expanded rows. |
| `sort` (bindable) | `TableSort` |  | Current sorting, or empty for the order of `rows`. |
| `selectable` | `'single' \| 'multiple'` |  | Adds a checkbox to each row: `multiple` also adds "select all" in the header and selects a range with shift-click, `single` keeps at most one row selected. |
| `selected` (bindable) | `Row[]` |  | Selected rows, compared through `rowKey`. |
| `selectedAll` (bindable) | `boolean` |  | Every row is selected, also those not loaded (for example on other pages), except `excluded`. Set by the app or by `DataTable`; the header checkbox of the table selects only the rows it shows. |
| `excluded` (bindable) | `Row[]` |  | Rows left out of `selectedAll`. |
| `expanded` (bindable) | `(string \| number)[]` |  | Keys (`rowKey`) of the expanded rows. |
| `expandable` | `(row: Row) => boolean` |  | Which rows can expand. Defaults to all of them when `expandedSnippet` is set. |
| `rowHref` | `(row: Row) => string \| undefined` |  | URL of a row: the row becomes a link, with a real link inside for the keyboard and screen readers. Ctrl-click and middle click open it in a new tab. |
| `rowClass` | `(row: Row) => ClassValue` |  | Extra classes of a row. |
| `empty` | `string` | `'—'` | Text of empty cells (`null`, `undefined`, empty string) of every column, unless the column sets its own. |
| `loading` | `boolean` | `false` | Shows that the rows are loading: a progress bar under the header, or `loadingRows` placeholder rows when there are no rows yet. |
| `loadingRows` | `number` | `5` | Number of placeholder rows while loading without rows. |
| `noDataTitle` | `string` |  | Title shown when there are no rows. Defaults to the one of `NoData`, in the language of `locale`. |
| `columnState` (bindable) | `TableColumnState[]` |  | Order, visibility, width and pin of the columns, in display order: plain data to save and restore. Columns missing from it keep their defaults, unknown keys are ignored. |
| `columnsKey` | `string` |  | Saves `columnState` in the browser (`localStorage`) under this key and restores it on load, when the app does not pass its own. |
| `resizable` | `boolean` | `false` | Columns can be resized by dragging the edge of their header, or with the arrow keys when it has the focus. |
| `actionsVisibility` | `'always' \| 'hover'` | `'always'` | `always` shows the buttons of `actionsSnippet` on every row; `hover` only on the row under the pointer or with the focus inside, for dense tables (always on touch screens and in the cards). |
| `cardBreakpoint` | `number \| false` | `640` | Below this width of the table, in pixels, every row is shown as a card. `false` keeps the table, which scrolls sideways. |
| `cardTitle` | `string` |  | Key of the column used as the title of the cards and as the name of the rows for screen readers. Defaults to the first visible column. |
| `cardColumns` | `string[]` |  | Keys of the columns always shown in the cards, under the title; the other columns are behind a "Show more fields" button in each card. Defaults to the first 4 visible columns after the title. |
| `caption` | `string` |  | Accessible name of the table, read by screen readers. |
| `locale` | `string` |  | BCP 47 locale of the texts and of the formatting of numbers and dates: `it` and `en` texts are built in, other languages fall back to English. Defaults to the one set with `setDefaultLocale`, else `en`. |
| `tableElement` (bindable) | `HTMLTableElement` |  | The `<table>` element, empty while the cards are shown. |
| `virtualize` | `boolean \| number` | `200` | Above this number of rows only the rows in view, plus a margin, are in the page, so thousands of rows stay fast; the others are drawn while scrolling (the page, the app container or the table with `--table-max-height`). `true` always, `false` never. While it is on, the find of the browser and printing see only the drawn rows, and the columns keep the widths they had on the first rows. |
| `disabled` | `boolean` | `false` | Read-only table, for example while the app saves: rows are not clickable and sorting, selection and resizing are off. Expanding rows still works. |
| `selectAll` | `boolean` | `true` | With `selectable="multiple"`, shows the checkbox that selects every row (in the header, or above the cards). `false` keeps only the checkbox of each row. |

It also accepts the native attributes and events of `<div>` (for example `id`, `title`, `aria-label`, `onkeydown`), which are forwarded to the element.

## Snippets

| Name | Parameters | Description |
| --- | --- | --- |
| `toolbarSnippet` | `{ narrow: boolean }` | Buttons of the app at the end of the toolbar, for example "New". `narrow` is true below 640px of the table, where the toolbar is one row: show icon-only buttons there (with an `aria-label`). |
| `selectionActionsSnippet` | `{ selected: Row[]; selectedAll: boolean; excluded: Row[]; count: number \| undefined; clear: () => void; }` | Extra content of the selection bar, after `selectionActions`, for actions that need more than a button. `count` is `undefined` when every row is selected and the total is unknown; `clear` empties the selection. |
| `rangeSnippet` | `{ from: number; to: number; total: number \| undefined; page: number; pageCount: number \| undefined }` | Replaces the range in the footer ("1–20 of 312"). |
| `searchSnippet` | `{ value: string; setValue: (text: string) => void }` | Replaces the search field. Call `setValue` with the new text, already debounced. |
| `errorSnippet` | `{ error: unknown; retry: () => void }` | Replaces the error of a failed `loader`; `retry` loads again. |

### From Table

| Name | Parameters | Description |
| --- | --- | --- |
| `cellSnippet` | `{ row: Row; value: any; column: TableColumn<Row> }` | Content of the cells of `custom` columns, for the columns without a `cell` snippet. |
| `expandedSnippet` | `{ row: Row }` | Content of the detail row under an expanded row. |
| `actionsSnippet` | `{ row: Row }` | Buttons of a row, in a column that stays on the right while the table scrolls sideways. |
| `noDataSnippet` |  | Replaces `NoData` when there are no rows. |

## Events

| Name | Type | Description |
| --- | --- | --- |
| `onquerychange` | `(query: DataTableQuery) => void` | Called when the query changes (not when the table mounts): without `loader` the app loads the rows of `query` and passes them in `rows` and `total`. |
| `onloadmore` | `(query: DataTableQuery) => void` | With `pagination="infinite"` and without `loader`: called when the last rows come into view and more rows exist, with the `page` of the next batch. Append its rows to `rows`. |
| `onloaded` | `(event: { rows: Row[]; total: number \| undefined; query: DataTableQuery }) => void` | Called after the `loader` returns, with its rows (the batch only, with `pagination="infinite"`), its total and the query. |
| `onerror` | `(error: unknown) => void` | Called when the `loader` fails. |
| `oncolumnstatechange` | `(event: { columnState: TableColumnState[] }) => void` | Called when the user changes the columns: when they save the view of the `ColumnManager` and at the end of a resize, after `columnState` has changed. Save it here, for example in the user's settings. |

### From Table

| Name | Type | Description |
| --- | --- | --- |
| `onsortchange` | `(event: { sort: TableSort \| undefined }) => void` | Called when the user changes the sorting, after `sort` has changed. |
| `onselectionchange` | `(event: { selected: Row[]; selectedAll: boolean; excluded: Row[] }) => void` | Called when the user changes the selection, after `selected`, `selectedAll` and `excluded` have changed. |
| `onexpandedchange` | `(event: { expanded: (string \| number)[] }) => void` | Called when the user expands or collapses a row, after `expanded` has changed. |
| `onrowclick` | `(row: Row, event: MouseEvent \| KeyboardEvent) => void` | Called on a click on a row (not on its buttons, links and fields) and on Enter or Space when the row has the focus. With it every row is focusable. Calling `event.preventDefault()` stops the navigation of `rowHref`. |

## Methods

Call them on the instance: `<DataTable bind:this={ref} />`, then `ref.reload()`.

| Signature | Description |
| --- | --- |
| `reload()` | Loads the rows of the current query again, for example after the app has created or deleted one: with `loader` it calls it again (from the first batch with `pagination="infinite"`), without it calls `onquerychange`. |

## Types

Exported by the package: `import type { DataTableQuery, DataTableLoadResult, FilterField, FilterGroup, DataTableAction, TableColumn, TableSort, TableColumnState, StringFilterField, NumberFilterField, DateFilterField, SelectFilterField, BoolFilterField, CustomFilterField, FilterLogic, FilterNode, DataTableActionContext, FilterJoin, FilterThrough, FilterOperatorDefinition, FilterOperatorSet, FilterConditionValue, FilterCondition, FilterItem, FilterPeriod, FilterInput, Item } from '@likable-hair/svelte';`

### DataTableQuery

What a `DataTable` asks the server for. A change of page, page size, sorting, search or filters makes a new query.

`interface DataTableQuery`

| Name | Type | Description |
| --- | --- | --- |
| `page` (required) | `number` | Page to show, from 1. In `infinite` mode, the batch to load. |
| `pageSize` (required) | `number` | Rows per page, or per batch in `infinite` mode. |
| `sort` | `TableSort` | Current sorting, if any. |
| `search` (required) | `string` | Text of the search field, trimmed: empty without a search. |
| `filterValue` (required) | `FilterGroup` | Tree of the filters (the `value` of `Filters`), with complete conditions only. |
| `builder` (required) | `FilterBuilder` | The whole query for the backend: filters, search (one `ilike` group on `searchColumns` per word) and sorting. Send `builder.toJson()` together with `page` and `pageSize`. |

### DataTableLoadResult

What the `loader` of a `DataTable` returns.

`interface DataTableLoadResult<Row = any>`

| Name | Type | Description |
| --- | --- | --- |
| `rows` (required) | `Row[]` | Rows of the requested page or batch. |
| `total` | `number` | Number of rows of the whole result, on every page. |
| `pageCount` | `number` | Number of pages, when the backend gives it instead of `total`. |

### FilterField

A filterable field: what the app declares for each column the user can filter.

`type FilterField = StringFilterField \| NumberFilterField \| DateFilterField \| SelectFilterField \| BoolFilterField \| CustomFilterField`

### FilterGroup

A group of conditions and groups, combined with `logic`. The root of the tree is a group.

`interface FilterGroup`

| Name | Type | Description |
| --- | --- | --- |
| `id` (required) | `string` | Identity inside the tree, made by the helpers. |
| `logic` (required) | `FilterLogic` | `and`: every item must hold; `or`: at least one. |
| `items` (required) | `FilterNode[]` | Conditions and nested groups. |
| `locked` | `boolean` | The user cannot change or remove the group. |

### DataTableAction

An action on the selected rows of a `DataTable`, drawn as a button of the selection bar.

`interface DataTableAction<Row = any>`

| Name | Type | Description |
| --- | --- | --- |
| `label` (required) | `string` | Text of the button. |
| `icon` | `string` | SVG path of the icon. |
| `variant` | `'default' \| 'danger'` | `danger` for destructive actions, in the error color. |
| `disabled` | `boolean` | The action cannot run; with `disabledInfo` a tooltip says why. |
| `loading` | `boolean` | Shows a spinner on the button. The button also spins while the promise returned by `onclick` is pending. |
| `info` | `string` | Explanation of the action, in a tooltip on the button. |
| `disabledInfo` | `string` | Why the action is disabled, in a tooltip on the button. |
| `onclick` (required) | `(context: DataTableActionContext<Row>) => void \| Promise<unknown>` | Runs the action. Return a promise to show a spinner until it settles. |

### TableColumn

A column of a `Table`: what it shows, how it formats, sorts and sizes it.

`interface TableColumn<Row = any>`

| Name | Type | Description |
| --- | --- | --- |
| `key` (required) | `string` | Unique key of the column. Without `value` it is also the property of the row that the column shows. |
| `label` | `string` | Text of the header. |
| `type` | `'text' \| 'number' \| 'date' \| 'datetime' \| 'boolean' \| 'custom'` | How the value is formatted and sorted: `text` as is, `number` with `Intl.NumberFormat` (right-aligned, monospaced digits), `date` and `datetime` with `Intl.DateTimeFormat` (a `Date`, an ISO string, a timestamp or an object with `toJSDate()` such as a luxon `DateTime`), `boolean` as a check mark when true, `custom` with the `cellSnippet` of the table (sorted as text). Defaults to `text`. |
| `value` | `(row: Row) => unknown` | Reads the value of the column from a row, for nested or computed values. Defaults to `row[key]`. |
| `format` | `(value: any, row: Row) => string` | Turns the value into the text of the cell, instead of the formatting of `type`. Not called for empty values. |
| `numberFormat` | `Intl.NumberFormatOptions` | Options of `Intl.NumberFormat` for `number` columns, for example `{ style: 'currency', currency: 'EUR' }`. |
| `dateFormat` | `Intl.DateTimeFormatOptions` | Options of `Intl.DateTimeFormat` for `date` and `datetime` columns. Defaults to the day, the month and the year in digits, plus hours and minutes for `datetime`. |
| `empty` | `string` | Text of an empty cell (`null`, `undefined`, an empty string). Defaults to the `empty` of the table. |
| `align` | `'start' \| 'center' \| 'end'` | Horizontal alignment of the header and the cells. Defaults to `end` for numbers, else `start`. |
| `width` | `string` | Preferred width of the column, any CSS length (`120px`, `20%`): columns still shrink to fit the table, `minWidth` keeps them wider and makes the table scroll. A width set by resizing wins. |
| `minWidth` | `string` | Minimum width of the column, any CSS length. |
| `maxWidth` | `string` | Maximum width of the column, any CSS length: longer text is cut with an ellipsis. |
| `sortable` | `boolean` | The header becomes a button that sorts by this column: ascending, descending, then unsorted. |
| `compare` | `(a: Row, b: Row) => number` | Compares two rows when the table sorts by this column on its own, instead of comparing the values. Return a negative number when `a` comes first in ascending order. |
| `sort` | `(params: { builder: FilterBuilder; direction: 'asc' \| 'desc' }) => FilterBuilder` | Adds the sorting by this column to the query sent to the backend, instead of `orderBy(key, direction)`. Used when the table does not sort on its own (`sorting="manual"`, `DataTable`). |
| `pinned` | `boolean` | Keeps the column visible on the left while the table scrolls sideways. Pinned columns are moved before the others; they scroll like the others while, together with the checkboxes and the actions, they would take more than half of the table. |
| `hidden` | `boolean` | Hides the column until it is shown through `columnState` (for example with a `ColumnManager`). |
| `required` | `boolean` | The column is always shown: `columnState` cannot hide it and the `ColumnManager` has no button to hide it. |
| `icon` | `string` | SVG path of the icon of the column in the `ColumnManager`. Defaults to an icon of its `type`. |
| `description` | `string` | Description of the column in the `ColumnManager`, also matched by its search. Defaults to `info`. |
| `resizable` | `boolean` | With `resizable` on the table, `false` keeps this column at its size. |
| `info` | `string` | Explanation of the column, shown in a tooltip next to the header. |
| `footer` | `string \| Snippet<[{ rows: Row[]; column: TableColumn<Row> }]>` | Content of the column in the footer of the table: a text, or a snippet that receives every row, for example to show a total. |
| `cell` | `Snippet<[{ row: Row; value: any; column: TableColumn<Row> }]>` | Content of the cells of this column, instead of the formatted value. |
| `header` | `Snippet<[{ column: TableColumn<Row> }]>` | Content of the header of this column, instead of `label`. The sort arrow and the info icon stay. |

### TableSort

The sorting of a table: the key of the column and the direction.

`interface TableSort`

| Name | Type | Description |
| --- | --- | --- |
| `key` (required) | `string` | Key of the sorted column. |
| `direction` (required) | `'asc' \| 'desc'` | `asc` from the smallest value, `desc` from the largest. |

### TableColumnState

What the user changed about a column, in display order: plain data, ready to be saved.

`interface TableColumnState`

| Name | Type | Description |
| --- | --- | --- |
| `key` (required) | `string` | Key of the column. |
| `visible` (required) | `boolean` | Whether the column is shown. |
| `width` | `number` | Width in pixels set by resizing. |
| `pinned` | `boolean` | Whether the column is pinned on the left. |

### StringFilterField

A text field.

`interface StringFilterField extends FieldBase`

| Name | Type | Description |
| --- | --- | --- |
| `name` (required) | `string` | Identity of the field, stored in the conditions. |
| `label` (required) | `string` | Name shown to the user. |
| `icon` | `string` | SVG path of an icon shown in the list, the card and the pill. |
| `category` | `string` | Groups the fields in the list of "Add filter". |
| `description` | `string` | Secondary text in the list of fields. |
| `column` | `string` | Column of the query. Defaults to `name`. |
| `joins` | `FilterJoin[]` | Joins added to the query when the field has a condition. |
| `through` | `FilterThrough \| FilterThrough[]` | The condition is checked in a subquery on a related table (`column` is a column of the last hop). Several hops nest. |
| `operators` | `FilterOperatorSet \| (string \| FilterOperatorDefinition)[]` | Operators offered, in this order: names of the built-in ones of the type, definitions of new ones, or a whole set (`basic`, `standard`, `all`). Defaults to the set chosen on `Filters` (`standard`). |
| `defaultOperator` | `string` | Operator of a new condition. Defaults to the first one. |
| `pinned` | `boolean` | Always shown as a pill in the bar, even without a condition. |
| `hidden` | `boolean` | Never shown: its conditions (usually `locked`) only reach the query. |
| `defaultValue` | `FilterConditionValue` | Value of a new condition on this field (the card and the panel start with it). |
| `isComplete` | `(condition: FilterCondition) => boolean` | Decides when a condition on this field is complete (it reaches the query and gets a pill). Defaults to a check on the value for the operator. |
| `apply` | `(builder: FilterBuilder, condition: FilterCondition) => void` | Replaces the whole query of a condition on this field. |
| `whenAbsent` | `(builder: FilterBuilder) => void` | Query added when the field has no condition at all (for example "hide archived" until the user asks for them). |
| `format` | `(condition: FilterCondition) => string` | Replaces the text of the value in the pill. |
| `negativesIncludeEmpty` | `boolean` | Negative operators (`isNot`, `notContains`, `ne`, `notIn`, `noneOf`, `notBetween`) also keep the rows where the column is empty: "surname is not Rossi" shows the clients without a surname too. On by default (option of `Filters` / `filtersToBuilder`); this one wins. Needs a backend that knows `null` modifiers: pass `false` for backends E and E'. |
| `json` | `{ column: string; key: string; cast?: 'text' \| 'numeric' \| 'date' \| 'timestamp' \| 'boolean' }` | The value lives in a key of a JSONB column (`customFields.color`): equalities use `whereJsonSuperset`; with `cast` every operator works through a parametrized `whereRaw` (accepted only by backends that allow raw conditions). |
| `type` (required) | `'string'` |  |
| `columns` | `string[]` | Several columns: a condition holds when any of them matches (`contains`), or when none does (`isNot`, `notContains`). |
| `words` | `boolean` | Splits the text into words, for names split over `columns`: `contains` wants every word in some column; `is` wants every word as a whole word of some column, ignoring case unless `caseSensitive` ("mario rossi" finds Mario Rossi, Rossi Mario and Maria Grazia De Rossi with "maria rossi", not Mariolina Rossini); `notContains` and `isNot` are their exact opposites (some word is missing). The other operators compare the whole text. |
| `caseSensitive` | `boolean` | Tells upper and lower case apart. Without it every text operator ignores case: `contains` with `ilike`, `is`, `isNot`, `anyOf`, `noneOf`, `startsWith` and `endsWith` with a Postgres regex (`~*`). With it the equalities use `=`, `<>` and `in`, as in v4, which can use the column's index. |
| `suggest` | `(params: { searchText: string; signal: AbortSignal }) => Promise<FilterItem[]>` | Suggestions while typing, for the `match` operator: picking one filters on its exact value (on `suggestColumn`), keeping the typed text filters with `contains`. |
| `suggestColumn` | `string` | Column compared with the value of a picked suggestion. Defaults to `column`. |
| `blankIsEmpty` | `boolean` | With `empty` / `notEmpty`, an empty string counts as empty too. Default `true`. |
| `placeholder` | `string` | Placeholder of the input. |

### NumberFilterField

A number field.

`interface NumberFilterField extends FieldBase`

| Name | Type | Description |
| --- | --- | --- |
| `name` (required) | `string` | Identity of the field, stored in the conditions. |
| `label` (required) | `string` | Name shown to the user. |
| `icon` | `string` | SVG path of an icon shown in the list, the card and the pill. |
| `category` | `string` | Groups the fields in the list of "Add filter". |
| `description` | `string` | Secondary text in the list of fields. |
| `column` | `string` | Column of the query. Defaults to `name`. |
| `joins` | `FilterJoin[]` | Joins added to the query when the field has a condition. |
| `through` | `FilterThrough \| FilterThrough[]` | The condition is checked in a subquery on a related table (`column` is a column of the last hop). Several hops nest. |
| `operators` | `FilterOperatorSet \| (string \| FilterOperatorDefinition)[]` | Operators offered, in this order: names of the built-in ones of the type, definitions of new ones, or a whole set (`basic`, `standard`, `all`). Defaults to the set chosen on `Filters` (`standard`). |
| `defaultOperator` | `string` | Operator of a new condition. Defaults to the first one. |
| `pinned` | `boolean` | Always shown as a pill in the bar, even without a condition. |
| `hidden` | `boolean` | Never shown: its conditions (usually `locked`) only reach the query. |
| `defaultValue` | `FilterConditionValue` | Value of a new condition on this field (the card and the panel start with it). |
| `isComplete` | `(condition: FilterCondition) => boolean` | Decides when a condition on this field is complete (it reaches the query and gets a pill). Defaults to a check on the value for the operator. |
| `apply` | `(builder: FilterBuilder, condition: FilterCondition) => void` | Replaces the whole query of a condition on this field. |
| `whenAbsent` | `(builder: FilterBuilder) => void` | Query added when the field has no condition at all (for example "hide archived" until the user asks for them). |
| `format` | `(condition: FilterCondition) => string` | Replaces the text of the value in the pill. |
| `negativesIncludeEmpty` | `boolean` | Negative operators (`isNot`, `notContains`, `ne`, `notIn`, `noneOf`, `notBetween`) also keep the rows where the column is empty: "surname is not Rossi" shows the clients without a surname too. On by default (option of `Filters` / `filtersToBuilder`); this one wins. Needs a backend that knows `null` modifiers: pass `false` for backends E and E'. |
| `json` | `{ column: string; key: string; cast?: 'text' \| 'numeric' \| 'date' \| 'timestamp' \| 'boolean' }` | The value lives in a key of a JSONB column (`customFields.color`): equalities use `whereJsonSuperset`; with `cast` every operator works through a parametrized `whereRaw` (accepted only by backends that allow raw conditions). |
| `type` (required) | `'number'` |  |
| `unit` | `string` | Text after the value (`€`, `kg`). |
| `scale` | `number` | Multiplies the typed value before the query (for example `1000` to type tons of a column in kilograms). |
| `step` | `number` | `step` of the input. |
| `compareWith` | `{ column: string; label: string }[]` | Other columns the value can be compared with (`quantity < minimum quantity`): adds the column operators. |

### DateFilterField

A date field.

`interface DateFilterField extends FieldBase`

| Name | Type | Description |
| --- | --- | --- |
| `name` (required) | `string` | Identity of the field, stored in the conditions. |
| `label` (required) | `string` | Name shown to the user. |
| `icon` | `string` | SVG path of an icon shown in the list, the card and the pill. |
| `category` | `string` | Groups the fields in the list of "Add filter". |
| `description` | `string` | Secondary text in the list of fields. |
| `column` | `string` | Column of the query. Defaults to `name`. |
| `joins` | `FilterJoin[]` | Joins added to the query when the field has a condition. |
| `through` | `FilterThrough \| FilterThrough[]` | The condition is checked in a subquery on a related table (`column` is a column of the last hop). Several hops nest. |
| `operators` | `FilterOperatorSet \| (string \| FilterOperatorDefinition)[]` | Operators offered, in this order: names of the built-in ones of the type, definitions of new ones, or a whole set (`basic`, `standard`, `all`). Defaults to the set chosen on `Filters` (`standard`). |
| `defaultOperator` | `string` | Operator of a new condition. Defaults to the first one. |
| `pinned` | `boolean` | Always shown as a pill in the bar, even without a condition. |
| `hidden` | `boolean` | Never shown: its conditions (usually `locked`) only reach the query. |
| `defaultValue` | `FilterConditionValue` | Value of a new condition on this field (the card and the panel start with it). |
| `isComplete` | `(condition: FilterCondition) => boolean` | Decides when a condition on this field is complete (it reaches the query and gets a pill). Defaults to a check on the value for the operator. |
| `apply` | `(builder: FilterBuilder, condition: FilterCondition) => void` | Replaces the whole query of a condition on this field. |
| `whenAbsent` | `(builder: FilterBuilder) => void` | Query added when the field has no condition at all (for example "hide archived" until the user asks for them). |
| `format` | `(condition: FilterCondition) => string` | Replaces the text of the value in the pill. |
| `negativesIncludeEmpty` | `boolean` | Negative operators (`isNot`, `notContains`, `ne`, `notIn`, `noneOf`, `notBetween`) also keep the rows where the column is empty: "surname is not Rossi" shows the clients without a surname too. On by default (option of `Filters` / `filtersToBuilder`); this one wins. Needs a backend that knows `null` modifiers: pass `false` for backends E and E'. |
| `json` | `{ column: string; key: string; cast?: 'text' \| 'numeric' \| 'date' \| 'timestamp' \| 'boolean' }` | The value lives in a key of a JSONB column (`customFields.color`): equalities use `whereJsonSuperset`; with `cast` every operator works through a parametrized `whereRaw` (accepted only by backends that allow raw conditions). |
| `type` (required) | `'date'` |  |
| `dateOnly` | `boolean` | The column is a `date` (no time): the query compares `yyyy-MM-dd` strings. Otherwise it compares timestamps from the start to the end of the local days. |
| `periods` | `FilterPeriod[]` | Periods offered by the `period` operator, in this order. |
| `withTime` | `boolean` | The value has a time too: `before`, `after`, `between` and the relative operators compare instants (`yyyy-MM-ddTHH:mm`), and minutes and hours become available. |
| `compareWith` | `{ column: string; label: string }[]` | Other columns the value can be compared with (`deliveredAt after promisedAt`): adds the column operators. |

### SelectFilterField

A field whose value is chosen among options.

`interface SelectFilterField extends FieldBase`

| Name | Type | Description |
| --- | --- | --- |
| `name` (required) | `string` | Identity of the field, stored in the conditions. |
| `label` (required) | `string` | Name shown to the user. |
| `icon` | `string` | SVG path of an icon shown in the list, the card and the pill. |
| `category` | `string` | Groups the fields in the list of "Add filter". |
| `description` | `string` | Secondary text in the list of fields. |
| `column` | `string` | Column of the query. Defaults to `name`. |
| `joins` | `FilterJoin[]` | Joins added to the query when the field has a condition. |
| `through` | `FilterThrough \| FilterThrough[]` | The condition is checked in a subquery on a related table (`column` is a column of the last hop). Several hops nest. |
| `operators` | `FilterOperatorSet \| (string \| FilterOperatorDefinition)[]` | Operators offered, in this order: names of the built-in ones of the type, definitions of new ones, or a whole set (`basic`, `standard`, `all`). Defaults to the set chosen on `Filters` (`standard`). |
| `defaultOperator` | `string` | Operator of a new condition. Defaults to the first one. |
| `pinned` | `boolean` | Always shown as a pill in the bar, even without a condition. |
| `hidden` | `boolean` | Never shown: its conditions (usually `locked`) only reach the query. |
| `defaultValue` | `FilterConditionValue` | Value of a new condition on this field (the card and the panel start with it). |
| `isComplete` | `(condition: FilterCondition) => boolean` | Decides when a condition on this field is complete (it reaches the query and gets a pill). Defaults to a check on the value for the operator. |
| `apply` | `(builder: FilterBuilder, condition: FilterCondition) => void` | Replaces the whole query of a condition on this field. |
| `whenAbsent` | `(builder: FilterBuilder) => void` | Query added when the field has no condition at all (for example "hide archived" until the user asks for them). |
| `format` | `(condition: FilterCondition) => string` | Replaces the text of the value in the pill. |
| `negativesIncludeEmpty` | `boolean` | Negative operators (`isNot`, `notContains`, `ne`, `notIn`, `noneOf`, `notBetween`) also keep the rows where the column is empty: "surname is not Rossi" shows the clients without a surname too. On by default (option of `Filters` / `filtersToBuilder`); this one wins. Needs a backend that knows `null` modifiers: pass `false` for backends E and E'. |
| `json` | `{ column: string; key: string; cast?: 'text' \| 'numeric' \| 'date' \| 'timestamp' \| 'boolean' }` | The value lives in a key of a JSONB column (`customFields.color`): equalities use `whereJsonSuperset`; with `cast` every operator works through a parametrized `whereRaw` (accepted only by backends that allow raw conditions). |
| `type` (required) | `'select'` |  |
| `items` | `FilterItem[]` | The options, when they are known. |
| `searcher` | `(params: { searchText: string; signal: AbortSignal }) => Promise<FilterItem[]>` | Loads the options matching the typed text (from an API), instead of `items`. |
| `view` | `'autocomplete' \| 'toggle' \| 'countries'` | How the options are picked: an autocomplete (default), toggle buttons (few options), or countries with flags. |
| `shortcuts` | `FilterItem[]` | Options added at the top of the list, such as "Me" for the current user. |
| `locale` | `string` | Locale of the country names with `view: 'countries'`. |
| `placeholder` | `string` | Placeholder of the input. |
| `array` | `boolean` | The column (or the JSON key, with `json`) holds a list of values: `in` = has any of (`&&`), `notIn` = has none of, `all` = has all of (`@>`), `empty` = null or `{}`. |

### BoolFilterField

A yes/no field.

`interface BoolFilterField extends FieldBase`

| Name | Type | Description |
| --- | --- | --- |
| `name` (required) | `string` | Identity of the field, stored in the conditions. |
| `label` (required) | `string` | Name shown to the user. |
| `icon` | `string` | SVG path of an icon shown in the list, the card and the pill. |
| `category` | `string` | Groups the fields in the list of "Add filter". |
| `description` | `string` | Secondary text in the list of fields. |
| `column` | `string` | Column of the query. Defaults to `name`. |
| `joins` | `FilterJoin[]` | Joins added to the query when the field has a condition. |
| `through` | `FilterThrough \| FilterThrough[]` | The condition is checked in a subquery on a related table (`column` is a column of the last hop). Several hops nest. |
| `operators` | `FilterOperatorSet \| (string \| FilterOperatorDefinition)[]` | Operators offered, in this order: names of the built-in ones of the type, definitions of new ones, or a whole set (`basic`, `standard`, `all`). Defaults to the set chosen on `Filters` (`standard`). |
| `defaultOperator` | `string` | Operator of a new condition. Defaults to the first one. |
| `pinned` | `boolean` | Always shown as a pill in the bar, even without a condition. |
| `hidden` | `boolean` | Never shown: its conditions (usually `locked`) only reach the query. |
| `defaultValue` | `FilterConditionValue` | Value of a new condition on this field (the card and the panel start with it). |
| `isComplete` | `(condition: FilterCondition) => boolean` | Decides when a condition on this field is complete (it reaches the query and gets a pill). Defaults to a check on the value for the operator. |
| `apply` | `(builder: FilterBuilder, condition: FilterCondition) => void` | Replaces the whole query of a condition on this field. |
| `whenAbsent` | `(builder: FilterBuilder) => void` | Query added when the field has no condition at all (for example "hide archived" until the user asks for them). |
| `format` | `(condition: FilterCondition) => string` | Replaces the text of the value in the pill. |
| `negativesIncludeEmpty` | `boolean` | Negative operators (`isNot`, `notContains`, `ne`, `notIn`, `noneOf`, `notBetween`) also keep the rows where the column is empty: "surname is not Rossi" shows the clients without a surname too. On by default (option of `Filters` / `filtersToBuilder`); this one wins. Needs a backend that knows `null` modifiers: pass `false` for backends E and E'. |
| `json` | `{ column: string; key: string; cast?: 'text' \| 'numeric' \| 'date' \| 'timestamp' \| 'boolean' }` | The value lives in a key of a JSONB column (`customFields.color`): equalities use `whereJsonSuperset`; with `cast` every operator works through a parametrized `whereRaw` (accepted only by backends that allow raw conditions). |
| `type` (required) | `'bool'` |  |
| `trueLabel` | `string` | Text of `isTrue` in the pill and the card. Default `Yes`. |
| `falseLabel` | `string` | Text of `isFalse`. Default `No`. |
| `whenTrue` | `(builder: FilterBuilder) => void` | Query of `isTrue`, when it is not `column = true` (for example `whereColumn('quantity', '<', 'minQuantity')`). |
| `whenFalse` | `(builder: FilterBuilder) => void` | Query of `isFalse`, when it is not `column = false`. |
| `nullable` | `boolean` | The column can be null: adds `empty` and `notEmpty`. |

### CustomFilterField

A field with an input of the app.

`interface CustomFilterField extends FieldBase`

| Name | Type | Description |
| --- | --- | --- |
| `name` (required) | `string` | Identity of the field, stored in the conditions. |
| `label` (required) | `string` | Name shown to the user. |
| `icon` | `string` | SVG path of an icon shown in the list, the card and the pill. |
| `category` | `string` | Groups the fields in the list of "Add filter". |
| `description` | `string` | Secondary text in the list of fields. |
| `column` | `string` | Column of the query. Defaults to `name`. |
| `joins` | `FilterJoin[]` | Joins added to the query when the field has a condition. |
| `through` | `FilterThrough \| FilterThrough[]` | The condition is checked in a subquery on a related table (`column` is a column of the last hop). Several hops nest. |
| `operators` | `FilterOperatorSet \| (string \| FilterOperatorDefinition)[]` | Operators offered, in this order: names of the built-in ones of the type, definitions of new ones, or a whole set (`basic`, `standard`, `all`). Defaults to the set chosen on `Filters` (`standard`). |
| `defaultOperator` | `string` | Operator of a new condition. Defaults to the first one. |
| `pinned` | `boolean` | Always shown as a pill in the bar, even without a condition. |
| `hidden` | `boolean` | Never shown: its conditions (usually `locked`) only reach the query. |
| `defaultValue` | `FilterConditionValue` | Value of a new condition on this field (the card and the panel start with it). |
| `isComplete` | `(condition: FilterCondition) => boolean` | Decides when a condition on this field is complete (it reaches the query and gets a pill). Defaults to a check on the value for the operator. |
| `apply` | `(builder: FilterBuilder, condition: FilterCondition) => void` | Replaces the whole query of a condition on this field. |
| `whenAbsent` | `(builder: FilterBuilder) => void` | Query added when the field has no condition at all (for example "hide archived" until the user asks for them). |
| `format` | `(condition: FilterCondition) => string` | Replaces the text of the value in the pill. |
| `negativesIncludeEmpty` | `boolean` | Negative operators (`isNot`, `notContains`, `ne`, `notIn`, `noneOf`, `notBetween`) also keep the rows where the column is empty: "surname is not Rossi" shows the clients without a surname too. On by default (option of `Filters` / `filtersToBuilder`); this one wins. Needs a backend that knows `null` modifiers: pass `false` for backends E and E'. |
| `json` | `{ column: string; key: string; cast?: 'text' \| 'numeric' \| 'date' \| 'timestamp' \| 'boolean' }` | The value lives in a key of a JSONB column (`customFields.color`): equalities use `whereJsonSuperset`; with `cast` every operator works through a parametrized `whereRaw` (accepted only by backends that allow raw conditions). |
| `type` (required) | `'custom'` |  |

### FilterLogic

How the conditions of a group are combined.

`type FilterLogic = 'and' \| 'or'`

### FilterNode

A condition or a group.

`type FilterNode = FilterCondition \| FilterGroup`

### DataTableActionContext

What the `onclick` of a `DataTableAction` receives.

`interface DataTableActionContext<Row = any>`

| Name | Type | Description |
| --- | --- | --- |
| `selected` (required) | `Row[]` | Selected rows (empty while `selectedAll`). |
| `selectedAll` (required) | `boolean` | Every row of the result is selected, except `excluded`. |
| `excluded` (required) | `Row[]` | Rows left out of `selectedAll`. |
| `count` (required) | `number \| undefined` | Number of selected rows; `undefined` when every row is selected and the total is unknown. |
| `clear` (required) | `() => void` | Empties the selection. |
| `event` (required) | `MouseEvent` | The native click. |

### FilterJoin

A join the field needs, added once per query however many conditions use it.

`interface FilterJoin`

| Name | Type | Description |
| --- | --- | --- |
| `table` (required) | `string` | Table, with an alias if needed (`suppliers as primary_supplier`). |
| `on` (required) | `[string, string] \| [string, string, string]` | `[from, to]` (equality) or `[from, operator, to]`. |
| `kind` | `'left' \| 'inner'` | Default `left`, so the join itself filters nothing. |

### FilterThrough

A hop of a relation reached through a subquery: `key IN (SELECT select FROM from WHERE ...)`.

`interface FilterThrough`

| Name | Type | Description |
| --- | --- | --- |
| `key` (required) | `string` | Column of the outer query compared with the subquery (`users.id`). |
| `from` (required) | `string` | Table of the subquery (`user_residences`). |
| `select` (required) | `string` | Column selected by the subquery (`userId`). |
| `joins` | `FilterJoin[]` | Joins inside the subquery. |
| `where` | `(builder: FilterBuilder) => void` | Fixed conditions inside the subquery. |

### FilterOperatorDefinition

An operator defined by the app for one field.

`interface FilterOperatorDefinition`

| Name | Type | Description |
| --- | --- | --- |
| `name` (required) | `string` | Name stored in the conditions. |
| `label` (required) | `string` | Text between the field and the value (`is`, `≥`, `has tag`). |
| `input` (required) | `FilterInput` | Input shown for the value. `custom` uses the field's `inputSnippet`. |
| `apply` | `(builder: FilterBuilder, condition: FilterCondition) => void` | Adds the query for a condition with this operator. Without it the field's `apply` is used. |

### FilterOperatorSet

How many operators the fields offer: `basic` the essential ones, `standard` the common ones (default), `all` every built-in one.

`type FilterOperatorSet = 'basic' \| 'standard' \| 'all'`

### FilterConditionValue

Value of a condition. Its shape depends on the operator (see `FilterInput`). Dates are `yyyy-MM-dd` strings, so the whole tree is plain JSON.

`type FilterConditionValue = string \| number \| boolean \| { from?: number \| string; to?: number \| string } \| FilterItem[] \| FilterPeriod \| unknown`

### FilterCondition

A condition of the tree: a field, an operator and a value.

`interface FilterCondition`

| Name | Type | Description |
| --- | --- | --- |
| `id` (required) | `string` | Identity inside the tree, made by the helpers. Not shown anywhere. |
| `field` (required) | `string` | `name` of the field. |
| `operator` (required) | `string` | Name of the operator, one of the field's. |
| `value` | `FilterConditionValue` | Value for the operator. |
| `locked` | `boolean` | The user sees the condition but cannot change or remove it. |
| `preset` | `string` | `id` of the preset that added the condition: the preset chip is on while its conditions are in the tree. |

### FilterItem

An option of a select field: an `Item`, optionally standing for several values in the query.

`type FilterItem<Data = unknown> = Item<Data> & { … }`

| Name | Type | Description |
| --- | --- | --- |
| `values` | `(string \| number)[]` | Values the option stands for in the query (for example "In progress" = four statuses). Defaults to `[value]`. |

### FilterPeriod

A period relative to today, for the date operator `period`.

`type FilterPeriod = 'today' \| 'yesterday' \| 'tomorrow' \| 'thisWeek' \| 'lastWeek' \| 'nextWeek' \| 'thisMonth' \| 'lastMonth' \| 'nextMonth' \| 'thisQuarter' \| 'lastQuarter' \| 'nextQuarter' \| 'thisYear' \| 'lastYear' \| 'nextYear' \| 'monthToDate' \| 'quarterToDate' \| 'yearToDate'`

### FilterInput

Kind of value an operator asks for, which decides the input shown to the user.

`type FilterInput = 'none' \| 'text' \| 'texts' \| 'number' \| 'numbers' \| 'numberRange' \| 'date' \| 'dateRange' \| 'datetime' \| 'datetimeRange' \| 'days' \| 'relative' \| 'period' \| 'items' \| 'column' \| 'suggest' \| 'custom'`

### Item

An option of a picker (Autocomplete, Select, ...).

`type Item<Data = unknown> = { … }`

| Name | Type | Description |
| --- | --- | --- |
| `value` (required) | `string \| number` | Identity of the option: two items are the same option when their `value`s are equal (`===`). |
| `label` | `string \| number` | Text shown and searched. Defaults to `value`. |
| `icon` | `string` | SVG path of an icon shown before the label, for example from `@mdi/js`. |
| `data` | `Data` | Any extra data, available in snippets and callbacks. |

## CSS variables

For a single instance, pass them as style props: `<DataTable --data-table-background="tomato">`. The `--data-table-default-*` defaults apply to the whole app: override them in `:root` or in a theme.

It also takes the variables of Table (`/components/table.md`).

| Per-instance variable | Default |
| --- | --- |
| `--data-table-width` | `--data-table-default-width`: `100%` |
| `--data-table-border` | `--data-table-default-border`: `var(--global-border-width) solid var(--global-color-border)` |
| `--data-table-border-radius` | `--data-table-default-border-radius`: `var(--global-radius-lg)` |
| `--data-table-background` | `--data-table-default-background`: `var(--global-color-surface-solid)` |
| `--data-table-color` | `--data-table-default-color`: `var(--global-color-text)` |
| `--data-table-font-size` | `--data-table-default-font-size`: `13.5px` |
| `--data-table-toolbar-gap` | `--data-table-default-toolbar-gap`: `8px` |
| `--data-table-toolbar-padding` | `--data-table-default-toolbar-padding`: `10px 12px` |
| `--data-table-separator-color` | `--data-table-default-separator-color`: `var(--global-color-border)` |
| `--data-table-toolbar-background` | `--data-table-default-toolbar-background`: `transparent` |
| `--data-table-control-height` | `--data-table-default-control-height`: `28px` |
| `--data-table-search-width` | `--data-table-default-search-width`: `240px` |
| `--data-table-message-padding` | `--data-table-default-message-padding`: `12px 14px` |
| `--data-table-message-color` | `--data-table-default-message-color`: `var(--global-color-text-2)` |
| `--data-table-footer-font-size` | `--data-table-default-footer-font-size`: `12.5px` |
| `--data-table-error-color` | `--data-table-default-error-color`: `var(--global-color-error)` |
| `--data-table-selection-offset` | `--data-table-default-selection-offset`: `16px` |
| `--data-table-selection-padding` | `--data-table-default-selection-padding`: `6px 6px 6px 14px` |
| `--data-table-selection-border` | `--data-table-default-selection-border`: `var(--global-border-width) solid var(--global-color-border-strong)` |
| `--data-table-selection-border-radius` | `--data-table-default-selection-border-radius`: `var(--global-radius-lg)` |
| `--data-table-selection-background` | `--data-table-default-selection-background`: `var(--global-color-surface-pop)` |
| `--data-table-selection-shadow` | `--data-table-default-selection-shadow`: `var(--global-shadow-lg), 0 0 60px -20px var(--global-color-primary-glow)` |
| `--data-table-selection-color` | `--data-table-default-selection-color`: `var(--global-color-text)` |
| `--data-table-duration` | `--data-table-default-duration`: `var(--global-duration-fast)` |
| `--data-table-easing` | `--data-table-default-easing`: `var(--global-ease)` |
| `--data-table-selection-count-background` | `--data-table-default-selection-count-background`: `var(--global-color-primary)` |
| `--data-table-selection-count-color` | `--data-table-default-selection-count-color`: `var(--global-color-on-primary)` |
| `--data-table-footer-padding` | `--data-table-default-footer-padding`: `10px 14px` |
| `--data-table-footer-color` | `--data-table-default-footer-color`: `var(--global-color-text-3)` |
