Skip to content

Commit

Permalink
Cancel images on mouse-leave (#38)
Browse files Browse the repository at this point in the history
* Cancel images on mouse-leave

* Cancel images on mouse-leave

* Cancel images on mouse-leave
  • Loading branch information
cramforce authored Oct 21, 2024
1 parent 25d9be5 commit 770dea3
Showing 1 changed file with 37 additions and 13 deletions.
50 changes: 37 additions & 13 deletions src/components/ui/link.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ function sleep(ms: number) {
}

async function prefetchImages(href: string) {
if (!href.startsWith("/") || href.startsWith("/order")) {
if (!href.startsWith("/") || href.startsWith("/order") || href === "/") {
return [];
}
const url = new URL(href, window.location.href);
Expand All @@ -36,6 +36,7 @@ const seen = new Set<string>();

export const Link: typeof NextLink = (({ children, ...props }) => {
const [images, setImages] = useState<PrefetchImage[]>([]);
const [preloading, setPreloading] = useState<(() => void)[]>([]);
const linkRef = useRef<HTMLAnchorElement>(null);
const router = useRouter();
let prefetchTimeout: NodeJS.Timeout | null = null; // Track the timeout ID
Expand Down Expand Up @@ -85,21 +86,21 @@ export const Link: typeof NextLink = (({ children, ...props }) => {
<NextLink
ref={linkRef}
prefetch={false}
onMouseOver={() => {
onMouseEnter={() => {
router.prefetch(String(props.href));
if (preloading.length) return;
const p: (() => void)[] = [];
for (const image of images) {
if (image.loading === "lazy" || seen.has(image.srcset)) {
continue;
}
const img = new Image();
img.decoding = "async";
img.fetchPriority = "low";
img.sizes = image.sizes;
seen.add(image.srcset);
img.srcset = image.srcset;
img.src = image.src;
img.alt = image.alt;
const remove = prefetchImage(image);
if (remove) p.push(remove);
}
setPreloading(p);
}}
onMouseLeave={() => {
for (const remove of preloading) {
remove();
}
setPreloading([]);
}}
onMouseDown={(e) => {
const url = new URL(String(props.href), window.location.href);
Expand All @@ -121,3 +122,26 @@ export const Link: typeof NextLink = (({ children, ...props }) => {
</NextLink>
);
}) as typeof NextLink;

function prefetchImage(image: PrefetchImage) {
if (image.loading === "lazy" || seen.has(image.srcset)) {
return;
}
const img = new Image();
img.decoding = "async";
img.fetchPriority = "low";
img.sizes = image.sizes;
seen.add(image.srcset);
img.srcset = image.srcset;
img.src = image.src;
img.alt = image.alt;
let done = false;
img.onload = img.onerror = () => {
done = true;
};
return () => {
if (done) return;
img.src = img.srcset = "";
seen.delete(image.srcset);
};
}

0 comments on commit 770dea3

Please sign in to comment.