# Cells

Merged cells and long text that runs over empty neighbors make the table read like an Excel sheet.

## Merged cells

The `merges` prop merges cells: each `{ from, to }` rectangle becomes one cell with the content
and style of its first cell. `wrap` from `cellStyle` wraps long text inside it.

Rows and columns are counted as in `v-model:ranges`: by the row number on the current page and
the position among visible data columns.

The cursor lands on a merged cell as a whole and leaves it from its far edge. A selection extends
to cover merged cells completely, while selections of whole rows and columns stay as they are.
An edit changes the value of the first cell.

Paste, fill and clear leave the cells under a merged cell alone: their values are not seen. A paste
counts such cells as skipped.

When your own `commands` takes the edits, a block arrives whole with its `area`. The owner of the
data then decides what happens to the merges.

When a merged cell reaches into a pinned column, it is split at the edge of that column. A cell
spanning several rows gets no hover or row selection highlight and no stripe color. Merging does
not work with grouping, in a tree or with row details.

```vue
<template>
  <NuiTable
    cell-selection
    :columns="columns"
    :rows="slots"
    :get-key="keyOf"
    :merges="merges"
    :cell-style="styleOf"
    :column-menu="false"
    gridlines
    caption="Program of the day"
  />
</template>

<script setup lang="ts">
import {
  NuiTable,
  type NuiTableCellRef,
  type NuiTableCellStyle,
  type NuiTableColumn,
  type NuiTableRange,
} from '@numior/kit/table';

interface Slot {
  readonly time: string;
  readonly halls: readonly string[];
}

const HALLS = ['Hall A', 'Hall B', 'Hall C'];

const slots: Slot[] = [
  { time: '10:00', halls: ['Opening', '', ''] },
  { time: '11:00', halls: ['Forms without pain', 'Table workshop', 'Accessibility'] },
  { time: '12:00', halls: ['Themes and tokens', '', 'Icons on demand'] },
  { time: '13:00', halls: ['Lunch', '', ''] },
  { time: '14:00', halls: ['Virtual lists', 'Editor', 'Questions and answers'] },
];

const columns: NuiTableColumn<Slot>[] = [
  {
    key: 'time',
    label: 'Time',
    type: 'text',
    width: 96,
    sortable: false,
    filter: false,
    value: (row) => row.time,
  },
  ...HALLS.map((label, hall): NuiTableColumn<Slot> => ({
    key: `hall${hall}`,
    label,
    type: 'text',
    width: 170,
    flex: 1,
    sortable: false,
    filter: false,
    value: (row) => row.halls[hall],
  })),
];

const merges: NuiTableRange[] = [
  { from: { row: 0, col: 1 }, to: { row: 0, col: 3 } },
  { from: { row: 1, col: 2 }, to: { row: 2, col: 2 } },
  { from: { row: 3, col: 1 }, to: { row: 3, col: 3 } },
];

const COMMON: NuiTableCellStyle = { fill: 'var(--color-surface-muted)' };

const WORKSHOP: NuiTableCellStyle = {
  class: 'bg-primary-soft text-primary-soft-foreground',
  align: 'center',
  wrap: true,
};

const STYLES: Readonly<Record<string, NuiTableCellStyle>> = {
  '10:00 hall0': COMMON,
  '13:00 hall0': COMMON,
  '11:00 hall1': WORKSHOP,
};

const styleOf = ({ row, column }: NuiTableCellRef<Slot>): NuiTableCellStyle | undefined =>
  STYLES[`${row.time} ${column.key}`];

const keyOf = (slot: Slot): string => slot.time;
</script>
```

## Text over neighboring cells

With `overflow` in `cellStyle` long text continues over the following empty cells, as in
spreadsheets. The text runs up to the first filled cell, a merged cell or the edge of the
pinned columns. Text aligned to the end of the line runs the other way.

Centered text spreads to both sides, and `wrap` wraps the text inside its cell. A cell with its
own slot, a tree, detail or drag grip, or an open editor keeps its text inside.

The cells under the text stay separate: a click on the text over a neighboring cell lands in
that cell. Grid lines under the text are not drawn.

```vue
<template>
  <NuiTable
    :columns="columns"
    :rows="lines"
    :get-key="keyOf"
    :cell-style="styleOf"
    :column-menu="false"
    gridlines
    caption="Plans, ₽"
  />
</template>

<script setup lang="ts">
import {
  NuiTable,
  type NuiTableCellRef,
  type NuiTableCellStyle,
  type NuiTableColumn,
} from '@numior/kit/table';

interface Line {
  readonly name: string;
  readonly month: number | null;
  readonly year: number | null;
}

const DISCOUNT = 'The 20 % discount for yearly payment ends this month';

const lines: Line[] = [
  { name: 'Start', month: 990, year: 9900 },
  { name: 'Team', month: 2490, year: 24900 },
  { name: DISCOUNT, month: null, year: null },
  { name: 'Business', month: 4990, year: 49900 },
];

const columns: NuiTableColumn<Line>[] = [
  {
    key: 'name',
    label: 'Plan',
    type: 'text',
    width: 160,
    sortable: false,
    filter: false,
    value: (row) => row.name,
  },
  {
    key: 'month',
    label: 'Per month',
    type: 'number',
    width: 140,
    sortable: false,
    filter: false,
    value: (row) => row.month,
  },
  {
    key: 'year',
    label: 'Per year',
    type: 'number',
    width: 140,
    flex: 1,
    sortable: false,
    filter: false,
    value: (row) => row.year,
  },
];

const NOTE: NuiTableCellStyle = { color: 'var(--color-muted-foreground)', overflow: true };

const styleOf = ({ row, column }: NuiTableCellRef<Line>): NuiTableCellStyle | undefined =>
  column.key === 'name' && row.month === null ? NOTE : undefined;

const keyOf = (line: Line): string => line.name;
</script>
```

## Frozen rows

The `frozenRows` prop keeps the first rows in place under the header while the rest scroll under
them. These are ordinary data rows: they can be selected, copied and edited.

Freezing works only with `height`. Groups, a tree, row details and `source` turn it off. Rows
that are not part of the data are pinned with `pinnedRows`.

```vue
<template>
  <NuiTable
    :columns="columns"
    :rows="plans"
    :get-key="keyOf"
    :frozen-rows="1"
    :cell-style="styleOf"
    :column-menu="false"
    height="17rem"
    caption="Your plan and the options to switch to"
  />
</template>

<script setup lang="ts">
import {
  NuiTable,
  type NuiTableCellRef,
  type NuiTableCellStyle,
  type NuiTableColumn,
} from '@numior/kit/table';

interface Plan {
  readonly name: string;
  readonly cores: number;
  readonly memory: number;
  readonly disk: number;
  readonly price: number;
}

const plans: Plan[] = [
  { name: 'Your plan', cores: 2, memory: 4, disk: 60, price: 890 },
  { name: 'Mini', cores: 1, memory: 1, disk: 20, price: 290 },
  { name: 'Start', cores: 1, memory: 2, disk: 30, price: 390 },
  { name: 'Blog', cores: 2, memory: 2, disk: 40, price: 590 },
  { name: 'Site', cores: 2, memory: 4, disk: 80, price: 790 },
  { name: 'Shop', cores: 2, memory: 8, disk: 80, price: 1190 },
  { name: 'Team', cores: 4, memory: 8, disk: 120, price: 1590 },
  { name: 'Studio', cores: 4, memory: 16, disk: 160, price: 2390 },
  { name: 'Agency', cores: 6, memory: 16, disk: 240, price: 2990 },
  { name: 'Business', cores: 8, memory: 32, disk: 320, price: 4790 },
  { name: 'Corporate', cores: 12, memory: 48, disk: 480, price: 7190 },
  { name: 'Cluster', cores: 16, memory: 64, disk: 640, price: 9590 },
];

const columns: NuiTableColumn<Plan>[] = [
  {
    key: 'name',
    label: 'Plan',
    type: 'text',
    width: 170,
    sortable: false,
    filter: false,
    value: (row) => row.name,
  },
  {
    key: 'cores',
    label: 'Cores',
    type: 'number',
    width: 90,
    sortable: false,
    filter: false,
    value: (row) => row.cores,
  },
  {
    key: 'memory',
    label: 'Memory, GB',
    type: 'number',
    width: 120,
    sortable: false,
    filter: false,
    value: (row) => row.memory,
  },
  {
    key: 'disk',
    label: 'Disk, GB',
    type: 'number',
    width: 110,
    sortable: false,
    filter: false,
    value: (row) => row.disk,
  },
  {
    key: 'price',
    label: '₽ per month',
    type: 'number',
    width: 120,
    flex: 1,
    sortable: false,
    filter: false,
    value: (row) => row.price,
  },
];

const CURRENT: NuiTableCellStyle = {
  style: { 'font-weight': 'var(--font-weight-semibold)' },
};

const styleOf = ({ position }: NuiTableCellRef<Plan>): NuiTableCellStyle | undefined =>
  position === 0 ? CURRENT : undefined;

const keyOf = (plan: Plan): string => plan.name;
</script>
```

## Sheet from cells

For an Excel-like sheet pass the result of `tableCells(source)` to the table. The source holds
the row count `rows`, the column count `cols` and the `cellAt(row, col)` function. That function
returns the text and style of a cell.

Sheet rows get numbers, and columns get letters from A to XFD. The table asks only for visible
cells and creates no objects per row or column.

Ctrl with an arrow moves to the edge of the data. When the storage knows where its empty areas
are, its `nextEdge` function finds the edge without walking over cells. Its `lastCell` function
names the last used cell, and Ctrl+End goes there instead of the last cell of the sheet.

When data changes outside the table, for example after formulas are recalculated, call the
`invalidate(ranges)` method on the table ref. It redraws the rows of those ranges, or every row
without an argument.

```vue
<template>
  <NuiTable
    v-bind="cells"
    :column-menu="false"
    gridlines
    size="sm"
    height="18rem"
    caption="Team costs, thousand ₽"
  />
</template>

<script setup lang="ts">
import {
  NuiTable,
  tableCells,
  type NuiTableCellStyle,
  type NuiTableSourceCell,
} from '@numior/kit/table';

const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

const ITEMS = [
  'Rent',
  'Phone',
  'Cloud',
  'Ads',
  'Subscriptions',
  'Training',
  'Travel',
  'Hardware',
  'Stationery',
  'Delivery',
];

const ROWS = 1000;
const COLS = 52;

const HEAD: NuiTableCellStyle = {
  fill: 'var(--color-surface-muted)',
  style: { 'font-weight': 'var(--font-weight-semibold)' },
};

const NUMBER: NuiTableCellStyle = { align: 'end' };

const amountOf = (row: number, col: number): number => 40 + ((row * 37 + col * 23) % 160);

const headCell = (col: number): NuiTableSourceCell | undefined =>
  col <= MONTHS.length
    ? { text: col === 0 ? 'Item' : (MONTHS[col - 1] ?? ''), style: HEAD }
    : undefined;

const itemCell = (row: number, col: number): NuiTableSourceCell | undefined => {
  if (col === 0) {
    return { text: ITEMS[row - 1] ?? '' };
  }
  return col <= MONTHS.length ? { text: String(amountOf(row, col)), style: NUMBER } : undefined;
};

const cellAt = (row: number, col: number): NuiTableSourceCell | undefined => {
  if (row === 0) {
    return headCell(col);
  }
  return row <= ITEMS.length ? itemCell(row, col) : undefined;
};

const cells = tableCells({ rows: ROWS, cols: COLS, cellAt });
</script>
```

## Layer over the cells

The `overlay` slot draws content over the cells that scrolls with them: reference highlights,
images, charts. The slot receives the `rectOf(range)` function, which returns the position of a
range, and `window` with the rendered rows and columns.

The slot renders in the scrolling part of the table and again in the pinned columns and the
`frozenRows` rows, and `pane` names the part. The header covers the layer, and clicks pass through
it to the cells. The table ref has the same `rectOf` and `cellFromPoint(x, y)`, which finds the
cell under a point on screen.

The layer takes row heights from `rowHeight` and the `rowHeights` model. In a table without
`height` and with `rowHeight="auto"` it places marks by the measured rows, including rows that grew
because of wrapped text. In a table without `height` the `pinnedRows` are measured too.

```vue
<template>
  <NuiTable
    :columns="columns"
    :rows="regions"
    :get-key="keyOf"
    :column-menu="false"
    gridlines
    caption="Sales by quarter, million ₽"
  >
    <template #overlay="{ rectOf }">
      <div
        v-for="box in boxesOf(rectOf)"
        :key="box.key"
        class="absolute box-border rounded-sm border-2"
        :style="box.style"
      ></div>
    </template>
  </NuiTable>
</template>

<script setup lang="ts">
import {
  NuiTable,
  type NuiTableColumn,
  type NuiTableRange,
  type NuiTableRect,
} from '@numior/kit/table';

interface Region {
  readonly name: string;
  readonly quarters: readonly number[];
}

interface Mark {
  readonly range: NuiTableRange;
  readonly tone: string;
}

const regions: Region[] = [
  { name: 'North', quarters: [120, 135, 150, 170] },
  { name: 'South', quarters: [90, 95, 110, 105] },
  { name: 'West', quarters: [140, 150, 145, 160] },
  { name: 'East', quarters: [70, 85, 90, 100] },
  { name: 'Total', quarters: [420, 465, 495, 535] },
];

const QUARTERS = ['Q1', 'Q2', 'Q3', 'Q4'];

const columns: NuiTableColumn<Region>[] = [
  {
    key: 'name',
    label: 'Region',
    type: 'text',
    width: 160,
    sortable: false,
    filter: false,
    value: (row) => row.name,
  },
  ...QUARTERS.map((label, index): NuiTableColumn<Region> => ({
    key: `q${index + 1}`,
    label,
    type: 'number',
    width: 110,
    sortable: false,
    filter: false,
    value: (row) => row.quarters[index] ?? null,
  })),
];

const MARKS: readonly Mark[] = [
  { range: { from: { row: 0, col: 1 }, to: { row: 2, col: 2 } }, tone: 'var(--color-primary)' },
  { range: { from: { row: 4, col: 1 }, to: { row: 4, col: 4 } }, tone: 'var(--color-success)' },
];

const boxesOf = (rectOf: (range: NuiTableRange) => NuiTableRect | undefined) =>
  MARKS.flatMap((mark) => {
    const rect = rectOf(mark.range);

    return rect === undefined
      ? []
      : [
          {
            key: mark.tone,
            style: {
              insetBlockStart: `${rect.top}px`,
              insetInlineStart: `${rect.start}px`,
              inlineSize: `${rect.width}px`,
              blockSize: `${rect.height}px`,
              borderColor: mark.tone,
              background: `color-mix(in oklab, ${mark.tone} 10%, transparent)`,
            },
          },
        ];
  });

const keyOf = (region: Region): string => region.name;
</script>
```

## Peer frames

`NuiTablePeers` draws frames in the `overlay` layer around the cells other people work in, with
their names. Each person needs a `key`, a `name`, a `colour` number and a `cell`, and `areas` adds
their selection. On the first row the name sits under the frame so the header does not cover it.

Keep the cell of a person by its row key and column key: the row number changes with sorting and
filters. `keyOf(position)` on the table ref returns such a key. `positionOf(key)` finds the cell in
the current view, or returns `undefined` for a row hidden by a filter.

A computed value over `positionOf` updates itself when the rows move.

`tableRectStyle(rect)` gives the position styles for your own marks in the layer.

```vue
<template>
  <NuiTable
    ref="tasks-table"
    :columns="columns"
    :rows="tasks"
    :pinned-rows="shared"
    :get-key="keyOf"
    :column-menu="false"
    gridlines
    caption="Sprint tasks"
  >
    <template #overlay="{ rectOf }">
      <NuiTablePeers :peers="peers" :rect-of="rectOf" />
    </template>
  </NuiTable>
</template>

<script setup lang="ts">
import { computed, useTemplateRef } from 'vue';
import {
  NuiTable,
  NuiTablePeers,
  type NuiTableCellKey,
  type NuiTableColumn,
  type NuiTableExposed,
  type NuiTablePeer,
} from '@numior/kit/table';

interface Task {
  readonly id: string;
  readonly title: string;
  readonly owner: string;
  readonly hours: number;
}

interface Person {
  readonly id: string;
  readonly name: string;
  readonly colour: number;
  readonly at: NuiTableCellKey;
}

const tasks: Task[] = [
  { id: 't1', title: 'Sign-in screen', owner: 'Olga', hours: 6 },
  { id: 't2', title: 'Catalog search', owner: 'Igor', hours: 12 },
  { id: 't3', title: 'Card payment', owner: 'Anna', hours: 8 },
  { id: 't4', title: 'Monthly report', owner: 'Boris', hours: 4 },
];

const shared: Task[] = [
  {
    id: 't0',
    title: 'Shared work: calls, code reviews and help for the other teams',
    owner: 'Team',
    hours: 10,
  },
];

const people: readonly Person[] = [
  { id: 'anna', name: 'Anna', colour: 2, at: { row: 't3', column: 'hours' } },
  { id: 'boris', name: 'Boris', colour: 5, at: { row: 't1', column: 'title' } },
];

const columns: NuiTableColumn<Task>[] = [
  {
    key: 'title',
    label: 'Task',
    type: 'text',
    width: 200,
    wrap: true,
    value: (row) => row.title,
  },
  { key: 'owner', label: 'Owner', type: 'text', width: 140, value: (row) => row.owner },
  { key: 'hours', label: 'Hours', type: 'number', width: 100, value: (row) => row.hours },
];

const table = useTemplateRef<NuiTableExposed>('tasks-table');

const peers = computed(() =>
  people.reduce<NuiTablePeer[]>((shown, person) => {
    const position = table.value?.positionOf(person.at);

    if (position === undefined) {
      return shown;
    }

    shown.push({
      key: person.id,
      name: person.name,
      colour: person.colour,
      cell: { from: position, to: position },
    });

    return shown;
  }, []),
);

const keyOf = (task: Task): string => task.id;
</script>
```
