Move chapter files into new folder
This commit is contained in:
27
src/modules/chapter/Chapter.constants.ts
Normal file
27
src/modules/chapter/Chapter.constants.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* 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 { TranslationKey } from '@/Base.types.ts';
|
||||
import { ChapterListOptions, ChapterSortMode } from '@/modules/chapter/Chapter.types.ts';
|
||||
|
||||
export const DEFAULT_CHAPTER_OPTIONS: ChapterListOptions = {
|
||||
active: false,
|
||||
unread: undefined,
|
||||
downloaded: undefined,
|
||||
bookmarked: undefined,
|
||||
reverse: true,
|
||||
sortBy: 'source',
|
||||
showChapterNumber: false,
|
||||
};
|
||||
|
||||
export const CHAPTER_SORT_OPTIONS_TO_TRANSLATION_KEY: Record<ChapterSortMode, TranslationKey> = {
|
||||
source: 'global.sort.label.by_source',
|
||||
chapterNumber: 'global.sort.label.by_chapter_number',
|
||||
uploadedAt: 'global.sort.label.by_upload_date',
|
||||
fetchedAt: 'global.sort.label.by_fetch_date',
|
||||
};
|
||||
27
src/modules/chapter/Chapter.types.ts
Normal file
27
src/modules/chapter/Chapter.types.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* 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 { NullAndUndefined } from '@/Base.types.ts';
|
||||
|
||||
export type ChapterSortMode = 'fetchedAt' | 'source' | 'chapterNumber' | 'uploadedAt';
|
||||
|
||||
export interface ChapterListOptions {
|
||||
active: boolean;
|
||||
unread: NullAndUndefined<boolean>;
|
||||
downloaded: NullAndUndefined<boolean>;
|
||||
bookmarked: NullAndUndefined<boolean>;
|
||||
reverse: boolean;
|
||||
sortBy: ChapterSortMode;
|
||||
showChapterNumber: boolean;
|
||||
}
|
||||
|
||||
export type ChapterOptionsReducerAction =
|
||||
| { type: 'filter'; filterType: string; filterValue: NullAndUndefined<boolean> }
|
||||
| { type: 'sortBy'; sortBy: ChapterSortMode }
|
||||
| { type: 'sortReverse' }
|
||||
| { type: 'showChapterNumber' };
|
||||
279
src/modules/chapter/components/ChapterList.tsx
Normal file
279
src/modules/chapter/components/ChapterList.tsx
Normal file
@@ -0,0 +1,279 @@
|
||||
/*
|
||||
* 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 Box from '@mui/material/Box';
|
||||
import Stack from '@mui/material/Stack';
|
||||
import Tooltip from '@mui/material/Tooltip';
|
||||
import { styled } from '@mui/material/styles';
|
||||
import Typography from '@mui/material/Typography';
|
||||
import { ComponentProps, useCallback, useMemo, useState } from 'react';
|
||||
import { Virtuoso } from 'react-virtuoso';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import IconButton from '@mui/material/IconButton';
|
||||
import DownloadIcon from '@mui/icons-material/Download';
|
||||
import DoneAllIcon from '@mui/icons-material/DoneAll';
|
||||
import PopupState, { bindMenu, bindTrigger } from 'material-ui-popup-state';
|
||||
import Menu from '@mui/material/Menu';
|
||||
import { requestManager } from '@/lib/requests/requests/RequestManager.ts';
|
||||
import { ChapterCard } from '@/modules/chapter/components/cards/ChapterCard.tsx';
|
||||
import { ResumeFab } from '@/components/manga/ResumeFAB.tsx';
|
||||
import { filterAndSortChapters } from '@/modules/chapter/utils/ChapterList.util.tsx';
|
||||
import { EmptyViewAbsoluteCentered } from '@/modules/core/components/placeholder/EmptyViewAbsoluteCentered.tsx';
|
||||
import { ChaptersToolbarMenu } from '@/modules/chapter/components/ChaptersToolbarMenu.tsx';
|
||||
import { SelectionFAB } from '@/components/collection/SelectionFAB.tsx';
|
||||
import { DEFAULT_FULL_FAB_HEIGHT } from '@/modules/core/components/buttons/StyledFab.tsx';
|
||||
import {
|
||||
GetChaptersMangaQuery,
|
||||
GetChaptersMangaQueryVariables,
|
||||
MangaScreenFieldsFragment,
|
||||
} from '@/lib/graphql/generated/graphql.ts';
|
||||
import { useSelectableCollection } from '@/components/collection/useSelectableCollection.ts';
|
||||
import { SelectableCollectionSelectAll } from '@/components/collection/SelectableCollectionSelectAll.tsx';
|
||||
import { Chapters } from '@/modules/chapter/services/Chapters.ts';
|
||||
import { ChaptersWithMeta, ChapterWithMetaType } from '@/modules/chapter/services/ChaptersWithMeta.ts';
|
||||
import { ChapterActionMenuItems } from '@/modules/chapter/components/actions/ChapterActionMenuItems.tsx';
|
||||
import { ChaptersDownloadActionMenuItems } from '@/modules/chapter/components/actions/ChaptersDownloadActionMenuItems.tsx';
|
||||
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
|
||||
import { LoadingPlaceholder } from '@/modules/core/components/placeholder/LoadingPlaceholder.tsx';
|
||||
import { GET_CHAPTERS_MANGA } from '@/lib/graphql/queries/ChapterQuery.ts';
|
||||
import { Mangas } from '@/lib/data/Mangas.ts';
|
||||
import { useNavBarContext } from '@/components/context/NavbarContext.tsx';
|
||||
import { useResizeObserver } from '@/modules/core/hooks/useResizeObserver.tsx';
|
||||
import { MediaQuery } from '@/lib/ui/MediaQuery.tsx';
|
||||
import { shouldForwardProp } from '@/modules/core/utils/ShouldForwardProp.ts';
|
||||
import { useChapterOptions } from '@/modules/chapter/hooks/useChapterOptions.tsx';
|
||||
|
||||
type ChapterListHeaderProps = {
|
||||
scrollbarWidth: number;
|
||||
};
|
||||
const ChapterListHeader = styled(Stack, {
|
||||
shouldForwardProp: shouldForwardProp<ChapterListHeaderProps>(['scrollbarWidth']),
|
||||
})<ChapterListHeaderProps>(({ theme, scrollbarWidth }) => ({
|
||||
padding: theme.spacing(1),
|
||||
paddingRight: `calc(${scrollbarWidth}px + ${theme.spacing(1)})`,
|
||||
paddingBottom: 0,
|
||||
[theme.breakpoints.down('md')]: {
|
||||
paddingRight: theme.spacing(1),
|
||||
},
|
||||
}));
|
||||
|
||||
type StyledVirtuosoProps = { topOffset: number };
|
||||
const StyledVirtuoso = styled(Virtuoso, {
|
||||
shouldForwardProp: shouldForwardProp<StyledVirtuosoProps>(['topOffset']),
|
||||
})<StyledVirtuosoProps>(({ theme, topOffset }) => ({
|
||||
listStyle: 'none',
|
||||
padding: 0,
|
||||
[theme.breakpoints.up('md')]: {
|
||||
height: `calc(100vh - ${topOffset}px)`,
|
||||
margin: 0,
|
||||
},
|
||||
}));
|
||||
|
||||
export interface IChapterWithMeta extends ChapterWithMetaType<ComponentProps<typeof ChapterCard>['chapter']> {
|
||||
selected: boolean | null;
|
||||
}
|
||||
|
||||
export const ChapterList = ({
|
||||
manga,
|
||||
isRefreshing,
|
||||
}: {
|
||||
manga: Pick<MangaScreenFieldsFragment, 'id' | 'firstUnreadChapter' | 'chapters' | 'unreadCount' | 'downloadCount'>;
|
||||
isRefreshing: boolean;
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const { appBarHeight } = useNavBarContext();
|
||||
|
||||
const isMobileWidth = MediaQuery.useIsBelowWidth('md');
|
||||
|
||||
const [chapterListHeaderHeight, setChapterListHeaderHeight] = useState(50);
|
||||
const [chapterListHeaderRef, setChapterListHeaderRef] = useState<HTMLDivElement | null>(null);
|
||||
useResizeObserver(
|
||||
chapterListHeaderRef,
|
||||
useCallback(() => setChapterListHeaderHeight(chapterListHeaderRef?.offsetHeight ?? 0), [chapterListHeaderRef]),
|
||||
);
|
||||
|
||||
const scrollbarWidth = MediaQuery.useGetScrollbarSize('width');
|
||||
|
||||
const { data: downloaderData } = requestManager.useGetDownloadStatus();
|
||||
const queue = downloaderData?.downloadStatus.queue ?? [];
|
||||
|
||||
const [options, dispatch] = useChapterOptions(manga.id);
|
||||
const {
|
||||
data: chaptersData,
|
||||
loading: isLoading,
|
||||
error,
|
||||
refetch,
|
||||
} = requestManager.useGetMangaChapters<GetChaptersMangaQuery, GetChaptersMangaQueryVariables>(
|
||||
GET_CHAPTERS_MANGA,
|
||||
manga.id,
|
||||
{ notifyOnNetworkStatusChange: true },
|
||||
);
|
||||
const chapters = useMemo(() => chaptersData?.chapters.nodes ?? [], [chaptersData?.chapters.nodes]);
|
||||
|
||||
const chapterIds = useMemo(() => chapters.map((chapter) => chapter.id), [chapters]);
|
||||
|
||||
const { areNoItemsSelected, areAllItemsSelected, selectedItemIds, handleSelectAll, handleSelection } =
|
||||
useSelectableCollection(chapters.length, { itemIds: chapterIds, currentKey: 'default' });
|
||||
|
||||
const visibleChapters = useMemo(() => filterAndSortChapters(chapters, options), [chapters, options]);
|
||||
|
||||
const nextChapterIndexToRead = manga.firstUnreadChapter?.sourceOrder;
|
||||
|
||||
const areAllChaptersRead = Mangas.isFullyRead(manga);
|
||||
const areAllChaptersDownloaded = Mangas.isFullyDownloaded(manga);
|
||||
|
||||
const noChaptersFound = chapters.length === 0;
|
||||
const noChaptersMatchingFilter = !noChaptersFound && visibleChapters.length === 0;
|
||||
|
||||
const chaptersWithMeta: IChapterWithMeta[] = useMemo(
|
||||
() =>
|
||||
visibleChapters.map((chapter) => {
|
||||
const downloadChapter = queue?.find((cd) => cd.chapter.id === chapter.id);
|
||||
const selected = !areNoItemsSelected ? selectedItemIds.includes(chapter.id) : null;
|
||||
return {
|
||||
chapter,
|
||||
downloadChapter,
|
||||
selected,
|
||||
};
|
||||
}),
|
||||
[queue, selectedItemIds, visibleChapters],
|
||||
);
|
||||
|
||||
const chapterListFAB = useMemo(() => {
|
||||
const selectedChapters = chaptersWithMeta.filter((chapter) => chapter.selected);
|
||||
|
||||
if (selectedChapters.length) {
|
||||
return (
|
||||
<SelectionFAB selectedItemsCount={selectedChapters.length} title="chapter.title_one">
|
||||
{(handleClose) => (
|
||||
<ChapterActionMenuItems selectedChapters={selectedChapters} onClose={handleClose} />
|
||||
)}
|
||||
</SelectionFAB>
|
||||
);
|
||||
}
|
||||
|
||||
if (nextChapterIndexToRead !== undefined) {
|
||||
return <ResumeFab chapterIndex={nextChapterIndexToRead} mangaId={manga.id} />;
|
||||
}
|
||||
|
||||
return null;
|
||||
}, [chaptersWithMeta]);
|
||||
|
||||
if (isLoading || (noChaptersFound && isRefreshing)) {
|
||||
return (
|
||||
<Stack sx={{ justifyContent: 'center', alignItems: 'center', position: 'relative', flexGrow: 1 }}>
|
||||
<LoadingPlaceholder />
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<Stack sx={{ justifyContent: 'center', position: 'relative', flexGrow: 1 }}>
|
||||
<EmptyViewAbsoluteCentered
|
||||
message={t('global.error.label.failed_to_load_data')}
|
||||
messageExtra={error.message}
|
||||
retry={() => refetch().catch(defaultPromiseErrorHandler('ChapterList::refetch'))}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Stack direction="column" sx={{ position: 'relative', flexBasis: '60%' }}>
|
||||
<ChapterListHeader
|
||||
ref={setChapterListHeaderRef}
|
||||
direction="row"
|
||||
alignItems="center"
|
||||
justifyContent="space-between"
|
||||
scrollbarWidth={scrollbarWidth}
|
||||
>
|
||||
<Typography variant="h5" component="h3">
|
||||
{`${visibleChapters.length} ${t('chapter.title_one', {
|
||||
count: visibleChapters.length,
|
||||
})}`}
|
||||
</Typography>
|
||||
|
||||
<Stack direction="row">
|
||||
<Tooltip title={t('chapter.action.mark_as_read.add.label.action.current')}>
|
||||
<IconButton
|
||||
disabled={areAllChaptersRead}
|
||||
onClick={() =>
|
||||
Chapters.markAsRead(
|
||||
ChaptersWithMeta.getChapters(ChaptersWithMeta.getNonRead(chaptersWithMeta)),
|
||||
true,
|
||||
manga.id,
|
||||
)
|
||||
}
|
||||
>
|
||||
<DoneAllIcon />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<PopupState variant="popover" popupId="chapterlist-download-button">
|
||||
{(popupState) => (
|
||||
<>
|
||||
<Tooltip title={t('chapter.action.download.add.label.action')}>
|
||||
<IconButton disabled={areAllChaptersDownloaded} {...bindTrigger(popupState)}>
|
||||
<DownloadIcon />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
{popupState.isOpen && (
|
||||
<Menu {...bindMenu(popupState)}>
|
||||
<ChaptersDownloadActionMenuItems
|
||||
mangaIds={[manga.id]}
|
||||
closeMenu={popupState.close}
|
||||
/>
|
||||
</Menu>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</PopupState>
|
||||
|
||||
<ChaptersToolbarMenu options={options} optionsDispatch={dispatch} />
|
||||
<SelectableCollectionSelectAll
|
||||
areAllItemsSelected={areAllItemsSelected}
|
||||
areNoItemsSelected={areNoItemsSelected}
|
||||
onChange={(checked) =>
|
||||
handleSelectAll(checked, checked ? chapters.map((chapter) => chapter.id) : [])
|
||||
}
|
||||
/>
|
||||
</Stack>
|
||||
</ChapterListHeader>
|
||||
|
||||
{noChaptersFound && <EmptyViewAbsoluteCentered message={t('chapter.error.label.no_chapter_found')} />}
|
||||
{noChaptersMatchingFilter && (
|
||||
<EmptyViewAbsoluteCentered message={t('chapter.error.label.no_matches')} />
|
||||
)}
|
||||
|
||||
<StyledVirtuoso
|
||||
topOffset={appBarHeight + chapterListHeaderHeight}
|
||||
style={{
|
||||
// override Virtuoso default values and set them with class
|
||||
height: 'undefined',
|
||||
}}
|
||||
components={{ Footer: () => <Box sx={{ paddingBottom: DEFAULT_FULL_FAB_HEIGHT }} /> }}
|
||||
totalCount={visibleChapters.length}
|
||||
itemContent={(index: number) => (
|
||||
<ChapterCard
|
||||
{...chaptersWithMeta[index]}
|
||||
allChapters={chapters}
|
||||
showChapterNumber={options.showChapterNumber}
|
||||
onSelect={(selected, selectRange) =>
|
||||
handleSelection(chaptersWithMeta[index].chapter.id, selected, { selectRange })
|
||||
}
|
||||
/>
|
||||
)}
|
||||
useWindowScroll={isMobileWidth}
|
||||
overscan={window.innerHeight * 0.5}
|
||||
/>
|
||||
</Stack>
|
||||
{chapterListFAB}
|
||||
</>
|
||||
);
|
||||
};
|
||||
116
src/modules/chapter/components/ChapterOptions.tsx
Normal file
116
src/modules/chapter/components/ChapterOptions.tsx
Normal file
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* 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 RadioGroup from '@mui/material/RadioGroup';
|
||||
import React from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { RadioInput } from '@/modules/core/components/inputs/RadioInput.tsx';
|
||||
import { SortRadioInput } from '@/modules/core/components/inputs/SortRadioInput.tsx';
|
||||
import { ThreeStateCheckboxInput } from '@/modules/core/components/inputs/ThreeStateCheckboxInput.tsx';
|
||||
import { OptionsTabs } from '@/modules/core/components/OptionsTabs.tsx';
|
||||
import { CHAPTER_SORT_OPTIONS_TO_TRANSLATION_KEY } from '@/modules/chapter/Chapter.constants.ts';
|
||||
import { TranslationKey } from '@/Base.types.ts';
|
||||
import { ChapterListOptions, ChapterOptionsReducerAction } from '@/modules/chapter/Chapter.types.ts';
|
||||
|
||||
interface IProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
options: ChapterListOptions;
|
||||
optionsDispatch: React.Dispatch<ChapterOptionsReducerAction>;
|
||||
}
|
||||
|
||||
const TITLES: { [key in 'filter' | 'sort' | 'display']: TranslationKey } = {
|
||||
filter: 'global.label.filter',
|
||||
sort: 'global.label.sort',
|
||||
display: 'global.label.display',
|
||||
};
|
||||
|
||||
export const ChapterOptions: React.FC<IProps> = ({ open, onClose, options, optionsDispatch }) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<OptionsTabs<'filter' | 'sort' | 'display'>
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
minHeight={150}
|
||||
tabs={['filter', 'sort', 'display']}
|
||||
tabTitle={(key) => t(TITLES[key])}
|
||||
tabContent={(key) => {
|
||||
if (key === 'filter') {
|
||||
return (
|
||||
<>
|
||||
<ThreeStateCheckboxInput
|
||||
label={t('global.filter.label.unread')}
|
||||
checked={options.unread}
|
||||
onChange={(c) =>
|
||||
optionsDispatch({
|
||||
type: 'filter',
|
||||
filterType: 'unread',
|
||||
filterValue: c,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<ThreeStateCheckboxInput
|
||||
label={t('global.filter.label.downloaded')}
|
||||
checked={options.downloaded}
|
||||
onChange={(c) =>
|
||||
optionsDispatch({
|
||||
type: 'filter',
|
||||
filterType: 'downloaded',
|
||||
filterValue: c,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<ThreeStateCheckboxInput
|
||||
label={t('global.filter.label.bookmarked')}
|
||||
checked={options.bookmarked}
|
||||
onChange={(c) =>
|
||||
optionsDispatch({
|
||||
type: 'filter',
|
||||
filterType: 'bookmarked',
|
||||
filterValue: c,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
if (key === 'sort') {
|
||||
return Object.entries(CHAPTER_SORT_OPTIONS_TO_TRANSLATION_KEY).map(([mode, label]) => (
|
||||
<SortRadioInput
|
||||
key={mode}
|
||||
label={t(label)}
|
||||
checked={options.sortBy === mode}
|
||||
sortDescending={options.reverse}
|
||||
onClick={() =>
|
||||
mode !== options.sortBy
|
||||
? optionsDispatch({
|
||||
type: 'sortBy',
|
||||
sortBy: mode as keyof typeof CHAPTER_SORT_OPTIONS_TO_TRANSLATION_KEY,
|
||||
})
|
||||
: optionsDispatch({ type: 'sortReverse' })
|
||||
}
|
||||
/>
|
||||
));
|
||||
}
|
||||
if (key === 'display') {
|
||||
return (
|
||||
<RadioGroup
|
||||
onChange={() => optionsDispatch({ type: 'showChapterNumber' })}
|
||||
value={options.showChapterNumber}
|
||||
>
|
||||
<RadioInput label={t('chapter.option.display.label.source_title')} value={false} />
|
||||
<RadioInput label={t('chapter.option.display.label.chapter_number')} value />
|
||||
</RadioGroup>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
44
src/modules/chapter/components/ChaptersToolbarMenu.tsx
Normal file
44
src/modules/chapter/components/ChaptersToolbarMenu.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* 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 FilterList from '@mui/icons-material/FilterList';
|
||||
import IconButton from '@mui/material/IconButton';
|
||||
import Tooltip from '@mui/material/Tooltip';
|
||||
import * as React from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ChapterOptions } from '@/modules/chapter/components/ChapterOptions.tsx';
|
||||
import { isFilterActive } from '@/modules/chapter/utils/ChapterList.util.tsx';
|
||||
import { ChapterListOptions, ChapterOptionsReducerAction } from '@/modules/chapter/Chapter.types.ts';
|
||||
|
||||
interface IProps {
|
||||
options: ChapterListOptions;
|
||||
optionsDispatch: React.Dispatch<ChapterOptionsReducerAction>;
|
||||
}
|
||||
|
||||
export const ChaptersToolbarMenu = ({ options, optionsDispatch }: IProps) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const isFiltered = isFilterActive(options);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Tooltip title={t('settings.title')}>
|
||||
<IconButton onClick={() => setOpen(true)}>
|
||||
<FilterList color={isFiltered ? 'warning' : undefined} />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<ChapterOptions
|
||||
open={open}
|
||||
onClose={() => setOpen(false)}
|
||||
options={options}
|
||||
optionsDispatch={optionsDispatch}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,237 @@
|
||||
/*
|
||||
* 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 CheckBoxOutlineBlank from '@mui/icons-material/CheckBoxOutlineBlank';
|
||||
import Delete from '@mui/icons-material/Delete';
|
||||
import Download from '@mui/icons-material/Download';
|
||||
import RemoveDone from '@mui/icons-material/RemoveDone';
|
||||
import Done from '@mui/icons-material/Done';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import BookmarkRemove from '@mui/icons-material/BookmarkRemove';
|
||||
import BookmarkAdd from '@mui/icons-material/BookmarkAdd';
|
||||
import DoneAll from '@mui/icons-material/DoneAll';
|
||||
import { useMemo } from 'react';
|
||||
import LaunchIcon from '@mui/icons-material/Launch';
|
||||
import { SelectableCollectionReturnType } from '@/components/collection/useSelectableCollection.ts';
|
||||
import {
|
||||
actionToTranslationKey,
|
||||
ChapterAction,
|
||||
ChapterBookmarkInfo,
|
||||
ChapterDownloadInfo,
|
||||
ChapterIdInfo,
|
||||
ChapterMangaInfo,
|
||||
ChapterReadInfo,
|
||||
ChapterRealUrlInfo,
|
||||
Chapters,
|
||||
} from '@/modules/chapter/services/Chapters.ts';
|
||||
import { MenuItem } from '@/modules/core/components/menu/MenuItem.tsx';
|
||||
import { IChapterWithMeta } from '@/modules/chapter/components/ChapterList.tsx';
|
||||
import { ChaptersWithMeta } from '@/modules/chapter/services/ChaptersWithMeta.ts';
|
||||
import {
|
||||
createGetMenuItemTitle,
|
||||
createIsMenuItemDisabled,
|
||||
createShouldShowMenuItem,
|
||||
} from '@/modules/core/components/menu/Menu.utils.ts';
|
||||
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
|
||||
import { useMetadataServerSettings } from '@/lib/metadata/metadataServerSettings.ts';
|
||||
|
||||
type BaseProps = { onClose: () => void };
|
||||
|
||||
type TChapter = ChapterIdInfo &
|
||||
ChapterMangaInfo &
|
||||
ChapterDownloadInfo &
|
||||
ChapterBookmarkInfo &
|
||||
ChapterReadInfo &
|
||||
ChapterRealUrlInfo;
|
||||
|
||||
type SingleModeProps = {
|
||||
chapter: TChapter;
|
||||
allChapters: TChapter[];
|
||||
handleSelection?: SelectableCollectionReturnType<TChapter['id']>['handleSelection'];
|
||||
canBeDownloaded: boolean;
|
||||
};
|
||||
|
||||
type SelectModeProps = {
|
||||
selectedChapters: IChapterWithMeta[];
|
||||
};
|
||||
|
||||
type Props =
|
||||
| (BaseProps & SingleModeProps & PropertiesNever<SelectModeProps>)
|
||||
| (BaseProps & PropertiesNever<SingleModeProps> & SelectModeProps);
|
||||
|
||||
export const ChapterActionMenuItems = ({
|
||||
chapter,
|
||||
allChapters,
|
||||
handleSelection,
|
||||
canBeDownloaded = false,
|
||||
selectedChapters = [],
|
||||
onClose,
|
||||
}: Props) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const isSingleMode = !!chapter;
|
||||
const { isDownloaded, isRead, isBookmarked } = chapter ?? {};
|
||||
|
||||
const {
|
||||
settings: { deleteChaptersWithBookmark },
|
||||
} = useMetadataServerSettings();
|
||||
|
||||
const getMenuItemTitle = createGetMenuItemTitle(isSingleMode, actionToTranslationKey);
|
||||
const shouldShowMenuItem = createShouldShowMenuItem(isSingleMode);
|
||||
const isMenuItemDisabled = createIsMenuItemDisabled(isSingleMode);
|
||||
|
||||
const {
|
||||
downloadableChapters,
|
||||
downloadedChapters,
|
||||
unbookmarkedChapters,
|
||||
bookmarkedChapters,
|
||||
unreadChapters,
|
||||
readChapters,
|
||||
} = useMemo(
|
||||
() => ({
|
||||
downloadableChapters: ChaptersWithMeta.getDownloadable(selectedChapters),
|
||||
downloadedChapters: ChaptersWithMeta.getDownloaded(selectedChapters),
|
||||
unbookmarkedChapters: ChaptersWithMeta.getNonBookmarked(selectedChapters),
|
||||
bookmarkedChapters: ChaptersWithMeta.getBookmarked(selectedChapters),
|
||||
unreadChapters: ChaptersWithMeta.getNonRead(selectedChapters),
|
||||
readChapters: ChaptersWithMeta.getRead(selectedChapters),
|
||||
}),
|
||||
[selectedChapters],
|
||||
);
|
||||
|
||||
const handleSelect = () => {
|
||||
handleSelection?.(chapter.id, true);
|
||||
onClose();
|
||||
};
|
||||
|
||||
const performAction = (action: ChapterAction | 'mark_prev_as_read', chaptersWithMeta: IChapterWithMeta[]) => {
|
||||
const isMarkPrevAsRead = action === 'mark_prev_as_read';
|
||||
const actualAction: ChapterAction = isMarkPrevAsRead ? 'mark_as_read' : action;
|
||||
|
||||
if (actualAction === 'delete' && chapter) {
|
||||
const isDeletable = Chapters.isDeletable(chapter, deleteChaptersWithBookmark);
|
||||
if (!isDeletable) {
|
||||
onClose();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const getChapters = (): SingleModeProps['chapter'][] => {
|
||||
// select mode
|
||||
if (!chapter) {
|
||||
return ChaptersWithMeta.getChapters(chaptersWithMeta);
|
||||
}
|
||||
|
||||
if (!isMarkPrevAsRead) {
|
||||
return [chapter];
|
||||
}
|
||||
|
||||
const index = allChapters.findIndex(({ id: chapterId }) => chapterId === chapter.id);
|
||||
|
||||
const isFirstChapter = index + 1 > allChapters.length - 1;
|
||||
if (isFirstChapter) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return allChapters.slice(index + 1);
|
||||
};
|
||||
|
||||
const chapters = getChapters();
|
||||
|
||||
if (!chapters.length) {
|
||||
onClose();
|
||||
return;
|
||||
}
|
||||
|
||||
Chapters.performAction(actualAction, Chapters.getIds(chapters), {
|
||||
chapters,
|
||||
wasManuallyMarkedAsRead: true,
|
||||
trackProgressMangaId: chapters[0]?.mangaId,
|
||||
}).catch(defaultPromiseErrorHandler('ChapterActionMenuItems::performAction'));
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{isSingleMode && (
|
||||
<MenuItem onClick={handleSelect} Icon={CheckBoxOutlineBlank} title={t('chapter.action.label.select')} />
|
||||
)}
|
||||
{isSingleMode && (
|
||||
<MenuItem
|
||||
Icon={LaunchIcon}
|
||||
disabled={!chapter!.realUrl}
|
||||
onClick={() => {
|
||||
window.open(chapter!.realUrl!, '_blank', 'noopener,noreferrer');
|
||||
onClose();
|
||||
}}
|
||||
title={t('chapter.action.label.open_on_source')}
|
||||
/>
|
||||
)}
|
||||
{shouldShowMenuItem(canBeDownloaded) && (
|
||||
<MenuItem
|
||||
Icon={Download}
|
||||
disabled={isMenuItemDisabled(!downloadableChapters.length)}
|
||||
onClick={() => performAction('download', downloadableChapters)}
|
||||
title={getMenuItemTitle('download', downloadableChapters.length)}
|
||||
/>
|
||||
)}
|
||||
{shouldShowMenuItem(isDownloaded) && (
|
||||
<MenuItem
|
||||
Icon={Delete}
|
||||
disabled={isMenuItemDisabled(!downloadedChapters.length)}
|
||||
onClick={() =>
|
||||
performAction(
|
||||
'delete',
|
||||
ChaptersWithMeta.getDeletable(downloadedChapters, deleteChaptersWithBookmark),
|
||||
)
|
||||
}
|
||||
title={getMenuItemTitle('delete', downloadedChapters.length)}
|
||||
/>
|
||||
)}
|
||||
{shouldShowMenuItem(!isBookmarked) && (
|
||||
<MenuItem
|
||||
Icon={BookmarkAdd}
|
||||
disabled={isMenuItemDisabled(!unbookmarkedChapters.length)}
|
||||
onClick={() => performAction('bookmark', unbookmarkedChapters)}
|
||||
title={getMenuItemTitle('bookmark', unbookmarkedChapters.length)}
|
||||
/>
|
||||
)}
|
||||
{shouldShowMenuItem(isBookmarked) && (
|
||||
<MenuItem
|
||||
Icon={BookmarkRemove}
|
||||
disabled={isMenuItemDisabled(!bookmarkedChapters.length)}
|
||||
onClick={() => performAction('unbookmark', bookmarkedChapters)}
|
||||
title={getMenuItemTitle('unbookmark', bookmarkedChapters.length)}
|
||||
/>
|
||||
)}
|
||||
{shouldShowMenuItem(!isRead) && (
|
||||
<MenuItem
|
||||
Icon={Done}
|
||||
disabled={isMenuItemDisabled(!unreadChapters.length)}
|
||||
onClick={() => performAction('mark_as_read', unreadChapters)}
|
||||
title={getMenuItemTitle('mark_as_read', unreadChapters.length)}
|
||||
/>
|
||||
)}
|
||||
{shouldShowMenuItem(isRead) && (
|
||||
<MenuItem
|
||||
Icon={RemoveDone}
|
||||
disabled={isMenuItemDisabled(!readChapters.length)}
|
||||
onClick={() => performAction('mark_as_unread', readChapters)}
|
||||
title={getMenuItemTitle('mark_as_unread', readChapters.length)}
|
||||
/>
|
||||
)}
|
||||
{isSingleMode && (
|
||||
<MenuItem
|
||||
onClick={() => performAction('mark_prev_as_read', [])}
|
||||
Icon={DoneAll}
|
||||
title={t('chapter.action.mark_as_read.add.label.action.previous')}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
* 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 MenuItem from '@mui/material/MenuItem';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useMetadataServerSettings } from '@/lib/metadata/metadataServerSettings.ts';
|
||||
import { Mangas } from '@/lib/data/Mangas.ts';
|
||||
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
|
||||
import { MangaType } from '@/lib/graphql/generated/graphql.ts';
|
||||
|
||||
const DownloadRange = {
|
||||
NEXT_1: 1,
|
||||
NEXT_5: 5,
|
||||
NEXT_10: 10,
|
||||
NEXT_25: 25,
|
||||
ALL: undefined,
|
||||
};
|
||||
|
||||
export const ChaptersDownloadActionMenuItems = ({
|
||||
mangaIds,
|
||||
closeMenu,
|
||||
}: {
|
||||
mangaIds: MangaType['id'][];
|
||||
closeMenu: () => void;
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const {
|
||||
settings: { downloadAheadLimit },
|
||||
} = useMetadataServerSettings();
|
||||
|
||||
const handleSelect = (size?: number, onlyUnread: boolean = true, downloadAhead: boolean = false) => {
|
||||
Mangas.performAction('download', mangaIds, {
|
||||
downloadAhead,
|
||||
onlyUnread,
|
||||
size,
|
||||
}).catch(defaultPromiseErrorHandler('ChapterDownloadButton::handleSelect'));
|
||||
closeMenu?.();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<MenuItem onClick={() => handleSelect(DownloadRange.NEXT_1)}>
|
||||
{t('chapter.action.download.add.label.next')}
|
||||
</MenuItem>
|
||||
<MenuItem onClick={() => handleSelect(DownloadRange.NEXT_5)}>
|
||||
{t('chapter.action.download.add.label.next_five')}
|
||||
</MenuItem>
|
||||
<MenuItem onClick={() => handleSelect(DownloadRange.NEXT_10)}>
|
||||
{t('chapter.action.download.add.label.next_ten')}
|
||||
</MenuItem>
|
||||
<MenuItem onClick={() => handleSelect(DownloadRange.NEXT_25)}>
|
||||
{t('chapter.action.download.add.label.next_twentyfive')}
|
||||
</MenuItem>
|
||||
<MenuItem onClick={() => handleSelect(downloadAheadLimit, undefined, true)}>
|
||||
{t('chapter.action.download.add.label.ahead', { count: downloadAheadLimit })}
|
||||
</MenuItem>
|
||||
<MenuItem onClick={() => handleSelect(DownloadRange.ALL, true)}>
|
||||
{t('chapter.action.download.add.label.unread')}
|
||||
</MenuItem>
|
||||
<MenuItem onClick={() => handleSelect(DownloadRange.ALL, false)}>
|
||||
{t('chapter.action.download.add.label.all')}
|
||||
</MenuItem>
|
||||
</>
|
||||
);
|
||||
};
|
||||
199
src/modules/chapter/components/cards/ChapterCard.tsx
Normal file
199
src/modules/chapter/components/cards/ChapterCard.tsx
Normal file
@@ -0,0 +1,199 @@
|
||||
/*
|
||||
* 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 BookmarkIcon from '@mui/icons-material/Bookmark';
|
||||
import MoreVertIcon from '@mui/icons-material/MoreVert';
|
||||
import CardActionArea from '@mui/material/CardActionArea';
|
||||
import Checkbox from '@mui/material/Checkbox';
|
||||
import Stack from '@mui/material/Stack';
|
||||
import Tooltip from '@mui/material/Tooltip';
|
||||
import Card from '@mui/material/Card';
|
||||
import CardContent from '@mui/material/CardContent';
|
||||
import IconButton from '@mui/material/IconButton';
|
||||
import { useTheme } from '@mui/material/styles';
|
||||
import Typography from '@mui/material/Typography';
|
||||
import React, { MouseEvent, TouchEvent, useRef } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import PopupState, { bindMenu, bindTrigger } from 'material-ui-popup-state';
|
||||
import { useLongPress } from 'use-long-press';
|
||||
import { getDateString } from '@/util/DateHelper.ts';
|
||||
import { DownloadStateIndicator } from '@/modules/core/components/DownloadStateIndicator.tsx';
|
||||
import { ChapterType } from '@/lib/graphql/generated/graphql.ts';
|
||||
import { ChapterActionMenuItems } from '@/modules/chapter/components/actions/ChapterActionMenuItems.tsx';
|
||||
import { Menu } from '@/modules/core/components/menu/Menu.tsx';
|
||||
import { TypographyMaxLines } from '@/modules/core/components/TypographyMaxLines.tsx';
|
||||
import {
|
||||
ChapterBookmarkInfo,
|
||||
ChapterDownloadInfo,
|
||||
ChapterDownloadStatus,
|
||||
ChapterIdInfo,
|
||||
ChapterMangaInfo,
|
||||
ChapterNumberInfo,
|
||||
ChapterReadInfo,
|
||||
ChapterScanlatorInfo,
|
||||
} from '@/modules/chapter/services/Chapters.ts';
|
||||
import { ChaptersWithMeta } from '@/modules/chapter/services/ChaptersWithMeta.ts';
|
||||
|
||||
type TChapter = ChapterIdInfo &
|
||||
ChapterMangaInfo &
|
||||
ChapterDownloadInfo &
|
||||
ChapterReadInfo &
|
||||
ChapterBookmarkInfo &
|
||||
ChapterNumberInfo &
|
||||
ChapterScanlatorInfo &
|
||||
Pick<ChapterType, 'name' | 'sourceOrder' | 'uploadDate'>;
|
||||
|
||||
interface IProps {
|
||||
chapter: TChapter;
|
||||
allChapters: TChapter[];
|
||||
downloadChapter: ChapterDownloadStatus | undefined;
|
||||
showChapterNumber: boolean;
|
||||
onSelect: (selected: boolean, isShiftKey?: boolean) => void;
|
||||
selected: boolean | null;
|
||||
}
|
||||
|
||||
export const ChapterCard: React.FC<IProps> = (props: IProps) => {
|
||||
const { t } = useTranslation();
|
||||
const theme = useTheme();
|
||||
|
||||
const menuButtonRef = useRef<HTMLButtonElement>(null);
|
||||
|
||||
const { chapter, allChapters, downloadChapter: dc, showChapterNumber, onSelect, selected } = props;
|
||||
const isSelecting = selected !== null;
|
||||
|
||||
const { isDownloaded } = chapter;
|
||||
|
||||
const handleClick = (event: MouseEvent | TouchEvent) => {
|
||||
if (!isSelecting) return;
|
||||
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onSelect(!selected, event.shiftKey);
|
||||
};
|
||||
|
||||
const handleClickOpenMenu = (
|
||||
event: React.MouseEvent | React.TouchEvent,
|
||||
openMenu: (e: React.SyntheticEvent) => void,
|
||||
) => {
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
openMenu(event);
|
||||
};
|
||||
|
||||
const longPressBind = useLongPress((event, { context: openMenu }) => {
|
||||
if (!isSelecting && !!menuButtonRef.current) {
|
||||
handleClickOpenMenu(event, () => (openMenu as (event: Element) => void)?.(menuButtonRef.current!));
|
||||
return;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
event.shiftKey = true;
|
||||
handleClick(event);
|
||||
});
|
||||
|
||||
return (
|
||||
<li>
|
||||
<PopupState variant="popover" popupId="chapter-card-action-menu">
|
||||
{(popupState) => (
|
||||
<Stack sx={{ pt: 1, px: 1 }}>
|
||||
<Card sx={{ touchCallout: 'none' }}>
|
||||
<CardActionArea
|
||||
component={Link}
|
||||
to={`/manga/${chapter.mangaId}/chapter/${chapter.sourceOrder}`}
|
||||
style={{
|
||||
color: theme.palette.text[chapter.isRead ? 'disabled' : 'primary'],
|
||||
}}
|
||||
onClick={(e) => handleClick(e)}
|
||||
{...longPressBind(popupState.open)}
|
||||
>
|
||||
<CardContent
|
||||
sx={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
padding: 1.5,
|
||||
'&:last-child': { pb: 1.5 },
|
||||
}}
|
||||
>
|
||||
<Stack
|
||||
direction="column"
|
||||
sx={{
|
||||
flex: 1,
|
||||
}}
|
||||
>
|
||||
<Stack
|
||||
sx={{
|
||||
flexDirection: 'row',
|
||||
gap: 0.5,
|
||||
alignItems: 'center',
|
||||
}}
|
||||
>
|
||||
{chapter.isBookmarked && <BookmarkIcon color="primary" />}
|
||||
<TypographyMaxLines variant="h6" component="h4">
|
||||
{showChapterNumber
|
||||
? `${t('chapter.title_one')} ${chapter.chapterNumber}`
|
||||
: chapter.name}
|
||||
</TypographyMaxLines>
|
||||
</Stack>
|
||||
<Typography variant="caption">{chapter.scanlator}</Typography>
|
||||
<Typography variant="caption">
|
||||
{getDateString(Number(chapter.uploadDate ?? 0), true)}
|
||||
{isDownloaded && ` • ${t('chapter.status.label.downloaded')}`}
|
||||
</Typography>
|
||||
</Stack>
|
||||
|
||||
{dc && <DownloadStateIndicator download={dc} />}
|
||||
|
||||
<Stack sx={{ minHeight: '48px' }}>
|
||||
{selected === null ? (
|
||||
<Tooltip title={t('global.button.options')}>
|
||||
<IconButton
|
||||
ref={menuButtonRef}
|
||||
{...bindTrigger(popupState)}
|
||||
onClick={(e) => handleClickOpenMenu(e, popupState.open)}
|
||||
onTouchStart={(e) => handleClickOpenMenu(e, popupState.open)}
|
||||
aria-label="more"
|
||||
size="large"
|
||||
>
|
||||
<MoreVertIcon />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<Tooltip
|
||||
title={t(selected ? 'global.button.deselect' : 'global.button.select')}
|
||||
>
|
||||
<Checkbox checked={selected} />
|
||||
</Tooltip>
|
||||
)}
|
||||
</Stack>
|
||||
</CardContent>
|
||||
</CardActionArea>
|
||||
</Card>
|
||||
{!isSelecting && popupState.isOpen && (
|
||||
<Menu {...bindMenu(popupState)}>
|
||||
{(onClose) => (
|
||||
<ChapterActionMenuItems
|
||||
onClose={onClose}
|
||||
chapter={chapter}
|
||||
allChapters={allChapters}
|
||||
handleSelection={() => onSelect(true)}
|
||||
canBeDownloaded={ChaptersWithMeta.isDownloadable({
|
||||
chapter,
|
||||
downloadChapter: dc,
|
||||
})}
|
||||
/>
|
||||
)}
|
||||
</Menu>
|
||||
)}
|
||||
</Stack>
|
||||
)}
|
||||
</PopupState>
|
||||
</li>
|
||||
);
|
||||
};
|
||||
38
src/modules/chapter/hooks/useChapterOptions.tsx
Normal file
38
src/modules/chapter/hooks/useChapterOptions.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* 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 { t } from 'i18next';
|
||||
import { useReducerLocalStorage } from '@/modules/core/hooks/useStorage.tsx';
|
||||
import { DEFAULT_CHAPTER_OPTIONS } from '@/modules/chapter/Chapter.constants.ts';
|
||||
import { ChapterListOptions, ChapterOptionsReducerAction } from '@/modules/chapter/Chapter.types.ts';
|
||||
|
||||
function chapterOptionsReducer(state: ChapterListOptions, actions: ChapterOptionsReducerAction): ChapterListOptions {
|
||||
switch (actions.type) {
|
||||
case 'filter':
|
||||
return {
|
||||
...state,
|
||||
active: state.unread !== false && state.downloaded !== false && state.bookmarked !== false,
|
||||
[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(t('global.error.label.invalid_action'));
|
||||
}
|
||||
}
|
||||
|
||||
export const useChapterOptions = (mangaId: number) =>
|
||||
useReducerLocalStorage<ChapterListOptions, ChapterOptionsReducerAction>(
|
||||
chapterOptionsReducer,
|
||||
`${mangaId}filterOptions`,
|
||||
DEFAULT_CHAPTER_OPTIONS,
|
||||
);
|
||||
389
src/modules/chapter/services/Chapters.ts
Normal file
389
src/modules/chapter/services/Chapters.ts
Normal file
@@ -0,0 +1,389 @@
|
||||
/*
|
||||
* 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 { t as translate } from 'i18next';
|
||||
import gql from 'graphql-tag';
|
||||
import { DocumentNode } from '@apollo/client';
|
||||
import { makeToast } from '@/lib/ui/Toast.ts';
|
||||
import { requestManager } from '@/lib/requests/requests/RequestManager.ts';
|
||||
import { getMetadataServerSettings } from '@/lib/metadata/metadataServerSettings.ts';
|
||||
import {
|
||||
ChapterListFieldsFragment,
|
||||
ChapterType,
|
||||
DownloadStatusFieldsFragment,
|
||||
} from '@/lib/graphql/generated/graphql.ts';
|
||||
import { CHAPTER_LIST_FIELDS } from '@/lib/graphql/fragments/ChapterFragments.ts';
|
||||
import { MangaIdInfo } from '@/lib/data/Mangas.ts';
|
||||
|
||||
import { DirectionOffset, TranslationKey } from '@/Base.types.ts';
|
||||
|
||||
export type ChapterAction = 'download' | 'delete' | 'bookmark' | 'unbookmark' | 'mark_as_read' | 'mark_as_unread';
|
||||
|
||||
export const actionToTranslationKey: {
|
||||
[key in ChapterAction]: {
|
||||
action: {
|
||||
single: TranslationKey;
|
||||
selected: TranslationKey;
|
||||
};
|
||||
success: TranslationKey;
|
||||
error: TranslationKey;
|
||||
};
|
||||
} = {
|
||||
download: {
|
||||
action: {
|
||||
single: 'chapter.action.download.add.label.action',
|
||||
selected: 'chapter.action.download.add.button.selected',
|
||||
},
|
||||
success: 'chapter.action.download.add.label.success',
|
||||
error: 'chapter.action.download.add.label.error',
|
||||
},
|
||||
delete: {
|
||||
action: {
|
||||
single: 'chapter.action.download.delete.label.action',
|
||||
selected: 'chapter.action.download.delete.button.selected',
|
||||
},
|
||||
success: 'chapter.action.download.delete.label.success',
|
||||
error: 'chapter.action.download.delete.label.error',
|
||||
},
|
||||
bookmark: {
|
||||
action: {
|
||||
single: 'chapter.action.bookmark.add.label.action',
|
||||
selected: 'chapter.action.bookmark.add.button.selected',
|
||||
},
|
||||
success: 'chapter.action.bookmark.add.label.success',
|
||||
error: 'chapter.action.bookmark.add.label.error',
|
||||
},
|
||||
unbookmark: {
|
||||
action: {
|
||||
single: 'chapter.action.bookmark.remove.label.action',
|
||||
selected: 'chapter.action.bookmark.remove.button.selected',
|
||||
},
|
||||
success: 'chapter.action.bookmark.remove.label.success',
|
||||
error: 'chapter.action.bookmark.remove.label.error',
|
||||
},
|
||||
mark_as_read: {
|
||||
action: {
|
||||
single: 'chapter.action.mark_as_read.add.label.action.current',
|
||||
selected: 'chapter.action.mark_as_read.add.button.selected',
|
||||
},
|
||||
success: 'chapter.action.mark_as_read.add.label.success',
|
||||
error: 'chapter.action.mark_as_read.add.label.error',
|
||||
},
|
||||
mark_as_unread: {
|
||||
action: {
|
||||
single: 'chapter.action.mark_as_read.remove.label.action',
|
||||
selected: 'chapter.action.mark_as_read.remove.button.selected',
|
||||
},
|
||||
success: 'chapter.action.mark_as_read.remove.label.success',
|
||||
error: 'chapter.action.mark_as_read.remove.label.error',
|
||||
},
|
||||
};
|
||||
|
||||
export type ChapterDownloadStatus = DownloadStatusFieldsFragment['queue'][number];
|
||||
|
||||
export type ChapterIdInfo = Pick<ChapterType, 'id'>;
|
||||
export type ChapterMangaInfo = Pick<ChapterType, 'mangaId'>;
|
||||
export type ChapterDownloadInfo = ChapterIdInfo & Pick<ChapterType, 'isDownloaded'>;
|
||||
export type ChapterBookmarkInfo = ChapterIdInfo & Pick<ChapterType, 'isBookmarked'>;
|
||||
export type ChapterReadInfo = ChapterIdInfo & Pick<ChapterType, 'isRead'>;
|
||||
export type ChapterNumberInfo = ChapterIdInfo & Pick<ChapterType, 'chapterNumber'>;
|
||||
export type ChapterScanlatorInfo = ChapterIdInfo & Pick<ChapterType, 'scanlator'>;
|
||||
export type ChapterRealUrlInfo = Pick<ChapterType, 'realUrl'>;
|
||||
|
||||
export class Chapters {
|
||||
static getIds(chapters: { id: number }[]): number[] {
|
||||
return chapters.map((chapter) => chapter.id);
|
||||
}
|
||||
|
||||
static getFromCache<T = ChapterListFieldsFragment>(
|
||||
id: number,
|
||||
fragment: DocumentNode = CHAPTER_LIST_FIELDS,
|
||||
fragmentName: string = 'CHAPTER_LIST_FIELDS',
|
||||
): T | null {
|
||||
return requestManager.graphQLClient.client.cache.readFragment<T>({
|
||||
id: requestManager.graphQLClient.client.cache.identify({
|
||||
__typename: 'ChapterType',
|
||||
id,
|
||||
}),
|
||||
fragment,
|
||||
fragmentName,
|
||||
});
|
||||
}
|
||||
|
||||
static isDownloading(id: number): boolean {
|
||||
return !!requestManager.graphQLClient.client.cache.readFragment<ChapterType>({
|
||||
id: requestManager.graphQLClient.client.cache.identify({
|
||||
__typename: 'DownloadType',
|
||||
chapter: {
|
||||
__ref: requestManager.graphQLClient.client.cache.identify({
|
||||
__typename: 'ChapterType',
|
||||
id,
|
||||
}),
|
||||
},
|
||||
}),
|
||||
fragment: gql`
|
||||
fragment CHAPTER_DOWNLOAD_QUEUE_CHECK on ChapterType {
|
||||
id
|
||||
}
|
||||
`,
|
||||
fragmentName: 'CHAPTER_DOWNLOAD_QUEUE_CHECK',
|
||||
});
|
||||
}
|
||||
|
||||
static isDownloaded({ isDownloaded }: ChapterDownloadInfo): boolean {
|
||||
return isDownloaded;
|
||||
}
|
||||
|
||||
static getDownloaded<Chapter extends ChapterDownloadInfo>(chapters: Chapter[]): Chapter[] {
|
||||
return chapters.filter(Chapters.isDownloaded);
|
||||
}
|
||||
|
||||
static isDeletable(
|
||||
{ isBookmarked, ...chapter }: ChapterDownloadInfo & ChapterBookmarkInfo,
|
||||
canDeleteBookmarked: boolean = false,
|
||||
): boolean {
|
||||
return Chapters.isDownloaded(chapter) && (!isBookmarked || canDeleteBookmarked);
|
||||
}
|
||||
|
||||
static getDeletable<Chapters extends ChapterDownloadInfo & ChapterBookmarkInfo>(
|
||||
chapters: Chapters[],
|
||||
canDeleteBookmarked?: boolean,
|
||||
): Chapters[] {
|
||||
return chapters.filter((chapter) => Chapters.isDeletable(chapter, canDeleteBookmarked));
|
||||
}
|
||||
|
||||
static isBookmarked({ isBookmarked }: ChapterBookmarkInfo): boolean {
|
||||
return isBookmarked;
|
||||
}
|
||||
|
||||
static getBookmarked<Chapter extends ChapterBookmarkInfo>(chapters: Chapter[]): Chapter[] {
|
||||
return chapters.filter(Chapters.isBookmarked);
|
||||
}
|
||||
|
||||
static getNonBookmarked<Chapter extends ChapterBookmarkInfo>(chapters: Chapter[]): Chapter[] {
|
||||
return chapters.filter((chapter) => !Chapters.isBookmarked(chapter));
|
||||
}
|
||||
|
||||
static isRead({ isRead }: ChapterReadInfo): boolean {
|
||||
return isRead;
|
||||
}
|
||||
|
||||
static getRead<Chapter extends ChapterReadInfo>(chapters: Chapter[]): Chapter[] {
|
||||
return chapters.filter(Chapters.isRead);
|
||||
}
|
||||
|
||||
static getNonRead<Chapter extends ChapterReadInfo>(chapters: Chapter[]): Chapter[] {
|
||||
return chapters.filter((chapter) => !Chapters.isRead(chapter));
|
||||
}
|
||||
|
||||
static getMatchingChapterNumberChapters<Chapter extends ChapterNumberInfo>(
|
||||
chaptersA: Chapter[],
|
||||
chaptersB: Chapter[],
|
||||
): [ChapterA: Chapter, ChapterB: Chapter][] {
|
||||
return chaptersA
|
||||
.map((chapterA) => {
|
||||
const matchingChapter = chaptersB.find((chapterB) => chapterA.chapterNumber === chapterB.chapterNumber);
|
||||
|
||||
if (!matchingChapter) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [chapterA, matchingChapter];
|
||||
})
|
||||
.filter((matchingChapters): matchingChapters is [Chapter, Chapter] => matchingChapters !== null);
|
||||
}
|
||||
|
||||
static async download(chapterIds: number[]): Promise<void> {
|
||||
return Chapters.executeAction(
|
||||
'download',
|
||||
chapterIds.length,
|
||||
() => requestManager.addChaptersToDownloadQueue(chapterIds).response,
|
||||
);
|
||||
}
|
||||
|
||||
static async delete(chapterIds: number[]): Promise<void> {
|
||||
return Chapters.executeAction(
|
||||
'delete',
|
||||
chapterIds.length,
|
||||
() => requestManager.deleteDownloadedChapters(chapterIds).response,
|
||||
);
|
||||
}
|
||||
|
||||
static async markAsRead(
|
||||
chapters: (ChapterDownloadInfo & ChapterBookmarkInfo)[],
|
||||
wasManuallyMarkedAsRead: boolean = false,
|
||||
trackProgressMangaId?: MangaIdInfo['id'],
|
||||
): Promise<void> {
|
||||
const { deleteChaptersManuallyMarkedRead, deleteChaptersWithBookmark, updateProgressManualMarkRead } =
|
||||
await getMetadataServerSettings();
|
||||
const chapterIdsToDelete =
|
||||
deleteChaptersManuallyMarkedRead && wasManuallyMarkedAsRead
|
||||
? Chapters.getIds(Chapters.getDeletable(chapters, deleteChaptersWithBookmark))
|
||||
: [];
|
||||
return Chapters.executeAction(
|
||||
'mark_as_read',
|
||||
chapters.length,
|
||||
() =>
|
||||
requestManager.updateChapters(Chapters.getIds(chapters), {
|
||||
isRead: true,
|
||||
lastPageRead: 0,
|
||||
chapterIdsToDelete,
|
||||
trackProgressMangaId:
|
||||
updateProgressManualMarkRead && wasManuallyMarkedAsRead ? trackProgressMangaId : undefined,
|
||||
}).response,
|
||||
);
|
||||
}
|
||||
|
||||
static async markAsUnread(chapterIds: number[]): Promise<void> {
|
||||
return Chapters.executeAction(
|
||||
'mark_as_unread',
|
||||
chapterIds.length,
|
||||
() => requestManager.updateChapters(chapterIds, { isRead: false }).response,
|
||||
);
|
||||
}
|
||||
|
||||
static async bookmark(chapterIds: number[]): Promise<void> {
|
||||
return Chapters.executeAction(
|
||||
'bookmark',
|
||||
chapterIds.length,
|
||||
() => requestManager.updateChapters(chapterIds, { isBookmarked: true }).response,
|
||||
);
|
||||
}
|
||||
|
||||
static async unBookmark(chapterIds: number[]): Promise<void> {
|
||||
return Chapters.executeAction(
|
||||
'unbookmark',
|
||||
chapterIds.length,
|
||||
() => requestManager.updateChapters(chapterIds, { isBookmarked: false }).response,
|
||||
);
|
||||
}
|
||||
|
||||
private static async executeAction(
|
||||
action: ChapterAction,
|
||||
itemCount: number,
|
||||
fnToExecute: () => Promise<unknown>,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await fnToExecute();
|
||||
makeToast(translate(actionToTranslationKey[action].success, { count: itemCount }), 'success');
|
||||
} catch (e) {
|
||||
makeToast(translate(actionToTranslationKey[action].error, { count: itemCount }), 'error');
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
static async performAction<Action extends ChapterAction>(
|
||||
action: Action,
|
||||
chapterIds: number[],
|
||||
{
|
||||
wasManuallyMarkedAsRead,
|
||||
trackProgressMangaId,
|
||||
chapters,
|
||||
}: Action extends 'mark_as_read'
|
||||
? {
|
||||
wasManuallyMarkedAsRead: boolean;
|
||||
trackProgressMangaId?: MangaIdInfo['id'];
|
||||
chapters: (ChapterDownloadInfo & ChapterBookmarkInfo & ChapterReadInfo)[];
|
||||
}
|
||||
: {
|
||||
wasManuallyMarkedAsRead?: never;
|
||||
trackProgressMangaId?: never;
|
||||
chapters?: never;
|
||||
},
|
||||
): Promise<void> {
|
||||
switch (action) {
|
||||
case 'download':
|
||||
return Chapters.download(chapterIds);
|
||||
case 'delete':
|
||||
return Chapters.delete(chapterIds);
|
||||
case 'mark_as_read':
|
||||
return Chapters.markAsRead(chapters!, wasManuallyMarkedAsRead!, trackProgressMangaId);
|
||||
case 'mark_as_unread':
|
||||
return Chapters.markAsUnread(chapterIds);
|
||||
case 'bookmark':
|
||||
return Chapters.bookmark(chapterIds);
|
||||
case 'unbookmark':
|
||||
return Chapters.unBookmark(chapterIds);
|
||||
default:
|
||||
throw new Error(`Chapters::performAction: unknown action "${action}"`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the provided "uniqueChapters" plus their duplicates found in "allChapters"
|
||||
*/
|
||||
static addDuplicates<T extends ChapterScanlatorInfo & ChapterNumberInfo>(
|
||||
uniqueChapters: T[],
|
||||
allChapters: T[],
|
||||
): T[] {
|
||||
const chapterNumberToChapters = Object.groupBy(allChapters, ({ chapterNumber }) => chapterNumber);
|
||||
|
||||
return uniqueChapters
|
||||
.map((uniqueChapter) => chapterNumberToChapters[uniqueChapter.chapterNumber] ?? [uniqueChapter])
|
||||
.flat();
|
||||
}
|
||||
|
||||
static removeDuplicates<T extends ChapterScanlatorInfo & ChapterNumberInfo>(currentChapter: T, chapters: T[]): T[] {
|
||||
const chapterNumberToChapters = Object.groupBy(chapters, ({ chapterNumber }) => chapterNumber);
|
||||
|
||||
const uniqueChapters = Object.values(chapterNumberToChapters).map(
|
||||
(groupedChapters) =>
|
||||
// the result of groupBy can't result in undefined values
|
||||
groupedChapters!.find((chapter) => chapter.id === currentChapter.id) ??
|
||||
groupedChapters!.findLast((chapter) => chapter.scanlator === currentChapter.scanlator) ??
|
||||
groupedChapters!.slice(-1)[0],
|
||||
);
|
||||
|
||||
// keep the chapters in the same order as they were passed
|
||||
return chapters
|
||||
.map(({ id }) => uniqueChapters.find((chapter) => chapter.id === id))
|
||||
.filter((chapter): chapter is T => !!chapter);
|
||||
}
|
||||
|
||||
static getNextChapter<Chapter extends ChapterScanlatorInfo & ChapterNumberInfo & ChapterReadInfo>(
|
||||
currentChapter: Chapter,
|
||||
chapters: Chapter[],
|
||||
{
|
||||
offset = DirectionOffset.NEXT,
|
||||
...options
|
||||
}: { offset?: DirectionOffset; onlyUnread?: boolean; skipDupe?: boolean; skipDupeChapter?: Chapter } = {},
|
||||
): Chapter | undefined {
|
||||
const nextChapters = Chapters.getNextChapters(currentChapter, chapters, { offset, ...options });
|
||||
|
||||
const isNextChapterOffset = offset === DirectionOffset.NEXT;
|
||||
const sliceStartIndex = isNextChapterOffset ? -1 : 0;
|
||||
const sliceEndIndex = isNextChapterOffset ? undefined : 1;
|
||||
|
||||
return nextChapters.slice(sliceStartIndex, sliceEndIndex)[0];
|
||||
}
|
||||
|
||||
static getNextChapters<Chapter extends ChapterScanlatorInfo & ChapterNumberInfo & ChapterReadInfo>(
|
||||
fromChapter: Chapter,
|
||||
chapters: Chapter[],
|
||||
{
|
||||
offset = DirectionOffset.NEXT,
|
||||
onlyUnread = false,
|
||||
skipDupe = false,
|
||||
skipDupeChapter = fromChapter,
|
||||
}: { offset?: DirectionOffset; onlyUnread?: boolean; skipDupe?: boolean; skipDupeChapter?: Chapter } = {},
|
||||
): Chapter[] {
|
||||
const fromChapterIndex = chapters.findIndex((chapter) => chapter.id === fromChapter.id);
|
||||
|
||||
const isNextChapterOffset = offset === DirectionOffset.NEXT;
|
||||
const sliceStartIndex = isNextChapterOffset ? 0 : fromChapterIndex;
|
||||
const sliceEndIndex = isNextChapterOffset ? fromChapterIndex + 1 : undefined;
|
||||
|
||||
const nextChaptersIncludingCurrent = chapters.slice(sliceStartIndex, sliceEndIndex);
|
||||
const uniqueNextChapters = skipDupe
|
||||
? Chapters.removeDuplicates(skipDupeChapter, nextChaptersIncludingCurrent)
|
||||
: nextChaptersIncludingCurrent;
|
||||
const nextChapters = uniqueNextChapters.toSpliced(isNextChapterOffset ? -1 : 0, 1);
|
||||
|
||||
return onlyUnread ? Chapters.getNonRead(nextChapters) : nextChapters;
|
||||
}
|
||||
}
|
||||
76
src/modules/chapter/services/ChaptersWithMeta.ts
Normal file
76
src/modules/chapter/services/ChaptersWithMeta.ts
Normal file
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
* 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 {
|
||||
ChapterBookmarkInfo,
|
||||
ChapterDownloadInfo,
|
||||
ChapterDownloadStatus,
|
||||
ChapterReadInfo,
|
||||
Chapters,
|
||||
} from '@/modules/chapter/services/Chapters.ts';
|
||||
import { DownloadState } from '@/lib/graphql/generated/graphql.ts';
|
||||
|
||||
export type ChapterWithMetaType<
|
||||
Chapter extends ChapterDownloadInfo & ChapterReadInfo & ChapterBookmarkInfo = ChapterDownloadInfo &
|
||||
ChapterReadInfo &
|
||||
ChapterBookmarkInfo,
|
||||
> = {
|
||||
chapter: Chapter;
|
||||
downloadChapter: ChapterDownloadStatus | undefined;
|
||||
};
|
||||
|
||||
export class ChaptersWithMeta {
|
||||
static getChapters<ChaptersWithMeta extends ChapterWithMetaType>(
|
||||
chapters: ChaptersWithMeta[],
|
||||
): ChaptersWithMeta['chapter'][] {
|
||||
return chapters.map(({ chapter }) => chapter);
|
||||
}
|
||||
|
||||
static getIds(chapters: ChapterWithMetaType[]): number[] {
|
||||
return Chapters.getIds(ChaptersWithMeta.getChapters(chapters));
|
||||
}
|
||||
|
||||
static getDownloaded<Chapter extends ChapterWithMetaType>(chapters: Chapter[]): Chapter[] {
|
||||
return chapters.filter(({ chapter }) => Chapters.isDownloaded(chapter));
|
||||
}
|
||||
|
||||
static getDeletable<Chapter extends ChapterWithMetaType>(
|
||||
chapters: Chapter[],
|
||||
canDeleteBookmarked?: boolean,
|
||||
): Chapter[] {
|
||||
return chapters.filter(({ chapter }) => Chapters.isDeletable(chapter, canDeleteBookmarked));
|
||||
}
|
||||
|
||||
static getNonDownloaded<Chapter extends ChapterWithMetaType>(chapters: Chapter[]): Chapter[] {
|
||||
return chapters.filter(({ chapter }) => !Chapters.isDownloaded(chapter));
|
||||
}
|
||||
|
||||
static isDownloadable<Chapter extends ChapterWithMetaType>({ chapter, downloadChapter }: Chapter): boolean {
|
||||
return !Chapters.isDownloaded(chapter) && (!downloadChapter || downloadChapter?.state === DownloadState.Error);
|
||||
}
|
||||
|
||||
static getDownloadable<Chapter extends ChapterWithMetaType>(chapters: Chapter[]): Chapter[] {
|
||||
return chapters.filter(this.isDownloadable);
|
||||
}
|
||||
|
||||
static getBookmarked<Chapter extends ChapterWithMetaType>(chapters: Chapter[]): Chapter[] {
|
||||
return chapters.filter(({ chapter }) => Chapters.isBookmarked(chapter));
|
||||
}
|
||||
|
||||
static getNonBookmarked<Chapter extends ChapterWithMetaType>(chapters: Chapter[]): Chapter[] {
|
||||
return chapters.filter(({ chapter }) => !Chapters.isBookmarked(chapter));
|
||||
}
|
||||
|
||||
static getRead<Chapter extends ChapterWithMetaType>(chapters: Chapter[]): Chapter[] {
|
||||
return chapters.filter(({ chapter }) => Chapters.isRead(chapter));
|
||||
}
|
||||
|
||||
static getNonRead<Chapter extends ChapterWithMetaType>(chapters: Chapter[]): Chapter[] {
|
||||
return chapters.filter(({ chapter }) => !Chapters.isRead(chapter));
|
||||
}
|
||||
}
|
||||
101
src/modules/chapter/utils/ChapterList.util.tsx
Normal file
101
src/modules/chapter/utils/ChapterList.util.tsx
Normal file
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* 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 { ChapterBookmarkInfo, ChapterDownloadInfo, ChapterReadInfo } from '@/modules/chapter/services/Chapters.ts';
|
||||
import { ChapterType } from '@/lib/graphql/generated/graphql.ts';
|
||||
import { NullAndUndefined } from '@/Base.types.ts';
|
||||
import { ChapterListOptions } from '@/modules/chapter/Chapter.types.ts';
|
||||
|
||||
export function unreadFilter(unread: NullAndUndefined<boolean>, { isRead: isChapterRead }: ChapterReadInfo) {
|
||||
switch (unread) {
|
||||
case true:
|
||||
return !isChapterRead;
|
||||
case false:
|
||||
return isChapterRead;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function downloadFilter(downloaded: NullAndUndefined<boolean>, { isDownloaded: chapterDownload }: ChapterDownloadInfo) {
|
||||
switch (downloaded) {
|
||||
case true:
|
||||
return chapterDownload;
|
||||
case false:
|
||||
return !chapterDownload;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function bookmarkedFilter(
|
||||
bookmarked: NullAndUndefined<boolean>,
|
||||
{ isBookmarked: chapterBookmarked }: ChapterBookmarkInfo,
|
||||
) {
|
||||
switch (bookmarked) {
|
||||
case true:
|
||||
return chapterBookmarked;
|
||||
case false:
|
||||
return !chapterBookmarked;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
type TChapterSort = Pick<ChapterType, 'sourceOrder' | 'fetchedAt' | 'chapterNumber' | 'uploadDate'>;
|
||||
const sortChapters = <T extends TChapterSort>(
|
||||
chapters: T[],
|
||||
{ sortBy, reverse }: Pick<ChapterListOptions, 'sortBy' | 'reverse'>,
|
||||
): T[] => {
|
||||
const sortedChapters: T[] = [...chapters];
|
||||
|
||||
switch (sortBy) {
|
||||
case 'source':
|
||||
sortedChapters.sort((a, b) => a.sourceOrder - b.sourceOrder);
|
||||
break;
|
||||
case 'fetchedAt':
|
||||
sortedChapters.sort((a, b) => Number(a.fetchedAt ?? 0) - Number(b.fetchedAt ?? 0));
|
||||
break;
|
||||
case 'chapterNumber':
|
||||
sortedChapters.sort((a, b) => a.chapterNumber - b.chapterNumber);
|
||||
break;
|
||||
case 'uploadedAt':
|
||||
sortedChapters.sort((a, b) => Number(a.uploadDate ?? 0) - Number(b.uploadDate ?? 0));
|
||||
break;
|
||||
default:
|
||||
// nothing to do
|
||||
}
|
||||
|
||||
if (reverse) {
|
||||
sortedChapters.reverse();
|
||||
}
|
||||
|
||||
return sortedChapters;
|
||||
};
|
||||
|
||||
type TChapterFilter = TChapterSort & ChapterReadInfo & ChapterDownloadInfo & ChapterBookmarkInfo;
|
||||
export function filterAndSortChapters<Chapters extends TChapterFilter>(
|
||||
chapters: Chapters[],
|
||||
options: ChapterListOptions,
|
||||
): Chapters[] {
|
||||
const filtered = options.active
|
||||
? chapters.filter(
|
||||
(chp) =>
|
||||
unreadFilter(options.unread, chp) &&
|
||||
downloadFilter(options.downloaded, chp) &&
|
||||
bookmarkedFilter(options.bookmarked, chp),
|
||||
)
|
||||
: [...chapters];
|
||||
|
||||
return sortChapters(filtered, options);
|
||||
}
|
||||
|
||||
export const isFilterActive = (options: ChapterListOptions) => {
|
||||
const { unread, downloaded, bookmarked } = options;
|
||||
return unread != null || downloaded != null || bookmarked != null;
|
||||
};
|
||||
Reference in New Issue
Block a user