diff --git a/.github/workflows/extension.yml b/.github/workflows/extension.yml new file mode 100644 index 0000000..8fe89b8 --- /dev/null +++ b/.github/workflows/extension.yml @@ -0,0 +1,164 @@ +name: Extension Build & Chrome Web Store Publish + +on: + pull_request: + paths: + - 'manifest.json' + - 'src/**' + - 'icons/**' + - 'scripts/**' + - '.github/workflows/extension.yml' + push: + branches: + - master + paths: + - 'manifest.json' + - 'src/**' + - 'icons/**' + workflow_dispatch: + inputs: + publish_type: + description: 'DEFAULT_PUBLISH goes live after review; STAGED_PUBLISH waits for a manual publish in the dashboard' + type: choice + options: + - DEFAULT_PUBLISH + - STAGED_PUBLISH + default: DEFAULT_PUBLISH + cancel_pending: + description: 'Cancel an older submission that is still in review and replace it' + type: boolean + default: false + +permissions: + contents: read + +concurrency: + group: extension-${{ github.ref }} + # Never interrupt a store upload halfway; superseded PR runs can be cancelled + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + build: + name: Validate & package + runs-on: ubuntu-latest + outputs: + version: ${{ steps.package.outputs.version }} + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 20 + + - name: Require a version bump when extension code changes + if: github.event_name == 'pull_request' + env: + BASE_REF: ${{ github.base_ref }} + run: | + changed=$(git diff --name-only "origin/${BASE_REF}...HEAD" -- manifest.json src icons) + if [ -z "$changed" ]; then + echo "No shipped files changed; version bump not required." + exit 0 + fi + base_version=$(git show "origin/${BASE_REF}:manifest.json" | node -e "process.stdout.write(JSON.parse(require('fs').readFileSync(0,'utf8')).version)") + head_version=$(node -p "require('./manifest.json').version") + echo "Base v${base_version} -> PR v${head_version}" + newer=$(node -e " + const [a, b] = process.argv.slice(1).map(v => v.split('.').map(Number)); + let r = 0; + for (let i = 0; i < 4 && r === 0; i++) r = Math.sign((a[i] || 0) - (b[i] || 0)); + process.stdout.write(String(r > 0)); + " "$head_version" "$base_version") + if [ "$newer" != "true" ]; then + echo "::error file=manifest.json::Extension files changed but v${head_version} is not higher than v${base_version} on ${BASE_REF}. Bump \"version\" in manifest.json so the merge ships to the Chrome Web Store." + exit 1 + fi + + - name: Validate and package extension + id: package + run: | + zip_path=$(node scripts/build-extension.mjs --out dist | tail -n 1) + echo "zip=${zip_path}" >> "$GITHUB_OUTPUT" + echo "version=$(node -p "require('./manifest.json').version")" >> "$GITHUB_OUTPUT" + + - name: Upload package artifact + uses: actions/upload-artifact@v4 + with: + name: tabstack-extension + path: dist/*.zip + if-no-files-found: error + retention-days: 30 + + publish: + name: Publish to Chrome Web Store + needs: build + if: github.event_name != 'pull_request' + runs-on: ubuntu-latest + environment: + name: chrome-web-store + url: https://chromewebstore.google.com/detail/tabstack/${{ vars.CWS_EXTENSION_ID || 'pnjlcnpebjggdmkhbopnibjgechfbfjg' }} + permissions: + contents: write # create the GitHub release for the shipped version + env: + CWS_PUBLISHER_ID: ${{ secrets.CWS_PUBLISHER_ID }} + CWS_EXTENSION_ID: ${{ vars.CWS_EXTENSION_ID || 'pnjlcnpebjggdmkhbopnibjgechfbfjg' }} + CWS_SERVICE_ACCOUNT_JSON: ${{ secrets.CWS_SERVICE_ACCOUNT_JSON }} + CWS_CLIENT_ID: ${{ secrets.CWS_CLIENT_ID }} + CWS_CLIENT_SECRET: ${{ secrets.CWS_CLIENT_SECRET }} + CWS_REFRESH_TOKEN: ${{ secrets.CWS_REFRESH_TOKEN }} + CWS_PUBLISH_TYPE: ${{ inputs.publish_type || 'DEFAULT_PUBLISH' }} + CWS_CANCEL_PENDING: ${{ inputs.cancel_pending && 'true' || 'false' }} + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 20 + + - name: Check store credentials + id: creds + run: | + if [ -z "$CWS_PUBLISHER_ID" ] || { [ -z "$CWS_SERVICE_ACCOUNT_JSON" ] && [ -z "$CWS_REFRESH_TOKEN" ]; }; then + echo "::warning::Chrome Web Store secrets are not configured, so nothing was published. See docs/PUBLISHING.md." + echo "configured=false" >> "$GITHUB_OUTPUT" + else + echo "configured=true" >> "$GITHUB_OUTPUT" + fi + + - name: Compare with store version + id: check + if: steps.creds.outputs.configured == 'true' + run: node scripts/cws-publish.mjs check + + - name: Download package artifact + if: steps.check.outputs.should_publish == 'true' + uses: actions/download-artifact@v4 + with: + name: tabstack-extension + path: dist + + - name: Upload and submit for review + id: publish + if: steps.check.outputs.should_publish == 'true' + run: node scripts/cws-publish.mjs publish "dist/tabstack-${{ needs.build.outputs.version }}.zip" + + - name: Create GitHub release + if: steps.publish.outputs.submitted_version != '' + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ steps.publish.outputs.submitted_version }} + run: | + if gh release view "v${VERSION}" >/dev/null 2>&1; then + echo "Release v${VERSION} already exists" + else + gh release create "v${VERSION}" "dist/tabstack-${VERSION}.zip" \ + --target "${GITHUB_SHA}" \ + --title "TabStack v${VERSION}" \ + --generate-notes + fi diff --git a/README.md b/README.md index a767fe6..4477813 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@

Smart Tab Auto-Collapse & RAM Saver for Chromium Browsers
- Automatically clusters same-site tabs into native collapsible groups, expands only your active stack (Accordion Mode), and frees system memory. + Automatically clusters same-site tabs into native collapsible groups, expands only your active stack (Accordion Mode), frees system memory, and brings back windows you close by mistake.

@@ -64,7 +64,14 @@ Configure custom hibernation timeouts, root vs. subdomain grouping, minimum tab TabStack Options & Whitelist

-### 5. ๐Ÿงผ Clean, Minimal & Clutter-Free UI +### 5. ๐Ÿ•˜ Session Snapshots (Never Lose a Window Again) +Closed the wrong window? TabStack keeps a local copy of every open window and saves it the moment the window closes. It also takes periodic snapshots (every 1h, 3h, 6h, 24h or 7 days) and keeps the session that was open before the browser last restarted. Open the **Sessions** tab in the popup and click **Restore** to reopen the tabs in a new window with pinned tabs and tab groups (names, colors, collapsed state) intact. Snapshots can be exported to and imported from JSON in Settings. + +

+ TabStack Session Snapshots +

+ +### 6. ๐Ÿงผ Clean, Minimal & Clutter-Free UI Designed with an intuitive, distraction-free interface that gets completely out of your way. Fast, accessible, lightweight, and works seamlessly out of the box with zero complex setup. --- @@ -85,6 +92,7 @@ Designed with an intuitive, distraction-free interface that gets completely out * **Zero Injected Content Scripts:** TabStack never touches or inspects webpage DOM contents. * **100% Local Execution:** No remote analytics, tracking pixels, or data collection. Your open tabs and browsing history never leave your machine. +* **Local-Only Snapshots:** Session snapshots (tab URLs, titles and group names) are stored in your browser's extension storage and are never uploaded. Turn them off or delete them anytime in Settings. * **Lightweight Service Worker:** Event-driven architecture with debounced operations (150ms) to ensure 0% CPU overhead. --- @@ -106,6 +114,9 @@ Get TabStack directly from the official store: 3. Enable **Developer mode** in the top-right corner. 4. Click **Load unpacked** and select the root `tabstack/` folder. +### Releasing +Merging a version bump to `master` publishes it automatically: GitHub Actions validates and packages the extension, uploads it to the Chrome Web Store through the v2 API, and submits it for review. PRs that change extension code must bump `"version"` in `manifest.json`. One-time credential setup is in **[docs/PUBLISHING.md](docs/PUBLISHING.md)**. + ### Running the Landing Page Locally ```bash cd landing diff --git a/docs/PUBLISHING.md b/docs/PUBLISHING.md new file mode 100644 index 0000000..1946111 --- /dev/null +++ b/docs/PUBLISHING.md @@ -0,0 +1,94 @@ +# Publishing to the Chrome Web Store + +Merges to `master` that touch the extension (`manifest.json`, `src/`, `icons/`) are uploaded to the Chrome Web Store and submitted for review automatically by [`.github/workflows/extension.yml`](../.github/workflows/extension.yml). It uses the [Chrome Web Store API v2](https://developer.chrome.com/docs/webstore/using-api). The v1 API stops working on October 15, 2026. + +## How a release flows + +1. **Open a PR** that changes the extension and bumps `"version"` in `manifest.json`. The PR check fails if extension files changed but the version isn't higher than `master`'s. +2. **CI validates and packages** the extension: manifest sanity checks, a syntax check of every script, and a zip of `manifest.json`, `src/` and `icons/` attached to the run as an artifact. +3. **Merge.** The publish job compares the manifest version with the store: + - newer than the published and pending versions: uploads the zip and submits it for review + - already published or already in review: skips, with the reason in the job summary +4. **Google reviews the update.** It goes live automatically when approved (usually within a few days). +5. A **GitHub Release** `vX.Y.Z` is created with the submitted zip attached. + +Merges that only touch the landing page, docs or README never publish. The landing page has its own workflow (`deploy.yml`). + +## One-time setup + +You need your **Publisher ID** from the [Developer Dashboard](https://chrome.google.com/webstore/devconsole) under **Account โ†’ Publisher settings**. The publishing Google account must have 2-step verification turned on. + +Then pick **one** of the two auth methods below. + +### Option A: Service account (recommended) + +Service account keys don't expire, and they aren't tied to your personal Google login. + +1. In the [Google Cloud Console](https://console.cloud.google.com), create or pick a project and **enable the "Chrome Web Store API"**. +2. Go to **IAM & Admin โ†’ Service accounts** and create a service account. It doesn't need any IAM roles. +3. Open the service account, go to **Keys โ†’ Add key โ†’ Create new key โ†’ JSON**, and download the file. +4. In the Chrome Web Store [Developer Dashboard](https://chrome.google.com/webstore/devconsole), go to **Account**, find the service account section, and add the service account's email address. Only one service account can be added per publisher. +5. Add the secrets to the `chrome-web-store` environment (the commands are under [Add the GitHub secrets](#add-the-github-secrets)): + - `CWS_PUBLISHER_ID` + - `CWS_SERVICE_ACCOUNT_JSON`: the full contents of the JSON key file + +If your Google Cloud organization blocks service account key creation, use Option B. + +### Option B: OAuth client + refresh token + +1. In the Cloud Console, **enable the "Chrome Web Store API"**. +2. Configure the **OAuth consent screen** (External), then **publish the app to "In production"**. While the app is in "Testing", refresh tokens expire after 7 days and the pipeline starts failing. +3. Create an **OAuth client ID** of type *Web application* with the authorized redirect URI `https://developers.google.com/oauthplayground`. +4. Open the [OAuth Playground](https://developers.google.com/oauthplayground). Click the gear icon, tick **Use your own OAuth credentials**, and enter your client ID and secret. Authorize the scope `https://www.googleapis.com/auth/chromewebstore` with the publisher account, then click **Exchange authorization code for tokens** and copy the **refresh token**. +5. Add the secrets to the `chrome-web-store` environment: + - `CWS_PUBLISHER_ID` + - `CWS_CLIENT_ID` + - `CWS_CLIENT_SECRET` + - `CWS_REFRESH_TOKEN` + +### Add the GitHub secrets + +You can add them in **Settings โ†’ Environments โ†’ New environment โ†’ `chrome-web-store`**, or with the GitHub CLI: + +```bash +gh secret set CWS_PUBLISHER_ID --env chrome-web-store --repo YarooqH/tabstack +``` + +```bash +gh secret set CWS_SERVICE_ACCOUNT_JSON --env chrome-web-store --repo YarooqH/tabstack < path/to/service-account-key.json +``` + +Optional: +- **Required reviewers** on the `chrome-web-store` environment, to approve each store submission by hand before it runs. +- A repository **variable** `CWS_EXTENSION_ID` if the store item ID ever changes. It defaults to `pnjlcnpebjggdmkhbopnibjgechfbfjg`. + +Until the secrets exist, the publish job skips with a warning instead of failing. + +## Running it manually + +**Actions โ†’ Extension Build & Chrome Web Store Publish โ†’ Run workflow** on `master` offers two options: + +- **publish_type**: `STAGED_PUBLISH` holds the update after review approval until you click Publish in the dashboard. `DEFAULT_PUBLISH` (the default) goes live as soon as it's approved. +- **cancel_pending**: cancels an older version that is still in review and submits the current one instead. Without it, the job stops and tells you a submission is already pending. + +## Local commands + +```bash +node scripts/build-extension.mjs +``` + +This validates the extension and writes `dist/tabstack-.zip`. It needs the `zip` CLI. + +```bash +CWS_PUBLISHER_ID=... CWS_EXTENSION_ID=pnjlcnpebjggdmkhbopnibjgechfbfjg CWS_SERVICE_ACCOUNT_JSON="$(cat key.json)" node scripts/cws-publish.mjs check +``` + +This compares `manifest.json` with what's in the store and changes nothing. + +## What the pipeline does not update + +The API only uploads packages. Do these in the Developer Dashboard when they change: + +- Store listing text, screenshots and promo images +- **Privacy practices**: permission justifications and data-usage disclosures. For example, a newly added permission such as `unlimitedStorage` needs a justification before review. +- Distribution and visibility settings diff --git a/docs/images/tabstack-session-snapshots.png b/docs/images/tabstack-session-snapshots.png new file mode 100644 index 0000000..16c9956 Binary files /dev/null and b/docs/images/tabstack-session-snapshots.png differ diff --git a/landing/app.js b/landing/app.js index 5f0b0cc..170ddf2 100644 --- a/landing/app.js +++ b/landing/app.js @@ -455,11 +455,9 @@ function setupCompareSlider() { function setupStickyStorytelling() { const stepBlocks = document.querySelectorAll('.story-step-block'); - const visualPanes = { - 1: document.getElementById('visualPane-1'), - 2: document.getElementById('visualPane-2'), - 3: document.getElementById('visualPane-3') - }; + const visualPanes = Object.fromEntries( + [...document.querySelectorAll('.story-visual-pane')].map(pane => [pane.id.replace('visualPane-', ''), pane]) + ); if (!stepBlocks.length) return; diff --git a/landing/index.html b/landing/index.html index db7e92a..4ef6cfe 100644 --- a/landing/index.html +++ b/landing/index.html @@ -5,9 +5,9 @@ TabStack โ€” Make your tab bar usable again - + - + @@ -95,7 +95,7 @@

A clean tab bar
in one click.

- Native domain grouping, auto-collapsing stacks, and zero script injection. Free up memory and keep your browser fast. + Native domain grouping, auto-collapsing stacks, and zero script injection. Free up memory, and get back any window you close by mistake.

@@ -982,6 +982,13 @@

RAM Saver puts tabs to sleep

Background tabs automatically hibernate to free up memory, restoring instantly the moment you click back.

+ +
+ 04 +

Closed the wrong window? Get it back

+

TabStack saves every window the moment it closes and takes periodic snapshots. One click reopens all the tabs with their stacks, colors, and pins intact.

+
+ @@ -1150,6 +1157,63 @@

RAM Saver puts tabs to sleep

+ +
+
+
+ + YouTube + 8 +
+
+ + GitHub + 14 +
+
+ + Docs + 11 +
+
+ + Spotify + 7 +
+
+ +
+
+
+
+ Sessions + Saved locally +
+
+
+
+ Closed window + Yesterday, 11:42 PM ยท 40 tabs ยท 4 stacks +
+ Restore +
+
+
+ Auto snapshot + Today, 6:00 AM ยท 2 windows, 52 tabs +
+ Restore +
+
+
+ + 40 tabs back in a new window, stacks and pins intact +
+
+
+
+
+ @@ -1227,6 +1291,25 @@

Sleep idle stacks

Background groups collapse and sleep automatically, reclaiming memory used by idle pages.

+ +
  • +
    +
    +
    +
    + Closed window + Restore +
    + 40 tabs ยท 4 stacks saved +
    +
    + 04 / RESTORE +
    +
    +

    Never lose a window

    +

    Closed windows and periodic snapshots are saved on your device, ready to reopen in one click.

    +
    +
  • @@ -1256,7 +1339,7 @@

    What TabStack refuses to do

    Stores data remotely - All preferences and saved sessions stay on your local device. + Preferences, stashed stacks, and window snapshots stay on your device. Modifies URLs @@ -1288,11 +1371,11 @@

    Install TabStack

    AltShiftT - Stack now + Open TabStack
    AltShiftS - Sleep dormant stacks + Stack this window
    AltShiftA diff --git a/landing/privacy.html b/landing/privacy.html index 8462a64..22dc0fb 100644 --- a/landing/privacy.html +++ b/landing/privacy.html @@ -146,7 +146,7 @@
    @@ -97,6 +97,7 @@
    +
    @@ -132,6 +133,29 @@
    + +
    +
    +
    + Window snapshots + -- +
    + +
    + +
    + +
    + + +
    +
    diff --git a/src/popup/popup.js b/src/popup/popup.js index 8ffd609..e75d117 100644 --- a/src/popup/popup.js +++ b/src/popup/popup.js @@ -3,7 +3,7 @@ * Renders live tab stacks, search filtering, session stashing, whitelist manager, and quick actions */ -import { MESSAGE_TYPES } from '../shared/constants.js'; +import { MESSAGE_TYPES, SNAPSHOT_KINDS } from '../shared/constants.js'; import { getSettings, setSetting, removeStash } from '../shared/storage.js'; import { extractDomain, formatDomainTitle, getDomainColor } from '../background/utils.js'; import { initTheme, setTheme } from '../shared/theme.js'; @@ -16,6 +16,8 @@ let currentSettings = null; let activeFilterQuery = ''; let currentActiveDomain = null; let liveListenersAttached = false; +let snapshots = []; +const expandedSnapshotIds = new Set(); // DOM Elements const themeControl = document.getElementById('themeControl'); @@ -50,7 +52,15 @@ const currentDomainText = document.getElementById('currentDomainText'); const tabNavLive = document.getElementById('tabNavLive'); const tabNavStash = document.getElementById('tabNavStash'); const tabNavWhitelist = document.getElementById('tabNavWhitelist'); +const tabNavSessions = document.getElementById('tabNavSessions'); const stashCount = document.getElementById('stashCount'); +const sessionsCount = document.getElementById('sessionsCount'); + +const sessionsView = document.getElementById('sessionsView'); +const snapshotsList = document.getElementById('snapshotsList'); +const emptySnapshots = document.getElementById('emptySnapshots'); +const sessionsScheduleText = document.getElementById('sessionsScheduleText'); +const btnSnapshotNow = document.getElementById('btnSnapshotNow'); const whitelistCount = document.getElementById('whitelistCount'); const btnStackNow = document.getElementById('btnStackNow'); @@ -65,6 +75,9 @@ const toast = document.getElementById('toast'); async function init() { await initTheme(); + const brandVersion = document.getElementById('brandVersion'); + if (brandVersion) brandVersion.textContent = `v${chrome.runtime.getManifest().version}`; + // Get active window const currentWindow = await chrome.windows.getCurrent(); currentWindowId = currentWindow.id; @@ -86,6 +99,7 @@ async function init() { // Initial load await refreshData(); + await loadSnapshots(); } function updateThemeButtonsActiveState(theme) { @@ -180,6 +194,18 @@ function setupEventListeners() { tabNavLive.addEventListener('click', () => switchView('live')); tabNavStash.addEventListener('click', () => switchView('stash')); tabNavWhitelist.addEventListener('click', () => switchView('whitelist')); + tabNavSessions.addEventListener('click', async () => { + switchView('sessions'); + await loadSnapshots(); + }); + + btnSnapshotNow.addEventListener('click', async () => { + btnSnapshotNow.disabled = true; + const res = await chrome.runtime.sendMessage({ type: MESSAGE_TYPES.TAKE_SNAPSHOT }); + btnSnapshotNow.disabled = false; + showToast(res?.success ? `Saved ${res.snapshot.tabCount} tab(s)` : 'No tabs to save'); + await loadSnapshots(); + }); // Search input searchInput.addEventListener('input', (e) => { @@ -297,16 +323,18 @@ async function refreshData() { /** * Switches between views - * @param {'live'|'stash'|'whitelist'} view + * @param {'live'|'stash'|'whitelist'|'sessions'} view */ function switchView(view) { tabNavLive.classList.toggle('active', view === 'live'); tabNavStash.classList.toggle('active', view === 'stash'); tabNavWhitelist.classList.toggle('active', view === 'whitelist'); + tabNavSessions.classList.toggle('active', view === 'sessions'); liveView.classList.toggle('hidden', view !== 'live'); stashView.classList.toggle('hidden', view !== 'stash'); whitelistView.classList.toggle('hidden', view !== 'whitelist'); + sessionsView.classList.toggle('hidden', view !== 'sessions'); searchContainer.classList.toggle('hidden', view !== 'live'); } @@ -663,6 +691,187 @@ function renderStashes() { } } +const SNAPSHOT_LABELS = { + [SNAPSHOT_KINDS.CLOSED_WINDOW]: 'Closed window', + [SNAPSHOT_KINDS.AUTO]: 'Auto snapshot', + [SNAPSHOT_KINDS.MANUAL]: 'Saved snapshot', + [SNAPSHOT_KINDS.PREVIOUS_SESSION]: 'Before browser restart' +}; + +const INTERVAL_LABELS = { + 60: 'every hour', + 180: 'every 3 hours', + 360: 'every 6 hours', + 1440: 'every 24 hours', + 10080: 'every 7 days' +}; + +async function loadSnapshots() { + const res = await chrome.runtime.sendMessage({ type: MESSAGE_TYPES.GET_SNAPSHOTS }); + snapshots = res?.snapshots || []; + sessionsCount.textContent = snapshots.length; + renderSnapshots(); +} + +function formatSnapshotDate(isoString) { + const date = new Date(isoString); + const time = date.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' }); + const today = new Date(); + const yesterday = new Date(today); + yesterday.setDate(today.getDate() - 1); + + if (date.toDateString() === today.toDateString()) return `Today, ${time}`; + if (date.toDateString() === yesterday.toDateString()) return `Yesterday, ${time}`; + return `${date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })}, ${time}`; +} + +/** + * Names the most common sites in a snapshot so similar entries can be told apart + */ +function summarizeSnapshotSites(snapshot) { + const counts = new Map(); + for (const win of snapshot.windows) { + for (const tab of win.tabs) { + const domain = extractDomain(tab.url, currentSettings?.domainMode); + if (domain) counts.set(domain, (counts.get(domain) || 0) + 1); + } + } + const top = [...counts.entries()] + .sort((a, b) => b[1] - a[1]) + .map(([d]) => (/^[\d.]+$/.test(d) || d.includes(':') ? d : formatDomainTitle(d))); + if (top.length === 0) return ''; + return top.length > 3 ? `${top.slice(0, 3).join(', ')} +${top.length - 3}` : top.join(', '); +} + +function renderSnapshotScheduleText() { + if (!currentSettings?.snapshotsEnabled) { + sessionsScheduleText.textContent = 'Periodic snapshots off'; + return; + } + const interval = INTERVAL_LABELS[currentSettings.snapshotIntervalMinutes] || `every ${currentSettings.snapshotIntervalMinutes} min`; + sessionsScheduleText.textContent = `Auto ${interval}, keeps ${currentSettings.snapshotKeepCount}`; +} + +function renderSnapshots() { + renderSnapshotScheduleText(); + snapshotsList.innerHTML = ''; + emptySnapshots.classList.toggle('hidden', snapshots.length > 0); + + for (const snapshot of snapshots) { + const windowCount = snapshot.windows.length; + const isExpanded = expandedSnapshotIds.has(snapshot.id); + const sites = summarizeSnapshotSites(snapshot); + + const card = document.createElement('div'); + card.className = `snapshot-card ${isExpanded ? 'expanded' : ''}`; + card.innerHTML = ` +
    +
    + ${escapeHtml(SNAPSHOT_LABELS[snapshot.kind] || 'Snapshot')} + + ${escapeHtml(formatSnapshotDate(snapshot.createdAt))} ยท ${windowCount > 1 ? `${windowCount} windows, ` : ''}${snapshot.tabCount} tab${snapshot.tabCount === 1 ? '' : 's'} + + ${sites ? `${escapeHtml(sites)}` : ''} +
    +
    + + +
    + +
    +
    +
    +
    ${isExpanded ? renderSnapshotDetailsHtml(snapshot) : ''}
    + `; + + card.querySelector('.snapshot-header').addEventListener('click', (e) => { + if (e.target.closest('button')) return; + const details = card.querySelector('.snapshot-details'); + if (expandedSnapshotIds.has(snapshot.id)) { + expandedSnapshotIds.delete(snapshot.id); + card.classList.remove('expanded'); + details.innerHTML = ''; + } else { + expandedSnapshotIds.add(snapshot.id); + card.classList.add('expanded'); + details.innerHTML = renderSnapshotDetailsHtml(snapshot); + attachSnapshotDetailEvents(card, snapshot); + } + }); + + card.querySelector('.btn-restore-snapshot').addEventListener('click', () => restoreSnapshot(snapshot.id, null)); + + card.querySelector('.btn-delete-snapshot').addEventListener('click', async () => { + await chrome.runtime.sendMessage({ type: MESSAGE_TYPES.DELETE_SNAPSHOT, snapshotId: snapshot.id }); + expandedSnapshotIds.delete(snapshot.id); + showToast('Snapshot deleted'); + await loadSnapshots(); + }); + + if (isExpanded) attachSnapshotDetailEvents(card, snapshot); + snapshotsList.appendChild(card); + } +} + +function renderSnapshotDetailsHtml(snapshot) { + const multiWindow = snapshot.windows.length > 1; + + return snapshot.windows.map((win, index) => { + const groupsById = new Map((win.groups || []).map(g => [g.id, g])); + const tabsHtml = win.tabs.map(tab => { + const group = groupsById.get(tab.groupId); + return ` + + + ${escapeHtml(tab.title || tab.url)} + ${tab.pinned ? 'Pinned' : ''} + ${group ? `${escapeHtml(group.title || 'Group')}` : ''} + + `; + }).join(''); + + return ` +
    + ${multiWindow ? ` +
    + Window ${index + 1} ยท ${win.tabs.length} tab${win.tabs.length === 1 ? '' : 's'} + +
    + ` : ''} + ${tabsHtml} +
    + `; + }).join(''); +} + +function attachSnapshotDetailEvents(card, snapshot) { + card.querySelectorAll('.snapshot-details .tab-favicon').forEach(img => { + img.addEventListener('error', () => { + img.src = DEFAULT_FAVICON; + }, { once: true }); + }); + + card.querySelectorAll('.btn-restore-window').forEach(btn => { + btn.addEventListener('click', () => restoreSnapshot(snapshot.id, parseInt(btn.dataset.windowIndex, 10))); + }); + + // Open a single remembered tab in the current window + card.querySelectorAll('.snapshot-tab').forEach(link => { + link.addEventListener('click', async (e) => { + e.preventDefault(); + await chrome.tabs.create({ url: link.dataset.url, windowId: currentWindowId, active: true }); + }); + }); +} + +function restoreSnapshot(snapshotId, windowIndex) { + showToast('Restoring tabs...'); + // The new window takes focus and closes this popup; the service worker finishes the restore + chrome.runtime.sendMessage({ type: MESSAGE_TYPES.RESTORE_SNAPSHOT, snapshotId, windowIndex }); +} + /** * Render Whitelist in Popup */ diff --git a/src/shared/constants.js b/src/shared/constants.js index 7aeb3b8..9f0d377 100644 --- a/src/shared/constants.js +++ b/src/shared/constants.js @@ -29,7 +29,18 @@ export const DEFAULT_SETTINGS = { ], customDomainColors: {}, // e.g. { "github.com": "purple" } customDomainNames: {}, // e.g. { "github.com": "GitHub Projects" } - stashedSessions: [] // Array of saved stacks: [{ id, domain, title, color, date, tabs: [{ title, url, favIconUrl }] }] + stashedSessions: [], // Array of saved stacks: [{ id, domain, title, color, date, tabs: [{ title, url, favIconUrl }] }] + snapshotsEnabled: true, // Periodically save every open window so it can be restored later + snapshotIntervalMinutes: 360, // 60 | 180 | 360 | 1440 | 10080 + snapshotKeepCount: 24, // Number of periodic snapshots to keep + snapshotClosedWindows: true // Save a window's tabs when it is closed +}; + +export const SNAPSHOT_KINDS = { + AUTO: 'auto', + MANUAL: 'manual', + CLOSED_WINDOW: 'closed-window', + PREVIOUS_SESSION: 'previous-session' }; export const MESSAGE_TYPES = { @@ -44,5 +55,11 @@ export const MESSAGE_TYPES = { DELETE_STASH: 'DELETE_STASH', DISCARD_NOW: 'DISCARD_NOW', DISCARD_TAB: 'DISCARD_TAB', + GET_SNAPSHOTS: 'GET_SNAPSHOTS', + TAKE_SNAPSHOT: 'TAKE_SNAPSHOT', + RESTORE_SNAPSHOT: 'RESTORE_SNAPSHOT', + DELETE_SNAPSHOT: 'DELETE_SNAPSHOT', + CLEAR_SNAPSHOTS: 'CLEAR_SNAPSHOTS', + IMPORT_SNAPSHOTS: 'IMPORT_SNAPSHOTS', SETTINGS_UPDATED: 'SETTINGS_UPDATED' };