All files / src/utils UndoRedoStore.ts

43.85% Statements 82/187
29.57% Branches 21/71
55.17% Functions 16/29
44.31% Lines 78/176

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 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491                                            33x 33x 33x 33x       33x 33x     33x     33x 33x 33x               140x 140x   140x                   140x                   140x                 33x 305470x     305470x             2944x 34x     34x 29x         34x 34x               69x         69x         69x     69x           69x 69x     69x       69x 69x 69x             2x   2x 2x   2x 2x 2x 2x 2x 2x                 2x   2x 2x   2x 2x 2x 2x 2x 2x           140x 107x 107x       140x 107x 107x             33x 2974x 2974x             5312x                                                                                                                                                                                                                                                                                                                                                                                                                                                     73x 73x 73x 73x   73x 73x             33x 33x 33x 7x 7x   7x 7x     7x 7x                                                                                     33x  
import SuperJSON from "superjson";
import { Command } from "@/types/commands";
 
interface SerializedStacks {
  undoStack: Command[];
  redoStack: Command[];
}
 
interface FlowsheetStacks {
  [flowsheetId: string]: SerializedStacks;
}
 
interface UndoRedoSnapshot {
  canUndo: boolean;
  canRedo: boolean;
  flowsheetId: string | null;
  isReady: boolean;
  undoStackSize: number;
  redoStackSize: number;
}
 
class UndoRedoStore {
  private subscribers = new Set<() => void>();
  private currentFlowsheet: string | null = null;
  private readonly maxStackSize: number = 100;
  private readonly storageKey: string = "ahuoraUndoRedoHistory";
  private stacksByFlowsheet: Map<
    string,
    { undoStack: Command[]; redoStack: Command[] }
  > = new Map();
  private initialized: boolean = false;
 
  // Cache the snapshot to prevent unnecessary re-renders
  private cachedSnapshot: UndoRedoSnapshot | null = null;
 
  constructor() {
    this.loadAllStacks();
    this.updateSnapshot(); // Initialize snapshot
    this.initialized = true;
  }
 
  /**
   * Update and cache the snapshot - follows React's immutable pattern
   * Only creates new snapshot if state actually changed
   */
  private updateSnapshot(): void {
    const undoStackSize = this.getUndoStackSize();
    const redoStackSize = this.getRedoStackSize();
 
    const newSnapshot: UndoRedoSnapshot = {
      canUndo: undoStackSize > 0,
      canRedo: redoStackSize > 0,
      flowsheetId: this.currentFlowsheet,
      isReady: this.currentFlowsheet !== null && this.initialized,
      undoStackSize,
      redoStackSize,
    };
 
    // Only update cached snapshot if it actually changed (React best practice)
    if (
      !this.cachedSnapshot ||
      this.cachedSnapshot.canUndo !== newSnapshot.canUndo ||
      this.cachedSnapshot.canRedo !== newSnapshot.canRedo ||
      this.cachedSnapshot.flowsheetId !== newSnapshot.flowsheetId ||
      this.cachedSnapshot.isReady !== newSnapshot.isReady ||
      this.cachedSnapshot.undoStackSize !== newSnapshot.undoStackSize ||
      this.cachedSnapshot.redoStackSize !== newSnapshot.redoStackSize
    ) {
      // Create new immutable snapshot
      this.cachedSnapshot = Object.freeze(newSnapshot);
    }
  }
 
  /**
   * Get current snapshot for React to render
   * This is the single source of truth for UI state
   * Returns immutable snapshot to comply with React's requirements
   */
  getSnapshot = (): UndoRedoSnapshot => {
    Iif (!this.cachedSnapshot) {
      this.updateSnapshot();
    }
    return this.cachedSnapshot!;
  };
 
  /**
   * Set the current flowsheet - this makes the store "ready"
   */
  setFlowsheet(id: string): void {
    if (this.currentFlowsheet !== id) {
      this.currentFlowsheet = id;
 
      // Initialize stacks for this flowsheet if they don't exist
      if (!this.stacksByFlowsheet.has(id)) {
        this.stacksByFlowsheet.set(id, {
          undoStack: [],
          redoStack: [],
        });
      }
      this.updateSnapshot();
      this.emit(); // Notify React of state change
    }
  }
 
  /**
   * Add command - only works if flowsheet is set
   */
  addCommand(cmd: Command): void {
    Iif (!this.currentFlowsheet) {
      console.warn("[UndoRedoStore] Cannot add command: No flowsheet set");
      return; // Prevents race condition
    }
 
    Iif (!cmd?.type) {
      console.error("[UndoRedoStore] Invalid command: missing type", cmd);
      return;
    }
 
    const stacks = this.stacksByFlowsheet.get(this.currentFlowsheet)!;
 
    // Create immutable command with timestamp
    const commandWithTimestamp: Command = Object.freeze({
      ...cmd,
      timestamp: Date.now(),
    });
 
    // Update stacks immutably
    stacks.undoStack.push(commandWithTimestamp);
    stacks.redoStack = []; // Clear redo stack
 
    // Enforce max stack size
    Iif (stacks.undoStack.length > this.maxStackSize) {
      stacks.undoStack.shift();
    }
 
    this.saveAllStacks();
    this.updateSnapshot();
    this.emit(); // Live update to React
  }
 
  /**
   * Undo operation - returns command for execution
   */
  undo(): Command | null {
    Iif (!this.currentFlowsheet) return null;
 
    const stacks = this.stacksByFlowsheet.get(this.currentFlowsheet)!;
    const command = stacks.undoStack.pop();
 
    if (command) {
      stacks.redoStack.push(command);
      this.saveAllStacks();
      this.updateSnapshot();
      this.emit(); // Live update to React
      return command;
    }
    return null;
  }
 
  /**
   * Redo operation - returns command for execution
   */
  redo(): Command | null {
    Iif (!this.currentFlowsheet) return null;
 
    const stacks = this.stacksByFlowsheet.get(this.currentFlowsheet)!;
    const command = stacks.redoStack.pop();
 
    if (command) {
      stacks.undoStack.push(command);
      this.saveAllStacks();
      this.updateSnapshot();
      this.emit(); // Live update to React
      return command;
    }
    return null;
  }
 
  private getUndoStackSize(): number {
    if (!this.currentFlowsheet) return 0;
    const stacks = this.stacksByFlowsheet.get(this.currentFlowsheet);
    return stacks ? stacks.undoStack.length : 0;
  }
 
  private getRedoStackSize(): number {
    if (!this.currentFlowsheet) return 0;
    const stacks = this.stacksByFlowsheet.get(this.currentFlowsheet);
    return stacks ? stacks.redoStack.length : 0;
  }
 
  /**
   * Subscribe to changes - used by useSyncExternalStore
   * Returns unsubscribe function as required by React
   */
  subscribe = (callback: () => void): (() => void) => {
    this.subscribers.add(callback);
    return () => this.subscribers.delete(callback);
  };
 
  /**
   * Notify all subscribers of state changes
   */
  private emit(): void {
    this.subscribers.forEach((cb) => cb());
  }
 
  // ---- Additional Store Methods ----
 
  /**
   * Reset stacks for current flowsheet
   */
  resetStacks(): void {
    Iif (!this.currentFlowsheet) return;
 
    const stacks = this.stacksByFlowsheet.get(this.currentFlowsheet);
    Iif (stacks) {
      stacks.undoStack = [];
      stacks.redoStack = [];
      this.saveAllStacks();
      this.updateSnapshot();
      this.emit();
    }
  }
 
  /**
   * Remove a flowsheet completely
   */
  removeFlowsheet(flowsheetId: string): void {
    this.stacksByFlowsheet.delete(flowsheetId);
 
    // If this was the current flowsheet, clear it
    Iif (this.currentFlowsheet === flowsheetId) {
      this.currentFlowsheet = null;
    }
 
    this.saveAllStacks();
    this.updateSnapshot();
    this.emit();
  }
 
  /**
   * Restore a command that failed to undo
   */
  restoreFailedUndo(command: Command): void {
    Iif (!this.currentFlowsheet) return;
 
    const stacks = this.stacksByFlowsheet.get(this.currentFlowsheet);
    Iif (stacks) {
      // Remove from redo stack and put back in undo stack
      const redoIndex = stacks.redoStack.findIndex(
        (cmd) => cmd.timestamp === command.timestamp,
      );
      Iif (redoIndex !== -1) {
        stacks.redoStack.splice(redoIndex, 1);
        stacks.undoStack.push(command);
        this.saveAllStacks();
        this.updateSnapshot();
        this.emit();
      }
    }
  }
 
  /**
   * Restore a command that failed to redo
   */
  restoreFailedRedo(command: Command): void {
    Iif (!this.currentFlowsheet) return;
 
    const stacks = this.stacksByFlowsheet.get(this.currentFlowsheet);
    Iif (stacks) {
      // Remove from undo stack and put back in redo stack
      const undoIndex = stacks.undoStack.findIndex(
        (cmd) => cmd.timestamp === command.timestamp,
      );
      Iif (undoIndex !== -1) {
        stacks.undoStack.splice(undoIndex, 1);
        stacks.redoStack.push(command);
        this.saveAllStacks();
        this.updateSnapshot();
        this.emit();
      }
    }
  }
 
  /**
   * Intelligently invalidate commands that reference deleted objects
   * This accounts for soft delete behavior, custom endpoints, and complex operations
   * Only invalidates commands that would truly fail if executed
   */
  invalidateCommandsForObjects(deletedObjectIds: number[]): void {
    Iif (!this.currentFlowsheet) return;
 
    const stacks = this.stacksByFlowsheet.get(this.currentFlowsheet);
    Iif (!stacks) return;
 
    const deletedIdSet = new Set(deletedObjectIds);
    let invalidatedCount = 0;
 
    // More sophisticated command analysis
    const shouldInvalidateCommand = (cmd: Command): boolean => {
      switch (cmd.type) {
        case "MOVE": {
          // Only invalidate MOVE commands if the PRIMARY object is deleted
          // Don't invalidate for group object references since those might be soft-deleted
          Iif (
            deletedIdSet.has(cmd.objectId) ||
            deletedIdSet.has(cmd.graphicObjectId)
          ) {
            invalidatedCount++;
            return true;
          }
          return false;
        }
 
        case "DELETE":
          // DELETE commands should NOT be invalidated - they may need to be undone
          // even if the objects are currently deleted (soft delete scenario)
          return false;
 
        case "CONNECT":
        case "DISCONNECT": {
          // For connection commands, only invalidate if ALL referenced objects are hard-deleted
          // This allows for partial restoration scenarios
          const connectionObjectIds = [cmd.objectId1, cmd.objectId2];
          const allObjectsDeleted = connectionObjectIds.every((id) =>
            deletedIdSet.has(id),
          );
 
          Iif (allObjectsDeleted) {
            invalidatedCount++;
            return true;
          }
          return false;
        }
 
        case "MERGE_STREAMS": {
          // For merge commands, only invalidate if BOTH streams are deleted
          // Single stream deletion might still allow undo (soft delete scenario)
          const mergeCmd = cmd as Command & {
            stream1Id?: number;
            stream2Id?: number;
          };
          Iif (mergeCmd.stream1Id && mergeCmd.stream2Id) {
            const bothStreamsDeleted =
              deletedIdSet.has(mergeCmd.stream1Id) &&
              deletedIdSet.has(mergeCmd.stream2Id);
            Iif (bothStreamsDeleted) {
              invalidatedCount++;
              return true;
            }
          }
          return false;
        }
 
        default:
          // For unknown command types, be conservative and don't invalidate
          console.warn(
            `[UndoRedoStore] Unknown command type for invalidation: ${(cmd as Command).type}`,
          );
          return false;
      }
    };
 
    // Apply filtering to both stacks
    const originalUndoLength = stacks.undoStack.length;
    const originalRedoLength = stacks.redoStack.length;
 
    stacks.undoStack = stacks.undoStack.filter(
      (cmd) => !shouldInvalidateCommand(cmd),
    );
    stacks.redoStack = stacks.redoStack.filter(
      (cmd) => !shouldInvalidateCommand(cmd),
    );
 
    if (invalidatedCount > 0) {
      this.saveAllStacks();
      this.updateSnapshot();
      this.emit();
    } else {
      // console.log(`[UndoRedoStore] Smart invalidation: No commands needed to be removed for objects:`, deletedObjectIds);
    }
  }
 
  /**
   * Validate if a command can still be executed (for soft delete scenarios)
   * This can be called before executing commands to provide better error handling
   */
  canExecuteCommand(command: Command): {
    canExecute: boolean;
    reason?: string;
  } {
    switch (command.type) {
      case "MOVE":
        // For move commands, we need to check if the graphic object still exists
        // This is handled in the CommandExecutor with pre-validation
        return { canExecute: true };
 
      case "DELETE":
        // Delete commands can usually be undone via restore operations
        return { canExecute: true };
 
      case "CONNECT":
      case "DISCONNECT":
        // Connection commands depend on port/stream availability
        // Better to attempt and handle gracefully than pre-validate
        return { canExecute: true };
 
      case "MERGE_STREAMS":
        // Merge commands have complex restoration logic
        // Let the executor handle validation
        return { canExecute: true };
 
      default:
        return {
          canExecute: false,
          reason: `Unknown command type: ${(command as Command).type}`,
        };
    }
  }
 
  // ---- Storage Implementation ----
  private saveAllStacks(): void {
    try {
      const flowsheetsObject: FlowsheetStacks = {};
      this.stacksByFlowsheet.forEach((stacks, flowsheetId) => {
        flowsheetsObject[flowsheetId] = stacks;
      });
      const serializedData = SuperJSON.stringify(flowsheetsObject);
      localStorage.setItem(this.storageKey, serializedData);
    } catch (error) {
      console.warn("[UndoRedoStore] Failed to save to localStorage:", error);
    }
  }
 
  private loadAllStacks(): void {
    try {
      const serializedData = localStorage.getItem(this.storageKey);
      if (serializedData) {
        const allStacksData = SuperJSON.parse<FlowsheetStacks>(serializedData);
        this.stacksByFlowsheet.clear();
 
        for (const flowsheetId in allStacksData) {
          if (
            Object.prototype.hasOwnProperty.call(allStacksData, flowsheetId)
          ) {
            const stacks = allStacksData[flowsheetId];
            this.stacksByFlowsheet.set(flowsheetId, {
              undoStack: stacks.undoStack || [],
              redoStack: stacks.redoStack || [],
            });
          }
        }
      }
    } catch (error) {
      console.warn("[UndoRedoStore] Failed to load from localStorage:", error);
      this.stacksByFlowsheet.clear();
    }
  }
 
  // ---- Debug and Utility Methods ----
  getDebugInfo(): {
    currentFlowsheet: string | null;
    undoCount: number;
    redoCount: number;
    lastCommand?: Command;
    allFlowsheets: string[];
  } {
    const undoCount = this.getUndoStackSize();
    const redoCount = this.getRedoStackSize();
    let lastCommand: Command | undefined;
 
    Iif (this.currentFlowsheet) {
      const stacks = this.stacksByFlowsheet.get(this.currentFlowsheet);
      Iif (stacks && stacks.undoStack.length > 0) {
        lastCommand = stacks.undoStack[stacks.undoStack.length - 1];
      }
    }
 
    return {
      currentFlowsheet: this.currentFlowsheet,
      undoCount,
      redoCount,
      lastCommand,
      allFlowsheets: Array.from(this.stacksByFlowsheet.keys()),
    };
  }
}
 
// Export singleton instance
export const undoRedoStore = new UndoRedoStore();