forked from nisargkolhe/arcify
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsidebar.js
More file actions
1565 lines (1353 loc) · 64.1 KB
/
sidebar.js
File metadata and controls
1565 lines (1353 loc) · 64.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { ChromeHelper } from './chromeHelper.js';
import { FOLDER_CLOSED_ICON, FOLDER_OPEN_ICON } from './icons.js';
import { LocalStorage } from './localstorage.js';
import { Utils } from './utils.js';
// Constants
const MouseButton = {
LEFT: 0,
MIDDLE: 1,
RIGHT: 2
};
// DOM Elements
const spacesList = document.getElementById('spacesList');
const spaceSwitcher = document.getElementById('spaceSwitcher');
const addSpaceBtn = document.getElementById('addSpaceBtn');
const newTabBtn = document.getElementById('newTabBtn');
const spaceTemplate = document.getElementById('spaceTemplate');
// Global state
let spaces = [];
let activeSpaceId = null;
let isCreatingSpace = false;
// let isCreatingTab = false;
let isOpeningBookmark = false;
let isDraggingTab = false;
let currentWindow = null;
// Helper function to update bookmark for a tab
async function updateBookmarkForTab(tab) {
console.log("updating tab", tab);
const arcifyFolder = await LocalStorage.getOrCreateArcifyFolder();
const spaceFolders = await chrome.bookmarks.getChildren(arcifyFolder.id);
for (const spaceFolder of spaceFolders) {
console.log("looking for space folder", spaceFolder);
const bookmarks = await chrome.bookmarks.getChildren(spaceFolder.id);
console.log("looking for bookmarks", bookmarks);
const bookmark = bookmarks.find(b => b.url === tab.url);
if (bookmark) {
await chrome.bookmarks.update(bookmark.id, {
title: tab.title,
url: tab.url
});
}
}
}
console.log("hi");
// Function to update pinned favicons
async function updatePinnedFavicons() {
const pinnedFavicons = document.getElementById('pinnedFavicons');
const pinnedTabs = await chrome.tabs.query({ pinned: true });
// Remove favicon elements for tabs that are no longer pinned
Array.from(pinnedFavicons.children).forEach(element => {
const tabId = element.dataset.tabId;
if (!pinnedTabs.some(tab => tab.id.toString() === tabId)) {
element.remove();
}
});
pinnedTabs.forEach(tab => {
// Check if favicon element already exists for this tab
const existingElement = pinnedFavicons.querySelector(`[data-tab-id="${tab.id}"]`);
if (!existingElement) {
const faviconElement = document.createElement('div');
faviconElement.className = 'pinned-favicon';
faviconElement.title = tab.title;
faviconElement.dataset.tabId = tab.id;
const img = document.createElement('img');
img.src = Utils.getFaviconUrl(tab.url, "96");
img.alt = tab.title;
faviconElement.appendChild(img);
faviconElement.addEventListener('click', () => {
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
document.querySelectorAll('.pinned-favicon').forEach(t => t.classList.remove('active'));
// Add active class to clicked tab
faviconElement.classList.add('active');
chrome.tabs.update(tab.id, { active: true });
});
pinnedFavicons.appendChild(faviconElement);
}
});
pinnedFavicons.addEventListener('dragover', e => {
e.preventDefault();
e.currentTarget.classList.add('drag-over');
});
pinnedFavicons.addEventListener('dragleave', e => {
e.preventDefault();
e.currentTarget.classList.remove('drag-over');
});
pinnedFavicons.addEventListener('drop', async e => {
e.preventDefault();
e.currentTarget.classList.remove('drag-over');
const draggingElement = document.querySelector('.dragging');
if (draggingElement && draggingElement.dataset.tabId) {
const tabId = parseInt(draggingElement.dataset.tabId);
await chrome.tabs.update(tabId, { pinned: true });
updatePinnedFavicons();
// Remove the tab from its original container
draggingElement.remove();
}
});
}
// Initialize the sidebar when the DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
console.log('DOM loaded, initializing sidebar...');
initSidebar();
updatePinnedFavicons(); // Initial load of pinned favicons
// Add Chrome tab event listeners
chrome.tabs.onCreated.addListener(handleTabCreated);
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
handleTabUpdate(tabId, changeInfo, tab);
if (tab.pinned) updatePinnedFavicons(); // Update favicons when a tab is pinned/unpinned
});
chrome.tabs.onRemoved.addListener(handleTabRemove);
// chrome.tabs.onMoved.addListener(handleTabMove);
chrome.tabs.onActivated.addListener(handleTabActivated);
});
async function initSidebar() {
console.log('Initializing sidebar...');
try {
currentWindow = await chrome.windows.getCurrent({populate: false});
let tabGroups = await chrome.tabGroups.query({});
let allTabs = await chrome.tabs.query({currentWindow: true});
console.log("tabGroups", tabGroups);
console.log("allTabs", allTabs);
// Create bookmarks folder for spaces if it doesn't exist
const spacesFolder = await LocalStorage.getOrCreateArcifyFolder();
if (tabGroups.length === 0) {
let currentTabs = allTabs.filter(tab => tab.id && !tab.pinned) ?? [];
if (currentTabs.length == 0) {
await chrome.tabs.create({ active: true });
allTabs = await chrome.tabs.query({});
currentTabs = allTabs.filter(tab => tab.id && !tab.pinned) ?? [];
}
// Create default tab group and move all tabs to it
console.log('currentTabs', currentTabs);
const groupId = await chrome.tabs.group({tabIds: currentTabs.map(tab => tab.id)});
await chrome.tabGroups.update(groupId, {title: 'Home', color: 'grey'});
// Create default space with UUID
const defaultSpace = {
id: groupId,
uuid: Utils.generateUUID(),
name: 'Home',
color: 'grey',
spaceBookmarks: [],
temporaryTabs: currentTabs.map(tab => tab.id),
};
// Create bookmark folder for space bookmarks using UUID
await chrome.bookmarks.create({
parentId: spacesFolder.id,
title: defaultSpace.name
});
spaces = [defaultSpace];
saveSpaces();
createSpaceElement(defaultSpace);
await setActiveSpace(defaultSpace.id);
} else {
// Find tabs that aren't in any group
const ungroupedTabs = allTabs.filter(tab => tab.groupId === -1 && !tab.pinned);
let defaultGroupId = null;
// If there are ungrouped tabs, check for existing Default group or create new one
if (ungroupedTabs.length > 0) {
console.log("found ungrouped tabs", ungroupedTabs);
const defaultGroup = tabGroups.find(group => group.title === 'Home');
if (defaultGroup) {
console.log("found existing default group", defaultGroup);
if (defaultGroup.windowId === currentWindow.id) {
// Move ungrouped tabs to existing Default group
await chrome.tabs.group({tabIds: ungroupedTabs.map(tab => tab.id), groupId: defaultGroup.id});
} else {
// Create new Default group
defaultGroupId = await chrome.tabs.group({tabIds: ungroupedTabs.map(tab => tab.id)});
await chrome.tabGroups.update(defaultGroupId, {title: 'Home'+currentWindow.id, color: 'grey'});
}
} else {
// Create new Default group
defaultGroupId = await chrome.tabs.group({tabIds: ungroupedTabs.map(tab => tab.id)});
await chrome.tabGroups.update(defaultGroupId, {title: 'Home', color: 'grey'});
}
}
tabGroups = await chrome.tabGroups.query({});
// Load existing tab groups as spaces
spaces = await Promise.all(tabGroups.map(async group => {
const tabs = await chrome.tabs.query({groupId: group.id});
console.log("processing group", group);
const mainFolder = await chrome.bookmarks.getSubTree(spacesFolder.id);
const bookmarkFolder = mainFolder[0].children?.find(f => f.title == group.title);
console.log("looking for existing folder", group.title, mainFolder, bookmarkFolder);
let spaceBookmarks = [];
if (!bookmarkFolder) {
console.log("creating new folder", group.title)
await chrome.bookmarks.create({
parentId: spacesFolder.id,
title: group.title
});
} else {
console.log("found folder", group.title)
// Loop over bookmarks in the folder and add them to spaceBookmarks if there's an open tab
const processBookmarkFolder = async (folder) => {
const bookmarks = [];
const items = await chrome.bookmarks.getChildren(folder.id);
for (const item of items) {
if (item.url) {
// This is a bookmark
const tab = tabs.find(t => t.url === item.url);
if (tab) {
bookmarks.push(tab.id);
}
} else {
// This is a folder, recursively process it
const subFolderBookmarks = await processBookmarkFolder(item);
bookmarks.push(...subFolderBookmarks);
}
}
return bookmarks;
};
spaceBookmarks = await processBookmarkFolder(bookmarkFolder);
// Remove null values from spaceBookmarks
spaceBookmarks = spaceBookmarks.filter(id => id !== null);
console.log("space bookmarks in", group.title, spaceBookmarks);
}
const space = {
id: group.id,
uuid: Utils.generateUUID(),
name: group.title,
color: group.color,
spaceBookmarks: spaceBookmarks,
temporaryTabs: tabs.filter(tab => !spaceBookmarks.includes(tab.id)).map(tab => tab.id)
};
return space;
}));
spaces.forEach(space => createSpaceElement(space));
console.log("initial save", spaces);
saveSpaces();
let activeTabs = await chrome.tabs.query({ active: true, currentWindow: true });
if (activeTabs.length > 0) {
const activeTab = activeTabs[0];
if (activeTab.pinned) {
await setActiveSpace(spaces[0].id, false);
updatePinnedFavicons();
} else {
await setActiveSpace(activeTab.groupId, false);
}
} else {
await setActiveSpace(defaultGroupId ?? spaces[0].id);
}
}
} catch (error) {
console.error('Error initializing sidebar:', error);
}
setupDOMElements();
}
function createSpaceElement(space) {
console.log('Creating space element for:', space.id);
const spaceElement = spaceTemplate.content.cloneNode(true);
const sidebarContainer = document.getElementById('sidebar-container');
const spaceContainer = spaceElement.querySelector('.space');
spaceContainer.dataset.spaceId = space.id;
spaceContainer.style.display = space.id === activeSpaceId ? 'block' : 'none';
spaceContainer.dataset.spaceUuid = space.id;
// Set space background color based on the tab group color
sidebarContainer.style.setProperty('--space-bg-color', `var(--chrome-${space.color}-color, rgba(255, 255, 255, 0.1))`);
// Set up color select
const colorSelect = spaceElement.getElementById('spaceColorSelect');
colorSelect.value = space.color;
colorSelect.addEventListener('change', async () => {
const newColor = colorSelect.value;
space.color = newColor;
// Update tab group color
await chrome.tabGroups.update(space.id, { color: newColor });
// Update space background color
sidebarContainer.style.setProperty('--space-bg-color', `var(--chrome-${newColor}-color, rgba(255, 255, 255, 0.1))`);
saveSpaces();
updateSpaceSwitcher();
});
// Handle color swatch clicks
const spaceOptionColorSwatch = spaceElement.getElementById('spaceOptionColorSwatch');
spaceOptionColorSwatch.addEventListener('click', (e) => {
if (e.target.classList.contains('color-swatch')) {
const colorPicker = e.target.closest('.color-picker-grid');
const color = e.target.dataset.color;
// Update selected swatch
colorPicker.querySelectorAll('.color-swatch').forEach(swatch => {
swatch.classList.remove('selected');
});
e.target.classList.add('selected');
// Update hidden select value
colorSelect.value = color;
// Trigger change event on select
const event = new Event('change');
colorSelect.dispatchEvent(event);
}
});
// Set up space name input
const nameInput = spaceElement.querySelector('.space-name');
nameInput.value = space.name;
nameInput.addEventListener('change', async () => {
// Update bookmark folder name
const oldName = space.name;
const oldFolder = await LocalStorage.getOrCreateSpaceFolder(oldName);
await chrome.bookmarks.update(oldFolder.id, { title: nameInput.value });
const tabGroups = await chrome.tabGroups.query({});
const tabGroupForSpace = tabGroups.find(group => group.id === space.id);
console.log("updating tabGroupForSpace", tabGroupForSpace);
if (tabGroupForSpace) {
await chrome.tabGroups.update(tabGroupForSpace.id, {title: nameInput.value, color: 'grey'});
}
space.name = nameInput.value;
saveSpaces();
updateSpaceSwitcher();
});
// Set up containers
const pinnedContainer = spaceElement.querySelector('[data-tab-type="pinned"]');
const tempContainer = spaceElement.querySelector('[data-tab-type="temporary"]');
// Set up drag and drop
setupDragAndDrop(pinnedContainer, tempContainer);
// Set up clean tabs button
const cleanBtn = spaceElement.querySelector('.clean-tabs-btn');
cleanBtn.addEventListener('click', () => cleanTemporaryTabs(space.id));
// Set up options menu
const newFolderBtn = spaceElement.querySelector('.new-folder-btn');
const deleteSpaceBtn = spaceElement.querySelector('.delete-space-btn');
newFolderBtn.addEventListener('click', () => {
createNewFolder(spaceContainer);
});
deleteSpaceBtn.addEventListener('click', () => {
if (confirm('Delete this space and close all its tabs?')) {
deleteSpace(space.id);
}
});
// Load tabs
loadTabs(space, pinnedContainer, tempContainer);
// Add to DOM
spacesList.appendChild(spaceElement);
}
function updateSpaceSwitcher() {
console.log('Updating space switcher...');
spaceSwitcher.innerHTML = '';
spaces.forEach(space => {
const button = document.createElement('button');
button.textContent = space.name;
button.classList.toggle('active', space.id === activeSpaceId);
button.addEventListener('click', async () => await setActiveSpace(space.id));
spaceSwitcher.appendChild(button);
});
}
function getDragAfterElement(container, y) {
const draggableElements = [...container.querySelectorAll('.tab:not(.dragging), .folder:not(.dragging)')]
return draggableElements.reduce((closest, child) => {
const box = child.getBoundingClientRect()
const offset = y - box.top - box.height / 2
if (offset < 0 && offset > closest.offset) {
return { offset: offset, element: child }
} else {
return closest
}
}, { offset: Number.NEGATIVE_INFINITY }).element
}
async function setActiveSpace(spaceId, updateTab = true) {
console.log('Setting active space:', spaceId);
// Centralize logic in our new helper function
activateSpaceInDOM(spaceId);
let tabGroups = await chrome.tabGroups.query({});
let tabGroupsToClose = tabGroups.filter(group => group.id !== spaceId);
tabGroupsToClose.forEach(async group => {
await chrome.tabGroups.update(group.id, {collapsed: true})
});
const tabGroupForSpace = tabGroups.find(group => group.id === spaceId);
if (!tabGroupForSpace) {
const space = spaces.find(s => s.id === spaceId);
const newTab = await ChromeHelper.createNewTab();
const groupId = await ChromeHelper.createNewTabGroup(newTab, space.name, space.color);
// update spaceId with new groupId
spaces = spaces.map(s => {
if (s.id === spaceId) {
return { ...s, id: groupId };
}
return s;
});
saveSpaces();
} else {
// Uncollpase space's tab group
await chrome.tabGroups.update(spaceId, {collapsed: false})
// Get all tabs in the space and activate the last one
if (updateTab) {
const space = spaces.find(s => s.id === parseInt(spaceId));
console.log("updateTab space",space);
chrome.tabs.query({ groupId: spaceId }, tabs => {
if (tabs.length > 0) {
const lastTab = space.lastTab ?? tabs[tabs.length - 1].id;
chrome.tabs.update(lastTab, { active: true });
activateTabInDOM(lastTab);
}
});
}
}
}
function saveSpaces() {
console.log('Saving spaces to storage...', spaces);
chrome.storage.local.set({ spaces }, () => {
console.log('Spaces saved successfully');
});
}
const searchBookmarks = async (folderId, tab) => {
const items = await chrome.bookmarks.getChildren(folderId);
console.log("searching to delete", folderId, items);
for (const item of items) {
if (item.url === tab.url) {
console.log("found and deleted");
await chrome.bookmarks.remove(item.id);
} else if (!item.url) {
console.log("recursive folder search", item.id);
// Recursively search in subfolders
await searchBookmarks(item.id, tab);
}
}
};
async function moveTabToPinned(space, tab) {
space.temporaryTabs = space.temporaryTabs.filter(id => id !== tab.id);
if (!space.spaceBookmarks.includes(tab.id)) {
space.spaceBookmarks.push(tab.id);
}
const spaceFolder = await LocalStorage.getOrCreateSpaceFolder(space.name);
const bookmarks = await chrome.bookmarks.getChildren(spaceFolder.id);
const existingBookmark = bookmarks.find(b => b.url === tab.url);
if (!existingBookmark) {
// delete existing bookmark
await searchBookmarks(spaceFolder.id, tab);
await chrome.bookmarks.create({
parentId: spaceFolder.id,
title: tab.title,
url: tab.url
});
}
}
async function moveTabToTemp(space, tab) {
const arcifyFolder = await LocalStorage.getOrCreateArcifyFolder();
const spaceFolders = await chrome.bookmarks.getChildren(arcifyFolder.id);
const spaceFolder = spaceFolders.find(f => f.title === space.name);
if (spaceFolder) {
const searchAndRemoveBookmark = async (folderId) => {
const items = await chrome.bookmarks.getChildren(folderId);
for (const item of items) {
if (item.url === tab.url) {
await chrome.bookmarks.remove(item.id);
return true;
} else if (!item.url) {
const found = await searchAndRemoveBookmark(item.id);
if (found) return true;
}
}
return false;
};
await searchAndRemoveBookmark(spaceFolder.id);
}
// Move tab from bookmarks to temporary tabs in space data
space.spaceBookmarks = space.spaceBookmarks.filter(id => id !== tab.id);
if (!space.temporaryTabs.includes(tab.id)) {
space.temporaryTabs.push(tab.id);
}
saveSpaces();
}
async function setupDragAndDrop(pinnedContainer, tempContainer) {
console.log('Setting up drag and drop handlers...');
[pinnedContainer, tempContainer].forEach(container => {
container.addEventListener('dragover', e => {
e.preventDefault();
const draggingElement = document.querySelector('.dragging');
if (draggingElement) {
const targetFolder = e.target.closest('.folder-content');
const targetContainer = targetFolder || container;
// Get the element we're dragging over
const afterElement = getDragAfterElement(targetContainer, e.clientY);
if (afterElement) {
targetContainer.insertBefore(draggingElement, afterElement);
} else {
targetContainer.appendChild(draggingElement);
}
// Handle tab being moved to pinned section or folder
if (container.dataset.tabType === 'pinned' && draggingElement.dataset.tabId && !isDraggingTab) {
console.log("Tab dragged to pinned section or folder");
isDraggingTab = true;
const tabId = parseInt(draggingElement.dataset.tabId);
chrome.tabs.get(tabId, async (tab) => {
const spaceId = container.closest('.space').dataset.spaceId;
const space = spaces.find(s => s.id === parseInt(spaceId));
if (space && tab) {
// Move tab from temporary to pinned in space data
space.temporaryTabs = space.temporaryTabs.filter(id => id !== tabId);
if (!space.spaceBookmarks.includes(tabId)) {
space.spaceBookmarks.push(tabId);
}
// Determine the target folder or container
const targetFolderContent = draggingElement.closest('.folder-content');
const targetFolder = targetFolderContent ? targetFolderContent.closest('.folder') : null;
// Add to bookmarks if URL doesn't exist
const spaceFolder = await LocalStorage.getOrCreateSpaceFolder(space.name);
if (spaceFolder) {
let parentId = spaceFolder.id;
if (targetFolder) {
console.log("moving into a folder");
const folderElement = targetFolder.closest('.folder');
const folderName = folderElement.querySelector('.folder-name').value;
const existingFolders = await chrome.bookmarks.getChildren(spaceFolder.id);
let folder = existingFolders.find(f => f.title === folderName);
if (!folder) {
folder = await chrome.bookmarks.create({
parentId: spaceFolder.id,
title: folderName
});
}
parentId = folder.id;
// Check if bookmark already exists in the target folder
const existingBookmarks = await chrome.bookmarks.getChildren(parentId);
if (existingBookmarks.some(b => b.url === tab.url)) {
console.log('Bookmark already exists in folder:', folderName);
isDraggingTab = false;
return;
}
// Find and remove the bookmark from its original location
await searchBookmarks(spaceFolder.id, tab);
// Create the bookmark in the new location
await chrome.bookmarks.create({
parentId: parentId,
title: tab.title,
url: tab.url
});
// hide placeholder
const placeHolderElement = folderElement.querySelector('.tab-placeholder');
if (placeHolderElement) {
console.log("hiding from", folderElement);
placeHolderElement.classList.add('hidden');
}
} else {
await moveTabToPinned(space, tab);
}
}
saveSpaces();
}
isDraggingTab = false;
});
} else if (container.dataset.tabType === 'temporary' && draggingElement.dataset.tabId && !isDraggingTab) {
console.log("Tab dragged to temporary section");
isDraggingTab = true;
const tabId = parseInt(draggingElement.dataset.tabId);
chrome.tabs.get(tabId, async (tab) => {
const space = spaces.find(s => s.id === parseInt(activeSpaceId));
if (space && tab) {
// Remove tab from bookmarks if it exists
moveTabToTemp(space, tab);
}
isDraggingTab = false;
});
}
}
});
});
}
async function createNewFolder(spaceElement) {
const pinnedContainer = spaceElement.querySelector('[data-tab-type="pinned"]');
const folderTemplate = document.getElementById('folderTemplate');
const newFolder = folderTemplate.content.cloneNode(true);
const folderElement = newFolder.querySelector('.folder');
const folderHeader = folderElement.querySelector('.folder-header');
const folderTitle = folderElement.querySelector('.folder-title');
const folderNameInput = folderElement.querySelector('.folder-name');
const folderIcon = folderElement.querySelector('.folder-icon');
const folderToggle = folderElement.querySelector('.folder-toggle');
const folderContent = folderElement.querySelector('.folder-content');
// Open new folder by default
folderElement.classList.toggle('collapsed');
folderContent.classList.toggle('collapsed');
folderToggle.classList.toggle('collapsed');
folderHeader.addEventListener('click', () => {
folderElement.classList.toggle('collapsed');
folderContent.classList.toggle('collapsed');
folderToggle.classList.toggle('collapsed');
folderIcon.innerHTML = folderElement.classList.contains('collapsed') ? FOLDER_CLOSED_ICON : FOLDER_OPEN_ICON;
});
// Set up folder name input
folderNameInput.addEventListener('change', async () => {
const spaceName = spaceElement.querySelector('.space-name').value;
const spaceFolder = await LocalStorage.getOrCreateSpaceFolder(spaceName);
const existingFolders = await chrome.bookmarks.getChildren(spaceFolder.id);
const folder = existingFolders.find(f => f.title === folderNameInput.value);
if (!folder) {
await chrome.bookmarks.create({
parentId: spaceFolder.id,
title: folderNameInput.value
});
folderNameInput.classList.toggle('hidden');
folderTitle.innerHTML = folderNameInput.value;
folderTitle.classList.toggle('hidden');
}
});
// Add the new folder to the pinned container
pinnedContainer.appendChild(folderElement);
folderNameInput.focus();
}
async function loadTabs(space, pinnedContainer, tempContainer) {
console.log('Loading tabs for space:', space.id);
console.log('Space bookmarks in space:', space.spaceBookmarks);
var bookmarkedTabURLs = [];
try {
const tabs = await chrome.tabs.query({});
const arcifyFolder = await LocalStorage.getOrCreateArcifyFolder();
const spaceFolders = await chrome.bookmarks.getChildren(arcifyFolder.id);
const spaceFolder = spaceFolders.find(f => f.title == space.name);
if (spaceFolder) {
// Recursive function to process bookmarks and folders
async function processBookmarkNode(node, container) {
const bookmarks = await chrome.bookmarks.getChildren(node.id);
console.log('Processing bookmarks:', bookmarks);
const processedUrls = new Set();
for (const item of bookmarks) {
if (!item.url) {
// This is a folder
const folderTemplate = document.getElementById('folderTemplate');
const newFolder = folderTemplate.content.cloneNode(true);
const folderElement = newFolder.querySelector('.folder');
const folderHeader = folderElement.querySelector('.folder-header');
const folderIcon = folderElement.querySelector('.folder-icon');
const folderTitle = folderElement.querySelector('.folder-title');
const folderNameInput = folderElement.querySelector('.folder-name');
const folderContent = folderElement.querySelector('.folder-content');
const folderToggle = folderElement.querySelector('.folder-toggle');
const placeHolderElement = folderElement.querySelector('.tab-placeholder');
// Set up folder toggle functionality
// Add context menu for folder
folderElement.addEventListener('contextmenu', async (e) => {
e.preventDefault();
const contextMenu = document.createElement('div');
contextMenu.classList.add('context-menu');
contextMenu.style.position = 'fixed';
contextMenu.style.left = `${e.clientX}px`;
contextMenu.style.top = `${e.clientY}px`;
const deleteOption = document.createElement('div');
deleteOption.classList.add('context-menu-item');
deleteOption.textContent = 'Delete Folder';
deleteOption.addEventListener('click', async () => {
if (confirm('Are you sure you want to delete this folder and all its contents?')) {
const arcifyFolder = await LocalStorage.getOrCreateArcifyFolder();
const spaceFolders = await chrome.bookmarks.getChildren(arcifyFolder.id);
const spaceFolder = spaceFolders.find(f => f.title === space.name);
if (spaceFolder) {
const folders = await chrome.bookmarks.getChildren(spaceFolder.id);
const folder = folders.find(f => f.title === item.title);
if (folder) {
await chrome.bookmarks.removeTree(folder.id);
folderElement.remove();
}
}
}
contextMenu.remove();
});
contextMenu.appendChild(deleteOption);
document.body.appendChild(contextMenu);
// Close context menu when clicking outside
const closeContextMenu = (e) => {
if (!contextMenu.contains(e.target)) {
contextMenu.remove();
document.removeEventListener('click', closeContextMenu);
}
};
document.addEventListener('click', closeContextMenu);
});
folderHeader.addEventListener('click', () => {
folderElement.classList.toggle('collapsed');
folderContent.classList.toggle('collapsed');
folderToggle.classList.toggle('collapsed');
folderIcon.innerHTML = folderElement.classList.contains('collapsed') ? FOLDER_CLOSED_ICON : FOLDER_OPEN_ICON;
});
folderNameInput.value = item.title;
folderNameInput.readOnly = true;
folderNameInput.disabled = true;
folderNameInput.classList.toggle('hidden');
folderTitle.innerHTML = item.title;
folderTitle.classList.toggle('hidden');
placeHolderElement.classList.remove('hidden');
container.appendChild(folderElement);
// Recursively process the folder's contents
await processBookmarkNode(item, folderElement.querySelector('.folder-content'));
} else {
// This is a bookmark
if (!processedUrls.has(item.url)) {
const existingTab = tabs.find(t => t.url === item.url);
if (existingTab) {
console.log('Creating UI element for active bookmark:', existingTab);
bookmarkedTabURLs.push(existingTab.url);
const tabElement = createTabElement(existingTab, true);
container.appendChild(tabElement);
} else {
// Create UI element for inactive bookmark
const bookmarkTab = {
id: null,
title: item.title,
url: item.url,
favIconUrl: null,
spaceName: space.name
};
console.log('Creating UI element for inactive bookmark:', item.title);
const tabElement = createTabElement(bookmarkTab, true, true);
bookmarkedTabURLs.push(item.url);
container.appendChild(tabElement);
}
processedUrls.add(item.url);
const placeHolderElement = container.querySelector('.tab-placeholder');
if (placeHolderElement) {
placeHolderElement.classList.add('hidden');
}
}
}
}
return bookmarkedTabURLs;
}
// Process the space folder and get all bookmarked URLs
bookmarkedTabURLs = await processBookmarkNode(spaceFolder, pinnedContainer);
}
// Load temporary tabs
space.temporaryTabs.forEach(tabId => {
console.log("checking", tabId, spaces);
const tab = tabs.find(t => t.id === tabId);
const pinned = bookmarkedTabURLs.find(url => url == tab.url);
console.log("pinned", pinned);
if (tab && pinned == null) {
const tabElement = createTabElement(tab);
tempContainer.appendChild(tabElement);
}
});
} catch (error) {
console.error('Error loading tabs:', error);
}
}
async function closeTab(tabElement, tab, isPinned = false, isBookmarkOnly = false) {
console.log('Closing tab:', tab, tabElement, isPinned, isBookmarkOnly);
if (isBookmarkOnly) {
// Remove from bookmarks
const arcifyFolder = await LocalStorage.getOrCreateArcifyFolder();
const spaceFolders = await chrome.bookmarks.getChildren(arcifyFolder.id);
const activeSpace = spaces.find(s => s.id === activeSpaceId);
const spaceFolder = spaceFolders.find(f => f.title === activeSpace.name);
console.log("spaceFolder", spaceFolder);
if (spaceFolder) {
const searchAndRemoveBookmark = async (folderId) => {
const items = await chrome.bookmarks.getChildren(folderId);
for (const item of items) {
if (item.url === tab.url) {
console.log("removing bookmark", item);
await chrome.bookmarks.remove(item.id);
tabElement.remove();
return true; // Bookmark found and removed
} else if (!item.url) {
// This is a folder, search recursively
const found = await searchAndRemoveBookmark(item.id);
if (found) return true;
}
}
return false;
};
await searchAndRemoveBookmark(spaceFolder.id);
}
return;
}
// If last tab is closed, create a new empty tab to prevent tab group from closing
const tabsInGroup = await chrome.tabs.query({ groupId: activeSpaceId });
console.log("tabsInGroup", tabsInGroup);
if (tabsInGroup.length < 2) {
console.log("creating new tab");
await createNewTab(async () => {
closeTab(tabElement, tab, isPinned, isBookmarkOnly);
});
return;
}
const activeSpace = spaces.find(s => s.id === activeSpaceId);
console.log("activeSpace", activeSpace);
const isCurrentlyPinned = activeSpace?.spaceBookmarks.includes(tab.id);
const isCurrentlyTemporary= activeSpace?.temporaryTabs.includes(tab.id);
console.log("isCurrentlyPinned", isCurrentlyPinned, "isCurrentlyTemporary", isCurrentlyTemporary, "isPinned", isPinned);
if (isCurrentlyPinned || (isPinned && !isCurrentlyTemporary)) {
const arcifyFolder = await LocalStorage.getOrCreateArcifyFolder();
const spaceFolders = await chrome.bookmarks.getChildren(arcifyFolder.id);
const spaceFolder = spaceFolders.find(f => f.title === activeSpace.name);
console.log("spaceFolder", spaceFolder);
if (spaceFolder) {
const bookmarkTab = {
id: null,
title: tab.title,
url: tab.url,
favIconUrl: tab.favIconUrl,
spaceName: tab.spaceName
};
const inactiveTabElement = createTabElement(bookmarkTab, true, true);
tabElement.replaceWith(inactiveTabElement);
chrome.tabs.remove(tab.id);
return;
}
} else {
chrome.tabs.remove(tab.id);
}
}
function createTabElement(tab, isPinned = false, isBookmarkOnly = false) {
console.log('Creating tab element:', tab.id);
const tabElement = document.createElement('div');
tabElement.classList.add('tab');
if (!isBookmarkOnly) {
tabElement.dataset.tabId = tab.id;
tabElement.draggable = true;
// Add active class if this is the active tab
if (tab.active) {
tabElement.classList.add('active');
}
} else {
tabElement.classList.add('inactive');
tabElement.dataset.url = tab.url;
}
const favicon = document.createElement('img');
favicon.src = Utils.getFaviconUrl(tab.url);
favicon.classList.add('tab-favicon');
const title = document.createElement('span');
title.textContent = tab.title;
title.classList.add('tab-title');
const actionButton = document.createElement('button');
actionButton.classList.add(isBookmarkOnly ? 'tab-remove' : 'tab-close');
actionButton.innerHTML = isBookmarkOnly ? '-' : '×';
actionButton.addEventListener('click', async (e) => {
e.stopPropagation(); // Prevent tab activation when closing
closeTab(tabElement, tab, isPinned, isBookmarkOnly);
});
tabElement.appendChild(favicon);
tabElement.appendChild(title);
tabElement.appendChild(actionButton);
// Add click handler
tabElement.addEventListener('click', async () => {
// Remove active class from all tabs
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
document.querySelectorAll('.pinned-favicon').forEach(t => t.classList.remove('active'));
if (isBookmarkOnly) {
console.log('Opening bookmark:', tab.url);
isOpeningBookmark = true;
// Create new tab with bookmark URL
const newTab = await chrome.tabs.create({ url: tab.url, active: true });
console.log("newTab", newTab);
const bookmarkTab = {
id: newTab.id,
title: tab.title,
url: tab.url,
favIconUrl: tab.favIconUrl,
spaceName: tab.spaceName
};
const activeBookmark = createTabElement(bookmarkTab, true, false);
activeBookmark.classList.add('active');
console.log("activeBookmark", activeBookmark);
tabElement.replaceWith(activeBookmark);
await chrome.tabs.group({ tabIds: newTab.id, groupId: activeSpaceId });
isOpeningBookmark = false;
// if (isPinned) {
// const space = spaces.find(s => s.name === tab.spaceName);
// if (space) {
// space.spaceBookmarks.push(newTab.id);
// saveSpaces();
// }
// }
} else {
// Add active class to clicked tab
tabElement.classList.add('active');
chrome.tabs.update(tab.id, { active: true });
}
});
// Close tab on middle click
tabElement.addEventListener('mousedown', (event) => {
if (event.button === MouseButton.MIDDLE) {
closeTab(tabElement, tab, isPinned, isBookmarkOnly);
}
});