How to implement an undo and redo system in javascript?

Question:

I see in some native tools in javascript , the redo and undo option, as if it were a Ctrl + z and Ctrl + y , but they are graphical tools and not forms.

I thought of something like…

  1. Components will be estáticos .
  2. Each component will have its own dynamically generated code.
  3. Each action will have a start value and an end value, this data will be stored in an objeto to undo along with the component code.
  4. When pressing Ctrl + Z the last element is removed from the undo objeto and placed in another one responsible for restoring, and when moving its initial value it is replaced by the final one and compiled in the component with angular and vice versa.

I did some tests and it is totally possible to do this, but the work will be huge, as everything is created dynamically. Is there any other way to implement this? using cache or some library? I didn't find anything related on the internet.

Answer:

I found this library on GitHub that makes the undo and redo approach easier. You only need to say which methods are responsible for creating and removing the components (both graphics, characters, etc). Everything is stored on a stack and then you just call the UndoManager class methods to perform the operations: undoManager.undo(); and undoManager.redo(); . It might be useful for you.

var undoManager = new UndoManager(),
people = {},
addPerson,
removePerson,
createPerson;        

addPerson = function(id, name) {
    people[id] = name;
};

removePerson = function(id) {
    delete people[id];
};

createPerson = function (id, name) {
    // first creation
    addPerson(id, name);

    // make undo-able
    undoManager.add({
        undo: function() {
        removePerson(id)
    },
    redo: function() {
        addPerson(id, name);
        }
    });
}

createPerson(101, "John");
createPerson(102, "Mary");

console.log("people", people); // {101: "John", 102: "Mary"}

undoManager.undo();
console.log("people", people); // {101: "John"}

undoManager.undo();
console.log("people", people); // {}

undoManager.redo();
console.log("people", people); // {101: "John"}

Here you can test the library working.

Scroll to Top