TrackedJSON
TrackedJSON is a JavaScript library which provides frictionless undo/redo for JSON objects.
TrackedJSON tries to maintain a relatively minimal API - the core of the library is the .data
property which represents the JSON object you want to keep track of. You can update it just like a regular JavaScript object, with the only requirement being that properties have to be valid JSON types.
Install
npm install tracked-json
Basic Usage
You can use it like so:
const tracked = new TrackedJSON();
tracked.data.value = 1;
tracked.data.value = 2;
tracked.data.value = 3;
tracked.undo();
tracked.undo();
tracked.redo();
tracked.redo();
Docs
See the docs here
Common questions answered on usage:
How many undo/redo operations are there for my data object?
You can get the size of the undo stack using undoSize
like so:
const tracked = new TrackedJSON({ initialState: { value: 0 } });
tracked.data.value = 1;
tracked.data.value = 2;
console.log(tracked.undoSize);
tracked.undo();
tracked.undo();
console.log(tracked.redoSize);
How do I instantiate with a given state?
You can instantiate an object with a starting state like so:
const tracked = new TrackedJSON({ initialState: { value: 0 } });
console.log(tracked.data.value);
Can I replace the whole data object with a new one?
If you want to replace the whole data object, this is possible and will be tracked as normal, like so:
const tracked = new TrackedJSON();
tracked.data.value = 0;
tracked.data = { value: 1 };
tracked.undo();
console.log(tracked.data.value);
Do I need to guard against non JSON?
Properties and nested properties of the data object must be valid JSON. Attempting to set non valid JSON properties and will throw an error like so:
const tracked = new TrackedJSON();
tracked.data.value = {};
tracked.data.value = 1;
tracked.data.value = [];
tracked.data.value = "string";
tracked.data.value = true;
tracked.data.value = new Map();
License
MIT