-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
2982 lines (2541 loc) · 132 KB
/
script.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
// Improved service worker registration with update handling
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('./service-worker.js')
.then(registration => {
console.log('Service Worker registered with scope:', registration.scope);
// Check for updates to the service worker
registration.addEventListener('updatefound', () => {
const newWorker = registration.installing;
console.log('Service Worker update found!');
newWorker.addEventListener('statechange', () => {
// When the new service worker is installed and waiting
if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
console.log('New service worker installed, but waiting.');
// Notify user that an update is available
if (window.offlineManager) {
// Optional: Show update notification through offline manager
}
}
});
});
// Check if there is a waiting service worker
if (registration.waiting) {
console.log('New service worker waiting to activate');
// Optional: Show update ready notification
}
})
.catch(error => {
console.error('Service Worker registration failed:', error);
});
// Handle service worker updates
let refreshing = false;
navigator.serviceWorker.addEventListener('controllerchange', () => {
if (!refreshing) {
refreshing = true;
console.log('New service worker activated, reloading page...');
window.location.reload();
}
});
});
}
// ========== VARIABLE DECLARATIONS ==========
document.addEventListener('DOMContentLoaded', function() {
const mainWindow = document.getElementById('main-window');
const tabIcons = document.querySelectorAll('.tab-icon');
const tabContents = document.querySelectorAll('.tab-content');
let currentTabIndex = 0;
// Shortcut management variables
const shortcutsGrid = document.getElementById('shortcuts-grid');
const addShortcutBtn = document.getElementById('add-shortcut-toggle');
const shortcutForm = document.getElementById('shortcut-form');
const shortcutNameInput = document.getElementById('shortcut-name');
const shortcutUrlInput = document.getElementById('shortcut-url');
const saveShortcutBtn = document.getElementById('save-shortcut');
const cancelShortcutBtn = document.getElementById('cancel-shortcut');
let editingShortcutIndex = null; // Track which shortcut is being edited
// Settings management variables
const settingsBtn = document.getElementById('settings-toggle');
const settingsForm = document.getElementById('settings-form');
const exportBtn = document.getElementById('export-btn');
const importBtn = document.getElementById('import-btn');
const importFile = document.getElementById('import-file');
const closeSettingsBtn = document.getElementById('close-settings');
const importNotification = document.getElementById('import-notification');
// Notes and Todo variables
const notesArea = document.getElementById('notes-area');
const todoInput = document.getElementById('todo-input');
const addTodoBtn = document.getElementById('add-todo-btn');
const todoList = document.getElementById('todo-list');
const todoSection = document.querySelector('.todo-section');
const notesSection = document.querySelector('.notes-section');
const body = document.body;
const statusBar = document.querySelector('.status-bar');
const mainWindowElement = document.querySelector('.main-window'); // Added for direct style access
// Updated UI elements
const addWebsiteOption = document.getElementById('add-website-option');
const toggleEditModeOption = document.getElementById('toggle-edit-mode');
const editModeLabel = document.getElementById('edit-mode-label');
const shortcutsLeft = document.querySelector('.shortcuts-left');
const dropdown = document.querySelector('.add-dropdown'); // Define the dropdown variable
// Add constants for limits
const MAX_TOTAL_SHORTCUTS = 12;
// List of all localStorage keys used by the application
const APP_LOCAL_STORAGE_KEYS = [
'dmx-shortcuts',
'dmx-notes',
'dmx-todos',
'dmx-background',
'dmx-blur',
'dmx-edit-mode',
'dmx-weather-settings',
'dmx-rss-feeds',
'dmx-sharp-borders',
'dmx-overlay-color',
'dmx-overlay-opacity',
'dmx-tab-visibility', // Added key for tab visibility settings
'dmx-weather-units', // Added key for weather units
'dmx-disable-shadow', // Added key for shadow setting
'dmx-window-bg-color', // Added key for window background color
'dmx-window-bg-opacity' // Added key for window background opacity
// Note: Favicon cache uses dynamic keys like 'dmx-favicon-cache-<domain>'
];
// Tab2 Settings variables
const tab2SettingsBtn = document.getElementById('tab2-settings-toggle');
const tab2SettingsForm = document.getElementById('tab2-settings-form');
const weatherApiKeyInput = document.getElementById('weather-api-key');
const weatherCityInput = document.getElementById('weather-city');
const useGeolocationBtn = document.getElementById('use-geolocation');
const saveTab2SettingsBtn = document.getElementById('save-tab2-settings');
const closeTab2SettingsBtn = document.getElementById('close-tab2-settings');
const settingsTabs = document.querySelectorAll('.settings-tab');
const settingsPanels = document.querySelectorAll('.settings-panel');
const addFeedBtn = document.getElementById('add-feed-btn');
const saveFeedBtn = document.getElementById('save-feed-btn');
const cancelFeedBtn = document.getElementById('cancel-feed-btn');
const feedNameInput = document.getElementById('feed-name');
const feedUrlInput = document.getElementById('feed-url');
const addFeedForm = document.querySelector('.add-feed-form');
const rssContainer = document.getElementById('rss-feeds-container');
let editingFeedIndex = null;
// Add flags to track if Tab2 data has been loaded
let weatherDataLoaded = false;
let rssDataLoaded = false;
// Variables for drag-and-drop functionality
let draggedItem = null;
let draggedItemIndex = null;
let originalPosition = null;
let dropTargetIndex = null;
let dragPlaceholder = null;
// Tab1 Settings variables
const tab1SettingsBtn = document.getElementById('tab1-settings-toggle');
const tab1SettingsForm = document.getElementById('tab1-settings-form');
const saveTab1SettingsBtn = document.getElementById('save-tab1-settings');
const closeTab1SettingsBtn = document.getElementById('close-tab1-settings');
const tab2Toggle = document.getElementById('tab2-toggle');
const tab3Toggle = document.getElementById('tab3-toggle');
const newTabToggle = document.getElementById('new-tab-toggle');
// Background settings variables
const bgConfigBtn = document.getElementById('bg-config-toggle');
const backgroundForm = document.getElementById('background-form');
const closeBackgroundBtn = document.getElementById('close-bg-settings');
const bgOptions = document.querySelectorAll('.bg-option');
const customBgUrl = document.getElementById('custom-bg-url');
const applyCustomBgBtn = document.getElementById('apply-custom-bg');
const blurSlider = document.getElementById('blur-slider');
const blurValue = document.getElementById('blur-value');
const resetBackgroundSettingsBtn = document.getElementById('resetBackgroundSettingsBtn');
const sharpBordersToggle = document.getElementById('sharp-borders-toggle'); // Added
const customBgColorInput = document.getElementById('custom-bg-color'); // Added
const applyCustomColorBtn = document.getElementById('apply-custom-color'); // Added
const backgroundOverlay = document.getElementById('background-overlay'); // Added for color overlay
const customColorOpacitySlider = document.getElementById('custom-color-opacity-slider'); // Added
const customColorOpacityValue = document.getElementById('custom-color-opacity-value'); // Added
const overlayOpacitySection = document.querySelector('.overlay-opacity-section'); // Added to show/hide slider
const disableShadowToggle = document.getElementById('disable-shadow-toggle'); // Added
const windowBgColorInput = document.getElementById('window-bg-color'); // Added
const windowBgOpacitySlider = document.getElementById('window-bg-opacity-slider'); // Added
const windowBgOpacityValue = document.getElementById('window-bg-opacity-value'); // Added
const applyWindowBgBtn = document.getElementById('apply-window-bg'); // Added: New apply button
// ========== FUNCTION DECLARATIONS ==========
// Function to switch tabs with slide animation
function switchTab(tabId) {
// Close dropdown menu when switching tabs
if (dropdown) {
dropdown.style.display = 'none';
}
// Close tab2 settings form when switching tabs
if (tab2SettingsForm) {
tab2SettingsForm.classList.remove('active');
}
// Also close tab1 settings form when switching tabs
if (tab1SettingsForm) {
tab1SettingsForm.classList.remove('active');
}
// Close tab3 settings form (main settings) when switching tabs
if (settingsForm) {
settingsForm.classList.remove('active');
}
// Check if the requested tab is hidden
const targetTab = document.getElementById(tabId);
if (targetTab && targetTab.classList.contains('tab-hidden')) {
// If it's hidden, find the next visible tab
const tabIndex = Array.from(tabContents).findIndex(content => content.id === tabId);
let nextVisibleTabId = null;
// Try to find next visible tab
for (let i = tabIndex + 1; i < tabContents.length; i++) {
if (!tabContents[i].classList.contains('tab-hidden')) {
nextVisibleTabId = tabContents[i].id;
break;
}
}
// If no next visible tab, try previous ones
if (!nextVisibleTabId) {
for (let i = tabIndex - 1; i >= 0; i--) {
if (!tabContents[i].classList.contains('tab-hidden')) {
nextVisibleTabId = tabContents[i].id;
break;
}
}
}
// Use the visible tab id instead, or stay on current if none found
if (nextVisibleTabId) {
tabId = nextVisibleTabId;
} else {
// All tabs are hidden? This shouldn't happen, but just in case
return;
}
}
const targetTabIndex = Array.from(tabContents).findIndex(content => content.id === tabId);
// Don't do anything if it's already the active tab
if (targetTabIndex === currentTabIndex) return;
// Determine direction of animation
const direction = targetTabIndex > currentTabIndex ? 'right' : 'left';
// Position all tabs based on their relation to the target tab
tabContents.forEach((tab, index) => {
if (index < targetTabIndex) {
tab.classList.remove('active', 'right');
tab.classList.add('left');
} else if (index > targetTabIndex) {
tab.classList.remove('active', 'left');
tab.classList.add('right');
} else {
tab.classList.remove('left', 'right');
tab.classList.add('active');
}
});
// Update icon active states
tabIcons.forEach(icon => icon.classList.remove('active'));
document.querySelector(`.tab-icon[data-tab="${tabId}"]`).classList.add('active');
// Show/hide add button based on active tab
if (tabId === 'tab1') {
addShortcutBtn.style.display = 'flex';
settingsBtn.style.display = 'none';
tab2SettingsBtn.style.display = 'none';
tab1SettingsBtn.style.display = 'flex'; // Show Tab1 settings button
} else if (tabId === 'tab2') {
addShortcutBtn.style.display = 'none';
settingsBtn.style.display = 'none';
tab2SettingsBtn.style.display = 'flex';
// Load Tab2 content only if it hasn't been loaded yet
if (!weatherDataLoaded) {
loadWeatherData();
}
if (!rssDataLoaded) {
loadRssData();
}
} else if (tabId === 'tab3') {
addShortcutBtn.style.display = 'none';
settingsBtn.style.display = 'flex';
tab2SettingsBtn.style.display = 'none';
} else {
addShortcutBtn.style.display = 'none';
settingsBtn.style.display = 'none';
tab2SettingsBtn.style.display = 'none';
}
// Update current tab index
currentTabIndex = targetTabIndex;
}
// Add click event listeners to tab icons
tabIcons.forEach(icon => {
icon.addEventListener('click', function() {
const tabId = this.getAttribute('data-tab');
switchTab(tabId);
// Update Tab1 settings button visibility
if (tabId === 'tab1') {
tab1SettingsBtn.style.display = 'flex';
} else {
tab1SettingsBtn.style.display = 'none';
}
});
});
// Prevent wheel events in todo and notes sections from triggering tab changes
todoSection.addEventListener('wheel', function(event) {
event.stopPropagation(); // Stops the event from bubbling up to main-window
});
notesSection.addEventListener('wheel', function(event) {
event.stopPropagation(); // Stops the event from bubbling up to main-window
});
// Similarly protect the shortcuts-left container
shortcutsLeft.addEventListener('wheel', function(event) {
event.stopPropagation();
});
// Prevent wheel events in news section from triggering tab changes
document.querySelector('.news-section').addEventListener('wheel', function(event) {
event.stopPropagation(); // Stops the event from bubbling up to main-window
});
// Also prevent wheel events specifically in the news articles container
document.querySelector('.news-articles-container').addEventListener('wheel', function(event) {
event.stopPropagation();
});
// Add debounce mechanism to prevent rapid tab switching
let wheelTimeout = null;
const wheelDebounceTime = 10; // milliseconds to wait between wheel events
// Helper function to find next visible tab
function findNextVisibleTab(startIndex) {
for (let i = startIndex + 1; i < tabContents.length; i++) {
if (!tabContents[i].classList.contains('tab-hidden')) {
return i;
}
}
return null; // No visible tab found
}
// Helper function to find previous visible tab
function findPrevVisibleTab(startIndex) {
for (let i = startIndex - 1; i >= 0; i--) {
if (!tabContents[i].classList.contains('tab-hidden')) {
return i;
}
}
return null; // No visible tab found
}
// Function to handle tab switching via wheel event with debounce
function handleWheelTabSwitch(event) {
event.preventDefault();
// Clear any existing timeout to reset the debounce timer
if (wheelTimeout) {
clearTimeout(wheelTimeout);
}
wheelTimeout = setTimeout(() => {
if (event.deltaY > 0) {
// Scroll down - go to next visible tab
const nextVisibleIndex = findNextVisibleTab(currentTabIndex);
if (nextVisibleIndex !== null) {
const tabId = tabContents[nextVisibleIndex].id;
switchTab(tabId);
}
} else {
// Scroll up - go to previous visible tab
const prevVisibleIndex = findPrevVisibleTab(currentTabIndex);
if (prevVisibleIndex !== null) {
const tabId = tabContents[prevVisibleIndex].id;
switchTab(tabId);
}
}
// Reset timeout variable when done
wheelTimeout = null;
}, wheelDebounceTime);
}
// Add wheel event listener to main window for scrolling through tabs
mainWindow.addEventListener('wheel', function(event) {
// Check if event is coming from todo or notes sections
if (event.target.closest('.todo-section') || event.target.closest('.notes-section')) {
return; // Don't switch tabs if scrolling in these sections
}
handleWheelTabSwitch(event);
});
// Add wheel event listeners to body and status bar for tab switching
body.addEventListener('wheel', function(event) {
// Only handle events that didn't originate in main window
if (!event.target.closest('#main-window')) {
handleWheelTabSwitch(event);
}
});
statusBar.addEventListener('wheel', function(event) {
handleWheelTabSwitch(event);
});
// Initialize first tab positioning
tabContents[0].classList.add('active');
for (let i = 1; i < tabContents.length; i++) {
tabContents[i].classList.add('right');
}
// Initial setup for button visibility
if (currentTabIndex === 0) {
addShortcutBtn.style.display = 'flex';
settingsBtn.style.display = 'none';
tab2SettingsBtn.style.display = 'none';
tab1SettingsBtn.style.display = 'flex'; // Show Tab1 settings button
} else if (currentTabIndex === 1) { // Tab2 is index 1
addShortcutBtn.style.display = 'none';
settingsBtn.style.display = 'none';
tab2SettingsBtn.style.display = 'flex';
} else if (currentTabIndex === 2) { // Tab3 is index 2
addShortcutBtn.style.display = 'none';
settingsBtn.style.display = 'flex';
tab2SettingsBtn.style.display = 'none';
} else {
addShortcutBtn.style.display = 'none';
settingsBtn.style.display = 'none';
tab2SettingsBtn.style.display = 'none';
}
// ===== SHORTCUTS MANAGEMENT =====
// Load shortcuts from local storage
function loadShortcuts() {
const shortcuts = JSON.parse(localStorage.getItem('dmx-shortcuts')) || [];
shortcutsGrid.innerHTML = '';
if (shortcuts.length > 0) {
// Organize shortcuts into rows of maximum 6 items
const maxItemsPerRow = 6;
let currentRow = null;
shortcuts.forEach((shortcut, index) => {
// Create new row if needed
if (index % maxItemsPerRow === 0) {
currentRow = document.createElement('div');
currentRow.className = 'row';
shortcutsGrid.appendChild(currentRow);
}
// Add shortcut to the current row instead of directly to grid
addShortcutToGrid(shortcut, index, currentRow);
});
} else {
// If no shortcuts exist, add a default help message with improved styling
const helpText = document.createElement('div');
helpText.innerHTML = "<i class='fas fa-lightbulb' style='font-size: 24px; margin-bottom: 15px;'></i><br>Click the + button to add your favorite websites <br> Found in bottom corner of the page";
/* helpText.style.color = "#787c99"; */
helpText.style.color = "#bb9af7";
helpText.style.padding = "20px 20px";
helpText.style.textAlign = "center";
helpText.style.gridColumn = "1 / -1"; // Span all columns
helpText.style.fontSize = "16px";
helpText.style.backgroundColor = "rgba(26, 27, 38, 0.8)";
helpText.style.top = "85%";
helpText.style.position = "relative";
/* helpText.style.borderRadius = "12px"; */
shortcutsGrid.appendChild(helpText);
}
// Always show shortcuts-left
shortcutsLeft.classList.remove('empty-container');
updateDropdownCounters();
handleWindowResize();
}
// Save shortcuts to local storage
function saveShortcuts(shortcuts) {
localStorage.setItem('dmx-shortcuts', JSON.stringify(shortcuts));
updateDropdownCounters();
}
// Add shortcut to grid
function addShortcutToGrid(shortcut, index, container) {
// Create container div for the shortcut
const shortcutElement = document.createElement('div');
shortcutElement.className = 'shortcut-item sharp';
shortcutElement.dataset.index = index;
// Add draggable attribute and drag events when in edit mode
shortcutElement.setAttribute('draggable', 'true');
// Add drag event listeners
shortcutElement.addEventListener('dragstart', handleDragStart);
shortcutElement.addEventListener('dragend', handleDragEnd);
shortcutElement.addEventListener('dragover', handleDragOver);
shortcutElement.addEventListener('dragenter', handleDragEnter);
shortcutElement.addEventListener('dragleave', handleDragLeave);
shortcutElement.addEventListener('drop', handleDrop);
// Create the actual link element
const linkElement = document.createElement('a');
linkElement.href = shortcut.url;
linkElement.className = 'shortcut-link';
// Check if shortcuts should open in new tab
const tabSettings = JSON.parse(localStorage.getItem('dmx-tab-visibility')) || {};
if (tabSettings.openInNewTab === true) { // Open-in-New Tab setting disabled by default
linkElement.target = '_blank';
linkElement.rel = 'noopener noreferrer'; // Security best practice
}
// Get favicon or use default icon
const iconElement = document.createElement('div');
iconElement.className = 'shortcut-icon';
// Create image with loading placeholder
const iconImg = document.createElement('img');
// Add a placeholder icon while loading
iconImg.src = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NCIgaGVpZ2h0PSI2NCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiM3YWEyZjciIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48Y2lyY2xlIGN4PSIxMiIgY3k9IjEyIiByPSIxMCI+PC9jaXJjbGU+PC9zdmc+';
// Get the favicon URL (check cache first, then Google service)
const domain = extractDomain(shortcut.url);
if (domain) {
shortcutElement.dataset.domain = domain; // Set data attribute here
getFaviconUrl(domain, (faviconUrl) => {
if (faviconUrl) {
iconImg.src = faviconUrl; // Set src directly to cached data URL or fetched URL
}
// If faviconUrl is null (error fetching/converting), the placeholder remains
});
}
iconElement.appendChild(iconImg);
const nameElement = document.createElement('div');
nameElement.className = 'shortcut-name sharp';
nameElement.textContent = shortcut.name;
// Add icon and name to the link
linkElement.appendChild(iconElement);
linkElement.appendChild(nameElement);
// Add link to the container
shortcutElement.appendChild(linkElement);
// Add edit button (separate from the link)
const editBtn = document.createElement('div');
editBtn.className = 'edit-shortcut';
editBtn.innerHTML = '<i class="fas fa-edit"></i>';
editBtn.addEventListener('click', (e) => {
e.stopPropagation();
configureShortcut(index);
});
shortcutElement.appendChild(editBtn);
// Add the element to the specified container instead of shortcutsGrid
container.appendChild(shortcutElement);
}
// Helper function to extract domain from URL
function extractDomain(url) {
try {
const urlObject = new URL(url);
return urlObject.hostname;
} catch (e) {
return null;
}
}
// Helper function to get favicon URL for a website - with localStorage caching
function getFaviconUrl(domain, callback) {
if (!domain) {
console.error("[Favicon] getFaviconUrl called with no domain."); // Added log
callback('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NCIgaGVpZ2h0PSI2NCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiM3YWEyZjciIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48Y2lyY2xlIGN4PSIxMiIgY3k9IjEyIiByPSIxMCI+PC9jaXJjbGU+PC9zdmc+'); // Default icon on error
return;
}
const cacheKey = `dmx-favicon-cache-${domain}`;
const cachedFavicon = localStorage.getItem(cacheKey);
if (cachedFavicon) {
console.log(`[Favicon] Cache hit for ${domain}`); // Added log
callback(cachedFavicon);
return;
}
console.log(`[Favicon] Cache miss for ${domain}. Fetching via proxy...`); // Updated log
// Use allorigins proxy to bypass CORS
const googleFaviconUrl = `https://www.google.com/s2/favicons?domain=${domain}&sz=64`;
// Use the /raw endpoint which might return the image directly
const proxyUrl = `https://api.allorigins.win/raw?url=${encodeURIComponent(googleFaviconUrl)}`;
console.log(`[Favicon] Requesting proxied URL: ${proxyUrl}`); // Added log
fetch(proxyUrl) // Fetch via the proxy
.then(response => {
if (!response.ok) {
// Log the status text from the proxy response
throw new Error(`[Favicon] Proxy response was not ok for ${domain}: ${response.status} ${response.statusText}`);
}
// Check content type - might be useful for debugging
console.log(`[Favicon] Proxy response Content-Type for ${domain}: ${response.headers.get('Content-Type')}`);
return response.blob();
})
.then(blob => {
// Check if the blob is valid image data (basic check)
if (!blob || blob.size === 0 || !blob.type.startsWith('image/')) {
console.warn(`[Favicon] Received invalid blob for ${domain}. Type: ${blob?.type}, Size: ${blob?.size}`);
throw new Error(`Invalid blob received for ${domain}`);
}
// Use FileReader to convert blob to base64 data URL
const reader = new FileReader();
reader.onloadend = () => {
const base64data = reader.result;
console.log(`[Favicon] Fetched and caching for ${domain}`); // Added log
try {
// Check if base64 data looks reasonable before saving
if (base64data && base64data.startsWith('data:image')) {
localStorage.setItem(cacheKey, base64data);
callback(base64data);
} else {
console.warn(`[Favicon] Invalid base64 data received for ${domain}, not caching.`);
throw new Error(`Invalid base64 data received for ${domain}`);
}
} catch (e) {
console.error(`[Favicon] Error saving to localStorage for ${domain}:`, e);
// Fallback to default icon if storage fails or data is invalid
callback('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NCIgaGVpZ2h0PSI2NCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiM3YWEyZjciIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48Y2lyY2xlIGN4PSIxMiIgY3k9IjEyIiByPSIxMCI+PC9jaXJjbGU+PC9zdmc+');
}
};
reader.onerror = (error) => { // Handle FileReader errors
console.error(`[Favicon] FileReader error for ${domain}:`, error);
callback('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NCIgaGVpZ2h0PSI2NCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiM3YWEyZjciIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48Y2lyY2xlIGN4PSIxMiIgY3k9IjEyIiByPSIxMCI+PC9jaXJjbGU+PC9zdmc+');
};
reader.readAsDataURL(blob);
})
.catch(error => {
console.error(`[Favicon] Error fetching proxied favicon for ${domain}:`, error);
// Fallback to default icon on fetch error
callback('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI2NCIgaGVpZ2h0PSI2NCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiM3YWEyZjciIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48Y2lyY2xlIGN4PSIxMiIgY3k9IjEyIiByPSIxMCI+PC9jaXJjbGU+PC9zdmc+');
});
}
// Configure an existing shortcut
function configureShortcut(index) {
const shortcuts = JSON.parse(localStorage.getItem('dmx-shortcuts')) || [];
const shortcut = shortcuts[index];
// Set form inputs to current values
shortcutNameInput.value = shortcut.name;
shortcutUrlInput.value = shortcut.url;
// Hide category selection section if it exists
const categorySelect = document.querySelector('.form-group:has(#shortcut-category)');
if (categorySelect) {
categorySelect.style.display = 'none';
}
// Add delete option if it doesn't exist yet
let deleteOption = document.querySelector('.delete-shortcut-option');
if (!deleteOption) {
deleteOption = document.createElement('div');
deleteOption.className = 'delete-shortcut-option';
const deleteBtn = document.createElement('button');
deleteBtn.className = 'delete-btn';
deleteBtn.textContent = 'Delete Shortcut';
deleteBtn.id = 'delete-shortcut-btn';
deleteOption.appendChild(deleteBtn);
shortcutForm.insertBefore(deleteOption, document.querySelector('.form-buttons'));
// Add event listener to delete button
document.getElementById('delete-shortcut-btn').addEventListener('click', () => {
if (editingShortcutIndex !== null) {
deleteShortcut(editingShortcutIndex);
shortcutForm.classList.remove('active');
editingShortcutIndex = null;
}
});
}
// Show delete option
deleteOption.style.display = 'block';
// Update form title
const formTitle = shortcutForm.querySelector('h3');
formTitle.textContent = 'Edit Shortcut';
// Show the form
shortcutForm.classList.add('active');
// Set editing index
editingShortcutIndex = index;
}
// Delete shortcut
function deleteShortcut(index) {
const shortcuts = JSON.parse(localStorage.getItem('dmx-shortcuts')) || [];
shortcuts.splice(index, 1);
saveShortcuts(shortcuts);
loadShortcuts();
// Also close the form if it was open for editing the deleted shortcut
if (editingShortcutIndex === index) {
shortcutForm.classList.remove('active');
editingShortcutIndex = null;
}
}
// Toggle shortcut form for adding new shortcut
addWebsiteOption.addEventListener('click', (e) => {
e.stopPropagation(); // Prevent event bubbling
// Check if total shortcut limit has been reached
const shortcuts = JSON.parse(localStorage.getItem('dmx-shortcuts')) || [];
if (shortcuts.length >= MAX_TOTAL_SHORTCUTS) {
alert(`You can only create a maximum of ${MAX_TOTAL_SHORTCUTS} shortcuts total.`);
return;
}
// Reset form for adding new shortcut
shortcutForm.querySelector('h3').textContent = 'Add New Shortcut';
shortcutNameInput.value = '';
shortcutUrlInput.value = '';
// Hide category selection if it exists
const categorySelect = document.querySelector('.form-group:has(#shortcut-category)');
if (categorySelect) {
categorySelect.style.display = 'none';
}
editingShortcutIndex = null;
// Hide delete option if it exists
const deleteOption = document.querySelector('.delete-shortcut-option');
if (deleteOption) {
deleteOption.style.display = 'none';
}
shortcutForm.classList.add('active');
});
// Cancel shortcut form
cancelShortcutBtn.addEventListener('click', () => {
shortcutForm.classList.remove('active');
editingShortcutIndex = null;
});
// Save shortcut (new or edited)
saveShortcutBtn.addEventListener('click', () => {
const name = shortcutNameInput.value.trim();
let url = shortcutUrlInput.value.trim();
if (!name || !url) {
alert('Please fill in all fields');
return;
}
// Add https:// if not present
if (!/^https?:\/\//i.test(url)) {
url = 'https://' + url;
}
const shortcuts = JSON.parse(localStorage.getItem('dmx-shortcuts')) || [];
if (editingShortcutIndex !== null) {
// Update existing shortcut
shortcuts[editingShortcutIndex] = { name, url };
} else {
// Add new shortcut
shortcuts.push({ name, url });
}
saveShortcuts(shortcuts);
loadShortcuts();
shortcutForm.classList.remove('active');
editingShortcutIndex = null;
});
// ===== NOTES FUNCTIONALITY =====
// Load saved notes from localStorage
function loadNotes() {
const savedNotes = localStorage.getItem('dmx-notes') || '';
notesArea.value = savedNotes;
}
// Save notes to localStorage when changed
notesArea.addEventListener('input', () => {
localStorage.setItem('dmx-notes', notesArea.value);
});
// ===== TODO LIST FUNCTIONALITY =====
// Load todo items from localStorage
function loadTodoItems() {
const todos = JSON.parse(localStorage.getItem('dmx-todos')) || [];
todoList.innerHTML = '';
todos.forEach((todo, index) => {
addTodoToList(todo, index);
});
}
// Save todo items to localStorage
function saveTodoItems(todos) {
localStorage.setItem('dmx-todos', JSON.stringify(todos));
}
// Add todo item to the list
function addTodoToList(todo, index) {
const todoItem = document.createElement('li');
todoItem.className = 'todo-item';
if (todo.completed) {
todoItem.classList.add('todo-completed');
}
todoItem.dataset.index = index;
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.className = 'todo-checkbox';
checkbox.checked = todo.completed;
checkbox.addEventListener('change', () => toggleTodoComplete(index));
const todoText = document.createElement('span');
todoText.className = 'todo-text';
todoText.textContent = todo.text;
const deleteBtn = document.createElement('span');
deleteBtn.className = 'todo-delete';
deleteBtn.innerHTML = '<i class="fas fa-times"></i>';
deleteBtn.addEventListener('click', () => deleteTodoItem(index));
todoItem.appendChild(checkbox);
todoItem.appendChild(todoText);
todoItem.appendChild(deleteBtn);
todoList.appendChild(todoItem);
}
// Add new todo item
addTodoBtn.addEventListener('click', () => {
const todoText = todoInput.value.trim();
if (todoText) {
const todos = JSON.parse(localStorage.getItem('dmx-todos')) || [];
const newTodo = {
text: todoText,
completed: false
};
todos.push(newTodo);
saveTodoItems(todos);
loadTodoItems();
todoInput.value = '';
}
});
// Allow adding todo with Enter key
todoInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
addTodoBtn.click();
}
});
// Toggle todo completed state
function toggleTodoComplete(index) {
const todos = JSON.parse(localStorage.getItem('dmx-todos')) || [];
todos[index].completed = !todos[index].completed;
saveTodoItems(todos);
loadTodoItems();
}
// Delete todo item
function deleteTodoItem(index) {
const todos = JSON.parse(localStorage.getItem('dmx-todos')) || [];
todos.splice(index, 1);
saveTodoItems(todos);
loadTodoItems();
}
// ===== EXPORT/IMPORT FUNCTIONALITY =====
// Toggle settings form
settingsBtn.addEventListener('click', () => {
console.log('Settings button clicked'); // Log click
if (settingsForm) {
console.log('Settings form found. Current classes before toggle:', settingsForm.className);
settingsForm.classList.toggle('active');
console.log('Settings form classes after toggle:', settingsForm.className);
// Ensure notification is reset when opening
if (importNotification) importNotification.className = 'import-notification';
} else {
console.error('Settings form element (#settings-form) not found!');
}
});
// Close settings form
closeSettingsBtn.addEventListener('click', () => {
settingsForm.classList.remove('active');
if (importNotification) importNotification.className = 'import-notification';
});
// Update export to include only current data structures
exportBtn.addEventListener('click', () => {
const shortcuts = JSON.parse(localStorage.getItem('dmx-shortcuts')) || [];
const notes = localStorage.getItem('dmx-notes') || '';
const todos = JSON.parse(localStorage.getItem('dmx-todos')) || [];
const weatherSettings = JSON.parse(localStorage.getItem('dmx-weather-settings')) || {};
const rssFeeds = JSON.parse(localStorage.getItem('dmx-rss-feeds')) || [];
const background = localStorage.getItem('dmx-background');
const blur = localStorage.getItem('dmx-blur');
const sharpBorders = localStorage.getItem('dmx-sharp-borders');
const overlayColor = localStorage.getItem('dmx-overlay-color');
const overlayOpacity = localStorage.getItem('dmx-overlay-opacity');
const tabVisibility = JSON.parse(localStorage.getItem('dmx-tab-visibility')) || {};
const disableShadow = localStorage.getItem('dmx-disable-shadow'); // Added
const windowBgColor = localStorage.getItem('dmx-window-bg-color'); // Added
const windowBgOpacity = localStorage.getItem('dmx-window-bg-opacity'); // Added
const settings = {
shortcuts: shortcuts,
notes: notes,
todos: todos,
weatherSettings: weatherSettings,
rssFeeds: rssFeeds,
background: background, // Include background settings
blur: blur,
sharpBorders: sharpBorders,
overlayColor: overlayColor,
overlayOpacity: overlayOpacity,
tabVisibility: tabVisibility,
disableShadow: disableShadow, // Added
windowBgColor: windowBgColor, // Added
windowBgOpacity: windowBgOpacity // Added
// Favicon cache is NOT exported intentionally, it will rebuild
};
const dataStr = JSON.stringify(settings, null, 2);
const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
const exportFileDefaultName = 'dmx-tab-settings.json';
const linkElement = document.createElement('a');
linkElement.setAttribute('href', dataUri);
linkElement.setAttribute('download', exportFileDefaultName);
linkElement.click();
});
// Update import to handle expanded data structure
importBtn.addEventListener('click', () => {
const file = importFile.files[0];
if (!file) {
showImportNotification('Please select a file to import', 'error');
return;
}
const reader = new FileReader();
reader.onload = function(e) {
try {
const importedSettings = JSON.parse(e.target.result);
// Clear existing favicon cache before importing other settings
clearFaviconCache();
// Import shortcuts
if (importedSettings.shortcuts && Array.isArray(importedSettings.shortcuts)) {
// Basic validation for shortcut structure
const validShortcuts = importedSettings.shortcuts.filter(s => s && typeof s.name === 'string' && typeof s.url === 'string');
localStorage.setItem('dmx-shortcuts', JSON.stringify(validShortcuts));
loadShortcuts(); // Reload UI
} else {
localStorage.removeItem('dmx-shortcuts'); // Clear if invalid/missing
loadShortcuts();
}
// Import notes
if (importedSettings.notes) {
localStorage.setItem('dmx-notes', importedSettings.notes);
}
// Import todos
if (importedSettings.todos) {
localStorage.setItem('dmx-todos', JSON.stringify(importedSettings.todos));
}