"use client"; import { useState } from "react"; import { z } from "zod"; import { Icon, Loader, Status } from "~/components/Global"; import { Alert, AlertDescription, AlertTitle } from "~/components/ui/alert"; import useLoading from "~/hooks/useLoading"; import { cn } from "~/utils/cn"; import { Schema_File } from "~/types/schema"; import { CreateDownloadToken } from "actions"; import config from "config"; type Props = { file: z.infer; }; export default function PreviewImage({ file }: Props) { const [imgSrc, setImgSrc] = useState(`/api/thumb/${file.encryptedId}?size=4`); const [imgLoaded, setImgLoaded] = useState(false); const [error, setError] = useState(""); const loading = useLoading(async () => { try { if (!file.encryptedWebContentLink) { setError("No image to preview"); return; } const token = await CreateDownloadToken(); const streamURL = new URL(`/api/thumb/${file.encryptedId}?size=1000`, config.basePath); streamURL.searchParams.set("token", token); fetch(streamURL, { headers: { Range: `bytes=0-${(file.size || 1) - 1}`, }, }) .then((res) => { if (!res.ok) { throw new Error("Could not load image"); } return res.blob(); }) .then((blob) => { const urlobject = URL.createObjectURL(blob); setImgSrc(urlobject); const timeout = setTimeout(() => { setImgLoaded(true); clearTimeout(timeout); }, 150); // Add a delay to show the image }); } catch (error) { const e = error as Error; console.error(e); setError(e.message); } }, [file]); return (
{loading ? ( ) : error ? ( ) : (
Preview Only This image is a preview and may not be the full resolution. Please download the file for the full resolution.
{file.name} { console.error(e); setError("Could not preview this image, try downloading the file"); }} />
)}
); }