magic-img
Version:
79 lines (77 loc) • 2.27 kB
JavaScript
import {
imgPlaceholder
} from "./chunk-7XC4PFDB.mjs";
import "./chunk-NHABU752.mjs";
// src/frameWork/react/index.tsx
import { useEffect, useRef, useState } from "react";
import { jsx, jsxs } from "react/jsx-runtime";
function MagicImg({ src, ...reset }) {
const magicImage = useRef(null);
const data = JSON.parse(src);
const [placeholderStatus, setPlaceholderStatus] = useState("");
const [targetStatus, setTargetStatus] = useState("");
const [realSrc, setRealSrc] = useState("");
const start = () => {
setPlaceholderStatus("from");
setTargetStatus("from");
const start2 = performance.now();
const img = new Image();
img.onload = () => requestAnimationFrame(() => {
const status = performance.now() - start2 > 100 ? "to" : "noPrevice";
setRealSrc(data.src);
setPlaceholderStatus(status);
setTargetStatus(status);
});
img.src = data.src;
};
useEffect(() => {
const intersection = new IntersectionObserver(async (entrys) => {
for (const { isIntersecting } of entrys) {
if (isIntersecting) {
start();
intersection.disconnect();
}
}
});
intersection.observe(magicImage.current);
return () => {
intersection.disconnect();
};
}, [src]);
return /* @__PURE__ */ jsxs("div", { ref: magicImage, "magic-img": "true", ...{ magic: data.magic, ...reset }, children: [
!imgPlaceholder.includes(data.magic) ? /* @__PURE__ */ jsx(
"svg",
{
className: "magic-placeholder",
...{ status: placeholderStatus },
preserveAspectRatio: "none",
dangerouslySetInnerHTML: { __html: data.content },
width: data.width,
height: data.height,
viewBox: `0 0 ${data.width_ || data.width} ${data.height_ || data.height}`
}
) : /* @__PURE__ */ jsx(
"img",
{
className: "magic-placeholder",
...{ status: placeholderStatus },
src: data.content,
width: data.width,
height: data.height,
alt: ""
}
),
/* @__PURE__ */ jsx(
"img",
{
className: "magic-target",
...{ status: targetStatus },
src: realSrc,
alt: ""
}
)
] });
}
export {
MagicImg as default
};