2021-07-14 16:14:04 +02:00
|
|
|
// @flow
|
|
|
|
import React from 'react';
|
|
|
|
import { getThumbnailCdnUrl } from 'util/thumbnail';
|
|
|
|
|
2022-03-21 04:40:32 +01:00
|
|
|
function scaleToDevicePixelRatio(value: number) {
|
2021-07-14 16:14:04 +02:00
|
|
|
const devicePixelRatio = window.devicePixelRatio || 1.0;
|
|
|
|
return Math.ceil(value * devicePixelRatio);
|
|
|
|
}
|
|
|
|
|
2022-03-21 04:40:32 +01:00
|
|
|
function getOptimizedImgUrl(url, width, height, quality) {
|
|
|
|
let optimizedUrl = url;
|
|
|
|
if (url && !url.startsWith('/public/')) {
|
|
|
|
optimizedUrl = url.trim().replace(/^http:\/\//i, 'https://');
|
2021-07-14 16:14:04 +02:00
|
|
|
|
2022-03-21 04:40:32 +01:00
|
|
|
if (!optimizedUrl.endsWith('.gif')) {
|
|
|
|
optimizedUrl = getThumbnailCdnUrl({ thumbnail: optimizedUrl, width, height, quality });
|
2021-07-14 16:14:04 +02:00
|
|
|
}
|
|
|
|
}
|
2022-03-21 04:40:32 +01:00
|
|
|
return optimizedUrl;
|
|
|
|
}
|
2021-07-14 16:14:04 +02:00
|
|
|
|
2022-03-21 04:40:32 +01:00
|
|
|
// ****************************************************************************
|
|
|
|
// OptimizedImage
|
|
|
|
// ****************************************************************************
|
2021-07-14 16:14:04 +02:00
|
|
|
|
2022-03-21 04:40:32 +01:00
|
|
|
type Props = {
|
|
|
|
src: string,
|
|
|
|
width?: number,
|
|
|
|
quality?: number,
|
|
|
|
waitLoad?: boolean,
|
|
|
|
};
|
2021-07-14 16:14:04 +02:00
|
|
|
|
2022-03-21 04:40:32 +01:00
|
|
|
function OptimizedImage(props: Props) {
|
|
|
|
const {
|
|
|
|
src,
|
|
|
|
width = 0, // 0 = use intrinsic width
|
|
|
|
quality = 85,
|
|
|
|
waitLoad,
|
|
|
|
...imgProps
|
|
|
|
} = props;
|
2021-07-14 16:14:04 +02:00
|
|
|
|
2022-03-21 04:40:32 +01:00
|
|
|
const ref = React.useRef<any>();
|
|
|
|
const optimizedSrc = getOptimizedImgUrl(src, scaleToDevicePixelRatio(width), 0, quality);
|
2021-07-14 16:14:04 +02:00
|
|
|
|
2022-02-07 21:59:20 +01:00
|
|
|
if (!src || !optimizedSrc) {
|
2021-07-14 16:14:04 +02:00
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
return (
|
|
|
|
<img
|
|
|
|
ref={ref}
|
|
|
|
{...imgProps}
|
2021-10-27 20:20:47 +02:00
|
|
|
style={{ visibility: waitLoad ? 'hidden' : 'visible' }}
|
2021-07-14 16:14:04 +02:00
|
|
|
src={optimizedSrc}
|
2021-10-27 20:20:47 +02:00
|
|
|
onLoad={() => {
|
2022-03-21 04:40:32 +01:00
|
|
|
if (waitLoad) {
|
|
|
|
ref.current.style.visibility = 'visible';
|
|
|
|
}
|
2021-10-27 20:20:47 +02:00
|
|
|
}}
|
2021-07-14 16:14:04 +02:00
|
|
|
/>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
export default OptimizedImage;
|