Structure "source" in sub-features

This commit is contained in:
schroda
2025-08-16 15:48:07 +02:00
parent 9e5af57a5f
commit 32bfca8db2
18 changed files with 21 additions and 18 deletions

View File

@@ -0,0 +1,299 @@
/*
* 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 FilterListIcon from '@mui/icons-material/FilterList';
import Button from '@mui/material/Button';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import IconButton from '@mui/material/IconButton';
import SaveIcon from '@mui/icons-material/Save';
import Chip from '@mui/material/Chip';
import DeleteIcon from '@mui/icons-material/Delete';
import Typography from '@mui/material/Typography';
import PopupState, { bindDialog, bindTrigger } from 'material-ui-popup-state';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import TextField from '@mui/material/TextField';
import { CustomTooltip } from '@/base/components/CustomTooltip.tsx';
import { OptionsPanel } from '@/base/components/modals/OptionsPanel.tsx';
import { CheckBoxFilter } from '@/features/source/browse/components/filters/CheckBoxFilter.tsx';
import { HeaderFilter } from '@/features/source/browse/components/filters/HeaderFilter.tsx';
import { SelectFilter } from '@/features/source/browse/components/filters/SelectFilter.tsx';
import { SortFilter } from '@/features/source/browse/components/filters/SortFilter.tsx';
import { TextFilter } from '@/features/source/browse/components/filters/TextFilter.tsx';
import { TriStateFilter } from '@/features/source/browse/components/filters/TriStateFilter.tsx';
// this can only cycle once, so should be fine
// eslint-disable-next-line import/no-cycle
import { GroupFilter } from '@/features/source/browse/components/filters/GroupFilter.tsx';
import { SeparatorFilter } from '@/features/source/browse/components/filters/SeparatorFilter.tsx';
import { StyledFab } from '@/base/components/buttons/StyledFab.tsx';
import { awaitConfirmation } from '@/base/utils/AwaitableDialog.tsx';
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
import { ISourceMetadata, SourceFilters } from '@/features/source/Source.types.ts';
interface IFilters {
sourceFilter: SourceFilters[];
updateFilterValue: Function;
group: number | undefined;
update: any;
}
interface IFilters1 {
savedSearches: ISourceMetadata['savedSearches'];
selectSavedSearch: (savedSearch: string) => void;
updateSavedSearches: (savedSearch: string, updateType: 'create' | 'delete') => void;
sourceFilter: SourceFilters[];
updateFilterValue: Function;
resetFilterValue: Function;
setTriggerUpdate: Function;
update: any;
}
export function Options({ sourceFilter, group, updateFilterValue, update }: IFilters) {
return (
<Stack key={`filters ${group}`}>
{sourceFilter.map((e, index) => {
let checkif = update.find(
(el: { group: number | undefined; position: number }) =>
el.group === group && el.position === index,
);
checkif = checkif ? checkif.state : checkif;
switch (e.type) {
case 'CheckBoxFilter':
return (
<CheckBoxFilter
key={`filters ${e.name}`}
name={e.name}
state={checkif ?? e.CheckBoxFilterDefault}
position={index}
group={group}
updateFilterValue={updateFilterValue}
update={update}
/>
);
case 'GroupFilter':
return (
<GroupFilter
key={`filters ${e.name}`}
name={e.name}
state={e.filters}
position={index}
updateFilterValue={updateFilterValue}
update={update}
/>
);
case 'HeaderFilter':
return <HeaderFilter key={`filters ${e.name}`} name={e.name} />;
case 'SelectFilter':
return (
<SelectFilter
key={`filters ${e.name}`}
name={e.name}
values={e.values}
state={checkif != null ? parseInt(checkif, 10) : e.SelectFilterDefault}
position={index}
group={group}
updateFilterValue={updateFilterValue}
update={update}
/>
);
case 'SeparatorFilter':
return <SeparatorFilter key={`filters ${e.name}`} name={e.name} />;
case 'SortFilter':
return (
<SortFilter
key={`filters ${e.name}`}
name={e.name}
values={e.values}
state={
checkif ?? {
ascending: e.SortFilterDefault?.ascending,
index: e.SortFilterDefault?.index,
}
}
position={index}
group={group}
updateFilterValue={updateFilterValue}
update={update}
/>
);
case 'TextFilter':
return (
<TextFilter
key={`filters ${e.name}`}
name={e.name}
state={checkif ?? e.TextFilterDefault}
position={index}
group={group}
updateFilterValue={updateFilterValue}
update={update}
/>
);
case 'TriStateFilter':
return (
<TriStateFilter
key={`filters ${e.name}`}
name={e.name}
state={checkif != null ? checkif : e.TriStateFilterDefault}
position={index}
group={group}
updateFilterValue={updateFilterValue}
update={update}
/>
);
default:
throw new Error(`Unknown source filter "${e}"`);
}
})}
</Stack>
);
}
export function SourceOptions({
savedSearches = {},
selectSavedSearch,
updateSavedSearches,
sourceFilter,
updateFilterValue,
resetFilterValue,
setTriggerUpdate,
update,
}: IFilters1) {
const { t } = useTranslation();
const [FilterOptions, setFilterOptions] = useState(false);
const [newSavedSearch, setNewSavedSearch] = useState('');
const savedSearchNames = Object.keys(savedSearches);
const savedSearchesExist = !!savedSearchNames.length;
function handleReset() {
resetFilterValue(0);
setFilterOptions(false);
}
function handleSubmit() {
setTriggerUpdate(0);
setFilterOptions(false);
}
return (
<>
<StyledFab onClick={() => setFilterOptions(!FilterOptions)} variant="extended" color="primary">
<FilterListIcon />
{t('global.button.filter')}
</StyledFab>
<OptionsPanel open={FilterOptions} onClose={() => setFilterOptions(false)}>
<Box sx={{ p: 2, pb: savedSearchesExist ? undefined : 0 }}>
<Box sx={{ display: 'flex', pb: 1 }}>
<Button onClick={handleReset}>{t('global.button.reset')}</Button>
<PopupState variant="dialog" popupId="source-browse-save-search">
{(popupState) => (
<>
<CustomTooltip title={t('source.filter.save_search.label.save')}>
<IconButton sx={{ marginLeft: 'auto' }} {...bindTrigger(popupState)}>
<SaveIcon />
</IconButton>
</CustomTooltip>
<Dialog {...bindDialog(popupState)} maxWidth="xs" fullWidth>
<DialogTitle>{t('source.filter.save_search.dialog.label.title')}</DialogTitle>
<DialogContent>
<TextField
sx={{ width: '100%' }}
value={newSavedSearch}
onChange={(e) => setNewSavedSearch(e.target.value as string)}
slotProps={{
htmlInput: { maxLength: 50 },
}}
/>
</DialogContent>
<DialogActions>
<Button
onClick={() => {
setNewSavedSearch('');
popupState.close();
}}
>
{t('global.button.cancel')}
</Button>
<Button
onClick={() => {
updateSavedSearches(newSavedSearch, 'create');
setNewSavedSearch('');
popupState.close();
}}
>
{t('global.button.ok')}
</Button>
</DialogActions>
</Dialog>
</>
)}
</PopupState>
<Button variant="contained" onClick={handleSubmit}>
{t('global.button.submit')}
</Button>
</Box>
{savedSearchesExist && (
<>
<Typography sx={{ pb: 1 }}>Saved searches</Typography>
<Stack sx={{ flexDirection: 'row' }}>
{savedSearchNames.map((savedSearch) => (
<Chip
label={savedSearch}
onClick={() => {
setFilterOptions(false);
selectSavedSearch(savedSearch);
}}
onDelete={() => {
awaitConfirmation({
title: t('global.label.are_you_sure'),
message: t('source.filter.save_search.dialog.label.delete', {
name: savedSearch,
}),
actions: {
confirm: { title: t('global.button.delete') },
},
})
.then(() => updateSavedSearches(savedSearch, 'delete'))
.catch(defaultPromiseErrorHandler('SourceOptions::deleteSavedSearch'));
}}
deleteIcon={
<CustomTooltip title={t('source.filter.save_search.label.delete')}>
<DeleteIcon />
</CustomTooltip>
}
variant="outlined"
/>
))}
</Stack>
</>
)}
</Box>
<Box
sx={{
pb: 2,
mx: 2,
}}
>
<Options
sourceFilter={sourceFilter}
updateFilterValue={updateFilterValue}
group={undefined}
update={update}
/>
</Box>
</OptionsPanel>
</>
);
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import React from 'react';
import { CheckboxInput } from '@/base/components/inputs/CheckboxInput.tsx';
interface Props {
state: boolean;
name: string;
position: number;
group: number | undefined;
updateFilterValue: Function;
update: any;
}
export const CheckBoxFilter: React.FC<Props> = (props: Props) => {
const { state, name, position, group, updateFilterValue, update } = props;
const [val, setval] = React.useState(state);
const handleChange = (event: { target: { name: any; checked: any } }) => {
setval(event.target.checked);
const upd = update.filter(
(e: { position: number; group: number | undefined }) => !(position === e.position && group === e.group),
);
updateFilterValue([...upd, { type: 'checkBoxState', position, state: event.target.checked, group }]);
};
if (state !== undefined) {
return <CheckboxInput label={name} checked={val} onChange={handleChange} />;
}
return null;
};

View File

@@ -0,0 +1,53 @@
/*
* 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 ExpandLess from '@mui/icons-material/ExpandLess';
import ExpandMore from '@mui/icons-material/ExpandMore';
import Collapse from '@mui/material/Collapse';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemText from '@mui/material/ListItemText';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import React from 'react';
// eslint-disable-next-line import/no-cycle
import { Options } from '@/features/source/browse/components/SourceOptions.tsx';
import { SourceFilters } from '@/features/source/Source.types.ts';
interface Props {
state: ExtractByKeyValue<SourceFilters, '__typename', 'GroupFilter'>['filters'];
name: string;
position: number;
updateFilterValue: Function;
update: any;
}
export const GroupFilter: React.FC<Props> = (props: Props) => {
const { state, name, position, updateFilterValue, update } = props;
const [open, setOpen] = React.useState(false);
return (
<Box sx={{ mx: -2 }}>
<ListItemButton onClick={() => setOpen(!open)}>
<ListItemText primary={name} />
{open ? <ExpandLess /> : <ExpandMore />}
</ListItemButton>
<Collapse in={open}>
{/* Container is moved outside 2, so content has to go inside 4 */}
<Stack sx={{ mx: 4 }}>
<Options
sourceFilter={state as SourceFilters[]}
group={position}
updateFilterValue={updateFilterValue}
update={update}
/>
</Stack>
</Collapse>
</Box>
);
};

View File

@@ -0,0 +1,20 @@
/*
* 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 Typography from '@mui/material/Typography';
import React from 'react';
interface Props {
name: string;
}
export const HeaderFilter: React.FC<Props> = ({ name }) => (
<Typography key={name} sx={{ mt: 2 }} variant="subtitle2">
{name}
</Typography>
);

View File

@@ -0,0 +1,64 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import React from 'react';
import InputLabel from '@mui/material/InputLabel';
import FormControl from '@mui/material/FormControl';
import MenuItem from '@mui/material/MenuItem';
import Select from '@mui/material/Select';
interface Props {
values: any;
name: string;
state: number;
position: number;
updateFilterValue: Function;
group: number | undefined;
update: any;
}
function noSelect(
values: string[],
name: string,
state: number,
position: number,
updateFilterValue: Function,
update: any,
group?: number,
) {
const [val, setval] = React.useState(state);
if (values) {
const handleChange = (event: { target: { name: any; value: any } }) => {
const vall = values.indexOf(`${event.target.value}`);
setval(vall);
const upd = update.filter(
(e: { position: number; group: number | undefined }) => !(position === e.position && group === e.group),
);
updateFilterValue([...upd, { type: 'selectState', position, state: vall, group }]);
};
const rett = values.map((value: string) => (
<MenuItem key={`${name} ${value}`} value={value}>
{value}
</MenuItem>
));
return (
<FormControl sx={{ my: 1 }} variant="standard">
<InputLabel>{name}</InputLabel>
<Select name={name} value={values[val]} label={name} onChange={handleChange}>
{rett}
</Select>
</FormControl>
);
}
return null;
}
export const SelectFilter: React.FC<Props> = ({ values, name, state, position, updateFilterValue, update, group }) =>
noSelect(values, name, state, position, updateFilterValue, update, group);

View File

@@ -0,0 +1,20 @@
/*
* 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 Divider from '@mui/material/Divider';
import React from 'react';
interface Props {
name: string;
}
export const SeparatorFilter: React.FC<Props> = ({ name }) => (
<Divider key={name} sx={{ my: 1 }} textAlign="center">
{name}
</Divider>
);

View File

@@ -0,0 +1,79 @@
/*
* 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 ExpandLess from '@mui/icons-material/ExpandLess';
import ExpandMore from '@mui/icons-material/ExpandMore';
import Collapse from '@mui/material/Collapse';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemText from '@mui/material/ListItemText';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import React from 'react';
import { SortRadioInput } from '@/base/components/inputs/SortRadioInput.tsx';
import { SortSelectionInput } from '@/lib/graphql/generated/graphql.ts';
interface Props {
values: any;
name: string;
state: SortSelectionInput;
position: number;
group: number | undefined;
updateFilterValue: Function;
update: any;
}
export const SortFilter: React.FC<Props> = (props: Props) => {
const { values, name, state, position, group, updateFilterValue, update } = props;
const [val, setval] = React.useState(state);
const [open, setOpen] = React.useState(false);
const handleClick = () => {
setOpen(!open);
};
if (values) {
const handleChange = (index: number) => {
const tmp = val;
if (tmp.index === index) {
tmp.ascending = !tmp.ascending;
} else {
tmp.ascending = true;
}
tmp.index = index;
setval(tmp);
const upd = update.filter(
(e: { position: number; group: number | undefined }) => !(position === e.position && group === e.group),
);
updateFilterValue([...upd, { type: 'sortState', position, state: tmp, group }]);
};
return (
<Box sx={{ mx: -2 }}>
<ListItemButton onClick={handleClick}>
<ListItemText primary={name} />
{open ? <ExpandLess /> : <ExpandMore />}
</ListItemButton>
<Collapse in={open}>
<Stack sx={{ mx: 4 }}>
{values.map((value: string, index: number) => (
<SortRadioInput
key={`${name} ${value}`}
label={value}
checked={val.index === index}
sortDescending={!val.ascending}
onClick={() => handleChange(index)}
/>
))}
</Stack>
</Collapse>
</Box>
);
}
return null;
};

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 SearchIcon from '@mui/icons-material/Search';
import FormControl from '@mui/material/FormControl';
import Input from '@mui/material/Input';
import InputAdornment from '@mui/material/InputAdornment';
import InputLabel from '@mui/material/InputLabel';
import React, { useEffect } from 'react';
import { useDebounce } from '@/base/hooks/useDebounce.ts';
interface Props {
state: string;
name: string;
position: number;
group: number | undefined;
updateFilterValue: Function;
update: any;
}
export const TextFilter: React.FC<Props> = (props) => {
const { state, name, position, group, updateFilterValue, update } = props;
const [Search, setsearch] = React.useState(state || '');
const inputText = useDebounce(Search, 500);
useEffect(() => {
const upd = update.filter(
(el: { position: number; group: number | undefined }) => !(position === el.position && group === el.group),
);
updateFilterValue([...upd, { type: 'textState', position, state: inputText, group }]);
}, [inputText]);
if (state !== undefined) {
return (
<FormControl sx={{ my: 1 }} variant="standard">
<InputLabel>{name}</InputLabel>
<Input
name={name}
value={Search}
onChange={({ target: { value } }) => setsearch(value)}
endAdornment={
<InputAdornment position="end">
<SearchIcon />
</InputAdornment>
}
/>
</FormControl>
);
}
return null;
};

View File

@@ -0,0 +1,80 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import React from 'react';
import { ThreeStateCheckboxInput } from '@/base/components/inputs/ThreeStateCheckboxInput.tsx';
import { TriState } from '@/lib/graphql/generated/graphql.ts';
interface Props {
state: TriState;
name: string;
position: number;
group: number | undefined;
updateFilterValue: Function;
update: any;
}
const convertTriStateToNumber = (triState: TriState): number => {
switch (triState) {
case TriState.Ignore:
return 0;
case TriState.Include:
return 1;
case TriState.Exclude:
return 2;
default:
throw new Error(`Unexpected TriState ${triState}`);
}
};
const convertNumberToTriState = (state: number): TriState => {
switch (state) {
case 0:
return TriState.Ignore;
case 1:
return TriState.Include;
case 2:
return TriState.Exclude;
default:
throw new Error(`Unexpected state number ${state}`);
}
};
export const TriStateFilter: React.FC<Props> = (props) => {
const { state, name, position, group, updateFilterValue, update } = props;
const [val, setval] = React.useState(convertTriStateToNumber(state));
const handleChange = (checked: boolean | null | undefined) => {
// eslint-disable-next-line no-nested-ternary
const newState = checked === undefined ? 0 : checked ? 1 : 2;
setval(newState);
const upd = update.filter(
(e: { position: number; group: number | undefined }) => !(position === e.position && group === e.group),
);
updateFilterValue([
...upd,
{
type: 'triState',
position,
state: convertNumberToTriState(newState),
group,
},
]);
};
if (state !== undefined) {
return (
<ThreeStateCheckboxInput
label={name}
checked={[undefined, true, false][val]}
onChange={(checked) => handleChange(checked)}
/>
);
}
return null;
};

View File

@@ -0,0 +1,507 @@
/*
* 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 { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useParams, useNavigate, useLocation, useSearchParams } from 'react-router-dom';
import IconButton from '@mui/material/IconButton';
import SettingsIcon from '@mui/icons-material/Settings';
import { useQueryParam, StringParam } from 'use-query-params';
import { useTranslation } from 'react-i18next';
import Link from '@mui/material/Link';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import { styled } from '@mui/material/styles';
import FavoriteIcon from '@mui/icons-material/Favorite';
import NewReleasesIcon from '@mui/icons-material/NewReleases';
import FilterListIcon from '@mui/icons-material/FilterList';
import { CustomTooltip } from '@/base/components/CustomTooltip.tsx';
import {
requestManager,
AbortableApolloUseMutationPaginatedResponse,
SPECIAL_ED_SOURCES,
} from '@/lib/requests/RequestManager.ts';
import { SourceGridLayout } from '@/features/source/components/SourceGridLayout.tsx';
import { AppbarSearch } from '@/base/components/AppbarSearch.tsx';
import { SourceOptions } from '@/features/source/browse/components/SourceOptions.tsx';
import { BaseMangaGrid } from '@/features/manga/components/BaseMangaGrid.tsx';
import {
GetSourceBrowseQuery,
GetSourceBrowseQueryVariables,
GetSourceMangasFetchMutation,
GetSourceMangasFetchMutationVariables,
} from '@/lib/graphql/generated/graphql.ts';
import {
updateMetadataServerSettings,
useMetadataServerSettings,
} from '@/features/settings/services/ServerSettingsMetadata.ts';
import { useLocalStorage, useSessionStorage } from '@/base/hooks/useStorage.tsx';
import { MANGA_GRID_SNAPSHOT_KEY } from '@/features/manga/components/MangaGrid.tsx';
import { createUpdateSourceMetadata, useGetSourceMetadata } from '@/features/source/services/SourceMetadata.ts';
import { makeToast } from '@/base/utils/Toast.ts';
import { GET_SOURCE_BROWSE } from '@/lib/graphql/queries/SourceQuery.ts';
import { IPos, SourceIdInfo } from '@/features/source/Source.types.ts';
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
import { EmptyView } from '@/base/components/feedback/EmptyView.tsx';
import { EmptyViewAbsoluteCentered } from '@/base/components/feedback/EmptyViewAbsoluteCentered.tsx';
import { MangaIdInfo } from '@/features/manga/Manga.types.ts';
import { GridLayout, SearchParam, TranslationKey } from '@/base/Base.types.ts';
import { AppRoutes } from '@/base/AppRoute.constants.ts';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
import { Sources } from '@/features/source/services/Sources.ts';
import { useAppTitleAndAction } from '@/features/navigation-bar/hooks/useAppTitleAndAction.ts';
import { useNavBarContext } from '@/features/navigation-bar/NavbarContext.tsx';
import { VirtuosoUtil } from '@/lib/virtuoso/Virtuoso.util.tsx';
const DEFAULT_SOURCE: SourceIdInfo = { id: '-1' };
const ContentTypeMenu = styled('div')(({ theme }) => ({
display: 'flex',
position: 'sticky',
width: '100%',
zIndex: 1,
padding: theme.spacing(1),
gap: theme.spacing(1),
backgroundColor: theme.palette.background.default,
}));
const ContentTypeButton = styled(Button)(() => ({}));
const StyledGridWrapper = styled(Box)(() => ({
minHeight: '100%',
position: 'relative',
}));
export enum SourceContentType {
POPULAR,
LATEST,
SEARCH,
}
const SOURCE_CONTENT_TYPE_TO_ERROR_MSG_KEY: { [contentType in SourceContentType]: TranslationKey } = {
[SourceContentType.POPULAR]: 'manga.error.label.no_mangas_found',
[SourceContentType.LATEST]: 'manga.error.label.no_mangas_found',
[SourceContentType.SEARCH]: 'manga.error.label.no_matches',
};
const getUniqueMangas = <Manga extends MangaIdInfo>(mangas: Manga[]): Manga[] => {
const mangaIdToManga: Record<string, Manga> = {};
const uniqueMangas: Manga[] = [];
mangas.forEach((manga) => {
const isDuplicate = !!mangaIdToManga[manga.id];
if (!isDuplicate) {
mangaIdToManga[manga.id] = manga;
uniqueMangas.push(manga);
}
});
return uniqueMangas;
};
const useSourceManga = (
sourceId: string,
contentType: SourceContentType,
searchTerm: string | null | undefined,
filters: IPos[],
initialPages: number,
hideLibraryEntries: boolean,
): [
AbortableApolloUseMutationPaginatedResponse<GetSourceMangasFetchMutation, GetSourceMangasFetchMutationVariables>[0],
AbortableApolloUseMutationPaginatedResponse<
GetSourceMangasFetchMutation,
GetSourceMangasFetchMutationVariables
>[1][number] & { filteredOutAllItemsOfFetchedPage: boolean },
] => {
let result: AbortableApolloUseMutationPaginatedResponse<
GetSourceMangasFetchMutation,
GetSourceMangasFetchMutationVariables
>;
switch (contentType) {
case SourceContentType.POPULAR:
result = requestManager.useGetSourcePopularMangas(sourceId, initialPages);
break;
case SourceContentType.LATEST:
result = requestManager.useGetSourceLatestMangas(sourceId, initialPages);
break;
case SourceContentType.SEARCH:
result = requestManager.useSourceSearch(
sourceId,
searchTerm ?? '',
filters.map((filter) => {
const { position, state, group } = filter;
const isPartOfGroup = group !== undefined;
if (isPartOfGroup) {
return {
position: group,
groupChange: {
position,
[filter.type]: state,
},
};
}
return {
position,
[filter.type]: state,
};
}),
initialPages,
);
break;
default:
throw new Error(`Unknown ContentType "${contentType}"`);
}
const pages = result[1]!;
const lastLoadedPageIndex = pages.findLastIndex((page) => !!page.data?.fetchSourceManga);
const lastLoadedPage = pages[lastLoadedPageIndex];
const isPageLoading = pages.slice(-1)[0].isLoading;
let filteredOutAllItemsOfFetchedPage = !isPageLoading;
const items = useMemo(() => {
type FetchItemsResult = NonNullable<GetSourceMangasFetchMutation['fetchSourceManga']>['mangas'];
let allItems: FetchItemsResult = [];
pages.forEach((page, index) => {
const pageItems = page.data?.fetchSourceManga?.mangas ?? [];
const nonLibraryPageItems = pageItems.filter((item) => !hideLibraryEntries || !item.inLibrary);
const uniqueItems = getUniqueMangas([...allItems, ...nonLibraryPageItems]);
const isLastPage = !isPageLoading && pages.length === index + 1;
filteredOutAllItemsOfFetchedPage = isLastPage && !nonLibraryPageItems.length && !!pageItems.length;
allItems = uniqueItems;
});
return allItems;
}, [pages, hideLibraryEntries]);
if (lastLoadedPageIndex === -1) {
return [result[0], { ...result[1][result[1].length - 1], filteredOutAllItemsOfFetchedPage }];
}
return [
result[0],
{
...pages[pages.length - 1],
data: {
...lastLoadedPage!.data,
fetchSourceManga: {
...lastLoadedPage!.data!.fetchSourceManga,
hasNextPage:
pages.length > lastLoadedPageIndex + 1
? false
: !!lastLoadedPage!.data!.fetchSourceManga?.hasNextPage,
mangas: items,
},
},
filteredOutAllItemsOfFetchedPage,
},
];
};
export function SourceMangas() {
const { t } = useTranslation();
const { appBarHeight } = useNavBarContext();
const { sourceId } = useParams<{ sourceId: string }>();
const [searchParams, setSearchParams] = useSearchParams();
const navigate = useNavigate();
const location = useLocation();
const { key: locationKey, state: locationState } = location;
const { contentType: initialContentType = SourceContentType.POPULAR, clearCache = false } =
useLocation<{
contentType: SourceContentType;
clearCache: boolean;
}>().state ?? {};
const {
settings: { hideLibraryEntries },
} = useMetadataServerSettings();
const [sourceGridLayout] = useLocalStorage('source-grid-layout', GridLayout.Compact);
const [query] = useQueryParam(SearchParam.QUERY, StringParam);
const [currentFiltersToApply, setCurrentFiltersToApply] = useSessionStorage<IPos[] | undefined>(
`source-mangas-${sourceId}-filters`,
[],
);
const [filtersToApply, setLocationFiltersToApply] = useSessionStorage<IPos[]>(
`source-mangas-location-${locationKey}-${sourceId}-filters`,
currentFiltersToApply ?? [],
);
const [dialogFiltersToApply, setDialogFiltersToApply] = useState<IPos[]>(filtersToApply);
const [currentContentType, setCurrentContentType] = useSessionStorage<SourceContentType | undefined>(
`source-mangas-${sourceId}-content-type`,
initialContentType,
);
const [contentType, setLocationContentType] = useSessionStorage(
`source-mangas-location-${locationKey}-${sourceId}-content-type`,
query ? SourceContentType.SEARCH : currentContentType!,
);
const { key: persistedGridStateKey, deleteState: deletePersistedGridState } =
VirtuosoUtil.usePersistState(MANGA_GRID_SNAPSHOT_KEY);
const scrollToTop = useCallback(() => {
deletePersistedGridState();
window.scrollTo(0, 0);
}, [persistedGridStateKey]);
const currentQuery = useRef(query);
const currentAbortRequest = useRef<(reason: any) => void>(() => {});
const didSearchChange = currentQuery.current !== query;
if (didSearchChange && contentType === SourceContentType.SEARCH) {
currentQuery.current = query;
currentAbortRequest.current(new Error(`SourceMangas(${sourceId}): search string changed`));
scrollToTop();
}
useEffect(
() => () => {
setCurrentFiltersToApply(undefined);
setCurrentContentType(undefined);
},
[sourceId],
);
const setFiltersToApply = (filters: IPos[]) => {
setCurrentFiltersToApply(filters);
setLocationFiltersToApply(filters);
scrollToTop();
};
const setContentType = (newContentType: SourceContentType) => {
setCurrentContentType(newContentType);
setLocationContentType(newContentType);
};
const gridKey = `${contentType}${JSON.stringify(filtersToApply)}${query}`;
const [
loadPage,
{ data, error, isLoading: loading, size: lastPageNum, abortRequest, filteredOutAllItemsOfFetchedPage },
] = useSourceManga(sourceId, contentType, query, filtersToApply, 1, hideLibraryEntries);
currentAbortRequest.current = abortRequest;
const isLoading = loading || filteredOutAllItemsOfFetchedPage;
const mangas = data?.fetchSourceManga?.mangas ?? [];
const hasNextPage = !!data?.fetchSourceManga?.hasNextPage;
const { data: sourceData } = requestManager.useGetSource<GetSourceBrowseQuery, GetSourceBrowseQueryVariables>(
GET_SOURCE_BROWSE,
sourceId,
);
const source = sourceData?.source;
const filters = source?.filters ?? [];
const { savedSearches = {} } = useGetSourceMetadata(source ?? DEFAULT_SOURCE);
const updateSourceMetadata = createUpdateSourceMetadata<'savedSearches'>(source ?? { id: '-1' }, (e) =>
makeToast(t('global.error.label.failed_to_save_changes'), 'error', getErrorMessage(e)),
);
const selectSavedSearch = useCallback(
(savedSearch: string) => {
const { query: savedSearchQuery, filters: savedSearchFilters } = savedSearches[savedSearch];
if (savedSearchFilters) {
setDialogFiltersToApply(savedSearchFilters);
setFiltersToApply(savedSearchFilters);
}
if (savedSearchQuery) {
searchParams.set(SearchParam.QUERY, savedSearchQuery);
setSearchParams(searchParams);
}
},
[savedSearches, locationState],
);
const handleSavedSearchesUpdate = useCallback(
(savedSearch: string, updateType: 'create' | 'delete') => {
if (updateType === 'delete') {
const savedSearchesCopy = { ...savedSearches };
delete savedSearchesCopy[savedSearch];
updateSourceMetadata('savedSearches', savedSearchesCopy);
return;
}
const updatedSavedSearches = {
...savedSearches,
[savedSearch]: { query: query ?? undefined, filters: dialogFiltersToApply },
};
updateSourceMetadata('savedSearches', updatedSavedSearches);
},
[savedSearches, query, dialogFiltersToApply],
);
const message = !isLoading ? t(SOURCE_CONTENT_TYPE_TO_ERROR_MSG_KEY[contentType]) : undefined;
const isLocalSource = sourceId === Sources.LOCAL_SOURCE_ID;
const messageExtra = isLocalSource ? (
<>
<span>{t('source.local_source.label.checkout')} </span>
<Link href="https://github.com/Suwayomi/Suwayomi-Server/wiki/Local-Source" target="_blank" rel="noreferrer">
{t('source.local_source.label.guide')}
</Link>
</>
) : undefined;
const updateContentType = useCallback(
(newContentType: SourceContentType, newSearch?: string | null) => {
setContentType(newContentType);
scrollToTop();
if (query && !newSearch) {
navigate(
{
pathname: '',
},
{
state: { ...locationState, contentType: newContentType },
},
);
}
},
[setContentType, query, scrollToTop],
);
const setSearchContentType = !!query && contentType !== SourceContentType.SEARCH;
if (setSearchContentType) {
updateContentType(SourceContentType.SEARCH, query);
}
const loadMore = useCallback(() => {
if (!hasNextPage) {
return;
}
loadPage(lastPageNum + 1);
}, [lastPageNum, hasNextPage, contentType]);
const resetFilters = () => {
setDialogFiltersToApply([]);
setFiltersToApply([]);
};
useEffect(() => {
updateMetadataServerSettings('lastUsedSourceId', sourceId).catch(
defaultPromiseErrorHandler('SourceMangas::setLastUsedSourceId'),
);
}, [sourceId]);
useEffect(() => {
if (filteredOutAllItemsOfFetchedPage && hasNextPage && !loading) {
loadPage(lastPageNum + 1);
}
}, [filteredOutAllItemsOfFetchedPage, loading]);
useEffect(() => {
if (!clearCache) {
return;
}
const requiresClear = SPECIAL_ED_SOURCES.REVALIDATION.includes(sourceId);
if (!requiresClear) {
return;
}
requestManager.clearBrowseCacheFor(sourceId);
}, [clearCache]);
useAppTitleAndAction(
source?.displayName ?? t('source.title_one'),
<>
<AppbarSearch />
<SourceGridLayout />
{source?.isConfigurable && (
<CustomTooltip title={t('settings.title')}>
<IconButton
onClick={() => navigate(AppRoutes.sources.childRoutes.configure.path(sourceId))}
aria-label="display more actions"
edge="end"
color="inherit"
>
<SettingsIcon />
</IconButton>
</CustomTooltip>
)}
</>,
[source],
);
const EmptyViewComponent = mangas.length ? EmptyView : EmptyViewAbsoluteCentered;
return (
<StyledGridWrapper>
<ContentTypeMenu sx={{ top: `${appBarHeight}px` }}>
<ContentTypeButton
variant={contentType === SourceContentType.POPULAR ? 'contained' : 'outlined'}
startIcon={<FavoriteIcon />}
onClick={() => updateContentType(SourceContentType.POPULAR)}
>
{t('global.button.popular')}
</ContentTypeButton>
{source?.supportsLatest === undefined || source.supportsLatest ? (
<ContentTypeButton
disabled={!source?.supportsLatest}
variant={contentType === SourceContentType.LATEST ? 'contained' : 'outlined'}
startIcon={<NewReleasesIcon />}
onClick={() => updateContentType(SourceContentType.LATEST)}
>
{t('global.button.latest')}
</ContentTypeButton>
) : null}
<ContentTypeButton
variant={contentType === SourceContentType.SEARCH ? 'contained' : 'outlined'}
startIcon={<FilterListIcon />}
onClick={() => updateContentType(SourceContentType.SEARCH, query)}
>
{t('global.button.filter')}
</ContentTypeButton>
</ContentTypeMenu>
{(isLoading || !error || (!!error && !!mangas.length)) && (
<BaseMangaGrid
// the key needs to include filters and query to force a re-render of the virtuoso grid to prevent https://github.com/petyosi/react-virtuoso/issues/1242
key={gridKey}
gridWrapperProps={{ sx: { px: 1, pb: 1 } }}
mangas={mangas}
hasNextPage={hasNextPage}
loadMore={loadMore}
message={message}
messageExtra={messageExtra}
isLoading={isLoading}
gridLayout={sourceGridLayout}
mode="source"
inLibraryIndicator
/>
)}
{error && (
<EmptyViewComponent
message={t('global.error.label.failed_to_load_data')}
messageExtra={getErrorMessage(error)}
retry={() => loadPage(lastPageNum).catch(defaultPromiseErrorHandler('SourceMangas::refetch'))}
/>
)}
{contentType === SourceContentType.SEARCH && (
<SourceOptions
savedSearches={savedSearches}
selectSavedSearch={selectSavedSearch}
updateSavedSearches={handleSavedSearchesUpdate}
sourceFilter={filters}
updateFilterValue={setDialogFiltersToApply}
setTriggerUpdate={() => {
setFiltersToApply(dialogFiltersToApply);
}}
resetFilterValue={resetFilters}
update={dialogFiltersToApply}
/>
)}
</StyledGridWrapper>
);
}