page.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. "use client";
  2. import { useState, useEffect, useCallback } from "react";
  3. import { useRouter } from "next/navigation";
  4. import { Header } from "@/components/layout";
  5. import { AppLayout } from "@/components/layout";
  6. import { Button } from "@/components/ui/button";
  7. import { Card, CardContent } from "@/components/ui/card";
  8. import { Badge } from "@/components/ui/badge";
  9. import { apiClient, type JobDetailsResponse } from "@/lib/api";
  10. import {
  11. Loader2,
  12. Download,
  13. RefreshCw,
  14. Calendar,
  15. Image as ImageIcon,
  16. Maximize2,
  17. ArrowUp,
  18. } from "lucide-react";
  19. import { downloadAuthenticatedImage } from "@/lib/utils";
  20. interface GalleryImage {
  21. jobId: string;
  22. filename: string;
  23. url: string;
  24. thumbnailUrl: string;
  25. prompt?: string;
  26. negativePrompt?: string;
  27. width?: number;
  28. height?: number;
  29. steps?: number;
  30. cfgScale?: number;
  31. seed?: string;
  32. model?: string;
  33. createdAt: string;
  34. status: string;
  35. }
  36. interface ImageModalProps {
  37. image: GalleryImage | null;
  38. isOpen: boolean;
  39. onClose: () => void;
  40. }
  41. function ImageModal({ image, isOpen, onClose }: ImageModalProps) {
  42. if (!isOpen || !image) return null;
  43. const handleBackdropClick = (e: React.MouseEvent) => {
  44. if (e.target === e.currentTarget) {
  45. onClose();
  46. }
  47. };
  48. return (
  49. <div
  50. className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-sm p-4"
  51. onClick={handleBackdropClick}
  52. >
  53. <div className="relative max-w-[95vw] max-h-[95vh] flex flex-col w-full">
  54. {/* Image container with responsive sizing */}
  55. <div className="flex items-center justify-center bg-muted/50 p-4 rounded-lg flex-1 min-h-0">
  56. <div className="relative w-full h-full flex items-center justify-center">
  57. <img
  58. src={image.url}
  59. alt="Generated image"
  60. className="max-w-full max-h-full object-contain rounded-lg shadow-lg"
  61. style={{
  62. width: 'auto',
  63. height: 'auto',
  64. maxWidth: '100%',
  65. maxHeight: '100%'
  66. }}
  67. />
  68. </div>
  69. </div>
  70. </div>
  71. </div>
  72. );
  73. }
  74. function GalleryGrid() {
  75. const router = useRouter();
  76. const [images, setImages] = useState<GalleryImage[]>([]);
  77. const [loading, setLoading] = useState(true);
  78. const [error, setError] = useState<string | null>(null);
  79. const [selectedImage, setSelectedImage] = useState<GalleryImage | null>(null);
  80. const [isModalOpen, setIsModalOpen] = useState(false);
  81. const [sortBy, setSortBy] = useState<"newest" | "oldest">("newest");
  82. const loadGalleryImages = useCallback(async () => {
  83. try {
  84. setLoading(true);
  85. setError(null);
  86. console.log("Gallery: Loading images...");
  87. // Get queue status to find all completed jobs
  88. const queueStatus = await apiClient.getQueueStatus();
  89. console.log("Gallery: Queue status:", queueStatus);
  90. const completedJobs = queueStatus.jobs.filter(
  91. (job) => job.status === "completed",
  92. );
  93. console.log("Gallery: Completed jobs:", completedJobs);
  94. const galleryImages: GalleryImage[] = [];
  95. // Fetch individual job details to get output information
  96. for (const job of completedJobs) {
  97. const jobId = job.request_id || job.id || "";
  98. if (!jobId) continue;
  99. try {
  100. // Get detailed job information including outputs
  101. console.log(`Gallery: Fetching details for job ${jobId}`);
  102. const jobDetails: JobDetailsResponse =
  103. await apiClient.getJobStatus(jobId);
  104. console.log(`Gallery: Job ${jobId} details:`, jobDetails);
  105. // API response has outputs nested in job object
  106. if (
  107. jobDetails.job &&
  108. jobDetails.job.outputs &&
  109. jobDetails.job.outputs.length > 0
  110. ) {
  111. for (const output of jobDetails.job.outputs) {
  112. const filename = output.filename;
  113. const url = apiClient.getImageUrl(jobId, filename);
  114. // Create thumbnail URL (we'll use the same URL but let the browser handle scaling)
  115. const thumbnailUrl = url;
  116. galleryImages.push({
  117. jobId,
  118. filename,
  119. url,
  120. thumbnailUrl,
  121. prompt: jobDetails.job.prompt || "", // Get prompt from job details
  122. negativePrompt: "", // Job info doesn't include negative prompt
  123. width: undefined, // Job info doesn't include request details
  124. height: undefined, // Job info doesn't include request details
  125. steps: undefined, // Job info doesn't include request details
  126. cfgScale: undefined, // Job info doesn't include request details
  127. seed: undefined, // Job info doesn't include request details
  128. model: "Unknown", // Job info doesn't include request details
  129. createdAt:
  130. jobDetails.job.created_at || new Date().toISOString(),
  131. status: jobDetails.job.status,
  132. });
  133. }
  134. }
  135. } catch (err) {
  136. console.warn(`Failed to fetch details for job ${jobId}:`, err);
  137. // Continue with other jobs even if one fails
  138. }
  139. }
  140. // Sort images
  141. galleryImages.sort((a, b) => {
  142. const dateA = new Date(a.createdAt).getTime();
  143. const dateB = new Date(b.createdAt).getTime();
  144. return sortBy === "newest" ? dateB - dateA : dateA - dateB;
  145. });
  146. console.log("Gallery: Final images array:", galleryImages);
  147. setImages(galleryImages);
  148. } catch (err) {
  149. console.error("Gallery: Error loading images:", err);
  150. setError(
  151. err instanceof Error ? err.message : "Failed to load gallery images",
  152. );
  153. } finally {
  154. setLoading(false);
  155. }
  156. }, [sortBy]);
  157. useEffect(() => {
  158. loadGalleryImages();
  159. }, [sortBy, loadGalleryImages]);
  160. const handleImageClick = (image: GalleryImage) => {
  161. setSelectedImage(image);
  162. setIsModalOpen(true);
  163. };
  164. const handleModalClose = () => {
  165. setIsModalOpen(false);
  166. setSelectedImage(null);
  167. };
  168. const handleDownload = (image: GalleryImage, e: React.MouseEvent) => {
  169. e.stopPropagation();
  170. const authToken = localStorage.getItem("auth_token");
  171. const unixUser = localStorage.getItem("unix_user");
  172. downloadAuthenticatedImage(
  173. image.url,
  174. `gallery-${image.jobId}-${image.filename}`,
  175. authToken || undefined,
  176. unixUser || undefined,
  177. );
  178. };
  179. const handleUpscale = (image: GalleryImage, e: React.MouseEvent) => {
  180. e.stopPropagation();
  181. // Navigate to upscaler page with image URL as query parameter
  182. router.push(`/upscaler?imageUrl=${encodeURIComponent(image.url)}`);
  183. };
  184. const formatDate = (dateString: string) => {
  185. return new Date(dateString).toLocaleDateString("en-US", {
  186. year: "numeric",
  187. month: "short",
  188. day: "numeric",
  189. hour: "2-digit",
  190. minute: "2-digit",
  191. });
  192. };
  193. if (loading) {
  194. return (
  195. <AppLayout>
  196. <Header title="Gallery" description="Browse your generated images" />
  197. <div className="container mx-auto p-6">
  198. <div className="flex items-center justify-center h-96">
  199. <div className="flex items-center gap-2">
  200. <Loader2 className="h-6 w-6 animate-spin" />
  201. <span>Loading gallery...</span>
  202. </div>
  203. </div>
  204. </div>
  205. </AppLayout>
  206. );
  207. }
  208. if (error) {
  209. return (
  210. <AppLayout>
  211. <Header title="Gallery" description="Browse your generated images" />
  212. <div className="container mx-auto p-6">
  213. <div className="flex flex-col items-center justify-center h-96 gap-4">
  214. <div className="text-destructive text-center">
  215. <p className="text-lg font-medium">Error loading gallery</p>
  216. <p className="text-sm">{error}</p>
  217. </div>
  218. <Button onClick={loadGalleryImages} variant="outline">
  219. <RefreshCw className="h-4 w-4 mr-2" />
  220. Try Again
  221. </Button>
  222. </div>
  223. </div>
  224. </AppLayout>
  225. );
  226. }
  227. return (
  228. <AppLayout>
  229. <Header title="Gallery" description="Browse your generated images" />
  230. <div className="container mx-auto p-6">
  231. {/* Controls */}
  232. <div className="flex items-center justify-between mb-6">
  233. <div className="flex items-center gap-4">
  234. <h2 className="text-2xl font-bold">
  235. {images.length} {images.length === 1 ? "Image" : "Images"}
  236. </h2>
  237. <Button onClick={loadGalleryImages} variant="outline" size="sm">
  238. <RefreshCw className="h-4 w-4 mr-2" />
  239. Refresh
  240. </Button>
  241. </div>
  242. <div className="flex items-center gap-2">
  243. <span className="text-sm text-muted-foreground">Sort by:</span>
  244. <Button
  245. variant={sortBy === "newest" ? "default" : "outline"}
  246. size="sm"
  247. onClick={() => setSortBy("newest")}
  248. >
  249. Newest
  250. </Button>
  251. <Button
  252. variant={sortBy === "oldest" ? "default" : "outline"}
  253. size="sm"
  254. onClick={() => setSortBy("oldest")}
  255. >
  256. Oldest
  257. </Button>
  258. </div>
  259. </div>
  260. {/* Gallery Grid */}
  261. {images.length === 0 ? (
  262. <div className="flex flex-col items-center justify-center h-96 border-2 border-dashed border-border rounded-lg">
  263. <ImageIcon className="h-12 w-12 text-muted-foreground mb-4" />
  264. <h3 className="text-lg font-medium text-muted-foreground mb-2">
  265. No images found
  266. </h3>
  267. <p className="text-sm text-muted-foreground text-center max-w-md">
  268. Generate some images first using the Text to Image, Image to
  269. Image, or Inpainting tools.
  270. </p>
  271. </div>
  272. ) : (
  273. <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-3">
  274. {images.map((image: GalleryImage, index: number) => (
  275. <Card
  276. key={`${image.jobId}-${image.filename}-${index}`}
  277. className="group cursor-pointer overflow-hidden hover:shadow-lg transition-all duration-200 hover:scale-105"
  278. onClick={() => handleImageClick(image)}
  279. >
  280. <CardContent className="p-0">
  281. <div className="relative aspect-square">
  282. {/* Thumbnail with hover effect */}
  283. <div className="relative w-full h-full overflow-hidden">
  284. <img
  285. src={image.thumbnailUrl}
  286. alt={`Generated image ${index + 1}`}
  287. className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-110"
  288. loading="lazy"
  289. />
  290. </div>
  291. {/* Date badge */}
  292. <div className="absolute top-2 left-2">
  293. <Badge
  294. variant="secondary"
  295. className="text-xs bg-black/70 text-white border-none"
  296. >
  297. {formatDate(image.createdAt)}
  298. </Badge>
  299. </div>
  300. {/* Model indicator */}
  301. {image.model && image.model !== "Unknown" && (
  302. <div className="absolute bottom-2 left-2">
  303. <Badge
  304. variant="outline"
  305. className="text-xs max-w-20 truncate bg-black/70 text-white border-white/20"
  306. >
  307. {image.model}
  308. </Badge>
  309. </div>
  310. )}
  311. </div>
  312. {/* Image info */}
  313. <div className="p-2 bg-background">
  314. <div className="flex items-center justify-between text-xs text-muted-foreground">
  315. <span className="truncate">
  316. {image.width && image.height
  317. ? `${image.width}×${image.height}`
  318. : "Unknown size"}
  319. </span>
  320. <div className="flex items-center gap-1">
  321. <Calendar className="h-3 w-3" />
  322. <span className="text-xs">
  323. {new Date(image.createdAt).toLocaleDateString()}
  324. </span>
  325. </div>
  326. </div>
  327. {image.prompt && (
  328. <p className="mt-1 text-xs text-muted-foreground line-clamp-2">
  329. {image.prompt}
  330. </p>
  331. )}
  332. {/* Action buttons */}
  333. <div className="grid grid-cols-3 gap-1 mt-2">
  334. <Button
  335. size="sm"
  336. variant="outline"
  337. className="h-7 text-xs px-1"
  338. onClick={(e: React.MouseEvent) => {
  339. e.stopPropagation();
  340. handleImageClick(image);
  341. }}
  342. title="View full size"
  343. >
  344. <Maximize2 className="h-3 w-3" />
  345. </Button>
  346. <Button
  347. size="sm"
  348. variant="outline"
  349. className="h-7 text-xs px-1"
  350. onClick={(e: React.MouseEvent) => handleDownload(image, e)}
  351. title="Download image"
  352. >
  353. <Download className="h-3 w-3" />
  354. </Button>
  355. <Button
  356. size="sm"
  357. variant="outline"
  358. className="h-7 text-xs px-1"
  359. onClick={(e: React.MouseEvent) => handleUpscale(image, e)}
  360. title="Upscale image"
  361. >
  362. <ArrowUp className="h-3 w-3" />
  363. </Button>
  364. </div>
  365. </div>
  366. </CardContent>
  367. </Card>
  368. ))}
  369. </div>
  370. )}
  371. {/* Image Modal */}
  372. <ImageModal
  373. image={selectedImage}
  374. isOpen={isModalOpen}
  375. onClose={handleModalClose}
  376. />
  377. </div>
  378. </AppLayout>
  379. );
  380. }
  381. export default function GalleryPage() {
  382. return <GalleryGrid />;
  383. }