Skip to content

Commit

Permalink
feat(compare): add layoutSettings state persistence (#1519)
Browse files Browse the repository at this point in the history
  • Loading branch information
dgrebb committed Jan 18, 2024
1 parent 43b55e5 commit 68d3ed8
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 2 deletions.
2 changes: 1 addition & 1 deletion compare/output/index_bundle.js

Large diffs are not rendered by default.

64 changes: 63 additions & 1 deletion compare/src/store.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,43 @@
import { createStore } from 'redux';
import rootReducer from './reducers';

/**
* Parses a JSON string from local storage and handles any errors.
*
* This function attempts to parse a JSON string provided in `localStorageItem`.
* If the parsing fails (typically due to corrupt or invalid JSON data),
* it logs the error, warns the user, and removes the corrupted item from
* local storage. If parsing is successful, it returns the parsed object.
* In the case of an error, it returns `false`.
*
* @param {string} localStorageItem - The JSON string to parse, typically retrieved from local storage.
* @returns {object|boolean} The parsed JSON object, or `false` if settings aren't set or parsing fails.
*/
function parseLocalStorage (localStorageItem) {
let data;
try {
data = JSON.parse(localStorageItem);
} catch (error) {
console.error(error);
console.warn('BackstopJS LocalStorage settings appear to be corrupted. Let me fix that for you.');
localStorage.removeItem('backstopjs');
data = false;
}
return data;
}

/**
* Retrieves the state from local storage, if available.
* @returns {object|boolean} The persisted state object or false if not available.
*/
const localState = localStorage.getItem('backstopjs');
const persistedState = localState
? parseLocalStorage(localState)
: false;

/**
* Default state for the Redux store.
*/
const defaultState = {
suiteInfo: {
testSuiteName: window.tests.testSuite,
Expand All @@ -24,10 +61,35 @@ const defaultState = {
}
};

/**
* Merges persisted state with default state if available, otherwise uses default state.
*/
const state = persistedState
? {
...defaultState,
...persistedState
}
: defaultState;

/**
* Creates the Redux store with root reducer, initial state, and devtools extension.
* TODO: Consider using Redux Toolkit for more efficient and modern state management.
*/
const store = createStore(
rootReducer,
defaultState,
state,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

/**
* Subscribes to store changes to persist layout settings in local storage.
*/
store.subscribe(function () {
const layoutSettings = store.getState().layoutSettings;
const localStateItems = JSON.stringify({
layoutSettings
});
localStorage.setItem('backstopjs', localStateItems);
});

export default store;

0 comments on commit 68d3ed8

Please sign in to comment.