import { useRouter } from '@tanstack/react-router' import { useEffect } from 'react' /** How long to wait for a hash target that mounts late (behind auth, hydration or a query skeleton). */ export const HASH_TARGET_MOUNT_TIMEOUT_MS = 10_000 /** How long after the first scroll to keep the target aligned while content above it settles. */ export const HASH_LAYOUT_SETTLE_TIMEOUT_MS = 2_000 const CANCEL_EVENTS = ['wheel', 'pointerdown', 'touchstart', 'keydown'] as const const getScrollParent = (element: HTMLElement): HTMLElement | null => { for (let el = element.parentElement; el && el !== document.body; el = el.parentElement) { // `overflow-x: hidden` alone computes `overflow-y` to `auto`, so also check it actually scrolls const { overflowY } = window.getComputedStyle(el) const isScrollable = overflowY === 'auto' || overflowY === 'scroll' if (isScrollable && el.scrollHeight > el.clientHeight) return el } return null } // The target's offset from the top of its scrollable content. Unlike its viewport position, // this only changes when layout shifts, not while a smooth scroll is in flight. const getContentOffset = (target: HTMLElement) => { const top = target.getBoundingClientRect().top const scrollParent = getScrollParent(target) if (!scrollParent) return window.scrollY + top return scrollParent.scrollTop + top - scrollParent.getBoundingClientRect().top } /** * Scrolls to the element with `id === hash`, waiting for it to mount if needed, then keeps it * aligned while content above it shifts. Stops on timeout or as soon as the user scrolls, * clicks or types. Returns a function that cancels it. */ const scrollToHash = (hash: string) => { let alignedOffset: number | undefined let timeoutId = window.setTimeout(() => stop(), HASH_TARGET_MOUNT_TIMEOUT_MS) const align = () => { const target = document.getElementById(hash) if (!target) return const offset = getContentOffset(target) if (alignedOffset !== undefined && Math.abs(offset - alignedOffset) <= 1) return const isFirstScroll = alignedOffset === undefined alignedOffset = offset if (isFirstScroll) { window.clearTimeout(timeoutId) timeoutId = window.setTimeout(() => stop(), HASH_LAYOUT_SETTLE_TIMEOUT_MS) } const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches target.scrollIntoView({ // Re-alignments jump so they don't restart a smooth scroll on every layout shift. behavior: isFirstScroll && !prefersReducedMotion ? 'smooth' : 'instant', block: 'start', }) } const observer = new MutationObserver(align) const stop = () => { window.clearTimeout(timeoutId) observer.disconnect() CANCEL_EVENTS.forEach((name) => window.removeEventListener(name, stop, true)) } CANCEL_EVENTS.forEach((name) => window.addEventListener(name, stop, { capture: true, passive: true }) ) observer.observe(document.body, { childList: true, subtree: true }) align() return stop } /** * Owns URL fragment (`#section`) scrolling for all of Studio, so a deep-linkable section only * needs an `id`. Unlike the router's built-in hash scroll, it handles targets that mount * asynchronously and content above the target that shifts after it mounts. */ export const HashScrollController = () => { const router = useRouter() useEffect(() => { const { hash } = router.state.location // The initial render's `onRendered` fires before this effect subscribes. let cancel = hash ? scrollToHash(hash) : undefined const unsubscribe = router.subscribe( 'onRendered', ({ toLocation, pathChanged, hashChanged }) => { // Search-param updates (e.g. nuqs opening a dialog) and `router.invalidate()` re-render the // same path and hash; scrolling back to the anchor then would yank the page. if (!pathChanged && !hashChanged) return cancel?.() cancel = toLocation.hash ? scrollToHash(toLocation.hash) : undefined } ) return () => { unsubscribe() cancel?.() } }, [router]) return null }