All files / src/pages/VisProgPage/visualProgrammingUI VisProgStores.tsx

0% Statements 0/102
0% Branches 0/26
0% Functions 0/42
0% Lines 0/81

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 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
import { create } from 'zustand';
import {
  applyNodeChanges,
  applyEdgeChanges,
  addEdge,
  reconnectEdge,
  type Node,
  type Edge,
  type XYPosition,
} from '@xyflow/react';
import '@xyflow/react/dist/style.css';
import type { FlowState } from './VisProgTypes';
import {
  NodeDefaults,
  NodeConnections as NodeCs,
  NodeDisconnections as NodeDs,
  NodeDeletes
} from './NodeRegistry';
import { UndoRedo } from "./EditorUndoRedo.ts";
 
 
/**
 * A Function to create a new node with the correct default data and properties.
 *
 * @param id - The unique ID of the node.
 * @param type - The type of node to create (must exist in NodeDefaults).
 * @param position - The XY position of the node in the flow canvas.
 * @param data - The data object to initialize the node with.
 * @param deletable - Optional flag to indicate if the node can be deleted (can be deleted by default).
 * @returns A fully initialized Node object ready to be added to the flow.
 */
function createNode(id: string, type: string, position: XYPosition, data: Record<string, unknown>, deletable?: boolean) {
    const defaultData = NodeDefaults[type as keyof typeof NodeDefaults]
    return {
      id,
      type,
      position,
      deletable,
      data: {
        ...JSON.parse(JSON.stringify(defaultData)),
        ...data,
      },
    }
}
 
  //* Initial nodes, created by using createNode. */
  // Start and End don't need to apply the UUID, since they are technically never compiled into a program.
  const startNode = createNode('start', 'start', {x: 110, y: 100}, {label: "Start"}, false)
  const endNode = createNode('end', 'end', {x: 590, y: 100}, {label: "End"}, false)
  const initialPhaseNode = createNode(crypto.randomUUID(), 'phase', {x:235, y:100}, {label: "Phase 1", children : [], isFirstPhase: false, nextPhaseId: null})
 
  const initialNodes : Node[] = [startNode, endNode, initialPhaseNode,];
 
// Initial edges, leave empty as setting initial edges...
// ...breaks logic that is dependent on connection events
const initialEdges: Edge[] = [];
 
 
/**
 * useFlowStore contains the implementation for all editor functionality
 * and stores the current state of the visual programming editor
 *
 *  * Provides:
 * - Node and edge state management
 * - Node creation, deletion, and updates
 * - Custom connection handling via NodeConnects
 * - Edge reconnection handling
 * - Undo Redo functionality through custom middleware
 */
const useFlowStore = create<FlowState>(UndoRedo((set, get) => ({
  nodes: initialNodes,
  edges: initialEdges,
  edgeReconnectSuccessful: true,
  scrollable: true,
 
  /**
   * handles changing the scrollable state of the editor,
   * this is used to control if scrolling is captured by the editor
   * or if it's available to other components within the reactFlowProvider
   * @param {boolean} val - the desired state
   */
  setScrollable: (val) => set({scrollable: val}),
 
   /**
   * Handles changes to nodes triggered by ReactFlow.
   */
  onNodesChange: (changes) => set({nodes: applyNodeChanges(changes, get().nodes)}),
 
  onNodesDelete: (nodes) => nodes.forEach(node => get().unregisterNodeRules(node.id)),
 
  onEdgesDelete: (edges) => {
    // we make sure any affected nodes get updated to reflect removal of edges
    edges.forEach((edge) => {
        const nodes = get().nodes;
 
        const sourceNode = nodes.find((n) => n.id == edge.source);
        const targetNode = nodes.find((n) => n.id == edge.target);
 
        if (sourceNode) { NodeDs.Sources[sourceNode.type as keyof typeof NodeDs.Sources](sourceNode, edge.target); }
        if (targetNode) { NodeDs.Targets[targetNode.type as keyof typeof NodeDs.Targets](targetNode, edge.source); }
      });
  },
  /**
   * Handles changes to edges triggered by ReactFlow.
   */
  onEdgesChange: (changes) => {
    set({ edges: applyEdgeChanges(changes, get().edges) })
  },
 
  /**
   * Handles creating a new connection between nodes.
   * Updates edges and calls the node-specific connection functions.
   */
  onConnect: (connection) => {
    get().pushSnapshot();
    set({edges: addEdge(connection, get().edges)});
 
    // We make sure to perform any required data updates on the newly connected nodes
    const nodes = get().nodes;
 
    const sourceNode = nodes.find((n) => n.id == connection.source);
    const targetNode = nodes.find((n) => n.id == connection.target);
 
    if (sourceNode) { NodeCs.Sources[sourceNode.type as keyof typeof NodeCs.Sources](sourceNode, connection.target); }
    if (targetNode) { NodeCs.Targets[targetNode.type as keyof typeof NodeCs.Targets](targetNode, connection.source); }
  },
 
  /**
   * Handles reconnecting an edge between nodes.
   */
  onReconnect: (oldEdge, newConnection) => {
    get().edgeReconnectSuccessful = true;
    set({ edges: reconnectEdge(oldEdge, newConnection, get().edges) });
 
    // We make sure to perform any required data updates on the newly reconnected nodes
    const nodes = get().nodes;
 
    const oldSourceNode = nodes.find((n) => n.id == oldEdge.source)!;
    const oldTargetNode = nodes.find((n) => n.id == oldEdge.target)!;
    const newSourceNode = nodes.find((n) => n.id == newConnection.source)!;
    const newTargetNode = nodes.find((n) => n.id == newConnection.target)!;
 
    if (oldSourceNode === newSourceNode && oldTargetNode === newTargetNode) return;
 
    NodeCs.Sources[newSourceNode.type as keyof typeof NodeCs.Sources](newSourceNode, newConnection.target);
    NodeCs.Targets[newTargetNode.type as keyof typeof NodeCs.Targets](newTargetNode, newConnection.source);
 
    NodeDs.Sources[oldSourceNode.type as keyof typeof NodeDs.Sources](oldSourceNode, oldEdge.target);
    NodeDs.Targets[oldTargetNode.type as keyof typeof NodeDs.Targets](oldTargetNode, oldEdge.source);
  },
 
  onReconnectStart: () => {
    get().pushSnapshot();
    set({ edgeReconnectSuccessful: false })
  },
 
  /**
   * handles potential dropping (deleting) of an edge
   * if it is not reconnected to a node after detaching it
   *
   * @param _evt - the event
   * @param edge - the described edge
   */
  onReconnectEnd: (_evt, edge) => {
    if (!get().edgeReconnectSuccessful) {
      // delete the edge from the flowState
      set({ edges: get().edges.filter((e) => e.id !== edge.id) });
 
      // update node data to reflect the dropped edge
      const nodes = get().nodes;
 
      const sourceNode = nodes.find((n) => n.id == edge.source)!;
      const targetNode = nodes.find((n) => n.id == edge.target)!;
 
      NodeDs.Sources[sourceNode.type as keyof typeof NodeDs.Sources](sourceNode, edge.target);
      NodeDs.Targets[targetNode.type as keyof typeof NodeDs.Targets](targetNode, edge.source);
    }
    set({ edgeReconnectSuccessful: true });
  },
 
  /**
   * Deletes a node by ID, respecting NodeDeletes rules.
   * Also removes all edges connected to that node.
   */
  deleteNode: (nodeId) => {
    get().pushSnapshot();
 
    // Let's find our node to check if they have a special deletion function
    const ourNode = get().nodes.find((n)=>n.id==nodeId);
    const ourFunction = Object.entries(NodeDeletes).find(([t])=>t==ourNode?.type)?.[1]
    
    // If there's no function, OR, our function tells us we can delete it, let's do so...
    if (ourFunction == undefined || ourFunction()) {
      set({
      nodes: get().nodes.filter((n) => n.id !== nodeId),
      edges: get().edges.filter((e) => e.source !== nodeId && e.target !== nodeId),
      })}
  },
 
  /**
   * Replaces the entire nodes array in the store.
   */
  setNodes: (nodes) => set({ nodes }),
 
  /**
   * Replaces the entire edges array in the store.
   */
  setEdges: (edges) => set({ edges }),
 
  /**
   * Updates the data of a node by merging new data with existing data.
   */
  updateNodeData: (nodeId, data) => {
    get().pushSnapshot();
    set({
      nodes: get().nodes.map((node) => {
        if (node.id === nodeId) {
          node = { ...node, data: { ...node.data, ...data }};
        }
        return node;
      }),
    });
  },
 
  /**
   * Adds a new node to the flow store.
   */
  addNode: (node: Node) => {
    get().pushSnapshot();
    set({ nodes: [...get().nodes, node] });
  },
 
  // undo redo default values
  past: [],
  future: [],
  isBatchAction: false,
 
  // handleRuleRegistry definitions
  /**
   * stores registered rules for handle connection validation
   */
  ruleRegistry: new Map(),
 
  /**
   * gets the rules registered by that handle described by the given node and handle ids
   *
   * @param {string} targetNodeId
   * @param {string} targetHandleId
   * @returns {HandleRule[]}
   */
  getTargetRules: (targetNodeId, targetHandleId) => {
    const key = `${targetNodeId}:${targetHandleId}`;
    const rules = get().ruleRegistry.get(key);
 
    // helper function that handles a situation where no rules were registered
    const missingRulesResponse = () => {
      console.warn(
        `No rules were registered for the following handle "${key}"!
          returning and empty handleRule[] to avoid crashing`);
      return []
    }
 
    return rules
      ? rules
      : missingRulesResponse()
  },
 
  /**
   * registers a handle's connection rules
   *
   * @param {string} nodeId
   * @param {string} handleId
   * @param {HandleRule[]} rules
   */
  registerRules: (nodeId, handleId, rules) => {
      const registry = get().ruleRegistry;
      registry.set(`${nodeId}:${handleId}`, rules);
      set({ ruleRegistry: registry }) ;
  },
 
  /**
   * unregisters a handles connection rules
   *
   * @param {string} nodeId
   * @param {string} handleId
   */
  unregisterHandleRules: (nodeId, handleId) => {
    set( () => {
      const registry = get().ruleRegistry;
      registry.delete(`${nodeId}:${handleId}`);
      return { ruleRegistry: registry };
    })
  },
 
  /**
   * unregisters connection rules for all handles on the given node
   * used for cleaning up rules on node deletion
   *
   * @param {string} nodeId
   */
  unregisterNodeRules: (nodeId) => {
    set(() => {
      const registry = get().ruleRegistry;
      registry.forEach((_,key) => {
        if (key.startsWith(`${nodeId}:`)) registry.delete(key)
      })
      return { ruleRegistry: registry };
    })
  }
  }))
);
 
export default useFlowStore;