Files
suwayomi-material-you-webui/src/screens/Updates.tsx

251 lines
12 KiB
TypeScript
Raw Normal View History

2021-09-28 00:41:12 +03:30
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
2021-09-28 00:41:12 +03:30
import DownloadIcon from '@mui/icons-material/Download';
import Box from '@mui/material/Box';
import CardActionArea from '@mui/material/CardActionArea';
import Tooltip from '@mui/material/Tooltip';
import Avatar from '@mui/material/Avatar';
2021-09-28 00:41:12 +03:30
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import React, { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
2023-10-28 00:32:02 +02:00
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { LoadingPlaceholder } from '@/components/util/LoadingPlaceholder';
2024-04-29 15:29:33 +02:00
import { EmptyViewAbsoluteCentered } from '@/components/util/EmptyViewAbsoluteCentered.tsx';
2023-10-28 00:32:02 +02:00
import { DownloadStateIndicator } from '@/components/molecules/DownloadStateIndicator';
import { ChapterType } from '@/lib/graphql/generated/graphql.ts';
2023-10-28 00:32:02 +02:00
import { NavBarContext } from '@/components/context/NavbarContext.tsx';
import { UpdateChecker } from '@/components/library/UpdateChecker.tsx';
import { StyledGroupedVirtuoso } from '@/components/virtuoso/StyledGroupedVirtuoso.tsx';
import { StyledGroupHeader } from '@/components/virtuoso/StyledGroupHeader.tsx';
import { StyledGroupItemWrapper } from '@/components/virtuoso/StyledGroupItemWrapper.tsx';
import { Mangas } from '@/lib/data/Mangas.ts';
import { SpinnerImage } from '@/components/util/SpinnerImage.tsx';
import { dateTimeFormatter, epochToDate, getDateString } from '@/util/date.ts';
2024-05-05 00:50:15 +02:00
import { defaultPromiseErrorHandler } from '@/util/defaultPromiseErrorHandler.ts';
import { TypographyMaxLines } from '@/components/atoms/TypographyMaxLines.tsx';
import { ChapterIdInfo, ChapterMangaInfo } from '@/lib/data/Chapters.ts';
2024-08-05 15:20:09 +02:00
import { makeToast } from '@/components/util/Toast.tsx';
2021-09-28 00:41:12 +03:30
const groupByDate = (updates: Pick<ChapterType, 'fetchedAt'>[]): [date: string, items: number][] => {
if (!updates.length) {
return [];
}
2021-09-28 00:41:12 +03:30
const dateToItemMap = new Map<string, number>();
updates.forEach((item) => {
const date = getDateString(epochToDate(Number(item.fetchedAt)));
dateToItemMap.set(date, (dateToItemMap.get(date) ?? 0) + 1);
2021-09-28 00:41:12 +03:30
});
return [...dateToItemMap.entries()];
};
2021-09-28 00:41:12 +03:30
2023-10-28 00:32:02 +02:00
export const Updates: React.FC = () => {
const { t } = useTranslation();
const location = useLocation();
2021-09-28 00:41:12 +03:30
2023-10-28 00:32:02 +02:00
const { setTitle, setAction } = useContext(NavBarContext);
const {
data: chapterUpdateData,
loading: isLoading,
2024-05-05 00:50:15 +02:00
error,
fetchMore,
2024-05-05 00:50:15 +02:00
refetch,
} = requestManager.useGetRecentlyUpdatedChapters(undefined, {
fetchPolicy: 'cache-and-network',
notifyOnNetworkStatusChange: true,
});
const hasNextPage = !!chapterUpdateData?.chapters.pageInfo.hasNextPage;
const endCursor = chapterUpdateData?.chapters.pageInfo.endCursor;
2023-10-15 16:03:08 +02:00
const updateEntries = chapterUpdateData?.chapters.nodes ?? [];
const groupedUpdates = useMemo(() => groupByDate(updateEntries), [updateEntries]);
const groupCounts: number[] = useMemo(() => groupedUpdates.map((group) => group[1]), [groupedUpdates]);
const { data: downloaderData } = requestManager.useGetDownloadStatus();
const queue = downloaderData?.downloadStatus.queue ?? [];
2021-09-28 00:41:12 +03:30
const lastUpdateTimestampCompRef = useRef<HTMLElement>(null);
const [lastUpdateTimestampCompHeight, setLastUpdateTimestampCompHeight] = useState(0);
useLayoutEffect(() => {
setLastUpdateTimestampCompHeight(lastUpdateTimestampCompRef.current?.clientHeight ?? 0);
}, [lastUpdateTimestampCompRef.current]);
const { data: lastUpdateTimestampData } = requestManager.useGetLastGlobalUpdateTimestamp({
/**
* The {@link UpdateChecker} is responsible for updating the timestamp
*/
fetchPolicy: 'cache-only',
});
const lastUpdateTimestamp = lastUpdateTimestampData?.lastUpdateTimestamp.timestamp;
2021-09-28 00:41:12 +03:30
useEffect(() => {
setTitle(t('updates.title'));
setAction(<UpdateChecker />);
return () => {
setTitle('');
setAction(null);
};
}, [t, lastUpdateTimestamp]);
2021-09-28 00:41:12 +03:30
const downloadForChapter = (chapter: Pick<ChapterType, 'sourceOrder'> & ChapterMangaInfo) => {
const { sourceOrder, mangaId } = chapter;
return queue.find((q) => sourceOrder === q.chapter.sourceOrder && mangaId === q.manga.id);
2021-09-28 00:41:12 +03:30
};
const downloadChapter = (chapter: ChapterIdInfo) => {
2024-08-05 15:20:09 +02:00
requestManager
.addChapterToDownloadQueue(chapter.id)
.response.catch(() => makeToast(t('global.error.label.failed_to_save_changes'), 'error'));
2021-09-28 00:41:12 +03:30
};
const loadMore = useCallback(() => {
if (!hasNextPage) {
return;
}
fetchMore({ variables: { offset: updateEntries.length } });
}, [hasNextPage, endCursor]);
2024-05-05 00:50:15 +02:00
if (error) {
return (
<EmptyViewAbsoluteCentered
message={t('global.error.label.failed_to_load_data')}
messageExtra={error.message}
retry={() => refetch().catch(defaultPromiseErrorHandler('Updates::refetch'))}
/>
);
}
if (!isLoading && updateEntries.length === 0) {
2024-04-29 15:29:33 +02:00
return <EmptyViewAbsoluteCentered message={t('updates.error.label.no_updates_available')} />;
}
2021-09-28 00:41:12 +03:30
return (
<>
<Typography
ref={lastUpdateTimestampCompRef}
sx={{
marginLeft: '10px',
paddingTop: (theme) => ({ [theme.breakpoints.up('sm')]: { paddingTop: '6px' } }),
}}
>
{t('library.settings.global_update.label.last_update', {
date: lastUpdateTimestamp ? dateTimeFormatter.format(+lastUpdateTimestamp) : '-',
})}
</Typography>
<StyledGroupedVirtuoso
heightToSubtract={lastUpdateTimestampCompHeight}
style={{
// override Virtuoso default values and set them with class
height: 'undefined',
}}
components={{
Footer: () => (isLoading ? <LoadingPlaceholder usePadding /> : null),
}}
overscan={window.innerHeight * 0.5}
endReached={loadMore}
groupCounts={groupCounts}
groupContent={(index) => (
<StyledGroupHeader variant="h5" isFirstItem={index === 0}>
{groupedUpdates[index][0]}
</StyledGroupHeader>
)}
itemContent={(index) => {
const chapter = updateEntries[index];
const { manga } = chapter;
const download = downloadForChapter(chapter);
return (
2024-07-11 17:22:52 +02:00
<StyledGroupItemWrapper key={index}>
<Card>
<CardActionArea
component={Link}
to={`/manga/${chapter.manga.id}/chapter/${chapter.sourceOrder}`}
state={location.state}
sx={{
color: (theme) => theme.palette.text[chapter.isRead ? 'disabled' : 'primary'],
}}
>
<CardContent
sx={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
padding: 2,
}}
>
<Box sx={{ display: 'flex' }}>
<Link to={`/manga/${chapter.manga.id}`} style={{ textDecoration: 'none' }}>
<Avatar
variant="rounded"
sx={{
width: 56,
height: 56,
flex: '0 0 auto',
marginRight: 2,
background: 'transparent',
}}
>
<SpinnerImage
imgStyle={{
objectFit: 'cover',
width: '100%',
height: '100%',
imageRendering: 'pixelated',
}}
spinnerStyle={{ small: true }}
alt={manga.title}
src={Mangas.getThumbnailUrl(manga)}
/>
</Avatar>
</Link>
<Box sx={{ display: 'flex', flexDirection: 'column' }}>
<TypographyMaxLines variant="h5" component="h2">
{manga.title}
</TypographyMaxLines>
<TypographyMaxLines
variant="caption"
display="block"
gutterBottom
lines={1}
>
{chapter.name}
</TypographyMaxLines>
</Box>
</Box>
{download && <DownloadStateIndicator download={download} />}
{download == null && !chapter.isDownloaded && (
<Tooltip title={t('chapter.action.download.add.label.action')}>
<IconButton
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
downloadChapter(chapter);
}}
size="large"
>
<DownloadIcon />
</IconButton>
</Tooltip>
)}
</CardContent>
</CardActionArea>
</Card>
</StyledGroupItemWrapper>
);
}}
/>
</>
2021-09-28 00:41:12 +03:30
);
};