diff --git a/.changeset/tanstack-spreadsheet.md b/.changeset/tanstack-spreadsheet.md new file mode 100644 index 0000000000..1d16189a15 --- /dev/null +++ b/.changeset/tanstack-spreadsheet.md @@ -0,0 +1,12 @@ +--- +'@tanstack/spreadsheet-core': minor +'@tanstack/spreadsheet-store': minor +'@tanstack/spreadsheet-packs': minor +'@tanstack/spreadsheet-xlsx': minor +'@tanstack/spreadsheet-codemode': minor +'@tanstack/spreadsheet-agent': minor +'@tanstack/spreadsheet-table': minor +'@tanstack/react-spreadsheet': minor +--- + +Add TanStack Spreadsheet (experimental): a headless, framework-agnostic spreadsheet engine — addressing, parser, dependency graph, and evaluator — that projects into TanStack Table v9. Includes the core workbook, a TanStack Store interop layer, async function packs, `.xlsx` import/export, on-the-fly Code Mode cell functions, an agent toolkit, the table adapter, and React bindings. diff --git a/README.md b/README.md index eb7ca70268..47023eea2b 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,12 @@ A headless table library for building powerful datagrids with full control over - Sorting, filtering, grouping, aggregation & row selection - Lightweight, virtualizable & server‑side friendly +> [!NOTE] +> **TanStack Spreadsheet (experimental)** — a headless, framework-agnostic +> spreadsheet engine (parser, dependency graph, evaluator) that projects into +> TanStack Table. See the +> [Spreadsheet docs](https://tanstack.com/table/latest/docs/spreadsheet/overview). + ### Read the Docs → ## Using an AI Coding Agent? diff --git a/_artifacts/domain_map.yaml b/_artifacts/domain_map.yaml index 88c55cb357..5c17d9eb20 100644 --- a/_artifacts/domain_map.yaml +++ b/_artifacts/domain_map.yaml @@ -2625,6 +2625,115 @@ skills: thresholds, accessors, bounds, and diacritic handling. Routes TanStack Table filterMeta wiring to filtering skills. requires: [] + - slug: core + package: '@tanstack/spreadsheet-core' + domain: spreadsheet + type: core + purpose: + Establish the headless workbook kernel, the input-patch commit pipeline, + errors and pending as first-class cell values, region subscriptions, and + the opt-in capability model. + sources: + - TanStack/table:packages/spreadsheet-core/src/index.ts + - TanStack/table:packages/spreadsheet-core/src/types.ts + - TanStack/table:packages/spreadsheet-core/src/workbook.ts + - TanStack/table:packages/spreadsheet-core/src/kernel.ts + - TanStack/table:packages/spreadsheet-core/src/construct.ts + - TanStack/table:packages/spreadsheet-core/src/capability.ts + - TanStack/table:packages/spreadsheet-core/src/eval.ts + - TanStack/table:packages/spreadsheet-core/src/capabilities/index.ts + failure_modes: + - Treating an error or pending result as an exception or null instead of + narrowing the CellValue with isErr, isPending, or isBlocking. + - Mutating cells directly or storing computed values in patches rather + than committing input strings through setInput and applyPatches. + - Reaching for every capability by default instead of constructing a + lean workbook with only the capabilities the task needs. + description: + Use the TanStack Spreadsheet workbook kernel and capability model. Route + cell input, patches, computed reads, errors and pending as values, region + subscriptions, and opt-in capabilities. Load before the react, table-v9, + or xlsx spreadsheet skills. + requires: [] + - slug: core + package: '@tanstack/react-spreadsheet' + domain: spreadsheet + type: framework + framework: react + purpose: Drive a workbook from React with owned or provided instances, + revision-tracked cell and region reads, and the /table grid entry. + sources: + - TanStack/table:packages/react-spreadsheet/src/index.ts + - TanStack/table:packages/react-spreadsheet/src/hooks.ts + - TanStack/table:packages/react-spreadsheet/src/table.ts + - TanStack/table:packages/react-spreadsheet/src/useSpreadsheetTable.ts + failure_modes: + - Rendering a raw CellValue that may be an error or pending object into + JSX instead of narrowing and formatting it first. + - Expecting later useSpreadsheet option changes to rebuild the workbook + when construction is frozen on first render. + - Importing the /table grid hook into cell-only views and pulling in the + table-v9 projection unnecessarily. + description: + Drive a TanStack Spreadsheet workbook from React. Route owned vs. provided + workbooks, revision-tracked cell and region reads, and the /table grid + entry. Use spreadsheet-core for the kernel and value model. + requires: + - '@tanstack/spreadsheet-core#core' + - slug: core + package: '@tanstack/spreadsheet-table' + domain: spreadsheet + type: framework + purpose: + Project a workbook sheet window onto a TanStack Table v9 instance with + createSpreadsheetTable, the registered feature set, and the selection, + fill, clipboard, and merge verbs. + sources: + - TanStack/table:packages/spreadsheet-table/src/index.ts + - TanStack/table:packages/spreadsheet-table/src/controller.ts + - TanStack/table:packages/spreadsheet-table/src/features.ts + - TanStack/table:packages/spreadsheet-table/src/projection.ts + - TanStack/table:packages/spreadsheet-table/src/types.ts + failure_modes: + - Mutating the projected rows instead of editing through the verbs or the + workbook, which is the single source of truth. + - Forgetting to call destroy and leaking the workbook revision + subscription when the table is discarded. + - Treating the result as a plain object rather than a v9 Table whose + standard row-model APIs coexist with the spreadsheet verbs. + description: + Project a TanStack Spreadsheet workbook onto a TanStack Table v9 instance + with createSpreadsheetTable. Route the registered features, the + sheet-to-rows/columns projection, and the spreadsheet verbs. Use + spreadsheet-core for the kernel. + requires: + - '@tanstack/spreadsheet-core#core' + - slug: core + package: '@tanstack/spreadsheet-xlsx' + domain: spreadsheet + type: integration + purpose: + Round-trip .xlsx bytes through a workbook with importXlsx and exportXlsx, + surfacing the structured issues model and the fixed dropped-feature list. + sources: + - TanStack/table:packages/spreadsheet-xlsx/src/index.ts + - TanStack/table:packages/spreadsheet-xlsx/src/importer.ts + - TanStack/table:packages/spreadsheet-xlsx/src/exporter.ts + - TanStack/table:packages/spreadsheet-xlsx/src/drops.ts + failure_modes: + - Assuming a clean import instead of reading ImportResult.issues and + summary.byKind for degraded cells and dropped features. + - Expecting an unsupported formula to throw rather than keeping its cached + value and recording an issue. + - Exporting without warning users via DROPPED_FEATURES or + DROPPED_FEATURES_SENTENCE about features that cannot cross over. + description: + Round-trip .xlsx bytes through a TanStack Spreadsheet workbook with + importXlsx and exportXlsx. Route the issues/degradation model and the + fixed dropped-feature list. Use spreadsheet-core for the workbook and + value model. + requires: + - '@tanstack/spreadsheet-core#core' cross_references: - from: core diff --git a/_artifacts/skill_tree.yaml b/_artifacts/skill_tree.yaml index 0588b272ee..679997548c 100644 --- a/_artifacts/skill_tree.yaml +++ b/_artifacts/skill_tree.yaml @@ -925,3 +925,77 @@ skills: - TanStack/table:packages/match-sorter-utils/src/index.ts - TanStack/table:docs/framework/react/guide/fuzzy-filtering.md - TanStack/table:examples/react/filters-fuzzy + - name: Spreadsheet Core + slug: core + type: core + domain: spreadsheet + path: packages/spreadsheet-core/skills/core/SKILL.md + package: packages/spreadsheet-core + description: + Use the TanStack Spreadsheet workbook kernel and capability model. Route + cell input, patches, computed reads, errors and pending as values, region + subscriptions, and opt-in capabilities. Load before the react, table-v9, + or xlsx spreadsheet skills. + sources: + - TanStack/table:packages/spreadsheet-core/src/index.ts + - TanStack/table:packages/spreadsheet-core/src/types.ts + - TanStack/table:packages/spreadsheet-core/src/workbook.ts + - TanStack/table:packages/spreadsheet-core/src/kernel.ts + - TanStack/table:packages/spreadsheet-core/src/construct.ts + - TanStack/table:packages/spreadsheet-core/src/capability.ts + - TanStack/table:packages/spreadsheet-core/src/eval.ts + - TanStack/table:packages/spreadsheet-core/src/capabilities/index.ts + - name: React Spreadsheet Core + slug: core + type: framework + domain: spreadsheet + path: packages/react-spreadsheet/skills/core/SKILL.md + package: packages/react-spreadsheet + description: + Drive a TanStack Spreadsheet workbook from React. Route owned vs. provided + workbooks, revision-tracked cell and region reads, and the /table grid + entry. Use spreadsheet-core for the kernel and value model. + requires: + - '@tanstack/spreadsheet-core#core' + sources: + - TanStack/table:packages/react-spreadsheet/src/index.ts + - TanStack/table:packages/react-spreadsheet/src/hooks.ts + - TanStack/table:packages/react-spreadsheet/src/table.ts + - TanStack/table:packages/react-spreadsheet/src/useSpreadsheetTable.ts + - name: Spreadsheet Table + slug: core + type: framework + domain: spreadsheet + path: packages/spreadsheet-table/skills/core/SKILL.md + package: packages/spreadsheet-table + description: + Project a TanStack Spreadsheet workbook onto a TanStack Table v9 instance + with createSpreadsheetTable. Route the registered features, the + sheet-to-rows/columns projection, and the spreadsheet verbs. Use + spreadsheet-core for the kernel. + requires: + - '@tanstack/spreadsheet-core#core' + sources: + - TanStack/table:packages/spreadsheet-table/src/index.ts + - TanStack/table:packages/spreadsheet-table/src/controller.ts + - TanStack/table:packages/spreadsheet-table/src/features.ts + - TanStack/table:packages/spreadsheet-table/src/projection.ts + - TanStack/table:packages/spreadsheet-table/src/types.ts + - name: Spreadsheet XLSX + slug: core + type: integration + domain: spreadsheet + path: packages/spreadsheet-xlsx/skills/core/SKILL.md + package: packages/spreadsheet-xlsx + description: + Round-trip .xlsx bytes through a TanStack Spreadsheet workbook with + importXlsx and exportXlsx. Route the issues/degradation model and the + fixed dropped-feature list. Use spreadsheet-core for the workbook and + value model. + requires: + - '@tanstack/spreadsheet-core#core' + sources: + - TanStack/table:packages/spreadsheet-xlsx/src/index.ts + - TanStack/table:packages/spreadsheet-xlsx/src/importer.ts + - TanStack/table:packages/spreadsheet-xlsx/src/exporter.ts + - TanStack/table:packages/spreadsheet-xlsx/src/drops.ts diff --git a/docs/config.json b/docs/config.json index 2625aaeae7..0d4b66d1f3 100644 --- a/docs/config.json +++ b/docs/config.json @@ -1631,6 +1631,28 @@ ] } ] + }, + { + "label": "TanStack Spreadsheet (Experimental)", + "children": [ + { "label": "Overview", "to": "spreadsheet/overview" }, + { "label": "Quick Start", "to": "spreadsheet/quick-start" }, + { "label": "Installation", "to": "spreadsheet/installation" }, + { "label": "Formula Language", "to": "spreadsheet/formula-language" }, + { "label": "Workbook API", "to": "spreadsheet/workbook-api" }, + { + "label": "Functions, Packs & the Registry", + "to": "spreadsheet/registry-and-packs" + }, + { + "label": "Projecting into TanStack Table", + "to": "spreadsheet/projection-guide" + }, + { "label": "React Bindings", "to": "spreadsheet/react-guide" }, + { "label": "XLSX Fidelity", "to": "spreadsheet/xlsx-fidelity" }, + { "label": "TanStack Store", "to": "spreadsheet/store-guide" }, + { "label": "The Agent Surface", "to": "spreadsheet/agent-guide" } + ] } ] } diff --git a/docs/spreadsheet/agent-guide.md b/docs/spreadsheet/agent-guide.md new file mode 100644 index 0000000000..b126071c54 --- /dev/null +++ b/docs/spreadsheet/agent-guide.md @@ -0,0 +1,80 @@ +--- +title: The Agent Surface +--- + +`@tanstack/spreadsheet-agent` is the one tool surface an agent calls against a +workbook. It is A1-addressed, reads the real dependency graph (no formula +re-parsing), returns plain data, and composes into any agent framework. There is +no second, library-shaped toolkit — this is the single door. + +Above: the demo's `/agent` route. Claude writes a **Code Mode** program (TypeScript +run in a QuickJS-WASM sandbox in the browser) that calls this very tool surface — +`set_cells`, `read_sheet`, `verify` — to build and check the sheet. The model +completion runs server-side, so the API key never reaches the browser; the +generated code runs sandboxed in it. + +## The tools + +```ts +import { + setCells, + readSheet, + explain, + listErrors, + listPending, + listFunctions, + verify, +} from '@tanstack/spreadsheet-agent' + +setCells(wb, [ + { a1: 'A1', input: '10' }, + { a1: 'A2', input: '=A1*2' }, +]) // one batched transaction → one recalc + +readSheet(wb, 's1') // [{ a1, input, value, kind }, …] +explain(wb, 'A2') // { value, input, precedents, precedentRanges, dependents } — all A1 +listErrors(wb) // [{ a1, code }] +listPending(wb) // ['B3', …] +listFunctions(wb) // the function catalog (with origin + callSites) +``` + +`explain` reads `workbook.precedentsOf` / `dependentsOf` directly — it does not +re-parse formulas, and it follows the graph the engine actually computes on. + +## Verify composition + +`verify` is a **pure** function: it takes the (already settled) workbook plus +the caller's checks and returns a list of [`Issue`](./xlsx-fidelity.md)s — the +same shared type XLSX import produces. Sequencing is the caller's ordinary async +code, shown explicitly: + +```ts +build(wb) // your edits, e.g. setCells(...) +await wb.settle() // let async cells resolve +const issues = verify(wb, { + sheet: 's1', + checks: [{ label: 'total is 30', ok: total(wb) === 30 }], +}) +if (issues.length) { + /* failing checks + unexpected error cells, each with a message (and ref) */ +} +``` + +There is no `buildAndVerify` hybrid: `verify` verifies, `settle` settles, and +your code composes them. + +## Framework tool definitions + +`spreadsheetTools(wb)` returns framework-agnostic specs +(`{ name, description, parameters, execute }`) you map onto your framework's tool +definition — e.g. TanStack AI's `toolDefinition`. The demo's `/agent` route +dogfoods exactly this surface: its `set_cells` / `read_sheet` / `verify` tool +bodies call these functions rather than re-implementing workbook access. + +## With Code Mode + +Authoring a Code Mode function (`@tanstack/spreadsheet-codemode`: +`stageFunction` → `approveAndRegister`) and calling the agent tools fit together: +the agent builds the sheet with `setCells`, authors a function (staged + example +-gated), a human approves registration, and `verify` confirms the result before +a diff is shown. Code Mode is authoring; the agent surface is read/edit/verify. diff --git a/docs/spreadsheet/formula-language.md b/docs/spreadsheet/formula-language.md new file mode 100644 index 0000000000..f55a1f9377 --- /dev/null +++ b/docs/spreadsheet/formula-language.md @@ -0,0 +1,195 @@ +--- +title: Formula Language Reference +--- + +The engine speaks an Excel-compatible formula language. Excel is the reference +spec: where this page and Excel disagree, that is a bug unless it appears under +[Documented non-goals](#documented-non-goals). A formula is any cell input that +begins with `=`; everything else is a literal (see [Value coercion](#value-coercion)). + +## Operators and precedence + +Binding power, tightest last. The ordering encodes Excel's quirks exactly — the +golden-file suite is what pins them. + +| Group | Operators | Notes | +| -------------- | -------------------------- | ----------------------------------------------------------------------------- | +| Comparison | `=` `<>` `<` `<=` `>` `>=` | Loosest. Numeric when both sides read as numbers, else case-insensitive text. | +| Concatenation | `&` | Sits between arithmetic and comparison. | +| Additive | `+` `-` | | +| Multiplicative | `*` `/` | `/` by zero → `#DIV/0!`. | +| Exponent | `^` | **Left**-associative: `2^3^2 = 64`, not 512. | +| Percent | `%` (postfix) | Tighter than `^`: `50%` = 0.5. | +| Unary | `-` `+` (prefix) | **Tighter than `^`**: `-2^2 = 4`, not −4. | +| Range | `:` | Tightest. Builds a range from two endpoints. | + +Parentheses override precedence as usual. These are the two quirks most engines +get wrong, and both are deliberate here: unary minus binds tighter than `^`, and +`^` is left-associative. + +## References and ranges + +- **Cell** — `A1`, `$A$1`, `B$2`. A `$` anchors that axis against fill/paste + translation. +- **Range** — `A1:B10`. Whole column `A:A`, whole row `1:1`. +- **Cross-sheet** — `Sheet2!A1`, `'My Sheet'!A1:B2` (quote a sheet name that is + not a bare identifier). A single sheet qualifier distributes across a range: + both endpoints of `Sheet2!A1:B2` live on `Sheet2`. +- **3D range** — `Jan!A1:Dec!A1` names the same block on **every sheet from + `Jan` through `Dec` inclusive, in workbook sheet order**. Sheet order is + load-bearing data: the dependency graph and aggregates iterate the span, so + moving or reordering sheets changes the result, and a cell changing on any + sheet in the span recalculates the formula. Serialization round-trips both + endpoint sheets. + +## Defined names + +A name binds to a range, a constant, or a formula, and is a first-class +precedent: a formula that reads a name recalculates when the name's target +changes, and serialization round-trips the name verbatim (never its expansion). + +```ts +wb.defineName('Rate', '0.2') // a constant +wb.defineName('Prices', 'Sheet1!B2:B50') // a range +wb.defineName('Tax', '=Subtotal*Rate') // a formula +wb.defineName('Local', 'A1', { scope: 's1' }) // sheet-scoped + +wb.listNames() // discover — the agent-facing catalog surface +wb.getName('Rate') // { name, scope?, definition } +wb.removeName('Rate') // dependents re-evaluate (to #NAME? if now undefined) +``` + +- **Scope** — a name is workbook-scoped by default, or sheet-scoped via + `{ scope }`. A bare reference (`=Rate`) resolves against the owning sheet's + scope first, then the workbook; a qualified reference (`=Budget!Total`) + targets that sheet's scope, then the workbook. +- **Rules (enforced; violations throw with a message)** — a name may not + collide with a cell reference (`A1`), a sheet name, or a function name; must + be a valid identifier (letter/underscore first); may not be `TRUE`/`FALSE`; + and may not be cyclic. +- An **undefined** name evaluates to `#NAME?`, exactly like an unknown function. + +## Value coercion + +Literal cell input is coerced on entry (no `=`): + +| Input | Becomes | +| ------------------ | ------------------------------------------------------------------------- | +| `` (empty) | `null` (blank — a value state, not an error) | +| `TRUE` / `FALSE` | boolean | +| `2020-01-01` | a **date serial** (Excel epoch 1899-12-30); an impossible date stays text | +| `42`, `1.5`, `2e3` | number | +| `'123` | the text `123` (leading apostrophe forces text) | +| anything else | text | + +Inside formulas, coercion is contextual and errors/`pending` propagate through +every operator: + +- **To number** — booleans are 1/0, blank is 0, numeric text parses, other text + → `#VALUE!`. +- **To text** — numbers stringify, booleans are `TRUE`/`FALSE`, blank is `""`. +- **To boolean** — numbers are nonzero, `"TRUE"`/`"FALSE"` parse, blank/`""` is + false, other text → `#VALUE!`. + +Dates are serial numbers; display formatting is the adapter/format layer's job +(`setFormat`, `TEXT`). + +## Criteria and wildcards + +`SUMIF`, `COUNTIF`, and the `*IFS` family take criteria like `">10"`, `"<>0"`, +`"Gadgets"`. On `=`/`<>` text matches, Excel wildcards apply: + +- `*` — any run of characters (`"Gadget*"` matches `Gadgetry`) +- `?` — any single character (`"?adget"` matches `Gadget`) +- `~` — escapes a literal `*`, `?`, or `~` (`"a~*b"` matches only `a*b`) + +## Error codes + +Errors are values. Distinct failure kinds get distinct codes (no `#N/A` +costumes); an error value may carry a human-readable `detail`. + +| Code | Meaning | +| ----------- | ------------------------------------------------------------------- | +| `#DIV/0!` | Division by zero. | +| `#VALUE!` | A value could not be coerced to the type an operation needs. | +| `#REF!` | A reference points off-sheet (e.g. translated out of bounds). | +| `#NAME?` | Unknown function or undefined name. | +| `#N/A` | A lookup found no match. | +| `#NUM!` | A numeric result is not finite/representable. | +| `#NULL!` | (reserved) | +| `#ERR!` | A formula failed to **parse**. `detail` carries the parser message. | +| `#CIRCULAR` | The cell participates in a dependency cycle. | + +## Built-in functions + +46 built-ins, registered into every workbook. Each row is generated from the +same descriptor that drives validation and the agent catalog +(`workbook.functionCatalog()`); `…` in the arity column means variadic. + +| Signature | Args | Returns | Description | +| ------------------------------------------------------ | ---- | ------- | ---------------------------------------------------------------------------------- | +| `ABS(number)` | 1–1 | number | Absolute value of a number. | +| `AGGREGATE(functionCode, options, range1)` | 3–… | number | Aggregate with options to ignore hidden rows and/or errors. | +| `AND(logical1)` | 1–… | boolean | TRUE if every argument is TRUE. | +| `AVERAGE(number1, number2?)` | 1–… | number | Arithmetic mean of the numeric values. | +| `AVERAGEIF(range, criterion, averageRange?)` | 2–3 | number | Average the cells that meet a single criterion. | +| `AVERAGEIFS(averageRange, criteriaRange1, criterion1)` | 3–… | number | Average the cells that meet multiple criteria. | +| `CONCAT(text1)` | 1–… | string | Join text values into one string. | +| `CONCATENATE(text1)` | 1–… | string | Join text values into one string (legacy alias of CONCAT). | +| `COUNT(number1, number2?)` | 1–… | number | Count of numeric values. | +| `COUNTA(number1, number2?)` | 1–… | number | Count of non-blank values. | +| `COUNTIF(range, criterion)` | 2–2 | number | Count the cells that meet a single criterion. | +| `COUNTIFS(criteriaRange1, criterion1)` | 2–… | number | Count the cells that meet multiple criteria. | +| `DATE(year, month, day)` | 3–3 | date | Date serial from year, month, and day (overflow rolls over). | +| `DAY(date)` | 1–1 | number | Day of the month (1–31) of a date serial. | +| `IF(condition, ifTrue, ifFalse?)` | 2–3 | any | Return one value if a condition is true, another if false. | +| `IFERROR(value, fallback)` | 2–2 | any | Return a fallback value when the first argument is an error. | +| `IFPENDING(value, fallback)` | 2–2 | any | Return a fallback while an async value is still pending. | +| `INDEX(range, row, column?)` | 2–3 | any | Value at a given row/column position within a range. | +| `ISRESOLVED(value)` | 1–1 | boolean | TRUE once an async value has arrived (not pending). | +| `LEFT(text, count?)` | 1–2 | string | Leftmost characters of a text string. | +| `LEN(text)` | 1–1 | number | Number of characters in a text string. | +| `LOWER(text)` | 1–1 | string | Convert text to lower case. | +| `MATCH(key, range, matchType?)` | 2–3 | number | Position of a value within a one-row or one-column range. | +| `MAX(number1, number2?)` | 1–… | number | Largest numeric value. | +| `MAXIFS(maxRange, criteriaRange1, criterion1)` | 3–… | number | Largest value among cells that meet multiple criteria. | +| `MID(text, start, count)` | 3–3 | string | Characters from the middle of a text string. | +| `MIN(number1, number2?)` | 1–… | number | Smallest numeric value. | +| `MINIFS(minRange, criteriaRange1, criterion1)` | 3–… | number | Smallest value among cells that meet multiple criteria. | +| `MONTH(date)` | 1–1 | number | Month (1–12) of a date serial. | +| `NOT(logical)` | 1–1 | boolean | Reverse the logical value of its argument. | +| `NOW()` | 0–0 | date | Current date and time as a serial number (volatile). | +| `OR(logical1)` | 1–… | boolean | TRUE if any argument is TRUE. | +| `RIGHT(text, count?)` | 1–2 | string | Rightmost characters of a text string. | +| `ROUND(number, digits)` | 2–2 | number | Round a number to a given number of digits. | +| `ROUNDDOWN(number, digits)` | 2–2 | number | Round a number toward zero to a given number of digits. | +| `ROUNDUP(number, digits)` | 2–2 | number | Round a number away from zero to a given number of digits. | +| `SUBTOTAL(functionCode, range1)` | 2–… | number | Aggregate (SUM/AVERAGE/…) honouring row visibility. | +| `SUM(number1, number2?)` | 1–… | number | Add all numbers in the arguments or ranges. | +| `SUMIF(range, criterion, sumRange?)` | 2–3 | number | Sum the cells that meet a single criterion. | +| `SUMIFS(sumRange, criteriaRange1, criterion1)` | 3–… | number | Sum the cells that meet multiple criteria. | +| `TEXT(value, formatCode)` | 2–2 | string | Format a value as text using a number-format code. | +| `TODAY()` | 0–0 | date | Today's date as a serial number (volatile). | +| `TRIM(text)` | 1–1 | string | Remove extra whitespace from text. | +| `UPPER(text)` | 1–1 | string | Convert text to upper case. | +| `VLOOKUP(key, range, colIndex, approximate?)` | 3–4 | any | Look up a value in the first column of a range and return a value in the same row. | +| `YEAR(date)` | 1–1 | number | Year of a date serial. | + +Custom and async functions register into the same catalog — see the +[Workbook API](./workbook-api.md). + +## Documented non-goals + +Deliberate divergences from Excel, recorded so they are not mistaken for bugs: + +- **Spill / dynamic arrays** — a formula returns one scalar; array spilling is + not modelled. +- **Space intersection operator** — whitespace is insignificant; the implicit + range-intersection operator is not supported. +- **Array constants** — `{1,2;3,4}` literals are not parsed. +- **R1C1 notation** — addressing is A1-only. +- **External-workbook references** — `[Book.xlsx]Sheet!A1` is not supported. +- **`LAMBDA` and `LET`** — user-defined inline functions/bindings are not + parsed; use [defined names](#defined-names) and workbook-defined functions. +- **STDEV/VAR in SUBTOTAL/AGGREGATE** — function codes outside the + SUM/AVERAGE/COUNT/MIN/MAX/PRODUCT set return `#VALUE!`. diff --git a/docs/spreadsheet/installation.md b/docs/spreadsheet/installation.md new file mode 100644 index 0000000000..3378a158fb --- /dev/null +++ b/docs/spreadsheet/installation.md @@ -0,0 +1,47 @@ +--- +title: Installation +--- + +> **Experimental.** The spreadsheet packages ship alongside TanStack Table and +> share its version line, but the API is still settling — expect changes between +> minor releases. + +## The packages + +Start with `@tanstack/spreadsheet-core`; add the others only as you need them. + +```bash +npm install @tanstack/spreadsheet-core +``` + +| Package | Install it when you need… | +| -------------------------------- | ------------------------------------------------------------------------------------ | +| `@tanstack/spreadsheet-core` | The engine itself — addressing, parser, dependency graph, evaluator. Always. | +| `@tanstack/spreadsheet-table` | To project a sheet into a TanStack Table **v9** grid, with the `spreadsheetFeature`. | +| `@tanstack/react-spreadsheet` | React bindings (hooks) over workbook subscriptions. | +| `@tanstack/spreadsheet-xlsx` | To import/export `.xlsx` workbooks (values + formulas). | +| `@tanstack/spreadsheet-packs` | Async function packs: a mock decision model and a REST data pack. | +| `@tanstack/spreadsheet-store` | TanStack Store interop: cell/range facades, virtual sheets, Tier-1 staging. | +| `@tanstack/spreadsheet-codemode` | Code Mode cell functions authored on the fly, plus an AI read/build toolkit. | +| `@tanstack/spreadsheet-agent` | A framework-agnostic agent toolkit (read/write/explain/verify) over a workbook. | + +The React bindings also need their peers: + +```bash +npm install @tanstack/react-spreadsheet @tanstack/table-core react react-dom +``` + +## Build from source + +The packages live in the TanStack Table monorepo. + +```bash +git clone https://github.com/TanStack/table.git +cd table +pnpm install +pnpm build # builds all packages (ESM + .d.ts via tsdown) +``` + +See [Quick Start](./quick-start.md) for first usage, and the repository's +[Contributing guide](https://github.com/TanStack/table/blob/main/CONTRIBUTING.md) +for the full development loop. diff --git a/docs/spreadsheet/overview.md b/docs/spreadsheet/overview.md new file mode 100644 index 0000000000..6176f33974 --- /dev/null +++ b/docs/spreadsheet/overview.md @@ -0,0 +1,54 @@ +--- +title: Overview +--- + +TanStack Spreadsheet is a headless, framework-agnostic spreadsheet engine — a +dependency-graph compute core with TanStack Table display/editing on top — that +can serve as an application's state manager. It adds a plugin function registry; +asynchronous cell equations for decision models and live data, resolved through +a cached, graph-aware scheduler; Code Mode functions authored on the fly and +stored in the workbook as Snippets; bidirectional TanStack Store interop; and AI +that reads, explains, builds, and generates UI over the workbook — all proven by +a fluid-budgeting demo in which every number on screen can be flipped over and +read as an equation. + +> **Status: unreleased.** Every package is `0.0.0` and `private`; nothing is +> published to npm yet. See [Installation](./installation.md) for clone-and-build +> instructions. + +## Two roles in one dependency + +TanStack Spreadsheet plays two roles at once, and they are the same object seen +from two sides: + +- **A headless spreadsheet control** — the interaction layer (selection, formula + bar, fill, clipboard, merges) projected onto the TanStack Table v9 adapter, with + React bindings. You render; it computes. +- **A reactive state manager** — the workbook _is_ your application state. Mutate + through patches, subscribe to regions, read settled values — no UI required. + Every value is backed by an equation you can read back. + +Because the core depends only on `@tanstack/store`, the state-manager role runs +anywhere JavaScript runs, and the control is just its first consumer. + +## How it layers + +- The **compute core** (`@tanstack/spreadsheet-core`) is the whole model: + addressing, parser, dependency graph, and evaluator. Its only dependency is + `@tanstack/store`, so it runs in Node, a worker, or a serverless function. +- **Display and editing** sit on top as adapters — the TanStack Table v9 + projection and the React bindings — none of which the core depends on. +- Because the core has no UI dependency, the **workbook is usable on its own as + a reactive state manager**: mutate through patches, subscribe to regions, and + read settled values. A grid is one consumer of that model, not a requirement. + +A spreadsheet is not a table: a table is row-oriented with columns as schema, +while a sheet is a sparse 2D cell store with its own address space and ordering +independent of how it is displayed. The core owns addressing; TanStack Table is +a consumer of it. + +## Where to go next + +- [Quick Start](./quick-start.md) — build and read a workbook in a few lines. +- [Installation](./installation.md) — the packages and how to build them today. +- [Workbook API](./workbook-api.md) — the full `Workbook` surface. diff --git a/docs/spreadsheet/projection-guide.md b/docs/spreadsheet/projection-guide.md new file mode 100644 index 0000000000..ce2bb0ba11 --- /dev/null +++ b/docs/spreadsheet/projection-guide.md @@ -0,0 +1,76 @@ +--- +title: Projecting a Sheet into TanStack Table +--- + +`@tanstack/spreadsheet-table` projects a workbook sheet into a **TanStack +Table v9** grid. v9 is the only adapter — there is no v8. The projection is thin +on purpose: the workbook stays the source of truth, and the table is a view. + +The demo's `/grid` route is this projection in action — selection, the formula +bar, fill, and clipboard all flow through the table instance while React only +renders. The `runFormula(…)` panel at the bottom evaluates against the same model +with no cell written, showing the workbook as a headless data engine. + +## Rows are pointers into sheet address space + +A projected row is not a copy of cell data — it is a pointer to a sheet row. +Column accessors read the **computed** value live from the workbook: + +```ts +accessorFn: (row) => workbook.getCell({ sheet, row: row.sheetRow, col })?.value +``` + +Two consequences fall out for free: + +- **Sort-by-computed** — sorting uses the accessor's computed value, so a column + of formulas sorts by result, not by formula text. +- **Anchored A1 addressing** — a row carries its `sheetRow` (its address), stable + across sorts and windowing, so selection and fill map back to sheet + coordinates regardless of display order. + +## Building a table + +```ts +import { createSpreadsheetTable } from '@tanstack/spreadsheet-table' + +const table = createSpreadsheetTable(workbook, { + sheet: 's1', + rows: { from: 0, to: 200 }, // the visible window + cols: { from: 0, to: 26 }, +}) +``` + +The returned value is a standard v9 `Table` with the spreadsheet verbs attached, +acting on the current selection / focused cell: + +```ts +table.getFormulaBarValue() +table.commitFocusedCell('=A1+B1') +table.fillDown() // fillUp / fillRight / fillLeft +table.copySelection() // → Clipboard +table.pasteToSelection(clip) +table.mergeSelection() // unmergeSelection, getMerges, getMergeAt +table.getSelectionRect() +``` + +Merges are **read from the workbook** (`getMerges`), the single source of truth — +no adapter-local copy. (`SharedState` is internal plumbing, not exported.) + +## Reactivity — the adapter subscribes to the workbook + +The adapter subscribes to the workbook itself and rebuilds its row model on every +commit, so an **external edit** — another view, an agent tool, an async settle — +appears in an open grid without calling one of the table's own verbs. The old +manual `invalidate()` per verb is gone; `table.refresh()` is the same rebuild, +exposed for the rare host-driven mutation, and `table.destroy()` detaches the +subscription when the table is discarded. + +In React this is wired for you by `useSpreadsheetTable` (see the +[React guide](./react-guide.md)). + +## Documented deviation: multi-region selection + +A disjoint multi-region selection collapses to its **bounding-box union** before +a verb acts on it (fill/copy/merge operate on one rectangle). This is a +deliberate simplification, not disjoint-region semantics — recorded here and in +the code rather than left silent. diff --git a/docs/spreadsheet/quick-start.md b/docs/spreadsheet/quick-start.md new file mode 100644 index 0000000000..bf6efc766a --- /dev/null +++ b/docs/spreadsheet/quick-start.md @@ -0,0 +1,56 @@ +--- +title: Quick Start +--- + +The `Workbook` is the whole model — no UI, framework, or Table dependency (its +only dependency is `@tanstack/store`). This walkthrough builds one and reads it +back, all headless. + +## 1. Create a workbook + +```ts +import { createWorkbook } from '@tanstack/spreadsheet-core' + +const wb = createWorkbook() +``` + +## 2. Add a sheet + +```ts +wb.addSheet('s1') +``` + +## 3. Set input and commit + +Mutation and commit are **separate**. `setInput` returns patches; it does not +apply them. Everything funnels through `applyPatches`, which runs the full +synchronous recalc pipeline and returns once the graph is settled. + +```ts +wb.applyPatches(wb.setInput({ sheet: 's1', row: 1, col: 0 }, '10')) +wb.applyPatches(wb.setInput({ sheet: 's1', row: 2, col: 0 }, '20')) +wb.applyPatches(wb.setInput({ sheet: 's1', row: 0, col: 0 }, '=SUM(A2:A5)')) +``` + +## 4. Read a computed cell + +```ts +wb.getCell({ sheet: 's1', row: 0, col: 0 })?.value // 30 +``` + +## 5. Evaluate a formula ad-hoc + +`runFormula` evaluates against the workbook's current settled values without +writing a cell or creating dependency edges. A leading `=` is optional; errors +are returned as values. + +```ts +wb.runFormula('AVERAGE(A2:A5)') // 15 +wb.runFormula('1/0') // { kind: 'error', code: '#DIV/0!' } +``` + +## Next steps + +See the [Workbook API](./workbook-api.md) for the full surface: the function +registry, asynchronous cell equations, display formats, workbook-defined +functions, virtual sheets, undo/redo, and region subscriptions. diff --git a/docs/spreadsheet/react-guide.md b/docs/spreadsheet/react-guide.md new file mode 100644 index 0000000000..41388125e2 --- /dev/null +++ b/docs/spreadsheet/react-guide.md @@ -0,0 +1,62 @@ +--- +title: React Bindings +--- + +`@tanstack/react-spreadsheet` is a thin `useSyncExternalStore` shim over the +workbook's reactive surface. Pick the hook that matches the job. + +## Which hook for which job + +| Hook | Job | Re-renders on | +| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | +| `useSpreadsheet(wb)` | **Workbook level** — the umbrella front door (mirrors `useReactTable`). Returns `{ workbook, revision, getCellValue }`. | any commit | +| `useSpreadsheetTable(wb, config)` | **The grid hook** — owns a `createSpreadsheetTable` for a sheet window and drives the grid. From `@tanstack/react-spreadsheet/table`. | table state (selection/focus) + any commit | +| `useCell(wb, ref)` | **Granular, whole-cell** — input/formula text, value, format-aware `display`, `pending`. What a custom cell renders from. | that cell | +| `useCellValue(wb, ref)` | Granular, raw value only (may be a `PendingValue`). The primitive beneath `useCell`. | that cell | +| `useSheetValues(wb, { sheet, rect })` | Granular, a dense 2D value grid for a window. | any cell in the region | +| `useRevision(wb)` | The raw revision counter. | any commit | + +## The grid hook + +Lives behind the `@tanstack/react-spreadsheet/table` entry so the root hooks +stay pure workbook bindings — a consumer that only reads cells never pulls in +`@tanstack/spreadsheet-table`. + +```tsx +import { useSpreadsheetTable } from '@tanstack/react-spreadsheet/table' + +function Grid({ workbook }) { + const table = useSpreadsheetTable(workbook, { + sheet: 's1', + rows: { from: 0, to: 200 }, + cols: { from: 0, to: 26 }, + }) + // call the table verbs directly — commitFocusedCell, fillDown, copySelection, … + return {/* render table.getRowModel() */}
+} +``` + +The hook owns the table across renders, re-renders on the table's own state and +on workbook commits (so an external edit shows up without a verb), and tears the +table's workbook subscription down (`table.destroy()`) on unmount or rebuild. + +## The whole-cell hook + +`useCell` is what a custom-UI builder renders from — it hands back the whole cell, +not just the value, with a **format-aware display string** (never a raw +`PendingValue` object or `[object Object]`): + +```tsx +function Cell({ workbook, sheet, row, col }) { + const { input, kind, value, display, pending } = useCell(workbook, { + sheet, + row, + col, + }) + return {display} +} +``` + +`display` honours the cell's number format (`workbook.getFormat`) via core's +`formatValue`: a percent cell shows `50.00%`, a pending async cell shows `…`, an +error shows its code. diff --git a/docs/spreadsheet/registry-and-packs.md b/docs/spreadsheet/registry-and-packs.md new file mode 100644 index 0000000000..5706ff64b6 --- /dev/null +++ b/docs/spreadsheet/registry-and-packs.md @@ -0,0 +1,140 @@ +--- +title: Functions, Packs & the Registry +--- + +Every function — builtin, pack, async, Code Mode — lives in **one** workbook +registry. A pack is a registration convenience; there is no second manifest, no +sidecar, and no separate lifecycle. This page is how you register a function, +bundle a pack, wire an async route, and read the manifest view. + +The demo's `/functions` route renders the catalog straight off the workbook: one +descriptor per function drives validation, help text, the `origin` chip, and the +row you see. Bare names are reserved for builtins; packs are namespaced (e.g. +`ACME.TAX`) and cannot shadow them. + +## One registry, one manifest + +Each registered function carries an **origin** tag: + +| Origin | How it got there | +| ----------- | ----------------------------------------------------------- | +| `builtin` | A core built-in (bare names, reserved). | +| `pack` | Registered as part of a `FunctionPack` (see `pack`). | +| `code-mode` | Authored on the fly (Code Mode); carries a source record. | +| `host` | Registered directly by the host — the trusted escape hatch. | + +```ts +wb.functionCatalog() // every function: origin, signature, version, callSites +wb.functionManifest() // registered packs: { name, version } +wb.missingFunctions() // names a formula references but nothing registered +``` + +`functionCatalog()` entries carry a **live `callSites` count** — how many +formulas reference each function right now — so unused functions are surfaceable +for cleanup. Mutating a function with zero live call sites skips the recalc +fan-out. + +## Registering functions + +```ts +// A pack — the painless way to register related functions under one namespace. +wb.registerPack({ + name: 'ACME', + version: '1.2.3', + functions: [{ name: 'ACME.TAX', minArgs: 1, evaluate: (ctx) => /* … */ }], +}) + +// The host-trusted direct path (origin `host`). Bypasses the Code Mode example +// gate — call it for functions you already trust. +wb.upsertFunction(def) + +// Remove a function everywhere — registry and export. Call sites re-evaluate. +wb.removeFunction('ACME.TAX') +``` + +Custom names must be namespaced (`PACK.NAME`); bare names are reserved for +builtins. A collision throws `FunctionCollisionError`. + +### Pack-missing degrade + +A formula that references an **unregistered** function (e.g. a pack that was not +loaded) evaluates to `#NAME?`, and the function name appears in +`wb.missingFunctions()` — the degrade is visible, not silent. An XLSX import +seeds the last cached value for such a cell where one exists, so the number +survives even when the pack is absent. + +## Async functions + +An async function (`kind: 'async'`) is resolved by a host **execution port**; +the evaluator never awaits. Registering one with **no port wired throws at +registration** — there is no silent, never-resolving `pending`. + +```ts +const wb = createWorkbook({ + asyncPort, + packs: [decisionPack(model)], +}) +await wb.settle() // resolve once nothing is in flight +``` + +**Port contract:** `execute(name, requests)` returns one result per request, +each carrying a per-request value — an error _value_ for a failed request, never +a thrown exception. A rejected/thrown batch fails _every_ request in it to +`#VALUE!`, so a port wanting per-request fidelity must resolve, not throw. + +**Range arguments** reach non-builtins too: a range argument is materialized to +a 2D grid and folded into the call key by content, so an async function recalcs +when a cell in its range argument changes. `JEV.CHOICE(value, A1:A5)` (a range +of labels) and `JEV.CHOICE(value, "a,b,c")` (the CSV form) both work. + +### Budget, resume, and refresh + +The async budget is an **opt-in spend cap** (`asyncBudget`), unlimited by +default — the engine never silently seizes. When the cap is hit, requests are +_budget-paused_ (visible as `asyncStats().paused`), and `resumeAsync()` raises +the cap and re-flushes them. + +```ts +wb.asyncStats() // { cached, inFlight, dispatched, batches, paused, budget } +wb.resumeAsync() // lift the cap, re-dispatch paused requests +wb.refreshAsync() // invalidate all cached results → refire on next recalc +wb.refreshAsync({ functionName: 'REST.GET' }) // or one function +wb.refreshAsync({ key }) // or one call key +``` + +Success results are cached permanently (a precedent change produces a _new_ key, +so stale results are never read). **Error** results are negative-cached with a +cooldown (`asyncNegativeTtl`, default 30 s): past the cooldown the entry expires +and the next recalc refires it — errors are not cached forever, and are never +left to a silent third option. + +## Code Mode functions + +A Code Mode function is authored, tested against supplied examples, and +registered only after a human approves — the function body never registers +anything itself. + +```ts +import { + stageFunction, + approveAndRegister, +} from '@tanstack/spreadsheet-codemode' + +const staged = stageFunction(spec, [{ args: [100, 1120, 0], expected: 11.2 }]) +staged.passed // false unless ≥1 supplied example passes (empty examples cannot pass) +approveAndRegister(wb, staged) // throws unless staged.passed +``` + +- **Execution is a host-injected port** (`CodeExecutor`) — plug in a real + isolate (QuickJS, a worker). The default `unsafeInProcessExecutor` runs the + body in-process via `new Function` with I/O globals shadowed; it is a dev/test + fallback and **not a sandbox** — a production host injects a real isolate. +- A runtime **throw keeps its message** on the resulting error value's `detail` + (not a bare `#VALUE!`). The version identity is a collision-resistant 64-bit + hash, load-bearing for cache invalidation. +- A Code Mode function can declare a **range argument** (`acceptsRange`) and + receives it as a 2D grid, like a builtin. + +Code Mode functions persist as part of the one registry — `removeFunction` +drops them from the export, so a removed function stays removed through +export/rehydrate. diff --git a/docs/spreadsheet/store-guide.md b/docs/spreadsheet/store-guide.md new file mode 100644 index 0000000000..539126c8cc --- /dev/null +++ b/docs/spreadsheet/store-guide.md @@ -0,0 +1,68 @@ +--- +title: TanStack Store Interop +--- + +`@tanstack/spreadsheet-store` bridges a workbook and `@tanstack/store` in both +directions. Nothing here is a lookalike: facades are real store atoms, and +virtual sheets are first-class. + +## Spreadsheet → Store: facades + +A cell or region is exposed as a **real** `@tanstack/store` computed atom +(`ReadonlyAtom`), so it composes with other atoms and the framework store hooks. +Read views are genuinely read-only — the type tells the truth. + +```ts +import { + cellValueFacade, + rangeFacade, + writeCells, +} from '@tanstack/spreadsheet-store' + +const a1 = cellValueFacade(wb, { sheet: 's1', row: 0, col: 0 }) +a1.get() // the current value +const sub = a1.subscribe(() => render()) // recomputes on commit +sub.unsubscribe() + +rangeFacade(wb, 's1', { r0: 0, c0: 0, r1: 9, c1: 3 }).get() // dense 2D grid + +writeCells(wb, [{ ref, value: 42 }]) // the write path — one applyPatches +``` + +The facades track the workbook's `revision` atom, so they recompute on every +commit (coarser than `subscribeRegion`, which stays the per-region perf +primitive — these are the interop layer). Writes go through `writeCells`. + +## Store → Spreadsheet: virtual sheets + +Map a `Store` into a read-only virtual sheet a formula can reference by name. + +```ts +import { storeSheet } from '@tanstack/spreadsheet-store' + +const detach = storeSheet(wb, 'FX', fxStore, (s, row, col) => + row === 0 ? (col === 0 ? s.usd : s.eur) : null, +) +// =FX!A1 + FX!B1 recomputes when fxStore changes +detach() // unsubscribe + remove the virtual sheet +``` + +A store update that re-enters recalc (a cross-boundary cycle) is rejected by the +core; virtual sheets list alongside real sheets (`workbook.listSheets()`) and +read through `getCell` (see the [Workbook API](./workbook-api.md)). + +## Tier-1 staging + +Write endpoint data into a dedicated **source sheet** as inputs (never a +formula — an injection guard escapes incoming `=`), with provenance and the +staged extent recorded on the workbook. Re-staging a smaller block blanks the +previous extent's tail, so no ghost rows linger. + +```ts +import { stageData, provenanceOf } from '@tanstack/spreadsheet-store' + +stageData(wb, 'src', rows, { + provenance: { endpoint: '/api/x', fetchedAt: now }, +}) +provenanceOf(wb, 'src') // { endpoint, fetchedAt } +``` diff --git a/docs/spreadsheet/workbook-api.md b/docs/spreadsheet/workbook-api.md new file mode 100644 index 0000000000..ca5de97229 --- /dev/null +++ b/docs/spreadsheet/workbook-api.md @@ -0,0 +1,353 @@ +--- +title: Workbook API +--- + +# `Workbook` API — `@tanstack/spreadsheet-core` + +The `Workbook` is the whole model. It has **no UI, framework, or Table +dependency** (its only dependency is `@tanstack/store`), so it runs in Node, a +worker, or a serverless function and can be used as a standalone data engine. + +```ts +import { createWorkbook } from '@tanstack/spreadsheet-core' + +const wb = createWorkbook() +wb.addSheet('s1') +wb.applyPatches(wb.setInput({ sheet: 's1', row: 0, col: 0 }, '=SUM(A2:A5)')) +wb.getCell({ sheet: 's1', row: 0, col: 0 })?.value // computed value +wb.runFormula('AVERAGE(A2:A5)') // ad-hoc, no cell written +``` + +--- + +## Construction + +```ts +createWorkbook(opts?: WorkbookOptions) // documented entry point (delegates to `new Workbook`) + +interface WorkbookOptions { + functions?: FunctionRegistry // default: builtins() — the 37 built-in functions + packs?: FunctionPack[] // custom function packs registered into the registry + functionPorts?: FunctionPorts // host ports surfaced to every function via FnContext.ports + asyncPort?: AsyncPort // executes async requests (§3); without it, async cells stay pending + asyncBudget?: number // max async requests dispatched before pausing. default: unlimited + asyncCache?: AsyncCacheSeed[] // seed the async result cache on load (persistence) + clock?: Clock // default: system clock (NOW/TODAY). Inject for determinism. + rng?: Rng // default: Math.random (RAND). Seed in tests. + locale?: Locale // reserved (arg/decimal separators) + visibility?: VisibilityPort // optional; consulted by SUBTOTAL/AGGREGATE (101–111) +} +``` + +## Reactive atoms (from `@tanstack/store`) + +```ts +wb.atoms.revision: Atom // bumps once per settled commit +wb.atoms.sheets: Atom + +const sub = wb.atoms.revision.subscribe(() => { /* the graph just settled */ }) +sub.unsubscribe() +``` + +## Sheets + +```ts +wb.addSheet(id: SheetId): Sheet +wb.removeSheet(id: SheetId): boolean +wb.getSheet(id: SheetId): ReadonlySheet | undefined // read-only view of that sheet's cells +``` + +## Reading + +```ts +wb.getCell(ref: Ref): Cell | undefined +// Cell = { input: string; kind: 'literal' | 'formula'; ast?: Node; value: CellValue } +``` + +### Ad-hoc evaluation (headless / outside any cell) + +```ts +wb.runFormula(input: string, opts?: { sheet?: SheetId }): CellValue +``` + +Evaluates a formula against the workbook's current **settled** values. It does +**not** write a cell and does **not** create dependency edges. A leading `=` is +optional; unqualified references resolve against `opts.sheet` (default: first +sheet); cross-sheet refs (`Sheet2!A1`) always work. + +```ts +wb.runFormula('SUM(E1:E6)') +wb.runFormula('VLOOKUP("Gadgets", A1:F4, 5, FALSE)', { sheet: 's1' }) +wb.runFormula('1/0') // → { kind: 'error', code: '#DIV/0!' } (errors are values) +``` + +For advanced use, `wb.environment` exposes the evaluator `Environment` so you can +reuse a pre-parsed AST across many evaluations: + +```ts +import { parse, evaluate } from '@tanstack/spreadsheet-core' +const ast = parse('SUM(A1:A100)', { defaultSheet: 's1' }) +evaluate(ast, wb.environment) // re-run against fresh values, no re-parse +``` + +## Mutation & commit + +Mutation and commit are **separate**. `setInput` returns patches; it does not +apply them. Everything funnels through `applyPatches`, so undo/redo, +collaborative merges, and agent edits all get recalc for free. + +```ts +wb.setInput(ref: Ref, input: string): Patch[] // '' clears the cell; no-ops → [] +wb.applyPatches(patches: Patch[]): CommitResult +``` + +`applyPatches` runs the **full synchronous pipeline** — apply inputs → update the +dependency graph → gather the transitive dirty set → topo-sort (detecting +cycles) → evaluate → notify regions. When it returns, the graph is **settled**: + +```ts +interface CommitResult { + applied: Patch[] // patches actually applied (no-ops dropped) + recalculated: Ref[] // cells whose computed value may have changed (sheet-qualified) + cycles: Ref[][] // circular groups detected this commit (→ #CIRCULAR) +} +``` + +`recalculated` and `cycles` are full workbook-global `Ref`s — a single commit +can recalc cells across several sheets, so a bare `CellKey` (sheet-local) would +flatten them together. + +### Convenience surface (sugar) + +One-call writes compose `setInput` + `applyPatches`. They accept an A1 string +(`'B2'`, `'Sheet1!B2'`, `"'My Sheet'!B2"`) or a `Ref`; patches remain the power +surface for batching and undo. + +```ts +wb.set(ref: Ref | string, input: string): CommitResult +wb.setMany(edits: { ref: Ref | string; input: string }[]): CommitResult +``` + +The data-movement helpers are workbook **methods** (not free functions): + +```ts +wb.serializeRange(sheet, rect): string // TSV; throws on an unknown sheet +wb.copyRange(sheet, rect): Clipboard // captures origin for re-anchoring +wb.buildPastePatches(target, clip, into?): Patch[] +wb.buildFillPatches(sheet, source, target): Patch[] +``` + +### The error convention + +An **invalid operation** throws with a real message, so a caller (or an agent +reading tool-call feedback) gets insight: writing to a read-only virtual sheet, +serializing an unknown sheet, defining a colliding/cyclic name. An **empty or +missing cell is a value state**, not an error — `getCell` returns `undefined`. +Error _values_ in cells keep their messages reachable (`ErrorValue.detail`), and +distinct failure kinds get distinct codes (a parse failure is `#ERR!`, not a +`#N/A` costume). + +### Dependency graph queries + +The real dependency graph is queryable — nothing outside core needs to re-parse +formulas to walk precedents/dependents: + +```ts +wb.precedentsOf(ref): { cells: Ref[]; ranges: { sheet; rect }[] } +wb.dependentsOf(ref): Ref[] // formulas reading ref, via scalar or range edges +``` + +### Merges + +Merge state is **workbook-owned** — one source of truth that every view and the +exporter read: + +```ts +wb.mergeCells(sheet, rect): CommitResult // replaces overlapping merges +wb.unmergeCells(sheet, rect): CommitResult // clears intersecting merges +wb.getMerges(sheet): Rect[] // a copy, never the live array +wb.getMergeAt(sheet, row, col): Rect | undefined +``` + +### Undo / redo + +Patches carry input strings only (never computed values), so inversion is exact: + +```ts +import { invertPatches } from '@tanstack/spreadsheet-core' +const cmd = wb.setInput(ref, '=A1+1') +wb.applyPatches(cmd) // do +wb.applyPatches(invertPatches(cmd)) // undo +wb.applyPatches(cmd) // redo +``` + +## Region subscriptions (the virtualization primitive) + +Pull model: the callback fires once per commit when a change lands inside the +rectangle; re-read via `getCell`. A grid observes only its ~2k visible cells. + +```ts +const off = wb.subscribeRegion(sheet: SheetId, rect: Rect, cb: () => void): () => void +// rect = { r0, c0, r1, c1 } (inclusive, 0-based) +off() // unsubscribe +``` + +--- + +## Function registry + +The workbook carries a `FunctionRegistry` (the builtins by default). Packs are +namespaced sets of functions; registering a pack whose name collides with an +existing function throws a `FunctionCollisionError`. + +```ts +wb.registerPack(pack: FunctionPack): this // register a pack (chainable) +wb.functionCatalog(): FunctionCatalogEntry[] // machine-readable catalog (builtins + packs) +wb.functionManifest(): PackManifestEntry[] // { name, version } per pack (portability) +wb.validateFormula(input: string, opts?: { sheet?: SheetId }): FormulaValidation +``` + +`validateFormula` parses and checks a formula against the registry **without** +committing it — reporting parse errors, unknown functions, and bad argument +counts. It powers formula-bar linting and agent checks; a leading `=` is +optional. + +```ts +interface FormulaValidation { + ok: boolean + diagnostics: FunctionDiagnostic[] + parseError?: string // set when the formula could not be parsed (diagnostics empty) +} +``` + +## Workbook-defined functions + +Register or replace a single custom function — e.g. a Code Mode function. A +version bump re-evaluates every call site, so replacing a definition +invalidates the cells that use it correctly. + +```ts +wb.upsertFunction(def: FunctionDef): CommitResult // register/replace; recalcs call sites +wb.removeFunction(name: string): CommitResult // remove; call sites re-evaluate to #NAME? +``` + +## Async cell equations + +An async function returns a `pending` value until its result arrives, and +pending propagates through dependents (`isBlocking`). Supply an `asyncPort` at +construction to execute requests. + +```ts +wb.settle(): Promise // resolve once no async requests remain in flight +wb.asyncStats(): SchedulerStats // cache size, in-flight, dispatched, batches, paused +wb.exportAsyncCache(): AsyncCacheSeed[] // persist the result cache (value + timestamp per call key) +``` + +```ts +// async formula → cell is pending → await settle() → resolved value +const ref = { sheet: 's1', row: 0, col: 0 } +wb.applyPatches(wb.setInput(ref, '=REST.GET("https://example.com/n")')) +wb.getCell(ref)?.value // → { kind: 'pending' } +await wb.settle() +wb.getCell(ref)?.value // → the resolved value +``` + +## Display formats + +A display number-format code attached to a cell. Purely descriptive — the +engine ignores it; adapters render with it via `formatValue`. It is independent +of the cell value, so it survives input edits. + +```ts +wb.setFormat(ref: Ref, code: string | undefined): void // pass undefined to clear +wb.getFormat(ref: Ref): string | undefined +``` + +## Virtual sheets + +Register a read-only external sheet (e.g. backed by a Store). Formulas +reference it by name (`ExtSheet!A1`) and the workbook treats its cells as +precedents. The id must not collide with a real sheet. + +```ts +wb.addVirtualSheet(id: SheetId, provider: SheetProvider): void +wb.removeVirtualSheet(id: SheetId): boolean +wb.hasVirtualSheet(id: SheetId): boolean +wb.recalcVirtual(sheet: SheetId, cells?: { row: number; col: number }[]): CommitResult +``` + +A virtual sheet is a **first-class citizen**, not evaluator-only: it lists +alongside real sheets (flagged) and reads through `getCell`. + +```ts +wb.listSheets(): { id: SheetId; kind: 'real' | 'virtual'; readOnly: boolean }[] +wb.getCell({ sheet: 'ExtSheet', row, col }) // synthesized read-only cell view +``` + +Writing to a virtual sheet (`setInput`/`set`) **throws** — it is read-only. +`recalcVirtual` signals that virtual cells changed and recalcs their dependents +(omit `cells` to invalidate every formula that reads the sheet); it **throws** +if called re-entrantly from within a recalc — a cross-boundary cycle. + +## Sheet provenance & Tier-1 staging + +Where a sheet's data came from is workbook state, not a module sidecar: + +```ts +wb.setSheetProvenance(sheet, { endpoint, fetchedAt, ... } | undefined): void +wb.sheetProvenance(sheet): SheetProvenance | undefined +wb.getStagedExtent(sheet): Rect | undefined +wb.setStagedExtent(sheet, rect | undefined): void +``` + +`@tanstack/spreadsheet-store`'s `stageData` uses these: it records provenance +and the staged extent on the workbook, and blanks the previous extent's tail +when a re-stage writes a smaller block (no ghost rows). + +--- + +## Core types + +```ts +type SheetId = string +interface Ref { + sheet: SheetId + row: number + col: number +} // 0-based +interface Rect { + r0: number + c0: number + r1: number + c1: number +} // inclusive +type CellKey = number // packed row*16384+col (sheet-local); see addr.ts +type CellValue = number | string | boolean | ErrorValue | PendingValue | null +interface ErrorValue { + kind: 'error' + code: ErrorCode +} +interface PendingValue { + kind: 'pending' +} // a not-yet-arrived async value; propagates through dependents +// ErrorCode: '#DIV/0!' | '#VALUE!' | '#REF!' | '#NAME?' | '#N/A' | '#NUM!' | '#NULL!' | '#CIRCULAR' +``` + +> **Exhaustiveness:** `PendingValue` has been a first-class `CellValue` since +> A `switch` over `CellValue` must handle the `{ kind: 'pending' }` case +> (use `isPending` / `isBlocking`). + +## Related exports (all framework-free) + +- **Parser:** `parse`, `tokenize`, `refsOf`, `serialize`, `ParseError` +- **Evaluator:** `evaluate`, `err`, `isErr`, `pending`, `isPending`, + `isBlocking`, `toNum`, `toStr`, `toBool`, `looseCompare` +- **Addressing:** `pack`, `rowOf`, `colOf`, `colToLetter`, `letterToCol`, + `parseA1`, `formatA1`, `translate`, `makeRect`, `rectContains`, … +- **Fill / clipboard:** `translateFormula`, `buildFillPatches`, `copyRange`, + `serializeRange`, `parseTsv`, `buildPastePatches` +- **Ports / functions:** `FunctionRegistry`, `FunctionCollisionError`, + `builtins`, `validateCalls`, `systemClock`, `mathRng` +- **Async:** `Scheduler` +- **Formats:** `formatValue`, `isDateFormat` +- **Graph:** `DepGraph`, `nodeId`, `decodeNode` diff --git a/docs/spreadsheet/xlsx-fidelity.md b/docs/spreadsheet/xlsx-fidelity.md new file mode 100644 index 0000000000..781525a8ae --- /dev/null +++ b/docs/spreadsheet/xlsx-fidelity.md @@ -0,0 +1,79 @@ +--- +title: XLSX Fidelity +--- + +`@tanstack/spreadsheet-xlsx` imports and exports `.xlsx`. Import stops losing +things silently: what travels travels, what drops is reported, and a degraded +cell is addressable so a UI can highlight it. + +```ts +import { importXlsx, exportXlsx } from '@tanstack/spreadsheet-xlsx' + +const { workbook, sheetNames, issues, summary } = importXlsx(bytes) +const out = exportXlsx(workbook) +``` + +## What travels + +- **Values and formulas** — supported formulas import live; shared formulas are + re-anchored per cell. +- **Number formats** — per-cell number-format codes round-trip. +- **Merges** — `` ranges import into the workbook's merge state and + export back (they are core state now, not an adapter copy). +- **Defined names** — workbook- and sheet-scoped (`localSheetId`) names import as + workbook defined names and export back; a formula referencing a name stays + live after import. + +A workbook with merges and defined names round-trips through export → import +intact. + +## The `ImportResult` + +```ts +interface ImportResult { + workbook: Workbook + sheetNames: string[] + issues: Issue[] // cell-by-cell + workbook-level problems + summary: { cells: number; issues: number; byKind: Record } +} +``` + +Each `Issue` (the shared core type, also used by the agent `verify` surface) +carries a machine-readable `kind`, a human `message`, the affected cell (`ref`, +A1-addressable) where cell-scoped, and the `original` content where relevant — +enough to paint the degraded cells red and say why. + +| Issue kind | Raised when | +| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | +| `unsupported-formula` | A formula uses a function the engine doesn't have — its **last cached value** is kept, and the original formula text is on `original`. | +| `unknown-number-format` | A cell references a number-format id we don't recognise. | +| `dropped-feature` | A present-but-unsupported feature (see below), including array formulas (kept as their cached value) and un-importable defined names. | + +## The cached-value fallback + +An unsupported formula is not dropped — the cell keeps the **cached value** the +file carried, so the number a customer saw in Excel survives, and the loss is +reported as an `unsupported-formula` issue rather than hidden. Export writes +``, so Excel recalculates on open: a cell exported +without a cached value (e.g. a still-pending async cell) shows a real number, +never a bare formula displayed as `0`. + +## What drops + +The drop list is a single shared source (`DROPPED_FEATURES`), referenced by both +import and export so they cannot disagree. Import **detects and reports** the +cell-addressable ones it finds; the rest are documented: + +- fonts, fills, and borders; column widths and row heights +- data validations; conditional formatting +- array formulas (imported as their cached value) +- charts and drawings; pivot tables; table (list) ranges + +## Other fidelity fixes + +- **1904 date system** — import honours the `date1904` workbook flag: a + date-formatted serial is shifted by 1462 days into the engine's 1900 system, + so a 1904-file's dates land on the right day (no silent ~4-year drift). +- **Atomic import** — sheet names are validated up front; a duplicate or + colliding name throws **before any sheet is added**, so a bad file never + leaves a half-imported workbook. diff --git a/examples/react/spreadsheet-demo/.env.example b/examples/react/spreadsheet-demo/.env.example new file mode 100644 index 0000000000..311432f9e4 --- /dev/null +++ b/examples/react/spreadsheet-demo/.env.example @@ -0,0 +1,4 @@ +# Only the /agent route needs this. The key is read server-side by the +# /api/agent route (via @tanstack/ai-anthropic) and never reaches the browser. +# Copy this file to .env.local and fill in your key. +ANTHROPIC_API_KEY= diff --git a/examples/react/spreadsheet-demo/.gitignore b/examples/react/spreadsheet-demo/.gitignore new file mode 100644 index 0000000000..8d112a69b1 --- /dev/null +++ b/examples/react/spreadsheet-demo/.gitignore @@ -0,0 +1,10 @@ +# TanStack Start build output +dist/ +.output/ +.nitro/ +.tanstack/ + +# Local environment files (never commit real keys; see .env.example) +.env +.env.local +.env.*.local diff --git a/examples/react/spreadsheet-demo/README.md b/examples/react/spreadsheet-demo/README.md new file mode 100644 index 0000000000..1d7f796118 --- /dev/null +++ b/examples/react/spreadsheet-demo/README.md @@ -0,0 +1,45 @@ +# Spreadsheet demo + +A [TanStack Start](https://tanstack.com/start) app that exercises the headless +spreadsheet engine across one route per capability, all bound to live workbooks. + +## Routes + +| Route | Demonstrates | +| --------------------- | ---------------------------------------------------------------------------------------- | +| `/` | Landing page and index of the routes below. | +| `/simple-spreadsheet` | The live grid on the TanStack Table v9 adapter (selection, fill, formulas, xlsx I/O). | +| `/state-manager` | A plain form whose inputs/outputs are workbook cells — the spreadsheet as app state. | +| `/functions` | The function registry and pluggable function packs (toggling a pack rebuilds the sheet). | +| `/async` | Asynchronous cell equations: a `pending` value resolved through the scheduler. | +| `/agent` | A live TanStack AI Code Mode agent that builds a sheet and authors a Code Mode function. | +| `/budget` | The "Fluid Budget" capstone — guardrails-as-formulas, async classification, runway. | + +## Running + +From the repository root (build the workspace packages first if you have not): + +```bash +pnpm install +pnpm --filter tanstack-react-table-example-spreadsheet-demo dev +``` + +## `ANTHROPIC_API_KEY` (the `/agent` route) + +Only `/agent` calls a live LLM. It needs an `ANTHROPIC_API_KEY`: + +```bash +cp .env.example .env.local # in this directory +# then edit .env.local and set ANTHROPIC_API_KEY=... +``` + +The key is read **server-side** by the `/api/agent` route (via +`@tanstack/ai-anthropic`) and never reaches the browser. The browser runs the +agent loop and executes the generated orchestration TypeScript locally in a +QuickJS WASM isolate. Every other route works without any key. + +> [!WARNING] +> `/api/agent` is an **unauthenticated** proxy to the server's Anthropic key with +> no rate limiting — it's built for local development. Do not deploy this example +> publicly as-is; anyone who can reach the route can spend your key. Add +> authentication and rate limiting before hosting it anywhere. diff --git a/examples/react/spreadsheet-demo/package.json b/examples/react/spreadsheet-demo/package.json new file mode 100644 index 0000000000..eff8edb7d3 --- /dev/null +++ b/examples/react/spreadsheet-demo/package.json @@ -0,0 +1,50 @@ +{ + "name": "tanstack-react-table-example-spreadsheet-demo", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite dev", + "build": "vite build", + "preview": "vite preview", + "lint": "eslint ./src", + "test:types": "tsc", + "test:lib": "vitest run" + }, + "dependencies": { + "@tanstack/ai": "^1.1.0", + "@tanstack/ai-anthropic": "^1.1.0", + "@tanstack/ai-client": "^1.1.0", + "@tanstack/ai-code-mode": "^1.1.0", + "@tanstack/ai-isolate-quickjs": "^1.1.0", + "@tanstack/ai-react": "^1.0.2", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-spreadsheet": "workspace:*", + "@tanstack/react-start": "^1.169.5", + "@tanstack/spreadsheet-agent": "workspace:*", + "@tanstack/spreadsheet-codemode": "workspace:*", + "@tanstack/spreadsheet-core": "workspace:*", + "@tanstack/spreadsheet-packs": "workspace:*", + "@tanstack/spreadsheet-store": "workspace:*", + "@tanstack/spreadsheet-table": "workspace:*", + "@tanstack/spreadsheet-xlsx": "workspace:*", + "@tanstack/table-core": "workspace:*", + "fflate": "^0.8.3", + "quickjs-emscripten": "^0.32.0", + "react": "^19.3.1", + "react-dom": "^19.3.1", + "react-markdown": "^10.1.0", + "remark-gfm": "^4.0.1", + "zod": "^4.6.7" + }, + "devDependencies": { + "@rolldown/plugin-babel": "^0.3.1", + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "@vitejs/plugin-react": "^6.3.0", + "babel-plugin-react-compiler": "^1.0.0", + "typescript": "6.0.3", + "vite": "^8.3.8", + "vitest": "^5.1.0" + } +} diff --git a/examples/react/spreadsheet-demo/src/agent/model.ts b/examples/react/spreadsheet-demo/src/agent/model.ts new file mode 100644 index 0000000000..efb268d85c --- /dev/null +++ b/examples/react/spreadsheet-demo/src/agent/model.ts @@ -0,0 +1,114 @@ +/** + * M15 — the `/agent` demo (Extension Spec v0.3 §12), live TanStack AI Code Mode. + * + * Shared constants for the agent's workbook tools + the deterministic test. The + * *live* agent builds the sheet itself (see `routes/api.agent.ts` system prompt); + * these constants fix the layout the prompt asks for, so the KPIs, the verify + * checks, and the runway formula know where to look. + */ + +import { createWorkbook } from '@tanstack/spreadsheet-core' +import type { CellValue, Ref, Workbook } from '@tanstack/spreadsheet-core' +import type { CodeFunctionSpec, Example } from '@tanstack/spreadsheet-codemode' + +export const AGENT_SHEET = 's1' +export const ref = (row: number, col: number): Ref => ({ + sheet: AGENT_SHEET, + row, + col, +}) + +/** The grid the UI renders (the tracker + runway block fit inside). */ +export const AGENT_ROWS = 13 +export const AGENT_COLS = 6 + +/** The category anchors/actuals the prompt asks the agent to enter (all land green). */ +export const CATS = [ + { name: 'Cloud', anchor: 20, actual: 21 }, + { name: 'Software', anchor: 8, actual: 8 }, + { name: 'Contractors', anchor: 30, actual: 28 }, + { name: 'Travel', anchor: 5, actual: 4 }, + { name: 'Marketing', anchor: 12, actual: 10 }, +] +export const ANCHOR_TOTAL = CATS.reduce((s, c) => s + c.anchor, 0) // 75 + +// Fixed layout the system prompt enforces (0-based rows). +const FIRST_CAT_ROW = 1 +const TOTAL_ROW = 6 // A1 row 7 +const CASH_ROW = 8 // A1 row 9 +const BURN_ROW = 9 // A1 row 10 +const ONEOFF_ROW = 10 // A1 row 11 +const BUILTIN_RUNWAY_ROW = 11 // A1 row 12 +export const TRUE_RUNWAY_ROW = 12 // A1 row 13 + +/** Cell refs the UI reads back / patches. */ +export const CELLS = { + firstAnchor: ref(FIRST_CAT_ROW, 1), // B2 + anchorTotal: ref(TOTAL_ROW, 1), // B7 + builtinRunway: ref(BUILTIN_RUNWAY_ROW, 1), // B12 + trueRunway: ref(TRUE_RUNWAY_ROW, 1), // B13 + trueRunwayLabel: ref(TRUE_RUNWAY_ROW, 0), // A13 +} + +/** Act-1 self-verification checks (run through `buildAndVerify`, which also scans errors). */ +export function agentChecks( + wb: Workbook, +): Array<{ label: string; ok: boolean }> { + const anchorTotal = wb.getCell(CELLS.anchorTotal)?.value + const builtin = wb.getCell(CELLS.builtinRunway)?.value + const statuses = CATS.map( + (_, i) => wb.getCell(ref(FIRST_CAT_ROW + i, 5))?.value, + ) + const allStatuses = statuses.every( + (s) => s === 'OK' || s === 'OVER' || s === 'UNDER', + ) + return [ + { + label: `Anchor total ties out (= ${ANCHOR_TOTAL})`, + ok: anchorTotal === ANCHOR_TOTAL, + }, + { label: 'Every category has an OK/OVER/UNDER status', ok: allStatuses }, + { label: 'Built-in runway computes (= 11.2)', ok: builtin === 11.2 }, + ] +} + +// --- Act 2: the Code Mode function the agent authors ----------------------------- + +/** The CFO's definition: runway excluding one-off hardware spikes from burn. */ +export const TRUE_RUNWAY_SPEC: CodeFunctionSpec = { + name: 'FN.TRUE_RUNWAY', + args: [{ name: 'burn' }, { name: 'cash' }, { name: 'oneOff' }], + returns: 'number', + description: + 'Months of runway, excluding a one-off hardware spike from burn.', + source: 'return Math.round((cash / (burn - oneOff)) * 10) / 10', +} + +/** Supplied examples — registration is blocked until all of these pass. */ +export const TRUE_RUNWAY_EXAMPLES: Array = [ + { args: [100, 1120, 0], expected: 11.2 }, + { args: [120, 1500, 20], expected: 15 }, +] + +/** The formula wired into the runway cell after approval (burn B10, cash B9, oneOff B11). */ +export const RUNWAY_FORMULA = '=FN.TRUE_RUNWAY(B10,B9,B11)' + +/** A fresh, empty workbook with the sheet added. Pure — SSR-safe. */ +export function freshWorkbook(): Workbook { + const wb = createWorkbook() + wb.addSheet(AGENT_SHEET) + return wb +} + +/** 'B12' → { sheet, row, col } (0-based row/col). Used by the set_cells tool. */ +export function a1ToRef(a1: string): Ref { + const m = /^([A-Za-z]+)(\d+)$/.exec(a1.trim()) + if (!m) throw new Error(`Bad A1 reference: ${a1}`) + const letters = m[1].toUpperCase() + let col = 0 + for (const ch of letters) col = col * 26 + (ch.charCodeAt(0) - 64) + return ref(Number(m[2]) - 1, col - 1) +} + +export const cellValue = (wb: Workbook, r: Ref): CellValue => + wb.getCell(r)?.value ?? null diff --git a/examples/react/spreadsheet-demo/src/agent/tools.ts b/examples/react/spreadsheet-demo/src/agent/tools.ts new file mode 100644 index 0000000000..7a37852ccf --- /dev/null +++ b/examples/react/spreadsheet-demo/src/agent/tools.ts @@ -0,0 +1,206 @@ +/** + * The agent's workbook tools + client-side Code Mode wiring (§12, live). + * + * `createAgentCodeMode(wb, handlers)` builds a QuickJS **WASM** isolate in the + * browser and exposes four tools to the model's generated TypeScript as + * `external_*` functions. The tools are plain async closures over the live + * client `Workbook`, so when the model's code runs it mutates the real sheet and + * the grid re-renders. The returned `execute_typescript` is a **client tool** for + * `useChat` — only the LLM completion crosses to the server. + */ + +import { toolDefinition } from '@tanstack/ai' +import { z } from 'zod' +import { createCodeMode } from '@tanstack/ai-code-mode' +import { stageFunction } from '@tanstack/spreadsheet-codemode' +import { + readSheet as readSheetImpl, + setCells as setCellsImpl, + verify as verifyImpl, +} from '@tanstack/spreadsheet-agent' +import { formatValue } from '@tanstack/spreadsheet-core' +import { + AGENT_SHEET, + TRUE_RUNWAY_EXAMPLES, + TRUE_RUNWAY_SPEC, + agentChecks, +} from './model' +import type { Workbook } from '@tanstack/spreadsheet-core' +import type { StagedFunction } from '@tanstack/spreadsheet-codemode' + +export type AgentEvent = + | { kind: 'code'; code: string } + | { kind: 'tool'; name: string; summary: string } + | { kind: 'staged'; staged: StagedFunction } + +export interface AgentHandlers { + onEvent: (event: AgentEvent) => void +} + +/** + * Build the workbook tools (as Code Mode `ServerTool`s) over a live workbook. + * The tool bodies dogfood the packaged `@tanstack/spreadsheet-agent` surface — + * `setCells` / `readSheet` / `verify` — rather than re-implementing workbook + * access here. + */ +function workbookTools(wb: Workbook, { onEvent }: AgentHandlers) { + const setCells = toolDefinition({ + name: 'set_cells', + description: + 'Write raw values or formulas into cells. Each cell is { a1, input } where input is a literal ("20") or a formula starting with "=". Returns the resulting values.', + inputSchema: z.object({ + cells: z + .array(z.object({ a1: z.string(), input: z.string() })) + .describe( + 'Cells to write, e.g. [{ a1: "A1", input: "Category" }, { a1: "D2", input: "=B2*0.8" }]', + ), + }), + outputSchema: z.object({ + cells: z.array(z.object({ a1: z.string(), value: z.string() })), + }), + }).server(async ({ cells }) => { + // One batched transaction through the packaged tool (no display side effect; + // the Phase-4 formatter owns display now). + const written = setCellsImpl(wb, cells, AGENT_SHEET) + onEvent({ + kind: 'tool', + name: 'set_cells', + summary: `wrote ${cells.length} cell(s)`, + }) + return { + cells: written.map((c) => ({ a1: c.a1, value: formatValue(c.value) })), + } + }) + + const readSheet = toolDefinition({ + name: 'read_sheet', + description: + 'Read the populated cells of the sheet: their A1 address, input (formula or literal), computed value, and kind (formula | literal).', + inputSchema: z.object({}), + outputSchema: z.object({ + cells: z.array( + z.object({ + a1: z.string(), + input: z.string(), + value: z.string(), + kind: z.string(), + }), + ), + }), + }).server(async () => { + const cells = readSheetImpl(wb, AGENT_SHEET).map((c) => ({ + a1: c.a1, + input: c.input, + value: formatValue(c.value), + kind: c.kind === 'formula' ? 'formula' : 'literal', + })) + onEvent({ + kind: 'tool', + name: 'read_sheet', + summary: `${cells.length} populated cell(s)`, + }) + return { cells } + }) + + const authorRunway = toolDefinition({ + name: 'author_runway_function', + description: + 'Author FN.TRUE_RUNWAY as a Code Mode function. Provide the JS function BODY (params are burn, cash, oneOff; must `return` a number). It is compiled and TESTED against the supplied examples but NOT registered — a human approves registration in the UI. Returns { passed, version, results }.', + inputSchema: z.object({ + source: z + .string() + .describe( + 'Function body, e.g. "return Math.round((cash / (burn - oneOff)) * 10) / 10"', + ), + }), + outputSchema: z.object({ + passed: z.boolean(), + version: z.string(), + results: z.array( + z.object({ + args: z.array(z.number()), + expected: z.number(), + actual: z.string(), + pass: z.boolean(), + }), + ), + }), + }).server(async ({ source }) => { + const staged = stageFunction( + { ...TRUE_RUNWAY_SPEC, source }, + TRUE_RUNWAY_EXAMPLES, + ) + onEvent({ kind: 'staged', staged }) + return { + passed: staged.passed, + version: staged.compiled.version, + results: staged.results.map((r) => ({ + args: r.args as Array, + expected: r.expected as number, + actual: String(r.actual), + pass: r.pass, + })), + } + }) + + const verify = toolDefinition({ + name: 'verify', + description: + 'Self-verify the built sheet: settles async work, runs the budget checks, and scans for error cells. Returns { ok, checks, errors }.', + inputSchema: z.object({}), + outputSchema: z.object({ + ok: z.boolean(), + checks: z.array(z.object({ label: z.string(), ok: z.boolean() })), + errorCount: z.number(), + }), + }).server(async () => { + // The caller sequences build + settle, then the pure `verify` returns Issues. + await wb.settle() + const checks = agentChecks(wb) + const issues = verifyImpl(wb, { sheet: AGENT_SHEET, checks }) + onEvent({ + kind: 'tool', + name: 'verify', + summary: issues.length === 0 ? 'all checks passed' : 'checks failed', + }) + return { + ok: issues.length === 0, + checks, + errorCount: issues.filter((i) => i.ref !== undefined).length, + } + }) + + return [setCells, readSheet, authorRunway, verify] +} + +/** + * Build the browser QuickJS-WASM Code Mode and return the `execute_typescript` + * CLIENT tool + the generated system prompt (forward it to the server so the LLM + * knows the available `external_*` functions). Dynamic-imports the WASM isolate + * so it never loads during SSR. + */ +export async function createAgentCodeMode( + wb: Workbook, + handlers: AgentHandlers, +) { + const { createQuickJSIsolateDriver } = + await import('@tanstack/ai-isolate-quickjs') + const cm = createCodeMode({ + driver: createQuickJSIsolateDriver(), + tools: workbookTools(wb, handlers), + timeout: 60000, + memoryLimit: 128, + }) + + const executeTypescript = toolDefinition({ + name: 'execute_typescript', + description: + 'Run TypeScript in a sandbox. Call the external_* functions to build and inspect the sheet. Use `return` to pass a result back.', + inputSchema: z.object({ typescriptCode: z.string() }), + }).client(async (input: { typescriptCode: string }) => { + handlers.onEvent({ kind: 'code', code: input.typescriptCode }) + return cm.tool.execute!(input) + }) + + return { executeTypescript, codeModeSystemPrompt: cm.systemPrompt } +} diff --git a/examples/react/spreadsheet-demo/src/budget/model.ts b/examples/react/spreadsheet-demo/src/budget/model.ts new file mode 100644 index 0000000000..290d0b0ddd --- /dev/null +++ b/examples/react/spreadsheet-demo/src/budget/model.ts @@ -0,0 +1,243 @@ +/** + * The Fluid Budget model (Extension Spec §8.1) — a deterministic budgeting + * workbook that ties out. An anchor budget per category, ±20% guardrail bands as + * *formulas*, actuals summed from an async-classified transactions feed, and a + * runway driven by a Code Mode `FN.TRUE_RUNWAY` function. + * + * Everything is pure + seeded so the verification script (`verify.ts`) can assert + * exact numbers. The decision model runs in-page here (a deterministic mock) — + * the `/async` route shows the server-function variant. + */ + +import { createWorkbook } from '@tanstack/spreadsheet-core' +import { decisionPack, decisionPort } from '@tanstack/spreadsheet-packs' +import { + compileCodeFunction, + registerCompiled, +} from '@tanstack/spreadsheet-codemode' +import type { Ref, Workbook } from '@tanstack/spreadsheet-core' +import type { DecisionRule } from '@tanstack/spreadsheet-packs' + +export const BUDGET = 'budget' +export const TXN = 'txn' +export const MODEL = 'model' + +export const CATEGORIES = 'Cloud,Software,Contractors,Travel,Marketing' +export const CONFIDENCE_THRESHOLD = 0.6 + +const RULES: Array = [ + { + match: /aws|cloud|gcp|azure|render|vercel/i, + choice: 'Cloud', + confidence: 0.97, + }, + { + match: /figma|notion|slack|github|subscription|saas/i, + choice: 'Software', + confidence: 0.93, + }, + { + match: /contractor|invoice|consult|design/i, + choice: 'Contractors', + confidence: 0.88, + }, + { + match: /uber|flight|hotel|travel|lyft/i, + choice: 'Travel', + confidence: 0.9, + }, + { match: /ads?|marketing|campaign/i, choice: 'Marketing', confidence: 0.84 }, +] + +export const budgetModel = { + id: 'mock-jev', + version: '2026.11', + decide(value: unknown, labels: Array) { + const text = String(value ?? '') + const hit = RULES.find((r) => r.match.test(text)) + if (hit && labels.includes(hit.choice)) + return { choice: hit.choice, confidence: hit.confidence } + return { choice: 'Uncategorized', confidence: 0.42 } + }, + probability(value: unknown) { + const text = String(value ?? '') + return RULES.find((r) => r.match.test(text))?.confidence ?? 0.42 + }, + bool(value: unknown) { + return this.probability(value) >= 0.5 + }, +} + +export interface Txn { + desc: string + amount: number +} + +/** The scripted feed. Amounts in $k. Two rows are deliberately low-confidence. */ +export const SEED_TXNS: Array = [ + { desc: 'AWS cloud bill — November', amount: 18 }, + { desc: 'GCP data egress', amount: 3 }, + { desc: 'Figma annual subscription', amount: 7 }, + { desc: 'Slack + Notion renewal', amount: 1 }, + { desc: 'Contractor invoice — Rivera Design', amount: 28 }, + { desc: 'Google Ads campaign', amount: 10 }, + { desc: 'Uber to the airport', amount: 4 }, + { desc: 'Mystery charge 4821', amount: 3 }, // → Uncategorized, REVIEW + { desc: 'Unlabeled wire 7781', amount: 2 }, // → Uncategorized, REVIEW +] + +const CATS = [ + { name: 'Cloud', anchor: 20 }, + { name: 'Software', anchor: 8 }, + { name: 'Contractors', anchor: 30 }, + { name: 'Travel', anchor: 5 }, + { name: 'Marketing', anchor: 12 }, +] +export const CATEGORY_NAMES = CATS.map((c) => c.name) + +// --- Model-sheet cell map (row indices) ------------------------------------ +export const MODEL_CELLS = { + cash: 0, + payroll: 1, + categorized: 2, + uncategorized: 3, + burn: 4, + oneOff: 5, + builtinRunway: 6, + trueRunway: 7, + /** Approvals-enabled gate — TRUE iff every guardrail is green. */ + gate: 8, +} as const + +export const ref = (sheet: string, row: number, col: number): Ref => ({ + sheet, + row, + col, +}) +const r1 = (row: number) => row + 1 // 0-based row → A1 row number + +export interface BuildOptions { + /** Simulated classification latency (ms) for the UI; 0 for headless tests. */ + latency?: number +} + +/** The `FN.TRUE_RUNWAY` spec — exactly what `/code-functions` authors. */ +export const TRUE_RUNWAY_SPEC = { + name: 'FN.TRUE_RUNWAY', + args: [{ name: 'cash' }, { name: 'burn' }, { name: 'oneOff' }], + returns: 'number' as const, + description: 'Runway months: cash ÷ (burn + pulled-forward one-off spend).', + source: 'return Math.round((cash / (burn + oneOff)) * 10) / 10', +} + +/** + * Build the full budget workbook. Transactions are seeded as inputs; their + * classification columns are async (fill pending → resolved on `settle()`). + */ +export function buildBudgetWorkbook(opts: BuildOptions = {}): Workbook { + const wb = createWorkbook({ + packs: [decisionPack(budgetModel)], + asyncPort: decisionPort(budgetModel, { latency: opts.latency ?? 0 }), + }) + wb.addSheet(BUDGET) + wb.addSheet(TXN) + wb.addSheet(MODEL) + registerCompiled(wb, compileCodeFunction(TRUE_RUNWAY_SPEC)) + + const P = [] as Array[number]> + const set = (sheet: string, row: number, col: number, input: string) => + P.push(...wb.setInput(ref(sheet, row, col), input)) + + // --- Transactions: description + amount inputs, async classification ------- + const headers = ['Description', 'Category', 'Confidence', 'Status', 'Amount'] + headers.forEach((h, c) => set(TXN, 0, c, h)) + const n = SEED_TXNS.length + SEED_TXNS.forEach((t, i) => { + const row = i + 1 + const a = r1(row) + set(TXN, row, 0, t.desc) + set(TXN, row, 1, `=JEV.CHOICE(A${a},"${CATEGORIES}")`) + set(TXN, row, 2, `=JEV.CONFIDENCE(A${a},"${CATEGORIES}")`) + set(TXN, row, 3, `=IF(C${a}<${CONFIDENCE_THRESHOLD},"REVIEW",B${a})`) + set(TXN, row, 4, String(t.amount)) + }) + const catRange = `$B$2:$B$${n + 1}` + const amtRange = `$E$2:$E$${n + 1}` + + // --- Budget: anchors, actuals (SUMIF over classified txns), guardrails ----- + ;['Category', 'Anchor', 'Actual', 'Lower', 'Upper', 'Status'].forEach( + (h, c) => set(BUDGET, 0, c, h), + ) + CATS.forEach((cat, i) => { + const row = i + 1 + const a = r1(row) + set(BUDGET, row, 0, cat.name) + set(BUDGET, row, 1, String(cat.anchor)) + set(BUDGET, row, 2, `=SUMIF(${TXN}!${catRange}, A${a}, ${TXN}!${amtRange})`) + set(BUDGET, row, 3, `=B${a}*0.8`) + set(BUDGET, row, 4, `=B${a}*1.2`) + set(BUDGET, row, 5, `=IF(C${a}>E${a},"OVER",IF(C${a} { + set(MODEL, row, 0, label) + set(MODEL, row, 1, b) + } + mset(M.cash, 'Cash on hand', '1120') + mset(M.payroll, 'Payroll', '24') + mset( + M.categorized, + 'Categorized spend', + `=SUM(${BUDGET}!C2:C${CATS.length + 1})`, + ) + mset( + M.uncategorized, + 'Uncategorized', + `=SUMIF(${TXN}!${catRange},"Uncategorized",${TXN}!${amtRange})`, + ) + mset( + M.burn, + 'Monthly burn', + `=B${r1(M.payroll)}+B${r1(M.categorized)}+B${r1(M.uncategorized)}`, + ) + mset(M.oneOff, 'Pulled-forward one-off', '0') + mset( + M.builtinRunway, + 'Built-in runway', + `=ROUND(B${r1(M.cash)}/B${r1(M.burn)},1)`, + ) + mset( + M.trueRunway, + 'True runway', + `=FN.TRUE_RUNWAY(B${r1(M.cash)},B${r1(M.burn)},B${r1(M.oneOff)})`, + ) + // The approval gate IS a cell: TRUE only when every guardrail is green. + mset( + M.gate, + 'Approvals enabled', + `=COUNTIF(${BUDGET}!F2:F${CATS.length + 1},"OK")=${CATS.length}`, + ) + + wb.applyPatches(P) + + // Display the numeric budget columns (B Anchor, C Actual, D Lower, E Upper) + // as fixed one-decimal — otherwise `*0.8` / `*1.2` leak float noise. + const NUM1 = '0.0' + for (let i = 0; i < CATS.length; i++) { + const row = i + 1 + for (const col of [1, 2, 3, 4]) wb.setFormat(ref(BUDGET, row, col), NUM1) + } + wb.setFormat(ref(BUDGET, totalRow, 1), NUM1) + wb.setFormat(ref(BUDGET, totalRow, 2), NUM1) + + return wb +} + +export const modelVal = (wb: Workbook, row: number) => + wb.getCell(ref(MODEL, row, 1))?.value ?? null diff --git a/examples/react/spreadsheet-demo/src/budget/scenario.ts b/examples/react/spreadsheet-demo/src/budget/scenario.ts new file mode 100644 index 0000000000..fc39091ea6 --- /dev/null +++ b/examples/react/spreadsheet-demo/src/budget/scenario.ts @@ -0,0 +1,92 @@ +/** + * The "fluid moment" (§8.3 Act 4). A $40k hardware need is pulled forward, + * reallocating from underspent Marketing. It lands as a **staged patch diff** + * (input strings only) that a human approves on `/budget/review`; approval + * applies it and records an audit trail (the diff, the approver, the runway + * before/after, and the function versions involved). + */ + +import { exportCodeFunctions } from '@tanstack/spreadsheet-codemode' +import { BUDGET, MODEL, MODEL_CELLS, modelVal, ref } from './model' +import type { CellValue, Ref, Workbook } from '@tanstack/spreadsheet-core' + +export interface DiffRow { + ref: Ref + a1: string + label: string + before: string + after: string +} + +export interface Reallocation { + label: string + rationale: string + diff: Array +} + +// Marketing is category index 4 → budget row 5 (A1 row 6). +const MARKETING_ANCHOR = ref(BUDGET, 5, 1) +const ONE_OFF = ref(MODEL, MODEL_CELLS.oneOff, 1) + +const inputOf = (wb: Workbook, r: Ref) => wb.getCell(r)?.input ?? '' + +/** The staged reallocation: amortize the hardware, trim the Marketing anchor. */ +export function pullForwardHardware(wb: Workbook): Reallocation { + return { + label: 'Pull forward $40k hardware', + rationale: + 'Amortize the one-off hardware (+5/mo) and reallocate from underspent Marketing (12 → 10). Guardrails stay green.', + diff: [ + { + ref: ONE_OFF, + a1: 'model!B6', + label: 'Pulled-forward one-off', + before: inputOf(wb, ONE_OFF), + after: '5', + }, + { + ref: MARKETING_ANCHOR, + a1: 'budget!B6', + label: 'Marketing anchor', + before: inputOf(wb, MARKETING_ANCHOR), + after: '10', + }, + ], + } +} + +export interface AuditEntry { + approver: string + label: string + diff: Array + runwayBefore: CellValue + runwayAfter: CellValue + functions: Array<{ name: string; version: string }> +} + +/** + * Apply an approved reallocation (inputs only) and return an audit entry. The + * runway before/after is read from the live model; function versions come from + * the code-function manifest. + */ +export function approveReallocation( + wb: Workbook, + realloc: Reallocation, + approver: string, +): AuditEntry { + const runwayBefore = modelVal(wb, MODEL_CELLS.trueRunway) + const patches = realloc.diff.flatMap((d) => wb.setInput(d.ref, d.after)) + wb.applyPatches(patches) + const runwayAfter = modelVal(wb, MODEL_CELLS.trueRunway) + return { + approver, + label: realloc.label, + diff: realloc.diff, + runwayBefore, + runwayAfter, + functions: exportCodeFunctions(wb).map((f) => ({ + name: f.name, + version: f.version, + })), + } +} diff --git a/examples/react/spreadsheet-demo/src/budget/store.ts b/examples/react/spreadsheet-demo/src/budget/store.ts new file mode 100644 index 0000000000..5b5dbe4b52 --- /dev/null +++ b/examples/react/spreadsheet-demo/src/budget/store.ts @@ -0,0 +1,35 @@ +/** + * A single budget workbook shared across the `/budget*` routes (the dashboard, + * the spreadsheet, and the review queue are three renderings of one living + * workbook). Built lazily on the client so SSR never fires the classifier. + */ + +import { buildBudgetWorkbook } from './model' +import type { Workbook } from '@tanstack/spreadsheet-core' +import type { AuditEntry } from './scenario' + +let wb: Workbook | null = null +let audit: Array = [] + +export function budgetWorkbook(): Workbook { + if (!wb) wb = buildBudgetWorkbook({ latency: 500 }) + return wb +} + +export function resetBudget(): Workbook { + wb = buildBudgetWorkbook({ latency: 500 }) + audit = [] + return wb +} + +export function auditLog(): Array { + return audit +} + +export function recordAudit(entry: AuditEntry): void { + audit = [entry, ...audit] +} + +export function reallocationApplied(): boolean { + return audit.length > 0 +} diff --git a/examples/react/spreadsheet-demo/src/budget/verify.ts b/examples/react/spreadsheet-demo/src/budget/verify.ts new file mode 100644 index 0000000000..a50654f516 --- /dev/null +++ b/examples/react/spreadsheet-demo/src/budget/verify.ts @@ -0,0 +1,90 @@ +/** + * The demo verification (§8.4 "numbers tie out"). Settles the workbook, then + * asserts category totals = transaction sums, runway figures match hand-computed + * expectations, guardrails are green, exactly the scripted rows are flagged for + * review, and there are zero unexpected error cells. A budgeting demo whose + * numbers don't reconcile is an own goal. + */ + +import { listErrors } from '@tanstack/spreadsheet-agent' +import { + BUDGET, + CATEGORY_NAMES, + MODEL_CELLS, + SEED_TXNS, + TXN, + modelVal, + ref, +} from './model' +import type { CellValue, Workbook } from '@tanstack/spreadsheet-core' + +export interface Check { + label: string + ok: boolean + detail?: string +} + +export interface VerifyReport { + ok: boolean + checks: Array + errorCount: number +} + +const num = (v: CellValue): number => (typeof v === 'number' ? v : NaN) + +/** Run the verification against a (freshly built) budget workbook. */ +export async function verifyBudget(wb: Workbook): Promise { + await wb.settle() + const checks: Array = [] + const check = (label: string, ok: boolean, detail?: string) => + checks.push({ label, ok, detail }) + + const totalTxns = SEED_TXNS.reduce((s, t) => s + t.amount, 0) // 76 + const categorized = num(modelVal(wb, MODEL_CELLS.categorized)) + const uncategorized = num(modelVal(wb, MODEL_CELLS.uncategorized)) + check( + 'category totals + uncategorized = transaction sum', + categorized + uncategorized === totalTxns, + `${categorized} + ${uncategorized} = ${categorized + uncategorized} (expected ${totalTxns})`, + ) + + check('monthly burn = 100', num(modelVal(wb, MODEL_CELLS.burn)) === 100) + check( + 'built-in runway = 11.2', + num(modelVal(wb, MODEL_CELLS.builtinRunway)) === 11.2, + ) + check( + 'true runway = 11.2', + num(modelVal(wb, MODEL_CELLS.trueRunway)) === 11.2, + ) + + // guardrails: every category OK + const statuses = CATEGORY_NAMES.map( + (_, i) => wb.getCell(ref(BUDGET, i + 1, 5))?.value, + ) + check( + 'all guardrails green (OK)', + statuses.every((s) => s === 'OK'), + statuses.join(', '), + ) + + // exactly two rows flagged for review (the low-confidence transactions) + let reviews = 0 + for (let r = 1; r <= SEED_TXNS.length; r++) { + if (wb.getCell(ref(TXN, r, 3))?.value === 'REVIEW') reviews++ + } + check( + 'exactly 2 transactions flagged REVIEW', + reviews === 2, + `${reviews} flagged`, + ) + + const errors = listErrors(wb) + check( + 'zero unexpected error cells', + errors.length === 0, + errors.map((e) => e.code).join(', '), + ) + + return { ok: checks.every((c) => c.ok), checks, errorCount: errors.length } +} diff --git a/examples/react/spreadsheet-demo/src/decide.ts b/examples/react/spreadsheet-demo/src/decide.ts new file mode 100644 index 0000000000..ab7213d450 --- /dev/null +++ b/examples/react/spreadsheet-demo/src/decide.ts @@ -0,0 +1,60 @@ +import { createServerFn } from '@tanstack/react-start' +import { + composeAsyncPort, + decisionPort, + namespacedPort, + restPort, +} from '@tanstack/spreadsheet-packs' +import { CANNED_ENDPOINTS, decisionModel } from './model' +import type { AsyncArgValue, AsyncPort } from '@tanstack/spreadsheet-core' + +interface Payload { + name: string + version: string + // Async args include range grids (CellValue[][]), so this is AsyncArgValue, + // not CellValue — matching what AsyncRequest.args carries. + requests: Array<{ key: string; args: Array }> +} + +/** + * The async execution proxy as a TanStack Start **server function** (§8.0). This + * handler runs server-side only, so the model, the canned endpoints, and (in a + * real deployment) API keys never reach the client bundle. It routes each batch + * to the right pack port by function name. + */ +export const decideServerFn = createServerFn({ method: 'POST' }) + .validator((d: Payload) => d) + .handler(async ({ data }) => { + const port = composeAsyncPort([ + namespacedPort('JEV', decisionPort(decisionModel, { latency: 600 })), + namespacedPort( + 'REST', + restPort(async (url) => { + if (!(url in CANNED_ENDPOINTS)) throw new Error('404') + return CANNED_ENDPOINTS[url] + }), + ), + ]) + const requests = data.requests.map((r) => ({ + name: data.name, + version: data.version, + key: r.key, + args: r.args, + })) + return port.execute(data.name, requests) + }) + +/** Client {@link AsyncPort} that forwards each batch to the server function. */ +export function serverAsyncPort(): AsyncPort { + return { + async execute(name, requests) { + return decideServerFn({ + data: { + name, + version: requests[0]?.version ?? '', + requests: requests.map((r) => ({ key: r.key, args: r.args })), + }, + }) + }, + } +} diff --git a/examples/react/spreadsheet-demo/src/model.ts b/examples/react/spreadsheet-demo/src/model.ts new file mode 100644 index 0000000000..1f98534a75 --- /dev/null +++ b/examples/react/spreadsheet-demo/src/model.ts @@ -0,0 +1,50 @@ +import { + decisionPack, + mockDecisionModel, + restPack, +} from '@tanstack/spreadsheet-packs' +import type { DecisionRule } from '@tanstack/spreadsheet-packs' + +/** The budget classifier — a deterministic "System One" model (mocked). */ +const RULES: Array = [ + { + match: /aws|cloud|gcp|azure|render|vercel/i, + choice: 'Cloud', + confidence: 0.97, + }, + { + match: /figma|notion|slack|github|subscription|saas/i, + choice: 'Software', + confidence: 0.93, + }, + { + match: /contractor|invoice|consult/i, + choice: 'Contractors', + confidence: 0.88, + }, + { + match: /uber|flight|hotel|travel|lyft/i, + choice: 'Travel', + confidence: 0.9, + }, + { match: /ads?|marketing|campaign/i, choice: 'Marketing', confidence: 0.84 }, +] + +export const CATEGORIES = 'Cloud,Software,Contractors,Travel,Marketing' + +/** Shared model (client registers the pack descriptors; server runs the port). */ +export const decisionModel = mockDecisionModel({ + id: 'mock-jev', + version: '2026.11', + rules: RULES, + fallback: { choice: 'Uncategorized', confidence: 0.42 }, +}) + +/** The `JEV.*` and `REST.*` packs — descriptors registered per-workbook. */ +export const jevPack = decisionPack(decisionModel) +export const restDataPack = restPack({ version: '1' }) + +/** A canned "REST endpoint" the server port serves (deterministic, offline). */ +export const CANNED_ENDPOINTS: Record = { + 'https://rates.demo/runway': { months: 11.2, asOf: '2026-11-01' }, +} diff --git a/examples/react/spreadsheet-demo/src/packs.ts b/examples/react/spreadsheet-demo/src/packs.ts new file mode 100644 index 0000000000..b45962c34c --- /dev/null +++ b/examples/react/spreadsheet-demo/src/packs.ts @@ -0,0 +1,48 @@ +import { toNum } from '@tanstack/spreadsheet-core' +import type { FunctionPack } from '@tanstack/spreadsheet-core' + +/** + * A test/demo sync pack (§2) — the kind a domain team would ship. Namespaced + * under `ACME`, registered per-workbook, impossible to shadow a builtin. + */ +export function acmePack(): FunctionPack { + return { + name: 'ACME', + version: '1.0.0', + functions: [ + { + name: 'ACME.TAX', + kind: 'sync', + minArgs: 1, + maxArgs: 1, + description: 'Apply the ACME 9% tax rate to an amount.', + returns: 'number', + args: [{ name: 'amount', type: 'number' }], + evaluate(ctx) { + const n = toNum(ctx.args.scalar(0)) + return typeof n === 'number' ? n * 0.09 : n + }, + }, + { + name: 'ACME.MARGIN', + kind: 'sync', + minArgs: 2, + maxArgs: 2, + description: 'Gross margin % from revenue and cost.', + returns: 'number', + args: [ + { name: 'revenue', type: 'number' }, + { name: 'cost', type: 'number' }, + ], + evaluate(ctx) { + const rev = toNum(ctx.args.scalar(0)) + const cost = toNum(ctx.args.scalar(1)) + if (typeof rev !== 'number') return rev + if (typeof cost !== 'number') return cost + if (rev === 0) return { kind: 'error', code: '#DIV/0!' } + return Math.round(((rev - cost) / rev) * 1000) / 10 + }, + }, + ], + } +} diff --git a/examples/react/spreadsheet-demo/src/routeTree.gen.ts b/examples/react/spreadsheet-demo/src/routeTree.gen.ts new file mode 100644 index 0000000000..8db44fca69 --- /dev/null +++ b/examples/react/spreadsheet-demo/src/routeTree.gen.ts @@ -0,0 +1,247 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as AgentRouteImport } from './routes/agent' +import { Route as AsyncRouteImport } from './routes/async' +import { Route as BudgetRouteImport } from './routes/budget' +import { Route as FunctionsRouteImport } from './routes/functions' +import { Route as SimpleSpreadsheetRouteImport } from './routes/simple-spreadsheet' +import { Route as StateManagerRouteImport } from './routes/state-manager' +import { Route as ApiAgentRouteImport } from './routes/api.agent' +import { Route as BudgetIndexRouteImport } from './routes/budget.index' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const AgentRoute = AgentRouteImport.update({ + id: '/agent', + path: '/agent', + getParentRoute: () => rootRouteImport, +} as any) +const AsyncRoute = AsyncRouteImport.update({ + id: '/async', + path: '/async', + getParentRoute: () => rootRouteImport, +} as any) +const BudgetRoute = BudgetRouteImport.update({ + id: '/budget', + path: '/budget', + getParentRoute: () => rootRouteImport, +} as any) +const FunctionsRoute = FunctionsRouteImport.update({ + id: '/functions', + path: '/functions', + getParentRoute: () => rootRouteImport, +} as any) +const SimpleSpreadsheetRoute = SimpleSpreadsheetRouteImport.update({ + id: '/simple-spreadsheet', + path: '/simple-spreadsheet', + getParentRoute: () => rootRouteImport, +} as any) +const StateManagerRoute = StateManagerRouteImport.update({ + id: '/state-manager', + path: '/state-manager', + getParentRoute: () => rootRouteImport, +} as any) +const ApiAgentRoute = ApiAgentRouteImport.update({ + id: '/api/agent', + path: '/api/agent', + getParentRoute: () => rootRouteImport, +} as any) +const BudgetIndexRoute = BudgetIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => BudgetRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/agent': typeof AgentRoute + '/async': typeof AsyncRoute + '/budget': typeof BudgetRouteWithChildren + '/functions': typeof FunctionsRoute + '/simple-spreadsheet': typeof SimpleSpreadsheetRoute + '/state-manager': typeof StateManagerRoute + '/api/agent': typeof ApiAgentRoute + '/budget/': typeof BudgetIndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/agent': typeof AgentRoute + '/async': typeof AsyncRoute + '/functions': typeof FunctionsRoute + '/simple-spreadsheet': typeof SimpleSpreadsheetRoute + '/state-manager': typeof StateManagerRoute + '/api/agent': typeof ApiAgentRoute + '/budget': typeof BudgetIndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/agent': typeof AgentRoute + '/async': typeof AsyncRoute + '/budget': typeof BudgetRouteWithChildren + '/functions': typeof FunctionsRoute + '/simple-spreadsheet': typeof SimpleSpreadsheetRoute + '/state-manager': typeof StateManagerRoute + '/api/agent': typeof ApiAgentRoute + '/budget/': typeof BudgetIndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/agent' + | '/async' + | '/budget' + | '/functions' + | '/simple-spreadsheet' + | '/state-manager' + | '/api/agent' + | '/budget/' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/agent' + | '/async' + | '/functions' + | '/simple-spreadsheet' + | '/state-manager' + | '/api/agent' + | '/budget' + id: + | '__root__' + | '/' + | '/agent' + | '/async' + | '/budget' + | '/functions' + | '/simple-spreadsheet' + | '/state-manager' + | '/api/agent' + | '/budget/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + AgentRoute: typeof AgentRoute + AsyncRoute: typeof AsyncRoute + BudgetRoute: typeof BudgetRouteWithChildren + FunctionsRoute: typeof FunctionsRoute + SimpleSpreadsheetRoute: typeof SimpleSpreadsheetRoute + StateManagerRoute: typeof StateManagerRoute + ApiAgentRoute: typeof ApiAgentRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/agent': { + id: '/agent' + path: '/agent' + fullPath: '/agent' + preLoaderRoute: typeof AgentRouteImport + parentRoute: typeof rootRouteImport + } + '/async': { + id: '/async' + path: '/async' + fullPath: '/async' + preLoaderRoute: typeof AsyncRouteImport + parentRoute: typeof rootRouteImport + } + '/budget': { + id: '/budget' + path: '/budget' + fullPath: '/budget' + preLoaderRoute: typeof BudgetRouteImport + parentRoute: typeof rootRouteImport + } + '/functions': { + id: '/functions' + path: '/functions' + fullPath: '/functions' + preLoaderRoute: typeof FunctionsRouteImport + parentRoute: typeof rootRouteImport + } + '/simple-spreadsheet': { + id: '/simple-spreadsheet' + path: '/simple-spreadsheet' + fullPath: '/simple-spreadsheet' + preLoaderRoute: typeof SimpleSpreadsheetRouteImport + parentRoute: typeof rootRouteImport + } + '/state-manager': { + id: '/state-manager' + path: '/state-manager' + fullPath: '/state-manager' + preLoaderRoute: typeof StateManagerRouteImport + parentRoute: typeof rootRouteImport + } + '/api/agent': { + id: '/api/agent' + path: '/api/agent' + fullPath: '/api/agent' + preLoaderRoute: typeof ApiAgentRouteImport + parentRoute: typeof rootRouteImport + } + '/budget/': { + id: '/budget/' + path: '/' + fullPath: '/budget/' + preLoaderRoute: typeof BudgetIndexRouteImport + parentRoute: typeof BudgetRoute + } + } +} + +interface BudgetRouteChildren { + BudgetIndexRoute: typeof BudgetIndexRoute +} + +const BudgetRouteChildren: BudgetRouteChildren = { + BudgetIndexRoute: BudgetIndexRoute, +} + +const BudgetRouteWithChildren = + BudgetRoute._addFileChildren(BudgetRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + AgentRoute: AgentRoute, + AsyncRoute: AsyncRoute, + BudgetRoute: BudgetRouteWithChildren, + FunctionsRoute: FunctionsRoute, + SimpleSpreadsheetRoute: SimpleSpreadsheetRoute, + StateManagerRoute: StateManagerRoute, + ApiAgentRoute: ApiAgentRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { createStart } from '@tanstack/react-start' +declare module '@tanstack/react-start' { + interface Register { + ssr: true + router: Awaited> + } +} diff --git a/examples/react/spreadsheet-demo/src/router.tsx b/examples/react/spreadsheet-demo/src/router.tsx new file mode 100644 index 0000000000..e59e199b48 --- /dev/null +++ b/examples/react/spreadsheet-demo/src/router.tsx @@ -0,0 +1,10 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + scrollRestoration: true, + defaultPreload: 'intent', + }) +} diff --git a/examples/react/spreadsheet-demo/src/routes/__root.tsx b/examples/react/spreadsheet-demo/src/routes/__root.tsx new file mode 100644 index 0000000000..cbbcb5f665 --- /dev/null +++ b/examples/react/spreadsheet-demo/src/routes/__root.tsx @@ -0,0 +1,111 @@ +import { useState } from 'react' +import { + HeadContent, + Link, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' +import appCss from '../styles.css?url' +import type { ReactNode } from 'react' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { title: 'TanStack Spreadsheet — demo' }, + ], + links: [{ rel: 'stylesheet', href: appCss }], + }), + component: RootComponent, +}) + +/** One route per capability (§8.0): the demo is a tour, not a mega-screen. */ +const NAV: Array<{ to: string; label: string; blurb: string }> = [ + { to: '/', label: 'Tour', blurb: 'start here' }, + { + to: '/simple-spreadsheet', + label: 'Simple Spreadsheet', + blurb: 'the spreadsheet (M1–M7)', + }, + { + to: '/state-manager', + label: 'State Manager', + blurb: 'form in → sheet → values out', + }, + { to: '/functions', label: 'Functions', blurb: 'registry + catalog (M8)' }, + { to: '/async', label: 'Async', blurb: 'pending → resolved (M9)' }, + { + to: '/agent', + label: 'Agent', + blurb: 'live Code Mode builds a sheet (M15)', + }, + { to: '/budget', label: 'Fluid Budget', blurb: 'the capstone (M14)' }, +] + +function RootComponent() { + const [navOpen, setNavOpen] = useState(false) + const close = () => setNavOpen(false) + return ( + +
+ + {navOpen &&
} + +
+ +
+
+ + ) +} + +function RootDocument({ children }: Readonly<{ children: ReactNode }>) { + return ( + + + + + + {children} + + + + ) +} diff --git a/examples/react/spreadsheet-demo/src/routes/agent.tsx b/examples/react/spreadsheet-demo/src/routes/agent.tsx new file mode 100644 index 0000000000..42aa92a248 --- /dev/null +++ b/examples/react/spreadsheet-demo/src/routes/agent.tsx @@ -0,0 +1,522 @@ +import { useEffect, useRef, useState } from 'react' +import ReactMarkdown from 'react-markdown' +import remarkGfm from 'remark-gfm' +import { createFileRoute } from '@tanstack/react-router' +import { colToLetter, formatValue } from '@tanstack/spreadsheet-core' +import { useRevision } from '@tanstack/react-spreadsheet' +import { fetchServerSentEvents, useChat } from '@tanstack/ai-react' +import { + approveAndRegister, + exportCodeFunctions, +} from '@tanstack/spreadsheet-codemode' +import { createAgentCodeMode } from '../agent/tools' +import { + AGENT_COLS, + AGENT_ROWS, + CELLS, + RUNWAY_FORMULA, + freshWorkbook, +} from '../agent/model' +import { isError, isPendingValue } from '../seed' +import type { AgentEvent } from '../agent/tools' +import type { CellValue, Ref, Workbook } from '@tanstack/spreadsheet-core' +import type { StagedFunction } from '@tanstack/spreadsheet-codemode' + +export const Route = createFileRoute('/agent')({ + component: AgentRoute, +}) + +type CodeMode = Awaited> + +const ACT1_PROMPT = + 'Build a Q1 budget tracker: five categories with anchor budgets, ±20% guardrail bands, actuals, an OK/OVER/UNDER status, totals, and a runway line. Then verify your work.' +const ACT2_PROMPT = + 'Runway is wrong — it should exclude one-off hardware spikes.' + +function AgentRoute() { + const [wb, setWb] = useState(freshWorkbook) + const [resetN, setResetN] = useState(0) + const [cm, setCm] = useState(null) + // cm is built in the outer component so useChat has stable client tools from + // the first render; its onEvent is routed to the inner demo via this ref. + const eventsRef = useRef<(e: AgentEvent) => void>(() => {}) + + useEffect(() => { + let alive = true + setCm(null) + createAgentCodeMode(wb, { onEvent: (e) => eventsRef.current(e) }).then( + (r) => { + if (alive) setCm(r) + }, + ) + return () => { + alive = false + } + }, [wb]) + + return ( +
+
+

Agent builds a sheet

+

+ A live agent (Claude Sonnet 4.6, via TanStack AI Code Mode) + builds a Q1 budget tracker by writing TypeScript that runs in a{' '} + QuickJS-WASM sandbox in your browser and calls tools that + mutate this workbook. When the runway definition is wrong, it authors + a Code Mode function, tests it, and — on your approval — it's + registered and wired into the sheet. Only the model completion runs + server-side (the API key never reaches the browser). +

+
+ {cm ? ( + { + setWb(freshWorkbook()) + setResetN((n) => n + 1) + }} + /> + ) : ( +
Booting the in-browser sandbox…
+ )} +
+ ) +} + +/* ---------------- the live demo ---------------- */ + +interface ActivityItem { + kind: 'code' | 'tool' + text: string +} + +function AgentDemo({ + wb, + cm, + eventsRef, + onReset, +}: { + wb: Workbook + cm: CodeMode + eventsRef: React.MutableRefObject<(e: AgentEvent) => void> + onReset: () => void +}) { + const rev = useRevision(wb) + const [activity, setActivity] = useState>([]) + const [staged, setStaged] = useState(null) + const [registered, setRegistered] = useState(false) + + // Route Code Mode tool events (fired from inside the WASM isolate) to the feed. + useEffect(() => { + eventsRef.current = (e: AgentEvent) => { + if (e.kind === 'code') + setActivity((a) => [...a, { kind: 'code', text: e.code }]) + else if (e.kind === 'tool') + setActivity((a) => [ + ...a, + { kind: 'tool', text: `${e.name} — ${e.summary}` }, + ]) + else if (e.kind === 'staged') setStaged(e.staged) + } + }, [eventsRef]) + + const [input, setInput] = useState('') + + const chat = useChat({ + threadId: 'agent', + connection: fetchServerSentEvents('/api/agent'), + tools: [cm.executeTypescript], + forwardedProps: { codeModeSystemPrompt: cm.codeModeSystemPrompt }, + }) + + const send = (text: string) => { + const t = text.trim() + if (!t || chat.isLoading) return + void chat.sendMessage(t) + } + const submit = () => { + send(input) + setInput('') + } + + // The runway formula references the cash/burn/one-off inputs, so it only makes + // sense once the tracker is built — guard "Fix runway" to avoid a #NUM!. + const built = typeof wb.getCell(CELLS.builtinRunway)?.value === 'number' + + const approve = () => { + if (!staged?.passed) return + approveAndRegister(wb, staged) + wb.applyPatches([ + ...wb.setInput(CELLS.trueRunwayLabel, 'True runway'), + ...wb.setInput(CELLS.trueRunway, RUNWAY_FORMULA), + ]) + setRegistered(true) + } + + const cellVal = (r: Ref): CellValue => wb.getCell(r)?.value ?? null + const show = (r: Ref) => { + const v = cellVal(r) + if (v === null) return '—' + if (isPendingValue(v)) return '…' + return formatValue(v, wb.getFormat(r)) + } + + return ( +
+ {/* ---------------- left: the live sheet ---------------- */} +
+
+ + +
+ +

+ The agent writes equations, not painted numbers — edit any{' '} + blue anchor (column B) and the bands, status, and totals + recalc. +

+ {registered && } +
+ + {/* ---------------- right: the conversation ---------------- */} +
+
+ + Try: + + + + {chat.isLoading ? ( + + ) : ( + + )} + + {chat.isLoading ? 'thinking…' : 'idle'} + +
+ + {chat.error && ( +
+ {chat.error.message} +
+ )} + + {/* transcript: the model's narration + the TypeScript it runs */} +
+ {chat.messages.length === 0 && ( +
+ Type a message below, or click a suggestion above. The agent is + Claude Sonnet 4.6 writing TypeScript that runs in your browser. +
+ )} + {chat.messages.map((m, i) => ( + + ))} + {activity.map((item, i) => ( +
+ +
+ {item.kind === 'code' ? ( + <> +
ran code in the sandbox
+
{item.text}
+ + ) : ( +
{item.text}
+ )} +
+
+ ))} +
+ + {/* approval gate for the authored function */} + {staged && ( +
+
+ FN.TRUE_RUNWAY + v{staged.compiled.version} + + {staged.passed ? 'examples pass' : 'examples fail'} + +
+
{staged.compiled.spec.source}
+ + + + + + + + + + + {staged.results.map((r, i) => ( + + + + + + + ))} + +
argsexpectedactualpass
+ ({(r.args as Array).join(', ')}) + {String(r.expected)}{String(r.actual)}{r.pass ? '✓' : '✗'}
+ +
+ )} + + {/* real chat input — type anything to the agent */} +
{ + e.preventDefault() + submit() + }} + > +