-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
2629 lines (2407 loc) · 82.6 KB
/
Copy pathcontent.js
File metadata and controls
2629 lines (2407 loc) · 82.6 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 网页内悬浮结果面板。
// 本次修改:优化即梦等 AI 绘图站点的页面提示词与标题抓取逻辑。
// 修改原因:用户在设置页点击“抓取”时,会把页面上所有提示词都抓进来,无法精准定位到当前展示图片的“图片提示词”;且标题未抓取时会留空,需要自动从提示词中提取主体作为标题。
// 具体修改点:
// 1. 新增 collectorExtractJimengPrompt,针对 jimeng.jianying.com 特化抓取“图片提示词”标签附近的内容,并在遇到操作按钮前截断,避免抓取整页文字。
// 2. 新增 collectorExtractTitleFromPrompt,在 document.title 为空或只剩站点名时,从提示词首句提取最多 30 字作为标题。
// 3. 扩展 collectorCleanupPrompt 的截断词表(生成视频、去画布编辑、用作参考图等),并增强标题兜底与提示词复用逻辑。
// 4. 保留之前“保存本地/上传云端”按钮、默认提示词回退、懒加载图片抓取等能力。
// 5. 增强 collectorExtractJimengPrompt:先通过“图片提示词”标签定位当前图片对应的提示词容器,避免抓到页面上其他图片的提示词;找不到标签时才兜底收集所有 prompt-value 取最长。
// 6. 修复 collectorCleanupPrompt 的误截断问题:原本用贪婪替换会把提示词中间出现的“超清/下载”等词之后的内容全删掉,现改为仅当这些词位于文末 75% 之后才截断。
// 7. 清理即梦图片元信息栏:去掉“图片 4.7 | 9:16 | 2K | 详细信息”这类信息,但保留尺寸比例(如 9:16)。
const CONFIG = window.ImgPromptConfig || {};
const UI_STRINGS = CONFIG.UI_STRINGS;
function throttle(fn, wait) {
let lastCall = 0;
let timeoutId = null;
return function throttled(...args) {
const now = Date.now();
const remaining = wait - (now - lastCall);
if (remaining <= 0) {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
lastCall = now;
fn.apply(this, args);
} else if (!timeoutId) {
timeoutId = setTimeout(() => {
lastCall = Date.now();
timeoutId = null;
fn.apply(this, args);
}, remaining);
}
};
}
const PANEL_ROOT_ID = "image-prompt-inspector-root";
const PANEL_Z_INDEX = "2147483647";
const HOVER_BUTTON_ROOT_ID = "picprompt-hover-button-root";
const MAX_IMAGE_EDGE = 1024;
const COMPRESSED_IMAGE_QUALITY = 0.86;
let lastContextImage = null;
let activeRequestId = "";
let activeLanguage = "zh";
let currentPrompts = {
zh: "",
en: "",
image_type: "",
aspect_ratio: "",
background: "",
subject: null,
surrounding_elements: "",
composition: "",
text_content: "",
style: "",
lighting: "",
color_palette: "",
negative: null,
parameters: null,
};
let currentSource = { srcUrl: "", imageDataUrl: "" };
let currentTrigger = "unknown";
let isGenerating = false;
let dragState = null;
let hoverImage = null;
let isHoverButtonHovered = false;
let isHoverButtonDismissed = false;
let isHoverButtonEnabled = true;
let uiLanguage = "zh";
let preferredPromptLanguage = null;
let maxImageEdge = 1024;
let generationStartedAt = 0;
let progressTimerId = 0;
let currentProgressText = "";
let panelDismissed = false;
let isJsonMode = false;
let collectorSelectedImageUrl = "";
let lastHoverImageUrl = ""; // 缓存最后一次悬浮图片的 URL 字符串(DOM 元素可能被 SPA 销毁)
// Convert structured prompt fields to readable text for normal mode display
function buildReadableText(prompts) {
if (!prompts) return "";
if (activeLanguage === "en" && typeof prompts.en === "string" && prompts.en.trim()) {
const enParts = [prompts.en.trim()];
if (prompts.negative) {
enParts.push(`Negative: ${String(prompts.negative).trim()}`);
}
return enParts.join("\n\n");
}
if (activeLanguage === "zh" && typeof prompts.zh === "string" && prompts.zh.trim()) {
return prompts.zh.trim();
}
const dict = UI_STRINGS[activeLanguage] || UI_STRINGS.zh;
const parts = [];
if (prompts.image_type) parts.push(prompts.image_type);
if (prompts.aspect_ratio) parts.push(dict.labelAspectRatio + ": " + prompts.aspect_ratio);
if (prompts.background) parts.push(dict.labelBackground + ": " + prompts.background);
if (prompts.subject) {
const s = prompts.subject;
const subParts = [];
if (s.identity) subParts.push(s.identity);
if (s.appearance) subParts.push(s.appearance);
if (s.clothing) subParts.push(s.clothing);
if (s.posture) subParts.push(s.posture);
if (s.position) subParts.push(s.position);
if (subParts.length) parts.push(dict.labelSubject + ": " + subParts.join(", "));
}
if (prompts.surrounding_elements)
parts.push(dict.labelSurroundingElements + ": " + prompts.surrounding_elements);
if (prompts.composition) parts.push(dict.labelComposition + ": " + prompts.composition);
if (prompts.text_content) parts.push(dict.labelTextContent + ": " + prompts.text_content);
if (prompts.style) parts.push(dict.labelStyle + ": " + prompts.style);
if (prompts.lighting) parts.push(dict.labelLighting + ": " + prompts.lighting);
if (prompts.color_palette) parts.push(dict.labelColorPalette + ": " + prompts.color_palette);
const structured = parts.join("\n");
if (structured) return structured;
// Fallback to the other language prompt if current language is missing
if (activeLanguage === "zh" && typeof prompts.en === "string" && prompts.en.trim()) {
return prompts.en.trim();
}
if (activeLanguage === "en" && typeof prompts.zh === "string" && prompts.zh.trim()) {
return prompts.zh.trim();
}
return "";
}
function buildStructuredPromptJson(prompts) {
const jsonData = {};
if (!prompts) {
return jsonData;
}
if (prompts.image_type) jsonData.image_type = prompts.image_type;
if (prompts.aspect_ratio) jsonData.aspect_ratio = prompts.aspect_ratio;
if (prompts.background) jsonData.background = prompts.background;
if (prompts.subject) jsonData.subject = prompts.subject;
if (prompts.surrounding_elements) jsonData.surrounding_elements = prompts.surrounding_elements;
if (prompts.composition) jsonData.composition = prompts.composition;
if (prompts.text_content) jsonData.text_content = prompts.text_content;
if (prompts.style) jsonData.style = prompts.style;
if (prompts.lighting) jsonData.lighting = prompts.lighting;
if (prompts.color_palette) jsonData.color_palette = prompts.color_palette;
if (prompts.negative) jsonData.negative = prompts.negative;
if (prompts.parameters) jsonData.parameters = prompts.parameters;
return jsonData;
}
function getCurrentPromptText() {
if (isJsonMode && currentPrompts) {
const jsonData = buildStructuredPromptJson(currentPrompts);
return Object.keys(jsonData).length ? JSON.stringify(jsonData, null, 2) : "";
}
const textarea = document
.getElementById(PANEL_ROOT_ID)
?.shadowRoot?.querySelector(".ipi-textarea");
return textarea?.value.trim() || buildReadableText(currentPrompts);
}
// ===== 页面采集逻辑(移植自 browser-extension) =====
function collectorNormalizeText(value) {
return (value || "").replace(/\s+/g, " ").trim();
}
function collectorAbsoluteUrl(value) {
try {
return new URL(value, window.location.href).href;
} catch {
return "";
}
}
function collectorIsVisible(element) {
const style = window.getComputedStyle(element);
const rect = element.getBoundingClientRect();
return (
style.display !== "none" && style.visibility !== "hidden" && rect.width > 0 && rect.height > 0
);
}
function collectorCleanupPrompt(value) {
let clean = collectorNormalizeText(value)
.replace(/^提示词[::\s]*/i, "")
.replace(/^prompt[::\s]*/i, "")
.replace(/^图片提示词[::\s]*/i, "")
// 只移除位于文末附近的操作按钮/标签,避免把正常提示词中间的关键词(如“超清”)误删
.replace(/图片\s*\|\s*即梦图片[\s\S]*$/i, "")
.replace(/一键复制[\s\S]*$/i, "")
.replace(/一键同款[\s\S]*$/i, "")
.replace(/举报\s*$/i, "");
// 去掉即梦图片元信息栏:图片 4.7 | 9:16 | 2K | 详细信息,保留尺寸比例(如 9:16)
const metaMatch = clean.match(
/图片\s*[\d.]+[\s::|]*((\d+):(\d+))?[\s::|]*\d+[Kk][\s::|]*详细信息/i,
);
if (metaMatch) {
const ratio = metaMatch[1];
clean = clean.slice(0, metaMatch.index).trim();
if (ratio && clean.length > 0) {
clean = clean + (/[,。;,.::\s]$/.test(clean) ? "" : ",") + ratio;
}
}
const trailingStopWords = [
"生成视频",
"去画布编辑",
"用作参考图",
"生成图片",
"下载",
"举报",
"一键同款",
"一键复制",
"智能超清",
"多角度",
"超清",
"细节修复",
"局部重绘",
"扩图",
"消除笔",
"对口型",
"重新编辑",
"再次生成",
];
for (const stop of trailingStopWords) {
const idx = clean.lastIndexOf(stop);
if (idx >= 0 && idx + stop.length >= clean.length * 0.75) {
clean = clean.slice(0, idx).trim();
}
}
return clean.trim();
}
function collectorScorePrompt(text, element) {
const cleanText = collectorCleanupPrompt(text);
if (cleanText.length < 24) return null;
let score = Math.min(cleanText.length, 1000);
const nearby = collectorNormalizeText(element.parentElement?.innerText || "");
if (/提示词|prompt/i.test(nearby)) score += 650;
if (/[,。;、,.]/.test(cleanText)) score += 80;
if (/采用|设计|画面|风格|品牌|构图|光影|色彩|生成|展示|产品|系列|海报|宣传/.test(cleanText))
score += 120;
// 核心优化:极重惩罚包含过多子元素的包裹层,迫使算法选中最深层的纯文本节点
if (element.childElementCount > 2) {
score -= element.childElementCount * 500;
}
return { text: cleanText, score };
}
function collectorExtractJimengPrompt() {
// 即梦特化逻辑:优先通过“图片提示词”标签定位当前展示图片对应的提示词
const labels = Array.from(
document.querySelectorAll("p, div, span, h1, h2, h3, h4, label"),
).filter(
(el) => collectorIsVisible(el) && /^(图片)?提示词(?:\s*\d+)?$/.test(el.textContent.trim()),
);
// 1. 精确路径:对每个可见标签,先找它紧邻的 prompt-value 容器
const labelCandidates = [];
for (const label of labels) {
// 1a. 直接后续兄弟中的 prompt-value 容器
let sibling = label.nextElementSibling;
while (sibling) {
if (sibling.matches('[class*="prompt-value"], [class*="promptValue"]')) {
const text = collectorNormalizeText(sibling.textContent || "");
if (text.length >= 20) {
const cleaned = collectorCleanupPrompt(text);
if (cleaned.length >= 20) labelCandidates.push(cleaned);
}
}
const innerValue = sibling.querySelector('[class*="prompt-value"], [class*="promptValue"]');
if (innerValue) {
const text = collectorNormalizeText(innerValue.textContent || "");
if (text.length >= 20) {
const cleaned = collectorCleanupPrompt(text);
if (cleaned.length >= 20) labelCandidates.push(cleaned);
}
}
sibling = sibling.nextElementSibling;
}
// 1b. 父容器内的 prompt-value 容器
let scope = label.parentElement;
for (let depth = 0; depth < 3 && scope; depth += 1) {
const valueEl = scope.querySelector('[class*="prompt-value"], [class*="promptValue"]');
if (valueEl) {
const text = collectorNormalizeText(valueEl.textContent || "");
if (text.length >= 20) {
const cleaned = collectorCleanupPrompt(text);
if (cleaned.length >= 20) labelCandidates.push(cleaned);
}
}
scope = scope.parentElement;
}
}
// 如果标签路径找到了候选,直接返回最长的一个(同一标签对应的提示词不会错)
if (labelCandidates.length > 0) {
const unique = [...new Set(labelCandidates)];
unique.sort((a, b) => b.length - a.length);
return unique[0];
}
// 2. 兜底:没有标签时,再收集所有 prompt-value 容器取最长
const candidates = [];
const pushCandidate = (text) => {
const cleaned = collectorCleanupPrompt(collectorNormalizeText(text || ""));
if (cleaned.length >= 20) candidates.push(cleaned);
};
const valueContainers = document.querySelectorAll(
'[class*="prompt-value"], [class*="promptValue"]',
);
for (const container of valueContainers) {
pushCandidate(container.textContent || "");
}
const copyEl =
document.querySelector("[data-clipboard-text]") ||
document.querySelector('[aria-label*="复制" i]') ||
document.querySelector('[aria-label*="copy" i]');
if (copyEl) {
pushCandidate(copyEl.getAttribute("data-clipboard-text") || copyEl.textContent || "");
}
const unique = [...new Set(candidates)];
if (unique.length > 0) {
unique.sort((a, b) => b.length - a.length);
return unique[0];
}
return null;
}
function collectorExtractTitleFromPrompt(prompt) {
if (!prompt || prompt.length < 4) return "";
const clean = prompt.replace(/^生成[一幅个张份]*|^一张|^一幅|^创建|^制作/, "").trim();
const firstSegment = clean.split(/[,。;,.::]/)[0].trim();
return firstSegment.slice(0, 30).trim();
}
function collectorExtractPrompt() {
const isZcool = window.location.hostname.includes("zcool.com.cn");
const isJimeng =
window.location.hostname.includes("jimeng.jianying.com") ||
window.location.hostname.includes("jimeng.");
if (isZcool) {
// 站酷特化逻辑:寻找带有“提示词”字样的元素,并提取其最接近的纯文本邻居
const labels = Array.from(document.querySelectorAll("p, div, span, h1, h2, h3, h4")).filter(
(el) => collectorIsVisible(el) && /^提示词(?:\s*\d+)?$/.test(el.textContent.trim()),
);
if (labels.length > 0) {
const label = labels[labels.length - 1]; // 取最深层的那个
// 尝试寻找下一个兄弟节点
if (label.nextElementSibling && label.nextElementSibling.textContent.length > 10) {
return collectorNormalizeText(label.nextElementSibling.textContent);
}
// 或者尝试父容器里的文本
if (
label.parentElement &&
label.parentElement.textContent.length > label.textContent.length + 10
) {
return collectorNormalizeText(label.parentElement.textContent.replace("提示词", ""));
}
}
// 回退到针对站酷严格惩罚大包裹层的智能抓取
const zcoolContainer = document.querySelector(
".work-content-wrap, .article-content, .work-show-box, .work-details, main",
);
if (zcoolContainer) {
const zcoolCandidates = Array.from(zcoolContainer.querySelectorAll("p, div, span, section"))
.filter(collectorIsVisible)
.map((el) => collectorScorePrompt(el.innerText || el.textContent || "", el))
.filter(Boolean)
.sort((a, b) => b.score - a.score);
if (zcoolCandidates.length > 0) return zcoolCandidates[0].text;
}
}
if (isJimeng) {
const jimengPrompt = collectorExtractJimengPrompt();
if (jimengPrompt) return jimengPrompt;
}
const selection = collectorNormalizeText(window.getSelection()?.toString() || "");
if (selection.length >= 12) return selection;
const labelElements = Array.from(
document.querySelectorAll("h1,h2,h3,h4,p,div,span,section,aside"),
)
.filter(collectorIsVisible)
.filter((el) => /提示词|prompt/i.test(collectorNormalizeText(el.textContent || "")));
const candidates = [];
for (const label of labelElements) {
let scope = label;
for (let depth = 0; depth < 4 && scope; depth += 1) {
const scored = collectorScorePrompt(scope.innerText || scope.textContent || "", scope);
if (scored) candidates.push(scored);
scope = scope.parentElement;
}
}
if (candidates.length > 0) {
return candidates.sort((a, b) => b.score - a.score)[0].text;
}
const generic = Array.from(document.querySelectorAll("p,article,section,aside,div"))
.filter(collectorIsVisible)
.map((el) => collectorScorePrompt(el.innerText || el.textContent || "", el))
.filter(Boolean)
.sort((a, b) => b.score - a.score);
return generic[0]?.text || "";
}
function collectorReadPage() {
const isZcool = window.location.hostname.includes("zcool.com.cn");
const imageRoot = isZcool
? document.querySelector(
".work-content-wrap, .article-content, .work-show-box, .work-details",
) || document
: document;
// 收集所有 <img> 元素,优先取真实已加载地址,其次各种懒加载属性
const extractedImages = Array.from(imageRoot.querySelectorAll("img"))
.map((image) => {
const rawSrc =
image.currentSrc ||
image.src ||
image.dataset.src ||
image.dataset.original ||
image.dataset.lazySrc ||
image.dataset.lazySrcset ||
"";
const hasLazyAttr = Boolean(
image.dataset.src ||
image.dataset.original ||
image.dataset.lazySrc ||
image.dataset.lazySrcset,
);
// 对 background-image 也尝试提取(常见于封面图)
const bgStyle = window.getComputedStyle(image).backgroundImage;
const bgMatch = bgStyle && bgStyle !== "none" ? /url\(["']?(.*?)["']?\)/.exec(bgStyle) : null;
// 获取图片在屏幕上的实际渲染尺寸
const rect = image.getBoundingClientRect();
const visArea = rect.width * rect.height;
const natArea = (image.naturalWidth || 0) * (image.naturalHeight || 0);
const score = Math.max(visArea, natArea);
return {
src: collectorAbsoluteUrl(rawSrc) || (bgMatch ? collectorAbsoluteUrl(bgMatch[1]) : ""),
alt: image.alt || "",
width: image.naturalWidth || image.width || rect.width || 0,
height: image.naturalHeight || image.height || rect.height || 0,
score,
hasLazyAttr,
};
})
.filter((image) => image.src && /^https?:\/\//i.test(image.src) && image.score > 5000);
// 动态过滤:找出当前页面最大的图片面积,只保留面积达到最大图片 25% 以上的“主要大图”
const maxScore = extractedImages.reduce((max, img) => Math.max(max, img.score), 0);
const images = extractedImages
.filter((image) => image.score >= maxScore * 0.25)
.sort((a, b) => b.score - a.score)
.slice(0, 24);
let cleanTitle = document.title || "";
if (isZcool) {
cleanTitle = cleanTitle.replace(/-?\s*站酷.*?$/i, "").trim();
} else {
cleanTitle = cleanTitle.replace(/-?\s*(即梦|站酷|ZCOOL|ArtStation|Jimeng).*$/i, "").trim();
}
// 先提取提示词,供标题兜底使用,也避免重复计算
const prompt = collectorExtractPrompt();
// 如果标题为空或只剩站点名/通用名,从提示词中提取主体作为标题
const genericTitlePattern = /^(即梦|Jimeng|站酷|ZCOOL|首页|主页|AI绘画|AI 绘画|生成图片|创作)$/i;
if (!cleanTitle || cleanTitle.length < 2 || genericTitlePattern.test(cleanTitle)) {
cleanTitle = collectorExtractTitleFromPrompt(prompt);
}
return {
title: cleanTitle,
url: window.location.href,
prompt,
images,
};
}
function renderCollectorImages(shadowRoot, images) {
const grid = shadowRoot.querySelector("[data-collector-grid]");
const count = shadowRoot.querySelector("[data-collector-count]");
if (!grid) return;
grid.textContent = "";
if (count) count.textContent = images.length + " 张";
collectorSelectedImageUrl = "";
if (images.length === 0) {
const empty = document.createElement("div");
empty.className = "ipi-collector-empty";
empty.textContent = "没有发现可用图片,点击抓取重新读取";
grid.appendChild(empty);
return;
}
for (const image of images) {
const button = document.createElement("button");
button.type = "button";
button.title = image.alt || image.src;
const preview = document.createElement("img");
preview.src = image.src;
preview.alt = image.alt || "";
preview.referrerPolicy = "no-referrer";
button.appendChild(preview);
button.addEventListener("click", () => {
collectorSelectedImageUrl = image.src;
for (const option of grid.querySelectorAll("button")) {
option.classList.remove("is-selected");
}
button.classList.add("is-selected");
});
grid.appendChild(button);
}
}
function grabPageContent(shadowRoot) {
const context = collectorReadPage();
renderCollectorImages(shadowRoot, context.images || []);
const textarea = shadowRoot.querySelector(".ipi-textarea");
if (textarea && context.prompt) {
const currentText = textarea.value.trim();
if (!currentText) {
textarea.value = context.prompt;
}
}
const categoryInput = shadowRoot.querySelector("[data-collector-category]");
if (categoryInput && !categoryInput.value.trim()) {
chrome.storage.local.get({ xihahaDefaultGroup: "未分组" }, (result) => {
if (!categoryInput.value.trim()) {
categoryInput.value = result.xihahaDefaultGroup || "未分组";
}
});
}
setStatus(shadowRoot, "已抓取 " + (context.images || []).length + " 张图片");
}
async function loadCollectorCategories(shadowRoot) {
const datalist = shadowRoot.querySelector("#ipi-category-options");
if (!datalist) return;
try {
const response = await chrome.runtime.sendMessage({ type: "xihaha:get-categories" });
if (!response?.ok || !Array.isArray(response.categories)) return;
datalist.textContent = "";
for (const category of response.categories) {
const value = String(category || "").trim();
if (!value) continue;
const option = document.createElement("option");
option.value = value;
datalist.appendChild(option);
}
} catch {
// 分组加载失败不影响手动输入
}
}
function isExtensionContextError(error) {
const message = error instanceof Error ? error.message : String(error || "");
return (
message.includes("Extension context invalidated") ||
message.includes("Receiving end does not exist") ||
message.includes("The message port closed before a response was received")
);
}
function safeSendRuntimeMessage(payload, callback) {
try {
chrome.runtime.sendMessage(payload, callback);
return true;
} catch (error) {
if (isExtensionContextError(error)) {
return false;
}
throw error;
}
}
document.addEventListener(
"contextmenu",
(event) => {
const path = event.composedPath ? event.composedPath() : [];
const matched = path.find(
(node) =>
node instanceof HTMLImageElement || (node instanceof Element && node.closest?.("img")),
);
if (matched instanceof HTMLImageElement) {
lastContextImage = matched;
return;
}
if (matched instanceof Element) {
lastContextImage = matched.closest("img");
}
},
true,
);
document.addEventListener("pointermove", throttle(handleDocumentPointerMove, 100), true);
document.addEventListener("scroll", () => updateHoverButtonPosition(), true);
window.addEventListener("resize", () => updateHoverButtonPosition());
chrome.storage.local.get(
{ hoverButtonEnabled: true, uiLanguage: "zh", maxImageEdge: 1024, preferredPromptLanguage: null },
(result) => {
isHoverButtonEnabled = result.hoverButtonEnabled !== false;
uiLanguage = result.uiLanguage || "zh";
maxImageEdge = result.maxImageEdge || 1024;
preferredPromptLanguage = result.preferredPromptLanguage || null;
if (!isHoverButtonEnabled) {
hoverImage = null;
hideHoverButton();
}
},
);
chrome.storage.onChanged.addListener((changes, areaName) => {
if (changes.hoverButtonEnabled) {
isHoverButtonEnabled = changes.hoverButtonEnabled.newValue !== false;
isHoverButtonDismissed = false;
if (!isHoverButtonEnabled) {
hoverImage = null;
isHoverButtonHovered = false;
hideHoverButton();
} else {
updateHoverButtonPosition();
}
}
if (changes.uiLanguage) {
uiLanguage = changes.uiLanguage.newValue || "zh";
preferredPromptLanguage = null;
chrome.storage.local.remove("preferredPromptLanguage");
// If panel exists, update it
const panel = document.getElementById(PANEL_ROOT_ID);
if (panel && panel.shadowRoot) {
updatePanelLanguage(panel.shadowRoot);
}
}
if (changes.maxImageEdge) {
maxImageEdge = changes.maxImageEdge.newValue || 1024;
}
});
// Reload settings when notified from options page
function handleSettingsUpdate() {
chrome.storage.local.get(
{
hoverButtonEnabled: true,
uiLanguage: "zh",
maxImageEdge: 1024,
preferredPromptLanguage: null,
},
(result) => {
isHoverButtonEnabled = result.hoverButtonEnabled !== false;
uiLanguage = result.uiLanguage || "zh";
maxImageEdge = result.maxImageEdge || 1024;
preferredPromptLanguage = result.preferredPromptLanguage || null;
if (!isHoverButtonEnabled) {
hoverImage = null;
isHoverButtonHovered = false;
hideHoverButton();
}
// Update panel language if it exists
const panel = document.getElementById(PANEL_ROOT_ID);
if (panel && panel.shadowRoot) {
updatePanelLanguage(panel.shadowRoot);
}
},
);
}
function updatePanelLanguage(shadow) {
const dict = UI_STRINGS[uiLanguage] || UI_STRINGS.zh;
// Update static text in the panel
const nameEl = shadow.querySelector(".ipi-name");
const subtitleEl = shadow.querySelector(".ipi-subtitle");
const dragEl = shadow.querySelector(".ipi-drag");
const stopEl = shadow.querySelector(".ipi-stop");
const textareaEl = shadow.querySelector(".ipi-textarea");
const zhBtn = shadow.querySelector('[data-lang="zh"]');
const enBtn = shadow.querySelector('[data-lang="en"]');
const copyBtn = shadow.querySelector('[data-action="copy"]');
const stageLoadingEl = shadow.querySelector(".ipi-stage-loading");
if (nameEl) nameEl.textContent = "ImgPrompt";
if (subtitleEl) subtitleEl.textContent = dict.subtitle;
if (dragEl) dragEl.setAttribute("aria-label", dict.dragCard);
if (stopEl) stopEl.setAttribute("aria-label", dict.stopButton);
if (textareaEl) textareaEl.placeholder = dict.placeholder;
if (zhBtn) zhBtn.textContent = dict.zhBtn;
if (enBtn) enBtn.textContent = dict.enBtn;
if (stageLoadingEl) stageLoadingEl.textContent = dict.imageLoading;
if (copyBtn && copyBtn.getAttribute("data-state") === "idle") {
copyBtn.textContent = dict.copyBtn;
} else if (copyBtn && copyBtn.getAttribute("data-state") === "done") {
copyBtn.textContent = dict.copied;
}
// Update status if not currently generating (or update based on current state)
const statusEl = shadow.querySelector(".ipi-status");
if (statusEl) {
const currentStatus = statusEl.textContent;
// Simple heuristic to translate current status if it matches a known one
for (const lang in UI_STRINGS) {
for (const key in UI_STRINGS[lang]) {
if (UI_STRINGS[lang][key] === currentStatus) {
statusEl.textContent = dict[key];
break;
}
}
}
}
}
// 响应设置页“抓取当前页面”请求:返回当前页面的图片列表(供设置页图片网格展示)
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
if (message?.type === "xihaha:collect-page-images") {
try {
const page = collectorReadPage();
sendResponse({
ok: true,
images: page.images,
prompt: page.prompt,
title: page.title,
pageUrl: page.url,
});
} catch (e) {
sendResponse({ ok: false, error: e instanceof Error ? e.message : String(e) });
}
return true;
}
return false;
});
chrome.runtime.onMessage.addListener((message) => {
switch (message?.type) {
case "prompt:start-snipping":
startSnipper(message.dataUrl);
break;
case "prompt:start-analysis":
handleStartAnalysis(message);
break;
case "prompt:load-history-item":
handleLoadHistoryItem(message);
break;
case "prompt:progress":
if (message.requestId === activeRequestId) {
updateProgress(message.progress, message.text);
}
break;
case "prompt:result":
if (message.requestId === activeRequestId) {
handleResult(message);
}
break;
case "prompt:canceled":
if (message.requestId === activeRequestId) {
handleCanceled();
}
break;
case "prompt:error":
if (message.requestId === activeRequestId) {
handleError(message);
}
break;
case "settings:updated":
// Reload settings from storage
handleSettingsUpdate();
break;
default:
break;
}
});
async function handleStartAnalysis(message) {
activeRequestId = message.requestId;
panelDismissed = false;
currentTrigger = message.trigger || "unknown";
currentSource = {
srcUrl: message.srcUrl || "",
imageDataUrl: message.imageDataUrl || "",
};
currentPrompts = {
zh: "",
en: "",
image_type: "",
aspect_ratio: "",
background: "",
subject: null,
surrounding_elements: "",
composition: "",
text_content: "",
style: "",
lighting: "",
color_palette: "",
negative: null,
parameters: null,
};
const panel = ensurePanel();
const dict = UI_STRINGS[uiLanguage] || UI_STRINGS.zh;
activeLanguage = preferredPromptLanguage || uiLanguage || "zh";
// Button order is fixed by HTML structure: 中文 → English → JSON
// No need to dynamically change CSS order
setPreview(panel, message.imageDataUrl || message.srcUrl || "");
setTextareaValue(panel, "");
setStatus(panel, dict.preparing);
startProgressTimer();
updateProgress(6, dict.locatingImage);
setLoadingState(panel, true);
setError(panel, "");
syncLanguageButtons(panel);
resetCopyButton(panel);
setContentVisibility(panel, false);
setStopButtonState(panel, true);
setScannerVisibility(panel, true);
isGenerating = true;
// Simply pass srcUrl; background will handle image fetching and compression
const sent = safeSendRuntimeMessage(
{
type: "prompt:begin-generation",
requestId: message.requestId,
srcUrl: message.srcUrl || "",
imageDataUrl: message.imageDataUrl || "",
trigger: currentTrigger,
pageContext: {
altText: lastContextImage?.alt || "",
title: document.title,
pageUrl: window.location.href,
},
},
(response) => {
if (activeRequestId !== message.requestId) {
return;
}
const runtimeError = chrome.runtime.lastError;
if (runtimeError) {
const dict = UI_STRINGS[uiLanguage] || UI_STRINGS.zh;
showGenerationError(panel, runtimeError.message || dict.unknownError);
return;
}
if (!response?.ok) {
const dict = UI_STRINGS[uiLanguage] || UI_STRINGS.zh;
showGenerationError(panel, response?.error || dict.generationFailed);
}
},
);
if (!sent) {
isGenerating = false;
stopProgressTimer();
setLoadingState(panel, false);
setStopButtonState(panel, false);
shadowSafeHidePanel(panel);
}
}
function startAnalysisForImage(image) {
if (!(image instanceof HTMLImageElement)) {
console.warn("[ImgPrompt] startAnalysisForImage 收到非 img 元素:", image?.constructor?.name);
return;
}
const srcUrl = image.currentSrc || image.src || "";
if (!srcUrl) {
console.warn("[ImgPrompt] startAnalysisForImage: img 元素无 src (可能被 SPA 回收),URL 为空");
return;
}
// 即使图片已不在 DOM 中(SPA 替换),只要有 srcUrl 就可以继续
lastContextImage = image;
lastHoverImageUrl = srcUrl; // 再次缓存,确保最新
hideHoverButton();
handleStartAnalysis({
requestId: crypto.randomUUID(),
srcUrl,
trigger: "hover_button",
});
}
function handleResult(message) {
if (panelDismissed) {
isGenerating = false;
stopProgressTimer();
return;
}
// Parse structured prompt data - only visual analysis fields
const prompts = message.prompts || {};
currentPrompts = {
zh: prompts.zh || "",
en: prompts.en || "",
image_type: prompts.image_type || "",
aspect_ratio: prompts.aspect_ratio || "",
background: prompts.background || "",
subject: prompts.subject || null,
surrounding_elements: prompts.surrounding_elements || "",
composition: prompts.composition || "",
text_content: prompts.text_content || "",
style: prompts.style || "",
lighting: prompts.lighting || "",
color_palette: prompts.color_palette || "",
negative: prompts.negative || null,
parameters: prompts.parameters || null,
};
currentSource = message.source || currentSource;
const panel = ensurePanel();
const dict = UI_STRINGS[uiLanguage] || UI_STRINGS.zh;
isGenerating = false;
stopProgressTimer();
setLoadingState(panel, false);
updateProgress(100, dict.generationComplete);
setStatus(panel, dict.completed);
setError(panel, "");
setTextareaValue(panel, buildReadableText(currentPrompts));
resetCopyButton(panel);
setScannerVisibility(panel, false);
setContentVisibility(panel, true);
setStopButtonState(panel, false);
if (currentSource.imageDataUrl || currentSource.srcUrl) {
setPreview(panel, currentSource.imageDataUrl || currentSource.srcUrl);
}
}
function handleLoadHistoryItem(message) {
const historyData = message.data;
if (!historyData?.prompts) {
return;
}
panelDismissed = false;
const prompts = historyData.prompts || {};
currentPrompts = {
zh: prompts.zh || "",
en: prompts.en || "",
image_type: prompts.image_type || "",
aspect_ratio: prompts.aspect_ratio || "",
background: prompts.background || "",
subject: prompts.subject || null,
surrounding_elements: prompts.surrounding_elements || "",
composition: prompts.composition || "",
text_content: prompts.text_content || "",
style: prompts.style || "",
lighting: prompts.lighting || "",
color_palette: prompts.color_palette || "",
negative: prompts.negative || null,
parameters: prompts.parameters || null,
};
currentSource = {
srcUrl: historyData.srcUrl || "",
imageDataUrl: historyData.imageDataUrl || "",
};
currentTrigger = "history";
const panel = ensurePanel();
const dict = UI_STRINGS[uiLanguage] || UI_STRINGS.zh;
// Reset state
isGenerating = false;
stopProgressTimer();
// Set language preference
activeLanguage = preferredPromptLanguage || uiLanguage || "zh";
// Button order is fixed by HTML structure: 中文 → English → JSON