From ae17593cfbd33be64fc74c2ae81c0926945ebf69 Mon Sep 17 00:00:00 2001 From: Triston Armstrong Date: Thu, 10 Oct 2024 03:39:17 -0400 Subject: [PATCH] feat(storage): remember where the user was last on the screen When a user refreshes the page, it will now scroll the users position to the position they were when last on this page --- src/components/InfinateCanvas.tsx | 52 ++++++++++++++++++++++++++----- 1 file changed, 44 insertions(+), 8 deletions(-) diff --git a/src/components/InfinateCanvas.tsx b/src/components/InfinateCanvas.tsx index 7d5f1a7..5a7eb0c 100644 --- a/src/components/InfinateCanvas.tsx +++ b/src/components/InfinateCanvas.tsx @@ -14,25 +14,32 @@ export default function InfiniteCanvas() { const isDarkTheme = useThemeDetector() useEffect(() => { - window.scrollTo({ - left: (canvasDimentsion.value.width / 2) - (window.innerWidth / 2), - top: (canvasDimentsion.value.height / 2) - (window.innerHeight / 2) - }) + const initPos = getInitialPosition(canvasDimentsion) + window.scrollTo(initPos) - const updateDimensions = () => { + const _updateDimensions = () => { canvasDimentsion.value = { width: Math.max(canvasDimentsion.value.width, window.innerWidth), height: Math.max(canvasDimentsion.value.height, window.innerHeight), } } - updateDimensions() - window.addEventListener("resize", updateDimensions) + function _updatePosition() { + localStorage.setItem("pos", JSON.stringify({ + left: window.scrollX, + top: window.scrollY + })) + } + + _updateDimensions() + window.addEventListener("resize", _updateDimensions) + window.addEventListener("scrollend", _updatePosition) notes.loadLocalStorage() images.loadLocalStorage() return () => { - window.removeEventListener("resize", updateDimensions) + window.removeEventListener("resize", _updateDimensions) + window.removeEventListener("scrollend", _updatePosition) } }, []) @@ -72,3 +79,32 @@ export default function InfiniteCanvas() { ) } + +interface ScrollToOptions extends ScrollOptions { + left?: number; + top?: number; +} + +function getInitialPosition(canvasDimensions: typeof canvasDimentsion): ScrollToOptions { + const defaultScroll: ScrollToOptions = { + left: (canvasDimensions.value.width / 2) - (window.innerWidth / 2), + top: (canvasDimensions.value.height / 2) - (window.innerHeight / 2) + } + + let initPosition; + try { + initPosition = JSON.parse(localStorage.getItem("pos") ?? "") + } catch (e) { + console.error("no local storage for pos") + } + + if (!initPosition) return defaultScroll + return initPosition +} + + + + + + +