refactor ChapterOptions (#126)

* Added a useLocalStorageReducer funtion
This is mostly  a refactor of ChapterOptions to simplify it with  a reducer function
Also moved a lot of function used in ChaperList to a utility file

* Added UseCallback where needed

* renamed utility folder to util to follow the convention throughout the app

* Refactor: Moved Resume FAB to seperate file

* Renamed  Types and Function for chapter filtering and sorting with the chapterOption prefix

* more renaming
This commit is contained in:
abhijeetChawla
2022-01-24 15:09:28 +05:30
committed by GitHub
parent f273b11a82
commit aaaadebfb3
7 changed files with 216 additions and 167 deletions

View File

@@ -5,17 +5,20 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect, useCallback } from 'react';
import { Box, styled } from '@mui/system'; import { Box, styled } from '@mui/system';
import { Virtuoso } from 'react-virtuoso'; import { Virtuoso } from 'react-virtuoso';
import Typography from '@mui/material/Typography'; import Typography from '@mui/material/Typography';
import { CircularProgress, Fab } from '@mui/material'; import { CircularProgress, Stack } from '@mui/material';
import { Link } from 'react-router-dom';
import makeToast from 'components/util/Toast'; import makeToast from 'components/util/Toast';
import PlayArrow from '@mui/icons-material/PlayArrow';
import ChapterOptions from 'components/chapter/ChapterOptions'; import ChapterOptions from 'components/chapter/ChapterOptions';
import ChapterCard from 'components/chapter/ChapterCard'; import ChapterCard from 'components/chapter/ChapterCard';
import useLocalStorage from 'util/useLocalStorage'; import { useReducerLocalStorage } from 'util/useLocalStorage';
import {
chapterOptionsReducer, defaultChapterOptions, findFirstUnreadChapter,
filterAndSortChapters,
} from 'components/chapter/util';
import ResumeFab from 'components/chapter/ResumeFAB';
import useFetchChapters from './useFetchChapters'; import useFetchChapters from './useFetchChapters';
const CustomVirtuoso = styled(Virtuoso)(({ theme }) => ({ const CustomVirtuoso = styled(Virtuoso)(({ theme }) => ({
@@ -40,65 +43,15 @@ interface IProps {
id: string 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) { export default function ChapterList(props: IProps) {
const { id } = props; const { id } = props;
const [chapters, triggerChaptersUpdate, noChaptersFound] = useFetchChapters(id); const [chapters, triggerChaptersUpdate, noChaptersFound] = useFetchChapters(id);
const [firstUnreadChapter, setFirstUnreadChapter] = useState<IChapter>(); const [firstUnreadChapter, setFirstUnreadChapter] = useState<IChapter>();
const [filteredChapters, setFilteredChapters] = useState<IChapter[]>([]); const [filteredChapters, setFilteredChapters] = useState<IChapter[]>([]);
const [options, setOptions] = useLocalStorage<ChapterListOptions>( // eslint-disable-next-line max-len
`${id}filterOptions`, const [options, optionsDispatch] = useReducerLocalStorage<ChapterListOptions, ChapterOptionsReducerAction>(
{ chapterOptionsReducer, `${id}filterOptions`, defaultChapterOptions,
active: false,
unread: undefined,
downloaded: undefined,
bookmarked: undefined,
reverse: false,
sortBy: 'source',
showChapterNumber: false,
},
); );
const [, setWsClient] = useState<WebSocket>(); const [, setWsClient] = useState<WebSocket>();
@@ -120,7 +73,7 @@ export default function ChapterList(props: IProps) {
triggerChaptersUpdate(); triggerChaptersUpdate();
}, [queue.length]); }, [queue.length]);
const downloadStatusStringFor = (chapter: IChapter) => { const downloadStatusStringFor = useCallback((chapter: IChapter) => {
let rtn = ''; let rtn = '';
if (chapter.downloaded) { if (chapter.downloaded) {
rtn = ' • Downloaded'; rtn = ' • Downloaded';
@@ -131,39 +84,14 @@ export default function ChapterList(props: IProps) {
} }
}); });
return rtn; return rtn;
}; }, [queue]);
useEffect(() => { useEffect(() => {
const filtered = options.active const filtered = filterAndSortChapters(chapters, options);
? chapters.filter((chp) => unreadFilter(options.unread, chp) setFilteredChapters(filtered);
&& 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)); setFirstUnreadChapter(findFirstUnreadChapter(filtered));
}, [options, chapters]); }, [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>
));
useEffect(() => { useEffect(() => {
if (noChaptersFound) { if (noChaptersFound) {
makeToast('No chapters found', 'warning'); makeToast('No chapters found', 'warning');
@@ -185,11 +113,7 @@ export default function ChapterList(props: IProps) {
return ( return (
<> <>
<Box sx={{ <Stack direction="column">
display: 'flex',
flexDirection: 'column',
}}
>
<Box sx={{ <Box sx={{
display: 'flex', justifyContent: 'space-between', px: 1.5, mt: 1, display: 'flex', justifyContent: 'space-between', px: 1.5, mt: 1,
}} }}
@@ -197,7 +121,7 @@ export default function ChapterList(props: IProps) {
<Typography variant="h5"> <Typography variant="h5">
{`${filteredChapters.length} Chapters`} {`${filteredChapters.length} Chapters`}
</Typography> </Typography>
<ChapterOptions options={options} setOptions={setOptions} /> <ChapterOptions options={options} optionsDispatch={optionsDispatch} />
</Box> </Box>
<CustomVirtuoso <CustomVirtuoso
@@ -218,8 +142,8 @@ export default function ChapterList(props: IProps) {
useWindowScroll={window.innerWidth < 900} useWindowScroll={window.innerWidth < 900}
overscan={window.innerHeight * 0.5} overscan={window.innerHeight * 0.5}
/> />
</Box> </Stack>
<ResumeFab /> {firstUnreadChapter && <ResumeFab chapter={firstUnreadChapter} mangaId={id} />}
</> </>
); );
} }

View File

@@ -5,10 +5,10 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
import React, { useState } from 'react'; import React, { useState, useCallback } from 'react';
import FilterListIcon from '@mui/icons-material/FilterList'; import FilterListIcon from '@mui/icons-material/FilterList';
import { import {
Drawer, FormControlLabel, IconButton, Typography, Tab, Tabs, Radio, RadioGroup, Drawer, FormControlLabel, IconButton, Typography, Tab, Tabs, Radio, RadioGroup, Stack,
} from '@mui/material'; } from '@mui/material';
import ThreeStateCheckbox from 'components/util/ThreeStateCheckbox'; import ThreeStateCheckbox from 'components/util/ThreeStateCheckbox';
import { Box } from '@mui/system'; import { Box } from '@mui/system';
@@ -17,51 +17,21 @@ import TabPanel from 'components/util/TabPanel';
interface IProps{ interface IProps{
options: ChapterListOptions options: ChapterListOptions
setOptions: React.Dispatch<React.SetStateAction<ChapterListOptions>> optionsDispatch: React.Dispatch<ChapterOptionsReducerAction>
} }
const SortTab: [ChapterSortMode, string][] = [['source', 'By Source'], ['fetchedAt', 'By Fetch date']]; const SortTab: [ChapterSortMode, string][] = [['source', 'By Source'], ['fetchedAt', 'By Fetch date']];
export default function ChapterOptions(props: IProps) { export default function ChapterOptions(props: IProps) {
const { options, setOptions } = props; const { options, optionsDispatch } = props;
const [filtersOpen, setFiltersOpen] = useState(false); const [filtersOpen, setFiltersOpen] = useState(false);
const [tabNum, setTabNum] = useState(0); const [tabNum, setTabNum] = useState(0);
const setUnread = (newUnread: NullAndUndefined<boolean>) => { const filterOptions = useCallback(
const active = options.unread !== false (value: NullAndUndefined<boolean>, name: string) => {
&& options.downloaded !== false optionsDispatch({ type: 'filter', filterType: name.toLowerCase(), filterValue: value });
&& 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: ChapterSortMode) => {
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 ( return (
<> <>
@@ -101,51 +71,45 @@ export default function ChapterOptions(props: IProps) {
</Tabs> </Tabs>
<TabPanel index={0} currentIndex={tabNum}> <TabPanel index={0} currentIndex={tabNum}>
<Box sx={{ display: 'flex', flexDirection: 'column', minHeight: '150px' }}> <Box sx={{ display: 'flex', flexDirection: 'column', minHeight: '150px' }}>
<FormControlLabel control={<ThreeStateCheckbox name="Unread" checked={options.unread} onChange={setUnread} />} label="Unread" /> <FormControlLabel control={<ThreeStateCheckbox name="Unread" checked={options.unread} onChange={filterOptions} />} label="Unread" />
<FormControlLabel control={<ThreeStateCheckbox name="Downloaded" checked={options.downloaded} onChange={setDownloaded} />} label="Downloaded" /> <FormControlLabel control={<ThreeStateCheckbox name="Downloaded" checked={options.downloaded} onChange={filterOptions} />} label="Downloaded" />
<FormControlLabel control={<ThreeStateCheckbox name="Bookmarked" checked={options.bookmarked} onChange={setBookmarked} />} label="Bookmarked" /> <FormControlLabel control={<ThreeStateCheckbox name="Bookmarked" checked={options.bookmarked} onChange={filterOptions} />} label="Bookmarked" />
</Box> </Box>
</TabPanel> </TabPanel>
<TabPanel index={1} currentIndex={tabNum}> <TabPanel index={1} currentIndex={tabNum}>
<Box sx={{ display: 'flex', flexDirection: 'column', minHeight: '150px' }}> <Box sx={{ display: 'flex', flexDirection: 'column', minHeight: '150px' }}>
{ {
SortTab.map((item) => ( SortTab.map((item) => (
<Box <Stack
onClick={() => setSort(item[0])} direction="row"
sx={{ alignItems="center"
display: 'flex', spacing="2"
alignItems: 'center', sx={{ py: 1, height: 42 }}
gap: 1, onClick={() => (item[0] !== options.sortBy
height: 42, ? optionsDispatch({ type: 'sortBy', sortBy: item[0] })
py: 1, : optionsDispatch({ type: 'sortReverse' }))}
}}
> >
<Box sx={{ <Box sx={{ height: 24, width: 24 }}>
height: 24, {
width: 24, options.sortBy === item[0]
}} && (options.reverse
> ? (<ArrowUpward color="primary" />) : (<ArrowDownward color="primary" />))
{options.sortBy === item[0] }
&& (options.reverse ? (
<ArrowUpward color="primary" />
) : (
<ArrowDownward color="primary" />
))}
</Box> </Box>
<Typography>{item[1]}</Typography> <Typography>{item[1]}</Typography>
</Box> </Stack>
)) ))
} }
</Box> </Box>
</TabPanel> </TabPanel>
<TabPanel index={2} currentIndex={tabNum}> <TabPanel index={2} currentIndex={tabNum}>
<Box sx={{ display: 'flex', flexDirection: 'column', minHeight: '150px' }}> <Stack flexDirection="column" sx={{ minHeight: '150px' }}>
<RadioGroup name="chapter-title-display" onChange={handleDisplay} value={options.showChapterNumber}> <RadioGroup name="chapter-title-display" onChange={() => optionsDispatch({ type: 'showChapterNumber' })} value={options.showChapterNumber}>
<FormControlLabel label="By Source Title" value="title" control={<Radio checked={!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} />} /> <FormControlLabel label="By Chapter Number" value="chapterNumber" control={<Radio checked={options.showChapterNumber} />} />
</RadioGroup> </RadioGroup>
</Box> </Stack>
</TabPanel> </TabPanel>
</Box> </Box>
</Drawer> </Drawer>

View File

@@ -0,0 +1,32 @@
/*
* 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 from 'react';
import { Fab } from '@mui/material';
import { Link } from 'react-router-dom';
import { PlayArrow } from '@mui/icons-material';
interface ResumeFABProps{
chapter: IChapter
mangaId: string
}
export default function ResumeFab(props: ResumeFABProps) {
const { chapter: { index, lastPageRead }, mangaId } = props;
return (
<Fab
sx={{ position: 'fixed', bottom: '2em', right: '3em' }}
component={Link}
variant="extended"
color="primary"
to={`/manga/${mangaId}/chapter/${index}/page/${lastPageRead}`}
>
<PlayArrow />
{index === 1 ? 'Start' : 'Resume' }
</Fab>
);
}

View File

@@ -0,0 +1,99 @@
/*
* 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/. */
export const defaultChapterOptions: ChapterListOptions = {
active: false,
unread: undefined,
downloaded: undefined,
bookmarked: undefined,
reverse: false,
sortBy: 'source',
showChapterNumber: false,
};
export function chapterOptionsReducer(state: ChapterListOptions,
actions: ChapterOptionsReducerAction)
: ChapterListOptions {
switch (actions.type) {
case 'filter':
// eslint-disable-next-line no-case-declarations
const active = state.unread !== false
&& state.downloaded !== false
&& state.bookmarked !== false;
return {
...state,
active,
[actions.filterType!]: actions.filterValue,
};
case 'sortBy':
return { ...state, sortBy: actions.sortBy };
case 'sortReverse':
return { ...state, reverse: !state.reverse };
case 'showChapterNumber':
return { ...state, showChapterNumber: !state.showChapterNumber };
default:
throw Error('This is not a valid Action');
}
}
export function unreadFilter(unread: NullAndUndefined<boolean>, { read: isChapterRead }: IChapter) {
switch (unread) {
case true:
return !isChapterRead;
case false:
return isChapterRead;
default:
return true;
}
}
export function downloadFilter(downloaded: NullAndUndefined<boolean>,
{ downloaded: chapterDownload }: IChapter) {
switch (downloaded) {
case true:
return chapterDownload;
case false:
return !chapterDownload;
default:
return true;
}
}
export function bookmarkdFilter(bookmarked: NullAndUndefined<boolean>,
{ bookmarked: chapterBookmarked }: IChapter) {
switch (bookmarked) {
case true:
return chapterBookmarked;
case false:
return !chapterBookmarked;
default:
return true;
}
}
export function filterAndSortChapters(chapters: IChapter[], options: ChapterListOptions)
: IChapter[] {
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();
}
return Sorted;
}
export function findFirstUnreadChapter(chapters: IChapter[]): IChapter | undefined {
for (let index = chapters.length - 1; index >= 0; index--) {
if (!chapters[index].read) return chapters[index];
}
return undefined;
}

View File

@@ -14,7 +14,7 @@ import React, {
export interface IThreeStateCheckboxProps { export interface IThreeStateCheckboxProps {
name: string name: string
checked: boolean | undefined | null checked: boolean | undefined | null
onChange: (change: boolean | undefined | null) => void onChange: (change: boolean | undefined | null, name: string) => void
} }
enum CheckState { enum CheckState {
@@ -61,10 +61,10 @@ const ThreeStateCheckbox = (props: IThreeStateCheckboxProps) => {
} = props; } = props;
const [localChecked, setLocalChecked] = useState(checkedToState(checked)); const [localChecked, setLocalChecked] = useState(checkedToState(checked));
useEffect(() => setLocalChecked(checkedToState(checked)), [checked]); useEffect(() => setLocalChecked(checkedToState(checked)), [checked]);
const handleChange = () => { const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setLocalChecked(stateTransition(localChecked)); setLocalChecked(stateTransition(localChecked));
if (onChange) { if (onChange) {
onChange(stateToChecked(stateTransition(localChecked))); onChange(stateToChecked(stateTransition(localChecked)), e.currentTarget.name);
} }
}; };
const CancelBox = createSvgIcon( const CancelBox = createSvgIcon(

6
src/typings.d.ts vendored
View File

@@ -230,3 +230,9 @@ interface ChapterListOptions {
sortBy: ChapterSortMode sortBy: ChapterSortMode
showChapterNumber: boolean showChapterNumber: boolean
} }
type ChapterOptionsReducerAction =
{ type: 'filter', filterType:string, filterValue: NullAndUndefined<boolean> }
| { type: 'sortBy', sortBy: ChapterSortMode }
| { type: 'sortReverse' }
| { type: 'showChapterNumber' };

View File

@@ -5,13 +5,24 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * 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/. */ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
import React, { useState, Dispatch, SetStateAction } from 'react'; import React, {
useState,
Dispatch,
SetStateAction,
useReducer,
Reducer,
} from 'react';
import storage from './localStorage'; import storage from './localStorage';
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
export default function useLocalStorage<T>(key: string, defaultValue: T | (() => T)) : [T, Dispatch<SetStateAction<T>>] { export default function useLocalStorage<T>(
key: string,
defaultValue: T | (() => T),
): [T, Dispatch<SetStateAction<T>>] {
const initialState = defaultValue instanceof Function ? defaultValue() : defaultValue; const initialState = defaultValue instanceof Function ? defaultValue() : defaultValue;
const [storedValue, setStoredValue] = useState<T>(storage.getItem(key, initialState)); const [storedValue, setStoredValue] = useState<T>(
storage.getItem(key, initialState),
);
const setValue = ((value: T | ((prevState: T) => T)) => { const setValue = ((value: T | ((prevState: T) => T)) => {
// Allow value to be a function so we have same API as useState // Allow value to be a function so we have same API as useState
@@ -22,3 +33,16 @@ export default function useLocalStorage<T>(key: string, defaultValue: T | (() =>
return [storedValue, setValue]; return [storedValue, setValue];
} }
export function useReducerLocalStorage<S, A>(
reducer: Reducer<S, A>,
key: string,
defaultState: S | (() => S),
) {
const [storedValue, setValue] = useLocalStorage(key, defaultState);
return useReducer((state: S, action: A): S => {
const newState = reducer(state, action);
setValue(newState);
return newState;
}, storedValue);
}