Undo/Redo

All change history is preserved. Making versioning simple.

Change histories are stored as immer patches. But developers can choose their own state management modules, hence libraries like Redux or MobX can create state histories/patches.

useSpreadsheetState uses immer to product patches during state updates.

import React, { useState } from "react";
import { CanvasGrid, CellData } from "@rowsncolumns/spreadsheet";
import { produceWithPatches } from "immer";
import {
  SheetData,
  useSpreadsheetState,
} from "@rowsncolumns/spreadsheet-state";

const MySpreadsheet = () => {
  const [sheetData, onChangeSheetData] = useState<SheetData<CellData>>({});
  const { createHistory } = useSpreadsheetState({});
  return (
    <CanvasGrid
      sheetId={1}
      rowCount={100}
      columnCount={100}
      onChange={(sheetId, activeCell, value) => {
        const saveHistory = createHistory();
        // Update sheet data
        onChangeSheetData?.((prevSheetData) => {
          const [nextState, patches, inversePatches] = produceWithPatches(
            prevSheetData,
            (draft) => {
              draft[sheetId][activeCell.rowIndex].values[
                activeCell.columnIndex
              ] = {
                userEnteredValue: value,
              };
            }
          );

          saveHistory({
            sheetData: { patches, inversePatches },
          });

          return nextState;
        });
      }}
    />
  );
};

Last updated