-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpopup.js
1091 lines (934 loc) · 38.7 KB
/
popup.js
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
console.log('[Reddit Copycat] Popup script loaded');
document.addEventListener('DOMContentLoaded', function() {
const saveButton = document.getElementById('saveSubredditsBtn');
const joinButton = document.getElementById('joinSavedSubreddits');
const showButton = document.getElementById('showSavedBtn');
const exportButton = document.getElementById('exportListBtn');
const importButton = document.getElementById('importListBtn');
const importInput = document.getElementById('importInput');
const statusDiv = document.querySelector('.status');
const subredditList = document.getElementById('subredditList');
const progressContainer = document.querySelector('.progress-container');
const progressFill = document.querySelector('.progress-fill');
const progressText = document.querySelector('.progress-text');
const filterContainer = document.querySelector('.filter-container');
const filterCheckbox = document.getElementById('filterUnjoined');
const statsDiv = document.querySelector('.stats');
const selectionControls = document.querySelector('.selection-controls');
const selectAllBtn = document.getElementById('selectAllBtn');
const deselectAllBtn = document.getElementById('deselectAllBtn');
const selectUnjoinedBtn = document.getElementById('selectUnjoinedBtn');
const joinSelectedBtn = document.getElementById('joinSelectedBtn');
const selectedCountDiv = document.querySelector('.selected-count');
const progressInfo = document.querySelector('.progress-info');
const leaveSelectedBtn = document.getElementById('leaveSelectedBtn');
const leaveSavedSubreddits = document.getElementById('leaveSavedSubreddits');
let currentSubreddits = [];
let joinedSubreddits = [];
let selectedSubreddits = new Set();
let progressListener = null;
let currentCompletionListener = null;
// Tab handling for new UI
const tabs = document.querySelectorAll('.tab');
const tabContents = document.querySelectorAll('.tab-content');
// Debug log for initial element check
console.log('[Reddit Copycat] Settings button:', document.querySelector('.settings-button'));
console.log('[Reddit Copycat] Settings content:', document.querySelector('.settings-content'));
// Close all dropdowns when clicking outside
document.addEventListener('click', (event) => {
if (!event.target.closest('.settings-dropdown') && !event.target.closest('.dropdown')) {
// Close settings dropdown
document.querySelectorAll('.settings-content').forEach(content => {
content.classList.remove('show');
});
document.querySelectorAll('.settings-dropdown').forEach(dropdown => {
dropdown.classList.remove('active');
});
// Close bulk actions dropdown
document.querySelectorAll('.dropdown-content').forEach(content => {
content.classList.remove('show');
});
document.querySelectorAll('.dropdown').forEach(dropdown => {
dropdown.classList.remove('active');
});
}
});
// Settings dropdown handler
const settingsButtons = document.querySelectorAll('.settings-button');
settingsButtons.forEach(button => {
button.addEventListener('click', (event) => {
console.log('[Reddit Copycat] Settings button clicked');
event.stopPropagation();
const dropdown = event.target.closest('.settings-dropdown');
const content = dropdown.querySelector('.settings-content');
// Toggle active state
dropdown.classList.toggle('active');
// If we're showing the dropdown, ensure smooth animation
if (!content.classList.contains('show')) {
content.style.display = 'block';
// Force a reflow
content.offsetHeight;
content.classList.add('show');
} else {
content.classList.remove('show');
// Wait for animation to finish before hiding
setTimeout(() => {
if (!content.classList.contains('show')) {
content.style.display = 'none';
}
}, 200);
}
});
});
// Handle filter checkbox
document.addEventListener('change', (event) => {
if (event.target.matches('#filterUnjoined')) {
console.log('[Reddit Copycat] Filter checkbox changed:', event.target.checked);
chrome.storage.local.get('savedSubreddits').then(savedSubs => {
if (savedSubs.savedSubreddits) {
updateSubredditList(savedSubs.savedSubreddits, event.target.checked);
}
});
}
});
tabs.forEach(tab => {
tab.addEventListener('click', () => {
tabs.forEach(t => t.classList.remove('active'));
tabContents.forEach(c => c.classList.remove('active'));
tab.classList.add('active');
const targetId = `${tab.dataset.tab}-content`;
document.getElementById(targetId).classList.add('active');
});
});
function showStatus(message, isError = false, duration = 3000, isLoading = false) {
if (!message) {
statusDiv.style.display = 'none';
document.querySelector('.status-overlay').style.display = 'none';
return;
}
console.log(`[Reddit Copycat] Status: ${message} (${isError ? 'error' : isLoading ? 'loading' : 'success'})`);
statusDiv.textContent = message;
statusDiv.style.display = 'block';
document.querySelector('.status-overlay').style.display = 'block';
statusDiv.className = `status ${isError ? 'error' : isLoading ? 'loading' : 'success'}`;
// Only set timeout for non-loading messages or if explicitly specified
if (duration > 0 && (!isLoading || message !== 'Fetching current subreddits...')) {
setTimeout(() => {
// Only hide if this is still the current message
if (statusDiv.textContent === message) {
statusDiv.style.display = 'none';
document.querySelector('.status-overlay').style.display = 'none';
}
}, duration);
}
}
function showProgress(show = true, isLeaving = false) {
if (progressContainer) {
if (show) {
// Reset all progress elements when showing
if (progressFill) progressFill.style.width = '0%';
if (progressText) progressText.textContent = 'Progress: 0/0 subreddits';
if (progressInfo) progressInfo.textContent = isLeaving ? 'Leaving subreddits in progress...' : 'Joining subreddits in progress...';
progressContainer.style.display = 'flex';
} else {
progressContainer.style.display = 'none';
}
}
}
function updateProgressInfo(current, total, status, isLeaving = false) {
if (progressFill && progressText && progressInfo) {
// Ensure we have valid numbers for current and total
const validCurrent = typeof current === 'number' ? current : 0;
const validTotal = typeof total === 'number' ? total : 0;
const percentage = validTotal > 0 ? (validCurrent / validTotal) * 100 : 0;
progressFill.style.width = `${percentage}%`;
// Format the progress text with validated numbers
const progressString = `${validCurrent}/${validTotal} subreddits`;
progressText.textContent = status || `Progress: ${progressString}`;
// Update progress info with validated text
progressInfo.textContent = validCurrent === validTotal
? (isLeaving ? 'Leaving complete!' : 'Joining complete!')
: (isLeaving ? 'Leaving subreddits in progress...' : 'Joining subreddits in progress...');
// If we're complete, add completion message
if (validCurrent === validTotal && validTotal > 0) {
progressText.textContent = `Completed: ${progressString}`;
}
}
}
function saveProgressState(current, total, status, isLeaving = false) {
chrome.storage.local.set({
joinProgress: {
current,
total,
status,
timestamp: Date.now(),
isLeaving: isLeaving
}
});
}
function clearProgressState() {
chrome.storage.local.set({
joinProgress: {
inProgress: false,
current: 0,
total: 0,
status: '',
isLeaving: false
}
});
}
function updateProgress(current, total, status, isLeaving = false) {
// Validate the numbers before updating
const validCurrent = typeof current === 'number' ? current : 0;
const validTotal = typeof total === 'number' ? total : 0;
updateProgressInfo(validCurrent, validTotal, status, isLeaving);
console.log(`[Reddit Copycat] Progress: ${status || `${validCurrent}/${validTotal}`}`);
saveProgressState(validCurrent, validTotal, status, isLeaving);
// Handle completion with validated numbers
if (validCurrent === validTotal && validTotal > 0) {
if (progressInfo) {
progressInfo.textContent = isLeaving ? 'Leaving complete!' : 'Joining complete!';
}
if (progressText) {
progressText.textContent = `Completed: ${validCurrent}/${validTotal} subreddits`;
}
}
}
async function checkJoinStatus() {
try {
const response = await chrome.runtime.sendMessage({ action: 'checkJoinStatus' });
return response.isJoining;
} catch (error) {
console.error('[Reddit Copycat] Error checking join status:', error);
return false;
}
}
function setupProgressListener() {
cleanupProgressListener();
progressListener = function(msg) {
if (msg.action === 'joinProgress' || msg.action === 'leaveProgress') {
console.log('[Reddit Copycat] Progress update:', msg);
showProgress(true, msg.action === 'leaveProgress');
updateProgress(msg.current, msg.total, msg.status, msg.action === 'leaveProgress');
// Let the completion listeners handle the cleanup
if (msg.current === msg.total) {
setTimeout(checkProgressState, 2000);
}
}
};
chrome.runtime.onMessage.addListener(progressListener);
}
function cleanupProgressListener() {
if (progressListener) {
chrome.runtime.onMessage.removeListener(progressListener);
progressListener = null;
}
}
async function checkProgressState() {
try {
const { joinProgress } = await chrome.storage.local.get(['joinProgress']);
const status = await chrome.runtime.sendMessage({ action: 'checkJoinStatus' });
if (status.isJoining || (joinProgress?.inProgress && joinProgress.current < joinProgress.total)) {
try {
await chrome.tabs.get(status.activeTabId);
showProgress(true, status.currentOperation?.isLeaving || joinProgress?.isLeaving);
if (joinProgress) {
updateProgress(
joinProgress.current,
joinProgress.total,
joinProgress.status,
status.currentOperation?.isLeaving || joinProgress?.isLeaving
);
}
} catch (error) {
showStatus('The Reddit tab was closed. Please reopen Reddit and try again.', true);
showProgress(false);
}
} else if (joinProgress?.error) {
showStatus(joinProgress.error, true);
showProgress(false);
}
} catch (error) {
console.error('[Reddit Copycat] Error checking progress state:', error);
}
}
// Check progress state on load and periodically
checkProgressState();
setInterval(checkProgressState, 1000);
async function injectContentScriptIfNeeded() {
try {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
try {
const response = await chrome.tabs.sendMessage(tab.id, { action: 'ping' });
if (response.success) {
console.log('[Reddit Copycat] Content script is already active');
return true;
}
} catch (error) {
console.log('[Reddit Copycat] Content script not detected, injecting...');
}
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['content.js']
});
await new Promise(resolve => setTimeout(resolve, 500));
try {
const response = await chrome.tabs.sendMessage(tab.id, { action: 'ping' });
if (response.success) {
console.log('[Reddit Copycat] Content script successfully injected');
return true;
}
} catch (error) {
console.error('[Reddit Copycat] Failed to verify content script injection:', error);
return false;
}
} catch (error) {
console.error('[Reddit Copycat] Error injecting content script:', error);
return false;
}
}
async function isRedditTab() {
try {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
return tab.url.includes('reddit.com');
} catch (error) {
console.error('[Reddit Copycat] Error checking if Reddit tab:', error);
return false;
}
}
async function getCurrentUserSubreddits() {
try {
if (!await isRedditTab()) {
throw new Error('Please navigate to Reddit before using this feature.');
}
if (!await injectContentScriptIfNeeded()) {
throw new Error('Failed to initialize Reddit Copycat. Please refresh the page and try again.');
}
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const response = await chrome.tabs.sendMessage(tab.id, { action: 'getCurrentSubreddits' });
if (!response.success) {
throw new Error('Failed to fetch subreddits. Please make sure you are logged in to Reddit.');
}
return response.subreddits || [];
} catch (error) {
console.error('[Reddit Copycat] Error getting current subreddits:', error);
showStatus(error.message || 'An error occurred while fetching subreddits', true);
return [];
}
}
function updateSelectedCount() {
const selectedCount = selectedSubreddits.size;
const floatingActions = document.querySelector('.floating-actions');
const actionCount = document.querySelector('.action-count');
if (actionCount) {
actionCount.textContent = `${selectedCount} Selected`;
}
if (floatingActions) {
if (selectedCount > 0) {
floatingActions.classList.add('visible');
} else {
floatingActions.classList.remove('visible');
}
}
}
function updateCheckboxes() {
const checkboxes = document.querySelectorAll('#subredditList input[type="checkbox"]');
checkboxes.forEach(checkbox => {
checkbox.checked = selectedSubreddits.has(checkbox.dataset.subreddit);
});
updateSelectedCount();
}
async function updateSubredditList(savedSubs, filter = false) {
try {
const ul = subredditList.querySelector('ul') || document.createElement('ul');
ul.innerHTML = '';
if (joinedSubreddits.length === 0) {
showStatus('Fetching current subreddits...', false, 0, true);
if (!await isRedditTab()) {
throw new Error('Please navigate to Reddit to see joined status.');
}
if (!await injectContentScriptIfNeeded()) {
throw new Error('Failed to initialize. Please refresh the Reddit page and try again.');
}
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const response = await chrome.tabs.sendMessage(tab.id, { action: 'getCurrentSubreddits' });
if (!response || !response.success) {
throw new Error(response?.error || 'Failed to fetch current subreddits. Please make sure you are logged in to Reddit.');
}
joinedSubreddits = response.subreddits;
showStatus('', false, 0); // Clear the status only after we have the data
}
let subsToShow = savedSubs;
if (filter) {
subsToShow = savedSubs.filter(sub => !joinedSubreddits.includes(sub));
}
// Sort subreddits with Not Joined first, then alphabetically within each group
subsToShow.sort((a, b) => {
const aJoined = joinedSubreddits.includes(a);
const bJoined = joinedSubreddits.includes(b);
if (aJoined === bJoined) {
// If both are joined or both are not joined, sort alphabetically
return a.localeCompare(b);
}
// Put not joined first
return aJoined ? 1 : -1;
});
subsToShow.forEach(sub => {
const li = document.createElement('li');
const subInfo = document.createElement('div');
subInfo.className = 'sub-info';
const checkboxWrapper = document.createElement('div');
checkboxWrapper.className = 'checkbox-wrapper';
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.dataset.subreddit = sub;
checkbox.checked = selectedSubreddits.has(sub);
checkbox.addEventListener('change', () => {
if (checkbox.checked) {
selectedSubreddits.add(sub);
} else {
selectedSubreddits.delete(sub);
}
updateSelectedCount();
});
const nameSpan = document.createElement('span');
nameSpan.className = 'sub-name';
nameSpan.textContent = `r/${sub}`;
const statusBadge = document.createElement('span');
statusBadge.className = 'status-badge ' + (joinedSubreddits.includes(sub) ? 'joined' : 'not-joined');
statusBadge.textContent = joinedSubreddits.includes(sub) ? 'Joined' : 'Not Joined';
const visitBtn = document.createElement('button');
visitBtn.className = 'secondary-button';
visitBtn.style.padding = '4px 8px';
visitBtn.style.width = 'auto';
visitBtn.innerHTML = `
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path>
<polyline points="15 3 21 3 21 9"></polyline>
<line x1="10" y1="14" x2="21" y2="3"></line>
</svg>
`;
visitBtn.title = 'Visit Subreddit';
visitBtn.onclick = () => window.open(`https://reddit.com/r/${sub}`, '_blank');
checkboxWrapper.appendChild(checkbox);
subInfo.appendChild(checkboxWrapper);
subInfo.appendChild(nameSpan);
subInfo.appendChild(statusBadge);
subInfo.appendChild(visitBtn);
li.appendChild(subInfo);
ul.appendChild(li);
});
if (!subredditList.contains(ul)) {
subredditList.appendChild(ul);
}
if (statsDiv) {
const totalSubs = savedSubs.length;
const joinedCount = savedSubs.filter(sub => joinedSubreddits.includes(sub)).length;
const unjoinedCount = totalSubs - joinedCount;
statsDiv.innerHTML = `
<div class="stats-item">
<span class="stats-label">Total:</span>
<span>${totalSubs}</span>
</div>
<div class="stats-item">
<span class="stats-label">Joined:</span>
<span>${joinedCount}</span>
</div>
<div class="stats-item">
<span class="stats-label">Not Joined:</span>
<span>${unjoinedCount}</span>
</div>
`;
}
subredditList.style.display = 'block';
updateSelectedCount();
} catch (error) {
console.error('[Reddit Copycat] Error updating subreddit list:', error);
showStatus(error.message, true);
joinedSubreddits = []; // Reset so it will try again next time
}
}
// Event Listeners
if (selectAllBtn) {
selectAllBtn.addEventListener('click', () => {
const checkboxes = document.querySelectorAll('#subredditList input[type="checkbox"]');
const totalCheckboxes = checkboxes.length;
const buttonText = selectAllBtn.querySelector('.button-text');
// If all are selected, deselect all. Otherwise, select all.
if (selectedSubreddits.size === totalCheckboxes) {
selectedSubreddits.clear();
buttonText.textContent = 'Select All';
} else {
checkboxes.forEach(checkbox => {
selectedSubreddits.add(checkbox.dataset.subreddit);
});
buttonText.textContent = 'Deselect All';
}
updateCheckboxes();
});
}
if (selectUnjoinedBtn) {
selectUnjoinedBtn.addEventListener('click', async () => {
try {
// First, ensure we have the current joined subreddits
if (joinedSubreddits.length === 0) {
if (!await isRedditTab()) {
throw new Error('Please navigate to Reddit first.');
}
if (!await injectContentScriptIfNeeded()) {
throw new Error('Failed to initialize. Please refresh the Reddit page and try again.');
}
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const response = await chrome.tabs.sendMessage(tab.id, { action: 'getCurrentSubreddits' });
if (!response || !response.success) {
throw new Error('Failed to fetch current subreddits. Please make sure you are logged in to Reddit.');
}
joinedSubreddits = response.subreddits;
}
const checkboxes = document.querySelectorAll('#subredditList input[type="checkbox"]');
const unjoinedBoxes = Array.from(checkboxes).filter(checkbox =>
!joinedSubreddits.includes(checkbox.dataset.subreddit)
);
const buttonText = selectUnjoinedBtn.querySelector('.button-text');
// If all unjoined are selected, deselect them. Otherwise, select all unjoined.
const allUnjoinedSelected = unjoinedBoxes.every(checkbox =>
selectedSubreddits.has(checkbox.dataset.subreddit)
);
if (allUnjoinedSelected) {
// Deselect all unjoined
unjoinedBoxes.forEach(checkbox => {
selectedSubreddits.delete(checkbox.dataset.subreddit);
});
buttonText.textContent = 'Select Unjoined Only';
} else {
// Select all unjoined
unjoinedBoxes.forEach(checkbox => {
selectedSubreddits.add(checkbox.dataset.subreddit);
});
buttonText.textContent = 'Deselect Unjoined';
}
// Update UI
updateCheckboxes();
} catch (error) {
console.error('[Reddit Copycat] Error selecting unjoined subreddits:', error);
}
});
}
if (joinSelectedBtn) {
joinSelectedBtn.addEventListener('click', async () => {
if (selectedSubreddits.size === 0) return;
try {
joinSelectedBtn.disabled = true;
showProgress(true);
setupProgressListener();
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const response = await chrome.runtime.sendMessage({
action: 'startJoining',
tabId: tab.id,
subreddits: Array.from(selectedSubreddits)
});
if (response.success) {
let message = `Successfully started joining ${selectedSubreddits.size} subreddits!`;
showStatus(message);
// Reset joined subreddits to force a refresh on next update
joinedSubreddits = [];
// Clear selected subreddits
selectedSubreddits.clear();
updateSelectedCount();
// Set up completion listener
setupCompletionListener(false);
} else {
const errorMsg = response.error || 'Failed to start joining process. Please make sure you are logged in to Reddit and refresh the page.';
showStatus(errorMsg, true);
showProgress(false);
}
} catch (error) {
console.error('[Reddit Copycat] Join error:', error);
showStatus('Error: ' + (error.message || 'Unknown error occurred'), true);
showProgress(false);
} finally {
joinSelectedBtn.disabled = false;
}
});
}
if (leaveSelectedBtn) {
leaveSelectedBtn.addEventListener('click', async () => {
if (selectedSubreddits.size === 0) return;
try {
leaveSelectedBtn.disabled = true;
showProgress(true, true);
setupProgressListener();
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const response = await chrome.runtime.sendMessage({
action: 'startLeaving',
tabId: tab.id,
subreddits: Array.from(selectedSubreddits)
});
if (response.success) {
let message = `Successfully started leaving ${selectedSubreddits.size} subreddits!`;
showStatus(message);
// Reset joined subreddits to force a refresh on next update
joinedSubreddits = [];
// Clear selected subreddits
selectedSubreddits.clear();
updateSelectedCount();
// Set up completion listener
setupCompletionListener(true);
} else {
const errorMsg = response.error || 'Failed to start leaving process. Please make sure you are logged in to Reddit and refresh the page.';
showStatus(errorMsg, true);
showProgress(false);
}
} catch (error) {
console.error('[Reddit Copycat] Leave error:', error);
showStatus('Error: ' + (error.message || 'Unknown error occurred'), true);
showProgress(false);
} finally {
leaveSelectedBtn.disabled = false;
}
});
}
if (leaveSavedSubreddits) {
leaveSavedSubreddits.addEventListener('click', async () => {
try {
console.log('[Reddit Copycat] Leave all button clicked');
leaveSavedSubreddits.disabled = true;
if (!await isRedditTab()) {
showStatus('Please navigate to Reddit before using this feature.', true);
return;
}
await injectContentScriptIfNeeded();
showProgress(true, true);
setupProgressListener();
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const response = await chrome.runtime.sendMessage({
action: 'startLeaving',
tabId: tab.id
});
if (response.success) {
showStatus('Successfully started leaving process!');
// Reset joined subreddits to force a refresh on next update
joinedSubreddits = [];
// Set up completion listener with force refresh
chrome.storage.local.get(['savedSubreddits'], async (result) => {
if (result.savedSubreddits) {
currentSubreddits = result.savedSubreddits;
}
});
setupCompletionListener(true);
} else if (response.error === 'Operation in progress') {
showStatus('Please wait, another operation is in progress...', true);
showProgress(false);
} else {
const errorMsg = response.error || 'Failed to start leaving process. Please make sure you are logged in to Reddit and refresh the page.';
showStatus(errorMsg, true);
showProgress(false);
}
} catch (error) {
console.error('[Reddit Copycat] Leave error:', error);
showStatus('Error: ' + (error.message || 'Unknown error occurred'), true);
showProgress(false);
} finally {
leaveSavedSubreddits.disabled = false;
}
});
}
// Load saved subreddits automatically when popup opens
chrome.storage.local.get(['savedSubreddits'], async (result) => {
if (result.savedSubreddits && result.savedSubreddits.length > 0) {
try {
currentSubreddits = result.savedSubreddits;
await updateSubredditList(currentSubreddits, filterCheckbox?.checked);
} catch (error) {
console.error('[Reddit Copycat] Error displaying subreddits:', error);
showStatus('Error loading subreddits. Please try again.', true);
}
}
});
// Dropdown functionality
const bulkActionsBtn = document.getElementById('bulkActionsBtn');
const dropdownContent = document.querySelector('.dropdown-content');
const joinAllBtn = document.getElementById('joinAllBtn');
const leaveAllBtn = document.getElementById('leaveAllBtn');
const floatingJoinBtn = document.getElementById('floatingJoinBtn');
const floatingLeaveBtn = document.getElementById('floatingLeaveBtn');
// Toggle dropdown when clicking the bulk actions button
if (bulkActionsBtn) {
bulkActionsBtn.addEventListener('click', (e) => {
e.stopPropagation();
const dropdown = e.target.closest('.dropdown');
const content = dropdown.querySelector('.dropdown-content');
// Toggle active state
dropdown.classList.toggle('active');
// If we're showing the dropdown, ensure smooth animation
if (!content.classList.contains('show')) {
content.style.display = 'block';
// Force a reflow
content.offsetHeight;
content.classList.add('show');
} else {
content.classList.remove('show');
// Wait for animation to finish before hiding
setTimeout(() => {
if (!content.classList.contains('show')) {
content.style.display = 'none';
}
}, 200);
}
});
}
// Handle join all action
joinAllBtn.addEventListener('click', async () => {
dropdownContent.classList.remove('show');
try {
console.log('[Reddit Copycat] Join all button clicked');
if (!await isRedditTab()) {
showStatus('Please navigate to Reddit before using this feature.', true);
return;
}
await injectContentScriptIfNeeded();
showProgress(true);
setupProgressListener();
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const response = await chrome.runtime.sendMessage({
action: 'startJoining',
tabId: tab.id
});
if (response.success) {
showStatus('Successfully started joining process!');
joinedSubreddits = [];
setupCompletionListener(false);
} else if (response.error === 'Operation in progress') {
showStatus('Please wait, another operation is in progress...', true);
showProgress(false);
} else {
const errorMsg = response.error || 'Failed to start joining process. Please make sure you are logged in to Reddit.';
showStatus(errorMsg, true);
showProgress(false);
}
} catch (error) {
console.error('[Reddit Copycat] Join error:', error);
showStatus('Error: ' + (error.message || 'Unknown error occurred'), true);
showProgress(false);
}
});
// Handle leave all action
leaveAllBtn.addEventListener('click', async () => {
dropdownContent.classList.remove('show');
try {
console.log('[Reddit Copycat] Leave all button clicked');
if (!await isRedditTab()) {
showStatus('Please navigate to Reddit before using this feature.', true);
return;
}
await injectContentScriptIfNeeded();
showProgress(true, true);
setupProgressListener();
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const response = await chrome.runtime.sendMessage({
action: 'startLeaving',
tabId: tab.id
});
if (response.success) {
showStatus('Successfully started leaving process!');
joinedSubreddits = [];
setupCompletionListener(true);
} else if (response.error === 'Operation in progress') {
showStatus('Please wait, another operation is in progress...', true);
showProgress(false);
} else {
const errorMsg = response.error || 'Failed to start leaving process. Please make sure you are logged in to Reddit.';
showStatus(errorMsg, true);
showProgress(false);
}
} catch (error) {
console.error('[Reddit Copycat] Leave error:', error);
showStatus('Error: ' + (error.message || 'Unknown error occurred'), true);
showProgress(false);
}
});
// Handle floating join selected action
floatingJoinBtn.addEventListener('click', async () => {
if (selectedSubreddits.size === 0) return;
try {
floatingJoinBtn.disabled = true;
showProgress(true);
setupProgressListener();
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const response = await chrome.runtime.sendMessage({
action: 'startJoining',
tabId: tab.id,
subreddits: Array.from(selectedSubreddits)
});
if (response.success) {
showStatus(`Successfully started joining ${selectedSubreddits.size} subreddits!`);
joinedSubreddits = [];
selectedSubreddits.clear();
updateSelectedCount();
setupCompletionListener(false);
} else {
const errorMsg = response.error || 'Failed to start joining process. Please make sure you are logged in to Reddit.';
showStatus(errorMsg, true);
showProgress(false);
}
} catch (error) {
console.error('[Reddit Copycat] Join error:', error);
showStatus('Error: ' + (error.message || 'Unknown error occurred'), true);
showProgress(false);
} finally {
floatingJoinBtn.disabled = false;
}
});
// Handle floating leave selected action
floatingLeaveBtn.addEventListener('click', async () => {
if (selectedSubreddits.size === 0) return;
try {
floatingLeaveBtn.disabled = true;
showProgress(true, true);
setupProgressListener();
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const response = await chrome.runtime.sendMessage({
action: 'startLeaving',
tabId: tab.id,
subreddits: Array.from(selectedSubreddits)
});
if (response.success) {
showStatus(`Successfully started leaving ${selectedSubreddits.size} subreddits!`);
joinedSubreddits = [];
selectedSubreddits.clear();
updateSelectedCount();
setupCompletionListener(true);
} else {
const errorMsg = response.error || 'Failed to start leaving process. Please make sure you are logged in to Reddit.';
showStatus(errorMsg, true);
showProgress(false);
}
} catch (error) {
console.error('[Reddit Copycat] Leave error:', error);
showStatus('Error: ' + (error.message || 'Unknown error occurred'), true);
showProgress(false);
} finally {
floatingLeaveBtn.disabled = false;
}
});
// Restore all the event listeners and functionality
if (filterCheckbox) {
filterCheckbox.addEventListener('change', () => {
if (currentSubreddits.length > 0) {
updateSubredditList(currentSubreddits, filterCheckbox.checked);
}
});
}
if (saveButton) {
saveButton.addEventListener('click', async () => {
try {
console.log('[Reddit Copycat] Save button clicked');
saveButton.disabled = true;
if (!await isRedditTab()) {
showStatus('Please navigate to Reddit before using this feature.', true);
return;
}
await injectContentScriptIfNeeded();
showStatus('Fetching your subreddits... This may take a moment.', false, 0);
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
console.log('[Reddit Copycat] Sending saveSubreddits message to tab:', tab.id);
const response = await chrome.tabs.sendMessage(tab.id, { action: 'saveSubreddits' });
if (response.success) {
showStatus(`Successfully saved ${response.count} subreddits!`);
currentSubreddits = response.subreddits;
await updateSubredditList(response.subreddits, filterCheckbox?.checked || false);
} else {
showStatus('Failed to save subreddits. Please make sure you are logged in to Reddit.', true);
}
} catch (error) {
console.error('[Reddit Copycat] Save error:', error);
showStatus('Error: ' + (error.message || 'Unknown error occurred'), true);
} finally {
saveButton.disabled = false;
}
});
}
// Export functionality
if (exportButton) {
exportButton.addEventListener('click', () => {
chrome.storage.local.get(['savedSubreddits'], (result) => {
if (!result.savedSubreddits || result.savedSubreddits.length === 0) {
showStatus('No subreddits to export. Save some subreddits first!', true);
return;