import { type BaseItemDto, BaseItemKind, } from "@jellyfin/sdk/lib/generated-client"; import { useSuspenseQuery } from "@tanstack/react-query"; import { getRouteApi } from "@tanstack/react-router"; import { useWindowVirtualizer } from "@tanstack/react-virtual"; import React, { useCallback, useEffect, useMemo, useRef, useState, } from "react"; import "./libraryItemsGrid.scss"; import { useShallow } from "zustand/shallow"; import { getLibraryQueryOptions } from "@/utils/queries/library"; import { getLibraryItemsQueryOptions } from "@/utils/queries/libraryItems"; import { useApiInContext } from "@/utils/store/api"; import { useBackdropStore } from "@/utils/store/backdrop"; import { useCentralStore } from "@/utils/store/central"; import { useLibraryStateStore } from "@/utils/store/libraryState"; import BackdropWorker from "@/utils/workers/backdrop.worker?worker"; import { Card } from "../card/card"; const libraryRoute = getRouteApi("/_api/library/$id"); /** * Virtualized library items grid. * Virtualizes vertical scrolling only; items are arranged into responsive columns. * Assumptions: * - Card aspect ratio handled by CSS; we approximate a fixed height for virtualization. * - Width changes trigger re-measure via ResizeObserver. * Future improvements: * - Dynamic row height based on item type. * - Horizontal virtualization for extremely wide displays. */ const LibraryItemsGrid = () => { const api = useApiInContext((s) => s.api); const user = useCentralStore((s) => s.currentUser); const { id: currentLibraryId } = libraryRoute.useParams(); const { currentViewType, sortAscending, sortBy, filters, videoTypesState, nameStartsWith, genreIds, } = useLibraryStateStore( useShallow((s) => { const slice = s.libraries[currentLibraryId || ""]; return { currentViewType: slice?.currentViewType, sortAscending: slice?.sortAscending ?? true, sortBy: slice?.sortBy ?? "Name", filters: slice?.filters, videoTypesState: slice?.videoTypesState, nameStartsWith: slice?.nameStartsWith, genreIds: slice?.genreIds, }; }), ); const updateLibrary = useLibraryStateStore((s) => s.updateLibrary); const currentLibrary = useSuspenseQuery( getLibraryQueryOptions(api, user?.Id, currentLibraryId), ); useEffect(() => { if (currentLibraryId && !currentViewType && currentLibrary.data?.Type) { updateLibrary(currentLibraryId, { currentViewType: currentLibrary.data.Type as BaseItemKind, }); } }, [ currentLibrary.data?.Type, currentLibraryId, currentViewType, updateLibrary, ]); const items = useSuspenseQuery( getLibraryItemsQueryOptions(api, user?.Id, currentLibraryId, { currentViewType, sortAscending, sortBy, filters, videoTypesState, nameStartsWith, genreIds, collectionType: currentLibrary.data.CollectionType as any, }), ); // --- Backdrop --- const setBackdrop = useBackdropStore(useShallow((s) => s.setBackdrop)); const backdropItems = useMemo(() => { if (!items.isSuccess || !items.data?.Items) return []; return items.data.Items.filter( (item) => Object.keys(item.ImageBlurHashes?.Backdrop ?? {}).length > 0, ); }, [items.isSuccess, items.data?.Items]); useEffect(() => { const worker = new BackdropWorker(); worker.onmessage = (event: MessageEvent) => { if (event.data.type === "UPDATE_BACKDROP") { const schedule = (window as any).requestIdleCallback || window.requestAnimationFrame; schedule(() => setBackdrop(event.data.payload)); } }; if (backdropItems.length > 0) { worker.postMessage({ type: "SET_BACKDROP_ITEMS", payload: backdropItems, }); worker.postMessage({ type: "START" }); } return () => { worker.postMessage({ type: "STOP" }); worker.terminate(); }; }, [backdropItems, setBackdrop]); // --- Virtualization setup --- const parentRef = useRef(null); const [containerWidth, setContainerWidth] = useState(0); const [scrollMargin, setScrollMargin] = useState(0); // Determine column count based on container width (simple heuristic) const [columns, setColumns] = useState(1); const measureColumns = useCallback(() => { if (!parentRef.current) return; const width = parentRef.current.clientWidth; setContainerWidth(width); setScrollMargin(parentRef.current.offsetTop); // Base desired approximate card width (including gap) 180px const ideal = Math.max(1, Math.floor(width / 180)); setColumns(ideal); }, []); useEffect(() => { measureColumns(); if (!parentRef.current) return; const ro = new ResizeObserver(() => measureColumns()); ro.observe(parentRef.current); // The header above the grid can change height (filters, wrapping): keep the // window-virtualizer offset in sync so rows never jump while scrolling. ro.observe(document.body); window.addEventListener("resize", measureColumns); return () => { ro.disconnect(); window.removeEventListener("resize", measureColumns); }; }, [measureColumns]); const itemCount = items.data?.Items?.length ?? 0; // Compute number of virtual rows const rowCount = Math.ceil(itemCount / columns); // Estimated row height (depends on card type). Using 260px as base (portrait taller) // Compute card width minus gaps const cardGap = 16; // px gap between cards const cardWidth = useMemo(() => { if (columns <= 0) return 180; const totalGap = (columns - 1) * cardGap; return Math.floor((containerWidth - totalGap) / columns); }, [columns, containerWidth]); // Approximate card height: width / aspect ratio + text block (title + caption). // Square artwork (music, genres) is shorter than portrait posters. const cardAspect = useMemo(() => { const first = items.data?.Items?.[0]; const square = first?.Type === BaseItemKind.MusicAlbum || first?.Type === BaseItemKind.Audio || first?.Type === BaseItemKind.Genre || first?.Type === BaseItemKind.MusicGenre || first?.Type === BaseItemKind.Studio || first?.Type === BaseItemKind.Playlist; return square ? 1 : 0.666666; }, [items.data?.Items]); const estimateRowHeight = useCallback( () => Math.round(cardWidth / cardAspect + 60), [cardWidth, cardAspect], ); const virtualizer = useWindowVirtualizer({ count: rowCount, estimateSize: estimateRowHeight, overscan: 4, scrollMargin, }); const virtualItems = virtualizer.getVirtualItems(); // Update count in Zustand so header can display it without extra fetches useEffect(() => { const total = items.data?.TotalRecordCount; if (currentLibraryId && typeof total === "number") { updateLibrary(currentLibraryId, { itemsTotalCount: total }); } }, [items.data?.TotalRecordCount, currentLibraryId, updateLibrary]); return (
{items.isSuccess && itemCount === 0 ? (
sentiment_dissatisfied
No items to show
Try adjusting filters, sort, or the A–Z selector.
) : (
{virtualItems.map((row) => { const startIndex = row.index * columns; const endIndex = Math.min(startIndex + columns, itemCount); return (
{items.data?.Items?.slice(startIndex, endIndex).map( (item: BaseItemDto, localIndex: number) => { return (
); }, )}
); })}
)}
); }; export default LibraryItemsGrid;