|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import { usePathname } from 'next/navigation'; |
| 4 | +import { useLayoutEffect } from 'react'; |
| 5 | + |
| 6 | +const SCROLL_POSITIONS_KEY = 'scroll-positions'; |
| 7 | + |
| 8 | +const getScrollPositions = (): Map<string, number> => { |
| 9 | + if (typeof window === 'undefined') return new Map(); |
| 10 | + |
| 11 | + try { |
| 12 | + const stored = sessionStorage.getItem(SCROLL_POSITIONS_KEY); |
| 13 | + if (stored) { |
| 14 | + const parsed = JSON.parse(stored); |
| 15 | + return new Map( |
| 16 | + Object.entries(parsed).map(([key, value]) => [key, Number(value)]), |
| 17 | + ); |
| 18 | + } |
| 19 | + } catch (error) { |
| 20 | + console.warn('Failed to load scroll positions from sessionStorage:', error); |
| 21 | + } |
| 22 | + |
| 23 | + return new Map(); |
| 24 | +}; |
| 25 | + |
| 26 | +const saveScrollPositions = (positions: Map<string, number>) => { |
| 27 | + if (typeof window === 'undefined') return; |
| 28 | + |
| 29 | + try { |
| 30 | + const obj = Object.fromEntries(positions.entries()); |
| 31 | + sessionStorage.setItem(SCROLL_POSITIONS_KEY, JSON.stringify(obj)); |
| 32 | + } catch (error) { |
| 33 | + console.warn('Failed to save scroll positions to sessionStorage:', error); |
| 34 | + } |
| 35 | +}; |
| 36 | + |
| 37 | +export const useScrollRestoration = () => { |
| 38 | + const pathname = usePathname(); |
| 39 | + |
| 40 | + useLayoutEffect(() => { |
| 41 | + if (typeof window === 'undefined') return; |
| 42 | + |
| 43 | + if ('scrollRestoration' in window.history) { |
| 44 | + window.history.scrollRestoration = 'manual'; |
| 45 | + } |
| 46 | + |
| 47 | + // 스크롤 점프 방지를 위한 CSS 조작 |
| 48 | + const preventScrollJump = () => { |
| 49 | + const positions = getScrollPositions(); |
| 50 | + const savedPosition = positions.get(pathname); |
| 51 | + |
| 52 | + if (savedPosition !== undefined) { |
| 53 | + document.documentElement.style.scrollBehavior = 'auto'; |
| 54 | + document.body.scrollTo(0, savedPosition); |
| 55 | + requestAnimationFrame(() => { |
| 56 | + document.documentElement.style.scrollBehavior = ''; |
| 57 | + }); |
| 58 | + } |
| 59 | + }; |
| 60 | + |
| 61 | + if (document.readyState === 'loading') { |
| 62 | + document.addEventListener('DOMContentLoaded', preventScrollJump); |
| 63 | + } else { |
| 64 | + preventScrollJump(); |
| 65 | + } |
| 66 | + |
| 67 | + // 페이지 이탈 시 현재 스크롤 위치 저장 |
| 68 | + const handleBeforeUnload = () => { |
| 69 | + // NOTE: posts 기준으로 body에 스크롤이 있음. window.scrollY가 필요하다면 개선 필요 |
| 70 | + const scrollY = document.body.scrollTop; |
| 71 | + const positions = getScrollPositions(); |
| 72 | + positions.set(pathname, scrollY); |
| 73 | + saveScrollPositions(positions); |
| 74 | + }; |
| 75 | + return () => { |
| 76 | + handleBeforeUnload(); |
| 77 | + }; |
| 78 | + }, [pathname]); |
| 79 | +}; |
0 commit comments