2020-01-18 02:07:52 +05:30
|
|
|
import React, { ComponentType, useEffect, useState } from 'react';
|
2019-12-08 01:13:08 +05:30
|
|
|
import clsx from 'clsx';
|
2020-01-18 02:07:52 +05:30
|
|
|
|
2019-12-08 00:32:00 +05:30
|
|
|
import { SKIN_LIGHT } from 'app/components/ui';
|
2017-11-20 01:47:23 +05:30
|
|
|
|
2020-01-18 02:07:52 +05:30
|
|
|
import ComponentLoader from './ComponentLoader';
|
2017-11-20 01:47:23 +05:30
|
|
|
import styles from './imageLoader.scss';
|
|
|
|
|
2020-01-18 02:07:52 +05:30
|
|
|
interface Props {
|
2020-05-24 04:38:24 +05:30
|
|
|
src: string;
|
|
|
|
alt: string;
|
|
|
|
ratio: number; // width:height ratio
|
|
|
|
onLoad?: () => void;
|
2020-01-18 02:07:52 +05:30
|
|
|
}
|
2017-11-20 01:47:23 +05:30
|
|
|
|
2020-05-24 04:38:24 +05:30
|
|
|
const ImageLoader: ComponentType<Props> = ({ src, alt, ratio, onLoad = () => {} }) => {
|
|
|
|
const [isLoading, setIsLoading] = useState<boolean>(true);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
function preloadImage() {
|
|
|
|
const img = new Image();
|
|
|
|
img.onload = () => {
|
|
|
|
setIsLoading(false);
|
|
|
|
onLoad();
|
|
|
|
};
|
|
|
|
img.onerror = preloadImage;
|
|
|
|
img.src = src;
|
|
|
|
}
|
|
|
|
|
|
|
|
preloadImage();
|
|
|
|
}, [src]);
|
|
|
|
|
|
|
|
return (
|
|
|
|
<div className={styles.container}>
|
|
|
|
<div
|
|
|
|
style={{
|
|
|
|
height: 0,
|
|
|
|
paddingBottom: `${ratio * 100}%`,
|
|
|
|
}}
|
|
|
|
/>
|
|
|
|
|
|
|
|
{isLoading && (
|
|
|
|
<div className={styles.loader}>
|
|
|
|
<ComponentLoader skin={SKIN_LIGHT} />
|
|
|
|
</div>
|
|
|
|
)}
|
|
|
|
|
|
|
|
<div
|
|
|
|
className={clsx(styles.image, {
|
|
|
|
[styles.imageLoaded]: !isLoading,
|
|
|
|
})}
|
|
|
|
>
|
|
|
|
<img src={src} alt={alt} />
|
|
|
|
</div>
|
2019-11-27 14:33:32 +05:30
|
|
|
</div>
|
2020-05-24 04:38:24 +05:30
|
|
|
);
|
2020-01-18 02:07:52 +05:30
|
|
|
};
|
|
|
|
|
|
|
|
export default ImageLoader;
|