forked from Darsh-A/Ai-TabGroups-ZenBrowser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtab_sort_clear.uc.js
More file actions
1718 lines (1521 loc) · 86.1 KB
/
tab_sort_clear.uc.js
File metadata and controls
1718 lines (1521 loc) · 86.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
// VERSION 4.11.0 (Added Mistral API support)
(() => {
// --- Configuration ---
// Feature toggle preference keys
const ENABLE_SORT_PREF = "extensions.tabgroups.enable_sort";
const ENABLE_CLEAR_PREF = "extensions.tabgroups.enable_clear";
// Preference Key for AI Model Selection
const AI_MODEL_PREF = "extensions.tabgroups.ai_model"; // '1' for Gemini, '2' for Ollama, '3' for Mistral
// Preference Keys for AI Config
const OLLAMA_ENDPOINT_PREF = "extensions.tabgroups.ollama_endpoint";
const OLLAMA_MODEL_PREF = "extensions.tabgroups.ollama_model";
const GEMINI_API_KEY_PREF = "extensions.tabgroups.gemini_api_key";
const GEMINI_MODEL_PREF = "extensions.tabgroups.gemini_model";
const MISTRAL_API_KEY_PREF = "extensions.tabgroups.mistral_api_key";
const MISTRAL_MODEL_PREF = "extensions.tabgroups.mistral_model";
// Helper function to read preferences with fallbacks
const getPref = (prefName, defaultValue = "") => {
try {
const prefService = Services.prefs;
if (prefService.prefHasUserValue(prefName)) {
switch (prefService.getPrefType(prefName)) {
case prefService.PREF_STRING:
return prefService.getStringPref(prefName);
case prefService.PREF_INT:
return prefService.getIntPref(prefName);
case prefService.PREF_BOOL:
return prefService.getBoolPref(prefName);
}
}
} catch (e) {
console.warn(`Failed to read preference ${prefName}:`, e);
}
return defaultValue;
};
// Read preference values
const ENABLE_SORT_VALUE = getPref(ENABLE_SORT_PREF, true);
const ENABLE_CLEAR_VALUE = getPref(ENABLE_CLEAR_PREF, true);
const AI_MODEL_VALUE = getPref(AI_MODEL_PREF, "1"); // Default to Gemini
const OLLAMA_ENDPOINT_VALUE = getPref(OLLAMA_ENDPOINT_PREF, "http://localhost:11434/api/generate");
const OLLAMA_MODEL_VALUE = getPref(OLLAMA_MODEL_PREF, "llama3.2");
const GEMINI_API_KEY_VALUE = getPref(GEMINI_API_KEY_PREF, "");
const GEMINI_MODEL_VALUE = getPref(GEMINI_MODEL_PREF, "gemini-2.0-flash");
const MISTRAL_API_KEY_VALUE = getPref(MISTRAL_API_KEY_PREF, "");
const MISTRAL_MODEL_VALUE = getPref(MISTRAL_MODEL_PREF, "mistral-large-latest");
const CONFIG = {
featureConfig: {
sort: ENABLE_SORT_VALUE,
clear: ENABLE_CLEAR_VALUE
},
apiConfig: {
ollama: {
endpoint: OLLAMA_ENDPOINT_VALUE,
enabled: AI_MODEL_VALUE == "2",
model: OLLAMA_MODEL_VALUE,
promptTemplateBatch: `Analyze the following numbered list of tab data (Title, URL, Description) and assign a concise category (1-2 words, Title Case) for EACH tab.
Existing Categories (Use these EXACT names if a tab fits):
{EXISTING_CATEGORIES_LIST}
---
Instructions for Assignment:
1. **Prioritize Existing:** For each tab below, determine if it clearly belongs to one of the 'Existing Categories'. Base this primarily on the URL/Domain, then Title/Description. If it fits, you MUST use the EXACT category name provided in the 'Existing Categories' list. DO NOT create a minor variation (e.g., if 'Project Docs' exists, use that, don't create 'Project Documentation').
2. **Assign New Category (If Necessary):** Only if a tab DOES NOT fit an existing category, assign the best NEW concise category (1-2 words, Title Case).
* PRIORITIZE the URL/Domain (e.g., 'GitHub', 'YouTube', 'StackOverflow').
* Use Title/Description for specifics or generic domains.
3. **Consistency is CRITICAL:** Use the EXACT SAME category name for all tabs belonging to the same logical group (whether assigned an existing or a new category). If multiple tabs point to 'google.com/search?q=recipes', categorize them consistently (e.g., 'Google Search' or 'Recipes', but use the same one for all).
4. **Format:** 1-2 words, Title Case.
---
Input Tab Data:
{TAB_DATA_LIST}
---
Instructions for Output:
1. Output ONLY the category names.
2. Provide EXACTLY ONE category name per line.
3. The number of lines in your output MUST EXACTLY MATCH the number of tabs in the Input Tab Data list above.
4. DO NOT include numbering, explanations, apologies, markdown formatting, or any surrounding text like "Output:" or backticks.
5. Just the list of categories, separated by newlines.
---
Output:`
},
gemini: {
enabled: AI_MODEL_VALUE == "1",
apiKey: GEMINI_API_KEY_VALUE,
model: GEMINI_MODEL_VALUE,
// Endpoint structure: https://generativelanguage.googleapis.com/v1beta/models/{model}:{method}
apiBaseUrl: 'https://generativelanguage.googleapis.com/v1beta/models/',
promptTemplateBatch: `Analyze the following numbered list of tab data (Title, URL, Description) and assign a concise category (1-2 words, Title Case) for EACH tab.
Existing Categories (Use these EXACT names if a tab fits):
{EXISTING_CATEGORIES_LIST}
---
Instructions for Assignment:
1. **Prioritize Existing:** For each tab below, determine if it clearly belongs to one of the 'Existing Categories'. Base this primarily on the URL/Domain, then Title/Description. If it fits, you MUST use the EXACT category name provided in the 'Existing Categories' list. DO NOT create a minor variation (e.g., if 'Project Docs' exists, use that, don't create 'Project Documentation').
2. **Assign New Category (If Necessary):** Only if a tab DOES NOT fit an existing category, assign the best NEW concise category (1-2 words, Title Case).
* PRIORITIZE the URL/Domain (e.g., 'GitHub', 'YouTube', 'StackOverflow').
* Use Title/Description for specifics or generic domains.
3. **Consistency is CRITICAL:** Use the EXACT SAME category name for all tabs belonging to the same logical group (whether assigned an existing or a new category). If multiple tabs point to 'google.com/search?q=recipes', categorize them consistently (e.g., 'Google Search' or 'Recipes', but use the same one for all).
4. **Format:** 1-2 words, Title Case.
---
Input Tab Data:
{TAB_DATA_LIST}
---
Instructions for Output:
1. Output ONLY the category names.
2. Provide EXACTLY ONE category name per line.
3. The number of lines in your output MUST EXACTLY MATCH the number of tabs in the Input Tab Data list above.
4. DO NOT include numbering, explanations, apologies, markdown formatting, or any surrounding text like "Output:" or backticks.
5. Just the list of categories, separated by newlines.
---
Output:`,
generationConfig: {
temperature: 0.1, // Low temp for consistency
// maxOutputTokens: calculated dynamically based on tab count
candidateCount: 1, // Only need one best answer
// stopSequences: ["---"] // Optional: define sequences to stop generation
}
},
mistral: {
enabled: AI_MODEL_VALUE == "3",
apiKey: MISTRAL_API_KEY_VALUE,
model: MISTRAL_MODEL_VALUE,
apiBaseUrl: 'https://api.mistral.ai/v1/chat/completions',
promptTemplateBatch: `Analyze the following numbered list of tab data (Title, URL, Description) and assign a concise category (1-2 words, Title Case) for EACH tab.
Existing Categories (Use these EXACT names if a tab fits):
{EXISTING_CATEGORIES_LIST}
---
Instructions for Assignment:
1. **Prioritize Existing:** For each tab below, determine if it clearly belongs to one of the 'Existing Categories'. Base this primarily on the URL/Domain, then Title/Description. If it fits, you MUST use the EXACT category name provided in the 'Existing Categories' list. DO NOT create a minor variation (e.g., if 'Project Docs' exists, use that, don't create 'Project Documentation').
2. **Assign New Category (If Necessary):** Only if a tab DOES NOT fit an existing category, assign the best NEW concise category (1-2 words, Title Case).
* PRIORITIZE the URL/Domain (e.g., 'GitHub', 'YouTube', 'StackOverflow').
* Use Title/Description for specifics or generic domains.
3. **Consistency is CRITICAL:** Use the EXACT SAME category name for all tabs belonging to the same logical group (whether assigned an existing or a new category). If multiple tabs point to 'google.com/search?q=recipes', categorize them consistently (e.g., 'Google Search' or 'Recipes', but use the same one for all).
4. **Format:** 1-2 words, Title Case.
---
Input Tab Data:
{TAB_DATA_LIST}
---
Instructions for Output:
1. Output ONLY the category names.
2. Provide EXACTLY ONE category name per line.
3. The number of lines in your output MUST EXACTLY MATCH the number of tabs in the Input Tab Data list above.
4. DO NOT include numbering, explanations, apologies, markdown formatting, or any surrounding text like "Output:" or backticks.
5. Just the list of categories, separated by newlines.
---
Output:`,
generationConfig: {
temperature: 0.1, // Low temp for consistency
max_tokens: 512, // Default, will be calculated dynamically
top_p: 0.9,
frequency_penalty: 0.0,
presence_penalty: 0.0
}
},
customApi: {
enabled: false,
// ... (custom API config if needed)
}
},
groupColors: [
"var(--tab-group-color-blue)", "var(--tab-group-color-red)", "var(--tab-group-color-yellow)",
"var(--tab-group-color-green)", "var(--tab-group-color-pink)", "var(--tab-group-color-purple)",
"var(--tab-group-color-orange)", "var(--tab-group-color-cyan)", "var(--tab-group-color-gray)"
],
groupColorNames: [
"blue", "red", "yellow", "green", "pink", "purple", "orange", "cyan", "gray"
],
preGroupingThreshold: 2, // Min tabs for keyword/hostname pre-grouping
titleKeywordStopWords: new Set([
'a', 'an', 'the', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'with', 'by', 'of',
'is', 'am', 'are', 'was', 'were', 'be', 'being', 'been', 'has', 'have', 'had', 'do', 'does', 'did',
'how', 'what', 'when', 'where', 'why', 'which', 'who', 'whom', 'whose',
'new', 'tab', 'untitled', 'page', 'home', 'com', 'org', 'net', 'io', 'dev', 'app',
'get', 'set', 'list', 'view', 'edit', 'create', 'update', 'delete',
'my', 'your', 'his', 'her', 'its', 'our', 'their', 'me', 'you', 'him', 'her', 'it', 'us', 'them',
'about', 'search', 'results', 'posts', 'index', 'dashboard', 'profile', 'settings',
'official', 'documentation', 'docs', 'wiki', 'help', 'support', 'faq', 'guide',
'error', 'login', 'signin', 'sign', 'up', 'out', 'welcome', 'loading', 'vs', 'using', 'code',
'microsoft', 'google', 'apple', 'amazon', 'facebook', 'twitter'
]),
minKeywordLength: 3,
consolidationDistanceThreshold: 2, // Max Levenshtein distance to merge similar group names
styles: `
#sort-button {
opacity: 0;
transition: opacity 0.1s ease-in-out;
position: absolute;
/* Simple, stable positioning. The parent container's right edge never moves. */
right: 0px;
top: 50%;
transform: translateY(-50%);
font-size: 12px;
width: 60px;
height: auto;
pointer-events: auto;
appearance: none;
padding: 2px 4px;
color: gray;
z-index: 10; /* Higher z-index to ensure buttons are on top */
label { display: block; }
}
@media (-moz-bool-pref: "${ENABLE_CLEAR_PREF}") {
#sort-button {
right: 55px;
}
}
#sort-button:hover {
opacity: 1;
color: white;
border-radius: 4px;
}
#clear-button {
opacity: 0;
transition: opacity 0.1s ease-in-out;
position: absolute;
right: 0; /* Simple and stable */
top: 50%;
transform: translateY(-50%);
font-size: 12px;
width: 60px;
height: auto;
pointer-events: auto;
appearance: none;
padding: 2px 4px;
color: grey;
z-index: 10; /* Higher z-index to ensure buttons are on top */
label { display: block; }
}
#clear-button:hover {
opacity: 1;
color: white;
border-radius: 4px;
}
/* disable the buttons according to preferences */
@media not (-moz-bool-pref: "${ENABLE_SORT_PREF}") {
#sort-button {
display: none;
}
}
@media not (-moz-bool-pref: "${ENABLE_CLEAR_PREF}") {
#clear-button {
display: none;
}
}
/*======== sort-button , clear-button ============*/
.pinned-tabs-container-separator{
height: 100% !important;
transition: all .2s ease-in-out !important;
display: flex !important;
flex-direction: column;
margin-left: 0;
min-height: 1px;
padding-top: 0.4px;
padding-bottom: 0.4px;
position: relative; /* Acts as the anchor for children */
background-color: transparent !important; /* The container itself is invisible */
overflow: visible !important; /* Ensure buttons don't get clipped */
}
.pinned-tabs-container-separator::before {
content: '';
position: absolute;
left: 0;
top: 0;
height: 100%;
width: 100%; /* Default state: full width */
background-color: var(--lwt-toolbarbutton-border-color, rgba(200, 200, 200, 0.1));
transition: width 0.1s ease-in-out, background-color 0.3s ease-out;
}
/* Disable hover width tweak when actively sorting to avoid overriding animation */
.pinned-tabs-container-separator.separator-is-sorting:hover::before {
width: 100% !important;
}
/* widths for when we have both enabled */
@media (-moz-bool-pref: "${ENABLE_CLEAR_PREF}") and (-moz-bool-pref: "${ENABLE_SORT_PREF}") {
.pinned-tabs-container-separator:hover::before {
width: calc(100% - 115px);
background-color: var(--lwt-toolbarbutton-hover-background, rgba(200, 200, 200, 0.2));
}
.zen-workspace-tabs-section[hide-separator] .pinned-tabs-container-separator:hover::before {
width: calc(100% - 115px);
}
/* Make sure the separator background adjusts for buttons during sorting ONLY when hovered */
.separator-is-sorting:hover::before {
width: calc(100% - 115px) !important;
}
/* Make the animated overlay shrink when hovering over buttons */
.pinned-tabs-container-separator.separator-is-sorting:hover::after {
width: calc(100% - 115px);
}
/* For zen-workspace-tabs-section with hide-separator */
.zen-workspace-tabs-section[hide-separator] .pinned-tabs-container-separator.separator-is-sorting:hover::after {
width: calc(100% - 115px);
}
}
/* when we only have clear */
@media (-moz-bool-pref: "${ENABLE_CLEAR_PREF}") and (not (-moz-bool-pref: "${ENABLE_SORT_PREF}")) {
.pinned-tabs-container-separator:hover::before {
width: calc(100% - 60px);
background-color: var(--lwt-toolbarbutton-hover-background, rgba(200, 200, 200, 0.2));
}
.zen-workspace-tabs-section[hide-separator] .pinned-tabs-container-separator:hover::before {
width: calc(100% - 60px);
}
/* Make sure the separator background adjusts for buttons during sorting ONLY when hovered */
.separator-is-sorting:hover::before {
width: calc(100% - 60px) !important;
}
/* Make the animated overlay shrink when hovering over buttons */
.pinned-tabs-container-separator.separator-is-sorting:hover::after {
width: calc(100% - 60px);
}
/* For zen-workspace-tabs-section with hide-separator */
.zen-workspace-tabs-section[hide-separator] .pinned-tabs-container-separator.separator-is-sorting:hover::after {
width: calc(100% - 60px);
}
}
/* when we only have sort */
@media (not (-moz-bool-pref: "${ENABLE_CLEAR_PREF}")) and (-moz-bool-pref: "${ENABLE_SORT_PREF}") {
.pinned-tabs-container-separator:hover::before {
width: calc(100% - 65px);
background-color: var(--lwt-toolbarbutton-hover-background, rgba(200, 200, 200, 0.2));
}
.zen-workspace-tabs-section[hide-separator] .pinned-tabs-container-separator:hover::before {
width: calc(100% - 65px);
}
/* Make sure the separator background adjusts for buttons during sorting ONLY when hovered */
.separator-is-sorting:hover::before {
width: calc(100% - 65px) !important;
}
/* Make the animated overlay shrink when hovering over buttons */
.pinned-tabs-container-separator.separator-is-sorting:hover::after {
width: calc(100% - 65px);
}
/* For zen-workspace-tabs-section with hide-separator */
.zen-workspace-tabs-section[hide-separator] .pinned-tabs-container-separator.separator-is-sorting:hover::after {
width: calc(100% - 65px);
}
}
.pinned-tabs-container-separator:hover #sort-button,
.pinned-tabs-container-separator:hover #clear-button {
opacity: 1;
}
.zen-workspace-tabs-section[hide-separator] .pinned-tabs-container-separator {
margin-top: 5px !important;
margin-bottom: 8px !important;
}
.zen-workspace-tabs-section[hide-separator] .pinned-tabs-container-separator.separator-is-sorting:hover::before {
background-color: transparent !important;
}
.zen-workspace-tabs-section[hide-separator] .pinned-tabs-container-separator:hover::before {
background-color: var(--lwt-toolbarbutton-hover-background, rgba(200, 200, 200, 0.2));
}
.zen-workspace-tabs-section[hide-separator] .pinned-tabs-container-separator.separator-is-sorting:hover::before {
width: 100% !important;
}
/* Additional style to ensure separator is visible during sorting */
.separator-is-sorting {
position: relative;
overflow: visible !important;
/* Remove background from the main element to avoid overlap */
}
/* Fallback: use the same CSS variable on the element itself */
.pinned-tabs-container-separator.separator-is-sorting {
background-image: none !important;
background-color: var(--sorting-color, #ebbcba);
}
/* Ensure buttons work properly during sorting - don't force visibility */
.separator-is-sorting #sort-button,
.separator-is-sorting #clear-button {
z-index: 200 !important;
pointer-events: auto !important;
/* Let normal hover behavior control opacity and styling */
}
/* While sorting, neutralize the original ::before so hover/theme styles can't override */
.pinned-tabs-container-separator.separator-is-sorting::before {
content: '';
position: absolute;
left: 0;
top: 0;
height: 100%;
width: 100%;
background: transparent !important;
}
/* Dedicated overlay for sorting animation */
.pinned-tabs-container-separator.separator-is-sorting::after {
content: '';
position: absolute;
left: 0;
top: 0;
height: 100%;
width: 100%;
pointer-events: none;
z-index: 2;
background-image: none !important;
background-color: var(--sorting-color, #ebbcba);
border-radius: 1px;
opacity: 0.9 !important;
transition: width 0.1s ease-in-out;
}
/* Remove hover interference: animated color stays visible while sorting */
.pinned-tabs-container-separator.separator-is-sorting:hover::before { background-image: none !important; }
.tab-closing {
animation: fadeUp 0.5s forwards;
}
@keyframes fadeUp {
0% { opacity: 1; transform: translateY(0); }
100% { opacity: 0; transform: translateY(-20px); max-height: 0px; padding: 0; margin: 0; border: 0; }
}
@keyframes loading-pulse-tab {
0%, 100% { opacity: 0.6; }
50% { opacity: 1; }
}
.tab-is-sorting .tab-icon-image,
.tab-is-sorting .tab-label {
animation: loading-pulse-tab 1.5s ease-in-out infinite;
will-change: opacity;
}
.tabbrowser-tab {
transition: transform 0.3s ease-out, opacity 0.3s ease-out, max-height 0.5s ease-out, margin 0.5s ease-out, padding 0.5s ease-out;
}
`
};
// --- Globals & State ---
let groupColorIndex = 0;
let isSorting = false;
let commandListenerAdded = false;
// --- Helper Functions ---
const injectStyles = () => {
let styleElement = document.getElementById('tab-sort-clear-styles');
if (styleElement) {
if (styleElement.textContent !== CONFIG.styles) {
styleElement.textContent = CONFIG.styles;
console.log("BUTTONS: Styles updated.");
}
return;
}
styleElement = Object.assign(document.createElement('style'), {
id: 'tab-sort-clear-styles',
textContent: CONFIG.styles
});
document.head.appendChild(styleElement);
console.log("BUTTONS: Styles injected.");
};
const getTabData = (tab) => {
if (!tab || !tab.isConnected) {
return { title: 'Invalid Tab', url: '', hostname: '', description: '' };
}
let title = 'Untitled Page';
let fullUrl = '';
let hostname = '';
let description = '';
try {
const originalTitle = tab.getAttribute('label') || tab.querySelector('.tab-label, .tab-text')?.textContent || '';
const browser = tab.linkedBrowser || tab._linkedBrowser || gBrowser?.getBrowserForTab?.(tab);
if (browser?.currentURI?.spec && !browser.currentURI.spec.startsWith('about:')) {
try {
const currentURL = new URL(browser.currentURI.spec);
fullUrl = currentURL.href;
hostname = currentURL.hostname.replace(/^www\./, '');
} catch (e) {
hostname = 'Invalid URL';
fullUrl = browser?.currentURI?.spec || 'Invalid URL';
}
} else if (browser?.currentURI?.spec) {
fullUrl = browser.currentURI.spec;
hostname = 'Internal Page';
}
if (!originalTitle || originalTitle === 'New Tab' || originalTitle === 'about:blank' || originalTitle === 'Loading...' || originalTitle.startsWith('http:') || originalTitle.startsWith('https:')) {
if (hostname && hostname !== 'Invalid URL' && hostname !== 'localhost' && hostname !== '127.0.0.1' && hostname !== 'Internal Page') {
title = hostname;
} else {
try {
const pathSegment = new URL(fullUrl).pathname.split('/')[1];
if (pathSegment) {
title = pathSegment;
}
} catch { /* ignore */ }
}
} else {
title = originalTitle.trim();
}
title = title || 'Untitled Page';
try {
if (browser && browser.contentDocument) {
const metaDescElement = browser.contentDocument.querySelector('meta[name="description"]');
if (metaDescElement) {
description = metaDescElement.getAttribute('content')?.trim() || '';
description = description.substring(0, 200);
}
}
} catch (contentError) {
/* ignore permission errors */
}
} catch (e) {
console.error('Error getting tab data for tab:', tab, e);
title = 'Error Processing Tab';
}
return { title: title, url: fullUrl, hostname: hostname || 'N/A', description: description || 'N/A' };
};
const toTitleCase = (str) => {
if (!str) return ""; // Added guard for null/undefined input
return str.toLowerCase()
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
};
const processTopic = (text) => {
if (!text) return "Uncategorized";
const originalTextTrimmedLower = text.trim().toLowerCase();
const normalizationMap = {
'github.com': 'GitHub', 'github': 'GitHub',
'stackoverflow.com': 'Stack Overflow', 'stack overflow': 'Stack Overflow', 'stackoverflow': 'Stack Overflow',
'google docs': 'Google Docs', 'docs.google.com': 'Google Docs',
'google drive': 'Google Drive', 'drive.google.com': 'Google Drive',
'youtube.com': 'YouTube', 'youtube': 'YouTube',
'reddit.com': 'Reddit', 'reddit': 'Reddit',
'chatgpt': 'ChatGPT', 'openai.com': 'OpenAI',
'gmail': 'Gmail', 'mail.google.com': 'Gmail',
'aws': 'AWS', 'amazon web services': 'AWS',
'pinterest.com': 'Pinterest', 'pinterest': 'Pinterest',
'developer.mozilla.org': 'MDN Web Docs', 'mdn': 'MDN Web Docs', 'mozilla': 'Mozilla'
};
if (normalizationMap[originalTextTrimmedLower]) {
return normalizationMap[originalTextTrimmedLower];
}
let processedText = text.replace(/^(Category is|The category is|Topic:)\s*"?/i, '');
processedText = processedText.replace(/^\s*[\d.\-*]+\s*/, '');
let words = processedText.trim().split(/\s+/);
let category = words.slice(0, 2).join(' ');
category = category.replace(/["'*().:;,]/g, '');
return toTitleCase(category).substring(0, 40) || "Uncategorized";
};
const extractTitleKeywords = (title) => {
if (!title || typeof title !== 'string') {
return new Set();
}
const cleanedTitle = title.toLowerCase()
.replace(/[-_]/g, ' ')
.replace(/[^\w\s]/g, '')
.replace(/\s+/g, ' ')
.trim();
const words = cleanedTitle.split(' ');
const keywords = new Set();
for (const word of words) {
if (word.length >= CONFIG.minKeywordLength && !CONFIG.titleKeywordStopWords.has(word) && !/^\d+$/.test(word)) {
keywords.add(word);
}
}
return keywords;
};
const getNextGroupColorName = () => {
const colorName = CONFIG.groupColorNames[groupColorIndex % CONFIG.groupColorNames.length];
groupColorIndex++;
return colorName;
};
const findGroupElement = (topicName, workspaceId) => {
const sanitizedTopicName = topicName.trim();
if (!sanitizedTopicName) return null;
// Escape special characters for CSS selector
const safeSelectorTopicName = sanitizedTopicName.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
// Use :has() to find the group by label that CONTAINS a tab with the correct workspace ID
const selector = `tab-group[label="${safeSelectorTopicName}"]:has(tab[zen-workspace-id="${workspaceId}"])`;
try {
// console.log(`findGroupElement: Searching with selector: ${selector}`); // Optional debug log
return document.querySelector(selector);
} catch (e) {
console.error(`Error finding group with selector: ${selector}`, e);
return null;
}
};
const levenshteinDistance = (a, b) => {
if (!a || !b) return Math.max(a?.length ?? 0, b?.length ?? 0);
a = a.toLowerCase();
b = b.toLowerCase();
if (a.length === 0) return b.length;
if (b.length === 0) return a.length;
const matrix = [];
for (let i = 0; i <= b.length; i++) {
matrix[i] = [i];
}
for (let j = 0; j <= a.length; j++) {
matrix[0][j] = j;
}
for (let i = 1; i <= b.length; i++) {
for (let j = 1; j <= a.length; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
matrix[i][j] = Math.min(
matrix[i - 1][j] + 1, // Deletion
matrix[i][j - 1] + 1, // Insertion
matrix[i - 1][j - 1] + cost // Substitution
);
}
}
return matrix[b.length][a.length];
};
// --- End Helper Functions ---
// --- AI Interaction ---
const askAIForMultipleTopics = async (tabs, existingCategoryNames = []) => {
const validTabs = tabs.filter(tab => tab && tab.isConnected);
if (!validTabs || validTabs.length === 0) {
return [];
}
const { gemini, ollama, mistral } = CONFIG.apiConfig;
let result = [];
let apiChoice = "None";
validTabs.forEach(tab => tab.classList.add('tab-is-sorting'));
try {
if (gemini.enabled) {
apiChoice = "Gemini";
if (!gemini.apiKey) {
throw new Error("Gemini API key is missing or not set. Please paste your key in the CONFIG section.");
}
console.log(`Batch AI (Gemini): Requesting categories for ${validTabs.length} tabs, considering ${existingCategoryNames.length} existing categories...`);
const tabDataArray = validTabs.map(getTabData);
const formattedTabDataList = tabDataArray.map((data, index) =>
`${index + 1}.\nTitle: "${data.title}"\nURL: "${data.url}"\nDescription: "${data.description}"`
).join('\n\n');
const formattedExistingCategories = existingCategoryNames.length > 0
? existingCategoryNames.map(name => `- ${name}`).join('\n')
: "None";
const prompt = gemini.promptTemplateBatch
.replace("{EXISTING_CATEGORIES_LIST}", formattedExistingCategories)
.replace("{TAB_DATA_LIST}", formattedTabDataList);
const apiUrl = `${gemini.apiBaseUrl}${gemini.model}:generateContent?key=${gemini.apiKey}`;
const headers = { 'Content-Type': 'application/json' };
const estimatedOutputTokens = Math.max(256, validTabs.length * 16); // Dynamic estimation
const requestBody = {
contents: [{ parts: [{ text: prompt }] }],
generationConfig: {
...gemini.generationConfig,
maxOutputTokens: estimatedOutputTokens
}
};
const response = await fetch(apiUrl, {
method: 'POST',
headers: headers,
body: JSON.stringify(requestBody)
});
if (!response.ok) {
let errorText = `API Error ${response.status}`;
try {
const errorData = await response.json();
errorText += `: ${errorData?.error?.message || response.statusText}`;
console.error("Gemini API Error Response:", errorData);
} catch (parseError) {
errorText += `: ${response.statusText}`;
const rawText = await response.text().catch(() => '');
console.error("Gemini API Error Raw Response:", rawText);
}
if (response.status === 400 && errorText.includes("API key not valid")) {
throw new Error(`Gemini API Error: API key is not valid. Please check the key in the script configuration. (${errorText})`);
}
if (response.status === 403) {
throw new Error(`Gemini API Error: Permission denied. Ensure the API key has the 'generativelanguage.models.generateContent' permission enabled. (${errorText})`);
}
throw new Error(errorText);
}
const data = await response.json();
const aiText = data?.candidates?.[0]?.content?.parts?.[0]?.text?.trim();
if (!aiText) {
console.error("Gemini API: Empty or unexpected response structure.", data);
if (data?.promptFeedback?.blockReason) {
throw new Error(`Gemini API Error: Request blocked due to ${data.promptFeedback.blockReason}. Check safety ratings: ${JSON.stringify(data.promptFeedback.safetyRatings)}`);
}
if (data?.candidates?.[0]?.finishReason && data.candidates[0].finishReason !== "STOP") {
throw new Error(`Gemini API Error: Generation finished unexpectedly due to ${data.candidates[0].finishReason}.`);
}
throw new Error("Gemini API response content is missing or empty.");
}
console.log("Gemini Raw Response Text:\n---\n", aiText, "\n---");
const lines = aiText.split('\n').map(line => line.trim()).filter(Boolean);
if (lines.length !== validTabs.length) {
console.warn(`Batch AI (Gemini): Mismatch! Expected ${validTabs.length} topics, received ${lines.length}.`);
if (validTabs.length === 1 && lines.length > 0) {
const firstLineTopic = processTopic(lines[0]);
console.warn(` -> Mismatch Correction (Single Tab): Using first line "${lines[0]}" -> Topic: "${firstLineTopic}"`);
result = [{ tab: validTabs[0], topic: firstLineTopic }];
} else if (lines.length > validTabs.length) {
console.warn(` -> Mismatch Correction (Too Many Lines): Truncating response to ${validTabs.length} lines.`);
const processedTopics = lines.slice(0, validTabs.length).map(processTopic);
result = validTabs.map((tab, index) => ({ tab: tab, topic: processedTopics[index] }));
} else {
console.warn(` -> Fallback (Too Few Lines): Assigning remaining tabs "Uncategorized".`);
const processedTopics = lines.map(processTopic);
result = validTabs.map((tab, index) => ({
tab: tab,
topic: index < processedTopics.length ? processedTopics[index] : "Uncategorized"
}));
}
} else {
const processedTopics = lines.map(processTopic);
console.log("Batch AI (Gemini): Processed Topics:", processedTopics);
result = validTabs.map((tab, index) => ({ tab: tab, topic: processedTopics[index] }));
}
} else if (ollama.enabled) {
// --- OLLAMA LOGIC ---
apiChoice = "Ollama";
console.log(`Batch AI (Ollama): Requesting categories for ${validTabs.length} tabs, considering ${existingCategoryNames.length} existing categories...`);
let apiUrl = ollama.endpoint;
let headers = { 'Content-Type': 'application/json' };
const tabDataArray = validTabs.map(getTabData);
const formattedTabDataList = tabDataArray.map((data, index) =>
`${index + 1}.\nTitle: "${data.title}"\nURL: "${data.url}"\nDescription: "${data.description}"`
).join('\n\n');
const formattedExistingCategories = existingCategoryNames.length > 0
? existingCategoryNames.map(name => `- ${name}`).join('\n')
: "None";
const prompt = ollama.promptTemplateBatch
.replace("{EXISTING_CATEGORIES_LIST}", formattedExistingCategories)
.replace("{TAB_DATA_LIST}", formattedTabDataList);
const requestBody = {
model: ollama.model,
prompt: prompt,
stream: false,
options: { temperature: 0.1, num_predict: validTabs.length * 15 } // Dynamic estimation
};
const response = await fetch(apiUrl, {
method: 'POST',
headers: headers,
body: JSON.stringify(requestBody)
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown API error reason');
throw new Error(`Ollama API Error ${response.status}: ${errorText}`);
}
const data = await response.json();
let aiText = data.response?.trim();
if (!aiText) {
throw new Error("Ollama: Empty API response");
}
const lines = aiText.split('\n').map(line => line.trim()).filter(Boolean);
if (lines.length !== validTabs.length) {
console.warn(`Batch AI (Ollama): Mismatch! Expected ${validTabs.length} topics, received ${lines.length}. AI Response:\n${aiText}`);
if (validTabs.length === 1 && lines.length > 0) {
const firstLineTopic = processTopic(lines[0]);
console.warn(` -> Mismatch Correction (Single Tab): Using first line "${lines[0]}" -> Topic: "${firstLineTopic}"`);
result = [{ tab: validTabs[0], topic: firstLineTopic }];
} else if (lines.length > validTabs.length) {
console.warn(` -> Mismatch Correction (Too Many Lines): Truncating response to ${validTabs.length} lines.`);
const processedTopics = lines.slice(0, validTabs.length).map(processTopic);
result = validTabs.map((tab, index) => ({ tab: tab, topic: processedTopics[index] }));
} else {
console.warn(` -> Fallback (Too Few Lines): Assigning remaining tabs "Uncategorized".`);
const processedTopics = lines.map(processTopic);
result = validTabs.map((tab, index) => ({
tab: tab,
topic: index < processedTopics.length ? processedTopics[index] : "Uncategorized"
}));
}
} else {
const processedTopics = lines.map(processTopic);
console.log("Batch AI (Ollama): Processed Topics:", processedTopics);
result = validTabs.map((tab, index) => ({ tab: tab, topic: processedTopics[index] }));
}
} else if (mistral.enabled) {
// --- MISTRAL LOGIC ---
apiChoice = "Mistral";
console.log(`Batch AI (Mistral): Requesting categories for ${validTabs.length} tabs, considering ${existingCategoryNames.length} existing categories...`);
let apiUrl = mistral.apiBaseUrl;
let headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${mistral.apiKey}`
};
const tabDataArray = validTabs.map(getTabData);
const formattedTabDataList = tabDataArray.map((data, index) =>
`${index + 1}.\nTitle: "${data.title}"\nURL: "${data.url}"\nDescription: "${data.description}"`
).join('\n\n');
const formattedExistingCategories = existingCategoryNames.length > 0
? existingCategoryNames.map(name => `- ${name}`).join('\n')
: "None";
const prompt = mistral.promptTemplateBatch
.replace("{EXISTING_CATEGORIES_LIST}", formattedExistingCategories)
.replace("{TAB_DATA_LIST}", formattedTabDataList);
const estimatedOutputTokens = Math.max(256, validTabs.length * 16); // Dynamic estimation
const requestBody = {
model: mistral.model,
messages: [{ role: "user", content: prompt }],
max_tokens: estimatedOutputTokens,
temperature: mistral.generationConfig.temperature,
top_p: mistral.generationConfig.top_p,
frequency_penalty: mistral.generationConfig.frequency_penalty,
presence_penalty: mistral.generationConfig.presence_penalty
};
const response = await fetch(apiUrl, {
method: 'POST',
headers: headers,
body: JSON.stringify(requestBody)
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown API error reason');
throw new Error(`Mistral API Error ${response.status}: ${errorText}`);
}
const data = await response.json();
let aiText = data.choices?.[0]?.message?.content?.trim();
if (!aiText) {
throw new Error("Mistral: Empty API response");
}
const lines = aiText.split('\n').map(line => line.trim()).filter(Boolean);
if (lines.length !== validTabs.length) {
console.warn(`Batch AI (Mistral): Mismatch! Expected ${validTabs.length} topics, received ${lines.length}. AI Response:\n${aiText}`);
if (validTabs.length === 1 && lines.length > 0) {
const firstLineTopic = processTopic(lines[0]);
console.warn(` -> Mismatch Correction (Single Tab): Using first line "${lines[0]}" -> Topic: "${firstLineTopic}"`);
result = [{ tab: validTabs[0], topic: firstLineTopic }];
} else if (lines.length > validTabs.length) {
console.warn(` -> Mismatch Correction (Too Many Lines): Truncating response to ${validTabs.length} lines.`);
const processedTopics = lines.slice(0, validTabs.length).map(processTopic);
result = validTabs.map((tab, index) => ({ tab: tab, topic: processedTopics[index] }));
} else {
console.warn(` -> Fallback (Too Few Lines): Assigning remaining tabs "Uncategorized".`);
const processedTopics = lines.map(processTopic);
result = validTabs.map((tab, index) => ({
tab: tab,
topic: index < processedTopics.length ? processedTopics[index] : "Uncategorized"
}));
}
} else {
const processedTopics = lines.map(processTopic);
console.log("Batch AI (Mistral): Processed Topics:", processedTopics);
result = validTabs.map((tab, index) => ({ tab: tab, topic: processedTopics[index] }));
}
} else {
throw new Error("No AI API is enabled in the configuration (Gemini, Ollama, or Mistral).");
}
return result;
} catch (error) {
console.error(`Batch AI (${apiChoice}): Error getting topics:`, error);
// Return "Uncategorized" for all tabs on error
return validTabs.map(tab => ({ tab, topic: "Uncategorized" }));
} finally {
// Remove sorting indicator after a short delay
setTimeout(() => {
validTabs.forEach(tab => {
if (tab && tab.isConnected) {
tab.classList.remove('tab-is-sorting');
}
});
}, 200);
}
};
// --- End AI Interaction ---
// --- Main Sorting Function ---
const sortTabsByTopic = async () => {
if (isSorting) {
console.log("Sorting already in progress.");
return;
}
isSorting = true;
// Check for multiple tab selection
const selectedTabs = gBrowser.selectedTabs;
const isSortingSelectedTabs = selectedTabs.length > 1;
const actionType = isSortingSelectedTabs ? "selected tabs" : "all ungrouped tabs";
console.log(`Starting tab sort (${actionType} mode) - (v4.10.0 - Flexible Group Selector)...`);
let separatorsToSort = []; // Keep track of separators to remove class later
try {
separatorsToSort = document.querySelectorAll('.pinned-tabs-container-separator');
if(separatorsToSort.length > 0) {
console.log("Applying sorting indicator to separator(s)...");
separatorsToSort.forEach(sep => {
sep.classList.add('separator-is-sorting');
// Force a reflow to ensure the animation starts immediately
sep.offsetHeight;
console.log("Animation class added to separator:", sep, "Classes:", sep.className);
try {
const elemStyles = getComputedStyle(sep);
const beforeStyles = getComputedStyle(sep, '::before');
const afterStyles = getComputedStyle(sep, '::after');
console.log("Separator computed styles:", {
elementAnimationName: elemStyles?.animationName,
elementBackgroundColor: elemStyles?.backgroundColor,
beforeAnimationName: beforeStyles?.animationName,
beforeBackgroundColor: beforeStyles?.backgroundColor,
beforeBackgroundImage: beforeStyles?.backgroundImage,
afterAnimationName: afterStyles?.animationName,
afterBackgroundColor: afterStyles?.backgroundColor,
afterBackgroundImage: afterStyles?.backgroundImage
});
// Start JS-driven color cycle using a CSS variable
const colors = ['#ebbcba', '#c4a7e7', '#9ccfd8'];
let colorIndex = 0;
if (sep._sortingColorInterval) {
clearInterval(sep._sortingColorInterval);
}
// Set initial color immediately
sep.style.setProperty('--sorting-color', colors[0]);
sep._sortingColorInterval = setInterval(() => {
colorIndex = (colorIndex + 1) % colors.length;