---
name: table
description: "Use when building or changing a data table or list page in app: useLayoutTable, LayoutTable, createLayoutColumnHelper, columns and headers, cell formatters, filter variants, sorting, row selection and bulk actions, per-row actions, pagination or server paging, footer aggregation, column sizing, or styling table parts."
metadata:
  type: convention
  library: wcz-layout
---

`useLayoutTable` and `createLayoutColumnHelper` (`wcz-layout/hooks`) are the `useAppTable` and
`createAppColumnHelper` of TanStack Table v9's `createTableHook`, with wcz-layout's features and
components; feature APIs: load `@tanstack/table-core#table-features`. Never render a
`<table>` or `useTable` yourself, and ignore upstream's own virtualization and pagination
setup: `LayoutTable` (`wcz-layout/components`) does both.

## Rules

- `const table = useLayoutTable({ data, columns })`, then `<LayoutTable table={table} />`.
  Rows are keyed by `row.id`, so every row needs an `id`. A list page wraps it in
  `Fullscreen` and passes `loading={isLoading}` from `useLiveQuery`.
- Columns: `columnHelper.columns([...])` with `columnHelper.accessor("field", …)` or
  `columnHelper.display({ id, … })`, from a module-level
  `const columnHelper = createLayoutColumnHelper<Entity>()`. No row models: the features are
  installed.
- Cells render the bound formatters, `cell.ValueCell`, `NumberCell`, `DateCell`, `DateTimeCell`,
  `BooleanCell`: they carry alignment, locale formats and one-line ellipsis. Raw JSX only for a
  link or another interactive element.
- Selection and actions display columns: `size: 50`, `enableResizing: false`,
  `enableCellSelection: false`; each extra visible action button adds about 40 px.
- `meta` keys: `label`, `align`, `variant`, `options`, `flex`. A column whose `header` is not
  a plain string needs `meta.label` (header menu, column selector and filter picker read it).
- `meta.variant` picks the filter: `"text"` (default), `"number"`, `"boolean"`, `"date"`,
  `"select"`, `"multi-select"`. Select variants build their options from the faceted unique
  values; pass `options` only when labels differ from stored values or the list is fixed, and
  for a database enum derive them from `.enumValues`.
- `size` is the starting width. `meta.flex` lets a column grow and shrink in proportion, like
  CSS `flex`, so the table fills its container without horizontal scroll; it stops at
  `minSize` (default 20), after which the table scrolls. A resized column keeps its width.
- Rows and columns virtualize and rows are measured: a cell may wrap onto several lines once
  its content has `whiteSpace: "normal"`.
- Toolbar actions: create (`RouterIconButton` to the create page), edit when exactly one row is
  selected, delete when any are: `confirm(t("DeleteConfirmation", { count }))`, the optimistic
  delete, `when("settled")`, then `table.resetRowSelection()`; `catch` alerts. Icons are
  `fontSize="small"` inside a `Tooltip`.
- `LayoutTable` props: `title`, `actions`, `showToolbar`, `loading`, `pagination`,
  `pageSizeOptions`, `onRowClick`, `onRowDoubleClick`, `sx`, and `disableSearch`,
  `disableColumnFilter`, `disableColumnSelector`, `disableColumnMenu`.
- Server-paged tables (reports, lists sorted over more rows than the browser should hold;
  deep offset collection queries load a growing prefix, see client-db): use Query/server pages.
  Load upstream Query integration/state guidance for request keys, totals and manual flags; pass
  `manualPagination: true`, `rowCount` and controlled `state.pagination` /
  `onPaginationChange` (plus the `manual*` flags for what the server sorts and filters) to
  `useLayoutTable`, with `pagination` on `LayoutTable`.

## Example

```tsx
// src/routes/features/index.tsx
import { Fullscreen, LayoutTable, RouterIconButton, RouterLink } from "wcz-layout/components";
import {
  createLayoutColumnHelper,
  useDialogs,
  useLayoutTable,
  useTranslation,
} from "wcz-layout/hooks";

export const Route = createFileRoute("/features/")({
  component: RouteComponent,
  beforeLoad: requireAuth("admin"),
  loader: ({ context }) => context.dbClient.preloadLiveQuery(featuresQueryOptions),
});

const columnHelper = createLayoutColumnHelper<Feature>();

function RouteComponent() {
  const { t } = useTranslation();
  const { confirm, alert } = useDialogs();
  const navigate = useNavigate();
  const features = useFeatureCollection();
  const { data, isLoading } = useLiveQuery(featuresQueryOptions);

  const columns = columnHelper.columns([
    columnHelper.display({
      id: "select",
      header: ({ header }) => <header.SelectAllCell scope="all" />,
      cell: ({ cell }) => <cell.SelectCell />,
      size: 50,
      enableResizing: false,
      enableCellSelection: false,
    }),
    columnHelper.accessor("name", {
      header: t("Feature.Name"),
      cell: ({ cell }) => (
        <RouterLink
          to="/features/$id"
          params={{ id: cell.row.original.id }}
          underline="hover"
          color="inherit"
        >
          {cell.getValue()}
        </RouterLink>
      ),
      size: 260,
      meta: { flex: 1 },
    }),
  ]);

  const table = useLayoutTable({ data, columns });
  const selectedIds = table.getSelectedRowIds();

  const handleOnDelete = createOptimisticAction<Array<string>>({
    onMutate: (ids) => {
      ids.forEach((id) => {
        features.delete(id);
      });
    },
    mutationFn: async (ids) => {
      await deleteFeatures({ data: ids });
      await features.utils.refetch({ throwOnError: true });
    },
  });

  return (
    <Fullscreen>
      <LayoutTable
        table={table}
        loading={isLoading}
        showToolbar
        title={t("Feature.Features")}
        onRowDoubleClick={(row) => navigate({ to: "/features/$id", params: { id: row.id } })}
        actions={
          <>
            <Tooltip title={t("Create")}>
              <RouterIconButton to="/features/create">
                <Add fontSize="small" />
              </RouterIconButton>
            </Tooltip>
            {selectedIds.length === 1 && (
              <Tooltip title={t("Edit")}>
                <RouterIconButton to="/features/edit/$id" params={{ id: selectedIds[0] }}>
                  <Edit fontSize="small" />
                </RouterIconButton>
              </Tooltip>
            )}
            {selectedIds.length > 0 && (
              <Tooltip title={t("Delete")}>
                <IconButton
                  onClick={async () => {
                    if (!(await confirm(t("DeleteConfirmation", { count: selectedIds.length }))))
                      return;
                    try {
                      await handleOnDelete(selectedIds).when("settled");
                      table.resetRowSelection();
                    } catch (error) {
                      if (error instanceof Error) await alert(error.message);
                    }
                  }}
                >
                  <Badge
                    badgeContent={selectedIds.length}
                    invisible={selectedIds.length <= 1}
                    color="error"
                  >
                    <Delete fontSize="small" />
                  </Badge>
                </IconButton>
              </Tooltip>
            )}
          </>
        }
      />
    </Fullscreen>
  );
}
```

Additional columns only when the entity schema has these fields:

```tsx
import { Typography } from "@mui/material";
import { featureStatusEnum } from "~/server/db/schemas/feature";

columnHelper.accessor("quantity", {
  header: t("Feature.Quantity"),
  cell: ({ cell }) => <cell.NumberCell />,
  footer: ({ header }) => <header.AggregationFooter />,
  aggregationFn: "sum",
  meta: { variant: "number", align: "right" },
});
columnHelper.accessor("active", {
  header: t("Feature.Active"),
  cell: ({ cell }) => <cell.BooleanCell />,
  meta: { variant: "boolean", align: "center" },
});
columnHelper.accessor("dueAt", {
  header: t("Feature.DueAt"),
  cell: ({ cell }) => <cell.DateCell />,
  meta: { variant: "date" },
});
columnHelper.accessor("status", {
  header: t("Feature.Status"),
  cell: ({ cell }) => (
    <Typography variant="body2" noWrap>
      {t(`Feature.StatusLabels.${cell.getValue()}`)}
    </Typography>
  ),
  meta: {
    variant: "multi-select",
    options: featureStatusEnum.enumValues.map((value) => ({
      value,
      label: t(`Feature.StatusLabels.${value}`),
    })),
  },
});
```

```tsx
// per-row actions: one inline button, the rest in the row menu
columnHelper.display({
  id: "actions",
  cell: ({ cell }) => (
    <cell.ActionsCell
      actions={[
        {
          label: t("Edit"),
          icon: <Edit fontSize="small" />,
          onClick: (row) => navigate({ to: "/features/edit/$id", params: { id: row.id } }),
        },
        {
          label: t("Delete"),
          icon: <Delete fontSize="small" />,
          showInMenu: true,
          onClick: (row) => remove(row.id),
        },
      ]}
    />
  ),
  size: 50,
  enableResizing: false,
  enableCellSelection: false,
});
```

## Bound components

Header render prop: `SelectAllCell`, `ExpandAllCell`, `AggregationFooter`, `HeaderMenu`,
`HeaderSortLabel`, `HeaderResizeHandle`. Cell render prop: `SelectCell`, `ExpandCell`,
`GroupCell`, `PinRowCell`, `ActionsCell` and the formatters. `LayoutTable` already places the
menu, sort label and resize handle. A custom cell or header is a plain component reading
`useCellContext<TValue>()`, `useHeaderContext()` or `useTableContext()` from `wcz-layout/hooks`;
`layoutTableFeatures` and `LayoutTableFeatures` only type a hand-built table instance.
