-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
2046 lines (1718 loc) · 84.1 KB
/
Copy pathcontent.js
File metadata and controls
2046 lines (1718 loc) · 84.1 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
/*
Yummy! 内容脚本 (v1.0.0)
这是 Yummy! 扩展的核心脚本,负责向 ChatGPT 页面注入所有交互功能。
其主要功能模块包括:
1. **评价栏注入**:为 AI 回复的每个内容块(段落、标题、列表项等)动态添加"喜欢/不喜欢"的评价工具。
2. **分级评价系统**:为标题(父级元素)实现一种复杂的、两级的评价逻辑。
3. **划词高亮系统**:提供一个独立的"划词模式",并支持在普通模式下通过快捷按钮进行高亮。
4. **UI面板与交互**:创建并管理右侧的控制面板和左侧的收集面板。
5. **提示词生成**:根据用户标记的内容,智能地生成可用于后续提问的提示词。
此脚本通过 MutationObserver 监听页面的动态变化,确保功能对流式输出的内容同样有效。
*/
(function() {
'use strict';
const STORAGE_KEY_PREFIX = 'yummy_conversation_';
let currentConversationId = null;
let currentConversationState = {};
let messageElementsCache = new Map();
// 通过检查 `update_url` (一个只在发布版 manifest.json 中存在的字段) 来判断扩展是否处于本地解压的开发模式。
const isDevMode = !('update_url' in chrome.runtime.getManifest());
if (!isDevMode) {
window.logger = {
log: () => {},
info: () => {},
warn: () => {},
error: () => {},
debug: () => {},
group: () => {},
groupEnd: () => {},
init: () => {}
};
}
logger.info('Yummy! 内容脚本已加载。');
const EMOJI_LIKE = '😋';
const EMOJI_DISLIKE = '🤮';
let syncCollectionPanelWithDOM = () => logger.warn('syncCollectionPanelWithDOM not implemented yet');
function getConversationId() {
const match = window.location.pathname.match(/\/c\/([a-zA-Z0-9-]+)/);
return match ? match[1] : null;
}
function getStableElementId(element) {
const assistantMessages = Array.from(document.querySelectorAll('[data-message-author-role="assistant"]'));
const messageIndex = assistantMessages.findIndex(msg => msg.contains(element));
if (messageIndex === -1) return null;
const key = `message-${messageIndex}`;
let elementsInMessage;
if (messageElementsCache.has(key)) {
elementsInMessage = messageElementsCache.get(key);
} else {
elementsInMessage = Array.from(assistantMessages[messageIndex].querySelectorAll(CONTENT_ELEMENTS_SELECTOR));
messageElementsCache.set(key, elementsInMessage);
}
const elementIndex = elementsInMessage.findIndex(el => el === element);
return elementIndex > -1 ? `yummy-m${messageIndex}-e${elementIndex}` : null;
}
async function saveData(elementId, data) {
if (!currentConversationId || !elementId) return;
// Update local state first
if (data) {
currentConversationState[elementId] = { ...currentConversationState[elementId], ...data };
} else {
delete currentConversationState[elementId]; // Handles removal of markings
}
// Clean up empty objects
if (currentConversationState[elementId] && Object.keys(currentConversationState[elementId]).length === 0) {
delete currentConversationState[elementId];
}
try {
const storageKey = `${STORAGE_KEY_PREFIX}${currentConversationId}`;
if (Object.keys(currentConversationState).length > 0) {
await chrome.storage.local.set({ [storageKey]: currentConversationState });
logger.debug(`Data saved for ${elementId}`, currentConversationState[elementId]);
} else {
// If the last marking is removed, clean up the entire entry from storage
await chrome.storage.local.remove(storageKey);
logger.debug(`Conversation ${currentConversationId} has no markings, removed from storage.`);
}
} catch (error) {
logger.error('Failed to save data to chrome.storage.local:', error);
}
}
async function applyHierarchicalState(targetElement, state) {
const elementId = getStableElementId(targetElement);
const descendantSelector = 'p, h1, h2, h3, h4, h5, h6, li';
targetElement.classList.remove('yummy-liked', 'yummy-disliked');
const descendants = targetElement.querySelectorAll(descendantSelector);
descendants.forEach(d => d.classList.remove('yummy-liked', 'yummy-disliked'));
if (state === 'liked') {
targetElement.classList.add('yummy-liked');
descendants.forEach(d => d.classList.add('yummy-liked'));
if(elementId) await saveData(elementId, { rating: 'liked' });
} else if (state === 'disliked') {
targetElement.classList.add('yummy-disliked');
descendants.forEach(d => d.classList.add('yummy-disliked'));
if(elementId) await saveData(elementId, { rating: 'disliked' });
} else { // state === 'none'
if(elementId) await saveData(elementId, { rating: null });
}
logger.debug(`已将状态 '${state}' 应用到元素及其子项。`, targetElement);
syncCollectionPanelWithDOM();
}
function addRatingBar(element) {
if (element.dataset.yummyProcessed) return;
element.dataset.yummyProcessed = 'true';
const container = document.createElement('div');
container.className = 'yummy-paragraph-container';
element.parentNode.insertBefore(container, element);
container.appendChild(element);
const ratingBar = document.createElement('div');
ratingBar.className = 'yummy-rating-bar';
const turnContainer = element.closest('.group\\/turn-messages');
if (turnContainer) {
const turnContainerRect = turnContainer.getBoundingClientRect();
const containerRect = container.getBoundingClientRect();
const indentation = containerRect.left - turnContainerRect.left;
const baseLeftOffset = -85;
ratingBar.style.left = `${baseLeftOffset - indentation}px`;
} else {
// Fallback for elements not inside a turn container, though less likely.
ratingBar.style.left = '-85px';
}
const likeButton = document.createElement('span');
likeButton.className = 'yummy-rating-button';
likeButton.textContent = EMOJI_LIKE;
likeButton.title = '想吃 (Like)';
likeButton.addEventListener('click', async (e) => {
e.stopPropagation();
// Sugar Rush Easter Egg Logic
const now = Date.now();
const tracker = likeClickTracker.get(element) || { count: 0, lastClickTime: 0 };
if (now - tracker.lastClickTime < 3000) {
tracker.count++;
} else {
tracker.count = 1;
}
tracker.lastClickTime = now;
likeClickTracker.set(element, tracker);
if (tracker.count >= 7) {
triggerSugarRush();
likeClickTracker.delete(element); // Reset after triggering
}
const isParent = /H[1-6]/.test(element.tagName);
if (isParent) {
await handleParentRating(element, 'liked');
} else {
const isAlreadyLiked = element.classList.contains('yummy-liked');
await applyHierarchicalState(element, isAlreadyLiked ? 'none' : 'liked');
}
});
const dislikeButton = document.createElement('span');
dislikeButton.className = 'yummy-rating-button';
dislikeButton.textContent = EMOJI_DISLIKE;
dislikeButton.title = '想吐 (Dislike)';
dislikeButton.addEventListener('click', async (e) => {
e.stopPropagation();
const isParent = /H[1-6]/.test(element.tagName);
if (isParent) {
await handleParentRating(element, 'disliked');
} else {
const isAlreadyDisliked = element.classList.contains('yummy-disliked');
await applyHierarchicalState(element, isAlreadyDisliked ? 'none' : 'disliked');
}
});
ratingBar.appendChild(likeButton);
ratingBar.appendChild(dislikeButton);
container.appendChild(ratingBar);
}
const CONTENT_ELEMENTS_SELECTOR = `[data-message-author-role="assistant"] h1, [data-message-author-role="assistant"] h2, [data-message-author-role="assistant"] h3, [data-message-author-role="assistant"] h4, [data-message-author-role="assistant"] h5, [data-message-author-role="assistant"] h6, [data-message-author-role="assistant"] p, [data-message-author-role="assistant"] pre, [data-message-author-role="assistant"] li, [data-message-author-role="assistant"] table`;
async function processNewElements() {
// 旧的 isUnHighlighting 锁检查已被移除,新的锁机制在 debouncedProcessNewElements 中处理
const elementsToProcess = document.querySelectorAll(CONTENT_ELEMENTS_SELECTOR);
for (const element of elementsToProcess) {
const elementId = getStableElementId(element);
// Always try to restore state first from the central state object.
if (elementId && currentConversationState[elementId]) {
const savedData = currentConversationState[elementId];
// BUGFIX: More robust check. Only restore highlight if it's in storage
// AND not already present in the DOM for this element. This prevents
// re-running the destructive innerHTML operation on subsequent updates.
if (savedData.highlightHTML && !element.querySelector('.yummy-selection-highlight')) {
logger.debug(`processNewElements: 正在为 ${elementId} 恢复高亮`, { html: savedData.highlightHTML });
restoreHighlight(element, savedData.highlightHTML);
}
element.classList.remove('yummy-liked', 'yummy-disliked');
if (savedData.rating === 'liked') {
element.classList.add('yummy-liked');
} else if (savedData.rating === 'disliked') {
element.classList.add('yummy-disliked');
}
}
if (!element.dataset.yummyProcessed) {
addRatingBar(element);
}
}
syncCollectionPanelWithDOM();
}
const parentClickState = new Map();
function getSubsequentSiblings(startElement) {
const results = [];
if (!startElement) return results;
const container = startElement.closest('.yummy-paragraph-container');
if (!container) return results;
let nextSibling = container.nextElementSibling;
const startTag = startElement.tagName;
const startLevel = parseInt(startTag.substring(1), 10);
while (nextSibling) {
const elementsInSibling = [];
// Check if the sibling itself is a processable element
if (nextSibling.matches(CONTENT_ELEMENTS_SELECTOR)) {
elementsInSibling.push(nextSibling);
}
// And also find all processable descendants within it.
// This is key to finding all <li>s inside a <ul>.
elementsInSibling.push(...Array.from(nextSibling.querySelectorAll(CONTENT_ELEMENTS_SELECTOR)));
// Remove duplicates that might arise from the above two steps
const uniqueElements = [...new Set(elementsInSibling)];
if (uniqueElements.length > 0) {
const firstContentEl = uniqueElements[0];
// Check if the first element marks a new section, which should stop us.
if (firstContentEl.tagName.match(/^H[1-6]$/)) {
const nextLevel = parseInt(firstContentEl.tagName.substring(1), 10);
if (nextLevel <= startLevel) {
break; // Stop before this new section.
}
}
results.push(...uniqueElements);
}
nextSibling = nextSibling.nextElementSibling;
}
return results;
}
async function handleParentRating(parentElement, newRating) {
const state = parentClickState.get(parentElement) || { rating: 'none', level: 0 };
const children = getSubsequentSiblings(parentElement);
let changedElements = new Map(); // Collect elements and their new state
const applyState = async (el, ratingState) => {
el.classList.remove('yummy-liked', 'yummy-disliked');
if (ratingState === 'liked') el.classList.add('yummy-liked');
else if (ratingState === 'disliked') el.classList.add('yummy-disliked');
const elId = getStableElementId(el);
if (elId) changedElements.set(elId, { rating: ratingState === 'none' ? null : ratingState });
};
if (newRating === state.rating) {
if (state.level === 1) { // Second click -> rate all children
state.level = 2;
for (const child of children) { await applyState(child, newRating); }
logger.debug(`块状评价 (二次点击): ${newRating}`, parentElement);
} else { // Third click -> un-rate all
state.rating = 'none';
state.level = 0;
await applyState(parentElement, 'none');
for (const child of children) { await applyState(child, 'none'); }
logger.debug(`块状评价 (取消): none`, parentElement);
}
} else {
if (state.level === 2) { // Was level 2, now flipping color
state.rating = newRating;
await applyState(parentElement, newRating);
for (const child of children) { await applyState(child, newRating); }
logger.debug(`块状评价 (翻转): ${newRating}`, parentElement);
} else { // First click, or was level 1 and flipping
state.rating = newRating;
state.level = 1;
await applyState(parentElement, 'none'); // Clear visual state first
for (const child of children) { await applyState(child, 'none'); }
await applyState(parentElement, newRating); // Then apply new state to parent only
children.forEach(child => flashElement(child));
logger.debug(`块状评价 (首次点击): ${newRating}`, parentElement);
}
}
parentClickState.set(parentElement, state);
// Batch save all changes at the end
for (const [id, data] of changedElements.entries()) {
await saveData(id, data);
}
syncCollectionPanelWithDOM();
}
let debounceTimer = null;
const debouncedProcessNewElements = () => {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(async () => {
// 在处理任何新元素前,必须等待当前所有的高亮操作(添加/删除)完成。
// 这是确保我们不会在 unhighlight 刚移除DOM节点但还未保存数据时进行重绘的关键。
await highlightLock;
messageElementsCache.clear(); // Clear cache before processing
logger.debug("debouncedProcessNewElements: 锁已释放,开始处理新元素。");
await processNewElements();
}, 500);
};
const observer = new MutationObserver(debouncedProcessNewElements);
let isSelectionModeActive = false;
let quickHighlightButton = null;
let lastSelectionRange = null;
let cursorFollower = null;
let latestMouseX = 0,
latestMouseY = 0;
let isTicking = false;
let collectionPanel = null;
let collectionContent = null;
let collectionHideTimer = null;
let copyToast = null;
let isCollectionPanelPinned = false;
let isAutoSendActive = false;
let activeContextMenu = null;
let previewTooltip = null;
let isPanelAnimating = false;
let collectionItemStates = new Map();
let isMarkdownMode = false; // 新增状态,控制面板显示模式
let turndownService; // 用于转换 HTML 到 Markdown
// let isUnHighlighting = false; // 废弃旧的锁机制
// vNext: 新增一个更可靠的异步锁,用于同步所有可能冲突的重绘和数据操作。
// 所有修改高亮状态的函数都必须先等待这个锁,并在执行关键代码时"持有"它。
let highlightLock = Promise.resolve();
// --- Easter Egg State ---
const likeClickTracker = new Map();
let emptyCopyClickCount = 0;
let emptyCopyClickTimer = null;
let globalAlert = null;
// vNext: 指令菜单所需的状态变量
let instructionMenu = null;
let isInstructionMenuVisible = false;
let currentInstructionIndex = -1;
let aggregatedContentCache = ''; // 用于缓存聚合后的内容
// vNext: 预设指令集
const INSTRUCTIONS = [
{ label: '举一反三', instruction: '请基于我喜欢的部分,再多提供几个类似的例子或观点。', emoji: '1️⃣' },
{ label: '综合优化', instruction: '请综合我的偏好,优化你刚才的回答。', emoji: '2️⃣' },
{ label: '批判性思考', instruction: '请针对我喜欢的内容,提出一些挑战性的问题或反方观点。', emoji: '3️⃣' },
{ label: '融合成文', instruction: '请将我标记为喜欢的所有内容,无缝地整合成一段连贯的文字。', emoji: '4️⃣' },
{ label: '提炼要点', instruction: '请从我喜欢的内容中,提炼出核心要点,并以列表形式呈现。', emoji: '5️⃣' },
{ label: '风格迁移', instruction: '请模仿我喜欢的语句风格,改写我不喜欢的部分。', emoji: '6️⃣' }
];
function flashElement(element) {
element.classList.add('yummy-flash');
setTimeout(() => {
element.classList.remove('yummy-flash');
}, 500);
}
const getCleanText = (element) => {
if (!element) return '';
const clone = element.cloneNode(true);
clone.querySelectorAll('.yummy-rating-bar, .yummy-selection-highlight, .yummy-control-panel, #yummy-quick-highlight-button, #yummy-collection-panel').forEach(ui => ui.remove());
return clone.textContent.trim();
};
function simpleHash(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash |= 0;
}
return `yummy-id-${Math.abs(hash)}`;
}
const getTextWithHighlight = (element) => {
if (!element) return '';
const clone = element.cloneNode(true);
clone.querySelectorAll('.yummy-rating-bar, .yummy-control-panel, #yummy-quick-highlight-button, #yummy-collection-panel').forEach(ui => ui.remove());
return clone.textContent.trim();
};
function generateAggregatePrompt(scopeElement) {
const likedItems = new Set();
scopeElement.querySelectorAll('.yummy-liked').forEach(el => {
const text = getTextWithHighlight(el);
if (text) likedItems.add(text);
});
const dislikedItems = new Set();
scopeElement.querySelectorAll('.yummy-disliked').forEach(el => {
const text = getTextWithHighlight(el);
if (text) dislikedItems.add(text);
});
const highlightedItems = new Set();
scopeElement.querySelectorAll('.yummy-selection-highlight').forEach(el => {
const text = getCleanText(el);
if(text) highlightedItems.add(text);
});
let prompt = '';
const likedText = Array.from(likedItems).join('\n');
const dislikedText = Array.from(dislikedItems).join('\n');
const highlightedText = Array.from(highlightedItems).join('\n');
if (likedText) {
prompt += `在我刚刚生成的内容中,我喜欢的语句有:\n${likedText}`;
}
if (dislikedText) {
if (prompt) prompt += '\n\n';
prompt += `我不喜欢的语句有:\n${dislikedText}`;
}
if (highlightedText) {
if (prompt) prompt += '\n\n';
prompt += `我划线高亮的重点有:\n${highlightedText}`;
}
return prompt ? prompt : null;
}
function injectAndSendPrompt(promptText) {
const inputBox = document.querySelector('div#prompt-textarea');
if (!inputBox) {
showToast('Yummy错误:\n找不到输入框!');
return;
}
let p = inputBox.querySelector('p');
if (!p) {
p = document.createElement('p');
inputBox.innerHTML = '';
inputBox.appendChild(p);
}
p.innerText = promptText;
if (p.classList.contains('placeholder')) {
p.classList.remove('placeholder');
}
inputBox.dispatchEvent(new Event('input', { bubbles: true }));
setTimeout(() => {
const sendButton = document.querySelector('button[data-testid*="send"]:not(:disabled)');
if (sendButton) {
sendButton.click();
} else {
logger.warn('自动发送失败:找不到发送按钮。');
}
}, 200);
}
function openInstructionMenuWithContent(aggregatedContent) {
const inputBox = document.querySelector('div#prompt-textarea');
if (!inputBox) {
showToast('Yummy错误:\n找不到输入框!');
return;
}
let existingText = Array.from(inputBox.querySelectorAll('p')).map(p => p.innerText).join('\n');
const instructionParts = INSTRUCTIONS.map(i => i.instruction.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
const instructionRegex = new RegExp(`\\n\\n(?:${instructionParts.join('|')})$`);
let baseText = existingText.replace(instructionRegex, '').trim();
let newBaseText = baseText;
if (!baseText.includes(aggregatedContent)) {
newBaseText += (baseText ? '\n\n' : '') + aggregatedContent;
}
aggregatedContentCache = newBaseText;
showInstructionMenu();
}
function stableScrollToBottom(scrollContainer) {
requestAnimationFrame(() => {
requestAnimationFrame(() => {
scrollContainer.scrollTop = scrollContainer.scrollHeight;
});
});
}
function updateInputBoxWithInstruction(instructionText = '', isCustom = false) {
const inputBox = document.querySelector('div#prompt-textarea');
if (!inputBox) return;
let p = inputBox.querySelector('p');
if (!p) {
p = document.createElement('p');
inputBox.innerHTML = '';
inputBox.appendChild(p);
}
const baseContent = aggregatedContentCache;
let fullText;
if (isCustom) {
// 修复BUG:在末尾添加一个"零宽度空格",以强制浏览器正确渲染两个换行符,并为光标提供可靠的定位锚点。
fullText = `${baseContent}\n\n\u200B`;
} else {
// 预设指令的情况保持不变。
fullText = instructionText ? `${baseContent}\n\n${instructionText}` : baseContent;
}
p.innerText = fullText;
inputBox.dispatchEvent(new Event('input', { bubbles: true }));
inputBox.focus();
// 修复BUG:使用 requestAnimationFrame 替代 setTimeout,确保光标定位和滚动在DOM完全更新后执行。
requestAnimationFrame(() => {
const selection = window.getSelection();
if (!selection) return;
const paragraph = inputBox.querySelector('p');
if (!paragraph || !paragraph.lastChild) return;
const lastTextNode = paragraph.lastChild;
const textContent = lastTextNode.textContent || '';
const range = document.createRange();
if (!isCustom && instructionText) {
const selectionStart = textContent.length - instructionText.length;
if (selectionStart >= 0) {
range.setStart(lastTextNode, selectionStart);
range.setEnd(lastTextNode, textContent.length);
}
} else {
// 对于自定义情况,将光标定位在段落的末尾。
range.selectNodeContents(paragraph);
range.collapse(false);
}
selection.removeAllRanges();
selection.addRange(range);
// 确保在光标定位后,滚动条稳定地滚动到底部。
const scrollContainer = inputBox.closest('[class*="overflow-auto"]');
if (scrollContainer) {
stableScrollToBottom(scrollContainer);
}
});
}
let toastTimer = null;
function showToast(message, event = null, anchorToFooter = false) {
if (!copyToast) return;
if (toastTimer) {
clearTimeout(toastTimer);
}
copyToast.classList.remove('yummy-toast-panel-mode', 'yummy-toast-cursor-mode', 'yummy-toast-footer-mode', 'visible');
void copyToast.offsetWidth;
copyToast.firstElementChild.textContent = message;
if (anchorToFooter) {
copyToast.classList.add('yummy-toast-footer-mode');
copyToast.style.left = '';
copyToast.style.top = '';
} else if (event) {
copyToast.classList.add('yummy-toast-cursor-mode');
const toastWidth = copyToast.offsetWidth;
let left = event.clientX + 10;
if (left + toastWidth > window.innerWidth) {
left = event.clientX - toastWidth - 10;
}
copyToast.style.left = `${left}px`;
copyToast.style.top = `${event.clientY + 10}px`;
} else {
copyToast.classList.add('yummy-toast-panel-mode');
copyToast.style.left = '50%';
copyToast.style.top = '';
}
copyToast.classList.add('visible');
toastTimer = setTimeout(() => {
copyToast.classList.remove('visible');
toastTimer = null;
}, 2000);
}
function updateFollower() {
if (cursorFollower) {
cursorFollower.style.transform = `translate(${latestMouseX}px, ${latestMouseY}px)`;
}
isTicking = false;
}
function onMouseMove(e) {
latestMouseX = e.clientX;
latestMouseY = e.clientY;
if (!isTicking) {
window.requestAnimationFrame(updateFollower);
isTicking = true;
}
}
function getContainingBlock(node) {
if (!node) return null;
if (node.nodeType !== Node.ELEMENT_NODE) {
node = node.parentElement;
}
if (!node) return null;
return node.closest(CONTENT_ELEMENTS_SELECTOR);
}
function cleanFragment(fragment) {
fragment.querySelectorAll('.yummy-rating-bar').forEach(el => el.remove());
return fragment;
}
function normalizeHighlights(container) {
if (!container) return;
let hasChanges = true;
while (hasChanges) {
hasChanges = false;
// Pass 1: Unwrap nested highlights
const nested = container.querySelector('.yummy-selection-highlight .yummy-selection-highlight');
if (nested && nested.parentNode) {
const parent = nested.parentNode;
while (nested.firstChild) {
parent.insertBefore(nested.firstChild, nested);
}
nested.remove();
hasChanges = true;
continue;
}
// Pass 2: Merge adjacent highlights, even across formatting tags
const highlights = Array.from(container.querySelectorAll('.yummy-selection-highlight'));
for (const current of highlights) {
if (!current.parentNode) continue;
let adjacent = current.nextSibling;
while (adjacent && adjacent.nodeType === Node.TEXT_NODE && adjacent.textContent.trim() === '') {
adjacent = adjacent.nextSibling;
}
if (!adjacent || adjacent.nodeType !== Node.ELEMENT_NODE) continue;
if (adjacent.classList.contains('yummy-selection-highlight')) {
while (adjacent.firstChild) current.appendChild(adjacent.firstChild);
adjacent.remove();
hasChanges = true;
break;
}
const childHighlights = adjacent.querySelectorAll('.yummy-selection-highlight');
const childText = Array.from(childHighlights).map(n => n.textContent).join('');
if (childHighlights.length > 0 && adjacent.textContent.trim() === childText.trim()) {
while (adjacent.firstChild) current.appendChild(adjacent.firstChild);
adjacent.remove();
hasChanges = true;
break;
}
}
}
container.normalize();
}
async function highlightSelection(range) {
let releaseLock;
highlightLock = highlightLock.then(() => new Promise(resolve => {
releaseLock = resolve;
}));
logger.group('highlightSelection: 开始应用高亮');
const selection = window.getSelection();
try {
const effectiveRange = range || (selection.rangeCount > 0 ? selection.getRangeAt(0) : null);
if (!effectiveRange || effectiveRange.collapsed) {
if (selection.rangeCount > 0) selection.removeAllRanges();
logger.debug("highlightSelection: 无有效选中范围,操作取消。");
return;
}
const ancestor = effectiveRange.commonAncestorContainer;
const assistantMessageContainer = (ancestor.nodeType === Node.ELEMENT_NODE ? ancestor : ancestor.parentElement)
.closest('[data-message-author-role="assistant"]');
if (!assistantMessageContainer || (ancestor.nodeType === Node.ELEMENT_NODE && ancestor.closest('.yummy-control-panel, .yummy-rating-bar, #yummy-collection-panel'))) {
if (selection.rangeCount > 0) selection.removeAllRanges();
logger.debug("highlightSelection: 选中内容不在有效区域,操作取消。");
return;
}
const intersectingBlocks = Array.from(assistantMessageContainer.querySelectorAll(CONTENT_ELEMENTS_SELECTOR))
.filter(block => effectiveRange.intersectsNode(block) && !block.closest('.yummy-rating-bar'));
const finalBlocks = intersectingBlocks.filter(el => {
return !intersectingBlocks.some(otherEl => el !== otherEl && el.contains(otherEl));
});
for (const block of finalBlocks) {
const blockRange = document.createRange();
blockRange.selectNodeContents(block);
const intersectionRange = effectiveRange.cloneRange();
if (intersectionRange.compareBoundaryPoints(Range.START_TO_START, blockRange) < 0) {
intersectionRange.setStart(blockRange.startContainer, blockRange.startOffset);
}
if (intersectionRange.compareBoundaryPoints(Range.END_TO_END, blockRange) > 0) {
intersectionRange.setEnd(blockRange.endContainer, blockRange.endOffset);
}
if (!intersectionRange.collapsed) {
const highlightSpan = document.createElement('span');
highlightSpan.className = 'yummy-selection-highlight';
highlightSpan.addEventListener('click', () => unhighlightElement(highlightSpan));
try {
const contents = intersectionRange.extractContents();
cleanFragment(contents);
highlightSpan.appendChild(contents);
intersectionRange.insertNode(highlightSpan);
} catch (e) {
logger.warn('highlightSelection: 包装内容时失败。', e);
}
}
}
finalBlocks.forEach(block => normalizeHighlights(block));
const allBlocksInContainer = new Set(finalBlocks);
const savePromises = [];
for (const block of allBlocksInContainer) {
const elementId = getStableElementId(block);
if (elementId) {
const hasHighlights = block.querySelector('.yummy-selection-highlight');
const oldState = currentConversationState[elementId] || {};
const newHTML = hasHighlights ? block.innerHTML : null;
if (oldState.highlightHTML !== newHTML) {
logger.debug(`highlightSelection: 准备为 ${elementId} 保存数据`, { newHTML });
savePromises.push(saveData(elementId, { highlightHTML: newHTML }));
}
}
}
await Promise.all(savePromises);
logger.info('highlightSelection: 新增高亮数据已保存。');
syncCollectionPanelWithDOM();
} catch (e) {
logger.error('highlightSelection: 高亮过程中发生错误。', e);
} finally {
if (selection.rangeCount > 0) selection.removeAllRanges();
logger.groupEnd();
if (releaseLock) releaseLock();
}
}
async function unhighlightElement(clickedElement) {
let releaseLock;
// 关键:在现有锁之后链接此操作,并创建一个新的未解决的 Promise 作为新的锁。
highlightLock = highlightLock.then(() => new Promise(resolve => {
releaseLock = resolve;
}));
logger.group('unhighlightElement: 开始移除高亮');
try {
const blocksToUpdate = new Set();
const parentBlock = getContainingBlock(clickedElement);
if (parentBlock) {
blocksToUpdate.add(parentBlock);
logger.debug('unhighlightElement: 找到父区块', parentBlock);
}
const parent = clickedElement.parentNode;
if (parent) {
while (clickedElement.firstChild) {
parent.insertBefore(clickedElement.firstChild, clickedElement);
}
parent.removeChild(clickedElement);
logger.debug('unhighlightElement: 已将高亮标签从DOM中移除');
}
// After removing, re-normalize the affected block to merge any now-adjacent highlights
if (parentBlock) {
normalizeHighlights(parentBlock);
logger.debug('unhighlightElement: 已对父区块进行标准化处理');
}
const savePromises = Array.from(blocksToUpdate).map(async (block) => {
block.normalize();
const elementId = getStableElementId(block);
if (elementId) {
const remainingHighlights = block.querySelector('.yummy-selection-highlight');
const newHTML = remainingHighlights ? block.innerHTML : null;
logger.debug(`unhighlightElement: 准备为 ${elementId} 保存数据`, { newHTML });
// 关键:等待数据保存完成
await saveData(elementId, { highlightHTML: newHTML });
}
});
await Promise.all(savePromises);
logger.info(`unhighlightElement: 高亮数据已成功保存。`);
// 数据完全保存后,再同步UI
syncCollectionPanelWithDOM();
} catch (error) {
logger.error('unhighlightElement: 移除高亮过程中发生错误:', error);
} finally {
logger.groupEnd();
// 关键:所有操作完成后,解析Promise,释放锁给下一个等待的操作。
if (releaseLock) {
releaseLock();
}
}
}
function handleTextSelection(event) {
// Debounce mouseup to handle messy selection state from GPT's UI
setTimeout(async () => {
// 在处理文本选择之前,先等待任何可能正在进行的(取消)高亮操作完成。
await highlightLock;
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {
if (quickHighlightButton) quickHighlightButton.style.display = 'none';
return;
}
if (isSelectionModeActive) {
await highlightSelection();
return;
}
const range = selection.getRangeAt(0);
const parentElement = range.commonAncestorContainer.parentElement;
const isInsideAssistantMessage = parentElement.closest('[data-message-author-role="assistant"]');
const isInsideYummyUI = parentElement.closest('.yummy-control-panel, .yummy-rating-bar, #yummy-collection-panel, #yummy-quick-highlight-button');
if (!isInsideAssistantMessage || isInsideYummyUI) {
if (quickHighlightButton) quickHighlightButton.style.display = 'none';
return;
}
lastSelectionRange = range.cloneRange();
quickHighlightButton.style.display = 'flex';
const rect = range.getBoundingClientRect();
quickHighlightButton.style.left = `${event.clientX + 5}px`;
quickHighlightButton.style.top = `${event.clientY + 5}px`;
}, 50);
}
function closeActiveContextMenu() {
if (activeContextMenu) {
activeContextMenu.remove();
activeContextMenu = null;
}
}
syncCollectionPanelWithDOM = function() {
if (!collectionContent) return;
// BUGFIX: Preserve the temporary easter egg item if it exists.
const eggElement = collectionContent.querySelector('.yummy-collection-item-temp-egg');
let collectedItems = [];
const processedElements = new Set();
const addItem = (el, type, customTextExtractor = getCleanText) => {
if (processedElements.has(el)) return;
const text = customTextExtractor(el);
if (text) {
const id = simpleHash(text + type);
const rect = el.getBoundingClientRect();
collectedItems.push({
id,
text,
type,
position: rect.top + window.scrollY,
element: el
});
processedElements.add(el);
}
};
document.querySelectorAll('.yummy-liked:not(.yummy-selection-highlight)').forEach(el => {
if (!el.parentElement.closest('.yummy-liked')) {
addItem(el, 'liked', getTextWithHighlight);
}
});
document.querySelectorAll('.yummy-selection-highlight').forEach(el => {
addItem(el, 'highlight');
});
collectedItems.sort((a, b) => {
const position = a.element.compareDocumentPosition(b.element);
if (position & Node.DOCUMENT_POSITION_FOLLOWING) {
return -1;
} else if (position & Node.DOCUMENT_POSITION_PRECEDING) {
return 1;
} else {
return 0;
}
});
const newIds = collectedItems.map(item => item.id);
const currentIds = Array.from(collectionContent.querySelectorAll('.yummy-collection-item')).map(item => item.dataset.yummyItemId);
let typeChanged = false;
if (newIds.length === currentIds.length && newIds.every((id, index) => id === currentIds[index])) {
const currentItems = Array.from(collectionContent.querySelectorAll('.yummy-collection-item'));
for(let i=0; i<currentItems.length; i++){
const currentTypeClass = Array.from(currentItems[i].classList).find(c => c.startsWith('type-'));
if (currentTypeClass !== `type-${collectedItems[i].type}`) {
typeChanged = true;
break;
}
}
if (!typeChanged) return;
}
const existingIds = new Set(newIds);
for (const id of collectionItemStates.keys()) {
if (!existingIds.has(id)) {
collectionItemStates.delete(id);
}
}
collectionContent.innerHTML = '';
// If the egg element was found, put it back at the top.
if (eggElement) {
collectionContent.prepend(eggElement);
}
if (collectedItems.length > 0) {
collectedItems.forEach(item => {
addItemToCollection(item);
});
}
updateCategoryCheckboxStates();
logger.info(`收集面板已自动同步,共 ${collectedItems.length} 个条目。`);
}
function addItemToCollection(itemData) {