File size: 2,131 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
import React, { useMemo, useState } from 'react';
import { createStyles, css } from 'antd-style';
import classNames from 'classnames';
import { CSSMotionList } from 'rc-motion';
import { COLOR_IMAGES, getClosetColor } from './colorUtil';
export interface BackgroundImageProps {
colorPrimary?: string;
isLight?: boolean;
}
const useStyle = createStyles(({ token }) => ({
image: css`
transition: all ${token.motionDurationSlow};
position: absolute;
inset-inline-start: 0;
top: 0;
height: 100%;
width: 100%;
object-fit: cover;
object-position: right top;
`,
}));
const onShow = () => ({ opacity: 1 });
const onHide = () => ({ opacity: 0 });
const BackgroundImage: React.FC<BackgroundImageProps> = ({ colorPrimary, isLight }) => {
const activeColor = useMemo(() => getClosetColor(colorPrimary), [colorPrimary]);
const { styles } = useStyle();
const [keyList, setKeyList] = useState<string[]>([]);
React.useLayoutEffect(() => {
setKeyList([activeColor as string]);
}, [activeColor]);
return (
<CSSMotionList
keys={keyList}
motionName="transition"
onEnterStart={onHide}
onAppearStart={onHide}
onEnterActive={onShow}
onAppearActive={onShow}
onLeaveStart={onShow}
onLeaveActive={onHide}
motionDeadline={500}
>
{({ key: color, className, style }) => {
const cls = classNames(styles.image, className);
const entity = COLOR_IMAGES.find((ent) => ent.color === color);
if (!entity || !entity.url) {
return null as unknown as React.ReactElement;
}
const { opacity } = style || {};
return (
<picture>
<source srcSet={entity.webp} type="image/webp" />
<source srcSet={entity.url} type="image/jpeg" />
<img
draggable={false}
className={cls}
style={{ ...style, opacity: isLight ? opacity : 0 }}
src={entity.url}
alt="bg"
/>
</picture>
);
}}
</CSSMotionList>
);
};
export default BackgroundImage;
|