diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ec7f01..83bb784 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,35 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). --- +## [1.17.0] — 2026-11-02 + +### Settings → Database +DB Inspector and DB Schema are back in the UI, as a seventh Settings tab. Since the sidebar's Database section was removed, they could only be opened with `showView()` from DevTools. This is PR #10's tab rebuilt on the Clarity redesign; its v1.11.0 version predates the redesign and was never released. + +- **Tab:** **Database**, last in the Settings tab bar, in plain text. It is part of the Settings tablist, so arrow keys, Home and End reach it, and it uses the same 1000px page as the other tabs. +- **Sub-tabs:** **DB Inspector** (opens first) and **DB Schema**, as a segmented tab control like Forecast's Savings / Investments (`.seg.tabs-seg`, `role="tab"`, `aria-selected`; arrow keys, Home and End). The one you picked is remembered for the session (`dbToolsTab`); nothing is saved. +- **How it's built:** the tab is the `db-tools` view in `views-db.js`. It renders the existing `db-inspector` or `db-schema` view into one `role="tabpanel"`. Both still open on their own with `showView()`, and so does `showView('changelog')`. +- **A Settings tab whose view isn't registered is hidden** instead of throwing when Settings opens. The Database tab lives in `views-db.js`, which v1.9.4 showed can stop loading partway through. The tab's code sits above the Changelog view's for the same reason. +- **Phones:** the Settings tab bar now scrolls the selected tab into view. Before, every render scrolled it back to the start, so a selected Data & reset or Database tab was off-screen at 390px. + +### DB Inspector +- **Clarity layout:** a panel with the store picker, search, **Clear search**, **Refresh** and the record count ("257 records found (257 total in store)"). Below it, the records in a `.tbl` table that scrolls sideways, with the Transactions screen's pager. The store's key is the first column; field names keep their case. Values are colored by type through `.dv-*` classes (dates, numbers, lists, true/false, null) instead of hard-coded legacy colors. +- **Re-reads the store on every visit.** Before, a second visit redrew the rows cached from the first load, so imports or clears made in between didn't show, and the count line was blank. It keeps the chosen store, search and page, and moves back to the last page if the store got smaller. +- **Picking a store reads it right away, and the search filters as you type.** **Load** is now **Refresh** (read the store again). **Clear** is now **Clear search**: it shows the whole store again instead of emptying the table. +- **The API key isn't shown.** Its `app_state` row says "Hidden: an API key is saved", and the search ignores its value, so typing can't reveal it. Before, the inspector printed the key in full (CLAUDE.md §13: never expose it). + +### DB Schema +- **One Clarity panel titled "Database schema".** It was titled "Database Schema & Inspector", from when one card held both; the inspector is its own sub-tab now. The legend is a `.legend` row in the same panel. +- **Colors come from the theme.** Each store's lines and text use a `.sch-*` class that reads the tokens (`--teal-2`/`--teal-text`, `--warn`/`--warn-text`, `--sky`/`--sky-text`, `--violet`/`--violet-text`). No hex, `rgba()`, `white` or legacy aliases, and no text faded with opacity. The diagram follows light and dark without a redraw. +- **Fits the 1000px Settings page** (872px wide). The relationship labels sit in the gaps between boxes, on a background, instead of over the boxes. The `app_state` key list wraps inside its box. Below 900px the diagram scrolls sideways inside its panel, and a note says so. +- **Text corrected:** the `app_state` key list matches the keys the code writes (`catRules`, not `categoryRules`; adds `recurring`, `cardDetails`, `sampleData`, `lastFolderName` and `csvAutoImportPaused`). `accounts.kind` gives the current kinds (`bank_checking|credit_card|…`). `import_log` lists `rowsRemoved` (leftover duplicate copies removed, since v1.8.1), which its records have. + +### Docs +- **README:** a Tip for **Settings → Database**; the Project Structure line for `views-db.js`. +- **CLAUDE.md:** §1 version; §3 file roles; §6 the Database classes; §12 the seventh Settings tab, its sub-tabs, the hidden-tab guard and view registrations; §19 the database views. + +--- + ## [1.16.27] — 2026-11-02 Minor fixes, grouped in one release (CLAUDE.md §0). diff --git a/CLAUDE.md b/CLAUDE.md index 0e88fdd..9c22731 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -59,7 +59,7 @@ Until then, this section is the rule. FinLens is a **single-origin, zero-build, vanilla JavaScript personal finance dashboard** that runs entirely in the browser. There is no server, no npm, no bundler, no framework, and no TypeScript. The entry point is `index.html`; everything else is a plain `.js` file in the `js/` folder. -**Current version:** v1.16.27 (updated in `index.html` footer, `README.md`, and `CHANGELOG.md` on every release). +**Current version:** v1.17.0 (updated in `index.html` footer, `README.md`, and `CHANGELOG.md` on every release). **What it does:** Imports CSV exports from a bank (checking + savings) and credit cards, parses and normalizes them into a unified transaction model, and renders a multi-tab financial dashboard with budgeting, debt tracking, savings forecasting, investment planning, and Claude-powered AI analysis. @@ -124,7 +124,7 @@ FinLens/ ├── views-data.js ← Settings tabs Import, Accounts, Credit cards, Categories; folder + sync badge; sample data; Import Logs ├── views-settings.js ← Settings shell (tab bar) + General tab (display, Anthropic API key) ├── views-cleanup.js ← Settings → Data & reset: what's stored, clean up, JSON export/import, start over (§20) - ├── views-db.js ← DB Schema diagram, DB Inspector, Changelog views (developer only; Changelog reads CHANGELOG.md) + ├── views-db.js ← Settings → Database tab (DB Inspector, DB Schema sub-tabs); Changelog view (developer only; reads CHANGELOG.md) ├── views-eval.js ← AI Eval: grounding eval for AI Analysis (developer only, §21) └── init.js ← App boot IIFE — event wiring, DB.open(), DB.loadAll(), first render ``` @@ -495,6 +495,15 @@ Use `--on-solid` for text on any solid fill, never `#fff`, so a dark theme can s body[data-view="settings"], body.first-run — Settings and the Welcome are 1000px wide; a first run hides the app bar's nav and tools ``` +**Settings → Database (v1.17.0)** adds: + +``` +.tbl.db-tbl .insp-store .dv-null/.dv-hidden/.dv-date/.dv-arr/.dv-num/.dv-obj/.dv-true/.dv-false — DB Inspector's raw table and its values by type +.sch (the schema SVG) .sch-teal/.sch-warn/.sch-sky/.sch-violet/.sch-neutral (set --c for lines and --ct for text; warn uses --warn-strong-text) + .box-bg .box .band .rule .stripe .st-name .st-kind .f-name .f-type .f-note .st-note .badge(.pk) .badge-t(.pk) .rel .rel-head .rel-bg .rel-t — its shapes and text +.sch-scroll .sch-hint .sch-legend .key-badge(.pk) .sch-opt — the diagram's scroll box, its phone note and legend +``` + Prefer these over inline styles. Keep touch targets ≥ 44px where feasible (`@media (pointer:coarse)` raises pills and remove buttons). --- @@ -905,8 +914,9 @@ FinLens · Overview · Transactions · Plan ▾ · Trends · AI Analysis [S Transactions has filter pills: All · Income · Spending · Bills · Payments · Transfers (All and Payments filter the list; the other four open registered views — see below) Forecast has sub-tabs: Savings · Investments -Gear → Settings, with tabs: General · Import · Accounts · Credit cards · Categories · Data & reset - (General holds About (the version) and Anthropic API key; all clearing/reset lives in Data & reset) +Gear → Settings, with tabs: General · Import · Accounts · Credit cards · Categories · Data & reset · Database + (General holds Display and Anthropic API key; all clearing/reset lives in Data & reset; + Database has sub-tabs: DB Inspector · DB Schema) ``` - **Right side:** the sync badge, then the date-range and accounts icon buttons (each opens a popover), then the Settings gear. There is no theme button or theme setting (light only for now). @@ -916,6 +926,8 @@ Gear → Settings, with tabs: General · Import · Accounts · Credit cards · C - **Page title:** the shell renders it (`#pageTitle` from the registered title, `#rangeLabel` the range). Views never render their own H1. On screens that ignore the date range (`NO_RANGE_VIEWS`: the five Plan screens, Trends, Settings and the developer views) `showView()` hides `#rangeLabel` (v1.15.0, v1.16.0, v1.16.27). A new view that ignores the range goes in that list. The Welcome rewords the title with `shellHero()` instead of adding an H1. - **The Welcome (v1.16.0)** is the Overview with no transactions (`renderWelcome()` in views-main.js). On a true first run (`isFirstRun()`: no folder, plans, AI history or key) the app bar shows only the brand. Its buttons call the existing import paths from their click: `pickDataFolder()` (`reloadDataFiles()` when a folder is connected), `loadSampleData()`, and `#filePick`. - **Settings (v1.16.0)** is a `role="tablist"` (arrow keys, Home, End) and one `role="tabpanel"`; each tab is a registered view rendered into it. Fields save when you leave them (`change`) and report in a `.status-line`; destructive buttons ask for a second click. A screen's buttons and one-line note go in a `.page-actions` row at the top (`pageActions()` in views-main.js). + - **A tab whose view isn't registered is hidden** (its file failed to load) instead of throwing; Settings falls back to General. On a phone the tab bar scrolls the selected tab into view on every render (v1.17.0). + - **Database (v1.17.0)** is the `db-tools` view: a `.seg.tabs-seg` tablist (DB Inspector · DB Schema; arrow keys, Home, End) and one `role="tabpanel"` that the `db-inspector` or `db-schema` view renders into. `dbToolsTab` remembers the choice for the session only, like `forecastTab`. **Transactions pills (v1.14.0).** `renderTxPills(root, current)` draws the row on all five screens. **All** and **Payments** set `txPillFilter` and show the `transactions` view, which lists one or the other. **Income**, **Spending**, **Bills** and **Transfers** set `txPillFilter` and open the registered views `income`, `spending`, `bills`, `transfers` (titles "Income", "Spending", "Bills & subscriptions", "Transfers"). The Transactions view treats any other `txPillFilter` as All, so the app bar link always lands on the list. `TX_VIEWS` (ui.js) keeps Transactions underlined on all five. @@ -928,7 +940,7 @@ View registrations by file: - `views-data.js` — import, accounts, credit-cards, categories (Settings tabs); db-logs (Import Logs, not in nav) - `views-settings.js` — settings (internal use only, not in nav) - `views-cleanup.js` — data-cleanup (Settings → Data & reset tab) -- `views-db.js` — db-inspector, db-schema, changelog (not in nav; developer reference only) +- `views-db.js` — db-tools (Settings → Database tab), db-inspector, db-schema, changelog. Only db-tools is reachable from the UI; all four also open with `showView()` from DevTools. - `views-eval.js` — ai-eval (not in nav; developer only — `showView('ai-eval')` from DevTools, §21) ### Nav label and icon rule (replaces the emoji rule, v1.13.0) @@ -1121,11 +1133,11 @@ Multiple credit card files can be loaded simultaneously. Each gets a unique `acc --- -*Last updated: v1.16.27 — 2026-11-02 (§9 and §12 the developer views are in `NO_RANGE_VIEWS`; §14 the tab's name is Data & reset; §20 a render partway through an action keeps its button's done label (`DataCleanup.running`); v1.16.26: the type decides whether a transaction is a transfer: §4.1 the drawers note, a type changed away from Transfer; §8 the sums go by type, `ownCategories()`, `withoutDirection()`, `redetectTransfers()`; §11 the type decides, Transfer out / in only on transfers, a type change re-runs detection; §11.1 a retyped autopay's card payment; §13 the summary's totals go by type; v1.16.25: Re-categorize all is saved: §1 version; §4.1 `ruleCategories`; §4.2 categories; §8 `categoryFromRules()`; §9 `recategorizeAll()`; §20 where `ruleCategories` is kept, what clears it, left out of the JSON export; v1.16.24: a transfer that stops being one gets its own type and category back: §8 `undoTransferDetection()`, §11 un-transferring; v1.16.23: transfer detection respects the user's type and categories: §1 version, §4.1 the drawers note, §11 the user's edit wins; v1.16.22: §13 the AI summary's trend stops at a past period's end, subscriptions labelled current; §21 the parser finds sections by their heading's start; v1.16.21: §8 `overrideBalanceAt()`, `balanceAt()`; §18 a card's amount owed is taken back plus the later transactions, a bank balance minus them; the sign of a card's balance; v1.16.20: §18 a balance override at the end of every range is the override less the later transactions, no 7-day exception; v1.16.19: overlapping exports of one account count each shared row once: §4.5 one transaction per id; §8 `mergeImported()`, `importParsedCsv()`; §10 overlapping exports of one account; §19 the leftover-copy check keeps the import's ids; v1.16.18: a JSON import's transaction edits show at once: §9 `applyImportedEdits()`; §20 what takes effect without a reload; v1.16.17: a file read into another account takes its rows with it: §4.3 the account's `files`, `accountFiles()`; §4.5 the exception to an import never dropping rows; §8 `accountFiles()`, `earlierCopies()`, `moveEarlierCopies()`; §10 Read as changes the ids; §19 `DB.removeTransactions()`, `DB.patchAccount()`; §22 `_rekey()` is also used by imports; v1.16.16: the transaction and transfer drawers store only the fields you change: §4.1 TxOverride, §11 transfer keywords, §12 state mutations; v1.16.15: §1 desktop only; §3 `views-database.js` removed, the Changelog view reads CHANGELOG.md; §6, §18, §19 point to the current screens; v1.16.14: §9 the drawer is a modal dialog: inert page, Tab wraps, first field focused, focus returns after a re-render; v1.16.13: account order: §4.1 `accountOrder` keeps ids not loaded; §8 `orderedAccounts()`; §18 display order; v1.16.12: account names: §4.1 `accountLabels`; §4.3 an account's `name` is its default; §8 `defaultAccountName()`; §9 `acctName()`; §13 the summary lists accounts by `acctName()`; §18 names you type, and clearing them; v1.16.11: AI summary balances at the end of the selected period: §13 `summaryBalanceEnd()` and the date notes; §21 the parser reads the balance lines by how they start; v1.16.10: starting balance counted in every range: §8 `startingBalance()`, `currentBalances()`; §13 summary balances; §18 one balance rule; v1.16.9: the transaction drawer stores only the flags you change: §4.2 flags, §12 state mutations; v1.16.8: flags from transaction rules are worked out on load, never read from storage: §4.2 flags, §8 `txRuleFlag()` / `txFlags()` / `applyTxRulesToAll()`, §19 flags in the transactions store; v1.16.7: transaction links to budgets, buckets and debts by id: §1 version; §3 migrate.js role; §4.1 the `id` fields, TxOverride and its `link` shape; §8 `PLAN_LINK_TYPES`, `newPlanId()`; §9 `planItem()`, `linkedTransactions()`, `unlinkPlanItems()`, `ensurePlanIds()`; §20 clearing budgets, buckets or debts removes their links; §22 the plan-link migration; v1.16.6: JSON export carries account names and order, Read as, flag rules, transfer keywords and theme: §9 `JSON_EXPORT_KEYS`; §12 adding a persisted field; §20 what the export holds; v1.16.5: a new database copies every saved setting: §4.5 the keys that go through `storageKey()`; §12 adding a persisted field; §19 `DB.APP_STATE_KEYS`; v1.16.4: JSON import saves under the storage keys: §4.5 `STORAGE_KEYS` / `storageKey()`; §8 `storageKey()`; §12 adding a persisted field uses the State name; v1.16.3: An import keeps the loaded transactions it doesn't replace: §4.5 an import never drops loaded transactions; §8 `mergeImported()`, `undoTransferDetection()`; §10 memory follows the same re-upload rules; §11 kept transfers are detected again; v1.16.2: Imports read every file before changing anything: §8 `loadFiles()` options and result, `parseCsvFile()` reads only, `importParsedCsv()`, `importProblemText()`, `reloadFromDirHandle()`; §20 Rebuild from your folder reads before it clears, read before clearing; v1.16.1: Clear transaction edits works from memory: §4.2 `_originalCategories`, `_originalType` and what a transaction keeps of its row; §4.5 IndexedDB may not hold the loaded transactions; §10 a stored row holds the CSV's values; §20 Clear transaction edits; v1.16.0: Trends, AI Analysis, Settings and the Welcome rebuilt: §3 file roles; §4.1 `cardDetails`, `sampleData`, AI history `model`; §6 tile tokens and Insights/Settings/Welcome components; §7 rule 7 covers Trends; §8 `loadFiles()` sample option; §9 `shellHero()`, `NO_RANGE_VIEWS`, ☰ → ×, JSON export/import buttons; §12 Settings tabs renamed, the Welcome, range label hidden on Trends and Settings; §13 quick analyses, tab state, history; §20 new fields, Use my own files, Export/Import JSON; §21 quick analyses send `AI_PROMPTS`; v1.15.0: Plan screens rebuilt: §3 file roles; §4.1 `debtPlan` and the Budget / Bucket / Debt / Scenario shapes; §6 `--teal-text` and Plan components; §7 rule 7 covers the Plan charts; §8 plan helpers (`payoffPlan()`, `growthByYear()` …); §9 plan form helpers, `simulatePayoff()` kept unused; §12 Plan titles, Forecast tabs, range label hidden on Plan screens; §13 debt balances in the summary; §20 Clear forecast scenarios / investment mix, Clear debts resets `debtPlan`; v1.14.0: Finances screens rebuilt: §4.1 Bill shape and `recurringConfirmed`; §6 new tokens and Finances components; §7 rule 7 inline SVG charts; §8 new aggregation helpers; §9 drawer, `TX_VIEWS`, SVG/heatmap/format helpers, bill helpers, removed renderers; §11 keywords re-run detection, `transferPairs()`, card payments; §12 page actions and Transactions pills; §20 Clear bills also clears spotted-charge choices; v1.13.0: Clarity redesign — §6 tokens and components; §9 theme, chart colors and app bar helpers; §12 app bar navigation replaces the sidebar and the emoji rule; §17 footer; §20 Data & Reset; v1.12.0: bank-neutral account codes, names, samples and docs; §22 `migrate.js` added; §3, §4, §5, §10, §18, §21 updated; v1.10.5: no section changes: Import Logs race fix; v1.10.4: §8, §13 single `~` is literal; §21 excerpts escape `~`; v1.10.3: §13 refusals; §21 declined runs; v1.10.2: §13 summary states its dates; §21 per-month derivations; v1.10.1: §13 `AI_MAX_TOKENS`, thinking and cut-off answers; v1.10.0: §21 AI Eval added; §13 `callClaude()` raw mode; v1.9.6: §14 folder access lasts until the last tab closes, not one page load; v1.9.5: §7 chart guard; v1.9.4: views-db.js changelog reads CRLF checkouts; v1.9.3: §14 folder permission: re-request on click, Reconnect banner, browser copy wins; v1.9.2: §0 branch, PR and approval workflow added; v1.9.1: §4.5 rehydrate transactions loaded from JSON; v1.9.0: §20 Data & Reset added; v1.8.1: §10 re-upload dedup rewritten for the occurrence-suffix fix; v1.8.0: AI Analysis restored with API-key and output hardening; `renderMarkdown()` added; `samples/` added; §1–3, §13, §14, §17 corrected to match the code)* +*Last updated: v1.17.0 — 2026-11-02 (Settings → Database tab, DB Inspector and DB Schema rebuilt on Clarity: §1 version; §3 views-db.js role; §6 Database classes; §12 seventh Settings tab, its sub-tabs, the hidden-tab guard, the tab bar scrolling to the selected tab, view registrations; §19 database views; v1.16.27: §9 and §12 the developer views are in `NO_RANGE_VIEWS`; §14 the tab's name is Data & reset; §20 a render partway through an action keeps its button's done label (`DataCleanup.running`); v1.16.26: the type decides whether a transaction is a transfer: §4.1 the drawers note, a type changed away from Transfer; §8 the sums go by type, `ownCategories()`, `withoutDirection()`, `redetectTransfers()`; §11 the type decides, Transfer out / in only on transfers, a type change re-runs detection; §11.1 a retyped autopay's card payment; §13 the summary's totals go by type; v1.16.25: Re-categorize all is saved: §1 version; §4.1 `ruleCategories`; §4.2 categories; §8 `categoryFromRules()`; §9 `recategorizeAll()`; §20 where `ruleCategories` is kept, what clears it, left out of the JSON export; v1.16.24: a transfer that stops being one gets its own type and category back: §8 `undoTransferDetection()`, §11 un-transferring; v1.16.23: transfer detection respects the user's type and categories: §1 version, §4.1 the drawers note, §11 the user's edit wins; v1.16.22: §13 the AI summary's trend stops at a past period's end, subscriptions labelled current; §21 the parser finds sections by their heading's start; v1.16.21: §8 `overrideBalanceAt()`, `balanceAt()`; §18 a card's amount owed is taken back plus the later transactions, a bank balance minus them; the sign of a card's balance; v1.16.20: §18 a balance override at the end of every range is the override less the later transactions, no 7-day exception; v1.16.19: overlapping exports of one account count each shared row once: §4.5 one transaction per id; §8 `mergeImported()`, `importParsedCsv()`; §10 overlapping exports of one account; §19 the leftover-copy check keeps the import's ids; v1.16.18: a JSON import's transaction edits show at once: §9 `applyImportedEdits()`; §20 what takes effect without a reload; v1.16.17: a file read into another account takes its rows with it: §4.3 the account's `files`, `accountFiles()`; §4.5 the exception to an import never dropping rows; §8 `accountFiles()`, `earlierCopies()`, `moveEarlierCopies()`; §10 Read as changes the ids; §19 `DB.removeTransactions()`, `DB.patchAccount()`; §22 `_rekey()` is also used by imports; v1.16.16: the transaction and transfer drawers store only the fields you change: §4.1 TxOverride, §11 transfer keywords, §12 state mutations; v1.16.15: §1 desktop only; §3 `views-database.js` removed, the Changelog view reads CHANGELOG.md; §6, §18, §19 point to the current screens; v1.16.14: §9 the drawer is a modal dialog: inert page, Tab wraps, first field focused, focus returns after a re-render; v1.16.13: account order: §4.1 `accountOrder` keeps ids not loaded; §8 `orderedAccounts()`; §18 display order; v1.16.12: account names: §4.1 `accountLabels`; §4.3 an account's `name` is its default; §8 `defaultAccountName()`; §9 `acctName()`; §13 the summary lists accounts by `acctName()`; §18 names you type, and clearing them; v1.16.11: AI summary balances at the end of the selected period: §13 `summaryBalanceEnd()` and the date notes; §21 the parser reads the balance lines by how they start; v1.16.10: starting balance counted in every range: §8 `startingBalance()`, `currentBalances()`; §13 summary balances; §18 one balance rule; v1.16.9: the transaction drawer stores only the flags you change: §4.2 flags, §12 state mutations; v1.16.8: flags from transaction rules are worked out on load, never read from storage: §4.2 flags, §8 `txRuleFlag()` / `txFlags()` / `applyTxRulesToAll()`, §19 flags in the transactions store; v1.16.7: transaction links to budgets, buckets and debts by id: §1 version; §3 migrate.js role; §4.1 the `id` fields, TxOverride and its `link` shape; §8 `PLAN_LINK_TYPES`, `newPlanId()`; §9 `planItem()`, `linkedTransactions()`, `unlinkPlanItems()`, `ensurePlanIds()`; §20 clearing budgets, buckets or debts removes their links; §22 the plan-link migration; v1.16.6: JSON export carries account names and order, Read as, flag rules, transfer keywords and theme: §9 `JSON_EXPORT_KEYS`; §12 adding a persisted field; §20 what the export holds; v1.16.5: a new database copies every saved setting: §4.5 the keys that go through `storageKey()`; §12 adding a persisted field; §19 `DB.APP_STATE_KEYS`; v1.16.4: JSON import saves under the storage keys: §4.5 `STORAGE_KEYS` / `storageKey()`; §8 `storageKey()`; §12 adding a persisted field uses the State name; v1.16.3: An import keeps the loaded transactions it doesn't replace: §4.5 an import never drops loaded transactions; §8 `mergeImported()`, `undoTransferDetection()`; §10 memory follows the same re-upload rules; §11 kept transfers are detected again; v1.16.2: Imports read every file before changing anything: §8 `loadFiles()` options and result, `parseCsvFile()` reads only, `importParsedCsv()`, `importProblemText()`, `reloadFromDirHandle()`; §20 Rebuild from your folder reads before it clears, read before clearing; v1.16.1: Clear transaction edits works from memory: §4.2 `_originalCategories`, `_originalType` and what a transaction keeps of its row; §4.5 IndexedDB may not hold the loaded transactions; §10 a stored row holds the CSV's values; §20 Clear transaction edits; v1.16.0: Trends, AI Analysis, Settings and the Welcome rebuilt: §3 file roles; §4.1 `cardDetails`, `sampleData`, AI history `model`; §6 tile tokens and Insights/Settings/Welcome components; §7 rule 7 covers Trends; §8 `loadFiles()` sample option; §9 `shellHero()`, `NO_RANGE_VIEWS`, ☰ → ×, JSON export/import buttons; §12 Settings tabs renamed, the Welcome, range label hidden on Trends and Settings; §13 quick analyses, tab state, history; §20 new fields, Use my own files, Export/Import JSON; §21 quick analyses send `AI_PROMPTS`; v1.15.0: Plan screens rebuilt: §3 file roles; §4.1 `debtPlan` and the Budget / Bucket / Debt / Scenario shapes; §6 `--teal-text` and Plan components; §7 rule 7 covers the Plan charts; §8 plan helpers (`payoffPlan()`, `growthByYear()` …); §9 plan form helpers, `simulatePayoff()` kept unused; §12 Plan titles, Forecast tabs, range label hidden on Plan screens; §13 debt balances in the summary; §20 Clear forecast scenarios / investment mix, Clear debts resets `debtPlan`; v1.14.0: Finances screens rebuilt: §4.1 Bill shape and `recurringConfirmed`; §6 new tokens and Finances components; §7 rule 7 inline SVG charts; §8 new aggregation helpers; §9 drawer, `TX_VIEWS`, SVG/heatmap/format helpers, bill helpers, removed renderers; §11 keywords re-run detection, `transferPairs()`, card payments; §12 page actions and Transactions pills; §20 Clear bills also clears spotted-charge choices; v1.13.0: Clarity redesign — §6 tokens and components; §9 theme, chart colors and app bar helpers; §12 app bar navigation replaces the sidebar and the emoji rule; §17 footer; §20 Data & Reset; v1.12.0: bank-neutral account codes, names, samples and docs; §22 `migrate.js` added; §3, §4, §5, §10, §18, §21 updated; v1.10.5: no section changes: Import Logs race fix; v1.10.4: §8, §13 single `~` is literal; §21 excerpts escape `~`; v1.10.3: §13 refusals; §21 declined runs; v1.10.2: §13 summary states its dates; §21 per-month derivations; v1.10.1: §13 `AI_MAX_TOKENS`, thinking and cut-off answers; v1.10.0: §21 AI Eval added; §13 `callClaude()` raw mode; v1.9.6: §14 folder access lasts until the last tab closes, not one page load; v1.9.5: §7 chart guard; v1.9.4: views-db.js changelog reads CRLF checkouts; v1.9.3: §14 folder permission: re-request on click, Reconnect banner, browser copy wins; v1.9.2: §0 branch, PR and approval workflow added; v1.9.1: §4.5 rehydrate transactions loaded from JSON; v1.9.0: §20 Data & Reset added; v1.8.1: §10 re-upload dedup rewritten for the occurrence-suffix fix; v1.8.0: AI Analysis restored with API-key and output hardening; `renderMarkdown()` added; `samples/` added; §1–3, §13, §14, §17 corrected to match the code)* --- -## 19. IndexedDB Architecture (v1.4.0) + Database Views (v1.4.1) +## 19. IndexedDB Architecture (v1.4.0) + Database Views (v1.4.1, in Settings → Database since v1.17.0) The full IndexedDB implementation is live. See **`docs/archive/INDEXEDDB_PLAN.md`** for the original spec. @@ -1144,6 +1156,14 @@ The full IndexedDB implementation is live. See **`docs/archive/INDEXEDDB_PLAN.md ### Adding a new bank Add a new object to `BANK_SCHEMAS` in `core.js`. No other code changes needed if the bank follows standard column conventions (`date`, `amount`, `description`). For non-standard conventions use: `amountSign: 'inverted'`, custom `columns` map, `dateFormat` (`'YYYY-MM-DD'` | `'MM/DD/YYYY'` | `'DD/MM/YYYY'`), and `postDateFormat` if the post-date column uses a different format than the primary date column (see the `credit_card` schema). +### Database views (views-db.js, Settings → Database since v1.17.0) +- **DB Inspector** (`db-inspector`) reads one store with `getAll()` and shows it 50 records a page, the store's keyPath first. Its state lives on the `DBInspector` object, in memory only: store, search, page and the records last read. + - **It re-reads the store on every render**, keeping the store, search and page; a page past the end moves back to the last one. The read runs after the render (`setTimeout`), and it looks its elements up again afterwards, because the view may have been left. + - **Read-only.** Picking a store reads it; the search matches each record's JSON as you type; Refresh reads the store again. + - **The API key is never shown.** Its `app_state` row says it's hidden, and the search skips its value (`DBInspector.isSecret()`, §13). +- **DB Schema** (`db-schema`) draws the five stores as inline SVG, 872px wide so it fits Settings' 1000px page. Colors come from `.sch-*` classes in `index.html` (§6), never from the script. The field lists and the `app_state` key list are written by hand: when a store or a saved key changes, update them. +- **Changelog** (`changelog` view) reads `CHANGELOG.md` each time it opens (`loadChangelog()`, v1.16.15); there is no embedded copy any more. + ### Deferred - Column Mapping UI for truly unknown CSV formats (show a modal when `detectSchema()` returns null). - Forecast Savings account-driven inputs (see §4 in INDEXEDDB_PLAN.md — separate task). diff --git a/README.md b/README.md index 0158a93..6708afa 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ > A zero-install, browser-native finance dashboard. Drop in your bank CSVs, get instant clarity on your money. -**Version:** v1.16.27  ·  **Stack:** Vanilla JS, HTML, CSS  ·  **Install:** None +**Version:** v1.17.0  ·  **Stack:** Vanilla JS, HTML, CSS  ·  **Install:** None --- @@ -143,7 +143,7 @@ Reference lists for learning, not financial advice. Type your own % next to nine Ask Claude about your finances: eight quick analyses (a monthly spending review, where to cut back, a subscription audit, a savings-rate check, a debt payoff plan, budget suggestions, a 12-month forecast and a summary) or your own question. Claude receives a text summary of your balances, income and spending by category for the dates on screen, the monthly trend up to their end, and your current debts and subscriptions, never your CSV files. Answers can be copied or saved as Markdown, and a cut-off answer says so. History keeps up to 50 answers in your browser; open any of them again, or export them all as Markdown. Requires your own [Anthropic API key](https://console.anthropic.com). ### Settings -Six tabs: **General** (theme and your API key), **Import** (your CSV folder, how each file is read and the import log), **Accounts** (names, display order and starting balances), **Credit cards** (balance, credit limit, APR and payment due day), **Categories** (add or delete; deleting moves a category's transactions to Other) and **Data & reset** (what's stored, clean up, JSON export and import, start over). +Seven tabs: **General** (theme and your API key), **Import** (your CSV folder, how each file is read and the import log), **Accounts** (names, display order and starting balances), **Credit cards** (balance, credit limit, APR and payment due day), **Categories** (add or delete; deleting moves a category's transactions to Other), **Data & reset** (what's stored, clean up, JSON export and import, start over) and **Database** (DB Inspector and DB Schema, for looking at the raw data). --- @@ -226,7 +226,7 @@ FinLens/ ├── views-data.js ← Settings tabs Import, Accounts, Credit cards, Categories; sample data; Import Logs ├── views-settings.js ← Settings shell + General tab (display, API key) ├── views-cleanup.js ← Settings → Data & reset (clean up data, export/import JSON, start over) - ├── views-db.js ← DB Inspector, DB Schema diagram, Changelog views + ├── views-db.js ← Settings → Database (DB Inspector, DB Schema diagram); Changelog view ├── views-eval.js ← AI Eval: grounding eval for AI Analysis (developer view) └── init.js ← App boot and event wiring ``` @@ -251,6 +251,8 @@ FinLens/ - **Export or import JSON:** your plans, transaction edits and rules, account names, order and balances, card details, categories, transfer keywords and AI history in one file (no transactions, no API key). Older exports still import; anything they don't have stays as it is. - **Start over from scratch:** type `RESET` to erase everything and reload. Your backup file is either kept as `finlens-state-backup-DDMMYYYY.json` or deleted, your choice. Your CSV files are never touched. +**Looking at the raw data** — **Settings → Database** has two sub-tabs. **DB Inspector** browses each IndexedDB store, read-only and searchable; your API key is never shown. **DB Schema** diagrams the five stores and how they link. + **Exporting** — the Transactions screen has an **Export CSV** button: it exports every transaction in the current date range and accounts. AI answers can be saved as Markdown from the AI Analysis tab, one at a time or the whole history. --- @@ -261,4 +263,4 @@ See [CHANGELOG.md](CHANGELOG.md) for the full release history. --- -*FinLens v1.16.27 — Built for one person's finances, designed to be useful for anyone's.* +*FinLens v1.17.0 — Built for one person's finances, designed to be useful for anyone's.* diff --git a/index.html b/index.html index f6b272f..c59bc09 100644 --- a/index.html +++ b/index.html @@ -1002,6 +1002,52 @@ .radio-set label{display:flex;align-items:center;gap:10px;min-height:36px;font-size:14px;cursor:pointer;overflow-wrap:anywhere} .radio-set input{width:18px;height:18px;margin:0;flex-shrink:0;accent-color:var(--accent)} .field .input.reset-in{width:200px;font-weight:600;letter-spacing:.08em} +/* Settings → Database (v1.17.0): DB Inspector table, DB Schema diagram */ +.tbl.db-tbl{font-size:13px} +.tbl.db-tbl th,.tbl.db-tbl td{max-width:240px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding:10px;text-transform:none;letter-spacing:0} +.form-row .field.insp-store{flex:0 1 200px} +.tbl.db-tbl thead th{text-transform:none;letter-spacing:0;font:500 12px 'DM Mono',ui-monospace,monospace;color:var(--text-2)} +.tbl.db-tbl tbody th{font:500 12.5px 'DM Mono',ui-monospace,monospace;color:var(--text);text-align:left;border-bottom:1px solid var(--divider)} +.tbl.db-tbl tr:hover th{background:var(--surface-2)} +.tbl.db-tbl tbody tr:last-child>*{border-bottom:0} +.tbl.db-tbl th:first-child,.tbl.db-tbl td:first-child{padding-left:24px} +.tbl.db-tbl th:last-child,.tbl.db-tbl td:last-child{padding-right:24px} +.dv-null,.dv-hidden{color:var(--text-3);font-style:italic} +.dv-date{color:var(--teal-text)} .dv-arr{color:var(--violet-text)} .dv-num{color:var(--sky-text);font-variant-numeric:tabular-nums} +.dv-obj{color:var(--text-2);font:12px 'DM Mono',ui-monospace,monospace} +.dv-true{color:var(--good-text)} .dv-false{color:var(--text-3)} +/* the schema: each store's .sch-* sets --c (lines, fills) and --ct (text) from the theme */ +.sch-teal{--c:var(--teal-2);--ct:var(--teal-text)} .sch-warn{--c:var(--warn);--ct:var(--warn-strong-text)} +.sch-sky{--c:var(--sky);--ct:var(--sky-text)} .sch-violet{--c:var(--violet);--ct:var(--violet-text)} +.sch-neutral{--c:var(--text-3);--ct:var(--text-2)} +.sch-scroll{border-radius:var(--radius-sm)} +.sch-scroll:focus-visible{outline:2px solid var(--accent-border);outline-offset:2px} +svg.sch{display:block;font-family:'DM Mono',ui-monospace,Menlo,monospace} +.sch .box-bg{fill:var(--surface)} +.sch .box{fill:none;stroke:var(--c);stroke-width:1.5} +.sch .band{fill:color-mix(in srgb,var(--c) 12%,var(--surface))} +.sch .rule{stroke:var(--c);stroke-opacity:.5} +.sch .stripe{fill:var(--surface-2)} +.sch .st-name{fill:var(--ct);font-size:13px;font-weight:500} +.sch .st-kind{fill:var(--text-3);font-size:10px} +.sch .f-name{fill:var(--text);font-size:12px} +.sch .f-type{fill:var(--text-3);font-size:10.5px;font-style:italic} +.sch .f-note{fill:var(--ct);font-size:10px} +.sch .st-note{fill:var(--text-3);font-size:10px;font-style:italic} +.sch .badge{fill:var(--muted)} +.sch .badge.pk{fill:color-mix(in srgb,var(--c) 16%,var(--surface));stroke:var(--c)} +.sch .badge-t{fill:var(--text-2);font:700 9px 'Inter',system-ui,sans-serif} +.sch .badge-t.pk{fill:var(--ct)} +.sch .rel{fill:none;stroke:var(--c);stroke-width:1.5;stroke-dasharray:5 3} +.sch .rel-head{fill:var(--c)} +.sch .rel-bg{fill:var(--surface)} +.sch .rel-t{fill:var(--ct);font-size:10px} +.key-badge{display:inline-block;padding:1px 6px;border:1px solid transparent;border-radius:4px;background:var(--muted);color:var(--text-2);font-size:10px;font-weight:700;line-height:14px} +.key-badge.pk{background:color-mix(in srgb,var(--c) 16%,var(--surface));border-color:var(--c);color:var(--ct)} +.sch-opt{font:italic 11px 'DM Mono',ui-monospace,monospace;color:var(--text-3)} +.sch-hint{display:none} +@media (max-width:900px){.panel .sub.sch-hint{display:block;margin:0}} +@media (max-width:720px){.tbl.db-tbl th:first-child,.tbl.db-tbl td:first-child{padding-left:16px} .tbl.db-tbl th:last-child,.tbl.db-tbl td:last-child{padding-right:16px}} /* Welcome */ .welcome{display:flex;flex-direction:column;align-items:center;gap:16px;text-align:center} .welcome .lead{margin:0;max-width:620px;font-size:18px;line-height:1.55;color:var(--text-2)} @@ -1164,7 +1210,7 @@
- + diff --git a/js/views-db.js b/js/views-db.js index 6007ff7..b578573 100644 --- a/js/views-db.js +++ b/js/views-db.js @@ -1,520 +1,407 @@ /* ================================================================ FINLENS — views-db.js - Database views: Schema Diagram, DB Inspector, Changelog + Database views: the DB Schema diagram and DB Inspector, the + Settings → Database tab that shows them as sub-tabs (Clarity, + v1.17.0), and the Changelog. + Colors come from CSS classes in index.html (.sch-*, .dv-*), which + read the theme tokens, so nothing here names a color. ================================================================ */ /* ══════════════════════════════════════════════════════════════ 1. DB SCHEMA DIAGRAM - Visual ERD of all 5 IndexedDB stores with fields and relationships + The 5 IndexedDB object stores in finlens_db, their fields and how + they link, as an inline SVG. ══════════════════════════════════════════════════════════════ */ registerView('db-schema', 'DB Schema', (root) => { - - const card = document.createElement('div'); - card.className = 'card'; - card.innerHTML = ` -

Database Schema & Inspector

-

- All data stored locally in your browser. No server, no cloud. Five object stores with relationships shown below. -

`; - root.appendChild(card); - - const diagramCard = document.createElement('div'); - diagramCard.className = 'card'; - diagramCard.style.padding = '0'; - diagramCard.style.overflow = 'hidden'; - - // Build the diagram as an SVG embedded in HTML - diagramCard.innerHTML = `
`; - root.appendChild(diagramCard); - - setTimeout(() => { - const holder = document.getElementById('dbDiagram'); - if (!holder) return; - - // ── Store definitions ────────────────────────────────────── - const stores = [ - { - id: 'transactions', - label: 'transactions', - color: 'var(--teal)', - colorSoft: 'var(--teal-soft)', - fields: [ - { name: 'id', type: 'string', key: 'PK', note: 'deterministic hash' }, - { name: 'date', type: 'Date', key: 'IDX' }, - { name: 'yearMonth', type: 'string', key: 'IDX', note: 'YYYY-MM' }, - { name: 'account', type: 'string', key: 'IDX', note: '→ accounts.id' }, - { name: 'type', type: 'string', key: 'IDX', note: 'debit|credit|transfer' }, - { name: 'schemaId', type: 'string', key: 'IDX', note: '→ BANK_SCHEMAS.id' }, - { name: 'description', type: 'string', key: '' }, - { name: 'amount', type: 'number', key: '' }, - { name: 'categories', type: 'string[]', key: '' }, - { name: 'isRecurring', type: 'boolean', key: '' }, - { name: 'isBill', type: 'boolean', key: '' }, - { name: 'isSubscription',type: 'boolean', key: '' }, - { name: '_originalDesc', type: 'string', key: '' }, - ], - }, - { - id: 'tx_overrides', - label: 'tx_overrides', - color: 'var(--amber)', - colorSoft: 'var(--amber-soft)', - fields: [ - { name: 'txId', type: 'string', key: 'PK', note: '→ transactions.id' }, - { name: 'description', type: 'string?', key: '' }, - { name: 'categories', type: 'string[]?', key: '' }, - { name: 'type', type: 'string?', key: '' }, - { name: 'notes', type: 'string?', key: '' }, - { name: 'isRecurring', type: 'boolean?', key: '' }, - { name: 'isBill', type: 'boolean?', key: '' }, - { name: 'isSubscription',type: 'boolean?', key: '' }, - { name: 'accountOverride',type:'string?', key: '' }, - { name: 'link', type: 'object?', key: '', note: '{type,id}' }, - { name: 'modifiedAt', type: 'Date', key: '' }, - ], - }, - { - id: 'accounts', - label: 'accounts', - color: 'var(--blue)', - colorSoft: 'rgba(59,130,246,.08)', - fields: [ - { name: 'id', type: 'string', key: 'PK', note: 'e.g. bank_checking' }, - { name: 'name', type: 'string', key: '' }, - { name: 'kind', type: 'string', key: '', note: 'checking|savings|credit|…' }, - { name: 'schemaId', type: 'string', key: '' }, - { name: 'sourceFile', type: 'string', key: '' }, - { name: 'displayOrder', type: 'number', key: '' }, - { name: 'manualBalance', type: 'number?', key: '' }, - { name: 'creditLimit', type: 'number?', key: '' }, - { name: 'initialBalance',type: 'number?', key: '' }, - { name: 'dataRangeMin', type: 'Date?', key: '', note: 'coverage tracking' }, - { name: 'dataRangeMax', type: 'Date?', key: '', note: 'coverage tracking' }, - { name: 'txCount', type: 'number', key: '', note: 'coverage tracking' }, - ], - }, - { - id: 'import_log', - label: 'import_log', - color: 'var(--purple)', - colorSoft: 'rgba(139,92,246,.08)', - fields: [ - { name: 'id', type: 'number', key: 'PK', note: 'auto-increment' }, - { name: 'timestamp', type: 'Date', key: '' }, - { name: 'filename', type: 'string', key: '' }, - { name: 'accountId', type: 'string', key: '', note: '→ accounts.id' }, - { name: 'schemaId', type: 'string', key: '' }, - { name: 'rowsFound', type: 'number', key: '' }, - { name: 'rowsInserted', type: 'number', key: '' }, - { name: 'rowsSkipped', type: 'number', key: '' }, - { name: 'dateRangeMin', type: 'Date', key: '' }, - { name: 'dateRangeMax', type: 'Date', key: '' }, - ], - }, - { - id: 'app_state', - label: 'app_state', - color: 'var(--text-2)', - colorSoft: 'var(--surface-2)', - fields: [ - { name: 'key', type: 'string', key: 'PK', note: 'lsSet() key' }, - { name: 'value', type: 'any', key: '', note: 'JSON-serializable' }, - ], - note: 'budgets · bills · debts · buckets · categories · apiKey · aiHistory · scenarios · investAlloc · debtPlan · manualBalances · txOverrides · accountOrder · accountLabels · categoryRules · ruleCategories · txRules · transferKeywords · customSchemas · fileAssignments · theme', - }, - ]; - - // ── Layout: 3-column grid ────────────────────────────────── - // Col 0: transactions (tall) - // Col 1: tx_overrides, accounts - // Col 2: import_log, app_state - const COL_W = 260; - const COL_GAP = 80; - const ROW_H = 28; - const HDR_H = 40; - const FIELD_PAD = 8; - - function storeHeight(s) { - return HDR_H + s.fields.length * ROW_H + FIELD_PAD * 2 + (s.note ? 32 : 0); - } - - const layout = { - transactions: { col: 0, row: 0 }, - tx_overrides: { col: 1, row: 0 }, - accounts: { col: 1, row: 1 }, - import_log: { col: 2, row: 0 }, - app_state: { col: 2, row: 1 }, - }; - - // Compute X positions - const colX = [0, COL_W + COL_GAP, (COL_W + COL_GAP) * 2]; - - // Compute Y positions per (col, row) - const colRowY = { '1_0': 0, '1_1': 0, '2_0': 0, '2_1': 0 }; - const txH = storeHeight(stores[0]); - colRowY['1_0'] = 0; - colRowY['1_1'] = storeHeight(stores[1]) + 32; - colRowY['2_0'] = 0; - colRowY['2_1'] = storeHeight(stores[3]) + 32; - - function boxPos(storeId) { - const l = layout[storeId]; - const x = colX[l.col]; - let y = 0; - if (l.col === 0) y = 0; - else y = colRowY[`${l.col}_${l.row}`]; - return { x, y }; - } - - const totalW = COL_W * 3 + COL_GAP * 2; - const totalH = Math.max( - storeHeight(stores[0]), - storeHeight(stores[1]) + 32 + storeHeight(stores[2]), - storeHeight(stores[3]) + 32 + storeHeight(stores[4]) - ); - - // ── SVG builder ────────────────────────────────────────────── - let svg = ``; - - // Draw each store box - stores.forEach(s => { - const { x, y } = boxPos(s.id); - const h = storeHeight(s); - - // Box shadow / background - svg += ``; - - // Header band - svg += ``; - // Mask bottom corners of header - svg += ``; - - // Header divider - svg += ``; - - // Store name - svg += `${s.label}`; - svg += `IndexedDB Object Store`; - - // Fields - s.fields.forEach((f, i) => { - const fy = y + HDR_H + FIELD_PAD + i * ROW_H; - const isKey = f.key === 'PK' || f.key === 'IDX'; - - // Row hover band (every other) - if (i % 2 === 0) { - svg += ``; - } - - // Key badge - if (f.key) { - const badgeColor = f.key === 'PK' ? s.color : 'var(--text-3)'; - svg += ``; - svg += `${f.key}`; - } - - const nameX = f.key ? x + 14 + (f.key.length * 7 + 14) : x + 14; - svg += `${f.name}`; - - // Type (right-aligned) - const typeStr = f.type + (f.note ? '' : ''); - svg += `${typeStr}`; - - // Note tooltip (small below type) - if (f.note) { - svg += `${f.note}`; - } - }); - - // Store note (description of keys) - if (s.note) { - const noteY = y + HDR_H + FIELD_PAD + s.fields.length * ROW_H + 6; - // Wrap note text - const words = s.note.split(' · '); - const line1 = words.slice(0, Math.ceil(words.length / 2)).join(' · '); - const line2 = words.slice(Math.ceil(words.length / 2)).join(' · '); - svg += `${escapeHtml(line1)}`; - svg += `${escapeHtml(line2)}`; - } - }); - - // ── Relationship arrows ────────────────────────────────────── - // transactions.id ←→ tx_overrides.txId + // hue: a .sch-* class (index.html) that sets --c (lines) and --ct (text) from the theme. + const stores = [ { - const from = boxPos('transactions'); - const to = boxPos('tx_overrides'); - // transactions right edge, vertically at 'id' field - const x1 = from.x + COL_W; - const y1 = from.y + HDR_H + FIELD_PAD + 0 * ROW_H + 14; - const x2 = to.x; - const y2 = to.y + HDR_H + FIELD_PAD + 0 * ROW_H + 14; - const mx = (x1 + x2) / 2; - svg += ``; - // Arrow head - svg += ``; - // Label - svg += `1:N id → txId`; - } - - // transactions.account → accounts.id + id: 'transactions', hue: 'teal', + fields: [ + { name: 'id', type: 'string', key: 'PK', note: 'deterministic hash' }, + { name: 'date', type: 'Date', key: 'IDX' }, + { name: 'yearMonth', type: 'string', key: 'IDX', note: 'YYYY-MM' }, + { name: 'account', type: 'string', key: 'IDX', note: '→ accounts.id' }, + { name: 'type', type: 'string', key: 'IDX', note: 'debit|credit|transfer' }, + { name: 'schemaId', type: 'string', key: 'IDX', note: '→ BANK_SCHEMAS.id' }, + { name: 'description', type: 'string', key: '' }, + { name: 'amount', type: 'number', key: '' }, + { name: 'categories', type: 'string[]', key: '' }, + { name: 'isRecurring', type: 'boolean', key: '' }, + { name: 'isBill', type: 'boolean', key: '' }, + { name: 'isSubscription',type: 'boolean', key: '' }, + { name: '_originalDesc', type: 'string', key: '' }, + ], + }, { - const from = boxPos('transactions'); - const to = boxPos('accounts'); - const accountFieldIdx = stores[0].fields.findIndex(f => f.name === 'account'); - const x1 = from.x + COL_W; - const y1 = from.y + HDR_H + FIELD_PAD + accountFieldIdx * ROW_H + 14; - const x2 = to.x; - const y2 = to.y + HDR_H + FIELD_PAD + 0 * ROW_H + 14; - const mx = (x1 + x2) / 2; - svg += ``; - svg += ``; - svg += `N:1 account → id`; - } - - // import_log.accountId → accounts.id + id: 'tx_overrides', hue: 'warn', + fields: [ + { name: 'txId', type: 'string', key: 'PK', note: '→ transactions.id' }, + { name: 'description', type: 'string?', key: '' }, + { name: 'categories', type: 'string[]?', key: '' }, + { name: 'type', type: 'string?', key: '' }, + { name: 'notes', type: 'string?', key: '' }, + { name: 'isRecurring', type: 'boolean?', key: '' }, + { name: 'isBill', type: 'boolean?', key: '' }, + { name: 'isSubscription',type: 'boolean?', key: '' }, + { name: 'accountOverride',type:'string?', key: '' }, + { name: 'link', type: 'object?', key: '', note: '{type,id}' }, + { name: 'modifiedAt', type: 'Date', key: '' }, + ], + }, { - const from = boxPos('import_log'); - const to = boxPos('accounts'); - const acctFieldIdx = stores[3].fields.findIndex(f => f.name === 'accountId'); - const x1 = from.x; - const y1 = from.y + HDR_H + FIELD_PAD + acctFieldIdx * ROW_H + 14; - const x2 = to.x + COL_W; - const y2 = to.y + HDR_H + FIELD_PAD + 0 * ROW_H + 14; - const mx = (x1 + x2) / 2; - svg += ``; - svg += ``; - svg += `N:1 accountId → id`; - } + id: 'accounts', hue: 'sky', + fields: [ + { name: 'id', type: 'string', key: 'PK', note: 'e.g. bank_checking' }, + { name: 'name', type: 'string', key: '' }, + { name: 'kind', type: 'string', key: '', note: 'bank_checking|credit_card|…' }, + { name: 'schemaId', type: 'string', key: '' }, + { name: 'sourceFile', type: 'string', key: '' }, + { name: 'displayOrder', type: 'number', key: '' }, + { name: 'manualBalance', type: 'number?', key: '' }, + { name: 'creditLimit', type: 'number?', key: '' }, + { name: 'initialBalance',type: 'number?', key: '' }, + { name: 'dataRangeMin', type: 'Date?', key: '', note: 'coverage tracking' }, + { name: 'dataRangeMax', type: 'Date?', key: '', note: 'coverage tracking' }, + { name: 'txCount', type: 'number', key: '', note: 'coverage tracking' }, + ], + }, + { + id: 'import_log', hue: 'violet', + fields: [ + { name: 'id', type: 'number', key: 'PK', note: 'auto-increment' }, + { name: 'timestamp', type: 'Date', key: '' }, + { name: 'filename', type: 'string', key: '' }, + { name: 'accountId', type: 'string', key: '', note: '→ accounts.id' }, + { name: 'schemaId', type: 'string', key: '' }, + { name: 'rowsFound', type: 'number', key: '' }, + { name: 'rowsInserted', type: 'number', key: '' }, + { name: 'rowsSkipped', type: 'number', key: '' }, + { name: 'rowsRemoved', type: 'number', key: '', note: 'leftover duplicates' }, + { name: 'dateRangeMin', type: 'Date', key: '' }, + { name: 'dateRangeMax', type: 'Date', key: '' }, + ], + }, + { + id: 'app_state', hue: 'neutral', + fields: [ + { name: 'key', type: 'string', key: 'PK', note: 'lsSet() key' }, + { name: 'value', type: 'any', key: '', note: 'JSON-serializable' }, + ], + // The lsSet() keys the code writes (and customSchemas, which it reads). + note: 'budgets · bills · recurring · debts · debtPlan · buckets · categories · catRules · ruleCategories · txRules · apiKey · aiHistory · scenarios · investAlloc · manualBalances · cardDetails · txOverrides · accountOrder · accountLabels · transferKeywords · customSchemas · fileAssignments · lastFolderName · csvAutoImportPaused · sampleData · theme', + }, + ]; + + // ── Layout: three columns ──────────────────────────────────── + // transactions | tx_overrides over accounts | import_log over app_state + // 3 × 228 + 2 × 94 = 872px: fits Settings' 1000px page inside a panel. The gaps hold + // the relationship labels. Text is DM Mono, about 0.6em a character. + const W = 228, GAP = 94, ROW_H = 30, HDR_H = 44, PAD = 8, STACK = 28, NOTE_LH = 13; + const byId = Object.fromEntries(stores.map(s => [s.id, s])); + // Wrap a store's note into lines that fit the box (10px text ≈ 6px a character). + const perLine = Math.floor((W - 24) / 6); + stores.forEach(s => { + s.lines = []; + if (!s.note) return; + let line = ''; + s.note.split(' · ').forEach(w => { + const next = line ? line + ' · ' + w : w; + if (next.length > perLine && line) { s.lines.push(line + ' ·'); line = w; } else line = next; + }); + if (line) s.lines.push(line); + }); + const height = (s) => HDR_H + s.fields.length * ROW_H + PAD * 2 + (s.lines.length ? s.lines.length * NOTE_LH + 8 : 0); + const at = { + transactions: { x: 0, y: 0 }, + tx_overrides: { x: W + GAP, y: 0 }, + accounts: { x: W + GAP, y: height(byId.tx_overrides) + STACK }, + import_log: { x: (W + GAP) * 2, y: 0 }, + app_state: { x: (W + GAP) * 2, y: height(byId.import_log) + STACK }, + }; + const totalW = W * 3 + GAP * 2; + const totalH = Math.max(...stores.map(s => at[s.id].y + height(s))) + 2; + const fieldY = (id, name) => at[id].y + HDR_H + PAD + byId[id].fields.findIndex(f => f.name === name) * ROW_H + ROW_H / 2; + const esc = escapeHtml; + + let svg = ''; + stores.forEach(s => { + const { x, y } = at[s.id]; + const h = height(s), r = 10; + svg += ``; + svg += ``; + // header band: rounded at the top only + svg += ``; + svg += ``; + svg += `${esc(s.id)}`; + svg += `IndexedDB object store`; + s.fields.forEach((f, i) => { + const fy = y + HDR_H + PAD + i * ROW_H; + if (i % 2 === 0) svg += ``; + let nameX = x + 12; + if (f.key) { + const bw = f.key.length * 6.5 + 8, pk = f.key === 'PK' ? ' pk' : ''; + svg += ``; + svg += `${f.key}`; + nameX += bw + 7; + } + svg += `${esc(f.name)}`; + svg += `${esc(f.type)}`; + if (f.note) svg += `${esc(f.note)}`; + }); + const ny = y + HDR_H + PAD + s.fields.length * ROW_H + 8; + s.lines.forEach((l, i) => { svg += `${esc(l)}`; }); + svg += ``; // outline on top of the band + svg += ``; + }); - svg += ``; - holder.innerHTML = svg; + // ── Relationships: a dashed curve from the field to the key it points at ── + // [from store, field, to store, field, hue, label lines, label position 'above' | 'mid'] + const rels = [ + ['transactions', 'id', 'tx_overrides', 'txId', 'teal', ['1:N', 'id → txId'], 'above'], + ['transactions', 'account', 'accounts', 'id', 'sky', ['N:1', 'account → id'], 'mid'], + ['import_log', 'accountId', 'accounts', 'id', 'violet', ['N:1', 'accountId → id'], 'mid'], + ]; + rels.forEach(([fs, ff, ts, tf, hue, label, pos]) => { + const leftToRight = at[fs].x < at[ts].x; + const x1 = leftToRight ? at[fs].x + W : at[fs].x, y1 = fieldY(fs, ff); + const x2 = leftToRight ? at[ts].x : at[ts].x + W, y2 = fieldY(ts, tf); + const mx = (x1 + x2) / 2, d = leftToRight ? -8 : 8; + svg += ``; + svg += ``; + svg += ``; + const ly = pos === 'above' ? Math.min(y1, y2) - 30 : (y1 + y2) / 2 - 13; + const lw = Math.max(...label.map(l => l.length)) * 6 + 10; + svg += ``; + label.forEach((l, i) => { svg += `${esc(l)}`; }); + svg += ``; + }); - // ── Legend card ────────────────────────────────────────────── - const legend = document.createElement('div'); - legend.className = 'card'; - legend.style.marginTop = '0'; - legend.innerHTML = ` -

Legend

-
-
- PK - Primary Key (keyPath) -
-
- IDX - Indexed field (fast queries) -
-
- - Foreign key relationship -
-
- type? - Optional field (may be null) -
-
-
- Database: finlens_db · Version: 1 · Storage: IndexedDB (browser-native) · All data stays on your device. -
`; - root.appendChild(legend); - }, 0); + const desc = 'Diagram of the five IndexedDB object stores and their fields: transactions, tx_overrides, accounts, import_log and app_state. ' + + 'transactions.id links to tx_overrides.txId (one transaction, many edits); transactions.account and import_log.accountId each point at accounts.id.'; + appendHtml(root, `
+

Database schema

+

The five object stores FinLens keeps in this browser's IndexedDB database, their fields, and how they link. No server, no cloud.

+

Scroll sideways to see the whole diagram.

+
+ ${svg} +
+
+ PKPrimary key (the store's keyPath) + IDXIndexed field (fast queries) + Link between stores + type?Optional field (may be missing) +
+

Database finlens_db · version 1 · IndexedDB in this browser. Your data stays on this device.

+
`); }); /* ══════════════════════════════════════════════════════════════ 2. DB INSPECTOR - Browse any IndexedDB store — select store, search, paginate + Browse any IndexedDB store: pick a store, search, page through. + Read-only. Re-reads the store on every visit, keeping the store, + search and page (a page past the end moves back to the last one). ══════════════════════════════════════════════════════════════ */ const DB_INSPECTOR_STORES = ['transactions', 'tx_overrides', 'accounts', 'import_log', 'app_state']; - -let _inspectorStore = 'transactions'; -let _inspectorPage = 0; -let _inspectorSearch = ''; -let _inspectorRows = []; const INSPECTOR_PAGE_SIZE = 50; +// Session memory (nothing is saved): the chosen store, search and page, and the records last read. +const DBInspector = { + store: 'transactions', + search: '', // as typed; matched case-insensitively against each record's JSON + page: 0, // 0-based + all: [], // the store's records, as last read + rows: [], // …those that match the search + keyPath: 'id', // the store's key, shown first + // The API key is in app_state (CLAUDE.md §13). Show that it's there, never its value, and + // leave its value out of the search so typing can't reveal it a character at a time. + isSecret: (r) => DBInspector.store === 'app_state' && r && r.key === 'apiKey', + matches(r, q) { + const v = this.isSecret(r) ? { key: r.key } : r; + return JSON.stringify(v).toLowerCase().includes(q); + }, +}; registerView('db-inspector', 'DB Inspector', (root) => { - - const ctrl = document.createElement('div'); - ctrl.className = 'card'; - ctrl.innerHTML = ` -

DB Inspector

-

Browse the raw contents of any IndexedDB store. Read-only.

-
-
- - -
-
- - -
-
- - -
+ const I = DBInspector; + appendHtml(root, `
+

DB Inspector

Read-only
+

The raw records in this browser's database, one store at a time. Nothing here can be changed.

+
+ + + +
-
`; - root.appendChild(ctrl); - - const tableCard = document.createElement('div'); - tableCard.className = 'card'; - tableCard.innerHTML = `

Select a store and click Load.

`; - root.appendChild(tableCard); - - const pagCtrl = document.createElement('div'); - pagCtrl.style.display = 'flex'; - pagCtrl.style.gap = '8px'; - pagCtrl.style.alignItems = 'center'; - pagCtrl.style.flexWrap = 'wrap'; - pagCtrl.innerHTML = ` - - - `; - root.appendChild(pagCtrl); - - // Load data - async function loadStore() { - _inspectorStore = $('#inspStoreSelect').value; - _inspectorSearch = ($('#inspSearch').value||'').trim().toLowerCase(); - _inspectorPage = 0; - await _fetchAndRender(); - } - - async function _fetchAndRender() { - if (typeof DB === 'undefined' || !DB._db) { - $('#inspTable').innerHTML = '
IndexedDB not available.
'; +

+
+
+

Reading the store…

+
+
`); + + // Read the selected store, then draw. Runs after the render (renders stay synchronous, + // CLAUDE.md §15) and looks its elements up again afterwards: the view may have been left. + async function fetchAndRender() { + const store = I.store; + let rows = null; + try { + if (typeof DB !== 'undefined' && DB._db) { + rows = await new Promise((res) => { + const os = DB._db.transaction(store, 'readonly').objectStore(store); + I.keyPath = typeof os.keyPath === 'string' ? os.keyPath : 'id'; + const req = os.getAll(); + req.onsuccess = () => res(req.result || []); + req.onerror = () => res(null); + }); + } + } catch (e) { rows = null; } + if (store !== I.store) return; // another store was picked meanwhile + const tbl = $('#inspTable'); + if (!tbl) return; + if (!rows) { + I.all = []; I.rows = []; + tbl.innerHTML = `
${callout('warn', 'The browser database isn\'t available, so there is nothing to show.')}
`; + const meta = $('#inspMeta'); if (meta) meta.textContent = ''; + const pi = $('#inspPageInfo'); if (pi) pi.textContent = ''; + const pg = $('#inspPager'); if (pg) pg.innerHTML = ''; return; } - const store = _inspectorStore; - const rows = await new Promise(res => { - const req = DB._db.transaction(store, 'readonly').objectStore(store).getAll(); - req.onsuccess = () => res(req.result || []); - req.onerror = () => res([]); - }); - - // Filter - _inspectorRows = _inspectorSearch - ? rows.filter(r => JSON.stringify(r).toLowerCase().includes(_inspectorSearch)) - : rows; - - const meta = document.getElementById('inspMeta'); - if (meta) meta.textContent = `${_inspectorRows.length.toLocaleString()} record${_inspectorRows.length!==1?'s':''} found (${rows.length.toLocaleString()} total in store)`; - - _renderPage(); + I.all = rows; + applySearch(); } - function _renderPage() { - const start = _inspectorPage * INSPECTOR_PAGE_SIZE; - const pageRows = _inspectorRows.slice(start, start + INSPECTOR_PAGE_SIZE); - const totalPages = Math.ceil(_inspectorRows.length / INSPECTOR_PAGE_SIZE); - - const pageInfo = document.getElementById('inspPageInfo'); - if (pageInfo) pageInfo.textContent = _inspectorRows.length - ? `Page ${_inspectorPage + 1} of ${totalPages} (${start + 1}–${Math.min(start + INSPECTOR_PAGE_SIZE, _inspectorRows.length)} of ${_inspectorRows.length})` - : ''; + function applySearch() { + const q = I.search.trim().toLowerCase(); + I.rows = q ? I.all.filter(r => I.matches(r, q)) : I.all; + const meta = $('#inspMeta'); + if (meta) meta.textContent = `${plural(I.rows.length, 'record')} found (${I.all.length.toLocaleString()} total in store)`; + renderPage(); + } - const prev = document.getElementById('inspPrev'); - const next = document.getElementById('inspNext'); - if (prev) prev.disabled = _inspectorPage === 0; - if (next) next.disabled = _inspectorPage >= totalPages - 1; + // One cell. Strings are escaped; long values are cut, with the full value (up to 500 + // characters) in the cell's title. + function cell(r, k) { + const v = r[k]; + if (I.isSecret(r) && k === 'value') return `Hidden: an API key is saved`; + let disp, full; + if (v === null || v === undefined) disp = 'null'; + else if (v instanceof Date || (typeof v === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(v))) { + const d = dayjs(v); + disp = `${d.isValid() ? d.format('MMM D YYYY, h:mm A') : escapeHtml(String(v))}`; + full = v instanceof Date ? v.toISOString() : v; + } else if (Array.isArray(v)) { + full = '[' + v.map(x => typeof x === 'object' ? JSON.stringify(x) : String(x)).join(', ') + ']'; + disp = `${escapeHtml(full.slice(0, 100))}`; + } else if (typeof v === 'object') { + full = JSON.stringify(v); + disp = `${escapeHtml(full.slice(0, 80))}`; + } else if (typeof v === 'boolean') disp = `${v}`; + else if (typeof v === 'number') disp = `${v.toLocaleString()}`; + else { full = String(v); disp = escapeHtml(full.slice(0, 100)); } + const title = full && full.length > 20 ? ` title="${escapeHtml(full.slice(0, 500))}"` : ''; + return `${disp}`; + } - const tbl = document.getElementById('inspTable'); + function renderPage() { + const pages = Math.max(1, Math.ceil(I.rows.length / INSPECTOR_PAGE_SIZE)); + I.page = Math.max(0, Math.min(I.page, pages - 1)); // the store may have shrunk + const start = I.page * INSPECTOR_PAGE_SIZE; + const pageRows = I.rows.slice(start, start + INSPECTOR_PAGE_SIZE); + const tbl = $('#inspTable'), info = $('#inspPageInfo'), pager = $('#inspPager'); if (!tbl) return; - + if (info) info.textContent = I.rows.length + ? `Page ${I.page + 1} of ${pages} · ${(start + 1).toLocaleString()}–${Math.min(start + INSPECTOR_PAGE_SIZE, I.rows.length).toLocaleString()} of ${I.rows.length.toLocaleString()}` + : ''; + if (pager) { + const nums = []; + for (let p = 0; p < pages; p++) if (p === 0 || p === pages - 1 || Math.abs(p - I.page) <= 1) nums.push(p); else if (nums[nums.length - 1] !== '…') nums.push('…'); + pager.innerHTML = pages > 1 ? ` + ${nums.map(p => p === '…' ? '' : ``).join('')} + ` : ''; + $$('[data-page]', pager).forEach(b => b.onclick = () => { + I.page = +b.dataset.page; renderPage(); + const cur = $('#inspPager [aria-current="page"]'); if (cur) cur.focus({ preventScroll: true }); + }); + } if (!pageRows.length) { - tbl.innerHTML = '

No records found.

'; + const q = I.search.trim(); + tbl.innerHTML = `

${q ? `No records in ${escapeHtml(I.store)} match “${escapeHtml(q)}”.` : `${escapeHtml(I.store)} is empty.`}

`; return; } + // Columns: the store's key first, then every other key on this page, in first-seen order. + const keys = [I.keyPath]; + pageRows.forEach(r => Object.keys(r).forEach(k => { if (!keys.includes(k)) keys.push(k); })); + const head = `${keys.map(k => `${escapeHtml(k)}`).join('')}`; + const body = `${pageRows.map(r => { + const id = r[I.keyPath]; + return `${escapeHtml(String(id ?? ''))}${keys.slice(1).map(k => cell(r, k)).join('')}`; + }).join('')}`; + tbl.innerHTML = `${head}${body}
${escapeHtml(I.store)}, page ${I.page + 1} of ${pages}
`; + } - // Collect all keys across all rows for columns - const allKeys = []; - const keySeen = new Set(); - pageRows.forEach(r => Object.keys(r).forEach(k => { if (!keySeen.has(k)){ keySeen.add(k); allKeys.push(k); } })); + // Picking a store reads it; the search filters as you type (no re-read). + $('#inspStoreSelect').onchange = (e) => { I.store = e.target.value; I.page = 0; I.all = []; I.rows = []; fetchAndRender(); }; + $('#inspSearch').oninput = debounce((e) => { I.search = e.target.value; I.page = 0; applySearch(); }, 200); + $('#inspSearch').onkeydown = (e) => { if (e.key === 'Enter') { e.preventDefault(); I.search = e.target.value; I.page = 0; applySearch(); } }; + $('#inspClear').onclick = () => { const s = $('#inspSearch'); s.value = ''; I.search = ''; I.page = 0; applySearch(); s.focus(); }; + $('#inspLoad').onclick = () => fetchAndRender(); - const thead = `${allKeys.map(k => `${escapeHtml(k)}`).join('')}`; - const tbody = `${pageRows.map(r => `${allKeys.map(k => { - const v = r[k]; - let disp; - if (v === null || v === undefined) disp = 'null'; - else if (v instanceof Date || (typeof v === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(v))) - disp = `${dayjs(v).format('MMM D YYYY, h:mm A')}`; - else if (Array.isArray(v)) - disp = `[${v.map(x=>escapeHtml(String(x))).join(', ')}]`; - else if (typeof v === 'object') - disp = `${escapeHtml(JSON.stringify(v).slice(0,80))}`; - else if (typeof v === 'boolean') - disp = v ? 'true' : 'false'; - else if (typeof v === 'number') - disp = `${v.toLocaleString()}`; - else disp = escapeHtml(String(v).slice(0, 100)); - return `${disp}`; - }).join('')}`).join('')}`; + // Every visit reads the store again: rows from the last visit may be stale (an import + // or a clear since then). The store, search and page are kept. + setTimeout(fetchAndRender, 0); +}); - tbl.innerHTML = `
${thead}${tbody}
`; - } - // Wire events after DOM is ready - const loadBtn = document.getElementById('inspLoad'); - const clearBtn = document.getElementById('inspClear'); - const prevBtn = document.getElementById('inspPrev'); - const nextBtn = document.getElementById('inspNext'); +/* ══════════════════════════════════════════════════════════════ + 3. SETTINGS → DATABASE TAB (v1.17.0) + DB Inspector and DB Schema as sub-tabs: a segmented tab control, + as on Forecast (Savings / Investments), and one tabpanel the chosen + view renders into. Both are still views of their own, so + showView('db-inspector') and showView('db-schema') keep working. + Kept above the Changelog block so this tab still registers if + that block ever throws (see v1.9.4). +══════════════════════════════════════════════════════════════ */ - if (loadBtn) loadBtn.onclick = loadStore; - if (clearBtn) { - clearBtn.onclick = () => { - const si = document.getElementById('inspSearch'); - if (si) si.value = ''; - _inspectorSearch = ''; - _inspectorPage = 0; - _inspectorRows = []; - const tbl = document.getElementById('inspTable'); - if (tbl) tbl.innerHTML = '

Select a store and click Load.

'; - const meta = document.getElementById('inspMeta'); - if (meta) meta.textContent = ''; +const DB_TOOLS_TABS = [ + ['db-inspector', 'DB Inspector', 'dbTabInsp'], + ['db-schema', 'DB Schema', 'dbTabSchema'], +]; +let dbToolsTab = 'db-inspector'; // remembered for the session only, like forecastTab + +registerView('db-tools', 'Database', (root) => { + const tabs = DB_TOOLS_TABS.filter(([k]) => VIEWS[k]); + if (!tabs.length) return; + if (!tabs.some(([k]) => k === dbToolsTab)) dbToolsTab = tabs[0][0]; + appendHtml(root, `
${tabs.map(([k, l, id]) => + ``).join('')}
`); + // Arrow keys, Home and End move between the sub-tabs; focus follows. + const pick = (k) => { dbToolsTab = k; renderActive(); const t = $(`[role="tab"][data-db-tab="${k}"]`); if (t) t.focus(); }; + const btns = $$('[data-db-tab]', root); + btns.forEach((b, i) => { + b.onclick = () => pick(b.dataset.dbTab); + b.onkeydown = (e) => { + const n = e.key === 'ArrowRight' ? i + 1 : e.key === 'ArrowLeft' ? i - 1 : e.key === 'Home' ? 0 : e.key === 'End' ? btns.length - 1 : null; + if (n == null) return; + e.preventDefault(); e.stopPropagation(); pick(btns[(n + btns.length) % btns.length].dataset.dbTab); }; - } - if (prevBtn) prevBtn.onclick = () => { _inspectorPage = Math.max(0, _inspectorPage - 1); _renderPage(); }; - if (nextBtn) nextBtn.onclick = () => { - const totalPages = Math.ceil(_inspectorRows.length / INSPECTOR_PAGE_SIZE); - _inspectorPage = Math.min(totalPages - 1, _inspectorPage + 1); - _renderPage(); - }; - - // Auto-load on render if we have previous data - setTimeout(async () => { - if (_inspectorRows.length) { _renderPage(); return; } - await loadStore(); - }, 0); + }); + const panel = document.createElement('div'); + panel.id = 'dbPanel'; + panel.className = 'tab-panel'; + panel.setAttribute('role', 'tabpanel'); + panel.setAttribute('aria-labelledby', tabs.find(([k]) => k === dbToolsTab)[2]); + root.appendChild(panel); + VIEWS[dbToolsTab].render(panel); }); /* ══════════════════════════════════════════════════════════════ - 3. CHANGELOG + 4. CHANGELOG Reads CHANGELOG.md (next to index.html) each time the view opens, so it always matches the file (v1.16.15). Before, it showed a copy embedded here, which nobody updated after v1.4.1. A page opened as a file (file://) can't read other files, so diff --git a/js/views-settings.js b/js/views-settings.js index 4f34c47..c5ba822 100644 --- a/js/views-settings.js +++ b/js/views-settings.js @@ -2,7 +2,8 @@ FINLENS — views-settings.js Settings shell (tab bar) + General tab: About (version), Anthropic API key. The other tabs are views of their own: Import, Accounts, Credit cards and - Categories in views-data.js, Data & reset in views-cleanup.js (Clarity, v1.16.0). + Categories in views-data.js, Data & reset in views-cleanup.js (Clarity, v1.16.0), + Database (DB Inspector and DB Schema) in views-db.js (v1.17.0). ================================================================ */ let settingsTab='general'; @@ -14,21 +15,24 @@ const SETTINGS_TABS=[ ['credit-cards','Credit cards'], ['categories','Categories'], ['data-cleanup','Data & reset'], + ['db-tools', 'Database'], // views-db.js: DB Inspector and DB Schema sub-tabs ]; registerView('settings','Settings',(root)=>{ - if (!SETTINGS_TABS.some(t=>t[0]===settingsTab)) settingsTab='general'; + // Tabs live in other files. If one failed to load, hide its tab instead of throwing. + const shown=SETTINGS_TABS.filter(([k])=>k==='general'||VIEWS[k]); + if (!shown.some(t=>t[0]===settingsTab)) settingsTab='general'; pageActions(root,'Everything here stays on this computer',''); const tabBar=document.createElement('div'); tabBar.className='tabs'; tabBar.setAttribute('role','tablist'); tabBar.setAttribute('aria-label','Settings sections'); - tabBar.innerHTML=SETTINGS_TABS.map(([k,l])=> + tabBar.innerHTML=shown.map(([k,l])=> `` ).join(''); root.appendChild(tabBar); // On a phone the tab bar scrolls sideways, and each render starts it at the left. Bring the - // selected tab into view (Data & reset, the last one, was off-screen at 390px). + // selected tab into view (the last ones, Data & reset and Database, were off-screen). const selTab=$('[aria-selected="true"]',tabBar); if (selTab) { const b=tabBar.getBoundingClientRect(), s=selTab.getBoundingClientRect(); @@ -60,7 +64,7 @@ function _renderGeneralSettings(root) { /* ---- About (the Theme row is gone: light only for now) ---- */ appendHtml(root,`

About

-
VersionFinLens v1.16.27
+
VersionFinLens v1.17.0
`); /* ---- Anthropic API key ---- */