feat: use tanstack virtual for rendering library items

This commit is contained in:
Prayag Prajapati committed 2024-04-26 22:26:41 +05:30
1 parent 150dd91fac
commit 38946a126b
7 files changed
+351 -147

No files matched your search

+1
View File
@@ -22,6 +22,7 @@
"@tanem/react-nprogress": "^5.0.51",
"@tanstack/react-query": "^5.28.4",
"@tanstack/react-query-devtools": "^5.28.4",
"@tanstack/react-virtual": "^3.4.0",
"@tauri-apps/api": "^1.5.3",
"@types/node": "^20.11.28",
"@types/react": "^18.2.66",
+18
View File
@@ -35,6 +35,9 @@ dependencies:
'@tanstack/react-query-devtools':
specifier: ^5.28.4
version: 5.28.6(@tanstack/react-query@5.28.6)(react@18.2.0)
'@tanstack/react-virtual':
specifier: ^3.4.0
version: 3.4.0(react-dom@18.2.0)(react@18.2.0)
'@tauri-apps/api':
specifier: ^1.5.3
version: 1.5.3
@@ -1391,6 +1394,21 @@ packages:
react: 18.2.0
dev: false
/@tanstack/react-virtual@3.4.0(react-dom@18.2.0)(react@18.2.0):
resolution: {integrity: sha512-GZN4xn/Tg5w7gvYeVcMVCeL4pEyUhvg+Cp6KX2Z01C4FRNxIWMgIQ9ibgMarNQfo+gt0PVLcEER4A9sNv/jlow==}
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0
react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0
dependencies:
'@tanstack/virtual-core': 3.4.0
react: 18.2.0
react-dom: 18.2.0(react@18.2.0)
dev: false
/@tanstack/virtual-core@3.4.0:
resolution: {integrity: sha512-75jXqXxqq5M5Veb9KP1STi8kA5u408uOOAefk2ftHDGCpUk3RP6zX++QqfbmHJTBiU72NQ+ghgCZVts/Wocz8Q==}
dev: false
/@tauri-apps/api@1.5.3:
resolution: {integrity: sha512-zxnDjHHKjOsrIzZm6nO5Xapb/BxqUq1tc7cGkFXsFkGTsSWgCPH1D8mm0XS9weJY2OaR73I3k3S+b7eSzJDfqA==}
engines: {node: '>= 14.6.0', npm: '>= 6.6.0', yarn: '>= 1.19.1'}
+69 -69
View File
@@ -407,7 +407,7 @@ function AppReady() {
<div className="app-backdrop-container">
<AnimatePresence>
<motion.img
key={backdropId}
key={`${backdropId}${backdropLoading}`}
src={backdropUrl}
alt=""
className="app-backdrop"
@@ -421,7 +421,7 @@ function AppReady() {
opacity: 0,
}}
transition={{
duration: 0.8,
duration: 1.2,
ease: "easeInOut",
}}
onLoadCapture={() => {
@@ -430,9 +430,9 @@ function AppReady() {
onLoad={() => {
setBackdropLoading(false);
}}
loading="eager"
loading="lazy"
style={{
transition: "opacity 0.8s",
transition: "opacity 1.2s",
}}
/>
</AnimatePresence>
@@ -449,72 +449,72 @@ function AppReady() {
{audioPlayerVisible && <AudioPlayer />}
<ErrorBoundary FallbackComponent={ErrorNotice} key={location.key}>
<Routes location={location}>
<Route path="/" element={<Navigate to={initialRoute} />} />
<Route
path="/error"
element={
<Dialog
open
onClose={handleRelaunch}
aria-labelledby="alert-dialog-text"
aria-describedby="alert-dialog-desc"
maxWidth="md"
>
<DialogTitle id="alert-dialog-text">
Unable to reach server
</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-desc">
Unable to connect to the jellyfin server.
</DialogContentText>
</DialogContent>
<DialogActions>
<Button
color="secondary"
variant="contained"
onClick={() => navigate("/servers/list")}
>
Change Server
</Button>
<Button
variant="contained"
color="primary"
onClick={handleRelaunch}
>
Restart JellyPlayer
</Button>
</DialogActions>
</Dialog>
}
/>
<Route path="/login/index" element={<LoginRoute />} />
<Route path="/" element={<Navigate to={initialRoute} />} />
<Route
path="/error"
element={
<Dialog
open
onClose={handleRelaunch}
aria-labelledby="alert-dialog-text"
aria-describedby="alert-dialog-desc"
maxWidth="md"
>
<DialogTitle id="alert-dialog-text">
Unable to reach server
</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-desc">
Unable to connect to the jellyfin server.
</DialogContentText>
</DialogContent>
<DialogActions>
<Button
color="secondary"
variant="contained"
onClick={() => navigate("/servers/list")}
>
Change Server
</Button>
<Button
variant="contained"
color="primary"
onClick={handleRelaunch}
>
Restart JellyPlayer
</Button>
</DialogActions>
</Dialog>
}
/>
<Route path="/login/index" element={<LoginRoute />} />
<Route path="/home" element={<Home />} />
<Route path="/setup/server" element={<ServerSetup />} />
<Route path="/servers/list" element={<ServerList />} />
<Route
path="/login/withImg/:userName/:userId/"
element={<LoginWithImage />}
/>
<Route path="/login/users" element={<UserLogin />} />
<Route path="/login/manual" element={<UserLoginManual />} />
<Route path="/library/:id" element={<LibraryView />} />
<Route path="/item/:id" element={<ItemDetail />} />
<Route
path="/musicalbum/:id"
element={<MusicAlbumTitlePage />}
errorElement={<div>Error</div>}
/>
<Route path="/artist/:id" element={<ArtistTitlePage />} />
<Route path="/boxset/:id" element={<BoxSetTitlePage />} />
<Route path="/episode/:id" element={<EpisodeTitlePage />} />
<Route path="/person/:id" element={<PersonTitlePage />} />
<Route path="/playlist/:id" element={<PlaylistTitlePage />} />
<Route path="/series/:id" element={<SeriesTitlePage />} />
<Route path="/search" element={<SearchPage />} />
<Route path="/favorite" element={<FavoritePage />} />
<Route path="/about" element={<About />} />
<Route path="/player" element={<VideoPlayer />} />
<Route path="/home" element={<Home />} />
<Route path="/setup/server" element={<ServerSetup />} />
<Route path="/servers/list" element={<ServerList />} />
<Route
path="/login/withImg/:userName/:userId/"
element={<LoginWithImage />}
/>
<Route path="/login/users" element={<UserLogin />} />
<Route path="/login/manual" element={<UserLoginManual />} />
<Route path="/library/:id" element={<LibraryView />} />
<Route path="/item/:id" element={<ItemDetail />} />
<Route
path="/musicalbum/:id"
element={<MusicAlbumTitlePage />}
errorElement={<div>Error</div>}
/>
<Route path="/artist/:id" element={<ArtistTitlePage />} />
<Route path="/boxset/:id" element={<BoxSetTitlePage />} />
<Route path="/episode/:id" element={<EpisodeTitlePage />} />
<Route path="/person/:id" element={<PersonTitlePage />} />
<Route path="/playlist/:id" element={<PlaylistTitlePage />} />
<Route path="/series/:id" element={<SeriesTitlePage />} />
<Route path="/search" element={<SearchPage />} />
<Route path="/favorite" element={<FavoritePage />} />
<Route path="/about" element={<About />} />
<Route path="/player" element={<VideoPlayer />} />
</Routes>
</ErrorBoundary>
</div>
+1
View File
@@ -4,6 +4,7 @@
backdrop-filter $transition-time-fast,
box-shadow $transition-time-default !important;
padding: 0.8em ($page-margin - 1.7em);
z-index: 999 !important;
.flex {
transition: $transition-time-fast;
border-radius: 1000px;
@@ -2,7 +2,7 @@ import { motion } from "framer-motion";
import React, { useState, useEffect, useLayoutEffect } from "react";
import { useParams } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
import Accordion from "@mui/material/Accordion";
import AccordionDetails from "@mui/material/AccordionDetails";
@@ -35,6 +35,7 @@ import { Card } from "../../components/card/card";
import { EmptyNotice } from "../../components/notices/emptyNotice/emptyNotice";
import {
type BaseItemDtoQueryResult,
BaseItemKind,
ItemFields,
SortOrder,
@@ -42,15 +43,37 @@ import {
import GenreView from "../../components/layouts/library/genreView";
import MusicTrack from "../../components/musicTrack";
import { ErrorNotice } from "../../components/notices/errorNotice/errorNotice";
import { useBackdropStore } from "../../utils/store/backdrop";
import { setBackdrop, useBackdropStore } from "../../utils/store/backdrop";
import { getUserLibraryApi } from "@jellyfin/sdk/lib/utils/api/user-library-api";
import { useScrollTrigger } from "@mui/material";
import { useVirtualizer, useWindowVirtualizer } from "@tanstack/react-virtual";
import type { AxiosResponse } from "axios";
import { enqueueSnackbar } from "notistack";
import { useApi } from "../../utils/store/api";
import "./library.module.scss";
const useWindowWidth = () => {
const [width, setWidth] = React.useState(window.innerWidth);
React.useEffect(() => {
const onResize = () => setWidth(window.innerWidth);
window.addEventListener("resize", onResize, {
capture: false,
passive: true,
});
return () => {
window.removeEventListener("resize", onResize);
};
}, []);
return width;
};
const LibraryView = () => {
const [api] = useApi((state) => [state.api]);
const [page, setPage] = useState(1);
const maxDisplayItems = 100;
const { id } = useParams();
@@ -221,7 +244,6 @@ const LibraryView = () => {
"libraryView",
"currentLibItems",
id,
`page: ${page}`,
{
currentViewType: currentViewType,
sortAscending: sortAscending,
@@ -244,41 +266,31 @@ const LibraryView = () => {
},
],
queryFn: async () => {
let result;
let result: AxiosResponse<BaseItemDtoQueryResult, any>;
if (currentViewType === "MusicArtist") {
result = await getArtistsApi(api).getAlbumArtists({
userId: user.data.Id,
parentId: id,
startIndex: maxDisplayItems * (page - 1),
limit: maxDisplayItems,
});
} else if (currentViewType === "Person") {
result = await getPersonsApi(api).getPersons({
userId: user.data.Id,
personTypes: ["Actor"],
startIndex: maxDisplayItems * (page - 1),
limit: maxDisplayItems,
});
} else if (currentViewType === "Genre") {
result = await getGenresApi(api).getGenres({
userId: user.data.Id,
parentId: id,
startIndex: maxDisplayItems * (page - 1),
limit: maxDisplayItems,
});
} else if (currentViewType === "MusicGenre") {
result = await getMusicGenresApi(api).getMusicGenres({
userId: user.data.Id,
parentId: id,
startIndex: maxDisplayItems * (page - 1),
limit: maxDisplayItems,
});
} else if (currentViewType === "Studio") {
result = await getStudiosApi(api).getStudios({
userId: user.data.Id,
parentId: id,
startIndex: maxDisplayItems * (page - 1),
limit: maxDisplayItems,
});
} else {
result = await getItemsApi(api).getItems({
@@ -301,8 +313,6 @@ const LibraryView = () => {
isHd: isHD || undefined,
is4K: is4K || undefined,
is3D: is3D || undefined,
startIndex: maxDisplayItems * (page - 1),
limit: maxDisplayItems,
enableUserData: true,
});
}
@@ -314,6 +324,27 @@ const LibraryView = () => {
// gcTime: 0,
});
const cardSize =
items.data?.Items[0].Type === BaseItemKind.MusicAlbum ||
items.data?.Items[0].Type === BaseItemKind.Audio ||
items.data?.Items[0].Type === BaseItemKind.Genre ||
items.data?.Items[0].Type === BaseItemKind.MusicGenre ||
items.data?.Items[0].Type === BaseItemKind.Studio ||
items.data?.Items[0].Type === BaseItemKind.Playlist
? 260
: 356; // This is going to be approx height of each card in libraryView
const windowWidth = useWindowWidth();
const itemsPerRow = Math.max(1, Math.floor(windowWidth / 200));
const count = Math.ceil(
Number.parseInt(items.data?.TotalRecordCount) / itemsPerRow,
);
const virtualizer = useWindowVirtualizer({
count,
estimateSize: () => cardSize,
overscan: 7,
});
const disabledSortViews = [
"MusicArtist",
"Person",
@@ -327,13 +358,38 @@ const LibraryView = () => {
const [filterButtonAnchorEl, setFilterButtonAnchorEl] = useState(null);
const [filterMenuOpen, setFilterMenuOpen] = useState(false);
const [setAppBackdrop] = useBackdropStore((state) => [state.setBackdrop]);
const scrollTrigger = useScrollTrigger({
disableHysteresis: true,
threshold: 20,
});
const [backdropItems, setBackdropItems] = useState([]);
useEffect(() => {
// Filter all items having backdrop images for library backdrop
if (items.isSuccess) {
const backdropItemsTemp = items.data.Items?.filter(
(item) => item.BackdropImageTags?.length > 0,
);
setBackdropItems(backdropItemsTemp);
}
}, [items.dataUpdatedAt]);
useEffect(() => {
// Remove App backdrop in library page
setAppBackdrop("", "");
// console.log(items.isSuccess);
}, []);
if (backdropItems.length > 0) {
const intervalId = setInterval(() => {
const itemIndex = Math.floor(Math.random() * backdropItems?.length);
const backdropItem = backdropItems[itemIndex];
// enqueueSnackbar("Running");
setBackdrop(
api?.getItemImageUrl(backdropItem.Id, "Backdrop", {
tag: backdropItem.BackdropImageTags[0],
}),
backdropItem.Id,
);
}, 10000); // Update backdrop every 10s
return () => clearInterval(intervalId);
}
}, [backdropItems]);
if (items.isError) {
console.error(items.error);
@@ -358,12 +414,15 @@ const LibraryView = () => {
<div
style={{
padding: "1em 1em 1em 0.6em",
height: "4em",
boxShadow: "0 0px 10px 12px hsl(256, 100%, 6%)",
zIndex: 10,
height: "4.4em",
zIndex: "10",
display: "flex",
alignItems: "center",
justifyContent: "flex-start",
position: "absolute",
top: "0px",
left: "50%",
transform: "translate(-50%)",
}}
>
<div
@@ -393,7 +452,13 @@ const LibraryView = () => {
</div>
</div>
<div className="library-items">
<div className="library-items-header">
<div
className={
scrollTrigger
? "library-items-header glass scrolling"
: "library-items-header"
}
>
<div className="library-items-options">
{disabledSortViews.includes(currentViewType) ? (
<></>
@@ -963,7 +1028,7 @@ const LibraryView = () => {
</Popper>
</div>
</div>
{!items.isSuccess ? (
{items.isPending ? (
<Box
sx={{
position: "absolute",
@@ -1002,14 +1067,131 @@ const LibraryView = () => {
);
})
) : currentViewType !== BaseItemKind.Audio ? (
<div className="library-grid">
{items.data.Items.map((item) => {
<div
style={{
height: virtualizer.getTotalSize(),
width: "100%",
position: "relative",
}}
>
{virtualizer.getVirtualItems().map((virtualRow) => {
const index = virtualRow.index;
const displayItems = [];
const fromIndex = index * itemsPerRow;
const toIndex = Math.min(
fromIndex + itemsPerRow,
items.data?.TotalRecordCount,
);
for (let i = fromIndex; i < toIndex; i++) {
const item = items.data?.Items[i];
displayItems.push(
<div
className="library-virtual-item"
key={i}
data-index={virtualRow.index}
ref={virtualizer.measureElement}
>
<Card
item={item}
seriesId={item.SeriesId}
cardTitle={
item.Type === BaseItemKind.Episode
? item.SeriesName
: item.Name
}
imageType={"Primary"}
cardCaption={
item.Type === BaseItemKind.Episode
? `S${item.ParentIndexNumber}:E${item.IndexNumber} - ${item.Name}`
: item.Type === BaseItemKind.Series
? `${item.ProductionYear} - ${
item.EndDate
? new Date(item.EndDate).toLocaleString(
[],
{
year: "numeric",
},
)
: "Present"
}`
: item.ProductionYear
}
disableOverlay={
item.Type === BaseItemKind.Person ||
item.Type === BaseItemKind.Genre ||
item.Type === BaseItemKind.MusicGenre ||
item.Type === BaseItemKind.Studio
}
cardType={
item.Type === BaseItemKind.MusicAlbum ||
item.Type === BaseItemKind.Audio ||
item.Type === BaseItemKind.Genre ||
item.Type === BaseItemKind.MusicGenre ||
item.Type === BaseItemKind.Studio ||
item.Type === BaseItemKind.Playlist
? "square"
: "portrait"
}
queryKey={[
"libraryView",
"currentLibItems",
id,
{
currentViewType: currentViewType,
sortAscending: sortAscending,
sortBy: sortBy,
playbackFilters: filterArray,
extraFilters: {
hasSubtitles: hasSubtitles,
hasTrailer: hasTrailer,
hasSpecialFeature: hasSpecialFeature,
hasThemeSong: hasThemeSong,
hasThemeVideo: hasThemeVideo,
},
qualityFilters: {
isBluRay: isBluRay,
isDVD: isDVD,
isHD: isHD,
is4K: is4K,
is3D: is3D,
},
},
]}
userId={user.data.Id}
imageBlurhash={
!!item.ImageBlurHashes?.Primary &&
item.ImageBlurHashes?.Primary[
Object.keys(item.ImageBlurHashes.Primary)[0]
]
}
/>
</div>,
);
}
return (
<div
className="library-virtual-item-row"
key={virtualRow.key}
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: virtualRow.size,
transform: `translateY(${virtualRow.start}px)`,
}}
>
{displayItems}
</div>
);
})}
{/* {items.data?.Items?.map((item) => {
return (
<motion.div
style={{
width: "100%",
}}
key={`${item.Id}${page}`}
key={`${item.Id}`}
initial={{
opacity: 0,
transform: "scale(0.9)",
@@ -1039,14 +1221,14 @@ const LibraryView = () => {
item.Type === BaseItemKind.Episode
? `S${item.ParentIndexNumber}:E${item.IndexNumber} - ${item.Name}`
: item.Type === BaseItemKind.Series
? `${item.ProductionYear} - ${
? `${item.ProductionYear} - ${
item.EndDate
? new Date(item.EndDate).toLocaleString([], {
year: "numeric",
})
})
: "Present"
}`
: item.ProductionYear
}`
: item.ProductionYear
}
disableOverlay={
item.Type === BaseItemKind.Person ||
@@ -1068,7 +1250,6 @@ const LibraryView = () => {
"libraryView",
"currentLibItems",
id,
`page: ${page}`,
{
currentViewType: currentViewType,
sortAscending: sortAscending,
@@ -1100,7 +1281,7 @@ const LibraryView = () => {
/>
</motion.div>
);
})}
})} */}
</div>
) : (
<div
@@ -1117,7 +1298,6 @@ const LibraryView = () => {
"libraryView",
"currentLibItems",
id,
`page: ${page}`,
{
currentViewType: currentViewType,
sortAscending: sortAscending,
@@ -1144,33 +1324,6 @@ const LibraryView = () => {
))}
</div>
)}
{items.isSuccess && items.data.TotalRecordCount > maxDisplayItems && (
<Stack
alignItems="center"
justifyContent="center"
paddingTop={2}
direction="row"
>
<Typography variant="subtitle2" sx={{ opacity: 0.5 }}>
{maxDisplayItems * (page - 1)} -{" "}
{items.data.TotalRecordCount <= maxDisplayItems * page
? items.data.TotalRecordCount
: maxDisplayItems * page}{" "}
of {items.data.TotalRecordCount}
</Typography>
<Pagination
page={page}
onChange={(e, val) => {
setPage(val);
}}
count={Math.ceil(items.data.TotalRecordCount / maxDisplayItems)}
sx={{
width: "fit-content",
}}
/>
</Stack>
)}
</div>
{items.isError && <ErrorNotice />}
+44 -13
View File
@@ -18,7 +18,7 @@
&-icon {
font-size: 3em;
fill: url(#clr-gradient-default) !important;
&-container {
position: absolute;
top: 0;
@@ -49,27 +49,34 @@
align-items: start;
}
&-items {
height: calc(100vh - 8.4em);
height: fit-content;
overflow-y: auto;
overflow-x: hidden;
padding: 1.5em 1em;
padding: 1.5em $page-margin;
padding-top: 4em;
&-header {
position: absolute;
position: fixed;
top: 4.4em;
z-index: 10;
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 4em;
height: fit-content;
left: 50%;
transform: translate(-50%);
border-radius: 100px;
overflow: hidden;
transition: $transition-time-default;
z-index: 1000;
&.scrolling {
background: rgb(0 0 0 / 0.4) !important;
top: 1em;
}
}
&-options {
padding: 0.5em 1.2em;
gap: 0.5em;
background: $clr-background-opacity-0_5;
border-radius: 100px;
overflow: hidden;
backdrop-filter: blur(10px);
display: flex;
align-items: center;
justify-content: center;
@@ -82,15 +89,14 @@
max-height: 32em;
background: rgb(0 0 0 / 0.65);
border-radius: $border-radius-default;
box-shadow: 0 0 10px rgb(0 0 0 / 0.4);
backdrop-filter: blur(10px);
overflow-y: overlay;
}
width: 100%;
justify-content: space-between;
margin: 0 0.5em !important;
&-title {
justify-self: start;
}
@@ -115,4 +121,29 @@
}
}
}
}
// Fix card width with virtual rows
.card {
width: 100%;
height: fit-content;
margin: 0;
}
// Layout css for dynamic virtual rows
&-virtual-item{
&-row{
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
flex-basis: 14%;
}
width: 14%;
height: fit-content;
display: inline-flex;
flex-direction: row;
justify-content: center;
align-items: center;
padding: 0.75em;
}
}
+1 -1
View File
@@ -291,6 +291,6 @@ h1 {
}
.glass {
background: rgb(255 255 255 / 0.1) !important;
background: rgb(0 0 0 / 0.1) !important;
backdrop-filter: blur(40px);
}