# Pinned columns and sticky rows

> Pin columns to the start or end, fix them in place between the scrolling columns, and keep the first or last rows in view while the body scrolls.

Canonical: https://salmonui.dev/docs/data-grid/pinned-columns

Pinned columns (also called frozen columns) stay in view while the other
columns scroll horizontally. The grid splits its columns into three zones:
a start zone, the scrolling center and an end zone. Only the center zone is
column-virtualized; pinned columns always render.

## Pinning columns

A column definition pins itself with `pinned: 'start'` or
`pinned: 'end'`. The sides are logical: `start` is the left edge in
a left-to-right grid and the right edge in RTL.

The grid `pinnedColumns` prop is a count shorthand:
`pinnedColumns={{ start: 2 }}` pins the
first two visible columns and `end` the last ones. It is reactive, and an
explicit column `pinned` always wins over the count.

```tsx
<DataGrid
  columns={[
    { field: 'id', header: 'Order', pinned: 'start' },
    // ...
    { field: 'amount', header: 'Amount', pinned: 'end' },
  ]}
  pinnedColumns={{ start: 2 }}
  stickyRows={2}
  stickyBottomRows={1}
/>
```

## Fixed columns

`pinned: 'center'` fixes a column in place: the column
stays where it is declared among the scrolling columns, with scrolling
columns on both sides of it. When you scroll, it moves with its slot until
it reaches the start edge (after the start-pinned columns and any earlier
fixed column), then stays there while the other columns pass beneath it.
A fixed column declared beyond the first screen waits at the end edge
(before the end-pinned columns) until its slot scrolls into view. So a
fixed column is always visible, and the slot it leaves is always covered.

```tsx
const columns = [
  { field: 'id', header: 'Order', pinned: 'start' },
  { field: 'customer', header: 'Customer' },
  { field: 'product', header: 'Product', pinned: 'center' },
  // ...
];
```

A fixed column keeps its place in the column order: keyboard navigation,
`aria-colindex` and reordering treat it as a scrolling column (drag it to
move its slot), and it stays rendered under column virtualization. When
focus scrolls another column into view, the grid keeps that column clear
of the fixed ones. `api.pinColumn(field, 'center')` fixes a column at
runtime; `null` releases it in place. With stacked headers, only the fixed
leaf header is sticky; its group header scrolls with the center.

## Pinning at runtime

The column menu and the header context menu carry `pinStart`, `pinEnd` and
`unpin` items; `unpin` also releases a fixed column. With the keyboard, Alt+Shift+ArrowLeft and
Alt+Shift+ArrowRight pin the focused header to the start or end and
Alt+Shift+ArrowUp unpins it. `api.pinColumn(field, 'start' | 'end' | 'center' | null)`
does the same from code. Every path raises the cancelable
`onBeforeColumnPinChange` (call `preventDefault()` to keep the column where
it is) and then `onColumnPinChange` with `pinned` and `previousPinned`.

A pinned column moves to the inner edge of its new zone; the column set is
not recompiled. Reordering, by drag or Mod+ArrowLeft / Mod+ArrowRight
(Alt+ArrowLeft / Alt+ArrowRight also work; Mod is Ctrl, or ⌘ on macOS),
never moves a column across a zone edge.

A shadow marks the edge of each pinned zone while content scrolls beneath
it, mirrored in RTL and replaced by a border in forced-colors mode.

## Editing pinned columns

Pinning only changes where a column is drawn. Cells of pinned columns edit
like scrolling cells: double-click, F2 and Enter start editing, and a column
pinned at runtime keeps its editor and validation. The demo below
uses `editing={{ mode: 'cell' }}`; edit the pinned Amount column, or pin
Customer and edit it there.

The fill handle, detail rows and child grids work with pinned columns too:

- **Fill handle.** With `editing.fillHandle`, a range drags across a pin
  edge like any column edge: from a start-pinned column into the scrolling
  columns, or from the scrolling columns into an end-pinned one, and down
  past the rendered rows with auto-scroll. The [Range fill](https://salmonui.dev/docs/data-grid/selection)
  demo pins Customer to the start and Note to the end.
- **Detail rows.** A detail row spans the full grid width under start and
  end pinned columns, and its content stays in view while the columns
  scroll (see [Detail rows](https://salmonui.dev/docs/data-grid/detail-rows)).
- **Child grids.** A child grid mounts in a full-width detail row of a
  parent with pinned columns and stays in view while the parent columns
  scroll (see [Child grids](https://salmonui.dev/docs/data-grid/child-grids)).

## Sticky rows

`stickyRows` keeps the first N rows of the visible row model below the
header, and `stickyBottomRows` keeps the last N above the footer.
The rows are positions
in the sorted, filtered row model, so they follow sorting and filtering, and
the virtual row window skips them.

### Live demo: Pinned columns and sticky rows

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

Columns pinned to the start or end, or fixed in place (`pinned: 'center'`), by definition, by the reactive `pinnedColumns` count or at runtime from the column menu, Alt+Shift+Arrow keys and `api.pinColumn`, plus `stickyRows` and `stickyBottomRows` over 2,000 virtualized rows.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, type DataGridApi, type DataGridColumn, type DataGridColumnMenuItemId, type DataGridMenuItem, type DataGridPinnedColumns } 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(2_000, 17);

// Wide enough to scroll horizontally: Order is pinned to the start and Amount
// to the end by definition; the rest scroll between them. Product is fixed
// (`pinned: 'center'`): it scrolls with its slot,
// then stays in view at the start or end edge of the scrolling columns.
const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110, pinned: 'start' },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'city', header: 'City', width: 130 },
  { field: 'product', header: 'Product', width: 150, pinned: 'center' },
  { field: 'category', header: 'Category', width: 120 },
  { field: 'quantity', header: 'Qty', type: 'number', align: 'end', width: 80 },
  { field: 'unitPrice', header: 'Unit price', type: 'number', format: 'C2', align: 'end', width: 110 },
  { field: 'discount', header: 'Discount', type: 'number', format: 'P0', align: 'end', width: 100 },
  { field: 'placed', header: 'Placed', type: 'datetime', format: 'yMMMd', width: 130 },
  { field: 'priority', header: 'Priority', width: 100 },
  { field: 'note', header: 'Note', width: 240 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120, pinned: 'end' },
];

// Pin items first; a separator is an item object.
const columnMenu: readonly (DataGridColumnMenuItemId | DataGridMenuItem)[] = ['pinStart', 'pinEnd', 'unpin', { id: 'separator', separator: true }, 'autoSize', 'autoSizeAll'];

const COUNT_OPTIONS = [0, 1, 2, 3].map((n) => ({ value: String(n), label: String(n) }));

// Cell editing works in every zone: double-click or press F2 on a pinned cell too.
const editing = { mode: 'cell' } as const;

export default function PinnedColumnsDemo() {
  const api = useRef<DataGridApi<Order> | null>(null);
  const [startCount, setStartCount] = useState(0);
  const [stickyRows, setStickyRows] = useState(2);
  const [stickyBottomRows, setStickyBottomRows] = useState(1);
  const [locked, setLocked] = useState(false);
  const [log, push] = useEventLog();
  // Reactive count shorthand: a new object re-applies; an explicit `pinned` beats the count.
  const pinnedColumns: DataGridPinnedColumns = { start: startCount };
  return (
    <>
      <div className="demo-toolbar">
        <label>
          Pinned start count
          <Select aria-label="Pinned start count" data={COUNT_OPTIONS} value={String(startCount)} onValueChange={(value) => value != null && setStartCount(Number(value))} />
        </label>
        <label>
          Sticky top rows
          <Select aria-label="Sticky top rows" data={COUNT_OPTIONS} value={String(stickyRows)} onValueChange={(value) => value != null && setStickyRows(Number(value))} />
        </label>
        <label>
          Sticky bottom rows
          <Select aria-label="Sticky bottom rows" data={COUNT_OPTIONS} value={String(stickyBottomRows)} onValueChange={(value) => value != null && setStickyBottomRows(Number(value))} />
        </label>
        <Checkbox checked={locked} onCheckedChange={(checked) => setLocked(checked)}>
          Cancel pin changes
        </Checkbox>
      </div>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={() => api.current?.pinColumn('customer', 'start')}>
          Pin Customer to the start
        </Button>
        <Button variant="outline" onClick={() => api.current?.pinColumn('priority', 'end')}>
          Pin Priority to the end
        </Button>
        <Button variant="outline" onClick={() => api.current?.pinColumn('amount', null)}>
          Unpin Amount
        </Button>
        <Button variant="outline" onClick={() => api.current?.pinColumn('note', 'center')}>
          Fix Note in place
        </Button>
        <Button variant="outline" onClick={() => api.current?.pinColumn('product', null)}>
          Unfix Product
        </Button>
      </div>
      <DataGrid<Order>
        aria-label="Orders with pinned columns and sticky rows"
        data={orders}
        columns={columns}
        pinnedColumns={pinnedColumns}
        stickyRows={stickyRows}
        stickyBottomRows={stickyBottomRows}
        columnMenu={columnMenu}
        editing={editing}
        sorting
        resizable
        reorderable
        height={380}
        locale="en-US"
        currency="USD"
        timeZone="UTC"
        ref={api}
        onBeforeColumnPinChange={(event) => {
          if (locked) {
            event.preventDefault();
            push(`pin canceled: ${event.field} → ${event.pinned ?? 'unpinned'}`);
          }
        }}
        onColumnPinChange={(event) => push(`pin (${event.source}): ${event.field} ${event.previousPinned ?? 'unpinned'} → ${event.pinned ?? 'unpinned'}`)}
        onColumnReorder={(event) => push(`reorder (${event.source}): ${event.field} ${event.fromIndex} → ${event.toIndex}`)}
      />
      <EventLog entries={log} />
    </>
  );
}
```

## API reference

[`DataGridColumn`](https://salmonui.dev/docs/reference/data-grid/DataGridColumn) has the
`pinned` field, [`DataGridPinnedColumns`](https://salmonui.dev/docs/reference/data-grid/DataGridPinnedColumns)
the `pinnedColumns` shape,
[`DataGridColumnPinChangeEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridColumnPinChangeEvent)
the pin events and [`DataGridApi`](https://salmonui.dev/docs/reference/data-grid/DataGridApi)
`pinColumn`.
