-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
1121 lines (954 loc) · 39.4 KB
/
Copy pathpopup.js
File metadata and controls
1121 lines (954 loc) · 39.4 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
// HaRiverse Extension - Enhanced Popup Script
class HaRiversePopup {
constructor() {
this.currentTab = 'screenshot';
this.colorHistory = this.loadColorHistory();
this.isCapturing = false;
this.isPickingColor = false;
this.isAnalyzing = false;
this.currentColor = '#6366f1';
this.settings = this.loadSettings();
this.currentTheme = this.loadTheme();
this.init();
}
init() {
this.setupEventListeners();
this.setupMessageListener();
this.updateColorDisplay(this.currentColor);
this.updateColorPalette();
this.initializeQRContent();
this.initTheme();
console.log('HaRiverse popup v2.0 initialized');
}
setupEventListeners() {
// Feature navigation
document.querySelectorAll('.feature-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
const tab = e.target.closest('.feature-btn').dataset.tab;
this.switchTab(tab);
});
});
// Screenshot functionality
const captureBtn = document.getElementById('captureBtn');
if (captureBtn) {
captureBtn.addEventListener('click', () => this.captureFullPage());
}
// Color picker functionality
const pickColorBtn = document.getElementById('pickColorBtn');
if (pickColorBtn) {
pickColorBtn.addEventListener('click', () => this.pickColor());
}
// Copy buttons for color codes
document.querySelectorAll('.copy-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
const copyType = e.target.closest('.copy-btn').dataset.copy;
this.copyColorCode(copyType);
});
});
// QR Code functionality
const generateQrBtn = document.getElementById('generateQrBtn');
if (generateQrBtn) {
generateQrBtn.addEventListener('click', () => this.generateQRCode());
}
const downloadQrBtn = document.getElementById('downloadQrBtn');
if (downloadQrBtn) {
downloadQrBtn.addEventListener('click', () => this.downloadQRCode());
}
// Video Speed Controller
this.initVideoSpeedController();
// Cookie Blocker
this.initCookieBlocker();
// Theme Toggle
this.initThemeToggle();
// Settings functionality
const settingsBtn = document.getElementById('settingsBtn');
if (settingsBtn) {
settingsBtn.addEventListener('click', () => this.openSettings());
}
const closeSettings = document.getElementById('closeSettings');
if (closeSettings) {
closeSettings.addEventListener('click', () => this.closeSettings());
}
const saveSettings = document.getElementById('saveSettings');
if (saveSettings) {
saveSettings.addEventListener('click', () => this.saveSettings());
}
const resetSettings = document.getElementById('resetSettings');
if (resetSettings) {
resetSettings.addEventListener('click', () => this.resetSettings());
}
// Theme toggle functionality
const themeToggleBtn = document.getElementById('themeToggleBtn');
if (themeToggleBtn) {
themeToggleBtn.addEventListener('click', () => this.toggleTheme());
}
// Palette color clicks
document.addEventListener('click', (e) => {
if (e.target.classList.contains('palette-color')) {
const color = e.target.dataset.color;
if (color) {
this.updateColorDisplay(color);
}
}
});
// Modal backdrop click
const settingsModal = document.getElementById('settingsModal');
if (settingsModal) {
settingsModal.addEventListener('click', (e) => {
if (e.target.id === 'settingsModal') {
this.closeSettings();
}
});
}
// Cleanup when popup closes
window.addEventListener('beforeunload', () => {
this.cleanup();
});
}
setupMessageListener() {
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'captureProgress') {
if (message.status) {
this.updateStatus(message.status);
}
if (message.progress !== undefined) {
this.updateProgress(message.progress);
}
} else if (message.action === 'cookieBlockerStats') {
if (message.stats) {
this.cookieBlockerStats = message.stats;
this.updateCookieBlockerUI();
}
}
});
}
switchTab(tabName) {
// Update active feature button
document.querySelectorAll('.feature-btn').forEach(btn => {
btn.classList.remove('active');
});
document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
// Update active tab panel
document.querySelectorAll('.tab-panel').forEach(panel => {
panel.classList.remove('active');
});
document.getElementById(tabName).classList.add('active');
this.currentTab = tabName;
console.log('Switched to tab:', tabName);
}
// ===== SCREENSHOT FUNCTIONALITY =====
async captureFullPage() {
if (this.isCapturing) return;
this.isCapturing = true;
const captureBtn = document.getElementById('captureBtn');
const progressContainer = document.getElementById('progressContainer');
try {
captureBtn.disabled = true;
captureBtn.classList.add('loading');
progressContainer.classList.remove('hidden');
// Get settings
const format = document.getElementById('screenshotFormat').value;
const quality = document.getElementById('screenshotQuality').value;
// Get current tab
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
this.updateStatus('Preparing screenshot...');
this.updateProgress(10);
// Use Chrome DevTools Protocol for full page screenshot
const response = await chrome.runtime.sendMessage({
action: 'captureFullPage',
tabId: tab.id,
format: format,
quality: quality
});
if (response.success) {
this.updateStatus('Screenshot captured successfully!');
this.updateProgress(100);
if (this.settings.autoDownload) {
await this.downloadImage(response.dataUrl, format);
}
this.showToast('success', 'Success', 'Full page screenshot captured!');
} else {
throw new Error(response.error || 'Failed to capture screenshot');
}
} catch (error) {
console.error('Screenshot failed:', error);
this.updateStatus('Failed to capture screenshot');
this.showToast('error', 'Error', error.message);
} finally {
this.resetCaptureUI();
this.isCapturing = false;
}
}
// ===== COLOR PICKER FUNCTIONALITY =====
async pickColor() {
if (this.isPickingColor) return;
this.isPickingColor = true;
const pickColorBtn = document.getElementById('pickColorBtn');
try {
pickColorBtn.disabled = true;
pickColorBtn.classList.add('loading');
// Try modern EyeDropper API first
if ('EyeDropper' in window) {
const eyeDropper = new EyeDropper();
const result = await eyeDropper.open();
if (result && result.sRGBHex) {
this.updateColorDisplay(result.sRGBHex);
this.addToColorHistory(result.sRGBHex);
this.showToast('success', 'Success', 'Color picked successfully!');
}
} else {
// Fallback to content script
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
const response = await chrome.tabs.sendMessage(tab.id, {
action: 'startColorPicker'
});
if (response && response.success && response.color) {
this.updateColorDisplay(response.color);
this.addToColorHistory(response.color);
this.showToast('success', 'Success', 'Color picked successfully!');
} else {
throw new Error(response?.error || 'Color picking failed');
}
}
} catch (error) {
console.error('Color picker failed:', error);
if (error.name !== 'AbortError') {
this.showToast('error', 'Error', 'Color picking failed');
}
} finally {
pickColorBtn.disabled = false;
pickColorBtn.classList.remove('loading');
this.isPickingColor = false;
}
}
updateColorDisplay(color) {
this.currentColor = color;
// Update color swatch
const colorSwatch = document.getElementById('colorSwatch');
if (colorSwatch) {
colorSwatch.style.backgroundColor = color;
}
// Convert to different formats
const rgb = this.hexToRgb(color);
const hsl = this.rgbToHsl(rgb.r, rgb.g, rgb.b);
// Update input fields
document.getElementById('hexValue').value = color.toUpperCase();
document.getElementById('rgbValue').value = `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`;
document.getElementById('hslValue').value = `hsl(${Math.round(hsl.h)}, ${Math.round(hsl.s)}%, ${Math.round(hsl.l)}%)`;
}
async copyColorCode(type) {
let textToCopy = '';
switch (type) {
case 'hex':
textToCopy = document.getElementById('hexValue').value;
break;
case 'rgb':
textToCopy = document.getElementById('rgbValue').value;
break;
case 'hsl':
textToCopy = document.getElementById('hslValue').value;
break;
}
try {
await navigator.clipboard.writeText(textToCopy);
this.showToast('success', 'Copied!', `${type.toUpperCase()} color code copied`);
} catch (error) {
console.error('Failed to copy:', error);
this.showToast('error', 'Error', 'Failed to copy color code');
}
}
addToColorHistory(color) {
// Remove if already exists
this.colorHistory = this.colorHistory.filter(c => c !== color);
// Add to beginning
this.colorHistory.unshift(color);
// Keep only last 8 colors
this.colorHistory = this.colorHistory.slice(0, 8);
// Save and update display
this.saveColorHistory();
this.updateColorPalette();
}
updateColorPalette() {
const paletteContainer = document.getElementById('colorPalette');
if (!paletteContainer) return;
paletteContainer.innerHTML = '';
this.colorHistory.forEach(color => {
const colorDiv = document.createElement('div');
colorDiv.className = 'palette-color';
colorDiv.style.backgroundColor = color;
colorDiv.dataset.color = color;
colorDiv.title = color;
paletteContainer.appendChild(colorDiv);
});
}
// ===== QR CODE FUNCTIONALITY =====
initializeQRContent() {
const qrContent = document.getElementById('qrContent');
if (qrContent && !qrContent.value) {
// Set current page URL as default
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (tabs[0]) {
qrContent.value = tabs[0].url;
}
});
}
}
async generateQRCode() {
const contentInput = document.getElementById('qrContent');
const sizeSelect = document.getElementById('qrSize');
const canvas = document.getElementById('qrCanvas');
const placeholder = document.getElementById('qrPlaceholder');
const downloadBtn = document.getElementById('downloadQrBtn');
let content = contentInput ? contentInput.value.trim() : '';
const size = sizeSelect ? parseInt(sizeSelect.value) : 256;
// If no content provided, use current page URL
if (!content) {
try {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
if (tab && tab.url) {
content = tab.url;
if (contentInput) {
contentInput.value = content;
}
} else {
this.showToast('error', 'Error', 'Please enter content for QR code');
return;
}
} catch (error) {
this.showToast('error', 'Error', 'Please enter content for QR code');
return;
}
}
try {
// Generate QR code using background script
const response = await chrome.runtime.sendMessage({
action: 'generateQRCode',
content: content,
size: size
});
if (response.success) {
// Display QR code
this.displayQRCode(response.dataUrl, canvas, placeholder);
downloadBtn.classList.remove('hidden');
this.showToast('success', 'Success', 'QR code generated successfully!');
} else {
throw new Error(response.error || 'Failed to generate QR code');
}
} catch (error) {
console.error('QR generation failed:', error);
this.showToast('error', 'Error', 'Failed to generate QR code');
}
}
displayQRCode(dataUrl, canvas, placeholder) {
const img = new Image();
img.onload = () => {
const ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
canvas.style.display = 'block';
placeholder.style.display = 'none';
};
img.src = dataUrl;
}
async downloadQRCode() {
const canvas = document.getElementById('qrCanvas');
const formatSelect = document.getElementById('qrFormat');
const format = formatSelect ? formatSelect.value : 'png';
if (!canvas || canvas.style.display === 'none') {
this.showToast('error', 'Error', 'No QR code to download');
return;
}
try {
const dataUrl = canvas.toDataURL(`image/${format}`);
await this.downloadImage(dataUrl, format, 'qrcode');
this.showToast('success', 'Success', 'QR code downloaded successfully!');
} catch (error) {
console.error('QR download failed:', error);
this.showToast('error', 'Error', 'Failed to download QR code');
}
}
// ===== VIDEO SPEED CONTROLLER FUNCTIONALITY =====
initVideoSpeedController() {
this.currentSpeed = 1.0;
this.videoCount = 0;
this.activeVideo = null;
// Initialize UI elements
const speedSlider = document.getElementById('speedSlider');
const currentSpeedDisplay = document.getElementById('currentSpeed');
const resetBtn = document.getElementById('resetSpeedBtn');
const applyAllBtn = document.getElementById('applyToAllBtn');
const presetBtns = document.querySelectorAll('.preset-btn');
const speedMarks = document.querySelectorAll('.mark');
// Slider event listener
if (speedSlider) {
speedSlider.addEventListener('input', (e) => {
const speed = parseFloat(e.target.value);
this.setVideoSpeed(speed);
});
}
// Preset buttons
presetBtns.forEach(btn => {
btn.addEventListener('click', () => {
const speed = parseFloat(btn.dataset.speed);
this.setVideoSpeed(speed);
if (speedSlider) speedSlider.value = speed;
});
});
// Speed marks (clickable)
speedMarks.forEach(mark => {
mark.addEventListener('click', () => {
const speed = parseFloat(mark.dataset.speed);
this.setVideoSpeed(speed);
if (speedSlider) speedSlider.value = speed;
});
});
// Control buttons
if (resetBtn) {
resetBtn.addEventListener('click', () => {
this.setVideoSpeed(1.0);
if (speedSlider) speedSlider.value = 1.0;
});
}
if (applyAllBtn) {
applyAllBtn.addEventListener('click', () => {
this.applySpeedToAllVideos();
});
}
// Initialize video detection
this.detectVideos();
// Set up periodic video detection
this.videoDetectionInterval = setInterval(() => {
this.detectVideos();
}, 2000);
}
async setVideoSpeed(speed) {
this.currentSpeed = speed;
// Update UI
const currentSpeedDisplay = document.getElementById('currentSpeed');
if (currentSpeedDisplay) {
currentSpeedDisplay.textContent = speed.toFixed(2);
}
// Update active preset button
const presetBtns = document.querySelectorAll('.preset-btn');
presetBtns.forEach(btn => {
btn.classList.remove('active');
if (parseFloat(btn.dataset.speed) === speed) {
btn.classList.add('active');
}
});
try {
// Get current tab
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
// Try to send message to content script
try {
await chrome.tabs.sendMessage(tab.id, {
action: 'setVideoSpeed',
speed: speed
});
} catch (messageError) {
// If content script is not available, inject it first
console.log('Content script not available, injecting...');
try {
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['content.js']
});
// Wait a bit for the script to initialize
await new Promise(resolve => setTimeout(resolve, 100));
// Try sending the message again
await chrome.tabs.sendMessage(tab.id, {
action: 'setVideoSpeed',
speed: speed
});
} catch (injectionError) {
console.error('Failed to inject content script:', injectionError);
this.showToast('error', 'Error', 'Cannot control videos on this page');
return;
}
}
} catch (error) {
console.error('Failed to set video speed:', error);
this.showToast('error', 'Error', 'Failed to change video speed');
}
}
async applySpeedToAllVideos() {
try {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
try {
await chrome.tabs.sendMessage(tab.id, {
action: 'setVideoSpeed',
speed: this.currentSpeed,
applyToAll: true
});
this.showToast('success', 'Success', `Applied ${this.currentSpeed}x speed to all videos`);
} catch (messageError) {
// If content script is not available, inject it first
try {
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['content.js']
});
await new Promise(resolve => setTimeout(resolve, 100));
await chrome.tabs.sendMessage(tab.id, {
action: 'setVideoSpeed',
speed: this.currentSpeed,
applyToAll: true
});
this.showToast('success', 'Success', `Applied ${this.currentSpeed}x speed to all videos`);
} catch (injectionError) {
this.showToast('error', 'Error', 'Cannot control videos on this page');
}
}
} catch (error) {
console.error('Failed to apply speed to all videos:', error);
this.showToast('error', 'Error', 'Failed to apply speed to all videos');
}
}
async detectVideos() {
try {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
try {
const response = await chrome.tabs.sendMessage(tab.id, {
action: 'detectVideos'
});
if (response && response.success) {
this.updateVideoInfo(response.videoCount, response.activeVideo);
}
} catch (messageError) {
// If content script is not available, inject it first
try {
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ['content.js']
});
await new Promise(resolve => setTimeout(resolve, 100));
const response = await chrome.tabs.sendMessage(tab.id, {
action: 'detectVideos'
});
if (response && response.success) {
this.updateVideoInfo(response.videoCount, response.activeVideo);
}
} catch (injectionError) {
// Silently handle injection errors for video detection
this.updateVideoInfo(0, 'None');
}
}
} catch (error) {
// Silently handle errors for video detection
console.log('Video detection failed:', error);
}
}
updateVideoInfo(count, activeVideo) {
this.videoCount = count;
this.activeVideo = activeVideo;
const videoCountEl = document.getElementById('videoCount');
const activeVideoEl = document.getElementById('activeVideo');
if (videoCountEl) {
videoCountEl.textContent = count;
}
if (activeVideoEl) {
activeVideoEl.textContent = activeVideo || 'None';
}
}
// Clean up interval when popup closes
cleanup() {
if (this.videoDetectionInterval) {
clearInterval(this.videoDetectionInterval);
}
}
// ===== COOKIE BLOCKER FUNCTIONALITY =====
async initCookieBlocker() {
this.cookieBlockerEnabled = false;
this.cookieBlockerStats = { blocked: 0, sites: 0 };
// Load saved settings
await this.loadCookieBlockerSettings();
// Initialize UI elements
const toggle = document.getElementById('cookieBlockerToggle');
const status = document.getElementById('cookieBlockerStatus');
const statsDisplay = document.getElementById('cookieBlockerStats');
const resetStatsBtn = document.getElementById('resetCookieBlockerStats');
// Toggle event listener
if (toggle) {
toggle.addEventListener('change', (e) => {
this.toggleCookieBlocker(e.target.checked);
});
}
// Reset stats button
if (resetStatsBtn) {
resetStatsBtn.addEventListener('click', () => {
this.resetCookieBlockerStats();
});
}
// Update UI
this.updateCookieBlockerUI();
console.log('Cookie blocker initialized');
}
async loadCookieBlockerSettings() {
try {
const result = await chrome.storage.sync.get(['cookieBlockerEnabled', 'cookieBlockerStats']);
this.cookieBlockerEnabled = result.cookieBlockerEnabled || false;
this.cookieBlockerStats = result.cookieBlockerStats || { blocked: 0, sites: 0 };
} catch (error) {
console.error('Failed to load cookie blocker settings:', error);
}
}
async saveCookieBlockerSettings() {
try {
await chrome.storage.sync.set({
cookieBlockerEnabled: this.cookieBlockerEnabled,
cookieBlockerStats: this.cookieBlockerStats
});
} catch (error) {
console.error('Failed to save cookie blocker settings:', error);
}
}
async toggleCookieBlocker(enabled) {
this.cookieBlockerEnabled = enabled;
await this.saveCookieBlockerSettings();
// Send message to background script to enable/disable cookie blocker
try {
await chrome.runtime.sendMessage({
action: 'toggleCookieBlocker',
enabled: enabled
});
this.updateCookieBlockerUI();
const message = enabled ? 'Cookie blocker enabled' : 'Cookie blocker disabled';
this.showToast('success', 'Cookie Blocker', message);
} catch (error) {
console.error('Failed to toggle cookie blocker:', error);
this.showToast('error', 'Error', 'Failed to toggle cookie blocker');
}
}
updateCookieBlockerUI() {
const toggle = document.getElementById('cookieBlockerToggle');
const status = document.getElementById('cookieBlockerStatus');
const statsDisplay = document.getElementById('cookieBlockerStats');
const resetStatsBtn = document.getElementById('resetCookieBlockerStats');
if (toggle) {
toggle.checked = this.cookieBlockerEnabled;
}
if (status) {
status.textContent = this.cookieBlockerEnabled ? 'Enabled' : 'Disabled';
status.className = `cookie-blocker-status ${this.cookieBlockerEnabled ? 'enabled' : 'disabled'}`;
}
if (statsDisplay) {
const { blocked, sites } = this.cookieBlockerStats;
statsDisplay.textContent = `Blocked: ${blocked} banners on ${sites} sites`;
}
if (resetStatsBtn) {
const hasStats = this.cookieBlockerStats.blocked > 0 || this.cookieBlockerStats.sites > 0;
resetStatsBtn.classList.toggle('hidden', !hasStats);
}
}
async resetCookieBlockerStats() {
this.cookieBlockerStats = { blocked: 0, sites: 0 };
await this.saveCookieBlockerSettings();
this.updateCookieBlockerUI();
this.showToast('success', 'Cookie Blocker', 'Statistics reset');
}
async updateCookieBlockerStats(blocked, site) {
this.cookieBlockerStats.blocked += blocked;
if (site && !this.cookieBlockerStats.sites.includes?.(site)) {
this.cookieBlockerStats.sites += 1;
}
await this.saveCookieBlockerSettings();
this.updateCookieBlockerUI();
}
// ===== SETTINGS FUNCTIONALITY =====
openSettings() {
const modal = document.getElementById('settingsModal');
const themeSelect = document.getElementById('themeSelect');
const formatSelect = document.getElementById('defaultFormat');
const autoDownload = document.getElementById('autoDownload');
if (themeSelect) themeSelect.value = this.settings.theme;
if (formatSelect) formatSelect.value = this.settings.defaultFormat;
if (autoDownload) autoDownload.checked = this.settings.autoDownload;
if (modal) {
modal.classList.remove('hidden');
}
}
closeSettings() {
const modal = document.getElementById('settingsModal');
if (modal) {
modal.classList.add('hidden');
}
}
saveSettings() {
const themeSelect = document.getElementById('themeSelect');
const formatSelect = document.getElementById('defaultFormat');
const autoDownload = document.getElementById('autoDownload');
if (themeSelect) this.settings.theme = themeSelect.value;
if (formatSelect) this.settings.defaultFormat = formatSelect.value;
if (autoDownload) this.settings.autoDownload = autoDownload.checked;
this.saveSettingsToStorage();
this.showToast('success', 'Success', 'Settings saved successfully!');
this.closeSettings();
}
resetSettings() {
this.settings = {
theme: 'auto',
defaultFormat: 'png',
autoDownload: true
};
this.saveSettingsToStorage();
this.openSettings(); // Refresh the modal
this.showToast('info', 'Reset', 'Settings reset to default');
}
// ===== UTILITY FUNCTIONS =====
async downloadImage(dataUrl, format, filename = 'screenshot') {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const finalFilename = `hariverse_${filename}_${timestamp}.${format}`;
try {
const response = await chrome.runtime.sendMessage({
action: 'downloadImage',
dataUrl: dataUrl,
filename: finalFilename
});
if (!response.success) {
throw new Error(response.error);
}
} catch (error) {
console.error('Download failed:', error);
// Fallback: create download link
const link = document.createElement('a');
link.href = dataUrl;
link.download = finalFilename;
link.click();
}
}
updateProgress(percent) {
const progressFill = document.getElementById('progressFill');
if (progressFill) {
progressFill.style.width = `${percent}%`;
}
}
updateStatus(message) {
const statusElement = document.getElementById('screenshotStatus');
if (statusElement) {
statusElement.textContent = message;
}
}
resetCaptureUI() {
const captureBtn = document.getElementById('captureBtn');
const progressContainer = document.getElementById('progressContainer');
if (captureBtn) {
captureBtn.disabled = false;
captureBtn.classList.remove('loading');
}
if (progressContainer) {
progressContainer.classList.add('hidden');
}
this.updateProgress(0);
}
showToast(type, title, message) {
const container = document.getElementById('toastContainer');
if (!container) return;
const toast = document.createElement('div');
toast.className = `toast ${type}`;
toast.innerHTML = `
<div class="toast-icon">${this.getToastIcon(type)}</div>
<div class="toast-content">
<div class="toast-title">${title}</div>
<div class="toast-message">${message}</div>
</div>
<button class="toast-close">×</button>
`;
// Add close functionality
toast.querySelector('.toast-close').addEventListener('click', () => {
toast.remove();
});
container.appendChild(toast);
// Auto remove after 3 seconds
setTimeout(() => {
if (toast.parentNode) {
toast.remove();
}
}, 3000);
}
getToastIcon(type) {
const icons = {
success: '✅',
error: '❌',
info: 'ℹ️',
warning: '⚠️'
};
return icons[type] || 'ℹ️';
}
// Color utility functions
hexToRgb(hex) {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
rgbToHsl(r, g, b) {
r /= 255;
g /= 255;
b /= 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
let h, s, l = (max + min) / 2;
if (max === min) {
h = s = 0;
} else {
const d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return {
h: Math.round(h * 360),
s: Math.round(s * 100),
l: Math.round(l * 100)
};
}
// Storage functions
loadColorHistory() {
const stored = localStorage.getItem('hariverse-color-history');
return stored ? JSON.parse(stored) : [
'#6366f1', '#8b5cf6', '#ec4899', '#10b981',
'#f59e0b', '#ef4444', '#84cc16', '#06b6d4'
];
}
saveColorHistory() {
localStorage.setItem('hariverse-color-history', JSON.stringify(this.colorHistory));
}
loadSettings() {
const stored = localStorage.getItem('hariverse-settings');
return stored ? JSON.parse(stored) : {
theme: 'auto',
defaultFormat: 'png',
autoDownload: true
};
}
saveSettingsToStorage() {
localStorage.setItem('hariverse-settings', JSON.stringify(this.settings));
}
// ===== THEME FUNCTIONALITY =====
initTheme() {
this.applyTheme(this.currentTheme);
this.updateThemeIcon();
}
toggleTheme() {
this.currentTheme = this.currentTheme === 'light' ? 'dark' : 'light';
this.applyTheme(this.currentTheme);
this.updateThemeIcon();
this.saveTheme();
}
applyTheme(theme) {
document.documentElement.setAttribute('data-color-scheme', theme);
}
updateThemeIcon() {
const sunIcon = document.querySelector('.sun-icon');
const moonIcon = document.querySelector('.moon-icon');