# sheet

> The spreadsheet plugin: multi-tab workbooks with formulas, rules, charts, filters, CSV and Excel import/export, and ordered live-room co-editing.

Source: https://clayjs.com/docs/plugins/sheet/

The `sheet` plugin turns a `[sheet-workbook]` inside a `[sap]` root into a multi-tab spreadsheet. Load it by name with `?plugins=sheet`. In edit mode it brings `sync` and `live-room` with it; in view mode the loader adds its reader half, `sheet-view`, on its own.

## What it does

`?plugins=sheet` is an edit-only plugin. Depending on the page's mode, ClayJS loads one of two halves:

- **Edit mode (`sheet`):** mounts the workbook model, toolbar, formula bar, grid selection, context menus, tab strip, per-tab undo history, and ordered live-room binding (`clay.liveRoom("sheet", ...)`). `clay.ready` waits for `sheet` to mount its workbooks and settle its initial room setup.
- **View mode (`sheet-view`):** added automatically by the loader when the page is in neither edit mode nor draft mode (never named in a URL, and without loading `sync` or `live-room`). `sheet-view` installs the virtualized row window on every `[sap] table[grid]`, paints saved conditional rules and chart figures, loads the extended formula pack on idle, and loads custom number formats on demand when a sheet uses one. It draws no editing chrome or tab strip; in view mode and in print, sheets stack vertically with their `<h2 bind="name">` headings visible.
- **Draft mode (`visitor-drafts`):** on a [free document](https://clayjs.com/docs/guide/free-documents/), draft mode keeps `sheet` while dropping `sync` and `live-room`, so visitors get the full spreadsheet editor backed by their browser's draft store.

In edit mode, `clay.sheet` exposes the active installation:

| Member | What it is |
|---|---|
| `clay.sheet.windows` | `Map` from each `<table grid>` element to its virtualized row-window controller |
| `clay.sheet.books` | `Map` from each `[sheet-workbook]` element to its workbook handle |
| `clay.sheet.ui` | the editor interface (`{ selection, of(workbook), notice(text, action), hideNotice(), reveal(target), setConflicts(targets), restart(), dispose() }`), or `null` when no workbook is mounted |
| `clay.sheet.room` | the ordered live-room binding for the first clean `[sheet-workbook]`, or `null` |
| `clay.sheet.leaveRoom()` | disposes the active room binding |

## Saved markup

A sheet workbook lives inside a `[sap]` root that loads SapJS's `grid` plugin. The loader auto-adds `derive` whenever `[sap]` is present, and `clay.region.own` claims `[sheet-workbook]` so generic DOM morphing and document-wide `undo` leave the workbook to its own codec:

```html
<main sap plugins="grid">
  <div items="sheets" sheet-workbook>
    <section item data-id="s1" data-pos="V">
      <h2 bind="name">Nov budget</h2>
      <table grid>
        <colgroup>
          <col data-id="c1" data-pos="V" style="width:190px">
          <col data-id="c2" data-pos="l" style="width:110px">
          <col data-id="c3" data-pos="t" style="width:110px">
        </colgroup>
        <thead>
          <tr data-id="r1" data-pos="V">
            <td style="font-weight:bold">Expense</td>
            <td style="font-weight:bold">Planned</td>
            <td style="font-weight:bold">Actual</td>
          </tr>
        </thead>
        <tbody>
          <tr data-id="r2" data-pos="l">
            <td>Groceries</td>
            <td n v="760" fmt="$#,##0.00">$760.00</td>
            <td n v="715" fmt="$#,##0.00">$715.00</td>
          </tr>
          <tr data-id="r3" data-pos="t">
            <td style="font-weight:bold">Remaining</td>
            <td></td>
            <td n f="=B2-C2" v="45" fmt="$#,##0.00">$45.00</td>
          </tr>
        </tbody>
      </table>
    </section>
    <script type="application/json" sheet-commit>{"rev":1}</script>
  </div>
</main>
<script src="https://clayjs.com/v1/clay.js?plugins=sheet&exclude=richclay"></script>
```

Every saved element inside `[sheet-workbook]` follows a strict canonical HTML grammar:

- **Tabs (`<section item data-id="..." data-pos="...">`):** ordered by their fractional-index `data-pos` key (falling back to `data-id`), each starting with `<h2 bind="name">` for the tab's title and `<table grid>` for its cells. If the tab has charts, `<figure chart="ID" sap-ignore=""><svg ...>...</svg></figure>` elements follow `<table grid>` in rule order (up to 1,048,576 characters per figure) so charts render before JavaScript runs and on paper.
- **Table attributes (`<table grid>`):** optional `freeze-cols="N"` (`N >= 1`) freezes the leftmost `N` columns; bare `stale` marks a sheet whose raw inputs were patched on the server without recalculating formulas.
- **Columns (`<colgroup>`):** one `<col data-id="..." data-pos="...">` per column, carrying optional `fmt="..."`, `hidden`, and `style="width:Npx"`.
- **Frozen and body rows (`<thead>` and `<tbody>`):** optional `<thead>` holds frozen top rows (`<tr data-id="..." data-pos="...">`). Body rows are grouped into `<tbody>` blocks of **50 rows** each, extended past 50 whenever a vertical `rowspan` merge crosses a boundary so a merge never splits across two `<tbody>` elements. On screen, the row window hides off-screen `<tbody>` groups through an adopted `CSSStyleSheet` (`@media screen`) rather than removing nodes, so the DOM stays complete for saves, searches, and printing.
- **Cells (`<td>`):** trailing empty unstyled cells at the end of a row are omitted. Cell attributes are `n` (number), `t` (forced plain text), `f="=..."` (formula), `v="..."` (raw stored value when the formatted text differs from the canonical value), `fmt="..."` (number or date format), `colspan="N"` and `rowspan="N"` (`N >= 2` on a merge's top-left cell), `hidden` (empty covered cell inside a merge), and `style="..."`.
- **Value typing:** numeric input up to 15 significant digits is stored as a number (`n`), while leading-zero codes (`02134`) and 16+ digit strings (such as card numbers) stay text unless given a format. Uppercase `TRUE` and `FALSE` are booleans. Dates are stored as serial days since `1899-12-30`.
- **Rules (`<template rules>`):** optional template after the last `<tbody>`, holding `<rule data-id="..." data-pos="..." kind="..." range="...">` elements in `data-pos` order.
- **Commit record (`<script type="application/json" sheet-commit>`):** follows the `<section item>` tabs inside `[sheet-workbook]`. Starts at `{"rev":1}` and stores the v2 room lineage record once an ordered room saves a checkpoint.

## Editing and formulas

Select cells by clicking, dragging, Shift-clicking, clicking row or column headers, or clicking the top-left corner to select the whole sheet. Double-click a cell, press **Enter** or **F2**, or start typing to edit in the cell or in the `fx` formula bar:

- **Commit and fill:** **Enter** commits and moves down (**Shift+Enter** up), **Tab** moves right (**Shift+Tab** left), **⌥Enter** (**Alt+Enter**) inserts a line break inside the cell, **⌘Enter** (**Ctrl+Enter**) fills every cell in the current selection with the entry while shifting relative references, and **Escape** cancels.
- **Pointing at references:** while typing a formula (`=`), click or drag cells to insert or replace an A1 range, including after clicking another sheet tab (`'Nov budget'!C2:C14` or open-ended `A2:A`). Press **F4** to cycle `$A$1` absolute locks on the reference under the caret. An inline function card shows arguments as you type.
- **Functions:** 86 core functions ship in `sap-grid` and 26 extended functions load on idle from `sap-grid-functions` (112 total across math, lookup, logic, text, date, statistical, and financial functions, including `SUM`, `IFS`, `XLOOKUP`, `INDEX`, `MATCH`, `SUMIFS`, `COUNTIFS`, `TEXT`, `WORKDAY`, `EDATE`, `NPV`, and `PMT`).
- **Floating and volatile formulas:** a reference past the current edge of a sheet reads blank without growing the table, and binds to real row and column ids once rows or columns are inserted to reach it. Volatile functions (`TODAY`, `NOW`, `RAND`, `RANDBETWEEN`) recalculate on open without marking the file unsaved.
- **Series fill and clipboard:** drag the selection's corner fill handle to extend numbers, dates, text ending in an integer, or relative formulas; double-click the fill handle to fill down alongside an adjacent populated column. **⌘D** (**Ctrl+D**) fills down and **⌘R** (**Ctrl+R**) fills right. **⌘C**, **⌘X**, and **⌘V** copy, cut, and paste; **⌘⇧V** (**Ctrl+Shift+V**) pastes values only; **Paste special** also offers format-only and transposed paste.
- **Status bar, links, and search:** selecting more than one cell shows `Sum`, `Average`, and `Count` (or `Count` for text) in the bottom bar across up to 100,000 cells. URLs (`http://`, `https://`, `mailto:`) and `=HYPERLINK("url", "label")` cells open on **⌘-click** (**Ctrl-click**). **⌘F** (**Ctrl+F**) and **⌘⇧H** (**Ctrl+H**) find and replace across tabs with an option to **Search formulas**, and **⌘J** (**Ctrl+J**) focuses the Name box to jump to any cell or range.

## Formatting, structure and tabs

- **Cell appearance:** **Bold**, **Italic**, **Underline**, **Strikethrough**, six text colors and six fill tints, cell borders (`All`, `Outer`, `Inner`, `Top`, `Bottom`, `Left`, `Right`, `None`), horizontal alignment (`Left`, `Center`, `Right`), text wrapping, merge/unmerge (prompting which value to keep when multiple cells in the range are non-empty), and clear formatting (**⌘\\** / **Ctrl+\\**).
- **Number and date formats:** `Automatic`, `Plain text` (`@`), `Number` (`#,##0.00`), `Thousands` (`#,##0`), `Percent` (`0.00%`), `Currency` (`$#,##0.00`), `Date` (`m/d/yyyy`), `Long date` (`mmmm d, yyyy`), `Time` (`h:mm AM/PM`), `Date and time` (`m/d/yyyy h:mm`), `.0` / `.00` decimal steppers, and **Custom format…** (up to 255 characters, loading `grid-formats` on demand).
- **Rows, columns, and tabs:** freeze top rows into `<thead>` or leftmost columns via `freeze-cols`, drag header edges or use the row/column menu to resize or fit to data, hide and unhide rows or columns, and sort the sheet or selected range (`A to Z`, `Z to A`). In the bottom tab bar, `+` adds a sheet, double-clicking a tab renames it, and the tab menu duplicates, moves, or deletes a tab (with confirmation).

## Rules: checkboxes, dropdowns, conditional formatting and color scales

Rules live inside `<template rules>` at the end of `<table grid>` and travel with the saved HTML:

- **Checkboxes (`kind="check"`):** cells with `TRUE` are checked and `FALSE` or blank are unchecked; click or press **Space** to toggle. Cells holding non-boolean text (such as column headers) stay text.
- **Dropdowns (`kind="list"`):** pick from an explicit list (`items`, 1 to 500 items of up to 255 characters each) or a sheet range (`source`, such as `Lists!A2:A`). Dropdowns are closed by default and refuse unlisted entries (`"Pick one of the dropdown's items."`); turning on **Allow other values** (`open`) keeps custom entries and marks them with a red underline. Open the menu from the cell chevron or **⌥Down** (**Alt+Down**).
- **Conditional formatting (`kind="when"`):** highlights cells matching `empty`, `filled`, `contains`, `starts`, `ends`, `eq`, `ne`, `gt`, `ge`, `lt`, `le`, `between`, `outside`, `duplicate`, `unique`, or a custom `formula`, applying bold, italic, strikethrough, text color, or fill color. Earlier rules in `data-pos` order win per CSS property.
- **Color scales (`kind="scale"`):** interpolates fill color across numeric values in `range` from `low` (minimum) through optional `mid` (median) to `high` (maximum), with **White to green**, **Red to white to green**, and **White to red** presets.

## Charts

Adding a chart writes a `<rule kind="chart">` entry alongside a rendered `<figure chart="ID" sap-ignore="">` SVG inside the sheet's `<section item>`, updating live whenever cells change:

- **Types:** `column`, `bar`, `line`, `area`, `pie`, and `scatter`, with optional `title` (up to 255 characters), `stacked` (on `column`, `bar`, and `area`), and `series="rows"` to read series across rows instead of columns.
- **Interaction:** drag a chart to reposition it over the grid, drag its corner handle to resize, double-click or press **Enter** on a selected chart to edit its settings, and press **Delete** or **Backspace** to remove it. Hidden rows and rows hidden by a viewer's filter are excluded from chart plots.

## Per-viewer filters

Clicking **Filter** in the toolbar adds filter buttons to the header row of the active range. Each column filters by condition (`Is empty`, `Is not empty`, text comparisons, or number comparisons) and by checked distinct values (listing up to 500 values before search), and offers **Sort A to Z** and **Sort Z to A**.

Filters are **runtime-only per viewer** (`"Filters only your view — other editors keep theirs"`). Filtered-out rows are hidden through the row window's adopted stylesheet without mutating the DOM or marking the page unsaved, and `Delete`, `Space` on checkboxes, copy/cut, charts, and status-bar aggregates skip rows hidden by your filter.

## CSV, TSV and Excel import and export

Both menus live under **More tools** (`…`) in the toolbar:

- **Import CSV or TSV…** accepts `.csv`, `.tsv`, and `.txt` files up to **5 MB** and **200,000 cells**. It detects comma, semicolon, or tab delimiters, previews the first 20 rows, lets you set each column to **Automatic** or **Plain text**, and writes into either a **New tab** or **At the selected cell** (adding at most 10,000 rows and 1,000 columns). Values starting with `=` are imported as literal text rather than formulas.
- **Download this tab as CSV / TSV** exports displayed cell values with formula-injection quoting for leading `=`, `+`, `-`, and `@` characters.
- **Import Excel file (`.xlsx`)…** accepts workbooks up to **20 MB**, **10,000 rows** and **1,000 columns** per tab, and **200,000 cells** across imported tabs, loading `exceljs` on first use. Before changing the workbook, it opens an inspection report listing the tabs to add, any tabs skipped for size, and **What won't come across** (unsupported Excel functions kept as their cached result, named ranges and external links, spilled array formulas, Excel tables, charts, images, comments, pivot tables, macros, data validations, conditional formats, filters, and hidden sheets, rows, or columns). It converts 1900 and 1904 date systems, theme and ARGB colors, borders, merges, frozen panes, row heights, column widths, and shared formulas, and rewrites cross-tab formula names when tab titles collide.
- **Download all tabs as Excel file (`.xlsx`)** writes every tab with values, formulas (adding `_xlfn.` prefixes where Excel requires them) plus cached results, number formats, colors, borders, merges, frozen panes, and row/column dimensions.

## Keyboard shortcuts

Press **⌘/** (**Ctrl+/** on Windows and Linux) to open the five-group **Keyboard shortcuts** reference (*Move and select*, *Edit*, *Format*, *Rows and columns*, and *Find and tools*). Common shortcuts:

| Keys (Mac / Windows & Linux) | Action |
|---|---|
| `Enter` or `F2` | Edit selected cell |
| `⌥Enter` / `Alt+Enter` | New line inside cell |
| `⌘Enter` / `Ctrl+Enter` | Fill selection with entry |
| `F4` | Cycle `$A$1` reference lock while editing a formula |
| `⌘D` / `Ctrl+D`, `⌘R` / `Ctrl+R` | Fill down, fill right |
| `⌘⇧V` / `Ctrl+Shift+V` | Paste values only |
| `⌘\` / `Ctrl+\` | Clear formatting |
| `⌘⌥=` / `Ctrl+Alt+=` | Insert row or column |
| `⌘⌥-` / `Ctrl+Alt+-` | Delete row or column |
| `⌘F` / `Ctrl+F`, `⌘⇧H` / `Ctrl+H` | Find, find and replace |
| `⌘J` / `Ctrl+J` | Go to cell or range (Name box) |
| `⇧F10` | Open context menu |
| `⌘/` / `Ctrl+/` | Show all keyboard shortcuts |

## Compact and phone layouts

The chrome adapts to the width of the sheet container itself rather than the browser window:

- **Wide (`960 px` and up):** full toolbar and formula bar.
- **Compact (`760 px` to `959 px`):** data tools fold into **More tools** (`…`).
- **Phone (under `760 px`):** a single-row toolbar with `44 px` minimum tap targets (**Undo**, **Bold**, **$%** number format, **Filter**, **Row +**, and **More tools**). On coarse touch pointers, the formula bar stays hidden while reading (the status line shows `A1 · content`) and docks above the on-screen keyboard (`visualViewport`) while editing, adding a **Formula symbols** strip (`=`, `(`, `)`, `:`, `+`, `$`). A single tap selects with draggable range handles, a second tap on the selected cell starts editing, and a 420 ms long-press opens cell, tab, or chart context menus.

## Co-editing, undo and recovery

In edit mode outside draft mode, the first clean `[sheet-workbook]` joins an ordered live room via `clay.liveRoom("sheet", { codec: Sap.grid.roomCodec, page })` ([Ordered live rooms](https://clayjs.com/docs/guide/live-sync/#ordered-live-rooms)):

- **Bound formulas and admitted saves:** before an edit leaves the tab, formula references are bound to row and column ids in the author's current frame (`Sap.grid.bound`), so a coworker's concurrent row or column insert cannot shift what the formula points to. Saves splice the room's **admitted copy** into the served page, never unadmitted local DOM state, writing cached formula values and chart SVGs when the room is quiet. Every 2 seconds while quiet, the binding checks the live DOM against `room.view()` and repairs any drift. Actions exceeding the room's size budget are refused with `"That change is too large to share."`, while multi-frame edits split into 63 KiB / 128-op parts automatically.
- **Per-tab guarded undo and redo:** each tab keeps up to **200 steps** and **64 MB** of history (dropping the oldest steps past 64 MB with `"Undo history is full, so your oldest steps were cleared. Recent changes still undo."`). Adding, renaming, moving, or deleting a sheet tab is not undoable. Outside a room, undo checks that touched cells, sizes, and sorts still hold what the step wrote (`"Can't undo: those cells changed after this step."`). Inside a room, undo submits a `revert` action carrying what the step wrote: cells a coworker changed afterward stay as the coworker left them (`"Can't undo: <cells> changed after your edit."`, or `"Undid your edit, leaving <cells> as changed since."`).
- **Save chip and Recovered edits:** the bottom bar mounts the live-room save chip (`Connecting…`, `N local edits`, `Shared, saving…`, `Checking save…`, `Saved`, `Restoring edits…`, `N conflicts to review`, `N copies not stored`, `Offline, kept in tab`, `Offline, retrying`, or `Cannot save here` with **Download copy**) alongside **Recovered edits** in **More tools**. When a room generation ends with unsettled edits (after a version restore, outside write, or retired session), immutable HTML recovery copies are stored at `/_/copies`, non-conflicting edits replay automatically on reconnect, and overlapping cell edits appear in **Recovered edits** showing **Copy**, **Saw then**, and **Current** values with **Keep current**, **Take copy**, **Keep current for the rest**, and **Show in sheet** (plus **Copy value**, **Download copy**, and **Dismiss** for edits that no longer fit). If an older tab encounters a newer sheet codec, it leaves the room and displays a **Reload** banner (plus **Download copy** when unsaved local edits exist).

## Repairing a damaged sheet

If a `<table grid>` loads with structural grammar violations (`grid.issues.length > 0`, such as hand-edited HTML with duplicate `data-id` attributes or broken merge spans), SapJS refuses grid writes (`W60`), the workbook stays out of the live room, and a notice reads **This sheet's markup has errors and is read-only until repaired.** with **Repair sheet**.

Clicking **Repair sheet** runs `grid.repair()` across every affected tab, saves the cleaned HTML with `clay.save()`, and joins the live room once every tab is clean (`grid.repair()` throws if called directly while joined to a room).

## New blank document

When a sheet template opts into [New blank document](https://clayjs.com/docs/plugins/menu/#new-document-and-visitor-drafts) (`<script type="application/json" clay-new-document>`) and declares a `@codec(sheet)` rule in a `data-rules-version="2"` `api` tag, `clay.newDocument.build()` skips blanking the codec region through field rules so a `clay:newdocument` listener can reset `[sheet-workbook]` cleanly on `event.detail.document`.

## Limits in v1

- **Partial-width sort:** when sorting a multi-column block narrower than the full sheet width, a coworker's same-moment edit into an empty cell inside that block can land on a different row.
- **Out-of-order room undo on formula ranges:** undoing an earlier row insert out of order in a live room can narrow a formula range by one row without producing `#REF!`.
- **Volatile random functions:** `RAND()` and `RANDBETWEEN()` evaluate independently in each open tab until the next save writes one shared result into the file.
- **Server JSON API writes do not recalculate formulas:** patching cells through HTML Clay's `POST /_/api/<file>` writes the new inputs, marks `<table grid stale>`, and answers `recalculated: false, stale: true`. Formulas recalculate on the next browser open.
