b5630f0ed6
Continuation of 1009 (2eae20f0
)
It can probably be handled inside the existing getThumbnailCdnUrl to reduce 1 function, but since the functionality is somewhat different (the proxy doesn't compress), it's probably clearer to separate it.
66 lines
1.6 KiB
JavaScript
66 lines
1.6 KiB
JavaScript
// @flow
|
|
import React from 'react';
|
|
import { getImageProxyUrl, getThumbnailCdnUrl } from 'util/thumbnail';
|
|
|
|
function scaleToDevicePixelRatio(value: number) {
|
|
const devicePixelRatio = window.devicePixelRatio || 1.0;
|
|
return Math.ceil(value * devicePixelRatio);
|
|
}
|
|
|
|
function getOptimizedImgUrl(url, width, height, quality) {
|
|
let optimizedUrl = url;
|
|
if (url && !url.startsWith('/public/')) {
|
|
optimizedUrl = url.trim().replace(/^http:\/\//i, 'https://');
|
|
|
|
if (optimizedUrl.endsWith('.gif')) {
|
|
optimizedUrl = getImageProxyUrl(optimizedUrl);
|
|
} else {
|
|
optimizedUrl = getThumbnailCdnUrl({ thumbnail: optimizedUrl, width, height, quality });
|
|
}
|
|
}
|
|
return optimizedUrl;
|
|
}
|
|
|
|
// ****************************************************************************
|
|
// OptimizedImage
|
|
// ****************************************************************************
|
|
|
|
type Props = {
|
|
src: string,
|
|
width?: number,
|
|
quality?: number,
|
|
waitLoad?: boolean,
|
|
};
|
|
|
|
function OptimizedImage(props: Props) {
|
|
const {
|
|
src,
|
|
width = 0, // 0 = use intrinsic width
|
|
quality = 85,
|
|
waitLoad,
|
|
...imgProps
|
|
} = props;
|
|
|
|
const ref = React.useRef<any>();
|
|
const optimizedSrc = getOptimizedImgUrl(src, scaleToDevicePixelRatio(width), 0, quality);
|
|
|
|
if (!src || !optimizedSrc) {
|
|
return null;
|
|
}
|
|
|
|
return (
|
|
<img
|
|
ref={ref}
|
|
{...imgProps}
|
|
style={{ visibility: waitLoad ? 'hidden' : 'visible' }}
|
|
src={optimizedSrc}
|
|
onLoad={() => {
|
|
if (waitLoad) {
|
|
ref.current.style.visibility = 'visible';
|
|
}
|
|
}}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export default OptimizedImage;
|