FabricJs history handler

Home   »   FabricJs history handler

const MAX_HISTORY_LENGTH = 100;

// event 'history:undo:pop'
// event 'history:redo:pop'
// event 'history:undo:push'

export default (fabric) => {
  fabric.History = fabric.util.createClass(fabric.Observable, {
    undoActions: [],
    redoActions: [],

    getRedoActions() {
      return [...this.redoActions];
    },

    getUndoActions() {
      return [...this.undoActions];
    },

    popUndoAction() {
      const lastAction = this.undoActions.pop();

      this.fire('history:undo:pop', { lastAction });
      this.redoActions(lastAction);

      return lastAction;
    },

    popRedoAction() {
      const lastAction = this.redoActions.pop();

      this.fire('history:redo:pop', { lastAction });

      return lastAction;
    },

    pushUndoActions(snapshot: object) {
      this.redoActions.length = 0;
      this.undoActions.push(snapshot);

      if (this.undoActions > MAX_HISTORY_LENGTH) {
        this.undoActions.shift();
      }

      this.fire('history:undo:push', { actions: this.undoActions, lastAdded: snapshot });

      return this.undoActions;
    },
  });

  // initialize history handler
  fabric.history = new fabric.History();
};

Leave a Reply

Your email address will not be published. Required fields are marked *