Skip to main contentElyra

Command stack

The CommandStack is a JavaScript class that provides the functionality to support do/undo/redo of commands. It maintains an internal stack of commands with a cursor that moves up and down when commands are undone or redone. Commands are also Javascript classes that implement a simple interface.

The CommandStack API allows application code to programmatically add commands to the command stack. You can get the Command Stack by calling the CanvasController.getCommandStack() method. The CommandStack API provides the following methods:

do(command) - push the command onto the command stack and then invoke command.do()
undo() - pop a command from the command stack and then invoke command.undo()
redo() - push last undo command onto the command stack and then invoke command.redo()
canUndo() - returns true if there is a command on the command stack.
canRedo() - returns true if there is an undo command that can be redo.
clearCommandStack()
getUndoCommand() - returns the next command to be undone or null.
getRedoCommand() - returns the next command to be redone or null.

Each commands that is added to the command stack is a Javascript class that need to implement these methods:

constructor()
do()
undo()
redo()

constructor()

initial setup do() - Performs all actions necessary to execute the command undo() - Performs all actions necessary to reverse the actions performed in do() redo() - Performs all actions necessary to re-execute the command. For some commands this is the same as do() but others it is different.

Here is some sample code that shows how a create-node command might be written:

export default class CreateNodeAction extends Action {
constructor(data) {
super(data);
this.newNode = createNode(data);
}
do() {
ObjectModel.addNode(this.newNode);
}

Here is an example of using the CommandStack API to create a command action and push it on the stack:

const command = new CreateNodeAction(data);
CommandStack.do(command);

When using CommonCanvas, the canvas-controller creates an instance of the command stack. CommonCanvas provides command objects for each of the commands that are performed by the user, such as: create node, delete comment, link nodes together, etc. Common canvas also provides undo/redo options in its default context menu, on the toolbar and via keystrokes ctrl+z (undo) and ctrl+shift+z (redo). You can implement your own undo and redo UI if required using the API.