Rename folder "modules" to "features"

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

View File

@@ -0,0 +1,74 @@
/*
* 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 {
ExtensionType,
GetSourceBrowseQuery,
GetSourceSettingsQuery,
SourceMetaFieldsFragment,
SourcePreferenceChangeInput,
SourceType,
} 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>;
isPinned: boolean;
isEnabled: boolean;
}
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'>;
export type SourceIdInfo = Pick<SourceType, 'id'>;
export type SourceLanguageInfo = Pick<SourceType, 'lang'>;
export type SourceNameInfo = Pick<SourceType, 'name'>;
export type SourceDisplayNameInfo = Pick<SourceType, 'displayName'>;
export type SourceNsfwInfo = Pick<SourceType, 'isNsfw'>;
export type SourceRepoInfo = { extension: Pick<ExtensionType, 'repo'> };
export type SourceMetaInfo = { meta: SourceMetaFieldsFragment[] };
export type SourceConfigurableInfo = Pick<SourceType, 'isConfigurable'>;
export type SourceIconInfo = Pick<SourceType, 'iconUrl'>;

View File

@@ -0,0 +1,119 @@
/*
* 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 Button from '@mui/material/Button';
import Card from '@mui/material/Card';
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 PushPinIcon from '@mui/icons-material/PushPin';
import PushPinOutlinedIcon from '@mui/icons-material/PushPinOutlined';
import IconButton from '@mui/material/IconButton';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { SourceContentType } from '@/features/source/screens/SourceMangas.tsx';
import { GetSourcesListQuery } from '@/lib/graphql/generated/graphql.ts';
import { AppRoutes } from '@/features/core/AppRoute.constants.ts';
import { MUIUtil } from '@/lib/mui/MUI.util.ts';
import { Sources } from '@/features/source/services/Sources.ts';
import { ListCardAvatar } from '@/features/core/components/lists/cards/ListCardAvatar.tsx';
import { ListCardContent } from '@/features/core/components/lists/cards/ListCardContent.tsx';
import { CustomTooltip } from '@/features/core/components/CustomTooltip.tsx';
import { createUpdateSourceMetadata, useGetSourceMetadata } from '@/features/source/services/SourceMetadata.ts';
import { makeToast } from '@/features/core/utils/Toast.ts';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
import { languageCodeToName } from '@/features/core/utils/Languages.ts';
interface IProps {
source: GetSourcesListQuery['sources']['nodes'][number];
showSourceRepo: boolean;
showLanguage: boolean;
}
export const SourceCard: React.FC<IProps> = (props: IProps) => {
const { t } = useTranslation();
const { source, showSourceRepo, showLanguage } = props;
const {
id,
name,
lang,
iconUrl,
supportsLatest,
isNsfw,
extension: { repo },
} = source;
const { isPinned } = useGetSourceMetadata(source);
const sourceName = Sources.isLocalSource(source) ? t('source.local_source.title') : name;
const updateSetting = createUpdateSourceMetadata(source, (e) =>
makeToast(t('global.error.label.failed_to_save_changes'), 'error', getErrorMessage(e)),
);
return (
<Card>
<CardActionArea
component={Link}
to={AppRoutes.sources.childRoutes.browse.path(id)}
state={{ contentType: SourceContentType.POPULAR, clearCache: true }}
>
<ListCardContent>
<ListCardAvatar iconUrl={requestManager.getValidImgUrlFor(iconUrl)} alt={sourceName} />
<Stack
sx={{
justifyContent: 'center',
flexGrow: 1,
flexShrink: 1,
wordBreak: 'break-word',
}}
>
<Typography variant="h6" component="h3">
{sourceName}
</Typography>
<Typography variant="caption">
{showLanguage && languageCodeToName(lang)}
{isNsfw && (
<Typography variant="caption" color="error">
{' 18+'}
</Typography>
)}
</Typography>
{showSourceRepo && <Typography variant="caption">{repo}</Typography>}
</Stack>
{supportsLatest && (
<Button
{...MUIUtil.preventRippleProp()}
variant="outlined"
component={Link}
to={AppRoutes.sources.childRoutes.browse.path(id)}
state={{ contentType: SourceContentType.LATEST, clearCache: true }}
>
{t('global.button.latest')}
</Button>
)}
<CustomTooltip title={t(isPinned ? 'source.pin.remove' : 'source.pin.add')}>
<IconButton
{...MUIUtil.preventRippleProp()}
onClick={(e) => {
e.preventDefault();
updateSetting('isPinned', !isPinned);
}}
color={isPinned ? 'primary' : 'inherit'}
>
{isPinned ? <PushPinIcon /> : <PushPinOutlinedIcon />}
</IconButton>
</CustomTooltip>
</ListCardContent>
</CardActionArea>
</Card>
);
};

View 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 { GridLayouts } from '@/features/core/components/GridLayouts.tsx';
import { useLocalStorage } from '@/features/core/hooks/useStorage.tsx';
import { GridLayout } from '@/features/core/Core.types.ts';
export function SourceGridLayout() {
const [sourceGridLayout, setSourceGridLayout] = useLocalStorage('source-grid-layout', GridLayout.Compact);
return <GridLayouts gridLayout={sourceGridLayout} onChange={setSourceGridLayout} />;
}

View File

@@ -0,0 +1,186 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { useMemo, useState } from 'react';
import Button from '@mui/material/Button';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';
import Dialog from '@mui/material/Dialog';
import Switch from '@mui/material/Switch';
import IconButton from '@mui/material/IconButton';
import FilterListIcon from '@mui/icons-material/FilterList';
import ListItemText from '@mui/material/ListItemText';
import ListItem from '@mui/material/ListItem';
import { useTranslation } from 'react-i18next';
import { Virtuoso } from 'react-virtuoso';
import Box from '@mui/material/Box';
import ListItemAvatar from '@mui/material/ListItemAvatar';
import { CustomTooltip } from '@/features/core/components/CustomTooltip.tsx';
import { translateExtensionLanguage } from '@/features/extension/Extensions.utils.ts';
import { languageSortComparator, toUniqueLanguageCodes } from '@/features/core/utils/Languages.ts';
import {
SourceDisplayNameInfo,
SourceIconInfo,
SourceIdInfo,
SourceLanguageInfo,
SourceMetaInfo,
SourceNameInfo,
} from '@/features/source/Source.types.ts';
import { Sources } from '@/features/source/services/Sources';
import { getSourceMetadata, updateSourceMetadata } from '@/features/source/services/SourceMetadata.ts';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { ListCardAvatar } from '@/features/core/components/lists/cards/ListCardAvatar.tsx';
import { makeToast } from '@/features/core/utils/Toast.ts';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
export const SourceLanguageSelect = ({
selectedLanguages,
setSelectedLanguages,
languages,
sources,
}: {
selectedLanguages: string[];
setSelectedLanguages: (languages: string[]) => void;
languages: string[];
sources: (SourceIdInfo &
SourceLanguageInfo &
SourceNameInfo &
SourceDisplayNameInfo &
SourceIconInfo &
SourceMetaInfo)[];
}) => {
const { t } = useTranslation();
const [tmpSourceIdToEnabledState, setTmpSourceIdToEnabledState] = useState<Record<SourceIdInfo['id'], boolean>>({});
const [tmpSelectedLanguages, setTmpSelectedLanguages] = useState(toUniqueLanguageCodes(selectedLanguages));
const [open, setOpen] = useState<boolean>(false);
const sourcesByLanguage = useMemo(() => Sources.groupByLanguage(sources), [sources]);
const languagesSortedBySelectState = useMemo(
() =>
toUniqueLanguageCodes([
...tmpSelectedLanguages.toSorted(languageSortComparator),
...languages.toSorted(languageSortComparator),
]),
[languages, tmpSelectedLanguages],
);
const handleCancel = () => {
setOpen(false);
setTmpSourceIdToEnabledState({});
setTmpSelectedLanguages(toUniqueLanguageCodes(selectedLanguages));
};
const handleOk = () => {
setOpen(false);
Promise.all(
Object.entries(tmpSourceIdToEnabledState).map(([sourceId, enabled]) =>
updateSourceMetadata(sources.find((source) => source.id === sourceId)!, 'isEnabled', enabled),
),
).catch((e) => makeToast(t('global.error.label.failed_to_save_changes'), 'error', getErrorMessage(e)));
setTmpSourceIdToEnabledState({});
setSelectedLanguages(toUniqueLanguageCodes(tmpSelectedLanguages));
};
const handleChange = (language: string, selected: boolean) => {
if (selected) {
setTmpSelectedLanguages([...tmpSelectedLanguages, language]);
} else {
setTmpSelectedLanguages(tmpSelectedLanguages.toSpliced(tmpSelectedLanguages.indexOf(language), 1));
}
};
return (
<>
<CustomTooltip title={t('settings.title')}>
<IconButton onClick={() => setOpen(true)} aria-label="display more actions" edge="end" color="inherit">
<FilterListIcon />
</IconButton>
</CustomTooltip>
<Dialog fullWidth maxWidth="xs" open={open} onClose={handleCancel}>
<DialogTitle>{t('global.language.title.enabled_languages')}</DialogTitle>
<DialogContent dividers sx={{ padding: 0 }}>
<Virtuoso
style={{
height: languagesSortedBySelectState.length * 54,
minHeight: '25vh',
maxHeight: '50vh',
}}
data={languagesSortedBySelectState}
increaseViewportBy={400}
computeItemKey={(index) => languagesSortedBySelectState[index]}
itemContent={(_index, language) => {
const sourcesOfLanguage = sourcesByLanguage[language] ?? [];
const isEnabled = tmpSelectedLanguages.includes(language);
return (
<>
<ListItem>
<ListItemText primary={translateExtensionLanguage(language)} />
<Switch
checked={isEnabled}
onChange={(e) => handleChange(language, e.target.checked)}
/>
</ListItem>
{isEnabled && sourcesOfLanguage.length && (
<Box sx={{ ml: 1 }}>
{sourcesOfLanguage.map((source) => (
<ListItem key={source.id}>
<ListItemAvatar sx={{ minWidth: 32, mr: 1 }}>
<ListCardAvatar
iconUrl={requestManager.getValidImgUrlFor(source.iconUrl)}
alt={source.name}
slots={{
avatarProps: {
sx: {
width: 32,
height: 32,
},
},
}}
/>
</ListItemAvatar>
<ListItemText primary={source.name} />
<Switch
checked={
tmpSourceIdToEnabledState[source.id] ??
getSourceMetadata(source).isEnabled
}
onChange={(e) =>
setTmpSourceIdToEnabledState({
...tmpSourceIdToEnabledState,
[source.id]: e.target.checked,
})
}
/>
</ListItem>
))}
</Box>
)}
</>
);
}}
/>
</DialogContent>
<DialogActions>
<Button autoFocus onClick={handleCancel} color="primary">
{t('global.button.cancel')}
</Button>
<Button onClick={handleOk} color="primary">
{t('global.button.ok')}
</Button>
</DialogActions>
</Dialog>
</>
);
};

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 '@/features/core/components/CustomTooltip.tsx';
import { OptionsPanel } from '@/features/core/components/modals/OptionsPanel.tsx';
import { CheckBoxFilter } from '@/features/source/components/filters/CheckBoxFilter.tsx';
import { HeaderFilter } from '@/features/source/components/filters/HeaderFilter.tsx';
import { SelectFilter } from '@/features/source/components/filters/SelectFilter.tsx';
import { SortFilter } from '@/features/source/components/filters/SortFilter.tsx';
import { TextFilter } from '@/features/source/components/filters/TextFilter.tsx';
import { TriStateFilter } from '@/features/source/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/components/filters/GroupFilter.tsx';
import { SeparatorFilter } from '@/features/source/components/filters/SeparatorFilter.tsx';
import { StyledFab } from '@/features/core/components/buttons/StyledFab.tsx';
import { awaitConfirmation } from '@/features/core/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 '@/features/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;
};

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/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 '@/features/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;
};

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 '@/features/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;
};

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 '@/features/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;
};

View File

@@ -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 '@/features/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>
</>
);
}

View File

@@ -0,0 +1,152 @@
/*
* 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 '@/features/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}
onClose={handleCancel}
>
<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}
/>
</>
);
}

View File

@@ -0,0 +1,162 @@
/*
* 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 '@/features/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}
onClose={handleCancel}
>
<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}
/>
</>
);
}

View File

@@ -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 '@/features/source/Source.types.ts';
function getTwoStateType(type: TwoStatePreferenceProps['twoStateType']) {
if (type === 'Switch') {
return Switch;
}
return Checkbox;
}
const getTwoStateValues = (
props: TwoStatePreferenceProps,
): {
title: string | null | undefined;
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" />;
}

View File

@@ -0,0 +1,101 @@
/*
* 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 } from 'react';
import { useParams } from 'react-router-dom';
import List from '@mui/material/List';
import { useTranslation } from 'react-i18next';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { cloneObject } from '@/util/cloneObject.tsx';
import {
SwitchPreferenceCompat,
CheckBoxPreference,
} from '@/features/source/components/sourceConfiguration/TwoStatePreference.tsx';
import { ListPreference } from '@/features/source/components/sourceConfiguration/ListPreference.tsx';
import { EditTextPreference } from '@/features/source/components/sourceConfiguration/EditTextPreference.tsx';
import { MultiSelectListPreference } from '@/features/source/components/sourceConfiguration/MultiSelectListPreference.tsx';
import { LoadingPlaceholder } from '@/features/core/components/feedback/LoadingPlaceholder.tsx';
import { EmptyViewAbsoluteCentered } from '@/features/core/components/feedback/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 '@/features/core/utils/Toast.ts';
import { PreferenceProps } from '@/features/source/Source.types.ts';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
import { useAppTitle } from '@/features/navigation-bar/hooks/useAppTitle.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();
useAppTitle(t('source.configuration.title'));
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((e) =>
makeToast(t('global.error.label.failed_to_save_changes'), 'error', getErrorMessage(e)),
);
};
if (loading) {
return <LoadingPlaceholder />;
}
if (error) {
return (
<EmptyViewAbsoluteCentered
message={t('global.error.label.failed_to_load_data')}
messageExtra={getErrorMessage(error)}
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>
);
}

View File

@@ -0,0 +1,508 @@
/*
* 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 '@/features/core/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 '@/features/core/components/AppbarSearch.tsx';
import { SourceOptions } from '@/features/source/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 '@/features/core/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 '@/features/core/utils/Toast.ts';
import { GET_SOURCE_BROWSE } from '@/lib/graphql/queries/SourceQuery.ts';
import { TranslationKey } from '@/Base.types.ts';
import { IPos, SourceIdInfo } from '@/features/source/Source.types.ts';
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
import { EmptyView } from '@/features/core/components/feedback/EmptyView.tsx';
import { EmptyViewAbsoluteCentered } from '@/features/core/components/feedback/EmptyViewAbsoluteCentered.tsx';
import { MangaIdInfo } from '@/features/manga/Manga.types.ts';
import { GridLayout, SearchParam } from '@/features/core/Core.types.ts';
import { AppRoutes } from '@/features/core/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/contexts/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>
);
}

View File

@@ -0,0 +1,165 @@
/*
* 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, useMemo } from 'react';
import IconButton from '@mui/material/IconButton';
import TravelExploreIcon from '@mui/icons-material/TravelExplore';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import Typography from '@mui/material/Typography';
import { CustomTooltip } from '@/features/core/components/CustomTooltip.tsx';
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { DefaultLanguage } from '@/features/core/utils/Languages.ts';
import { LoadingPlaceholder } from '@/features/core/components/feedback/LoadingPlaceholder.tsx';
import { SourceCard } from '@/features/source/components/SourceCard.tsx';
import { EmptyViewAbsoluteCentered } from '@/features/core/components/feedback/EmptyViewAbsoluteCentered.tsx';
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
import { isPinnedOrLastUsedSource, translateExtensionLanguage } from '@/features/extension/Extensions.utils.ts';
import { AppRoutes } from '@/features/core/AppRoute.constants.ts';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
import { Sources as SourceService } from '@/features/source/services/Sources.ts';
import { useMetadataServerSettings } from '@/features/settings/services/ServerSettingsMetadata.ts';
import { useAppAction } from '@/features/navigation-bar/hooks/useAppAction.ts';
import { StyledGroupedVirtuoso } from '@/features/core/components/virtuoso/StyledGroupedVirtuoso.tsx';
import { VirtuosoUtil } from '@/lib/virtuoso/Virtuoso.util.tsx';
import { StyledGroupHeader } from '@/features/core/components/virtuoso/StyledGroupHeader.tsx';
import { StyledGroupItemWrapper } from '@/features/core/components/virtuoso/StyledGroupItemWrapper.tsx';
import { SourceLanguageSelect } from '@/features/source/components/SourceLanguageSelect.tsx';
export function Sources({ tabsMenuHeight }: { tabsMenuHeight: number }) {
const { t } = useTranslation();
const { languages: shownLangs, setLanguages: setShownLangs } = SourceService.useLanguages();
const {
settings: { showNsfw, lastUsedSourceId },
} = useMetadataServerSettings();
const {
data,
loading: isLoading,
error,
refetch,
} = requestManager.useGetSourceList({ notifyOnNetworkStatusChange: true });
const sources = data?.sources.nodes;
const filteredSources = useMemo(
() =>
SourceService.filter(sources ?? [], {
showNsfw,
languages: shownLangs,
keepLocalSource: true,
enabled: true,
}),
[sources, shownLangs],
);
const sourcesByLanguage = useMemo(() => {
const lastUsedSource = SourceService.getLastUsedSource(lastUsedSourceId, filteredSources);
const groupedByLanguageTuple = Object.entries(SourceService.groupByLanguage(filteredSources));
if (lastUsedSource) {
return [
[DefaultLanguage.LAST_USED_SOURCE, [lastUsedSource]],
...groupedByLanguageTuple,
] satisfies typeof groupedByLanguageTuple;
}
return groupedByLanguageTuple;
}, [filteredSources]);
const sourceLanguages = useMemo(() => SourceService.getLanguages(sources ?? []), [sources]);
const areSourcesFromDifferentRepos = useMemo(
() => SourceService.areFromMultipleRepos(filteredSources),
[filteredSources],
);
const visibleSources = useMemo(
() => sourcesByLanguage.map(([, sourcesOfLanguage]) => sourcesOfLanguage).flat(1),
[sourcesByLanguage],
);
const groupCounts = useMemo(
() => sourcesByLanguage.map((sourceGroup) => sourceGroup[1].length),
[sourcesByLanguage],
);
const computeItemKey = VirtuosoUtil.useCreateGroupedComputeItemKey(
groupCounts,
useCallback((index) => sourcesByLanguage[index][0], [sourcesByLanguage]),
useCallback(
(index, groupIndex) => `${sourcesByLanguage[groupIndex][0]}_${visibleSources[index].id}`,
[visibleSources],
),
);
const navigate = useNavigate();
useAppAction(
<>
<CustomTooltip title={t('search.title.global_search')}>
<IconButton onClick={() => navigate(AppRoutes.sources.childRoutes.searchAll.path())} color="inherit">
<TravelExploreIcon />
</IconButton>
</CustomTooltip>
<SourceLanguageSelect
selectedLanguages={shownLangs}
setSelectedLanguages={setShownLangs}
languages={sourceLanguages}
sources={sources ?? []}
/>
</>,
[t, shownLangs, sourceLanguages, sources],
);
if (isLoading) return <LoadingPlaceholder />;
if (error) {
return (
<EmptyViewAbsoluteCentered
message={t('global.error.label.failed_to_load_data')}
messageExtra={getErrorMessage(error)}
retry={() => refetch().catch(defaultPromiseErrorHandler('Sources::refetch'))}
/>
);
}
if (sources?.length === 0) {
return <EmptyViewAbsoluteCentered message={t('source.error.label.no_sources_found')} />;
}
return (
<StyledGroupedVirtuoso
persistKey="sources"
heightToSubtract={tabsMenuHeight}
overscan={window.innerHeight * 0.5}
groupCounts={groupCounts}
computeItemKey={computeItemKey}
groupContent={(index) => {
const [language] = sourcesByLanguage[index];
return (
<StyledGroupHeader isFirstItem={!index}>
<Typography variant="h5" component="h2">
{translateExtensionLanguage(language)}
</Typography>
</StyledGroupHeader>
);
}}
itemContent={(index, groupIndex) => {
const language = sourcesByLanguage[groupIndex][0];
const source = visibleSources[index];
return (
<StyledGroupItemWrapper>
<SourceCard
source={source}
showSourceRepo={areSourcesFromDifferentRepos}
showLanguage={isPinnedOrLastUsedSource(language)}
/>
</StyledGroupItemWrapper>
);
}}
/>
);
}

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 { useEffect, useMemo } from 'react';
import { requestUpdateSourceMetadata } from '@/features/metadata/services/MetadataUpdater.ts';
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
import { ISourceMetadata, SourceIdInfo, SourceMetadataKeys } from '@/features/source/Source.types.ts';
import { convertFromGqlMeta } from '@/features/metadata/services/MetadataConverter.ts';
import { getMetadataFrom } from '@/features/metadata/services/MetadataReader.ts';
import { AllowedMetadataValueTypes, GqlMetaHolder, Metadata } from '@/features/metadata/Metadata.types.ts';
const DEFAULT_SOURCE_METADATA: ISourceMetadata = {
savedSearches: undefined,
isPinned: false,
isEnabled: true,
};
const convertAppMetadataToGqlMetadata = (
metadata: Partial<ISourceMetadata>,
): Metadata<string, AllowedMetadataValueTypes> => ({
...metadata,
savedSearches: metadata.savedSearches ? JSON.stringify(metadata.savedSearches) : undefined,
});
const getMetadata = (metaHolder: SourceIdInfo & GqlMetaHolder, useEffectFn?: typeof useEffect): ISourceMetadata =>
getMetadataFrom(
'source',
{ ...metaHolder, meta: convertFromGqlMeta(metaHolder.meta) },
DEFAULT_SOURCE_METADATA,
undefined,
useEffectFn,
);
export const getSourceMetadata = (metaHolder: SourceIdInfo & GqlMetaHolder): ISourceMetadata => getMetadata(metaHolder);
export const useGetSourceMetadata = (metaHolder: SourceIdInfo & GqlMetaHolder): ISourceMetadata => {
const metadata = getMetadata(metaHolder, useEffect);
return useMemo(() => metadata, [metaHolder]);
};
export const updateSourceMetadata = async <
MetadataKeys extends SourceMetadataKeys = SourceMetadataKeys,
MetadataKey extends MetadataKeys = MetadataKeys,
>(
source: SourceIdInfo & GqlMetaHolder,
metadataKey: MetadataKey,
value: ISourceMetadata[MetadataKey],
): Promise<void[]> =>
requestUpdateSourceMetadata(source, [
[metadataKey, convertAppMetadataToGqlMetadata({ [metadataKey]: value })[metadataKey]],
]);
export const createUpdateSourceMetadata =
<Settings extends SourceMetadataKeys>(
source: SourceIdInfo & GqlMetaHolder,
handleError: (error: any) => void = defaultPromiseErrorHandler('createUpdateSourceMetadata'),
): ((...args: OmitFirst<Parameters<typeof updateSourceMetadata<Settings>>>) => Promise<void | void[]>) =>
(metadataKey, value) =>
updateSourceMetadata(source, metadataKey, value).catch(handleError);

View File

@@ -0,0 +1,169 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import { useTranslation } from 'react-i18next';
import { useCallback } from 'react';
import {
SourceDisplayNameInfo,
SourceIdInfo,
SourceLanguageInfo,
SourceNsfwInfo,
SourceMetaInfo,
SourceRepoInfo,
} from '@/features/source/Source.types.ts';
import {
DefaultLanguage,
languageSpecialSortComparator,
toComparableLanguage,
toComparableLanguages,
toUniqueLanguageCodes,
} from '@/features/core/utils/Languages.ts';
import { getSourceMetadata } from '@/features/source/services/SourceMetadata.ts';
import {
createUpdateMetadataServerSettings,
useMetadataServerSettings,
} from '@/features/settings/services/ServerSettingsMetadata.ts';
import { makeToast } from '@/features/core/utils/Toast.ts';
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
export class Sources {
static readonly LOCAL_SOURCE_ID = '0';
static isLocalSource(source: SourceIdInfo): boolean {
return source.id === Sources.LOCAL_SOURCE_ID;
}
static getLanguage(source: SourceIdInfo & SourceLanguageInfo): string {
if (Sources.isLocalSource(source)) {
return DefaultLanguage.OTHER;
}
return source.lang;
}
static getLanguages(sources: (SourceIdInfo & SourceLanguageInfo)[]): string[] {
return [...new Set(sources.map(Sources.getLanguage))];
}
static groupByLanguage<Source extends SourceIdInfo & SourceLanguageInfo & SourceDisplayNameInfo & SourceMetaInfo>(
sources: Source[],
): Record<string, Source[]> {
const sourcesByLanguage = Object.groupBy(sources, (source) => {
if (getSourceMetadata(source).isPinned) {
return DefaultLanguage.PINNED;
}
return Sources.getLanguage(source);
});
const sourcesBySortedLanguage = Object.entries(sourcesByLanguage).toSorted(([a], [b]) => {
const isAPinned = a === DefaultLanguage.PINNED;
const isBPinned = b === DefaultLanguage.PINNED;
if (isAPinned) {
return -1;
}
if (isBPinned) {
return 1;
}
return languageSpecialSortComparator(a, b);
});
const sortedSourcesBySortedLanguage = sourcesBySortedLanguage.map(([language, sourcesOfLanguage]) => [
language,
(sourcesOfLanguage ?? []).toSorted((a, b) => a.displayName.localeCompare(b.displayName)),
]);
return Object.fromEntries(sortedSourcesBySortedLanguage);
}
static filter<Source extends SourceIdInfo & SourceLanguageInfo & SourceNsfwInfo>(
sources: Source[],
{
showNsfw,
languages,
keepLocalSource,
pinned,
enabled,
}: {
showNsfw?: boolean;
languages?: string[];
keepLocalSource?: boolean;
pinned?: boolean;
enabled?: boolean;
} = {},
): Source[] {
const normalizedLanguages = toComparableLanguages(toUniqueLanguageCodes(languages ?? []));
return sources
.filter(
(source) =>
showNsfw === undefined ||
showNsfw ||
!source.isNsfw ||
(keepLocalSource && Sources.isLocalSource(source)),
)
.filter(
(source) =>
!languages ||
normalizedLanguages.includes(toComparableLanguage(Sources.getLanguage(source))) ||
(keepLocalSource && Sources.isLocalSource(source)),
)
.filter(
(source) =>
pinned === undefined ||
!pinned ||
getSourceMetadata(source).isPinned ||
(keepLocalSource && Sources.isLocalSource(source)),
)
.filter(
(source) =>
enabled === undefined ||
!enabled ||
getSourceMetadata(source).isEnabled ||
(keepLocalSource && Sources.isLocalSource(source)),
);
}
static areFromMultipleRepos<Source extends SourceIdInfo & SourceRepoInfo>(sources: Source[]): boolean {
const repo = sources.find((source) => !!source.extension.repo)?.extension.repo;
if (!repo || !sources.length) {
return false;
}
return sources.some((source) => source.extension.repo !== repo && !Sources.isLocalSource(source));
}
static getLastUsedSource<Source extends SourceIdInfo & SourceMetaInfo>(
lastUsedSourceId: SourceIdInfo['id'] | null,
sources: Source[],
): Source | undefined {
return sources.find((source) => source.id === lastUsedSourceId);
}
static useLanguages(): {
languages: string[];
setLanguages: (languages: string[]) => void;
} {
const { t } = useTranslation();
const {
settings: { sourceLanguages },
} = useMetadataServerSettings();
const updateSetting = createUpdateMetadataServerSettings<'sourceLanguages'>((e) =>
makeToast(t('global.error.label.failed_to_save_changes', getErrorMessage(e)), 'error'),
);
const setLanguages = useCallback((languages: string[]) => updateSetting('sourceLanguages', languages), []);
return {
languages: sourceLanguages,
setLanguages,
};
}
}