Structure "source" in sub-features

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

View File

@@ -18,7 +18,7 @@ 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 { SourceContentType } from '@/features/source/browse/screens/SourceMangas.tsx';
import { GetSourcesListQuery } from '@/lib/graphql/generated/graphql.ts';
import { AppRoutes } from '@/base/AppRoute.constants.ts';
import { MUIUtil } from '@/lib/mui/MUI.util.ts';

View File

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

View File

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

View File

@@ -1,53 +0,0 @@
/*
* 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

@@ -1,20 +0,0 @@
/*
* 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

@@ -1,64 +0,0 @@
/*
* 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

@@ -1,20 +0,0 @@
/*
* 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

@@ -1,79 +0,0 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import ExpandLess from '@mui/icons-material/ExpandLess';
import ExpandMore from '@mui/icons-material/ExpandMore';
import Collapse from '@mui/material/Collapse';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemText from '@mui/material/ListItemText';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import React from 'react';
import { SortRadioInput } from '@/base/components/inputs/SortRadioInput.tsx';
import { SortSelectionInput } from '@/lib/graphql/generated/graphql.ts';
interface Props {
values: any;
name: string;
state: SortSelectionInput;
position: number;
group: number | undefined;
updateFilterValue: Function;
update: any;
}
export const SortFilter: React.FC<Props> = (props: Props) => {
const { values, name, state, position, group, updateFilterValue, update } = props;
const [val, setval] = React.useState(state);
const [open, setOpen] = React.useState(false);
const handleClick = () => {
setOpen(!open);
};
if (values) {
const handleChange = (index: number) => {
const tmp = val;
if (tmp.index === index) {
tmp.ascending = !tmp.ascending;
} else {
tmp.ascending = true;
}
tmp.index = index;
setval(tmp);
const upd = update.filter(
(e: { position: number; group: number | undefined }) => !(position === e.position && group === e.group),
);
updateFilterValue([...upd, { type: 'sortState', position, state: tmp, group }]);
};
return (
<Box sx={{ mx: -2 }}>
<ListItemButton onClick={handleClick}>
<ListItemText primary={name} />
{open ? <ExpandLess /> : <ExpandMore />}
</ListItemButton>
<Collapse in={open}>
<Stack sx={{ mx: 4 }}>
{values.map((value: string, index: number) => (
<SortRadioInput
key={`${name} ${value}`}
label={value}
checked={val.index === index}
sortDescending={!val.ascending}
onClick={() => handleChange(index)}
/>
))}
</Stack>
</Collapse>
</Box>
);
}
return null;
};

View File

@@ -1,56 +0,0 @@
/*
* Copyright (C) Contributors to the Suwayomi project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import SearchIcon from '@mui/icons-material/Search';
import FormControl from '@mui/material/FormControl';
import Input from '@mui/material/Input';
import InputAdornment from '@mui/material/InputAdornment';
import InputLabel from '@mui/material/InputLabel';
import React, { useEffect } from 'react';
import { useDebounce } from '@/base/hooks/useDebounce.ts';
interface Props {
state: string;
name: string;
position: number;
group: number | undefined;
updateFilterValue: Function;
update: any;
}
export const TextFilter: React.FC<Props> = (props) => {
const { state, name, position, group, updateFilterValue, update } = props;
const [Search, setsearch] = React.useState(state || '');
const inputText = useDebounce(Search, 500);
useEffect(() => {
const upd = update.filter(
(el: { position: number; group: number | undefined }) => !(position === el.position && group === el.group),
);
updateFilterValue([...upd, { type: 'textState', position, state: inputText, group }]);
}, [inputText]);
if (state !== undefined) {
return (
<FormControl sx={{ my: 1 }} variant="standard">
<InputLabel>{name}</InputLabel>
<Input
name={name}
value={Search}
onChange={({ target: { value } }) => setsearch(value)}
endAdornment={
<InputAdornment position="end">
<SearchIcon />
</InputAdornment>
}
/>
</FormControl>
);
}
return null;
};

View File

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

View File

@@ -1,81 +0,0 @@
/*
* 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

@@ -1,152 +0,0 @@
/*
* 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

@@ -1,162 +0,0 @@
/*
* 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 '@/base/utils/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

@@ -1,87 +0,0 @@
/*
* 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" />;
}