From ece8496cba370987d7186818a7753ab1a3b4f0f8 Mon Sep 17 00:00:00 2001 From: mrWD Date: Tue, 11 Aug 2026 10:25:46 +0200 Subject: [PATCH 1/7] Move the library to IndexedDB and share backups on iOS MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Same change as FilmTable's, for the same reasons: the library moves from localStorage to IndexedDB (lib/idb-storage.ts) — no more ~5 MB ceiling, and the format a native storage plugin migrates from when the app is wrapped for the stores. The old localStorage value is copied once and left frozen, so a rollback still finds the library. Hydration became async; main.tsx holds the first render until it settles. Exporting a backup on iOS opens the share sheet instead of a download nobody finds. Co-Authored-By: Claude Opus 5 --- CLAUDE.md | 5 +- docs/ARCHITECTURE.md | 28 ++++---- docs/DECISIONS.md | 13 ++++ src/lib/export.ts | 49 ++++++++++++++ src/lib/idb-storage.ts | 131 ++++++++++++++++++++++++++++++++++++++ src/main.tsx | 17 +++-- src/pages/ProfilePage.tsx | 15 ++--- src/store/library.ts | 36 ++--------- 8 files changed, 235 insertions(+), 59 deletions(-) create mode 100644 src/lib/export.ts create mode 100644 src/lib/idb-storage.ts diff --git a/CLAUDE.md b/CLAUDE.md index 27588c1..167f531 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -20,8 +20,9 @@ look at the neighbouring project. ## Principles (do not break without the owner's explicit consent) -1. **The library lives on the device.** `localStorage`, no accounts, nothing - personal collected. There is exactly as much server code as it takes to hide +1. **The library lives on the device.** IndexedDB for the library (moved from + `localStorage` in 2026-08, see DECISIONS), localStorage for small prefs; no + accounts, nothing personal collected. There is exactly as much server code as it takes to hide the key and work around the missing CORS — and it stores nothing. The one exception is `src/components/Analytics.tsx`: on a `.vercel.app` host it reports cookieless screen-view counts to Vercel Web Analytics. It sends a screen name diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index bc16d7e..29235b1 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -169,28 +169,30 @@ on RPG, which The Witcher already covered. ## Storage: how much fits and what is wrong with it -Measurements in Chromium (July 2026): localStorage caps out at **4.94 MB** per -origin, even when `navigator.storage.estimate()` reports 10 GB — it has its own -quota. +Since 2026-08 the library lives in IndexedDB (`gamestable-kv`, adapter in +`lib/idb-storage.ts`), whose quota is measured in gigabytes, so size is no +longer the pressing constraint. The history still explains the code: +localStorage capped out at **4.94 MB** per origin in Chromium (measured July +2026), even when `navigator.storage.estimate()` reported 10 GB. The size of a record, measured across twenty real RAWG responses: **507 B** per -game. A thousand games is 480 KB, a tenth of the limit. With the description a +game. A thousand games is 480 KB. With the description a record weighed 1,229 B instead of 407 (Elden Ring, a 778-character description) — meaning 60% of the library's weight was data that is never displayed anywhere. -Three things follow from this, and all three are already done: +What the localStorage era left behind, and what remains true: -- **`description` is not written to storage.** It is re-fetched every time the - detail page opens and is never shown in lists, yet it tripled the size of a - record. It is stripped via `partialize` and kept in memory for the session. For - records added earlier, the description disappears on the very first write to the - library — `partialize` applies to the whole store at once. -- **`QuotaExceededError` is caught.** Without that, the exception was thrown in the - middle of an update, the change was silently lost, and the person found out much - later. +- **`description` is still not written to storage.** It is re-fetched every time + the detail page opens and is never shown in lists; writing it would only + inflate the library and the backup file. It is stripped via `partialize` and + kept in memory for the session. +- **Write failures are still caught** — in `idb-storage.ts` now. A failed write + toasts once and asks for an export instead of silently losing the change. - **The app offers to install itself to the home screen.** This is not marketing: Safari clears script storage for sites that have not been visited in a while, and the rule does not apply to installed apps. That is what the prompt's text says. + This applies to IndexedDB exactly as it did to localStorage — moving between + them changes quotas, not eviction. The cost of writing is not a problem: zustand serialises the whole store on every change, but at 2,000 games (2.5 MB) that is 4.5 ms to serialise and 1.8 ms to diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 7e42671..1793e90 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -55,6 +55,19 @@ In FilmTable, series live in a separate cache with a TTL because new episodes co out. A game's metadata does not change, so the whole record is stored in the library. Simpler, and the library reads fully offline. +## IndexedDB instead of localStorage (2026-08) + +Same decision as FilmTable's, made at the same time and with the owner's +explicit consent: the library moved to IndexedDB (`gamestable-kv`, adapter in +`lib/idb-storage.ts`) to shed the ~5 MB ceiling and to be on the storage a +native wrapper migrates from when the app goes to the stores. The old +localStorage value is copied once on first read and left frozen, so a rollback +finds the library as of the migration moment. Hydration became asynchronous — +`main.tsx` holds the first render until it settles. Small prefs (`theme`, +`stats`) stay in localStorage; `theme` must be readable synchronously or the +first paint flashes the wrong theme. Exporting a backup on iOS goes through the +share sheet (`lib/export.ts`) because File System Access does not exist there. + ## Lessons from FilmTable — do not repeat them - **Vercel and `"type": "module"`.** The function must be ESM (`export default`). diff --git a/src/lib/export.ts b/src/lib/export.ts new file mode 100644 index 0000000..74ecb3f --- /dev/null +++ b/src/lib/export.ts @@ -0,0 +1,49 @@ +/** + * Getting a backup file out of the app, per platform. + * + * On iOS an `` click technically works, but lands in a download popup people + * rarely find, and in home-screen web apps has been flaky across versions. The share + * sheet is the platform's own way out: Save to Files, AirDrop, mail to yourself. Web + * Share with files needs user activation, which an export button click provides. + * + * Everywhere else the plain download link stays: on desktop a share dialog for saving + * a file would be a worse answer than the Downloads folder. + */ + +/** iPadOS reports itself as a Mac, so touch support is part of the test. */ +function isIos(): boolean { + return ( + /iPad|iPhone|iPod/.test(navigator.userAgent) || + (/Macintosh/.test(navigator.userAgent) && navigator.maxTouchPoints > 1) + ) +} + +export type ExportOutcome = 'shared' | 'downloaded' | 'cancelled' + +export async function exportJsonFile(data: unknown, fileName: string): Promise { + const json = JSON.stringify(data, null, 2) + + if (isIos() && typeof navigator.share === 'function' && typeof navigator.canShare === 'function') { + const file = new File([json], fileName, { type: 'application/json' }) + if (navigator.canShare({ files: [file] })) { + try { + await navigator.share({ files: [file] }) + return 'shared' + } catch (err) { + // Closing the sheet is a normal answer, not an error. + if (err instanceof Error && err.name === 'AbortError') return 'cancelled' + // Anything else (a target that rejects files, a WebKit quirk) falls through + // to the download path rather than losing the export. + } + } + } + + const blob = new Blob([json], { type: 'application/json' }) + const url = URL.createObjectURL(blob) + const a = document.createElement('a') + a.href = url + a.download = fileName + a.click() + URL.revokeObjectURL(url) + return 'downloaded' +} diff --git a/src/lib/idb-storage.ts b/src/lib/idb-storage.ts new file mode 100644 index 0000000..5b05a4c --- /dev/null +++ b/src/lib/idb-storage.ts @@ -0,0 +1,131 @@ +import type { StateStorage } from 'zustand/middleware' +import { useUi } from '../store/ui' + +/** + * IndexedDB-backed storage for the store that holds real data: the library. + * + * localStorage served well until two of its limits started to matter. Its ~5 MB ceiling + * is why game descriptions are stripped before writing and why a quota guard existed at + * all; IndexedDB quotas are measured in hundreds of megabytes. And on iOS the plan is to + * wrap the app natively, where the WebView's localStorage is the first thing the OS + * reclaims under pressure — IndexedDB is both sturdier there and the format the native + * storage plugin migrates from. + * + * The values are still the same JSON strings zustand's persist writes; only the shelf + * they sit on changes. Each value lives under its store name in one object store. + */ + +const DB_NAME = 'gamestable-kv' +const STORE = 'kv' + +let dbPromise: Promise | null = null + +function openDb(): Promise { + if (!dbPromise) { + dbPromise = new Promise((resolve, reject) => { + const req = indexedDB.open(DB_NAME, 1) + req.onupgradeneeded = () => req.result.createObjectStore(STORE) + req.onsuccess = () => { + // If the connection is severed (another tab upgrades, browser reclaims it), + // drop the cached promise so the next call reopens instead of failing forever. + req.result.onclose = () => { + dbPromise = null + } + resolve(req.result) + } + req.onerror = () => { + dbPromise = null + reject(req.error) + } + }) + } + return dbPromise +} + +function request(mode: IDBTransactionMode, run: (store: IDBObjectStore) => IDBRequest): Promise { + return openDb().then( + (db) => + new Promise((resolve, reject) => { + const tx = db.transaction(STORE, mode) + const req = run(tx.objectStore(STORE)) + req.onsuccess = () => resolve(req.result) + req.onerror = () => reject(req.error) + }), + ) +} + +/** A write that fails silently would lose check-ins one by one; say so, once. */ +let writeWarned = false + +/** + * The one-time move from localStorage. The old value is copied, not deleted: a frozen + * copy costs a few megabytes and means that rolling back to a build that still reads + * localStorage finds the library as of the migration moment rather than nothing. + */ +async function migrateFromLocalStorage(name: string): Promise { + const legacy = localStorage.getItem(name) + if (legacy === null) return null + try { + await request('readwrite', (s) => s.put(legacy, name)) + } catch { + // IndexedDB refused; the app keeps running off the localStorage value this session. + } + return legacy +} + +export const idbStorage: StateStorage = { + getItem: async (name) => { + try { + const value = await request('readonly', (s) => s.get(name)) + if (value !== undefined) return value + return await migrateFromLocalStorage(name) + } catch { + // IndexedDB unavailable (broken profile, some private modes) — fall back to + // whatever localStorage holds so the person at least sees their old library. + return localStorage.getItem(name) + } + }, + setItem: async (name, value) => { + try { + await request('readwrite', (s) => s.put(value, name)) + writeWarned = false + } catch { + if (writeWarned) return + writeWarned = true + useUi.getState().showToast('Saving failed — export a backup from your profile') + } + }, + removeItem: async (name) => { + try { + await request('readwrite', (s) => s.delete(name)) + } catch { + // Nothing to do: the key either goes next time or the DB itself is gone. + } + }, +} + +/** + * Async storage means async hydration: for a moment after load the stores hold their + * defaults, and anything reading them sees an empty library. Rendering is therefore + * held until hydration settles (main.tsx). The timeout is a backstop for the rare + * profile where IndexedDB hangs on open — a late library beats a blank screen. + */ +export function whenHydrated( + stores: { persist: { hasHydrated: () => boolean; onFinishHydration: (fn: () => void) => () => void } }[], + timeoutMs = 2500, +): Promise { + const all = Promise.all( + stores.map( + (s) => + new Promise((resolve) => { + if (s.persist.hasHydrated()) return resolve() + const un = s.persist.onFinishHydration(() => { + un() + resolve() + }) + }), + ), + ) + const timeout = new Promise((resolve) => setTimeout(resolve, timeoutMs)) + return Promise.race([all, timeout]).then(() => undefined) +} diff --git a/src/main.tsx b/src/main.tsx index fbba0ac..20d4691 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -3,11 +3,18 @@ import { createRoot } from 'react-dom/client' import { registerSW } from 'virtual:pwa-register' import './styles.css' import App from './App' +import { whenHydrated } from './lib/idb-storage' +import { useLibrary } from './store/library' registerSW({ immediate: true }) -createRoot(document.getElementById('root')!).render( - - - , -) +// The library now hydrates from IndexedDB, which is asynchronous. Rendering before it +// settles would flash an empty library (and let startup effects act on one). The read is +// a few milliseconds; the page background covers it. +void whenHydrated([useLibrary]).then(() => { + createRoot(document.getElementById('root')!).render( + + + , + ) +}) diff --git a/src/pages/ProfilePage.tsx b/src/pages/ProfilePage.tsx index 97efeb5..b1260ce 100644 --- a/src/pages/ProfilePage.tsx +++ b/src/pages/ProfilePage.tsx @@ -5,6 +5,7 @@ import { useUi } from '../store/ui' import { useTheme, type ThemeChoice } from '../store/theme' import { useStats } from '../store/stats' import { AutoBackup } from '../components/AutoBackup' +import { exportJsonFile } from '../lib/export' import { formatHours } from '../lib/format' import { IconDownload, IconPad, IconTrash, IconUpload } from '../components/Icons' import { SupportLinks } from '../components/Support' @@ -64,14 +65,10 @@ export default function ProfilePage() { const stats = buildStats(games) - const doExport = () => { - const blob = new Blob([JSON.stringify(buildBackup(), null, 2)], { type: 'application/json' }) - const url = URL.createObjectURL(blob) - const a = document.createElement('a') - a.href = url - a.download = `gamestable-backup-${new Date().toISOString().slice(0, 10)}.json` - a.click() - URL.revokeObjectURL(url) + const doExport = async () => { + const name = `gamestable-backup-${new Date().toISOString().slice(0, 10)}.json` + const outcome = await exportJsonFile(buildBackup(), name) + if (outcome === 'cancelled') return useStats.getState().recordExport() showToast('Backup exported') } @@ -166,7 +163,7 @@ export default function ProfilePage() {

Data

-