# Spreadsheet

A spreadsheet that computes formulas on the page and opens and saves XLSX files.

```vue
<template>
  <NuiSpreadsheet
    class="w-full"
    :book="book"
    :calculator="calculator"
    label="Sales by city"
    height="18rem"
  />
</template>

<script setup lang="ts">
import { NuiSpreadsheet } from '@numior/kit/spreadsheet';
import {
  createCalculator,
  createWorkbook,
  numberValue,
  textValue,
} from '@numior/kit/spreadsheet/core';

const HEADER = ['City', 'January', 'February', 'Total'];

const CITIES = [
  { city: 'London', january: 1240, february: 1315 },
  { city: 'Leeds', january: 640, february: 702 },
  { city: 'York', january: 410, february: 388 },
  { city: 'Bath', january: 275, february: 310 },
];

const book = createWorkbook();
const calculator = createCalculator(book);
const sheet = book.addSheet('Sales');

HEADER.forEach((title, col) => {
  sheet.cells.set(0, col, textValue(title));
});

CITIES.forEach(({ city, january, february }, index) => {
  const row = index + 1;
  const line = String(row + 1);

  sheet.cells.set(row, 0, textValue(city));
  sheet.cells.set(row, 1, numberValue(january));
  sheet.cells.set(row, 2, numberValue(february));
  calculator.setFormula(sheet, row, 3, `=SUM(B${line}:C${line})`);
});

calculator.recalculate();
</script>
```

Create a book with `createWorkbook()`, fill its sheets and pass it to `book`. Edits change that same
book, and the `change` event reports each of them.

`createCalculator(book)` computes the formulas. Pass it to `calculator` when formulas are set before
the sheet is shown. Otherwise the component creates its own.

## Installation

```ts
import { NuiSpreadsheet } from '@numior/kit/spreadsheet';
```

The book model and formulas live in `@numior/kit/spreadsheet/core`. That entry works without Vue,
including on a server.

## Examples

### Read only

Turn editing off with `readonly`.

```vue
<template>
  <NuiSpreadsheet
    class="w-full"
    :book="book"
    :formula-bar="false"
    :sheet-tabs="false"
    readonly
    label="Plans"
    height="12rem"
  />
</template>

<script setup lang="ts">
import { NuiSpreadsheet } from '@numior/kit/spreadsheet';
import { createWorkbook, numberValue, textValue } from '@numior/kit/spreadsheet/core';

const PLANS = [
  { plan: 'Starter', price: 490 },
  { plan: 'Team', price: 1290 },
  { plan: 'Business', price: 3900 },
];

const book = createWorkbook();
const sheet = book.addSheet('Plans');

sheet.cells.set(0, 0, textValue('Plan'));
sheet.cells.set(0, 1, textValue('Price per month, $'));

PLANS.forEach(({ plan, price }, index) => {
  sheet.cells.set(index + 1, 0, textValue(plan));
  sheet.cells.set(index + 1, 1, numberValue(price));
});
</script>
```

Values can still be selected and copied. The `formulaBar` and `sheetTabs` props remove the formula
bar and the tabs.

### Opening and saving XLSX

Show the file bar with `fileBar`.

```vue
<template>
  <NuiSpreadsheet
    v-bind="opened"
    class="w-full"
    file-bar
    label="Department budget"
    height="16rem"
    @open="onOpen"
  />
</template>

<script setup lang="ts">
import { NuiSpreadsheet, type NuiSpreadsheetFile } from '@numior/kit/spreadsheet';
import {
  createWorkbook,
  numberValue,
  textValue,
  type Workbook,
} from '@numior/kit/spreadsheet/core';
import { markRaw, shallowRef } from 'vue';

interface FirstBook {
  readonly book: Workbook;
  readonly fileName: string;
}

const createBudget = (): FirstBook => {
  const book = createWorkbook();
  const sheet = book.addSheet('Budget');

  sheet.cells.set(0, 0, textValue('Item'));
  sheet.cells.set(0, 1, textValue('Amount, $'));
  sheet.cells.set(1, 0, textValue('Rent'));
  sheet.cells.set(1, 1, numberValue(95000));
  sheet.cells.set(2, 0, textValue('Salaries'));
  sheet.cells.set(2, 1, numberValue(310000));

  return { book, fileName: 'Budget.xlsx' };
};

const opened = shallowRef<FirstBook | NuiSpreadsheetFile>(markRaw(createBudget()));

const onOpen = (file: NuiSpreadsheetFile): void => {
  opened.value = markRaw(file);
};
</script>
```

The bar holds the file name and Open and Save buttons. Once a file is read, the `open` event hands
over the new book: put it in `book`.

Without `saveFile` the browser downloads the file. Pass `saveFile` to send it to a server.

Parts of the file the component does not understand are saved unchanged. If an edit could affect
them, the component asks whether to save with losses.

A cell of an XLSX file holds 32,767 characters. The sheet keeps a longer text whole. On saving, the
component asks about the loss and cuts such a text in the file only.

### Your own menu items

Return the items of the cell menu from `contextMenu`.

```vue
<template>
  <div class="flex w-full flex-col gap-3">
    <NuiSpreadsheet :book="book" :context-menu="menu" label="Sprint tasks" height="12rem" />
    <p class="text-muted-foreground">{{ note }}</p>
  </div>
</template>

<script setup lang="ts">
import { NuiSpreadsheet, type NuiSpreadsheetContextMenu } from '@numior/kit/spreadsheet';
import { columnName, createWorkbook, textValue } from '@numior/kit/spreadsheet/core';
import { ref } from 'vue';

const TASKS = ['Card payments', 'Report export', 'Email sign-in'];

const book = createWorkbook();
const sheet = book.addSheet('Sprint');

TASKS.forEach((task, row) => {
  sheet.cells.set(row, 0, textValue(task));
});

const note = ref('Right-click a cell to open the menu.');

const menu: NuiSpreadsheetContextMenu = ({ selection }) => {
  const address = `${columnName(selection.active.col)}${String(selection.active.row + 1)}`;

  return [
    {
      key: 'ticket',
      label: 'Create a task from the cell',
      onSelect: () => {
        note.value = `Task created from cell ${address}.`;
      },
    },
  ];
};
</script>
```

The function receives the sheet and the selection.

### Editing together

`useCollabWorkbook` from `@numior/kit/collaboration/spreadsheet` connects a book to a server.

```vue
<template>
  <NuiCollabFailure v-if="failure !== undefined" :failure="failure" @rejoin="rejoin" />
  <NuiSpreadsheet
    v-if="ready"
    :book="book"
    :calculator="calculator"
    :collaboration="document"
    :readonly="readOnly"
    :peers="peers"
    label="Shared book"
    @change="sync"
    @presence="sharePlace"
  />
</template>

<script setup lang="ts">
import { webSocketTransport } from '@numior/kit/collaboration';
import { useCollabWorkbook } from '@numior/kit/collaboration/spreadsheet';
import { NuiCollabFailure } from '@numior/kit/collaboration/vue';
import { NuiSpreadsheet } from '@numior/kit/spreadsheet';
import { createCalculator, createWorkbook } from '@numior/kit/spreadsheet/core';

const book = createWorkbook();
const calculator = createCalculator(book);

const { document, ready, readOnly, peers, failure, sync, sharePlace, rejoin } = useCollabWorkbook({
  doc: 'budget',
  user: { id: 'ann', name: 'Ann' },
  transport: webSocketTransport('wss://example.com/collab'),
  book,
  calculator,
});
</script>
```

`sync` from `change` sends your edits. Edits by other people appear on their own and do not fire
`change`. `ready` turns on once the book has loaded from the server, and `sharePlace` shows the
others the cell you are in.

When someone else inserts or removes rows and columns, the active cell and the selection stay on
their data. An open cell moves with its row: the typed text, the focus and the caret are kept. If
its row or column was removed, the edit closes and the sheet says so in a note.

The references of an unfinished formula follow the data too. After a row is inserted above the
ninth one, `=SUM(A3:A9)` becomes `=SUM(A3:A10)`, and the caret stays at the same character. A
reference to removed cells turns into `#REF!`, as in a saved formula.

While a word is being composed through an IME, the cell and the references of its formula wait.
They move once the word is done, so the input is not broken.

The screen keeps the same data: rows inserted above the window do not push away what you read. A
sheet scrolled to its very start shows rows inserted at the start right away.

Conditional formatting rules that different people add at the same time are all kept. The order of
the rules follows the person who changed it.

When two people create a sheet or a table under one name at the same time, both are kept. The second
gets the next name, "Sheet3" after "Sheet2", and its cells and formulas stay on it. A sheet renamed, or
removed and brought back by undo, stays the same sheet for everyone, and the frames of other people
stay on it.

Once the connection fails, edits are no longer sent: `readOnly` turns on and `failure` holds the
reason. `NuiCollabFailure` explains it and offers to open the book again, which calls `rejoin`. The
page is not reloaded.

The server then sends the whole book. It replaces the local one together with the unsent edits, and
the sheet stays on the same tab. Until the book arrives, the sheet stays read-only.

Do not show `fileBar` in a shared book: opening a file replaces the book, and the others stop seeing
it. The `readonly` prop turns editing off.

## Behavior

### Formulas

Text that starts with `=` becomes a formula. While the cursor sits where an operand goes, a click, a
drag or the arrows insert a reference, and `F4` cycles its `$` signs.

References in the formula text and range frames on the sheet share a color. Drag a frame by its edge
or corner and the reference in the formula changes. A list of functions appears after letters, and
a hint shows the current argument inside parentheses.

References combine with the operators of Excel. A colon spans two references (`A1:INDEX(A:A,5)`),
and a space intersects them (`A1:C3 B2:D4`). A list in parentheses joins several areas
(`SUM((A1,C1:C3))`).

Areas go to the functions Excel gives them to — `SUM`, `COUNT`, `INDEX`, `AREAS` and others; the
rest return `#VALUE!`.

A large book recalculates in parts. Values still being computed are marked, and the bottom of the
sheet shows the progress with a stop button.

### Selection and fill

The handle in the corner of a selection continues a number series or copies formulas with shifted
references. Dragging the handle back clears cells.

The cell menu holds inserting and deleting rows and columns, merging cells, conditional formatting,
pivot tables, charts and pictures. Sheets are added, renamed and deleted on their tabs.

### Merging cells

"Merge cells" in the cell menu turns the selected range into one cell. Each selected range is merged
on its own, and the merges inside it are replaced by the new one.

The merged cell keeps the value of the first filled cell of the range, counted row by row. The
other values are removed, and the sheet says so in a note. `Ctrl+Z` returns the cells and their
values in one step.

"Unmerge cells" takes apart the merges that the selection meets. The value stays in the first cell.
Whole rows and columns are not merged, and inside a table or a pivot table the sheet refuses with
the `merge-blocked` reason.

Your own toolbar runs the same actions with the `mergeCells()` and `unmergeCells()` methods.

### Column widths and row heights

Drag the right edge of a column header or the bottom edge of a row number. On the keyboard press
`Alt` with an arrow on a column header or on a row number.

A double click on the edge of a column header fits the width to the longest text of its cells. An
empty column returns to the width of the sheet. A double click on the edge of a row number returns
the default height.

The fit reads the cells on screen and the first cells from the top, up to 10,000 per gesture. When
a column has more cells, the sheet says so in a note. Hidden rows and cells merged across several
columns are left out.

The size is stored in the book per sheet: `Ctrl+Z` undoes it, XLSX files keep it and co-authors see
it. The book step is written once, at the end of the gesture.

When several whole rows or columns are selected, the edge of one of them sizes all of them. A
double click fits the width of every selected column.

With the whole sheet selected the default size changes and the sizes of single lines are dropped.
The sheet does not size more than 20,000 rows in one gesture and answers with the `lines-too-many`
reason.

In a read-only book the size changes on screen only, while this sheet is shown.

### Pictures and charts

A picture is selected with a click, or with `Alt+F10` from a cell. `Tab` moves to the next
picture. The arrows move a selected picture and `Delete` removes it.

A picture has its own menu: a right click, a long press on a phone, or `Shift+F10` on a selected
picture. The menu offers «Delete», and a chart also offers «Chart settings». A read-only book shows
no picture menu.

### Refused actions

An action the sheet did not apply is explained by a note in the bottom corner of the sheet. The
sheet answers this way to a fill across merged cells and to a merge of table cells. An edit of a
pivot table cell and a row inserted past the limit get the same note.

A note with the `cell-gone` reason also reports an edit whose cell was removed by someone else.

The note fades after six seconds, after the next edit that goes through, or on a click. It stays
while the pointer is over it. The live region gets the same text.

The `refuse` event carries `{ reason, message }`. The reasons are listed in
`NuiSpreadsheetRefusalReason`: an app uses them to show its own message or to keep a log.

## Accessibility

The sheet is marked up as `role="grid"`. Tab enters it once, and the arrows move focus between
cells. The formula bar is tied to the active cell, and results of edits are announced in a live
region.

On a phone a double tap starts editing and a long press opens the menu of a cell or a picture.

| Keys | Action |
| --- | --- |
| `F2` | Starts editing the active cell. |
| `Enter / Tab` | Commits the edit and moves down or right. |
| `Escape` | Cancels the cell edit. |
| `Alt+Enter` | Breaks the line in the formula bar. |
| `F4` | In a formula cycles the `$` signs of a reference. |
| `Ctrl+Z / Ctrl+Y` | Undoes and redoes an edit. |
| `Ctrl+C / Ctrl+X / Ctrl+V` | Copies, cuts and pastes a range, shifting the references in formulas. |
| `Ctrl+D / Ctrl+R` | Fills the selection down or right from its first row or column. |
| `Delete` | Clears the selected cells. |
| `Shift+F10 / ContextMenu` | Opens the menu of the cell or of the selected picture. |
| `Alt+F10` | Selects the first picture of the sheet; `Tab` moves to the next one, `Escape` returns to the cells. |
| `Ctrl+S / Ctrl+O` | With `fileBar` saves the book and opens a file. |

## API

### NuiSpreadsheet

```ts
import { NuiSpreadsheet } from '@numior/kit/spreadsheet';
```

#### Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `book` (required) | `Workbook` |  | Book from `createWorkbook()` or an opened file. Edits change it in place. |
| `calculator` | `Calculator` |  | Calculator of the book from `createCalculator(book)`. Created automatically when omitted. |
| `label` (required) | `string` |  | Accessible name of the grid. |
| `locale` | `BookLocale` |  | Language of formulas and numbers: `RU_LOCALE` or `EN_LOCALE`. Follows the app language by default. |
| `height` | `string` | `"28rem"` | Height of the component, any CSS value. |
| `readonly` | `boolean` | `false` | Turns editing off. Values can still be read and copied. |
| `formulaBar` | `boolean` | `true` | Shows the name box and the formula bar. |
| `sheetTabs` | `boolean` | `true` | Shows the sheet tabs. |
| `contextMenu` | `NuiSpreadsheetContextMenu` |  | Adds items to the cell menu. Receives `{ sheet, selection }` and returns menu items. |
| `report` | `LimitationsReport` |  | Limitations report of an opened file. A book with `readOnly: true` opens read-only. |
| `fileBar` | `boolean` | `false` | Shows the bar with the file name, Open and Save buttons, and turns on `Ctrl+O` and `Ctrl+S`. |
| `fileName` | `string` |  | File name on the bar and when saving. |
| `source` | `OriginalPackage` |  | Original XLSX package. Parts the component does not understand are saved from it unchanged. |
| `saveFile` | `NuiSpreadsheetSaveAdapter` |  | Receives `{ name, bytes, report }` instead of the browser downloading the file. |
| `collaboration` | `WorkbookDocument` |  | Shared document from `createWorkbookDocument`. Edits by other people appear without a `change` event. |
| `peers` | `readonly WorkbookPeer[]` | `[]` | Who else has the book open: the result of `workbookPeers` from the client `onPresence`. Selections of people on the shown sheet are drawn as colored frames with a name. |

#### Models

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `v-model:sheet` | `number` | `0` | Index of the shown sheet, starting at zero. |
| `v-model:selection` | `NuiSpreadsheetSelection` |  | Active cell `active` and selected ranges `ranges`. |

#### Events

| Name | Payload | Description |
| --- | --- | --- |
| `open` | `[file: NuiSpreadsheetFile]` | Fires when a file is opened, with the new `book`, `calculator`, `report`, `source` and `fileName`. |
| `change` | `[change: NuiSpreadsheetChange]` | Fires after each local edit and undo, with `{ steps }`. |
| `saved` | `[saved: NuiSpreadsheetSaved]` | Fires after saving, with `{ name, bytes, report }`. |
| `presence` | `[place: WorkbookPlace \| undefined]` | Your place in the book changed: `{ sheet, selection }` or `undefined` while no sheet is shown. Pass it to `client.setPresence({ user, place })`. |
| `refuse` | `[refusal: NuiSpreadsheetRefusal]` | The sheet did not apply an action. Carries `{ reason, message }`: a reason from `NuiSpreadsheetRefusalReason` and the text the sheet showed in its note. |

#### Exposed

| Name | Type | Description |
| --- | --- | --- |
| `refresh` | `() => void` | Recalculates formulas and redraws cells after the book changed from outside. |
| `apply` | `(steps: readonly WorkbookStep[]) => boolean` | Applies workbook steps as one undoable edit. Returns `false` when a step fails or the list is empty. |
| `mergeCells` | `() => boolean` | Merges each selected range into one cell, as "Merge cells" of the cell menu does. Returns `false` when there is nothing to merge or the sheet refused. |
| `unmergeCells` | `() => boolean` | Takes apart the merges that the selection meets. Returns `false` when there are none. |
| `openRules` | `() => void` | Opens the conditional formatting rules popover at the active cell. |
| `save` | `() => Promise<boolean>` | Saves the book as XLSX. Returns `true` when the file is written. |
| `open` | `(file: File) => Promise<boolean>` | Opens the given XLSX file. Returns `true` when the file is read. |
