Batch Updates, Undo and Redo
Edits that belong together, such as filling a small table and adding its total, should be one step for the user. Group related application edits in a batch, so that users can undo a logical action and the editor can process a coherent change. Make small independent changes individually when that better matches the interaction.
Group Edits in a Batch
The following code writes a small table, its total and a bold heading row in one batch, then undoes and redoes it. editor is the Spreadsheet of the browser editor, created as in JavaScript:
const book = editor.workbook;
const sheet = book.sheets.at(0);
book.batch(() => {
sheet.range('A1:B3').setValues([
['Item', 'Amount'], ['Hardware', 120], ['Software', 80]
]);
sheet.cell('B4').setFormula('=SUM(B2:B3)');
sheet.range('A1:B1').format({ font: { bold: true } });
});
book.history.undo();
book.history.redo();
The code works as follows:
- Workbook.batch runs the callback as one group of document changes. Batched edits emit one change notification.
- Range.setValues writes the headings and the items as a typed matrix to
A1:B3. - Cell.setFormula writes the total
=SUM(B2:B3)toB4. - Range.format makes the heading row bold.
- Workbook.history offers
undo()andredo(), which undo and redo the batch.
Important
Synchronous Callback. The batch callback performs synchronous document changes. Fetch external data before you enter the callback, and do not assume that an asynchronous callback is awaited as a document transaction.
Validate the intended input matrix and the shapes of the options before the mutation.
How History Differs From Storage
Undo and redo are authoring features. They do not save a file, update a database or restore a data service that your application owns.
Loading another document changes the document state and can invalidate handles. In batch report generation, do not use the history as a replacement for a clean template.
React to Changes
Observe the workbook events for successful changes and for the supported cancelable preflight events. Avoid reentrant changes from notification handlers.
If your application maintains a dirty indicator, distinguish user and document edits from a successful save and from view changes that only concern your application.
Write Large Amounts of Data
For large writes, use rectangular matrices and respect the limits of each operation. Break workloads into meaningful chunks when appropriate. The number of JavaScript statements is not an indication of the total cost of calculation or rendering.
Next Steps
- Events and Cancellation: subscribe to workbook changes and cancel operations.
- Measuring Performance: measure the complete workflow of your application.
- Lifetime and Concurrency: understand who owns a document and when handles become invalid.