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

[docs-infra] Prefetch pages on hover #40314

Merged
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
46 changes: 41 additions & 5 deletions docs/src/modules/components/MarkdownLinks.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,7 @@ export function samePageLinkNavigation(event) {
return false;
}

/**
* @param {MouseEvent} event
*/
function handleClick(event) {
function isLink(event) {
let activeElement = event.target;
while (activeElement?.nodeType === Node.ELEMENT_NODE && activeElement.nodeName !== 'A') {
activeElement = activeElement.parentElement;
Expand All @@ -33,6 +30,18 @@ function handleClick(event) {
activeElement.getAttribute('data-no-markdown-link') === 'true' ||
activeElement.getAttribute('href').indexOf('/') !== 0
) {
return null;
}

return activeElement;
}

/**
* @param {MouseEvent} event
*/
function handleClick(event) {
const activeElement = isLink(event);
if (activeElement === null) {
return;
}

Expand All @@ -47,11 +56,38 @@ function handleClick(event) {
Router.push(canonicalPathname, as);
}

/**
* Source copied from https://github.com/vercel/next.js/blob/ebc4eaaa2564b4283711646079d68e430496c88b/packages/next/src/client/link.tsx
*/
function handleMouseOver(event) {
const activeElement = isLink(event);
if (activeElement === null) {
return;
}

const as = activeElement.getAttribute('href');
const canonicalPathname = pathnameToLanguage(as).canonicalPathname;

const prefetchPromise = Router.prefetch(canonicalPathname, as, { priority: true });
// Prefetch the JSON page if asked (only in the client)
// We need to handle a prefetch error here since we may be
// loading with priority which can reject but we don't
// want to force navigation since this is only a prefetch
Promise.resolve(prefetchPromise).catch((err) => {
if (process.env.NODE_ENV !== 'production') {
// rethrow to show invalid URL errors
throw err;
}
});
}

export default function MarkdownLinks() {
React.useEffect(() => {
document.addEventListener('click', handleClick);
document.addEventListener('mouseover', handleMouseOver);
return () => {
document.addEventListener('click', handleClick);
document.removeEventListener('click', handleClick);
document.removeEventListener('mouseover', handleMouseOver);
};
}, []);

Expand Down