Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(waku/router): prefetch on view (<Link />) #672

Merged
merged 4 commits into from
Apr 26, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
bysxx marked this conversation as resolved.
Show resolved Hide resolved
} & 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>();

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 (router && url.href !== window.location.href) {
const route = parseRoute(url);
router.prefetchRoute(route);
}
}
});
},
{ threshold: 0.1 },
);

observer.observe(ref.current);

return () => {
observer.disconnect();
};
}
}, [unstable_prefetchOnView, router, to]);
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
Loading