Saving and syncing

Keeping a sheet, files in and out, and other people and agents in the same sheet.

The store is the seam

Every write to a sheet lands in the editor’s store as a diff of records, and is announced with where it came from: user for this screen, remote for what was put in from elsewhere. Saving and syncing are listeners on that one stream. The library itself keeps nothing and sends nothing anywhere.

editor.store.listen((diff, source) => {
	// diff.added, diff.updated ([before, after] per record), diff.removed
});

A sheet in the browser

The whole sheet is small enough to write down after every change:

import { Editor, parseSheetFile, toSheetFile } from '@klementine/svelte-sheet';

const kept = localStorage.getItem('my-sheet');
const editor = new Editor({ records: kept ? parseSheetFile(kept).records : [] });

let timer: ReturnType<typeof setTimeout>;
editor.store.listen(() => {
	clearTimeout(timer);
	timer = setTimeout(() => {
		const file = toSheetFile('Budget', editor.store.snapshot());
		localStorage.setItem('my-sheet', JSON.stringify(file));
	}, 300);
});

Storage that answers later (IndexedDB, a server) cannot hand its records to new Editor. Load them into the editor that is already on the screen:

editor.loadDocument(records); // what storage held: not an undo step, announced as `remote`

editor.getDocument() is the other direction: the records and the version of their shape.

Record by record

A cell is one record, so a change is a few records, never the whole sheet. That is what a server wants: one row per record, and two people who write different cells both keep their work.

import { checkRecord, Editor } from '@klementine/svelte-sheet';

const editor = new Editor();
const { store } = editor;

// Out: what this person changed.
store.listen((diff, source) => {
	if (source !== 'user') return;
	send({
		put: [...Object.values(diff.added), ...Object.values(diff.updated).map(([, to]) => to)],
		remove: Object.keys(diff.removed)
	});
});

// In: what someone else changed. `checkRecord` throws for what is no sheet record.
function receive(put: unknown[], remove: string[]) {
	store.transact(() => {
		store.remove(remove, 'remote');
		store.put(put.map(checkRecord), 'remote');
	}, 'remote');
}

A change that arrives as remote is not an undo step: undo takes back only what this user did. No sync is written. What happens when two people write the same cell in the same moment is the sync’s rule to make; with a record per cell, the usual rule is that the last write wins for that cell.

Other people

Where the others are is your app’s to know, over its own connection. Tell the editor, and the grid draws each one’s range, cell and name flag in their colour:

editor.peers.set([
	{
		id: 'ada',
		row: 2,
		col: 1,
		top: 2,
		left: 1,
		bottom: 4,
		right: 3,
		color: '#2e9455',
		label: 'Ada'
	}
]);

The flag fades a moment after they move; writing: true keeps it while they type. What this user has selected, to send to the others, is editor.anchor and editor.focus: signals with a listen of their own.

Agents and scripts

A script or an AI agent’s tool changes the same sheet through applySheetOps: an edit as plain data, by address, that nobody has checked yet. It is carried out or refused with a code, and answers the records it changed, to save or to send:

import { applySheetOps, readSheet, sheetErrors } from '@klementine/svelte-sheet/core';

const { put, remove } = applySheetOps(sheet, {
	write: [
		{
			at: 'A1',
			rows: [
				['Channel', 'Units'],
				['Website', 21000]
			]
		}
	],
	format: [{ range: 'A1:B1', bold: true }]
});

readSheet(sheet); // { range: 'A1:B2', rows: what is typed, values: what it works out to }
sheetErrors(sheet); // the cells that show an error, like [{ cell: 'B7', error: '#DIV/0!' }]

On a server, sheet is new Sheet(records) from the engine entry; in a browser it is editor.sheet.

Files

import { parseSheetFile, toCsv, toSheetFile } from '@klementine/svelte-sheet';

const file = toSheetFile('Shopping', editor.store.snapshot());
const { title, records } = parseSheetFile(JSON.stringify(file));
const csv = toCsv(editor.sheet);

The sheet file is plain JSON by address, made to be read without this library:

{
	"format": "svelte-sheet",
	"title": "Shopping",
	"version": 1,
	"cells": {
		"A1": "Flour",
		"B1": 1.5,
		"B2": { "input": "=B1*2", "style": { "format": "eur" } }
	},
	"columns": { "A": { "width": 180 } }
}

CSV out is the values as worked out, never the formulas; text that another program would run as a formula gets a leading apostrophe. For CSV in, delimiterOf finds the separator (a comma, a semicolon or a tab), parseDelimited splits the text, decimalCommas reads a semicolon file’s numbers, and recordsFromRows makes the records. The demo’s File menu does all of it.

What is refused

What the engine refuses, it throws as a SheetError with a code. The code is the contract; the message is English prose for whoever asked. Show your own words by the code.

CodeWhen
cell_invalida cell, a style, a width or a value is not one a sheet holds, or lies outside it
range_invalida range’s name does not name a range on the sheet
file_invalida file is not a sheet file, not valid JSON, from a newer version, or too large