Move source files into new folder
This commit is contained in:
59
src/modules/source/Source.types.ts
Normal file
59
src/modules/source/Source.types.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* 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 {
|
||||
GetSourceBrowseQuery,
|
||||
GetSourceSettingsQuery,
|
||||
SourcePreferenceChangeInput,
|
||||
} from '@/lib/graphql/generated/graphql.ts';
|
||||
|
||||
export interface IPos {
|
||||
type: 'selectState' | 'textState' | 'checkBoxState' | 'triState' | 'sortState';
|
||||
position: number;
|
||||
state: any;
|
||||
group?: number;
|
||||
}
|
||||
|
||||
export type SavedSourceSearch = { query?: string; filters?: IPos[] };
|
||||
|
||||
export interface ISourceMetadata {
|
||||
savedSearches?: Record<string, SavedSourceSearch>;
|
||||
}
|
||||
|
||||
export type SourceFilters = GetSourceBrowseQuery['source']['filters'][number];
|
||||
|
||||
export type SourceMetadataKeys = keyof ISourceMetadata;
|
||||
|
||||
export type SourcePreferences = GetSourceSettingsQuery['source']['preferences'][number];
|
||||
|
||||
export interface PreferenceProps {
|
||||
updateValue: <Key extends keyof Omit<SourcePreferenceChangeInput, 'position'>>(
|
||||
type: Key,
|
||||
value: SourcePreferenceChangeInput[Key],
|
||||
) => void;
|
||||
}
|
||||
|
||||
export type CheckBoxPreferenceProps = PreferenceProps &
|
||||
ExtractByKeyValue<SourcePreferences, '__typename', 'CheckBoxPreference'>;
|
||||
|
||||
export type SwitchPreferenceCompatProps = PreferenceProps &
|
||||
ExtractByKeyValue<SourcePreferences, '__typename', 'SwitchPreference'>;
|
||||
|
||||
export type TwoStatePreferenceProps = (CheckBoxPreferenceProps | SwitchPreferenceCompatProps) & {
|
||||
// intetnal props
|
||||
twoStateType: 'Switch' | 'Checkbox';
|
||||
};
|
||||
|
||||
export type ListPreferenceProps = PreferenceProps &
|
||||
ExtractByKeyValue<SourcePreferences, '__typename', 'ListPreference'>;
|
||||
|
||||
export type MultiSelectListPreferenceProps = PreferenceProps &
|
||||
ExtractByKeyValue<SourcePreferences, '__typename', 'MultiSelectListPreference'>;
|
||||
|
||||
export type EditTextPreferenceProps = PreferenceProps &
|
||||
ExtractByKeyValue<SourcePreferences, '__typename', 'EditTextPreference'>;
|
||||
159
src/modules/source/components/SourceCard.tsx
Normal file
159
src/modules/source/components/SourceCard.tsx
Normal file
@@ -0,0 +1,159 @@
|
||||
/*
|
||||
* 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 CardActionArea from '@mui/material/CardActionArea';
|
||||
import Box from '@mui/material/Box';
|
||||
import Avatar from '@mui/material/Avatar';
|
||||
import Button from '@mui/material/Button';
|
||||
import Card from '@mui/material/Card';
|
||||
import CardContent from '@mui/material/CardContent';
|
||||
import Typography from '@mui/material/Typography';
|
||||
import React from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Link } from 'react-router-dom';
|
||||
import Stack from '@mui/material/Stack';
|
||||
import { requestManager } from '@/lib/requests/requests/RequestManager.ts';
|
||||
import { translateExtensionLanguage } from '@/screens/util/Extensions.ts';
|
||||
import { SourceContentType } from '@/modules/source/screens/SourceMangas.tsx';
|
||||
import { SpinnerImage } from '@/modules/core/components/SpinnerImage.tsx';
|
||||
import { GetSourcesListQuery } from '@/lib/graphql/generated/graphql.ts';
|
||||
import { MediaQuery } from '@/lib/ui/MediaQuery.tsx';
|
||||
|
||||
interface IProps {
|
||||
source: GetSourcesListQuery['sources']['nodes'][number];
|
||||
showSourceRepo: boolean;
|
||||
}
|
||||
|
||||
export const SourceCard: React.FC<IProps> = (props: IProps) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const isMobileWidth = MediaQuery.useIsMobileWidth();
|
||||
|
||||
const {
|
||||
source: {
|
||||
id,
|
||||
name,
|
||||
lang,
|
||||
iconUrl,
|
||||
supportsLatest,
|
||||
isNsfw,
|
||||
extension: { repo },
|
||||
},
|
||||
showSourceRepo,
|
||||
} = props;
|
||||
|
||||
const isLocalSource = Number(id) === 0;
|
||||
const sourceName = isLocalSource ? t('source.local_source.title') : name;
|
||||
|
||||
return (
|
||||
<Card
|
||||
sx={{
|
||||
margin: 1,
|
||||
marginTop: 0,
|
||||
}}
|
||||
>
|
||||
<CardActionArea
|
||||
component={Link}
|
||||
to={`/sources/${id}`}
|
||||
state={{ contentType: SourceContentType.POPULAR, clearCache: true }}
|
||||
>
|
||||
<CardContent
|
||||
sx={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
padding: 1.5,
|
||||
}}
|
||||
>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center' }}>
|
||||
<Avatar
|
||||
variant="rounded"
|
||||
alt={sourceName}
|
||||
sx={{
|
||||
width: 56,
|
||||
height: 56,
|
||||
flex: '0 0 auto',
|
||||
mr: 1,
|
||||
background: 'transparent',
|
||||
}}
|
||||
>
|
||||
<SpinnerImage
|
||||
spinnerStyle={{ small: true }}
|
||||
imgStyle={{ objectFit: 'cover', width: '100%', height: '100%' }}
|
||||
alt={sourceName}
|
||||
src={requestManager.getValidImgUrlFor(iconUrl)}
|
||||
/>
|
||||
</Avatar>
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
>
|
||||
<Typography variant="h6" component="h3">
|
||||
{sourceName}
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="caption"
|
||||
sx={{
|
||||
display: 'block',
|
||||
}}
|
||||
>
|
||||
{translateExtensionLanguage(lang)}
|
||||
{isNsfw && (
|
||||
<Typography
|
||||
variant="caption"
|
||||
color="error"
|
||||
sx={{
|
||||
display: 'inline',
|
||||
}}
|
||||
>
|
||||
{' 18+'}
|
||||
</Typography>
|
||||
)}
|
||||
{showSourceRepo && (
|
||||
<Typography
|
||||
variant="caption"
|
||||
sx={{
|
||||
display: 'block',
|
||||
}}
|
||||
>
|
||||
{repo}
|
||||
</Typography>
|
||||
)}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
<Stack sx={{ flexDirection: 'row', gap: 1 }}>
|
||||
{supportsLatest && (
|
||||
<Button
|
||||
variant="outlined"
|
||||
component={Link}
|
||||
to={`/sources/${id}`}
|
||||
state={{ contentType: SourceContentType.LATEST, clearCache: true }}
|
||||
>
|
||||
{t('global.button.latest')}
|
||||
</Button>
|
||||
)}
|
||||
{!isMobileWidth && (
|
||||
<Button
|
||||
variant="outlined"
|
||||
component={Link}
|
||||
to={`/sources/${id}`}
|
||||
state={{ contentType: SourceContentType.POPULAR, clearCache: true }}
|
||||
>
|
||||
{t('global.button.popular')}
|
||||
</Button>
|
||||
)}
|
||||
</Stack>
|
||||
</CardContent>
|
||||
</CardActionArea>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
17
src/modules/source/components/SourceGridLayout.tsx
Normal file
17
src/modules/source/components/SourceGridLayout.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* 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 { GridLayout } from '@/modules/library/contexts/LibraryOptionsContext.tsx';
|
||||
import { GridLayouts } from '@/modules/core/components/GridLayouts.tsx';
|
||||
import { useLocalStorage } from '@/modules/core/hooks/useStorage.tsx';
|
||||
|
||||
export function SourceGridLayout() {
|
||||
const [sourceGridLayout, setSourceGridLayout] = useLocalStorage('source-grid-layout', GridLayout.Compact);
|
||||
|
||||
return <GridLayouts gridLayout={sourceGridLayout} onChange={setSourceGridLayout} />;
|
||||
}
|
||||
299
src/modules/source/components/SourceOptions.tsx
Normal file
299
src/modules/source/components/SourceOptions.tsx
Normal 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 Tooltip from '@mui/material/Tooltip';
|
||||
import { OptionsPanel } from '@/modules/core/components/OptionsPanel.tsx';
|
||||
import { CheckBoxFilter } from '@/modules/source/components/filters/CheckBoxFilter.tsx';
|
||||
import { HeaderFilter } from '@/modules/source/components/filters/HeaderFilter.tsx';
|
||||
import { SelectFilter } from '@/modules/source/components/filters/SelectFilter.tsx';
|
||||
import { SortFilter } from '@/modules/source/components/filters/SortFilter.tsx';
|
||||
import { TextFilter } from '@/modules/source/components/filters/TextFilter.tsx';
|
||||
import { TriStateFilter } from '@/modules/source/components/filters/TriStateFilter.tsx';
|
||||
// this can only cycle once, so should be fine
|
||||
// eslint-disable-next-line import/no-cycle
|
||||
import { GroupFilter } from '@/modules/source/components/filters/GroupFilter.tsx';
|
||||
import { SeparatorFilter } from '@/modules/source/components/filters/SeparatorFilter.tsx';
|
||||
import { StyledFab } from '@/modules/core/components/buttons/StyledFab.tsx';
|
||||
import { awaitConfirmation } from '@/lib/ui/AwaitableDialog.tsx';
|
||||
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
|
||||
import { ISourceMetadata, SourceFilters } from '@/modules/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) => (
|
||||
<>
|
||||
<Tooltip title={t('source.filter.save_search.label.save')}>
|
||||
<IconButton sx={{ marginLeft: 'auto' }} {...bindTrigger(popupState)}>
|
||||
<SaveIcon />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<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={
|
||||
<Tooltip title={t('source.filter.save_search.label.delete')}>
|
||||
<DeleteIcon />
|
||||
</Tooltip>
|
||||
}
|
||||
variant="outlined"
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
</>
|
||||
)}
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
pb: 2,
|
||||
mx: 2,
|
||||
}}
|
||||
>
|
||||
<Options
|
||||
sourceFilter={sourceFilter}
|
||||
updateFilterValue={updateFilterValue}
|
||||
group={undefined}
|
||||
update={update}
|
||||
/>
|
||||
</Box>
|
||||
</OptionsPanel>
|
||||
</>
|
||||
);
|
||||
}
|
||||
37
src/modules/source/components/filters/CheckBoxFilter.tsx
Normal file
37
src/modules/source/components/filters/CheckBoxFilter.tsx
Normal 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 '@/modules/core/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;
|
||||
};
|
||||
53
src/modules/source/components/filters/GroupFilter.tsx
Normal file
53
src/modules/source/components/filters/GroupFilter.tsx
Normal 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 '@/modules/source/components/SourceOptions.tsx';
|
||||
import { SourceFilters } from '@/modules/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>
|
||||
);
|
||||
};
|
||||
20
src/modules/source/components/filters/HeaderFilter.tsx
Normal file
20
src/modules/source/components/filters/HeaderFilter.tsx
Normal 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>
|
||||
);
|
||||
64
src/modules/source/components/filters/SelectFilter.tsx
Normal file
64
src/modules/source/components/filters/SelectFilter.tsx
Normal 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);
|
||||
20
src/modules/source/components/filters/SeparatorFilter.tsx
Normal file
20
src/modules/source/components/filters/SeparatorFilter.tsx
Normal 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>
|
||||
);
|
||||
79
src/modules/source/components/filters/SortFilter.tsx
Normal file
79
src/modules/source/components/filters/SortFilter.tsx
Normal 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 '@/modules/core/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;
|
||||
};
|
||||
56
src/modules/source/components/filters/TextFilter.tsx
Normal file
56
src/modules/source/components/filters/TextFilter.tsx
Normal 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 '@/modules/core/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;
|
||||
};
|
||||
80
src/modules/source/components/filters/TriStateFilter.tsx
Normal file
80
src/modules/source/components/filters/TriStateFilter.tsx
Normal 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 '@/modules/core/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;
|
||||
};
|
||||
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
* 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 { useState } from 'react';
|
||||
import ListItemText from '@mui/material/ListItemText';
|
||||
import Dialog from '@mui/material/Dialog';
|
||||
import DialogTitle from '@mui/material/DialogTitle';
|
||||
import DialogContent from '@mui/material/DialogContent';
|
||||
import DialogContentText from '@mui/material/DialogContentText';
|
||||
import DialogActions from '@mui/material/DialogActions';
|
||||
import TextField from '@mui/material/TextField';
|
||||
import Button from '@mui/material/Button';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import ListItemButton from '@mui/material/ListItemButton';
|
||||
|
||||
import { EditTextPreferenceProps } from '@/modules/source/Source.types.ts';
|
||||
|
||||
export function EditTextPreference(props: EditTextPreferenceProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const {
|
||||
EditTextPreferenceTitle: title,
|
||||
summary,
|
||||
dialogTitle,
|
||||
dialogMessage,
|
||||
EditTextPreferenceCurrentValue: currentValue,
|
||||
updateValue,
|
||||
} = props;
|
||||
|
||||
const [internalCurrentValue, setInternalCurrentValue] = useState<string>(currentValue ?? '');
|
||||
const [dialogOpen, setDialogOpen] = useState<boolean>(false);
|
||||
|
||||
const handleDialogCancel = () => {
|
||||
setDialogOpen(false);
|
||||
|
||||
// reset the dialog
|
||||
setInternalCurrentValue(currentValue ?? '');
|
||||
};
|
||||
|
||||
const handleDialogSubmit = () => {
|
||||
setDialogOpen(false);
|
||||
|
||||
updateValue('editTextState', internalCurrentValue);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<ListItemButton onClick={() => setDialogOpen(true)}>
|
||||
<ListItemText primary={title} secondary={summary} />
|
||||
</ListItemButton>
|
||||
<Dialog open={dialogOpen} onClose={handleDialogCancel}>
|
||||
<DialogTitle>{dialogTitle}</DialogTitle>
|
||||
<DialogContent>
|
||||
<DialogContentText>{dialogMessage}</DialogContentText>
|
||||
<TextField
|
||||
autoFocus
|
||||
margin="dense"
|
||||
id="name"
|
||||
type="text"
|
||||
fullWidth
|
||||
value={internalCurrentValue}
|
||||
onChange={(e) => setInternalCurrentValue(e.target.value)}
|
||||
/>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={handleDialogCancel} color="primary">
|
||||
{t('global.button.cancel')}
|
||||
</Button>
|
||||
<Button onClick={handleDialogSubmit} color="primary">
|
||||
{t('global.button.ok')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
/*
|
||||
* 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, { useState, useEffect } from 'react';
|
||||
import ListItemText from '@mui/material/ListItemText';
|
||||
import Dialog from '@mui/material/Dialog';
|
||||
import DialogTitle from '@mui/material/DialogTitle';
|
||||
import DialogContent from '@mui/material/DialogContent';
|
||||
import DialogActions from '@mui/material/DialogActions';
|
||||
import RadioGroup from '@mui/material/RadioGroup';
|
||||
import Radio from '@mui/material/Radio';
|
||||
import FormControlLabel from '@mui/material/FormControlLabel';
|
||||
import Button from '@mui/material/Button';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import ListItemButton from '@mui/material/ListItemButton';
|
||||
|
||||
import { ListPreferenceProps } from '@/modules/source/Source.types.ts';
|
||||
|
||||
interface IListDialogProps {
|
||||
value: string;
|
||||
open: boolean;
|
||||
onClose: (arg0: string | null) => void;
|
||||
options: string[];
|
||||
title: string;
|
||||
}
|
||||
|
||||
function ListDialog(props: IListDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const { value: valueProp, open, onClose, options, title } = props;
|
||||
const [value, setValue] = React.useState(valueProp);
|
||||
const radioGroupRef = React.useRef<HTMLDivElement>(null);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!open) {
|
||||
setValue(valueProp);
|
||||
}
|
||||
}, [valueProp, open]);
|
||||
|
||||
const handleEntering = () => {
|
||||
if (radioGroupRef.current != null) {
|
||||
radioGroupRef?.current.focus();
|
||||
}
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
onClose(null);
|
||||
};
|
||||
|
||||
const handleOk = () => {
|
||||
onClose(value);
|
||||
};
|
||||
|
||||
const handleChange = (event: any) => {
|
||||
setValue(event.target.value);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
sx={{ '& .MuiDialog-paper': { width: '80%', maxHeight: 435 } }}
|
||||
maxWidth="xs"
|
||||
TransitionProps={{ onEntering: handleEntering }}
|
||||
open={open}
|
||||
>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogContent dividers>
|
||||
<RadioGroup ref={radioGroupRef} value={value} onChange={handleChange}>
|
||||
{options.map((option) => (
|
||||
<FormControlLabel value={option} key={option} control={<Radio />} label={option} />
|
||||
))}
|
||||
</RadioGroup>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button autoFocus onClick={handleCancel}>
|
||||
{t('global.button.cancel')}
|
||||
</Button>
|
||||
<Button onClick={handleOk}>{t('global.button.ok')}</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export function ListPreference(props: ListPreferenceProps) {
|
||||
const {
|
||||
ListPreferenceTitle: title,
|
||||
summary,
|
||||
ListPreferenceCurrentValue: currentValue,
|
||||
ListPreferenceDefault: defaultValue,
|
||||
updateValue,
|
||||
entryValues,
|
||||
entries,
|
||||
} = props;
|
||||
const [internalCurrentValue, setInternalCurrentValue] = useState(currentValue ?? defaultValue ?? '');
|
||||
const [dialogOpen, setDialogOpen] = useState<boolean>(false);
|
||||
|
||||
useEffect(() => {
|
||||
setInternalCurrentValue(currentValue ?? defaultValue ?? '');
|
||||
}, [currentValue]);
|
||||
|
||||
const findEntryOf = (value: string) => {
|
||||
const idx = entryValues.indexOf(value);
|
||||
return entries[idx];
|
||||
};
|
||||
|
||||
const findEntryValueOf = (value: string) => {
|
||||
const idx = entries.indexOf(value);
|
||||
return entryValues[idx];
|
||||
};
|
||||
|
||||
const getSummary = () => {
|
||||
if (currentValue == null) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (summary === '%s') {
|
||||
return findEntryOf(currentValue);
|
||||
}
|
||||
return summary;
|
||||
};
|
||||
|
||||
const handleDialogClose = (newValue: string | null) => {
|
||||
if (newValue !== null) {
|
||||
updateValue('listState', findEntryValueOf(newValue));
|
||||
|
||||
// appear smooth
|
||||
setInternalCurrentValue(newValue);
|
||||
}
|
||||
|
||||
setDialogOpen(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<ListItemButton onClick={() => setDialogOpen(true)}>
|
||||
<ListItemText primary={title} secondary={getSummary()} />
|
||||
</ListItemButton>
|
||||
<ListDialog
|
||||
title={title ?? ''}
|
||||
open={dialogOpen}
|
||||
onClose={handleDialogClose}
|
||||
value={findEntryOf(internalCurrentValue)}
|
||||
options={entries}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
/*
|
||||
* 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, { useState, useEffect } from 'react';
|
||||
import ListItemText from '@mui/material/ListItemText';
|
||||
import Dialog from '@mui/material/Dialog';
|
||||
import DialogTitle from '@mui/material/DialogTitle';
|
||||
import DialogContent from '@mui/material/DialogContent';
|
||||
import DialogActions from '@mui/material/DialogActions';
|
||||
import FormGroup from '@mui/material/FormGroup';
|
||||
import Checkbox from '@mui/material/Checkbox';
|
||||
import FormControlLabel from '@mui/material/FormControlLabel';
|
||||
import Button from '@mui/material/Button';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import ListItemButton from '@mui/material/ListItemButton';
|
||||
import { cloneObject } from '@/util/cloneObject.tsx';
|
||||
import { MultiSelectListPreferenceProps } from '@/modules/source/Source.types.ts';
|
||||
|
||||
interface IListDialogProps {
|
||||
selectedValues: string[];
|
||||
open: boolean;
|
||||
onClose: (arg0: string[] | null) => void;
|
||||
values: string[];
|
||||
title: string;
|
||||
}
|
||||
|
||||
function ListDialog(props: IListDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const { selectedValues: selectedValuesProp, open, onClose, values, title } = props;
|
||||
const [selectedValues, setSelectedValues] = React.useState(selectedValuesProp);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!open) {
|
||||
setSelectedValues(selectedValuesProp);
|
||||
}
|
||||
}, [selectedValuesProp, open]);
|
||||
|
||||
const handleCancel = () => {
|
||||
onClose(null);
|
||||
};
|
||||
|
||||
const handleOk = () => {
|
||||
onClose(selectedValues);
|
||||
};
|
||||
|
||||
const handleChange = (event: React.ChangeEvent<HTMLInputElement>, value: string) => {
|
||||
const { checked } = event.target as HTMLInputElement;
|
||||
|
||||
const hasEntry = selectedValues.some((selectedValue) => value === selectedValue);
|
||||
if (checked) {
|
||||
if (!hasEntry) {
|
||||
const selectedValuesClone = cloneObject(selectedValues) as string[];
|
||||
selectedValuesClone.push(value);
|
||||
setSelectedValues(selectedValuesClone);
|
||||
}
|
||||
} else if (hasEntry) {
|
||||
// not checked and has entry
|
||||
const selectedValuesClone = cloneObject(selectedValues) as string[];
|
||||
const index = selectedValuesClone.indexOf(value);
|
||||
selectedValuesClone.splice(index, 1);
|
||||
setSelectedValues(selectedValuesClone);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog sx={{ '& .MuiDialog-paper': { width: '80%', maxHeight: 435 } }} maxWidth="xs" open={open}>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogContent dividers>
|
||||
<FormGroup>
|
||||
{values.map((value) => (
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Checkbox
|
||||
checked={selectedValues.some((selectedValue) => value === selectedValue)}
|
||||
onChange={(e) => handleChange(e, value)}
|
||||
/>
|
||||
}
|
||||
label={value}
|
||||
key={value}
|
||||
/>
|
||||
))}
|
||||
</FormGroup>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button autoFocus onClick={handleCancel}>
|
||||
{t('global.button.cancel')}
|
||||
</Button>
|
||||
<Button onClick={handleOk}>{t('global.button.ok')}</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export function MultiSelectListPreference(props: MultiSelectListPreferenceProps) {
|
||||
const {
|
||||
MultiSelectListPreferenceTitle: title,
|
||||
summary,
|
||||
MultiSelectListPreferenceCurrentValue: currentValue,
|
||||
MultiSelectListPreferenceDefault: defaultValue,
|
||||
updateValue,
|
||||
entryValues,
|
||||
entries,
|
||||
} = props;
|
||||
const [internalCurrentValue, setInternalCurrentValue] = useState(currentValue ?? defaultValue);
|
||||
const [dialogOpen, setDialogOpen] = useState<boolean>(false);
|
||||
|
||||
useEffect(() => {
|
||||
setInternalCurrentValue(currentValue);
|
||||
}, [currentValue]);
|
||||
|
||||
const findEntriesOf = (values?: string[] | null) =>
|
||||
values?.map((value) => {
|
||||
const idx = entryValues.indexOf(value);
|
||||
return entries[idx];
|
||||
}) ?? [];
|
||||
|
||||
const findEntryValuesOf = (values?: string[] | null) =>
|
||||
values?.map((value) => {
|
||||
const idx = entries.indexOf(value);
|
||||
return entryValues[idx];
|
||||
}) ?? [];
|
||||
|
||||
const getSummary = () => summary;
|
||||
|
||||
const handleDialogClose = (newValue: string[] | null) => {
|
||||
if (newValue !== null) {
|
||||
// console.log(newValue);
|
||||
updateValue('multiSelectState', findEntryValuesOf(newValue));
|
||||
|
||||
// appear smooth
|
||||
setInternalCurrentValue(newValue);
|
||||
}
|
||||
|
||||
setDialogOpen(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<ListItemButton onClick={() => setDialogOpen(true)}>
|
||||
<ListItemText primary={title} secondary={getSummary()} />
|
||||
</ListItemButton>
|
||||
<ListDialog
|
||||
title={title ?? ''}
|
||||
open={dialogOpen}
|
||||
onClose={handleDialogClose}
|
||||
selectedValues={findEntriesOf(internalCurrentValue)}
|
||||
values={entries}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
* 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 { useState, useEffect, useMemo } from 'react';
|
||||
import ListItem from '@mui/material/ListItem';
|
||||
import ListItemText from '@mui/material/ListItemText';
|
||||
import Switch from '@mui/material/Switch';
|
||||
import Checkbox from '@mui/material/Checkbox';
|
||||
import {
|
||||
CheckBoxPreferenceProps,
|
||||
SwitchPreferenceCompatProps,
|
||||
TwoStatePreferenceProps,
|
||||
} from '@/modules/source/Source.types.ts';
|
||||
|
||||
function getTwoStateType(type: TwoStatePreferenceProps['twoStateType']) {
|
||||
if (type === 'Switch') {
|
||||
return Switch;
|
||||
}
|
||||
return Checkbox;
|
||||
}
|
||||
|
||||
const getTwoStateValues = (
|
||||
props: TwoStatePreferenceProps,
|
||||
): {
|
||||
title: string;
|
||||
defaultValue: boolean;
|
||||
currentValue?: boolean | null | undefined;
|
||||
} => {
|
||||
if (props.type === 'CheckBoxPreference') {
|
||||
return {
|
||||
title: props.CheckBoxTitle,
|
||||
defaultValue: props.CheckBoxDefault,
|
||||
currentValue: props.CheckBoxCheckBoxCurrentValue,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
title: props.SwitchPreferenceTitle,
|
||||
defaultValue: props.SwitchPreferenceDefault,
|
||||
currentValue: props.SwitchPreferenceCurrentValue,
|
||||
};
|
||||
};
|
||||
|
||||
function TwoSatePreference(props: TwoStatePreferenceProps) {
|
||||
const { title, defaultValue, currentValue, summary, updateValue, twoStateType } = {
|
||||
...props,
|
||||
...getTwoStateValues(props),
|
||||
};
|
||||
const [internalCurrentValue, setInternalCurrentValue] = useState(currentValue ?? defaultValue);
|
||||
|
||||
useEffect(() => {
|
||||
setInternalCurrentValue(currentValue ?? defaultValue);
|
||||
}, [currentValue]);
|
||||
|
||||
const TwoStateComponent = useMemo(() => getTwoStateType(twoStateType), [twoStateType]);
|
||||
|
||||
return (
|
||||
<ListItem>
|
||||
<ListItemText primary={title} secondary={summary} />
|
||||
<TwoStateComponent
|
||||
{...{
|
||||
edge: 'end',
|
||||
checked: internalCurrentValue,
|
||||
onChange: () => {
|
||||
updateValue(twoStateType === 'Switch' ? 'switchState' : 'checkBoxState', !currentValue);
|
||||
|
||||
// appear smooth
|
||||
setInternalCurrentValue(!currentValue);
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</ListItem>
|
||||
);
|
||||
}
|
||||
|
||||
export function CheckBoxPreference(props: CheckBoxPreferenceProps) {
|
||||
return <TwoSatePreference {...props} twoStateType="Checkbox" />;
|
||||
}
|
||||
|
||||
export function SwitchPreferenceCompat(props: SwitchPreferenceCompatProps) {
|
||||
return <TwoSatePreference {...props} twoStateType="Switch" />;
|
||||
}
|
||||
107
src/modules/source/screens/SourceConfigure.tsx
Normal file
107
src/modules/source/screens/SourceConfigure.tsx
Normal 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 { createElement, useContext, useLayoutEffect } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import List from '@mui/material/List';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { requestManager } from '@/lib/requests/requests/RequestManager.ts';
|
||||
import { cloneObject } from '@/util/cloneObject.tsx';
|
||||
import {
|
||||
SwitchPreferenceCompat,
|
||||
CheckBoxPreference,
|
||||
} from '@/modules/source/components/sourceConfiguration/TwoStatePreference.tsx';
|
||||
import { ListPreference } from '@/modules/source/components/sourceConfiguration/ListPreference.tsx';
|
||||
import { EditTextPreference } from '@/modules/source/components/sourceConfiguration/EditTextPreference.tsx';
|
||||
import { MultiSelectListPreference } from '@/modules/source/components/sourceConfiguration/MultiSelectListPreference.tsx';
|
||||
import { NavBarContext } from '@/components/context/NavbarContext.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 { GetCategoriesSettingsQueryVariables, GetSourceSettingsQuery } from '@/lib/graphql/generated/graphql.ts';
|
||||
import { GET_SOURCE_SETTINGS } from '@/lib/graphql/queries/SourceQuery.ts';
|
||||
import { makeToast } from '@/lib/ui/Toast.ts';
|
||||
import { PreferenceProps } from '@/modules/source/Source.types.ts';
|
||||
|
||||
function getPrefComponent(type: string) {
|
||||
switch (type) {
|
||||
case 'CheckBoxPreference':
|
||||
return CheckBoxPreference;
|
||||
case 'SwitchPreference':
|
||||
return SwitchPreferenceCompat;
|
||||
case 'ListPreference':
|
||||
return ListPreference;
|
||||
case 'EditTextPreference':
|
||||
return EditTextPreference;
|
||||
case 'MultiSelectListPreference':
|
||||
return MultiSelectListPreference;
|
||||
default:
|
||||
throw new Error(`Unexpected preference type "${type}"`);
|
||||
}
|
||||
}
|
||||
|
||||
export function SourceConfigure() {
|
||||
const { t } = useTranslation();
|
||||
const { setTitle, setAction } = useContext(NavBarContext);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
setTitle(t('source.configuration.title'));
|
||||
setAction(null);
|
||||
|
||||
return () => {
|
||||
setTitle('');
|
||||
setAction(null);
|
||||
};
|
||||
}, [t]);
|
||||
|
||||
const { sourceId } = useParams<{ sourceId: string }>();
|
||||
const { data, loading, error, refetch } = requestManager.useGetSource<
|
||||
GetSourceSettingsQuery,
|
||||
GetCategoriesSettingsQueryVariables
|
||||
>(GET_SOURCE_SETTINGS, sourceId, {
|
||||
notifyOnNetworkStatusChange: true,
|
||||
});
|
||||
const sourcePreferences = data?.source.preferences ?? [];
|
||||
|
||||
const updateValue =
|
||||
(position: number): PreferenceProps['updateValue'] =>
|
||||
(type, value) => {
|
||||
requestManager
|
||||
.setSourcePreferences(sourceId, { position, [type]: value })
|
||||
.response.catch(() => makeToast(t('global.error.label.failed_to_save_changes'), 'error'));
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return <LoadingPlaceholder />;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<EmptyViewAbsoluteCentered
|
||||
message={t('global.error.label.failed_to_load_data')}
|
||||
messageExtra={error.message}
|
||||
retry={() => refetch().catch(defaultPromiseErrorHandler('SourceConfigure::refetch'))}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<List sx={{ padding: 0 }}>
|
||||
{sourcePreferences.map((it, index) => {
|
||||
const props = cloneObject(it);
|
||||
|
||||
// TypeScript is dumb in detecting extra props
|
||||
// @ts-ignore
|
||||
return createElement(getPrefComponent(it.type), {
|
||||
...props,
|
||||
updateValue: updateValue(index),
|
||||
});
|
||||
})}
|
||||
</List>
|
||||
);
|
||||
}
|
||||
486
src/modules/source/screens/SourceMangas.tsx
Normal file
486
src/modules/source/screens/SourceMangas.tsx
Normal file
@@ -0,0 +1,486 @@
|
||||
/*
|
||||
* 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, useContext, useEffect, useLayoutEffect, useMemo, useState } from 'react';
|
||||
import { useParams, useNavigate, useLocation } 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 Tooltip from '@mui/material/Tooltip';
|
||||
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 {
|
||||
requestManager,
|
||||
AbortableApolloUseMutationPaginatedResponse,
|
||||
SPECIAL_ED_SOURCES,
|
||||
} from '@/lib/requests/requests/RequestManager.ts';
|
||||
import { GridLayout } from '@/modules/library/contexts/LibraryOptionsContext.tsx';
|
||||
import { SourceGridLayout } from '@/modules/source/components/SourceGridLayout.tsx';
|
||||
import { AppbarSearch } from '@/modules/core/components/AppbarSearch.tsx';
|
||||
import { SourceOptions } from '@/modules/source/components/SourceOptions.tsx';
|
||||
import { BaseMangaGrid } from '@/modules/manga/components/BaseMangaGrid.tsx';
|
||||
import {
|
||||
GetSourceBrowseQuery,
|
||||
GetSourceBrowseQueryVariables,
|
||||
GetSourceMangasFetchMutation,
|
||||
GetSourceMangasFetchMutationVariables,
|
||||
} from '@/lib/graphql/generated/graphql.ts';
|
||||
import { NavBarContext } from '@/components/context/NavbarContext.tsx';
|
||||
import { useMetadataServerSettings } from '@/lib/metadata/metadataServerSettings.ts';
|
||||
import { useLocalStorage, useSessionStorage } from '@/modules/core/hooks/useStorage.tsx';
|
||||
import { AppStorage } from '@/lib/AppStorage.ts';
|
||||
import { getGridSnapshotKey } from '@/modules/manga/components/MangaGrid.tsx';
|
||||
import { createUpdateSourceMetadata, getSourceMetadata } from '@/modules/source/services/SourceMetadata.ts';
|
||||
import { makeToast } from '@/lib/ui/Toast.ts';
|
||||
import { GET_SOURCE_BROWSE } from '@/lib/graphql/queries/SourceQuery.ts';
|
||||
import { MangaIdInfo } from '@/modules/manga/services/Mangas.ts';
|
||||
import { TranslationKey } from '@/Base.types.ts';
|
||||
import { IPos } from '@/modules/source/Source.types.ts';
|
||||
|
||||
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 { setTitle, setAction, appBarHeight } = useContext(NavBarContext);
|
||||
|
||||
const { sourceId } = useParams<{ sourceId: string }>();
|
||||
|
||||
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 [isFirstRender, setIsFirstRender] = useState(true);
|
||||
useEffect(() => {
|
||||
setIsFirstRender(false);
|
||||
}, []);
|
||||
|
||||
const {
|
||||
settings: { hideLibraryEntries },
|
||||
} = useMetadataServerSettings();
|
||||
|
||||
const [sourceGridLayout] = useLocalStorage('source-grid-layout', GridLayout.Compact);
|
||||
const [query] = useQueryParam('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!,
|
||||
);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
setCurrentFiltersToApply(undefined);
|
||||
setCurrentContentType(undefined);
|
||||
},
|
||||
[sourceId],
|
||||
);
|
||||
|
||||
const scrollToTop = useCallback(() => {
|
||||
AppStorage.session.setItem(getGridSnapshotKey(location), undefined, false);
|
||||
window.scrollTo(0, 0);
|
||||
}, [locationKey]);
|
||||
|
||||
const setFiltersToApply = (filters: IPos[]) => {
|
||||
setCurrentFiltersToApply(filters);
|
||||
setLocationFiltersToApply(filters);
|
||||
scrollToTop();
|
||||
};
|
||||
|
||||
const setContentType = (newContentType: SourceContentType) => {
|
||||
setCurrentContentType(newContentType);
|
||||
setLocationContentType(newContentType);
|
||||
};
|
||||
|
||||
const [loadPage, { data, isLoading: loading, size: lastPageNum, abortRequest, filteredOutAllItemsOfFetchedPage }] =
|
||||
useSourceManga(sourceId, contentType, query, filtersToApply, 1, hideLibraryEntries);
|
||||
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 = {} } = useMemo(() => getSourceMetadata(source), [source, source?.meta]);
|
||||
const updateSourceMetadata = createUpdateSourceMetadata<'savedSearches'>(source ?? { id: sourceId }, () =>
|
||||
makeToast(t('global.error.label.failed_to_save_changes'), 'error'),
|
||||
);
|
||||
|
||||
const selectSavedSearch = useCallback(
|
||||
(savedSearch: string) => {
|
||||
const { query: savedSearchQuery, filters: savedSearchFilters } = savedSearches[savedSearch];
|
||||
|
||||
if (savedSearchFilters) {
|
||||
setDialogFiltersToApply(savedSearchFilters);
|
||||
setFiltersToApply(savedSearchFilters);
|
||||
}
|
||||
|
||||
navigate(
|
||||
{
|
||||
pathname: '',
|
||||
search: savedSearchQuery ? `query=${savedSearchQuery}` : undefined,
|
||||
},
|
||||
{ state: { ...locationState, contentType: SourceContentType.SEARCH } },
|
||||
);
|
||||
},
|
||||
[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: filtersToApply },
|
||||
};
|
||||
updateSourceMetadata('savedSearches', updatedSavedSearches);
|
||||
},
|
||||
[savedSearches, query, filtersToApply],
|
||||
);
|
||||
|
||||
const message = !isLoading ? t(SOURCE_CONTENT_TYPE_TO_ERROR_MSG_KEY[contentType]) : undefined;
|
||||
const isLocalSource = sourceId === '0';
|
||||
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(() => {
|
||||
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]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (contentType !== SourceContentType.SEARCH || isFirstRender) {
|
||||
return;
|
||||
}
|
||||
// INFO:
|
||||
// with strict mode + dev mode the first request will be aborted. due to using SWR there won't be an
|
||||
// immediate second request since it's the same key. instead the "second" request will be the error handling of SWR
|
||||
abortRequest(new Error(`SourceMangas(${sourceId}): search string changed`));
|
||||
scrollToTop();
|
||||
},
|
||||
[query],
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
setTitle(source?.displayName ?? t('source.title_one'));
|
||||
setAction(
|
||||
<>
|
||||
<AppbarSearch />
|
||||
<SourceGridLayout />
|
||||
{source?.isConfigurable && (
|
||||
<Tooltip title={t('settings.title')}>
|
||||
<IconButton
|
||||
onClick={() => navigate(`/sources/${sourceId}/configure/`)}
|
||||
aria-label="display more actions"
|
||||
edge="end"
|
||||
color="inherit"
|
||||
size="large"
|
||||
>
|
||||
<SettingsIcon />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
</>,
|
||||
);
|
||||
|
||||
return () => {
|
||||
setTitle('');
|
||||
setAction(null);
|
||||
};
|
||||
}, [t, source]);
|
||||
|
||||
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>
|
||||
<BaseMangaGrid
|
||||
key={contentType}
|
||||
gridWrapperProps={{ sx: { px: 1, pb: 1 } }}
|
||||
mangas={mangas}
|
||||
hasNextPage={hasNextPage}
|
||||
loadMore={loadMore}
|
||||
message={message}
|
||||
messageExtra={messageExtra}
|
||||
isLoading={isLoading}
|
||||
gridLayout={sourceGridLayout}
|
||||
mode="source"
|
||||
inLibraryIndicator
|
||||
/>
|
||||
{contentType === SourceContentType.SEARCH && (
|
||||
<SourceOptions
|
||||
savedSearches={savedSearches}
|
||||
selectSavedSearch={selectSavedSearch}
|
||||
updateSavedSearches={handleSavedSearchesUpdate}
|
||||
sourceFilter={filters}
|
||||
updateFilterValue={setDialogFiltersToApply}
|
||||
setTriggerUpdate={() => {
|
||||
setFiltersToApply(dialogFiltersToApply);
|
||||
}}
|
||||
resetFilterValue={resetFilters}
|
||||
update={dialogFiltersToApply}
|
||||
/>
|
||||
)}
|
||||
</StyledGridWrapper>
|
||||
);
|
||||
}
|
||||
187
src/modules/source/screens/Sources.tsx
Normal file
187
src/modules/source/screens/Sources.tsx
Normal file
@@ -0,0 +1,187 @@
|
||||
/*
|
||||
* 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 { Fragment, useContext, useEffect, useLayoutEffect, useMemo } from 'react';
|
||||
import IconButton from '@mui/material/IconButton';
|
||||
import Tooltip from '@mui/material/Tooltip';
|
||||
import Typography from '@mui/material/Typography';
|
||||
import TravelExploreIcon from '@mui/icons-material/TravelExplore';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { requestManager } from '@/lib/requests/requests/RequestManager.ts';
|
||||
import { useLocalStorage } from '@/modules/core/hooks/useStorage.tsx';
|
||||
import { sourceDefualtLangs, sourceForcedDefaultLangs, langSortCmp, DefaultLanguage } from '@/lib/Languages.tsx';
|
||||
import { translateExtensionLanguage } from '@/screens/util/Extensions.ts';
|
||||
import { LoadingPlaceholder } from '@/modules/core/components/placeholder/LoadingPlaceholder.tsx';
|
||||
import { SourceCard } from '@/modules/source/components/SourceCard.tsx';
|
||||
import { LangSelect } from '@/modules/core/components/inputs/LangSelect.tsx';
|
||||
import { NavBarContext } from '@/components/context/NavbarContext.tsx';
|
||||
import { EmptyViewAbsoluteCentered } from '@/modules/core/components/placeholder/EmptyViewAbsoluteCentered.tsx';
|
||||
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
|
||||
import { SourceType } from '@/lib/graphql/generated/graphql.ts';
|
||||
|
||||
function sourceToLangList(sources: Pick<SourceType, 'id' | 'lang'>[]) {
|
||||
const result = new Set<string>();
|
||||
|
||||
sources.forEach((source) => {
|
||||
const isLocalSource = Number(source.id) === 0;
|
||||
const lang = isLocalSource ? DefaultLanguage.OTHER : source.lang;
|
||||
|
||||
result.add(lang);
|
||||
});
|
||||
|
||||
return [...result].sort(langSortCmp);
|
||||
}
|
||||
|
||||
function groupByLang<Source extends Pick<SourceType, 'id' | 'name' | 'lang'>>(
|
||||
sources: Source[],
|
||||
): Record<string, Source[]> {
|
||||
const result: Record<string, Source[]> = {};
|
||||
|
||||
sources.forEach((source) => {
|
||||
const isLocalSource = Number(source.id) === 0;
|
||||
const lang = isLocalSource ? DefaultLanguage.OTHER : source.lang;
|
||||
|
||||
result[lang] ??= [];
|
||||
result[lang].push(source);
|
||||
});
|
||||
|
||||
Object.values(result).forEach((langSources) => langSources.sort((a, b) => a.name.localeCompare(b.name)));
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function Sources() {
|
||||
const { t } = useTranslation();
|
||||
const { setAction } = useContext(NavBarContext);
|
||||
|
||||
const [shownLangs, setShownLangs] = useLocalStorage<string[]>('shownSourceLangs', sourceDefualtLangs());
|
||||
const [showNsfw] = useLocalStorage<boolean>('showNsfw', true);
|
||||
|
||||
const {
|
||||
data,
|
||||
loading: isLoading,
|
||||
error,
|
||||
refetch,
|
||||
} = requestManager.useGetSourceList({ notifyOnNetworkStatusChange: true });
|
||||
const sources = data?.sources.nodes;
|
||||
|
||||
const areSourcesFromDifferentRepos = useMemo(() => {
|
||||
if (!sources || !!sources?.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const { repo } = sources[0].extension;
|
||||
return sources.some((source) => source.extension.repo !== repo);
|
||||
}, [sources]);
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
// make sure all of forcedDefaultLangs() exists in shownLangs
|
||||
sourceForcedDefaultLangs().forEach((forcedLang) => {
|
||||
let hasLang = false;
|
||||
shownLangs.forEach((lang) => {
|
||||
if (lang === forcedLang) hasLang = true;
|
||||
});
|
||||
if (!hasLang) {
|
||||
setShownLangs((shownLangsCopy) => {
|
||||
shownLangsCopy.push(forcedLang);
|
||||
return shownLangsCopy;
|
||||
});
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
setAction(
|
||||
<>
|
||||
<Tooltip title={t('search.title.global_search')}>
|
||||
<IconButton onClick={() => navigate('/sources/all/search/')} size="large" color="inherit">
|
||||
<TravelExploreIcon />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<LangSelect
|
||||
shownLangs={shownLangs}
|
||||
setShownLangs={setShownLangs}
|
||||
allLangs={sourceToLangList(sources ?? [])}
|
||||
forcedLangs={sourceForcedDefaultLangs()}
|
||||
/>
|
||||
</>,
|
||||
);
|
||||
|
||||
return () => {
|
||||
setAction(null);
|
||||
};
|
||||
}, [t, shownLangs, sources]);
|
||||
|
||||
if (isLoading) return <LoadingPlaceholder />;
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<EmptyViewAbsoluteCentered
|
||||
message={t('global.error.label.failed_to_load_data')}
|
||||
messageExtra={error.message}
|
||||
retry={() => refetch().catch(defaultPromiseErrorHandler('Sources::refetch'))}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (sources?.length === 0) {
|
||||
return <EmptyViewAbsoluteCentered message={t('source.error.label.no_sources_found')} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{Object.entries(groupByLang(sources ?? []))
|
||||
.sort((a, b) => langSortCmp(a[0], b[0]))
|
||||
.map(
|
||||
([lang, list]) =>
|
||||
(lang === DefaultLanguage.OTHER || shownLangs.includes(lang)) && (
|
||||
<Fragment key={lang}>
|
||||
<Typography
|
||||
key={lang}
|
||||
variant="h5"
|
||||
component="h2"
|
||||
sx={{
|
||||
paddingLeft: 3,
|
||||
paddingTop: 1,
|
||||
paddingBottom: 2,
|
||||
fontWeight: 'bold',
|
||||
}}
|
||||
>
|
||||
{translateExtensionLanguage(lang)}
|
||||
</Typography>
|
||||
{list
|
||||
.filter((source) => {
|
||||
const isLangOther = lang === DefaultLanguage.OTHER;
|
||||
if (isLangOther) {
|
||||
const isLocalSource = Number(source.id) === 0;
|
||||
const isLangShown = shownLangs.includes(lang);
|
||||
|
||||
const isLangOtherSourceShown = isLangShown || isLocalSource;
|
||||
if (!isLangOtherSourceShown) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return showNsfw || !source.isNsfw;
|
||||
})
|
||||
.map((source) => (
|
||||
<SourceCard
|
||||
key={source.id}
|
||||
source={source}
|
||||
showSourceRepo={areSourcesFromDifferentRepos}
|
||||
/>
|
||||
))}
|
||||
</Fragment>
|
||||
),
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
53
src/modules/source/services/SourceMetadata.ts
Normal file
53
src/modules/source/services/SourceMetadata.ts
Normal 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 { AllowedMetadataValueTypes, AppMetadataKeys, GqlMetaHolder, Metadata } from '@/typings.ts';
|
||||
import { jsonSaveParse } from '@/lib/HelperFunctions.ts';
|
||||
import { convertFromGqlMeta, getMetadataFrom, requestUpdateSourceMetadata } from '@/lib/metadata/metadata.ts';
|
||||
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
|
||||
import { SourceType } from '@/lib/graphql/generated/graphql.ts';
|
||||
import { ISourceMetadata, SourceMetadataKeys } from '@/modules/source/Source.types.ts';
|
||||
|
||||
const convertAppMetadataToGqlMetadata = (
|
||||
metadata: Partial<ISourceMetadata>,
|
||||
): Metadata<string, AllowedMetadataValueTypes> => ({
|
||||
...metadata,
|
||||
savedSearches: metadata.savedSearches ? JSON.stringify(metadata.savedSearches) : undefined,
|
||||
});
|
||||
|
||||
export const convertGqlMetadataToAppMetadata = (
|
||||
metadata: Partial<Metadata<AppMetadataKeys, AllowedMetadataValueTypes>>,
|
||||
): ISourceMetadata => ({
|
||||
...(metadata as unknown as ISourceMetadata),
|
||||
savedSearches: jsonSaveParse<ISourceMetadata['savedSearches']>(metadata.savedSearches as string) ?? undefined,
|
||||
});
|
||||
|
||||
export const getSourceMetadata = ({ meta }: GqlMetaHolder = {}, applyMetadataMigration?: boolean): ISourceMetadata =>
|
||||
convertGqlMetadataToAppMetadata(
|
||||
getMetadataFrom({ meta: convertFromGqlMeta(meta) }, { savedSearches: undefined }, applyMetadataMigration),
|
||||
);
|
||||
|
||||
export const updateSourceMetadata = async <
|
||||
MetadataKeys extends SourceMetadataKeys = SourceMetadataKeys,
|
||||
MetadataKey extends MetadataKeys = MetadataKeys,
|
||||
>(
|
||||
source: Pick<SourceType, 'id'> & GqlMetaHolder,
|
||||
metadataKey: MetadataKey,
|
||||
value: ISourceMetadata[MetadataKey],
|
||||
): Promise<void[]> =>
|
||||
requestUpdateSourceMetadata(source, [
|
||||
[metadataKey, convertAppMetadataToGqlMetadata({ [metadataKey]: value })[metadataKey]],
|
||||
]);
|
||||
|
||||
export const createUpdateSourceMetadata =
|
||||
<Settings extends SourceMetadataKeys>(
|
||||
source: Pick<SourceType, 'id'> & GqlMetaHolder,
|
||||
handleError: (error: any) => void = defaultPromiseErrorHandler('createUpdateSourceMetadata'),
|
||||
): ((...args: OmitFirst<Parameters<typeof updateSourceMetadata<Settings>>>) => Promise<void | void[]>) =>
|
||||
(metadataKey, value) =>
|
||||
updateSourceMetadata(source, metadataKey, value).catch(handleError);
|
||||
Reference in New Issue
Block a user