tabSync.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { STORAGE_KEYS } from "../app_constants";
  2. // in-memory state (this tab's current state) versions. Currently just
  3. // timestamps of the last time the state was saved to browser storage.
  4. const LOCAL_STATE_VERSIONS = {
  5. [STORAGE_KEYS.VERSION_DATA_STATE]: -1,
  6. [STORAGE_KEYS.VERSION_FILES]: -1,
  7. };
  8. type BrowserStateTypes = keyof typeof LOCAL_STATE_VERSIONS;
  9. export const isBrowserStorageStateNewer = (type: BrowserStateTypes) => {
  10. const storageTimestamp = JSON.parse(localStorage.getItem(type) || "-1");
  11. return storageTimestamp > LOCAL_STATE_VERSIONS[type];
  12. };
  13. export const updateBrowserStateVersion = (type: BrowserStateTypes) => {
  14. const timestamp = Date.now();
  15. try {
  16. localStorage.setItem(type, JSON.stringify(timestamp));
  17. LOCAL_STATE_VERSIONS[type] = timestamp;
  18. } catch (error) {
  19. console.error("error while updating browser state verison", error);
  20. }
  21. };
  22. export const resetBrowserStateVersions = () => {
  23. try {
  24. for (const key of Object.keys(
  25. LOCAL_STATE_VERSIONS,
  26. ) as BrowserStateTypes[]) {
  27. const timestamp = -1;
  28. localStorage.setItem(key, JSON.stringify(timestamp));
  29. LOCAL_STATE_VERSIONS[key] = timestamp;
  30. }
  31. } catch (error) {
  32. console.error("error while resetting browser state verison", error);
  33. }
  34. };