Move library files into new folder
This commit is contained in:
46
src/modules/library/Library.types.ts
Normal file
46
src/modules/library/Library.types.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* 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 { MangaStatus, TrackerType } from '@/lib/graphql/generated/graphql.ts';
|
||||
import { GridLayout } from '@/modules/core/Core.types.ts';
|
||||
|
||||
export type MetadataLibrarySettings = {
|
||||
showAddToLibraryCategorySelectDialog: boolean;
|
||||
ignoreFilters: boolean;
|
||||
removeMangaFromCategories: boolean;
|
||||
showTabSize: boolean;
|
||||
};
|
||||
export type LibrarySortMode =
|
||||
| 'unreadChapters'
|
||||
| 'totalChapters'
|
||||
| 'alphabetically'
|
||||
| 'dateAdded'
|
||||
| 'lastRead'
|
||||
| 'latestFetchedChapter'
|
||||
| 'latestUploadedChapter';
|
||||
|
||||
export interface LibraryOptions {
|
||||
// display options
|
||||
showContinueReadingButton: boolean;
|
||||
showDownloadBadge: boolean;
|
||||
showUnreadBadge: boolean;
|
||||
gridLayout: GridLayout;
|
||||
|
||||
// sort options
|
||||
sortBy: NullAndUndefined<LibrarySortMode>;
|
||||
sortDesc: NullAndUndefined<boolean>;
|
||||
|
||||
// filter options
|
||||
hasDownloadedChapters: NullAndUndefined<boolean>;
|
||||
hasBookmarkedChapters: NullAndUndefined<boolean>;
|
||||
hasUnreadChapters: NullAndUndefined<boolean>;
|
||||
hasDuplicateChapters: NullAndUndefined<boolean>;
|
||||
hasTrackerBinding: Record<TrackerType['id'], NullAndUndefined<boolean>>;
|
||||
hasStatus: Record<MangaStatus, NullAndUndefined<boolean>>;
|
||||
}
|
||||
49
src/modules/library/components/LibraryMangaGrid.tsx
Normal file
49
src/modules/library/components/LibraryMangaGrid.tsx
Normal file
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright (C) Contributors to the Suwayomi project
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import React, { useLayoutEffect } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { GridLayout, useLibraryOptionsContext } from '@/modules/library/contexts/LibraryOptionsContext.tsx';
|
||||
import { IMangaGridProps, MangaGrid } from '@/modules/manga/components/MangaGrid.tsx';
|
||||
|
||||
interface LibraryMangaGridProps
|
||||
extends Required<Pick<IMangaGridProps, 'isSelectModeActive' | 'selectedMangaIds' | 'handleSelection' | 'mangas'>>,
|
||||
Pick<IMangaGridProps, 'retry' | 'message' | 'messageExtra'> {
|
||||
showFilteredOutMessage: boolean;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
export const LibraryMangaGrid: React.FC<LibraryMangaGridProps> = ({
|
||||
showFilteredOutMessage,
|
||||
message,
|
||||
messageExtra,
|
||||
...gridProps
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const { options } = useLibraryOptionsContext();
|
||||
|
||||
useLayoutEffect(() => {
|
||||
document.body.style.overflowY = options.gridLayout === GridLayout.List ? 'auto' : 'scroll';
|
||||
return () => {
|
||||
document.body.style.overflowY = 'auto';
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<MangaGrid
|
||||
gridWrapperProps={{ sx: { p: 1 } }}
|
||||
{...gridProps}
|
||||
hasNextPage={false}
|
||||
loadMore={() => undefined}
|
||||
message={showFilteredOutMessage ? t('library.error.label.no_matches') : message}
|
||||
messageExtra={showFilteredOutMessage ? undefined : messageExtra}
|
||||
gridLayout={options.gridLayout}
|
||||
/>
|
||||
);
|
||||
};
|
||||
216
src/modules/library/components/LibraryOptionsPanel.tsx
Normal file
216
src/modules/library/components/LibraryOptionsPanel.tsx
Normal file
@@ -0,0 +1,216 @@
|
||||
/*
|
||||
* 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 FormLabel from '@mui/material/FormLabel';
|
||||
import RadioGroup from '@mui/material/RadioGroup';
|
||||
import { useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { CheckboxInput } from '@/modules/core/components/inputs/CheckboxInput.tsx';
|
||||
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 { GridLayout } from '@/modules/library/contexts/LibraryOptionsContext.tsx';
|
||||
import { OptionsTabs } from '@/modules/core/components/OptionsTabs.tsx';
|
||||
import { requestManager } from '@/lib/requests/requests/RequestManager.ts';
|
||||
import { Trackers } from '@/lib/data/Trackers.ts';
|
||||
import { GetTrackersSettingsQuery, MangaStatus } from '@/lib/graphql/generated/graphql.ts';
|
||||
import { GET_TRACKERS_SETTINGS } from '@/lib/graphql/queries/TrackerQuery.ts';
|
||||
import { statusToTranslationKey } from '@/modules/manga/services/Mangas.ts';
|
||||
import { CategoryMetadataInfo } from '@/lib/data/Categories.ts';
|
||||
import { createUpdateCategoryMetadata, getCategoryMetadata } from '@/lib/metadata/categoryMetadata.ts';
|
||||
import { makeToast } from '@/lib/ui/Toast.ts';
|
||||
import {
|
||||
createUpdateMetadataServerSettings,
|
||||
useMetadataServerSettings,
|
||||
} from '@/lib/metadata/metadataServerSettings.ts';
|
||||
import { TranslationKey } from '@/Base.types.ts';
|
||||
import { LibrarySortMode } from '@/modules/library/Library.types.ts';
|
||||
|
||||
const TITLES: { [key in 'filter' | 'sort' | 'display']: TranslationKey } = {
|
||||
filter: 'global.label.filter',
|
||||
sort: 'global.label.sort',
|
||||
display: 'global.label.display',
|
||||
};
|
||||
|
||||
const SORT_OPTIONS: [LibrarySortMode, TranslationKey][] = [
|
||||
['unreadChapters', 'library.option.sort.label.by_unread_chapters'],
|
||||
['totalChapters', 'library.option.sort.label.by_total_chapters'],
|
||||
['alphabetically', 'library.option.sort.label.alphabetically'],
|
||||
['dateAdded', 'library.option.sort.label.by_date_added'],
|
||||
['lastRead', 'library.option.sort.label.by_last_read'],
|
||||
['latestFetchedChapter', 'library.option.sort.label.by_latest_fetched_chapter'],
|
||||
['latestUploadedChapter', 'library.option.sort.label.by_latest_uploaded_chapter'],
|
||||
];
|
||||
|
||||
export const LibraryOptionsPanel = ({
|
||||
category,
|
||||
open,
|
||||
onClose,
|
||||
}: {
|
||||
category: CategoryMetadataInfo;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const trackerList = requestManager.useGetTrackerList<GetTrackersSettingsQuery>(GET_TRACKERS_SETTINGS);
|
||||
const loggedInTrackers = Trackers.getLoggedIn(trackerList.data?.trackers.nodes ?? []);
|
||||
|
||||
const categoryLibraryOptions = useMemo(() => getCategoryMetadata(category), [category]);
|
||||
const updateCategoryLibraryOptions = createUpdateCategoryMetadata(category, () =>
|
||||
makeToast(t('global.error.label.failed_to_save_changes', 'error')),
|
||||
);
|
||||
|
||||
const {
|
||||
settings: { showTabSize },
|
||||
} = useMetadataServerSettings();
|
||||
const setSettingValue = createUpdateMetadataServerSettings<'showTabSize'>(() =>
|
||||
makeToast(t('search.error.label.failed_to_save_settings'), 'warning'),
|
||||
);
|
||||
|
||||
return (
|
||||
<OptionsTabs<'filter' | 'sort' | 'display'>
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
tabs={['filter', 'sort', 'display']}
|
||||
tabTitle={(key) => t(TITLES[key])}
|
||||
tabContent={(key) => {
|
||||
if (key === 'filter') {
|
||||
return (
|
||||
<>
|
||||
<ThreeStateCheckboxInput
|
||||
label={t('global.filter.label.unread')}
|
||||
checked={categoryLibraryOptions.hasUnreadChapters}
|
||||
onChange={(c) => updateCategoryLibraryOptions('hasUnreadChapters', c)}
|
||||
/>
|
||||
<ThreeStateCheckboxInput
|
||||
label={t('global.filter.label.downloaded')}
|
||||
checked={categoryLibraryOptions.hasDownloadedChapters}
|
||||
onChange={(c) => updateCategoryLibraryOptions('hasDownloadedChapters', c)}
|
||||
/>
|
||||
<ThreeStateCheckboxInput
|
||||
label={t('global.filter.label.bookmarked')}
|
||||
checked={categoryLibraryOptions.hasBookmarkedChapters}
|
||||
onChange={(c) => updateCategoryLibraryOptions('hasBookmarkedChapters', c)}
|
||||
/>
|
||||
<ThreeStateCheckboxInput
|
||||
label={t('global.filter.label.duplicate_chapters')}
|
||||
checked={categoryLibraryOptions.hasDuplicateChapters}
|
||||
onChange={(c) => updateCategoryLibraryOptions('hasDuplicateChapters', c)}
|
||||
/>
|
||||
<FormLabel sx={{ mt: 2 }}>{t('manga.label.status')}</FormLabel>
|
||||
{Object.values(MangaStatus).map((status) => (
|
||||
<ThreeStateCheckboxInput
|
||||
key={status}
|
||||
label={t(statusToTranslationKey[status])}
|
||||
checked={categoryLibraryOptions.hasStatus[status]}
|
||||
onChange={(checked) =>
|
||||
updateCategoryLibraryOptions('hasStatus', {
|
||||
...categoryLibraryOptions.hasStatus,
|
||||
[status]: checked,
|
||||
})
|
||||
}
|
||||
/>
|
||||
))}
|
||||
<FormLabel sx={{ mt: 2 }}>{t('global.filter.label.tracked')}</FormLabel>
|
||||
{loggedInTrackers.map((tracker) => (
|
||||
<ThreeStateCheckboxInput
|
||||
key={tracker.id}
|
||||
label={tracker.name}
|
||||
checked={categoryLibraryOptions.hasTrackerBinding[tracker.id]}
|
||||
onChange={(checked) =>
|
||||
updateCategoryLibraryOptions('hasTrackerBinding', {
|
||||
...categoryLibraryOptions.hasTrackerBinding,
|
||||
[tracker.id]: checked,
|
||||
})
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
if (key === 'sort') {
|
||||
return SORT_OPTIONS.map(([mode, label]) => (
|
||||
<SortRadioInput
|
||||
key={mode}
|
||||
label={t(label)}
|
||||
checked={categoryLibraryOptions.sortBy === mode}
|
||||
sortDescending={categoryLibraryOptions.sortDesc}
|
||||
onClick={() =>
|
||||
mode !== categoryLibraryOptions.sortBy
|
||||
? updateCategoryLibraryOptions('sortBy', mode)
|
||||
: updateCategoryLibraryOptions('sortDesc', !categoryLibraryOptions.sortDesc)
|
||||
}
|
||||
/>
|
||||
));
|
||||
}
|
||||
if (key === 'display') {
|
||||
const { gridLayout, showContinueReadingButton, showDownloadBadge, showUnreadBadge } =
|
||||
categoryLibraryOptions;
|
||||
return (
|
||||
<>
|
||||
<FormLabel>{t('global.grid_layout.title')}</FormLabel>
|
||||
<RadioGroup
|
||||
onChange={(e) => updateCategoryLibraryOptions('gridLayout', Number(e.target.value))}
|
||||
value={gridLayout}
|
||||
>
|
||||
<RadioInput
|
||||
label={t('global.grid_layout.label.compact_grid')}
|
||||
value={GridLayout.Compact}
|
||||
checked={gridLayout == null || gridLayout === GridLayout.Compact}
|
||||
/>
|
||||
<RadioInput
|
||||
label={t('global.grid_layout.label.comfortable_grid')}
|
||||
value={GridLayout.Comfortable}
|
||||
checked={gridLayout === GridLayout.Comfortable}
|
||||
/>
|
||||
<RadioInput
|
||||
label={t('global.grid_layout.label.list')}
|
||||
value={GridLayout.List}
|
||||
checked={gridLayout === GridLayout.List}
|
||||
/>
|
||||
</RadioGroup>
|
||||
|
||||
<FormLabel sx={{ mt: 2 }}>{t('library.option.display.badge.title')}</FormLabel>
|
||||
<CheckboxInput
|
||||
label={t('library.option.display.badge.label.unread_badges')}
|
||||
checked={showUnreadBadge}
|
||||
onChange={() => updateCategoryLibraryOptions('showUnreadBadge', !showUnreadBadge)}
|
||||
/>
|
||||
<CheckboxInput
|
||||
label={t('library.option.display.badge.label.download_badges')}
|
||||
checked={showDownloadBadge}
|
||||
onChange={() => updateCategoryLibraryOptions('showDownloadBadge', !showDownloadBadge)}
|
||||
/>
|
||||
|
||||
<FormLabel sx={{ mt: 2 }}>{t('library.option.display.tab.title')}</FormLabel>
|
||||
<CheckboxInput
|
||||
label={t('library.option.display.tab.label.show_number_of_items')}
|
||||
checked={showTabSize}
|
||||
onChange={() => setSettingValue('showTabSize', !showTabSize)}
|
||||
/>
|
||||
|
||||
<FormLabel sx={{ mt: 2 }}>{t('global.label.other')}</FormLabel>
|
||||
<CheckboxInput
|
||||
label={t('library.option.display.other.label.show_continue_reading_button')}
|
||||
checked={showContinueReadingButton}
|
||||
onChange={() =>
|
||||
updateCategoryLibraryOptions(
|
||||
'showContinueReadingButton',
|
||||
!showContinueReadingButton,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
44
src/modules/library/components/LibraryToolbarMenu.tsx
Normal file
44
src/modules/library/components/LibraryToolbarMenu.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Copyright (C) Contributors to the Suwayomi project
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import FilterList from '@mui/icons-material/FilterList';
|
||||
import IconButton from '@mui/material/IconButton';
|
||||
import Tooltip from '@mui/material/Tooltip';
|
||||
import { ComponentProps, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { LibraryOptionsPanel } from '@/modules/library/components/LibraryOptionsPanel.tsx';
|
||||
import { useLibraryOptionsContext } from '@/modules/library/contexts/LibraryOptionsContext.tsx';
|
||||
|
||||
export const LibraryToolbarMenu = ({
|
||||
category,
|
||||
}: {
|
||||
category: ComponentProps<typeof LibraryOptionsPanel>['category'];
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [open, setOpen] = useState(false);
|
||||
const { options } = useLibraryOptionsContext();
|
||||
const active =
|
||||
options.hasDownloadedChapters != null ||
|
||||
options.hasUnreadChapters != null ||
|
||||
options.hasBookmarkedChapters != null ||
|
||||
options.hasDuplicateChapters != null ||
|
||||
Object.values(options.hasStatus).some((hasStatus) => hasStatus != null) ||
|
||||
Object.values(options.hasTrackerBinding).some((trackerFilterStatus) => trackerFilterStatus != null);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Tooltip title={t('settings.title')}>
|
||||
<IconButton onClick={() => setOpen(!open)} color={active ? 'warning' : 'inherit'}>
|
||||
<FilterList />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<LibraryOptionsPanel category={category} open={open} onClose={() => setOpen(false)} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
31
src/modules/library/contexts/LibraryOptionsContext.tsx
Normal file
31
src/modules/library/contexts/LibraryOptionsContext.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright (C) Contributors to the Suwayomi project
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import React, { useContext } from 'react';
|
||||
import { getDefaultCategoryMetadata } from '@/lib/metadata/categoryMetadata.ts';
|
||||
import { LibraryOptions } from '@/modules/library/Library.types.ts';
|
||||
|
||||
type ContextType = {
|
||||
options: LibraryOptions;
|
||||
setOptions: React.Dispatch<React.SetStateAction<LibraryOptions>>;
|
||||
};
|
||||
|
||||
export enum GridLayout {
|
||||
Compact = 0,
|
||||
Comfortable = 1,
|
||||
List = 2,
|
||||
}
|
||||
|
||||
export const LibraryOptionsContext = React.createContext<ContextType>({
|
||||
options: getDefaultCategoryMetadata(),
|
||||
setOptions: () => {},
|
||||
});
|
||||
|
||||
export function useLibraryOptionsContext() {
|
||||
return useContext(LibraryOptionsContext);
|
||||
}
|
||||
28
src/modules/library/contexts/LibraryOptionsProvider.tsx
Normal file
28
src/modules/library/contexts/LibraryOptionsProvider.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Copyright (C) Contributors to the Suwayomi project
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import React, { useMemo } from 'react';
|
||||
import { useLocalStorage } from '@/modules/core/hooks/useStorage.tsx';
|
||||
import { LibraryOptionsContext } from '@/modules/library/contexts/LibraryOptionsContext.tsx';
|
||||
import { getDefaultCategoryMetadata } from '@/lib/metadata/categoryMetadata.ts';
|
||||
import { LibraryOptions } from '@/modules/library/Library.types.ts';
|
||||
|
||||
interface IProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export const LibraryOptionsContextProvider: React.FC<IProps> = ({ children }) => {
|
||||
const [options, setOptions] = useLocalStorage<LibraryOptions>('libraryOptions', getDefaultCategoryMetadata());
|
||||
|
||||
const value = useMemo(
|
||||
() => ({ options: { ...getDefaultCategoryMetadata(), ...options }, setOptions }),
|
||||
[options, setOptions],
|
||||
);
|
||||
|
||||
return <LibraryOptionsContext.Provider value={value}>{children}</LibraryOptionsContext.Provider>;
|
||||
};
|
||||
259
src/modules/library/hooks/useGetVisibleLibraryMangas.ts
Normal file
259
src/modules/library/hooks/useGetVisibleLibraryMangas.ts
Normal file
@@ -0,0 +1,259 @@
|
||||
/*
|
||||
* 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 { StringParam, useQueryParam } from 'use-query-params';
|
||||
import { useMemo } from 'react';
|
||||
import { useMetadataServerSettings } from '@/lib/metadata/metadataServerSettings.ts';
|
||||
import { ChapterType, MangaType, SourceType, TrackRecordType } from '@/lib/graphql/generated/graphql.ts';
|
||||
import { MangaChapterCountInfo, MangaIdInfo } from '@/modules/manga/services/Mangas.ts';
|
||||
import { enhancedCleanup } from '@/lib/data/Strings.ts';
|
||||
import { CategoryMetadataInfo } from '@/lib/data/Categories.ts';
|
||||
import { getCategoryMetadata } from '@/lib/metadata/categoryMetadata.ts';
|
||||
import { NullAndUndefined } from '@/Base.types.ts';
|
||||
import { LibraryOptions, LibrarySortMode } from '@/modules/library/Library.types.ts';
|
||||
|
||||
const triStateFilter = (
|
||||
triState: NullAndUndefined<boolean>,
|
||||
enabledFilter: () => boolean,
|
||||
disabledFilter: () => boolean,
|
||||
): boolean => {
|
||||
switch (triState) {
|
||||
case true:
|
||||
return enabledFilter();
|
||||
case false:
|
||||
return disabledFilter();
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
const triStateFilterNumber = (triState: NullAndUndefined<boolean>, count?: number): boolean =>
|
||||
triStateFilter(
|
||||
triState,
|
||||
() => !!count && count >= 1,
|
||||
() => count === 0,
|
||||
);
|
||||
|
||||
const triStateFilterBoolean = (triState: NullAndUndefined<boolean>, status?: boolean): boolean =>
|
||||
triStateFilter(
|
||||
triState,
|
||||
() => !!status,
|
||||
() => !status,
|
||||
);
|
||||
|
||||
const performSearch = (
|
||||
queries: NullAndUndefined<string>[] | undefined,
|
||||
strings: NullAndUndefined<string>[],
|
||||
): boolean => {
|
||||
const actualQueries = queries?.filter((query) => query != null);
|
||||
const actualStrings = strings?.filter((str) => str != null);
|
||||
|
||||
if (!actualQueries?.length) return true;
|
||||
|
||||
const cleanedUpQueries = actualQueries.map(enhancedCleanup);
|
||||
const cleanedUpStrings = actualStrings.map(enhancedCleanup).join(', ');
|
||||
|
||||
return cleanedUpQueries.every((query) => cleanedUpStrings.includes(query));
|
||||
};
|
||||
|
||||
type TMangaQueryFilter = Pick<MangaType, 'title' | 'genre' | 'description' | 'artist' | 'author'> & {
|
||||
source?: NullAndUndefined<Pick<SourceType, 'displayName'>>;
|
||||
};
|
||||
const querySearchManga = (
|
||||
query: NullAndUndefined<string>,
|
||||
{ title, genre: genres, description, artist, author, source }: TMangaQueryFilter,
|
||||
): boolean =>
|
||||
performSearch([query], [title]) ||
|
||||
performSearch(
|
||||
query?.split(','),
|
||||
genres.map((genre) => enhancedCleanup(genre)),
|
||||
) ||
|
||||
performSearch([query], [description]) ||
|
||||
performSearch([query], [artist]) ||
|
||||
performSearch([query], [author]) ||
|
||||
performSearch([query], [source?.displayName]);
|
||||
|
||||
type TMangaTrackerFilter = { trackRecords: { nodes: Pick<TrackRecordType, 'id' | 'trackerId'>[] } };
|
||||
const trackerFilter = (trackFilters: LibraryOptions['hasTrackerBinding'], manga: TMangaTrackerFilter): boolean =>
|
||||
Object.entries(trackFilters)
|
||||
.map(([trackFilterId, trackFilterState]) => {
|
||||
const isTrackerBound = manga.trackRecords.nodes.some(
|
||||
(trackRecord) => trackRecord.trackerId === Number(trackFilterId),
|
||||
);
|
||||
|
||||
return triStateFilter(
|
||||
trackFilterState,
|
||||
() => isTrackerBound,
|
||||
() => !isTrackerBound,
|
||||
);
|
||||
})
|
||||
.every(Boolean);
|
||||
|
||||
type TMangaStatusFilter = Pick<MangaType, 'status'>;
|
||||
const statusFilter = (statusFilters: LibraryOptions['hasStatus'], manga: TMangaStatusFilter): boolean =>
|
||||
Object.entries(statusFilters)
|
||||
.map(([status, statusFilterState]) => triStateFilterBoolean(statusFilterState, status === manga.status))
|
||||
.every(Boolean);
|
||||
|
||||
type TMangaFilterOptions = Pick<
|
||||
LibraryOptions,
|
||||
| 'hasUnreadChapters'
|
||||
| 'hasDownloadedChapters'
|
||||
| 'hasBookmarkedChapters'
|
||||
| 'hasDuplicateChapters'
|
||||
| 'hasTrackerBinding'
|
||||
| 'hasStatus'
|
||||
>;
|
||||
type TMangaFilter = Pick<MangaType, 'downloadCount' | 'unreadCount' | 'bookmarkCount' | 'hasDuplicateChapters'> &
|
||||
TMangaTrackerFilter &
|
||||
TMangaStatusFilter;
|
||||
const filterManga = (
|
||||
manga: TMangaFilter,
|
||||
{
|
||||
hasDownloadedChapters,
|
||||
hasUnreadChapters,
|
||||
hasBookmarkedChapters,
|
||||
hasDuplicateChapters,
|
||||
hasTrackerBinding,
|
||||
hasStatus,
|
||||
}: TMangaFilterOptions,
|
||||
): boolean =>
|
||||
triStateFilterNumber(hasDownloadedChapters, manga.downloadCount) &&
|
||||
triStateFilterNumber(hasUnreadChapters, manga.unreadCount) &&
|
||||
triStateFilterNumber(hasBookmarkedChapters, manga.bookmarkCount) &&
|
||||
triStateFilterBoolean(hasDuplicateChapters, manga.hasDuplicateChapters) &&
|
||||
trackerFilter(hasTrackerBinding, manga) &&
|
||||
statusFilter(hasStatus, manga);
|
||||
|
||||
type TMangasFilter = TMangaQueryFilter & TMangaFilter;
|
||||
const filterMangas = <Manga extends TMangasFilter>(
|
||||
mangas: Manga[],
|
||||
query: NullAndUndefined<string>,
|
||||
options: TMangaFilterOptions & { ignoreFilters: boolean },
|
||||
): Manga[] => {
|
||||
const ignoreFiltersWhileSearching = options.ignoreFilters && query?.length;
|
||||
|
||||
return mangas.filter((manga) => {
|
||||
const matchesSearch = querySearchManga(query, manga);
|
||||
const matchesFilters = ignoreFiltersWhileSearching || filterManga(manga, options);
|
||||
|
||||
return matchesSearch && matchesFilters;
|
||||
});
|
||||
};
|
||||
|
||||
const sortByNumber = (a: number | string = 0, b: number | string = 0) => Number(a) - Number(b);
|
||||
|
||||
const sortByString = (a: string, b: string): number => a.localeCompare(b);
|
||||
|
||||
type TMangaSort = Pick<MangaType, 'title' | 'inLibraryAt' | 'unreadCount'> &
|
||||
MangaChapterCountInfo & {
|
||||
lastReadChapter?: Pick<ChapterType, 'lastReadAt'> | null;
|
||||
latestUploadedChapter?: Pick<ChapterType, 'uploadDate'> | null;
|
||||
latestFetchedChapter?: Pick<ChapterType, 'fetchedAt'> | null;
|
||||
};
|
||||
const sortManga = <Manga extends TMangaSort>(
|
||||
manga: Manga[],
|
||||
sort: NullAndUndefined<LibrarySortMode>,
|
||||
desc: NullAndUndefined<boolean>,
|
||||
): Manga[] => {
|
||||
const result = [...manga];
|
||||
|
||||
switch (sort) {
|
||||
case 'alphabetically':
|
||||
result.sort((a, b) => sortByString(a.title, b.title));
|
||||
break;
|
||||
case 'dateAdded':
|
||||
result.sort((a, b) => sortByNumber(a.inLibraryAt, b.inLibraryAt));
|
||||
break;
|
||||
case 'unreadChapters':
|
||||
result.sort((a, b) => sortByNumber(a.unreadCount, b.unreadCount));
|
||||
break;
|
||||
case 'lastRead':
|
||||
result.sort((a, b) => sortByNumber(a.lastReadChapter?.lastReadAt, b.lastReadChapter?.lastReadAt));
|
||||
break;
|
||||
case 'latestUploadedChapter':
|
||||
result.sort((a, b) =>
|
||||
sortByNumber(a.latestUploadedChapter?.uploadDate, b.latestUploadedChapter?.uploadDate),
|
||||
);
|
||||
break;
|
||||
case 'latestFetchedChapter':
|
||||
result.sort((a, b) => sortByNumber(a.latestFetchedChapter?.fetchedAt, b.latestFetchedChapter?.fetchedAt));
|
||||
break;
|
||||
case 'totalChapters':
|
||||
result.sort((a, b) => sortByNumber(a.chapters.totalCount, b.chapters.totalCount));
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (desc) {
|
||||
result.reverse();
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
export const useGetVisibleLibraryMangas = <Manga extends MangaIdInfo & TMangasFilter & TMangaSort>(
|
||||
mangas: Manga[],
|
||||
category?: CategoryMetadataInfo,
|
||||
): {
|
||||
visibleMangas: Manga[];
|
||||
showFilteredOutMessage: boolean;
|
||||
} => {
|
||||
const [query] = useQueryParam('query', StringParam);
|
||||
const options = getCategoryMetadata(category);
|
||||
const {
|
||||
hasUnreadChapters,
|
||||
hasDownloadedChapters,
|
||||
hasBookmarkedChapters,
|
||||
hasTrackerBinding,
|
||||
hasDuplicateChapters,
|
||||
hasStatus,
|
||||
} = options;
|
||||
const { settings } = useMetadataServerSettings();
|
||||
|
||||
const filteredMangas = useMemo(
|
||||
() =>
|
||||
filterMangas(mangas, query, {
|
||||
...options,
|
||||
ignoreFilters: settings.ignoreFilters,
|
||||
}),
|
||||
[
|
||||
mangas,
|
||||
query,
|
||||
hasUnreadChapters,
|
||||
hasDownloadedChapters,
|
||||
hasBookmarkedChapters,
|
||||
hasTrackerBinding,
|
||||
hasDuplicateChapters,
|
||||
hasStatus,
|
||||
settings.ignoreFilters,
|
||||
],
|
||||
);
|
||||
const sortedMangas = useMemo(
|
||||
() => sortManga(filteredMangas, options.sortBy, options.sortDesc),
|
||||
[filteredMangas, options.sortBy, options.sortDesc],
|
||||
);
|
||||
|
||||
const isATrackFilterActive = Object.values(options.hasTrackerBinding).some(
|
||||
(trackFilterState) => trackFilterState != null,
|
||||
);
|
||||
const showFilteredOutMessage =
|
||||
(hasUnreadChapters != null ||
|
||||
hasDownloadedChapters != null ||
|
||||
hasBookmarkedChapters != null ||
|
||||
!!query ||
|
||||
isATrackFilterActive) &&
|
||||
filteredMangas.length === 0 &&
|
||||
mangas.length > 0;
|
||||
|
||||
return {
|
||||
visibleMangas: sortedMangas,
|
||||
showFilteredOutMessage,
|
||||
};
|
||||
};
|
||||
295
src/modules/library/screens/Library.tsx
Normal file
295
src/modules/library/screens/Library.tsx
Normal file
@@ -0,0 +1,295 @@
|
||||
/*
|
||||
* 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 Chip, { ChipProps } from '@mui/material/Chip';
|
||||
import Tab from '@mui/material/Tab';
|
||||
import { styled } from '@mui/material/styles';
|
||||
import { useCallback, useContext, useLayoutEffect, useMemo, useState } from 'react';
|
||||
import { useQueryParam, NumberParam } from 'use-query-params';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { requestManager } from '@/lib/requests/requests/RequestManager.ts';
|
||||
import { EmptyViewAbsoluteCentered } from '@/modules/core/components/placeholder/EmptyViewAbsoluteCentered.tsx';
|
||||
import { LoadingPlaceholder } from '@/modules/core/components/placeholder/LoadingPlaceholder.tsx';
|
||||
import { TabPanel } from '@/modules/core/components/tabs/TabPanel.tsx';
|
||||
import { LibraryToolbarMenu } from '@/modules/library/components/LibraryToolbarMenu.tsx';
|
||||
import { LibraryMangaGrid } from '@/modules/library/components/LibraryMangaGrid.tsx';
|
||||
import { AppbarSearch } from '@/modules/core/components/AppbarSearch.tsx';
|
||||
import { UpdateChecker } from '@/modules/core/components/UpdateChecker.tsx';
|
||||
import { NavBarContext } from '@/components/context/NavbarContext.tsx';
|
||||
import { useSelectableCollection } from '@/modules/collection/hooks/useSelectableCollection.ts';
|
||||
import { SelectableCollectionSelectMode } from '@/modules/collection/components/SelectableCollectionSelectMode.tsx';
|
||||
import { useGetVisibleLibraryMangas } from '@/modules/library/hooks/useGetVisibleLibraryMangas.ts';
|
||||
import { SelectionFAB } from '@/modules/collection/components/SelectionFAB.tsx';
|
||||
import { MangaActionMenuItems } from '@/modules/manga/components/MangaActionMenuItems.tsx';
|
||||
import { TabsMenu } from '@/modules/core/components/tabs/TabsMenu.tsx';
|
||||
import { TabsWrapper } from '@/modules/core/components/tabs/TabsWrapper.tsx';
|
||||
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
|
||||
import {
|
||||
GetCategoriesLibraryQuery,
|
||||
GetCategoriesLibraryQueryVariables,
|
||||
MangaChapterStatFieldsFragment,
|
||||
MangaType,
|
||||
} from '@/lib/graphql/generated/graphql.ts';
|
||||
import { GET_CATEGORIES_LIBRARY } from '@/lib/graphql/queries/CategoryQuery.ts';
|
||||
import { Mangas } from '@/modules/manga/services/Mangas.ts';
|
||||
import { MANGA_CHAPTER_STAT_FIELDS } from '@/lib/graphql/fragments/MangaFragments.ts';
|
||||
import { useLibraryOptionsContext } from '@/modules/library/contexts/LibraryOptionsContext.tsx';
|
||||
import { useMetadataServerSettings } from '@/lib/metadata/metadataServerSettings.ts';
|
||||
import { getCategoryMetadata } from '@/lib/metadata/categoryMetadata.ts';
|
||||
|
||||
const TitleWithSizeTag = styled('span')({
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
});
|
||||
|
||||
const TitleSizeTag = ({ sx, ...props }: ChipProps) => (
|
||||
<Chip {...props} size="small" sx={{ ...sx, marginLeft: '5px' }} />
|
||||
);
|
||||
|
||||
export function Library() {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const {
|
||||
settings: { showTabSize },
|
||||
} = useMetadataServerSettings();
|
||||
|
||||
const {
|
||||
data: categoriesResponse,
|
||||
error: tabsError,
|
||||
loading: areCategoriesLoading,
|
||||
refetch: refetchCategories,
|
||||
} = requestManager.useGetCategories<GetCategoriesLibraryQuery, GetCategoriesLibraryQueryVariables>(
|
||||
GET_CATEGORIES_LIBRARY,
|
||||
{
|
||||
notifyOnNetworkStatusChange: true,
|
||||
},
|
||||
);
|
||||
const tabsData = categoriesResponse?.categories.nodes.filter(
|
||||
(category) => category.id !== 0 || (category.id === 0 && category.mangas.totalCount),
|
||||
);
|
||||
const tabs = tabsData ?? [];
|
||||
const librarySize = useMemo(
|
||||
() => tabs.map((tab) => tab.mangas.totalCount).reduce((prev, curr) => prev + curr, 0),
|
||||
[tabs],
|
||||
);
|
||||
|
||||
const [tabSearchParam, setTabSearchParam] = useQueryParam('tab', NumberParam);
|
||||
|
||||
const { setOptions } = useLibraryOptionsContext();
|
||||
const activeTab: (typeof tabs)[number] | undefined = tabs.find((tab) => tab.order === tabSearchParam) ?? tabs[0];
|
||||
|
||||
useLayoutEffect(() => {
|
||||
setOptions(getCategoryMetadata(activeTab));
|
||||
}, [activeTab]);
|
||||
|
||||
const {
|
||||
data: categoryMangaResponse,
|
||||
error: mangaError,
|
||||
loading: mangaLoading,
|
||||
refetch: refetchCategoryMangas,
|
||||
} = requestManager.useGetCategoryMangas(activeTab?.id, { skip: !activeTab, notifyOnNetworkStatusChange: true });
|
||||
const categoryMangas = categoryMangaResponse?.mangas.nodes ?? [];
|
||||
const { visibleMangas: mangas, showFilteredOutMessage } = useGetVisibleLibraryMangas(categoryMangas, activeTab);
|
||||
|
||||
const retryFetchCategoryMangas = useCallback(
|
||||
() => refetchCategoryMangas().catch(defaultPromiseErrorHandler('Library::refetchCategoryMangas')),
|
||||
[refetchCategoryMangas, activeTab],
|
||||
);
|
||||
|
||||
const mangaIds = useMemo(() => mangas.map((manga) => manga.id), [mangas]);
|
||||
|
||||
const [isSelectModeActive, setIsSelectModeActive] = useState(false);
|
||||
const {
|
||||
areNoItemsForKeySelected: areNoItemsSelected,
|
||||
areAllItemsForKeySelected: areAllItemsSelected,
|
||||
selectedItemIds,
|
||||
handleSelectAll,
|
||||
handleSelection,
|
||||
clearSelection,
|
||||
} = useSelectableCollection<MangaType['id'], string>(mangas.length, {
|
||||
itemIds: mangaIds,
|
||||
currentKey: activeTab?.id.toString(),
|
||||
});
|
||||
|
||||
const handleSelect: typeof handleSelection = (id, selected, selectOptions) => {
|
||||
setIsSelectModeActive(!!(selectedItemIds.length + (selected ? 1 : -1)));
|
||||
handleSelection(id, selected, selectOptions);
|
||||
};
|
||||
|
||||
const selectedMangas = useMemo(
|
||||
() =>
|
||||
selectedItemIds
|
||||
.map((id) =>
|
||||
Mangas.getFromCache<MangaChapterStatFieldsFragment>(
|
||||
id,
|
||||
MANGA_CHAPTER_STAT_FIELDS,
|
||||
'MANGA_CHAPTER_STAT_FIELDS',
|
||||
),
|
||||
)
|
||||
.filter((manga) => !!manga),
|
||||
[selectedItemIds.length, mangas],
|
||||
);
|
||||
|
||||
const selectionFab = useMemo(() => {
|
||||
if (!isSelectModeActive) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<SelectionFAB selectedItemsCount={selectedItemIds.length} title="manga.title">
|
||||
{(handleClose, setHideMenu) => (
|
||||
<MangaActionMenuItems
|
||||
selectedMangas={selectedMangas}
|
||||
onClose={() => {
|
||||
handleClose();
|
||||
setIsSelectModeActive(false);
|
||||
clearSelection();
|
||||
}}
|
||||
setHideMenu={setHideMenu}
|
||||
/>
|
||||
)}
|
||||
</SelectionFAB>
|
||||
);
|
||||
}, [isSelectModeActive, selectedMangas]);
|
||||
|
||||
const { setTitle, setAction } = useContext(NavBarContext);
|
||||
useLayoutEffect(() => {
|
||||
const title = t('library.title');
|
||||
const navBarTitle = (
|
||||
<TitleWithSizeTag>
|
||||
{title}
|
||||
{showTabSize && <TitleSizeTag sx={{ color: 'inherit' }} label={librarySize} />}
|
||||
</TitleWithSizeTag>
|
||||
);
|
||||
setTitle(navBarTitle, title);
|
||||
setAction(
|
||||
<>
|
||||
{!isSelectModeActive && (
|
||||
<>
|
||||
<AppbarSearch />
|
||||
<LibraryToolbarMenu category={activeTab} />
|
||||
<UpdateChecker categoryId={activeTab?.id} />
|
||||
</>
|
||||
)}
|
||||
<SelectableCollectionSelectMode
|
||||
isActive={isSelectModeActive}
|
||||
areAllItemsSelected={areAllItemsSelected}
|
||||
areNoItemsSelected={areNoItemsSelected}
|
||||
onSelectAll={(selectAll) =>
|
||||
handleSelectAll(selectAll, [...new Set(mangas.map((manga) => manga.id))])
|
||||
}
|
||||
onModeChange={(checked) => {
|
||||
setIsSelectModeActive(checked);
|
||||
|
||||
if (checked) {
|
||||
handleSelectAll(true, [...new Set(mangas.map((manga) => manga.id))]);
|
||||
} else {
|
||||
tabs.forEach((tab) => handleSelectAll(false, [], tab.id.toString()));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</>,
|
||||
);
|
||||
return () => {
|
||||
setTitle('');
|
||||
setAction(null);
|
||||
};
|
||||
}, [
|
||||
t,
|
||||
librarySize,
|
||||
areCategoriesLoading,
|
||||
isSelectModeActive,
|
||||
areNoItemsSelected,
|
||||
areAllItemsSelected,
|
||||
selectedItemIds.length,
|
||||
mangas.length,
|
||||
activeTab,
|
||||
showTabSize,
|
||||
]);
|
||||
|
||||
const handleTabChange = (newTab: number) => {
|
||||
setTabSearchParam(newTab);
|
||||
};
|
||||
|
||||
if (tabsError != null) {
|
||||
return (
|
||||
<EmptyViewAbsoluteCentered
|
||||
message={t('category.error.label.request_failure')}
|
||||
messageExtra={tabsError.message}
|
||||
retry={() => refetchCategories().catch(defaultPromiseErrorHandler('Library::refetchCategories'))}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (areCategoriesLoading) {
|
||||
return <LoadingPlaceholder />;
|
||||
}
|
||||
|
||||
if (tabs.length === 0) {
|
||||
return <EmptyViewAbsoluteCentered message={t('library.error.label.empty')} />;
|
||||
}
|
||||
|
||||
if (tabs.length === 1) {
|
||||
return (
|
||||
<>
|
||||
<LibraryMangaGrid
|
||||
mangas={mangas}
|
||||
message={mangaError ? t('manga.error.label.request_failure') : t('library.error.label.empty')}
|
||||
messageExtra={mangaError?.message}
|
||||
isLoading={mangaLoading}
|
||||
selectedMangaIds={selectedItemIds}
|
||||
isSelectModeActive={isSelectModeActive}
|
||||
handleSelection={handleSelect}
|
||||
showFilteredOutMessage={!mangaError && showFilteredOutMessage}
|
||||
retry={mangaError && retryFetchCategoryMangas}
|
||||
/>
|
||||
{selectionFab}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<TabsWrapper>
|
||||
<TabsMenu value={activeTab.order} onChange={(e, newTab) => handleTabChange(newTab)}>
|
||||
{tabs.map((tab) => (
|
||||
<Tab
|
||||
sx={{ display: 'flex' }}
|
||||
key={tab.id}
|
||||
label={
|
||||
<TitleWithSizeTag>
|
||||
{tab.name}
|
||||
{showTabSize ? <TitleSizeTag label={tab.mangas.totalCount} /> : null}
|
||||
</TitleWithSizeTag>
|
||||
}
|
||||
value={tab.order}
|
||||
/>
|
||||
))}
|
||||
</TabsMenu>
|
||||
{tabs.map((tab) => (
|
||||
<TabPanel key={tab.order} index={tab.order} currentIndex={activeTab.order}>
|
||||
{tab === activeTab && (
|
||||
<LibraryMangaGrid
|
||||
mangas={mangas}
|
||||
message={
|
||||
mangaError ? t('manga.error.label.request_failure') : t('library.error.label.empty')
|
||||
}
|
||||
messageExtra={mangaError?.message}
|
||||
isLoading={mangaLoading}
|
||||
selectedMangaIds={selectedItemIds}
|
||||
isSelectModeActive={isSelectModeActive}
|
||||
handleSelection={handleSelect}
|
||||
showFilteredOutMessage={!mangaError && showFilteredOutMessage}
|
||||
retry={mangaError && retryFetchCategoryMangas}
|
||||
/>
|
||||
)}
|
||||
</TabPanel>
|
||||
))}
|
||||
{selectionFab}
|
||||
</TabsWrapper>
|
||||
);
|
||||
}
|
||||
237
src/modules/library/screens/LibraryDuplicates.tsx
Normal file
237
src/modules/library/screens/LibraryDuplicates.tsx
Normal file
@@ -0,0 +1,237 @@
|
||||
/*
|
||||
* Copyright (C) Contributors to the Suwayomi project
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useContext, useLayoutEffect, useMemo } from 'react';
|
||||
import IconButton from '@mui/material/IconButton';
|
||||
import SettingsIcon from '@mui/icons-material/Settings';
|
||||
import PopupState, { bindMenu, bindTrigger } from 'material-ui-popup-state';
|
||||
import Menu from '@mui/material/Menu';
|
||||
import MenuItem from '@mui/material/MenuItem';
|
||||
import Box from '@mui/material/Box';
|
||||
import { requestManager } from '@/lib/requests/requests/RequestManager.ts';
|
||||
import { NavBarContext } from '@/components/context/NavbarContext.tsx';
|
||||
import { useLocalStorage } from '@/modules/core/hooks/useStorage.tsx';
|
||||
import { GridLayout } from '@/modules/library/contexts/LibraryOptionsContext.tsx';
|
||||
import { GridLayouts } from '@/components/source/GridLayouts.tsx';
|
||||
import { CheckboxInput } from '@/modules/core/components/inputs/CheckboxInput.tsx';
|
||||
import { LoadingPlaceholder } from '@/modules/core/components/placeholder/LoadingPlaceholder.tsx';
|
||||
import { EmptyViewAbsoluteCentered } from '@/modules/core/components/placeholder/EmptyViewAbsoluteCentered.tsx';
|
||||
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
|
||||
import { MangaCard } from '@/modules/manga/components/cards/MangaCard.tsx';
|
||||
import { StyledGroupedVirtuoso } from '@/modules/core/components/virtuoso/StyledGroupedVirtuoso.tsx';
|
||||
import { StyledGroupHeader } from '@/modules/core/components/virtuoso/StyledGroupHeader.tsx';
|
||||
import {
|
||||
GetMangasDuplicatesQuery,
|
||||
GetMangasDuplicatesQueryVariables,
|
||||
MangaType,
|
||||
} from '@/lib/graphql/generated/graphql.ts';
|
||||
import { GET_MANGAS_DUPLICATES } from '@/lib/graphql/queries/MangaQuery.ts';
|
||||
import { BaseMangaGrid } from '@/components/source/BaseMangaGrid.tsx';
|
||||
import { IMangaGridProps } from '@/modules/manga/components/MangaGrid.tsx';
|
||||
import { StyledGroupItemWrapper } from '@/modules/core/components/virtuoso/StyledGroupItemWrapper.tsx';
|
||||
import { enhancedCleanup } from '@/lib/data/Strings.ts';
|
||||
|
||||
const findDuplicatesByTitle = <Manga extends Pick<MangaType, 'title'>>(
|
||||
libraryMangas: Manga[],
|
||||
): Record<string, Manga[]> => {
|
||||
const titleToMangas = Object.groupBy(libraryMangas, ({ title }) => enhancedCleanup(title));
|
||||
|
||||
return Object.fromEntries(
|
||||
Object.entries(titleToMangas)
|
||||
.filter((titleToMangaMap): titleToMangaMap is [string, Manga[]] => (titleToMangaMap[1]?.length ?? 0) > 1)
|
||||
.map(([, mangas]) => [mangas[0].title, mangas]),
|
||||
);
|
||||
};
|
||||
|
||||
type TMangaDuplicate = Pick<MangaType, 'id' | 'title' | 'description'>;
|
||||
const findDuplicatesByTitleAndAlternativeTitles = <Manga extends TMangaDuplicate>(
|
||||
libraryMangas: Manga[],
|
||||
): Record<string, Manga[]> => {
|
||||
const titleToMangas: Record<string, Set<Manga>> = {};
|
||||
const titleToAlternativeTitleMatches: Record<string, Set<Manga>> = {};
|
||||
|
||||
libraryMangas.forEach((mangaToCheck) => {
|
||||
const titleToCheck = enhancedCleanup(mangaToCheck.title);
|
||||
|
||||
titleToMangas[titleToCheck] ??= new Set();
|
||||
titleToMangas[titleToCheck].add(mangaToCheck);
|
||||
|
||||
titleToAlternativeTitleMatches[titleToCheck] ??= new Set();
|
||||
titleToAlternativeTitleMatches[titleToCheck].add(mangaToCheck);
|
||||
|
||||
libraryMangas.forEach((libraryManga) => {
|
||||
const isDifferentManga = mangaToCheck.id !== libraryManga.id;
|
||||
if (!isDifferentManga) {
|
||||
return;
|
||||
}
|
||||
|
||||
const doesTitleMatch = enhancedCleanup(libraryManga.title) === titleToCheck;
|
||||
const doesAlternativeTitleMatch = enhancedCleanup(libraryManga?.description ?? '').includes(titleToCheck);
|
||||
|
||||
const isDuplicate = doesTitleMatch || doesAlternativeTitleMatch;
|
||||
if (!isDuplicate) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (doesTitleMatch) {
|
||||
titleToMangas[titleToCheck].add(libraryManga);
|
||||
}
|
||||
|
||||
if (doesAlternativeTitleMatch) {
|
||||
titleToAlternativeTitleMatches[titleToCheck].add(libraryManga);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const titleToDuplicatesEntries = Object.entries(titleToMangas)
|
||||
.map(([title, titleMatches]) => {
|
||||
const originalTitle = [...titleMatches][0].title;
|
||||
|
||||
const combinedDuplicates = [...titleMatches, ...(titleToAlternativeTitleMatches[title] ?? [])];
|
||||
const duplicates = [...new Set([...combinedDuplicates])];
|
||||
|
||||
const noDuplicatesFound = duplicates.length === 1;
|
||||
if (noDuplicatesFound) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return [originalTitle, duplicates];
|
||||
})
|
||||
.filter((entry) => !!entry);
|
||||
|
||||
return Object.fromEntries(titleToDuplicatesEntries);
|
||||
};
|
||||
|
||||
export const LibraryDuplicates = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [gridLayout, setGridLayout] = useLocalStorage('libraryDuplicatesGridLayout', GridLayout.List);
|
||||
const [checkAlternativeTitles, setCheckAlternativeTitles] = useLocalStorage(
|
||||
'libraryDuplicatesCheckAlternativeTitles',
|
||||
false,
|
||||
);
|
||||
|
||||
const { setTitle, setAction } = useContext(NavBarContext);
|
||||
useLayoutEffect(() => {
|
||||
setTitle(t('library.settings.advanced.duplicates.label.title'));
|
||||
setAction(
|
||||
<>
|
||||
<GridLayouts gridLayout={gridLayout} onChange={setGridLayout} />
|
||||
<PopupState variant="popover" popupId="library-dupliactes-settings">
|
||||
{(popupState) => (
|
||||
<>
|
||||
<IconButton {...bindTrigger(popupState)} color="inherit">
|
||||
<SettingsIcon />
|
||||
</IconButton>
|
||||
<Menu {...bindMenu(popupState)}>
|
||||
<MenuItem>
|
||||
<CheckboxInput
|
||||
label={t(
|
||||
'library.settings.advanced.duplicates.settings.label.check_description',
|
||||
)}
|
||||
checked={checkAlternativeTitles}
|
||||
onChange={(_, checked) => setCheckAlternativeTitles(checked)}
|
||||
/>
|
||||
</MenuItem>
|
||||
</Menu>
|
||||
</>
|
||||
)}
|
||||
</PopupState>
|
||||
</>,
|
||||
);
|
||||
|
||||
return () => {
|
||||
setTitle('');
|
||||
setAction(null);
|
||||
};
|
||||
}, [t, gridLayout, checkAlternativeTitles]);
|
||||
|
||||
const { data, loading, error, refetch } = requestManager.useGetMangas<
|
||||
GetMangasDuplicatesQuery,
|
||||
GetMangasDuplicatesQueryVariables
|
||||
>(GET_MANGAS_DUPLICATES, { condition: { inLibrary: true } });
|
||||
|
||||
const mangasByTitle = useMemo(() => {
|
||||
const libraryMangas: TMangaDuplicate[] = data?.mangas.nodes ?? [];
|
||||
|
||||
if (checkAlternativeTitles) {
|
||||
return findDuplicatesByTitleAndAlternativeTitles(libraryMangas);
|
||||
}
|
||||
|
||||
return findDuplicatesByTitle(libraryMangas);
|
||||
}, [data?.mangas.nodes, checkAlternativeTitles]);
|
||||
|
||||
const duplicatedTitles = useMemo(
|
||||
() => Object.keys(mangasByTitle).toSorted((titleA, titleB) => titleA.localeCompare(titleB)),
|
||||
[mangasByTitle],
|
||||
);
|
||||
const duplicatedMangas = useMemo(
|
||||
() => duplicatedTitles.map((title) => mangasByTitle[title]).flat(),
|
||||
[mangasByTitle],
|
||||
);
|
||||
const mangasCountByTitle = useMemo(
|
||||
() => duplicatedTitles.map((title) => mangasByTitle[title]).map((mangas) => mangas.length),
|
||||
[mangasByTitle],
|
||||
);
|
||||
|
||||
if (loading) {
|
||||
return <LoadingPlaceholder />;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<EmptyViewAbsoluteCentered
|
||||
message={t('global.error.label.failed_to_load_data')}
|
||||
messageExtra={error.message}
|
||||
retry={() => refetch().catch(defaultPromiseErrorHandler('LibraryDuplicates::refetch'))}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (gridLayout === GridLayout.List) {
|
||||
return (
|
||||
<StyledGroupedVirtuoso
|
||||
groupCounts={mangasCountByTitle}
|
||||
groupContent={(index) => (
|
||||
<StyledGroupHeader variant="h5" isFirstItem={index === 0}>
|
||||
{duplicatedTitles[index]}
|
||||
</StyledGroupHeader>
|
||||
)}
|
||||
itemContent={(index) => (
|
||||
<StyledGroupItemWrapper key={duplicatedMangas[index].id}>
|
||||
<MangaCard
|
||||
manga={duplicatedMangas[index] as IMangaGridProps['mangas'][number]}
|
||||
gridLayout={gridLayout}
|
||||
selected={null}
|
||||
mode="duplicate"
|
||||
/>
|
||||
</StyledGroupItemWrapper>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return duplicatedTitles.map((title, index) => (
|
||||
<Box key={title}>
|
||||
<StyledGroupHeader sx={{ pt: index === 0 ? undefined : 0, pb: 0 }} variant="h5" isFirstItem={false}>
|
||||
{title}
|
||||
</StyledGroupHeader>
|
||||
<BaseMangaGrid
|
||||
mangas={mangasByTitle[title] as IMangaGridProps['mangas']}
|
||||
hasNextPage={false}
|
||||
loadMore={() => {}}
|
||||
isLoading={false}
|
||||
gridLayout={gridLayout}
|
||||
inLibraryIndicator={false}
|
||||
horizontal
|
||||
mode="duplicate"
|
||||
/>
|
||||
</Box>
|
||||
));
|
||||
};
|
||||
194
src/modules/library/screens/LibrarySettings.tsx
Normal file
194
src/modules/library/screens/LibrarySettings.tsx
Normal file
@@ -0,0 +1,194 @@
|
||||
/*
|
||||
* 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 { useTranslation } from 'react-i18next';
|
||||
import { useContext, useLayoutEffect } from 'react';
|
||||
import List from '@mui/material/List';
|
||||
import ListItem from '@mui/material/ListItem';
|
||||
import ListItemButton from '@mui/material/ListItemButton';
|
||||
import ListItemText from '@mui/material/ListItemText';
|
||||
import Switch from '@mui/material/Switch';
|
||||
import ListSubheader from '@mui/material/ListSubheader';
|
||||
import { t as translate } from 'i18next';
|
||||
import { NavBarContext } from '@/components/context/NavbarContext.tsx';
|
||||
import { GlobalUpdateSettings } from '@/components/settings/globalUpdate/GlobalUpdateSettings.tsx';
|
||||
import { makeToast } from '@/lib/ui/Toast.ts';
|
||||
import {
|
||||
createUpdateMetadataServerSettings,
|
||||
useMetadataServerSettings,
|
||||
} from '@/lib/metadata/metadataServerSettings.ts';
|
||||
import { requestManager } from '@/lib/requests/requests/RequestManager.ts';
|
||||
import { Mangas } from '@/modules/manga/services/Mangas.ts';
|
||||
import { EmptyViewAbsoluteCentered } from '@/modules/core/components/placeholder/EmptyViewAbsoluteCentered.tsx';
|
||||
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
|
||||
import { LoadingPlaceholder } from '@/modules/core/components/placeholder/LoadingPlaceholder.tsx';
|
||||
import { ListItemLink } from '@/modules/core/components/ListItemLink.tsx';
|
||||
import {
|
||||
GetCategoriesSettingsQuery,
|
||||
GetCategoriesSettingsQueryVariables,
|
||||
GetMangasBaseQuery,
|
||||
GetMangasBaseQueryVariables,
|
||||
} from '@/lib/graphql/generated/graphql.ts';
|
||||
import { GET_CATEGORIES_SETTINGS } from '@/lib/graphql/queries/CategoryQuery.ts';
|
||||
import { GET_MANGAS_BASE } from '@/lib/graphql/queries/MangaQuery.ts';
|
||||
import { MetadataLibrarySettings } from '@/modules/library/Library.types.ts';
|
||||
|
||||
const removeNonLibraryMangasFromCategories = async (): Promise<void> => {
|
||||
try {
|
||||
const nonLibraryMangas = await requestManager.getMangas<GetMangasBaseQuery, GetMangasBaseQueryVariables>(
|
||||
GET_MANGAS_BASE,
|
||||
{
|
||||
filter: { inLibrary: { equalTo: false }, categoryId: { isNull: false } },
|
||||
},
|
||||
).response;
|
||||
|
||||
const mangaIdsToRemove = Mangas.getIds(nonLibraryMangas.data.mangas.nodes);
|
||||
|
||||
if (mangaIdsToRemove.length) {
|
||||
await requestManager.updateMangasCategories(mangaIdsToRemove, {
|
||||
clearCategories: true,
|
||||
}).response;
|
||||
}
|
||||
makeToast(translate('library.settings.advanced.database.cleanup.label.success'), 'success');
|
||||
} catch (e) {
|
||||
makeToast(translate('library.settings.advanced.database.cleanup.label.error'), 'error');
|
||||
}
|
||||
};
|
||||
|
||||
export function LibrarySettings() {
|
||||
const { t } = useTranslation();
|
||||
const { setTitle, setAction } = useContext(NavBarContext);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
setTitle(t('library.settings.title'));
|
||||
setAction(null);
|
||||
|
||||
return () => {
|
||||
setTitle('');
|
||||
setAction(null);
|
||||
};
|
||||
}, [t]);
|
||||
|
||||
const categories = requestManager.useGetCategories<GetCategoriesSettingsQuery, GetCategoriesSettingsQueryVariables>(
|
||||
GET_CATEGORIES_SETTINGS,
|
||||
);
|
||||
const serverSettings = requestManager.useGetServerSettings({ notifyOnNetworkStatusChange: true });
|
||||
const {
|
||||
settings,
|
||||
loading: areMetadataServerSettingsLoading,
|
||||
request: { error: metadataServerSettingsError, refetch: refetchMetadataServerSettings },
|
||||
} = useMetadataServerSettings();
|
||||
|
||||
const setSettingValue = createUpdateMetadataServerSettings<keyof MetadataLibrarySettings>(() =>
|
||||
makeToast(t('search.error.label.failed_to_save_settings'), 'warning'),
|
||||
);
|
||||
|
||||
const loading = serverSettings.loading || areMetadataServerSettingsLoading || categories.loading;
|
||||
if (loading) {
|
||||
return <LoadingPlaceholder />;
|
||||
}
|
||||
|
||||
const error = serverSettings.error ?? metadataServerSettingsError ?? categories.error;
|
||||
if (error) {
|
||||
return (
|
||||
<EmptyViewAbsoluteCentered
|
||||
message={t('global.error.label.failed_to_load_data')}
|
||||
messageExtra={error.message}
|
||||
retry={() => {
|
||||
if (serverSettings.error) {
|
||||
serverSettings
|
||||
?.refetch()
|
||||
.catch(defaultPromiseErrorHandler('LibrarySettings::refetchServerSettings'));
|
||||
}
|
||||
|
||||
if (metadataServerSettingsError) {
|
||||
refetchMetadataServerSettings().catch(
|
||||
defaultPromiseErrorHandler('LibrarySettings::refetchMetadataServerSettings'),
|
||||
);
|
||||
}
|
||||
|
||||
if (categories.error) {
|
||||
categories.refetch().catch(defaultPromiseErrorHandler('LibrarySettings::refetchCategories'));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<List sx={{ pt: 0 }}>
|
||||
<List
|
||||
subheader={
|
||||
<ListSubheader component="div" id="library-general-settings">
|
||||
{t('global.label.general')}
|
||||
</ListSubheader>
|
||||
}
|
||||
>
|
||||
<ListItem>
|
||||
<ListItemText
|
||||
primary={t('library.settings.general.search.ignore_filters.label.title')}
|
||||
secondary={t('library.settings.general.search.ignore_filters.label.description')}
|
||||
/>
|
||||
<Switch
|
||||
edge="end"
|
||||
checked={settings.ignoreFilters}
|
||||
onChange={(e) => setSettingValue('ignoreFilters', e.target.checked)}
|
||||
/>
|
||||
</ListItem>
|
||||
<ListItem>
|
||||
<ListItemText
|
||||
primary={t('library.settings.general.add_to_library.category_selection.label.title')}
|
||||
secondary={t('library.settings.general.add_to_library.category_selection.label.description')}
|
||||
/>
|
||||
<Switch
|
||||
edge="end"
|
||||
checked={settings.showAddToLibraryCategorySelectDialog}
|
||||
onChange={(e) => setSettingValue('showAddToLibraryCategorySelectDialog', e.target.checked)}
|
||||
/>
|
||||
</ListItem>
|
||||
<ListItem>
|
||||
<ListItemText
|
||||
primary={t('library.settings.general.remove_from_library.remove_from_categories.label.title')}
|
||||
secondary={t(
|
||||
'library.settings.general.remove_from_library.remove_from_categories.label.description',
|
||||
)}
|
||||
/>
|
||||
<Switch
|
||||
edge="end"
|
||||
checked={settings.removeMangaFromCategories}
|
||||
onChange={(e) => setSettingValue('removeMangaFromCategories', e.target.checked)}
|
||||
/>
|
||||
</ListItem>
|
||||
</List>
|
||||
<GlobalUpdateSettings
|
||||
serverSettings={serverSettings.data!.settings}
|
||||
categories={categories.data!.categories.nodes}
|
||||
/>
|
||||
<List
|
||||
subheader={
|
||||
<ListSubheader component="div" id="library-advanced">
|
||||
{t('global.label.advanced')}
|
||||
</ListSubheader>
|
||||
}
|
||||
>
|
||||
<ListItemButton onClick={() => removeNonLibraryMangasFromCategories()}>
|
||||
<ListItemText
|
||||
primary={t('library.settings.advanced.database.cleanup.label.title')}
|
||||
secondary={t('library.settings.advanced.database.cleanup.label.description')}
|
||||
/>
|
||||
</ListItemButton>
|
||||
<ListItemLink to="duplicates">
|
||||
<ListItemText
|
||||
primary={t('library.settings.advanced.duplicates.label.title')}
|
||||
secondary={t('library.settings.advanced.duplicates.label.description')}
|
||||
/>
|
||||
</ListItemLink>
|
||||
</List>
|
||||
</List>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user