refactor: improve library page, fix playbutton issues, improve overall app performance
This commit is contained in:
12 files changed
+1867
-2017
No files matched your search
@@ -1,22 +1,9 @@
|
||||
import {
|
||||
type BaseItemDto,
|
||||
type BaseItemDtoQueryResult,
|
||||
BaseItemKind,
|
||||
ItemFields,
|
||||
ItemFilter,
|
||||
LocationType,
|
||||
type MediaSegmentDtoQueryResult,
|
||||
type PlaybackInfoResponse,
|
||||
SortOrder,
|
||||
} from "@jellyfin/sdk/lib/generated-client";
|
||||
import { getDisplayPreferencesApi } from "@jellyfin/sdk/lib/utils/api/display-preferences-api";
|
||||
import { getItemsApi } from "@jellyfin/sdk/lib/utils/api/items-api";
|
||||
import { getMediaInfoApi } from "@jellyfin/sdk/lib/utils/api/media-info-api";
|
||||
import { getMediaSegmentsApi } from "@jellyfin/sdk/lib/utils/api/media-segments-api";
|
||||
import { getPlaylistsApi } from "@jellyfin/sdk/lib/utils/api/playlists-api";
|
||||
import { getTvShowsApi } from "@jellyfin/sdk/lib/utils/api/tv-shows-api";
|
||||
import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api";
|
||||
import { getUserLibraryApi } from "@jellyfin/sdk/lib/utils/api/user-library-api";
|
||||
import type { SxProps } from "@mui/material";
|
||||
import Button, { type ButtonProps } from "@mui/material/Button";
|
||||
import Fab from "@mui/material/Fab";
|
||||
@@ -24,16 +11,14 @@ import LinearProgress from "@mui/material/LinearProgress";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import { useMutation, useQuery } from "@tanstack/react-query";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import type { AxiosResponse } from "axios";
|
||||
import { useSnackbar } from "notistack";
|
||||
import React, { type MouseEvent, memo } from "react"; // Import memo
|
||||
import type PlayResult from "@//utils/types/playResult";
|
||||
import { getRuntimeCompact } from "@/utils/date/time";
|
||||
import getSubtitle from "@/utils/methods/getSubtitles";
|
||||
import playbackProfile from "@/utils/playback-profiles";
|
||||
import { getNextEpisode, getPlaybackInfo } from "@/utils/methods/playback";
|
||||
import { useApiInContext } from "@/utils/store/api";
|
||||
import { generateAudioStreamUrl, playAudio } from "@/utils/store/audioPlayback";
|
||||
import { useCentralStore } from "@/utils/store/central";
|
||||
import { usePhotosPlayback } from "@/utils/store/photosPlayback";
|
||||
import { playItem } from "@/utils/store/playback";
|
||||
import { setQueue } from "@/utils/store/queue";
|
||||
@@ -73,7 +58,7 @@ const MemoizedLinearProgress = memo(({ value }: { value: number }) => (
|
||||
zIndex: 0,
|
||||
mixBlendMode: "difference",
|
||||
}}
|
||||
//@ts-ignore
|
||||
//@ts-expect-error
|
||||
color="white"
|
||||
/>
|
||||
));
|
||||
@@ -95,7 +80,6 @@ const PlayButton = ({
|
||||
playlistItemId = "",
|
||||
}: PlayButtonProps) => {
|
||||
const api = useApiInContext((s) => s.api);
|
||||
const user = useCentralStore((s) => s.currentUser);
|
||||
const navigate = useNavigate();
|
||||
// const setPlaybackDataLoading = usePlaybackDataLoadStore(
|
||||
// (state) => state.setisPending,
|
||||
@@ -107,348 +91,23 @@ const PlayButton = ({
|
||||
const itemQuery = useMutation({
|
||||
mutationKey: ["playButton", item?.Id, userId],
|
||||
mutationFn: async (currentEpisodeId?: string) => {
|
||||
// setPlaybackDataLoading(true);
|
||||
|
||||
/**
|
||||
* Item / Items QueryResult
|
||||
*/
|
||||
let result: undefined | AxiosResponse<BaseItemDtoQueryResult, any>;
|
||||
/**
|
||||
* Current item MediaSource info
|
||||
*/
|
||||
let mediaSource: undefined | AxiosResponse<PlaybackInfoResponse, any>;
|
||||
/**
|
||||
* Current item MediaSegments
|
||||
*/
|
||||
let mediaSegments: undefined | MediaSegmentDtoQueryResult;
|
||||
/**
|
||||
* Index of episode or item in queue
|
||||
*/
|
||||
let index = 0;
|
||||
if (!api) {
|
||||
throw new Error("API is not available");
|
||||
}
|
||||
if (!userId) {
|
||||
throw new Error("User ID is not available");
|
||||
}
|
||||
if (!item.Id) {
|
||||
throw new Error("Item ID is not available");
|
||||
}
|
||||
if (playlistItem) {
|
||||
result = await getPlaylistsApi(api).getPlaylistItems({
|
||||
userId: userId,
|
||||
playlistId: playlistItemId,
|
||||
});
|
||||
} else {
|
||||
switch (itemType) {
|
||||
case BaseItemKind.Episode:
|
||||
if (item.SeriesId && item.SeasonId) {
|
||||
result = await getTvShowsApi(api).getEpisodes({
|
||||
seriesId: item.SeriesId,
|
||||
fields: [
|
||||
ItemFields.MediaSources,
|
||||
ItemFields.MediaStreams,
|
||||
ItemFields.Overview,
|
||||
ItemFields.Chapters,
|
||||
ItemFields.Trickplay,
|
||||
],
|
||||
enableUserData: true,
|
||||
userId: userId,
|
||||
seasonId: item.SeasonId,
|
||||
isMissing: false,
|
||||
// startItemId: item.Id,
|
||||
});
|
||||
|
||||
if (
|
||||
result.data.Items?.map((i) => i.Id).indexOf(
|
||||
currentEpisodeId,
|
||||
) === -1
|
||||
) {
|
||||
throw new Error(
|
||||
`Episode having id ${currentEpisodeId} not found, index return -1`,
|
||||
);
|
||||
}
|
||||
index =
|
||||
result.data.Items?.map((i) => i.Id).indexOf(currentEpisodeId) ??
|
||||
0;
|
||||
if (currentAudioTrack === "auto") {
|
||||
const defaultAudioStreamIndex =
|
||||
result.data.Items?.[index].MediaSources?.[0]
|
||||
.DefaultAudioStreamIndex;
|
||||
mediaSource = await getMediaInfoApi(api).getPostedPlaybackInfo({
|
||||
audioStreamIndex: Number(defaultAudioStreamIndex),
|
||||
subtitleStreamIndex:
|
||||
currentSubTrack === "nosub" ? -1 : currentSubTrack,
|
||||
itemId: result.data.Items?.[index]?.Id ?? "",
|
||||
startTimeTicks:
|
||||
result.data.Items?.[index].UserData?.PlaybackPositionTicks,
|
||||
userId: userId,
|
||||
mediaSourceId:
|
||||
result.data.Items?.[index].MediaSources?.[0]?.Id ?? "",
|
||||
playbackInfoDto: {
|
||||
DeviceProfile: playbackProfile,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
mediaSource = await getMediaInfoApi(api).getPostedPlaybackInfo({
|
||||
audioStreamIndex: currentAudioTrack,
|
||||
subtitleStreamIndex:
|
||||
currentSubTrack === "nosub" ? -1 : currentSubTrack,
|
||||
itemId: result.data.Items?.[index]?.Id ?? "",
|
||||
startTimeTicks:
|
||||
result.data.Items?.[index].UserData?.PlaybackPositionTicks,
|
||||
userId: userId,
|
||||
mediaSourceId:
|
||||
result.data.Items?.[index].MediaSources?.[0]?.Id ?? "",
|
||||
playbackInfoDto: {
|
||||
DeviceProfile: playbackProfile,
|
||||
},
|
||||
});
|
||||
}
|
||||
mediaSegments = (
|
||||
await getMediaSegmentsApi(api).getItemSegments({
|
||||
itemId: result.data.Items?.[index]?.Id ?? "",
|
||||
})
|
||||
)?.data;
|
||||
}
|
||||
break;
|
||||
case BaseItemKind.Series:
|
||||
result = await getTvShowsApi(api).getEpisodes({
|
||||
seriesId: item.Id,
|
||||
fields: [
|
||||
ItemFields.MediaSources,
|
||||
ItemFields.MediaStreams,
|
||||
ItemFields.Overview,
|
||||
ItemFields.Chapters,
|
||||
ItemFields.Trickplay,
|
||||
],
|
||||
enableUserData: true,
|
||||
userId: userId,
|
||||
isMissing: false,
|
||||
});
|
||||
if (
|
||||
currentEpisodeId &&
|
||||
result.data.Items?.map((i) => i.Id).indexOf(currentEpisodeId) ===
|
||||
-1
|
||||
) {
|
||||
throw new Error(
|
||||
`Episode having id=${currentEpisodeId} not found, index return -1`,
|
||||
);
|
||||
}
|
||||
if (!currentEpisodeId) {
|
||||
index = 0;
|
||||
} else {
|
||||
index =
|
||||
result.data.Items?.map((i) => i.Id).indexOf(currentEpisodeId) ??
|
||||
0;
|
||||
}
|
||||
if (
|
||||
result.data.Items?.[index].Id &&
|
||||
result.data.Items?.[index].MediaSources?.[0]?.Id
|
||||
) {
|
||||
if (currentAudioTrack === "auto") {
|
||||
const defaultAudioStreamIndex =
|
||||
result?.data.Items?.[
|
||||
index
|
||||
].MediaSources?.[0].MediaStreams?.find(
|
||||
(track) => track.IsDefault,
|
||||
)?.Index ??
|
||||
result?.data.Items?.[
|
||||
index
|
||||
].MediaSources?.[0].MediaStreams?.find(
|
||||
(track) =>
|
||||
track.Language ===
|
||||
user?.Configuration?.AudioLanguagePreference,
|
||||
)?.Index ??
|
||||
result.data.Items?.[index].MediaSources?.[0]
|
||||
.DefaultAudioStreamIndex;
|
||||
mediaSource = await getMediaInfoApi(api).getPostedPlaybackInfo({
|
||||
audioStreamIndex: Number(defaultAudioStreamIndex),
|
||||
subtitleStreamIndex:
|
||||
currentSubTrack === "nosub" ? -1 : currentSubTrack,
|
||||
itemId: result.data.Items[index].Id ?? "",
|
||||
startTimeTicks:
|
||||
result.data.Items?.[0].UserData?.PlaybackPositionTicks,
|
||||
userId: userId,
|
||||
mediaSourceId:
|
||||
result.data.Items?.[index].MediaSources?.[0].Id ?? "",
|
||||
playbackInfoDto: {
|
||||
DeviceProfile: playbackProfile,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
mediaSource = await getMediaInfoApi(api).getPostedPlaybackInfo({
|
||||
audioStreamIndex: currentAudioTrack,
|
||||
subtitleStreamIndex:
|
||||
currentSubTrack === "nosub" ? -1 : currentSubTrack,
|
||||
itemId: result.data.Items[index].Id ?? "",
|
||||
startTimeTicks:
|
||||
result.data.Items?.[0].UserData?.PlaybackPositionTicks,
|
||||
userId: userId,
|
||||
mediaSourceId:
|
||||
result.data.Items?.[index].MediaSources?.[0].Id ?? "",
|
||||
playbackInfoDto: {
|
||||
DeviceProfile: playbackProfile,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
mediaSegments = (
|
||||
await getMediaSegmentsApi(api).getItemSegments({
|
||||
itemId: result.data.Items?.[index].Id ?? "",
|
||||
})
|
||||
)?.data;
|
||||
} else {
|
||||
throw new Error(
|
||||
`No media source id provieded for the episode. Return values are seriesId = ${result.data.Items?.[index].Id}, mediaSourceId = ${result.data.Items?.[index].MediaSources?.[0]?.Id}, index = ${index}`,
|
||||
);
|
||||
}
|
||||
break;
|
||||
case BaseItemKind.Playlist:
|
||||
case BaseItemKind.MusicAlbum:
|
||||
result = await getItemsApi(api).getItems({
|
||||
parentId: item.Id,
|
||||
userId: userId,
|
||||
fields: [ItemFields.MediaSources, ItemFields.MediaStreams],
|
||||
sortOrder: [SortOrder.Ascending],
|
||||
sortBy: ["IndexNumber"],
|
||||
});
|
||||
break;
|
||||
case BaseItemKind.MusicArtist:
|
||||
result = await getItemsApi(api).getItems({
|
||||
artistIds: [item.Id ?? ""],
|
||||
recursive: true,
|
||||
includeItemTypes: [BaseItemKind.Audio],
|
||||
userId: userId,
|
||||
fields: [ItemFields.MediaSources, ItemFields.MediaStreams],
|
||||
sortOrder: [SortOrder.Ascending],
|
||||
sortBy: ["PremiereDate", "ProductionYear", "SortName"],
|
||||
});
|
||||
break;
|
||||
case BaseItemKind.BoxSet:
|
||||
result = await getItemsApi(api).getItems({
|
||||
parentId: item.Id,
|
||||
userId,
|
||||
fields: [
|
||||
ItemFields.MediaSources,
|
||||
ItemFields.MediaStreams,
|
||||
ItemFields.Chapters,
|
||||
ItemFields.Trickplay,
|
||||
],
|
||||
sortOrder: [SortOrder.Ascending],
|
||||
sortBy: ["IndexNumber"],
|
||||
});
|
||||
if (
|
||||
result.data.Items?.[index]?.Id &&
|
||||
result.data.Items?.[index].MediaSources?.[0]?.Id
|
||||
) {
|
||||
if (currentAudioTrack === "auto") {
|
||||
const defaultAudioStreamIndex =
|
||||
result.data.Items?.[index].MediaSources?.[0]
|
||||
.DefaultAudioStreamIndex;
|
||||
mediaSource = await getMediaInfoApi(api).getPostedPlaybackInfo({
|
||||
audioStreamIndex: Number(defaultAudioStreamIndex),
|
||||
subtitleStreamIndex:
|
||||
currentSubTrack === "nosub" ? -1 : currentSubTrack,
|
||||
itemId: result.data.Items?.[index].Id ?? "",
|
||||
startTimeTicks:
|
||||
result.data.Items?.[0].UserData?.PlaybackPositionTicks,
|
||||
userId: userId,
|
||||
mediaSourceId:
|
||||
result.data.Items?.[index].MediaSources?.[0].Id ?? "",
|
||||
playbackInfoDto: {
|
||||
DeviceProfile: playbackProfile,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
mediaSource = await getMediaInfoApi(api).getPostedPlaybackInfo({
|
||||
audioStreamIndex: currentAudioTrack,
|
||||
subtitleStreamIndex:
|
||||
currentSubTrack === "nosub" ? -1 : currentSubTrack,
|
||||
itemId: result.data.Items?.[index].Id ?? "",
|
||||
startTimeTicks:
|
||||
result.data.Items?.[0].UserData?.PlaybackPositionTicks,
|
||||
userId: userId,
|
||||
mediaSourceId:
|
||||
result.data.Items?.[index].MediaSources?.[0].Id ?? "",
|
||||
playbackInfoDto: {
|
||||
DeviceProfile: playbackProfile,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
break;
|
||||
case BaseItemKind.Photo:
|
||||
{
|
||||
const photo = (
|
||||
await getUserLibraryApi(api).getItem({
|
||||
itemId: item.Id,
|
||||
})
|
||||
).data;
|
||||
result = await getItemsApi(api).getItems({
|
||||
parentId: photo.ParentId ?? "",
|
||||
filters: [ItemFilter.IsNotFolder],
|
||||
recursive: false,
|
||||
sortBy: ["SortName"],
|
||||
mediaTypes: ["Photo"],
|
||||
excludeLocationTypes: [LocationType.Virtual],
|
||||
collapseBoxSetItems: false,
|
||||
});
|
||||
}
|
||||
break;
|
||||
default:
|
||||
result = await getItemsApi(api).getItems({
|
||||
ids: [item.Id ?? ""],
|
||||
userId: userId,
|
||||
fields: [
|
||||
ItemFields.MediaSources,
|
||||
ItemFields.MediaStreams,
|
||||
ItemFields.Chapters,
|
||||
ItemFields.Trickplay,
|
||||
],
|
||||
sortOrder: [SortOrder.Ascending],
|
||||
sortBy: ["IndexNumber"],
|
||||
});
|
||||
if (currentAudioTrack === "auto") {
|
||||
const defaultAudioStreamIndex =
|
||||
result.data.Items?.[index].MediaSources?.[0]
|
||||
.DefaultAudioStreamIndex;
|
||||
mediaSource = await getMediaInfoApi(api).getPostedPlaybackInfo({
|
||||
audioStreamIndex: Number(defaultAudioStreamIndex),
|
||||
subtitleStreamIndex:
|
||||
currentSubTrack === "nosub" ? -1 : currentSubTrack,
|
||||
itemId: item.Id ?? "",
|
||||
startTimeTicks:
|
||||
result.data.Items?.[0].UserData?.PlaybackPositionTicks,
|
||||
userId: userId,
|
||||
mediaSourceId:
|
||||
result.data.Items?.[0].MediaSources?.[0]?.Id ?? "",
|
||||
playbackInfoDto: {
|
||||
DeviceProfile: playbackProfile,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
mediaSource = await getMediaInfoApi(api).getPostedPlaybackInfo({
|
||||
audioStreamIndex: currentAudioTrack,
|
||||
subtitleStreamIndex:
|
||||
currentSubTrack === "nosub" ? -1 : currentSubTrack,
|
||||
itemId: item.Id ?? "",
|
||||
startTimeTicks:
|
||||
result.data.Items?.[0].UserData?.PlaybackPositionTicks,
|
||||
userId: userId,
|
||||
mediaSourceId:
|
||||
result.data.Items?.[0].MediaSources?.[0]?.Id ?? "",
|
||||
playbackInfoDto: {
|
||||
DeviceProfile: playbackProfile,
|
||||
},
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return {
|
||||
item: result?.data,
|
||||
mediaSource: mediaSource?.data,
|
||||
mediaSegments,
|
||||
episodeIndex: index,
|
||||
};
|
||||
return await getPlaybackInfo(api, userId, item, {
|
||||
currentAudioTrack,
|
||||
currentSubTrack,
|
||||
currentEpisodeId,
|
||||
playlistItem,
|
||||
playlistItemId,
|
||||
});
|
||||
},
|
||||
onSuccess: async (result: PlayResult | null) => {
|
||||
if (!api) {
|
||||
@@ -472,14 +131,6 @@ const PlayButton = ({
|
||||
return;
|
||||
}
|
||||
|
||||
const displayPreferences = await getDisplayPreferencesApi(
|
||||
api,
|
||||
).getDisplayPreferences({
|
||||
userId: userId,
|
||||
displayPreferencesId: api.deviceInfo.id,
|
||||
client: "blink",
|
||||
});
|
||||
|
||||
if (audio) {
|
||||
// Album/Individual audio track playback
|
||||
const playbackUrl = generateAudioStreamUrl(
|
||||
@@ -522,41 +173,55 @@ const PlayButton = ({
|
||||
}
|
||||
|
||||
// Subtitle
|
||||
const userSubtitleLanguagePreference = (await getUserApi(api).getCurrentUser()).data.Configuration?.SubtitleLanguagePreference;
|
||||
const userSubtitleLanguagePreference = (
|
||||
await getUserApi(api).getCurrentUser()
|
||||
).data.Configuration?.SubtitleLanguagePreference;
|
||||
// Get all subtitle streams
|
||||
const allSubtitles = result?.mediaSource?.MediaSources?.[0]?.MediaStreams?.filter(
|
||||
(stream) => stream.Type === "Subtitle"
|
||||
);
|
||||
const allSubtitles =
|
||||
result?.mediaSource?.MediaSources?.[0]?.MediaStreams?.filter(
|
||||
(stream) => stream.Type === "Subtitle",
|
||||
);
|
||||
// Find preferred subtitle based on user's language preference
|
||||
const preferredSubtitle =
|
||||
allSubtitles?.find(sub => sub.Language === userSubtitleLanguagePreference)
|
||||
|| null;
|
||||
allSubtitles?.find(
|
||||
(sub) => sub.Language === userSubtitleLanguagePreference,
|
||||
) || null;
|
||||
|
||||
const subtitle = getSubtitle(
|
||||
preferredSubtitle?.Index ?? result.mediaSource.MediaSources?.[0].DefaultSubtitleStreamIndex ?? -1,
|
||||
preferredSubtitle?.Index ??
|
||||
result.mediaSource.MediaSources?.[0].DefaultSubtitleStreamIndex ??
|
||||
-1,
|
||||
result?.mediaSource?.MediaSources?.[0]?.MediaStreams,
|
||||
);
|
||||
|
||||
// Audio
|
||||
const userAudioLanguagePreference = (await getUserApi(api).getCurrentUser()).data.Configuration?.AudioLanguagePreference;
|
||||
const userAudioLanguagePreference = (
|
||||
await getUserApi(api).getCurrentUser()
|
||||
).data.Configuration?.AudioLanguagePreference;
|
||||
// Get all audio streams
|
||||
const allAudioTracks = result.mediaSource.MediaSources?.[0].MediaStreams?.filter(
|
||||
(value) => value.Type === "Audio",
|
||||
);
|
||||
const allAudioTracks =
|
||||
result.mediaSource.MediaSources?.[0].MediaStreams?.filter(
|
||||
(value) => value.Type === "Audio",
|
||||
);
|
||||
// Find preferred audio track based on user's language preference
|
||||
const preferredAudioTrack =
|
||||
allAudioTracks?.find(track => track.Language === userAudioLanguagePreference)
|
||||
|| allAudioTracks?.find(track => track.IsDefault)
|
||||
|| allAudioTracks?.[0];
|
||||
const preferredAudioTrack =
|
||||
allAudioTracks?.find(
|
||||
(track) => track.Language === userAudioLanguagePreference,
|
||||
) ||
|
||||
allAudioTracks?.find((track) => track.IsDefault) ||
|
||||
allAudioTracks?.[0];
|
||||
|
||||
const audio = {
|
||||
track: preferredAudioTrack?.Index ?? result.mediaSource.MediaSources?.[0].DefaultAudioStreamIndex ?? 0,
|
||||
track:
|
||||
preferredAudioTrack?.Index ??
|
||||
result.mediaSource.MediaSources?.[0].DefaultAudioStreamIndex ??
|
||||
0,
|
||||
allTracks: allAudioTracks,
|
||||
};
|
||||
|
||||
// URL generation
|
||||
const urlOptions: URLSearchParams = {
|
||||
//@ts-ignore
|
||||
//@ts-expect-error
|
||||
Static: true,
|
||||
tag: result?.mediaSource.MediaSources?.[0].ETag,
|
||||
mediaSourceId: result?.mediaSource.MediaSources?.[0].Id,
|
||||
@@ -579,14 +244,6 @@ const PlayButton = ({
|
||||
const startPosition =
|
||||
result?.item?.Items?.[episodeIndex].UserData?.PlaybackPositionTicks;
|
||||
|
||||
let initVolume = "1";
|
||||
if (
|
||||
displayPreferences.data.CustomPrefs?.RememberVolume &&
|
||||
displayPreferences.data.CustomPrefs?.Volume
|
||||
) {
|
||||
initVolume = displayPreferences.data.CustomPrefs?.Volume;
|
||||
}
|
||||
|
||||
const videoTrack =
|
||||
result.mediaSource.MediaSources?.[0].MediaStreams?.filter(
|
||||
(value) => value.Type === "Video",
|
||||
@@ -659,46 +316,44 @@ const PlayButton = ({
|
||||
if (!item.Id) {
|
||||
throw new Error("Item ID is not available");
|
||||
}
|
||||
let data: BaseItemDtoQueryResult | null = null;
|
||||
const continueWatching = await getItemsApi(api).getResumeItems({
|
||||
const seasons = await getTvShowsApi(api).getSeasons({
|
||||
seriesId: item.Id,
|
||||
userId: userId,
|
||||
limit: 1,
|
||||
mediaTypes: ["Video"],
|
||||
parentId: item.Id,
|
||||
enableUserData: true,
|
||||
fields: [ItemFields.MediaStreams, ItemFields.MediaSources],
|
||||
});
|
||||
const nextUp = await getTvShowsApi(api).getNextUp({
|
||||
userId: userId,
|
||||
parentId: item.Id,
|
||||
limit: 1,
|
||||
|
||||
const currentSeason = seasons.data.Items?.find((season) => {
|
||||
return season.UserData?.Played !== true;
|
||||
});
|
||||
if ((continueWatching.data.Items?.length ?? 0) > 0) {
|
||||
data = continueWatching.data;
|
||||
} else if ((nextUp.data.Items?.length ?? 0) > 0) {
|
||||
data = nextUp.data;
|
||||
} else {
|
||||
return null;
|
||||
|
||||
const episode = await getNextEpisode(
|
||||
api,
|
||||
userId,
|
||||
item.Id,
|
||||
currentSeason?.IndexNumber ?? 0,
|
||||
);
|
||||
if (episode) {
|
||||
return { Items: [episode] };
|
||||
}
|
||||
return data;
|
||||
return { Items: [] };
|
||||
},
|
||||
// enabled: itemType === BaseItemKind.Series,
|
||||
});
|
||||
|
||||
if (iconOnly) {
|
||||
return (
|
||||
//@ts-ignore
|
||||
//@ts-expect-error
|
||||
<Fab
|
||||
color="primary"
|
||||
aria-label="Play"
|
||||
className={className}
|
||||
onClick={(e) => {
|
||||
if (item.Type === "Episode") {
|
||||
handleClick(e, item.Id)
|
||||
handleClick(e, item.Id);
|
||||
} else if (itemType === BaseItemKind.Series) {
|
||||
handleClick(e, currentEpisode.data?.Items?.[0]?.Id)
|
||||
handleClick(e, currentEpisode.data?.Items?.[0]?.Id);
|
||||
} else {
|
||||
handleClick(e)
|
||||
handleClick(e);
|
||||
}
|
||||
}}
|
||||
sx={sx}
|
||||
@@ -759,7 +414,7 @@ const PlayButton = ({
|
||||
position: "relative",
|
||||
overflow: "hidden",
|
||||
}}
|
||||
//@ts-ignore - white color is a custom color in the theme which mui's types don't know about
|
||||
//@ts-expect-error - white color is a custom color in the theme which mui's types don't know about
|
||||
color="white"
|
||||
size={size}
|
||||
disabled={
|
||||
@@ -770,31 +425,30 @@ const PlayButton = ({
|
||||
!currentEpisode.data.Items[0].Id
|
||||
}
|
||||
>
|
||||
{currentEpisode.isPending
|
||||
? "Loading..."
|
||||
: !currentEpisode.data ||
|
||||
!currentEpisode.data.Items ||
|
||||
currentEpisode.data.Items.length === 0
|
||||
? "No episodes to watch found"
|
||||
: (
|
||||
<>
|
||||
Watch S{currentEpisode.data.Items[0].ParentIndexNumber ?? 1}E
|
||||
{currentEpisode.data.Items[0]?.IndexNumber ?? 1}
|
||||
<MemoizedLinearProgress
|
||||
//@ts-ignore
|
||||
value={
|
||||
100 >
|
||||
(currentEpisode.data.Items[0].UserData?.PlayedPercentage ??
|
||||
100) &&
|
||||
{currentEpisode.isPending ? (
|
||||
"Loading..."
|
||||
) : !currentEpisode.data ||
|
||||
!currentEpisode.data.Items ||
|
||||
currentEpisode.data.Items.length === 0 ? (
|
||||
"No episodes to watch found"
|
||||
) : (
|
||||
<>
|
||||
Watch S{currentEpisode.data.Items[0].ParentIndexNumber ?? 1}E
|
||||
{currentEpisode.data.Items[0]?.IndexNumber ?? 1}
|
||||
<MemoizedLinearProgress
|
||||
//@ts-expect-error
|
||||
value={
|
||||
100 >
|
||||
(currentEpisode.data.Items[0].UserData?.PlayedPercentage ??
|
||||
0) > 0
|
||||
? currentEpisode.data.Items[0].UserData?.PlayedPercentage
|
||||
: 0
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
100) &&
|
||||
(currentEpisode.data.Items[0].UserData?.PlayedPercentage ??
|
||||
0) > 0
|
||||
? currentEpisode.data.Items[0].UserData?.PlayedPercentage
|
||||
: 0
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
{(currentEpisode.data?.Items?.[0]?.UserData?.PlaybackPositionTicks ??
|
||||
0) > 0 && (
|
||||
@@ -849,7 +503,7 @@ const PlayButton = ({
|
||||
position: "relative",
|
||||
overflow: "hidden",
|
||||
}}
|
||||
//@ts-ignore - white color is a custom color in the theme which mui's types don't know about
|
||||
//@ts-expect-error - white color is a custom color in the theme which mui's types don't know about
|
||||
color="white"
|
||||
size={size}
|
||||
>
|
||||
@@ -863,7 +517,7 @@ const PlayButton = ({
|
||||
? "Play Now"
|
||||
: "Watch Now"}
|
||||
<MemoizedLinearProgress
|
||||
//@ts-ignore
|
||||
//@ts-expect-error
|
||||
value={
|
||||
100 > (item.UserData?.PlayedPercentage ?? 100) &&
|
||||
(item.UserData?.PlayedPercentage ?? 0) > 0
|
||||
|
||||
+124
-79
@@ -1,40 +1,24 @@
|
||||
/** @format */
|
||||
|
||||
|
||||
import {
|
||||
type BaseItemDto,
|
||||
BaseItemKind,
|
||||
type ImageType,
|
||||
} from "@jellyfin/sdk/lib/generated-client";
|
||||
import Typography from "@mui/material/Typography";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import React, { memo } from "react";
|
||||
import type React from "react";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
import { ErrorBoundary } from "react-error-boundary";
|
||||
import { useInView } from "react-intersection-observer";
|
||||
import getImageUrlsApi from "@/utils/methods/getImageUrlsApi";
|
||||
import { useApiInContext } from "@/utils/store/api";
|
||||
import LikeButton from "../buttons/likeButton";
|
||||
import MarkPlayedButton from "../buttons/markPlayedButton";
|
||||
import PlayButton from "../buttons/playButton";
|
||||
import { getTypeIcon } from "../utils/iconsCollection";
|
||||
import "./card.scss";
|
||||
|
||||
import { useInView } from "react-intersection-observer";
|
||||
import getImageUrlsApi from "@/utils/methods/getImageUrlsApi";
|
||||
import { useApiInContext } from "@/utils/store/api";
|
||||
|
||||
const CardComponent = ({
|
||||
item,
|
||||
cardTitle,
|
||||
cardCaption,
|
||||
imageType = "Primary",
|
||||
cardType = "square",
|
||||
queryKey,
|
||||
userId,
|
||||
seriesId,
|
||||
hideText = false,
|
||||
onClick,
|
||||
disableOverlay = false,
|
||||
overrideIcon,
|
||||
skipInView = false,
|
||||
}: {
|
||||
interface CardProps {
|
||||
item: BaseItemDto;
|
||||
cardTitle: string | undefined | null;
|
||||
cardCaption?: string | null | number;
|
||||
@@ -48,10 +32,32 @@ const CardComponent = ({
|
||||
disableOverlay?: boolean;
|
||||
overrideIcon?: any;
|
||||
skipInView?: boolean;
|
||||
}
|
||||
|
||||
const CardContent = ({
|
||||
item,
|
||||
cardTitle,
|
||||
cardCaption,
|
||||
imageType = "Primary",
|
||||
cardType = "square",
|
||||
queryKey,
|
||||
userId,
|
||||
seriesId,
|
||||
hideText = false,
|
||||
onClick,
|
||||
disableOverlay = false,
|
||||
overrideIcon,
|
||||
inView,
|
||||
forwardedRef,
|
||||
}: CardProps & {
|
||||
inView: boolean;
|
||||
forwardedRef?: React.Ref<HTMLDivElement>;
|
||||
}) => {
|
||||
const api = useApiInContext((s) => s.api);
|
||||
const navigate = useNavigate();
|
||||
const defaultOnClick = () => {
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
|
||||
const defaultOnClick = useCallback(() => {
|
||||
if (item?.Id) {
|
||||
switch (item?.Type) {
|
||||
case BaseItemKind.BoxSet:
|
||||
@@ -80,21 +86,23 @@ const CardComponent = ({
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
}, [item?.Id, item?.Type, navigate]);
|
||||
|
||||
const { ref, inView } = useInView({
|
||||
threshold: 0.1,
|
||||
skip: skipInView,
|
||||
});
|
||||
const handleInteractionStart = useCallback(() => setIsHovered(true), []);
|
||||
const handleInteractionEnd = useCallback(() => setIsHovered(false), []);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="card"
|
||||
ref={ref}
|
||||
onClick={onClick ? onClick : defaultOnClick}
|
||||
ref={forwardedRef}
|
||||
onClick={onClick || defaultOnClick}
|
||||
onMouseEnter={handleInteractionStart}
|
||||
onMouseLeave={handleInteractionEnd}
|
||||
onFocus={handleInteractionStart}
|
||||
onBlur={handleInteractionEnd}
|
||||
>
|
||||
<div className={`card-image-container ${cardType}`}>
|
||||
<ErrorBoundary fallback>
|
||||
<ErrorBoundary fallback={<></>}>
|
||||
<div
|
||||
className="card-indicator check"
|
||||
style={{
|
||||
@@ -109,13 +117,17 @@ const CardComponent = ({
|
||||
opacity: item.UserData?.UnplayedItemCount ? 1 : 0,
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
variant="subtitle2"
|
||||
padding="0.1em 0.4em"
|
||||
fontWeight={400}
|
||||
<span
|
||||
style={{
|
||||
padding: "0.1em 0.4em",
|
||||
fontWeight: 400,
|
||||
fontSize: "0.875rem",
|
||||
lineHeight: 1.57,
|
||||
fontFamily: "inherit",
|
||||
}}
|
||||
>
|
||||
{item.UserData?.UnplayedItemCount}
|
||||
</Typography>
|
||||
</span>
|
||||
</div>
|
||||
</ErrorBoundary>
|
||||
<div className="card-image-icon-container">
|
||||
@@ -123,7 +135,7 @@ const CardComponent = ({
|
||||
? getTypeIcon(overrideIcon)
|
||||
: getTypeIcon(item.Type ?? "universal")}
|
||||
</div>
|
||||
{(skipInView || inView) && (
|
||||
{inView && (
|
||||
<img
|
||||
alt={item.Name ?? "blink"}
|
||||
src={
|
||||
@@ -146,48 +158,53 @@ const CardComponent = ({
|
||||
width: "100%",
|
||||
opacity: 0,
|
||||
display: "block",
|
||||
transition: "opacity 0.3s ease-in-out",
|
||||
}}
|
||||
loading="lazy"
|
||||
onLoad={(e) => {
|
||||
e.currentTarget.style.setProperty("opacity", "1");
|
||||
e.currentTarget.style.opacity = "1";
|
||||
}}
|
||||
className="card-image"
|
||||
/>
|
||||
)}
|
||||
{(skipInView || inView) && !disableOverlay && (
|
||||
{inView && !disableOverlay && (
|
||||
<div className="card-overlay">
|
||||
<PlayButton
|
||||
item={item}
|
||||
userId={userId}
|
||||
itemType={item.Type ?? "Movie"}
|
||||
currentAudioTrack="auto"
|
||||
currentSubTrack={-1}
|
||||
currentVideoTrack={0}
|
||||
className="card-play-button"
|
||||
iconOnly
|
||||
audio={
|
||||
item.Type === BaseItemKind.MusicAlbum ||
|
||||
item.Type === BaseItemKind.Audio ||
|
||||
item.Type === BaseItemKind.AudioBook ||
|
||||
item.Type === BaseItemKind.Playlist
|
||||
}
|
||||
playlistItem={item.Type === BaseItemKind.Playlist}
|
||||
playlistItemId={item.Id}
|
||||
/>
|
||||
<LikeButton
|
||||
itemId={item.Id}
|
||||
itemName={item.Name ?? ""}
|
||||
isFavorite={item.UserData?.IsFavorite}
|
||||
queryKey={queryKey}
|
||||
userId={userId}
|
||||
/>
|
||||
<MarkPlayedButton
|
||||
itemId={item.Id}
|
||||
itemName={item.Name ?? ""}
|
||||
isPlayed={item.UserData?.Played}
|
||||
queryKey={queryKey}
|
||||
userId={userId}
|
||||
/>
|
||||
{isHovered && (
|
||||
<>
|
||||
<PlayButton
|
||||
item={item}
|
||||
userId={userId}
|
||||
itemType={item.Type ?? "Movie"}
|
||||
currentAudioTrack="auto"
|
||||
currentSubTrack={-1}
|
||||
currentVideoTrack={0}
|
||||
className="card-play-button"
|
||||
iconOnly
|
||||
audio={
|
||||
item.Type === BaseItemKind.MusicAlbum ||
|
||||
item.Type === BaseItemKind.Audio ||
|
||||
item.Type === BaseItemKind.AudioBook ||
|
||||
item.Type === BaseItemKind.Playlist
|
||||
}
|
||||
playlistItem={item.Type === BaseItemKind.Playlist}
|
||||
playlistItemId={item.Id}
|
||||
/>
|
||||
<LikeButton
|
||||
itemId={item.Id}
|
||||
itemName={item.Name ?? ""}
|
||||
isFavorite={item.UserData?.IsFavorite}
|
||||
queryKey={queryKey}
|
||||
userId={userId}
|
||||
/>
|
||||
<MarkPlayedButton
|
||||
itemId={item.Id}
|
||||
itemName={item.Name ?? ""}
|
||||
isPlayed={item.UserData?.Played}
|
||||
queryKey={queryKey}
|
||||
userId={userId}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{(item.UserData?.PlaybackPositionTicks ?? -1) > 0 && (
|
||||
@@ -205,20 +222,48 @@ const CardComponent = ({
|
||||
className="card-text-container"
|
||||
style={{ display: hideText ? "none" : "block", marginLeft: "0.2em" }}
|
||||
>
|
||||
<Typography mt={1} variant="subtitle2" noWrap style={{ opacity: 0.9 }}>
|
||||
<div
|
||||
style={{
|
||||
marginTop: "8px",
|
||||
opacity: 0.9,
|
||||
fontSize: "0.875rem",
|
||||
fontWeight: 500,
|
||||
whiteSpace: "nowrap",
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
}}
|
||||
>
|
||||
{cardTitle}
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="caption"
|
||||
noWrap
|
||||
style={{ opacity: 0.6 }}
|
||||
lineHeight="auto"
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
opacity: 0.6,
|
||||
fontSize: "0.75rem",
|
||||
whiteSpace: "nowrap",
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
}}
|
||||
>
|
||||
{cardCaption}
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const CardWithInView = (props: CardProps) => {
|
||||
const { ref, inView } = useInView({
|
||||
threshold: 0.1,
|
||||
});
|
||||
|
||||
return <CardContent {...props} inView={inView} forwardedRef={ref} />;
|
||||
};
|
||||
|
||||
const CardComponent = (props: CardProps) => {
|
||||
if (props.skipInView) {
|
||||
return <CardContent {...props} inView={true} />;
|
||||
}
|
||||
return <CardWithInView {...props} />;
|
||||
};
|
||||
|
||||
export const Card = memo(CardComponent);
|
||||
@@ -0,0 +1,7 @@
|
||||
import React from "react";
|
||||
|
||||
const ItemHeader = () => {
|
||||
return <div>Item Header</div>;
|
||||
};
|
||||
|
||||
export default ItemHeader;
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
} from "@jellyfin/sdk/lib/generated-client";
|
||||
import { useSuspenseQuery } from "@tanstack/react-query";
|
||||
import { getRouteApi } from "@tanstack/react-router";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { useWindowVirtualizer } from "@tanstack/react-virtual";
|
||||
import React, {
|
||||
useCallback,
|
||||
useEffect,
|
||||
@@ -20,6 +20,8 @@ import { useApiInContext } from "@/utils/store/api";
|
||||
import { useBackdropStore } from "@/utils/store/backdrop";
|
||||
import { useCentralStore } from "@/utils/store/central";
|
||||
import { useLibraryStateStore } from "@/utils/store/libraryState";
|
||||
// @ts-expect-error: Vite worker import
|
||||
import BackdropWorker from "@/utils/workers/backdrop.worker?worker";
|
||||
import { Card } from "../card/card";
|
||||
|
||||
const libraryRoute = getRouteApi("/_api/library/$id");
|
||||
@@ -64,6 +66,20 @@ const LibraryItemsGrid = () => {
|
||||
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,
|
||||
@@ -78,44 +94,39 @@ const LibraryItemsGrid = () => {
|
||||
);
|
||||
// --- Backdrop ---
|
||||
const setBackdrop = useBackdropStore(useShallow((s) => s.setBackdrop));
|
||||
const backdropIndexRef = useRef(0);
|
||||
const backdropItems = useMemo<BaseItemDto[]>(() => {
|
||||
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(() => {
|
||||
if (!api || !backdropItems || backdropItems.length === 0) return;
|
||||
// Set initial backdrop once when items change
|
||||
const firstBackdrop = backdropItems[0];
|
||||
const firstKey = Object.keys(
|
||||
firstBackdrop?.ImageBlurHashes?.Backdrop ?? {},
|
||||
)[0];
|
||||
const initialHash = firstBackdrop?.ImageBlurHashes?.Backdrop?.[firstKey];
|
||||
if (initialHash) setBackdrop(initialHash);
|
||||
backdropIndexRef.current = 0;
|
||||
|
||||
const intervalId = setInterval(() => {
|
||||
backdropIndexRef.current =
|
||||
(backdropIndexRef.current + 1) % backdropItems.length;
|
||||
const idx = backdropIndexRef.current;
|
||||
const keys = Object.keys(
|
||||
backdropItems[idx]?.ImageBlurHashes?.Backdrop ?? {},
|
||||
);
|
||||
const nextHash = backdropItems[idx]?.ImageBlurHashes?.Backdrop?.[keys[0]];
|
||||
if (nextHash) {
|
||||
// Defer backdrop update to idle/raf to avoid blocking UI
|
||||
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(nextHash));
|
||||
schedule(() => setBackdrop(event.data.payload));
|
||||
}
|
||||
}, 10_000); // Update backdrop every 10s
|
||||
return () => clearInterval(intervalId);
|
||||
}, [api, backdropItems, setBackdrop]);
|
||||
};
|
||||
|
||||
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<HTMLDivElement | null>(null);
|
||||
const scrollParentRef = useRef<HTMLElement | null>(null);
|
||||
const [containerWidth, setContainerWidth] = useState<number>(0);
|
||||
|
||||
// Determine column count based on container width (simple heuristic)
|
||||
@@ -132,10 +143,7 @@ const LibraryItemsGrid = () => {
|
||||
useEffect(() => {
|
||||
measureColumns();
|
||||
if (!parentRef.current) return;
|
||||
// Find the page's scroll container ('.scrollY') to avoid nested scrolling
|
||||
scrollParentRef.current = parentRef.current.closest(
|
||||
".scrollY",
|
||||
) as HTMLElement | null;
|
||||
|
||||
const ro = new ResizeObserver(() => measureColumns());
|
||||
ro.observe(parentRef.current);
|
||||
return () => ro.disconnect();
|
||||
@@ -166,11 +174,11 @@ const LibraryItemsGrid = () => {
|
||||
[estimatedTallCardHeight],
|
||||
);
|
||||
|
||||
const virtualizer = useVirtualizer({
|
||||
const virtualizer = useWindowVirtualizer({
|
||||
count: rowCount,
|
||||
getScrollElement: () => scrollParentRef.current,
|
||||
estimateSize: estimateRowHeight,
|
||||
overscan: 2,
|
||||
overscan: 6,
|
||||
scrollMargin: parentRef.current?.offsetTop ?? 0,
|
||||
});
|
||||
|
||||
const virtualItems = virtualizer.getVirtualItems();
|
||||
@@ -229,7 +237,9 @@ const LibraryItemsGrid = () => {
|
||||
key={row.key}
|
||||
style={{
|
||||
position: "absolute",
|
||||
transform: `translateY(${row.start}px)`,
|
||||
transform: `translateY(${
|
||||
row.start - virtualizer.options.scrollMargin
|
||||
}px)`,
|
||||
left: 0,
|
||||
width: "100%",
|
||||
display: "flex",
|
||||
|
||||
Reference in new issue
Block a user