import type { Settings } from '../types'; import { isAccountDb, offlineDb } from './offlineDb'; /* * The account's settings as the server last answered them, so an app started * without a connection draws the map the user chose (provider, style, template) * and keeps their units, rather than falling back to the built-in defaults until * the first answer arrives. The server stays the source of truth: its next * answer replaces the row, and a kept row is never sent back. * * The row lives in the signed-in user's own database (offlineDb.ts), so another * account on the device never reads it, and logout deletes it with the database. * It holds what the server sent this user, the map keys included: the trip data * beside it is no less private, and without the CARTO key a stored CARTO * template could not be drawn offline. Secrets the server masks arrive masked. * * Every function here is best effort and never rejects. A device that cannot * keep the row (IndexedDB refused in a private window) behaves as before: it * starts on the defaults until the server answers. */ /** The settings the server last answered, or null when this device kept none. */ export async function cachedAccountSettings(): Promise | null> { try { if (!isAccountDb()) return null; return (await offlineDb.accountSettings.get('account'))?.settings ?? null; } catch { return null; } } /** Keeps the server's answer, replacing the one kept before. */ export async function cacheAccountSettings(settings: Partial): Promise { try { if (!isAccountDb()) return; await offlineDb.accountSettings.put({ key: 'account', settings }); } catch { /* Nothing kept: the next start without a connection shows the defaults, as it always did. */ } } /** * Lays settings the server just accepted over the kept answer, so a change made * online is what the next start without a connection shows. */ export async function cacheAccountSettingsPatch(patch: Partial): Promise { try { if (!isAccountDb()) return; await offlineDb.transaction('rw', offlineDb.accountSettings, async () => { const kept = (await offlineDb.accountSettings.get('account'))?.settings; await offlineDb.accountSettings.put({ key: 'account', settings: { ...kept, ...patch } }); }); } catch { /* The kept answer stays as it was; the next server answer replaces it anyway. */ } }