Chapter filter is woking (#114)

This commit is contained in:
abhijeetChawla
2021-12-13 19:52:56 +05:30
committed by GitHub
parent 51376be845
commit d382998d06
5 changed files with 424 additions and 127 deletions

View File

@@ -24,12 +24,15 @@ interface IProps{
chapter: IChapter
triggerChaptersUpdate: () => void
downloadStatusString: string
showChapterNumber: boolean
}
export default function ChapterCard(props: IProps) {
const theme = useTheme();
const { chapter, triggerChaptersUpdate, downloadStatusString } = props;
const {
chapter, triggerChaptersUpdate, downloadStatusString, showChapterNumber,
} = props;
const dateStr = chapter.uploadDate && new Date(chapter.uploadDate).toISOString().slice(0, 10);
@@ -109,7 +112,7 @@ export default function ChapterCard(props: IProps) {
<span style={{ color: theme.palette.primary.dark }}>
{chapter.bookmarked && <BookmarkIcon />}
</span>
{chapter.name}
{ showChapterNumber ? `Chapter ${chapter.chapterNumber}` : chapter.name}
</Typography>
<Typography variant="caption" display="block" gutterBottom>
{chapter.scanlator}

View File

@@ -0,0 +1,246 @@
/*
* 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/. */
import React, { useState, useEffect } from 'react';
import { Box, styled } from '@mui/system';
import { Virtuoso } from 'react-virtuoso';
import Typography from '@mui/material/Typography';
import ChapterCard from 'components/ChapterCard';
import { CircularProgress, Fab } from '@mui/material';
import { Link } from 'react-router-dom';
import makeToast from 'components/util/Toast';
import client from 'util/client';
import PlayArrow from '@mui/icons-material/PlayArrow';
import ChapterOptions from 'components/ChapterOptions';
import useLocalStorage from '../util/useLocalStorage';
const List = styled(Virtuoso)(({ theme }) => ({
listStyle: 'none',
padding: 0,
minHeight: '200px',
[theme.breakpoints.up('md')]: {
width: '50vw',
// 64px for the Appbar, 40px for the ChapterCount Header
height: 'calc(100vh - 64px - 40px)',
margin: 0,
},
}));
const baseWebsocketUrl = JSON.parse(window.localStorage.getItem('serverBaseURL')!).replace('http', 'ws');
const initialQueue = {
status: 'Stopped',
queue: [],
} as IQueue;
interface IProps {
id: string
}
function unreadFilter(unread: NullAndUndefined<boolean>, { read: isChapterRead }: IChapter) {
switch (unread) {
case true:
return !isChapterRead;
case false:
return isChapterRead;
default:
return true;
}
}
function downloadFilter(downloaded: NullAndUndefined<boolean>,
{ downloaded: chapterDownload }: IChapter) {
switch (downloaded) {
case true:
return chapterDownload;
case false:
return !chapterDownload;
default:
return true;
}
}
function bookmarkdFilter(bookmarked: NullAndUndefined<boolean>,
{ bookmarked: chapterBookmarked }: IChapter) {
switch (bookmarked) {
case true:
return chapterBookmarked;
case false:
return !chapterBookmarked;
default:
return true;
}
}
function findFirstUnreadChapter(chapters: IChapter[]): IChapter | undefined {
for (let index = chapters.length - 1; index >= 0; index--) {
if (!chapters[index].read) return chapters[index];
}
return undefined;
}
export default function ChapterList(props: IProps) {
const { id } = props;
const [chapters, setChapters] = useState<IChapter[]>([]);
const [noChaptersFound, setNoChaptersFound] = useState(false);
const [chapterUpdateTriggerer, setChapterUpdateTriggerer] = useState(0);
const [fetchedOnline, setFetchedOnline] = useState(false);
const [fetchedOffline, setFetchedOffline] = useState(false);
const [firstUnreadChapter, setFirstUnreadChapter] = useState<IChapter>();
const [filteredChapters, setFilteredChapters] = useState<IChapter[]>([]);
const [options, setOptions] = useLocalStorage<ChapterListOptions>(
`${id}filterOptions`,
{
active: false,
unread: undefined,
downloaded: undefined,
bookmarked: undefined,
reverse: false,
sortBy: 'source',
showChapterNumber: false,
},
);
const [, setWsClient] = useState<WebSocket>();
const [{ queue }, setQueueState] = useState<IQueue>(initialQueue);
function triggerChaptersUpdate() {
setChapterUpdateTriggerer(chapterUpdateTriggerer + 1);
}
useEffect(() => {
const wsc = new WebSocket(`${baseWebsocketUrl}/api/v1/downloads`);
wsc.onmessage = (e) => {
const data = JSON.parse(e.data) as IQueue;
setQueueState(data);
};
setWsClient(wsc);
return () => wsc.close();
}, []);
useEffect(() => {
triggerChaptersUpdate();
}, [queue.length]);
const downloadStatusStringFor = (chapter: IChapter) => {
let rtn = '';
if (chapter.downloaded) {
rtn = ' • Downloaded';
}
queue.forEach((q) => {
if (chapter.index === q.chapterIndex && chapter.mangaId === q.mangaId) {
rtn = ` • Downloading (${(q.progress * 100).toFixed(2)}%)`;
}
});
return rtn;
};
useEffect(() => {
const shouldFetchOnline = fetchedOffline && !fetchedOnline;
client.get(`/api/v1/manga/${id}/chapters?onlineFetch=${shouldFetchOnline}`)
.then((response) => response.data)
.then((data) => {
if (data.length === 0 && fetchedOffline) {
makeToast('No chapters found', 'warning');
setNoChaptersFound(true);
}
setChapters(data);
})
.then(() => {
if (shouldFetchOnline) {
setFetchedOnline(true);
} else setFetchedOffline(true);
});
}, [fetchedOnline, fetchedOffline, chapterUpdateTriggerer]);
useEffect(() => {
const filtered = options.active
? chapters.filter((chp) => unreadFilter(options.unread, chp)
&& downloadFilter(options.downloaded, chp)
&& bookmarkdFilter(options.bookmarked, chp))
: [...chapters];
const Sorted = options.sortBy === 'fetchedAt'
? filtered.sort((a, b) => a.fetchedAt - b.fetchedAt)
: filtered;
if (options.reverse) {
Sorted.reverse();
}
setFilteredChapters(Sorted);
setFirstUnreadChapter(findFirstUnreadChapter(filtered));
}, [options, chapters]);
const ResumeFab = () => (firstUnreadChapter === undefined ? null
: (
<Fab
sx={{ position: 'fixed', bottom: '2em', right: '3em' }}
component={Link}
variant="extended"
color="primary"
to={`/manga/${id}/chapter/${firstUnreadChapter.index}/page/${firstUnreadChapter.lastPageRead}`}
>
<PlayArrow />
{firstUnreadChapter.index === 1 ? 'Start' : 'Resume' }
</Fab>
));
if (chapters.length === 0 || noChaptersFound) {
return (
<div style={{
margin: '10px auto',
display: 'flex',
justifyContent: 'center',
}}
>
<CircularProgress thickness={5} />
</div>
);
}
return (
<>
<Box sx={{
display: 'flex',
flexDirection: 'column',
}}
>
<Box sx={{
display: 'flex', justifyContent: 'space-between', px: 1.5, mt: 1,
}}
>
<Typography variant="h5">
{`${filteredChapters.length} Chapters`}
</Typography>
<ChapterOptions options={options} setOptions={setOptions} />
</Box>
<List
style={{ // override Virtuoso default values and set them with class
height: 'undefined',
// 900 is the md breakpoint in MUI
overflowY: window.innerWidth < 900 ? 'visible' : 'auto',
}}
totalCount={filteredChapters.length}
itemContent={(index:number) => (
<ChapterCard
showChapterNumber={options.showChapterNumber}
chapter={filteredChapters[index]}
downloadStatusString={downloadStatusStringFor(filteredChapters[index])}
triggerChaptersUpdate={triggerChaptersUpdate}
/>
)}
useWindowScroll={window.innerWidth < 900}
overscan={window.innerHeight * 0.5}
/>
</Box>
<ResumeFab />
</>
);
}

View File

@@ -0,0 +1,155 @@
/*
* 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/. */
import React, { useState } from 'react';
import FilterListIcon from '@mui/icons-material/FilterList';
import {
Drawer, FormControlLabel, IconButton, Typography, Tab, Tabs, Radio, RadioGroup,
} from '@mui/material';
import ThreeStateCheckbox from 'components/util/ThreeStateCheckbox';
import { Box } from '@mui/system';
import { ArrowDownward, ArrowUpward } from '@mui/icons-material';
import TabPanel from 'components/util/TabPanel';
interface IProps{
options: ChapterListOptions
setOptions: React.Dispatch<React.SetStateAction<ChapterListOptions>>
}
const SortTab: [SortMode, string][] = [['source', 'By Source'], ['fetchedAt', 'By Fetch date']];
export default function ChapterOptions(props: IProps) {
const { options, setOptions } = props;
const [filtersOpen, setFiltersOpen] = useState(false);
const [tabNum, setTabNum] = useState(0);
const setUnread = (newUnread: NullAndUndefined<boolean>) => {
const active = options.unread !== false
&& options.downloaded !== false
&& options.bookmarked !== false;
setOptions({ ...options, active, unread: newUnread });
};
const setDownloaded = (newDownloaded: NullAndUndefined<boolean>) => {
const active = options.unread !== false
&& options.downloaded !== false
&& options.bookmarked !== false;
setOptions({ ...options, active, downloaded: newDownloaded });
};
const setBookmarked = (newBookmarked: NullAndUndefined<boolean>) => {
const active = options.unread !== false
&& options.downloaded !== false
&& options.bookmarked !== false;
setOptions({ ...options, active, bookmarked: newBookmarked });
};
const setSort = (newSort: SortMode) => {
if (newSort !== options.sortBy) {
setOptions({ ...options, sortBy: newSort });
} else {
setOptions({ ...options, reverse: !options.reverse });
}
};
const handleDisplay = (e: React.ChangeEvent<HTMLInputElement>) => {
const showChapterNumber = e.target.value === 'chapterNumber';
if (showChapterNumber !== options.showChapterNumber) {
setOptions({ ...options, showChapterNumber });
}
};
return (
<>
<IconButton
onClick={() => setFiltersOpen(!filtersOpen)}
color={options.active ? 'warning' : 'default'}
>
<FilterListIcon />
</IconButton>
<Drawer
anchor="bottom"
open={filtersOpen}
onClose={() => setFiltersOpen(false)}
PaperProps={{
style: {
maxWidth: 600,
padding: '1em',
marginLeft: 'auto',
marginRight: 'auto',
minHeight: '150px',
},
}}
>
<Box>
<Tabs
key={tabNum}
value={tabNum}
variant="fullWidth"
onChange={(e, newTab) => setTabNum(newTab)}
indicatorColor="primary"
textColor="primary"
>
<Tab value={0} label="Filter" />
<Tab value={1} label="Sort" />
<Tab value={2} label="Display" />
</Tabs>
<TabPanel index={0} currentIndex={tabNum}>
<Box sx={{ display: 'flex', flexDirection: 'column', minHeight: '150px' }}>
<FormControlLabel control={<ThreeStateCheckbox name="Unread" checked={options.unread} onChange={setUnread} />} label="Unread" />
<FormControlLabel control={<ThreeStateCheckbox name="Downloaded" checked={options.downloaded} onChange={setDownloaded} />} label="Downloaded" />
<FormControlLabel control={<ThreeStateCheckbox name="Bookmarked" checked={options.bookmarked} onChange={setBookmarked} />} label="Bookmarked" />
</Box>
</TabPanel>
<TabPanel index={1} currentIndex={tabNum}>
<Box sx={{ display: 'flex', flexDirection: 'column', minHeight: '150px' }}>
{
SortTab.map((item) => (
<Box
onClick={() => setSort(item[0])}
sx={{
display: 'flex',
alignItems: 'center',
gap: 1,
height: 42,
py: 1,
}}
>
<Box sx={{
height: 24,
width: 24,
}}
>
{options.sortBy === item[0]
&& (options.reverse ? (
<ArrowUpward color="primary" />
) : (
<ArrowDownward color="primary" />
))}
</Box>
<Typography>{item[1]}</Typography>
</Box>
))
}
</Box>
</TabPanel>
<TabPanel index={2} currentIndex={tabNum}>
<Box sx={{ display: 'flex', flexDirection: 'column', minHeight: '150px' }}>
<RadioGroup name="chapter-title-display" onChange={handleDisplay} value={options.showChapterNumber}>
<FormControlLabel label="By Source Title" value="title" control={<Radio checked={!options.showChapterNumber} />} />
<FormControlLabel label="By Chapter Number" value="chapterNumber" control={<Radio checked={options.showChapterNumber} />} />
</RadioGroup>
</Box>
</TabPanel>
</Box>
</Drawer>
</>
);
}