// Tab Park - keyboard commands, popup actions and the idle sweep. Loaded // after common.js, so the tu* helpers are in scope. const TU_ALARM = 'tu-idle-sweep'; const TU_SWEEP_MINUTES = 0.25; // 15 s // ---------- idle sweep async function tuSyncAlarm() { const { autoUnload } = await tuSettings(); if (autoUnload) { browser.alarms.create(TU_ALARM, { periodInMinutes: TU_SWEEP_MINUTES }); } else { await browser.alarms.clear(TU_ALARM); } } async function tuSweep() { const { autoUnload, idleSeconds, skipAudible } = await tuSettings(); if (!autoUnload) return 0; const cutoff = Date.now() - idleSeconds * 1000; const protectedIds = await tuProtectedIds(); const tabs = await browser.tabs.query({}); const idle = tuCandidates(tabs, { skipAudible }).filter(tab => !protectedIds.has(tab.id) && typeof tab.lastAccessed === 'number' && tab.lastAccessed <= cutoff ); return tuDiscard(idle); } // ---------- wiring browser.runtime.onInstalled.addListener(() => { tuSyncAlarm(); }); browser.runtime.onStartup.addListener(() => { tuSyncAlarm(); }); browser.storage.onChanged.addListener((changes, area) => { if (area === 'local' && changes.autoUnload) tuSyncAlarm(); }); // Forget the parking tab once the user navigates it or closes it. Without the // "tabs" permission there is no URL to compare, but the tab has finished its // initial load before the id is recorded, so any later load is a navigation. browser.tabs.onUpdated.addListener(async (tabId, changeInfo) => { if (changeInfo.status !== 'loading') return; if (tabId === await tuParkingTabId()) { await browser.storage.session.remove(TU_PARKING_KEY); } }); browser.tabs.onRemoved.addListener(async tabId => { if (tabId === await tuParkingTabId()) { await browser.storage.session.remove(TU_PARKING_KEY); } if (await tuIsProtected(tabId)) { await tuSetProtected(tabId, false); } }); browser.alarms.onAlarm.addListener(alarm => { if (alarm.name === TU_ALARM) tuSweep(); }); browser.commands.onCommand.addListener(async command => { const [tab] = await browser.tabs.query({ active: true, currentWindow: true }); if (!tab) return; if (command === 'unload-current') { await tuUnloadActiveTab(tab); } else if (command === 'unload-others') { await tuUnloadOtherTabs(tab.windowId, tab.id); } }); // The popup hands the work over instead of doing it itself: switching tabs // closes the popup, which would kill the rest of its async handler. browser.runtime.onMessage.addListener(message => { if (!message || typeof message !== 'object') return; if (message.type === 'tu:unload-current') { if (typeof message.windowId !== 'number') return false; return browser.tabs.query({ active: true, windowId: message.windowId }) .then(([tab]) => tab ? tuUnloadActiveTab(tab) : false); } if (message.type === 'tu:unload-others') { return tuUnloadOtherTabs(message.windowId, message.tabId); } });