Add Cancel to revert unsaved changes in a section
Reverts the section (or print header) on screen to the last open/save and leaves edit mode. Closes #11 Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
55
src/ops.js
55
src/ops.js
@@ -109,3 +109,58 @@ export function addImageField(record, label, value) {
|
||||
record.fields.push(f);
|
||||
return f;
|
||||
}
|
||||
|
||||
// ---- revert to the last saved state (Cancel) ----
|
||||
// A baseline is a deep copy of the document taken at open / save.
|
||||
export function snapshotDoc(doc) {
|
||||
return JSON.parse(JSON.stringify(doc));
|
||||
}
|
||||
|
||||
// The date stamp changes on every edit, so it never counts as a difference.
|
||||
const stable = (doc) => JSON.stringify({ ...doc, meta: { ...doc.meta, lastUpdated: '' } });
|
||||
const sameJson = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
||||
|
||||
export function docDiffers(doc, baseline) {
|
||||
return stable(doc) !== stable(baseline);
|
||||
}
|
||||
|
||||
// A section the baseline doesn't have was added since: that counts as changed.
|
||||
export function sectionDiffers(doc, baseline, id) {
|
||||
const cur = doc.sections.find((s) => s.id === id);
|
||||
const old = baseline.sections.find((s) => s.id === id);
|
||||
if (!cur) return false;
|
||||
return !old || !sameJson(cur, old);
|
||||
}
|
||||
|
||||
export function headerDiffers(doc, baseline) {
|
||||
return !sameJson(doc.header, baseline.header);
|
||||
}
|
||||
|
||||
// Put the section back as it was in the baseline (in its current position),
|
||||
// or remove it if it was added since. Returns the id of the section to show
|
||||
// next (the same one, or a neighbour after a removal; undefined if none left).
|
||||
export function revertSection(doc, baseline, id) {
|
||||
const i = doc.sections.findIndex((s) => s.id === id);
|
||||
if (i < 0) return undefined;
|
||||
const old = baseline.sections.find((s) => s.id === id);
|
||||
if (old) {
|
||||
doc.sections[i] = snapshotDoc(old);
|
||||
syncDate(doc, baseline);
|
||||
return id;
|
||||
}
|
||||
doc.sections.splice(i, 1);
|
||||
syncDate(doc, baseline);
|
||||
const next = doc.sections[i] || doc.sections[i - 1];
|
||||
return next && next.id;
|
||||
}
|
||||
|
||||
export function revertHeader(doc, baseline) {
|
||||
if (baseline.header === undefined) delete doc.header;
|
||||
else doc.header = snapshotDoc(baseline.header);
|
||||
syncDate(doc, baseline);
|
||||
}
|
||||
|
||||
// If nothing differs any more, the "last updated" date goes back too.
|
||||
function syncDate(doc, baseline) {
|
||||
if (!docDiffers(doc, baseline)) doc.meta.lastUpdated = baseline.meta.lastUpdated;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user