Skip to content

Commit

Permalink
feat(playing): implement custom hook for image loading and caching
Browse files Browse the repository at this point in the history
  • Loading branch information
busybox11 committed Dec 8, 2024
1 parent 39fb756 commit d476c8c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
19 changes: 19 additions & 0 deletions app/hooks/Playing/usePlayingImage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { useEffect, useState } from "react";

export default function usePlayingImage(image: string) {
// Keep the last image in the cache
// until the next image is fully loaded
const [lastImage, setLastImage] = useState(image);

useEffect(() => {
if (image === lastImage) return;

const imageObj = new Image();
imageObj.src = image;
imageObj.onload = () => {
setLastImage(imageObj.src);
};
}, [image]);

return lastImage;
}
6 changes: 4 additions & 2 deletions app/routes/playing.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import usePlayer from "@/hooks/usePlayer";
import { twMerge } from "tailwind-merge";
import { store } from "@/state/store";
import { activeProviderAtom } from "@/state/player";
import usePlayingImage from "@/hooks/Playing/usePlayingImage";

export const Route = createFileRoute("/playing")({
component: PlayingRouteComponent,
Expand All @@ -32,6 +33,7 @@ function PlayingRouteComponent() {
}

const image = playerState?.meta.main_img_url ?? noSong;
const imageSrc = usePlayingImage(image);

const title = playerState?.item?.title ?? "NowPlaying";
const artist =
Expand Down Expand Up @@ -75,7 +77,7 @@ function PlayingRouteComponent() {
<div
className="bg-cover bg-center transition-[background] duration-[2s] ease-in-out z-[-10] h-full w-full blur-2xl transform-gpu"
style={{
backgroundImage: `url(${image})`,
backgroundImage: `url(${imageSrc})`,
}}
>
<div className="h-full w-full bg-black/30"></div>
Expand Down Expand Up @@ -107,7 +109,7 @@ function PlayingRouteComponent() {
<div className="flex flex-col landscape:flex-row lg:flex-row gap-6 lg:gap-12 justify-center items-center px-6 lg:px-12 xl:px-0 w-full xl:w-5/6">
<div className="relative w-[20rem] landscape:w-[20rem] landscape:lg:w-[30rem] md:w-[30rem] flex-shrink-0">
<img
src={image}
src={imageSrc}
className="rounded-2xl h-auto w-full custom-img-shadow"
/>

Expand Down

0 comments on commit d476c8c

Please sign in to comment.