Birch UI v0.1
Pricing

Calculating in a Web WorkerSpreadsheet

Run the formula engine in a Web Worker so recalculating a large workbook never blocks typing or scrolling, with the same engine on the main thread as a fallback.

Open .md

Recalculating a few thousand formulas takes a millisecond or two. Recalculating two hundred thousand takes a fifth of a second, and while it runs the page cannot scroll, type or paint. createWorkerEngine() moves the formula engine into a Web Worker: the page sends edits, the worker recalculates, and the page gets back only the values it asks for.

On a workbook with 200,000 formulas that all depend on one input, changing the input and reading back a screen of results costs the page well under a millisecond; the same edit on the main thread blocks it for about 200 ms. The package's performance tests assert this against a simulated worker channel that copies messages the way a real worker does.

Set-up#

The worker is a file in your application, two lines long. Your bundler builds it like any other worker.

src/calc.worker.ts
import { exposeFormulaEngine, xlsxToJSON } from '@birchui/spreadsheet';

exposeFormulaEngine({ importXlsx: xlsxToJSON });
src/model.ts
import { createWorkerEngine } from '@birchui/spreadsheet';

export const engine = createWorkerEngine({
  calculation: 'worker',
  worker: () => new Worker(new URL('./calc.worker.ts', import.meta.url), { type: 'module' }),
  sheets: ['Prices'],
});

importXlsx is optional. Leave it out if the worker never opens xlsx files, and the xlsx reader stays out of the worker's bundle.

Editing and reading#

Every method returns a promise. Edits resolve with the recalculation's statistics once the worker has finished.

TypeScript
await engine.load(workbookJson);

const stats = await engine.setCell('Prices', 'D1', 1.1);
console.log(`${stats.evaluated} formulas in ${stats.ms.toFixed(0)} ms`);

const rows = await engine.getRange('Prices', 'A1:J50');

To apply several edits as one recalculation, and read what the screen shows in the same round trip, use apply():

TypeScript
import { decodeCell } from '@birchui/spreadsheet';

const { stats, ranges, results } = await engine.apply(
  [
    { type: 'setCell', sheet: 'Prices', address: 'D1', input: 1.1 },
    { type: 'setRange', sheet: 'Prices', topLeft: 'F2', rows: [[0.19], [0.07]] },
    { type: 'addSheet', name: 'Scenario B' },
  ],
  [{ sheet: 'Prices', range: 'A1:J50' }],
);

const visible = ranges[0];
for (let row = 0; row < visible.rows; row++) paintCell(row, 1, decodeCell(visible, row, 1));

results holds one entry per operation: the name for addSheet and addTable, true or false for removeName, and undefined for the rest.

Method Purpose
ready() Resolves when the engine has started. Other calls wait for it on their own.
load(json) Replaces the workbook with a workbook JSON.
loadXlsx(bytes, { transfer? }) Parses an xlsx file inside the worker and loads it. With transfer: true the bytes move to the worker instead of being copied, and your array is emptied.
apply(operations, read?) Applies edits as one batch and returns the statistics, the result of each operation and the requested ranges.
setCell(), setRange(), clearRange() Single edits; they resolve with the statistics.
recalculate() Recalculates everything.
getRange(), getValue(), getFormula() Read values and formulas.
readRanges(ranges) Reads several ranges in their compact form, without decoding.
evaluate(formula, context?) Evaluates a formula without storing it.
toJSON() The whole workbook as JSON, with current values.
on('recalculated' | 'circularReference', listener) Subscribes to engine events; returns an unsubscribe function.
terminate() Stops the worker and rejects anything still pending.
calculation, sheetNames, pending Where the engine runs, the sheet names after the last edit, and the number of unanswered requests.

The operations of apply() are setCell, setRange, clearRange, insertRows, deleteRows, insertColumns, deleteColumns, sortRange, addSheet, removeSheet, renameSheet, moveSheet, defineName, removeName, addTable and removeTable, each with the arguments of the engine method of the same name.

A request the engine refuses, such as an edit to a sheet that does not exist, rejects its promise with the engine's message. The engine keeps running.

What crosses the thread boundary#

Sending data between threads copies it, and copying is work on the page. Three things keep that work small:

  • Edits are small. A cell edit is a few dozen bytes however many formulas depend on it.
  • Values come back as typed arrays. A range is encoded as a Uint8Array of value kinds, a Float64Array of numbers and a short list of distinct strings. The arrays are transferred, not copied, so reading a screen of cells from a sheet with 200,000 rows costs the page well under a millisecond. decodeCell(range, row, column) reads one value and decodeRange(range) rebuilds rows of values.
  • Files can be parsed in the worker. loadXlsx() hands the bytes over and the page never sees the parsed workbook.

Read what the user can see, not the workbook. toJSON() and load() copy the whole workbook; use them when opening and saving, not on every edit.

The options that are functions on the plain engine, now and random, cannot be sent to a worker and are not available here.

Custom functions#

A function cannot be sent to a worker, so custom functions are registered inside it. Keep the definitions in a module of their own, with a named export called functions:

src/sheet-functions.ts
import type { CustomFunctionSet } from '@birchui/spreadsheet';

export const functions: CustomFunctionSet = {
  NET_OF_TAX: (amount, rate) => Number(amount) / (1 + Number(rate)),
  FX_RATE: {
    impl: async (currency) => (await fetch(`/api/rates/${String(currency)}`)).json().then((body) => body.rate),
    async: true,
    args: 'currency',
  },
};

There are two ways to get them into the worker. Use one of them.

Import the module in the worker file. The bundler includes it in the worker's bundle:

src/calc.worker.ts
import { exposeFormulaEngine } from '@birchui/spreadsheet';
import { functions } from './sheet-functions';

exposeFormulaEngine({ functions });

Or name the module when you create the engine. The worker loads it with import() before it handles the first request. The URL must be absolute, or it is resolved against the worker's own location, and the file must be something the browser can import as it is:

TypeScript
const engine = createWorkerEngine({
  worker: () => new Worker(new URL('./calc.worker.ts', import.meta.url), { type: 'module' }),
  functionsModule: new URL('./sheet-functions.js', import.meta.url),
  functions,
});
await engine.ready();

ready() rejects when the module cannot be loaded or has no functions export; the engine then runs without those functions. functions in the same call is used only by the main-thread fallback, which registers them directly; the fallback also imports functionsModule on the main thread if you pass it. Pass both so the two paths calculate the same results.

Async functions resolve inside the worker. The worker recalculates and the engine emits recalculated and asyncResolved; read the ranges again at that point, or wait first:

TypeScript
await engine.setCell('Prices', 'D2', '=FX_RATE("EUR")');
await engine.whenCalculated();
await engine.getValue('Prices', 'D2');

on('functionError', listener) receives { name, sheet, address, message } when a function throws or rejects in the worker. The error object itself stays in the worker. registerFunction is not available on a worker engine: the set is fixed when the worker starts.

Fallback to the main thread#

Without a worker, the same engine runs on the main thread behind the same promise-based API, so calling code does not change:

Situation engine.calculation
calculation: 'main' 'main'. A worker you passed is not started.
No worker given 'main'
The worker function throws, for example where Worker does not exist during server-side rendering 'main', with one console warning
Otherwise 'worker'

Importing @birchui/spreadsheet never touches Worker, window or document, so the module is safe to import on a server. The worker starts when you call createWorkerEngine(). If your bundle does not import createWorkerEngine, none of this is included in it.

If the worker fails after it has started, for example because its script cannot be loaded, pending requests reject with the error. Create a new engine with calculation: 'main' to continue on the main thread.

With the spreadsheet component#

createSpreadsheet() calculates on the main thread by default. For most workbooks that is the right choice: an edit recalculates only the formulas that depend on it. For a workbook that takes noticeably long to recalculate, set calculation: 'worker' and pass a function that creates the worker:

TypeScript
import { createSpreadsheet } from '@birchui/spreadsheet';

const sheet = createSpreadsheet(container, {
  licenseKey,
  data: workbook,
  calculation: 'worker',
  calculationWorker: () => new Worker(new URL('./calc.worker.ts', import.meta.url), { type: 'module' }),
});

The worker file is the two-line file from Set-up.

Option Values
calculation 'sync' (default) calculates on the main thread. 'worker' calculates in the worker created by calculationWorker.
calculationWorker A function that returns a Worker, or anything with postMessage and addEventListener. It is called once, when the component is created or when calculation is switched to 'worker'.

What changes in worker mode:

  • Edits return immediately. The cell you typed in shows its new value at once. Formula cells keep the value they had until the worker has finished, then update together. A formula entered in an empty cell stays blank until then.
  • Opening a workbook shows the values stored with its formulas (from the xlsx file or the workbook JSON) and replaces them when the first calculation arrives.
  • The status bar shows Calculating… and the widget has aria-busy="true" while a result is outstanding.
  • Several edits made in the same turn of the event loop, such as a paste or a setRange() call, go to the worker as one request.
  • recalculated fires when the results have been applied, with the worker's changedCount and ms. Pivot tables, charts and conditional formats refresh at that point.
  • Dynamic arrays spill as they do on the main thread.
  • Circular references are reported through the error event as usual.

Reading a formula's value right after an edit returns the previous value. Wait for the calculation when you need the new one:

TypeScript
sheet.setValue('B2', 0.21);
await sheet.whenCalculated();
sheet.getValue('D40');

sheet.getCalculationMode();

whenCalculated() resolves when no calculation is outstanding; in 'sync' mode it resolves at once unless an async custom function is pending. getCalculationMode() returns 'worker' or 'sync', which tells you whether a fallback happened.

What still runs on the main thread#

  • The workbook model, undo history, formatting, sorting and filtering.
  • goalSeek(), which needs the result of each attempt before the next one. Data tables are calculated in the worker; adding or removing one sends the whole workbook again.
  • Sending the change. A cell edit sends only the changed cells. Inserting or deleting rows and columns, adding, renaming, moving or deleting a sheet, and defining or removing a name are sent as one operation each, which the worker applies to its own copy. Other structural changes (tables, sorting, undo and redo of a structural change, loading data, and hiding rows when the workbook uses SUBTOTAL or AGGREGATE) send the whole workbook to the worker again, which costs the page a serialisation of the workbook.
  • Applying the results: one pass over the formula cells.

Details to know#

  • recalculate() returns { changedCount: 0, ms: 0 } in worker mode. The real figures arrive with the recalculated event. It does not make the worker call async custom functions again; their cached results are kept until the worker restarts.
  • The cellChange event for a formula cell carries the value the cell showed before the worker answered.
  • The now option cannot be sent to a worker. TODAY(), NOW() and the random functions use the worker's clock and random numbers.
  • update({ calculation }) switches mode at any time. Changing dynamicArrays or iterativeCalculation restarts the worker with the new settings.
  • destroy() terminates the worker.

Custom functions in worker mode#

Register the same definitions in two places: on the component, and in the worker file.

TypeScript
import { functions } from './sheet-functions';

const sheet = createSpreadsheet(container, {
  functions,
  calculation: 'worker',
  calculationWorker: () => new Worker(new URL('./calc.worker.ts', import.meta.url), { type: 'module' }),
});
src/calc.worker.ts
import { exposeFormulaEngine } from '@birchui/spreadsheet';
import { functions } from './sheet-functions';

exposeFormulaEngine({ functions });

The worker's copy calculates the cells. The component's copy supplies autocomplete, the argument hint and listFunctions(), and it calculates when the component falls back to the main thread and inside goalSeek(). A function that exists only on the component gives #NAME? in worker mode, because the worker does not know it. registerFunction() called later changes the component's copy only, so in worker mode define every function up front in the shared module.

Async results arrive from the worker when they resolve: the cells change from #BUSY! to the value, recalculated fires, and whenCalculated() waits for them. A function that throws in the worker is reported through the component's error event with code: 'formula'.

Fallback#

Situation Result
calculation: 'worker' without calculationWorker Main thread, with one console warning
calculationWorker throws, for example because Worker does not exist during server-side rendering or in an old browser Main thread, with one console warning
The worker reports an error after it has started The component stops the worker, recalculates on the main thread and continues there, with one console warning

A separate model in a worker#

You can also keep a large model in a worker engine of your own and show only part of it in the component:

TypeScript
const sheet = createSpreadsheet(container, { licenseKey });
sheet.fromJSON(inputsWorkbook);

sheet.on('cellChange', async ({ sheet: name, address, newValue, formula }) => {
  const { ranges } = await engine.apply(
    [{ type: 'setCell', sheet: name, address, input: formula ?? newValue }],
    [{ sheet: 'Results', range: 'A1:F40' }],
  );
  showResults(ranges[0]);
});

Other workers and threads#

exposeFormulaEngine(endpoint, options?) accepts anything with postMessage and addEventListener('message', …), so the engine can also sit behind a MessagePort, a SharedWorker port or an adapter around Node's worker_threads. createWorkerEngine({ worker }) accepts the matching other end.

↑ ↓ to move, Enter to open, Esc to close