Skip to content

Commit

Permalink
feat: update prefetch on view
Browse files Browse the repository at this point in the history
  • Loading branch information
bysxx committed Apr 26, 2024
1 parent b606461 commit e72c7c4
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion packages/waku/src/router/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ export type LinkProps = {
notPending?: ReactNode;
children: ReactNode;
unstable_prefetchOnEnter?: boolean;
unstable_prefetchOnView?: boolean;
} & Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'>;

export function Link({
Expand All @@ -152,6 +153,7 @@ export function Link({
pending,
notPending,
unstable_prefetchOnEnter,
unstable_prefetchOnView,
...props
}: LinkProps): ReactElement {
const router = useContext(RouterContext);
Expand All @@ -166,6 +168,32 @@ export function Link({
throw new Error('Missing Router');
};
const [isPending, startTransition] = useTransition();
const ref = useRef<HTMLAnchorElement>(null);

useEffect(() => {
if (unstable_prefetchOnView && ref.current) {
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const url = new URL(to, window.location.href);
if (url.href !== window.location.href) {
const route = parseRoute(url);
prefetchRoute(route);
}
}
});
},
{ threshold: 0.1 }
);

observer.observe(ref.current);

return () => {
observer.disconnect();
};
}
}, [unstable_prefetchOnView, prefetchRoute, to, ref]);
const onClick = (event: MouseEvent<HTMLAnchorElement>) => {
event.preventDefault();
const url = new URL(to, window.location.href);
Expand Down Expand Up @@ -198,7 +226,7 @@ export function Link({
: props.onMouseEnter;
const ele = createElement(
'a',
{ ...props, href: to, onClick, onMouseEnter },
{ ...props, href: to, onClick, onMouseEnter, ref},
children,
);
if (isPending && pending !== undefined) {
Expand Down

0 comments on commit e72c7c4

Please sign in to comment.