infoalloggi-monorepo/apps/infoalloggi/src/components/allegato-iframe.tsx
2025-08-04 17:45:44 +02:00

56 lines
1.5 KiB
TypeScript

import { cn } from "~/lib/utils";
import type { TempTokensToken } from "~/schemas/public/TempTokens";
import { api } from "~/utils/api";
import { LoadingPage } from "~/components/loading";
import { useEffect, useRef, useState } from "react";
export const AllegatoIframe = ({
className,
allegato,
}: {
className?: string;
allegato: string;
}) => {
const if_ref = useRef<HTMLIFrameElement>(null);
const { mutateAsync: getToken } = api.storage.getStorageToken.useMutation();
const [token, setToken] = useState<TempTokensToken | null>(null);
const handleIframeLoad = () => {
if (if_ref.current && if_ref.current.contentWindow) {
const img = if_ref.current.contentWindow.document.querySelector("img");
if (img) {
img.style.width = "100%";
img.style.height = "100%";
img.style.objectFit = "contain";
}
}
};
useEffect(() => {
async function set() {
const token = await getToken();
setToken(token);
}
set().catch((e) => console.error(e));
}, []);
if (!token) return <LoadingPage />;
const requestUrl = `/go-api/storage/get/${allegato}?token=${String(token)}`;
return (
<div
className={cn(
"flex h-full w-full items-center justify-center object-contain",
className,
)}
>
<iframe
title="Allegato"
ref={if_ref}
src={requestUrl}
className="h-full w-full"
onLoad={handleIframeLoad}
allowFullScreen
/>
</div>
);
};