page.tsx 14 KB

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