'use client' import * as React from 'react' // Covers the 200ms accordion panel animation plus a frame of slack. const ANCHOR_DURATION_MS = 320 function findScrollParent(element: HTMLElement): HTMLElement { let parent = element.parentElement while (parent) { const { overflowY } = window.getComputedStyle(parent) if ( (overflowY === 'auto' || overflowY === 'scroll') && parent.scrollHeight > parent.clientHeight ) return parent parent = parent.parentElement } return document.scrollingElement as HTMLElement } // Keeps a tapped element at the same spot on screen while content above it resizes, e.g. an // accordion item above collapsing as the tapped one opens (one item open at a time). It scrolls back // by however far the element moved, from a `ResizeObserver` on the accordion's items (after // layout, before paint, so no frame shows the shift) and on every animation frame until the panel // animation ends. export function useScrollAnchor() { const stopRef = React.useRef<(() => void) | null>(null) React.useEffect(() => () => stopRef.current?.(), []) return React.useCallback((element: HTMLElement) => { stopRef.current?.() const scroller = findScrollParent(element) const anchorTop = element.getBoundingClientRect().top const start = performance.now() let frame = 0 const correct = () => { const drift = element.getBoundingClientRect().top - anchorTop if (drift !== 0) scroller.scrollTop += drift } const observer = new ResizeObserver(correct) // Every item, not the root: a closing trigger growing while the opening one shrinks leaves the // root's height unchanged for that frame. const root = element.closest('[data-slot=accordion]') const items = root ? root.querySelectorAll('[data-slot=accordion-item]') : [] for (const item of items) observer.observe(item) // The on-screen keyboard opening for a field that just took focus ends the hold, so the // keyboard reveal in `useFocusFirstField` is not scrolled back. const viewport = window.visualViewport const stop = () => { cancelAnimationFrame(frame) observer.disconnect() viewport?.removeEventListener('resize', stop) stopRef.current = null } const hold = () => { correct() if (performance.now() - start < ANCHOR_DURATION_MS) frame = requestAnimationFrame(hold) else stop() } frame = requestAnimationFrame(hold) viewport?.addEventListener('resize', stop) stopRef.current = stop }, []) }