-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopup.js
More file actions
764 lines (657 loc) · 28 KB
/
popup.js
File metadata and controls
764 lines (657 loc) · 28 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
document.addEventListener("DOMContentLoaded", function () {
// --- Theme Logic ---
const themeToggleBtn = document.getElementById("themeToggleBtn");
const storedTheme = localStorage.getItem("theme"); // Use localStorage for instant UI pref
// Apply saved theme or default to dark
if (storedTheme === "light") {
document.documentElement.setAttribute("data-theme", "light");
updateThemeIcon(true);
} else {
document.documentElement.removeAttribute("data-theme");
updateThemeIcon(false);
}
themeToggleBtn.addEventListener("click", function () {
const currentTheme = document.documentElement.getAttribute("data-theme");
if (currentTheme === "light") {
document.documentElement.removeAttribute("data-theme");
localStorage.setItem("theme", "dark");
updateThemeIcon(false);
} else {
document.documentElement.setAttribute("data-theme", "light");
localStorage.setItem("theme", "light");
updateThemeIcon(true);
}
});
function updateThemeIcon(isLight) {
const sun = themeToggleBtn.querySelector(".icon-sun");
const moon = themeToggleBtn.querySelector(".icon-moon");
if (isLight) {
sun.style.display = "none";
moon.style.display = "inline";
} else {
sun.style.display = "inline";
moon.style.display = "none";
}
}
// -------------------
loadSessions();
document.getElementById("saveBtn").addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
chrome.runtime.sendMessage({ action: "manualSaveSession" }, function (response) {
if (response && response.status === "success") {
loadSessions();
}
});
});
// Purge Daily
document.getElementById("purgeDailyBtn").addEventListener("click", function (e) {
if (confirm("Are you sure? This will delete all sessions except the LAST one of each day (and any locked sessions).")) {
chrome.runtime.sendMessage({ action: "purgeDaily" }, function (response) {
if (response && response.status === "success") {
loadSessions();
// alert("Purged daily sessions. Remaining: " + response.count);
}
});
}
});
// Purge Monthly
document.getElementById("purgeMonthlyBtn").addEventListener("click", function (e) {
if (confirm("WARNING: This will delete MOST of your history, keeping only the LAST session of each MONTH (and locked sessions). Are you sure?")) {
chrome.runtime.sendMessage({ action: "purgeMonthly" }, function (response) {
if (response && response.status === "success") {
loadSessions();
// alert("Purged monthly sessions. Remaining: " + response.count);
}
});
}
});
// Remove Duplicates
document.getElementById("purgeDuplicatesBtn").addEventListener("click", function (e) {
if (confirm("This will remove duplicate URLs from within each UNLOCKED session. Locked sessions will be skipped. Continue?")) {
chrome.runtime.sendMessage({ action: "purgeDuplicates" }, function (response) {
if (response && response.status === "success") {
loadSessions();
alert(`Removed ${response.count} duplicate tabs.`);
}
});
}
});
// Import event listener.
document.getElementById("importBtn").addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
importSessions();
});
// Search event listener
document.getElementById("searchInput").addEventListener("input", function (e) {
loadSessions(); // Rerender sessions based on search
});
// Delete Matched event listener
document.getElementById("deleteMatchedBtn").addEventListener("click", function (e) {
const searchInput = document.getElementById("searchInput");
const searchTerm = searchInput ? searchInput.value.toLowerCase().trim() : "";
if (!searchTerm || searchTerm.length < 3) {
alert("Please type at least 3 characters to delete matched tabs.");
return;
}
if (confirm(`Are you sure you want to delete ALL tabs matching "${searchTerm}" from UNLOCKED sessions?`)) {
deleteMatchedTabs(searchTerm);
}
});
const moveFilteredBtn = document.getElementById("moveFilteredBtn");
if (moveFilteredBtn) {
moveFilteredBtn.addEventListener("click", function (e) {
const searchInput = document.getElementById("searchInput");
const searchTerm = searchInput ? searchInput.value.toLowerCase().trim() : "";
if (!searchTerm || searchTerm.length < 3) {
alert("Please type at least 3 characters to move matched tabs.");
return;
}
if (confirm(`Are you sure you want to move ALL tabs matching "${searchTerm}" to a NEW window (within each session)?`)) {
moveFilteredTabs(searchTerm);
}
});
}
});
function moveFilteredTabs(searchTerm) {
chrome.storage.local.get({ savedSessions: [] }, function (result) {
let sessions = result.savedSessions;
let movedCount = 0;
sessions.forEach(session => {
if (session.locked) return; // Skip locked
const movedTabs = [];
if (session.windows) {
// 1. Extract tabs logic
session.windows.forEach(win => {
// Capture matches
const matchingInWindow = win.tabs.filter(tab => (tab.url || "").toLowerCase().includes(searchTerm));
movedTabs.push(...matchingInWindow);
// Remove from window
win.tabs = win.tabs.filter(tab => !(tab.url || "").toLowerCase().includes(searchTerm));
});
// 2. Cleanup empty windows
session.windows = session.windows.filter(win => win.tabs.length > 0);
// 3. Create new window if we found tabs
if (movedTabs.length > 0) {
session.windows.push({
tabs: movedTabs
});
movedCount += movedTabs.length;
}
}
});
chrome.storage.local.set({ savedSessions: sessions }, function () {
loadSessions();
alert(`Moved ${movedCount} tabs to new windows.`);
});
});
}
function deleteMatchedTabs(searchTerm) {
chrome.storage.local.get({ savedSessions: [] }, function (result) {
let sessions = result.savedSessions;
let tabsRemovedCount = 0;
// Filter out matching tabs from unlocked sessions
sessions.forEach(session => {
if (session.locked) return; // Skip locked sessions
if (session.windows) {
session.windows.forEach((win, winIndex) => {
// Filter tabs in place or map? Filter is easier.
const originalCount = win.tabs.length;
win.tabs = win.tabs.filter(tab => {
const url = (tab.url || "").toLowerCase();
return !url.includes(searchTerm);
});
tabsRemovedCount += (originalCount - win.tabs.length);
});
// Remove empty windows
session.windows = session.windows.filter(win => win.tabs.length > 0);
}
});
// Remove empty sessions if they became empty due to purge (optional, but cleaner)
// User might want to keep the session timestamp even if empty? Usually not.
sessions = sessions.filter(session => session.locked || (session.windows && session.windows.length > 0));
chrome.storage.local.set({ savedSessions: sessions }, function () {
loadSessions();
alert(`Deleted ${tabsRemovedCount} tabs matching "${searchTerm}".`);
});
});
}
// Helper to extract the real URL if a tab is suspended by Marvelous Suspender.
function getRealUrl(url) {
if (url && url.indexOf("suspended.html") !== -1) {
let hashPart = url.split('#')[1];
if (hashPart) {
let params = new URLSearchParams(hashPart);
if (params.has("uri")) {
return decodeURIComponent(params.get("uri"));
}
}
}
return url;
}
// Load sessions from storage and render them.
function loadSessions() {
const sessionsContainer = document.getElementById("sessions");
const searchInput = document.getElementById("searchInput");
const searchTerm = searchInput ? searchInput.value.toLowerCase().trim() : "";
// Show/Hide Delete Matched Button
const deleteMatchedBtn = document.getElementById("deleteMatchedBtn");
if (deleteMatchedBtn) {
// Require at least 3 characters for safety
deleteMatchedBtn.style.display = searchTerm.length >= 3 ? "block" : "none";
}
const moveFilteredBtn = document.getElementById("moveFilteredBtn");
if (moveFilteredBtn) {
moveFilteredBtn.style.display = searchTerm.length >= 3 ? "block" : "none";
}
// Preserve scroll position (maybe tricky if list changes size, but good effort)
const scrollPos = sessionsContainer.scrollTop;
// Record IDs of expanded sessions.
const expandedSessionIds = [];
const currentDetails = sessionsContainer.querySelectorAll("details.session");
currentDetails.forEach(details => {
if (details.hasAttribute("open")) {
expandedSessionIds.push(details.getAttribute("data-session-id"));
}
});
sessionsContainer.innerHTML = "";
chrome.storage.local.get({ savedSessions: [] }, function (result) {
const sessions = result.savedSessions;
// Sort sessions by id descending (newest first)
sessions.sort((a, b) => b.id - a.id);
// If searching, we might show "No matches" instead of "No saved sessions"
if (sessions.length === 0) {
sessionsContainer.textContent = "No saved sessions.";
return;
}
let hasVisibleSession = false;
sessions.forEach(session => {
// Logic for filtering:
// We need to keep track of ORIGINAL indices for deletion to work.
// So we will iterate windows/tabs and pick those that match, preserving their original index.
const visibleWindows = [];
let matchInSession = false;
session.windows.forEach((win, originalWinIndex) => {
const visibleTabs = [];
win.tabs.forEach((tab, originalTabIndex) => {
// If search term is empty, all match. Else check URL.
const url = (tab.url || "").toLowerCase();
if (!searchTerm || url.includes(searchTerm)) {
visibleTabs.push({ ...tab, originalTabIndex });
}
});
if (visibleTabs.length > 0) {
visibleWindows.push({ ...win, tabs: visibleTabs, originalWinIndex });
matchInSession = true;
}
});
// If we are searching and there are no matches in this session, skip rendering it.
if (searchTerm && !matchInSession) {
return;
}
hasVisibleSession = true;
// Count windows and total tabs (DISPLAYED ones vs TOTAL ones? Displayed makes sense for search context)
// Actually, typically the header shows the total, but if filtered, maybe show "Found X tabs"?
// For simplicity/stability, let's show the stats of the MATCHING content if searching, or full if not.
const numWindows = visibleWindows.length;
const numTabs = visibleWindows.reduce((acc, win) => acc + win.tabs.length, 0);
// Create a details element for the session.
const details = document.createElement("details");
details.classList.add("session");
details.setAttribute("data-session-id", session.id);
// Auto-expand if searching to show results
if (searchTerm) {
details.setAttribute("open", "");
} else if (expandedSessionIds.includes(String(session.id))) {
details.setAttribute("open", "");
}
// Format timestamp to "YYYY.MM.DD HH:MM" (drop seconds).
const formattedTimestamp = session.timestamp.slice(0, 16);
// Always show save duration (or N/A if not available).
const timingText = " (Save: " + (session.saveDuration || "N/A") + " ms)";
let countText = `${numWindows} window${numWindows !== 1 ? "s" : ""}, ${numTabs} tab${numTabs !== 1 ? "s" : ""}`;
if (searchTerm) {
countText = `Found: ${numTabs} tab${numTabs !== 1 ? "s" : ""}`;
}
const titleText = `Session: ${formattedTimestamp}${timingText}, ${countText}`;
// Build the summary element.
const summary = document.createElement("summary");
summary.classList.add("session-summary");
summary.style.display = "flex";
summary.style.justifyContent = "space-between";
summary.style.alignItems = "center";
// Left container: arrow + title + Lock + Delete.
const leftContainer = document.createElement("div");
leftContainer.classList.add("session-header");
leftContainer.style.display = "flex";
leftContainer.style.alignItems = "center";
const arrowSpan = document.createElement("span");
arrowSpan.classList.add("session-arrow");
arrowSpan.textContent = "▶"; // Simple arrow that rotates to down in CSS
leftContainer.appendChild(arrowSpan);
const titleSpan = document.createElement("span");
titleSpan.classList.add("session-title");
titleSpan.textContent = titleText;
leftContainer.appendChild(titleSpan);
// Lock Button (Visual Improvement)
const lockBtn = document.createElement("button");
lockBtn.type = "button";
lockBtn.classList.add("lock-btn"); // Use class for styling
// Inline overrides from JS can be removed in favor of classes: .locked / .unlocked
if (session.locked) {
lockBtn.textContent = "Locked"; // Icon via CSS? Or just text.
lockBtn.title = "Click to Unlock";
lockBtn.classList.add("locked");
lockBtn.classList.remove("unlocked");
} else {
lockBtn.textContent = "Unlocked";
lockBtn.title = "Click to Lock";
lockBtn.classList.add("unlocked");
lockBtn.classList.remove("locked");
}
lockBtn.addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation(); // prevent expanding
toggleSessionLock(session.id);
});
leftContainer.appendChild(lockBtn);
// Right side: delete session button.
// Old location of Delete Session Button removed. (Variable declaration removed to fix linter error)
// Move into left container to keep next to lock button
// leftContainer.appendChild(deleteSessionButton);
summary.appendChild(leftContainer);
// summary.appendChild(deleteSessionButton); // Removed from here
details.appendChild(summary);
// Update arrow on toggle? CSS handles rotation of .session-arrow inside details[open]
// So we don't need JS to swap characters anymore.
// details.addEventListener("toggle", function () { ... });
// Content container for detailed session info.
const contentContainer = document.createElement("div");
contentContainer.classList.add("session-content");
// Session-level buttons.
const sessionButtons = document.createElement("div");
sessionButtons.classList.add("session-buttons");
sessionButtons.style.display = "inline-flex";
sessionButtons.style.gap = "4px";
sessionButtons.style.marginBottom = "6px";
const restoreSessionButton = document.createElement("button");
restoreSessionButton.type = "button";
restoreSessionButton.textContent = "Restore Session";
restoreSessionButton.classList.add("session-action-btn", "btn-restore");
restoreSessionButton.addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
restoreSession(session);
});
sessionButtons.appendChild(restoreSessionButton);
const exportSessionButton = document.createElement("button");
exportSessionButton.type = "button";
exportSessionButton.textContent = "Export Session";
exportSessionButton.classList.add("session-action-btn", "btn-export");
exportSessionButton.addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
exportSessionToFile(session);
});
sessionButtons.appendChild(exportSessionButton);
// Move delete here
const deleteSessionButton = document.createElement("button");
deleteSessionButton.type = "button";
deleteSessionButton.textContent = "Delete Session";
deleteSessionButton.classList.add("session-action-btn", "btn-delete-session");
if (session.locked) {
deleteSessionButton.disabled = true;
deleteSessionButton.style.opacity = "0.5";
deleteSessionButton.title = "Unlock session to delete";
deleteSessionButton.style.cursor = "not-allowed";
}
deleteSessionButton.addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
if (!session.locked) {
// Confirm before deleting session? The instructions didn't explicitly ask for confirmation here,
// but it's good practice. The original code didn't have it either.
// Staying faithful to original logic: just delete.
removeSessionFromStorage(session.id);
}
});
sessionButtons.appendChild(deleteSessionButton);
contentContainer.appendChild(sessionButtons);
// Render windows and tabs from the VISIBLE list
visibleWindows.forEach((win) => {
// win has win.tabs and win.originalWinIndex
const table = document.createElement("table");
table.classList.add("session-details");
// Table header: a single cell with window title and inline action buttons.
const thead = document.createElement("thead");
const headerRow = document.createElement("tr");
const headerCell = document.createElement("th");
headerCell.colSpan = 3;
headerCell.style.whiteSpace = "nowrap";
// Create a header container with inline layout.
const headerContainer = document.createElement("div");
headerContainer.style.display = "flex";
headerContainer.style.justifyContent = "flex-start"; // align left
headerContainer.style.alignItems = "center";
const windowTitleSpan = document.createElement("span");
windowTitleSpan.textContent = `Window ${win.originalWinIndex + 1}`; // Use original index for display consistency? Or implicit? typical to use loop index. Let's use visible logic + Original info if helpful. "Window X" usually implies filtered view might skip window 1. Let's keep "Window X" as "Window [originalIndex + 1]"
headerContainer.appendChild(windowTitleSpan);
// Inline actions container.
const actionsContainer = document.createElement("div");
actionsContainer.style.display = "inline-flex";
actionsContainer.style.gap = "4px";
actionsContainer.style.marginLeft = "10px";
const restoreWindowButton = document.createElement("button");
restoreWindowButton.type = "button";
restoreWindowButton.textContent = "Restore Window";
restoreWindowButton.addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
// Restore needs the original full window? restoreWindow function uses correct indices.
restoreWindow(session, win.originalWinIndex);
});
actionsContainer.appendChild(restoreWindowButton);
const deleteWindowButton = document.createElement("button");
deleteWindowButton.type = "button";
deleteWindowButton.textContent = "[x]";
deleteWindowButton.classList.add("delete");
if (session.locked) {
deleteWindowButton.disabled = true;
deleteWindowButton.style.opacity = "0.5";
}
deleteWindowButton.addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
if (!session.locked) {
removeWindowFromSession(session.id, win.originalWinIndex);
}
});
actionsContainer.appendChild(deleteWindowButton);
headerContainer.appendChild(actionsContainer);
headerCell.appendChild(headerContainer);
headerRow.appendChild(headerCell);
thead.appendChild(headerRow);
table.appendChild(thead);
// Table body: list each tab.
const tbody = document.createElement("tbody");
win.tabs.forEach((tab) => {
// tab has tab.url and tab.originalTabIndex
const row = document.createElement("tr");
const deleteCell = document.createElement("td");
deleteCell.style.width = "30px";
const deleteTabButton = document.createElement("button");
deleteTabButton.type = "button";
deleteTabButton.classList.add("delete-tab-btn"); // Modern class
// SVG Trash Icon (small)
deleteTabButton.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="14" height="14">
<path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
</svg>
`;
if (session.locked) {
deleteTabButton.disabled = true;
deleteTabButton.style.opacity = "0.3"; // Lower opacity for locked
deleteTabButton.style.cursor = "not-allowed";
}
deleteTabButton.addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
if (!session.locked) {
removeTabFromSession(session.id, win.originalWinIndex, tab.originalTabIndex);
}
});
deleteCell.appendChild(deleteTabButton);
row.appendChild(deleteCell);
const urlCell = document.createElement("td");
urlCell.colSpan = 2;
urlCell.textContent = tab.url;
row.appendChild(urlCell);
tbody.appendChild(row);
});
table.appendChild(tbody);
contentContainer.appendChild(table);
});
details.appendChild(contentContainer);
sessionsContainer.appendChild(details);
});
if (searchTerm && !hasVisibleSession) {
sessionsContainer.textContent = "No matches found.";
}
// Only restore scroll pos if not searching, as searching changes height dramatically
if (!searchTerm) {
sessionsContainer.scrollTop = scrollPos;
}
// Update status bar with stats.
chrome.storage.local.getBytesInUse(null, function (bytesInUse) {
const statusBar = document.getElementById("status-bar");
if (statusBar) {
const kb = (bytesInUse / 1024).toFixed(2);
const mb = (bytesInUse / (1024 * 1024)).toFixed(2);
let sizeText = `${kb} KB`;
if (bytesInUse > 1024 * 1024) {
sizeText = `${mb} MB`;
}
statusBar.textContent = `Saved Sessions: ${sessions.length} | Storage Used: ${sizeText}`;
}
});
});
}
function toggleSessionLock(sessionId) {
chrome.storage.local.get({ savedSessions: [] }, function (result) {
let sessions = result.savedSessions;
let session = sessions.find(s => s.id === sessionId);
if (session) {
session.locked = !session.locked;
chrome.storage.local.set({ savedSessions: sessions }, function () {
loadSessions();
});
}
});
}
// Restore an entire session.
function restoreSession(session) {
// Signal background to pause auto-save
chrome.runtime.sendMessage({ action: "pauseAutoSave" }, function () {
session.windows.forEach(win => {
if (win.tabs && win.tabs.length > 0) {
const urls = win.tabs.map(tab => tab.url);
chrome.windows.create({ url: urls[0] }, function (newWindow) {
for (let i = 1; i < urls.length; i++) {
chrome.tabs.create({ windowId: newWindow.id, url: urls[i] });
}
});
}
});
});
}
// Restore a specific window.
function restoreWindow(session, winIndex) {
// Signal background to pause auto-save
chrome.runtime.sendMessage({ action: "pauseAutoSave" }, function () {
const win = session.windows[winIndex];
if (win && win.tabs && win.tabs.length > 0) {
const urls = win.tabs.map(tab => tab.url);
chrome.windows.create({ url: urls[0] }, function (newWindow) {
for (let i = 1; i < urls.length; i++) {
chrome.tabs.create({ windowId: newWindow.id, url: urls[i] });
}
});
}
});
}
// Remove a single tab. If its window becomes empty, remove the window.
function removeTabFromSession(sessionId, winIndex, tabIndex) {
chrome.storage.local.get({ savedSessions: [] }, function (result) {
let sessions = result.savedSessions;
let session = sessions.find(s => s.id === sessionId);
if (session && session.windows && session.windows[winIndex] && session.windows[winIndex].tabs) {
session.windows[winIndex].tabs.splice(tabIndex, 1);
if (session.windows[winIndex].tabs.length === 0) {
session.windows.splice(winIndex, 1);
}
chrome.storage.local.set({ savedSessions: sessions }, function () {
loadSessions();
});
}
});
}
// Remove an entire window.
function removeWindowFromSession(sessionId, winIndex) {
chrome.storage.local.get({ savedSessions: [] }, function (result) {
let sessions = result.savedSessions;
let session = sessions.find(s => s.id === sessionId);
if (session && session.windows && session.windows[winIndex]) {
session.windows.splice(winIndex, 1);
chrome.storage.local.set({ savedSessions: sessions }, function () {
loadSessions();
});
}
});
}
function moveFilteredTabs(searchTerm) {
chrome.storage.local.get({ savedSessions: [] }, function (result) {
let sessions = result.savedSessions;
let movedCount = 0;
sessions.forEach(session => {
if (session.locked) return; // Skip locked
const movedTabs = [];
if (session.windows) {
// 1. Extract tabs
session.windows.forEach(win => {
// We need to loop backwards or filter to remove safely?
// Actually filter is easiest for removal.
// But we need to capture them first.
const matchingInWindow = win.tabs.filter(tab => (tab.url || "").toLowerCase().includes(searchTerm));
movedTabs.push(...matchingInWindow);
// Remove from window
win.tabs = win.tabs.filter(tab => !(tab.url || "").toLowerCase().includes(searchTerm));
});
// 2. Cleanup empty windows
session.windows = session.windows.filter(win => win.tabs.length > 0);
// 3. Create new window if we found tabs
if (movedTabs.length > 0) {
session.windows.push({
tabs: movedTabs,
originalWinIndex: session.windows.length // Might need update structure? Load logic handles index.
});
movedCount += movedTabs.length;
}
}
});
chrome.storage.local.set({ savedSessions: sessions }, function () {
loadSessions();
alert(`Moved ${movedCount} tabs to new windows.`);
});
});
}
// Remove an entire session.
function removeSessionFromStorage(sessionId) {
chrome.storage.local.get({ savedSessions: [] }, function (result) {
let sessions = result.savedSessions;
sessions = sessions.filter(s => s.id !== sessionId);
chrome.storage.local.set({ savedSessions: sessions }, function () {
loadSessions();
});
});
}
// Export a session to a JSON file.
function exportSessionToFile(session) {
const exportData = {
id: session.id,
timestamp: session.timestamp,
date: session.date,
locked: session.locked || false, // Export locked status
windows: session.windows.map(win => ({
tabs: win.tabs.map(tab => ({ url: getRealUrl(tab.url) }))
}))
};
const dataStr = JSON.stringify(exportData, null, 2);
const blob = new Blob([dataStr], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
const safeTimestamp = session.timestamp.replace(/[\s:]/g, "-");
a.download = `session-${safeTimestamp}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// Import sessions from JSON.
function importSessions() {
let importText = document.getElementById("importTextarea").value;
try {
let importedSessions = JSON.parse(importText);
chrome.storage.local.get({ savedSessions: [] }, function (result) {
let sessions = result.savedSessions;
sessions = sessions.concat(importedSessions);
chrome.storage.local.set({ savedSessions: sessions }, function () {
loadSessions();
alert("Import successful");
});
});
} catch (e) {
alert("Error importing sessions: " + e.message);
}
}