-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
428 lines (372 loc) · 12.3 KB
/
script.js
File metadata and controls
428 lines (372 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
// ==================== Configuration ====================
const CONFIG = {
apiUrl: "http://127.0.0.1:8045/v1",
apiKey: "sk-5dddd30292e943a2bb7a88e127a1917d",
model: "gemini-3-pro-image",
maxHistoryItems: 12,
};
// ==================== State Management ====================
const state = {
currentPrompt: "",
currentSize: "1024x1024",
generatedImages: [],
};
// ==================== DOM Elements ====================
const elements = {
form: document.getElementById("generatorForm"),
promptInput: document.getElementById("prompt"),
generateBtn: document.getElementById("generateBtn"),
emptyState: document.getElementById("emptyState"),
loadingState: document.getElementById("loadingState"),
resultState: document.getElementById("resultState"),
errorState: document.getElementById("errorState"),
resultImage: document.getElementById("resultImage"),
resultPrompt: document.getElementById("resultPrompt"),
resultSize: document.getElementById("resultSize"),
resultTime: document.getElementById("resultTime"),
errorMessage: document.getElementById("errorMessage"),
retryBtn: document.getElementById("retryBtn"),
downloadBtn: document.getElementById("downloadBtn"),
copyBtn: document.getElementById("copyBtn"),
galleryGrid: document.getElementById("galleryGrid"),
galleryEmpty: document.getElementById("galleryEmpty"),
clearGalleryBtn: document.getElementById("clearGalleryBtn"),
toast: document.getElementById("toast"),
toastText: document.getElementById("toastText"),
confirmModal: document.getElementById("confirmModal"),
confirmTitle: document.getElementById("confirmTitle"),
confirmMessage: document.getElementById("confirmMessage"),
confirmOk: document.getElementById("confirmOk"),
confirmCancel: document.getElementById("confirmCancel"),
};
// ==================== Utility Functions ====================
function showToast(message) {
elements.toastText.textContent = message;
elements.toast.classList.remove("hidden");
setTimeout(() => {
elements.toast.classList.add("hidden");
}, 3000);
}
// Custom confirm dialog
function showConfirm(title, message) {
return new Promise((resolve) => {
elements.confirmTitle.textContent = title;
elements.confirmMessage.textContent = message;
elements.confirmModal.classList.remove("hidden");
// 防止重复绑定事件
const handleOk = () => {
cleanup();
resolve(true);
};
const handleCancel = () => {
cleanup();
resolve(false);
};
const handleOverlayClick = (e) => {
if (e.target === elements.confirmModal) {
cleanup();
resolve(false);
}
};
const cleanup = () => {
elements.confirmModal.classList.add("hidden");
elements.confirmOk.removeEventListener("click", handleOk);
elements.confirmCancel.removeEventListener("click", handleCancel);
elements.confirmModal.removeEventListener("click", handleOverlayClick);
};
elements.confirmOk.addEventListener("click", handleOk);
elements.confirmCancel.addEventListener("click", handleCancel);
elements.confirmModal.addEventListener("click", handleOverlayClick);
});
}
function formatTime(date) {
const now = new Date();
const diff = now - date;
const seconds = Math.floor(diff / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
if (days > 0) return `${days}天前`;
if (hours > 0) return `${hours}小时前`;
if (minutes > 0) return `${minutes}分钟前`;
return "刚刚";
}
function setState(newState) {
// Hide all states
elements.emptyState.classList.add("hidden");
elements.loadingState.classList.add("hidden");
elements.resultState.classList.add("hidden");
elements.errorState.classList.add("hidden");
// Show the requested state
switch (newState) {
case "empty":
elements.emptyState.classList.remove("hidden");
break;
case "loading":
elements.loadingState.classList.remove("hidden");
break;
case "result":
elements.resultState.classList.remove("hidden");
break;
case "error":
elements.errorState.classList.remove("hidden");
break;
}
}
function saveToLocalStorage() {
try {
localStorage.setItem(
"generatedImages",
JSON.stringify(state.generatedImages)
);
} catch (error) {
console.error("Failed to save to localStorage:", error);
}
}
function loadFromLocalStorage() {
try {
const saved = localStorage.getItem("generatedImages");
if (saved) {
state.generatedImages = JSON.parse(saved);
renderGallery();
}
} catch (error) {
console.error("Failed to load from localStorage:", error);
}
}
// ==================== API Functions ====================
async function generateImage(prompt, size) {
const response = await fetch(`${CONFIG.apiUrl}/chat/completions`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${CONFIG.apiKey}`,
},
body: JSON.stringify({
model: CONFIG.model,
messages: [
{
role: "user",
content: prompt,
},
],
extra_body: {
size: size,
},
}),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(
errorData.error?.message ||
`HTTP ${response.status}: ${response.statusText}`
);
}
const data = await response.json();
if (!data.choices || !data.choices[0] || !data.choices[0].message) {
throw new Error("Invalid response format from API");
}
let imageContent = data.choices[0].message.content;
if (!imageContent) {
throw new Error("No image content in response");
}
// 解析 markdown 格式的图片链接: 
// 或者直接返回的 base64 data URL
let imageUrl = imageContent;
// 检查是否是 markdown 格式
const markdownImageRegex = /!\[.*?\]\((data:image\/[^)]+)\)/;
const match = imageContent.match(markdownImageRegex);
if (match && match[1]) {
// 提取 markdown 中的 data URL
imageUrl = match[1];
} else if (!imageContent.startsWith('data:image/') && !imageContent.startsWith('http')) {
// 如果既不是 data URL 也不是 http URL,可能是纯 base64
// 尝试添加 data URL 前缀
if (imageContent.match(/^[A-Za-z0-9+/=]+$/)) {
imageUrl = `data:image/png;base64,${imageContent}`;
}
}
return imageUrl;
}
// ==================== Image Generation ====================
async function handleGenerate(event) {
event.preventDefault();
const prompt = elements.promptInput.value.trim();
const sizeRadio = document.querySelector('input[name="size"]:checked');
const size = sizeRadio ? sizeRadio.value : "1024x1024";
if (!prompt) {
showToast("请输入图片描述");
return;
}
state.currentPrompt = prompt;
state.currentSize = size;
// Update UI
setState("loading");
elements.generateBtn.disabled = true;
elements.generateBtn.classList.add("loading");
try {
const startTime = Date.now();
const imageUrl = await generateImage(prompt, size);
const endTime = Date.now();
const duration = ((endTime - startTime) / 1000).toFixed(1);
// Display result
elements.resultImage.src = imageUrl;
elements.resultPrompt.textContent = prompt;
elements.resultSize.textContent = size;
elements.resultTime.textContent = `${duration}秒`;
setState("result");
// Save to history
const imageData = {
id: Date.now(),
prompt,
size,
url: imageUrl,
timestamp: new Date().toISOString(),
};
state.generatedImages.unshift(imageData);
// Keep only the latest items
if (state.generatedImages.length > CONFIG.maxHistoryItems) {
state.generatedImages = state.generatedImages.slice(
0,
CONFIG.maxHistoryItems
);
}
saveToLocalStorage();
renderGallery();
showToast("图片生成成功!");
} catch (error) {
console.error("Generation error:", error);
elements.errorMessage.textContent = error.message || "生成失败,请稍后重试";
setState("error");
showToast("生成失败");
} finally {
elements.generateBtn.disabled = false;
elements.generateBtn.classList.remove("loading");
}
}
// ==================== Gallery Functions ====================
function renderGallery() {
if (state.generatedImages.length === 0) {
elements.galleryGrid.innerHTML = "";
elements.galleryEmpty.classList.remove("hidden");
return;
}
elements.galleryEmpty.classList.add("hidden");
elements.galleryGrid.innerHTML = state.generatedImages
.map(
(image) => `
<div class="gallery-item" data-id="${image.id}">
<img src="${image.url}" alt="${
image.prompt
}" class="gallery-item-image" loading="lazy">
<div class="gallery-item-info">
<div class="gallery-item-prompt">${image.prompt}</div>
<div class="gallery-item-meta">
${image.size} • ${formatTime(new Date(image.timestamp))}
</div>
</div>
</div>
`
)
.join("");
// Add click handlers
document.querySelectorAll(".gallery-item").forEach((item) => {
item.addEventListener("click", () => {
const id = parseInt(item.dataset.id);
const image = state.generatedImages.find((img) => img.id === id);
if (image) {
displayImage(image);
// Scroll to result
document
.querySelector("#generator")
.scrollIntoView({ behavior: "smooth" });
}
});
});
}
function displayImage(imageData) {
elements.resultImage.src = imageData.url;
elements.resultPrompt.textContent = imageData.prompt;
elements.resultSize.textContent = imageData.size;
elements.resultTime.textContent = formatTime(new Date(imageData.timestamp));
setState("result");
}
async function clearGallery() {
const confirmed = await showConfirm(
"清空历史记录",
"确定要清空所有历史记录吗?此操作无法撤销。"
);
if (confirmed) {
state.generatedImages = [];
saveToLocalStorage();
renderGallery();
setState("empty");
showToast("历史记录已清空");
}
}
// ==================== Download & Copy Functions ====================
async function downloadImage() {
try {
const imageUrl = elements.resultImage.src;
const response = await fetch(imageUrl);
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `ai-image-${Date.now()}.png`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
showToast("图片下载成功");
} catch (error) {
console.error("Download error:", error);
showToast("下载失败");
}
}
async function copyImageUrl() {
try {
const imageUrl = elements.resultImage.src;
await navigator.clipboard.writeText(imageUrl);
showToast("链接已复制到剪贴板");
} catch (error) {
console.error("Copy error:", error);
showToast("复制失败");
}
}
// ==================== Event Listeners ====================
elements.form.addEventListener("submit", handleGenerate);
elements.retryBtn.addEventListener("click", handleGenerate);
elements.downloadBtn.addEventListener("click", downloadImage);
elements.copyBtn.addEventListener("click", copyImageUrl);
elements.clearGalleryBtn.addEventListener("click", clearGallery);
// Size card selection visual feedback
document.querySelectorAll(".size-card").forEach((card) => {
card.addEventListener("click", () => {
const radio = card.querySelector('input[type="radio"]');
if (radio) {
radio.checked = true;
}
});
});
// Smooth scroll for navigation links
document.querySelectorAll(".nav-link").forEach((link) => {
link.addEventListener("click", (e) => {
e.preventDefault();
const targetId = link.getAttribute("href");
const targetElement = document.querySelector(targetId);
if (targetElement) {
targetElement.scrollIntoView({ behavior: "smooth" });
}
});
});
// ==================== Initialization ====================
function init() {
loadFromLocalStorage();
setState("empty");
console.log("AI Image Generator initialized");
console.log(`API: ${CONFIG.apiUrl}`);
console.log(`Model: ${CONFIG.model}`);
}
// Start the application
init();