From c9d16f466910c28868d378b8e215899cb80673ec Mon Sep 17 00:00:00 2001 From: Prayag Prajapati Date: Fri, 4 Jul 2025 15:19:38 +0530 Subject: [PATCH] refactor: use blurhash to render background --- package.json | 4 +- pnpm-lock.yaml | 20 +++++ pnpm-workspace.yaml | 4 + src/components/backdrop/index.tsx | 68 +++++++---------- src/components/blurhash-canvas/index.tsx | 60 +++++++++++++++ src/main.tsx | 20 ++--- src/routes/__root.tsx | 3 +- src/routes/_api/home/index.tsx | 61 +++++++--------- src/routes/_api/item/$id.tsx | 93 ++++++++++-------------- src/routes/_api/player/index.tsx | 4 +- src/utils/store/backdrop.tsx | 29 +++----- vite.config.ts | 3 +- 12 files changed, 205 insertions(+), 164 deletions(-) create mode 100644 pnpm-workspace.yaml create mode 100644 src/components/blurhash-canvas/index.tsx diff --git a/package.json b/package.json index 2729217..3db3346 100644 --- a/package.json +++ b/package.json @@ -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" } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 331ca59..fdd3af7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -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 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml new file mode 100644 index 0000000..2b12183 --- /dev/null +++ b/pnpm-workspace.yaml @@ -0,0 +1,4 @@ +onlyBuiltDependencies: + - '@parcel/watcher' + - core-js + - esbuild diff --git a/src/components/backdrop/index.tsx b/src/components/backdrop/index.tsx index 592b4ce..51914fd 100644 --- a/src/components/backdrop/index.tsx +++ b/src/components/backdrop/index.tsx @@ -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 (
- - setBackdropLoading(false)} - loading="lazy" - /> - +
); } \ No newline at end of file diff --git a/src/components/blurhash-canvas/index.tsx b/src/components/blurhash-canvas/index.tsx new file mode 100644 index 0000000..229dd50 --- /dev/null +++ b/src/components/blurhash-canvas/index.tsx @@ -0,0 +1,60 @@ +import * as blurhash from "blurhash-wasm"; +import React, { useEffect } from "react"; + +type BlurhashCanvasProps = { + canvasProps?: React.CanvasHTMLAttributes; + 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(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 ; +}; + +export default BlurhashCanvas; diff --git a/src/main.tsx b/src/main.tsx index 092e71f..cf481d3 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -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 ( 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 diff --git a/src/routes/_api/item/$id.tsx b/src/routes/_api/item/$id.tsx index 81c339a..8b1eeaf 100644 --- a/src/routes/_api/item/$id.tsx +++ b/src/routes/_api/item/$id.tsx @@ -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]); diff --git a/src/routes/_api/player/index.tsx b/src/routes/_api/player/index.tsx index 77f3b38..996f02a 100644 --- a/src/routes/_api/player/index.tsx +++ b/src/routes/_api/player/index.tsx @@ -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) { diff --git a/src/utils/store/backdrop.tsx b/src/utils/store/backdrop.tsx index 2a54cee..69c1d13 100644 --- a/src/utils/store/backdrop.tsx +++ b/src/utils/store/backdrop.tsx @@ -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( - (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((set) => ({ + backdropHash: "", + // backdropI: "", + setBackdrop: (hash) => set(() => ({ backdropHash: hash })), +})); diff --git a/vite.config.ts b/vite.config.ts index 1274859..6651dd1 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -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: {