mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 16:33:16 +00:00
feat(settings): keep the account's settings for a start without a connection
/api/settings is never cached, so an app started offline ran on DEFAULT_SETTINGS until the server answered: Leaflet instead of the map the user chose, and the default units. The answer the server gave last time now stands in until the next one arrives. - Dexie v18 adds accountSettings, one row in the signed-in user's own database, so another account on the device never reads it and logout deletes it with the database. The anonymous database never holds one. A new table only; the upgrade test covers it. - loadSettings lays the kept answer over the defaults while nothing newer arrived and keeps every server answer. A key the server then leaves out goes back to its default, so the server stays the source of truth. - A setting the server accepted is laid over the kept answer, so a change made online is what the next offline start shows. A refused save keeps nothing. Keeping is best effort: where IndexedDB is refused the app starts on the defaults as before.
This commit is contained in:
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* The account's settings kept for a start without a connection (FE-DB-ACCOUNTSETTINGS-*).
|
||||
*
|
||||
* The row belongs to the signed-in account's own database: another account on
|
||||
* the device never reads it, the anonymous database never holds it, and logout
|
||||
* takes it with the database.
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { cacheAccountSettings, cacheAccountSettingsPatch, cachedAccountSettings } from './cacheAccountSettings';
|
||||
import { deleteCurrentUserDb, offlineDb, reopenAnonymous, reopenForUser } from './offlineDb';
|
||||
|
||||
const LIBERTY = 'https://tiles.openfreemap.org/styles/liberty';
|
||||
const OSM = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png';
|
||||
|
||||
afterEach(async () => {
|
||||
vi.restoreAllMocks();
|
||||
for (const user of [701, 702]) {
|
||||
await reopenForUser(user);
|
||||
await deleteCurrentUserDb();
|
||||
}
|
||||
await reopenAnonymous();
|
||||
});
|
||||
|
||||
describe('account settings kept offline', () => {
|
||||
it('FE-DB-ACCOUNTSETTINGS-001: keeps the last answer, the next one replacing it', async () => {
|
||||
await reopenForUser(701);
|
||||
expect(await cachedAccountSettings()).toBeNull();
|
||||
|
||||
await cacheAccountSettings({ map_provider: 'mapbox-gl', distance_unit: 'imperial' });
|
||||
await cacheAccountSettings({ map_provider: 'maplibre-gl', maplibre_style: LIBERTY });
|
||||
|
||||
expect(await cachedAccountSettings()).toEqual({ map_provider: 'maplibre-gl', maplibre_style: LIBERTY });
|
||||
expect(await offlineDb.accountSettings.count()).toBe(1);
|
||||
});
|
||||
|
||||
it('FE-DB-ACCOUNTSETTINGS-002: a saved change is laid over the kept answer', async () => {
|
||||
await reopenForUser(701);
|
||||
await cacheAccountSettings({ map_provider: 'leaflet', map_tile_url: OSM });
|
||||
|
||||
await cacheAccountSettingsPatch({ map_provider: 'maplibre-gl' });
|
||||
|
||||
expect(await cachedAccountSettings()).toEqual({ map_provider: 'maplibre-gl', map_tile_url: OSM });
|
||||
});
|
||||
|
||||
it('FE-DB-ACCOUNTSETTINGS-003: a change saved before any answer was kept is kept on its own', async () => {
|
||||
await reopenForUser(701);
|
||||
|
||||
await cacheAccountSettingsPatch({ map_provider: 'maplibre-gl' });
|
||||
|
||||
expect(await cachedAccountSettings()).toEqual({ map_provider: 'maplibre-gl' });
|
||||
});
|
||||
|
||||
it('FE-DB-ACCOUNTSETTINGS-004: another account on the device reads nothing of the first', async () => {
|
||||
await reopenForUser(701);
|
||||
await cacheAccountSettings({ map_provider: 'maplibre-gl' });
|
||||
|
||||
await reopenForUser(702);
|
||||
expect(await cachedAccountSettings()).toBeNull();
|
||||
|
||||
await reopenForUser(701);
|
||||
expect(await cachedAccountSettings()).toEqual({ map_provider: 'maplibre-gl' });
|
||||
});
|
||||
|
||||
it('FE-DB-ACCOUNTSETTINGS-005: logout takes the kept settings with the database', async () => {
|
||||
await reopenForUser(701);
|
||||
await cacheAccountSettings({ map_provider: 'maplibre-gl' });
|
||||
|
||||
await deleteCurrentUserDb();
|
||||
await reopenForUser(701);
|
||||
|
||||
expect(await cachedAccountSettings()).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-DB-ACCOUNTSETTINGS-006: the anonymous database never holds account settings', async () => {
|
||||
await reopenAnonymous();
|
||||
|
||||
await cacheAccountSettings({ map_provider: 'maplibre-gl' });
|
||||
await cacheAccountSettingsPatch({ map_provider: 'mapbox-gl' });
|
||||
|
||||
expect(await offlineDb.accountSettings.count()).toBe(0);
|
||||
expect(await cachedAccountSettings()).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-DB-ACCOUNTSETTINGS-007: a database that refuses never fails the caller', async () => {
|
||||
await reopenForUser(701);
|
||||
vi.spyOn(offlineDb.accountSettings, 'get').mockRejectedValue(new Error('refused'));
|
||||
vi.spyOn(offlineDb.accountSettings, 'put').mockRejectedValue(new Error('refused'));
|
||||
|
||||
await expect(cachedAccountSettings()).resolves.toBeNull();
|
||||
await expect(cacheAccountSettings({ map_provider: 'maplibre-gl' })).resolves.toBeUndefined();
|
||||
await expect(cacheAccountSettingsPatch({ map_provider: 'maplibre-gl' })).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
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<Partial<Settings> | 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<Settings>): Promise<void> {
|
||||
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<Settings>): Promise<void> {
|
||||
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. */
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import type {
|
||||
PackingItem,
|
||||
Place,
|
||||
Reservation,
|
||||
Settings,
|
||||
Tag,
|
||||
TodoItem,
|
||||
Trip,
|
||||
@@ -260,6 +261,18 @@ interface AtlasSnapshotRow {
|
||||
data: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* The account's settings as the server last answered them, one row. Kept so an
|
||||
* offline cold start draws the map provider, style and template the user chose
|
||||
* instead of the built-in defaults; the server stays the source of truth and the
|
||||
* next answer replaces the row. The database is the signed-in user's own, so the
|
||||
* row needs no user key and goes with the database on logout.
|
||||
*/
|
||||
interface CachedAccountSettings {
|
||||
key: 'account';
|
||||
settings: Partial<Settings>;
|
||||
}
|
||||
|
||||
export interface SyncMeta {
|
||||
tripId: number;
|
||||
lastSyncedAt: number | null;
|
||||
@@ -394,6 +407,7 @@ export class TrekOfflineDb extends Dexie {
|
||||
tripAddons!: Table<CachedTripAddons, number>;
|
||||
userMutationQueue!: Table<UserQueuedMutation, string>;
|
||||
atlasSnapshot!: Table<AtlasSnapshotRow, AtlasSnapshotPart>;
|
||||
accountSettings!: Table<CachedAccountSettings, 'account'>;
|
||||
|
||||
constructor(name: string = ANON_DB_NAME) {
|
||||
super(name);
|
||||
@@ -514,6 +528,11 @@ export class TrekOfflineDb extends Dexie {
|
||||
atlasSnapshot: 'part',
|
||||
userMutationQueue: 'id, status, createdAt, entity',
|
||||
});
|
||||
|
||||
// v18: the account's settings as the server last answered them, one row, so
|
||||
// an offline cold start shows the user's map instead of the defaults. A new
|
||||
// table: nothing an install already holds is touched.
|
||||
this.version(18).stores({ accountSettings: 'key' });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -553,6 +572,15 @@ export async function reopenAnonymous(): Promise<void> {
|
||||
await switchTo(ANON_DB_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the open database belongs to a signed-in account. Account data (its
|
||||
* settings) is only ever kept there, never in the anonymous database the next
|
||||
* person on this device would open.
|
||||
*/
|
||||
export function isAccountDb(): boolean {
|
||||
return _db.name !== ANON_DB_NAME;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the current user's scoped database entirely and return to the anonymous
|
||||
* DB. Used on logout so no trace of the account's data remains on the device.
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* The settings on a start without a connection (FE-STORE-SETTINGS-OFFLINE-*).
|
||||
*
|
||||
* Until the server answers, the answer it gave last time stands in, so the map
|
||||
* shows the provider, style and template the user chose instead of
|
||||
* DEFAULT_SETTINGS (Leaflet). The server stays the source of truth: its answer
|
||||
* replaces the stand-in, and only what it accepted is kept for next time.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { settingsApi } from '../api/client';
|
||||
import { cacheAccountSettings, cachedAccountSettings } from '../db/cacheAccountSettings';
|
||||
import { deleteCurrentUserDb, reopenAnonymous, reopenForUser } from '../db/offlineDb';
|
||||
import { DEFAULT_SETTINGS, useSettingsStore } from './settingsStore';
|
||||
|
||||
vi.mock('../api/client', () => ({
|
||||
settingsApi: {
|
||||
get: vi.fn(),
|
||||
set: vi.fn(),
|
||||
setBulk: vi.fn(),
|
||||
},
|
||||
}));
|
||||
vi.mock('../sync/tilePrefetcher', () => ({ clearTileCache: vi.fn().mockResolvedValue(undefined) }));
|
||||
|
||||
const BRIGHT = 'https://tiles.openfreemap.org/styles/bright';
|
||||
const OSM_DE = 'https://tile.openstreetmap.de/{z}/{x}/{y}.png';
|
||||
const initialState = useSettingsStore.getState();
|
||||
const settings = () => useSettingsStore.getState().settings;
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.mocked(settingsApi.get).mockReset();
|
||||
vi.mocked(settingsApi.set).mockReset().mockResolvedValue(undefined);
|
||||
vi.mocked(settingsApi.setBulk).mockReset().mockResolvedValue(undefined);
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
useSettingsStore.setState(initialState, true);
|
||||
await reopenForUser(801);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
vi.restoreAllMocks();
|
||||
await deleteCurrentUserDb();
|
||||
await reopenAnonymous();
|
||||
});
|
||||
|
||||
describe('settings without a connection', () => {
|
||||
it('FE-STORE-SETTINGS-OFFLINE-001: the kept answer stands in when the server cannot be reached', async () => {
|
||||
await cacheAccountSettings({ map_provider: 'maplibre-gl', maplibre_style: BRIGHT, map_tile_url: OSM_DE });
|
||||
vi.mocked(settingsApi.get).mockRejectedValue(new Error('Network Error'));
|
||||
|
||||
await useSettingsStore.getState().loadSettings();
|
||||
|
||||
await vi.waitFor(() => expect(settings().map_provider).toBe('maplibre-gl'));
|
||||
expect(settings()).toMatchObject({ maplibre_style: BRIGHT, map_tile_url: OSM_DE });
|
||||
// Still not loaded, so the reconnect triggers keep asking the server.
|
||||
expect(useSettingsStore.getState().isLoaded).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-STORE-SETTINGS-OFFLINE-002: with nothing kept the defaults stay, as before', async () => {
|
||||
vi.mocked(settingsApi.get).mockRejectedValue(new Error('Network Error'));
|
||||
|
||||
await useSettingsStore.getState().loadSettings();
|
||||
await cachedAccountSettings();
|
||||
|
||||
expect(settings().map_provider).toBe(DEFAULT_SETTINGS.map_provider);
|
||||
});
|
||||
|
||||
it("FE-STORE-SETTINGS-OFFLINE-003: the server's answer wins over the kept one and is kept in its place", async () => {
|
||||
await cacheAccountSettings({ map_provider: 'maplibre-gl', maplibre_style: BRIGHT });
|
||||
vi.mocked(settingsApi.get).mockResolvedValue({ settings: { map_provider: 'mapbox-gl' } } as never);
|
||||
|
||||
await useSettingsStore.getState().loadSettings();
|
||||
// Let the read of the kept answer settle, whichever of the two came first.
|
||||
await cachedAccountSettings();
|
||||
|
||||
expect(settings().map_provider).toBe('mapbox-gl');
|
||||
// A key the server no longer sends is not set any more: back to its default.
|
||||
expect(settings().maplibre_style).toBe(DEFAULT_SETTINGS.maplibre_style);
|
||||
await vi.waitFor(async () => expect(await cachedAccountSettings()).toEqual({ map_provider: 'mapbox-gl' }));
|
||||
});
|
||||
|
||||
it('FE-STORE-SETTINGS-OFFLINE-004: a kept answer arriving after the server answered changes nothing', async () => {
|
||||
vi.mocked(settingsApi.get).mockResolvedValue({ settings: { map_provider: 'leaflet' } } as never);
|
||||
await useSettingsStore.getState().loadSettings();
|
||||
await cacheAccountSettings({ map_provider: 'maplibre-gl' });
|
||||
|
||||
// A second load (a reconnect trigger) while the first answer is in place.
|
||||
vi.mocked(settingsApi.get).mockRejectedValue(new Error('Network Error'));
|
||||
await useSettingsStore.getState().loadSettings();
|
||||
await cachedAccountSettings();
|
||||
|
||||
expect(settings().map_provider).toBe('leaflet');
|
||||
});
|
||||
|
||||
it('FE-STORE-SETTINGS-OFFLINE-005: a setting the server accepted is kept for the next start', async () => {
|
||||
await cacheAccountSettings({ map_provider: 'leaflet', distance_unit: 'imperial' });
|
||||
|
||||
await useSettingsStore.getState().updateSetting('map_provider', 'maplibre-gl');
|
||||
|
||||
await vi.waitFor(async () =>
|
||||
expect(await cachedAccountSettings()).toEqual({ map_provider: 'maplibre-gl', distance_unit: 'imperial' })
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-STORE-SETTINGS-OFFLINE-006: several settings saved at once are kept together', async () => {
|
||||
await useSettingsStore.getState().updateSettings({ map_provider: 'maplibre-gl', maplibre_style: BRIGHT });
|
||||
|
||||
await vi.waitFor(async () =>
|
||||
expect(await cachedAccountSettings()).toEqual({ map_provider: 'maplibre-gl', maplibre_style: BRIGHT })
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-STORE-SETTINGS-OFFLINE-007: a save the server refused is not kept', async () => {
|
||||
await cacheAccountSettings({ map_provider: 'leaflet' });
|
||||
vi.mocked(settingsApi.set).mockRejectedValue(new Error('Network Error'));
|
||||
vi.mocked(settingsApi.setBulk).mockRejectedValue(new Error('Network Error'));
|
||||
|
||||
await expect(useSettingsStore.getState().updateSetting('map_provider', 'maplibre-gl')).rejects.toThrow();
|
||||
await expect(useSettingsStore.getState().updateSettings({ map_provider: 'mapbox-gl' })).rejects.toThrow();
|
||||
|
||||
expect(await cachedAccountSettings()).toEqual({ map_provider: 'leaflet' });
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import { SUPPORTED_LANGUAGE_CODES } from '../i18n/supportedLanguages'
|
||||
import { detectBrowserLanguage } from '../i18n/detectBrowserLanguage'
|
||||
import { normalizeTileUrl, stripTileApiKey } from '../utils/tileUrl'
|
||||
import { clearTileCache } from '../sync/tilePrefetcher'
|
||||
import { cacheAccountSettings, cacheAccountSettingsPatch, cachedAccountSettings } from '../db/cacheAccountSettings'
|
||||
import { rememberStartDestination, DEFAULT_START_PAGE, DEFAULT_START_TRIP_TAB } from '../utils/startDestination'
|
||||
|
||||
interface SettingsState {
|
||||
@@ -115,6 +116,11 @@ export const DEFAULT_SETTINGS: Settings = {
|
||||
// periodic) can all fire a retry at once — collapse them into one in-flight GET.
|
||||
let _loadInFlight: Promise<void> | null = null
|
||||
|
||||
// The keys the kept answer laid over the defaults while the server was still out
|
||||
// (see loadSettings). A key the server then leaves out is one the account no
|
||||
// longer sets, so it goes back to its default rather than keeping the old value.
|
||||
let _standInKeys: (keyof Settings)[] = []
|
||||
|
||||
// Every tile consumer (planner map, journey map, tile prefetcher, the settings
|
||||
// preview) reads the template from this store, so the retired
|
||||
// {s}.tile.openstreetmap.org host is rewritten here — on the way in from the
|
||||
@@ -139,15 +145,29 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
|
||||
loadSettings: async () => {
|
||||
if (_loadInFlight !== null) return _loadInFlight
|
||||
_loadInFlight = (async () => {
|
||||
// Until the server answers, the settings it answered last time stand in, so
|
||||
// a start without a connection draws the user's own map and units instead
|
||||
// of the defaults (DEFAULT_SETTINGS means Leaflet). Laid only while nothing
|
||||
// newer arrived: once the server answered, its answer is the truth.
|
||||
void cachedAccountSettings().then((kept) => {
|
||||
if (!kept || get().isLoaded) return
|
||||
_standInKeys = Object.keys(kept) as (keyof Settings)[]
|
||||
set((state) => ({ settings: { ...state.settings, ...kept } }))
|
||||
})
|
||||
try {
|
||||
const data = await settingsApi.get()
|
||||
// Rewritten here so the Map settings input already shows the host that
|
||||
// still resolves, and persists it on the next save.
|
||||
const incoming = withNormalizedTileUrl({ ...data.settings } as Partial<Settings>)
|
||||
const unset = Object.fromEntries(
|
||||
_standInKeys.filter((key) => !(key in incoming)).map((key) => [key, DEFAULT_SETTINGS[key]])
|
||||
) as Partial<Settings>
|
||||
_standInKeys = []
|
||||
set((state) => ({
|
||||
settings: { ...state.settings, ...incoming },
|
||||
settings: { ...state.settings, ...unset, ...incoming },
|
||||
isLoaded: true,
|
||||
}))
|
||||
void cacheAccountSettings(incoming)
|
||||
// The startup redirect runs before this ever resolves, so keep a mirror
|
||||
// it can read synchronously on the next launch.
|
||||
rememberStartDestination(incoming)
|
||||
@@ -189,6 +209,7 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
|
||||
rememberStartDestination({ [key]: next } as Partial<Settings>)
|
||||
try {
|
||||
await settingsApi.set(key, next)
|
||||
void cacheAccountSettingsPatch({ [key]: next } as Partial<Settings>)
|
||||
} catch (err: unknown) {
|
||||
console.error('Failed to save setting:', err)
|
||||
throw new Error(getApiErrorMessage(err, 'Error saving setting'))
|
||||
@@ -221,6 +242,7 @@ export const useSettingsStore = create<SettingsState>((set, get) => ({
|
||||
rememberStartDestination(patch)
|
||||
try {
|
||||
await settingsApi.setBulk(patch)
|
||||
void cacheAccountSettingsPatch(patch)
|
||||
} catch (err: unknown) {
|
||||
console.error('Failed to save settings:', err)
|
||||
throw new Error(getApiErrorMessage(err, 'Error saving settings'))
|
||||
|
||||
Reference in New Issue
Block a user