refactor: use blurhash to render background

This commit is contained in:
Prayag Prajapati committed 2025-07-04 15:19:38 +05:30
1 parent 53311a1728
commit c9d16f4669
12 files changed
+205 -164

No files matched your search

+3 -1
View File
@@ -50,6 +50,7 @@
"axios": "^1.10.0",
"axios-tauri-api-adapter": "^2.0.6",
"blurhash": "^2.0.5",
"blurhash-wasm": "^0.2.0",
"immer": "^10.1.1",
"jassub": "^1.8.6",
"libpgs": "^0.8.1",
@@ -86,7 +87,8 @@
"eslint-plugin-react-hooks": "6.0.0-rc1",
"prop-types": "^15.8.1",
"sass": "^1.89.2",
"vite": "^7.0.0"
"vite": "^7.0.0",
"vite-plugin-wasm": "^3.4.1"
},
"license": "GPL-3.0-only"
}
+20
View File
@@ -119,6 +119,9 @@ importers:
blurhash:
specifier: ^2.0.5
version: 2.0.5
blurhash-wasm:
specifier: ^0.2.0
version: 0.2.0
immer:
specifier: ^10.1.1
version: 10.1.1
@@ -225,6 +228,9 @@ importers:
vite:
specifier: ^7.0.0
version: 7.0.0(@types/node@24.0.8)(sass@1.89.2)(tsx@4.20.3)(yaml@2.8.0)
vite-plugin-wasm:
specifier: ^3.4.1
version: 3.4.1(vite@7.0.0(@types/node@24.0.8)(sass@1.89.2)(tsx@4.20.3)(yaml@2.8.0))
packages:
@@ -1605,6 +1611,9 @@ packages:
resolution: {integrity: sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==}
engines: {node: '>=8'}
blurhash-wasm@0.2.0:
resolution: {integrity: sha512-d/jOMANMlth4VNQRs3Xr/bDj7K3S2/QuRvrwC3QldeOTX9/5MLHUn2+JQV11Ja2J4/kY+HbRJOCGCy9T4BBvJw==}
blurhash@2.0.5:
resolution: {integrity: sha512-cRygWd7kGBQO3VEhPiTgq4Wc43ctsM+o46urrmPOiuAe+07fzlSB9OJVdpgDL0jPqXUVQ9ht7aq7kxOeJHRK+w==}
@@ -2931,6 +2940,11 @@ packages:
peerDependencies:
vite: '>=2.6.0'
vite-plugin-wasm@3.4.1:
resolution: {integrity: sha512-ja3nSo2UCkVeitltJGkS3pfQHAanHv/DqGatdI39ja6McgABlpsZ5hVgl6wuR8Qx5etY3T5qgDQhOWzc5RReZA==}
peerDependencies:
vite: ^2 || ^3 || ^4 || ^5 || ^6
vite@7.0.0:
resolution: {integrity: sha512-ixXJB1YRgDIw2OszKQS9WxGHKwLdCsbQNkpJN171udl6szi/rIySHL6/Os3s2+oE4P/FLD4dxg4mD7Wust+u5g==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -4423,6 +4437,8 @@ snapshots:
binary-extensions@2.3.0: {}
blurhash-wasm@0.2.0: {}
blurhash@2.0.5: {}
brace-expansion@1.1.12:
@@ -5948,6 +5964,10 @@ snapshots:
- supports-color
- typescript
vite-plugin-wasm@3.4.1(vite@7.0.0(@types/node@24.0.8)(sass@1.89.2)(tsx@4.20.3)(yaml@2.8.0)):
dependencies:
vite: 7.0.0(@types/node@24.0.8)(sass@1.89.2)(tsx@4.20.3)(yaml@2.8.0)
vite@7.0.0(@types/node@24.0.8)(sass@1.89.2)(tsx@4.20.3)(yaml@2.8.0):
dependencies:
esbuild: 0.25.5
+4
View File
@@ -0,0 +1,4 @@
onlyBuiltDependencies:
- '@parcel/watcher'
- core-js
- esbuild
+28 -40
View File
@@ -1,50 +1,38 @@
import { AnimatePresence, motion } from "motion/react";
import React, { useLayoutEffect, useState } from "react";
import React from "react";
import { useShallow } from "zustand/shallow";
import { useBackdropStore } from "@/utils/store/backdrop";
import BlurhashCanvas from "../blurhash-canvas";
export default function Backdrop() {
const [backdropLoading, setBackdropLoading] = useState(true);
const [backdropId, backdropUrl] = useBackdropStore((state) => [
state.backdropId,
state.backdropUrl,
]);
// Reset loading status for backdrop
useLayoutEffect(() => {
setBackdropLoading(true);
}, [backdropId]);
if (!backdropUrl) {
// const [backdropLoading, setBackdropLoading] = useState(true);
const { backdropHash } = useBackdropStore(
useShallow((state) => ({
backdropHash: state.backdropHash,
})),
);
if (!backdropHash) {
return null;
}
return (
<div className="app-backdrop-container">
<AnimatePresence>
<motion.img
key={backdropId}
src={backdropUrl}
alt=""
className="app-backdrop"
initial={{
opacity: 0,
}}
animate={{
opacity: backdropLoading ? 0 : 1,
}}
exit={{
opacity: 0,
}}
transition={{
opacity: {
duration: 1.2,
},
}}
onLoad={() => setBackdropLoading(false)}
loading="lazy"
/>
</AnimatePresence>
<BlurhashCanvas
key={backdropHash}
blurhashString={backdropHash}
width={300}
height={150}
canvasProps={{
style: {
display: "block",
width: "100vw",
height: "100vh",
margin: "0 auto",
filter: "brightness(0.8) contrast(1.6) saturate(1.6)",
},
}}
/>
</div>
);
}
+60
View File
@@ -0,0 +1,60 @@
import * as blurhash from "blurhash-wasm";
import React, { useEffect } from "react";
type BlurhashCanvasProps = {
canvasProps?: React.CanvasHTMLAttributes<HTMLCanvasElement>;
blurhashString: string;
width?: number;
height?: number;
// punch?: number;
onLoad?: () => void;
onError?: (error: Error) => void;
};
const BlurhashCanvas = ({
canvasProps,
blurhashString,
width,
height,
// punch,
onLoad,
onError,
}: BlurhashCanvasProps) => {
const canvasRef = React.useRef<HTMLCanvasElement>(null);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext("2d");
if (!ctx) return;
const drawBlurhash = async () => {
try {
const imageDataBuffer = blurhash.decode(
blurhashString,
width || 32,
height || 32,
// punch || 1,
);
// canvas.width = width || 32;
// canvas.height = height || 32;
if (!imageDataBuffer) {
throw new Error("Failed to decode blurhash");
}
const imageData = new ImageData(
new Uint8ClampedArray(imageDataBuffer),
width || 32,
height || 32,
);
// imageData.data.set(imageDataBuffer);
ctx.putImageData(imageData, 0, 0);
if (onLoad) onLoad();
} catch (error) {
if (onError) onError(error as Error);
else console.error("Error decoding blurhash:", error);
}
};
drawBlurhash();
}, [blurhash, width, height, onLoad, onError]);
return <canvas ref={canvasRef} {...canvasProps} />;
};
export default BlurhashCanvas;
+10 -10
View File
@@ -1,6 +1,6 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createRouter, RouterProvider } from "@tanstack/react-router";
import React from "react";
import React, { useEffect } from "react";
import ReactDOM from "react-dom/client";
// Import the generated route tree
import { routeTree } from "./routeTree.gen";
@@ -64,15 +64,15 @@ function ProviderWrapper() {
if (api?.accessToken && !user?.Id) {
fetchCurrentUser(api);
}
// useEffect(() => {
// if (api) {
// console.log(`API is set - Route ${window.location.pathname}`);
// console.log(api);
// } else {
// console.log(`API is not set - Route ${window.location.pathname}`);
// }
// router.invalidate(); // This is a hack to force the router to re-evaluate the routes and re-run the beforeLoad functions
// }, [api]);
useEffect(() => {
if (api) {
console.log(`API is set - Route ${window.location.pathname}`);
console.log(api);
} else {
console.log(`API is not set - Route ${window.location.pathname}`);
}
router.invalidate(); // This is a hack to force the router to re-evaluate the routes and re-run the beforeLoad functions
}, [api]);
return (
<RouterProvider
router={router}
+2 -1
View File
@@ -1,5 +1,6 @@
// import { EasterEgg } from "@/components/utils/easterEgg";
import { CssBaseline, ThemeProvider } from "@mui/material";
import { CssBaseline } from "@mui/material";
import { ThemeProvider } from "@mui/material/styles";
import { createRootRouteWithContext, Outlet } from "@tanstack/react-router";
import { SnackbarProvider } from "notistack";
import React from "react";
+26 -35
View File
@@ -1,38 +1,31 @@
import React, { useCallback, useMemo } from "react";
import { useSuspenseQuery } from "@tanstack/react-query";
import React, { useCallback, useMemo } from "react";
import "./home.scss";
import Carousel from "@/components/carousel";
// Custom Components
import { Card } from "@/components/card/card";
import CardScroller from "@/components/cardScroller/cardScroller";
import { LatestMediaSection } from "@/components/layouts/homeSection/latestMediaSection";
import { getItemsApi } from "@jellyfin/sdk/lib/utils/api/items-api";
import { getTvShowsApi } from "@jellyfin/sdk/lib/utils/api/tv-shows-api";
import { getUserViewsApi } from "@jellyfin/sdk/lib/utils/api/user-views-api";
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useBackdropStore } from "@/utils/store/backdrop";
import CircularPageLoadingAnimation from "@/components/circularPageLoadingAnimation";
import { ErrorNotice } from "@/components/notices/errorNotice/errorNotice";
import getImageUrlsApi from "@/utils/methods/getImageUrlsApi";
import { getLatestItemsQueryOptions } from "@/utils/queries/items";
import { useApiInContext } from "@/utils/store/api";
import { useCentralStore } from "@/utils/store/central";
import type { Api } from "@jellyfin/sdk";
import {
type BaseItemDto,
BaseItemKind,
ItemFields,
} from "@jellyfin/sdk/lib/generated-client";
import { getItemsApi } from "@jellyfin/sdk/lib/utils/api/items-api";
import { getTvShowsApi } from "@jellyfin/sdk/lib/utils/api/tv-shows-api";
import { getUserViewsApi } from "@jellyfin/sdk/lib/utils/api/user-views-api";
import Typography from "@mui/material/Typography";
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { ErrorBoundary } from "react-error-boundary";
import { useShallow } from "zustand/shallow";
// Custom Components
import { Card } from "@/components/card/card";
import CardScroller from "@/components/cardScroller/cardScroller";
import Carousel from "@/components/carousel";
import CircularPageLoadingAnimation from "@/components/circularPageLoadingAnimation";
import { LatestMediaSection } from "@/components/layouts/homeSection/latestMediaSection";
import { ErrorNotice } from "@/components/notices/errorNotice/errorNotice";
import { getLatestItemsQueryOptions } from "@/utils/queries/items";
import { useApiInContext } from "@/utils/store/api";
import { useBackdropStore } from "@/utils/store/backdrop";
import { useCentralStore } from "@/utils/store/central";
export const Route = createFileRoute("/_api/home/")({
component: Home,
@@ -126,23 +119,21 @@ function Home() {
const navigate = useNavigate();
const setBackdrop = useBackdropStore((s) => s.setBackdrop);
const setBackdrop = useBackdropStore(useShallow((s) => s.setBackdrop));
const setBackdropForItem = useCallback(
(item: BaseItemDto, api: Api) => {
(item: BaseItemDto) => {
if (item?.ParentBackdropImageTags) {
setBackdrop(
getImageUrlsApi(api).getItemImageUrlById(item.Id ?? "", "Backdrop", {
tag: item.ParentBackdropImageTags[0],
}),
item.ParentBackdropImageTags[0] ?? item.Id,
item.ImageBlurHashes?.Backdrop?.[item.ParentBackdropImageTags[0]],
);
} else {
if (!item?.BackdropImageTags) {
setBackdrop(undefined);
return;
}
setBackdrop(
getImageUrlsApi(api).getItemImageUrlById(item.Id ?? "", "Backdrop", {
tag: item.BackdropImageTags?.[0],
}),
item.BackdropImageTags?.[0] ?? item.Id,
item.ImageBlurHashes?.Backdrop?.[item.BackdropImageTags[0]],
);
}
},
@@ -156,7 +147,7 @@ function Home() {
if (!currentItem) return;
// Extract this logic to a separate function
setBackdropForItem(currentItem, api);
setBackdropForItem(currentItem);
}
},
// Only depend on what you need
+39 -54
View File
@@ -1,68 +1,58 @@
import React, { useState, useLayoutEffect, useRef, useMemo } from "react";
import Chip from "@mui/material/Chip";
import MenuItem from "@mui/material/MenuItem";
import Stack from "@mui/material/Stack";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import { green, red, yellow } from "@mui/material/colors";
import { Blurhash } from "react-blurhash";
import useParallax from "@/utils/hooks/useParallax";
import { motion, useScroll } from "motion/react";
import {
BaseItemKind,
MediaStreamType,
} from "@jellyfin/sdk/lib/generated-client";
import { getLibraryApi } from "@jellyfin/sdk/lib/utils/api/library-api";
import Chip from "@mui/material/Chip";
import { green, red, yellow } from "@mui/material/colors";
import MenuItem from "@mui/material/MenuItem";
import Stack from "@mui/material/Stack";
import TextField from "@mui/material/TextField";
import Typography from "@mui/material/Typography";
import { useQuery, useSuspenseQuery } from "@tanstack/react-query";
import { motion, useScroll } from "motion/react";
import React, { useLayoutEffect, useMemo, useRef, useState } from "react";
import { Blurhash } from "react-blurhash";
import heroBg from "@/assets/herobg.png";
import { Card } from "@/components/card/card";
import CardScroller from "@/components/cardScroller/cardScroller";
import useParallax from "@/utils/hooks/useParallax";
import "./item.scss";
import { ErrorNotice } from "@/components/notices/errorNotice/errorNotice";
import { createFileRoute, Link } from "@tanstack/react-router";
import { useShallow } from "zustand/shallow";
import ultraHdIcon from "@/assets/icons/4k.svg";
import dolbyAtmosIcon from "@/assets/icons/dolby-atmos.svg";
import dolbyDigitalIcon from "@/assets/icons/dolby-digital.svg";
import dolbyDigitalPlusIcon from "@/assets/icons/dolby-digital-plus.svg";
import dolbyTrueHDIcon from "@/assets/icons/dolby-truehd.svg";
import dolbyVisionIcon from "@/assets/icons/dolby-vision.svg";
import dolbyVisionAtmosIcon from "@/assets/icons/dolby-vision-atmos.png";
import dtsIcon from "@/assets/icons/dts.svg";
import dtsHdMaIcon from "@/assets/icons/dts-hd-ma.svg";
import hdIcon from "@/assets/icons/hd.svg";
import hdrIcon from "@/assets/icons/hdr.svg";
import hdr10Icon from "@/assets/icons/hdr10.svg";
import hdr10PlusIcon from "@/assets/icons/hdr10-plus.svg";
import imaxIcon from "@/assets/icons/imax.svg";
import sdIcon from "@/assets/icons/sd.svg";
import sdrIcon from "@/assets/icons/sdr.svg";
import LikeButton from "@/components/buttons/likeButton";
import MarkPlayedButton from "@/components/buttons/markPlayedButton";
import PlayButton from "@/components/buttons/playButton";
import TrailerButton from "@/components/buttons/trailerButton";
import IconLink from "@/components/iconLink";
import { ErrorNotice } from "@/components/notices/errorNotice/errorNotice";
import ShowMoreText from "@/components/showMoreText";
import ItemSkeleton from "@/components/skeleton/item";
import { getTypeIcon } from "@/components/utils/iconsCollection";
import { endsAt, getRuntime } from "@/utils/date/time";
import { useBackdropStore } from "@/utils/store/backdrop";
import ItemSkeleton from "@/components/skeleton/item";
import ultraHdIcon from "@/assets/icons/4k.svg";
import dolbyAtmosIcon from "@/assets/icons/dolby-atmos.svg";
import dolbyDigitalPlusIcon from "@/assets/icons/dolby-digital-plus.svg";
import dolbyDigitalIcon from "@/assets/icons/dolby-digital.svg";
import dolbyTrueHDIcon from "@/assets/icons/dolby-truehd.svg";
import dolbyVisionAtmosIcon from "@/assets/icons/dolby-vision-atmos.png";
import dolbyVisionIcon from "@/assets/icons/dolby-vision.svg";
import dtsHdMaIcon from "@/assets/icons/dts-hd-ma.svg";
import dtsIcon from "@/assets/icons/dts.svg";
import hdIcon from "@/assets/icons/hd.svg";
import hdrIcon from "@/assets/icons/hdr.svg";
import hdr10PlusIcon from "@/assets/icons/hdr10-plus.svg";
import hdr10Icon from "@/assets/icons/hdr10.svg";
import imaxIcon from "@/assets/icons/imax.svg";
import sdIcon from "@/assets/icons/sd.svg";
import sdrIcon from "@/assets/icons/sdr.svg";
import type MediaQualityInfo from "@/utils/types/mediaQualityInfo";
import IconLink from "@/components/iconLink";
import getImageUrlsApi from "@/utils/methods/getImageUrlsApi";
import { getItemQueryOptions } from "@/utils/queries/items";
import { useBackdropStore } from "@/utils/store/backdrop";
import { useCentralStore } from "@/utils/store/central";
import { Link, createFileRoute } from "@tanstack/react-router";
import type MediaQualityInfo from "@/utils/types/mediaQualityInfo";
export const Route = createFileRoute("/_api/item/$id")({
component: ItemDetail,
@@ -286,23 +276,18 @@ function ItemDetail() {
};
}, [item.data?.Id]);
const setBackdrop = useBackdropStore((state) => state.setBackdrop);
const setBackdrop = useBackdropStore(useShallow((state) => state.setBackdrop));
useLayoutEffect(() => {
if (api && item.isSuccess && item.data) {
if ((item.data?.BackdropImageTags?.length ?? 0) > 0) {
if (item.data?.BackdropImageTags?.length) {
setBackdrop(
getImageUrlsApi(api).getItemImageUrlById(
item.data.Id ?? "",
"Backdrop",
{
tag: item.data.BackdropImageTags?.[0],
},
),
item.data.BackdropImageTags?.[0],
item.data.ImageBlurHashes?.Backdrop?.[
item.data.BackdropImageTags?.[0]
],
);
} else {
setBackdrop("", "");
setBackdrop("");
}
}
}, [item.isSuccess]);
+2 -2
View File
@@ -140,8 +140,8 @@ export function VideoPlayer() {
s.tracks,
]);
const setBackdrop = useBackdropStore((s) => s.setBackdrop);
useEffect(() => setBackdrop("", ""), []);
const setBackdrop = useBackdropStore(useShallow((s) => s.setBackdrop));
useEffect(() => setBackdrop(""), []);
const handleReady = async () => {
if (api && !isPlayerReady && player.current) {
+9 -20
View File
@@ -1,24 +1,13 @@
import { shallow } from "zustand/shallow";
import { createWithEqualityFn } from "zustand/traditional";
import { create } from "zustand";
type BackdropStore = {
backdropUrl: string;
backdropId: string;
setBackdrop: (url: string | undefined, id: string | undefined) => void;
backdropHash: string;
// backdropId: string;
setBackdrop: (hash: string | undefined) => void;
};
export const useBackdropStore = createWithEqualityFn<BackdropStore>(
(set) => ({
backdropUrl: "",
backdropId: "",
setBackdrop: (url, id) => set(() => ({ backdropUrl: url, backdropId: id })),
}),
shallow,
);
/**
* @deprecated Please use setBackdrop method from the store
*/
export const setBackdrop = () => {
// useBackdropStore.setState(() => ({ backdropUrl: url, backdropId: id }));
};
export const useBackdropStore = create<BackdropStore>((set) => ({
backdropHash: "",
// backdropI: "",
setBackdrop: (hash) => set(() => ({ backdropHash: hash })),
}));
+2 -1
View File
@@ -1,6 +1,7 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import svgr from "vite-plugin-svgr";
import wasm from "vite-plugin-wasm";
import { tanstackRouter } from '@tanstack/router-vite-plugin'
// import MillionLint from "@million/lint";
import path from "path";
@@ -20,7 +21,7 @@ const plugins = [react({
}],
],
}
}), svgr(), tanstackRouter()];
}), svgr(), tanstackRouter(), wasm()];
export default defineConfig({
plugins: plugins,
css: {