Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,36 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).

---

## [1.18.0] — 2026-11-02

### App bar: backup status in the sync badge
The sync badge now tells you whether `finlens-state.json` is up to date, not only whether a folder is connected. This is PR #23 rebuilt on the Clarity redesign: #23 put the status in the old sidebar, which the redesign removed, and its v1.17.0 number was never released.

- **Synced** — the last save worked and nothing is waiting. The tooltip gives the time and folder ("Saved at 10:42 AM to finlens-state.json in “FinLens Data”"). Click: opens **Settings → Import**.
- **Saving…** — new. Shows from a change until it's written: the 1.5 s wait, then the write. The pill turns neutral with a slowly pulsing dot (steady with reduced motion). It stays the same width as **Synced**, and a burst of edits keeps it on **Saving…** rather than flickering. Click: opens **Settings → Import**.
- **Not synced** — the existing label, now for three causes. The tooltip says which:
- **No folder:** changes are saved in this browser only. Click: opens **Settings → Import** to pick one.
- **Access lapsed:** the browser needs permission again. Click: **Reconnect** (asks for access), as the banner's button does.
- **The last save failed:** the tooltip gives the error. Click: **Retry**, which saves right away (`syncRetryClick()`). Before, this click only opened Settings.
- **Screen readers:** the button's name starts with the label and ends with what a click does ("Not synced, folder access lapsed. Reconnect folder"). A polite status region (`#syncStatus`) announces when backups stop or come back. It never announces **Saving…**, or **Synced** after an ordinary save.
- **How it's built:** `syncBadgeState()` (views-data.js) picks the state, label, tooltip, name and click in one place; `updateSyncBadge()` draws it and `syncBadgeClick()` runs its action, so the click always matches what the badge says. New `.sync.busy` style; colors are tokens, AA contrast.

### Persistence
- **Saves wait 1.5 seconds instead of 5.** Each change still restarts the wait, so a burst of edits makes one write. Your data reaches the browser's own storage at once either way; only the backup file waits (`SAVE_DELAY_MS`, `_saveStateDebounced()` in core.js).
- **Closing or reloading with a save still waiting asks first.** While a save is waiting or running and the folder is connected and writable, a `beforeunload` listener starts the save at once and asks the browser to confirm ("Leave site?"). The listener is attached only during that time (`backupWouldBeLost()`), so a page with nothing to save never has one. No folder, lapsed access and Start over never ask. Browsers show their own text and ask only after you've clicked or typed on the page.
- **Switching away saves right away.** When the tab is hidden (another tab, minimized), a waiting save runs immediately (`flushPendingSave()`).
- **Save now covers a waiting save.** Any immediate save cancels the scheduled one, since it writes everything as it is at that moment.
- **Kept as they were:** the Reconnect banner, `State._folderNeedsAccess`, `State._lastSaveError`, the folder-permission checks, and `State._resetInProgress`, which now also cancels a waiting save, so Start over can't re-create the file.

### Settings → Import
- **Auto-save** reads "1.5 seconds after a change".

### Docs
- **README:** the badge's states and clicks; saves 1.5 s after a change, on switching tabs, and the leave warning.
- **CLAUDE.md:** §1 version; §4.5 the save delay, save state, flush and leave warning; §6 the badge classes; §8 `flushPendingSave()`, `backupWouldBeLost()`; §9 the badge states; §12 the app bar; §14 the badge's clicks are the only new prompting code.

---

## [1.17.0] — 2026-11-02

### Settings → Database
Expand Down
40 changes: 31 additions & 9 deletions CLAUDE.md

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

> A zero-install, browser-native finance dashboard. Drop in your bank CSVs, get instant clarity on your money.

**Version:** v1.17.0  ·  **Stack:** Vanilla JS, HTML, CSS  ·  **Install:** None
**Version:** v1.18.0  ·  **Stack:** Vanilla JS, HTML, CSS  ·  **Install:** None

---

Expand Down Expand Up @@ -53,7 +53,7 @@ FinLens auto-detects which file is which based on filename and column headers. C

**3. Explore**

Use the top bar to move between views: Overview, Transactions, **Plan** (a menu with Budget, Buckets, Debt, Investments and Forecast), Trends and AI Analysis. Transactions has filter pills for Income, Spending, Bills, Payments and Transfers. On a phone or a narrow window they're in the **☰** menu. The calendar icon sets the date range for most views, and the bank icon picks which accounts to include. The **Synced** badge shows whether your changes are being saved to your folder.
Use the top bar to move between views: Overview, Transactions, **Plan** (a menu with Budget, Buckets, Debt, Investments and Forecast), Trends and AI Analysis. Transactions has filter pills for Income, Spending, Bills, Payments and Transfers. On a phone or a narrow window they're in the **☰** menu. The calendar icon sets the date range for most views, and the bank icon picks which accounts to include. The **Synced** badge shows whether your changes are being saved to your folder: **Saving…** right after a change, **Not synced** when there's no folder, its access has lapsed or a save failed. Hover it for the reason; clicking it reconnects, retries the save or opens **Settings → Import**.

---

Expand Down Expand Up @@ -88,7 +88,7 @@ FinLens stores all your data — budgets, bills, transaction edits, settings, AI

**How it works:**
1. When you pick a CSV folder (on the Welcome screen or in **Settings → Import**), FinLens begins auto-saving your complete state to `finlens-state.json` in that same folder.
2. Every 5 seconds (when you make changes), your dashboard state is written to this file. You can also click **Save now** in **Settings → Import** to force an immediate sync.
2. A moment after each change (1.5 seconds), your dashboard state is written to this file. The badge in the top bar says **Saving…** until it's written, then **Synced**. Switching to another tab saves right away, and if you close the tab while a save is still waiting, the browser asks first. You can also click **Save now** in **Settings → Import** to force an immediate sync.
3. On every page load, FinLens checks for `finlens-state.json` first — if it exists, your entire state (budgets, categories, overrides, settings, AI history) is restored instantly. If the file doesn't exist, it falls back to the browser's IndexedDB or localStorage.
4. Because the file lives on your computer (not in the browser), **it survives browser cache clearing**. Even if you clear all browser data, your `finlens-state.json` remains on your disk and will be restored on the next load.

Expand Down Expand Up @@ -263,4 +263,4 @@ See [CHANGELOG.md](CHANGELOG.md) for the full release history.

---

*FinLens v1.17.0 — Built for one person's finances, designed to be useful for anyone's.*
*FinLens v1.18.0 — Built for one person's finances, designed to be useful for anyone's.*
16 changes: 13 additions & 3 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -129,12 +129,18 @@
.menu a.active .t{color:var(--accent-strong-text)}
.menu a.active .d{color:var(--text-2)}
.appbar-tools{margin-left:auto;display:flex;align-items:center;gap:8px}
.sync{height:36px;display:inline-flex;align-items:center;gap:8px;padding:0 14px;margin-right:4px;border:0;border-radius:999px;font-size:13px;font-weight:600;white-space:nowrap}
/* min-width: "Synced" and "Saving…" are the same width, so the pill doesn't jump on every save */
.sync{height:36px;min-width:7.75em;display:inline-flex;align-items:center;justify-content:center;gap:8px;padding:0 14px;margin-right:4px;border:0;border-radius:999px;font-size:13px;font-weight:600;white-space:nowrap}
.sync .sdot{width:8px;height:8px;border-radius:50%;flex-shrink:0}
.sync.ok{background:var(--good-soft);color:var(--good-strong-text)}
.sync.ok .sdot{background:var(--good-dot)}
.sync.off{background:var(--warn-soft);color:var(--warn-strong-text)}
.sync.off .sdot{background:var(--warn)}
/* "Saving…" while a save waits or runs (v1.18.0): neutral, with a slow pulse on the dot */
.sync.busy{background:var(--muted);color:var(--text-2)}
.sync.busy .sdot{background:var(--accent)}
@media (prefers-reduced-motion:no-preference){.sync.busy .sdot{animation:sync-pulse 1.4s ease-in-out infinite}}
@keyframes sync-pulse{50%{opacity:.3}}
.pop-wrap{position:relative;display:flex}
.icon-btn{position:relative;width:40px;height:40px;display:grid;place-items:center;flex-shrink:0;border:1px solid var(--border);background:var(--surface);color:var(--text-2);border-radius:10px;cursor:pointer;text-decoration:none}
.icon-btn:hover{background:var(--surface-2);color:var(--text)}
Expand Down Expand Up @@ -1136,7 +1142,7 @@
</nav>

<div class="appbar-tools">
<button type="button" class="sync off" id="syncBadge"><span class="sdot"></span><span id="syncLabel">Not synced</span></button>
<button type="button" class="sync off" id="syncBadge"><span class="sdot" aria-hidden="true"></span><span id="syncLabel">Not synced</span></button>

<div class="pop-wrap">
<button type="button" class="icon-btn" id="rangeBtn" aria-haspopup="true" aria-expanded="false" aria-controls="rangePop" aria-label="Date range" title="Date range">
Expand Down Expand Up @@ -1186,6 +1192,10 @@
</div>
</div>

<!-- announces when backups stop or come back (updateSyncBadge(), views-data.js); outside
.appbar-tools, which the first-run Welcome hides -->
<span class="sr-only" id="syncStatus" role="status" aria-live="polite"></span>

<nav class="mobile-menu" id="mobileMenu" aria-label="Main" hidden>
<a href="#overview" data-view="overview">Overview</a>
<a href="#transactions" data-view="transactions">Transactions</a>
Expand All @@ -1210,7 +1220,7 @@
<div class="folder-banner-wrap" id="folderBanner" hidden></div>
<div class="content" id="content"></div>
</main>
<footer class="appfoot">v1.17.0 · FinLens</footer>
<footer class="appfoot">v1.18.0 · FinLens</footer>

<!-- side drawer: transaction detail, bill and plan forms (ui.js openDrawer) -->
<div class="drawer-scrim" id="drawerScrim" onclick="closeDrawer()" hidden></div>
Expand Down
103 changes: 94 additions & 9 deletions js/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -210,8 +210,13 @@ async function loadStateFromFile() {
async function saveStateToFile(state) {
// "Start over" sets this so a pending debounced save can't re-create the file
// between the reset and the page reload.
if (State._resetInProgress) return false;
if (State._resetInProgress) { _cancelScheduledSave(); _notifySaveStatus(); return false; }
// This write serializes State as it is when it gets there, so it covers a save still waiting.
_cancelScheduledSave();
State._lastSaveError = '';
_savesRunning++;
State._saving = true;
_notifySaveStatus();
try {
const dirHandle = await idbGet('csvDirHandle');
State._folderLinked = !!dirHandle;
Expand Down Expand Up @@ -270,20 +275,100 @@ async function saveStateToFile(state) {
State._folderNeedsAccess = false;
if (typeof updateFolderBanner === 'function') updateFolderBanner();
}
if (typeof updateSyncBadge === 'function') updateSyncBadge();
return true;
} catch(e) {
State._lastSaveError = e.message;
console.warn('[FinLens] Failed to save state to file:', e.message);
if (typeof updateSyncBadge === 'function') updateSyncBadge();
State._lastSaveError = e.message || String(e);
console.warn('[FinLens] Failed to save state to file:', State._lastSaveError);
return false;
} finally {
_savesRunning = Math.max(0, _savesRunning - 1);
State._saving = _savesRunning > 0;
_notifySaveStatus();
}
}

// Debounced state file save (max 1 save per 5 seconds)
const _saveStateDebounced = debounce(async (state) => {
await saveStateToFile(state);
}, 5000);
/* ---------- Scheduled saves and leaving the page (v1.18.0) ---------- */
// lsSet() schedules a write of finlens-state.json SAVE_DELAY_MS after the last change.
// Each new change restarts the wait, so a burst of edits makes one write. Changes reach
// localStorage and IndexedDB at once; only the file waits.
// State._savePending: a write is waiting. State._saving: a write is running (a count,
// since a manual save can overlap the scheduled one). The sync badge shows "Saving…"
// for both (updateSyncBadge() in views-data.js).
const SAVE_DELAY_MS = 1500;
let _saveTimer = null;
let _savesRunning = 0;
let _leaveGuardOn = false;
let _leaveGuardHold = false; // true from a beforeunload until its prompt is answered

function _saveStateDebounced(state) {
if (State._resetInProgress) { _cancelScheduledSave(); _notifySaveStatus(); return; }
clearTimeout(_saveTimer);
State._savePending = true;
_saveTimer = setTimeout(() => { _saveTimer = null; State._savePending = false; saveStateToFile(state || State); }, SAVE_DELAY_MS);
_notifySaveStatus();
}

function _cancelScheduledSave() {
clearTimeout(_saveTimer);
_saveTimer = null;
State._savePending = false;
}

// Runs a waiting save now (tab hidden, page closing). Returns the save's promise, or null
// when nothing was waiting.
function flushPendingSave() {
if (!_saveTimer) return null;
return saveStateToFile(State);
}

// True when leaving now could leave finlens-state.json behind this browser's copy: a save
// is waiting or running, a folder is connected (a stored handle, State._folderLinked) and
// its access hasn't lapsed. With no folder, or access lapsed (the banner and badge already
// say backups are paused), there's nothing to wait for. Start over never asks.
function backupWouldBeLost() {
if (State._resetInProgress) return false;
if (!State._savePending && !State._saving) return false;
return !!State._folderLinked && !State._folderNeedsAccess;
}

// The leave warning. Browsers show their own "Leave site?" text, ignore custom messages,
// and ask only if the page has had a click or keypress. The flush starts the write at
// once; a closing page may not finish it, which is why the browser is asked to wait.
function _onBeforeUnload(e) {
if (!backupWouldBeLost()) return;
e.preventDefault();
e.returnValue = '';
// Keep this listener attached until the prompt is answered. The flush can finish before
// the browser decides to ask (a fast write completes in the event's microtasks), and
// removing the listener then cancels the prompt (seen in Chromium 153). A timer runs only
// after the prompt closes, so the guard catches up then if the user stays.
_leaveGuardHold = true;
setTimeout(() => { _leaveGuardHold = false; _syncLeaveGuard(); }, 0);
flushPendingSave();
}

// The beforeunload listener is attached only while backupWouldBeLost(), so a page with
// nothing to save never has one (an always-on listener can also keep a page out of the
// browser's back/forward cache).
function _syncLeaveGuard() {
const want = backupWouldBeLost();
if (want === _leaveGuardOn || (!want && _leaveGuardHold)) return;
_leaveGuardOn = want;
if (want) window.addEventListener('beforeunload', _onBeforeUnload);
else window.removeEventListener('beforeunload', _onBeforeUnload);
}

// Every change to the save or folder state ends here: the leave warning, then the badge.
function _notifySaveStatus() {
_syncLeaveGuard();
if (typeof updateSyncBadge === 'function') updateSyncBadge();
}

// Switching tabs or minimizing: write a waiting save now instead of waiting out the delay.
// A hidden tab usually keeps running long enough to finish.
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') flushPendingSave();
});

/* ---------- Folder + state-file maintenance (Settings → Data & reset) ---------- */
// Browsers only show a file-permission prompt during a user gesture, so the
Expand Down
Loading