2

This started out as a question but in the process of asking it I figured out the answer. However since it's not well documented (that I could find anyway) I'm posting here for anyone else that comes along with the same issue.

I'm using the Autodesk Forge Viewer with the Edit2D tools. I see that in the default context it has an undo stack. I can subscribe and get a notification when the undo stack changes like this:

// @ts-ignore
e.defaultContext.undoStack.addEventListener(Autodesk.Edit2D.UndoStack.BEFORE_ACTION, s => {
  console.log(s);
});

// @ts-ignore
e.defaultContext.undoStack.addEventListener(Autodesk.Edit2D.UndoStack.AFTER_ACTION, s => {
  console.log(s);
});

However I want to tell the viewer to simply undo the last action and I can't find any documentation on how to do that. How do I implement an undo? If there is a documentation file or page somewhere that shows more data about the undo stack system?

sfaust
  • 2,089
  • 28
  • 54

2 Answers2

0

Looking into the events further, the argument passed to the undo stack action has an 'action' property with some data associated to it. This seems to be the definition of what was done and can be passed back into the undo stack to be undone. In order to do this, here is what worked for me.

First subscribe to the undo stack event as above (I used the after action but either would probably work).

// @ts-ignore
e.defaultContext.undoStack.addEventListener(
  Autodesk.Edit2D.UndoStack.AFTER_ACTION,
  (s: any) => {
    lastAction = s.action;
  }
);

Note also that you have to use typescript ignore since the context doesn't show up as a property of Autodesk.Viewing.Extension, I'm not sure why but it does show up at runtime. I then as shown store the last action in a variable so that I have it available.

Next handling the command. When the undo command is pressed, passed the last command into the undo method:

// @ts-ignore
state.editor.defaultContext.undoStack.undo(lastAction);

Note that this method was an educated guess as I found no documentation on it at all. I found some items on undo on this page. That shows part way down this code:

const action = new Actions.AddShapes(this.layer, shapes);
this.undoStack.run(action);

I made a guess that if there is a run method maybe there is an undo method as well so I just changed the name and it worked.


EDIT

Found a slightly simpler method. You can actually avoid storing the last action and just reference it directly from the stack:

const stack = state.editor.defaultContext.undoStack;
// @ts-ignore
stack.undo(stack.stack[stack.stack.length - 1]);
sfaust
  • 2,089
  • 28
  • 54
0

The undo stack has a simple undo method (without any parameters) that will take the last action, revert it, and pop it from the stack. So you should just be able to call

edit2d.defaultContext.undoStack.undo();
Petr Broz
  • 8,891
  • 2
  • 15
  • 24