const SCROLL_BOUNDARY_THRESHOLD = 2 export type PageScrollBoundary = 'none' | 'top' | 'middle' | 'bottom' export function getPageScrollBoundary(scrollTop: number): PageScrollBoundary { if (typeof window === 'undefined') { return 'none' } const scrollingElement = document.scrollingElement ?? document.documentElement const viewportHeight = window.visualViewport?.height ?? window.innerHeight const scrollHeight = Math.max( scrollingElement.scrollHeight, document.documentElement.scrollHeight, document.body?.scrollHeight ?? 0 ) const maxScrollTop = Math.max(0, scrollHeight - viewportHeight) if (maxScrollTop <= SCROLL_BOUNDARY_THRESHOLD) { return 'none' } if (scrollTop <= SCROLL_BOUNDARY_THRESHOLD) { return 'top' } if (maxScrollTop - scrollTop <= SCROLL_BOUNDARY_THRESHOLD) { return 'bottom' } return 'middle' }