-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqwenModifiedaiWebSummary.user.js
More file actions
1348 lines (1255 loc) · 58.2 KB
/
qwenModifiedaiWebSummary.user.js
File metadata and controls
1348 lines (1255 loc) · 58.2 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
// ==UserScript==
// @name AI Web Summarizer
// @namespace http://tampermonkey.net/
// @version 0.3 // <-- MODIFIED version
// @description Floating AI summarizer button for web pages - Draggable, Toasts, Configurable Hotkey, Import/Export, Reordering, Char Limit Fix, Error Handling, textContent, DOM Reuse
// @author Faisal Bhuiyan
// @match *://*/*
// @grant GM_setClipboard
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_addStyle
// ==/UserScript==
(function() {
'use strict';
// Default Chatbots
const DEFAULT_CHATBOTS = {
'byok': { id: 'byok', name: 'Gemini API', url: 'https://aistudio.google.com/apikey', characterLimit: 100000, premiumCharacterLimit: 200000 },
'chatgpt': { id: 'chatgpt', name: 'ChatGPT', url: 'https://chatgpt.com', characterLimit: 40000, premiumCharacterLimit: 200000 },
'claude': { id: 'claude', name: 'Claude', url: 'https://claude.ai/new', characterLimit: 50000, premiumCharacterLimit: 250000 },
'gemini': { id: 'gemini', name: 'Gemini', url: 'https://gemini.google.com/app', characterLimit: 32000, premiumCharacterLimit: 250000 },
'grok': { id: 'grok', name: 'Grok', url: 'https://grok.com', characterLimit: 100000, premiumCharacterLimit: 200000 },
'deepseek': { id: 'deepseek', name: 'DeepSeek', url: 'https://chat.deepseek.com', characterLimit: 200000, premiumCharacterLimit: 200000 },
'gemini_studio': { id: 'gemini_studio', name: 'Gemini AI Studio', url: 'https://aistudio.google.com/prompts/new_chat', characterLimit: 100000, premiumCharacterLimit: 200000 }
};
// Default Prompts
const DEFAULT_PROMPTS = [
{ id: 'summary', name: 'Summary - Short', content: `Please summarize the following text in under 100 words.
Instructions
1. The summary should be well formatted and easily scannable.
2. Don't start the text with "Let me...", or "Here is the summary...". Just give the results.
3. Please keep it SHORT, no more than 100 words!`, isDefault: true },
{ id: '5-10-points', name: '5-10 Key Points - Short', content: `Please provide the 5-10 most important points from the text.
Use bullet points and emojis to break up the text.` },
{ id: 'key-points-summary', name: 'Summary with Key Points & Takeaways - Detailed', content: `Please provide a summary of the following content in its original tone:
1. First, give a concise one-sentence summary that captures the core message/theme
2. Then, share a breakdown of the main topics discussed. For each topic:
- Expound very briefly on what was discussed on each topic
- Include any notable quotes or statistics if any.
3. End with a brief takeaways
4. Don't go beyond 200 words.
5. Don't start the text with "Let me...", or "Here is the summary...". Just give the results.` },
{ id: 'short-form', name: 'Blinkist-Like Summary - Detailed', content: `Summarize the following content how Blinkist would.
Keep the tone of the content. Keep it conversational.
Break the headers using relevant dynamic emojis.
Go beyond the title in giving the summary, look through entire content.
Sprinkle in quotes or excerpts to better link the summary to the content.
For less than 30 mins long content, don't go beyond 150 words.
For 1hr+ long content don't go beyond 300 words.
Don't start the text with "Let me...", or "Here is the summary...". Just give the results.` }
];
// Truncation Config
const TRUNC_CONFIG = {
characterLimit: 20000,
initialContentRatio: 0.4,
chunkSize: 300,
minChunksPerSegment: 3
};
// Storage Helpers
function getStored(key, defaultVal) {
return GM_getValue(key, defaultVal);
}
function setStored(key, val) {
GM_setValue(key, val);
}
// Initialize storage
if (!getStored('selectedBotId')) setStored('selectedBotId', 'chatgpt');
if (!getStored('selectedPromptId')) setStored('selectedPromptId', 'summary');
if (!getStored('excludedSites')) setStored('excludedSites', []);
if (!getStored('customChatbots')) setStored('customChatbots', {});
if (!getStored('customPrompts')) setStored('customPrompts', []);
if (!getStored('hotkey')) setStored('hotkey', 'Ctrl+J'); // <-- ADDED
if (!getStored('positions')) setStored('positions', {}); // <-- ADDED
// Get all chatbots (default + custom)
function getAllChatbots() {
const custom = getStored('customChatbots', {});
return { ...DEFAULT_CHATBOTS, ...custom };
}
// Get all prompts (default + custom)
function getAllPrompts() {
const custom = getStored('customPrompts', []);
return [...DEFAULT_PROMPTS, ...custom];
}
// Theme Detection
function isDarkMode() {
return window.matchMedia('(prefers-color-scheme: dark)').matches;
}
// --- DRAGGABLE BUTTON LOGIC START ---
let isDragging = false;
let dragStartX, dragStartY;
let initialX, initialY;
function getDraggablePosition() {
const positions = getStored('positions', {});
const hostname = window.location.hostname.replace(/^www\./, '');
return positions[hostname] || { x: '0px', y: '80px' }; // Default bottom-right
}
function saveDraggablePosition(x, y) {
const positions = getStored('positions', {});
const hostname = window.location.hostname.replace(/^www\./, '');
positions[hostname] = { x: x, y: y };
setStored('positions', positions);
}
function handleDragStart(e) {
isDragging = true;
const clientX = e.clientX || (e.touches && e.touches[0].clientX);
const clientY = e.clientY || (e.touches && e.touches[0].clientY);
if (!clientX || !clientY) return;
const style = window.getComputedStyle(container);
initialX = parseInt(style.left, 10) || 0;
initialY = parseInt(style.top, 10) || parseInt(style.bottom, 10) || 0; // Fallback to bottom if top not set
dragStartX = clientX;
dragStartY = clientY;
document.addEventListener('mousemove', handleDragMove);
document.addEventListener('mouseup', handleDragEnd);
document.addEventListener('touchmove', handleDragMove, { passive: false });
document.addEventListener('touchend', handleDragEnd);
}
function handleDragMove(e) {
if (!isDragging) return;
e.preventDefault(); // Prevent text selection during drag
const clientX = e.clientX || (e.touches && e.touches[0].clientX);
const clientY = e.clientY || (e.touches && e.touches[0].clientY);
if (!clientX || !clientY) return;
const dx = clientX - dragStartX;
const dy = clientY - dragStartY;
const newX = initialX + dx;
// For vertical positioning, decide if using top or bottom
// Assuming initialY was bottom, calculate top for positioning
const newTop = window.innerHeight - (initialY + dy); // Adjust for bottom positioning
container.style.left = `${newX}px`;
container.style.top = `${newTop}px`;
container.style.bottom = 'auto'; // Explicitly set to auto when using top
}
function handleDragEnd() {
if (isDragging) {
isDragging = false;
const currentX = parseInt(container.style.left, 10) || 0;
// Calculate bottom based on top for saving
const currentTop = parseInt(container.style.top, 10) || 0;
const currentBottom = window.innerHeight - currentTop;
saveDraggablePosition(`${currentX}px`, `${currentBottom}px`);
}
document.removeEventListener('mousemove', handleDragMove);
document.removeEventListener('mouseup', handleDragEnd);
document.removeEventListener('touchmove', handleDragMove);
document.removeEventListener('touchend', handleDragEnd);
}
// --- DRAGGABLE BUTTON LOGIC END ---
// --- TOAST NOTIFICATION LOGIC START ---
function showToast(message) {
const toast = document.getElementById('jsTLDR-toast');
if (toast) {
toast.textContent = message;
toast.classList.add('jsTLDR-toast-show');
setTimeout(() => {
toast.classList.remove('jsTLDR-toast-show');
}, 2000);
} else {
console.warn("Toast element not found, cannot show message:", message);
}
}
// --- TOAST NOTIFICATION LOGIC END ---
// --- UPDATE MAIN BUTTON TOOLTIP START ---
function updateMainButtonTooltip() {
const selectedBotId = getStored('selectedBotId');
const selectedPromptId = getStored('selectedPromptId');
const allBots = getAllChatbots();
const allPrompts = getAllPrompts();
const bot = allBots[selectedBotId];
const prompt = allPrompts.find(p => p.id === selectedPromptId);
const botName = bot ? bot.name : 'Unknown Bot';
const promptName = prompt ? prompt.name : 'Unknown Prompt';
mainButton.title = `🤖 ${botName} | 📝 ${promptName}`;
}
// --- UPDATE MAIN BUTTON TOOLTIP END ---
// Styles with namespacing - Added toast style
GM_addStyle(`
#jsTLDR-container {
position: fixed !important;
/* Removed initial bottom/right positioning, will be set by script */
z-index: 2147483647 !important;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif !important;
/* Initial cursor to indicate draggable */
cursor: move;
}
#jsTLDR-main-button {
width: 40px !important;
height: 40px !important;
background: rgba(255,255,255,0.1) !important;
opacity: 0.5 !important;
backdrop-filter: blur(10px) !important;
border-radius: 16px 0 0 16px !important;
border: none !important;
cursor: pointer !important;
transition: all 0.2s !important;
box-shadow: 0 4px 12px rgba(0,0,0,0.1) !important;
display: flex !important;
align-items: center !important;
justify-content: center !important;
font-size: 20px !important;
padding: 0 !important;
margin: 0 !important;
}
#jsTLDR-main-button:hover {
opacity: 1 !important;
transform: translateX(-2px) !important;
background: rgba(255,255,255,0.2) !important;
box-shadow: 0 4px 12px rgba(0,0,0,0.15) !important;
}
.jsTLDR-popup-menu {
position: absolute !important;
bottom: 44px !important;
right: 2px !important;
display: none !important;
flex-direction: column !important;
gap: 8px !important;
background: ${isDarkMode() ? 'rgba(30,30,30,0.95)' : 'rgba(255,255,255,0.95)'} !important;
border: 1px solid ${isDarkMode() ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.1)'} !important;
border-radius: 8px !important;
padding: 8px !important;
box-shadow: 0 4px 20px rgba(0,0,0,0.2) !important;
z-index: 2147483647 !important;
}
.jsTLDR-popup-menu.jsTLDR-show {
display: flex !important;
}
.jsTLDR-menu-button {
width: 32px !important;
height: 32px !important;
background: ${isDarkMode() ? 'rgba(60,60,60,0.8)' : 'rgba(240,240,240,0.8)'} !important;
border: none !important;
border-radius: 6px !important;
cursor: pointer !important;
transition: all 0.2s !important;
font-size: 16px !important;
display: flex !important;
align-items: center !important;
justify-content: center !important;
padding: 0 !important;
margin: 0 !important;
}
.jsTLDR-menu-button:hover {
background: ${isDarkMode() ? 'rgba(80,80,80,0.9)' : 'rgba(220,220,220,0.9)'} !important;
transform: scale(1.05) !important;
}
.jsTLDR-dropdown {
position: absolute !important;
right: 40px !important;
bottom: 0 !important;
width: 220px !important;
max-height: 300px !important;
overflow-y: auto !important;
background: ${isDarkMode() ? 'rgba(30,30,30,0.98)' : 'rgba(255,255,255,0.98)'} !important;
border: 1px solid ${isDarkMode() ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.1)'} !important;
border-radius: 8px !important;
padding: 4px !important;
display: none !important;
z-index: 2147483648 !important;
box-shadow: 0 4px 20px rgba(0,0,0,0.3) !important;
}
.jsTLDR-dropdown.jsTLDR-show {
display: block !important;
}
.jsTLDR-dropdown-item {
padding: 10px 12px !important;
cursor: pointer !important;
border: none !important;
width: 100% !important;
text-align: left !important;
background: transparent !important;
color: ${isDarkMode() ? '#fff' : '#000'} !important;
border-radius: 4px !important;
transition: background 0.15s !important;
font-size: 14px !important;
margin: 0 !important;
display: flex !important;
align-items: center !important;
justify-content: space-between !important;
}
.jsTLDR-dropdown-item:hover {
background: ${isDarkMode() ? 'rgba(80,80,80,0.5)' : 'rgba(0,0,0,0.05)'} !important;
}
.jsTLDR-dropdown-item.jsTLDR-selected {
background: ${isDarkMode() ? 'rgba(59,130,246,0.2)' : 'rgba(59,130,246,0.1)'} !important;
color: ${isDarkMode() ? '#60a5fa' : '#2563eb'} !important;
}
.jsTLDR-checkmark {
font-size: 12px !important;
margin-left: 8px !important;
}
/* Modal Styles */
.jsTLDR-modal-overlay {
position: fixed !important;
top: 0 !important;
left: 0 !important;
right: 0 !important;
bottom: 0 !important;
background: rgba(0,0,0,0.6) !important;
display: none !important;
align-items: center !important;
justify-content: center !important;
z-index: 2147483646 !important;
padding: 20px !important;
}
.jsTLDR-modal-overlay.jsTLDR-show {
display: flex !important;
}
.jsTLDR-modal {
background: ${isDarkMode() ? '#1a1a1a' : '#ffffff'} !important;
border-radius: 12px !important;
width: 100% !important;
max-width: 600px !important;
max-height: 80vh !important;
overflow-y: auto !important;
box-shadow: 0 20px 60px rgba(0,0,0,0.4) !important;
padding: 0 !important;
margin: 0 !important;
}
.jsTLDR-modal-header {
padding: 20px 24px !important;
border-bottom: 1px solid ${isDarkMode() ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.1)'} !important;
display: flex !important;
align-items: center !important;
justify-content: space-between !important;
}
.jsTLDR-modal-title {
font-size: 18px !important;
font-weight: 600 !important;
color: ${isDarkMode() ? '#fff' : '#000'} !important;
margin: 0 !important;
padding: 0 !important;
}
.jsTLDR-modal-close {
background: none !important;
border: none !important;
font-size: 24px !important;
cursor: pointer !important;
color: ${isDarkMode() ? '#999' : '#666'} !important;
padding: 0 !important;
margin: 0 !important;
line-height: 1 !important;
}
.jsTLDR-modal-close:hover {
color: ${isDarkMode() ? '#fff' : '#000'} !important;
}
.jsTLDR-modal-body {
padding: 24px !important;
}
.jsTLDR-tabs {
display: flex !important;
gap: 8px !important;
margin-bottom: 20px !important;
border-bottom: 1px solid ${isDarkMode() ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.1)'} !important;
}
.jsTLDR-tab {
padding: 10px 16px !important;
background: none !important;
border: none !important;
cursor: pointer !important;
color: ${isDarkMode() ? '#999' : '#666'} !important;
font-size: 14px !important;
font-weight: 500 !important;
border-bottom: 2px solid transparent !important;
transition: all 0.2s !important;
}
.jsTLDR-tab.jsTLDR-active {
color: ${isDarkMode() ? '#60a5fa' : '#2563eb'} !important;
border-bottom-color: ${isDarkMode() ? '#60a5fa' : '#2563eb'} !important;
}
.jsTLDR-tab-content {
display: none !important;
}
.jsTLDR-tab-content.jsTLDR-active {
display: block !important;
}
.jsTLDR-form-group {
margin-bottom: 16px !important;
}
.jsTLDR-label {
display: block !important;
margin-bottom: 6px !important;
color: ${isDarkMode() ? '#ccc' : '#333'} !important;
font-size: 14px !important;
font-weight: 500 !important;
}
.jsTLDR-input, .jsTLDR-textarea {
width: 100% !important;
padding: 10px 12px !important;
background: ${isDarkMode() ? '#2a2a2a' : '#f5f5f5'} !important;
border: 1px solid ${isDarkMode() ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.1)'} !important;
border-radius: 6px !important;
color: ${isDarkMode() ? '#fff' : '#000'} !important;
font-size: 14px !important;
font-family: inherit !important;
box-sizing: border-box !important;
}
.jsTLDR-textarea {
min-height: 120px !important;
resize: vertical !important;
}
.jsTLDR-button {
padding: 10px 20px !important;
background: ${isDarkMode() ? '#3b82f6' : '#2563eb'} !important;
color: #fff !important;
border: none !important;
border-radius: 6px !important;
cursor: pointer !important;
font-size: 14px !important;
font-weight: 500 !important;
transition: background 0.2s !important;
}
.jsTLDR-button:hover {
background: ${isDarkMode() ? '#2563eb' : '#1d4ed8'} !important;
}
.jsTLDR-button-secondary {
background: ${isDarkMode() ? '#374151' : '#e5e7eb'} !important;
color: ${isDarkMode() ? '#fff' : '#000'} !important;
}
.jsTLDR-button-secondary:hover {
background: ${isDarkMode() ? '#4b5563' : '#d1d5db'} !important;
}
.jsTLDR-list-item {
padding: 12px !important;
background: ${isDarkMode() ? '#2a2a2a' : '#f5f5f5'} !important;
border-radius: 6px !important;
margin-bottom: 8px !important;
display: flex !important;
justify-content: space-between !important;
align-items: center !important;
}
.jsTLDR-list-item-content {
flex: 1 !important;
}
.jsTLDR-list-item-title {
font-weight: 500 !important;
color: ${isDarkMode() ? '#fff' : '#000'} !important;
margin-bottom: 2px !important;
}
.jsTLDR-list-item-subtitle {
font-size: 12px !important;
color: ${isDarkMode() ? '#999' : '#666'} !important;
}
.jsTLDR-list-item-actions {
display: flex !important;
gap: 4px !important; /* Reduced gap for new buttons */
}
.jsTLDR-icon-button {
padding: 6px 10px !important;
background: ${isDarkMode() ? '#374151' : '#e5e7eb'} !important;
border: none !important;
border-radius: 4px !important;
cursor: pointer !important;
font-size: 12px !important;
color: ${isDarkMode() ? '#fff' : '#000'} !important;
}
.jsTLDR-icon-button:hover {
background: ${isDarkMode() ? '#4b5563' : '#d1d5db'} !important;
}
.jsTLDR-icon-button.jsTLDR-danger:hover {
background: #dc2626 !important;
color: #fff !important;
}
@media (max-width: 640px) {
.jsTLDR-modal {
max-width: 100% !important;
margin: 0 !important;
border-radius: 0 !important;
max-height: 100vh !important;
}
.jsTLDR-dropdown {
width: 200px !important;
}
}
/* Toast Notification Styles */
.jsTLDR-toast {
position: fixed !important;
bottom: 20px !important;
left: 50% !important;
transform: translateX(-50%) translateY(100%) !important;
background: rgba(0, 0, 0, 0.8) !important;
color: white !important;
padding: 12px 24px !important;
border-radius: 8px !important;
z-index: 2147483647 !important; /* Very high z-index */
transition: transform 0.3s ease !important;
font-size: 14px !important;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif !important;
box-shadow: 0 4px 12px rgba(0,0,0,0.2) !important;
}
.jsTLDR-toast.jsTLDR-toast-show {
transform: translateX(-50%) translateY(0) !important;
}
`);
// Extract Page Content
async function extractPageContent() {
const ignore = 'nav, aside, header, footer, button, script, style';
const targets = ['h1','h2','h3','h4','h5','h6','p','li','td','div:not(:empty)']
.map(tag => `${tag}:not(${ignore}):not(${ignore} *)`).join(', ');
const els = document.querySelectorAll(targets);
let content = '';
for (const el of els) {
if (el.offsetHeight === 0 || el.closest(ignore) || !el.textContent?.trim()) continue; // <-- MODIFIED: textContent
const parent = el.parentElement;
if (parent && (parent.matches('h1,h2,h3,h4,h5,h6,div,span,p,li') || parent.closest('h1,h2,h3,h4,h5,h6,div,span,p,li'))) continue;
let text = el.textContent.trim().replace(/<[^>]+>/g, '').trim(); // <-- MODIFIED: textContent
if (!text) continue;
switch (el.tagName.toLowerCase()) {
case 'h1': content += `# ${text}\n`; break;
case 'h2': content += `## ${text}\n`; break;
case 'h3': content += `### ${text}\n`; break;
case 'h4': case 'h5': case 'h6': content += `#### ${text}\n`; break;
case 'li': content += `• ${text}\n`; break;
default: content += `${text}\n`;
}
}
return content.replace(/\n{2,}/g, '\n');
}
// Truncation Helpers
function chunkText(text, size) {
const chunks = [];
let start = 0;
while (start < text.length) {
if (start + size >= text.length) {
chunks.push(text.slice(start).trim());
break;
}
let slice = text.slice(start, start + size);
const lastSpace = slice.lastIndexOf(' ');
slice = slice.slice(0, lastSpace);
start += lastSpace + 1;
chunks.push(slice.trim());
}
return chunks;
}
function totalLength(chunks) {
return chunks.reduce((sum, c) => sum + c.length, 0);
}
function getProportions(total, num) {
if (total <= 0 || num <= 0) return [];
const props = [];
const step = 1 / (num + 1);
for (let i = 1; i <= num; i++) props.push(step * i);
return props;
}
function truncateText(text, config) {
const cfg = { ...TRUNC_CONFIG, ...config };
if (text.length <= cfg.characterLimit) return text;
const chunks = chunkText(text, cfg.chunkSize);
const samples = [];
let len = 0;
const initLimit = Math.floor(cfg.characterLimit * cfg.initialContentRatio);
let i = 0;
while (i < chunks.length && len < initLimit) {
const c = chunks[i];
if (len + c.length <= initLimit) {
samples.push(c);
len += c.length;
} else {
const rem = initLimit - len;
if (rem > 10) {
samples.push(c.slice(0, rem));
len += rem;
}
break;
}
i++;
}
const remChunks = chunks.slice(i);
if (remChunks.length > 0) {
const avg = totalLength(remChunks) / remChunks.length;
const numSeg = Math.floor((cfg.characterLimit - len) / (avg * cfg.minChunksPerSegment));
const props = getProportions(remChunks.length, numSeg);
for (const p of props) {
if (len >= cfg.characterLimit) break;
const startIdx = Math.floor(remChunks.length * p);
const numC = Math.min(cfg.minChunksPerSegment, remChunks.length - startIdx);
for (let j = 0; j < numC; j++) {
const c = remChunks[startIdx + j];
const space = cfg.characterLimit - len;
if (c.length <= space) {
samples.push(c);
len += c.length;
} else if (space > 10) {
samples.push(c.slice(0, space));
len += space;
break;
}
}
}
}
return samples.join('').replace(/[\n\r]+/g, ' ').replace(/\s{2,}/g, ' ').trim();
}
// Summarize Action
async function summarize() {
try { // <-- ADDED: Try-catch for extraction
const botId = getStored('selectedBotId');
const promptId = getStored('selectedPromptId');
const allBots = getAllChatbots();
const allPrompts = getAllPrompts();
const bot = allBots[botId];
const prompt = allPrompts.find(p => p.id === promptId);
if (!bot || !prompt) {
alert('Please select a valid chatbot and prompt');
return;
}
const raw = await extractPageContent(); // <-- MODIFIED: Wrapped in try-catch
const botCharLimit = bot.characterLimit || Infinity; // Fallback if no limit set
// Calculate available space for content
const availableSpace = botCharLimit - prompt.content.length - 50; // 50 char buffer
// Truncate content first based on available space
const truncRaw = truncateText(raw, { characterLimit: availableSpace });
// Combine prompt and truncated content
const fullText = `${prompt.content}\nPage Content: ${truncRaw}`;
// Final truncation if necessary (e.g., if prompt itself was very long)
const final = truncateText(fullText, { characterLimit: botCharLimit });
try { // <-- ADDED: Try-catch for clipboard
GM_setClipboard(final);
showToast(`Copied! Opening ${bot.name}...`); // <-- ADDED: Toast notification
window.open(bot.url, '_blank');
} catch (clipError) { // <-- ADDED: Alert if clipboard fails
console.error("Clipboard copy failed:", clipError);
alert("Failed to copy text to clipboard. Please check browser permissions.");
}
} catch (extractError) { // <-- ADDED: Show toast if extraction fails
console.error("Content extraction failed:", extractError);
showToast("Content extraction failed.");
}
}
// UI State
let menuHideTimeout = null;
let lastTapTime = 0;
// Create UI
const container = document.createElement('div');
container.id = 'jsTLDR-container';
// Set initial position based on stored value or default
const initialPos = getDraggablePosition();
container.style.left = initialPos.x;
container.style.bottom = initialPos.y;
const mainButton = document.createElement('button');
mainButton.id = 'jsTLDR-main-button';
mainButton.innerHTML = '🤖'; // Or your original emoji
mainButton.title = 'AI Summarizer'; // Initial tooltip
// --- TOAST ELEMENT START ---
const toast = document.createElement('div');
toast.id = 'jsTLDR-toast';
toast.className = 'jsTLDR-toast';
document.body.appendChild(toast);
// --- TOAST ELEMENT END ---
const popupMenu = document.createElement('div');
popupMenu.className = 'jsTLDR-popup-menu';
// Show/hide menu with delay
function showMenu() {
if (menuHideTimeout) {
clearTimeout(menuHideTimeout);
menuHideTimeout = null;
}
popupMenu.classList.add('jsTLDR-show');
}
function hideMenuWithDelay() {
menuHideTimeout = setTimeout(() => {
popupMenu.classList.remove('jsTLDR-show');
}, 300);
}
// --- DRAGGABLE EVENT LISTENERS START ---
mainButton.addEventListener('mousedown', handleDragStart);
mainButton.addEventListener('touchstart', handleDragStart, { passive: false });
// --- DRAGGABLE EVENT LISTENERS END ---
// Desktop hover
mainButton.addEventListener('mouseenter', showMenu);
mainButton.addEventListener('mouseleave', hideMenuWithDelay);
popupMenu.addEventListener('mouseenter', showMenu);
popupMenu.addEventListener('mouseleave', hideMenuWithDelay);
// Desktop click
mainButton.addEventListener('click', (e) => {
e.preventDefault();
summarize();
});
// Mobile tap (single = show menu, double = summarize)
mainButton.addEventListener('touchstart', (e) => {
e.preventDefault();
const now = Date.now();
const timeSinceLastTap = now - lastTapTime;
if (timeSinceLastTap < 300 && timeSinceLastTap > 0) {
// Double tap
summarize();
} else {
// Single tap
if (popupMenu.classList.contains('jsTLDR-show')) {
popupMenu.classList.remove('jsTLDR-show');
} else {
showMenu();
}
}
lastTapTime = now;
});
// Bot Dropdown
const botBtn = document.createElement('button');
botBtn.className = 'jsTLDR-menu-button';
botBtn.innerHTML = '⚙️';
const botDropdown = document.createElement('div');
botDropdown.className = 'jsTLDR-dropdown';
botDropdown.id = 'jsTLDR-bot-dropdown';
function renderBotDropdown() {
botDropdown.innerHTML = ''; // This part remains the same for simplicity, but could be optimized
const allBots = getAllChatbots();
const selectedId = getStored('selectedBotId');
Object.values(allBots).forEach(bot => {
const item = document.createElement('button');
item.className = 'jsTLDR-dropdown-item';
if (bot.id === selectedId) {
item.classList.add('jsTLDR-selected');
}
item.innerHTML = `<span>${bot.name}</span>${bot.id === selectedId ? '<span class="jsTLDR-checkmark">✓</span>' : ''}`;
item.onclick = () => {
setStored('selectedBotId', bot.id);
botDropdown.classList.remove('jsTLDR-show');
renderBotDropdown();
updateMainButtonTooltip(); // <-- ADDED: Update tooltip after selection
};
botDropdown.appendChild(item);
});
}
botBtn.onclick = (e) => {
e.stopPropagation();
botDropdown.classList.toggle('jsTLDR-show');
promptDropdown.classList.remove('jsTLDR-show');
renderBotDropdown();
};
// Prompt Dropdown
const promptBtn = document.createElement('button');
promptBtn.className = 'jsTLDR-menu-button';
promptBtn.innerHTML = '📝';
const promptDropdown = document.createElement('div');
promptDropdown.className = 'jsTLDR-dropdown';
promptDropdown.id = 'jsTLDR-prompt-dropdown';
function renderPromptDropdown() {
promptDropdown.innerHTML = ''; // This part remains the same for simplicity, but could be optimized
const allPrompts = getAllPrompts();
const selectedId = getStored('selectedPromptId');
allPrompts.forEach(prompt => {
const item = document.createElement('button');
item.className = 'jsTLDR-dropdown-item';
if (prompt.id === selectedId) {
item.classList.add('jsTLDR-selected');
}
item.innerHTML = `<span>${prompt.name}</span>${prompt.id === selectedId ? '<span class="jsTLDR-checkmark">✓</span>' : ''}`;
item.onclick = () => {
setStored('selectedPromptId', prompt.id);
promptDropdown.classList.remove('jsTLDR-show');
renderPromptDropdown();
updateMainButtonTooltip(); // <-- ADDED: Update tooltip after selection
};
promptDropdown.appendChild(item);
});
}
promptBtn.onclick = (e) => {
e.stopPropagation();
promptDropdown.classList.toggle('jsTLDR-show');
botDropdown.classList.remove('jsTLDR-show');
renderPromptDropdown();
};
// --- SETTINGS MODAL DOM REUSE START ---
const modalOverlay = document.createElement('div');
modalOverlay.className = 'jsTLDR-modal-overlay';
const modal = document.createElement('div');
modal.className = 'jsTLDR-modal';
modalOverlay.appendChild(modal);
// Store initial modal structure parts for reuse
const settingsModalContent = document.createElement('div');
settingsModalContent.innerHTML = `
<div class="jsTLDR-modal-header">
<h2 class="jsTLDR-modal-title">Settings</h2>
<button class="jsTLDR-modal-close">✕</button>
</div>
<div class="jsTLDR-modal-body">
<div class="jsTLDR-tabs">
<button class="jsTLDR-tab jsTLDR-active" data-tab="prompts">Custom Prompts</button>
<button class="jsTLDR-tab" data-tab="chatbots">Custom Chatbots</button>
<button class="jsTLDR-tab" data-tab="exclusions">Site Exclusions</button>
<button class="jsTLDR-tab" data-tab="settings">General Settings</button> <!-- Added settings tab -->
</div>
<div class="jsTLDR-tab-content jsTLDR-active" data-content="prompts">
<div id="jsTLDR-prompts-list"></div>
<button class="jsTLDR-button" id="jsTLDR-add-prompt">+ Add Prompt</button>
</div>
<div class="jsTLDR-tab-content" data-content="chatbots">
<div id="jsTLDR-chatbots-list"></div>
<button class="jsTLDR-button" id="jsTLDR-add-chatbot">+ Add Chatbot</button>
</div>
<div class="jsTLDR-tab-content" data-content="exclusions">
<div id="jsTLDR-exclusions-list"></div>
<button class="jsTLDR-button" id="jsTLDR-add-exclusion">+ Exclude Current Site</button>
</div>
<div class="jsTLDR-tab-content" data-content="settings"> <!-- Added settings content -->
<div class="jsTLDR-form-group">
<label class="jsTLDR-label">Hotkey (e.g., Ctrl+J, Ctrl+Shift+K)</label>
<input type="text" class="jsTLDR-input" id="jsTLDR-hotkey-input" value="${getStored('hotkey', 'Ctrl+J')}">
</div>
<div style="margin-top: 20px;">
<button class="jsTLDR-button jsTLDR-button-secondary" id="jsTLDR-export-settings">Export Settings</button>
<button class="jsTLDR-button jsTLDR-button-secondary" style="margin-left: 8px;" id="jsTLDR-import-settings">Import Settings</button>
</div>
</div>
</div>
`;
function closeModal() {
modalOverlay.classList.remove('jsTLDR-show');
}
modalOverlay.onclick = (e) => {
if (e.target === modalOverlay) closeModal();
};
function renderModal() {
// Clear modal and append the stored structure
modal.innerHTML = '';
modal.appendChild(settingsModalContent.cloneNode(true));
// Tab switching
const tabs = modal.querySelectorAll('.jsTLDR-tab');
const contents = modal.querySelectorAll('.jsTLDR-tab-content');
tabs.forEach(tab => {
tab.onclick = () => {
tabs.forEach(t => t.classList.remove('jsTLDR-active'));
contents.forEach(c => c.classList.remove('jsTLDR-active'));
tab.classList.add('jsTLDR-active');
const contentId = tab.dataset.tab;
modal.querySelector(`[data-content="${contentId}"]`).classList.add('jsTLDR-active');
};
});
modal.querySelector('.jsTLDR-modal-close').onclick = closeModal;
// Populate list contents
renderPromptsList();
renderChatbotsList();
renderExclusionsList();
// Add handlers for Add buttons
modal.querySelector('#jsTLDR-add-prompt').onclick = () => showPromptForm();
modal.querySelector('#jsTLDR-add-chatbot').onclick = () => showChatbotForm();
modal.querySelector('#jsTLDR-add-exclusion').onclick = () => {
const site = window.location.hostname.replace(/^www\./, '');
const exclusions = getStored('excludedSites', []);
if (!exclusions.includes(site)) {
setStored('excludedSites', [...exclusions, site]);
renderExclusionsList();
}
};
// --- IMPORT/EXPORT HANDLERS START ---
modal.querySelector('#jsTLDR-export-settings').onclick = exportSettings;
modal.querySelector('#jsTLDR-import-settings').onclick = () => {
const input = document.createElement('input');
input.type = 'file';
input.accept = '.json';
input.onchange = (e) => {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = (event) => {
try {
const content = JSON.parse(event.target.result);
importSettings(content);
} catch (error) {
alert("Error parsing JSON file: " + error.message);
}
};
reader.readAsText(file);
}
};
input.click();
};
// --- IMPORT/EXPORT HANDLERS END ---
// --- HOTKEY INPUT HANDLER START ---
modal.querySelector('#jsTLDR-hotkey-input').onchange = (e) => {
setStored('hotkey', e.target.value.trim());
};
// --- HOTKEY INPUT HANDLER END ---
}
function renderPromptsList() {
const container = modal.querySelector('#jsTLDR-prompts-list');
if (!container) return; // Check if container exists in current modal instance
const customPrompts = getStored('customPrompts', []);
if (customPrompts.length === 0) {
container.innerHTML = '<p style="color: #999; text-align: center; padding: 20px;">No custom prompts yet</p>';
return;
}
container.innerHTML = ''; // Clear previous content
customPrompts.forEach((prompt, index) => {
const item = document.createElement('div');
item.className = 'jsTLDR-list-item';
item.innerHTML = `
<div class="jsTLDR-list-item-content">
<div class="jsTLDR-list-item-title">${prompt.name}</div>
<div class="jsTLDR-list-item-subtitle">${prompt.content.substring(0, 50)}...</div>
</div>
<div class="jsTLDR-list-item-actions">
<button class="jsTLDR-icon-button" data-action="up" data-index="${index}">↑</button> <!-- Added -->
<button class="jsTLDR-icon-button" data-action="down" data-index="${index}">↓</button> <!-- Added -->
<button class="jsTLDR-icon-button" data-action="edit" data-index="${index}">✏️</button>
<button class="jsTLDR-icon-button jsTLDR-danger" data-action="delete" data-index="${index}">🗑️</button>
</div>
`;
container.appendChild(item);
});
// Attach handlers for reorder buttons
container.querySelectorAll('[data-action="up"]').forEach(btn => {
btn.onclick = () => {
const index = parseInt(btn.dataset.index);
if (index > 0) {
const prompts = getStored('customPrompts', []);
[prompts[index - 1], prompts[index]] = [prompts[index], prompts[index - 1]];
setStored('customPrompts', prompts);
renderPromptsList(); // Refresh the list
renderPromptDropdown(); // Refresh dropdown
}
};
});
container.querySelectorAll('[data-action="down"]').forEach(btn => {
btn.onclick = () => {
const index = parseInt(btn.dataset.index);
const prompts = getStored('customPrompts', []);
if (index < prompts.length - 1) {
[prompts[index], prompts[index + 1]] = [prompts[index + 1], prompts[index]];
setStored('customPrompts', prompts);
renderPromptsList(); // Refresh the list
renderPromptDropdown(); // Refresh dropdown
}
};
});
// Attach handlers for edit/delete buttons (existing logic)
container.querySelectorAll('[data-action="edit"]').forEach(btn => {
btn.onclick = () => {
const index = parseInt(btn.dataset.index);
showPromptForm(customPrompts[index], index);
};
});