import { Download } from "lucide-react"; import { useCallback, useEffect, useRef, useState } from "react"; import { flushSync } from "react-dom"; import { ProgressCard } from "@/components/common/progress-card"; import { formatHeaders } from "@/lib/api"; import { useFileStore } from "@/stores/file-store"; const PAGE_SIZES: Record = { A4: [595.28, 841.89], Letter: [612, 792], A3: [841.89, 1190.55], A5: [419.53, 595.28], }; const PREVIEW_HEIGHT = 220; function PdfPagePreview({ pageSize, orientation, margin, imgUrl, }: { pageSize: string; orientation: "portrait" | "landscape"; margin: number; imgUrl: string | null; }) { const [imgSize, setImgSize] = useState<{ w: number; h: number } | null>(null); useEffect(() => { if (!imgUrl) { setImgSize(null); return; } const img = new Image(); img.onload = () => setImgSize({ w: img.naturalWidth, h: img.naturalHeight }); img.onerror = () => setImgSize(null); img.src = imgUrl; }, [imgUrl]); let [pageW, pageH] = PAGE_SIZES[pageSize] ?? PAGE_SIZES.A4; if (orientation === "landscape") [pageW, pageH] = [pageH, pageW]; const scale = PREVIEW_HEIGHT / pageH; const previewW = pageW * scale; const previewH = PREVIEW_HEIGHT; const marginScaled = margin * scale; const contentW = previewW - marginScaled * 2; const contentH = previewH - marginScaled * 2; let imgStyle: React.CSSProperties | null = null; if (imgSize && imgUrl && contentW > 0 && contentH > 0) { const imgScale = Math.min(contentW / imgSize.w, contentH / imgSize.h, 1); const scaledW = imgSize.w * imgScale; const scaledH = imgSize.h * imgScale; imgStyle = { width: scaledW, height: scaledH, position: "absolute" as const, left: marginScaled + (contentW - scaledW) / 2, top: marginScaled + (contentH - scaledH) / 2, objectFit: "contain" as const, }; } return (

Preview

{/* Margin area — dashed inner border */} {margin > 0 && (
)} {/* Image thumbnail */} {imgStyle && imgUrl && ( Preview )} {/* Empty state placeholder */} {!imgUrl && (
No image
)}
); } export function ImageToPdfSettings() { const { files, selectedIndex, entries, error, setProcessing, setError } = useFileStore(); const [pageSize, setPageSize] = useState<"A4" | "Letter" | "A3" | "A5">("A4"); const [orientation, setOrientation] = useState<"portrait" | "landscape">("portrait"); const [margin, setMargin] = useState(20); const [downloadUrl, setDownloadUrl] = useState(null); // Local processing state so the ProgressCard renders reliably const [busy, setBusy] = useState(false); const [progress, setProgress] = useState({ phase: "idle" as "idle" | "uploading" | "processing" | "complete", percent: 0, elapsed: 0, }); const elapsedRef = useRef | null>(null); const processingTimerRef = useRef | null>(null); const xhrRef = useRef(null); useEffect(() => { return () => { if (elapsedRef.current) clearInterval(elapsedRef.current); if (processingTimerRef.current) clearInterval(processingTimerRef.current); if (xhrRef.current) xhrRef.current.abort(); }; }, []); const cleanup = () => { if (elapsedRef.current) clearInterval(elapsedRef.current); if (processingTimerRef.current) clearInterval(processingTimerRef.current); elapsedRef.current = null; processingTimerRef.current = null; setBusy(false); setProcessing(false); }; const handleProcess = useCallback(() => { if (files.length === 0) return; // flushSync forces React to paint the ProgressCard before the XHR starts, // so users always see feedback even if the request completes quickly. flushSync(() => { setBusy(true); setProcessing(true); setError(null); setDownloadUrl(null); setProgress({ phase: "uploading", percent: 0, elapsed: 0 }); }); const startTime = Date.now(); elapsedRef.current = setInterval(() => { setProgress((prev) => ({ ...prev, elapsed: Math.floor((Date.now() - startTime) / 1000) })); }, 1000); const formData = new FormData(); for (const file of files) { formData.append("file", file); } formData.append("settings", JSON.stringify({ pageSize, orientation, margin })); const xhr = new XMLHttpRequest(); xhrRef.current = xhr; xhr.timeout = 180_000; xhr.upload.onprogress = (event) => { if (event.lengthComputable) { const uploadPercent = (event.loaded / event.total) * 40; setProgress((prev) => prev.phase === "uploading" ? { ...prev, percent: uploadPercent } : prev, ); } }; xhr.upload.onload = () => { setProgress((prev) => ({ ...prev, phase: "processing", percent: 40 })); const step = (95 - 40) / 90; processingTimerRef.current = setInterval(() => { setProgress((prev) => { if (prev.phase !== "processing") return prev; return { ...prev, percent: Math.min(95, prev.percent + step) }; }); }, 500); }; xhr.onload = () => { if (xhr.status >= 200 && xhr.status < 300) { try { const result = JSON.parse(xhr.responseText); setDownloadUrl(result.downloadUrl); setProgress((prev) => ({ ...prev, phase: "complete", percent: 100 })); } catch { setError("Failed to parse server response"); } } else { try { const body = JSON.parse(xhr.responseText); setError(body.error || `Failed: ${xhr.status}`); } catch { setError(`PDF creation failed: ${xhr.status}`); } } cleanup(); }; xhr.onerror = () => { setError("Network error during PDF creation"); cleanup(); }; xhr.ontimeout = () => { setError("Request timed out - the server may be overloaded"); cleanup(); }; xhr.open("POST", "/api/v1/tools/image-to-pdf"); const headers = formatHeaders(); for (const [key, value] of Object.entries(headers)) { xhr.setRequestHeader(key, value as string); } xhr.send(formData); }, [files, pageSize, orientation, margin, setProcessing, setError]); const hasFiles = files.length > 0; return (

{files.length} image{files.length !== 1 ? "s" : ""} will be combined into a PDF, one image per page.

Orientation

{margin}pt
setMargin(Number(e.target.value))} className="w-full mt-1" />
{error &&

{error}

} {busy ? ( ) : ( )} {downloadUrl && ( Download PDF )}
); }