sharpify-ai / src /components /BatchEnhancer.tsx
suplo6669's picture
Publish Sharpify AI static frontend
1d8be9a verified
Raw History Blame Contribute Delete
26.9 kB
"use client";
import Image from "next/image";
import {
Check,
CircleHelp,
Download,
FileImage,
Image as ImageIcon,
LoaderCircle,
Plus,
Trash2,
Upload,
WandSparkles,
X,
} from "lucide-react";
import { useEffect, useRef, useState, type ChangeEvent, type DragEvent } from "react";
import { ComparisonViewer } from "@/components/ComparisonViewer";
import { enhanceImage, EnhancementApiError } from "@/lib/api";
import { formatFileSize, validateImageFile } from "@/lib/fileValidation";
import { createImageArchive } from "@/lib/imageArchive";
import type { EnhancementResponse, EnhancementSettings, OutputFormat, UpscaleFactor } from "@/types/enhancement";
const MAX_BATCH_FILES = 10;
const MAX_BATCH_OUTPUT_PIXELS = 64_000_000;
const DEFAULT_SETTINGS: EnhancementSettings = { scale: 4, outputFormat: "png" };
type BatchItemStatus = "queued" | "processing" | "complete" | "failed";
type BatchItem = {
id: string;
file: File;
width: number;
height: number;
previewUrl: string;
resultPreviewUrl: string | null;
result: EnhancementResponse | null;
status: BatchItemStatus;
error: string | null;
};
type BatchEnhancerProps = {
accessToken: string | null;
requiresAuth: boolean;
onBusyChange: (busy: boolean) => void;
};
const formats: { value: OutputFormat; label: string; detail: string }[] = [
{ value: "png", label: "PNG", detail: "Lossless" },
{ value: "jpeg", label: "JPG", detail: "Smaller file" },
{ value: "webp", label: "WEBP", detail: "Modern" },
];
function makeId(): string {
return globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
}
function errorMessage(error: unknown): string {
return error instanceof EnhancementApiError
? error.message
: "Something went wrong while enhancing this image.";
}
function saveResult(item: BatchItem): void {
if (!item.result) return;
const downloadUrl = URL.createObjectURL(item.result.blob);
const anchor = document.createElement("a");
anchor.href = downloadUrl;
anchor.download = item.result.metadata.filename;
document.body.append(anchor);
anchor.click();
anchor.remove();
window.setTimeout(() => URL.revokeObjectURL(downloadUrl), 1_000);
}
export function BatchEnhancer({ accessToken, requiresAuth, onBusyChange }: BatchEnhancerProps) {
const [items, setItems] = useState<BatchItem[]>([]);
const [settings, setSettings] = useState<EnhancementSettings>(DEFAULT_SETTINGS);
const [selectedItemId, setSelectedItemId] = useState<string | null>(null);
const [isProcessing, setIsProcessing] = useState(false);
const [isPackaging, setIsPackaging] = useState(false);
const [isStopRequested, setIsStopRequested] = useState(false);
const [isPreviewing, setIsPreviewing] = useState(false);
const [isDragging, setIsDragging] = useState(false);
const [progress, setProgress] = useState({ current: 0, total: 0 });
const [archiveProgress, setArchiveProgress] = useState({ current: 0, total: 0 });
const [zoomState, setZoomState] = useState<{ itemId: string | null; value: number }>({ itemId: null, value: 1 });
const [notice, setNotice] = useState<string | null>(null);
const [requestStatus, setRequestStatus] = useState<string | null>(null);
const fileInput = useRef<HTMLInputElement>(null);
const packagingRef = useRef(false);
const previewingRef = useRef(false);
const stopAfterCurrentRef = useRef(false);
const itemsRef = useRef(items);
const archiveUrlRef = useRef<string | null>(null);
const archiveUrlTimerRef = useRef<number | null>(null);
const isBusy = isProcessing || isPackaging || isPreviewing;
const selected = items.find((item) => item.id === selectedItemId) ?? items[0] ?? null;
const zoom = zoomState.itemId === selected?.id ? zoomState.value : 1;
const completedCount = items.filter((item) => item.status === "complete").length;
const failedCount = items.filter((item) => item.status === "failed").length;
const pendingCount = items.filter((item) => item.status === "queued" || item.status === "failed").length;
const expectedOutputPixels = items.reduce((total, item) => total + (item.result
? item.result.metadata.enhancedWidth * item.result.metadata.enhancedHeight
: item.width * item.height * settings.scale * settings.scale), 0);
const exceedsOutputBudget = expectedOutputPixels > MAX_BATCH_OUTPUT_PIXELS;
useEffect(() => {
onBusyChange(isBusy);
}, [isBusy, onBusyChange]);
useEffect(() => {
itemsRef.current = items;
}, [items]);
useEffect(() => () => {
for (const item of itemsRef.current) {
URL.revokeObjectURL(item.previewUrl);
if (item.resultPreviewUrl) URL.revokeObjectURL(item.resultPreviewUrl);
}
if (archiveUrlTimerRef.current !== null) {
window.clearTimeout(archiveUrlTimerRef.current);
}
if (archiveUrlRef.current) URL.revokeObjectURL(archiveUrlRef.current);
}, []);
function releaseArchiveDownload() {
if (archiveUrlTimerRef.current !== null) {
window.clearTimeout(archiveUrlTimerRef.current);
archiveUrlTimerRef.current = null;
}
if (archiveUrlRef.current) {
URL.revokeObjectURL(archiveUrlRef.current);
archiveUrlRef.current = null;
}
}
function saveArchive(blob: Blob) {
releaseArchiveDownload();
const downloadUrl = URL.createObjectURL(blob);
archiveUrlRef.current = downloadUrl;
const anchor = document.createElement("a");
anchor.href = downloadUrl;
anchor.download = `sharpify-enhanced-${new Date().toISOString().replace(/[:.]/g, "-")}.zip`;
document.body.append(anchor);
anchor.click();
anchor.remove();
archiveUrlTimerRef.current = window.setTimeout(() => {
if (archiveUrlRef.current === downloadUrl) archiveUrlRef.current = null;
archiveUrlTimerRef.current = null;
URL.revokeObjectURL(downloadUrl);
}, 60_000);
}
async function addFiles(fileList: FileList | File[]) {
if (isBusy || packagingRef.current || previewingRef.current || isProcessing) return;
const files = Array.from(fileList);
if (files.length === 0) return;
const availableSlots = MAX_BATCH_FILES - items.length;
if (availableSlots <= 0) {
setNotice(`A batch can contain up to ${MAX_BATCH_FILES} images. Remove an image before adding more.`);
return;
}
const rejected: string[] = [];
const additions: BatchItem[] = [];
let capacityReached = false;
previewingRef.current = true;
setIsPreviewing(true);
onBusyChange(true);
setNotice(null);
try {
for (const file of files) {
if (additions.length >= availableSlots) {
capacityReached = true;
break;
}
const validation = validateImageFile(file);
if (validation) {
rejected.push(`${file.name || "Selected file"}: ${validation}`);
continue;
}
const previewUrl = URL.createObjectURL(file);
try {
const image = new window.Image();
image.src = previewUrl;
await image.decode();
if (image.naturalWidth < 1 || image.naturalHeight < 1) {
throw new Error("The image has invalid dimensions.");
}
additions.push({
id: makeId(),
file,
width: image.naturalWidth,
height: image.naturalHeight,
previewUrl,
resultPreviewUrl: null,
result: null,
status: "queued",
error: null,
});
} catch {
URL.revokeObjectURL(previewUrl);
rejected.push(`${file.name || "Selected file"}: This image could not be previewed.`);
}
}
if (additions.length > 0) {
releaseArchiveDownload();
setItems((current) => [...current, ...additions]);
setSelectedItemId((current) => current ?? additions[0].id);
}
const visibleRejections = rejected.slice(0, capacityReached ? 2 : 3);
if (capacityReached) {
visibleRejections.push(`The ${MAX_BATCH_FILES}-image batch limit was reached; some selected images were not added.`);
}
setNotice(visibleRejections.length > 0 ? visibleRejections.join(" ") : null);
} finally {
previewingRef.current = false;
setIsPreviewing(false);
onBusyChange(false);
}
}
async function processQueue() {
if (isBusy || packagingRef.current || isProcessing || previewingRef.current || pendingCount === 0) return;
const queue = items.filter((item) => item.status === "queued" || item.status === "failed");
if (queue.length === 0) return;
releaseArchiveDownload();
stopAfterCurrentRef.current = false;
setIsStopRequested(false);
setNotice(null);
setIsProcessing(true);
setProgress({ current: 0, total: queue.length });
onBusyChange(true);
setRequestStatus(null);
let encounteredFailure = false;
let stoppedAfterCurrent = false;
let requiresSignIn = false;
try {
for (const [index, item] of queue.entries()) {
if (stopAfterCurrentRef.current) {
stoppedAfterCurrent = true;
break;
}
setProgress({ current: index + 1, total: queue.length });
setSelectedItemId(item.id);
setItems((current) => current.map((candidate) => candidate.id === item.id
? { ...candidate, status: "processing", error: null }
: candidate));
try {
const result = await enhanceImage(item.file, settings, {
width: item.width,
height: item.height,
}, accessToken, (requestProgress) => {
if (requestProgress.stage === "queued") {
setRequestStatus(requestProgress.position
? `Waiting in shared GPU queue · position ${requestProgress.position}`
: "Waiting for the shared GPU queue…");
} else if (requestProgress.stage === "working") {
setRequestStatus("Enhancing with Real-ESRGAN…");
}
});
const resultPreviewUrl = URL.createObjectURL(result.blob);
setItems((current) => current.map((candidate) => candidate.id === item.id
? { ...candidate, result, resultPreviewUrl, status: "complete", error: null }
: candidate));
} catch (error) {
encounteredFailure = true;
setItems((current) => current.map((candidate) => candidate.id === item.id
? { ...candidate, status: "failed", error: errorMessage(error) }
: candidate));
if (error instanceof EnhancementApiError && ["auth_required", "unauthorized"].includes(error.code ?? "")) {
requiresSignIn = true;
stoppedAfterCurrent = true;
break;
}
}
if (stopAfterCurrentRef.current) {
stoppedAfterCurrent = encounteredFailure || index < queue.length - 1;
break;
}
if (index < queue.length - 1) {
await new Promise<void>((resolve) => window.setTimeout(resolve, 0));
}
}
} finally {
setIsProcessing(false);
setIsStopRequested(false);
stopAfterCurrentRef.current = false;
setRequestStatus(null);
onBusyChange(false);
if (requiresSignIn) {
setNotice("Your Hugging Face sign-in expired. Sign in again, then retry the unfinished images.");
} else if (stoppedAfterCurrent) {
setNotice("Batch paused after the current image. Unfinished images remain available to continue or retry.");
} else if (encounteredFailure) {
setNotice("Some images could not be enhanced. Their individual errors are shown in the queue; run the batch again to retry them.");
}
}
}
async function downloadCompletedImages() {
if (isBusy || packagingRef.current) return;
const completed = items.filter((item) => item.status === "complete" && item.result);
if (completed.length === 0) return;
packagingRef.current = true;
setNotice(null);
setArchiveProgress({ current: 0, total: completed.length });
setIsPackaging(true);
onBusyChange(true);
try {
const archive = await createImageArchive(
completed.map((item) => ({ filename: item.result!.metadata.filename, blob: item.result!.blob })),
(current, total) => setArchiveProgress({ current, total }),
);
saveArchive(archive);
} catch {
setNotice("The ZIP could not be prepared. You can still download each completed image individually.");
} finally {
packagingRef.current = false;
setIsPackaging(false);
onBusyChange(false);
}
}
function requestStopAfterCurrent() {
if (!isProcessing || isStopRequested) return;
stopAfterCurrentRef.current = true;
setIsStopRequested(true);
}
function removeItem(id: string) {
if (isBusy || packagingRef.current) return;
const item = items.find((candidate) => candidate.id === id);
if (!item) return;
releaseArchiveDownload();
URL.revokeObjectURL(item.previewUrl);
if (item.resultPreviewUrl) URL.revokeObjectURL(item.resultPreviewUrl);
const remaining = items.filter((candidate) => candidate.id !== id);
setItems(remaining);
if (selectedItemId === id) setSelectedItemId(remaining[0]?.id ?? null);
if (fileInput.current) fileInput.current.value = "";
}
function clearBatch() {
if (isBusy || packagingRef.current) return;
releaseArchiveDownload();
for (const item of items) {
URL.revokeObjectURL(item.previewUrl);
if (item.resultPreviewUrl) URL.revokeObjectURL(item.resultPreviewUrl);
}
setItems([]);
setSelectedItemId(null);
setNotice(null);
if (fileInput.current) fileInput.current.value = "";
}
function handleInputChange(event: ChangeEvent<HTMLInputElement>) {
const files = Array.from(event.currentTarget.files ?? []);
event.currentTarget.value = "";
if (files.length > 0) void addFiles(files);
}
function handleDrop(event: DragEvent<HTMLDivElement>) {
event.preventDefault();
setIsDragging(false);
if (event.dataTransfer.files.length > 0) void addFiles(event.dataTransfer.files);
}
function changeSetting<K extends keyof EnhancementSettings>(key: K, value: EnhancementSettings[K]) {
setSettings((current) => ({ ...current, [key]: value }));
}
function changeZoom(value: number) {
if (selected) setZoomState({ itemId: selected.id, value });
}
const selectedResult = selected?.result ?? null;
return (
<div
className={`studio-layout batch-layout${isDragging ? " is-dragging" : ""}`}
onDragEnter={(event) => {
if (event.dataTransfer.types.includes("Files")) setIsDragging(true);
}}
onDragOver={(event) => {
if (event.dataTransfer.types.includes("Files")) event.preventDefault();
}}
onDragLeave={(event) => {
if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setIsDragging(false);
}}
onDrop={handleDrop}
>
<input
ref={fileInput}
aria-label="Choose images for batch enhancement"
className="visually-hidden-input"
accept="image/jpeg,image/png,image/webp,.jpg,.jpeg,.png,.webp"
disabled={isBusy}
multiple
onChange={handleInputChange}
type="file"
/>
<section className="image-workspace" aria-label="Batch image workspace">
<div className="workspace-toolbar">
<div className="workspace-status">
<span className={items.length > 0 ? "status-dot" : "status-dot status-dot-muted"} />
{isProcessing
? `PROCESSING ${progress.current} / ${progress.total}`
: items.length > 0
? `${completedCount} OF ${items.length} COMPLETE`
: "BATCH QUEUE"}
</div>
<div className="workspace-actions">
<span className="local-badge"><ImageIcon size={13} /> UP TO {MAX_BATCH_FILES} IMAGES</span>
<button className="text-button" onClick={() => fileInput.current?.click()} type="button" disabled={isBusy || items.length >= MAX_BATCH_FILES}>
<Plus size={14} /> Add images
</button>
{items.length > 0 && (
<button className="icon-button" aria-label="Clear batch" onClick={clearBatch} type="button" disabled={isBusy}>
<Trash2 size={14} />
</button>
)}
</div>
</div>
<div className="image-stage batch-image-stage">
{selected && selectedResult && selected.resultPreviewUrl ? (
<ComparisonViewer
key={selected.id}
afterUrl={selected.resultPreviewUrl}
beforeUrl={selected.previewUrl}
metadata={selectedResult.metadata}
onZoomChange={changeZoom}
zoom={zoom}
/>
) : selected ? (
<div className="original-preview">
<div className="original-preview-image">
<Image src={selected.previewUrl} alt={`Original image: ${selected.file.name}`} fill sizes="(max-width: 960px) 100vw, 65vw" unoptimized />
<span className="comparison-label label-before">ORIGINAL</span>
</div>
<div className="original-file-card">
<span className="file-card-icon"><ImageIcon size={16} /></span>
<span className="file-card-name"><strong>{selected.file.name}</strong><small>{selected.width.toLocaleString()} × {selected.height.toLocaleString()} px · {formatFileSize(selected.file.size)}</small></span>
<span className="file-card-ready">{selected.status === "processing" ? "WORKING" : selected.status === "failed" ? "FAILED" : "QUEUED"}</span>
</div>
</div>
) : (
<div className={`batch-dropzone${isDragging ? " is-dragging" : ""}`}>
<div className="upload-icon-wrap"><FileImage size={24} strokeWidth={1.6} /></div>
<p className="upload-kicker">PROCESS A SMALL SET TOGETHER</p>
<h3>Add images to your batch</h3>
<p className="upload-description">Choose up to {MAX_BATCH_FILES} JPG, PNG, or WEBP images. Each image is enhanced in sequence.</p>
<button className="button button-dark upload-button" type="button" onClick={() => fileInput.current?.click()} disabled={isBusy}>
<Upload size={17} /> Choose images
</button>
<div className="upload-file-types"><span>JPG</span><span>PNG</span><span>WEBP</span><i /> <span>20 MB each</span></div>
<div className="upload-privacy"><Check size={14} /> Images stay in this session and are not permanently stored.</div>
{isDragging && <div className="drop-overlay"><FileImage size={19} /> Drop images to add them</div>}
</div>
)}
</div>
{selectedResult && (
<div className="result-file-row">
<div className="result-file-label"><span className="result-check"><Check size={13} /></span><span><strong>{selectedResult.metadata.filename}</strong><small>{formatFileSize(selectedResult.blob.size)} · Full-resolution output</small></span></div>
<button className="text-button result-start-over" type="button" onClick={() => selected && saveResult(selected)}><Download size={14} /> Download</button>
</div>
)}
{items.length > 0 && (
<div className="batch-queue-section">
<div className="batch-queue-heading"><strong>Image queue</strong><span>{completedCount} complete · {pendingCount} remaining</span></div>
{completedCount > 0 && (
<div className="batch-archive-row">
<button className="text-button batch-archive-button" onClick={() => void downloadCompletedImages()} type="button" disabled={isBusy}>
{isPackaging ? <LoaderCircle className="spin" size={14} /> : <Download size={14} />}
<span aria-live="polite">{isPackaging
? `Preparing ZIP · ${archiveProgress.current} of ${archiveProgress.total} images`
: `Download ${completedCount} completed ${completedCount === 1 ? "image" : "images"} as ZIP`}</span>
</button>
</div>
)}
{isProcessing && (
<div className="batch-progress">
<div className="batch-progress-status" role="status" aria-live="polite">
<LoaderCircle className="spin" size={15} />
<span>{requestStatus || `Enhancing image ${progress.current} of ${progress.total}. Images run one at a time to protect available memory.`}</span>
</div>
<button className="batch-progress-stop" onClick={requestStopAfterCurrent} type="button" disabled={isStopRequested}>
{isStopRequested ? "Stopping…" : "Stop after this image"}
</button>
</div>
)}
<ul className="batch-queue-list" aria-label="Batch enhancement progress">
{items.map((item) => (
<li className={`batch-queue-item${selected?.id === item.id ? " is-selected" : ""}`} key={item.id}>
<button
aria-pressed={selected?.id === item.id}
className="batch-queue-select"
onClick={() => setSelectedItemId(item.id)}
type="button"
>
<span className="batch-thumbnail"><Image src={item.previewUrl} alt="" fill sizes="52px" unoptimized /></span>
<span className="batch-file-copy"><strong title={item.file.name}>{item.file.name}</strong><small>{formatFileSize(item.file.size)} · {item.width.toLocaleString()} × {item.height.toLocaleString()}</small></span>
<span className={`batch-status batch-status-${item.status}`}>
{item.status === "processing" && <LoaderCircle className="spin" size={11} />}
{item.status === "queued" ? "QUEUED" : item.status === "processing" ? "WORKING" : item.status === "complete" ? "DONE" : "FAILED"}
</span>
</button>
{item.error && <p className="batch-item-error">{item.error}</p>}
<div className="batch-item-actions">
{item.result && (
<button aria-label={`Download ${item.result.metadata.filename}`} className="icon-button" onClick={() => saveResult(item)} type="button">
<Download size={14} />
</button>
)}
<button aria-label={`Remove ${item.file.name}`} className="icon-button batch-remove-button" onClick={() => removeItem(item.id)} type="button" disabled={isBusy}>
<X size={13} />
</button>
</div>
</li>
))}
</ul>
</div>
)}
{notice && (
<div className="error-notice" role="alert"><span className="error-mark">!</span><span>{notice}</span><button aria-label="Dismiss message" onClick={() => setNotice(null)} type="button"><X size={14} /></button></div>
)}
</section>
<aside className="settings-panel" aria-label="Batch enhancement settings">
<div className="settings-heading">
<div><p className="section-kicker">ONE SET OF SETTINGS</p><h3>Batch settings</h3></div>
<span className="settings-step">02 <span>/ 02</span></span>
</div>
<fieldset className="settings-field" disabled={isBusy}>
<legend>Upscale size</legend>
<p className="field-caption">Applied to every image in the next run.</p>
<div className="scale-options" role="group" aria-label="Batch upscale factor">
{([2, 4] as const).map((scale: UpscaleFactor) => (
<button aria-pressed={settings.scale === scale} className={`scale-option${settings.scale === scale ? " is-selected" : ""}`} key={scale} onClick={() => changeSetting("scale", scale)} type="button">
<span className="scale-option-top">{scale}×</span><span className="scale-option-bottom">{scale === 2 ? "Balanced" : "Maximum detail"}</span>
{settings.scale === scale && <span className="selected-mark"><Check size={11} /></span>}
</button>
))}
</div>
</fieldset>
<fieldset className="settings-field format-field" disabled={isBusy}>
<legend>Save format</legend>
<p className="field-caption">Choose one output format for this run.</p>
<div className="format-options" role="group" aria-label="Batch output image format">
{formats.map((format) => (
<button aria-pressed={settings.outputFormat === format.value} className={`format-option${settings.outputFormat === format.value ? " is-selected" : ""}`} key={format.value} onClick={() => changeSetting("outputFormat", format.value)} type="button">
<span className="format-label">{format.label}</span><span className="format-detail">{format.detail}</span>
</button>
))}
</div>
</fieldset>
<div className="batch-settings-summary">
<strong>{items.length} / {MAX_BATCH_FILES} images</strong>
<span>{completedCount} enhanced{failedCount > 0 ? ` · ${failedCount} failed` : ""}</span>
</div>
<p className={`batch-output-budget${exceedsOutputBudget ? " is-over-limit" : ""}`}>
Batch output budget: {Math.ceil(expectedOutputPixels / 1_000_000)}M / {MAX_BATCH_OUTPUT_PIXELS / 1_000_000}M pixels
</p>
<button className="button button-dark enhance-button" type="button" onClick={() => void processQueue()} disabled={items.length === 0 || pendingCount === 0 || isBusy || exceedsOutputBudget || (requiresAuth && !accessToken)}>
{isBusy ? <LoaderCircle className="spin" size={17} /> : <WandSparkles size={17} />}
{isPreviewing ? "Preparing images…" : isProcessing ? "Enhancing batch…" : requiresAuth && !accessToken ? "Sign in to enhance" : exceedsOutputBudget ? "Reduce batch output size" : pendingCount > 0 ? `${failedCount > 0 ? "Retry and enhance" : "Enhance"} ${pendingCount} image${pendingCount === 1 ? "" : "s"}` : "Batch complete"}
</button>
<p className="settings-footnote"><CircleHelp size={13} /> Images run sequentially. A failed image won’t stop the rest.</p>
<p className="batch-memory-note">For stability, a batch is limited to 64 million total output pixels. Remove images or lower the upscale to stay within the limit. Completed files stay in this browser tab until removed or cleared.</p>
</aside>
</div>
);
}