import { useEffect } from 'react'; export const useScrollPage = () => { useEffect(() => { const handleHashChange = () => { const anchor = window.location.hash; let animationFrameId; if (anchor) { const scrollToTarget = () => { const targetElement = document.querySelector(anchor); if (targetElement) { const parentContainer = document.getElementById('__next')?.firstElementChild; const parentContainerTop = parentContainer?.getBoundingClientRect().top || 0; const targetTop = targetElement.getBoundingClientRect().top; const offset = window.scrollY + targetTop - parentContainerTop; // Smoothly scroll to the target element window.scrollTo({ top: offset, behavior: 'smooth', }); } else { // Retry scrolling on the next animation frame if the target element is still not found animationFrameId = window.requestAnimationFrame(scrollToTarget); } }; scrollToTarget(); // remove animationframe after 1000ms to prevent calling infinity if the anchor is wrong. setTimeout(() => { if (animationFrameId) { window.cancelAnimationFrame(animationFrameId); } }, 1000); } }; // Add a 'hashchange' event listener to handle URL anchor changes window.addEventListener('hashchange', handleHashChange); handleHashChange(); return () => { window.removeEventListener('hashchange', handleHashChange); }; }, []); };