kontenhumas-fe/components/ui/image-blurry.tsx

78 lines
1.8 KiB
TypeScript

import React, { useEffect, useState } from "react";
interface ImageBlurryProps {
src: string;
alt?: string;
className?: string;
key?: string | number;
style?: React.CSSProperties;
priority?: boolean;
placeholder?: string;
}
const ImageBlurry: React.FC<ImageBlurryProps> = ({
src,
alt,
className,
key,
style,
priority = false,
placeholder,
}) => {
const [imgSrc, setImgSrc] = useState<string>(src);
const [isError, setIsError] = useState<boolean>(false);
useEffect(() => {
setImgSrc(src);
}, [src]);
const handleImage = () => {
const pics = document.querySelectorAll<HTMLImageElement>("img");
pics.forEach((pic) => {
if (pic.complete) {
checkImage(pic);
} else {
pic.addEventListener("load", function () {
checkImage(this as HTMLImageElement);
});
}
});
};
const checkImage = (img: HTMLImageElement) => {
if (img.naturalHeight > img.naturalWidth) {
img.classList.add("portrait");
} else if (Math.abs(img.naturalHeight - img.naturalWidth) < 10) {
img.classList.add("square");
} else {
img.classList.add("landscape");
}
};
const onLoad = () => {
console.log("Image loaded:", src);
handleImage();
};
return (
<div
className={`blurry-wrapper relative overflow-hidden bg-[#e9e9e9] rounded-t-lg ${
className || ""
}`}
key={key}
style={style}
>
<div
className="absolute -top-6 -bottom-6 -left-0 -right-6 bg-[#e9e9e9] blur-[8px] scale-[1.8] bg-center bg-no-repeat bg-contain blur-bg"
style={{ backgroundImage: `url(${imgSrc})` }}
></div>
<div
className="absolute inset-0 bg-transparent bg-center bg-no-repeat bg-contain image-bg"
style={{ backgroundImage: `url(${imgSrc})` }}
></div>
</div>
);
};
export default ImageBlurry;