Compare commits

..

2 Commits

Author SHA1 Message Date
fd1d55de5d Merge pull request 'feat(storage): remember where the user was last on the screen' (#7) from feat/location-memory into main
Reviewed-on: https://git.tristonarmstrong.com/Klectr/KSlab/pulls/7
2024-10-10 07:40:57 +00:00
ae17593cfb
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
2024-10-10 03:39:17 -04:00

View File

@ -14,25 +14,32 @@ export default function InfiniteCanvas() {
const isDarkTheme = useThemeDetector() const isDarkTheme = useThemeDetector()
useEffect(() => { useEffect(() => {
window.scrollTo({ const initPos = getInitialPosition(canvasDimentsion)
left: (canvasDimentsion.value.width / 2) - (window.innerWidth / 2), window.scrollTo(initPos)
top: (canvasDimentsion.value.height / 2) - (window.innerHeight / 2)
})
const updateDimensions = () => { const _updateDimensions = () => {
canvasDimentsion.value = { canvasDimentsion.value = {
width: Math.max(canvasDimentsion.value.width, window.innerWidth), width: Math.max(canvasDimentsion.value.width, window.innerWidth),
height: Math.max(canvasDimentsion.value.height, window.innerHeight), height: Math.max(canvasDimentsion.value.height, window.innerHeight),
} }
} }
updateDimensions() function _updatePosition() {
window.addEventListener("resize", updateDimensions) localStorage.setItem("pos", JSON.stringify({
left: window.scrollX,
top: window.scrollY
}))
}
_updateDimensions()
window.addEventListener("resize", _updateDimensions)
window.addEventListener("scrollend", _updatePosition)
notes.loadLocalStorage() notes.loadLocalStorage()
images.loadLocalStorage() images.loadLocalStorage()
return () => { 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
}