Files
suwayomi-material-you-webui/src/modules/core/components/buttons/ValueRotationButton.tsx

73 lines
2.2 KiB
TypeScript
Raw Normal View History

2024-10-03 04:02:59 +02:00
/*
* 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';
2024-11-04 18:00:35 +01:00
import { ReactNode, useMemo } from 'react';
2024-10-03 04:02:59 +02:00
import Button from '@mui/material/Button';
2024-11-04 18:00:35 +01:00
import { MultiValueButtonProps } from '@/modules/core/Core.types.ts';
2024-10-03 04:02:59 +02:00
export const ValueRotationButton = <Value extends string | number>({
value,
values,
setValue,
valueToDisplayData,
2024-11-04 18:00:35 +01:00
isDefaultable,
onDefault,
defaultIcon,
}: MultiValueButtonProps<Value> & { defaultIcon?: ReactNode }) => {
2024-10-03 04:02:59 +02:00
const { t } = useTranslation();
2024-11-04 18:00:35 +01:00
const isDefault = value === undefined;
const indexOfValue = useMemo(() => {
if (isDefault) {
return -1;
}
return values.indexOf(value);
}, [value, values]);
if (isDefault) {
return (
<Button
onClick={() => setValue(values[0])}
sx={{ justifyContent: 'start', textTransform: 'unset', flexGrow: 1 }}
variant="contained"
startIcon={defaultIcon}
size="large"
>
{t('global.label.default')}
</Button>
);
}
2024-10-03 04:02:59 +02:00
return (
<Button
2024-11-04 18:00:35 +01:00
onClick={() => {
const nextValueIndex = (indexOfValue + 1) % values.length;
const wasLastValue = nextValueIndex === 0;
const isDefaultNextValue = isDefaultable && wasLastValue;
if (isDefaultNextValue) {
onDefault?.();
return;
}
setValue(values[(indexOfValue + 1) % values.length]);
}}
2024-10-03 04:02:59 +02:00
sx={{ justifyContent: 'start', textTransform: 'unset', flexGrow: 1 }}
variant="contained"
startIcon={valueToDisplayData[value].icon}
size="large"
>
2024-10-28 18:03:29 +01:00
{valueToDisplayData[value].isTitleString
? valueToDisplayData[value].title
: t(valueToDisplayData[value].title)}
2024-10-03 04:02:59 +02:00
</Button>
);
};