import { forwardRef, useRef } from 'react' import { DynamicLink, type DynamicLinkProps } from '@/components/ui/DynamicLink' export interface PrefetchableLinkProps extends Omit< DynamicLinkProps, 'onMouseEnter' | 'onMouseLeave' > { prefetcher: () => void } const DELAY = 75 const PrefetchableLink = forwardRef( function PrefetchableLink({ prefetcher, href, replace, preload, children, ...props }, ref) { const mouseOverStartRef = useRef(null) const prefetchTimeoutRef = useRef(null) function onPrefetch() { const now = Date.now() // setTimeout is not guaranteed to be precise, so we need to check the time again if (mouseOverStartRef.current && now - mouseOverStartRef.current >= DELAY) { prefetcher() } } function onMouseEnter() { mouseOverStartRef.current = Date.now() prefetchTimeoutRef.current = window.setTimeout(onPrefetch, DELAY) } function onMouseLeave() { mouseOverStartRef.current = null if (prefetchTimeoutRef.current) { clearTimeout(prefetchTimeoutRef.current) prefetchTimeoutRef.current = null } } return ( {children} ) } ) export default PrefetchableLink