All files / src/hooks useAutoSave.js

87.14% Statements 61/70
73.07% Branches 19/26
92.85% Functions 13/14
86.36% Lines 57/66

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                2x 2x         2x                                                         2x 4x 4x 84x 40x     4x 4x 4x                   26x 26x         26x 5x   4x 4x 4x 4x 4x 4x                   26x 7x 7x 7x   5x     4x 1x 1x     3x   1x 1x             26x 2x 2x 2x                   26x 9x           26x 3x 3x   2x 2x       26x 26x 1x       1x     25x 2x         25x 25x 25x           26x 26x           26x 26x     26x                      
/**
 * @fileoverview Auto-save Hook
 * @description Automatically saves and loads simulation state to localStorage
 * @module hooks/useAutoSave
 */
 
import { useEffect, useCallback, useRef } from 'react';
 
const STORAGE_KEY = 'molecular-dynamics-autosave';
const AUTO_SAVE_INTERVAL = 30000; // 30 seconds
 
/**
 * Fields to save (exclude transient/computed fields)
 */
const SAVEABLE_FIELDS = [
  'atoms',
  'bonds',
  'nextAtomId',
  'playerId',
  'isPaused',
  'targetTemperature',
  'zoom',
  'pan',
  'showBonds',
  'showVelocityVectors',
  'showAtomLabels',
  'showBondLengths',
  'boundaryCondition',
  'timeStepMultiplier',
  'thermostatEnabled',
  'thermostatTau',
  'enableCoulomb',
  'colorByVelocity',
  'showMotionTrails',
  'trailLength',
  'theme',
];
 
/**
 * Extract saveable state from simulation
 * @param {Object} state - Full simulation state
 * @returns {Object} State subset safe for saving
 */
const extractSaveableState = (state) => {
  const saveState = {};
  SAVEABLE_FIELDS.forEach(field => {
    if (state[field] !== undefined) {
      saveState[field] = state[field];
    }
  });
  saveState.savedAt = Date.now();
  saveState.version = '1.0.0';
  return saveState;
};
 
/**
 * Auto-save hook for simulation state persistence
 * @param {Object} simulation - Current simulation state
 * @param {Function} dispatch - Dispatch function
 * @returns {Object} Auto-save controls
 */
export function useAutoSave(simulation, dispatch) {
  const lastSaveRef = useRef(null);
  const intervalRef = useRef(null);
 
  /**
   * Save current state to localStorage
   */
  const saveState = useCallback(() => {
    if (!simulation.autoSaveEnabled) return false;
    
    try {
      const saveData = extractSaveableState(simulation);
      localStorage.setItem(STORAGE_KEY, JSON.stringify(saveData));
      lastSaveRef.current = Date.now();
      dispatch({ type: 'SET_LAST_AUTO_SAVE', payload: lastSaveRef.current });
      return true;
    } catch (error) {
      console.warn('Auto-save failed:', error);
      return false;
    }
  }, [simulation, dispatch]);
 
  /**
   * Load state from localStorage
   */
  const loadState = useCallback(() => {
    try {
      const saved = localStorage.getItem(STORAGE_KEY);
      if (!saved) return null;
      
      const data = JSON.parse(saved);
      
      // Validate version compatibility
      if (!data.version || !data.atoms) {
        console.warn('Invalid save data format');
        return null;
      }
      
      return data;
    } catch (error) {
      console.warn('Load state failed:', error);
      return null;
    }
  }, []);
 
  /**
   * Clear saved state
   */
  const clearSavedState = useCallback(() => {
    try {
      localStorage.removeItem(STORAGE_KEY);
      return true;
    } catch (error) {
      console.warn('Clear save failed:', error);
      return false;
    }
  }, []);
 
  /**
   * Check if saved state exists
   */
  const hasSavedState = useCallback(() => {
    return localStorage.getItem(STORAGE_KEY) !== null;
  }, []);
 
  /**
   * Restore simulation from saved state
   */
  const restoreState = useCallback(() => {
    const savedState = loadState();
    if (!savedState) return false;
    
    dispatch({ type: 'LOAD_SIMULATION_STATE', payload: savedState });
    return true;
  }, [loadState, dispatch]);
 
  // Set up auto-save interval
  useEffect(() => {
    if (!simulation.autoSaveEnabled) {
      Iif (intervalRef.current) {
        clearInterval(intervalRef.current);
        intervalRef.current = null;
      }
      return;
    }
 
    intervalRef.current = setInterval(() => {
      Iif (!simulation.isPaused && simulation.atoms.length > 0) {
        saveState();
      }
    }, AUTO_SAVE_INTERVAL);
 
    return () => {
      Eif (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, [simulation.autoSaveEnabled, simulation.isPaused, simulation.atoms.length, saveState]);
 
  // Save on page unload
  useEffect(() => {
    const handleBeforeUnload = () => {
      if (simulation.autoSaveEnabled && simulation.atoms.length > 0) {
        saveState();
      }
    };
 
    window.addEventListener('beforeunload', handleBeforeUnload);
    return () => window.removeEventListener('beforeunload', handleBeforeUnload);
  }, [simulation.autoSaveEnabled, simulation.atoms.length, saveState]);
 
  return {
    saveState,
    loadState,
    clearSavedState,
    hasSavedState,
    restoreState,
    lastSave: lastSaveRef.current,
  };
}
 
export default useAutoSave;