feat: add option to cache images locally (#1213)

This commit is contained in:
sct
2021-03-18 21:37:25 +09:00
committed by GitHub
parent dfd4ff9229
commit 0ca3d43749
26 changed files with 293 additions and 108 deletions

View File

@@ -0,0 +1,18 @@
import Image, { ImageProps } from 'next/image';
import React from 'react';
import useSettings from '../../../hooks/useSettings';
/**
* The CachedImage component should be used wherever
* we want to offer the option to locally cache images.
*
* It uses the `next/image` Image component but overrides
* the `unoptimized` prop based on the application setting `cacheImages`.
**/
const CachedImage: React.FC<ImageProps> = (props) => {
const { currentSettings } = useSettings();
return <Image unoptimized={!currentSettings.cacheImages} {...props} />;
};
export default CachedImage;

View File

@@ -4,13 +4,13 @@ import React, {
HTMLAttributes,
ForwardRefRenderFunction,
} from 'react';
import Image from 'next/image';
import CachedImage from '../CachedImage';
interface ImageFaderProps extends HTMLAttributes<HTMLDivElement> {
backgroundImages: string[];
rotationSpeed?: number;
isDarker?: boolean;
useImage?: boolean;
forceOptimize?: boolean;
}
const DEFAULT_ROTATION_SPEED = 6000;
@@ -20,7 +20,7 @@ const ImageFader: ForwardRefRenderFunction<HTMLDivElement, ImageFaderProps> = (
backgroundImages,
rotationSpeed = DEFAULT_ROTATION_SPEED,
isDarker,
useImage,
forceOptimize,
...props
},
ref
@@ -46,6 +46,14 @@ const ImageFader: ForwardRefRenderFunction<HTMLDivElement, ImageFaderProps> = (
'linear-gradient(180deg, rgba(17, 24, 39, 0.47) 0%, rgba(17, 24, 39, 1) 100%)';
}
let overrides = {};
if (forceOptimize) {
overrides = {
unoptimized: false,
};
}
return (
<div ref={ref}>
{backgroundImages.map((imageUrl, i) => (
@@ -54,29 +62,20 @@ const ImageFader: ForwardRefRenderFunction<HTMLDivElement, ImageFaderProps> = (
className={`absolute inset-0 bg-cover bg-center transition-opacity duration-300 ease-in ${
i === activeIndex ? 'opacity-100' : 'opacity-0'
}`}
style={{
backgroundImage: !useImage
? `${gradient}, url(${imageUrl})`
: undefined,
}}
{...props}
>
{useImage && (
<>
<Image
className="absolute inset-0 w-full h-full"
alt=""
src={imageUrl}
layout="fill"
objectFit="cover"
quality={100}
/>
<div
className="absolute inset-0"
style={{ backgroundImage: gradient }}
/>
</>
)}
<CachedImage
className="absolute inset-0 w-full h-full"
alt=""
src={imageUrl}
layout="fill"
objectFit="cover"
{...overrides}
/>
<div
className="absolute inset-0"
style={{ backgroundImage: gradient }}
/>
</div>
))}
</div>