Rename folder "modules" to "features"
This commit is contained in:
9
src/features/category/Category.constants.ts
Normal file
9
src/features/category/Category.constants.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
/*
|
||||
* 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/.
|
||||
*/
|
||||
|
||||
export const CREATE_NEW_CATEGORY_ID = -1;
|
||||
21
src/features/category/Category.types.ts
Normal file
21
src/features/category/Category.types.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
/*
|
||||
* 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 { LibraryOptions } from '@/features/library/Library.types.ts';
|
||||
import { CategoryMetaType, CategoryType } from '@/lib/graphql/generated/graphql.ts';
|
||||
|
||||
export interface ICategoryMetadata extends LibraryOptions {}
|
||||
|
||||
export type CategoryMetadataKeys = keyof ICategoryMetadata;
|
||||
|
||||
export type CategoryIdInfo = Pick<CategoryType, 'id'>;
|
||||
export type CategoryNameInfo = Pick<CategoryType, 'name'>;
|
||||
export type CategoryDefaultInfo = Pick<CategoryType, 'default'>;
|
||||
export type CategoryUpdateInclusionInfo = Pick<CategoryType, 'includeInUpdate'>;
|
||||
export type CategoryDownloadInclusionInfo = Pick<CategoryType, 'includeInDownload'>;
|
||||
export type CategoryMetadataInfo = CategoryIdInfo & { meta: Pick<CategoryMetaType, 'key' | 'value'>[] };
|
||||
219
src/features/category/components/CategoriesInclusionSetting.tsx
Normal file
219
src/features/category/components/CategoriesInclusionSetting.tsx
Normal file
@@ -0,0 +1,219 @@
|
||||
/*
|
||||
* 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 { useEffect, useState } from 'react';
|
||||
import ListItemButton from '@mui/material/ListItemButton';
|
||||
import ListItemText from '@mui/material/ListItemText';
|
||||
import Dialog from '@mui/material/Dialog';
|
||||
import DialogContent from '@mui/material/DialogContent';
|
||||
import DialogTitle from '@mui/material/DialogTitle';
|
||||
import DialogContentText from '@mui/material/DialogContentText';
|
||||
import DialogActions from '@mui/material/DialogActions';
|
||||
import Button from '@mui/material/Button';
|
||||
import { t as translate } from 'i18next';
|
||||
import { ThreeStateCheckboxInput } from '@/features/core/components/inputs/ThreeStateCheckboxInput.tsx';
|
||||
import { makeToast } from '@/features/core/utils/Toast.ts';
|
||||
import { IncludeOrExclude } from '@/lib/graphql/generated/graphql.ts';
|
||||
import { requestManager } from '@/lib/requests/RequestManager.ts';
|
||||
import { CheckboxContainer } from '@/features/core/components/inputs/CheckboxContainer.ts';
|
||||
import {
|
||||
CategoryDownloadInclusionInfo,
|
||||
CategoryIdInfo,
|
||||
CategoryNameInfo,
|
||||
CategoryUpdateInclusionInfo,
|
||||
} from '@/features/category/Category.types.ts';
|
||||
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
|
||||
|
||||
type CategoryType = CategoryIdInfo & CategoryNameInfo & CategoryUpdateInclusionInfo & CategoryDownloadInclusionInfo;
|
||||
|
||||
const booleanToIncludeOrExcludeStatus = (status: boolean | null | undefined): IncludeOrExclude => {
|
||||
switch (status) {
|
||||
case false:
|
||||
return IncludeOrExclude.Exclude;
|
||||
case true:
|
||||
return IncludeOrExclude.Include;
|
||||
case null:
|
||||
case undefined:
|
||||
return IncludeOrExclude.Unset;
|
||||
default:
|
||||
throw new Error(`booleanToIncludeInStatus: unexpected IncludeOrExclude status "${status}"`);
|
||||
}
|
||||
};
|
||||
|
||||
const includeInUpdateStatusToBoolean = (status: IncludeOrExclude): boolean | null => {
|
||||
switch (status) {
|
||||
case IncludeOrExclude.Exclude:
|
||||
return false;
|
||||
case IncludeOrExclude.Include:
|
||||
return true;
|
||||
case IncludeOrExclude.Unset:
|
||||
return null;
|
||||
default:
|
||||
throw new Error(`includeInUpdateStatusToBoolean: unexpected IncludeOrExclude status "${status}"`);
|
||||
}
|
||||
};
|
||||
|
||||
const getCategoryUpdateInfo = (
|
||||
categories: CategoryType[],
|
||||
areIncluded: boolean,
|
||||
unsetCategories: number,
|
||||
allCategories: number,
|
||||
) => {
|
||||
const noSpecificallyIncludedCategories = areIncluded && !categories.length && unsetCategories;
|
||||
const includesAllCategories = categories.length === allCategories;
|
||||
if (noSpecificallyIncludedCategories || includesAllCategories) {
|
||||
return translate('extension.language.all');
|
||||
}
|
||||
|
||||
if (!categories.length) {
|
||||
return translate('global.label.none');
|
||||
}
|
||||
|
||||
return categories.map((category) => category.name).join(', ');
|
||||
};
|
||||
|
||||
type CategoryIncludeField = keyof Pick<CategoryType, 'includeInUpdate' | 'includeInDownload'>;
|
||||
|
||||
export type CategoriesInclusionSettingProps = {
|
||||
categories: CategoryType[];
|
||||
includeField: CategoryIncludeField;
|
||||
dialogText?: string;
|
||||
};
|
||||
|
||||
export const CategoriesInclusionSetting = ({
|
||||
categories,
|
||||
includeField,
|
||||
dialogText,
|
||||
}: CategoriesInclusionSettingProps) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [dialogCategories, setDialogCategories] = useState(categories);
|
||||
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!categories) {
|
||||
return;
|
||||
}
|
||||
|
||||
setDialogCategories(categories);
|
||||
}, [categories]);
|
||||
|
||||
const unsetCategories = categories.filter((category) => category[includeField] === IncludeOrExclude.Unset);
|
||||
const excludedCategories = categories.filter((category) => category[includeField] === IncludeOrExclude.Exclude);
|
||||
const includedCategories = categories.filter((category) => category[includeField] === IncludeOrExclude.Include);
|
||||
const excludedCategoriesText = getCategoryUpdateInfo(
|
||||
excludedCategories,
|
||||
false,
|
||||
unsetCategories.length,
|
||||
categories.length,
|
||||
);
|
||||
const includedCategoriesText = getCategoryUpdateInfo(
|
||||
includedCategories,
|
||||
true,
|
||||
unsetCategories.length,
|
||||
categories.length,
|
||||
);
|
||||
|
||||
const updateCategory = (category: CategoryType) =>
|
||||
requestManager.updateCategory(category.id, { [includeField]: category[includeField] }).response;
|
||||
|
||||
const updateCategories = async () => {
|
||||
const categoriesToUpdate = dialogCategories.filter((category) => {
|
||||
const currentCategory = categories?.find((currCategory) => currCategory.id === category.id);
|
||||
|
||||
if (!currentCategory) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return currentCategory[includeField] !== category[includeField];
|
||||
});
|
||||
|
||||
setIsDialogOpen(false);
|
||||
|
||||
try {
|
||||
await Promise.all(categoriesToUpdate.map((category) => updateCategory(category)));
|
||||
// TODO - update cache immediately
|
||||
// mutate(categoriesEndpoint, [...dialogCategories], { revalidate: false });
|
||||
} catch (e) {
|
||||
makeToast(t('global.error.label.failed_to_save_changes'), 'error', getErrorMessage(e));
|
||||
// mutate(categoriesEndpoint, [...categories]);
|
||||
}
|
||||
};
|
||||
|
||||
const closeDialog = () => {
|
||||
setDialogCategories(categories);
|
||||
setIsDialogOpen(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<ListItemButton onClick={() => setIsDialogOpen(true)}>
|
||||
<ListItemText
|
||||
primary={t('category.title.category_other')}
|
||||
secondary={
|
||||
<>
|
||||
<span>
|
||||
{t('category.settings.inclusion.label.include', {
|
||||
includedCategoriesText,
|
||||
})}
|
||||
</span>
|
||||
<span>
|
||||
{t('category.settings.inclusion.label.exclude', {
|
||||
excludedCategoriesText,
|
||||
})}
|
||||
</span>
|
||||
</>
|
||||
}
|
||||
secondaryTypographyProps={{ style: { display: 'flex', flexDirection: 'column' } }}
|
||||
/>
|
||||
</ListItemButton>
|
||||
|
||||
<Dialog open={isDialogOpen} onClose={closeDialog}>
|
||||
<DialogTitle>{t('category.title.category_other')}</DialogTitle>
|
||||
<DialogContent>
|
||||
{dialogText && <DialogContentText sx={{ paddingBottom: '10px' }}>{dialogText}</DialogContentText>}
|
||||
<CheckboxContainer>
|
||||
{dialogCategories.map((category) => (
|
||||
<ThreeStateCheckboxInput
|
||||
key={category.id}
|
||||
label={category.name}
|
||||
checked={includeInUpdateStatusToBoolean(category[includeField])}
|
||||
onChange={(checked) => {
|
||||
const newIncludeState = booleanToIncludeOrExcludeStatus(checked);
|
||||
|
||||
const categoryIndex = dialogCategories.findIndex(
|
||||
(category_) => category_ === category,
|
||||
);
|
||||
const updatedDialogCategories = [
|
||||
...dialogCategories.slice(0, categoryIndex),
|
||||
{
|
||||
...category,
|
||||
[includeField]: newIncludeState,
|
||||
},
|
||||
...dialogCategories.slice(categoryIndex + 1, dialogCategories.length),
|
||||
];
|
||||
|
||||
setDialogCategories(updatedDialogCategories);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</CheckboxContainer>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={closeDialog} color="primary">
|
||||
{t('global.button.cancel')}
|
||||
</Button>
|
||||
<Button onClick={updateCategories} color="primary">
|
||||
{t('global.button.ok')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
};
|
||||
255
src/features/category/components/CategorySelect.tsx
Normal file
255
src/features/category/components/CategorySelect.tsx
Normal file
@@ -0,0 +1,255 @@
|
||||
/*
|
||||
* 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 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 FormGroup from '@mui/material/FormGroup';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Link } from 'react-router-dom';
|
||||
import Stack from '@mui/material/Stack';
|
||||
import { requestManager } from '@/lib/requests/RequestManager.ts';
|
||||
import { Mangas } from '@/features/manga/services/Mangas.ts';
|
||||
import { useSelectableCollection } from '@/features/collection/hooks/useSelectableCollection.ts';
|
||||
import { ThreeStateCheckboxInput } from '@/features/core/components/inputs/ThreeStateCheckboxInput.tsx';
|
||||
import { Categories } from '@/features/category/services/Categories.ts';
|
||||
import { CheckboxInput } from '@/features/core/components/inputs/CheckboxInput.tsx';
|
||||
import { makeToast } from '@/features/core/utils/Toast.ts';
|
||||
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
|
||||
import { updateMetadataServerSettings } from '@/features/settings/services/ServerSettingsMetadata.ts';
|
||||
import {
|
||||
GetCategoriesBaseQuery,
|
||||
GetCategoriesBaseQueryVariables,
|
||||
GetMangaCategoriesQuery,
|
||||
GetMangaCategoriesQueryVariables,
|
||||
} from '@/lib/graphql/generated/graphql.ts';
|
||||
import { GET_CATEGORIES_BASE } from '@/lib/graphql/queries/CategoryQuery.ts';
|
||||
import { GET_MANGA_CATEGORIES } from '@/lib/graphql/queries/MangaQuery.ts';
|
||||
import { AppRoutes } from '@/features/core/AppRoute.constants.ts';
|
||||
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
|
||||
|
||||
type BaseProps = {
|
||||
open: boolean;
|
||||
onClose: (didUpdateCategories: boolean, addToCategories?: number[], removeFromCategories?: number[]) => void;
|
||||
};
|
||||
|
||||
type SingleMangaModeProps = {
|
||||
mangaId: number;
|
||||
addToLibrary?: boolean;
|
||||
};
|
||||
|
||||
type MultiMangaModeProps = {
|
||||
mangaIds: number[];
|
||||
};
|
||||
|
||||
export type CategorySelectProps =
|
||||
| (BaseProps & SingleMangaModeProps & PropertiesNever<MultiMangaModeProps>)
|
||||
| (BaseProps & PropertiesNever<SingleMangaModeProps> & MultiMangaModeProps);
|
||||
|
||||
const useGetMangaCategoryIds = (mangaId: number | undefined): number[] => {
|
||||
const { data: mangaResult } = requestManager.useGetManga<GetMangaCategoriesQuery, GetMangaCategoriesQueryVariables>(
|
||||
GET_MANGA_CATEGORIES,
|
||||
mangaId ?? -1,
|
||||
{ skip: mangaId === undefined },
|
||||
);
|
||||
|
||||
return useMemo(() => {
|
||||
if (mangaId === undefined || !mangaResult) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return Categories.getIds(mangaResult.manga.categories.nodes);
|
||||
}, [mangaResult?.manga.categories.nodes, mangaId]);
|
||||
};
|
||||
|
||||
const getCategoryCheckedState = (
|
||||
categoryId: number,
|
||||
categoriesToAdd: number[],
|
||||
categoriesToRemove: number[],
|
||||
isSingleSelectionMode: boolean,
|
||||
): boolean | undefined => {
|
||||
if (categoriesToAdd.includes(categoryId)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (isSingleSelectionMode) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (categoriesToRemove.includes(categoryId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
};
|
||||
|
||||
export function CategorySelect(props: CategorySelectProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const { open, onClose, mangaId, mangaIds: passedMangaIds, addToLibrary = false } = props;
|
||||
|
||||
const isSingleSelectionMode = mangaId !== undefined;
|
||||
const mangaIds = passedMangaIds ?? [mangaId];
|
||||
|
||||
const [doNotShowAddToLibraryDialogAgain, setDoNotShowAddToLibraryDialogAgain] = useState(false);
|
||||
|
||||
const mangaCategoryIds = useGetMangaCategoryIds(mangaId);
|
||||
|
||||
const { data } = requestManager.useGetCategories<GetCategoriesBaseQuery, GetCategoriesBaseQueryVariables>(
|
||||
GET_CATEGORIES_BASE,
|
||||
);
|
||||
const categoriesData = data?.categories.nodes;
|
||||
|
||||
const allCategories = useMemo(() => Categories.getUserCreated(categoriesData ?? []), [categoriesData]);
|
||||
|
||||
const defaultCategoryIds = useMemo(
|
||||
() => (addToLibrary ? Categories.getIds(Categories.getDefaults(allCategories)) : []),
|
||||
[allCategories],
|
||||
);
|
||||
|
||||
const { handleSelection, setSelectionForKey, getSelectionForKey } = useSelectableCollection<
|
||||
number,
|
||||
'categoriesToAdd' | 'categoriesToRemove'
|
||||
>(allCategories.length, {
|
||||
currentKey: 'categoriesToAdd',
|
||||
initialState: {
|
||||
categoriesToAdd: [...mangaCategoryIds, ...defaultCategoryIds],
|
||||
categoriesToRemove: [],
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
setSelectionForKey('categoriesToAdd', [...mangaCategoryIds, ...defaultCategoryIds]);
|
||||
setSelectionForKey('categoriesToRemove', []);
|
||||
}, [mangaCategoryIds]);
|
||||
|
||||
const categoriesToAdd = getSelectionForKey('categoriesToAdd');
|
||||
const categoriesToRemove = getSelectionForKey('categoriesToRemove');
|
||||
|
||||
const handleCancel = () => {
|
||||
setSelectionForKey('categoriesToAdd', mangaCategoryIds);
|
||||
setSelectionForKey('categoriesToRemove', []);
|
||||
onClose(false);
|
||||
};
|
||||
|
||||
const handleOk = () => {
|
||||
const addToCategories = isSingleSelectionMode
|
||||
? categoriesToAdd.filter((categoryId) => !mangaCategoryIds.includes(categoryId))
|
||||
: categoriesToAdd;
|
||||
const removeFromCategories = isSingleSelectionMode
|
||||
? mangaCategoryIds.filter((categoryId) => !categoriesToAdd.includes(categoryId))
|
||||
: categoriesToRemove;
|
||||
|
||||
onClose(true, addToCategories, removeFromCategories);
|
||||
|
||||
if (doNotShowAddToLibraryDialogAgain) {
|
||||
updateMetadataServerSettings('showAddToLibraryCategorySelectDialog', false).catch((e) =>
|
||||
makeToast(t('search.error.label.failed_to_save_settings'), 'error', getErrorMessage(e)),
|
||||
);
|
||||
}
|
||||
|
||||
const isUpdateRequired = !!addToCategories.length || !!removeFromCategories.length;
|
||||
if (!isUpdateRequired) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (addToLibrary) {
|
||||
// categories get updated in MangaDetails
|
||||
return;
|
||||
}
|
||||
|
||||
Mangas.performAction('change_categories', mangaIds, {
|
||||
changeCategoriesPatch: {
|
||||
addToCategories,
|
||||
removeFromCategories,
|
||||
},
|
||||
}).catch(defaultPromiseErrorHandler('CategorySelect::handleOk'));
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
sx={{
|
||||
'.MuiDialog-paper': {
|
||||
maxHeight: 435,
|
||||
width: '80%',
|
||||
},
|
||||
}}
|
||||
maxWidth="xs"
|
||||
open={open}
|
||||
onClose={handleCancel}
|
||||
>
|
||||
<DialogTitle>{t('category.title.set_categories')}</DialogTitle>
|
||||
<DialogContent dividers>
|
||||
<FormGroup>
|
||||
{allCategories.length === 0 && <span>{t('category.error.no_categories_found.label.info')}</span>}
|
||||
{allCategories.map((category) => (
|
||||
<ThreeStateCheckboxInput
|
||||
checked={getCategoryCheckedState(
|
||||
category.id,
|
||||
categoriesToAdd,
|
||||
categoriesToRemove,
|
||||
isSingleSelectionMode,
|
||||
)}
|
||||
onChange={(checked) => {
|
||||
handleSelection(category.id, false, { key: 'categoriesToAdd' });
|
||||
handleSelection(category.id, false, { key: 'categoriesToRemove' });
|
||||
|
||||
if (checked) {
|
||||
handleSelection(category.id, true, { key: 'categoriesToAdd' });
|
||||
}
|
||||
|
||||
if (checked === false) {
|
||||
handleSelection(category.id, true, { key: 'categoriesToRemove' });
|
||||
}
|
||||
}}
|
||||
label={category.name}
|
||||
key={category.id}
|
||||
/>
|
||||
))}
|
||||
</FormGroup>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Stack sx={{ width: '100%' }}>
|
||||
{addToLibrary && (
|
||||
<CheckboxInput
|
||||
sx={{ margin: 0 }}
|
||||
size="small"
|
||||
label={t('global.button.dont_show_dialog_again')}
|
||||
onChange={(e) => setDoNotShowAddToLibraryDialogAgain(e.target.checked)}
|
||||
/>
|
||||
)}
|
||||
<Stack
|
||||
direction="row"
|
||||
sx={{
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'end',
|
||||
width: '100%',
|
||||
}}
|
||||
>
|
||||
<Button component={Link} to={AppRoutes.settings.childRoutes.categories.path}>
|
||||
{t(allCategories.length ? 'global.button.edit' : 'global.button.create')}
|
||||
</Button>
|
||||
<Stack direction="row">
|
||||
<Button autoFocus onClick={handleCancel} color="primary">
|
||||
{t('global.button.cancel')}
|
||||
</Button>
|
||||
{!!allCategories.length && (
|
||||
<Button onClick={handleOk} color="primary">
|
||||
{t('global.button.ok')}
|
||||
</Button>
|
||||
)}
|
||||
</Stack>
|
||||
</Stack>
|
||||
</Stack>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
60
src/features/category/components/CategorySettingsCard.tsx
Normal file
60
src/features/category/components/CategorySettingsCard.tsx
Normal file
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright (C) Contributors to the Suwayomi project
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import IconButton from '@mui/material/IconButton';
|
||||
import DragHandleIcon from '@mui/icons-material/DragHandle';
|
||||
import EditIcon from '@mui/icons-material/Edit';
|
||||
import DeleteIcon from '@mui/icons-material/Delete';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import Box from '@mui/material/Box';
|
||||
import Card from '@mui/material/Card';
|
||||
import Stack from '@mui/material/Stack';
|
||||
import Typography from '@mui/material/Typography';
|
||||
import { CustomTooltip } from '@/features/core/components/CustomTooltip.tsx';
|
||||
import { requestManager } from '@/lib/requests/RequestManager.ts';
|
||||
import { CategoryType } from '@/lib/graphql/generated/graphql.ts';
|
||||
import { ListCardContent } from '@/features/core/components/lists/cards/ListCardContent.tsx';
|
||||
|
||||
export const CategorySettingsCard = ({
|
||||
category,
|
||||
onEdit,
|
||||
}: {
|
||||
category: Pick<CategoryType, 'id' | 'name'>;
|
||||
onEdit: () => void;
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const deleteCategory = () => {
|
||||
requestManager.deleteCategory(category.id);
|
||||
};
|
||||
|
||||
return (
|
||||
<Box sx={{ p: 1, pb: 0 }}>
|
||||
<Card>
|
||||
<ListCardContent sx={{ gap: 2 }}>
|
||||
<DragHandleIcon />
|
||||
<Typography sx={{ flexGrow: 1 }} variant="h6" component="h2">
|
||||
{category.name}
|
||||
</Typography>
|
||||
<Stack sx={{ flexDirection: 'row' }}>
|
||||
<CustomTooltip title={t('global.button.edit')}>
|
||||
<IconButton component={Box} onClick={onEdit}>
|
||||
<EditIcon />
|
||||
</IconButton>
|
||||
</CustomTooltip>
|
||||
<CustomTooltip title={t('chapter.action.download.delete.label.action')}>
|
||||
<IconButton component={Box} onClick={deleteCategory}>
|
||||
<DeleteIcon />
|
||||
</IconButton>
|
||||
</CustomTooltip>
|
||||
</Stack>
|
||||
</ListCardContent>
|
||||
</Card>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
* 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 Button from '@mui/material/Button';
|
||||
import TextField from '@mui/material/TextField';
|
||||
import Dialog from '@mui/material/Dialog';
|
||||
import DialogActions from '@mui/material/DialogActions';
|
||||
import DialogContent from '@mui/material/DialogContent';
|
||||
import DialogTitle from '@mui/material/DialogTitle';
|
||||
import Checkbox from '@mui/material/Checkbox';
|
||||
import FormControlLabel from '@mui/material/FormControlLabel';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { requestManager } from '@/lib/requests/RequestManager.ts';
|
||||
import { CategoryDefaultInfo, CategoryIdInfo, CategoryNameInfo } from '@/features/category/Category.types.ts';
|
||||
import { getErrorMessage } from '@/lib/HelperFunctions.ts';
|
||||
import { makeToast } from '@/features/core/utils/Toast.ts';
|
||||
import { assertIsDefined } from '@/Asserts.ts';
|
||||
|
||||
export const CreateOrEditCategoryDialog = ({
|
||||
category,
|
||||
onClose,
|
||||
}: {
|
||||
category: (CategoryIdInfo & CategoryNameInfo & CategoryDefaultInfo) | undefined;
|
||||
onClose: () => void;
|
||||
}) => {
|
||||
const isEditMode = !!category;
|
||||
|
||||
const { t } = useTranslation();
|
||||
|
||||
const [dialogName, setDialogName] = useState(category?.name);
|
||||
const [dialogDefault, setDialogDefault] = useState(!!category?.default);
|
||||
|
||||
const isInvalidName = dialogName !== undefined && !dialogName.trim().length;
|
||||
const canSubmit = dialogName !== undefined && !isInvalidName;
|
||||
|
||||
const handleDialogSubmit = () => {
|
||||
assertIsDefined(dialogName);
|
||||
|
||||
onClose();
|
||||
|
||||
if (isEditMode) {
|
||||
requestManager
|
||||
.updateCategory(category.id, { name: dialogName, default: dialogDefault })
|
||||
.response.catch((e) =>
|
||||
makeToast(t('global.error.label.failed_to_save_changes'), 'error', getErrorMessage(e)),
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
requestManager
|
||||
.createCategory({ name: dialogName, default: dialogDefault })
|
||||
.response.catch((e) => makeToast(t('category.error.label.create_failure'), 'error', getErrorMessage(e)));
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open onClose={onClose}>
|
||||
<DialogTitle id="form-dialog-title">
|
||||
{isEditMode ? t('category.dialog.title.edit_category_one') : t('category.dialog.title.new_category')}
|
||||
</DialogTitle>
|
||||
<DialogContent>
|
||||
<TextField
|
||||
autoFocus
|
||||
margin="dense"
|
||||
id="name"
|
||||
label={t('category.label.category_name')}
|
||||
type="text"
|
||||
fullWidth
|
||||
value={dialogName}
|
||||
onChange={(e) => setDialogName(e.target.value.trim())}
|
||||
error={isInvalidName}
|
||||
helperText={isInvalidName ? t`global.error.label.invalid_input` : undefined}
|
||||
/>
|
||||
<FormControlLabel
|
||||
control={<Checkbox checked={dialogDefault} onChange={(e) => setDialogDefault(e.target.checked)} />}
|
||||
label={t('category.label.use_as_default_category')}
|
||||
/>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={onClose} color="primary">
|
||||
{t('global.button.cancel')}
|
||||
</Button>
|
||||
<Button onClick={handleDialogSubmit} color="primary" disabled={!canSubmit}>
|
||||
{t('global.button.submit')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
43
src/features/category/hooks/useCategorySelect.tsx
Normal file
43
src/features/category/hooks/useCategorySelect.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* Copyright (C) Contributors to the Suwayomi project
|
||||
*
|
||||
* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
*/
|
||||
|
||||
import { useMemo, useState } from 'react';
|
||||
import { CategorySelect, CategorySelectProps } from '@/features/category/components/CategorySelect.tsx';
|
||||
|
||||
export const useCategorySelect = ({
|
||||
mangaId,
|
||||
mangaIds,
|
||||
onClose,
|
||||
addToLibrary,
|
||||
}: Omit<CategorySelectProps, 'open' | 'onClose'> & Pick<Partial<CategorySelectProps>, 'onClose'>) => {
|
||||
const [isCategorySelectOpen, setIsCategorySelectOpen] = useState(false);
|
||||
|
||||
const CategorySelectComponent = useMemo(() => {
|
||||
if (!isCategorySelectOpen) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<CategorySelect
|
||||
open={isCategorySelectOpen}
|
||||
onClose={(...args) => {
|
||||
setIsCategorySelectOpen(false);
|
||||
onClose?.(...args);
|
||||
}}
|
||||
mangaId={mangaId!} // either mangaId or mangaIds is undefined, however, ts is not able to infer it correctly and raises an error
|
||||
mangaIds={mangaIds as undefined}
|
||||
addToLibrary={addToLibrary}
|
||||
/>
|
||||
);
|
||||
}, [mangaId, mangaIds, addToLibrary, onClose, isCategorySelectOpen]);
|
||||
|
||||
return {
|
||||
openCategorySelect: setIsCategorySelectOpen,
|
||||
CategorySelectComponent,
|
||||
};
|
||||
};
|
||||
153
src/features/category/screens/CategorySettings.tsx
Normal file
153
src/features/category/screens/CategorySettings.tsx
Normal file
@@ -0,0 +1,153 @@
|
||||
/*
|
||||
* 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 { ComponentProps, useMemo, useState } from 'react';
|
||||
import Fab from '@mui/material/Fab';
|
||||
import AddIcon from '@mui/icons-material/Add';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import Box from '@mui/material/Box';
|
||||
import { closestCenter, DndContext, DragEndEvent } from '@dnd-kit/core';
|
||||
import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';
|
||||
import { requestManager } from '@/lib/requests/RequestManager.ts';
|
||||
import { DEFAULT_FULL_FAB_HEIGHT } from '@/features/core/components/buttons/StyledFab.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 { GetCategoriesSettingsQuery, GetCategoriesSettingsQueryVariables } from '@/lib/graphql/generated/graphql.ts';
|
||||
import { GET_CATEGORIES_SETTINGS } from '@/lib/graphql/queries/CategoryQuery.ts';
|
||||
import { CategorySettingsCard } from '@/features/category/components/CategorySettingsCard.tsx';
|
||||
import { CategoryIdInfo } from '@/features/category/Category.types.ts';
|
||||
import { getErrorMessage, noOp } from '@/lib/HelperFunctions.ts';
|
||||
import { DndSortableItem } from '@/lib/dnd-kit/DndSortableItem.tsx';
|
||||
import { DndKitUtil } from '@/lib/dnd-kit/DndKitUtil.ts';
|
||||
import { DndOverlayItem } from '@/lib/dnd-kit/DndOverlayItem.tsx';
|
||||
import { useAppTitle } from '@/features/navigation-bar/hooks/useAppTitle.ts';
|
||||
import { CREATE_NEW_CATEGORY_ID } from '@/features/category/Category.constants.ts';
|
||||
import { CreateOrEditCategoryDialog } from '@/features/category/components/CreateOrEditCategoryDialog.tsx';
|
||||
|
||||
export function CategorySettings() {
|
||||
const { t } = useTranslation();
|
||||
const dndSensors = DndKitUtil.useSensorsForDevice();
|
||||
|
||||
useAppTitle(t('category.dialog.title.edit_category_other'));
|
||||
|
||||
const { data, loading, error, refetch } = requestManager.useGetCategories<
|
||||
GetCategoriesSettingsQuery,
|
||||
GetCategoriesSettingsQueryVariables
|
||||
>(GET_CATEGORIES_SETTINGS, { notifyOnNetworkStatusChange: true });
|
||||
const [reorderCategory, { reset: revertReorder }] = requestManager.useReorderCategory();
|
||||
|
||||
const [categoryToEdit, setCategoryToEdit] = useState<number>(CREATE_NEW_CATEGORY_ID);
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [dndActiveCategory, setDndActiveCategory] = useState<
|
||||
ComponentProps<typeof CategorySettingsCard>['category'] | null
|
||||
>(null);
|
||||
|
||||
const categories = useMemo(() => {
|
||||
const res = [...(data?.categories.nodes ?? [])];
|
||||
if (res.length > 0 && res[0].name === 'Default') {
|
||||
res.shift();
|
||||
}
|
||||
return res;
|
||||
}, [data]);
|
||||
|
||||
const categoryReorder = (list: CategoryIdInfo[], from: number, to: number) => {
|
||||
const reorderedCategory = list[from];
|
||||
|
||||
reorderCategory({ variables: { input: { id: reorderedCategory.id, position: to + 1 } } }).catch(() =>
|
||||
revertReorder(),
|
||||
);
|
||||
};
|
||||
|
||||
const onDragEnd = (event: DragEndEvent) => {
|
||||
const { active, over } = event;
|
||||
|
||||
setDndActiveCategory(null);
|
||||
|
||||
if (!over || active.id === over.id) {
|
||||
return;
|
||||
}
|
||||
|
||||
const oldIndex = categories.findIndex((category) => category.id === active.id);
|
||||
const newIndex = categories.findIndex((category) => category.id === over.id);
|
||||
|
||||
categoryReorder(categories, oldIndex, newIndex);
|
||||
};
|
||||
|
||||
const handleDialogOpen = (categoryId?: CategoryIdInfo['id']) => {
|
||||
setCategoryToEdit(categoryId ?? CREATE_NEW_CATEGORY_ID);
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleDialogCancel = () => {
|
||||
setCategoryToEdit(CREATE_NEW_CATEGORY_ID);
|
||||
setDialogOpen(false);
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return <LoadingPlaceholder />;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<EmptyViewAbsoluteCentered
|
||||
message={t('category.error.label.request_failure')}
|
||||
messageExtra={getErrorMessage(error)}
|
||||
retry={() => refetch().catch(defaultPromiseErrorHandler('CategorySettings::refetch'))}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<DndContext
|
||||
sensors={dndSensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragStart={(event) =>
|
||||
setDndActiveCategory(categories.find((category) => category.id === event.active.id) ?? null)
|
||||
}
|
||||
onDragEnd={onDragEnd}
|
||||
onDragCancel={() => setDndActiveCategory(null)}
|
||||
onDragAbort={() => setDndActiveCategory(null)}
|
||||
>
|
||||
<Box sx={{ paddingBottom: DEFAULT_FULL_FAB_HEIGHT }}>
|
||||
<SortableContext items={categories} strategy={verticalListSortingStrategy}>
|
||||
{categories.map((category, index) => (
|
||||
<DndSortableItem
|
||||
key={category.id}
|
||||
id={category.id}
|
||||
isDragging={category.id === dndActiveCategory?.id}
|
||||
>
|
||||
<CategorySettingsCard category={category} onEdit={() => handleDialogOpen(index)} />
|
||||
</DndSortableItem>
|
||||
))}
|
||||
</SortableContext>
|
||||
<DndOverlayItem isActive={!!dndActiveCategory}>
|
||||
<CategorySettingsCard category={dndActiveCategory!} onEdit={noOp} />
|
||||
</DndOverlayItem>
|
||||
</Box>
|
||||
</DndContext>
|
||||
<Fab
|
||||
color="primary"
|
||||
aria-label="add"
|
||||
sx={{
|
||||
position: 'fixed',
|
||||
bottom: (theme) => theme.spacing(2),
|
||||
right: (theme) => theme.spacing(2),
|
||||
}}
|
||||
onClick={() => handleDialogOpen()}
|
||||
>
|
||||
<AddIcon />
|
||||
</Fab>
|
||||
|
||||
{dialogOpen && (
|
||||
<CreateOrEditCategoryDialog category={categories[categoryToEdit]} onClose={handleDialogCancel} />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
25
src/features/category/services/Categories.ts
Normal file
25
src/features/category/services/Categories.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* 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 { CategoryDefaultInfo, CategoryIdInfo } from '@/features/category/Category.types.ts';
|
||||
|
||||
export const DEFAULT_CATEGORY_ID = 0;
|
||||
|
||||
export class Categories {
|
||||
static getIds(categories: CategoryIdInfo[]): number[] {
|
||||
return categories.map((category) => category.id);
|
||||
}
|
||||
|
||||
static getUserCreated<Category extends CategoryIdInfo>(categories: Category[]): Category[] {
|
||||
return categories.filter((category) => category.id !== DEFAULT_CATEGORY_ID);
|
||||
}
|
||||
|
||||
static getDefaults<Category extends CategoryDefaultInfo>(categories: Category[]): Category[] {
|
||||
return categories.filter((category) => category.default);
|
||||
}
|
||||
}
|
||||
94
src/features/category/services/CategoryMetadata.ts
Normal file
94
src/features/category/services/CategoryMetadata.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
/*
|
||||
* 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 { requestUpdateCategoryMetadata } from '@/features/metadata/services/MetadataUpdater.ts';
|
||||
import { defaultPromiseErrorHandler } from '@/lib/DefaultPromiseErrorHandler.ts';
|
||||
import { LibraryOptions } from '@/features/library/Library.types.ts';
|
||||
import { CategoryIdInfo, CategoryMetadataKeys, ICategoryMetadata } from '@/features/category/Category.types.ts';
|
||||
import { convertFromGqlMeta } from '@/features/metadata/services/MetadataConverter.ts';
|
||||
import { getMetadataFrom } from '@/features/metadata/services/MetadataReader.ts';
|
||||
import {
|
||||
AllowedMetadataValueTypes,
|
||||
GqlMetaHolder,
|
||||
Metadata,
|
||||
MetadataHolder,
|
||||
} from '@/features/metadata/Metadata.types.ts';
|
||||
|
||||
export const DEFAULT_CATEGORY_METADATA: ICategoryMetadata = {
|
||||
// sort options
|
||||
sortDesc: undefined,
|
||||
sortBy: undefined,
|
||||
|
||||
// filter options
|
||||
hasDownloadedChapters: undefined,
|
||||
hasBookmarkedChapters: undefined,
|
||||
hasUnreadChapters: undefined,
|
||||
hasReadChapters: undefined,
|
||||
hasDuplicateChapters: undefined,
|
||||
hasTrackerBinding: {},
|
||||
hasStatus: {} as LibraryOptions['hasStatus'],
|
||||
};
|
||||
|
||||
const convertAppMetadataToGqlMetadata = (
|
||||
metadata: Partial<ICategoryMetadata>,
|
||||
): Metadata<string, AllowedMetadataValueTypes> => ({
|
||||
...metadata,
|
||||
hasTrackerBinding: metadata.hasTrackerBinding ? JSON.stringify(metadata.hasTrackerBinding) : undefined,
|
||||
hasStatus: metadata.hasStatus ? JSON.stringify(metadata.hasStatus) : undefined,
|
||||
});
|
||||
|
||||
const getCategoryMetadataWithDefaultValueFallback = (
|
||||
meta: CategoryIdInfo & MetadataHolder,
|
||||
defaultMetadata: ICategoryMetadata = DEFAULT_CATEGORY_METADATA,
|
||||
useEffectFn?: typeof useEffect,
|
||||
): ICategoryMetadata => getMetadataFrom('category', meta, defaultMetadata, undefined, useEffectFn);
|
||||
|
||||
const getMetadata = (
|
||||
metaHolder: CategoryIdInfo & GqlMetaHolder,
|
||||
defaultMetadata?: ICategoryMetadata,
|
||||
useEffectFn?: typeof useEffect,
|
||||
) =>
|
||||
getCategoryMetadataWithDefaultValueFallback(
|
||||
{ ...metaHolder, meta: convertFromGqlMeta(metaHolder.meta) },
|
||||
defaultMetadata,
|
||||
useEffectFn,
|
||||
);
|
||||
|
||||
export const getCategoryMetadata = (
|
||||
metaHolder: CategoryIdInfo & GqlMetaHolder,
|
||||
defaultMetadata?: ICategoryMetadata,
|
||||
): ICategoryMetadata => getMetadata(metaHolder, defaultMetadata);
|
||||
|
||||
export const useGetCategoryMetadata = (
|
||||
metaHolder: CategoryIdInfo & GqlMetaHolder,
|
||||
defaultMetadata?: ICategoryMetadata,
|
||||
): ICategoryMetadata => {
|
||||
const metadata = getMetadata(metaHolder, defaultMetadata, useEffect);
|
||||
return useMemo(() => metadata, [metaHolder, defaultMetadata]);
|
||||
};
|
||||
|
||||
export const updateCategoryMetadata = async <
|
||||
MetadataKeys extends CategoryMetadataKeys = CategoryMetadataKeys,
|
||||
MetadataKey extends MetadataKeys = MetadataKeys,
|
||||
>(
|
||||
category: CategoryIdInfo & GqlMetaHolder,
|
||||
metadataKey: MetadataKey,
|
||||
value: ICategoryMetadata[MetadataKey],
|
||||
): Promise<void[]> =>
|
||||
requestUpdateCategoryMetadata(category, [
|
||||
[metadataKey, convertAppMetadataToGqlMetadata({ [metadataKey]: value })[metadataKey]],
|
||||
]);
|
||||
|
||||
export const createUpdateCategoryMetadata =
|
||||
<Settings extends CategoryMetadataKeys>(
|
||||
category: CategoryIdInfo & GqlMetaHolder,
|
||||
handleError: (error: any) => void = defaultPromiseErrorHandler('createUpdateCategoryMetadata'),
|
||||
): ((...args: OmitFirst<Parameters<typeof updateCategoryMetadata<Settings>>>) => Promise<void | void[]>) =>
|
||||
(metadataKey, value) =>
|
||||
updateCategoryMetadata(category, metadataKey, value).catch(handleError);
|
||||
Reference in New Issue
Block a user