Files
suwayomi-material-you-webui/src/components/util/SpinnerImage.tsx

163 lines
5.7 KiB
TypeScript
Raw Normal View History

2021-05-28 19:37:26 +04:30
/*
* 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/.
*/
2021-05-28 19:37:26 +04:30
import { useState, CSSProperties, useEffect, forwardRef, ForwardedRef } from 'react';
2021-09-09 17:51:22 +04:30
import CircularProgress from '@mui/material/CircularProgress';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import BrokenImageIcon from '@mui/icons-material/BrokenImage';
import RefreshIcon from '@mui/icons-material/Refresh';
import { useTranslation } from 'react-i18next';
import ImageIcon from '@mui/icons-material/Image';
import { SxProps, Theme } from '@mui/material/styles';
2024-03-01 01:17:23 +01:00
import { requestManager } from '@/lib/requests/RequestManager.ts';
import { Priority } from '@/lib/Queue.ts';
2021-05-28 19:37:26 +04:30
interface IProps {
src: string;
alt: string;
2021-05-28 19:37:26 +04:30
spinnerStyle?: SxProps<Theme> & { small?: boolean };
imgStyle?: CSSProperties;
2021-05-28 19:37:26 +04:30
onImageLoad?: () => void;
useFetchApi?: boolean;
2021-05-28 19:37:26 +04:30
}
export const SpinnerImage = forwardRef((props: IProps, imgRef: ForwardedRef<HTMLImageElement | null>) => {
const { useFetchApi, src, alt, onImageLoad, spinnerStyle: { small, ...spinnerStyle } = {}, imgStyle } = props;
2021-05-28 19:37:26 +04:30
const { t } = useTranslation();
const showMissingImageIcon = !src.length;
2024-03-01 01:17:23 +01:00
const [imageSourceUrl, setImageSourceUrl] = useState('');
const [imgLoadRetryKey, setImgLoadRetryKey] = useState(0);
const [isLoading, setIsLoading] = useState<boolean | undefined>(undefined);
const [hasError, setHasError] = useState(false);
2021-05-28 19:37:26 +04:30
const updateImageState = (loading: boolean, error: boolean = false, aborted: boolean = false) => {
setIsLoading(loading);
setHasError(error);
if (!loading && !error && !aborted) {
onImageLoad?.();
}
};
2021-05-28 19:37:26 +04:30
useEffect(() => {
if (showMissingImageIcon) {
return () => {};
}
const imageRequest = requestManager.requestImage(src, Priority.HIGH, useFetchApi);
let cacheTimeout: NodeJS.Timeout;
2024-03-01 01:17:23 +01:00
const fetchImage = async () => {
try {
const updateImage = async () => {
const image = await imageRequest.response;
updateImageState(false);
setImageSourceUrl(image);
};
const checkCache = await Promise.race([
imageRequest.response,
new Promise((resolve) => {
cacheTimeout = setTimeout(resolve, 50);
}),
]);
2024-03-01 01:17:23 +01:00
const isImageCached = !!checkCache;
if (isImageCached) {
await updateImage();
return;
}
updateImageState(true);
await updateImage();
} catch (e) {
const wasAborted =
e instanceof Error && (e.name === 'AbortError' || e.message === 'Component was unmounted');
updateImageState(false, !wasAborted, wasAborted);
2024-03-01 01:17:23 +01:00
}
};
fetchImage().catch(() => {});
2024-03-01 01:17:23 +01:00
return () => {
imageRequest.cleanup();
clearTimeout(cacheTimeout);
2024-03-01 01:17:23 +01:00
imageRequest.abortRequest(new Error('Component was unmounted'));
};
}, [src, imgLoadRetryKey]);
return (
<>
{(isLoading || hasError) && (
<Box sx={{ height: '100%', ...spinnerStyle }}>
2024-09-03 17:15:47 +02:00
<Stack
sx={{
height: '100%',
alignItems: 'center',
justifyContent: 'center',
}}
>
{isLoading && <CircularProgress thickness={5} />}
2024-03-01 01:17:23 +01:00
{hasError && isLoading === false && (
<>
<BrokenImageIcon />
<Button
startIcon={!small && <RefreshIcon />}
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
setImgLoadRetryKey((prevState) => (prevState + 1) % 100);
}}
size={small ? 'small' : 'large'}
>
{small ? <RefreshIcon /> : t('global.button.retry')}
</Button>
</>
)}
</Stack>
</Box>
)}
2024-03-01 01:17:23 +01:00
{showMissingImageIcon ? (
<Stack
2024-09-03 17:15:47 +02:00
sx={{
height: '100%',
alignItems: 'center',
justifyContent: 'center',
background: (theme) => theme.palette.background.default,
...spinnerStyle,
}}
>
<ImageIcon fontSize="large" />
</Stack>
) : (
<img
key={`${src}_${imgLoadRetryKey}`}
style={{
...imgStyle,
display: !imageSourceUrl || isLoading || hasError ? 'none' : imgStyle?.display,
}}
ref={imgRef}
src={imageSourceUrl}
alt={alt}
draggable={false}
/>
)}
</>
);
});