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

71 lines
1.8 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-10-31 21:02:45 +03:30
import React, { useEffect, useState, CSSProperties } from 'react';
2021-09-09 17:51:22 +04:30
import CircularProgress from '@mui/material/CircularProgress';
2021-10-31 21:02:45 +03:30
import Box from '@mui/system/Box';
import { Theme } from '@mui/system/createTheme';
import { SxProps } from '@mui/system/styleFunctionSx';
2021-05-28 19:37:26 +04:30
interface IProps {
src: string;
alt: string;
2021-05-28 19:37:26 +04:30
imgRef?: React.RefObject<HTMLImageElement>;
2021-05-28 19:37:26 +04:30
spinnerStyle?: SxProps<Theme>;
imgStyle?: CSSProperties;
2021-05-28 19:37:26 +04:30
onImageLoad?: () => void;
2021-05-28 19:37:26 +04:30
}
export default function SpinnerImage(props: IProps) {
const { src, alt, onImageLoad, imgRef, spinnerStyle, imgStyle } = props;
2021-05-28 19:37:26 +04:30
const [imageSrc, setImagsrc] = useState<string>('');
useEffect(() => {
const img = new Image();
img.src = src;
img.onload = () => {
setImagsrc(src);
onImageLoad?.();
};
img.onerror = () => {
// Setting to an actual image so CSS styling works consistently
setImagsrc('/notFound.svg');
};
2021-05-28 19:37:26 +04:30
return () => {
img.onload = null;
img.onerror = null;
2021-05-28 19:37:26 +04:30
};
}, [src]);
if (imageSrc.length === 0) {
return (
<Box sx={spinnerStyle}>
2021-05-28 19:37:26 +04:30
<CircularProgress thickness={5} />
2021-10-31 21:02:45 +03:30
</Box>
2021-05-28 19:37:26 +04:30
);
}
if (imageSrc === 'Not Found') {
return <Box sx={spinnerStyle} />;
}
return <img style={imgStyle} ref={imgRef} src={imageSrc} alt={alt} />;
2021-05-28 19:37:26 +04:30
}
SpinnerImage.defaultProps = {
2021-10-31 21:02:45 +03:30
spinnerStyle: {},
imgStyle: {},
2021-05-28 19:37:26 +04:30
onImageLoad: () => {},
imgRef: undefined,
};