-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptions.js
More file actions
1407 lines (1226 loc) · 49.8 KB
/
Copy pathoptions.js
File metadata and controls
1407 lines (1226 loc) · 49.8 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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 本文件维护 ImgPrompt 设置页交互。
// 本次修改:将“禧哈哈灵感集”独立为单独的页面视图,点击顶部“ImgPrompt”标题即可在“图片转提示词”和“禧哈哈灵感集”两个独立视图间无缝切换。
// 具体修改点:新增页面切换逻辑(监听 #page-toggle 点击),在两个界面(#page-img2prompt 和 #page-xihaha)之间控制显示/隐藏。
// 历史修改接入“禧哈哈灵感集”配置,让设置页可保存管理员密码、默认分组和默认提示词,供生成结果面板的“保存本地”和“上传云端”使用;并修复抓取(图片/提示词/标题完整透传)与标题前缀移除。
// 历史修改点:新增灵感集表单字段读写、默认分组下拉选项自动加载和设置自动保存逻辑,移除不再需要的分组刷新代码。
const DEFAULT_SETTINGS = window.ImgPromptConfig.DEFAULT_SETTINGS;
const SETTINGS_I18N = window.ImgPromptConfig.SETTINGS_I18N;
const TRANSLATIONS = SETTINGS_I18N;
const PRESETS = window.ImgPromptConfig.USER_PROMPT_PRESETS;
const form = document.getElementById("settings-form");
const statusEl = document.getElementById("status");
const resetButton = document.getElementById("reset-defaults");
const customModeView = document.getElementById("custom-mode-view");
const customTitleInput = document.getElementById("customTitle");
const customPromptArea = document.getElementById("userPrompt");
const customSaveBtn = document.getElementById("btn-custom-save");
const customCancelBtn = document.getElementById("btn-custom-cancel");
const customDeleteBtn = document.getElementById("btn-custom-delete");
const addCustomBtn = document.getElementById("btn-add-custom");
let isHydrating = true;
let customTemplates = {};
let currentEditingId = null;
// 禧哈哈灵感集:记录最近一次“抓取”的结果,供保存本地 / 上传云端复用
let lastGrabbedImages = [];
let lastGrabbedTitle = "";
let lastGrabbedPageUrl = "";
init();
const presetChipsContainer = document.querySelector(".preset-chips");
presetChipsContainer.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
const chip = e.target.closest(".preset-chip");
if (!chip) return;
if (isHydrating) return;
const presetKey = chip.getAttribute("data-preset");
if (presetKey === "+add") {
enterCreateCustomMode();
return;
}
// Smart stacking logic
const basePrompt = ImgPromptConfig.BASE_USER_PROMPT;
if (PRESETS && PRESETS[presetKey]) {
if (presetKey === "general") {
// General: only base prompt
form.userPrompt.value = basePrompt;
} else {
// Scene preset: base + scene focus
form.userPrompt.value = basePrompt + PRESETS[presetKey];
}
// Directly highlight the clicked preset button
const allChips = document.querySelectorAll(".preset-chip");
allChips.forEach((chip) => chip.classList.remove("active"));
chip.classList.add("active");
// Hide custom mode view
showBuiltinMode();
handleAutoSave();
return;
}
if (presetKey.startsWith("custom_")) {
const customId = presetKey;
if (customTemplates[customId]) {
form.userPrompt.value = customTemplates[customId].prompt;
// Directly highlight the clicked custom preset button
const allChips = document.querySelectorAll(".preset-chip");
allChips.forEach((chip) => chip.classList.remove("active"));
chip.classList.add("active");
// Show custom edit mode
showCustomEditMode(customId);
handleAutoSave();
}
}
});
function showBuiltinMode() {
customModeView.style.display = "none";
currentEditingId = null;
}
function showCustomEditMode(id) {
customModeView.style.display = "flex";
customDeleteBtn.style.display = "block";
const tpl = customTemplates[id];
if (tpl) {
customTitleInput.value = tpl.title || "";
currentEditingId = id;
}
}
function showCustomCreateMode() {
customModeView.style.display = "flex";
customDeleteBtn.style.display = "none";
}
function enterCreateCustomMode() {
const allChips = document.querySelectorAll(".preset-chip");
allChips.forEach((chip) => chip.classList.remove("active"));
currentEditingId = null;
customTitleInput.value = "";
// 默认使用通用预设的提示词
form.userPrompt.value = PRESETS["general"] || "";
showCustomCreateMode();
// 同步更新标题输入框,让用户知道这是通用预设
const lang = document.querySelector('input[name="uiLanguage"]:checked')?.value || "zh";
customTitleInput.placeholder =
lang === "zh" ? "基于通用预设的自定义提示词..." : "Custom prompt based on General preset...";
}
function updateActiveChip(currentPrompt, isFromPresetClick = false) {
const allChips = document.querySelectorAll(".preset-chip");
allChips.forEach((chip) => chip.classList.remove("active"));
let found = false;
if (PRESETS) {
const match = Object.entries(PRESETS).find(([_, text]) => text === currentPrompt);
if (match) {
const chipToActivate = document.querySelector(`.preset-chip[data-preset="${match[0]}"]`);
if (chipToActivate) chipToActivate.classList.add("active");
showBuiltinMode();
found = true;
return;
}
}
const customMatch = Object.entries(customTemplates).find(
([_, tpl]) => tpl.prompt === currentPrompt,
);
if (customMatch) {
const chipToActivate = document.querySelector(`.preset-chip[data-preset="${customMatch[0]}"]`);
if (chipToActivate) chipToActivate.classList.add("active");
showCustomEditMode(customMatch[0]);
found = true;
return;
}
// Only enter create mode if explicitly requested (e.g., from +add button)
// Don't auto-enter create mode when clicking presets
if (!found && !isFromPresetClick) {
showCustomCreateMode();
} else if (!found && isFromPresetClick) {
showBuiltinMode();
}
}
customSaveBtn.addEventListener("click", async () => {
const uiLang = form.uiLanguage ? form.uiLanguage.value : "zh";
const title =
customTitleInput.value.trim() || TRANSLATIONS[uiLang]["custom-title-label"] || "Template";
const text = form.userPrompt.value.trim();
if (!text) {
setStatus("⚠️");
return;
}
const id = currentEditingId || "custom_" + Date.now();
customTemplates[id] = { title, prompt: text };
await chrome.storage.local.set({ customTemplates });
renderCustomChips();
updateActiveChip(text);
handleAutoSave();
setStatus("✅ Saved");
});
customDeleteBtn.addEventListener("click", async () => {
if (currentEditingId && customTemplates[currentEditingId]) {
delete customTemplates[currentEditingId];
await chrome.storage.local.set({ customTemplates });
renderCustomChips();
form.userPrompt.value = PRESETS["general"] || "";
updateActiveChip(form.userPrompt.value);
handleAutoSave();
setStatus("🗑️ Deleted");
}
});
customCancelBtn.addEventListener("click", async () => {
// 隐藏自定义编辑视图
customModeView.style.display = "none";
// 恢复到通用预设
form.userPrompt.value = PRESETS["general"] || "";
updateActiveChip(form.userPrompt.value);
// 重置编辑状态
currentEditingId = null;
customDeleteBtn.style.display = "none";
// 保存恢复后的设置
await handleAutoSave();
});
function renderCustomChips() {
const currentCustomChips = document.querySelectorAll(".preset-chip[data-preset^='custom_']");
currentCustomChips.forEach((chip) => chip.remove());
const container = document.querySelector(".preset-chips");
const addBtn = document.getElementById("btn-add-custom");
Object.entries(customTemplates).forEach(([id, tpl]) => {
const btn = document.createElement("button");
btn.type = "button";
btn.className = "preset-chip";
btn.setAttribute("data-preset", id);
btn.textContent = `⚙️ ${tpl.title}`;
if (container && addBtn) {
container.insertBefore(btn, addBtn);
}
});
}
async function init() {
const stored = await chrome.storage.local.get(["customTemplates"]);
if (stored.customTemplates) {
customTemplates = stored.customTemplates;
}
renderCustomChips();
const settings = await chrome.storage.local.get(Object.keys(DEFAULT_SETTINGS));
const merged = {
...DEFAULT_SETTINGS,
...settings,
};
fillForm(merged);
applyLanguage(merged.uiLanguage || "zh");
// Display extension version
const versionEl = document.getElementById("version-display");
if (versionEl) {
const version = chrome.runtime.getManifest().version;
versionEl.textContent = `v${version}`;
}
isHydrating = false;
loadHistory();
// Listen for history updates from background
chrome.runtime.onMessage.addListener((message) => {
if (message.type === "history:updated") {
loadHistory();
}
});
// Initialize custom dropdown
initCustomDropdown();
// Load inspiration categories into the default-group select (fire-and-forget)
loadXihahaCategories();
// 绑定“抓取当前页面”按钮
const grabBtn = document.getElementById("xihahaGrabBtn");
if (grabBtn) {
grabBtn.addEventListener("click", () => grabCurrentPageImages());
}
// 绑定“保存本地 / 上传云端”按钮(两个功能相互独立,均可独立触发)
const saveLocalBtn = document.getElementById("xihahaSaveLocalBtn");
if (saveLocalBtn) {
saveLocalBtn.addEventListener("click", () => handleSaveLocal());
}
const uploadCloudBtn = document.getElementById("xihahaUploadCloudBtn");
if (uploadCloudBtn) {
uploadCloudBtn.addEventListener("click", () => handleUploadCloud());
}
// 默认分组:自定义下拉组件(暗色主题,非原生select)
const groupSelectContainer = document.getElementById("xihahaDefaultGroupSelect");
const groupTrigger = document.getElementById("xihahaDefaultGroupTrigger");
const groupDropdown = document.getElementById("xihahaDefaultGroupDropdown");
if (groupSelectContainer && groupTrigger) {
groupTrigger.addEventListener("click", (e) => {
e.stopPropagation();
const isOpening = !groupSelectContainer.classList.contains("open");
groupSelectContainer.classList.toggle("open");
if (isOpening && groupDropdown) {
// 用 fixed 定位,脱离父容器
const rect = groupTrigger.getBoundingClientRect();
groupDropdown.style.top = `${rect.bottom + 6}px`;
groupDropdown.style.left = `${rect.left}px`;
groupDropdown.style.width = `${Math.max(rect.width, 110)}px`;
}
});
document.addEventListener("click", (e) => {
if (!groupSelectContainer.contains(e.target)) {
groupSelectContainer.classList.remove("open");
}
});
}
// 绑定页面切换逻辑
const pageToggle = document.getElementById("page-toggle");
const pageXihaha = document.getElementById("page-xihaha");
const pageImg2prompt = document.getElementById("page-img2prompt");
const pageSubtitle = document.getElementById("page-subtitle");
const headerActions = document.getElementById("header-actions");
if (pageToggle && pageXihaha && pageImg2prompt) {
pageToggle.addEventListener("click", () => {
const isXihaha = pageXihaha.style.display !== "none";
if (isXihaha) {
// 切换回 Img2Prompt
pageXihaha.style.display = "none";
pageImg2prompt.style.display = "grid";
if (pageSubtitle) {
const uiLang = document.querySelector('input[name="uiLanguage"]:checked')?.value || "zh";
pageSubtitle.textContent =
TRANSLATIONS[uiLang]?.["imgprompt-subtitle"] || "Image to Prompt";
}
if (headerActions) headerActions.style.display = "flex";
} else {
// 切换到 禧哈哈灵感集
pageXihaha.style.display = "block";
pageImg2prompt.style.display = "none";
if (pageSubtitle) pageSubtitle.textContent = "禧哈哈灵感集";
if (headerActions) headerActions.style.display = "none";
}
});
}
}
// 抓取当前浏览器标签页的页面图片并渲染到设置页网格
async function grabCurrentPageImages() {
const grid = document.getElementById("xihahaImageGrid");
const count = document.getElementById("xihahaImageCount");
const btn = document.getElementById("xihahaGrabBtn");
if (!grid || !btn) return;
const originalText = btn.textContent;
btn.textContent = "抓取中...";
btn.disabled = true;
try {
const response = await chrome.runtime.sendMessage({ type: "xihaha:collect-page-images" });
if (!response?.ok || !Array.isArray(response.images)) {
throw new Error(response?.error || "抓取失败");
}
renderXihahaImages(response.images);
// 记录抓取结果,供“保存本地 / 上传云端”复用
lastGrabbedImages = response.images || [];
lastGrabbedTitle = String(response.title || "").trim();
lastGrabbedPageUrl = String(response.pageUrl || "").trim();
// 强制自动填入当前抓取的新标题和提示词
const titleEl = document.getElementById("xihahaDefaultTitle");
if (titleEl && lastGrabbedTitle) {
titleEl.value = lastGrabbedTitle;
}
const promptEl = document.getElementById("xihahaDefaultPrompt");
if (promptEl && response.prompt) {
promptEl.value = response.prompt;
}
// 自动根据提示词和标题中的关键词匹配分组
const combinedText = ((lastGrabbedTitle || "") + " " + (response.prompt || "")).toLowerCase();
const dropdown = document.getElementById("xihahaDefaultGroupDropdown");
if (dropdown && combinedText) {
const options = Array.from(dropdown.querySelectorAll(".custom-select-option"));
let matchedCategory = null;
for (const opt of options) {
const val = opt.getAttribute("data-value");
if (val && val !== "未分组" && combinedText.includes(val.toLowerCase())) {
matchedCategory = opt;
break; // 匹配到第一个包含的分类即停止
}
}
if (matchedCategory) {
matchedCategory.click(); // 触发点击,更新选中的分类并高亮
}
}
} catch (error) {
grid.innerHTML = "";
const empty = document.createElement("div");
empty.className = "xihaha-collector-empty";
empty.textContent = "抓取失败:" + (error instanceof Error ? error.message : String(error));
grid.appendChild(empty);
if (count) count.textContent = "0 张";
} finally {
btn.textContent = originalText;
btn.disabled = false;
}
}
// 渲染页面图片网格(设置页禧哈哈灵感集区域)
function renderXihahaImages(images) {
const grid = document.getElementById("xihahaImageGrid");
const count = document.getElementById("xihahaImageCount");
if (!grid) return;
grid.textContent = "";
if (count) count.textContent = images.length + " 张";
if (images.length === 0) {
const empty = document.createElement("div");
empty.className = "xihaha-collector-empty";
empty.textContent = "当前页面没有可抓取的图片(需要宽度≥120、高度≥80)。";
grid.appendChild(empty);
return;
}
images.forEach((image) => {
const img = document.createElement("img");
img.src = image.src;
img.alt = image.alt || "";
img.loading = "lazy";
img.title = image.alt || image.src;
img.addEventListener("click", () => {
grid.querySelectorAll("img").forEach((el) => el.classList.remove("selected"));
img.classList.add("selected");
const urlInput = document.getElementById("xihahaImageUrl");
if (urlInput) {
urlInput.value = image.src;
urlInput.dispatchEvent(new Event("input", { bubbles: true }));
}
});
grid.appendChild(img);
});
// Auto-select the first image if available
if (images.length > 0) {
const firstImg = grid.querySelector("img");
if (firstImg) {
firstImg.click();
}
}
}
async function loadXihahaCategories() {
const trigger = document.getElementById("xihahaDefaultGroupTrigger");
const dropdown = document.getElementById("xihahaDefaultGroupDropdown");
if (!trigger || !dropdown) return;
try {
const response = await chrome.runtime.sendMessage({ type: "xihaha:get-categories" });
if (!response?.ok || !Array.isArray(response.categories)) return;
// 保留"未分组"固定项,将云端分类插入
response.categories
.map((category) => String(category || "").trim())
.filter(Boolean)
.forEach((category) => {
if (category === "未分组") return;
// 避免重复
if (
Array.from(dropdown.querySelectorAll(".custom-select-option")).some(
(o) => o.getAttribute("data-value") === category,
)
)
return;
const option = document.createElement("div");
option.className = "custom-select-option";
option.setAttribute("data-value", category);
option.textContent = category;
dropdown.appendChild(option);
});
// 绑定新选项的点击事件(关闭下拉并更新显示)
dropdown.querySelectorAll(".custom-select-option").forEach((opt) => {
opt.addEventListener("click", () => {
const val = opt.getAttribute("data-value");
const text = opt.textContent;
// 更新视觉状态
dropdown
.querySelectorAll(".custom-select-option")
.forEach((o) => o.classList.remove("selected"));
opt.classList.add("selected");
trigger.textContent = text;
trigger.setAttribute("data-value", val);
// 关闭下拉
document.getElementById("xihahaDefaultGroupSelect")?.classList.remove("open");
});
});
// 回填之前保存的分组值
const stored = await chrome.storage.local.get(["xihahaDefaultGroup"]);
const savedGroup = String(stored.xihahaDefaultGroup || "").trim();
if (savedGroup) {
const matchingOption = dropdown.querySelector(
`.custom-select-option[data-value="${savedGroup}"]`,
);
if (matchingOption) {
matchingOption.click(); // 复用上面的点击逻辑
}
}
} catch (error) {
console.error("[ImgPrompt] Failed to load categories:", error);
}
}
// 当前选中的分组(从自定义下拉组件读取,支持自定义项)
function getSelectedCategory() {
const trigger = document.getElementById("xihahaDefaultGroupTrigger");
const value = trigger?.getAttribute("data-value") || "未分组";
return value || "未分组";
}
// 组装一条灵感数据,供“保存本地 / 上传云端”使用(标题仅保留用户填写/抓取到的内容,不拼接任何前缀)
async function buildInspirationPayload() {
const settings = await chrome.storage.local.get(Object.keys(DEFAULT_SETTINGS));
const titleEl = document.getElementById("xihahaDefaultTitle");
const titleBase = (titleEl?.value || "").trim();
const title = titleBase || lastGrabbedTitle || "";
const prompt = (document.getElementById("xihahaDefaultPrompt")?.value || "").trim();
const imageUrlInput = (document.getElementById("xihahaImageUrl")?.value || "").trim();
const imageUrl = imageUrlInput || lastGrabbedImages[0]?.src || "";
return {
title,
category: getSelectedCategory(),
prompt,
imageUrl,
pageTitle: lastGrabbedTitle,
pageUrl: lastGrabbedPageUrl,
adminPassword: settings.xihahaAdminPassword || "",
};
}
function showXihahaToast(message, type = "info") {
let toast = document.getElementById("xihaha-toast");
if (!toast) {
toast = document.createElement("div");
toast.id = "xihaha-toast";
toast.style.cssText =
"position:fixed;left:50%;bottom:32px;transform:translateX(-50%);z-index:99999;" +
"max-width:82%;padding:10px 16px;border-radius:10px;font-size:13px;line-height:1.45;" +
"box-shadow:0 8px 24px rgba(0,0,0,0.35);color:#fff;opacity:0;transition:opacity .2s ease;text-align:center;";
document.body.appendChild(toast);
}
const bg =
type === "error"
? "rgba(220,38,38,0.96)"
: type === "success"
? "rgba(16,138,94,0.96)"
: "rgba(30,41,59,0.96)";
toast.style.background = bg;
toast.textContent = message;
requestAnimationFrame(() => {
toast.style.opacity = "1";
});
clearTimeout(showXihahaToast.timer);
showXihahaToast.timer = setTimeout(() => {
toast.style.opacity = "0";
}, 3400);
}
// 保存本地:写入本扩展的 chrome.storage.local,与云端完全独立、离线可用
async function handleSaveLocal() {
const btn = document.getElementById("xihahaSaveLocalBtn");
if (!btn) return;
const original = btn.textContent;
btn.disabled = true;
btn.textContent = "保存中…";
try {
const payload = await buildInspirationPayload();
const response = await chrome.runtime.sendMessage({ type: "xihaha:save-local", payload });
if (!response?.ok) throw new Error(response?.error || "保存失败");
showXihahaToast("已保存本地(扩展本地库,并尝试同步到桌面端「我的灵感」)。", "success");
} catch (error) {
showXihahaToast(
"保存本地失败:" + (error instanceof Error ? error.message : String(error)),
"error",
);
} finally {
btn.disabled = false;
btn.textContent = original;
}
}
// 上传云端:经 Cloudflare Worker 写入 Supabase + R2,桌面端从云端读取即可刷新
async function handleUploadCloud() {
const btn = document.getElementById("xihahaUploadCloudBtn");
if (!btn) return;
const original = btn.textContent;
btn.disabled = true;
btn.textContent = "上传中…";
try {
const payload = await buildInspirationPayload();
const response = await chrome.runtime.sendMessage({ type: "xihaha:upload-cloud", payload });
if (!response?.ok) throw new Error(response?.error || "上传失败");
showXihahaToast("已上传云端(Supabase + Cloudflare),桌面端将从云端刷新显示。", "success");
} catch (error) {
showXihahaToast(
"上传云端失败:" + (error instanceof Error ? error.message : String(error)),
"error",
);
} finally {
btn.disabled = false;
btn.textContent = original;
}
}
async function loadHistory() {
const response = await chrome.runtime.sendMessage({ type: "history:get" });
if (response?.ok && response.history) {
renderHistory(response.history);
}
}
function renderHistory(history) {
const container = document.getElementById("history-list");
const emptyEl = document.getElementById("history-empty");
const clearBtn = document.getElementById("btn-clear-history");
if (!history || history.length === 0) {
emptyEl.style.display = "block";
clearBtn.style.display = "none";
const items = container.querySelectorAll(".history-item");
items.forEach((item) => item.remove());
return;
}
emptyEl.style.display = "none";
clearBtn.style.display = "block";
const items = container.querySelectorAll(".history-item");
items.forEach((item) => item.remove());
history.forEach((item) => {
const el = createHistoryItem(item);
container.appendChild(el);
});
}
function buildHistoryStructuredPreview(prompts, lang = "zh") {
if (!prompts) return "";
const labels =
lang === "en"
? {
aspectRatio: "Aspect Ratio",
background: "Background",
subject: "Subject",
surrounding: "Surrounding Elements",
composition: "Composition",
text: "Text",
style: "Style",
lighting: "Lighting",
color: "Color Palette",
}
: {
aspectRatio: "宽高比",
background: "背景",
subject: "主体",
surrounding: "环绕元素",
composition: "构图",
text: "文字",
style: "风格",
lighting: "光线",
color: "色彩",
};
const parts = [];
if (prompts.image_type) parts.push(String(prompts.image_type).trim());
if (prompts.aspect_ratio)
parts.push(`${labels.aspectRatio}: ${String(prompts.aspect_ratio).trim()}`);
if (prompts.background) parts.push(`${labels.background}: ${String(prompts.background).trim()}`);
if (prompts.subject) {
const subject = prompts.subject;
const subjectParts = [
subject.identity,
subject.appearance,
subject.clothing,
subject.posture,
subject.position,
]
.filter(Boolean)
.map((value) => String(value).trim());
if (subjectParts.length) {
parts.push(`${labels.subject}: ${subjectParts.join(", ")}`);
}
}
if (prompts.surrounding_elements)
parts.push(`${labels.surrounding}: ${String(prompts.surrounding_elements).trim()}`);
if (prompts.composition)
parts.push(`${labels.composition}: ${String(prompts.composition).trim()}`);
if (prompts.text_content) parts.push(`${labels.text}: ${String(prompts.text_content).trim()}`);
if (prompts.style) parts.push(`${labels.style}: ${String(prompts.style).trim()}`);
if (prompts.lighting) parts.push(`${labels.lighting}: ${String(prompts.lighting).trim()}`);
if (prompts.color_palette) parts.push(`${labels.color}: ${String(prompts.color_palette).trim()}`);
return parts.join(" ");
}
function buildHistoryJsonPreview(prompts) {
if (!prompts) return "";
const jsonData = {};
const keys = [
"image_type",
"aspect_ratio",
"background",
"subject",
"surrounding_elements",
"composition",
"text_content",
"style",
"lighting",
"color_palette",
"negative",
"parameters",
];
keys.forEach((key) => {
const value = prompts[key];
if (value === undefined || value === null) return;
if (typeof value === "string" && !value.trim()) return;
jsonData[key] = value;
});
return Object.keys(jsonData).length ? JSON.stringify(jsonData) : "";
}
function buildHistoryPreviewText(prompts, mode) {
if (!prompts) return "";
if (mode === "zh") {
return String(prompts.zh || "").trim() || buildHistoryStructuredPreview(prompts, "zh");
}
if (mode === "en") {
return String(prompts.en || "").trim() || buildHistoryStructuredPreview(prompts, "en");
}
if (mode === "json") {
return buildHistoryJsonPreview(prompts);
}
return "";
}
function createHistoryItem(item) {
const div = document.createElement("div");
div.className = "history-item";
div.style.cssText =
"background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); border-radius: 12px; padding: 12px; display: flex; gap: 12px; cursor: pointer; transition: all 150ms ease;";
const time = new Date(item.timestamp).toLocaleString();
const zhPrompt = buildHistoryPreviewText(item.prompts, "zh");
const enPrompt = buildHistoryPreviewText(item.prompts, "en");
const jsonPrompt = buildHistoryPreviewText(item.prompts, "json");
const hasImage = item.imageDataUrl && item.imageDataUrl.startsWith("data:image");
const imageHtml = hasImage
? `<div style="width: 80px; height: 80px; flex-shrink: 0; border-radius: 8px; overflow: hidden; background: rgba(255,255,255,0.05);">
<img src="${escapeHtml(item.imageDataUrl)}" style="width: 100%; height: 100%; object-fit: cover;" loading="lazy" onerror="this.style.display='none'; this.parentElement.innerHTML='<span style=\"font-size: 24px; display: flex; align-items: center; justify-content: center; height: 100%;\">🖼️</span>';" />
</div>`
: `<div style="width: 80px; height: 80px; flex-shrink: 0; border-radius: 8px; background: rgba(255,255,255,0.05); display: flex; align-items: center; justify-content: center;">
<span style="font-size: 24px;">🖼️</span>
</div>`;
div.innerHTML = `
${imageHtml}
<div style="flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 4px;">
<div style="display: flex; justify-content: space-between; align-items: flex-start; gap: 8px; flex-wrap: wrap;">
<div style="font-size: 11px; color: rgba(255,255,255,0.4);">${time}</div>
<div style="display: flex; gap: 4px;">
<button type="button" class="history-copy-btn" data-id="${item.id}" style="border: 0; border-radius: 4px; padding: 3px 8px; font-size: 10px; font-weight: 600; cursor: pointer; background: rgba(139,211,255,0.15); color: #8bd3ff; transition: all 150ms ease;" data-i18n="historyCopy">复制</button>
<button type="button" class="history-delete-btn" data-id="${item.id}" style="border: 0; border-radius: 4px; padding: 3px 8px; font-size: 10px; font-weight: 600; cursor: pointer; background: rgba(255,107,107,0.15); color: #ff6b6b; transition: all 150ms ease;" data-i18n="historyDelete">删除</button>
</div>
</div>
<div title="${escapeHtml(zhPrompt)}" style="min-width: 0; font-size: 12px; color: rgba(255,255,255,0.85); line-height: 1.4; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
<span style="color: #8bd3ff; font-weight: 600;">中文:</span> ${escapeHtml(truncateText(zhPrompt))}
</div>
<div title="${escapeHtml(enPrompt)}" style="min-width: 0; font-size: 11px; color: rgba(255,255,255,0.68); line-height: 1.35; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
<span style="color: #f09cc0; font-weight: 600;">EN:</span> ${escapeHtml(truncateText(enPrompt))}
</div>
<div title="${escapeHtml(jsonPrompt)}" style="min-width: 0; font-size: 11px; color: rgba(255,255,255,0.56); line-height: 1.35; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
<span style="color: #f7d774; font-weight: 600;">JSON:</span> ${escapeHtml(truncateText(jsonPrompt))}
</div>
</div>
`;
div.addEventListener("click", (e) => {
if (e.target.closest(".history-copy-btn") || e.target.closest(".history-delete-btn")) return;
loadHistoryItem(item);
});
div.addEventListener("mouseenter", () => {
div.style.background = "rgba(255,255,255,0.06)";
div.style.borderColor = "rgba(255,255,255,0.15)";
});
div.addEventListener("mouseleave", () => {
div.style.background = "rgba(255,255,255,0.03)";
div.style.borderColor = "rgba(255,255,255,0.08)";
});
div.querySelector(".history-copy-btn").addEventListener("click", async (e) => {
e.stopPropagation();
const text = item.prompts?.zh || item.prompts?.en || "";
try {
await navigator.clipboard.writeText(text);
const btn = div.querySelector(".history-copy-btn");
btn.textContent = TRANSLATIONS[form.uiLanguage.value]?.historyCopied || "已复制";
btn.style.background = "rgba(154,230,180,0.2)";
btn.style.color = "#9ae6b4";
setTimeout(() => {
btn.textContent = TRANSLATIONS[form.uiLanguage.value]?.historyCopy || "复制";
btn.style.background = "rgba(139,211,255,0.15)";
btn.style.color = "#8bd3ff";
}, 1500);
} catch (err) {
console.error("Copy failed:", err);
}
});
div.querySelector(".history-delete-btn").addEventListener("click", async (e) => {
e.stopPropagation();
await chrome.runtime.sendMessage({ type: "history:delete", id: item.id });
loadHistory();
});
return div;
}
function escapeHtml(text) {
const div = document.createElement("div");
div.textContent = text;
return div.innerHTML;
}
function truncateText(text, maxLength = 60) {
const str = String(text || "")
.replace(/[\r\n\t]+/g, " ")
.replace(/\s+/g, " ")
.trim();
if (str.length <= maxLength) return str;
return str.slice(0, maxLength) + "...";
}
async function loadHistoryItem(item) {
// 核心目标:将历史数据推送到网页中的 ImgPrompt 悬浮结果面板(content script 的 ensurePanel)
// 策略:前端直连 → 失败则注入 content script → 重试发送 → 仍失败才降级
try {
const allTabs = await chrome.tabs.query({ currentWindow: true });
const webTabs = allTabs.filter(
(t) =>
t.id && t.url && /^https?:\/\//i.test(t.url) && !t.url.startsWith("chrome-extension://"),
);
if (webTabs.length === 0) {
setStatus("⚠️ 当前窗口无网页标签,无法打开面板");
return;
}
// 优先选激活的网页标签
const targetTab = webTabs.find((t) => t.active) || webTabs[0];
const tabId = targetTab.id;
// 构造要发送的消息载荷
const payload = {
type: "prompt:load-history-item",
data: {
prompts: item.prompts,
srcUrl: item.srcUrl || "",
imageDataUrl: item.imageDataUrl || "",
},
};
// 第一步:尝试直接发送
try {
await chrome.tabs.sendMessage(tabId, payload);
setStatus("✓ 已在主面板加载历史记录");
await chrome.tabs.update(tabId, { active: true });
return;
} catch (sendErr) {
console.warn("[ImgPrompt] sendMessage failed, injecting content script:", sendErr.message);
}
// 第二步:content script 不存在 → 用 scripting API 注入
try {
await chrome.scripting.executeScript({
target: { tabId },
files: ["config.js", "content.js"],
});
// 等待 content script 初始化完成(注册 onMessage 监听器)
await new Promise((resolve) => setTimeout(resolve, 300));
// 第三步:重试发送
await chrome.tabs.sendMessage(tabId, payload);
setStatus("✓ 已在主面板加载历史记录");
await chrome.tabs.update(tabId, { active: true });
} catch (injectErr) {
console.error("[ImgPrompt] inject + resend failed:", injectErr);
setStatus(
"⚠️ 无法打开面板:" + (injectErr instanceof Error ? injectErr.message : String(injectErr)),
);
}
} catch (err) {
console.error("Failed to load history item:", err);
setStatus("⚠️ 加载失败:" + (err instanceof Error ? err.message : String(err)));
}
}
document.getElementById("btn-clear-history").addEventListener("click", async () => {
if (
confirm(TRANSLATIONS[form.uiLanguage.value]?.historyClearConfirm || "确定要清空所有历史记录吗?")
) {
await chrome.runtime.sendMessage({ type: "history:clear" });
loadHistory();
}
});
// Export history
document.getElementById("btn-export-history").addEventListener("click", async () => {
const response = await chrome.runtime.sendMessage({ type: "history:get" });
if (response?.ok && response.history?.length > 0) {
const exportData = {
version: chrome.runtime.getManifest().version,
exportDate: new Date().toISOString(),
totalItems: response.history.length,
history: response.history,
};
const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `imgprompt-history-${Date.now()}.json`;
a.click();
URL.revokeObjectURL(url);
setStatus("✅ 历史记录已导出");
} else {
setStatus("⚠️ 没有可导出的历史记录");
}
});
form.addEventListener("input", (e) => {
if (e.target.name === "userPrompt") {
updateActiveChip(e.target.value.trim());
}
handleAutoSave();
});
form.addEventListener("change", handleAutoSave);
// Export settings
// 只导出三类核心设置:连接设置、提示词设置、使用体验设置
document.getElementById("export-settings").addEventListener("click", async () => {
const allSettings = await chrome.storage.local.get(Object.keys(DEFAULT_SETTINGS));
const customTemplatesData = await chrome.storage.local.get(["customTemplates"]);
// 只导出需要的设置项,不包含内部字段和历史记录
const exportData = {
version: chrome.runtime.getManifest().version,
exportDate: new Date().toISOString(),
settings: {
// 1. 连接设置
apiEndpoint: allSettings.apiEndpoint || "",
apiKey: allSettings.apiKey || "",
model: allSettings.model || "",
// 2. 提示词设置
systemPrompt: allSettings.systemPrompt || "",
userPrompt: allSettings.userPrompt || "",
// 3. 使用体验设置
uiLanguage: allSettings.uiLanguage || "zh",
hoverButtonEnabled:
allSettings.hoverButtonEnabled !== undefined ? allSettings.hoverButtonEnabled : true,
snippingShortcutEnabled:
allSettings.snippingShortcutEnabled !== undefined
? allSettings.snippingShortcutEnabled
: true,
recreateMode: allSettings.recreateMode !== undefined ? allSettings.recreateMode : false,
maxImageEdge: allSettings.maxImageEdge || 1024,
// 自定义模板(属于提示词设置)
customTemplates: customTemplatesData.customTemplates || {},
},
};
const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: "application/json" });