capiiii commited on
Commit
7fc7bd3
·
1 Parent(s): d93bff5

feat(image): 添加图片预览和多任务并发生成

Browse files

- 新增 ImageLightbox 组件,支持全屏预览、左右切换、键盘导航和下载
- 将单一 isGenerating 布尔锁改为 Set<string> 跟踪多个并发任务
- 侧栏为生成中的会话显示 loading 指示器
- 底部显示进行中任务计数

web/src/app/image/page.tsx CHANGED
@@ -5,6 +5,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
5
  import { ArrowUp, LoaderCircle, MessageSquarePlus, Trash2 } from "lucide-react";
6
  import { toast } from "sonner";
7
 
 
8
  import { Button } from "@/components/ui/button";
9
  import { Input } from "@/components/ui/input";
10
  import {
@@ -96,8 +97,10 @@ export default function ImagePage() {
96
  const [conversations, setConversations] = useState<ImageConversation[]>([]);
97
  const [selectedConversationId, setSelectedConversationId] = useState<string | null>(null);
98
  const [isLoadingHistory, setIsLoadingHistory] = useState(true);
99
- const [isGenerating, setIsGenerating] = useState(false);
100
  const [availableQuota, setAvailableQuota] = useState("加载中");
 
 
101
  const resultsViewportRef = useRef<HTMLDivElement>(null);
102
  const textareaRef = useRef<HTMLTextAreaElement>(null);
103
 
@@ -106,6 +109,38 @@ export default function ImagePage() {
106
  () => conversations.find((item) => item.id === selectedConversationId) ?? null,
107
  [conversations, selectedConversationId],
108
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
 
110
  useEffect(() => {
111
  let cancelled = false;
@@ -165,7 +200,7 @@ export default function ImagePage() {
165
  }, [loadQuota]);
166
 
167
  useEffect(() => {
168
- if (!selectedConversation && !isGenerating) {
169
  return;
170
  }
171
 
@@ -173,7 +208,7 @@ export default function ImagePage() {
173
  top: resultsViewportRef.current.scrollHeight,
174
  behavior: "smooth",
175
  });
176
- }, [selectedConversation, isGenerating]);
177
 
178
  const persistConversation = async (conversation: ImageConversation) => {
179
  setConversations((prev) => {
@@ -260,7 +295,7 @@ export default function ImagePage() {
260
  status: "generating",
261
  };
262
 
263
- setIsGenerating(true);
264
  setSelectedConversationId(conversationId);
265
  setImagePrompt("");
266
 
@@ -339,7 +374,7 @@ export default function ImagePage() {
339
  });
340
  toast.error(message);
341
  } finally {
342
- setIsGenerating(false);
343
  }
344
  };
345
 
@@ -379,6 +414,7 @@ export default function ImagePage() {
379
  ) : (
380
  conversations.map((conversation) => {
381
  const active = conversation.id === selectedConversationId;
 
382
  return (
383
  <div
384
  key={conversation.id}
@@ -394,7 +430,10 @@ export default function ImagePage() {
394
  onClick={() => setSelectedConversationId(conversation.id)}
395
  className="block w-full pr-8 text-left"
396
  >
397
- <div className="truncate text-sm font-semibold">{conversation.title}</div>
 
 
 
398
  <div className={cn("mt-1 text-xs", active ? "text-stone-500" : "text-stone-400")}>
399
  {formatConversationTime(conversation.createdAt)}
400
  </div>
@@ -471,14 +510,20 @@ export default function ImagePage() {
471
  {selectedConversation.images.map((image, index) => (
472
  <div key={image.id} className="break-inside-avoid overflow-hidden rounded-[22px]">
473
  {image.status === "success" && image.b64_json ? (
474
- <Image
475
- src={`data:image/png;base64,${image.b64_json}`}
476
- alt={`Generated result ${index + 1}`}
477
- width={1024}
478
- height={1024}
479
- unoptimized
480
- className="block h-auto w-full"
481
- />
 
 
 
 
 
 
482
  ) : image.status === "error" ? (
483
  <div className="flex min-h-[320px] items-center justify-center bg-rose-50 px-6 py-8 text-center text-sm leading-6 text-rose-600">
484
  {image.error || "生成失败"}
@@ -526,9 +571,7 @@ export default function ImagePage() {
526
  onKeyDown={(event) => {
527
  if (event.key === "Enter" && !event.shiftKey) {
528
  event.preventDefault();
529
- if (!isGenerating) {
530
- void handleGenerateImage();
531
- }
532
  }
533
  }}
534
  className="min-h-[148px] resize-none rounded-[32px] border-0 bg-transparent px-6 pt-6 pb-20 text-[15px] leading-7 text-stone-900 shadow-none placeholder:text-stone-400 focus-visible:ring-0"
@@ -539,6 +582,12 @@ export default function ImagePage() {
539
  <div className="rounded-full bg-stone-100 px-3 py-2 text-xs font-medium text-stone-600">
540
  剩余额度 {availableQuota}
541
  </div>
 
 
 
 
 
 
542
  <Select value={imageModel} onValueChange={(value) => setImageModel(value as ImageModel)}>
543
  <SelectTrigger className="h-10 w-[164px] rounded-full border-stone-200 bg-white text-sm font-medium text-stone-700 shadow-none focus-visible:ring-0">
544
  <SelectValue />
@@ -569,11 +618,11 @@ export default function ImagePage() {
569
  <button
570
  type="button"
571
  onClick={() => void handleGenerateImage()}
572
- disabled={isGenerating}
573
  className="inline-flex size-11 shrink-0 items-center justify-center rounded-full bg-stone-950 text-white transition hover:bg-stone-800 disabled:cursor-not-allowed disabled:bg-stone-300"
574
  aria-label="生成图片"
575
  >
576
- {isGenerating ? <LoaderCircle className="size-4 animate-spin" /> : <ArrowUp className="size-4" />}
577
  </button>
578
  </div>
579
  </div>
@@ -581,6 +630,14 @@ export default function ImagePage() {
581
  </div>
582
  </div>
583
  </section>
 
 
 
 
 
 
 
 
584
  </>
585
  );
586
  }
 
5
  import { ArrowUp, LoaderCircle, MessageSquarePlus, Trash2 } from "lucide-react";
6
  import { toast } from "sonner";
7
 
8
+ import { ImageLightbox } from "@/components/image-lightbox";
9
  import { Button } from "@/components/ui/button";
10
  import { Input } from "@/components/ui/input";
11
  import {
 
97
  const [conversations, setConversations] = useState<ImageConversation[]>([]);
98
  const [selectedConversationId, setSelectedConversationId] = useState<string | null>(null);
99
  const [isLoadingHistory, setIsLoadingHistory] = useState(true);
100
+ const [generatingIds, setGeneratingIds] = useState<Set<string>>(new Set());
101
  const [availableQuota, setAvailableQuota] = useState("加载中");
102
+ const [lightboxOpen, setLightboxOpen] = useState(false);
103
+ const [lightboxIndex, setLightboxIndex] = useState(0);
104
  const resultsViewportRef = useRef<HTMLDivElement>(null);
105
  const textareaRef = useRef<HTMLTextAreaElement>(null);
106
 
 
109
  () => conversations.find((item) => item.id === selectedConversationId) ?? null,
110
  [conversations, selectedConversationId],
111
  );
112
+ const isSelectedGenerating = selectedConversationId !== null && generatingIds.has(selectedConversationId);
113
+ const hasAnyGenerating = generatingIds.size > 0;
114
+
115
+ const addGeneratingId = useCallback((id: string) => {
116
+ setGeneratingIds((prev) => new Set(prev).add(id));
117
+ }, []);
118
+ const removeGeneratingId = useCallback((id: string) => {
119
+ setGeneratingIds((prev) => {
120
+ const next = new Set(prev);
121
+ next.delete(id);
122
+ return next;
123
+ });
124
+ }, []);
125
+
126
+ const lightboxImages = useMemo(
127
+ () =>
128
+ (selectedConversation?.images ?? [])
129
+ .filter((img): img is StoredImage & { b64_json: string } => img.status === "success" && !!img.b64_json)
130
+ .map((img) => ({ id: img.id, src: `data:image/png;base64,${img.b64_json}` })),
131
+ [selectedConversation],
132
+ );
133
+
134
+ const openLightbox = useCallback(
135
+ (imageId: string) => {
136
+ const idx = lightboxImages.findIndex((img) => img.id === imageId);
137
+ if (idx >= 0) {
138
+ setLightboxIndex(idx);
139
+ setLightboxOpen(true);
140
+ }
141
+ },
142
+ [lightboxImages],
143
+ );
144
 
145
  useEffect(() => {
146
  let cancelled = false;
 
200
  }, [loadQuota]);
201
 
202
  useEffect(() => {
203
+ if (!selectedConversation && !isSelectedGenerating) {
204
  return;
205
  }
206
 
 
208
  top: resultsViewportRef.current.scrollHeight,
209
  behavior: "smooth",
210
  });
211
+ }, [selectedConversation, isSelectedGenerating]);
212
 
213
  const persistConversation = async (conversation: ImageConversation) => {
214
  setConversations((prev) => {
 
295
  status: "generating",
296
  };
297
 
298
+ addGeneratingId(conversationId);
299
  setSelectedConversationId(conversationId);
300
  setImagePrompt("");
301
 
 
374
  });
375
  toast.error(message);
376
  } finally {
377
+ removeGeneratingId(conversationId);
378
  }
379
  };
380
 
 
414
  ) : (
415
  conversations.map((conversation) => {
416
  const active = conversation.id === selectedConversationId;
417
+ const generating = generatingIds.has(conversation.id);
418
  return (
419
  <div
420
  key={conversation.id}
 
430
  onClick={() => setSelectedConversationId(conversation.id)}
431
  className="block w-full pr-8 text-left"
432
  >
433
+ <div className="flex items-center gap-1.5 truncate text-sm font-semibold">
434
+ {generating && <LoaderCircle className="size-3.5 shrink-0 animate-spin text-stone-400" />}
435
+ <span className="truncate">{conversation.title}</span>
436
+ </div>
437
  <div className={cn("mt-1 text-xs", active ? "text-stone-500" : "text-stone-400")}>
438
  {formatConversationTime(conversation.createdAt)}
439
  </div>
 
510
  {selectedConversation.images.map((image, index) => (
511
  <div key={image.id} className="break-inside-avoid overflow-hidden rounded-[22px]">
512
  {image.status === "success" && image.b64_json ? (
513
+ <button
514
+ type="button"
515
+ onClick={() => openLightbox(image.id)}
516
+ className="group block w-full cursor-zoom-in"
517
+ >
518
+ <Image
519
+ src={`data:image/png;base64,${image.b64_json}`}
520
+ alt={`Generated result ${index + 1}`}
521
+ width={1024}
522
+ height={1024}
523
+ unoptimized
524
+ className="block h-auto w-full transition duration-200 group-hover:brightness-90"
525
+ />
526
+ </button>
527
  ) : image.status === "error" ? (
528
  <div className="flex min-h-[320px] items-center justify-center bg-rose-50 px-6 py-8 text-center text-sm leading-6 text-rose-600">
529
  {image.error || "生成失败"}
 
571
  onKeyDown={(event) => {
572
  if (event.key === "Enter" && !event.shiftKey) {
573
  event.preventDefault();
574
+ void handleGenerateImage();
 
 
575
  }
576
  }}
577
  className="min-h-[148px] resize-none rounded-[32px] border-0 bg-transparent px-6 pt-6 pb-20 text-[15px] leading-7 text-stone-900 shadow-none placeholder:text-stone-400 focus-visible:ring-0"
 
582
  <div className="rounded-full bg-stone-100 px-3 py-2 text-xs font-medium text-stone-600">
583
  剩余额度 {availableQuota}
584
  </div>
585
+ {hasAnyGenerating && (
586
+ <div className="flex items-center gap-1.5 rounded-full bg-amber-50 px-3 py-2 text-xs font-medium text-amber-700">
587
+ <LoaderCircle className="size-3 animate-spin" />
588
+ {generatingIds.size} 个任务进行中
589
+ </div>
590
+ )}
591
  <Select value={imageModel} onValueChange={(value) => setImageModel(value as ImageModel)}>
592
  <SelectTrigger className="h-10 w-[164px] rounded-full border-stone-200 bg-white text-sm font-medium text-stone-700 shadow-none focus-visible:ring-0">
593
  <SelectValue />
 
618
  <button
619
  type="button"
620
  onClick={() => void handleGenerateImage()}
621
+ disabled={!imagePrompt.trim()}
622
  className="inline-flex size-11 shrink-0 items-center justify-center rounded-full bg-stone-950 text-white transition hover:bg-stone-800 disabled:cursor-not-allowed disabled:bg-stone-300"
623
  aria-label="生成图片"
624
  >
625
+ <ArrowUp className="size-4" />
626
  </button>
627
  </div>
628
  </div>
 
630
  </div>
631
  </div>
632
  </section>
633
+
634
+ <ImageLightbox
635
+ images={lightboxImages}
636
+ currentIndex={lightboxIndex}
637
+ open={lightboxOpen}
638
+ onOpenChange={setLightboxOpen}
639
+ onIndexChange={setLightboxIndex}
640
+ />
641
  </>
642
  );
643
  }
web/src/components/image-lightbox.tsx ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useCallback, useEffect } from "react";
4
+ import Image from "next/image";
5
+ import * as DialogPrimitive from "@radix-ui/react-dialog";
6
+ import { ChevronLeft, ChevronRight, Download, X } from "lucide-react";
7
+
8
+ import { cn } from "@/lib/utils";
9
+
10
+ type LightboxImage = {
11
+ id: string;
12
+ src: string;
13
+ };
14
+
15
+ type ImageLightboxProps = {
16
+ images: LightboxImage[];
17
+ currentIndex: number;
18
+ open: boolean;
19
+ onOpenChange: (open: boolean) => void;
20
+ onIndexChange: (index: number) => void;
21
+ };
22
+
23
+ export function ImageLightbox({
24
+ images,
25
+ currentIndex,
26
+ open,
27
+ onOpenChange,
28
+ onIndexChange,
29
+ }: ImageLightboxProps) {
30
+ const current = images[currentIndex];
31
+ const hasPrev = currentIndex > 0;
32
+ const hasNext = currentIndex < images.length - 1;
33
+
34
+ const goPrev = useCallback(() => {
35
+ if (hasPrev) onIndexChange(currentIndex - 1);
36
+ }, [hasPrev, currentIndex, onIndexChange]);
37
+
38
+ const goNext = useCallback(() => {
39
+ if (hasNext) onIndexChange(currentIndex + 1);
40
+ }, [hasNext, currentIndex, onIndexChange]);
41
+
42
+ useEffect(() => {
43
+ if (!open) return;
44
+
45
+ const handleKeyDown = (e: KeyboardEvent) => {
46
+ if (e.key === "ArrowLeft") {
47
+ e.preventDefault();
48
+ goPrev();
49
+ } else if (e.key === "ArrowRight") {
50
+ e.preventDefault();
51
+ goNext();
52
+ }
53
+ };
54
+
55
+ window.addEventListener("keydown", handleKeyDown);
56
+ return () => window.removeEventListener("keydown", handleKeyDown);
57
+ }, [open, goPrev, goNext]);
58
+
59
+ const handleDownload = useCallback(() => {
60
+ if (!current) return;
61
+ const link = document.createElement("a");
62
+ link.href = current.src;
63
+ link.download = `image-${current.id}.png`;
64
+ link.click();
65
+ }, [current]);
66
+
67
+ if (!current) return null;
68
+
69
+ return (
70
+ <DialogPrimitive.Root open={open} onOpenChange={onOpenChange}>
71
+ <DialogPrimitive.Portal>
72
+ <DialogPrimitive.Overlay className="fixed inset-0 z-50 bg-black/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0" />
73
+ <DialogPrimitive.Content
74
+ className="fixed inset-0 z-50 flex items-center justify-center outline-none"
75
+ onPointerDownOutside={(e) => e.preventDefault()}
76
+ >
77
+ {/* toolbar */}
78
+ <div className="absolute top-4 right-4 z-10 flex items-center gap-2">
79
+ {images.length > 1 && (
80
+ <span className="rounded-full bg-black/50 px-3 py-1.5 text-xs font-medium text-white/90">
81
+ {currentIndex + 1} / {images.length}
82
+ </span>
83
+ )}
84
+ <button
85
+ type="button"
86
+ onClick={handleDownload}
87
+ className="inline-flex size-9 items-center justify-center rounded-full bg-black/50 text-white/90 transition hover:bg-black/70"
88
+ aria-label="下载图片"
89
+ >
90
+ <Download className="size-4" />
91
+ </button>
92
+ <DialogPrimitive.Close className="inline-flex size-9 items-center justify-center rounded-full bg-black/50 text-white/90 transition hover:bg-black/70">
93
+ <X className="size-4" />
94
+ <span className="sr-only">关闭</span>
95
+ </DialogPrimitive.Close>
96
+ </div>
97
+
98
+ {/* prev */}
99
+ {hasPrev && (
100
+ <button
101
+ type="button"
102
+ onClick={goPrev}
103
+ className="absolute left-4 z-10 inline-flex size-10 items-center justify-center rounded-full bg-black/40 text-white/90 transition hover:bg-black/60"
104
+ aria-label="上一张"
105
+ >
106
+ <ChevronLeft className="size-5" />
107
+ </button>
108
+ )}
109
+
110
+ {/* image */}
111
+ <div
112
+ className="flex max-h-[90vh] max-w-[90vw] items-center justify-center"
113
+ onClick={() => onOpenChange(false)}
114
+ >
115
+ <Image
116
+ src={current.src}
117
+ alt=""
118
+ width={1536}
119
+ height={1536}
120
+ unoptimized
121
+ className="max-h-[90vh] max-w-[90vw] rounded-lg object-contain"
122
+ onClick={(e) => e.stopPropagation()}
123
+ draggable={false}
124
+ />
125
+ </div>
126
+
127
+ {/* next */}
128
+ {hasNext && (
129
+ <button
130
+ type="button"
131
+ onClick={goNext}
132
+ className="absolute right-4 z-10 inline-flex size-10 items-center justify-center rounded-full bg-black/40 text-white/90 transition hover:bg-black/60"
133
+ aria-label="下一张"
134
+ >
135
+ <ChevronRight className="size-5" />
136
+ </button>
137
+ )}
138
+ </DialogPrimitive.Content>
139
+ </DialogPrimitive.Portal>
140
+ </DialogPrimitive.Root>
141
+ );
142
+ }