1 "use client"
2
3 import { usePathname } from "next/navigation"
4 import { useScrollController } from "../use-scroll-utils"
5 import { useEffect, useState } from "react"
6 import { getScrolledTop, isElmWindow } from "../../utils"
7
8 export const usePageScrollManager = () => {
9 const pathname = usePathname()
10 const { scrollableElement } = useScrollController()
11 const [checkedPageReload, setCheckedPageReload] = useState(false)
12
13 const isPageReloaded = () =>
14 (window.performance.navigation &&
15 window.performance.navigation.type === 1) ||
16 window.performance
17 .getEntriesByType("navigation")
18 .map((nav) => (nav as PerformanceNavigationTiming).type)
19 .includes("reload")
20
21 const tryToScroll = () => {
22 if (getScrolledTop(scrollableElement) !== 0 && !location.hash) {
23 scrollableElement?.scrollTo({
24 top: 0,
25 })
26 } else if (location.hash) {
27 // retrieve and scroll to element
28 const targetElm =
29 scrollableElement && typeof document !== "undefined"
30 ? document.getElementById(location.hash.replace("#", ""))
31 : undefined
32
33 scrollableElement?.scrollTo({
34 top: targetElm ? targetElm.offsetTop : 0,
35 })
36 }
37 }
38
39 useEffect(() => {
40 if (checkedPageReload) {
41 setCheckedPageReload(false)
42 }
43 }, [pathname])
44
45 useEffect(() => {
46 if (!scrollableElement || checkedPageReload) {
47 return
48 }
49
50 if (isPageReloaded()) {
51 const loadedScrollPosition = localStorage.getItem("scrollPos")
52 if (loadedScrollPosition) {
53 scrollableElement?.scrollTo({
54 top: parseInt(loadedScrollPosition),
55 })
56 localStorage.removeItem("scrollPos")
57 } else {
58 tryToScroll()
59 }
60 } else {
61 tryToScroll()
62 }
63
64 setCheckedPageReload(true)
65
66 window.addEventListener("beforeunload", () => {
67 const scrollPos = isElmWindow(scrollableElement)
68 ? scrollableElement.screenY
69 : scrollableElement?.scrollTop
70
71 if (scrollPos) {
72 localStorage.setItem(
73 "scrollPos",
74 `${
75 isElmWindow(scrollableElement)
76 ? scrollableElement.screenY
77 : scrollableElement?.scrollTop
78 }`
79 )
80 }
81 })
82 }, [scrollableElement, checkedPageReload])
83 }