Move chapter files into new folder

This commit is contained in:
schroda
2024-10-05 19:15:25 +02:00
parent 23a86a77f0
commit cb731cefc0
22 changed files with 129 additions and 97 deletions

View File

@@ -1,237 +0,0 @@
/*
* 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 '@/lib/data/Chapters.ts';
import { MenuItem } from '@/modules/core/components/menu/MenuItem.tsx';
import { IChapterWithMeta } from '@/components/chapter/ChapterList.tsx';
import { ChaptersWithMeta } from '@/lib/data/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')}
/>
)}
</>
);
};

View File

@@ -1,199 +0,0 @@
/*
* 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 '@/components/chapter/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 '@/lib/data/Chapters.ts';
import { ChaptersWithMeta } from '@/lib/data/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>
);
};

View File

@@ -1,278 +0,0 @@
/*
* 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 '@/components/chapter/ChapterCard.tsx';
import { ResumeFab } from '@/components/manga/ResumeFAB.tsx';
import { filterAndSortChapters, useChapterOptions } from '@/components/chapter/util.tsx';
import { EmptyViewAbsoluteCentered } from '@/modules/core/components/placeholder/EmptyViewAbsoluteCentered.tsx';
import { ChaptersToolbarMenu } from '@/components/chapter/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 '@/lib/data/Chapters.ts';
import { ChaptersWithMeta, ChapterWithMetaType } from '@/lib/data/ChaptersWithMeta.ts';
import { ChapterActionMenuItems } from '@/components/chapter/ChapterActionMenuItems.tsx';
import { ChaptersDownloadActionMenuItems } from '@/components/chapter/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';
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';
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}
</>
);
};

View File

@@ -1,113 +0,0 @@
/*
* 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 { ChapterListOptions, ChapterOptionsReducerAction } from '@/typings.ts';
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 { SORT_OPTIONS } from '@/components/chapter/util.tsx';
import { TranslationKey } from '@/Base.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(SORT_OPTIONS).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 SORT_OPTIONS })
: 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;
}}
/>
);
};

View File

@@ -1,71 +0,0 @@
/*
* 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>
</>
);
};

View File

@@ -1,44 +0,0 @@
/*
* 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 { ChapterListOptions, ChapterOptionsReducerAction } from '@/typings.ts';
import { ChapterOptions } from '@/components/chapter/ChapterOptions.tsx';
import { isFilterActive } from '@/components/chapter/util.tsx';
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}
/>
</>
);
};

View File

@@ -1,146 +0,0 @@
/*
* 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 { ChapterListOptions, ChapterOptionsReducerAction, ChapterSortMode } from '@/typings.ts';
import { useReducerLocalStorage } from '@/modules/core/hooks/useStorage.tsx';
import { ChapterBookmarkInfo, ChapterDownloadInfo, ChapterReadInfo } from '@/lib/data/Chapters.ts';
import { ChapterType } from '@/lib/graphql/generated/graphql.ts';
import { NullAndUndefined, TranslationKey } from '@/Base.types.ts';
const defaultChapterOptions: ChapterListOptions = {
active: false,
unread: undefined,
downloaded: undefined,
bookmarked: undefined,
reverse: true,
sortBy: 'source',
showChapterNumber: false,
};
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 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 useChapterOptions = (mangaId: number) =>
useReducerLocalStorage<ChapterListOptions, ChapterOptionsReducerAction>(
chapterOptionsReducer,
`${mangaId}filterOptions`,
defaultChapterOptions,
);
export const SORT_OPTIONS: 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',
};
export const isFilterActive = (options: ChapterListOptions) => {
const { unread, downloaded, bookmarked } = options;
return unread != null || downloaded != null || bookmarked != null;
};

View File

@@ -37,7 +37,7 @@ import {
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
import { TrackManga } from '@/components/tracker/TrackManga.tsx';
import { useCategorySelect } from '@/components/navbar/action/useCategorySelect.tsx';
import { ChaptersDownloadActionMenuItems } from '@/components/chapter/ChaptersDownloadActionMenuItems.tsx';
import { ChaptersDownloadActionMenuItems } from '@/modules/chapter/components/actions/ChaptersDownloadActionMenuItems.tsx';
import { NestedMenuItem } from '@/modules/core/components/menu/NestedMenuItem.tsx';
import { MangaChapterStatFieldsFragment, MangaType } from '@/lib/graphql/generated/graphql.ts';