SessionRestoreDim.jsx 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import useAsyncEffect from "use-async-effect";
  2. import { useBoardPosition } from "react-sync-board";
  3. import useSession from "../hooks/useSession";
  4. import useLocalStorage from "../hooks/useLocalStorage";
  5. // 150 days max for session dim
  6. const MAX_SESSION_DIM_RETENTION = 1000 * 60 * 60 * 24 * 150;
  7. export const SessionRestoreDim = () => {
  8. const { sessionLoaded, sessionId, getSession } = useSession();
  9. const [sessionDimensions, setSessionDimensions] = useLocalStorage(
  10. "sessionDimensions",
  11. {}
  12. );
  13. const { getDim, setDim, zoomToExtent } = useBoardPosition();
  14. /**
  15. * Load the previous dimension for this session if exists
  16. */
  17. useAsyncEffect(
  18. async (isMounted) => {
  19. if (sessionLoaded) {
  20. if (sessionDimensions[sessionId]) {
  21. const dim = {
  22. ...sessionDimensions[sessionId],
  23. timestamp: undefined,
  24. };
  25. setTimeout(() => {
  26. if (isMounted) {
  27. setDim(() => dim);
  28. }
  29. }, 500);
  30. } else {
  31. const session = await getSession();
  32. if (!isMounted) return;
  33. if (session.board.initialBoardPosition) {
  34. setTimeout(() => {
  35. zoomToExtent(session.board.initialBoardPosition);
  36. }, 500);
  37. }
  38. }
  39. const now = Date.now();
  40. const newDim = Object.fromEntries(
  41. Object.entries(sessionDimensions).filter(([, { timestamp }]) => {
  42. return timestamp && now - timestamp < MAX_SESSION_DIM_RETENTION;
  43. })
  44. );
  45. setSessionDimensions(newDim);
  46. }
  47. // We want to set dimension only when session is loaded
  48. // eslint-disable-next-line react-hooks/exhaustive-deps
  49. },
  50. [sessionLoaded]
  51. );
  52. /**
  53. * Save board dimension in localstorage every 2 seconds for next visit
  54. */
  55. useAsyncEffect((isMounted) => {
  56. const interval = setInterval(async () => {
  57. const currentDim = await getDim();
  58. if (isMounted) {
  59. setSessionDimensions((prev) => ({
  60. ...prev,
  61. [sessionId]: { ...currentDim, timestamp: Date.now() },
  62. }));
  63. }
  64. }, 2000);
  65. return () => clearInterval(interval);
  66. }, []);
  67. return null;
  68. };
  69. export default SessionRestoreDim;