-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanager.js
More file actions
1036 lines (893 loc) · 36.6 KB
/
manager.js
File metadata and controls
1036 lines (893 loc) · 36.6 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
// Manager page script for Window & Tab Manager - Masonry Layout
// This is a simplified version without theme switching redirects
class WindowManager {
constructor() {
this.windows = [];
this.dragData = null;
this.viewMode = 'masonry'; // 'masonry', 'list', or 'full-masonry'
this.compactMode = 'ultra'; // 'normal', 'compact', 'ultra'
this.groupByDomain = false; // Group tabs by domain
this.selectedTabs = new Set(); // Track selected tab IDs
this.initializeElements();
this.init(); // Initialize async operations
}
async init() {
await this.loadPreferences(); // Load saved preferences
this.applyPreferences(); // Apply the loaded preferences to UI
this.updateContainerClass(); // Apply initial CSS classes
this.setupEventListeners();
this.loadWindows();
}
async loadPreferences() {
try {
const result = await chrome.storage.local.get(['viewMode', 'compactMode', 'groupByDomain']);
if (result.viewMode) {
this.viewMode = result.viewMode;
}
if (result.compactMode) {
this.compactMode = result.compactMode;
}
if (result.groupByDomain !== undefined) {
this.groupByDomain = result.groupByDomain;
}
} catch (error) {
console.error('Failed to load preferences:', error);
}
}
async savePreferences() {
try {
await chrome.storage.local.set({
viewMode: this.viewMode,
compactMode: this.compactMode,
groupByDomain: this.groupByDomain
});
} catch (error) {
console.error('Failed to save preferences:', error);
}
}
applyPreferences() {
// Apply view mode
document.querySelectorAll('.layout-btn').forEach(btn => {
btn.classList.remove('active');
});
switch(this.viewMode) {
case 'masonry':
this.elements.masonryLayoutBtn?.classList.add('active');
break;
case 'list':
this.elements.listLayoutBtn?.classList.add('active');
break;
case 'full-masonry':
this.elements.fullMasonryLayoutBtn?.classList.add('active');
break;
}
// Apply view size
document.querySelectorAll('.size-btn').forEach(btn => {
btn.classList.remove('active');
});
switch(this.compactMode) {
case 'normal':
this.elements.normalSizeBtn?.classList.add('active');
break;
case 'compact':
this.elements.compactSizeBtn?.classList.add('active');
break;
case 'ultra':
this.elements.ultraSizeBtn?.classList.add('active');
break;
}
// Apply group by domain
if (this.groupByDomain) {
this.elements.groupByDomainBtn?.classList.add('active');
this.elements.groupByDomainBtn.innerHTML = `
<span class="icon">🌐</span>
Ungroup
`;
}
}
initializeElements() {
this.elements = {
loading: document.getElementById('loading'),
error: document.getElementById('error'),
content: document.getElementById('content'),
errorMessage: document.querySelector('.error-message'),
retryBtn: document.getElementById('retryBtn'),
refreshBtn: document.getElementById('refreshBtn'),
newWindowBtn: document.getElementById('newWindowBtn'),
windowsContainer: document.getElementById('windowsContainer'),
windowCount: document.getElementById('windowCount'),
tabCount: document.getElementById('tabCount'),
viewModeBtn: document.getElementById('viewModeBtn'),
compactModeBtn: document.getElementById('compactModeBtn'),
normalSizeBtn: document.getElementById('normalSizeBtn'),
compactSizeBtn: document.getElementById('compactSizeBtn'),
ultraSizeBtn: document.getElementById('ultraSizeBtn'),
masonryLayoutBtn: document.getElementById('masonryLayoutBtn'),
listLayoutBtn: document.getElementById('listLayoutBtn'),
fullMasonryLayoutBtn: document.getElementById('fullMasonryLayoutBtn'),
sendToNewWindowBtn: document.getElementById('sendToNewWindowBtn'),
searchBar: document.getElementById('search-bar'),
groupByDomainBtn: document.getElementById('groupByDomainBtn'),
dropZone: document.getElementById('dropZone'),
toast: document.getElementById('toast'),
confirmModal: document.getElementById('confirmModal'),
modalCancel: document.getElementById('modalCancel'),
modalConfirm: document.getElementById('modalConfirm')
};
}
setupEventListeners() {
// Header buttons
this.elements.retryBtn.addEventListener('click', () => this.loadWindows());
this.elements.refreshBtn.addEventListener('click', () => this.loadWindows());
this.elements.newWindowBtn.addEventListener('click', () => this.createNewWindow());
if (this.elements.compactModeBtn) {
this.elements.compactModeBtn.addEventListener('click', () => this.toggleCompactMode());
}
this.elements.groupByDomainBtn.addEventListener('click', () => this.toggleGroupByDomain());
this.elements.sendToNewWindowBtn.addEventListener('click', () => this.sendSelectedToNewWindow());
// Size button listeners
this.elements.normalSizeBtn.addEventListener('click', () => this.setViewSize('normal'));
this.elements.compactSizeBtn.addEventListener('click', () => this.setViewSize('compact'));
this.elements.ultraSizeBtn.addEventListener('click', () => this.setViewSize('ultra'));
// Layout button listeners
this.elements.masonryLayoutBtn.addEventListener('click', () => this.setViewLayout('masonry'));
this.elements.listLayoutBtn.addEventListener('click', () => this.setViewLayout('list'));
this.elements.fullMasonryLayoutBtn.addEventListener('click', () => this.setViewLayout('full-masonry'));
// Search bar
if (this.elements.searchBar) {
this.elements.searchBar.addEventListener('input', this.filterTabs.bind(this));
}
// Modal
this.elements.modalCancel.addEventListener('click', () => this.hideModal());
// Listen for background updates
chrome.runtime.onMessage.addListener((message) => {
if (message.action === 'windowsUpdated') {
this.loadWindows(true); // Preserve scroll position
} else if (message.action === 'windowsUpdatedImmediate') {
// Handle immediate updates without full refresh
this.handleImmediateUpdate(message.eventType, message.data);
}
});
// Global drag and drop events
document.addEventListener('dragover', (e) => e.preventDefault());
document.addEventListener('drop', (e) => e.preventDefault());
// Drop zone events
this.elements.dropZone.addEventListener('dragover', (e) => {
e.preventDefault();
this.elements.dropZone.classList.add('drag-over');
});
this.elements.dropZone.addEventListener('dragleave', (e) => {
e.preventDefault();
this.elements.dropZone.classList.remove('drag-over');
});
this.elements.dropZone.addEventListener('drop', (e) => {
e.preventDefault();
this.elements.dropZone.classList.remove('drag-over');
this.handleDropToNewWindow();
});
}
async loadWindows(preserveScrollPosition = false) {
try {
// Save scroll position if requested
let scrollPosition = 0;
if (preserveScrollPosition) {
scrollPosition = window.pageYOffset || document.documentElement.scrollTop;
} else {
this.showLoading();
}
const response = await this.sendMessage({ action: 'getAllWindows' });
if (response.error) {
throw new Error(response.error);
}
this.windows = response.windows || [];
this.renderWindows();
this.updateStats();
this.showContent();
// Restore scroll position if requested
if (preserveScrollPosition && scrollPosition > 0) {
// Use requestAnimationFrame to ensure DOM is updated
requestAnimationFrame(() => {
window.scrollTo(0, scrollPosition);
});
}
} catch (error) {
console.error('Failed to load windows:', error);
this.showError(error.message);
}
}
// Method to handle search input and filter tabs
filterTabs() {
const searchTerm = document.getElementById('search-bar').value.toLowerCase();
// Filter through all windows and tabs
const filteredWindows = this.windows.map(window => {
const filteredTabs = window.tabs.filter(tab => tab.url.toLowerCase().includes(searchTerm));
return { ...window, tabs: filteredTabs };
}).filter(window => window.tabs.length > 0);
// Re-render the window list with filtered results
this.renderWindows(filteredWindows);
}
renderWindows(windows = this.windows) {
this.elements.windowsContainer.innerHTML = '';
if (windows.length === 0) {
this.elements.windowsContainer.innerHTML = `
<div class="empty-state">
<h2>No windows found</h2>
</div>
`;
return;
}
windows.forEach((window, index) => {
const windowElement = this.createWindowElement(window, index);
this.elements.windowsContainer.appendChild(windowElement);
});
// Dispatch custom event to trigger masonry layout
document.dispatchEvent(new CustomEvent('windowsRendered'));
}
createWindowElement(window, index) {
const windowDiv = document.createElement('div');
windowDiv.className = `window-card ${window.focused ? 'focused' : ''}`;
windowDiv.dataset.windowId = window.id;
const windowTitle = this.getWindowTitle(window, index);
let tabsContent;
if (window.tabs.length === 0) {
tabsContent = '<div class="empty-tabs">No tabs</div>';
} else if (this.groupByDomain) {
// Group tabs by domain
tabsContent = this.createGroupedTabsHTML(window.tabs);
} else {
// Normal tab display
tabsContent = window.tabs.map(tab => this.createTabHTML(tab)).join('');
}
windowDiv.innerHTML = `
<div class="window-header">
<span class="window-title-count">${window.tabs.length}</span>
<span class="window-title">${this.escapeHtml(windowTitle)}</span>
<div class="window-actions">
<button class="window-btn focus-window-btn" data-window-id="${window.id}" title="Focus Window">
Focus
</button>
<button class="window-btn close-window-btn" data-window-id="${window.id}" title="Close Window">
Close
</button>
</div>
</div>
<div class="tabs-container ${window.tabs.length === 0 ? 'empty' : ''} ${this.groupByDomain ? 'grouped' : ''}">
${tabsContent}
</div>
`;
this.setupWindowEventListeners(windowDiv);
return windowDiv;
}
createGroupedTabsHTML(tabs) {
// Group tabs by domain
const groups = {};
tabs.forEach(tab => {
const domain = this.getDomainFromUrl(tab.url);
if (!groups[domain]) {
groups[domain] = [];
}
groups[domain].push(tab);
});
// Sort domains alphabetically
const sortedDomains = Object.keys(groups).sort();
// Create HTML for grouped tabs
let html = '';
sortedDomains.forEach(domain => {
const domainTabs = groups[domain];
const tabIds = domainTabs.map(tab => tab.id).join(',');
html += `
<div class="domain-group">
<div class="domain-header">
<div class="domain-info">
<span class="domain-name">${this.escapeHtml(domain)}</span>
<span class="domain-count">(${domainTabs.length})</span>
</div>
<button class="domain-action-btn move-domain-btn"
data-domain="${this.escapeHtml(domain)}"
data-tab-ids="${tabIds}"
title="Move all ${this.escapeHtml(domain)} tabs to new window">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<!-- Back tab -->
<path d="M3 8 L3 18 C3 19.1 3.9 20 5 20 L15 20 C16.1 20 17 19.1 17 18 L17 12" stroke-opacity="0.6"/>
<path d="M3 8 L8 8 C8.5 8 9 7.5 9 7 L9 6 C9 5.5 9.5 5 10 5 L15 5 C15.5 5 16 5.5 16 6 L16 7 C16 7.5 16.5 8 17 8 L17 8" stroke-opacity="0.6"/>
<!-- Front tab -->
<path d="M7 4 L7 14 C7 15.1 7.9 16 9 16 L19 16 C20.1 16 21 15.1 21 14 L21 8"/>
<path d="M7 4 L12 4 C12.5 4 13 3.5 13 3 L13 2 C13 1.5 13.5 1 14 1 L19 1 C19.5 1 20 1.5 20 2 L20 3 C20 3.5 20.5 4 21 4 L21 4"/>
<!-- Plus symbol to indicate duplication -->
<circle cx="19" cy="12" r="3" fill="currentColor" stroke="none"/>
<path d="M18 12 L20 12 M19 11 L19 13" stroke="white" stroke-width="1.5"/>
</svg>
</button>
<button class="domain-action-btn close-domain-btn"
data-domain="${this.escapeHtml(domain)}"
data-tab-ids="${tabIds}"
title="Close all ${this.escapeHtml(domain)} tabs">
<span class="icon">✕</span>
</button>
</div>
<div class="domain-tabs">
${domainTabs.map(tab => this.createTabHTML(tab)).join('')}
</div>
</div>
`;
});
return html;
}
getDomainFromUrl(url) {
try {
const urlObj = new URL(url);
return urlObj.hostname || 'Unknown';
} catch {
// Handle special Chrome URLs
if (url.startsWith('chrome://')) {
return 'Chrome Pages';
} else if (url.startsWith('chrome-extension://')) {
return 'Extensions';
} else if (url === 'about:blank' || !url) {
return 'Blank Pages';
}
return 'Unknown';
}
}
createTabHTML(tab) {
// Handle favicon URL with proper fallbacks
let faviconUrl = tab.favIconUrl;
// Determine the best favicon approach based on URL type
if (tab.url.startsWith('chrome-extension://')) {
// For extension pages, use a generic extension icon
faviconUrl = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24"><path fill="currentColor" d="M20.5,11H19V7c0-1.1-0.9-2-2-2h-4V3.5C13,2.12,11.88,1,10.5,1S8,2.12,8,3.5V5H4C2.9,5,2,5.9,2,7v3.8h1.5c1.4,0,2.5,1.1,2.5,2.5S4.9,16,3.5,16H2V20c0,1.1,0.9,2,2,2h3.8v-1.5c0-1.4,1.1-2.5,2.5-2.5s2.5,1.1,2.5,2.5V22H17c1.1,0,2-0.9,2-2v-4h1.5c1.38,0,2.5-1.12,2.5-2.5S21.88,11,20.5,11z"/></svg>';
} else if (tab.url.startsWith('file://')) {
// For local files, use a file icon
faviconUrl = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24"><path fill="currentColor" d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"/></svg>';
} else if (tab.url.startsWith('chrome://')) {
// For chrome pages, use a chrome icon
faviconUrl = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24"><path fill="currentColor" d="M12,20L15.46,14H8.54L12,20M12,4A8,8 0 0,1 20,12C20,12.34 19.97,12.67 19.92,13H16.64C17.21,12.17 17.21,11.83 16.64,11H19.92C19.97,11.33 20,11.66 20,12A8,8 0 0,1 12,20V4M4,12A8,8 0 0,1 12,4V20A8,8 0 0,1 4,12Z"/></svg>';
} else if (!faviconUrl && tab.url.startsWith('http')) {
// For web URLs without favicons, try chrome://favicon
faviconUrl = `chrome://favicon/size/16@2x/${encodeURIComponent(tab.url)}`;
} else if (!faviconUrl) {
// Generic fallback for any other case
faviconUrl = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24"><path fill="currentColor" d="M16.36,14C16.44,13.34 16.5,12.68 16.5,12C16.5,11.32 16.44,10.66 16.36,10H19.74C19.9,10.64 20,11.31 20,12C20,12.69 19.9,13.36 19.74,14M14.59,19.56C15.19,18.45 15.65,17.25 15.97,16H18.92C17.96,17.65 16.43,18.93 14.59,19.56M14.34,14H9.66C9.56,13.34 9.5,12.68 9.5,12C9.5,11.32 9.56,10.65 9.66,10H14.34C14.43,10.65 14.5,11.32 14.5,12C14.5,12.68 14.43,13.34 14.34,14M12,19.96C11.17,18.76 10.5,17.43 10.09,16H13.91C13.5,17.43 12.83,18.76 12,19.96M8,8H5.08C6.03,6.34 7.57,5.06 9.4,4.44C8.8,5.55 8.35,6.75 8,8M5.08,16H8C8.35,17.25 8.8,18.45 9.4,19.56C7.57,18.93 6.03,17.65 5.08,16M4.26,14C4.1,13.36 4,12.69 4,12C4,11.31 4.1,10.64 4.26,10H7.64C7.56,10.66 7.5,11.32 7.5,12C7.5,12.68 7.56,13.34 7.64,14M12,4.03C12.83,5.23 13.5,6.57 13.91,8H10.09C10.5,6.57 11.17,5.23 12,4.03M18.92,8H15.97C15.65,6.75 15.19,5.55 14.59,4.44C16.43,5.07 17.96,6.34 18.92,8Z"/></svg>';
}
const tabTitle = tab.title || 'Untitled';
const displayUrl = this.getDisplayUrl(tab.url);
const indicators = [];
if (tab.audible) indicators.push('<span class="tab-indicator tab-audible" title="Playing audio">🔊</span>');
if (tab.mutedInfo?.muted) indicators.push('<span class="tab-indicator tab-muted" title="Muted">🔇</span>');
if (tab.pinned) indicators.push('<span class="tab-indicator tab-pinned" title="Pinned">📌</span>');
return `
<div class="tab-item ${tab.active ? 'active' : ''} ${tab.pinned ? 'pinned' : ''}${this.selectedTabs.has(tab.id) ? ' selected' : ''}"
data-tab-id="${tab.id}"
data-window-id="${tab.windowId}"
draggable="true">
<input type="checkbox" class="tab-checkbox" data-tab-id="${tab.id}" ${this.selectedTabs.has(tab.id) ? 'checked' : ''}>
<img class="tab-favicon" src="${this.escapeHtml(faviconUrl)}" alt="">
<div class="tab-info">
<div class="tab-title">${this.escapeHtml(tabTitle)}</div>
<div class="tab-url">${this.escapeHtml(displayUrl)}</div>
</div>
<div class="tab-indicators">
${indicators.join('')}
</div>
<div class="tab-actions">
<button class="tab-btn focus-tab-btn" data-tab-id="${tab.id}" title="Focus Tab">
👁
</button>
<button class="tab-btn close-tab-btn" data-tab-id="${tab.id}" title="Close Tab">
✕
</button>
</div>
</div>
`;
}
setupWindowEventListeners(windowElement) {
const windowId = parseInt(windowElement.dataset.windowId);
// Window actions
const focusBtn = windowElement.querySelector('.focus-window-btn');
const closeBtn = windowElement.querySelector('.close-window-btn');
focusBtn.addEventListener('click', (e) => {
e.stopPropagation();
this.focusWindow(windowId);
});
closeBtn.addEventListener('click', (e) => {
e.stopPropagation();
this.confirmCloseWindow(windowId);
});
// Tab actions and drag/drop
const tabItems = windowElement.querySelectorAll('.tab-item');
const tabsContainer = windowElement.querySelector('.tabs-container');
tabItems.forEach(tabItem => {
this.setupTabEventListeners(tabItem);
// Handle favicon errors with better fallback
const favicon = tabItem.querySelector('.tab-favicon');
if (favicon) {
favicon.addEventListener('error', () => {
// Try a different approach based on the original URL
const tabId = parseInt(tabItem.dataset.tabId);
const tab = this.findTabById(tabId);
if (tab && favicon.src.includes('chrome://favicon')) {
// If chrome://favicon failed, try a generic web icon
favicon.src = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24"><path fill="currentColor" d="M16.36,14C16.44,13.34 16.5,12.68 16.5,12C16.5,11.32 16.44,10.66 16.36,10H19.74C19.9,10.64 20,11.31 20,12C20,12.69 19.9,13.36 19.74,14M14.59,19.56C15.19,18.45 15.65,17.25 15.97,16H18.92C17.96,17.65 16.43,18.93 14.59,19.56M14.34,14H9.66C9.56,13.34 9.5,12.68 9.5,12C9.5,11.32 9.56,10.65 9.66,10H14.34C14.43,10.65 14.5,11.32 14.5,12C14.5,12.68 14.43,13.34 14.34,14M12,19.96C11.17,18.76 10.5,17.43 10.09,16H13.91C13.5,17.43 12.83,18.76 12,19.96M8,8H5.08C6.03,6.34 7.57,5.06 9.4,4.44C8.8,5.55 8.35,6.75 8,8M5.08,16H8C8.35,17.25 8.8,18.45 9.4,19.56C7.57,18.93 6.03,17.65 5.08,16M4.26,14C4.1,13.36 4,12.69 4,12C4,11.31 4.1,10.64 4.26,10H7.64C7.56,10.66 7.5,11.32 7.5,12C7.5,12.68 7.56,13.34 7.64,14M12,4.03C12.83,5.23 13.5,6.57 13.91,8H10.09C10.5,6.57 11.17,5.23 12,4.03M18.92,8H15.97C15.65,6.75 15.19,5.55 14.59,4.44C16.43,5.07 17.96,6.34 18.92,8Z"/></svg>';
} else {
// Show a blank placeholder instead of hiding the favicon completely
favicon.src = 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><rect width="16" height="16" fill="transparent" stroke="%23ccc" stroke-width="1" rx="2"/></svg>';
favicon.style.display = 'inline';
}
});
}
});
// Tab checkbox event listeners
const tabCheckboxes = windowElement.querySelectorAll('.tab-checkbox');
tabCheckboxes.forEach(checkbox => {
checkbox.addEventListener('change', (e) => {
e.stopPropagation();
this.handleTabSelection(parseInt(checkbox.dataset.tabId), checkbox.checked);
});
});
// Domain action button listeners
const moveDomainBtns = windowElement.querySelectorAll('.move-domain-btn');
moveDomainBtns.forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const domain = btn.dataset.domain;
const tabIds = btn.dataset.tabIds.split(',').map(id => parseInt(id));
this.moveDomainToNewWindow(domain, tabIds);
});
});
const closeDomainBtns = windowElement.querySelectorAll('.close-domain-btn');
closeDomainBtns.forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const domain = btn.dataset.domain;
const tabIds = btn.dataset.tabIds.split(',').map(id => parseInt(id));
this.confirmCloseDomainTabs(domain, tabIds);
});
});
// Window drop zone
tabsContainer.addEventListener('dragover', (e) => {
e.preventDefault();
if (this.dragData && this.dragData.windowId !== windowId) {
windowElement.classList.add('drag-over');
}
});
tabsContainer.addEventListener('dragleave', (e) => {
e.preventDefault();
windowElement.classList.remove('drag-over');
});
tabsContainer.addEventListener('drop', (e) => {
e.preventDefault();
windowElement.classList.remove('drag-over');
if (this.dragData && this.dragData.windowId !== windowId) {
this.moveTabToWindow(this.dragData.tabId, windowId);
}
});
}
setupTabEventListeners(tabItem) {
const tabId = parseInt(tabItem.dataset.tabId);
const windowId = parseInt(tabItem.dataset.windowId);
// Tab click to focus
tabItem.addEventListener('click', (e) => {
if (e.target.classList.contains('tab-btn') || e.target.classList.contains('tab-checkbox')) return;
this.focusTab(tabId);
});
// Tab buttons
const focusBtn = tabItem.querySelector('.focus-tab-btn');
const closeBtn = tabItem.querySelector('.close-tab-btn');
if (focusBtn) {
focusBtn.addEventListener('click', (e) => {
e.stopPropagation();
this.focusTab(tabId);
});
}
if (closeBtn) {
closeBtn.addEventListener('click', (e) => {
e.stopPropagation();
this.closeTab(tabId);
});
}
// Drag and drop
tabItem.addEventListener('dragstart', (e) => {
this.dragData = { tabId, windowId };
tabItem.classList.add('dragging');
this.elements.dropZone.classList.remove('hidden');
// Set drag effect
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', ''); // Required for Firefox
});
tabItem.addEventListener('dragend', (e) => {
tabItem.classList.remove('dragging');
this.elements.dropZone.classList.add('hidden');
this.dragData = null;
// Remove drag-over classes from all windows
document.querySelectorAll('.window-card').forEach(card => {
card.classList.remove('drag-over');
});
});
}
async focusWindow(windowId) {
try {
await this.sendMessage({
action: 'focusWindow',
data: { windowId }
});
this.showToast('Window focused', 'success');
} catch (error) {
console.error('Failed to focus window:', error);
this.showToast('Failed to focus window', 'error');
}
}
async closeWindow(windowId) {
try {
await this.sendMessage({
action: 'closeWindow',
data: { windowId }
});
this.showToast('Window closed', 'success');
} catch (error) {
console.error('Failed to close window:', error);
this.showToast('Failed to close window', 'error');
}
}
async focusTab(tabId) {
try {
await this.sendMessage({
action: 'focusTab',
data: { tabId }
});
this.showToast('Tab focused', 'success');
} catch (error) {
console.error('Failed to focus tab:', error);
this.showToast('Failed to focus tab', 'error');
}
}
async closeTab(tabId) {
try {
await this.sendMessage({
action: 'closeTab',
data: { tabId }
});
this.showToast('Tab closed', 'success');
} catch (error) {
console.error('Failed to close tab:', error);
this.showToast('Failed to close tab', 'error');
}
}
async moveTabToWindow(tabId, targetWindowId) {
try {
await this.sendMessage({
action: 'moveTab',
data: { tabId, windowId: targetWindowId }
});
this.showToast('Tab moved', 'success');
} catch (error) {
console.error('Failed to move tab:', error);
this.showToast('Failed to move tab', 'error');
}
}
async handleDropToNewWindow() {
if (!this.dragData) return;
try {
// Create new window with the dragged tab
const newWindow = await chrome.windows.create({
tabId: this.dragData.tabId,
focused: true
});
this.showToast('New window created', 'success');
} catch (error) {
console.error('Failed to create new window:', error);
this.showToast('Failed to create new window', 'error');
}
}
async createNewWindow() {
try {
await chrome.windows.create({
url: 'chrome://newtab/',
focused: true
});
this.showToast('New window created', 'success');
} catch (error) {
console.error('Failed to create new window:', error);
this.showToast('Failed to create new window', 'error');
}
}
confirmCloseWindow(windowId) {
const window = this.windows.find(w => w.id === windowId);
const tabCount = window ? window.tabs.length : 0;
this.showModal(
'Close Window',
`Are you sure you want to close this window? ${tabCount} tab${tabCount !== 1 ? 's' : ''} will be closed.`,
() => this.closeWindow(windowId)
);
}
setViewSize(size) {
this.compactMode = size;
// Update active button states
document.querySelectorAll('.size-btn').forEach(btn => {
btn.classList.remove('active');
});
switch(size) {
case 'normal':
this.elements.normalSizeBtn.classList.add('active');
break;
case 'compact':
this.elements.compactSizeBtn.classList.add('active');
break;
case 'ultra':
this.elements.ultraSizeBtn.classList.add('active');
break;
}
this.updateContainerClass();
// Save preference
this.savePreferences();
}
setViewLayout(layout) {
this.viewMode = layout;
// Update active button states
document.querySelectorAll('.layout-btn').forEach(btn => {
btn.classList.remove('active');
});
switch(layout) {
case 'masonry':
this.elements.masonryLayoutBtn.classList.add('active');
break;
case 'list':
this.elements.listLayoutBtn.classList.add('active');
break;
case 'full-masonry':
this.elements.fullMasonryLayoutBtn.classList.add('active');
break;
}
this.updateContainerClass();
// Save preference
this.savePreferences();
}
toggleCompactMode() {
// Keep for backwards compatibility if needed
// Cycle through three modes: normal → compact → ultra → normal
switch (this.compactMode) {
case 'normal':
this.setViewSize('compact');
break;
case 'compact':
this.setViewSize('ultra');
break;
case 'ultra':
this.setViewSize('normal');
break;
}
}
toggleGroupByDomain() {
this.groupByDomain = !this.groupByDomain;
this.elements.groupByDomainBtn.innerHTML = `
<span class="icon">🌐</span>
${this.groupByDomain ? 'Ungroup' : 'Group by Domain'}
`;
this.elements.groupByDomainBtn.classList.toggle('active');
// Reload windows to apply grouping
this.loadWindows();
// Save preference
this.savePreferences();
}
updateContainerClass() {
const classes = ['windows-container', 'masonry-container'];
const mainElement = document.querySelector('.main');
// Add layout classes
switch(this.viewMode) {
case 'masonry':
classes.push('masonry-view');
mainElement.classList.remove('full-width');
break;
case 'list':
classes.push('list-view');
mainElement.classList.remove('full-width');
break;
case 'full-masonry':
classes.push('full-masonry-view');
mainElement.classList.add('full-width');
break;
}
// Add compact mode classes
if (this.compactMode === 'compact') {
classes.push('compact-view');
} else if (this.compactMode === 'ultra') {
classes.push('compact-view', 'ultra-compact-view');
}
this.elements.windowsContainer.className = classes.join(' ');
}
getWindowTitle(window, index) {
const activeTab = window.tabs.find(tab => tab.active);
if (activeTab && activeTab.title && !activeTab.title.includes('New Tab')) {
return `Window ${index + 1}: ${activeTab.title}`;
}
return `Window ${index + 1} (${window.tabs.length} tab${window.tabs.length !== 1 ? 's' : ''})`;
}
getDisplayUrl(url) {
try {
const urlObj = new URL(url);
return urlObj.hostname || url;
} catch {
return url;
}
}
updateStats() {
const totalTabs = this.windows.reduce((sum, window) => sum + window.tabs.length, 0);
this.elements.windowCount.textContent = `${this.windows.length} window${this.windows.length !== 1 ? 's' : ''}`;
this.elements.tabCount.textContent = `${totalTabs} tab${totalTabs !== 1 ? 's' : ''}`;
}
showLoading() {
this.elements.loading.classList.remove('hidden');
this.elements.error.classList.add('hidden');
this.elements.content.classList.add('hidden');
}
showError(message) {
this.elements.errorMessage.textContent = message;
this.elements.loading.classList.add('hidden');
this.elements.error.classList.remove('hidden');
this.elements.content.classList.add('hidden');
}
showContent() {
this.elements.loading.classList.add('hidden');
this.elements.error.classList.add('hidden');
this.elements.content.classList.remove('hidden');
}
showToast(message, type = 'success') {
const iconMap = {
success: '✅',
error: '❌',
info: 'ℹ️'
};
this.elements.toast.className = `toast ${type}`;
this.elements.toast.querySelector('.toast-icon').textContent = iconMap[type] || iconMap.info;
this.elements.toast.querySelector('.toast-message').textContent = message;
this.elements.toast.classList.remove('hidden');
setTimeout(() => {
this.elements.toast.classList.add('hidden');
}, 3000);
}
showModal(title, message, onConfirm) {
this.elements.confirmModal.querySelector('.modal-title').textContent = title;
this.elements.confirmModal.querySelector('.modal-message').textContent = message;
// Remove any existing confirm listeners
const newConfirmBtn = this.elements.modalConfirm.cloneNode(true);
this.elements.modalConfirm.parentNode.replaceChild(newConfirmBtn, this.elements.modalConfirm);
this.elements.modalConfirm = newConfirmBtn;
this.elements.modalConfirm.addEventListener('click', () => {
this.hideModal();
onConfirm();
});
this.elements.confirmModal.classList.remove('hidden');
}
hideModal() {
this.elements.confirmModal.classList.add('hidden');
}
sendMessage(message) {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage(message, (response) => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
} else {
resolve(response);
}
});
});
}
handleImmediateUpdate(eventType, data) {
// Handle specific immediate updates without full refresh
switch (eventType) {
case 'tabMoved':
// For now, just do a full refresh but this could be optimized
// to move specific DOM elements
this.loadWindows(true); // Preserve scroll position
break;
case 'tabAttached':
case 'tabDetached':
// Tab moved between windows - full refresh needed
this.loadWindows(true); // Preserve scroll position
break;
}
}
handleTabSelection(tabId, isSelected) {
if (isSelected) {
this.selectedTabs.add(tabId);
} else {
this.selectedTabs.delete(tabId);
}
// Update the button visibility based on selection count
if (this.elements.sendToNewWindowBtn) {
this.elements.sendToNewWindowBtn.style.display = this.selectedTabs.size > 0 ? 'inline-block' : 'none';
}
}
async sendSelectedToNewWindow() {
if (this.selectedTabs.size === 0) {
this.showToast('No tabs selected', 'error');
return;
}
try {
const tabIds = Array.from(this.selectedTabs);
// Create new window with the first selected tab
const firstTabId = tabIds[0];
const newWindow = await chrome.windows.create({
tabId: firstTabId,
focused: true
});
// Move remaining tabs to the new window
if (tabIds.length > 1) {
for (let i = 1; i < tabIds.length; i++) {
await chrome.tabs.move(tabIds[i], {
windowId: newWindow.id,
index: -1
});
}
}
// Clear selection
this.selectedTabs.clear();
this.showToast(`Moved ${tabIds.length} tab${tabIds.length !== 1 ? 's' : ''} to new window`, 'success');
} catch (error) {
console.error('Failed to move tabs to new window:', error);
this.showToast('Failed to move tabs to new window', 'error');
}
}
async moveDomainToNewWindow(domain, tabIds) {
if (tabIds.length === 0) return;
try {
// Create new window with the first tab
const firstTabId = tabIds[0];
const newWindow = await chrome.windows.create({
tabId: firstTabId,
focused: true
});
// Move remaining tabs to the new window
if (tabIds.length > 1) {
for (let i = 1; i < tabIds.length; i++) {
await chrome.tabs.move(tabIds[i], {
windowId: newWindow.id,
index: -1
});
}
}
this.showToast(`Moved ${tabIds.length} ${domain} tab${tabIds.length !== 1 ? 's' : ''} to new window`, 'success');
} catch (error) {
console.error('Failed to move domain tabs to new window:', error);
this.showToast(`Failed to move ${domain} tabs`, 'error');
}
}
confirmCloseDomainTabs(domain, tabIds) {
const tabCount = tabIds.length;
this.showModal(
'Close Domain Tabs',
`Are you sure you want to close all ${tabCount} tab${tabCount !== 1 ? 's' : ''} from ${domain}?`,
() => this.closeDomainTabs(domain, tabIds)
);
}
async closeDomainTabs(domain, tabIds) {
if (tabIds.length === 0) return;