Rename folder "modules" to "features"

This commit is contained in:
schroda
2025-08-15 22:02:58 +02:00
parent 7e6ced1d09
commit 1b4bf22542
415 changed files with 1859 additions and 1852 deletions

View File

@@ -0,0 +1,107 @@
/*
* 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 { ChapterAction, ChapterListOptions, ChapterSortMode } from '@/features/chapter/Chapter.types.ts';
export const FALLBACK_CHAPTER = { id: -1, name: '', realUrl: '', isBookmarked: false };
export const DEFAULT_CHAPTER_OPTIONS: ChapterListOptions = {
unread: undefined,
downloaded: undefined,
bookmarked: undefined,
reverse: true,
sortBy: 'source',
showChapterNumber: false,
excludedScanlators: [],
};
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',
};
export const CHAPTER_ACTION_TO_CONFIRMATION_REQUIRED: Record<
ChapterAction,
{ always: boolean; bulkAction: boolean; bulkActionCountForce?: number }
> = {
download: { always: false, bulkAction: false, bulkActionCountForce: 300 },
delete: { always: true, bulkAction: true },
bookmark: { always: false, bulkAction: false },
unbookmark: { always: false, bulkAction: true },
mark_as_read: { always: false, bulkAction: true },
mark_as_unread: { always: false, bulkAction: true },
};
export const CHAPTER_ACTION_TO_TRANSLATION: {
[key in ChapterAction]: {
action: {
single: TranslationKey;
selected: TranslationKey;
};
confirmation?: TranslationKey;
success: TranslationKey;
error: TranslationKey;
};
} = {
download: {
action: {
single: 'chapter.action.download.add.label.action',
selected: 'chapter.action.download.add.button.selected',
},
confirmation: 'chapter.action.download.add.label.confirmation',
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',
},
confirmation: 'chapter.action.download.delete.label.confirmation',
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',
},
confirmation: 'chapter.action.bookmark.remove.label.confirmation',
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',
},
confirmation: 'chapter.action.mark_as_read.add.label.confirmation',
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',
},
confirmation: 'chapter.action.mark_as_read.remove.label.confirmation',
success: 'chapter.action.mark_as_read.remove.label.success',
error: 'chapter.action.mark_as_read.remove.label.error',
},
};

View File

@@ -0,0 +1,50 @@
/*
* 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';
import {
ChapterReaderFieldsFragment,
ChapterType,
DownloadStatusFieldsFragment,
} from '@/lib/graphql/generated/graphql.ts';
export type ChapterSortMode = 'fetchedAt' | 'source' | 'chapterNumber' | 'uploadedAt';
export interface ChapterListOptions {
unread: NullAndUndefined<boolean>;
downloaded: NullAndUndefined<boolean>;
bookmarked: NullAndUndefined<boolean>;
reverse: boolean;
sortBy: ChapterSortMode;
showChapterNumber: boolean;
excludedScanlators: string[];
}
export type TChapterReader = ChapterReaderFieldsFragment;
export type ChapterAction = 'download' | 'delete' | 'bookmark' | 'unbookmark' | 'mark_as_read' | 'mark_as_unread';
export type ChapterDownloadStatus = DownloadStatusFieldsFragment['queue'][number];
export type ChapterIdInfo = Pick<ChapterType, 'id'>;
export type ChapterMangaInfo = Pick<ChapterType, 'mangaId'>;
export type ChapterDownloadInfo = Pick<ChapterType, 'isDownloaded'>;
export type ChapterBookmarkInfo = Pick<ChapterType, 'isBookmarked'>;
export type ChapterReadInfo = Pick<ChapterType, 'isRead'>;
export type ChapterNumberInfo = Pick<ChapterType, 'chapterNumber'>;
export type ChapterSourceOrderInfo = Pick<ChapterType, 'sourceOrder'>;
export type ChapterScanlatorInfo = Pick<ChapterType, 'scanlator'>;
export type ChapterRealUrlInfo = Pick<ChapterType, 'realUrl'>;

View File

@@ -0,0 +1,63 @@
/*
* 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 { bindTrigger, usePopupState } from 'material-ui-popup-state/hooks';
import { useTranslation } from 'react-i18next';
import PeopleAltOutlinedIcon from '@mui/icons-material/PeopleAltOutlined';
import DisabledByDefaultRounded from '@mui/icons-material/DisabledByDefaultRounded';
import { CheckboxListSetting } from '@/features/core/components/settings/CheckboxListSetting.tsx';
import { updateChapterListOptions } from '@/features/chapter/utils/ChapterList.util.tsx';
import { CheckboxInput } from '@/features/core/components/inputs/CheckboxInput.tsx';
export const ChapterExcludeSanlatorsFilter = ({
updateOption,
scanlators,
excludedScanlators,
}: {
updateOption: ReturnType<typeof updateChapterListOptions>;
scanlators: string[];
excludedScanlators: string[];
}) => {
const { t } = useTranslation();
const popupState = usePopupState({ variant: 'dialog', popupId: 'chapter-list-options-scanlator-filter-dialog' });
if (!scanlators.length) {
return null;
}
return (
<>
<CheckboxInput
{...bindTrigger(popupState)}
label={t('global.label.scanlator')}
icon={<PeopleAltOutlinedIcon />}
checkedIcon={<PeopleAltOutlinedIcon color="warning" />}
checked={!!excludedScanlators.length}
/>
<CheckboxListSetting
title={t('chapter.option.exclude_scanlators')}
open={popupState.isOpen}
onClose={(selectedScanlators) => {
if (selectedScanlators) {
updateOption('excludedScanlators', selectedScanlators);
}
popupState.close();
}}
items={scanlators}
getId={(scanlator) => scanlator}
getLabel={(scanlator) => scanlator}
isChecked={(scanlator) => excludedScanlators.includes(scanlator)}
slotProps={{
checkbox: {
checkedIcon: <DisabledByDefaultRounded />,
},
}}
/>
</>
);
};

View File

@@ -0,0 +1,266 @@
/*
* 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 { styled } from '@mui/material/styles';
import Typography from '@mui/material/Typography';
import { ComponentProps, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { ResumeFab } from '@/features/manga/components/ResumeFAB.tsx';
import {
filterAndSortChapters,
updateChapterListOptions,
useChapterListOptions,
} from '@/features/chapter/utils/ChapterList.util.tsx';
import { EmptyViewAbsoluteCentered } from '@/features/core/components/feedback/EmptyViewAbsoluteCentered.tsx';
import { ChaptersToolbarMenu } from '@/features/chapter/components/ChaptersToolbarMenu.tsx';
import { SelectionFAB } from '@/features/collection/components/SelectionFAB.tsx';
import { DEFAULT_FULL_FAB_HEIGHT } from '@/features/core/components/buttons/StyledFab.tsx';
import {
ChapterListFieldsFragment,
GetChaptersMangaQuery,
GetChaptersMangaQueryVariables,
MangaScreenFieldsFragment,
} from '@/lib/graphql/generated/graphql.ts';
import { useSelectableCollection } from '@/features/collection/hooks/useSelectableCollection.ts';
import { SelectableCollectionSelectAll } from '@/features/collection/components/SelectableCollectionSelectAll.tsx';
import { Chapters } from '@/features/chapter/services/Chapters.ts';
import { ChapterActionMenuItems } from '@/features/chapter/components/actions/ChapterActionMenuItems.tsx';
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
import { LoadingPlaceholder } from '@/features/core/components/feedback/LoadingPlaceholder.tsx';
import { GET_CHAPTERS_MANGA } from '@/lib/graphql/queries/ChapterQuery.ts';
import { useNavBarContext } from '@/features/navigation-bar/contexts/NavbarContext.tsx';
import { useResizeObserver } from '@/features/core/hooks/useResizeObserver.tsx';
import { MediaQuery } from '@/features/core/utils/MediaQuery.tsx';
import { shouldForwardProp } from '@/features/core/utils/ShouldForwardProp.ts';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
import { makeToast } from '@/features/core/utils/Toast.ts';
import { ChapterListCard } from '@/features/chapter/components/cards/ChapterListCard.tsx';
import { VirtuosoPersisted } from '@/lib/virtuoso/Component/VirtuosoPersisted.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(VirtuosoPersisted, {
shouldForwardProp: shouldForwardProp<StyledVirtuosoProps>(['topOffset']),
})<StyledVirtuosoProps>(({ theme, topOffset }) => ({
listStyle: 'none',
padding: 0,
[theme.breakpoints.up('md')]: {
height: `calc(100vh - ${topOffset}px)`,
margin: 0,
},
}));
const ChapterListFAB = ({
selectedChapters,
firstUnreadChapter,
onFABMenuClose,
}: {
selectedChapters: ChapterListFieldsFragment[];
firstUnreadChapter: ComponentProps<typeof ResumeFab>['chapter'] | null | undefined;
onFABMenuClose?: () => void;
}) => {
if (selectedChapters.length) {
return (
<SelectionFAB selectedItemsCount={selectedChapters.length} title="chapter.title_one">
{(handleClose) => (
<ChapterActionMenuItems
selectedChapters={selectedChapters}
onClose={() => {
onFABMenuClose?.();
handleClose();
}}
/>
)}
</SelectionFAB>
);
}
if (firstUnreadChapter) {
return <ResumeFab chapter={firstUnreadChapter} />;
}
return 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 options = useChapterListOptions(manga);
const updateOption = updateChapterListOptions(manga, (e) =>
makeToast(t('global.error.label.failed_to_save_changes'), 'error', getErrorMessage(e)),
);
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 visibleChapters = useMemo(() => filterAndSortChapters(chapters, options), [chapters, options]);
const visibleChapterIds = useMemo(() => Chapters.getIds(visibleChapters), [visibleChapters]);
const missingChapterCount = useMemo(() => Chapters.getMissingCount(visibleChapters), [visibleChapters]);
const noChaptersFound = chapters.length === 0;
const noChaptersMatchingFilter = !noChaptersFound && visibleChapters.length === 0;
const {
areNoItemsSelected,
areAllItemsSelected,
selectedItemIds,
handleSelectAll,
handleSelection,
clearSelection,
} = useSelectableCollection(visibleChapterIds.length, { itemIds: visibleChapterIds, currentKey: 'default' });
const onSelect = useCallback(
(id: number, selected: boolean, selectRange?: boolean) => handleSelection(id, selected, { selectRange }),
[handleSelection],
);
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={getErrorMessage(error)}
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}
>
<Stack>
<Typography variant="h5" component="h3">
{t('chapter.value', { count: visibleChapters.length })}
</Typography>
{!!missingChapterCount && (
<Typography variant="body2" color="warning">
{`${t('chapter.missing', {
count: missingChapterCount,
})}`}
</Typography>
)}
</Stack>
<Stack direction="row">
{areNoItemsSelected && (
<ChaptersToolbarMenu
mangaId={manga.id}
options={options}
updateOption={updateOption}
chapters={visibleChapters}
scanlators={Chapters.getScanlators(chapters)}
excludeScanlators={options.excludedScanlators}
/>
)}
{!!visibleChapterIds.length && (
<SelectableCollectionSelectAll
areAllItemsSelected={areAllItemsSelected}
areNoItemsSelected={areNoItemsSelected}
onChange={(checked) => handleSelectAll(checked, checked ? visibleChapterIds : [])}
/>
)}
</Stack>
</ChapterListHeader>
{noChaptersFound && <EmptyViewAbsoluteCentered message={t('chapter.error.label.no_chapter_found')} />}
{noChaptersMatchingFilter && (
<EmptyViewAbsoluteCentered message={t('chapter.error.label.no_matches')} />
)}
<StyledVirtuoso
persistKey={`manga-${manga.id}-chapter-list`}
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}
computeItemKey={(index) => visibleChapters[index].id}
itemContent={(index: number) => (
<ChapterListCard
index={index}
isSortDesc={options.reverse}
chapters={visibleChapters}
selected={!areNoItemsSelected ? selectedItemIds.includes(visibleChapters[index].id) : null}
showChapterNumber={options.showChapterNumber}
onSelect={onSelect}
/>
)}
useWindowScroll={isMobileWidth}
overscan={window.innerHeight * 0.5}
/>
</Stack>
<ChapterListFAB
selectedChapters={selectedItemIds
.map((id) => chapters.find((chapter) => chapter.id === id))
.filter((chapter) => chapter != null)}
firstUnreadChapter={manga.firstUnreadChapter}
onFABMenuClose={clearSelection}
/>
</>
);
};

View File

@@ -0,0 +1,114 @@
/*
* 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 '@/features/core/components/inputs/RadioInput.tsx';
import { SortRadioInput } from '@/features/core/components/inputs/SortRadioInput.tsx';
import { ThreeStateCheckboxInput } from '@/features/core/components/inputs/ThreeStateCheckboxInput.tsx';
import { OptionsTabs } from '@/features/core/components/modals/OptionsTabs.tsx';
import { CHAPTER_SORT_OPTIONS_TO_TRANSLATION_KEY } from '@/features/chapter/Chapter.constants.ts';
import { TranslationKey } from '@/Base.types.ts';
import { ChapterListOptions } from '@/features/chapter/Chapter.types.ts';
import { updateChapterListOptions } from '@/features/chapter/utils/ChapterList.util.tsx';
import { ChapterExcludeSanlatorsFilter } from '@/features/chapter/components/ChapterExcludeSanlatorsFilter.tsx';
interface IProps {
open: boolean;
onClose: () => void;
options: ChapterListOptions;
updateOption: ReturnType<typeof updateChapterListOptions>;
scanlators: string[];
excludedScanlators: string[];
}
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,
updateOption,
scanlators,
excludedScanlators,
}) => {
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) => updateOption('unread', c)}
/>
<ThreeStateCheckboxInput
label={t('global.filter.label.downloaded')}
checked={options.downloaded}
onChange={(c) => updateOption('downloaded', c)}
/>
<ThreeStateCheckboxInput
label={t('global.filter.label.bookmarked')}
checked={options.bookmarked}
onChange={(c) => updateOption('bookmarked', c)}
/>
<ChapterExcludeSanlatorsFilter
scanlators={scanlators}
excludedScanlators={excludedScanlators}
updateOption={updateOption}
/>
</>
);
}
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
? updateOption(
'sortBy',
mode as keyof typeof CHAPTER_SORT_OPTIONS_TO_TRANSLATION_KEY,
)
: updateOption('reverse', !options.reverse)
}
/>
));
}
if (key === 'display') {
return (
<RadioGroup
onChange={() => updateOption('showChapterNumber', !options.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

@@ -0,0 +1,108 @@
/*
* 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 * as React from 'react';
import { useTranslation } from 'react-i18next';
import PopupState, { bindMenu, bindTrigger } from 'material-ui-popup-state';
import Menu from '@mui/material/Menu';
import DownloadIcon from '@mui/icons-material/Download';
import DoneAllIcon from '@mui/icons-material/DoneAll';
import { useMemo } from 'react';
import { CustomTooltip } from '@/features/core/components/CustomTooltip.tsx';
import { ChapterOptions } from '@/features/chapter/components/ChapterOptions.tsx';
import { isFilterActive, updateChapterListOptions } from '@/features/chapter/utils/ChapterList.util.tsx';
import {
ChapterBookmarkInfo,
ChapterDownloadInfo,
ChapterIdInfo,
ChapterListOptions,
ChapterReadInfo,
} from '@/features/chapter/Chapter.types.ts';
import { ChaptersDownloadActionMenuItems } from '@/features/chapter/components/actions/ChaptersDownloadActionMenuItems.tsx';
import { Chapters } from '@/features/chapter/services/Chapters.ts';
interface IProps {
mangaId: number;
options: ChapterListOptions;
updateOption: ReturnType<typeof updateChapterListOptions>;
chapters: (ChapterIdInfo & ChapterReadInfo & ChapterDownloadInfo & ChapterBookmarkInfo)[];
scanlators: string[];
excludeScanlators: string[];
}
export const ChaptersToolbarMenu = ({
mangaId,
options,
updateOption,
chapters,
scanlators,
excludeScanlators,
}: IProps) => {
const { t } = useTranslation();
const [open, setOpen] = React.useState(false);
const isFiltered = isFilterActive(options);
const areAllChaptersRead = useMemo(() => chapters.every(Chapters.isRead), [chapters]);
const areAllChaptersDownloaded = useMemo(() => chapters.every(Chapters.isDownloaded), [chapters]);
return (
<>
<CustomTooltip
title={t('chapter.action.mark_as_read.add.label.action.current')}
disabled={areAllChaptersRead}
>
<IconButton
disabled={areAllChaptersRead}
onClick={() => Chapters.markAsRead(Chapters.getNonRead(chapters), true, mangaId)}
color="inherit"
>
<DoneAllIcon />
</IconButton>
</CustomTooltip>
<PopupState variant="popover" popupId="chapterlist-download-button">
{(popupState) => (
<>
<CustomTooltip
title={t('chapter.action.download.add.label.action')}
disabled={areAllChaptersRead}
>
<IconButton
disabled={areAllChaptersDownloaded}
{...bindTrigger(popupState)}
color="inherit"
>
<DownloadIcon />
</IconButton>
</CustomTooltip>
{popupState.isOpen && (
<Menu {...bindMenu(popupState)}>
<ChaptersDownloadActionMenuItems mangaIds={[mangaId]} closeMenu={popupState.close} />
</Menu>
)}
</>
)}
</PopupState>
<CustomTooltip title={t('settings.title')}>
<IconButton onClick={() => setOpen(true)} color="inherit">
<FilterList color={isFiltered ? 'warning' : undefined} />
</IconButton>
</CustomTooltip>
<ChapterOptions
open={open}
onClose={() => setOpen(false)}
options={options}
updateOption={updateOption}
scanlators={scanlators}
excludedScanlators={excludeScanlators}
/>
</>
);
};

View File

@@ -0,0 +1,56 @@
/*
* 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/.
*/
/*
* 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 Typography from '@mui/material/Typography';
import { useTranslation } from 'react-i18next';
export const MissingChaptersInfoSeparator = ({ missingChaptersGap }: { missingChaptersGap: number }) => {
const { t } = useTranslation();
return (
<Stack
sx={{
width: '100%',
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
p: 2,
pt: 3.5,
pb: 2.5,
}}
>
<Box
sx={{
flexGrow: 1,
border: '1px solid',
borderColor: (theme) => theme.palette.text.secondary,
}}
/>
<Typography sx={{ px: 2 }} variant="body2" color="textSecondary">
{t('chapter.missing', { count: missingChaptersGap })}
</Typography>
<Box
sx={{
flexGrow: 1,
border: '1px solid',
borderColor: (theme) => theme.palette.text.secondary,
}}
/>
</Stack>
);
};

View File

@@ -0,0 +1,263 @@
/*
* 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 { ComponentProps, useMemo } from 'react';
import { SelectableCollectionReturnType } from '@/features/collection/hooks/useSelectableCollection.ts';
import { Chapters } from '@/features/chapter/services/Chapters.ts';
import { MenuItem } from '@/features/core/components/menu/MenuItem.tsx';
import {
createGetMenuItemTitle,
createIsMenuItemDisabled,
createShouldShowMenuItem,
} from '@/features/core/components/menu/Menu.utils.ts';
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
import { useMetadataServerSettings } from '@/features/settings/services/ServerSettingsMetadata.ts';
import { ChapterCard } from '@/features/chapter/components/cards/ChapterCard.tsx';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { GetChaptersMangaQuery } from '@/lib/graphql/generated/graphql.ts';
import { GET_CHAPTERS_MANGA } from '@/lib/graphql/queries/ChapterQuery.ts';
import { CHAPTER_ACTION_TO_TRANSLATION } from '@/features/chapter/Chapter.constants.ts';
import {
ChapterAction,
ChapterBookmarkInfo,
ChapterDownloadInfo,
ChapterIdInfo,
ChapterMangaInfo,
ChapterReadInfo,
ChapterRealUrlInfo,
} from '@/features/chapter/Chapter.types.ts';
import { IconWebView } from '@/assets/icons/IconWebView.tsx';
import { IconBrowser } from '@/assets/icons/IconBrowser.tsx';
type BaseProps = { onClose: () => void; selectable?: boolean };
type TChapter = ChapterIdInfo &
ChapterMangaInfo &
ChapterDownloadInfo &
ChapterBookmarkInfo &
ChapterReadInfo &
ChapterRealUrlInfo;
type SingleModeProps = {
chapter: TChapter;
handleSelection?: SelectableCollectionReturnType<TChapter['id']>['handleSelection'];
canBeDownloaded: boolean;
};
type SelectModeProps = {
selectedChapters: ComponentProps<typeof ChapterCard>['chapter'][];
};
type Props =
| (BaseProps & SingleModeProps & PropertiesNever<SelectModeProps>)
| (BaseProps & PropertiesNever<SingleModeProps> & SelectModeProps);
export const ChapterActionMenuItems = ({
chapter,
handleSelection,
canBeDownloaded = false,
selectedChapters = [],
onClose,
selectable = true,
}: Props) => {
const { t } = useTranslation();
const isSingleMode = !!chapter;
const { isDownloaded, isRead, isBookmarked } = chapter ?? {};
const mangaChaptersResponse = requestManager.useGetMangaChapters<GetChaptersMangaQuery>(
GET_CHAPTERS_MANGA,
chapter?.mangaId ?? -1,
{
skip: !chapter,
fetchPolicy: 'cache-only',
},
);
const allChapters = mangaChaptersResponse.data?.chapters.nodes ?? [];
const {
settings: { deleteChaptersWithBookmark },
} = useMetadataServerSettings();
const getMenuItemTitle = createGetMenuItemTitle(isSingleMode, CHAPTER_ACTION_TO_TRANSLATION);
const shouldShowMenuItem = createShouldShowMenuItem(isSingleMode);
const isMenuItemDisabled = createIsMenuItemDisabled(isSingleMode);
const {
downloadableChapters,
downloadedChapters,
unbookmarkedChapters,
bookmarkedChapters,
unreadChapters,
readChapters,
} = useMemo(
() => ({
downloadableChapters: Chapters.getDownloadable(selectedChapters),
downloadedChapters: Chapters.getDownloaded(selectedChapters),
unbookmarkedChapters: Chapters.getNonBookmarked(selectedChapters),
bookmarkedChapters: Chapters.getBookmarked(selectedChapters),
unreadChapters: Chapters.getNonRead(selectedChapters),
readChapters: Chapters.getRead(selectedChapters),
}),
[selectedChapters],
);
const handleSelect = () => {
handleSelection?.(chapter.id, true);
onClose();
};
const performAction = (action: ChapterAction | 'mark_prev_as_read', chapters: TChapter[]) => {
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 chapters;
}
if (!isMarkPrevAsRead) {
return [chapter];
}
const index = allChapters.findIndex(({ id: chapterId }) => chapterId === chapter.id);
const isFirstChapter = index + 1 > allChapters.length - 1;
if (isFirstChapter) {
return [];
}
const previousChapters = allChapters.slice(index + 1);
return Chapters.getNonRead(previousChapters);
};
const chaptersToUpdate = getChapters();
if (!chaptersToUpdate.length) {
onClose();
return;
}
Chapters.performAction(actualAction, Chapters.getIds(chaptersToUpdate), {
chapters: chaptersToUpdate,
wasManuallyMarkedAsRead: true,
trackProgressMangaId: chaptersToUpdate[0]?.mangaId,
}).catch(defaultPromiseErrorHandler('ChapterActionMenuItems::performAction'));
onClose();
};
return (
<>
{isSingleMode && selectable && (
<MenuItem onClick={handleSelect} Icon={CheckBoxOutlineBlank} title={t('chapter.action.label.select')} />
)}
{isSingleMode && (
<>
<MenuItem
Icon={IconBrowser}
disabled={!chapter!.realUrl}
onClick={() => {
window.open(chapter!.realUrl!, '_blank', 'noopener,noreferrer');
onClose();
}}
title={t('global.button.open_browser')}
/>
<MenuItem
Icon={IconWebView}
disabled={!chapter!.realUrl}
onClick={() => {
window.open(
requestManager.getWebviewUrl(chapter!.realUrl!),
'_blank',
'noopener,noreferrer',
);
onClose();
}}
title={t('global.button.open_webview')}
/>
</>
)}
{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', Chapters.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

@@ -0,0 +1,166 @@
/*
* 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 gql from 'graphql-tag';
import { useMetadataServerSettings } from '@/features/settings/services/ServerSettingsMetadata.ts';
import { Mangas } from '@/features/manga/services/Mangas.ts';
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
import {
ChapterOrderBy,
GetChaptersMangaQuery,
GetChaptersMangaQueryVariables,
MangaType,
SortOrder,
} from '@/lib/graphql/generated/graphql.ts';
import { TranslationKey } from '@/Base.types.ts';
import { MANGA_META_FIELDS } from '@/lib/graphql/fragments/MangaFragments.ts';
import { getMangaMetadata } from '@/features/manga/services/MangaMetadata.ts';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { GET_CHAPTERS_MANGA } from '@/lib/graphql/queries/ChapterQuery.ts';
import { filterChapters } from '@/features/chapter/utils/ChapterList.util.tsx';
import { Chapters } from '@/features/chapter/services/Chapters.ts';
import { makeToast } from '@/features/core/utils/Toast.ts';
import { CHAPTER_ACTION_TO_TRANSLATION } from '@/features/chapter/Chapter.constants.ts';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
const DOWNLOAD_OPTIONS: {
title: TranslationKey;
getCount: (downloadAheadLimit: number) => number | undefined;
onlyUnread?: boolean;
isDownloadAhead?: boolean;
}[] = [
{ title: 'chapter.action.download.add.label.next', getCount: () => 1 },
{ title: 'chapter.action.download.add.label.next', getCount: () => 5 },
{ title: 'chapter.action.download.add.label.next', getCount: () => 10 },
{ title: 'chapter.action.download.add.label.next', getCount: () => 25 },
{
title: 'chapter.action.download.add.label.ahead',
getCount: (downloadAheadLimit) => downloadAheadLimit,
onlyUnread: true,
isDownloadAhead: true,
},
{ title: 'chapter.action.download.add.label.unread', getCount: () => undefined, onlyUnread: true },
{ title: 'chapter.action.download.add.label.all', getCount: () => undefined, onlyUnread: false },
];
const handleDownload = async (
mangaIds: MangaType['id'][],
onlyUnread: boolean,
size: number | undefined,
downloadAhead: boolean,
): Promise<void> => {
const isMultiMangaManga = mangaIds.length > 1;
if (isMultiMangaManga) {
Mangas.performAction('download', mangaIds, {
downloadAhead,
onlyUnread,
size,
}).catch(defaultPromiseErrorHandler('ChaptersDownloadActionMenuItems::handleSelect:multiMangaMode'));
return;
}
const mangaId = mangaIds[0];
const manga = Mangas.getFromCache(
mangaId,
gql`
${MANGA_META_FIELDS}
fragment MangaInLibraryState on MangaType {
id
meta {
...MANGA_META_FIELDS
}
}
`,
'MangaInLibraryState',
)!;
const meta = getMangaMetadata(manga);
const chapters = await requestManager.getChapters<GetChaptersMangaQuery, GetChaptersMangaQueryVariables>(
GET_CHAPTERS_MANGA,
{
// Align conditions/filters with the query from ChapterList to potentially be able to reuse the cache
condition: { mangaId: Number(mangaId) },
order: [{ by: ChapterOrderBy.SourceOrder, byType: SortOrder.Desc }],
},
).response;
const filteredChapters = filterChapters(chapters.data.chapters.nodes, meta);
const doNecessaryDownloadAheadDownloadsExist =
downloadAhead &&
Chapters.removeDuplicates(filteredChapters.slice(-1)[0], filteredChapters)
.slice(-(size ?? 0))
.every((chapter) => !Chapters.isRead(chapter) && Chapters.isDownloaded(chapter));
if (doNecessaryDownloadAheadDownloadsExist) {
return;
}
const unreadUndownloadedChapters = filteredChapters.filter((chapter) => {
if (onlyUnread && chapter.isRead) {
return false;
}
return !chapter.isDownloaded;
});
const uniqueChapters = Chapters.removeDuplicates(
unreadUndownloadedChapters.slice(-1)[0],
unreadUndownloadedChapters,
);
const chaptersToDownload = uniqueChapters.slice(-(size ?? 0));
const chaptersToDownloadWithDuplicates = Chapters.addDuplicates(chaptersToDownload, unreadUndownloadedChapters);
if (!chaptersToDownloadWithDuplicates.length) {
return;
}
Chapters.performAction('download', Chapters.getIds(chaptersToDownloadWithDuplicates), {}).catch(
defaultPromiseErrorHandler('ChaptersDownloadActionMenuItems::handleSelect::singleMangaMode'),
);
};
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) => {
handleDownload(mangaIds, onlyUnread, size, downloadAhead).catch((e) =>
makeToast(
t(CHAPTER_ACTION_TO_TRANSLATION.download.error, {
count: size,
}),
'error',
getErrorMessage(e),
),
);
closeMenu?.();
};
return (
<>
{DOWNLOAD_OPTIONS.map(({ title, getCount, onlyUnread, isDownloadAhead }) => (
<MenuItem
key={t(title, { count: getCount(downloadAheadLimit) })}
onClick={() => handleSelect(getCount(downloadAheadLimit), onlyUnread, isDownloadAhead)}
>
{t(title, { count: getCount(downloadAheadLimit) })}
</MenuItem>
))}
</>
);
};

View File

@@ -0,0 +1,56 @@
/*
* 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 IconButton from '@mui/material/IconButton';
import { useTranslation } from 'react-i18next';
import DownloadIcon from '@mui/icons-material/Download';
import { CustomTooltip } from '@/features/core/components/CustomTooltip.tsx';
import { Chapters } from '@/features/chapter/services/Chapters.ts';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { makeToast } from '@/features/core/utils/Toast.ts';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
import { MUIUtil } from '@/lib/mui/MUI.util.ts';
import { ChapterIdInfo } from '@/features/chapter/Chapter.types.ts';
export const ChapterDownloadButton = ({
chapterId,
isDownloaded,
}: {
chapterId: ChapterIdInfo['id'];
isDownloaded: boolean;
}) => {
const { t } = useTranslation();
const download = Chapters.useDownloadStatusFromCache(chapterId);
const downloadChapter = () => {
requestManager
.addChapterToDownloadQueue(chapterId)
.response.catch((e) =>
makeToast(t('global.error.label.failed_to_save_changes'), 'error', getErrorMessage(e)),
);
};
if (download == null && isDownloaded) {
return null;
}
return (
<CustomTooltip title={t('chapter.action.download.add.label.action')}>
<IconButton
{...MUIUtil.preventRippleProp()}
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
downloadChapter();
}}
>
<DownloadIcon />
</IconButton>
</CustomTooltip>
);
};

View File

@@ -0,0 +1,51 @@
/*
* 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 Refresh from '@mui/icons-material/Refresh';
import IconButton from '@mui/material/IconButton';
import { useTranslation } from 'react-i18next';
import { DownloadState } from '@/lib/graphql/generated/graphql.ts';
import { CustomTooltip } from '@/features/core/components/CustomTooltip.tsx';
import { Chapters } from '@/features/chapter/services/Chapters.ts';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { makeToast } from '@/features/core/utils/Toast.ts';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
import { MUIUtil } from '@/lib/mui/MUI.util.ts';
import { ChapterIdInfo } from '@/features/chapter/Chapter.types.ts';
export const ChapterDownloadRetryButton = ({ chapterId }: { chapterId: ChapterIdInfo['id'] }) => {
const { t } = useTranslation();
const download = Chapters.useDownloadStatusFromCache(chapterId);
const handleRetry = async () => {
try {
await requestManager.addChapterToDownloadQueue(chapterId).response;
} catch (e) {
makeToast(t('download.queue.error.label.failed_to_retry'), 'error', getErrorMessage(e));
}
};
if (download?.state !== DownloadState.Error) {
return null;
}
return (
<CustomTooltip title={t('global.button.retry')}>
<IconButton
{...MUIUtil.preventRippleProp()}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
handleRetry();
}}
>
<Refresh />
</IconButton>
</CustomTooltip>
);
};

View File

@@ -0,0 +1,228 @@
/*
* 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 Card from '@mui/material/Card';
import IconButton from '@mui/material/IconButton';
import { useTheme } from '@mui/material/styles';
import React, { memo, 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 { CustomTooltip } from '@/features/core/components/CustomTooltip.tsx';
import { getDateString } from '@/util/DateHelper.ts';
import { DownloadStateIndicator } from '@/features/core/components/downloads/DownloadStateIndicator.tsx';
import { ChapterType } from '@/lib/graphql/generated/graphql.ts';
import { ChapterActionMenuItems } from '@/features/chapter/components/actions/ChapterActionMenuItems.tsx';
import { Menu } from '@/features/core/components/menu/Menu.tsx';
import { Chapters } from '@/features/chapter/services/Chapters.ts';
import { applyStyles } from '@/features/core/utils/ApplyStyles.ts';
import { ChapterCardMetadata } from '@/features/chapter/components/cards/ChapterCardMetadata.tsx';
import { MUIUtil } from '@/lib/mui/MUI.util.ts';
import { ListCardContent } from '@/features/core/components/lists/cards/ListCardContent.tsx';
import {
ChapterBookmarkInfo,
ChapterDownloadInfo,
ChapterIdInfo,
ChapterMangaInfo,
ChapterNumberInfo,
ChapterReadInfo,
ChapterScanlatorInfo,
} from '@/features/chapter/Chapter.types.ts';
import { MediaQuery } from '@/features/core/utils/MediaQuery.tsx';
type TChapter = ChapterIdInfo &
ChapterMangaInfo &
ChapterDownloadInfo &
ChapterReadInfo &
ChapterBookmarkInfo &
ChapterNumberInfo &
ChapterScanlatorInfo &
Pick<ChapterType, 'name' | 'sourceOrder' | 'uploadDate'>;
interface IProps {
mode?: 'manga.page' | 'reader';
chapter: TChapter;
showChapterNumber: boolean;
onSelect: (id: number, selected: boolean, isShiftKey?: boolean) => void;
selected: boolean | null;
selectable?: boolean;
isActiveChapter?: boolean; // reader
}
export const ChapterCard = memo((props: IProps) => {
const { t } = useTranslation();
const theme = useTheme();
const preventMobileContextMenu = MediaQuery.usePreventMobileContextMenu();
const menuButtonRef = useRef<HTMLButtonElement>(null);
const {
mode = 'manga.page',
chapter,
showChapterNumber,
onSelect,
selected,
selectable = true,
isActiveChapter = false,
} = props;
const isSelecting = selected !== null;
const { isDownloaded } = chapter;
const handleClick = (event: MouseEvent | TouchEvent) => {
if (!isSelecting) return;
event.preventDefault();
event.stopPropagation();
onSelect(chapter.id, !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 (
<PopupState variant="popover" popupId="chapter-card-action-menu">
{(popupState) => (
<Stack sx={{ pt: 1, px: 1 }}>
<Card
sx={{
...applyStyles(mode === 'reader' && isActiveChapter, {
backgroundColor: 'primary.main',
}),
}}
>
<CardActionArea
component={Link}
to={Chapters.getReaderUrl(chapter)}
onContextMenu={preventMobileContextMenu}
sx={MediaQuery.preventMobileContextMenuSx()}
style={{
color: theme.palette.text[chapter.isRead ? 'disabled' : 'primary'],
}}
state={Chapters.getReaderOpenChapterLocationState(chapter, true)}
replace={mode === 'reader'}
onClick={(e) => handleClick(e)}
{...longPressBind(popupState.open)}
>
<ListCardContent>
<ChapterCardMetadata
title={
showChapterNumber
? `${t('chapter.title_one')} ${chapter.chapterNumber}`
: chapter.name
}
secondaryText={chapter.scanlator}
ternaryText={`${getDateString(Number(chapter.uploadDate ?? 0), true)}${isDownloaded ? `${t('chapter.status.label.downloaded')}` : ''}`}
infoIcons={
chapter.isBookmarked && (
<BookmarkIcon
color={mode === 'reader' && isActiveChapter ? 'secondary' : 'primary'}
/>
)
}
slotProps={{
title: {
variant: 'h6',
component: 'h3',
sx: applyStyles(mode === 'reader' && isActiveChapter, {
color: theme.palette.primary.contrastText,
}),
},
secondaryText: {
sx: applyStyles(mode === 'reader' && isActiveChapter, {
color: theme.palette.primary.contrastText,
}),
},
ternaryText: {
sx: applyStyles(mode === 'reader' && isActiveChapter, {
color: theme.palette.primary.contrastText,
}),
},
}}
/>
<DownloadStateIndicator
chapterId={chapter.id}
color={
mode === 'reader' && isActiveChapter
? theme.palette.primary.contrastText
: undefined
}
/>
<Stack sx={{ minHeight: '48px' }}>
{selected === null ? (
<CustomTooltip title={t('global.button.options')}>
<IconButton
ref={menuButtonRef}
{...MUIUtil.preventRippleProp(bindTrigger(popupState), {
onClick: (e: MouseEvent) => handleClickOpenMenu(e),
})}
aria-label="more"
sx={{
color: 'inherit',
...applyStyles(mode === 'reader' && isActiveChapter, {
color: 'primary.contrastText',
}),
}}
>
<MoreVertIcon />
</IconButton>
</CustomTooltip>
) : (
<CustomTooltip
title={t(selected ? 'global.button.deselect' : 'global.button.select')}
>
<Checkbox checked={selected} />
</CustomTooltip>
)}
</Stack>
</ListCardContent>
</CardActionArea>
</Card>
{!isSelecting && popupState.isOpen && (
<Menu {...bindMenu(popupState)}>
{(onClose) => (
<ChapterActionMenuItems
onClose={onClose}
chapter={chapter}
handleSelection={() => onSelect(chapter.id, true)}
canBeDownloaded={Chapters.isDownloadable(chapter)}
selectable={selectable}
/>
)}
</Menu>
)}
</Stack>
)}
</PopupState>
);
});

View File

@@ -0,0 +1,83 @@
/*
* 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 { ComponentProps, ReactNode } from 'react';
import Stack from '@mui/material/Stack';
import { TypographyMaxLines } from '@/features/core/components/texts/TypographyMaxLines.tsx';
import { CustomTooltip } from '@/features/core/components/CustomTooltip.tsx';
export const ChapterCardMetadata = ({
title,
secondaryText,
ternaryText,
infoIcons,
slotProps,
}: {
title: string;
secondaryText?: string | null;
ternaryText?: string | null;
infoIcons?: ReactNode;
slotProps?: {
title?: ComponentProps<typeof TypographyMaxLines>;
secondaryText?: ComponentProps<typeof TypographyMaxLines>;
ternaryText?: ComponentProps<typeof TypographyMaxLines>;
};
}) => (
<Box
sx={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
flexGrow: 1,
flexShrink: 1,
wordBreak: 'break-word',
}}
>
<Stack
sx={{
flexDirection: 'row',
gap: 0.5,
alignItems: 'center',
}}
>
{infoIcons}
<CustomTooltip title={title}>
<TypographyMaxLines variant="h6" component="h3" {...slotProps?.title}>
{title}
</TypographyMaxLines>
</CustomTooltip>
</Stack>
{secondaryText && (
<CustomTooltip title={secondaryText}>
<TypographyMaxLines
variant="caption"
display="block"
lines={1}
{...slotProps?.secondaryText}
sx={{ maxWidth: 'fit-content', ...slotProps?.secondaryText?.sx }}
>
{secondaryText}
</TypographyMaxLines>
</CustomTooltip>
)}
{ternaryText && (
<CustomTooltip title={ternaryText}>
<TypographyMaxLines
variant="caption"
display="block"
lines={1}
{...slotProps?.ternaryText}
sx={{ maxWidth: 'fit-content', ...slotProps?.ternaryText?.sx }}
>
{ternaryText}
</TypographyMaxLines>
</CustomTooltip>
)}
</Box>
);

View File

@@ -0,0 +1,32 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { Link } from 'react-router-dom';
import { AppRoutes } from '@/features/core/AppRoute.constants.ts';
import { Mangas } from '@/features/manga/services/Mangas.ts';
import { MangaIdInfo, MangaThumbnailInfo } from '@/features/manga/Manga.types.ts';
import { MangaType } from '@/lib/graphql/generated/graphql.ts';
import { ListCardAvatar } from '@/features/core/components/lists/cards/ListCardAvatar.tsx';
export const ChapterCardThumbnail = ({
mangaId,
mangaTitle,
thumbnailUrl,
thumbnailUrlLastFetched,
}: MangaThumbnailInfo & {
mangaId: MangaIdInfo['id'];
mangaTitle: MangaType['title'];
}) => (
<Link to={AppRoutes.manga.path(mangaId)} style={{ textDecoration: 'none' }}>
<ListCardAvatar
iconUrl={Mangas.getThumbnailUrl({ thumbnailUrl, thumbnailUrlLastFetched })}
alt={mangaTitle}
slots={{ spinnerImageProps: { imgStyle: { imageRendering: 'pixelated' } } }}
/>
</Link>
);

View File

@@ -0,0 +1,43 @@
/*
* 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 Stack from '@mui/material/Stack';
import { ComponentProps } from 'react';
import { ChapterCard } from '@/features/chapter/components/cards/ChapterCard.tsx';
import { Chapters } from '@/features/chapter/services/Chapters.ts';
import { applyStyles } from '@/features/core/utils/ApplyStyles.ts';
import { MissingChaptersInfoSeparator } from '@/features/chapter/components/MissingChaptersInfoSeparator.tsx';
type ChapterCardProps = ComponentProps<typeof ChapterCard>;
export const ChapterListCard = ({
index,
isSortDesc,
chapters,
...chapterCardProps
}: Omit<ChapterCardProps, 'chapter'> & {
index: number;
isSortDesc: boolean;
chapters: ChapterCardProps['chapter'][];
}) => {
const previousChapterIndex = isSortDesc ? index + 1 : index - 1;
const chapter = chapters[index];
const previousChapter = chapters[previousChapterIndex] ?? { chapterNumber: 0 };
const missingChaptersGap = Chapters.getGap(chapter, previousChapter);
const areChaptersMissing = missingChaptersGap > 0;
return (
<Stack sx={applyStyles(!isSortDesc, { flexDirection: 'column-reverse' })}>
<ChapterCard {...chapterCardProps} chapter={chapters[index]} />
{areChaptersMissing && <MissingChaptersInfoSeparator missingChaptersGap={missingChaptersGap} />}
</Stack>
);
};

View File

@@ -0,0 +1,485 @@
/*
* 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 { DocumentNode, MaybeMasked, Unmasked, useFragment } from '@apollo/client';
import { makeToast } from '@/features/core/utils/Toast.ts';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { getMetadataServerSettings } from '@/features/settings/services/ServerSettingsMetadata.ts';
import {
ChapterListFieldsFragment,
ChapterType,
DownloadState,
DownloadTypeFieldsFragment,
} from '@/lib/graphql/generated/graphql.ts';
import { CHAPTER_LIST_FIELDS } from '@/lib/graphql/fragments/ChapterFragments.ts';
import { DirectionOffset } from '@/Base.types.ts';
import { MangaIdInfo } from '@/features/manga/Manga.types.ts';
import { ReaderOpenChapterLocationState, ReaderResumeMode } from '@/features/reader/types/Reader.types.ts';
import { AppRoutes } from '@/features/core/AppRoute.constants.ts';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
import { DOWNLOAD_TYPE_FIELDS } from '@/lib/graphql/fragments/DownloadFragments.ts';
import { epochToDate, getDateString } from '@/util/DateHelper.ts';
import {
CHAPTER_ACTION_TO_CONFIRMATION_REQUIRED,
CHAPTER_ACTION_TO_TRANSLATION,
} from '@/features/chapter/Chapter.constants.ts';
import {
ChapterAction,
ChapterBookmarkInfo,
ChapterDownloadInfo,
ChapterIdInfo,
ChapterMangaInfo,
ChapterNumberInfo,
ChapterReadInfo,
ChapterScanlatorInfo,
ChapterSourceOrderInfo,
} from '@/features/chapter/Chapter.types.ts';
import { assertIsDefined } from '@/Asserts.ts';
import { awaitConfirmation } from '@/features/core/utils/AwaitableDialog.tsx';
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',
): Unmasked<T> | null {
return requestManager.graphQLClient.client.cache.readFragment<T>({
id: requestManager.graphQLClient.client.cache.identify({
__typename: 'ChapterType',
id,
}),
fragment,
fragmentName,
});
}
static getDownloadStatusFromCache<T = DownloadTypeFieldsFragment>(
id: number,
fragment: DocumentNode = DOWNLOAD_TYPE_FIELDS,
fragmentName: string = 'DOWNLOAD_TYPE_FIELDS',
): Unmasked<T> | null {
return requestManager.graphQLClient.client.cache.readFragment<T>({
id: requestManager.graphQLClient.client.cache.identify({
__typename: 'DownloadType',
chapter: {
__ref: requestManager.graphQLClient.client.cache.identify({ __typename: 'ChapterType', id }),
},
}),
fragment,
fragmentName,
});
}
static useDownloadStatusFromCache<T = DownloadTypeFieldsFragment>(
id: number,
fragment: DocumentNode = DOWNLOAD_TYPE_FIELDS,
fragmentName: string = 'DOWNLOAD_TYPE_FIELDS',
): MaybeMasked<T> | null {
const downloadStatus = useFragment<T>({
from: {
__typename: 'DownloadType',
chapter: {
__ref: requestManager.graphQLClient.client.cache.identify({ __typename: 'ChapterType', id }),
},
},
fragment,
fragmentName,
client: requestManager.graphQLClient.client,
});
if (!downloadStatus.complete || !Object.keys(downloadStatus.data ?? {}).length) {
return null;
}
return downloadStatus.data;
}
static getReaderUrl<Chapter extends ChapterMangaInfo & ChapterSourceOrderInfo>(chapter: Chapter): string {
return AppRoutes.reader.path(chapter.mangaId, chapter.sourceOrder);
}
static isDownloading(id: number): boolean {
const activeDownloadStates = [DownloadState.Downloading, DownloadState.Queued];
const downloadStatus = Chapters.getDownloadStatusFromCache(id);
return activeDownloadStates.includes(downloadStatus?.state as DownloadState);
}
static isDownloaded({ isDownloaded }: ChapterDownloadInfo): boolean {
return isDownloaded;
}
static getDownloaded<Chapter extends ChapterDownloadInfo>(chapters: Chapter[]): Chapter[] {
return chapters.filter(Chapters.isDownloaded);
}
static isDownloadable<Chapter extends ChapterIdInfo & ChapterDownloadInfo>(chapter: Chapter): boolean {
const downloadStatus = Chapters.getDownloadStatusFromCache(chapter.id);
return !Chapters.isDownloaded(chapter) && (!downloadStatus || downloadStatus.state === DownloadState.Error);
}
static getDownloadable<Chapter extends ChapterIdInfo & ChapterDownloadInfo>(chapters: Chapter[]): Chapter[] {
return chapters.filter(this.isDownloadable);
}
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[], disableConfirmation?: boolean): Promise<void> {
return Chapters.executeAction(
'download',
chapterIds.length,
() => requestManager.addChaptersToDownloadQueue(chapterIds).response,
disableConfirmation,
);
}
static async delete(chapterIds: number[], disableConfirmation?: boolean): Promise<void> {
return Chapters.executeAction(
'delete',
chapterIds.length,
() => requestManager.deleteDownloadedChapters(chapterIds).response,
disableConfirmation,
);
}
static async markAsRead(
chapters: (ChapterIdInfo & ChapterDownloadInfo & ChapterBookmarkInfo)[],
wasManuallyMarkedAsRead: boolean = false,
trackProgressMangaId?: MangaIdInfo['id'],
disableConfirmation?: boolean,
): 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,
disableConfirmation,
);
}
static async markAsUnread(chapterIds: number[], disableConfirmation?: boolean): Promise<void> {
return Chapters.executeAction(
'mark_as_unread',
chapterIds.length,
() => requestManager.updateChapters(chapterIds, { isRead: false }).response,
disableConfirmation,
);
}
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>,
disableConfirmation?: boolean,
): Promise<void> {
const { always, bulkAction, bulkActionCountForce } = CHAPTER_ACTION_TO_CONFIRMATION_REQUIRED[action];
const requiresConfirmation =
(!disableConfirmation && (always || (bulkAction && itemCount > 1))) ||
(bulkActionCountForce && itemCount >= bulkActionCountForce);
const confirmationMessage = CHAPTER_ACTION_TO_TRANSLATION[action].confirmation;
try {
if (requiresConfirmation) {
assertIsDefined(confirmationMessage);
try {
await awaitConfirmation({
title: translate('global.label.are_you_sure'),
message: translate(confirmationMessage, { count: itemCount }),
actions: {
confirm: {
title: translate('global.button.ok'),
},
},
});
} catch (_) {
return;
}
}
await fnToExecute();
makeToast(translate(CHAPTER_ACTION_TO_TRANSLATION[action].success, { count: itemCount }), 'success');
} catch (e) {
makeToast(
translate(CHAPTER_ACTION_TO_TRANSLATION[action].error, { count: itemCount }),
'error',
getErrorMessage(e),
);
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: (ChapterIdInfo & 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 ChapterIdInfo & 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 ChapterIdInfo & 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 ChapterIdInfo & 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;
}
static getReaderResumeMode(chapter: ChapterReadInfo): ReaderResumeMode {
if (chapter.isRead) {
return ReaderResumeMode.START;
}
return ReaderResumeMode.LAST_READ;
}
static getReaderOpenChapterLocationState(
chapter: ChapterReadInfo,
updateInitialChapter?: boolean,
): ReaderOpenChapterLocationState {
return {
resumeMode: Chapters.getReaderResumeMode(chapter),
updateInitialChapter,
};
}
/**
* Returns the chapters grouped by the passed key representing a timestamp.
*
* The timestamp gets mapped to a string via {@link getDateString}
*/
static groupByDate<
T extends Pick<ChapterType, 'lastReadAt'> | Pick<ChapterType, 'fetchedAt'> | Pick<ChapterType, 'uploadDate'>,
K extends keyof ExtractCommon<OmitNotMatching<ChapterType, 'lastReadAt' | 'fetchedAt' | 'uploadDate'>, T>,
>(chapters: T[], key: K): Record<string, T[]> {
return Object.groupBy(chapters, (chapter) => getDateString(epochToDate(Number(chapter[key])))) as Record<
string,
T[]
>;
}
static getMissingCount<Chapter extends ChapterNumberInfo>(chapters: Chapter[]): number {
const sortedChapters = chapters.toSorted((a, b) => a.chapterNumber - b.chapterNumber);
return sortedChapters.reduce(
(missingChapterCount, chapter, index) =>
missingChapterCount + Chapters.getGap(chapter, sortedChapters[index - 1]),
0,
);
}
static getGap<Chapter extends ChapterNumberInfo>(
chapterA: Chapter | undefined,
chapterB: Chapter | undefined,
): number {
if (!chapterA || !chapterB) {
return 0;
}
if (chapterA.chapterNumber === -1 || chapterB.chapterNumber === -1) {
return 0;
}
const higherChapterNumber = Math.max(chapterA.chapterNumber, chapterB.chapterNumber);
const lowerChapterNumber = Math.min(chapterA.chapterNumber, chapterB.chapterNumber);
return Math.max(0, Math.floor(higherChapterNumber) - Math.floor(lowerChapterNumber) - 1);
}
static getScanlators<Chapter extends ChapterScanlatorInfo>(chapters: Chapter[]): string[] {
return [
...new Set(
chapters.map((chapter) => chapter.scanlator).filter((scanlator) => typeof scanlator === 'string'),
),
];
}
}

View File

@@ -0,0 +1,136 @@
/*
* 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 { useMemo } from 'react';
import { ChapterType } from '@/lib/graphql/generated/graphql.ts';
import { NullAndUndefined } from '@/Base.types.ts';
import {
ChapterBookmarkInfo,
ChapterDownloadInfo,
ChapterListOptions,
ChapterReadInfo,
ChapterScanlatorInfo,
} from '@/features/chapter/Chapter.types.ts';
import { MangaIdInfo } from '@/features/manga/Manga.types.ts';
import { GqlMetaHolder } from '@/features/metadata/Metadata.types.ts';
import { createUpdateMangaMetadata, useGetMangaMetadata } from '@/features/manga/services/MangaMetadata.ts';
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.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;
}
}
function scanlatorFilter(excludedScanlators: string[], { scanlator }: ChapterScanlatorInfo): boolean {
return !scanlator || !excludedScanlators.includes(scanlator);
}
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 = ChapterReadInfo & ChapterDownloadInfo & ChapterBookmarkInfo & ChapterScanlatorInfo;
export function filterChapters<Chapters extends TChapterFilter>(
chapters: Chapters[],
options: ChapterListOptions,
): Chapters[] {
return chapters.filter(
(chp) =>
unreadFilter(options.unread, chp) &&
downloadFilter(options.downloaded, chp) &&
bookmarkedFilter(options.bookmarked, chp) &&
scanlatorFilter(options.excludedScanlators, chp),
);
}
export function filterAndSortChapters<Chapters extends TChapterSort & TChapterFilter>(
chapters: Chapters[],
options: ChapterListOptions,
): Chapters[] {
const filtered = filterChapters(chapters, options);
return sortChapters(filtered, options);
}
export const isFilterActive = (options: ChapterListOptions) => {
const { unread, downloaded, bookmarked, excludedScanlators } = options;
return unread != null || downloaded != null || bookmarked != null || !!excludedScanlators.length;
};
export const useChapterListOptions = (manga: MangaIdInfo & GqlMetaHolder): ChapterListOptions => {
const { unread, downloaded, bookmarked, reverse, sortBy, showChapterNumber, excludedScanlators } =
useGetMangaMetadata(manga);
return useMemo(
() => ({ unread, downloaded, bookmarked, reverse, sortBy, showChapterNumber, excludedScanlators }),
[unread, downloaded, bookmarked, reverse, sortBy, showChapterNumber, excludedScanlators],
);
};
export const updateChapterListOptions = (
manga: MangaIdInfo & GqlMetaHolder,
handleError: (error: any) => void = defaultPromiseErrorHandler('createUpdateMangaMetadata'),
) => createUpdateMangaMetadata(manga, handleError);