# Column operations

> Resize, reorder, pin, hide and autosize columns from the UI or the API, and save and restore the layout with ColumnState.

Users can rearrange columns directly in the header, and everything they can do is also available from code. The resulting layout is captured as plain `ColumnState` objects you can store and restore.

**Live demo: Pinned columns** (runs on the HTML version of this page). Source of `demos/pinned-columns.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
import { createGrid, type ColumnDef } from '@birchui/core';
import { button, currency, docsTheme, layout, onDocsThemeChange, seededRandom } from './_shared';

export const meta = { title: 'Pinned columns', height: 440 };

interface AccountRevenue {
  account: string;
  owner: string;
  months: number[];
}

const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const ACCOUNTS = [
  'Northwind Traders',
  'Blue Harbor Foods',
  'Alpine Outfitters',
  'Kestrel Logistics',
  'Maison Duval',
  'Oakridge Clinics',
  'Sakura Retail Group',
  'Harbourline Marine',
  'Lotus Electronics',
  'Andes Coffee Co.',
  'Rio Verde Agro',
  'Cedar & Stone',
];
const OWNERS = ['Amelia Hart', 'Jonas Becker', 'Priya Natarajan', 'Diego Alvarez'];

function makeAccounts(): AccountRevenue[] {
  const random = seededRandom(42);
  return Array.from({ length: 60 }, (_, i) => ({
    account: `${ACCOUNTS[i % ACCOUNTS.length]}${i >= ACCOUNTS.length ? ` (${Math.floor(i / ACCOUNTS.length) + 1})` : ''}`,
    owner: OWNERS[i % OWNERS.length],
    months: MONTHS.map(() => Math.round(8000 + random() * 42000)),
  }));
}

const money = (value: unknown) => (typeof value === 'number' ? currency.format(value) : '');

const columns: ColumnDef<AccountRevenue>[] = [
  { field: 'account', header: 'Account', width: 210, pinned: 'left' },
  { field: 'owner', header: 'Owner', width: 150 },
  ...MONTHS.map((month, index): ColumnDef<AccountRevenue> => ({
    id: month.toLowerCase(),
    header: month,
    type: 'number',
    width: 110,
    valueGetter: (row) => row.months[index],
    format: money,
  })),
  {
    id: 'total',
    header: 'Total',
    type: 'number',
    width: 130,
    pinned: 'right',
    valueGetter: (row) => row.months.reduce((sum, value) => sum + value, 0),
    format: money,
    cellClass: 'demo-total',
  },
];

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  const grid = createGrid<AccountRevenue>(body, {
    columns,
    rows: makeAccounts(),
    getRowId: (row) => row.account,
    theme: docsTheme(),
    ariaLabel: 'Monthly revenue by account',
  });
  let ownerPinned = false;
  toolbar.append(
    button('Pin or unpin Owner', () => {
      ownerPinned = !ownerPinned;
      grid.setColumnPinned('owner', ownerPinned ? 'left' : null);
    }),
    button('Autosize all', () => grid.autosizeColumns()),
    button('Reset layout', () => {
      ownerPinned = false;
      grid.setColumns(columns);
    }),
  );
  const describe = () => {
    const pinned = grid
      .getColumnState()
      .filter((c) => c.pinned)
      .map((c) => `${c.colId} (${c.pinned})`);
    status.textContent = `Pinned: ${pinned.join(', ') || 'none'}. Drag a header to reorder, or drag its edge to resize.`;
  };
  const off = grid.on('columnStateChanged', describe);
  describe();
  const stopTheme = onDocsThemeChange((theme) => grid.update({ theme }));
  return () => {
    off();
    stopTheme();
    grid.destroy();
  };
}
```

## Resizing

Drag the right edge of a header cell to resize a column. Widths are clamped to the column's `minWidth` (40 pixels by default) and `maxWidth`. Set `resizable: false` to lock a column.

```ts title="resizing.ts"
import { createGrid, type ColumnDef } from '@birchui/core';

const columns: ColumnDef<Order>[] = [
  { field: 'id', header: 'Order', width: 120, resizable: false },
  { field: 'customer', width: 240, minWidth: 160, maxWidth: 420 },
  { field: 'revenue', type: 'number', width: 140 },
];

const grid = createGrid<Order>(document.querySelector('#orders')!, { columns, rows: orders });

grid.setColumnWidth('customer', 300);
grid.on('columnResized', ({ colId, width }) => console.info(`${colId} is now ${width}px`));
```

A flex column that is resized keeps its new width and stops flexing.

### Autosizing

Double-click a header's resize edge to fit the column to its content. From code, `autosizeColumn(colId)` does the same and `autosizeColumns()` fits every visible, resizable column.

```ts
grid.autosizeColumns();
grid.autosizeColumn('customer');
```

The grid measures the header label and the formatted text of up to the first 1,000 display rows, adds room for padding and the header controls, and caps the result at 640 pixels before applying `minWidth` and `maxWidth`. Because it measures display rows, autosizing after a filter or sort can produce a different width. Call it once after the first data load, or in a `ready` listener.

## Reordering

Drag a header to a new position to reorder columns. A drop indicator shows where the column will land. Dropping a column among pinned columns pins it to that side, and dropping a pinned column among unpinned ones unpins it. Set `reorderable: false` to keep a column in place.

From code, `moveColumn(colId, toIndex)` moves a column to a position in the full column order, including hidden columns.

```ts
grid.moveColumn('revenue', 1);
grid.on('columnMoved', ({ colId, toIndex }) => console.info(`${colId} moved to ${toIndex}`));
```

## Pinning

Pinned columns stay visible while the rest of the grid scrolls horizontally. Left-pinned columns are drawn first, then unpinned columns, then right-pinned columns.

```ts
const columns: ColumnDef<Order>[] = [
  { field: 'id', header: 'Order', pinned: 'left', width: 120 },
  { field: 'customer', pinned: 'left', width: 220 },
  { field: 'region' },
  { field: 'product' },
  { field: 'quantity', type: 'number' },
  { field: 'unitPrice', type: 'number' },
  { field: 'revenue', type: 'number', pinned: 'right' },
];

grid.setColumnPinned('region', 'left');
grid.setColumnPinned('customer', null);
grid.on('columnPinned', ({ colId, pinned }) => console.info(colId, pinned ?? 'unpinned'));
```

> **Tip**
>
> Keep pinned areas narrow. Pinned columns never scroll, so on a small screen a wide pinned area leaves little room for everything else. A common pattern is to pin only the identifying column on the left and a total or action column on the right.

## Hiding

`hidden: true` in the column definition starts a column hidden. `setColumnHidden(colId, hidden)` toggles it at runtime. Hidden columns keep their width, position and pin state. They are still searched by the quick filter, but they are left out of CSV export.

```ts
const toggles = document.querySelectorAll<HTMLInputElement>('[data-column-toggle]');
for (const toggle of toggles) {
  toggle.checked = !grid.getColumn(toggle.value)?.hidden;
  toggle.addEventListener('change', () => grid.setColumnHidden(toggle.value, !toggle.checked));
}

grid.on('columnVisible', ({ colId, hidden }) => console.info(colId, hidden ? 'hidden' : 'shown'));
```

## The column menu

Each header has a menu button that appears on hover and focus. Right-clicking a header, pressing <kbd>Alt</kbd>+<kbd>Arrow Down</kbd> or the context menu key on a focused header opens the same menu. It offers:

| Group | Items |
| --- | --- |
| Sort (sortable columns) | Sort ascending, Sort descending, Clear sort |
| Pin | Pin left, Pin right, Unpin |
| Size | Autosize this column, Autosize all columns |
| Visibility | Hide column (disabled for the last visible column), Show all columns, when some are hidden |

Modules can add items with `addColumnMenuItems`; Grid Pro adds **Group by this column**, **Ungroup** and **Export to Excel** this way. See [Modules](https://docs.birchui.com/grid/modules.md#column-menu-items).

## Scrolling to a column

`scrollToColumn(colId)` scrolls horizontally until the column is in view. Pinned columns are always in view.

```ts
grid.scrollToColumn('unitPrice');
```

## Saving and restoring column state

`getColumnState()` returns one `ColumnState` per column with its current width, pin state, visibility and position. `applyColumnState(state)` applies a saved state. Each entry only changes the properties it contains, so a partial state such as `[{ colId: 'revenue', hidden: true }]` is valid.

**`ColumnState`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface ColumnState
```

| Property | Type | Description |
| --- | --- | --- |
| `colId` | `string` |  |
| `width?` | `number` |  |
| `pinned?` | `'left' \| 'right' \| null` |  |
| `hidden?` | `boolean` |  |
| `order?` | `number` |  |

### Persisting the layout in localStorage

```ts title="persist-columns.ts"
import { createGrid, type ColumnState } from '@birchui/core';

const STORAGE_KEY = 'orders-grid.columns.v1';

function loadColumnState(): ColumnState[] | null {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    return raw ? (JSON.parse(raw) as ColumnState[]) : null;
  } catch {
    return null;
  }
}

const grid = createGrid<Order>(document.querySelector('#orders')!, {
  columns,
  rows: orders,
  getRowId: (o) => o.id,
});

const saved = loadColumnState();
if (saved) grid.applyColumnState(saved);

grid.on('columnStateChanged', ({ state }) => {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
});

document.querySelector('#reset-layout')!.addEventListener('click', () => {
  localStorage.removeItem(STORAGE_KEY);
  grid.applyColumnState(
    columns.map((def, order) => ({
      colId: def.id ?? def.field!,
      width: def.flex ? undefined : (def.width ?? 150),
      pinned: def.pinned ?? null,
      hidden: def.hidden ?? false,
      order,
    })),
  );
});
```

`columnStateChanged` fires after any resize, move, pin or visibility change, with the full state, so one listener is enough to persist everything. Columns in a saved state that no longer exist are ignored, and new columns that are missing from it keep their defaults, so old saved layouts keep working when you add columns. Version the storage key when you change column IDs.

> **Note**
>
> Column state covers layout only. Sort and filters have their own models: save `getSort()` and `getFilterModel()` alongside it if you want to restore the whole view. See [Sorting](https://docs.birchui.com/grid/sorting.md#reacting-to-sort-changes) and [Filtering](https://docs.birchui.com/grid/filtering.md#reacting-to-filter-changes).

## API summary

**`GridApi`** (interface from `@birchui/core`, full reference: https://docs.birchui.com/api/core.md)

```ts
interface GridApi<TRow = RowData> extends Widget<GridOptions<TRow>, GridEvents<TRow>>, GridFeatureApi<TRow>
```

| Property | Type | Description |
| --- | --- | --- |
| `getColumns` | `() => readonly ResolvedColumn<TRow>[]` |  |
| `getDisplayColumns` | `() => readonly ResolvedColumn<TRow>[]` |  |
| `getColumn` | `(colId: string) => ResolvedColumn<TRow> \| undefined` |  |
| `getColumnState` | `() => ColumnState[]` |  |
| `applyColumnState` | `(state: ColumnState[]) => void` |  |
| `setColumnWidth` | `(colId: string, width: number) => void` |  |
| `autosizeColumn` | `(colId: string) => void` |  |
| `autosizeColumns` | `() => void` |  |
| `moveColumn` | `(colId: string, toIndex: number) => void` |  |
| `setColumnPinned` | `(colId: string, pinned: 'left' \| 'right' \| null) => void` |  |
| `setColumnHidden` | `(colId: string, hidden: boolean) => void` |  |
| `scrollToColumn` | `(colId: string) => void` |  |

## Column events

| Event | Payload | Fires when |
| --- | --- | --- |
| `columnResized` | `{ colId, width }` | A column width changes |
| `columnMoved` | `{ colId, toIndex }` | A column moves |
| `columnPinned` | `{ colId, pinned }` | A column is pinned or unpinned |
| `columnVisible` | `{ colId, hidden }` | A column is hidden or shown |
| `columnStateChanged` | `{ state }` | After any of the above |

See the [Events reference](https://docs.birchui.com/grid/events.md) for every grid event.
