All files / src/pages/VisProgPage/visualProgrammingUI EditorUndoRedo.ts

0% Statements 0/30
0% Branches 0/8
0% Functions 0/9
0% Lines 0/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129                                                                                                                                                                                                                                                                 
import type {Edge, Node} from "@xyflow/react";
import type {StateCreator, StoreApi } from 'zustand/vanilla';
import type {FlowState} from "./VisProgTypes.tsx";
 
export type FlowSnapshot = {
  nodes: Node[];
  edges: Edge[];
}
 
/**
 * A reduced version of the flowState type,
 * This removes the functions that are provided by UndoRedo from the expected input type
 */
type BaseFlowState = Omit<FlowState, 'undo' | 'redo' | 'pushSnapshot' | 'beginBatchAction' | 'endBatchAction'>;
 
 
/**
 * UndoRedo is implemented as a middleware for the FlowState store,
 * this allows us to keep the undo redo logic separate from the flowState,
 * and thus from the internal editor logic
 *
 * Allows users to undo and redo actions in the visual programming editor
 *
 * @param {(set: StoreApi<FlowState>["setState"], get: () => FlowState, api: StoreApi<FlowState>) => BaseFlowState} config
 * @returns {StateCreator<FlowState>}
 * @constructor
 */
export const UndoRedo = (
  config: (
    set: StoreApi<FlowState>['setState'],
    get: () => FlowState,
    api: StoreApi<FlowState>
  ) => BaseFlowState ) : StateCreator<FlowState> => (set, get, api) => {
  let batchTimeout: number | null = null;
 
  /**
   * Captures the current state for
   *
   * @param {BaseFlowState} state - the current state of the editor
   * @returns {FlowSnapshot} - returns a snapshot of the current editor state
   */
  const getSnapshot = (state : BaseFlowState) : FlowSnapshot => (structuredClone({
    nodes: state.nodes,
    edges: state.edges
  }));
 
  const initialState = config(set, get, api);
 
  return {
    ...initialState,
 
    /**
     *  Adds a snapshot of the current state to the undo history
     */
    pushSnapshot: () => {
      const state = get();
      // we don't add new snapshots during an ongoing batch action
      if (!state.isBatchAction) {
        set({
          past: [...state.past, getSnapshot(state)],
          future: []
        });
      }
 
    },
 
    /**
     * Undoes the last action from the editor,
     * The state before undoing is added to the future for potential redoing
     */
    undo: () => {
      const state = get();
      if (!state.past.length) return;
 
      const snapshot = state.past.pop()!; // pop last snapshot
      const currentSnapshot: FlowSnapshot = getSnapshot(state);
 
      set({
        nodes: snapshot.nodes,
        edges: snapshot.edges,
      });
 
      state.future.push(currentSnapshot); // push current to redo
    },
 
    /**
     * redoes the last undone action,
     * The state before redoing is added to the past for potential undoing
     */
    redo: () => {
      const state = get();
      if (!state.future.length) return;
 
      const snapshot = state.future.pop()!; // pop last redo
      const currentSnapshot: FlowSnapshot = getSnapshot(state);
 
      set({
        nodes: snapshot.nodes,
        edges: snapshot.edges,
      });
 
      state.past.push(currentSnapshot); // push current to undo
    },
 
    /**
     * Begins a batched action
     *
     * An example of a batched action is dragging a node in the editor,
     * where we want the entire action of moving a node to a different position
     * to be covered by one undoable snapshot
     */
    beginBatchAction: () => {
      get().pushSnapshot();
      set({ isBatchAction: true });
      if (batchTimeout) clearTimeout(batchTimeout);
    },
 
    /**
     * Ends a batched action,
     * a very short timeout is used to prevent new snapshots from being added
     * until we are certain that the batch event is finished
     */
    endBatchAction: () => {
      batchTimeout = window.setTimeout(() => {
        set({ isBatchAction: false });
      }, 10);
    }
  }
}