Diff view
With the baseline of trackChanges, compare a previous version of the rows with the current rows and color changed cells, added rows and removed rows. Step through changes with the counts and ▲ ▼ in the bottom bar
Pass a previous version of the rows (last month's table, the values on the server, data before an import and so on) to trackChanges={{ baseline }}, and the grid colors where it differs from the current rows (since 1.13.0). Rows are matched by rowKeyGetter keys: rows only in the current rows are "added", rows only in the baseline are "removed", and for rows in both, values are compared per column and differing cells are "changed".
<SpreadsheetGrid
rows={december}
columns={columns}
rowKeyGetter={(row) => row.code} // required, used to match rows
trackChanges={{ baseline: november, showRemoved: true }}
/>Demo (November and December stock lists)
Edit a cell and it turns yellow; type the November value back and it clears. Hover a yellow cell to see the November value. The ▲ ▼ in the bar below also step through the changes.
Look
| Kind of change | Look | Classes |
|---|---|---|
| Changed cell | Yellow background and a triangle at the top left. Hover for "Changed (was 120)" | .ssg-body-cell--unsaved on the cell, .ssg-body-row--unsaved on the row |
| Added row | Green background and a vertical line left of the row number. The row number is read as "Added row" | .ssg-body-row--added on the row, .ssg-row-header-cell--added on the row number |
Removed row (showRemoved) | Red background and strikethrough. "−" instead of a row number (read as "Removed row") | .ssg-body-row--removed on the row, .ssg-row-header-cell--removed on the row number |
- The grid's root gets
.ssg-root--diff, and the colors can be changed with the tokens--ssg-diff-changed/--ssg-diff-added/--ssg-diff-removed(the backgrounds are each color mixed in lightly). Marks and lines use the same colors. - The bottom bar shows a chip such as "1 row added, 2 rows removed, 3 cells changed (2 rows)" (shown even at 0) and ▲ ▼ buttons to step through the changes (in place of the "Unsaved: …" chip of
trackChanges(true)). While a large table is being compared for the first time, it says "Comparing…". - In Windows high contrast (
forced-colors), lines and marks in system colors are shown instead of colors.
/* change the colors of changes */
.ssg-root {
--ssg-diff-changed: #f59e0b;
--ssg-diff-added: #16a34a;
--ssg-diff-removed: #dc2626;
}Options
| Option | Default | Contents |
|---|---|---|
baseline | — | The array of rows to compare against |
showRemoved | false | Show rows in the baseline that are gone now, at their original place in the table, struck through |
changedOnly | false | Show only rows with changes (changed cells, added, removed). In tree data, show changed rows and the parents above them (parents that don't match in faint text) |
showOriginal | false | Show the previous value struck through inside changed cells (left of the current value) |
Removed rows (showRemoved)
- Place: in the baseline's order, right after the row that was just before it and still exists (at the top if it was the first row). While sorted, they're ordered by the same comparison using the baseline values, and column filters and the global search are also applied to the baseline values (rows that don't match aren't shown).
- Display only: they can't be edited, selected or made active (
↑↓skip them, as with label rows). They don't take a row number, so the numbers of later rows don't shift. They aren't in counts, the total row, selection aggregates, copy, export or find (Ctrl+F) either. - View row position: they don't take a row number, but they do take a view row position (the return value of
getViewRowIndex(), therowofselectCell/setActiveCell, and the spokenaria-rowindex). Positions of rows after a removed row shift back by one each, andselectCell/setActiveCellon a removed row's position snaps to the row right below. To point at a row, use row keys (revealRow(rowKey)and so on) rather than positions. - How they're drawn: values are drawn with the
valueFormattertext only (the contents ofrenderCell, conditional formatting, notes, validation marks andcellClassNamefunctions aren't used;cellClassNamegiven as a string is applied). - With row grouping (
rowGroup), label rows (labelRow) or tree data (treeData), removed rows aren't shown in the table (they're in the counts andgetChanges(). One warning in development).
Changed rows only (changedOnly)
- Only rows with changed cells and added rows (removed rows too with
showRemoved) are shown. Counts are the narrowed numbers. A row typed back to its baseline values drops out right away. - With row grouping and label rows, only the groups / sections containing changed rows are shown. In tree data, changed rows, the parents above them (unchanged parents in faint text, as with filtering) and the rows below them are shown.
- Even if an edit makes a row drop out or changes the order, the active cell follows the same row (the default of
activeCellFollowsbecomes'row'; write'position'to keep it at the position). - The empty table when there are no changes shows "No changes" (
diffNoChanges). While a large table is being compared for the first time, all rows are shown.
Stepping through changes (goToNextChange / goToPrevChange)
The handle's goToNextChange() / goToPrevChange() and the ▲ ▼ in the bottom bar step through changed cells (in column order within a row), added rows and removed rows in view order. At one end, they wrap to the other end.
- For changed cells, the active cell is placed there and scrolled into view. For added rows, it moves to that row keeping the current column (the first column if the current one isn't a data column).
- The active cell can't be placed on removed rows, so the row is scrolled into view and marked (
.ssg-body-row--change-target). Moving the active cell removes the mark. While the mark is shown,↑/↓move to the row right above / below the removed row. - Where you land is announced ("Unit price of P1: Changed (was ¥100) (1 of 3)", "Removed row: P3 (2 of 3)". The row name is the text of the first data column. Texts
diffNavCell/diffNavRow). - Only rows shown in the table are visited. Changes inside collapsed groups (
rowGroup) or closed tree-data parents aren't visited (open them first). - The return value is
trueif it moved,falseif there was no change to go to. With no changes, ▲ ▼ can't be pressed (when changes exist only in collapsed parts, they can be pressed but don't move).
<button type="button" onClick={() => gridRef.current?.goToNextChange()}>Next change</button>Editing and saving
- Editing still works during the diff view (use
readOnlyto stop it). Edited cells are compared with the baseline values, and typing back to the baseline value clears the color. - The saved values are the baseline values.
getChanges()is the result of comparing with the baseline and includesadded/removed/addedCount/removedCount(the same shape as{ rows: true }in change tracking; with a baseline they're included without writingrows: true).onChangesChangereports the same counts.getChanges()called insideonRowsChangeincludes that change. - The baseline is treated as the "saved rows". Even when comparing with a version unrelated to saving, such as last month's table,
getChanges()is the difference from that version. revertChanges()sets everything back to the baseline values (reverts changed cells, removes added rows, and puts removed rows back in place; recorded in the undo history as one change).revertChanges(rowKeys)reverts only those rows (removing them if they're added rows' keys, putting them back if they're removed rows' keys).- The context menu's
params.revertItems(needsenableContextMenu) reverts only changed cells. Reverting added and removed rows isn't included (the menu doesn't open on removed rows). For per-row revert items, add your own item that callsrevertChanges([rowKey]). markChangesSaved()does nothing. InapplyRows(next, { asSaved: true }),asSavedhas no effect and the rows are applied as a normalapplyRows(not recorded in the undo history) (each with one warning in development). After saving, pass the saved rows as the newbaseline(the comparison target changes and the colors clear).- Pass the rows as of sending as the baseline. Values edited while waiting for the save haven't been sent yet, so making the current rows after
awaitthe baseline marks unsent values as saved and clears their colors (they'd be lost on reload). Take the current rows before sending, and pass those.
const [baseline, setBaseline] = useState(serverRows);
const save = async () => {
const changes = gridRef.current?.getChanges();
if (!changes) return;
const sent = rows; // the rows as of sending (without values edited while waiting)
await api.save({
insert: changes.added?.map(({ row }) => row) ?? [],
update: changes.rows.map(({ row }) => row),
delete: changes.removed?.map(({ rowKey }) => rowKey) ?? [],
});
setBaseline(sent); // make the sent rows the new comparison target (cells edited while waiting stay changed)
};
<SpreadsheetGrid ref={gridRef} rows={rows} onRowsChange={setRows} rowKeyGetter={(row) => row.id} columns={columns} trackChanges={{ baseline }} />;- Solid tables that keep rows in a store (
createStore) copy the rows as of sending withsnapshot(state.rows)before passing them (passing the store's rows as they are lets later edits change the inside of the baseline, so the changes become invisible). - When the server corrects values and returns them (trimming spaces and so on), make the baseline the sent rows with the returned values laid over them, and in
rowsreplace with returned values only the rows not edited while waiting (ifrowsisn't replaced, the difference from the returned values remains as changes). - Tables only for comparing don't need
onRowsChange(unliketrackChanges(true), it compares without it). WithreadOnly, double-clicks and typed text don't open editors either.
How values are compared
- Values are compared with
Object.is, as in change tracking (multi-select values by contents andDates by time; even if a server response recreates a differentDate, the same date and time isn't a change). Other object values ({ amount, currency }and so on) count as changed if they're different objects even with the same contents, so pass them as strings or numbers. Computed columns (onlygetValue, nosetValue) aren't compared. - Only column values are compared. Fields not in any column and columns added or removed aren't compared.
- When two or more rows have the same key, only the first one is compared (duplicate keys are a
rowKeyGettermistake). - Speed: the index of baseline keys is built once, when the baseline array changes. Comparison results are kept per row object, and editing one cell recompares only that row. The first comparison of a large table (when the baseline or
rowsis replaced as a whole) is done bit by bit, showing the last finished result meanwhile, with "Comparing…" in the bottom bar (it also shows briefly after adding rows to a large table, until the comparison finishes). - Don't recreate the baseline and
rowson every render (recreating them recompares every time; keep them withuseMemo/ signals).
Screen readers
- When a changed cell becomes active, its description (
aria-description) reads "Changed (was 120)". Added rows and changed rows say "Added row" / "Has changes" in the row number's description, and removed rows are named "Removed row". - Where ▲ ▼ and
goToNextChange()/goToPrevChange()land is announced in a hidden live region (aria-live="polite") ("Stepping through changes" above). - Removed rows also take a view row position, so
aria-rowindexcounts them (the row number text doesn't).
When it works, and what isn't included
- It works when rows are passed with
rows(clientSide) and there is arowKeyGetter. It doesn't work with serverSide (dataSource). - Comparing three or more versions, showing added or removed columns, and exporting the diff aren't available. To export the diff, build it from
getChanges().
With /lite
With /lite, add both diffViewFeature and changeTrackingFeature (neither is in standardFeatures). Passing a baseline in a setup without diffViewFeature doesn't compare with the baseline (it's change tracking of edits made in the grid only), with one warning in development.
import { createSpreadsheetGrid, changeTrackingFeature, diffViewFeature } from '@ishibashi0112/spreadsheet-grid/lite';
const Grid = createSpreadsheetGrid({ features: { changeTracking: changeTrackingFeature, diffView: diffViewFeature } });Texts
The texts in localeText are diffChanges (the chip text such as "3 cells changed (2 rows)") / diffComparing / diffPrevChange / diffNextChange / diffChangedCell (Changed (was {value}) in English) / diffChangedRow / diffAddedRow / diffRemovedRow / diffNavCell ({column} of {row}: {change} ({position} of {total})) / diffNavRow ({change}: {row} ({position} of {total})) / diffNoChanges (the empty table text when changedOnly has no changes, "No changes") / dragRowDisabledRemoved (the tooltip of the row drag handle while removed rows are shown), plus the row counts unsavedAddedRows / unsavedRemovedRows / unsavedSeparator (they're in the English table localeTextEn too; English and text).