import CheckIcon from '@mui/icons-material/Check';
import SaveIcon from '@mui/icons-material/Save';
import {
always,
any,
cond,
isEmpty,
isNil,
not,
or,
pipe,
propEq,
T
} from 'ramda';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import type { Props } from '.';
interface StartIconConfigProps {
hasLabel: boolean;
loading: boolean;
succeeded: boolean;
enabled: boolean;
}
const isNilOrEmpty = (value: unknown): boolean =>
or(isNil(value), isEmpty(value));
const hasValue = any(pipe(isNilOrEmpty, not));
interface UseSaveState {
content: string | JSX.Element;
startIconToDisplay: null | JSX.Element;
hasLabel: boolean;
}
export const useSave = ({
labelLoading,
labelSave,
labelSucceeded,
loading,
succeeded,
startIcon
}: Pick<
Props,
| 'startIcon'
| 'succeeded'
| 'loading'
| 'labelSave'
| 'labelSucceeded'
| 'labelLoading'
>): UseSaveState => {
const { t } = useTranslation();
const hasLabel = hasValue([labelLoading, labelSave, labelSucceeded]);
const startIconConfig = {
enabled: startIcon,
hasLabel,
loading,
succeeded
} as StartIconConfigProps;
const content = useMemo(() => {
if (loading) {
return t(labelLoading || 'loading');
}
if (succeeded) {
return labelSucceeded ? t(labelSucceeded) : ;
}
return labelSave ? t(labelSave) : ;
}, [labelLoading, labelSucceeded, labelSave, loading, succeeded, t]);
const startIconToDisplay = useMemo(() => {
return cond, JSX.Element | null>([
[propEq(true, 'enabled'), always(null)],
[pipe(propEq(true, 'hasLabel'), not), always(null)],
[propEq(true, 'succeeded'), always()],
[propEq(true, 'loading'), always()],
[T, always()]
])(startIconConfig);
}, [startIconConfig]);
return {
content,
hasLabel,
startIconToDisplay
};
};