initial 0.1.0 commit

This commit is contained in:
Mattijs
2026-11-11 20:24:24 +01:00
parent febd628d37
commit 27b76e64b5
25 changed files with 1758 additions and 2 deletions
+190
View File
@@ -0,0 +1,190 @@
// Tab Park - settings and discard helpers shared by the background page,
// the popup and the options page. Loaded as a classic script, so declarations
// here are visible to whatever script follows.
const TU_DEFAULTS = {
autoUnload: false,
idleSeconds: 300,
skipAudible: true
};
// Below this the sweep would fight the user's own tab switching.
const TU_MIN_IDLE_SECONDS = 10;
async function tuSettings() {
const stored = await browser.storage.local.get(TU_DEFAULTS);
const idle = Math.round(Number(stored.idleSeconds));
return {
autoUnload: Boolean(stored.autoUnload),
idleSeconds: Number.isFinite(idle) && idle >= TU_MIN_IDLE_SECONDS ? idle : TU_DEFAULTS.idleSeconds,
skipAudible: Boolean(stored.skipAudible)
};
}
async function tuSaveSettings(patch) {
await browser.storage.local.set(patch);
}
// A tab is a discard candidate when it is loaded, not pinned, not the active
// tab of its window, and not mid-navigation. Firefox refuses to discard the
// active tab, so filtering it here keeps the counts honest.
function tuCandidates(tabs, { skipAudible = false } = {}) {
return tabs.filter(tab =>
!tab.discarded &&
!tab.pinned &&
!tab.active &&
tab.status !== 'loading' &&
(!skipAudible || !tab.audible)
);
}
const TU_PARKING_KEY = 'parkingTabId';
// The blank tab we opened to park the window on. Without the "tabs"
// permission Firefox does not reveal a tab's URL, so the id is the only way
// to tell this tab apart from a page the user opened.
async function tuParkingTabId() {
const stored = await browser.storage.session.get(TU_PARKING_KEY);
const id = stored[TU_PARKING_KEY];
return typeof id === 'number' ? id : null;
}
async function tuSetParkingTabId(tabId) {
await browser.storage.session.set({ [TU_PARKING_KEY]: tabId });
}
// A blank tab is the one place unloading makes no sense: there is nothing to
// free, and unloading it would only put another blank tab in its place.
// Without the "tabs" permission Firefox does not reveal tab URLs, so the id
// of the tab we opened is the only signal available.
async function tuIsParkingTab(tab) {
if (!tab) return false;
return tab.id === await tuParkingTabId();
}
const TU_PROTECTED_KEY = 'protectedTabIds';
// Tabs the user marked "never park". Stored by id, so the mark lives as long
// as the tab does. Without the "tabs" permission there is no stable
// identifier to carry it across a restart.
async function tuProtectedIds() {
const stored = await browser.storage.session.get(TU_PROTECTED_KEY);
const ids = stored[TU_PROTECTED_KEY];
return new Set(Array.isArray(ids) ? ids.filter(id => typeof id === 'number') : []);
}
async function tuIsProtected(tabId) {
return (await tuProtectedIds()).has(tabId);
}
async function tuSetProtected(tabId, protect) {
const ids = await tuProtectedIds();
if (protect) ids.add(tabId);
else ids.delete(tabId);
await browser.storage.session.set({ [TU_PROTECTED_KEY]: [...ids] });
}
async function tuWaitActive(tabId, timeoutMs = 1000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const tab = await browser.tabs.get(tabId).catch(() => null);
if (!tab) return false;
if (tab.active) return true;
await new Promise(resolve => setTimeout(resolve, 25));
}
return false;
}
async function tuWaitComplete(tabId, timeoutMs = 2000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const tab = await browser.tabs.get(tabId).catch(() => null);
if (!tab) return false;
if (tab.status === 'complete') return true;
await new Promise(resolve => setTimeout(resolve, 25));
}
return false;
}
// Opens the blank tab the window parks on. The id is recorded only after the
// initial load finishes, so a later "loading" event means the user navigated
// it and the id can be dropped.
async function tuCreateParkingTab(windowId) {
const created = await browser.tabs.create({ windowId, active: true });
await tuWaitActive(created.id);
await tuWaitComplete(created.id);
await tuSetParkingTabId(created.id);
return created;
}
// Discards in one batch, then reads the tabs back so the caller gets the
// number that actually unloaded. A tab with a beforeunload prompt cannot be
// discarded and rejects the batch, so fall back to one at a time.
async function tuDiscard(tabs) {
const ids = tabs.map(tab => tab.id).filter(id => typeof id === 'number');
if (ids.length === 0) return 0;
try {
await browser.tabs.discard(ids);
} catch (e) {
for (const id of ids) {
await browser.tabs.discard(id).catch(() => {});
}
}
const after = await browser.tabs.query({});
const byId = new Map(after.map(tab => [tab.id, tab]));
return ids.filter(id => {
const tab = byId.get(id);
return !tab || tab.discarded;
}).length;
}
// Unloads every candidate in the window except the tab the user asked to
// keep. tuCandidates already excludes the active tab; keepTabId covers the
// context menu case, where the tab to keep is not the active one.
async function tuUnloadOtherTabs(windowId, keepTabId) {
if (typeof windowId !== 'number') return 0;
const { skipAudible } = await tuSettings();
const protectedIds = await tuProtectedIds();
const tabs = await browser.tabs.query({ windowId });
return tuDiscard(
tuCandidates(tabs, { skipAudible })
.filter(tab => tab.id !== keepTabId && !protectedIds.has(tab.id))
);
}
// Unloads the active tab without leaving a blank window: switch to the next
// loaded tab first (wrapping around), or open a fresh tab when every other
// tab is already unloaded. Firefox will not discard the active tab, so the
// order matters. The discard is verified because tabs.discard() resolves
// without doing anything if the tab is still selected.
async function tuUnloadActiveTab(tab) {
if (await tuIsParkingTab(tab)) return false;
const tabs = await browser.tabs.query({ windowId: tab.windowId });
const current = tabs.find(other => other.id === tab.id) || tab;
const loaded = tabs
.filter(other => other.id !== current.id && !other.discarded && other.status !== 'loading')
.sort((a, b) => a.index - b.index);
const next = loaded.find(other => other.index > current.index) || loaded[0];
if (next) {
await browser.tabs.update(next.id, { active: true });
} else if (tabs.length > 1) {
await tuCreateParkingTab(current.windowId);
} else {
// The only tab in the window: there is nowhere to switch to.
return false;
}
for (let attempt = 0; attempt < 3; attempt++) {
try {
await browser.tabs.discard(current.id);
} catch (e) {
return false;
}
const after = await browser.tabs.get(current.id).catch(() => null);
if (!after || after.discarded) return true;
await new Promise(resolve => setTimeout(resolve, 120));
}
return false;
}